source: trunk/third/gcc/cpplib.c @ 11288

Revision 11288, 197.8 KB checked in by ghudson, 27 years ago (diff)
This commit was generated by cvs2svn to compensate for changes in r11287, which included commits to RCS files with non-trunk default branches.
Line 
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
6
7This program is free software; you can redistribute it and/or modify it
8under the terms of the GNU General Public License as published by the
9Free Software Foundation; either version 2, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with this program; if not, write to the Free Software
19Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
20
21#include "config.h"
22
23#ifndef STDC_VALUE
24#define STDC_VALUE 1
25#endif
26
27#include <ctype.h>
28#include <stdio.h>
29#include <signal.h>
30
31#ifdef HAVE_STDLIB_H
32#include <stdlib.h>
33#endif
34
35#ifdef TIME_WITH_SYS_TIME
36# include <sys/time.h>
37# include <time.h>
38#else
39# if HAVE_SYS_TIME_H
40# include <sys/time.h>
41# else
42#  include <time.h>
43#endif
44#endif
45
46#ifdef HAVE_SYS_TIMES_H
47#include <sys/times.h>
48#endif
49
50#ifdef HAVE_SYS_RESOURCE_H
51# include <sys/resource.h>
52#endif
53
54#ifdef HAVE_FCNTL_H
55# include <fcntl.h>
56#endif
57
58#if HAVE_LIMITS_H
59# include <limits.h>
60#endif
61
62#ifdef HAVE_STDLIB_H
63# include <stdlib.h>
64#endif
65
66#ifdef HAVE_STRING_H
67# include <string.h>
68# else
69# ifdef HAVE_STRINGS_H
70#  include <strings.h>
71#endif
72#endif
73
74/* This defines "errno" properly for VMS, and gives us EACCES.  */
75#include <errno.h>
76
77#include "cpplib.h"
78#include "cpphash.h"
79#include "gansidecl.h"
80
81#ifdef NEED_DECLARATION_INDEX
82extern char *index ();
83#endif
84
85#ifdef NEED_DECLARATION_RINDEX
86extern char *rindex ();
87#endif
88
89#ifdef NEED_DECLARATION_GETENV
90extern char *getenv ();
91#endif
92
93extern char *update_path ();
94
95#ifndef O_RDONLY
96#define O_RDONLY 0
97#endif
98
99#undef MIN
100#undef MAX
101#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
102#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
103
104/* Find the largest host integer type and set its size and type.
105   Watch out: on some crazy hosts `long' is shorter than `int'.  */
106
107#ifndef HOST_WIDE_INT
108# if HAVE_INTTYPES_H
109#  include <inttypes.h>
110#  define HOST_WIDE_INT intmax_t
111# else
112#  if (HOST_BITS_PER_LONG <= HOST_BITS_PER_INT \
113       && HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_INT)
114#   define HOST_WIDE_INT int
115#  else
116#  if (HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_LONG \
117       || ! (defined LONG_LONG_MAX || defined LLONG_MAX))
118#   define HOST_WIDE_INT long
119#  else
120#   define HOST_WIDE_INT long long
121#  endif
122#  endif
123# endif
124#endif
125
126#ifndef S_ISREG
127#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
128#endif
129
130#ifndef S_ISDIR
131#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
132#endif
133
134/* By default, colon separates directories in a path.  */
135#ifndef PATH_SEPARATOR
136#define PATH_SEPARATOR ':'
137#endif
138
139#ifndef STANDARD_INCLUDE_DIR
140#define STANDARD_INCLUDE_DIR "/usr/include"
141#endif
142#ifndef INCLUDE_LEN_FUDGE
143#define INCLUDE_LEN_FUDGE 0
144#endif
145
146/* Symbols to predefine.  */
147
148#ifdef CPP_PREDEFINES
149static char *predefs = CPP_PREDEFINES;
150#else
151static char *predefs = "";
152#endif
153
154/* We let tm.h override the types used here, to handle trivial differences
155   such as the choice of unsigned int or long unsigned int for size_t.
156   When machines start needing nontrivial differences in the size type,
157   it would be best to do something here to figure out automatically
158   from other information what type to use.  */
159
160/* The string value for __SIZE_TYPE__.  */
161
162#ifndef SIZE_TYPE
163#define SIZE_TYPE "long unsigned int"
164#endif
165
166/* The string value for __PTRDIFF_TYPE__.  */
167
168#ifndef PTRDIFF_TYPE
169#define PTRDIFF_TYPE "long int"
170#endif
171
172/* The string value for __WCHAR_TYPE__.  */
173
174#ifndef WCHAR_TYPE
175#define WCHAR_TYPE "int"
176#endif
177#define CPP_WCHAR_TYPE(PFILE) \
178        (CPP_OPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
179
180/* The string value for __USER_LABEL_PREFIX__ */
181
182#ifndef USER_LABEL_PREFIX
183#define USER_LABEL_PREFIX ""
184#endif
185
186/* The string value for __REGISTER_PREFIX__ */
187
188#ifndef REGISTER_PREFIX
189#define REGISTER_PREFIX ""
190#endif
191
192/* In the definition of a #assert name, this structure forms
193   a list of the individual values asserted.
194   Each value is itself a list of "tokens".
195   These are strings that are compared by name.  */
196
197struct tokenlist_list {
198  struct tokenlist_list *next;
199  struct arglist *tokens;
200};
201
202struct assertion_hashnode {
203  struct assertion_hashnode *next;      /* double links for easy deletion */
204  struct assertion_hashnode *prev;
205  /* also, a back pointer to this node's hash
206     chain is kept, in case the node is the head
207     of the chain and gets deleted.  */
208  struct assertion_hashnode **bucket_hdr;
209  int length;                   /* length of token, for quick comparison */
210  U_CHAR *name;                 /* the actual name */
211  /* List of token-sequences.  */
212  struct tokenlist_list *value;
213};
214
215#define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
216#define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
217
218#define PEEKN(N) (CPP_BUFFER (pfile)->rlimit - CPP_BUFFER (pfile)->cur >= (N) ? CPP_BUFFER (pfile)->cur[N] : EOF)
219#define FORWARD(N) CPP_FORWARD (CPP_BUFFER (pfile), (N))
220#define GETC() CPP_BUF_GET (CPP_BUFFER (pfile))
221#define PEEKC() CPP_BUF_PEEK (CPP_BUFFER (pfile))
222/* CPP_IS_MACRO_BUFFER is true if the buffer contains macro expansion.
223   (Note that it is false while we're expanding marco *arguments*.) */
224#define CPP_IS_MACRO_BUFFER(PBUF) ((PBUF)->cleanup == macro_cleanup)
225
226/* Move all backslash-newline pairs out of embarrassing places.
227   Exchange all such pairs following BP
228   with any potentially-embarrassing characters that follow them.
229   Potentially-embarrassing characters are / and *
230   (because a backslash-newline inside a comment delimiter
231   would cause it not to be recognized).  */
232
233#define NEWLINE_FIX \
234  do {while (PEEKC() == '\\' && PEEKN(1) == '\n') FORWARD(2); } while(0)
235
236/* Same, but assume we've already read the potential '\\' into C.  */
237#define NEWLINE_FIX1(C) do { \
238    while ((C) == '\\' && PEEKC() == '\n') { FORWARD(1); (C) = GETC(); }\
239  } while(0)
240
241struct cpp_pending {
242  struct cpp_pending *next;
243  char *cmd;
244  char *arg;
245};
246
247/* Forward declarations.  */
248
249char *xmalloc ();
250void cpp_fatal ();
251void cpp_file_line_for_message PARAMS ((cpp_reader *, char *, int, int));
252void cpp_hash_cleanup PARAMS ((cpp_reader *));
253void cpp_message ();
254void cpp_print_containing_files PARAMS ((cpp_reader *));
255
256static void add_import ();
257static void append_include_chain ();
258static void make_assertion ();
259static void path_include ();
260static void initialize_builtins ();
261static void initialize_char_syntax ();
262extern void delete_macro ();
263#if 0
264static void trigraph_pcp ();
265#endif
266static int finclude ();
267static void validate_else ();
268static int comp_def_part ();
269#ifdef abort
270extern void fancy_abort ();
271#endif
272static int lookup_import ();
273static int redundant_include_p ();
274static is_system_include ();
275static struct file_name_map *read_name_map ();
276static char *read_filename_string ();
277static int open_include_file ();
278static int check_macro_name ();
279static int compare_defs ();
280static int compare_token_lists ();
281static HOST_WIDE_INT eval_if_expression ();
282static int change_newlines ();
283extern int hashf ();
284static struct arglist *read_token_list ();
285static void free_token_list ();
286static int safe_read ();
287static void push_macro_expansion PARAMS ((cpp_reader *,
288                                          U_CHAR *, int, HASHNODE *));
289static struct cpp_pending *nreverse_pending PARAMS ((struct cpp_pending *));
290extern char *xrealloc ();
291static char *xcalloc ();
292static char *savestring ();
293
294static void conditional_skip ();
295static void skip_if_group ();
296
297/* Last arg to output_line_command.  */
298enum file_change_code {same_file, enter_file, leave_file};
299
300/* External declarations.  */
301
302extern HOST_WIDE_INT cpp_parse_expr PARAMS ((cpp_reader *));
303
304extern FILE *fdopen ();
305extern char *version_string;
306extern struct tm *localtime ();
307
308/* These functions are declared to return int instead of void since they
309   are going to be placed in a table and some old compilers have trouble with
310   pointers to functions returning void.  */
311
312static int do_define ();
313static int do_line ();
314static int do_include ();
315static int do_undef ();
316static int do_error ();
317static int do_pragma ();
318static int do_ident ();
319static int do_if ();
320static int do_xifdef ();
321static int do_else ();
322static int do_elif ();
323static int do_endif ();
324static int do_sccs ();
325static int do_once ();
326static int do_assert ();
327static int do_unassert ();
328static int do_warning ();
329
330struct file_name_list
331  {
332    struct file_name_list *next;
333    char *fname;
334    /* If the following is nonzero, it is a macro name.
335       Don't include the file again if that macro is defined.  */
336    U_CHAR *control_macro;
337    /* If the following is nonzero, it is a C-language system include
338       directory.  */
339    int c_system_include_path;
340    /* Mapping of file names for this directory.  */
341    struct file_name_map *name_map;
342    /* Non-zero if name_map is valid.  */
343    int got_name_map;
344  };
345
346/* If a buffer's dir field is SELF_DIR_DUMMY, it means the file was found
347   via the same directory as the file that #included it.  */
348#define SELF_DIR_DUMMY ((struct file_name_list *) (~0))
349
350/* #include "file" looks in source file dir, then stack.  */
351/* #include <file> just looks in the stack.  */
352/* -I directories are added to the end, then the defaults are added.  */
353/* The */
354static struct default_include {
355  char *fname;                  /* The name of the directory.  */
356  char *component;              /* The component containing the directory */
357  int cplusplus;                /* Only look here if we're compiling C++.  */
358  int cxx_aware;                /* Includes in this directory don't need to
359                                   be wrapped in extern "C" when compiling
360                                   C++.  */
361} include_defaults_array[]
362#ifdef INCLUDE_DEFAULTS
363  = INCLUDE_DEFAULTS;
364#else
365  = {
366    /* Pick up GNU C++ specific include files.  */
367    { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1 },
368    { OLD_GPLUSPLUS_INCLUDE_DIR, 0, 1, 1 },
369#ifdef CROSS_COMPILE
370    /* This is the dir for fixincludes.  Put it just before
371       the files that we fix.  */
372    { GCC_INCLUDE_DIR, "GCC", 0, 0 },
373    /* For cross-compilation, this dir name is generated
374       automatically in Makefile.in.  */
375    { CROSS_INCLUDE_DIR, "GCC",0, 0 },
376#ifdef TOOL_INCLUDE_DIR
377    /* This is another place that the target system's headers might be.  */
378    { TOOL_INCLUDE_DIR, "BINUTILS", 0, 1 },
379#endif
380#else /* not CROSS_COMPILE */
381#ifdef LOCAL_INCLUDE_DIR
382    /* This should be /usr/local/include and should come before
383       the fixincludes-fixed header files.  */
384    { LOCAL_INCLUDE_DIR, 0, 0, 1 },
385#endif
386#ifdef TOOL_INCLUDE_DIR
387    /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
388       Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h.  */
389    { TOOL_INCLUDE_DIR, "BINUTILS", 0, 1 },
390#endif
391    /* This is the dir for fixincludes.  Put it just before
392       the files that we fix.  */
393    { GCC_INCLUDE_DIR, "GCC", 0, 0 },
394    /* Some systems have an extra dir of include files.  */
395#ifdef SYSTEM_INCLUDE_DIR
396    { SYSTEM_INCLUDE_DIR, 0, 0, 0 },
397#endif
398#ifndef STANDARD_INCLUDE_COMPONENT
399#define STANDARD_INCLUDE_COMPONENT 0
400#endif
401    { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0 },
402#endif /* not CROSS_COMPILE */
403    { 0, 0, 0, 0 }
404    };
405#endif /* no INCLUDE_DEFAULTS */
406
407/* `struct directive' defines one #-directive, including how to handle it.  */
408
409struct directive {
410  int length;                   /* Length of name */
411  int (*func)();                /* Function to handle directive */
412  char *name;                   /* Name of directive */
413  enum node_type type;          /* Code which describes which directive.  */
414  char command_reads_line;      /* One if rest of line is read by func.  */
415};
416
417#define IS_INCLUDE_DIRECTIVE_TYPE(t) \
418((int) T_INCLUDE <= (int) (t) && (int) (t) <= (int) T_IMPORT)
419
420/* Here is the actual list of #-directives, most-often-used first.
421   The initialize_builtins function assumes #define is the very first.  */
422
423static struct directive directive_table[] = {
424  {  6, do_define, "define", T_DEFINE},
425  {  5, do_xifdef, "ifdef", T_IFDEF, 1},
426  {  6, do_xifdef, "ifndef", T_IFNDEF, 1},
427  {  7, do_include, "include", T_INCLUDE, 1},
428  { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
429  {  6, do_include, "import", T_IMPORT, 1},
430  {  5, do_endif, "endif", T_ENDIF, 1},
431  {  4, do_else, "else", T_ELSE, 1},
432  {  2, do_if, "if", T_IF, 1},
433  {  4, do_elif, "elif", T_ELIF, 1},
434  {  5, do_undef, "undef", T_UNDEF},
435  {  5, do_error, "error", T_ERROR},
436  {  7, do_warning, "warning", T_WARNING},
437  {  6, do_pragma, "pragma", T_PRAGMA},
438  {  4, do_line, "line", T_LINE, 1},
439  {  5, do_ident, "ident", T_IDENT, 1},
440#ifdef SCCS_DIRECTIVE
441  {  4, do_sccs, "sccs", T_SCCS},
442#endif
443  {  6, do_assert, "assert", T_ASSERT, 1},
444  {  8, do_unassert, "unassert", T_UNASSERT, 1},
445  {  -1, 0, "", T_UNUSED},
446};
447
448/* table to tell if char can be part of a C identifier.  */
449U_CHAR is_idchar[256];
450/* table to tell if char can be first char of a c identifier.  */
451U_CHAR is_idstart[256];
452/* table to tell if c is horizontal space.  */
453U_CHAR is_hor_space[256];
454/* table to tell if c is horizontal or vertical space.  */
455static U_CHAR is_space[256];
456
457/* Initialize syntactic classifications of characters.  */
458
459static void
460initialize_char_syntax (opts)
461     struct cpp_options *opts;
462{
463  register int i;
464
465  /*
466   * Set up is_idchar and is_idstart tables.  These should be
467   * faster than saying (is_alpha (c) || c == '_'), etc.
468   * Set up these things before calling any routines tthat
469   * refer to them.
470   */
471  for (i = 'a'; i <= 'z'; i++) {
472    is_idchar[i - 'a' + 'A'] = 1;
473    is_idchar[i] = 1;
474    is_idstart[i - 'a' + 'A'] = 1;
475    is_idstart[i] = 1;
476  }
477  for (i = '0'; i <= '9'; i++)
478    is_idchar[i] = 1;
479  is_idchar['_'] = 1;
480  is_idstart['_'] = 1;
481  is_idchar['$'] = opts->dollars_in_ident;
482  is_idstart['$'] = opts->dollars_in_ident;
483
484  /* horizontal space table */
485  is_hor_space[' '] = 1;
486  is_hor_space['\t'] = 1;
487  is_hor_space['\v'] = 1;
488  is_hor_space['\f'] = 1;
489  is_hor_space['\r'] = 1;
490
491  is_space[' '] = 1;
492  is_space['\t'] = 1;
493  is_space['\v'] = 1;
494  is_space['\f'] = 1;
495  is_space['\n'] = 1;
496  is_space['\r'] = 1;
497}
498
499
500/* Place into PFILE a quoted string representing the string SRC.
501   Caller must reserve enough space in pfile->token_buffer.  */
502
503static void
504quote_string (pfile, src)
505     cpp_reader *pfile;
506     char *src;
507{
508  U_CHAR c;
509
510  CPP_PUTC_Q (pfile, '\"');
511  for (;;)
512    switch ((c = *src++))
513      {
514      default:
515        if (isprint (c))
516          CPP_PUTC_Q (pfile, c);
517        else
518          {
519            sprintf ((char *)CPP_PWRITTEN (pfile), "\\%03o", c);
520            CPP_ADJUST_WRITTEN (pfile, 4);
521          }
522        break;
523
524      case '\"':
525      case '\\':
526        CPP_PUTC_Q (pfile, '\\');
527        CPP_PUTC_Q (pfile, c);
528        break;
529     
530      case '\0':
531        CPP_PUTC_Q (pfile, '\"');
532        CPP_NUL_TERMINATE_Q (pfile);
533        return;
534      }
535}
536
537/* Re-allocates PFILE->token_buffer so it will hold at least N more chars.  */
538
539void
540cpp_grow_buffer (pfile, n)
541     cpp_reader *pfile;
542     long n;
543{
544  long old_written = CPP_WRITTEN (pfile);
545  pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
546  pfile->token_buffer = (U_CHAR *)
547    xrealloc(pfile->token_buffer, pfile->token_buffer_size);
548  CPP_SET_WRITTEN (pfile, old_written);
549}
550
551
552/*
553 * process a given definition string, for initialization
554 * If STR is just an identifier, define it with value 1.
555 * If STR has anything after the identifier, then it should
556 * be identifier=definition.
557 */
558
559void
560cpp_define (pfile, str)
561     cpp_reader *pfile;
562     U_CHAR *str;
563{
564  U_CHAR *buf, *p;
565
566  buf = str;
567  p = str;
568  if (!is_idstart[*p])
569    {
570      cpp_error (pfile, "malformed option `-D %s'", str);
571      return;
572    }
573  while (is_idchar[*++p])
574    ;
575  if (*p == 0)
576    {
577      buf = (U_CHAR *) alloca (p - buf + 4);
578      strcpy ((char *)buf, str);
579      strcat ((char *)buf, " 1");
580    }
581  else if (*p != '=')
582    {
583      cpp_error (pfile, "malformed option `-D %s'", str);
584      return;
585    }
586  else
587    {
588      U_CHAR *q;
589      /* Copy the entire option so we can modify it.  */
590      buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
591      strncpy (buf, str, p - str);
592      /* Change the = to a space.  */
593      buf[p - str] = ' ';
594      /* Scan for any backslash-newline and remove it.  */
595      p++;
596      q = &buf[p - str];
597      while (*p)
598        {
599      if (*p == '\\' && p[1] == '\n')
600        p += 2;
601      else
602        *q++ = *p++;
603    }
604    *q = 0;
605  }
606 
607  do_define (pfile, NULL, buf, buf + strlen (buf));
608}
609
610/* Process the string STR as if it appeared as the body of a #assert.
611   OPTION is the option name for which STR was the argument.  */
612
613static void
614make_assertion (pfile, option, str)
615     cpp_reader *pfile;
616     char *option;
617     U_CHAR *str;
618{
619  struct directive *kt;
620  U_CHAR *buf, *p, *q;
621
622  /* Copy the entire option so we can modify it.  */
623  buf = (U_CHAR *) alloca (strlen (str) + 1);
624  strcpy ((char *) buf, str);
625  /* Scan for any backslash-newline and remove it.  */
626  p = q = buf;
627  while (*p) {
628#if 0
629    if (*p == '\\' && p[1] == '\n')
630      p += 2;
631    else
632#endif
633      *q++ = *p++;
634  }
635  *q = 0;
636
637  p = buf;
638  if (!is_idstart[*p]) {
639    cpp_error (pfile, "malformed option `%s %s'", option, str);
640    return;
641  }
642  while (is_idchar[*++p])
643    ;
644  while (*p == ' ' || *p == '\t') p++;
645  if (! (*p == 0 || *p == '(')) {
646    cpp_error (pfile, "malformed option `%s %s'", option, str);
647    return;
648  }
649 
650  if (cpp_push_buffer (pfile, buf, strlen (buf)) != NULL)
651    {
652      do_assert (pfile, NULL, NULL, NULL);
653      cpp_pop_buffer (pfile);
654    }
655}
656
657/* Append a chain of `struct file_name_list's
658   to the end of the main include chain.
659   FIRST is the beginning of the chain to append, and LAST is the end.  */
660
661static void
662append_include_chain (pfile, first, last)
663     cpp_reader *pfile;
664     struct file_name_list *first, *last;
665{
666  struct cpp_options *opts = CPP_OPTIONS (pfile);
667  struct file_name_list *dir;
668
669  if (!first || !last)
670    return;
671
672  if (opts->include == 0)
673    opts->include = first;
674  else
675    opts->last_include->next = first;
676
677  if (opts->first_bracket_include == 0)
678    opts->first_bracket_include = first;
679
680  for (dir = first; ; dir = dir->next) {
681    int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
682    if (len > pfile->max_include_len)
683      pfile->max_include_len = len;
684    if (dir == last)
685      break;
686  }
687
688  last->next = NULL;
689  opts->last_include = last;
690}
691
692/* Add output to `deps_buffer' for the -M switch.
693   STRING points to the text to be output.
694   SPACER is ':' for targets, ' ' for dependencies, zero for text
695   to be inserted literally.  */
696
697static void
698deps_output (pfile, string, spacer)
699     cpp_reader *pfile;
700     char *string;
701     int spacer;
702{
703  int size = strlen (string);
704
705  if (size == 0)
706    return;
707
708#ifndef MAX_OUTPUT_COLUMNS
709#define MAX_OUTPUT_COLUMNS 72
710#endif
711  if (spacer
712      && pfile->deps_column > 0
713      && (pfile->deps_column + size) > MAX_OUTPUT_COLUMNS)
714    {
715      deps_output (pfile, " \\\n  ", 0);
716      pfile->deps_column = 0;
717    }
718
719  if (pfile->deps_size + size + 8 > pfile->deps_allocated_size)
720    {
721      pfile->deps_allocated_size = (pfile->deps_size + size + 50) * 2;
722      pfile->deps_buffer = (char *) xrealloc (pfile->deps_buffer,
723                                              pfile->deps_allocated_size);
724    }
725  if (spacer == ' ' && pfile->deps_column > 0)
726    pfile->deps_buffer[pfile->deps_size++] = ' ';
727  bcopy (string, &pfile->deps_buffer[pfile->deps_size], size);
728  pfile->deps_size += size;
729  pfile->deps_column += size;
730  if (spacer == ':')
731    pfile->deps_buffer[pfile->deps_size++] = ':';
732  pfile->deps_buffer[pfile->deps_size] = 0;
733}
734
735/* Given a colon-separated list of file names PATH,
736   add all the names to the search path for include files.  */
737
738static void
739path_include (pfile, path)
740     cpp_reader *pfile;
741     char *path;
742{
743  char *p;
744
745  p = path;
746
747  if (*p)
748    while (1) {
749      char *q = p;
750      char *name;
751      struct file_name_list *dirtmp;
752
753      /* Find the end of this name.  */
754      while (*q != 0 && *q != PATH_SEPARATOR) q++;
755      if (p == q) {
756        /* An empty name in the path stands for the current directory.  */
757        name = (char *) xmalloc (2);
758        name[0] = '.';
759        name[1] = 0;
760      } else {
761        /* Otherwise use the directory that is named.  */
762        name = (char *) xmalloc (q - p + 1);
763        bcopy (p, name, q - p);
764        name[q - p] = 0;
765      }
766
767      dirtmp = (struct file_name_list *)
768        xmalloc (sizeof (struct file_name_list));
769      dirtmp->next = 0;         /* New one goes on the end */
770      dirtmp->control_macro = 0;
771      dirtmp->c_system_include_path = 0;
772      dirtmp->fname = name;
773      dirtmp->got_name_map = 0;
774      append_include_chain (pfile, dirtmp, dirtmp);
775
776      /* Advance past this name.  */
777      p = q;
778      if (*p == 0)
779        break;
780      /* Skip the colon.  */
781      p++;
782    }
783}
784
785void
786cpp_options_init (opts)
787     cpp_options *opts;
788{
789  bzero ((char *) opts, sizeof *opts);
790  opts->in_fname = NULL;
791  opts->out_fname = NULL;
792
793  /* Initialize is_idchar to allow $.  */
794  opts->dollars_in_ident = 1;
795  initialize_char_syntax (opts);
796
797  opts->no_line_commands = 0;
798  opts->no_trigraphs = 1;
799  opts->put_out_comments = 0;
800  opts->print_include_names = 0;
801  opts->dump_macros = dump_none;
802  opts->no_output = 0;
803  opts->remap = 0;
804  opts->cplusplus = 0;
805  opts->cplusplus_comments = 0;
806
807  opts->verbose = 0;
808  opts->objc = 0;
809  opts->lang_asm = 0;
810  opts->for_lint = 0;
811  opts->chill = 0;
812  opts->pedantic_errors = 0;
813  opts->inhibit_warnings = 0;
814  opts->warn_comments = 0;
815  opts->warn_import = 1;
816  opts->warnings_are_errors = 0;
817}
818
819enum cpp_token
820null_underflow (pfile)
821     cpp_reader *pfile;
822{
823  return CPP_EOF;
824}
825
826int
827null_cleanup (pbuf, pfile)
828     cpp_buffer *pbuf;
829     cpp_reader *pfile;
830{
831  return 0;
832}
833
834int
835macro_cleanup (pbuf, pfile)
836     cpp_buffer *pbuf;
837     cpp_reader *pfile;
838{
839  HASHNODE *macro = (HASHNODE *) pbuf->data;
840  if (macro->type == T_DISABLED)
841    macro->type = T_MACRO;
842  if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
843    free (pbuf->buf);
844  return 0;
845}
846
847int
848file_cleanup (pbuf, pfile)
849     cpp_buffer *pbuf;
850     cpp_reader *pfile;
851{
852  if (pbuf->buf)
853    {
854      free (pbuf->buf);
855      pbuf->buf = 0;
856    }
857  return 0;
858}
859
860/* Assuming we have read '/'.
861   If this is the start of a comment (followed by '*' or '/'),
862   skip to the end of the comment, and return ' '.
863   Return EOF if we reached the end of file before the end of the comment.
864   If not the start of a comment, return '/'.  */
865
866static int
867skip_comment (pfile, linep)
868     cpp_reader *pfile;
869     long *linep;
870{
871  int c = 0;
872  while (PEEKC() == '\\' && PEEKN(1) == '\n')
873    {
874      if (linep)
875        (*linep)++;
876      FORWARD(2);
877    }
878  if (PEEKC() == '*')
879    {
880      FORWARD(1);
881      for (;;)
882        {
883          int prev_c = c;
884          c = GETC ();
885          if (c == EOF)
886            return EOF;
887          while (c == '\\' && PEEKC() == '\n')
888            {
889              if (linep)
890                (*linep)++;
891              FORWARD(1), c = GETC();
892            }
893          if (prev_c == '*' && c == '/')
894            return ' ';
895          if (c == '\n' && linep)
896            (*linep)++;
897        }
898    }
899  else if (PEEKC() == '/' && CPP_OPTIONS (pfile)->cplusplus_comments)
900    {
901      FORWARD(1);
902      for (;;)
903        {
904          c = GETC ();
905          if (c == EOF)
906            return ' '; /* Allow // to be terminated by EOF.  */
907          while (c == '\\' && PEEKC() == '\n')
908            {
909              FORWARD(1);
910              c = GETC();
911              if (linep)
912                (*linep)++;
913            }
914          if (c == '\n')
915            {
916              /* Don't consider final '\n' to be part of comment.  */
917              FORWARD(-1);
918              return ' ';
919            }
920        }
921    }
922  else
923    return '/';
924}     
925
926/* Skip whitespace \-newline and comments.  Does not macro-expand.  */
927
928void
929cpp_skip_hspace (pfile)
930     cpp_reader *pfile;
931{
932  while (1)
933    {
934      int c = PEEKC();
935      if (c == EOF)
936        return; /* FIXME */
937      if (is_hor_space[c])
938        {
939          if ((c == '\f' || c == '\v') && CPP_PEDANTIC (pfile))
940            cpp_pedwarn (pfile, "%s in preprocessing directive",
941                         c == '\f' ? "formfeed" : "vertical tab");
942          FORWARD(1);
943        }
944      else if (c == '/')
945        {
946          FORWARD (1);
947          c = skip_comment (pfile, NULL);
948          if (c == '/')
949            FORWARD(-1);
950          if (c == EOF || c == '/')
951            return;
952        }
953      else if (c == '\\' && PEEKN(1) == '\n') {
954        FORWARD(2);
955      }
956      else if (c == '@' && CPP_BUFFER (pfile)->has_escapes
957               && is_hor_space[PEEKN(1)])
958        FORWARD(2);
959      else return;
960    }
961}
962
963/* Read the rest of the current line.
964   The line is appended to PFILE's output buffer.  */
965
966static void
967copy_rest_of_line (pfile)
968     cpp_reader *pfile;
969{
970  struct cpp_options *opts = CPP_OPTIONS (pfile);
971  for (;;)
972    {
973      int c = GETC();
974      int nextc;
975      switch (c)
976        {
977        case EOF:
978          goto end_directive;
979        case '\\':
980          if (PEEKC() == '\n')
981            {
982              FORWARD (1);
983              continue;
984            }
985        case '\'':
986        case '\"':
987          goto scan_directive_token;
988          break;
989        case '/':
990          nextc = PEEKC();
991          if (nextc == '*' || (opts->cplusplus_comments && nextc == '/'))
992            goto scan_directive_token;
993          break;
994        case '\f':
995        case '\v':
996          if (CPP_PEDANTIC (pfile))
997            cpp_pedwarn (pfile, "%s in preprocessing directive",
998                         c == '\f' ? "formfeed" : "vertical tab");
999          break;
1000
1001        case '\n':
1002          FORWARD(-1);
1003          goto end_directive;
1004        scan_directive_token:
1005          FORWARD(-1);
1006          cpp_get_token (pfile);
1007          continue;
1008        }
1009      CPP_PUTC (pfile, c);
1010    }
1011 end_directive: ;
1012  CPP_NUL_TERMINATE (pfile);
1013}
1014
1015void
1016skip_rest_of_line (pfile)
1017     cpp_reader *pfile;
1018{
1019  long old = CPP_WRITTEN (pfile);
1020  copy_rest_of_line (pfile);
1021  CPP_SET_WRITTEN (pfile, old);
1022}
1023
1024/* Handle a possible # directive.
1025   '#' has already been read.  */
1026
1027int
1028handle_directive (pfile)
1029     cpp_reader *pfile;
1030{ int c;
1031  register struct directive *kt;
1032  int ident_length;
1033  long after_ident;
1034  U_CHAR *ident, *line_end;
1035  long old_written = CPP_WRITTEN (pfile);
1036
1037  cpp_skip_hspace (pfile);
1038
1039  c = PEEKC ();
1040  if (c >= '0' && c <= '9')
1041    {
1042      /* Handle # followed by a line number.  */
1043      if (CPP_PEDANTIC (pfile))
1044        cpp_pedwarn (pfile, "`#' followed by integer");
1045      do_line (pfile, NULL);
1046      goto done_a_directive;
1047    }
1048
1049  /* Now find the directive name.  */
1050  CPP_PUTC (pfile, '#');
1051  parse_name (pfile, GETC());
1052  ident = pfile->token_buffer + old_written + 1;
1053  ident_length = CPP_PWRITTEN (pfile) - ident;
1054  if (ident_length == 0 && PEEKC() == '\n')
1055    {
1056      /* A line of just `#' becomes blank.  */
1057      goto done_a_directive;
1058    }
1059
1060#if 0
1061  if (ident_length == 0 || !is_idstart[*ident]) {
1062    U_CHAR *p = ident;
1063    while (is_idchar[*p]) {
1064      if (*p < '0' || *p > '9')
1065        break;
1066      p++;
1067    }
1068    /* Avoid error for `###' and similar cases unless -pedantic.  */
1069    if (p == ident) {
1070      while (*p == '#' || is_hor_space[*p]) p++;
1071      if (*p == '\n') {
1072        if (pedantic && !lang_asm)
1073          cpp_warning (pfile, "invalid preprocessor directive");
1074        return 0;
1075      }
1076    }
1077
1078    if (!lang_asm)
1079      cpp_error (pfile, "invalid preprocessor directive name");
1080
1081    return 0;
1082  }
1083#endif
1084  /*
1085   * Decode the keyword and call the appropriate expansion
1086   * routine, after moving the input pointer up to the next line.
1087   */
1088  for (kt = directive_table; ; kt++) {
1089    if (kt->length <= 0)
1090      goto not_a_directive;
1091    if (kt->length == ident_length && !strncmp (kt->name, ident, ident_length))
1092      break;
1093  }
1094
1095  if (kt->command_reads_line)
1096    after_ident = 0;
1097  else
1098    {
1099      /* Nonzero means do not delete comments within the directive.
1100         #define needs this when -traditional.  */
1101        int comments = CPP_TRADITIONAL (pfile) && kt->type == T_DEFINE;
1102        int save_put_out_comments = CPP_OPTIONS (pfile)->put_out_comments;
1103        CPP_OPTIONS (pfile)->put_out_comments = comments;
1104        after_ident = CPP_WRITTEN (pfile);
1105        copy_rest_of_line (pfile);
1106        CPP_OPTIONS (pfile)->put_out_comments = save_put_out_comments;
1107    }
1108
1109  /* We may want to pass through #define, #pragma, and #include.
1110     Other directives may create output, but we don't want the directive
1111     itself out, so we pop it now.  For example conditionals may emit
1112     #failed ... #endfailed stuff.  But note that popping the buffer
1113     means the parameters to kt->func may point after pfile->limit
1114     so these parameters are invalid as soon as something gets appended
1115     to the token_buffer.  */
1116
1117  line_end = CPP_PWRITTEN (pfile);
1118  if (! (kt->type == T_DEFINE
1119         || kt->type == T_PRAGMA
1120         || (IS_INCLUDE_DIRECTIVE_TYPE (kt->type)
1121             && CPP_OPTIONS (pfile)->dump_includes)))
1122    CPP_SET_WRITTEN (pfile, old_written);
1123
1124  (*kt->func) (pfile, kt, pfile->token_buffer + after_ident, line_end);
1125
1126  if (kt->type == T_DEFINE)
1127    {
1128      if (CPP_OPTIONS (pfile)->dump_macros == dump_names)
1129        {
1130          /* Skip "#define". */
1131          U_CHAR *p = pfile->token_buffer + old_written + 7;
1132
1133          SKIP_WHITE_SPACE (p);
1134          while (is_idchar[*p]) p++;
1135          pfile->limit = p;
1136          CPP_PUTC (pfile, '\n');
1137        }
1138      else if (CPP_OPTIONS (pfile)->dump_macros != dump_definitions)
1139        CPP_SET_WRITTEN (pfile, old_written);
1140    }
1141
1142 done_a_directive:
1143  return 1;
1144
1145 not_a_directive:
1146  return 0;
1147}
1148
1149/* Pass a directive through to the output file.
1150   BUF points to the contents of the directive, as a contiguous string.
1151   LIMIT points to the first character past the end of the directive.
1152   KEYWORD is the keyword-table entry for the directive.  */
1153
1154static void
1155pass_thru_directive (buf, limit, pfile, keyword)
1156     U_CHAR *buf, *limit;
1157     cpp_reader *pfile;
1158     struct directive *keyword;
1159{
1160  register unsigned keyword_length = keyword->length;
1161
1162  CPP_RESERVE (pfile, 1 + keyword_length + (limit - buf));
1163  CPP_PUTC_Q (pfile, '#');
1164  CPP_PUTS_Q (pfile, keyword->name, keyword_length);
1165  if (limit != buf && buf[0] != ' ')
1166    CPP_PUTC_Q (pfile, ' ');
1167  CPP_PUTS_Q (pfile, buf, limit - buf);
1168#if 0
1169  CPP_PUTS_Q (pfile, '\n');
1170  /* Count the line we have just made in the output,
1171     to get in sync properly.  */
1172  pfile->lineno++;
1173#endif
1174}
1175
1176/* The arglist structure is built by do_define to tell
1177   collect_definition where the argument names begin.  That
1178   is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
1179   would contain pointers to the strings x, y, and z.
1180   Collect_definition would then build a DEFINITION node,
1181   with reflist nodes pointing to the places x, y, and z had
1182   appeared.  So the arglist is just convenience data passed
1183   between these two routines.  It is not kept around after
1184   the current #define has been processed and entered into the
1185   hash table.  */
1186
1187struct arglist {
1188  struct arglist *next;
1189  U_CHAR *name;
1190  int length;
1191  int argno;
1192  char rest_args;
1193};
1194
1195/* Read a replacement list for a macro with parameters.
1196   Build the DEFINITION structure.
1197   Reads characters of text starting at BUF until END.
1198   ARGLIST specifies the formal parameters to look for
1199   in the text of the definition; NARGS is the number of args
1200   in that list, or -1 for a macro name that wants no argument list.
1201   MACRONAME is the macro name itself (so we can avoid recursive expansion)
1202   and NAMELEN is its length in characters.
1203   
1204   Note that comments, backslash-newlines, and leading white space
1205   have already been deleted from the argument.  */
1206
1207static DEFINITION *
1208collect_expansion (pfile, buf, limit, nargs, arglist)
1209     cpp_reader *pfile;
1210     U_CHAR *buf, *limit;
1211     int nargs;
1212     struct arglist *arglist;
1213{
1214  DEFINITION *defn;
1215  register U_CHAR *p, *lastp, *exp_p;
1216  struct reflist *endpat = NULL;
1217  /* Pointer to first nonspace after last ## seen.  */
1218  U_CHAR *concat = 0;
1219  /* Pointer to first nonspace after last single-# seen.  */
1220  U_CHAR *stringify = 0;
1221  int maxsize;
1222  int expected_delimiter = '\0';
1223
1224  /* Scan thru the replacement list, ignoring comments and quoted
1225     strings, picking up on the macro calls.  It does a linear search
1226     thru the arg list on every potential symbol.  Profiling might say
1227     that something smarter should happen.  */
1228
1229  if (limit < buf)
1230    abort ();
1231
1232  /* Find the beginning of the trailing whitespace.  */
1233  p = buf;
1234  while (p < limit && is_space[limit[-1]]) limit--;
1235
1236  /* Allocate space for the text in the macro definition.
1237     Leading and trailing whitespace chars need 2 bytes each.
1238     Each other input char may or may not need 1 byte,
1239     so this is an upper bound.  The extra 5 are for invented
1240     leading and trailing newline-marker and final null.  */
1241  maxsize = (sizeof (DEFINITION)
1242             + (limit - p) + 5);
1243  /* Occurrences of '@' get doubled, so allocate extra space for them.  */
1244  while (p < limit)
1245    if (*p++ == '@')
1246      maxsize++;
1247  defn = (DEFINITION *) xcalloc (1, maxsize);
1248
1249  defn->nargs = nargs;
1250  exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
1251  lastp = exp_p;
1252
1253  p = buf;
1254
1255  /* Add one initial space escape-marker to prevent accidental
1256     token-pasting (often removed by macroexpand).  */
1257  *exp_p++ = '@';
1258  *exp_p++ = ' ';
1259
1260  if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1261    cpp_error (pfile, "`##' at start of macro definition");
1262    p += 2;
1263  }
1264
1265  /* Process the main body of the definition.  */
1266  while (p < limit) {
1267    int skipped_arg = 0;
1268    register U_CHAR c = *p++;
1269
1270    *exp_p++ = c;
1271
1272    if (!CPP_TRADITIONAL (pfile)) {
1273      switch (c) {
1274      case '\'':
1275      case '\"':
1276        if (expected_delimiter != '\0') {
1277          if (c == expected_delimiter)
1278            expected_delimiter = '\0';
1279        } else
1280          expected_delimiter = c;
1281        break;
1282
1283      case '\\':
1284        if (p < limit && expected_delimiter) {
1285          /* In a string, backslash goes through
1286             and makes next char ordinary.  */
1287          *exp_p++ = *p++;
1288        }
1289        break;
1290
1291      case '@':
1292        /* An '@' in a string or character constant stands for itself,
1293           and does not need to be escaped.  */
1294        if (!expected_delimiter)
1295          *exp_p++ = c;
1296        break;
1297
1298      case '#':
1299        /* # is ordinary inside a string.  */
1300        if (expected_delimiter)
1301          break;
1302        if (p < limit && *p == '#') {
1303          /* ##: concatenate preceding and following tokens.  */
1304          /* Take out the first #, discard preceding whitespace.  */
1305          exp_p--;
1306          while (exp_p > lastp && is_hor_space[exp_p[-1]])
1307            --exp_p;
1308          /* Skip the second #.  */
1309          p++;
1310          /* Discard following whitespace.  */
1311          SKIP_WHITE_SPACE (p);
1312          concat = p;
1313          if (p == limit)
1314            cpp_error (pfile, "`##' at end of macro definition");
1315        } else if (nargs >= 0) {
1316          /* Single #: stringify following argument ref.
1317             Don't leave the # in the expansion.  */
1318          exp_p--;
1319          SKIP_WHITE_SPACE (p);
1320          if (p == limit || ! is_idstart[*p]
1321              || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '"')))
1322            cpp_error (pfile,
1323                     "`#' operator is not followed by a macro argument name");
1324          else
1325            stringify = p;
1326        }
1327        break;
1328      }
1329    } else {
1330      /* In -traditional mode, recognize arguments inside strings and
1331         and character constants, and ignore special properties of #.
1332         Arguments inside strings are considered "stringified", but no
1333         extra quote marks are supplied.  */
1334      switch (c) {
1335      case '\'':
1336      case '\"':
1337        if (expected_delimiter != '\0') {
1338          if (c == expected_delimiter)
1339            expected_delimiter = '\0';
1340        } else
1341          expected_delimiter = c;
1342        break;
1343
1344      case '\\':
1345        /* Backslash quotes delimiters and itself, but not macro args.  */
1346        if (expected_delimiter != 0 && p < limit
1347            && (*p == expected_delimiter || *p == '\\')) {
1348          *exp_p++ = *p++;
1349          continue;
1350        }
1351        break;
1352
1353      case '/':
1354        if (expected_delimiter != '\0') /* No comments inside strings.  */
1355          break;
1356        if (*p == '*') {
1357          /* If we find a comment that wasn't removed by handle_directive,
1358             this must be -traditional.  So replace the comment with
1359             nothing at all.  */
1360          exp_p--;
1361          p += 1;
1362          while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
1363            p++;
1364#if 0
1365          /* Mark this as a concatenation-point, as if it had been ##.  */
1366          concat = p;
1367#endif
1368        }
1369        break;
1370      }
1371    }
1372
1373    /* Handle the start of a symbol.  */
1374    if (is_idchar[c] && nargs > 0) {
1375      U_CHAR *id_beg = p - 1;
1376      int id_len;
1377
1378      --exp_p;
1379      while (p != limit && is_idchar[*p]) p++;
1380      id_len = p - id_beg;
1381
1382      if (is_idstart[c]
1383          && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
1384        register struct arglist *arg;
1385
1386        for (arg = arglist; arg != NULL; arg = arg->next) {
1387          struct reflist *tpat;
1388
1389          if (arg->name[0] == c
1390              && arg->length == id_len
1391              && strncmp (arg->name, id_beg, id_len) == 0) {
1392            if (expected_delimiter && CPP_OPTIONS (pfile)->warn_stringify) {
1393              if (CPP_TRADITIONAL (pfile)) {
1394                cpp_warning (pfile, "macro argument `%.*s' is stringified.",
1395                             id_len, arg->name);
1396              } else {
1397                cpp_warning (pfile,
1398                    "macro arg `%.*s' would be stringified with -traditional.",
1399                             id_len, arg->name);
1400              }
1401            }
1402            /* If ANSI, don't actually substitute inside a string.  */
1403            if (!CPP_TRADITIONAL (pfile) && expected_delimiter)
1404              break;
1405            /* make a pat node for this arg and append it to the end of
1406               the pat list */
1407            tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
1408            tpat->next = NULL;
1409            tpat->raw_before = concat == id_beg;
1410            tpat->raw_after = 0;
1411            tpat->rest_args = arg->rest_args;
1412            tpat->stringify = (CPP_TRADITIONAL (pfile)
1413                               ? expected_delimiter != '\0'
1414                               : stringify == id_beg);
1415
1416            if (endpat == NULL)
1417              defn->pattern = tpat;
1418            else
1419              endpat->next = tpat;
1420            endpat = tpat;
1421
1422            tpat->argno = arg->argno;
1423            tpat->nchars = exp_p - lastp;
1424            {
1425              register U_CHAR *p1 = p;
1426              SKIP_WHITE_SPACE (p1);
1427              if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
1428                tpat->raw_after = 1;
1429            }
1430            lastp = exp_p;      /* place to start copying from next time */
1431            skipped_arg = 1;
1432            break;
1433          }
1434        }
1435      }
1436
1437      /* If this was not a macro arg, copy it into the expansion.  */
1438      if (! skipped_arg) {
1439        register U_CHAR *lim1 = p;
1440        p = id_beg;
1441        while (p != lim1)
1442          *exp_p++ = *p++;
1443        if (stringify == id_beg)
1444          cpp_error (pfile,
1445                   "`#' operator should be followed by a macro argument name");
1446      }
1447    }
1448  }
1449
1450  if (!CPP_TRADITIONAL (pfile) && expected_delimiter == 0)
1451    {
1452      /* If ANSI, put in a "@ " marker to prevent token pasting.
1453         But not if "inside a string" (which in ANSI mode
1454         happens only for -D option).  */
1455      *exp_p++ = '@';
1456      *exp_p++ = ' ';
1457    }
1458
1459  *exp_p = '\0';
1460
1461  defn->length = exp_p - defn->expansion;
1462
1463  /* Crash now if we overrun the allocated size.  */
1464  if (defn->length + 1 > maxsize)
1465    abort ();
1466
1467#if 0
1468/* This isn't worth the time it takes.  */
1469  /* give back excess storage */
1470  defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
1471#endif
1472
1473  return defn;
1474}
1475
1476/*
1477 * special extension string that can be added to the last macro argument to
1478 * allow it to absorb the "rest" of the arguments when expanded.  Ex:
1479 *              #define wow(a, b...)            process (b, a, b)
1480 *              { wow (1, 2, 3); }      ->      { process (2, 3, 1, 2, 3); }
1481 *              { wow (one, two); }     ->      { process (two, one, two); }
1482 * if this "rest_arg" is used with the concat token '##' and if it is not
1483 * supplied then the token attached to with ## will not be outputted.  Ex:
1484 *              #define wow (a, b...)           process (b ## , a, ## b)
1485 *              { wow (1, 2); }         ->      { process (2, 1, 2); }
1486 *              { wow (one); }          ->      { process (one); {
1487 */
1488static char rest_extension[] = "...";
1489#define REST_EXTENSION_LENGTH   (sizeof (rest_extension) - 1)
1490
1491/* Create a DEFINITION node from a #define directive.  Arguments are
1492   as for do_define.  */
1493
1494static MACRODEF
1495create_definition (buf, limit, pfile, predefinition)
1496     U_CHAR *buf, *limit;
1497     cpp_reader *pfile;
1498     int predefinition;
1499{
1500  U_CHAR *bp;                   /* temp ptr into input buffer */
1501  U_CHAR *symname;              /* remember where symbol name starts */
1502  int sym_length;               /* and how long it is */
1503  int rest_args = 0;
1504  long line, col;
1505  char *file = CPP_BUFFER (pfile) ? CPP_BUFFER (pfile)->nominal_fname : "";
1506  DEFINITION *defn;
1507  int arglengths = 0;           /* Accumulate lengths of arg names
1508                                   plus number of args.  */
1509  MACRODEF mdef;
1510  cpp_buf_line_and_col (CPP_BUFFER (pfile), &line, &col);
1511
1512  bp = buf;
1513
1514  while (is_hor_space[*bp])
1515    bp++;
1516
1517  symname = bp;                 /* remember where it starts */
1518
1519  sym_length = check_macro_name (pfile, bp, "macro");
1520  bp += sym_length;
1521
1522  /* Lossage will occur if identifiers or control keywords are broken
1523     across lines using backslash.  This is not the right place to take
1524     care of that.  */
1525
1526  if (*bp == '(') {
1527    struct arglist *arg_ptrs = NULL;
1528    int argno = 0;
1529
1530    bp++;                       /* skip '(' */
1531    SKIP_WHITE_SPACE (bp);
1532
1533    /* Loop over macro argument names.  */
1534    while (*bp != ')') {
1535      struct arglist *temp;
1536
1537      temp = (struct arglist *) alloca (sizeof (struct arglist));
1538      temp->name = bp;
1539      temp->next = arg_ptrs;
1540      temp->argno = argno++;
1541      temp->rest_args = 0;
1542      arg_ptrs = temp;
1543
1544      if (rest_args)
1545        cpp_pedwarn (pfile, "another parameter follows `%s'", rest_extension);
1546
1547      if (!is_idstart[*bp])
1548        cpp_pedwarn (pfile, "invalid character in macro parameter name");
1549     
1550      /* Find the end of the arg name.  */
1551      while (is_idchar[*bp]) {
1552        bp++;
1553        /* do we have a "special" rest-args extension here? */
1554        if (limit - bp > REST_EXTENSION_LENGTH
1555            && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
1556          rest_args = 1;
1557          temp->rest_args = 1;
1558          break;
1559        }
1560      }
1561      temp->length = bp - temp->name;
1562      if (rest_args == 1)
1563        bp += REST_EXTENSION_LENGTH;
1564      arglengths += temp->length + 2;
1565      SKIP_WHITE_SPACE (bp);
1566      if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
1567        cpp_error (pfile, "badly punctuated parameter list in `#define'");
1568        goto nope;
1569      }
1570      if (*bp == ',') {
1571        bp++;
1572        SKIP_WHITE_SPACE (bp);
1573      }
1574      if (bp >= limit) {
1575        cpp_error (pfile, "unterminated parameter list in `#define'");
1576        goto nope;
1577      }
1578      {
1579        struct arglist *otemp;
1580
1581        for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
1582          if (temp->length == otemp->length
1583              && strncmp (temp->name, otemp->name, temp->length) == 0) {
1584              U_CHAR *name;
1585
1586              name = (U_CHAR *) alloca (temp->length + 1);
1587              (void) strncpy (name, temp->name, temp->length);
1588              name[temp->length] = '\0';
1589              cpp_error (pfile,
1590                         "duplicate argument name `%s' in `#define'", name);
1591              goto nope;
1592          }
1593      }
1594    }
1595
1596    ++bp;                       /* skip paren */
1597    SKIP_WHITE_SPACE (bp);
1598    /* now everything from bp before limit is the definition.  */
1599    defn = collect_expansion (pfile, bp, limit, argno, arg_ptrs);
1600    defn->rest_args = rest_args;
1601
1602    /* Now set defn->args.argnames to the result of concatenating
1603       the argument names in reverse order
1604       with comma-space between them.  */
1605    defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
1606    {
1607      struct arglist *temp;
1608      int i = 0;
1609      for (temp = arg_ptrs; temp; temp = temp->next) {
1610        bcopy (temp->name, &defn->args.argnames[i], temp->length);
1611        i += temp->length;
1612        if (temp->next != 0) {
1613          defn->args.argnames[i++] = ',';
1614          defn->args.argnames[i++] = ' ';
1615        }
1616      }
1617      defn->args.argnames[i] = 0;
1618    }
1619  } else {
1620    /* Simple expansion or empty definition.  */
1621
1622    if (bp < limit)
1623      {
1624        if (is_hor_space[*bp]) {
1625          bp++;
1626          SKIP_WHITE_SPACE (bp);
1627        } else {
1628          switch (*bp) {
1629            case '!':  case '"':  case '#':  case '%':  case '&':  case '\'':
1630            case ')':  case '*':  case '+':  case ',':  case '-':  case '.':
1631            case '/':  case ':':  case ';':  case '<':  case '=':  case '>':
1632            case '?':  case '[':  case '\\': case ']':  case '^':  case '{':
1633            case '|':  case '}':  case '~':
1634              cpp_warning (pfile, "missing white space after `#define %.*s'",
1635                           sym_length, symname);
1636              break;
1637
1638            default:
1639              cpp_pedwarn (pfile, "missing white space after `#define %.*s'",
1640                           sym_length, symname);
1641              break;
1642          }
1643        }
1644      }
1645    /* now everything from bp before limit is the definition.  */
1646    defn = collect_expansion (pfile, bp, limit, -1, NULL_PTR);
1647    defn->args.argnames = (U_CHAR *) "";
1648  }
1649
1650  defn->line = line;
1651  defn->file = file;
1652
1653  /* OP is null if this is a predefinition */
1654  defn->predefined = predefinition;
1655  mdef.defn = defn;
1656  mdef.symnam = symname;
1657  mdef.symlen = sym_length;
1658
1659  return mdef;
1660
1661 nope:
1662  mdef.defn = 0;
1663  return mdef;
1664}
1665
1666/* Check a purported macro name SYMNAME, and yield its length.
1667   USAGE is the kind of name this is intended for.  */
1668
1669static int
1670check_macro_name (pfile, symname, usage)
1671     cpp_reader *pfile;
1672     U_CHAR *symname;
1673     char *usage;
1674{
1675  U_CHAR *p;
1676  int sym_length;
1677
1678  for (p = symname; is_idchar[*p]; p++)
1679    ;
1680  sym_length = p - symname;
1681  if (sym_length == 0
1682      || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
1683    cpp_error (pfile, "invalid %s name", usage);
1684  else if (!is_idstart[*symname]) {
1685    U_CHAR *msg;                        /* what pain...  */
1686    msg = (U_CHAR *) alloca (sym_length + 1);
1687    bcopy (symname, msg, sym_length);
1688    msg[sym_length] = 0;
1689    cpp_error (pfile, "invalid %s name `%s'", usage, msg);
1690  } else {
1691    if (! strncmp (symname, "defined", 7) && sym_length == 7)
1692      cpp_error (pfile, "invalid %s name `defined'", usage);
1693  }
1694  return sym_length;
1695}
1696
1697/* Return zero if two DEFINITIONs are isomorphic.  */
1698
1699static int
1700compare_defs (pfile, d1, d2)
1701     cpp_reader *pfile;
1702     DEFINITION *d1, *d2;
1703{
1704  register struct reflist *a1, *a2;
1705  register U_CHAR *p1 = d1->expansion;
1706  register U_CHAR *p2 = d2->expansion;
1707  int first = 1;
1708
1709  if (d1->nargs != d2->nargs)
1710    return 1;
1711  if (CPP_PEDANTIC (pfile)
1712      && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
1713    return 1;
1714  for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
1715       a1 = a1->next, a2 = a2->next) {
1716    if (!((a1->nchars == a2->nchars && ! strncmp (p1, p2, a1->nchars))
1717          || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
1718        || a1->argno != a2->argno
1719        || a1->stringify != a2->stringify
1720        || a1->raw_before != a2->raw_before
1721        || a1->raw_after != a2->raw_after)
1722      return 1;
1723    first = 0;
1724    p1 += a1->nchars;
1725    p2 += a2->nchars;
1726  }
1727  if (a1 != a2)
1728    return 1;
1729  if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
1730                     p2, d2->length - (p2 - d2->expansion), 1))
1731    return 1;
1732  return 0;
1733}
1734
1735/* Return 1 if two parts of two macro definitions are effectively different.
1736   One of the parts starts at BEG1 and has LEN1 chars;
1737   the other has LEN2 chars at BEG2.
1738   Any sequence of whitespace matches any other sequence of whitespace.
1739   FIRST means these parts are the first of a macro definition;
1740    so ignore leading whitespace entirely.
1741   LAST means these parts are the last of a macro definition;
1742    so ignore trailing whitespace entirely.  */
1743
1744static int
1745comp_def_part (first, beg1, len1, beg2, len2, last)
1746     int first;
1747     U_CHAR *beg1, *beg2;
1748     int len1, len2;
1749     int last;
1750{
1751  register U_CHAR *end1 = beg1 + len1;
1752  register U_CHAR *end2 = beg2 + len2;
1753  if (first) {
1754    while (beg1 != end1 && is_space[*beg1]) beg1++;
1755    while (beg2 != end2 && is_space[*beg2]) beg2++;
1756  }
1757  if (last) {
1758    while (beg1 != end1 && is_space[end1[-1]]) end1--;
1759    while (beg2 != end2 && is_space[end2[-1]]) end2--;
1760  }
1761  while (beg1 != end1 && beg2 != end2) {
1762    if (is_space[*beg1] && is_space[*beg2]) {
1763      while (beg1 != end1 && is_space[*beg1]) beg1++;
1764      while (beg2 != end2 && is_space[*beg2]) beg2++;
1765    } else if (*beg1 == *beg2) {
1766      beg1++; beg2++;
1767    } else break;
1768  }
1769  return (beg1 != end1) || (beg2 != end2);
1770}
1771
1772/* Process a #define command.
1773BUF points to the contents of the #define command, as a contiguous string.
1774LIMIT points to the first character past the end of the definition.
1775KEYWORD is the keyword-table entry for #define,
1776or NULL for a "predefined" macro.  */
1777
1778static int
1779do_define (pfile, keyword, buf, limit)
1780     cpp_reader *pfile;
1781     struct directive *keyword;
1782     U_CHAR *buf, *limit;
1783{
1784  int hashcode;
1785  MACRODEF mdef;
1786  HASHNODE *hp;
1787
1788#if 0
1789  /* If this is a precompiler run (with -pcp) pass thru #define commands.  */
1790  if (pcp_outfile && keyword)
1791    pass_thru_directive (buf, limit, pfile, keyword);
1792#endif
1793
1794  mdef = create_definition (buf, limit, pfile, keyword == NULL);
1795  if (mdef.defn == 0)
1796    goto nope;
1797
1798  hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
1799
1800  if ((hp = cpp_lookup (pfile, mdef.symnam, mdef.symlen, hashcode)) != NULL)
1801    {
1802      int ok = 0;
1803      /* Redefining a precompiled key is ok.  */
1804      if (hp->type == T_PCSTRING)
1805        ok = 1;
1806      /* Redefining a macro is ok if the definitions are the same.  */
1807      else if (hp->type == T_MACRO)
1808        ok = ! compare_defs (pfile, mdef.defn, hp->value.defn);
1809      /* Redefining a constant is ok with -D.  */
1810      else if (hp->type == T_CONST)
1811        ok = ! CPP_OPTIONS (pfile)->done_initializing;
1812      /* Print the warning if it's not ok.  */
1813      if (!ok)
1814        {
1815          U_CHAR *msg;          /* what pain...  */
1816
1817          /* If we are passing through #define and #undef directives, do
1818             that for this re-definition now.  */
1819          if (CPP_OPTIONS (pfile)->debug_output && keyword)
1820            pass_thru_directive (buf, limit, pfile, keyword);
1821
1822          msg = (U_CHAR *) alloca (mdef.symlen + 22);
1823          *msg = '`';
1824          bcopy (mdef.symnam, msg + 1, mdef.symlen);
1825          strcpy ((char *) (msg + mdef.symlen + 1), "' redefined");
1826          cpp_pedwarn (pfile, msg);
1827          if (hp->type == T_MACRO)
1828            cpp_pedwarn_with_file_and_line (pfile, hp->value.defn->file, hp->value.defn->line,
1829                                      "this is the location of the previous definition");
1830        }
1831      /* Replace the old definition.  */
1832      hp->type = T_MACRO;
1833      hp->value.defn = mdef.defn;
1834    }
1835  else
1836    {
1837      /* If we are passing through #define and #undef directives, do
1838         that for this new definition now.  */
1839      if (CPP_OPTIONS (pfile)->debug_output && keyword)
1840        pass_thru_directive (buf, limit, pfile, keyword);
1841      install (mdef.symnam, mdef.symlen, T_MACRO, 0,
1842               (char *) mdef.defn, hashcode);
1843    }
1844
1845  return 0;
1846
1847nope:
1848
1849  return 1;
1850}
1851
1852/* This structure represents one parsed argument in a macro call.
1853   `raw' points to the argument text as written (`raw_length' is its length).
1854   `expanded' points to the argument's macro-expansion
1855   (its length is `expand_length').
1856   `stringified_length' is the length the argument would have
1857   if stringified.
1858   `use_count' is the number of times this macro arg is substituted
1859   into the macro.  If the actual use count exceeds 10,
1860   the value stored is 10.  */
1861
1862/* raw and expanded are relative to ARG_BASE */
1863#define ARG_BASE ((pfile)->token_buffer)
1864
1865struct argdata {
1866  /* Strings relative to pfile->token_buffer */
1867  long raw, expanded, stringified;
1868  int raw_length, expand_length;
1869  int stringified_length;
1870  char newlines;
1871  char use_count;
1872};
1873
1874/* Allocate a new cpp_buffer for PFILE, and push it on the input buffer stack.
1875   If BUFFER != NULL, then use the LENGTH characters in BUFFER
1876   as the new input buffer.
1877   Return the new buffer, or NULL on failure.  */
1878
1879cpp_buffer *
1880cpp_push_buffer (pfile, buffer, length)
1881     cpp_reader *pfile;
1882     U_CHAR *buffer;
1883     long length;
1884{
1885  register cpp_buffer *buf = CPP_BUFFER (pfile);
1886  if (buf == pfile->buffer_stack)
1887    {
1888      cpp_fatal (pfile, "%s: macro or `#include' recursion too deep",
1889                 buf->fname);
1890      return NULL;
1891    }
1892  buf--;
1893  bzero ((char *) buf, sizeof (cpp_buffer));
1894  CPP_BUFFER (pfile) = buf;
1895  buf->if_stack = pfile->if_stack;
1896  buf->cleanup = null_cleanup;
1897  buf->underflow = null_underflow;
1898  buf->buf = buf->cur = buffer;
1899  buf->alimit = buf->rlimit = buffer + length;
1900 
1901  return buf;
1902}
1903
1904cpp_buffer *
1905cpp_pop_buffer (pfile)
1906     cpp_reader *pfile;
1907{
1908  cpp_buffer *buf = CPP_BUFFER (pfile);
1909  (*buf->cleanup) (buf, pfile);
1910  return ++CPP_BUFFER (pfile);
1911}
1912
1913/* Scan until CPP_BUFFER (PFILE) is exhausted into PFILE->token_buffer.
1914   Pop the buffer when done.  */
1915
1916void
1917cpp_scan_buffer (pfile)
1918     cpp_reader *pfile;
1919{
1920  cpp_buffer *buffer = CPP_BUFFER (pfile);
1921  for (;;)
1922    {
1923      enum cpp_token token = cpp_get_token (pfile);
1924      if (token == CPP_EOF) /* Should not happen ...  */
1925        break;
1926      if (token == CPP_POP && CPP_BUFFER (pfile) == buffer)
1927        {
1928          cpp_pop_buffer (pfile);
1929          break;
1930        }
1931    }
1932}
1933
1934/*
1935 * Rescan a string (which may have escape marks) into pfile's buffer.
1936 * Place the result in pfile->token_buffer.
1937 *
1938 * The input is copied before it is scanned, so it is safe to pass
1939 * it something from the token_buffer that will get overwritten
1940 * (because it follows CPP_WRITTEN).  This is used by do_include.
1941 */
1942
1943static void
1944cpp_expand_to_buffer (pfile, buf, length)
1945     cpp_reader *pfile;
1946     U_CHAR *buf;
1947     int length;
1948{
1949  register cpp_buffer *ip;
1950  cpp_buffer obuf;
1951  U_CHAR *limit = buf + length;
1952  U_CHAR *buf1;
1953#if 0
1954  int odepth = indepth;
1955#endif
1956
1957  if (length < 0)
1958    abort ();
1959
1960  /* Set up the input on the input stack.  */
1961
1962  buf1 = (U_CHAR *) alloca (length + 1);
1963  {
1964    register U_CHAR *p1 = buf;
1965    register U_CHAR *p2 = buf1;
1966
1967    while (p1 != limit)
1968      *p2++ = *p1++;
1969  }
1970  buf1[length] = 0;
1971
1972  ip = cpp_push_buffer (pfile, buf1, length);
1973  if (ip == NULL)
1974    return;
1975  ip->has_escapes = 1;
1976#if 0
1977  ip->lineno = obuf.lineno = 1;
1978#endif
1979
1980  /* Scan the input, create the output.  */
1981  cpp_scan_buffer (pfile);
1982
1983#if 0
1984  if (indepth != odepth)
1985    abort ();
1986#endif
1987
1988  CPP_NUL_TERMINATE (pfile);
1989}
1990
1991
1992static void
1993adjust_position (buf, limit, linep, colp)
1994     U_CHAR *buf;
1995     U_CHAR *limit;
1996     long *linep;
1997     long *colp;
1998{
1999  while (buf < limit)
2000    {
2001      U_CHAR ch = *buf++;
2002      if (ch == '\n')
2003        (*linep)++, (*colp) = 1;
2004      else
2005        (*colp)++;
2006    }
2007}
2008
2009/* Move line_base forward, updating lineno and colno.  */
2010
2011static void
2012update_position (pbuf)
2013     register cpp_buffer *pbuf;
2014{
2015  unsigned char *old_pos = pbuf->buf + pbuf->line_base;
2016  unsigned char *new_pos = pbuf->cur;
2017  register struct parse_marker *mark;
2018  for (mark = pbuf->marks;  mark != NULL; mark = mark->next)
2019    {
2020      if (pbuf->buf + mark->position < new_pos)
2021        new_pos = pbuf->buf + mark->position;
2022    }
2023  pbuf->line_base += new_pos - old_pos;
2024  adjust_position (old_pos, new_pos, &pbuf->lineno, &pbuf->colno);
2025}
2026
2027void
2028cpp_buf_line_and_col (pbuf, linep, colp)
2029     register cpp_buffer *pbuf;
2030     long *linep, *colp;
2031{
2032  long dummy;
2033  if (colp == NULL)
2034    colp = &dummy;
2035  if (pbuf)
2036    {
2037      *linep = pbuf->lineno;
2038      *colp = pbuf->colno;
2039      adjust_position (pbuf->buf + pbuf->line_base, pbuf->cur, linep, colp);
2040    }
2041  else
2042    {
2043      *linep = 0;
2044      *colp = 0;
2045    }
2046}
2047
2048/* Return the cpp_buffer that corresponds to a file (not a macro).  */
2049
2050cpp_buffer *
2051cpp_file_buffer (pfile)
2052     cpp_reader *pfile;
2053{
2054  cpp_buffer *ip = CPP_BUFFER (pfile);
2055
2056  for ( ; ip != CPP_NULL_BUFFER (pfile); ip = CPP_PREV_BUFFER (ip))
2057    if (ip->fname != NULL)
2058      return ip;
2059  return NULL;
2060}
2061
2062static long
2063count_newlines (buf, limit)
2064     register U_CHAR *buf;
2065     register U_CHAR *limit;
2066{
2067  register long count = 0;
2068  while (buf < limit)
2069    {
2070      U_CHAR ch = *buf++;
2071      if (ch == '\n')
2072        count++;
2073    }
2074  return count;
2075}
2076
2077/*
2078 * write out a #line command, for instance, after an #include file.
2079 * If CONDITIONAL is nonzero, we can omit the #line if it would
2080 * appear to be a no-op, and we can output a few newlines instead
2081 * if we want to increase the line number by a small amount.
2082 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
2083 */
2084
2085static void
2086output_line_command (pfile, conditional, file_change)
2087     cpp_reader *pfile;
2088     int conditional;
2089     enum file_change_code file_change;
2090{
2091  int len;
2092  char *line_cmd_buf, *line_end;
2093  long line, col;
2094  cpp_buffer *ip = CPP_BUFFER (pfile);
2095
2096  if (ip->fname == NULL)
2097    return;
2098
2099  update_position (ip);
2100
2101  if (CPP_OPTIONS (pfile)->no_line_commands
2102      || CPP_OPTIONS (pfile)->no_output)
2103    return;
2104
2105  line = CPP_BUFFER (pfile)->lineno;
2106  col = CPP_BUFFER (pfile)->colno;
2107  adjust_position (CPP_LINE_BASE (ip), ip->cur, &line, &col);
2108
2109  if (CPP_OPTIONS (pfile)->no_line_commands)
2110    return;
2111
2112  if (conditional) {
2113    if (line == pfile->lineno)
2114      return;
2115
2116    /* If the inherited line number is a little too small,
2117       output some newlines instead of a #line command.  */
2118    if (line > pfile->lineno && line < pfile->lineno + 8) {
2119      CPP_RESERVE (pfile, 20);
2120      while (line > pfile->lineno) {
2121        CPP_PUTC_Q (pfile, '\n');
2122        pfile->lineno++;
2123      }
2124      return;
2125    }
2126  }
2127
2128#if 0
2129  /* Don't output a line number of 0 if we can help it.  */
2130  if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
2131      && *ip->bufp == '\n') {
2132    ip->lineno++;
2133    ip->bufp++;
2134  }
2135#endif
2136
2137  CPP_RESERVE (pfile, 4 * strlen (ip->nominal_fname) + 50);
2138  {
2139#ifdef OUTPUT_LINE_COMMANDS
2140    static char sharp_line[] = "#line ";
2141#else
2142    static char sharp_line[] = "# ";
2143#endif
2144    CPP_PUTS_Q (pfile, sharp_line, sizeof(sharp_line)-1);
2145  }
2146
2147  sprintf ((char *) CPP_PWRITTEN (pfile), "%ld ", line);
2148  CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
2149
2150  quote_string (pfile, ip->nominal_fname);
2151  if (file_change != same_file) {
2152    CPP_PUTC_Q (pfile, ' ');
2153    CPP_PUTC_Q (pfile, file_change == enter_file ? '1' : '2');
2154  }
2155  /* Tell cc1 if following text comes from a system header file.  */
2156  if (ip->system_header_p) {
2157    CPP_PUTC_Q (pfile, ' ');
2158    CPP_PUTC_Q (pfile, '3');
2159  }
2160#ifndef NO_IMPLICIT_EXTERN_C
2161  /* Tell cc1plus if following text should be treated as C.  */
2162  if (ip->system_header_p == 2 && CPP_OPTIONS (pfile)->cplusplus) {
2163    CPP_PUTC_Q (pfile, ' ');
2164    CPP_PUTC_Q (pfile, '4');
2165  }
2166#endif
2167  CPP_PUTC_Q (pfile, '\n');
2168  pfile->lineno = line;
2169}
2170
2171/*
2172 * Parse a macro argument and append the info on PFILE's token_buffer.
2173 * REST_ARGS means to absorb the rest of the args.
2174 * Return nonzero to indicate a syntax error.
2175 */
2176
2177static enum cpp_token
2178macarg (pfile, rest_args)
2179     cpp_reader *pfile;
2180     int rest_args;
2181{
2182  int paren = 0;
2183  enum cpp_token token;
2184  long arg_start = CPP_WRITTEN (pfile);
2185  char save_put_out_comments = CPP_OPTIONS (pfile)->put_out_comments;
2186  CPP_OPTIONS (pfile)->put_out_comments = 0;
2187
2188  /* Try to parse as much of the argument as exists at this
2189     input stack level.  */
2190  pfile->no_macro_expand++;
2191  for (;;)
2192    {
2193      token = cpp_get_token (pfile);
2194      switch (token)
2195        {
2196        case CPP_EOF:
2197          goto done;
2198        case CPP_POP:
2199          /* If we've hit end of file, it's an error (reported by caller).
2200             Ditto if it's the end of cpp_expand_to_buffer text.
2201             If we've hit end of macro, just continue.  */
2202          if (! CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
2203            goto done;
2204          break;
2205        case CPP_LPAREN:
2206          paren++;
2207          break;
2208        case CPP_RPAREN:
2209          if (--paren < 0)
2210            goto found;
2211          break;
2212        case CPP_COMMA:
2213          /* if we've returned to lowest level and
2214             we aren't absorbing all args */
2215          if (paren == 0 && rest_args == 0)
2216            goto found;
2217          break;
2218        found:
2219          /* Remove ',' or ')' from argument buffer.  */
2220          CPP_ADJUST_WRITTEN (pfile, -1);
2221          goto done;
2222      default: ;
2223        }
2224    }
2225
2226 done:
2227  CPP_OPTIONS (pfile)->put_out_comments = save_put_out_comments;
2228  pfile->no_macro_expand--;
2229
2230  return token;
2231}
2232
2233/* Turn newlines to spaces in the string of length LENGTH at START,
2234   except inside of string constants.
2235   The string is copied into itself with its beginning staying fixed.  */
2236
2237static int
2238change_newlines (start, length)
2239     U_CHAR *start;
2240     int length;
2241{
2242  register U_CHAR *ibp;
2243  register U_CHAR *obp;
2244  register U_CHAR *limit;
2245  register int c;
2246
2247  ibp = start;
2248  limit = start + length;
2249  obp = start;
2250
2251  while (ibp < limit) {
2252    *obp++ = c = *ibp++;
2253    switch (c) {
2254
2255    case '\'':
2256    case '\"':
2257      /* Notice and skip strings, so that we don't delete newlines in them.  */
2258      {
2259        int quotec = c;
2260        while (ibp < limit) {
2261          *obp++ = c = *ibp++;
2262          if (c == quotec)
2263            break;
2264          if (c == '\n' && quotec == '\'')
2265            break;
2266        }
2267      }
2268      break;
2269    }
2270  }
2271
2272  return obp - start;
2273}
2274
2275
2276static struct tm *
2277timestamp (pfile)
2278     cpp_reader *pfile;
2279{
2280  if (!pfile->timebuf) {
2281    time_t t = time ((time_t *) 0);
2282    pfile->timebuf = localtime (&t);
2283  }
2284  return pfile->timebuf;
2285}
2286
2287static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
2288                             "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
2289                            };
2290
2291/*
2292 * expand things like __FILE__.  Place the expansion into the output
2293 * buffer *without* rescanning.
2294 */
2295
2296static void
2297special_symbol (hp, pfile)
2298     HASHNODE *hp;
2299     cpp_reader *pfile;
2300{
2301  char *buf;
2302  int i, len;
2303  int true_indepth;
2304  cpp_buffer *ip = NULL;
2305  struct tm *timebuf;
2306
2307  int paren = 0;                /* For special `defined' keyword */
2308
2309#if 0
2310  if (pcp_outfile && pcp_inside_if
2311      && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
2312    cpp_error (pfile,
2313               "Predefined macro `%s' used inside `#if' during precompilation",
2314               hp->name);
2315#endif
2316   
2317  for (ip = CPP_BUFFER (pfile); ; ip = CPP_PREV_BUFFER (ip))
2318    {
2319      if (ip == CPP_NULL_BUFFER (pfile))
2320        {
2321          cpp_error (pfile, "cccp error: not in any file?!");
2322          return;                       /* the show must go on */
2323        }
2324      if (ip->fname != NULL)
2325        break;
2326    }
2327
2328  switch (hp->type)
2329    {
2330    case T_FILE:
2331    case T_BASE_FILE:
2332      {
2333        char *string;
2334        if (hp->type == T_BASE_FILE)
2335          {
2336            while (CPP_PREV_BUFFER (ip) != CPP_NULL_BUFFER (pfile))
2337              ip = CPP_PREV_BUFFER (ip);
2338          }
2339        string = ip->nominal_fname;
2340
2341        if (!string)
2342          string = "";
2343        CPP_RESERVE (pfile, 3 + 4 * strlen (string));
2344        quote_string (pfile, string);
2345        return;
2346      }
2347
2348    case T_INCLUDE_LEVEL:
2349      true_indepth = 0;
2350      ip = CPP_BUFFER (pfile);
2351      for (;  ip != CPP_NULL_BUFFER (pfile); ip = CPP_PREV_BUFFER (ip))
2352        if (ip->fname != NULL)
2353          true_indepth++;
2354
2355      buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
2356      sprintf (buf, "%d", true_indepth - 1);
2357      break;
2358
2359  case T_VERSION:
2360      buf = (char *) alloca (3 + strlen (version_string));
2361      sprintf (buf, "\"%s\"", version_string);
2362      break;
2363
2364#ifndef NO_BUILTIN_SIZE_TYPE
2365    case T_SIZE_TYPE:
2366      buf = SIZE_TYPE;
2367      break;
2368#endif
2369
2370#ifndef NO_BUILTIN_PTRDIFF_TYPE
2371    case T_PTRDIFF_TYPE:
2372      buf = PTRDIFF_TYPE;
2373      break;
2374#endif
2375
2376    case T_WCHAR_TYPE:
2377      buf = CPP_WCHAR_TYPE (pfile);
2378    break;
2379
2380    case T_USER_LABEL_PREFIX_TYPE:
2381      buf = USER_LABEL_PREFIX;
2382      break;
2383
2384    case T_REGISTER_PREFIX_TYPE:
2385      buf = REGISTER_PREFIX;
2386      break;
2387
2388  case T_CONST:
2389      buf = (char *) alloca (4 * sizeof (int));
2390      sprintf (buf, "%d", hp->value.ival);
2391#ifdef STDC_0_IN_SYSTEM_HEADERS
2392      if (ip->system_header_p
2393          && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
2394          && ! cpp_lookup (pfile, (U_CHAR *) "__STRICT_ANSI__", -1, -1))
2395        strcpy (buf, "0");
2396#endif
2397#if 0
2398      if (pcp_inside_if && pcp_outfile)
2399        /* Output a precondition for this macro use */
2400        fprintf (pcp_outfile, "#define %s %d\n", hp->name, hp->value.ival);
2401#endif
2402      break;
2403
2404    case T_SPECLINE:
2405      {
2406        long line = ip->lineno;
2407        long col = ip->colno;
2408        adjust_position (CPP_LINE_BASE (ip), ip->cur, &line, &col);
2409
2410        buf = (char *) alloca (10);
2411        sprintf (buf, "%ld", line);
2412      }
2413      break;
2414
2415    case T_DATE:
2416    case T_TIME:
2417      buf = (char *) alloca (20);
2418      timebuf = timestamp (pfile);
2419      if (hp->type == T_DATE)
2420        sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
2421                 timebuf->tm_mday, timebuf->tm_year + 1900);
2422      else
2423        sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
2424                 timebuf->tm_sec);
2425      break;
2426
2427    case T_SPEC_DEFINED:
2428      buf = " 0 ";              /* Assume symbol is not defined */
2429      ip = CPP_BUFFER (pfile);
2430      SKIP_WHITE_SPACE (ip->cur);
2431      if (*ip->cur == '(')
2432        {
2433          paren++;
2434          ip->cur++;                    /* Skip over the paren */
2435          SKIP_WHITE_SPACE (ip->cur);
2436        }
2437
2438      if (!is_idstart[*ip->cur])
2439        goto oops;
2440      if (ip->cur[0] == 'L' && (ip->cur[1] == '\'' || ip->cur[1] == '"'))
2441        goto oops;
2442      if (hp = cpp_lookup (pfile, ip->cur, -1, -1))
2443        {
2444#if 0
2445          if (pcp_outfile && pcp_inside_if
2446              && (hp->type == T_CONST
2447                  || (hp->type == T_MACRO && hp->value.defn->predefined)))
2448            /* Output a precondition for this macro use.  */
2449            fprintf (pcp_outfile, "#define %s\n", hp->name);
2450#endif
2451          buf = " 1 ";
2452        }
2453#if 0
2454      else
2455        if (pcp_outfile && pcp_inside_if)
2456          {
2457            /* Output a precondition for this macro use */
2458            U_CHAR *cp = ip->bufp;
2459            fprintf (pcp_outfile, "#undef ");
2460            while (is_idchar[*cp]) /* Ick! */
2461              fputc (*cp++, pcp_outfile);
2462            putc ('\n', pcp_outfile);
2463          }
2464#endif
2465      while (is_idchar[*ip->cur])
2466        ++ip->cur;
2467      SKIP_WHITE_SPACE (ip->cur);
2468      if (paren)
2469        {
2470          if (*ip->cur != ')')
2471            goto oops;
2472          ++ip->cur;
2473        }
2474      break;
2475
2476    oops:
2477
2478      cpp_error (pfile, "`defined' without an identifier");
2479      break;
2480
2481    default:
2482      cpp_error (pfile, "cccp error: invalid special hash type"); /* time for gdb */
2483      abort ();
2484    }
2485  len = strlen (buf);
2486  CPP_RESERVE (pfile, len + 1);
2487  CPP_PUTS_Q (pfile, buf, len);
2488  CPP_NUL_TERMINATE_Q (pfile);
2489
2490  return;
2491}
2492
2493/* Write out a #define command for the special named MACRO_NAME
2494   to PFILE's token_buffer.  */
2495
2496static void
2497dump_special_to_buffer (pfile, macro_name)
2498     cpp_reader *pfile;
2499     char *macro_name;
2500{
2501  static char define_directive[] = "#define ";
2502  int macro_name_length = strlen (macro_name);
2503  output_line_command (pfile, 0, same_file);
2504  CPP_RESERVE (pfile, sizeof(define_directive) + macro_name_length);
2505  CPP_PUTS_Q (pfile, define_directive, sizeof(define_directive)-1);
2506  CPP_PUTS_Q (pfile, macro_name, macro_name_length);
2507  CPP_PUTC_Q (pfile, ' ');
2508  cpp_expand_to_buffer (pfile, macro_name, macro_name_length);
2509  CPP_PUTC (pfile, '\n');
2510}
2511
2512/* Initialize the built-in macros.  */
2513
2514static void
2515initialize_builtins (pfile)
2516     cpp_reader *pfile;
2517{
2518  install ((U_CHAR *)"__LINE__", -1, T_SPECLINE, 0, 0, -1);
2519  install ((U_CHAR *)"__DATE__", -1, T_DATE, 0, 0, -1);
2520  install ((U_CHAR *)"__FILE__", -1, T_FILE, 0, 0, -1);
2521  install ((U_CHAR *)"__BASE_FILE__", -1, T_BASE_FILE, 0, 0, -1);
2522  install ((U_CHAR *)"__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, 0, 0, -1);
2523  install ((U_CHAR *)"__VERSION__", -1, T_VERSION, 0, 0, -1);
2524#ifndef NO_BUILTIN_SIZE_TYPE
2525  install ((U_CHAR *)"__SIZE_TYPE__", -1, T_SIZE_TYPE, 0, 0, -1);
2526#endif
2527#ifndef NO_BUILTIN_PTRDIFF_TYPE
2528  install ((U_CHAR *)"__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, 0, 0, -1);
2529#endif
2530  install ((U_CHAR *)"__WCHAR_TYPE__", -1, T_WCHAR_TYPE, 0, 0, -1);
2531  install ((U_CHAR *)"__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE, 0, 0, -1);
2532  install ((U_CHAR *)"__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE, 0, 0, -1);
2533  install ((U_CHAR *)"__TIME__", -1, T_TIME, 0, 0, -1);
2534  if (!CPP_TRADITIONAL (pfile))
2535    install ((U_CHAR *)"__STDC__", -1, T_CONST, STDC_VALUE, 0, -1);
2536  if (CPP_OPTIONS (pfile)->objc)
2537    install ((U_CHAR *)"__OBJC__", -1, T_CONST, 1, 0, -1);
2538/*  This is supplied using a -D by the compiler driver
2539    so that it is present only when truly compiling with GNU C.  */
2540/*  install ("__GNUC__", -1, T_CONST, 2, 0, -1);  */
2541
2542  if (CPP_OPTIONS (pfile)->debug_output)
2543    {
2544      dump_special_to_buffer (pfile, "__BASE_FILE__");
2545      dump_special_to_buffer (pfile, "__VERSION__");
2546#ifndef NO_BUILTIN_SIZE_TYPE
2547      dump_special_to_buffer (pfile, "__SIZE_TYPE__");
2548#endif
2549#ifndef NO_BUILTIN_PTRDIFF_TYPE
2550      dump_special_to_buffer (pfile, "__PTRDIFF_TYPE__");
2551#endif
2552      dump_special_to_buffer (pfile, "__WCHAR_TYPE__");
2553      dump_special_to_buffer (pfile, "__DATE__");
2554      dump_special_to_buffer (pfile, "__TIME__");
2555      if (!CPP_TRADITIONAL (pfile))
2556        dump_special_to_buffer (pfile, "__STDC__");
2557      if (CPP_OPTIONS (pfile)->objc)
2558        dump_special_to_buffer (pfile, "__OBJC__");
2559    }
2560}
2561
2562/* Return 1 iff a token ending in C1 followed directly by a token C2
2563   could cause mis-tokenization.  */
2564
2565static int
2566unsafe_chars (c1, c2)
2567     int c1, c2;
2568{
2569  switch (c1)
2570    {
2571    case '+': case '-':
2572      if (c2 == c1 || c2 == '=')
2573        return 1;
2574      goto letter;
2575    case '.':
2576    case '0': case '1': case '2': case '3': case '4':
2577    case '5': case '6': case '7': case '8': case '9':
2578    case 'e': case 'E': case 'p': case 'P':
2579      if (c2 == '-' || c2 == '+')
2580        return 1; /* could extend a pre-processing number */
2581      goto letter;
2582    case 'L':
2583      if (c2 == '\'' || c2 == '\"')
2584        return 1;   /* Could turn into L"xxx" or L'xxx'.  */
2585      goto letter;
2586    letter:
2587    case '_':
2588    case 'a': case 'b': case 'c': case 'd':           case 'f':
2589    case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2590    case 'm': case 'n': case 'o':           case 'q': case 'r':
2591    case 's': case 't': case 'u': case 'v': case 'w': case 'x':
2592    case 'y': case 'z':
2593    case 'A': case 'B': case 'C': case 'D':           case 'F':
2594    case 'G': case 'H': case 'I': case 'J': case 'K':
2595    case 'M': case 'N': case 'O':           case 'Q': case 'R':
2596    case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
2597    case 'Y': case 'Z':
2598      /* We're in the middle of either a name or a pre-processing number.  */
2599      return (is_idchar[c2] || c2 == '.');
2600    case '<': case '>': case '!': case '%': case '#': case ':':
2601    case '^': case '&': case '|': case '*': case '/': case '=':
2602      return (c2 == c1 || c2 == '=');
2603    }
2604  return 0;
2605}
2606
2607/* Expand a macro call.
2608   HP points to the symbol that is the macro being called.
2609   Put the result of expansion onto the input stack
2610   so that subsequent input by our caller will use it.
2611
2612   If macro wants arguments, caller has already verified that
2613   an argument list follows; arguments come from the input stack.  */
2614
2615static void
2616macroexpand (pfile, hp)
2617     cpp_reader *pfile;
2618     HASHNODE *hp;
2619{
2620  int nargs;
2621  DEFINITION *defn = hp->value.defn;
2622  register U_CHAR *xbuf;
2623  long start_line, start_column;
2624  int xbuf_len;
2625  struct argdata *args;
2626  long old_written = CPP_WRITTEN (pfile);
2627#if 0
2628  int start_line = instack[indepth].lineno;
2629#endif
2630  int rest_args, rest_zero;
2631      register int i;
2632
2633#if 0
2634  CHECK_DEPTH (return;);
2635#endif
2636
2637#if 0
2638  /* This macro is being used inside a #if, which means it must be */
2639  /* recorded as a precondition.  */
2640  if (pcp_inside_if && pcp_outfile && defn->predefined)
2641    dump_single_macro (hp, pcp_outfile);
2642#endif
2643
2644  pfile->output_escapes++;
2645  cpp_buf_line_and_col (cpp_file_buffer (pfile), &start_line, &start_column);
2646
2647  nargs = defn->nargs;
2648
2649  if (nargs >= 0)
2650    {
2651      enum cpp_token token;
2652
2653      args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
2654
2655      for (i = 0; i < nargs; i++)
2656        {
2657          args[i].raw = args[i].expanded = 0;
2658          args[i].raw_length = 0;
2659          args[i].expand_length = args[i].stringified_length = -1;
2660          args[i].use_count = 0;
2661        }
2662
2663      /* Parse all the macro args that are supplied.  I counts them.
2664         The first NARGS args are stored in ARGS.
2665         The rest are discarded.  If rest_args is set then we assume
2666         macarg absorbed the rest of the args.  */
2667      i = 0;
2668      rest_args = 0;
2669      rest_args = 0;
2670      FORWARD(1); /* Discard the open-parenthesis before the first arg.  */
2671      do
2672        {
2673          if (rest_args)
2674            continue;
2675          if (i < nargs || (nargs == 0 && i == 0))
2676            {
2677              /* if we are working on last arg which absorbs rest of args... */
2678              if (i == nargs - 1 && defn->rest_args)
2679                rest_args = 1;
2680              args[i].raw = CPP_WRITTEN (pfile);
2681              token = macarg (pfile, rest_args);
2682              args[i].raw_length = CPP_WRITTEN (pfile) - args[i].raw;
2683              args[i].newlines = 0; /* FIXME */
2684            }
2685          else
2686            token = macarg (pfile, 0);
2687          if (token == CPP_EOF || token == CPP_POP)
2688            {
2689              cpp_error_with_line (pfile, start_line, start_column,
2690                                   "unterminated macro call");
2691              return;
2692            }
2693          i++;
2694        } while (token == CPP_COMMA);
2695
2696      /* If we got one arg but it was just whitespace, call that 0 args.  */
2697      if (i == 1)
2698        {
2699          register U_CHAR *bp = ARG_BASE + args[0].raw;
2700          register U_CHAR *lim = bp + args[0].raw_length;
2701          /* cpp.texi says for foo ( ) we provide one argument.
2702             However, if foo wants just 0 arguments, treat this as 0.  */
2703          if (nargs == 0)
2704            while (bp != lim && is_space[*bp]) bp++;
2705          if (bp == lim)
2706            i = 0;
2707        }
2708
2709      /* Don't output an error message if we have already output one for
2710         a parse error above.  */
2711      rest_zero = 0;
2712      if (nargs == 0 && i > 0)
2713        {
2714          cpp_error (pfile, "arguments given to macro `%s'", hp->name);
2715        }
2716      else if (i < nargs)
2717        {
2718          /* traditional C allows foo() if foo wants one argument.  */
2719          if (nargs == 1 && i == 0 && CPP_TRADITIONAL (pfile))
2720            ;
2721          /* the rest args token is allowed to absorb 0 tokens */
2722          else if (i == nargs - 1 && defn->rest_args)
2723            rest_zero = 1;
2724          else if (i == 0)
2725            cpp_error (pfile, "macro `%s' used without args", hp->name);
2726          else if (i == 1)
2727            cpp_error (pfile, "macro `%s' used with just one arg", hp->name);
2728          else
2729            cpp_error (pfile, "macro `%s' used with only %d args",
2730                       hp->name, i);
2731      }
2732      else if (i > nargs)
2733        {
2734          cpp_error (pfile,
2735                     "macro `%s' used with too many (%d) args", hp->name, i);
2736        }
2737    }
2738
2739  /* If macro wants zero args, we parsed the arglist for checking only.
2740     Read directly from the macro definition.  */
2741  if (nargs <= 0)
2742    {
2743      xbuf = defn->expansion;
2744      xbuf_len = defn->length;
2745    }
2746  else
2747    {
2748      register U_CHAR *exp = defn->expansion;
2749      register int offset;      /* offset in expansion,
2750                                   copied a piece at a time */
2751      register int totlen;      /* total amount of exp buffer filled so far */
2752
2753      register struct reflist *ap, *last_ap;
2754
2755      /* Macro really takes args.  Compute the expansion of this call.  */
2756
2757      /* Compute length in characters of the macro's expansion.
2758         Also count number of times each arg is used.  */
2759      xbuf_len = defn->length;
2760      for (ap = defn->pattern; ap != NULL; ap = ap->next)
2761        {
2762          if (ap->stringify)
2763            {
2764              register struct argdata *arg = &args[ap->argno];
2765              /* Stringify it it hasn't already been */
2766              if (arg->stringified_length < 0)
2767                {
2768                  int arglen = arg->raw_length;
2769                  int escaped = 0;
2770                  int in_string = 0;
2771                  int c;
2772                  /* Initially need_space is -1.  Otherwise, 1 means the
2773                     previous character was a space, but we suppressed it;
2774                     0 means the previous character was a non-space.  */
2775                  int need_space = -1;
2776                  i = 0;
2777                  arg->stringified = CPP_WRITTEN (pfile);
2778                  if (!CPP_TRADITIONAL (pfile))
2779                    CPP_PUTC (pfile, '\"'); /* insert beginning quote */
2780                  for (; i < arglen; i++)
2781                    {
2782                      c = (ARG_BASE + arg->raw)[i];
2783
2784                      if (! in_string)
2785                        {
2786                          /* Internal sequences of whitespace are replaced by
2787                             one space except within an string or char token.*/
2788                          if (is_space[c])
2789                            {
2790                              if (CPP_WRITTEN (pfile) > arg->stringified
2791                                  && (CPP_PWRITTEN (pfile))[-1] == '@')
2792                                {
2793                                  /* "@ " escape markers are removed */
2794                                  CPP_ADJUST_WRITTEN (pfile, -1);
2795                                  continue;
2796                                }
2797                              if (need_space == 0)
2798                                need_space = 1;
2799                              continue;
2800                            }
2801                          else if (need_space > 0)
2802                            CPP_PUTC (pfile, ' ');
2803                          need_space = 0;
2804                        }
2805
2806                      if (escaped)
2807                        escaped = 0;
2808                      else
2809                        {
2810                          if (c == '\\')
2811                            escaped = 1;
2812                          if (in_string)
2813                            {
2814                              if (c == in_string)
2815                                in_string = 0;
2816                            }
2817                          else if (c == '\"' || c == '\'')
2818                            in_string = c;
2819                        }
2820
2821                      /* Escape these chars */
2822                      if (c == '\"' || (in_string && c == '\\'))
2823                        CPP_PUTC (pfile, '\\');
2824                      if (isprint (c))
2825                        CPP_PUTC (pfile, c);
2826                      else
2827                        {
2828                          CPP_RESERVE (pfile, 4);
2829                          sprintf ((char *)CPP_PWRITTEN (pfile), "\\%03o",
2830                                   (unsigned int) c);
2831                          CPP_ADJUST_WRITTEN (pfile, 4);
2832                        }
2833                    }
2834                  if (!CPP_TRADITIONAL (pfile))
2835                    CPP_PUTC (pfile, '\"'); /* insert ending quote */
2836                  arg->stringified_length
2837                    = CPP_WRITTEN (pfile) - arg->stringified;
2838                }
2839              xbuf_len += args[ap->argno].stringified_length;
2840            }
2841          else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL (pfile))
2842            /* Add 4 for two newline-space markers to prevent
2843               token concatenation.  */
2844            xbuf_len += args[ap->argno].raw_length + 4;
2845          else
2846            {
2847              /* We have an ordinary (expanded) occurrence of the arg.
2848                 So compute its expansion, if we have not already.  */
2849              if (args[ap->argno].expand_length < 0)
2850                {
2851                  args[ap->argno].expanded = CPP_WRITTEN (pfile);
2852                  cpp_expand_to_buffer (pfile,
2853                                        ARG_BASE + args[ap->argno].raw,
2854                                        args[ap->argno].raw_length);
2855
2856                  args[ap->argno].expand_length
2857                    = CPP_WRITTEN (pfile) - args[ap->argno].expanded;
2858                }
2859
2860              /* Add 4 for two newline-space markers to prevent
2861                 token concatenation.  */
2862              xbuf_len += args[ap->argno].expand_length + 4;
2863            }
2864          if (args[ap->argno].use_count < 10)
2865            args[ap->argno].use_count++;
2866        }
2867
2868      xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
2869
2870      /* Generate in XBUF the complete expansion
2871         with arguments substituted in.
2872         TOTLEN is the total size generated so far.
2873         OFFSET is the index in the definition
2874         of where we are copying from.  */
2875      offset = totlen = 0;
2876      for (last_ap = NULL, ap = defn->pattern; ap != NULL;
2877           last_ap = ap, ap = ap->next)
2878        {
2879          register struct argdata *arg = &args[ap->argno];
2880          int count_before = totlen;
2881
2882          /* Add chars to XBUF.  */
2883          for (i = 0; i < ap->nchars; i++, offset++)
2884            xbuf[totlen++] = exp[offset];
2885
2886          /* If followed by an empty rest arg with concatenation,
2887             delete the last run of nonwhite chars.  */
2888          if (rest_zero && totlen > count_before
2889              && ((ap->rest_args && ap->raw_before)
2890                  || (last_ap != NULL && last_ap->rest_args
2891                      && last_ap->raw_after)))
2892            {
2893              /* Delete final whitespace.  */
2894              while (totlen > count_before && is_space[xbuf[totlen - 1]])
2895                totlen--;
2896
2897              /* Delete the nonwhites before them.  */
2898              while (totlen > count_before && ! is_space[xbuf[totlen - 1]])
2899                totlen--;
2900            }
2901
2902          if (ap->stringify != 0)
2903            {
2904              bcopy (ARG_BASE + arg->stringified,
2905                     xbuf + totlen, arg->stringified_length);
2906              totlen += arg->stringified_length;
2907            }
2908          else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL (pfile))
2909            {
2910              U_CHAR *p1 = ARG_BASE + arg->raw;
2911              U_CHAR *l1 = p1 + arg->raw_length;
2912              if (ap->raw_before)
2913                {
2914                  while (p1 != l1 && is_space[*p1]) p1++;
2915                  while (p1 != l1 && is_idchar[*p1])
2916                    xbuf[totlen++] = *p1++;
2917                  /* Delete any no-reexpansion marker that follows
2918                     an identifier at the beginning of the argument
2919                     if the argument is concatenated with what precedes it.  */
2920                  if (p1[0] == '@' && p1[1] == '-')
2921                    p1 += 2;
2922                }
2923              if (ap->raw_after)
2924                {
2925                  /* Arg is concatenated after: delete trailing whitespace,
2926                     whitespace markers, and no-reexpansion markers.  */
2927                  while (p1 != l1)
2928                    {
2929                      if (is_space[l1[-1]]) l1--;
2930                      else if (l1[-1] == '-')
2931                        {
2932                          U_CHAR *p2 = l1 - 1;
2933                          /* If a `-' is preceded by an odd number of newlines then it
2934                             and the last newline are a no-reexpansion marker.  */
2935                          while (p2 != p1 && p2[-1] == '\n') p2--;
2936                          if ((l1 - 1 - p2) & 1) {
2937                            l1 -= 2;
2938                          }
2939                          else break;
2940                        }
2941                      else break;
2942                    }
2943                }
2944
2945              bcopy (p1, xbuf + totlen, l1 - p1);
2946              totlen += l1 - p1;
2947            }
2948          else
2949            {
2950              U_CHAR *expanded = ARG_BASE + arg->expanded;
2951              if (!ap->raw_before && totlen > 0 && arg->expand_length
2952                  && !CPP_TRADITIONAL(pfile)
2953                  && unsafe_chars (xbuf[totlen-1], expanded[0]))
2954                {
2955                  xbuf[totlen++] = '@';
2956                  xbuf[totlen++] = ' ';
2957                }
2958
2959              bcopy (expanded, xbuf + totlen, arg->expand_length);
2960              totlen += arg->expand_length;
2961
2962              if (!ap->raw_after && totlen > 0 && offset < defn->length
2963                  && !CPP_TRADITIONAL(pfile)
2964                  && unsafe_chars (xbuf[totlen-1], exp[offset]))
2965                {
2966                  xbuf[totlen++] = '@';
2967                  xbuf[totlen++] = ' ';
2968                }
2969
2970              /* If a macro argument with newlines is used multiple times,
2971                 then only expand the newlines once.  This avoids creating
2972                 output lines which don't correspond to any input line,
2973                 which confuses gdb and gcov.  */
2974              if (arg->use_count > 1 && arg->newlines > 0)
2975                {
2976                  /* Don't bother doing change_newlines for subsequent
2977                     uses of arg.  */
2978                  arg->use_count = 1;
2979                  arg->expand_length
2980                    = change_newlines (expanded, arg->expand_length);
2981                }
2982            }
2983
2984          if (totlen > xbuf_len)
2985            abort ();
2986      }
2987
2988      /* if there is anything left of the definition
2989         after handling the arg list, copy that in too.  */
2990
2991      for (i = offset; i < defn->length; i++)
2992        {
2993          /* if we've reached the end of the macro */
2994          if (exp[i] == ')')
2995            rest_zero = 0;
2996          if (! (rest_zero && last_ap != NULL && last_ap->rest_args
2997                 && last_ap->raw_after))
2998            xbuf[totlen++] = exp[i];
2999        }
3000
3001      xbuf[totlen] = 0;
3002      xbuf_len = totlen;
3003
3004    }
3005
3006  pfile->output_escapes--;
3007
3008  /* Now put the expansion on the input stack
3009     so our caller will commence reading from it.  */
3010  push_macro_expansion (pfile, xbuf, xbuf_len, hp);
3011  CPP_BUFFER (pfile)->has_escapes = 1;
3012
3013  /* Pop the space we've used in the token_buffer for argument expansion.  */
3014  CPP_SET_WRITTEN (pfile, old_written);
3015   
3016  /* Recursive macro use sometimes works traditionally.
3017     #define foo(x,y) bar (x (y,0), y)
3018     foo (foo, baz)  */
3019 
3020  if (!CPP_TRADITIONAL (pfile))
3021    hp->type = T_DISABLED;
3022}
3023
3024static void
3025push_macro_expansion (pfile, xbuf, xbuf_len, hp)
3026     cpp_reader *pfile;
3027     register U_CHAR *xbuf;
3028     int xbuf_len;
3029     HASHNODE *hp;
3030{
3031  register cpp_buffer *mbuf = cpp_push_buffer (pfile, xbuf, xbuf_len);
3032  if (mbuf == NULL)
3033    return;
3034  mbuf->cleanup = macro_cleanup;
3035  mbuf->data = hp;
3036
3037  /* The first chars of the expansion should be a "@ " added by
3038     collect_expansion.  This is to prevent accidental token-pasting
3039     between the text preceding the macro invocation, and the macro
3040     expansion text.
3041
3042     We would like to avoid adding unneeded spaces (for the sake of
3043     tools that use cpp, such as imake).  In some common cases we can
3044     tell that it is safe to omit the space.
3045
3046     The character before the macro invocation cannot have been an
3047     idchar (or else it would have been pasted with the idchars of
3048     the macro name).  Therefore, if the first non-space character
3049     of the expansion is an idchar, we do not need the extra space
3050     to prevent token pasting.
3051
3052     Also, we don't need the extra space if the first char is '(',
3053     or some other (less common) characters.  */
3054
3055  if (xbuf[0] == '@' && xbuf[1] == ' '
3056      && (is_idchar[xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
3057          || xbuf[2] == '\"'))
3058    mbuf->cur += 2;
3059}
3060
3061/* Like cpp_get_token, except that it does not read past end-of-line.
3062   Also, horizontal space is skipped, and macros are popped.  */
3063
3064static enum cpp_token
3065get_directive_token (pfile)
3066     cpp_reader *pfile;
3067{
3068  for (;;)
3069    {
3070      long old_written = CPP_WRITTEN (pfile);
3071      enum cpp_token token;
3072      cpp_skip_hspace (pfile);
3073      if (PEEKC () == '\n')
3074          return CPP_VSPACE;
3075      token = cpp_get_token (pfile);
3076      switch (token)
3077      {
3078      case CPP_POP:
3079          if (! CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
3080              return token;
3081          /* ... else fall though ...  */
3082      case CPP_HSPACE:  case CPP_COMMENT:
3083          CPP_SET_WRITTEN (pfile, old_written);
3084          break;
3085      default:
3086          return token;
3087      }
3088    }
3089}
3090
3091/* Handle #include and #import.
3092   This function expects to see "fname" or <fname> on the input.
3093
3094   The input is normally in part of the output_buffer following
3095   CPP_WRITTEN, and will get overwritten by output_line_command.
3096   I.e. in input file specification has been popped by handle_directive.
3097   This is safe.  */
3098
3099static int
3100do_include (pfile, keyword, unused1, unused2)
3101     cpp_reader *pfile;
3102     struct directive *keyword;
3103     U_CHAR *unused1, *unused2;
3104{
3105  int importing = (keyword->type == T_IMPORT);
3106  int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
3107  char *fname;          /* Dynamically allocated fname buffer */
3108  char *pcftry;
3109  char *pcfname;
3110  U_CHAR *fbeg, *fend;          /* Beginning and end of fname */
3111  enum cpp_token token;
3112
3113  /* Chain of dirs to search */
3114  struct file_name_list *search_start = CPP_OPTIONS (pfile)->include;
3115  struct file_name_list dsp[1]; /* First in chain, if #include "..." */
3116  struct file_name_list *searchptr = 0;
3117  long old_written = CPP_WRITTEN (pfile);
3118
3119  int flen;
3120
3121  int f;                        /* file number */
3122
3123  int retried = 0;              /* Have already tried macro
3124                                   expanding the include line */
3125  int angle_brackets = 0;       /* 0 for "...", 1 for <...> */
3126  int pcf = -1;
3127  char *pcfbuf;
3128  char *pcfbuflimit;
3129  int pcfnum;
3130  f= -1;                        /* JF we iz paranoid! */
3131
3132  if (CPP_PEDANTIC (pfile) && !CPP_BUFFER (pfile)->system_header_p)
3133    {
3134      if (importing)
3135        cpp_pedwarn (pfile, "ANSI C does not allow `#import'");
3136      if (skip_dirs)
3137        cpp_pedwarn (pfile, "ANSI C does not allow `#include_next'");
3138    }
3139
3140  if (importing && CPP_OPTIONS (pfile)->warn_import
3141      && !CPP_OPTIONS (pfile)->inhibit_warnings
3142      && !CPP_BUFFER (pfile)->system_header_p && !pfile->import_warning)
3143    {
3144      pfile->import_warning = 1;
3145      cpp_warning (pfile, "using `#import' is not recommended");
3146      fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
3147      fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
3148      fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
3149      fprintf (stderr, "  #ifndef _FOO_H_INCLUDED\n");
3150      fprintf (stderr, "  #define _FOO_H_INCLUDED\n");
3151      fprintf (stderr, "  ... <real contents of file> ...\n");
3152      fprintf (stderr, "  #endif /* Not _FOO_H_INCLUDED */\n\n");
3153      fprintf (stderr, "Then users can use `#include' any number of times.\n");
3154      fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
3155      fprintf (stderr, "when it is equipped with such a conditional.\n");
3156    }
3157
3158  pfile->parsing_include_directive++;
3159  token = get_directive_token (pfile);
3160  pfile->parsing_include_directive--;
3161
3162  if (token == CPP_STRING)
3163    {
3164      /* FIXME - check no trailing garbage */
3165      fbeg = pfile->token_buffer + old_written + 1;
3166      fend = CPP_PWRITTEN (pfile) - 1;
3167      if (fbeg[-1] == '<')
3168        {
3169          angle_brackets = 1;
3170          /* If -I-, start with the first -I dir after the -I-.  */
3171          if (CPP_OPTIONS (pfile)->first_bracket_include)
3172            search_start = CPP_OPTIONS (pfile)->first_bracket_include;
3173        }
3174      /* If -I- was specified, don't search current dir, only spec'd ones.  */
3175      else if (! CPP_OPTIONS (pfile)->ignore_srcdir)
3176        {
3177          cpp_buffer *fp = CPP_BUFFER (pfile);
3178          /* We have "filename".  Figure out directory this source
3179             file is coming from and put it on the front of the list.  */
3180
3181          for ( ; fp != CPP_NULL_BUFFER (pfile); fp = CPP_PREV_BUFFER (fp))
3182            {
3183              int n;
3184              char *ep,*nam;
3185
3186              if ((nam = fp->nominal_fname) != NULL)
3187                {
3188                  /* Found a named file.  Figure out dir of the file,
3189                     and put it in front of the search list.  */
3190                  dsp[0].next = search_start;
3191                  search_start = dsp;
3192#ifndef VMS
3193                  ep = rindex (nam, '/');
3194#else                           /* VMS */
3195                  ep = rindex (nam, ']');
3196                  if (ep == NULL) ep = rindex (nam, '>');
3197                  if (ep == NULL) ep = rindex (nam, ':');
3198                  if (ep != NULL) ep++;
3199#endif                          /* VMS */
3200                  if (ep != NULL)
3201                    {
3202                      n = ep - nam;
3203                      dsp[0].fname = (char *) alloca (n + 1);
3204                      strncpy (dsp[0].fname, nam, n);
3205                      dsp[0].fname[n] = '\0';
3206                      if (n + INCLUDE_LEN_FUDGE > pfile->max_include_len)
3207                        pfile->max_include_len = n + INCLUDE_LEN_FUDGE;
3208                    }
3209                  else
3210                    {
3211                      dsp[0].fname = 0; /* Current directory */
3212                    }
3213                  dsp[0].got_name_map = 0;
3214                  break;
3215                }
3216            }
3217        }
3218    }
3219#ifdef VMS
3220  else if (token == CPP_NAME)
3221    {
3222      /*
3223       * Support '#include xyz' like VAX-C to allow for easy use of all the
3224       * decwindow include files. It defaults to '#include <xyz.h>' (so the
3225       * code from case '<' is repeated here) and generates a warning.
3226       */
3227      cpp_warning (pfile,
3228                   "VAX-C-style include specification found, use '#include <filename.h>' !");
3229      angle_brackets = 1;
3230      /* If -I-, start with the first -I dir after the -I-.  */
3231      if (CPP_OPTIONS (pfile)->first_bracket_include)
3232        search_start = CPP_OPTIONS (pfile)->first_bracket_include;
3233      fbeg = pfile->token_buffer + old_written;
3234      fend = CPP_PWRITTEN (pfile);
3235    }
3236#endif
3237  else
3238    {
3239      cpp_error (pfile,
3240                 "`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
3241      CPP_SET_WRITTEN (pfile, old_written);
3242      skip_rest_of_line (pfile);
3243      return 0;
3244    }
3245
3246  *fend = 0;
3247
3248  token = get_directive_token (pfile);
3249  if (token != CPP_VSPACE)
3250    {
3251      cpp_error (pfile, "junk at end of `#include'");
3252      while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
3253        token = get_directive_token (pfile);
3254    }
3255
3256  /* For #include_next, skip in the search path
3257     past the dir in which the containing file was found.  */
3258  if (skip_dirs)
3259    {
3260      cpp_buffer *fp = CPP_BUFFER (pfile);
3261      for (; fp != CPP_NULL_BUFFER (pfile); fp = CPP_PREV_BUFFER (fp))
3262        if (fp->fname != NULL)
3263          {
3264            /* fp->dir is null if the containing file was specified with
3265               an absolute file name.  In that case, don't skip anything.  */
3266            if (fp->dir == SELF_DIR_DUMMY)
3267              search_start = CPP_OPTIONS (pfile)->include;
3268            else if (fp->dir)
3269              search_start = fp->dir->next;
3270            break;
3271          }
3272    }
3273
3274  CPP_SET_WRITTEN (pfile, old_written);
3275
3276  flen = fend - fbeg;
3277
3278  if (flen == 0)
3279    {
3280      cpp_error (pfile, "empty file name in `#%s'", keyword->name);
3281      return 0;
3282    }
3283
3284  /* Allocate this permanently, because it gets stored in the definitions
3285     of macros.  */
3286  fname = (char *) xmalloc (pfile->max_include_len + flen + 4);
3287  /* + 2 above for slash and terminating null.  */
3288  /* + 2 added for '.h' on VMS (to support '#include filename') */
3289
3290  /* If specified file name is absolute, just open it.  */
3291
3292  if (*fbeg == '/') {
3293    strncpy (fname, fbeg, flen);
3294    fname[flen] = 0;
3295    if (redundant_include_p (pfile, fname))
3296      return 0;
3297    if (importing)
3298      f = lookup_import (pfile, fname, NULL_PTR);
3299    else
3300      f = open_include_file (pfile, fname, NULL_PTR);
3301    if (f == -2)
3302      return 0;         /* Already included this file */
3303  } else {
3304    /* Search directory path, trying to open the file.
3305       Copy each filename tried into FNAME.  */
3306
3307    for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
3308      if (searchptr->fname) {
3309        /* The empty string in a search path is ignored.
3310           This makes it possible to turn off entirely
3311           a standard piece of the list.  */
3312        if (searchptr->fname[0] == 0)
3313          continue;
3314        strcpy (fname, searchptr->fname);
3315        strcat (fname, "/");
3316        fname[strlen (fname) + flen] = 0;
3317      } else {
3318        fname[0] = 0;
3319      }
3320      strncat (fname, fbeg, flen);
3321#ifdef VMS
3322      /* Change this 1/2 Unix 1/2 VMS file specification into a
3323         full VMS file specification */
3324      if (searchptr->fname && (searchptr->fname[0] != 0)) {
3325        /* Fix up the filename */
3326        hack_vms_include_specification (fname);
3327      } else {
3328        /* This is a normal VMS filespec, so use it unchanged.  */
3329        strncpy (fname, fbeg, flen);
3330        fname[flen] = 0;
3331        /* if it's '#include filename', add the missing .h */
3332        if (index(fname,'.')==NULL) {
3333          strcat (fname, ".h");
3334        }
3335      }
3336#endif /* VMS */
3337      /* ??? There are currently 3 separate mechanisms for avoiding processing
3338         of redundant include files: #import, #pragma once, and
3339         redundant_include_p.  It would be nice if they were unified.  */
3340      if (redundant_include_p (pfile, fname))
3341        return 0;
3342      if (importing)
3343        f = lookup_import (pfile, fname, searchptr);
3344      else
3345        f = open_include_file (pfile, fname, searchptr);
3346      if (f == -2)
3347        return 0;                       /* Already included this file */
3348#ifdef EACCES
3349      else if (f == -1 && errno == EACCES)
3350        cpp_warning (pfile, "Header file %s exists, but is not readable",
3351                     fname);
3352#endif
3353      if (f >= 0)
3354        break;
3355    }
3356  }
3357
3358  if (f < 0)
3359    {
3360      /* A file that was not found.  */
3361      strncpy (fname, fbeg, flen);
3362      fname[flen] = 0;
3363      /* If generating dependencies and -MG was specified, we assume missing
3364         files are leaf files, living in the same directory as the source file
3365         or other similar place; these missing files may be generated from
3366         other files and may not exist yet (eg: y.tab.h).  */
3367
3368      if (CPP_OPTIONS(pfile)->print_deps_missing_files
3369          && CPP_PRINT_DEPS (pfile)
3370          > (angle_brackets || (pfile->system_include_depth > 0)))
3371        {
3372          /* If it was requested as a system header file,
3373             then assume it belongs in the first place to look for such.  */
3374          if (angle_brackets)
3375            {
3376              for (searchptr = search_start; searchptr;
3377                   searchptr = searchptr->next)
3378                {
3379                  if (searchptr->fname)
3380                    {
3381                      char *p;
3382
3383                      if (searchptr->fname[0] == 0)
3384                        continue;
3385                      p = (char *) alloca (strlen (searchptr->fname)
3386                                           + strlen (fname) + 2);
3387                      strcpy (p, searchptr->fname);
3388                      strcat (p, "/");
3389                      strcat (p, fname);
3390                      deps_output (pfile, p, ' ');
3391                      break;
3392                    }
3393                }
3394            }
3395          else
3396            {
3397              /* Otherwise, omit the directory, as if the file existed
3398                 in the directory with the source.  */
3399              deps_output (pfile, fname, ' ');
3400            }
3401        }
3402      /* If -M was specified, and this header file won't be added to the
3403         dependency list, then don't count this as an error, because we can
3404         still produce correct output.  Otherwise, we can't produce correct
3405         output, because there may be dependencies we need inside the missing
3406         file, and we don't know what directory this missing file exists in.*/
3407      else if (CPP_PRINT_DEPS (pfile)
3408               && (CPP_PRINT_DEPS (pfile)
3409                   <= (angle_brackets || (pfile->system_include_depth > 0))))
3410        cpp_warning (pfile, "No include path in which to find %s", fname);
3411      else if (search_start)
3412        cpp_error_from_errno (pfile, fname);
3413      else
3414        cpp_error (pfile, "No include path in which to find %s", fname);
3415    }
3416  else {
3417    /* Check to see if this include file is a once-only include file.
3418       If so, give up.  */
3419
3420    struct file_name_list *ptr;
3421
3422    for (ptr = pfile->dont_repeat_files; ptr; ptr = ptr->next) {
3423      if (!strcmp (ptr->fname, fname)) {
3424        close (f);
3425        return 0;                               /* This file was once'd.  */
3426      }
3427    }
3428
3429    for (ptr = pfile->all_include_files; ptr; ptr = ptr->next) {
3430      if (!strcmp (ptr->fname, fname))
3431        break;                          /* This file was included before.  */
3432    }
3433
3434    if (ptr == 0) {
3435      /* This is the first time for this file.  */
3436      /* Add it to list of files included.  */
3437
3438      ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
3439      ptr->control_macro = 0;
3440      ptr->c_system_include_path = 0;
3441      ptr->next = pfile->all_include_files;
3442      pfile->all_include_files = ptr;
3443      ptr->fname = savestring (fname);
3444      ptr->got_name_map = 0;
3445
3446      /* For -M, add this file to the dependencies.  */
3447      if (CPP_PRINT_DEPS (pfile)
3448          > (angle_brackets || (pfile->system_include_depth > 0)))
3449        deps_output (pfile, fname, ' ');
3450    }   
3451
3452    /* Handle -H option.  */
3453    if (CPP_OPTIONS(pfile)->print_include_names)
3454      {
3455        cpp_buffer *buf = CPP_BUFFER (pfile);
3456        while ((buf = CPP_PREV_BUFFER (buf)) != CPP_NULL_BUFFER (pfile))
3457          putc ('.', stderr);
3458        fprintf (stderr, "%s\n", fname);
3459      }
3460
3461    if (angle_brackets)
3462      pfile->system_include_depth++;
3463
3464    /* Actually process the file.  */
3465
3466    /* Record file on "seen" list for #import.  */
3467    add_import (pfile, f, fname);
3468
3469    pcftry = (char *) alloca (strlen (fname) + 30);
3470    pcfbuf = 0;
3471    pcfnum = 0;
3472
3473#if 0
3474    if (!no_precomp)
3475      {
3476        struct stat stat_f;
3477
3478        fstat (f, &stat_f);
3479
3480        do {
3481          sprintf (pcftry, "%s%d", fname, pcfnum++);
3482
3483          pcf = open (pcftry, O_RDONLY, 0666);
3484          if (pcf != -1)
3485            {
3486              struct stat s;
3487
3488              fstat (pcf, &s);
3489              if (bcmp ((char *) &stat_f.st_ino, (char *) &s.st_ino,
3490                        sizeof (s.st_ino))
3491                  || stat_f.st_dev != s.st_dev)
3492                {
3493                  pcfbuf = check_precompiled (pcf, fname, &pcfbuflimit);
3494                  /* Don't need it any more.  */
3495                  close (pcf);
3496                }
3497              else
3498                {
3499                  /* Don't need it at all.  */
3500                  close (pcf);
3501                  break;
3502                }
3503            }
3504        } while (pcf != -1 && !pcfbuf);
3505      }
3506#endif
3507   
3508    /* Actually process the file */
3509    if (cpp_push_buffer (pfile, NULL, 0) == NULL)
3510      return 0;
3511    if (finclude (pfile, f, fname, is_system_include (pfile, fname),
3512                  searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
3513      {
3514        output_line_command (pfile, 0, enter_file);
3515        pfile->only_seen_white = 2;
3516      }
3517
3518    if (angle_brackets)
3519      pfile->system_include_depth--;
3520  }
3521  return 0;
3522}
3523
3524/* Return nonzero if there is no need to include file NAME
3525   because it has already been included and it contains a conditional
3526   to make a repeated include do nothing.  */
3527
3528static int
3529redundant_include_p (pfile, name)
3530     cpp_reader *pfile;
3531     char *name;
3532{
3533  struct file_name_list *l = pfile->all_include_files;
3534  for (; l; l = l->next)
3535    if (! strcmp (name, l->fname)
3536        && l->control_macro
3537        && cpp_lookup (pfile, l->control_macro, -1, -1))
3538      return 1;
3539  return 0;
3540}
3541
3542/* Return nonzero if the given FILENAME is an absolute pathname which
3543   designates a file within one of the known "system" include file
3544   directories.  We assume here that if the given FILENAME looks like
3545   it is the name of a file which resides either directly in a "system"
3546   include file directory, or within any subdirectory thereof, then the
3547   given file must be a "system" include file.  This function tells us
3548   if we should suppress pedantic errors/warnings for the given FILENAME.
3549
3550   The value is 2 if the file is a C-language system header file
3551   for which C++ should (on most systems) assume `extern "C"'.  */
3552
3553static int
3554is_system_include (pfile, filename)
3555     cpp_reader *pfile;
3556     register char *filename;
3557{
3558  struct file_name_list *searchptr;
3559
3560  for (searchptr = CPP_OPTIONS (pfile)->first_system_include; searchptr;
3561       searchptr = searchptr->next)
3562    if (searchptr->fname) {
3563      register char *sys_dir = searchptr->fname;
3564      register unsigned length = strlen (sys_dir);
3565
3566      if (! strncmp (sys_dir, filename, length) && filename[length] == '/')
3567        {
3568          if (searchptr->c_system_include_path)
3569            return 2;
3570          else
3571            return 1;
3572        }
3573    }
3574  return 0;
3575}
3576
3577
3578/*
3579 * Install a name in the assertion hash table.
3580 *
3581 * If LEN is >= 0, it is the length of the name.
3582 * Otherwise, compute the length by scanning the entire name.
3583 *
3584 * If HASH is >= 0, it is the precomputed hash code.
3585 * Otherwise, compute the hash code.
3586 */
3587
3588static ASSERTION_HASHNODE *
3589assertion_install (pfile, name, len, hash)
3590     cpp_reader *pfile;
3591     U_CHAR *name;
3592     int len;
3593     int hash;
3594{
3595  register ASSERTION_HASHNODE *hp;
3596  register int i, bucket;
3597  register U_CHAR *p, *q;
3598
3599  i = sizeof (ASSERTION_HASHNODE) + len + 1;
3600  hp = (ASSERTION_HASHNODE *) xmalloc (i);
3601  bucket = hash;
3602  hp->bucket_hdr = &pfile->assertion_hashtab[bucket];
3603  hp->next = pfile->assertion_hashtab[bucket];
3604  pfile->assertion_hashtab[bucket] = hp;
3605  hp->prev = NULL;
3606  if (hp->next != NULL)
3607    hp->next->prev = hp;
3608  hp->length = len;
3609  hp->value = 0;
3610  hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
3611  p = hp->name;
3612  q = name;
3613  for (i = 0; i < len; i++)
3614    *p++ = *q++;
3615  hp->name[len] = 0;
3616  return hp;
3617}
3618/*
3619 * find the most recent hash node for name name (ending with first
3620 * non-identifier char) installed by install
3621 *
3622 * If LEN is >= 0, it is the length of the name.
3623 * Otherwise, compute the length by scanning the entire name.
3624 *
3625 * If HASH is >= 0, it is the precomputed hash code.
3626 * Otherwise, compute the hash code.
3627 */
3628
3629static ASSERTION_HASHNODE *
3630assertion_lookup (pfile, name, len, hash)
3631     cpp_reader *pfile;
3632     U_CHAR *name;
3633     int len;
3634     int hash;
3635{
3636  register ASSERTION_HASHNODE *bucket;
3637
3638  bucket = pfile->assertion_hashtab[hash];
3639  while (bucket) {
3640    if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
3641      return bucket;
3642    bucket = bucket->next;
3643  }
3644  return NULL;
3645}
3646
3647static void
3648delete_assertion (hp)
3649     ASSERTION_HASHNODE *hp;
3650{
3651  struct tokenlist_list *tail;
3652  if (hp->prev != NULL)
3653    hp->prev->next = hp->next;
3654  if (hp->next != NULL)
3655    hp->next->prev = hp->prev;
3656
3657  for (tail = hp->value; tail; )
3658    {
3659      struct tokenlist_list *next = tail->next;
3660      free_token_list (tail->tokens);
3661      free (tail);
3662      tail = next;
3663    }
3664
3665  /* Make sure that the bucket chain header that
3666     the deleted guy was on points to the right thing afterwards.  */
3667  if (hp == *hp->bucket_hdr)
3668    *hp->bucket_hdr = hp->next;
3669
3670  free (hp);
3671}
3672
3673/* Convert a character string literal into a nul-terminated string.
3674   The input string is [IN ... LIMIT).
3675   The result is placed in RESULT.  RESULT can be the same as IN.
3676   The value returned in the end of the string written to RESULT,
3677   or NULL on error.  */
3678
3679static U_CHAR *
3680convert_string (pfile, result, in, limit, handle_escapes)
3681     cpp_reader *pfile;
3682     register U_CHAR *result, *in, *limit;
3683     int handle_escapes;
3684{
3685  U_CHAR c;
3686  c = *in++;
3687  if (c != '\"')
3688    return NULL;
3689  while (in < limit)
3690    {
3691      U_CHAR c = *in++;
3692      switch (c)
3693        {
3694        case '\0':
3695          return NULL;
3696        case '\"':
3697          limit = in;
3698          break;
3699        case '\\':
3700          if (handle_escapes)
3701            {
3702              char *bpc = (char *) in;
3703              int i = (U_CHAR) cpp_parse_escape (pfile, &bpc);
3704              in = (U_CHAR *) bpc;
3705              if (i >= 0)
3706                *result++ = (U_CHAR)c;
3707              break;
3708            }
3709          /* else fall through */
3710        default:
3711          *result++ = c;
3712        }
3713    }
3714  *result = 0;
3715  return result;
3716}
3717
3718/*
3719 * interpret #line command.  Remembers previously seen fnames
3720 * in its very own hash table.
3721 */
3722#define FNAME_HASHSIZE 37
3723
3724static int
3725do_line (pfile, keyword)
3726     cpp_reader *pfile;
3727     struct directive *keyword;
3728{
3729  cpp_buffer *ip = CPP_BUFFER (pfile);
3730  int new_lineno;
3731  long old_written = CPP_WRITTEN (pfile);
3732  enum file_change_code file_change = same_file;
3733  enum cpp_token token;
3734  int i;
3735
3736  token = get_directive_token (pfile);
3737
3738  if (token != CPP_NUMBER
3739      || !isdigit(pfile->token_buffer[old_written]))
3740    {
3741      cpp_error (pfile, "invalid format `#line' command");
3742      goto bad_line_directive;
3743    }
3744
3745  /* The Newline at the end of this line remains to be processed.
3746     To put the next line at the specified line number,
3747     we must store a line number now that is one less.  */
3748  new_lineno = atoi ((char *)(pfile->token_buffer + old_written)) - 1;
3749  CPP_SET_WRITTEN (pfile, old_written);
3750
3751  /* NEW_LINENO is one less than the actual line number here.  */
3752  if (CPP_PEDANTIC (pfile) && new_lineno < 0)
3753    cpp_pedwarn (pfile, "line number out of range in `#line' command");
3754
3755#if 0 /* #line 10"foo.c" is supposed to be allowed.  */
3756  if (PEEKC() && !is_space[PEEKC()]) {
3757    cpp_error (pfile, "invalid format `#line' command");
3758    goto bad_line_directive;
3759  }
3760#endif
3761
3762  token = get_directive_token (pfile);
3763
3764  if (token == CPP_STRING) {
3765    U_CHAR *fname = pfile->token_buffer + old_written;
3766    U_CHAR *end_name;
3767    static HASHNODE *fname_table[FNAME_HASHSIZE];
3768    HASHNODE *hp, **hash_bucket;
3769    U_CHAR *p;
3770    long num_start;
3771    int fname_length;
3772
3773    /* Turn the file name, which is a character string literal,
3774       into a null-terminated string.  Do this in place.  */
3775    end_name = convert_string (pfile, fname, fname, CPP_PWRITTEN (pfile), 1);
3776    if (end_name == NULL)
3777    {
3778        cpp_error (pfile, "invalid format `#line' command");
3779        goto bad_line_directive;
3780    }
3781
3782    fname_length = end_name - fname;
3783
3784    num_start = CPP_WRITTEN (pfile);
3785    token = get_directive_token (pfile);
3786    if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP) {
3787      p = pfile->token_buffer + num_start;
3788      if (CPP_PEDANTIC (pfile))
3789        cpp_pedwarn (pfile, "garbage at end of `#line' command");
3790
3791      if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
3792      {
3793        cpp_error (pfile, "invalid format `#line' command");
3794        goto bad_line_directive;
3795      }
3796      if (*p == '1')
3797        file_change = enter_file;
3798      else if (*p == 2)
3799        file_change = leave_file;
3800      else if (*p == 3)
3801        ip->system_header_p = 1;
3802      else /* if (*p == 4) */
3803        ip->system_header_p = 2;
3804
3805      CPP_SET_WRITTEN (pfile, num_start);
3806      token = get_directive_token (pfile);
3807      p = pfile->token_buffer + num_start;
3808      if (token == CPP_NUMBER && p[1] == '\0' && (*p == '3' || *p== '4')) {
3809        ip->system_header_p = *p == 3 ? 1 : 2;
3810        token = get_directive_token (pfile);
3811      }
3812      if (token != CPP_VSPACE) {
3813        cpp_error (pfile, "invalid format `#line' command");
3814        goto bad_line_directive;
3815      }
3816    }
3817
3818    hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
3819    for (hp = *hash_bucket; hp != NULL; hp = hp->next)
3820      if (hp->length == fname_length
3821          && strncmp (hp->value.cpval, fname, fname_length) == 0) {
3822        ip->nominal_fname = hp->value.cpval;
3823        break;
3824      }
3825    if (hp == 0) {
3826      /* Didn't find it; cons up a new one.  */
3827      hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
3828      hp->next = *hash_bucket;
3829      *hash_bucket = hp;
3830
3831      hp->length = fname_length;
3832      ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
3833      bcopy (fname, hp->value.cpval, fname_length);
3834    }
3835  }
3836  else if (token != CPP_VSPACE && token != CPP_EOF) {
3837    cpp_error (pfile, "invalid format `#line' command");
3838    goto bad_line_directive;
3839  }
3840
3841  ip->lineno = new_lineno;
3842 bad_line_directive:
3843  skip_rest_of_line (pfile);
3844  CPP_SET_WRITTEN (pfile, old_written);
3845  output_line_command (pfile, 0, file_change);
3846  return 0;
3847}
3848
3849/*
3850 * remove the definition of a symbol from the symbol table.
3851 * according to un*x /lib/cpp, it is not an error to undef
3852 * something that has no definitions, so it isn't one here either.
3853 */
3854
3855static int
3856do_undef (pfile, keyword, buf, limit)
3857     cpp_reader *pfile;
3858     struct directive *keyword;
3859     U_CHAR *buf, *limit;
3860{
3861  int sym_length;
3862  HASHNODE *hp;
3863  U_CHAR *orig_buf = buf;
3864
3865#if 0
3866  /* If this is a precompiler run (with -pcp) pass thru #undef commands.  */
3867  if (pcp_outfile && keyword)
3868    pass_thru_directive (buf, limit, pfile, keyword);
3869#endif
3870
3871  SKIP_WHITE_SPACE (buf);
3872  sym_length = check_macro_name (pfile, buf, "macro");
3873
3874  while ((hp = cpp_lookup (pfile, buf, sym_length, -1)) != NULL)
3875    {
3876      /* If we are generating additional info for debugging (with -g) we
3877         need to pass through all effective #undef commands.  */
3878      if (CPP_OPTIONS (pfile)->debug_output && keyword)
3879        pass_thru_directive (orig_buf, limit, pfile, keyword);
3880      if (hp->type != T_MACRO)
3881        cpp_warning (pfile, "undefining `%s'", hp->name);
3882      delete_macro (hp);
3883    }
3884
3885  if (CPP_PEDANTIC (pfile)) {
3886    buf += sym_length;
3887    SKIP_WHITE_SPACE (buf);
3888    if (buf != limit)
3889      cpp_pedwarn (pfile, "garbage after `#undef' directive");
3890  }
3891  return 0;
3892}
3893
3894/*
3895 * Report an error detected by the program we are processing.
3896 * Use the text of the line in the error message.
3897 * (We use error because it prints the filename & line#.)
3898 */
3899
3900static int
3901do_error (pfile, keyword, buf, limit)
3902     cpp_reader *pfile;
3903     struct directive *keyword;
3904     U_CHAR *buf, *limit;
3905{
3906  int length = limit - buf;
3907  U_CHAR *copy = (U_CHAR *) alloca (length + 1);
3908  bcopy (buf, copy, length);
3909  copy[length] = 0;
3910  SKIP_WHITE_SPACE (copy);
3911  cpp_error (pfile, "#error %s", copy);
3912  return 0;
3913}
3914
3915/*
3916 * Report a warning detected by the program we are processing.
3917 * Use the text of the line in the warning message, then continue.
3918 * (We use error because it prints the filename & line#.)
3919 */
3920
3921static int
3922do_warning (pfile, keyword, buf, limit)
3923     cpp_reader *pfile;
3924     struct directive *keyword;
3925     U_CHAR *buf, *limit;
3926{
3927  int length = limit - buf;
3928  U_CHAR *copy = (U_CHAR *) alloca (length + 1);
3929  bcopy (buf, copy, length);
3930  copy[length] = 0;
3931  SKIP_WHITE_SPACE (copy);
3932  /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
3933     if -pedantic-errors is given, #warning should cause an error.  */
3934  cpp_pedwarn (pfile, "#warning %s", copy);
3935  return 0;
3936}
3937
3938/* Remember the name of the current file being read from so that we can
3939   avoid ever including it again.  */
3940
3941static int
3942do_once (pfile)
3943     cpp_reader *pfile;
3944{
3945  cpp_buffer *ip = NULL;
3946  struct file_name_list *new;
3947
3948  for (ip = CPP_BUFFER (pfile); ; ip = CPP_PREV_BUFFER (ip))
3949    {
3950      if (ip == CPP_NULL_BUFFER (pfile))
3951        return 0;
3952      if (ip->fname != NULL)
3953        break;
3954    }
3955
3956   
3957  new = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
3958  new->next = pfile->dont_repeat_files;
3959  pfile->dont_repeat_files = new;
3960  new->fname = savestring (ip->fname);
3961  new->control_macro = 0;
3962  new->got_name_map = 0;
3963  new->c_system_include_path = 0;
3964
3965  return 0;
3966}
3967
3968/* Report program identification.  */
3969
3970static int
3971do_ident (pfile, keyword, buf, limit)
3972     cpp_reader *pfile;
3973     struct directive *keyword;
3974     U_CHAR *buf, *limit;
3975{
3976/*  long old_written = CPP_WRITTEN (pfile);*/
3977  int len;
3978
3979  /* Allow #ident in system headers, since that's not user's fault.  */
3980  if (CPP_PEDANTIC (pfile) && !CPP_BUFFER (pfile)->system_header_p)
3981    cpp_pedwarn (pfile, "ANSI C does not allow `#ident'");
3982
3983  /* Leave rest of line to be read by later calls to cpp_get_token.  */
3984
3985  return 0;
3986}
3987
3988/* #pragma and its argument line have already been copied to the output file.
3989   Just check for some recognized pragmas that need validation here.  */
3990
3991static int
3992do_pragma (pfile, keyword, buf, limit)
3993     cpp_reader *pfile;
3994     struct directive *keyword;
3995     U_CHAR *buf, *limit;
3996{
3997  while (*buf == ' ' || *buf == '\t')
3998    buf++;
3999  if (!strncmp (buf, "once", 4)) {
4000    /* Allow #pragma once in system headers, since that's not the user's
4001       fault.  */
4002    if (!CPP_BUFFER (pfile)->system_header_p)
4003      cpp_warning (pfile, "`#pragma once' is obsolete");
4004    do_once (pfile);
4005  }
4006
4007  if (!strncmp (buf, "implementation", 14)) {
4008    /* Be quiet about `#pragma implementation' for a file only if it hasn't
4009       been included yet.  */
4010    struct file_name_list *ptr;
4011    U_CHAR *p = buf + 14, *fname, *inc_fname;
4012    int fname_len;
4013    SKIP_WHITE_SPACE (p);
4014    if (*p == '\n' || *p != '\"')
4015      return 0;
4016
4017    fname = p + 1;
4018    p = (U_CHAR *) index (fname, '\"');
4019    fname_len = p != NULL ? p - fname : strlen (fname);
4020   
4021    for (ptr = pfile->all_include_files; ptr; ptr = ptr->next) {
4022      inc_fname = (U_CHAR *) rindex (ptr->fname, '/');
4023      inc_fname = inc_fname ? inc_fname + 1 : (U_CHAR *) ptr->fname;
4024      if (inc_fname && !strncmp (inc_fname, fname, fname_len))
4025        cpp_warning (pfile,
4026           "`#pragma implementation' for `%s' appears after file is included",
4027                     fname);
4028    }
4029  }
4030
4031  return 0;
4032}
4033
4034#if 0
4035/* This was a fun hack, but #pragma seems to start to be useful.
4036   By failing to recognize it, we pass it through unchanged to cc1.  */
4037
4038/*
4039 * the behavior of the #pragma directive is implementation defined.
4040 * this implementation defines it as follows.
4041 */
4042
4043static int
4044do_pragma ()
4045{
4046  close (0);
4047  if (open ("/dev/tty", O_RDONLY, 0666) != 0)
4048    goto nope;
4049  close (1);
4050  if (open ("/dev/tty", O_WRONLY, 0666) != 1)
4051    goto nope;
4052  execl ("/usr/games/hack", "#pragma", 0);
4053  execl ("/usr/games/rogue", "#pragma", 0);
4054  execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
4055  execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
4056nope:
4057  fatal ("You are in a maze of twisty compiler features, all different");
4058}
4059#endif
4060
4061/* Just ignore #sccs, on systems where we define it at all.  */
4062
4063static int
4064do_sccs (pfile, keyword, buf, limit)
4065     cpp_reader *pfile;
4066     struct directive *keyword;
4067     U_CHAR *buf, *limit;
4068{
4069  if (CPP_PEDANTIC (pfile))
4070    cpp_pedwarn (pfile, "ANSI C does not allow `#sccs'");
4071  return 0;
4072}
4073
4074/*
4075 * handle #if command by
4076 *   1) inserting special `defined' keyword into the hash table
4077 *      that gets turned into 0 or 1 by special_symbol (thus,
4078 *      if the luser has a symbol called `defined' already, it won't
4079 *      work inside the #if command)
4080 *   2) rescan the input into a temporary output buffer
4081 *   3) pass the output buffer to the yacc parser and collect a value
4082 *   4) clean up the mess left from steps 1 and 2.
4083 *   5) call conditional_skip to skip til the next #endif (etc.),
4084 *      or not, depending on the value from step 3.
4085 */
4086
4087static int
4088do_if (pfile, keyword, buf, limit)
4089     cpp_reader *pfile;
4090     struct directive *keyword;
4091     U_CHAR *buf, *limit;
4092{
4093  HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
4094  conditional_skip (pfile, value == 0, T_IF, NULL_PTR);
4095  return 0;
4096}
4097
4098/*
4099 * handle a #elif directive by not changing  if_stack  either.
4100 * see the comment above do_else.
4101 */
4102
4103static int
4104do_elif (pfile, keyword, buf, limit)
4105     cpp_reader *pfile;
4106     struct directive *keyword;
4107     U_CHAR *buf, *limit;
4108{
4109  if (pfile->if_stack == CPP_BUFFER (pfile)->if_stack) {
4110    cpp_error (pfile, "`#elif' not within a conditional");
4111    return 0;
4112  } else {
4113    if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF) {
4114      cpp_error (pfile, "`#elif' after `#else'");
4115#if 0
4116      fprintf (stderr, " (matches line %d", pfile->if_stack->lineno);
4117#endif
4118      if (pfile->if_stack->fname != NULL && CPP_BUFFER (pfile)->fname != NULL
4119          && strcmp (pfile->if_stack->fname,
4120                     CPP_BUFFER (pfile)->nominal_fname) != 0)
4121        fprintf (stderr, ", file %s", pfile->if_stack->fname);
4122      fprintf (stderr, ")\n");
4123    }
4124    pfile->if_stack->type = T_ELIF;
4125  }
4126
4127  if (pfile->if_stack->if_succeeded)
4128    skip_if_group (pfile, 0);
4129  else {
4130    HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
4131    if (value == 0)
4132      skip_if_group (pfile, 0);
4133    else {
4134      ++pfile->if_stack->if_succeeded;  /* continue processing input */
4135      output_line_command (pfile, 1, same_file);
4136    }
4137  }
4138  return 0;
4139}
4140
4141/*
4142 * evaluate a #if expression in BUF, of length LENGTH,
4143 * then parse the result as a C expression and return the value as an int.
4144 */
4145
4146static HOST_WIDE_INT
4147eval_if_expression (pfile, buf, length)
4148     cpp_reader *pfile;
4149     U_CHAR *buf;
4150     int length;
4151{
4152  HASHNODE *save_defined;
4153  HOST_WIDE_INT value;
4154  long old_written = CPP_WRITTEN (pfile);
4155
4156  save_defined = install ((U_CHAR *)"defined", -1, T_SPEC_DEFINED, 0, 0, -1);
4157  pfile->pcp_inside_if = 1;
4158
4159  value = cpp_parse_expr (pfile);
4160  pfile->pcp_inside_if = 0;
4161  delete_macro (save_defined);  /* clean up special symbol */
4162
4163  CPP_SET_WRITTEN (pfile, old_written); /* Pop */
4164
4165  return value;
4166}
4167
4168/*
4169 * routine to handle ifdef/ifndef.  Try to look up the symbol,
4170 * then do or don't skip to the #endif/#else/#elif depending
4171 * on what directive is actually being processed.
4172 */
4173
4174static int
4175do_xifdef (pfile, keyword, unused1, unused2)
4176     cpp_reader *pfile;
4177     struct directive *keyword;
4178     U_CHAR *unused1, *unused2;
4179{
4180  int skip;
4181  cpp_buffer *ip = CPP_BUFFER (pfile);
4182  U_CHAR *ident;
4183  int ident_length;
4184  enum cpp_token token;
4185  int start_of_file = 0;
4186  U_CHAR *control_macro = 0;
4187  int old_written = CPP_WRITTEN (pfile);
4188
4189  /* Detect a #ifndef at start of file (not counting comments).  */
4190  if (ip->fname != 0 && keyword->type == T_IFNDEF)
4191    start_of_file = pfile->only_seen_white == 2;
4192
4193  pfile->no_macro_expand++;
4194  token = get_directive_token (pfile);
4195  pfile->no_macro_expand--;
4196
4197  ident = pfile->token_buffer + old_written;
4198  ident_length = CPP_WRITTEN (pfile) - old_written;
4199  CPP_SET_WRITTEN (pfile, old_written); /* Pop */
4200
4201  if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
4202    {
4203      skip = (keyword->type == T_IFDEF);
4204      if (! CPP_TRADITIONAL (pfile))
4205        cpp_pedwarn (pfile, "`#%s' with no argument", keyword->name);
4206    }
4207  else if (token == CPP_NAME)
4208    {
4209      HASHNODE *hp = cpp_lookup (pfile, ident, ident_length, -1);
4210      skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
4211      if (start_of_file && !skip)
4212        {
4213          control_macro = (U_CHAR *) xmalloc (ident_length + 1);
4214          bcopy (ident, control_macro, ident_length + 1);
4215        }
4216    }
4217  else
4218    {
4219      skip = (keyword->type == T_IFDEF);
4220      if (! CPP_TRADITIONAL (pfile))
4221        cpp_error (pfile, "`#%s' with invalid argument", keyword->name);
4222    }
4223
4224  if (!CPP_TRADITIONAL (pfile))
4225    { int c;
4226      cpp_skip_hspace (pfile);
4227      c = PEEKC ();
4228      if (c != EOF && c != '\n')
4229        cpp_pedwarn (pfile, "garbage at end of `#%s' argument", keyword->name);
4230    }
4231  skip_rest_of_line (pfile);
4232
4233#if 0
4234    if (pcp_outfile) {
4235      /* Output a precondition for this macro.  */
4236      if (hp && hp->value.defn->predefined)
4237        fprintf (pcp_outfile, "#define %s\n", hp->name);
4238      else {
4239        U_CHAR *cp = buf;
4240        fprintf (pcp_outfile, "#undef ");
4241        while (is_idchar[*cp]) /* Ick! */
4242          fputc (*cp++, pcp_outfile);
4243        putc ('\n', pcp_outfile);
4244      }
4245#endif
4246
4247  conditional_skip (pfile, skip, T_IF, control_macro);
4248  return 0;
4249}
4250
4251/* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
4252   If this is a #ifndef starting at the beginning of a file,
4253   CONTROL_MACRO is the macro name tested by the #ifndef.
4254   Otherwise, CONTROL_MACRO is 0.  */
4255
4256static void
4257conditional_skip (pfile, skip, type, control_macro)
4258     cpp_reader *pfile;
4259     int skip;
4260     enum node_type type;
4261     U_CHAR *control_macro;
4262{
4263  IF_STACK_FRAME *temp;
4264
4265  temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
4266  temp->fname = CPP_BUFFER (pfile)->nominal_fname;
4267#if 0
4268  temp->lineno = CPP_BUFFER (pfile)->lineno;
4269#endif
4270  temp->next = pfile->if_stack;
4271  temp->control_macro = control_macro;
4272  pfile->if_stack = temp;
4273
4274  pfile->if_stack->type = type;
4275
4276  if (skip != 0) {
4277    skip_if_group (pfile, 0);
4278    return;
4279  } else {
4280    ++pfile->if_stack->if_succeeded;
4281    output_line_command (pfile, 1, same_file);
4282  }
4283}
4284
4285/*
4286 * skip to #endif, #else, or #elif.  adjust line numbers, etc.
4287 * leaves input ptr at the sharp sign found.
4288 * If ANY is nonzero, return at next directive of any sort.
4289 */
4290
4291static void
4292skip_if_group (pfile, any)
4293     cpp_reader *pfile;
4294     int any;
4295{
4296  int c;
4297  int at_beg_of_line = 1;
4298  struct directive *kt;
4299  IF_STACK_FRAME *save_if_stack = pfile->if_stack; /* don't pop past here */
4300#if 0
4301  U_CHAR *beg_of_line = bp;
4302#endif
4303  register int ident_length;
4304  U_CHAR *ident, *after_ident;
4305  struct parse_marker line_start_mark;
4306
4307  parse_set_mark (&line_start_mark, pfile);
4308
4309  if (CPP_OPTIONS (pfile)->output_conditionals) {
4310    static char failed[] = "#failed\n";
4311    CPP_PUTS (pfile, failed, sizeof(failed)-1);
4312    pfile->lineno++;
4313    output_line_command (pfile, 1, same_file);
4314  }
4315
4316 beg_of_line:
4317  if (CPP_OPTIONS (pfile)->output_conditionals)
4318    {
4319      cpp_buffer *pbuf = CPP_BUFFER (pfile);
4320      U_CHAR *start_line = pbuf->buf + line_start_mark.position;
4321      CPP_PUTS (pfile, start_line, pbuf->cur - start_line);
4322    }
4323  parse_move_mark (&line_start_mark, pfile);
4324  if (!CPP_TRADITIONAL (pfile))
4325      cpp_skip_hspace (pfile);
4326  c  = GETC();
4327  if (c == '#')
4328    {
4329      int old_written = CPP_WRITTEN (pfile);
4330      cpp_skip_hspace (pfile);
4331
4332      parse_name (pfile, GETC());
4333      ident_length = CPP_WRITTEN (pfile) - old_written;
4334      ident = pfile->token_buffer + old_written;
4335      pfile->limit = ident;
4336#if 0
4337      if (ident_length == 0)
4338        goto not_a_directive;
4339
4340      /* Handle # followed by a line number.  */
4341
4342      /* Avoid error for `###' and similar cases unless -pedantic.  */
4343#endif
4344
4345      for (kt = directive_table; kt->length >= 0; kt++)
4346        {
4347          IF_STACK_FRAME *temp;
4348          if (ident_length == kt->length
4349              && strncmp (ident, kt->name, kt->length) == 0)
4350            {
4351              /* If we are asked to return on next directive, do so now.  */
4352              if (any)
4353                goto done;
4354
4355              switch (kt->type)
4356                {
4357                case T_IF:
4358                case T_IFDEF:
4359                case T_IFNDEF:
4360                  temp
4361                    = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
4362                  temp->next = pfile->if_stack;
4363                  pfile->if_stack = temp;
4364#if 0
4365                  temp->lineno = CPP_BUFFER(pfile)->lineno;
4366#endif
4367                  temp->fname = CPP_BUFFER(pfile)->nominal_fname;
4368                  temp->type = kt->type;
4369                  break;
4370                case T_ELSE:
4371                case T_ENDIF:
4372                  if (CPP_PEDANTIC (pfile) && pfile->if_stack != save_if_stack)
4373                    validate_else (pfile,
4374                                   kt->type == T_ELSE ? "#else" : "#endif");
4375                case T_ELIF:
4376                  if (pfile->if_stack == CPP_BUFFER (pfile)->if_stack)
4377                    {
4378                      cpp_error (pfile,
4379                                 "`#%s' not within a conditional", kt->name);
4380                      break;
4381                    }
4382                  else if (pfile->if_stack == save_if_stack)
4383                    goto done;          /* found what we came for */
4384
4385                  if (kt->type != T_ENDIF)
4386                    {
4387                      if (pfile->if_stack->type == T_ELSE)
4388                        cpp_error (pfile, "`#else' or `#elif' after `#else'");
4389                      pfile->if_stack->type = kt->type;
4390                      break;
4391                    }
4392
4393                  temp = pfile->if_stack;
4394                  pfile->if_stack = temp->next;
4395                  free (temp);
4396                  break;
4397              default: ;
4398                }
4399              break;
4400            }
4401          /* Don't let erroneous code go by.  */
4402          if (kt->length < 0 && !CPP_OPTIONS (pfile)->lang_asm
4403              && CPP_PEDANTIC (pfile))
4404            cpp_pedwarn (pfile, "invalid preprocessor directive name");
4405        }
4406      c = GETC ();
4407    }
4408  /* We're in the middle of a line.  Skip the rest of it.  */
4409  for (;;) {
4410    switch (c)
4411      {
4412        long old;
4413      case EOF:
4414        goto done;
4415      case '/':                 /* possible comment */
4416        c = skip_comment (pfile, NULL);
4417        if (c == EOF)
4418          goto done;
4419        break;
4420      case '\"':
4421      case '\'':
4422        FORWARD(-1);
4423        old = CPP_WRITTEN (pfile);
4424        cpp_get_token (pfile);
4425        CPP_SET_WRITTEN (pfile, old);
4426        break;
4427      case '\\':
4428        /* Char after backslash loses its special meaning.  */
4429        if (PEEKC() == '\n')
4430          FORWARD (1);
4431        break;
4432      case '\n':
4433        goto beg_of_line;
4434        break;
4435      }
4436    c = GETC ();
4437  }
4438 done:
4439  if (CPP_OPTIONS (pfile)->output_conditionals) {
4440    static char end_failed[] = "#endfailed\n";
4441    CPP_PUTS (pfile, end_failed, sizeof(end_failed)-1);
4442    pfile->lineno++;
4443  }
4444  pfile->only_seen_white = 1;
4445  parse_goto_mark (&line_start_mark, pfile);
4446  parse_clear_mark (&line_start_mark);
4447}
4448
4449/*
4450 * handle a #else directive.  Do this by just continuing processing
4451 * without changing  if_stack ;  this is so that the error message
4452 * for missing #endif's etc. will point to the original #if.  It
4453 * is possible that something different would be better.
4454 */
4455
4456static int
4457do_else (pfile, keyword, buf, limit)
4458     cpp_reader *pfile;
4459     struct directive *keyword;
4460     U_CHAR *buf, *limit;
4461{
4462  cpp_buffer *ip = CPP_BUFFER (pfile);
4463
4464  if (CPP_PEDANTIC (pfile))
4465    validate_else (pfile, "#else");
4466  skip_rest_of_line (pfile);
4467
4468  if (pfile->if_stack == CPP_BUFFER (pfile)->if_stack) {
4469    cpp_error (pfile, "`#else' not within a conditional");
4470    return 0;
4471  } else {
4472    /* #ifndef can't have its special treatment for containing the whole file
4473       if it has a #else clause.  */
4474    pfile->if_stack->control_macro = 0;
4475
4476    if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF) {
4477      cpp_error (pfile, "`#else' after `#else'");
4478      fprintf (stderr, " (matches line %d", pfile->if_stack->lineno);
4479      if (strcmp (pfile->if_stack->fname, ip->nominal_fname) != 0)
4480        fprintf (stderr, ", file %s", pfile->if_stack->fname);
4481      fprintf (stderr, ")\n");
4482    }
4483    pfile->if_stack->type = T_ELSE;
4484  }
4485
4486  if (pfile->if_stack->if_succeeded)
4487    skip_if_group (pfile, 0);
4488  else {
4489    ++pfile->if_stack->if_succeeded;    /* continue processing input */
4490    output_line_command (pfile, 1, same_file);
4491  }
4492  return 0;
4493}
4494
4495/*
4496 * unstack after #endif command
4497 */
4498
4499static int
4500do_endif (pfile, keyword, buf, limit)
4501     cpp_reader *pfile;
4502     struct directive *keyword;
4503     U_CHAR *buf, *limit;
4504{
4505  if (CPP_PEDANTIC (pfile))
4506    validate_else (pfile, "#endif");
4507  skip_rest_of_line (pfile);
4508
4509  if (pfile->if_stack == CPP_BUFFER (pfile)->if_stack)
4510    cpp_error (pfile, "unbalanced `#endif'");
4511  else
4512    {
4513      IF_STACK_FRAME *temp = pfile->if_stack;
4514      pfile->if_stack = temp->next;
4515      if (temp->control_macro != 0)
4516        {
4517          /* This #endif matched a #ifndef at the start of the file.
4518             See if it is at the end of the file.  */
4519          struct parse_marker start_mark;
4520          int c;
4521
4522          parse_set_mark (&start_mark, pfile);
4523
4524          for (;;)
4525            {
4526              cpp_skip_hspace (pfile);
4527              c = GETC ();
4528              if (c != '\n')
4529                break;
4530            }
4531          parse_goto_mark (&start_mark, pfile);
4532          parse_clear_mark (&start_mark);
4533
4534          if (c == EOF)
4535            {
4536              /* If we get here, this #endif ends a #ifndef
4537                 that contains all of the file (aside from whitespace).
4538                 Arrange not to include the file again
4539                 if the macro that was tested is defined.
4540
4541                 Do not do this for the top-level file in a -include or any
4542                 file in a -imacros.  */
4543#if 0
4544FIXME!
4545              if (indepth != 0
4546                  && ! (indepth == 1 && pfile->no_record_file)
4547                  && ! (pfile->no_record_file && no_output))
4548#endif
4549                {
4550                  struct file_name_list *ifile = pfile->all_include_files;
4551                 
4552                  for ( ; ifile != NULL; ifile = ifile->next)
4553                    {
4554                      if (!strcmp (ifile->fname, CPP_BUFFER (pfile)->fname))
4555                        {
4556                          ifile->control_macro = temp->control_macro;
4557                          break;
4558                        }
4559                    }
4560                }
4561            }
4562        }
4563      free (temp);
4564      output_line_command (pfile, 1, same_file);
4565    }
4566  return 0;
4567}
4568
4569/* When an #else or #endif is found while skipping failed conditional,
4570   if -pedantic was specified, this is called to warn about text after
4571   the command name.  P points to the first char after the command name.  */
4572
4573static void
4574validate_else (pfile, directive)
4575     cpp_reader *pfile;
4576     char *directive;
4577{
4578  int c;
4579  cpp_skip_hspace (pfile);
4580  c = PEEKC ();
4581  if (c != EOF && c != '\n')
4582    cpp_pedwarn (pfile,
4583                 "text following `%s' violates ANSI standard", directive);
4584}
4585
4586/* Get the next token, and add it to the text in pfile->token_buffer.
4587   Return the kind of token we got.  */
4588 
4589enum cpp_token
4590cpp_get_token (pfile)
4591     cpp_reader *pfile;
4592{
4593  register int c, c2, c3;
4594  long old_written;
4595  long start_line, start_column;
4596  enum cpp_token token;
4597  struct cpp_options *opts = CPP_OPTIONS (pfile);
4598  CPP_BUFFER (pfile)->prev = CPP_BUFFER (pfile)->cur;
4599 get_next:
4600  c = GETC();
4601  if (c == EOF)
4602    {
4603    handle_eof:
4604      if (CPP_BUFFER (pfile)->seen_eof)
4605        {
4606          if (cpp_pop_buffer (pfile) != CPP_NULL_BUFFER (pfile))
4607            goto get_next;
4608          else
4609            return CPP_EOF;
4610        }
4611      else
4612        {
4613          cpp_buffer *next_buf
4614            = CPP_PREV_BUFFER (CPP_BUFFER (pfile));
4615          CPP_BUFFER (pfile)->seen_eof = 1;
4616          if (CPP_BUFFER (pfile)->nominal_fname
4617              && next_buf != CPP_NULL_BUFFER (pfile))
4618            {
4619              /* We're about to return from an #include file.
4620                 Emit #line information now (as part of the CPP_POP) result.
4621                 But the #line refers to the file we will pop to.  */
4622              cpp_buffer *cur_buffer = CPP_BUFFER (pfile);
4623              CPP_BUFFER (pfile) = next_buf;
4624              pfile->input_stack_listing_current = 0;
4625              output_line_command (pfile, 0, leave_file);
4626              CPP_BUFFER (pfile) = cur_buffer;
4627            }
4628          return CPP_POP;
4629        }
4630    }
4631  else
4632    {
4633      switch (c)
4634        {
4635          long newlines;
4636          struct parse_marker start_mark;
4637        case '/':
4638          if (PEEKC () == '=')
4639            goto op2;
4640          if (opts->put_out_comments)
4641            parse_set_mark (&start_mark, pfile);
4642          newlines = 0;
4643          cpp_buf_line_and_col (cpp_file_buffer (pfile),
4644                                &start_line, &start_column);
4645          c = skip_comment (pfile, &newlines);
4646          if (opts->put_out_comments && (c == '/' || c == EOF))
4647            parse_clear_mark (&start_mark);
4648          if (c == '/')
4649            goto randomchar;
4650          if (c == EOF)
4651            {
4652              cpp_error_with_line (pfile, start_line, start_column,
4653                                   "unterminated comment");
4654              goto handle_eof;
4655            }
4656          c = '/';  /* Initial letter of comment.  */
4657        return_comment:
4658          /* Comments are equivalent to spaces.
4659             For -traditional, a comment is equivalent to nothing.  */
4660          if (opts->put_out_comments)
4661            {
4662              cpp_buffer *pbuf = CPP_BUFFER (pfile);
4663              long dummy;
4664              U_CHAR *start = pbuf->buf + start_mark.position;
4665              int len = pbuf->cur - start;
4666              CPP_RESERVE(pfile, 1 + len);
4667              CPP_PUTC_Q (pfile, c);
4668              CPP_PUTS_Q (pfile, start, len);
4669              pfile->lineno += newlines;
4670              parse_clear_mark (&start_mark);
4671              return CPP_COMMENT;
4672            }
4673          else if (CPP_TRADITIONAL (pfile))
4674            {
4675              return CPP_COMMENT;
4676            }
4677          else
4678            {
4679#if 0
4680              /* This may not work if cpp_get_token is called recursively,
4681                 since many places look for horizontal space.  */
4682              if (newlines)
4683                {
4684                  /* Copy the newlines into the output buffer, in order to
4685                     avoid the pain of a #line every time a multiline comment
4686                     is seen.  */
4687                  CPP_RESERVE(pfile, newlines);
4688                  while (--newlines >= 0)
4689                    {
4690                      CPP_PUTC_Q (pfile, '\n');
4691                      pfile->lineno++;
4692                    }
4693                  return CPP_VSPACE;
4694                }
4695#endif
4696              CPP_RESERVE(pfile, 1);
4697              CPP_PUTC_Q (pfile, ' ');
4698              return CPP_HSPACE;
4699            }
4700#if 0
4701          if (opts->for_lint) {
4702            U_CHAR *argbp;
4703            int cmdlen, arglen;
4704            char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
4705           
4706            if (lintcmd != NULL) {
4707              /* I believe it is always safe to emit this newline: */
4708              obp[-1] = '\n';
4709              bcopy ("#pragma lint ", (char *) obp, 13);
4710              obp += 13;
4711              bcopy (lintcmd, (char *) obp, cmdlen);
4712              obp += cmdlen;
4713
4714              if (arglen != 0) {
4715                *(obp++) = ' ';
4716                bcopy (argbp, (char *) obp, arglen);
4717                obp += arglen;
4718              }
4719
4720              /* OK, now bring us back to the state we were in before we entered
4721                 this branch.  We need #line because the newline for the pragma
4722                 could mess things up.  */
4723              output_line_command (pfile, 0, same_file);
4724              *(obp++) = ' ';   /* just in case, if comments are copied thru */
4725              *(obp++) = '/';
4726            }
4727          }
4728#endif
4729
4730        case '#':
4731#if 0
4732          /* If this is expanding a macro definition, don't recognize
4733             preprocessor directives.  */
4734          if (ip->macro != 0)
4735            goto randomchar;
4736          /* If this is expand_into_temp_buffer, recognize them
4737             only after an actual newline at this level,
4738             not at the beginning of the input level.  */
4739          if (ip->fname == 0 && beg_of_line == ip->buf)
4740            goto randomchar;
4741          if (ident_length)
4742            goto specialchar;
4743#endif
4744
4745          if (!pfile->only_seen_white)
4746            goto randomchar;
4747          if (handle_directive (pfile))
4748            return CPP_DIRECTIVE;
4749          pfile->only_seen_white = 0;
4750          return CPP_OTHER;
4751
4752        case '\"':
4753        case '\'':
4754          /* A single quoted string is treated like a double -- some
4755             programs (e.g., troff) are perverse this way */
4756          cpp_buf_line_and_col (cpp_file_buffer (pfile),
4757                                &start_line, &start_column);
4758          old_written = CPP_WRITTEN (pfile);
4759        string:
4760          CPP_PUTC (pfile, c);
4761          while (1)
4762            {
4763              int cc = GETC();
4764              if (cc == EOF)
4765                {
4766                  if (CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
4767                    {
4768                      /* try harder: this string crosses a macro expansion
4769                         boundary.  This can happen naturally if -traditional.
4770                         Otherwise, only -D can make a macro with an unmatched
4771                         quote.  */
4772                        cpp_buffer *next_buf
4773                            = CPP_PREV_BUFFER (CPP_BUFFER (pfile));
4774                        (*CPP_BUFFER (pfile)->cleanup)
4775                            (CPP_BUFFER (pfile), pfile);
4776                        CPP_BUFFER (pfile) = next_buf;
4777                        continue;
4778                    }
4779                  if (!CPP_TRADITIONAL (pfile))
4780                    {
4781                      cpp_error_with_line (pfile, start_line, start_column,
4782                              "unterminated string or character constant");
4783                      if (pfile->multiline_string_line != start_line
4784                          && pfile->multiline_string_line != 0)
4785                        cpp_error_with_line (pfile,
4786                                             pfile->multiline_string_line, -1,
4787                               "possible real start of unterminated constant");
4788                      pfile->multiline_string_line = 0;
4789                    }
4790                  break;
4791                }
4792              CPP_PUTC (pfile, cc);
4793              switch (cc)
4794                {
4795                case '\n':
4796                  /* Traditionally, end of line ends a string constant with
4797                 no error.  So exit the loop and record the new line.  */
4798                  if (CPP_TRADITIONAL (pfile))
4799                    goto while2end;
4800                  if (c == '\'')
4801                    {
4802                      cpp_error_with_line (pfile, start_line, start_column,
4803                                           "unterminated character constant");
4804                      goto while2end;
4805                    }
4806                  if (CPP_PEDANTIC (pfile)
4807                      && pfile->multiline_string_line == 0)
4808                    {
4809                      cpp_pedwarn_with_line (pfile, start_line, start_column,
4810                               "string constant runs past end of line");
4811                    }
4812                  if (pfile->multiline_string_line == 0)
4813                    pfile->multiline_string_line = start_line;
4814                  break;
4815               
4816                case '\\':
4817                  cc = GETC();
4818                  if (cc == '\n')
4819                    {
4820                      /* Backslash newline is replaced by nothing at all.  */
4821                      CPP_ADJUST_WRITTEN (pfile, -1);
4822                      pfile->lineno++;
4823                    }
4824                  else
4825                    {
4826                      /* ANSI stupidly requires that in \\ the second \
4827                         is *not* prevented from combining with a newline.  */
4828                      NEWLINE_FIX1(cc);
4829                      if (cc != EOF)
4830                        CPP_PUTC (pfile, cc);
4831                    }
4832                  break;
4833
4834                case '\"':
4835                case '\'':
4836                  if (cc == c)
4837                    goto while2end;
4838                  break;
4839                }
4840            }
4841        while2end:
4842          pfile->lineno += count_newlines (pfile->token_buffer + old_written,
4843                                           CPP_PWRITTEN (pfile));
4844          pfile->only_seen_white = 0;
4845          return c == '\'' ? CPP_CHAR : CPP_STRING;
4846
4847        case '$':
4848          if (!opts->dollars_in_ident)
4849            goto randomchar;
4850          goto letter;
4851
4852        case ':':
4853          if (opts->cplusplus && PEEKC () == ':')
4854            goto op2;
4855          goto randomchar;
4856
4857        case '&':
4858        case '+':
4859        case '|':
4860          NEWLINE_FIX;
4861          c2 = PEEKC ();
4862          if (c2 == c || c2 == '=')
4863            goto op2;
4864          goto randomchar;
4865
4866        case '*':
4867        case '!':
4868        case '%':
4869        case '=':
4870        case '^':
4871          NEWLINE_FIX;
4872          if (PEEKC () == '=')
4873            goto op2;
4874          goto randomchar;
4875
4876        case '-':
4877          NEWLINE_FIX;
4878          c2 = PEEKC ();
4879          if (c2 == '-' && opts->chill)
4880            {
4881              /* Chill style comment */
4882              if (opts->put_out_comments)
4883                parse_set_mark (&start_mark, pfile);
4884              FORWARD(1);  /* Skip second '-'.  */
4885              for (;;)
4886                {
4887                  c = GETC ();
4888                  if (c == EOF)
4889                    break;
4890                  if (c == '\n')
4891                    {
4892                      /* Don't consider final '\n' to be part of comment.  */
4893                      FORWARD(-1);
4894                      break;
4895                    }
4896                }
4897              c = '-';
4898              goto return_comment;
4899            }
4900          if (c2 == '-' || c2 == '=' || c2 == '>')
4901            goto op2;
4902          goto randomchar;
4903
4904        case '<':
4905          if (pfile->parsing_include_directive)
4906            {
4907              for (;;)
4908                {
4909                  CPP_PUTC (pfile, c);
4910                  if (c == '>')
4911                    break;
4912                  c = GETC ();
4913                  NEWLINE_FIX1 (c);
4914                  if (c == '\n' || c == EOF)
4915                    {
4916                      cpp_error (pfile,
4917                                 "missing '>' in `#include <FILENAME>'");
4918                      break;
4919                    }
4920                }
4921              return CPP_STRING;
4922            }
4923          /* else fall through */
4924        case '>':
4925          NEWLINE_FIX;
4926          c2 = PEEKC ();
4927          if (c2 == '=')
4928            goto op2;
4929          if (c2 != c)
4930            goto randomchar;
4931          FORWARD(1);
4932          CPP_RESERVE (pfile, 4);
4933          CPP_PUTC (pfile, c);
4934          CPP_PUTC (pfile, c2);
4935          NEWLINE_FIX;
4936          c3 = PEEKC ();
4937          if (c3 == '=')
4938            CPP_PUTC_Q (pfile, GETC ());
4939          CPP_NUL_TERMINATE_Q (pfile);
4940          pfile->only_seen_white = 0;
4941          return CPP_OTHER;
4942
4943        case '@':
4944          if (CPP_BUFFER (pfile)->has_escapes)
4945            {
4946              c = GETC ();
4947              if (c == '-')
4948                {
4949                  if (pfile->output_escapes)
4950                    CPP_PUTS (pfile, "@-", 2);
4951                  parse_name (pfile, GETC ());
4952                  return CPP_NAME;
4953                }
4954              else if (is_space [c])
4955                {
4956                  CPP_RESERVE (pfile, 2);
4957                  if (pfile->output_escapes)
4958                    CPP_PUTC_Q (pfile, '@');
4959                  CPP_PUTC_Q (pfile, c);
4960                  return CPP_HSPACE;
4961                }
4962            }
4963          if (pfile->output_escapes)
4964            {
4965              CPP_PUTS (pfile, "@@", 2);
4966              return CPP_OTHER;
4967            }
4968          goto randomchar;
4969
4970        case '.':
4971          NEWLINE_FIX;
4972          c2 = PEEKC ();
4973          if (isdigit(c2))
4974            {
4975              CPP_RESERVE(pfile, 2);
4976              CPP_PUTC_Q (pfile, '.');
4977              c = GETC ();
4978              goto number;
4979            }
4980          /* FIXME - misses the case "..\\\n." */
4981          if (c2 == '.' && PEEKN(1) == '.')
4982            {
4983              CPP_RESERVE(pfile, 4);
4984              CPP_PUTC_Q (pfile, '.');
4985              CPP_PUTC_Q (pfile, '.');
4986              CPP_PUTC_Q (pfile, '.');
4987              FORWARD (2);
4988              CPP_NUL_TERMINATE_Q (pfile);
4989              pfile->only_seen_white = 0;
4990              return CPP_3DOTS;
4991            }
4992          goto randomchar;
4993
4994        op2:
4995          token = CPP_OTHER;
4996          pfile->only_seen_white = 0;
4997        op2any:
4998          CPP_RESERVE(pfile, 3);
4999          CPP_PUTC_Q (pfile, c);
5000          CPP_PUTC_Q (pfile, GETC ());
5001          CPP_NUL_TERMINATE_Q (pfile);
5002          return token;
5003
5004        case 'L':
5005          NEWLINE_FIX;
5006          c2 = PEEKC ();
5007          if ((c2 == '\'' || c2 == '\"') && !CPP_TRADITIONAL (pfile))
5008            {
5009              CPP_PUTC (pfile, c);
5010              c = GETC ();
5011              goto string;
5012            }
5013          goto letter;
5014
5015        case '0': case '1': case '2': case '3': case '4':
5016        case '5': case '6': case '7': case '8': case '9':
5017        number:
5018          c2  = '.';
5019          for (;;)
5020            {
5021              CPP_RESERVE (pfile, 2);
5022              CPP_PUTC_Q (pfile, c);
5023              NEWLINE_FIX;
5024              c = PEEKC ();
5025              if (c == EOF)
5026                break;
5027              if (!is_idchar[c] && c != '.'
5028                  && ((c2 != 'e' && c2 != 'E'
5029                       && ((c2 != 'p' && c2 != 'P') || CPP_C89 (pfile)))
5030                      || (c != '+' && c != '-')))
5031                break;
5032              FORWARD(1);
5033              c2= c;
5034            }
5035          CPP_NUL_TERMINATE_Q (pfile);
5036          pfile->only_seen_white = 0;
5037          return CPP_NUMBER;
5038        case 'b': case 'c': case 'd': case 'h': case 'o':
5039        case 'B': case 'C': case 'D': case 'H': case 'O':
5040          if (opts->chill && PEEKC () == '\'')
5041            {
5042              pfile->only_seen_white = 0;
5043              CPP_RESERVE (pfile, 2);
5044              CPP_PUTC_Q (pfile, c);
5045              CPP_PUTC_Q (pfile, '\'');
5046              FORWARD(1);
5047              for (;;)
5048                {
5049                  c = GETC();
5050                  if (c == EOF)
5051                    goto chill_number_eof;
5052                  if (!is_idchar[c])
5053                    {
5054                      if (c == '\\' && PEEKC() == '\n')
5055                        {
5056                          FORWARD(2);
5057                          continue;
5058                        }
5059                      break;
5060                    }
5061                  CPP_PUTC (pfile, c);
5062                }
5063              if (c == '\'')
5064                {
5065                  CPP_RESERVE (pfile, 2);
5066                  CPP_PUTC_Q (pfile, c);
5067                  CPP_NUL_TERMINATE_Q (pfile);
5068                  return CPP_STRING;
5069                }
5070              else
5071                {
5072                  FORWARD(-1);
5073                chill_number_eof:
5074                  CPP_NUL_TERMINATE (pfile);
5075                  return CPP_NUMBER;
5076                }
5077            }
5078          else
5079            goto letter;
5080        case '_':
5081        case 'a': case 'e': case 'f': case 'g': case 'i': case 'j':
5082        case 'k': case 'l': case 'm': case 'n': case 'p': case 'q':
5083        case 'r': case 's': case 't': case 'u': case 'v': case 'w':
5084        case 'x': case 'y': case 'z':
5085        case 'A': case 'E': case 'F': case 'G': case 'I': case 'J':
5086        case 'K': case 'M': case 'N': case 'P': case 'Q': case 'R':
5087        case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
5088        case 'Y': case 'Z':
5089        letter:
5090          {
5091            HASHNODE *hp;
5092            unsigned char *ident;
5093            int before_name_written = CPP_WRITTEN (pfile);
5094            int ident_len;
5095            parse_name (pfile, c);
5096            pfile->only_seen_white = 0;
5097            if (pfile->no_macro_expand)
5098              return CPP_NAME;
5099            ident = pfile->token_buffer + before_name_written;
5100            ident_len = CPP_PWRITTEN (pfile) - ident;
5101            hp = cpp_lookup (pfile, ident, ident_len, -1);
5102            if (!hp)
5103              return CPP_NAME;
5104            if (hp->type == T_DISABLED)
5105              {
5106                if (pfile->output_escapes)
5107                  { /* Return "@-IDENT", followed by '\0'.  */
5108                    int i;
5109                    CPP_RESERVE (pfile, 3);
5110                    ident = pfile->token_buffer + before_name_written;
5111                    CPP_ADJUST_WRITTEN (pfile, 2);
5112                    for (i = ident_len; i >= 0; i--) ident[i+2] = ident[i];
5113                    ident[0] = '@';
5114                    ident[1] = '-';
5115                  }
5116                return CPP_NAME;
5117              }
5118
5119            /* If macro wants an arglist, verify that a '(' follows.
5120               first skip all whitespace, copying it to the output
5121               after the macro name.  Then, if there is no '(',
5122               decide this is not a macro call and leave things that way.  */
5123            if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
5124            {
5125              struct parse_marker macro_mark;
5126              int is_macro_call;
5127              while (CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
5128                {
5129                  cpp_buffer *next_buf;
5130                  cpp_skip_hspace (pfile);
5131                  if (PEEKC () != EOF)
5132                    break;
5133                  next_buf = CPP_PREV_BUFFER (CPP_BUFFER (pfile));
5134                  (*CPP_BUFFER (pfile)->cleanup) (CPP_BUFFER (pfile), pfile);
5135                  CPP_BUFFER (pfile) = next_buf;
5136                }
5137              parse_set_mark (&macro_mark, pfile);
5138              for (;;)
5139                {
5140                  cpp_skip_hspace (pfile);
5141                  c = PEEKC ();
5142                  is_macro_call = c == '(';
5143                  if (c != '\n')
5144                    break;
5145                  FORWARD (1);
5146                }
5147              if (!is_macro_call)
5148                parse_goto_mark (&macro_mark, pfile);
5149              parse_clear_mark (&macro_mark);
5150              if (!is_macro_call)
5151                return CPP_NAME;
5152            }
5153            /* This is now known to be a macro call.  */
5154
5155            /* it might not actually be a macro.  */
5156            if (hp->type != T_MACRO) {
5157              int xbuf_len;  U_CHAR *xbuf;
5158              CPP_SET_WRITTEN (pfile, before_name_written);
5159              special_symbol (hp, pfile);
5160              xbuf_len = CPP_WRITTEN (pfile) - before_name_written;
5161              xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
5162              CPP_SET_WRITTEN (pfile, before_name_written);
5163              bcopy (CPP_PWRITTEN (pfile), xbuf, xbuf_len + 1);
5164              push_macro_expansion (pfile, xbuf, xbuf_len, hp);
5165            }
5166            else
5167              {
5168                /* Expand the macro, reading arguments as needed,
5169                   and push the expansion on the input stack.  */
5170                macroexpand (pfile, hp);
5171                CPP_SET_WRITTEN (pfile, before_name_written);
5172              }
5173
5174            /* An extra "@ " is added to the end of a macro expansion
5175               to prevent accidental token pasting.  We prefer to avoid
5176               unneeded extra spaces (for the sake of cpp-using tools like
5177               imake).  Here we remove the space if it is safe to do so.  */
5178            if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
5179                && pfile->buffer->rlimit[-2] == '@'
5180                && pfile->buffer->rlimit[-1] == ' ')
5181              {
5182                int c1 = pfile->buffer->rlimit[-3];
5183                int c2 = CPP_BUF_PEEK (CPP_PREV_BUFFER (CPP_BUFFER (pfile)));
5184                if (c2 == EOF || ! unsafe_chars (c1, c2))
5185                  pfile->buffer->rlimit -= 2;
5186              }
5187          }
5188          goto get_next;
5189
5190        case ' ':  case '\t':  case '\v':  case '\r':
5191          for (;;)
5192            {
5193              CPP_PUTC (pfile, c);
5194              c = PEEKC ();
5195              if (c == EOF || !is_hor_space[c])
5196                break;
5197              FORWARD(1);
5198            }
5199          return CPP_HSPACE;
5200
5201        case '\\':
5202          c2 = PEEKC ();
5203          if (c2 != '\n')
5204            goto randomchar;
5205          token = CPP_HSPACE;
5206          goto op2any;
5207
5208        case '\n':
5209          CPP_PUTC (pfile, c);
5210          if (pfile->only_seen_white == 0)
5211            pfile->only_seen_white = 1;
5212          pfile->lineno++;
5213          output_line_command (pfile, 1, same_file);
5214          return CPP_VSPACE;
5215
5216        case '(': token = CPP_LPAREN;    goto char1;
5217        case ')': token = CPP_RPAREN;    goto char1;
5218        case '{': token = CPP_LBRACE;    goto char1;
5219        case '}': token = CPP_RBRACE;    goto char1;
5220        case ',': token = CPP_COMMA;     goto char1;
5221        case ';': token = CPP_SEMICOLON; goto char1;
5222
5223        randomchar:
5224        default:
5225          token = CPP_OTHER;
5226        char1:
5227          pfile->only_seen_white = 0;
5228          CPP_PUTC (pfile, c);
5229          return token;
5230        }
5231    }
5232}
5233
5234/* Like cpp_get_token, but skip spaces and comments.  */
5235
5236enum cpp_token
5237cpp_get_non_space_token (pfile)
5238     cpp_reader *pfile;
5239{
5240  int old_written = CPP_WRITTEN (pfile);
5241  for (;;)
5242    {
5243      enum cpp_token token = cpp_get_token (pfile);
5244      if (token != CPP_COMMENT && token != CPP_POP
5245          && token != CPP_HSPACE && token != CPP_VSPACE)
5246        return token;
5247      CPP_SET_WRITTEN (pfile, old_written);
5248    }
5249}
5250
5251/* Parse an identifier starting with C.  */
5252
5253int
5254parse_name (pfile, c)
5255     cpp_reader *pfile; int c;
5256{
5257  for (;;)
5258  {
5259      if (! is_idchar[c])
5260      {
5261          if (c == '\\' && PEEKC() == '\n')
5262          {
5263              FORWARD(2);
5264              continue;
5265          }
5266          FORWARD (-1);
5267          break;
5268      }
5269
5270      if (c == '$' && CPP_PEDANTIC (pfile))
5271        cpp_pedwarn ("`$' in identifier");
5272
5273      CPP_RESERVE(pfile, 2); /* One more for final NUL.  */
5274      CPP_PUTC_Q (pfile, c);
5275      c = GETC();
5276      if (c == EOF)
5277        break;
5278  }
5279  CPP_NUL_TERMINATE_Q (pfile);
5280  return 1;
5281}
5282
5283
5284/* Maintain and search list of included files, for #import.  */
5285
5286/* Hash a file name for import_hash_table.  */
5287
5288static int
5289import_hash (f)
5290     char *f;
5291{
5292  int val = 0;
5293
5294  while (*f) val += *f++;
5295  return (val%IMPORT_HASH_SIZE);
5296}
5297
5298/* Search for file FILENAME in import_hash_table.
5299   Return -2 if found, either a matching name or a matching inode.
5300   Otherwise, open the file and return a file descriptor if successful
5301   or -1 if unsuccessful.  */
5302
5303static int
5304lookup_import (pfile, filename, searchptr)
5305     cpp_reader *pfile;
5306     char *filename;
5307     struct file_name_list *searchptr;
5308{
5309  struct import_file *i;
5310  int h;
5311  int hashval;
5312  struct stat sb;
5313  int fd;
5314
5315  hashval = import_hash (filename);
5316
5317  /* Attempt to find file in list of already included files */
5318  i = pfile->import_hash_table[hashval];
5319
5320  while (i) {
5321    if (!strcmp (filename, i->name))
5322      return -2;                /* return found */
5323    i = i->next;
5324  }
5325  /* Open it and try a match on inode/dev */
5326  fd = open_include_file (pfile, filename, searchptr);
5327  if (fd < 0)
5328    return fd;
5329  fstat (fd, &sb);
5330  for (h = 0; h < IMPORT_HASH_SIZE; h++) {
5331    i = pfile->import_hash_table[h];
5332    while (i) {
5333      /* Compare the inode and the device.
5334         Supposedly on some systems the inode is not a scalar.  */
5335      if (!bcmp ((char *) &i->inode, (char *) &sb.st_ino, sizeof (sb.st_ino))
5336          && i->dev == sb.st_dev) {
5337        close (fd);
5338        return -2;              /* return found */
5339      }
5340      i = i->next;
5341    }
5342  }
5343  return fd;                    /* Not found, return open file */
5344}
5345
5346/* Add the file FNAME, open on descriptor FD, to import_hash_table.  */
5347
5348static void
5349add_import (pfile, fd, fname)
5350     cpp_reader *pfile;
5351     int fd;
5352     char *fname;
5353{
5354  struct import_file *i;
5355  int hashval;
5356  struct stat sb;
5357
5358  hashval = import_hash (fname);
5359  fstat (fd, &sb);
5360  i = (struct import_file *)xmalloc (sizeof (struct import_file));
5361  i->name = (char *)xmalloc (strlen (fname)+1);
5362  strcpy (i->name, fname);
5363  bcopy ((char *) &sb.st_ino, (char *) &i->inode, sizeof (sb.st_ino));
5364  i->dev = sb.st_dev;
5365  i->next = pfile->import_hash_table[hashval];
5366  pfile->import_hash_table[hashval] = i;
5367}
5368
5369/* The file_name_map structure holds a mapping of file names for a
5370   particular directory.  This mapping is read from the file named
5371   FILE_NAME_MAP_FILE in that directory.  Such a file can be used to
5372   map filenames on a file system with severe filename restrictions,
5373   such as DOS.  The format of the file name map file is just a series
5374   of lines with two tokens on each line.  The first token is the name
5375   to map, and the second token is the actual name to use.  */
5376
5377struct file_name_map
5378{
5379  struct file_name_map *map_next;
5380  char *map_from;
5381  char *map_to;
5382};
5383
5384#define FILE_NAME_MAP_FILE "header.gcc"
5385
5386/* Read a space delimited string of unlimited length from a stdio
5387   file.  */
5388
5389static char *
5390read_filename_string (ch, f)
5391     int ch;
5392     FILE *f;
5393{
5394  char *alloc, *set;
5395  int len;
5396
5397  len = 20;
5398  set = alloc = xmalloc (len + 1);
5399  if (! is_space[ch])
5400    {
5401      *set++ = ch;
5402      while ((ch = getc (f)) != EOF && ! is_space[ch])
5403        {
5404          if (set - alloc == len)
5405            {
5406              len *= 2;
5407              alloc = xrealloc (alloc, len + 1);
5408              set = alloc + len / 2;
5409            }
5410          *set++ = ch;
5411        }
5412    }
5413  *set = '\0';
5414  ungetc (ch, f);
5415  return alloc;
5416}
5417
5418/* This structure holds a linked list of file name maps, one per directory.  */
5419
5420struct file_name_map_list
5421{
5422  struct file_name_map_list *map_list_next;
5423  char *map_list_name;
5424  struct file_name_map *map_list_map;
5425};
5426
5427/* Read the file name map file for DIRNAME.  */
5428
5429static struct file_name_map *
5430read_name_map (pfile, dirname)
5431     cpp_reader *pfile;
5432     char *dirname;
5433{
5434  register struct file_name_map_list *map_list_ptr;
5435  char *name;
5436  FILE *f;
5437
5438  for (map_list_ptr = CPP_OPTIONS (pfile)->map_list; map_list_ptr;
5439       map_list_ptr = map_list_ptr->map_list_next)
5440    if (! strcmp (map_list_ptr->map_list_name, dirname))
5441      return map_list_ptr->map_list_map;
5442
5443  map_list_ptr = ((struct file_name_map_list *)
5444                  xmalloc (sizeof (struct file_name_map_list)));
5445  map_list_ptr->map_list_name = savestring (dirname);
5446  map_list_ptr->map_list_map = NULL;
5447
5448  name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
5449  strcpy (name, dirname);
5450  if (*dirname)
5451    strcat (name, "/");
5452  strcat (name, FILE_NAME_MAP_FILE);
5453  f = fopen (name, "r");
5454  if (!f)
5455    map_list_ptr->map_list_map = NULL;
5456  else
5457    {
5458      int ch;
5459      int dirlen = strlen (dirname);
5460
5461      while ((ch = getc (f)) != EOF)
5462        {
5463          char *from, *to;
5464          struct file_name_map *ptr;
5465
5466          if (is_space[ch])
5467            continue;
5468          from = read_filename_string (ch, f);
5469          while ((ch = getc (f)) != EOF && is_hor_space[ch])
5470            ;
5471          to = read_filename_string (ch, f);
5472
5473          ptr = ((struct file_name_map *)
5474                 xmalloc (sizeof (struct file_name_map)));
5475          ptr->map_from = from;
5476
5477          /* Make the real filename absolute.  */
5478          if (*to == '/')
5479            ptr->map_to = to;
5480          else
5481            {
5482              ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
5483              strcpy (ptr->map_to, dirname);
5484              ptr->map_to[dirlen] = '/';
5485              strcpy (ptr->map_to + dirlen + 1, to);
5486              free (to);
5487            }         
5488
5489          ptr->map_next = map_list_ptr->map_list_map;
5490          map_list_ptr->map_list_map = ptr;
5491
5492          while ((ch = getc (f)) != '\n')
5493            if (ch == EOF)
5494              break;
5495        }
5496      fclose (f);
5497    }
5498 
5499  map_list_ptr->map_list_next = CPP_OPTIONS (pfile)->map_list;
5500  CPP_OPTIONS (pfile)->map_list = map_list_ptr;
5501
5502  return map_list_ptr->map_list_map;
5503
5504
5505/* Try to open include file FILENAME.  SEARCHPTR is the directory
5506   being tried from the include file search path.  This function maps
5507   filenames on file systems based on information read by
5508   read_name_map.  */
5509
5510static int
5511open_include_file (pfile, filename, searchptr)
5512     cpp_reader *pfile;
5513     char *filename;
5514     struct file_name_list *searchptr;
5515{
5516  if (CPP_OPTIONS (pfile)->remap)
5517    {
5518      register struct file_name_map *map;
5519      register char *from;
5520      char *p, *dir;
5521
5522      if (searchptr && ! searchptr->got_name_map)
5523        {
5524          searchptr->name_map = read_name_map (pfile,
5525                                               searchptr->fname
5526                                               ? searchptr->fname : ".");
5527          searchptr->got_name_map = 1;
5528        }
5529
5530      /* First check the mapping for the directory we are using.  */
5531      if (searchptr && searchptr->name_map)
5532        {
5533          from = filename;
5534          if (searchptr->fname)
5535            from += strlen (searchptr->fname) + 1;
5536          for (map = searchptr->name_map; map; map = map->map_next)
5537            {
5538              if (! strcmp (map->map_from, from))
5539                {
5540                  /* Found a match.  */
5541                  return open (map->map_to, O_RDONLY, 0666);
5542                }
5543            }
5544        }
5545
5546      /* Try to find a mapping file for the particular directory we are
5547         looking in.  Thus #include <sys/types.h> will look up sys/types.h
5548         in /usr/include/header.gcc and look up types.h in
5549         /usr/include/sys/header.gcc.  */
5550      p = rindex (filename, '/');
5551      if (! p)
5552        p = filename;
5553      if (searchptr
5554          && searchptr->fname
5555          && strlen (searchptr->fname) == p - filename
5556          && ! strncmp (searchptr->fname, filename, p - filename))
5557        {
5558          /* FILENAME is in SEARCHPTR, which we've already checked.  */
5559          return open (filename, O_RDONLY, 0666);
5560        }
5561
5562      if (p == filename)
5563        {
5564          dir = ".";
5565          from = filename;
5566        }
5567      else
5568        {
5569          dir = (char *) alloca (p - filename + 1);
5570          bcopy (filename, dir, p - filename);
5571          dir[p - filename] = '\0';
5572          from = p + 1;
5573        }
5574      for (map = read_name_map (pfile, dir); map; map = map->map_next)
5575        if (! strcmp (map->map_from, from))
5576          return open (map->map_to, O_RDONLY, 0666);
5577    }
5578
5579  return open (filename, O_RDONLY, 0666);
5580}
5581
5582/* Process the contents of include file FNAME, already open on descriptor F,
5583   with output to OP.
5584   SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5585   "system" include directories (as decided by the `is_system_include'
5586   function above).
5587   DIRPTR is the link in the dir path through which this file was found,
5588   or 0 if the file name was absolute or via the current directory.
5589   Return 1 on success, 0 on failure.
5590
5591   The caller is responsible for the cpp_push_buffer.  */
5592
5593static int
5594finclude (pfile, f, fname, system_header_p, dirptr)
5595     cpp_reader *pfile;
5596     int f;
5597     char *fname;
5598     int system_header_p;
5599     struct file_name_list *dirptr;
5600{
5601  struct stat st;
5602  size_t st_size;
5603  long i;
5604  int length;
5605  cpp_buffer *fp;                       /* For input stack frame */
5606  int missing_newline = 0;
5607
5608  if (fstat (f, &st) < 0)
5609    {
5610      cpp_perror_with_name (pfile, fname);
5611      close (f);
5612      cpp_pop_buffer (pfile);
5613      return 0;
5614    }
5615
5616  fp = CPP_BUFFER (pfile);
5617  fp->nominal_fname = fp->fname = fname;
5618#if 0
5619  fp->length = 0;
5620#endif
5621  fp->dir = dirptr;
5622  fp->system_header_p = system_header_p;
5623  fp->lineno = 1;
5624  fp->colno = 1;
5625  fp->cleanup = file_cleanup;
5626
5627  if (S_ISREG (st.st_mode)) {
5628    st_size = (size_t) st.st_size;
5629    if (st_size != st.st_size || st_size + 2 < st_size) {
5630      cpp_error (pfile, "file `%s' too large", fname);
5631      close (f);
5632      return 0;
5633    }
5634    fp->buf = (U_CHAR *) xmalloc (st_size + 2);
5635    fp->alimit = fp->buf + st_size + 2;
5636    fp->cur = fp->buf;
5637
5638    /* Read the file contents, knowing that st_size is an upper bound
5639       on the number of bytes we can read.  */
5640    length = safe_read (f, fp->buf, st_size);
5641    fp->rlimit = fp->buf + length;
5642    if (length < 0) goto nope;
5643  }
5644  else if (S_ISDIR (st.st_mode)) {
5645    cpp_error (pfile, "directory `%s' specified in #include", fname);
5646    close (f);
5647    return 0;
5648  } else {
5649    /* Cannot count its file size before reading.
5650       First read the entire file into heap and
5651       copy them into buffer on stack.  */
5652
5653    int bsize = 2000;
5654
5655    st_size = 0;
5656    fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5657
5658    for (;;) {
5659      i = safe_read (f, fp->buf + st_size, bsize - st_size);
5660      if (i < 0)
5661        goto nope;      /* error! */
5662      st_size += i;
5663      if (st_size != bsize)
5664        break;  /* End of file */
5665      bsize *= 2;
5666      fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5667    }
5668    fp->cur = fp->buf;
5669    length = st_size;
5670  }
5671
5672  if ((length > 0 && fp->buf[length - 1] != '\n')
5673      /* Backslash-newline at end is not good enough.  */
5674      || (length > 1 && fp->buf[length - 2] == '\\')) {
5675    fp->buf[length++] = '\n';
5676#if 0
5677    missing_newline = 1;
5678#endif
5679  }
5680  fp->buf[length] = '\0';
5681  fp->rlimit = fp->buf + length;
5682
5683  /* Close descriptor now, so nesting does not use lots of descriptors.  */
5684  close (f);
5685
5686  /* Must do this before calling trigraph_pcp, so that the correct file name
5687     will be printed in warning messages.  */
5688
5689  pfile->input_stack_listing_current = 0;
5690
5691#if 0
5692  if (!no_trigraphs)
5693    trigraph_pcp (fp);
5694#endif
5695
5696#if 0
5697  rescan (op, 0);
5698
5699  if (missing_newline)
5700    fp->lineno--;
5701
5702  if (CPP_PEDANTIC (pfile) && missing_newline)
5703    pedwarn ("file does not end in newline");
5704
5705  indepth--;
5706  input_file_stack_tick++;
5707  free (fp->buf);
5708#endif
5709  return 1;
5710
5711 nope:
5712
5713  cpp_perror_with_name (pfile, fname);
5714  close (f);
5715  free (fp->buf);
5716  return 1;
5717}
5718
5719/* This is called after options have been processed.
5720 * Check options for consistency, and setup for processing input
5721 * from the file named FNAME.  (Use standard input if FNAME==NULL.)
5722 * Return 1 on success, 0 on failure.
5723 */
5724
5725int
5726cpp_start_read (pfile, fname)
5727     cpp_reader *pfile;
5728     char *fname;
5729{
5730  struct cpp_options *opts = CPP_OPTIONS (pfile);
5731  struct cpp_pending *pend;
5732  char *p;
5733  int f;
5734  cpp_buffer *fp;
5735
5736  /* The code looks at the defaults through this pointer, rather than through
5737     the constant structure above.  This pointer gets changed if an environment
5738     variable specifies other defaults.  */
5739  struct default_include *include_defaults = include_defaults_array;
5740
5741  /* Add dirs from CPATH after dirs from -I.  */
5742  /* There seems to be confusion about what CPATH should do,
5743     so for the moment it is not documented.  */
5744  /* Some people say that CPATH should replace the standard include dirs,
5745     but that seems pointless: it comes before them, so it overrides them
5746     anyway.  */
5747  p = (char *) getenv ("CPATH");
5748  if (p != 0 && ! opts->no_standard_includes)
5749    path_include (pfile, p);
5750
5751  /* Now that dollars_in_ident is known, initialize is_idchar.  */
5752  initialize_char_syntax (opts);
5753
5754  /* Do partial setup of input buffer for the sake of generating
5755     early #line directives (when -g is in effect).  */
5756  fp = cpp_push_buffer (pfile, NULL, 0);
5757  if (!fp)
5758    return 0;
5759  if (opts->in_fname == NULL)
5760    opts->in_fname = "";
5761  fp->nominal_fname = fp->fname = opts->in_fname;
5762  fp->lineno = 0;
5763
5764  /* Install __LINE__, etc.  Must follow initialize_char_syntax
5765     and option processing.  */
5766  initialize_builtins (pfile);
5767
5768  /* Do standard #defines and assertions
5769     that identify system and machine type.  */
5770
5771  if (!opts->inhibit_predefs) {
5772    char *p = (char *) alloca (strlen (predefs) + 1);
5773    strcpy (p, predefs);
5774    while (*p) {
5775      char *q;
5776      while (*p == ' ' || *p == '\t')
5777        p++;
5778      /* Handle -D options.  */
5779      if (p[0] == '-' && p[1] == 'D') {
5780        q = &p[2];
5781        while (*p && *p != ' ' && *p != '\t')
5782          p++;
5783        if (*p != 0)
5784          *p++= 0;
5785        if (opts->debug_output)
5786          output_line_command (pfile, 0, same_file);
5787        cpp_define (pfile, q);
5788        while (*p == ' ' || *p == '\t')
5789          p++;
5790      } else if (p[0] == '-' && p[1] == 'A') {
5791        /* Handle -A options (assertions).  */
5792        char *assertion;
5793        char *past_name;
5794        char *value;
5795        char *past_value;
5796        char *termination;
5797        int save_char;
5798
5799        assertion = &p[2];
5800        past_name = assertion;
5801        /* Locate end of name.  */
5802        while (*past_name && *past_name != ' '
5803               && *past_name != '\t' && *past_name != '(')
5804          past_name++;
5805        /* Locate `(' at start of value.  */
5806        value = past_name;
5807        while (*value && (*value == ' ' || *value == '\t'))
5808          value++;
5809        if (*value++ != '(')
5810          abort ();
5811        while (*value && (*value == ' ' || *value == '\t'))
5812          value++;
5813        past_value = value;
5814        /* Locate end of value.  */
5815        while (*past_value && *past_value != ' '
5816               && *past_value != '\t' && *past_value != ')')
5817          past_value++;
5818        termination = past_value;
5819        while (*termination && (*termination == ' ' || *termination == '\t'))
5820          termination++;
5821        if (*termination++ != ')')
5822          abort ();
5823        if (*termination && *termination != ' ' && *termination != '\t')
5824          abort ();
5825        /* Temporarily null-terminate the value.  */
5826        save_char = *termination;
5827        *termination = '\0';
5828        /* Install the assertion.  */
5829        make_assertion (pfile, "-A", assertion);
5830        *termination = (char) save_char;
5831        p = termination;
5832        while (*p == ' ' || *p == '\t')
5833          p++;
5834      } else {
5835        abort ();
5836      }
5837    }
5838  }
5839
5840  /* Now handle the command line options.  */
5841
5842  /* Do -U's, -D's and -A's in the order they were seen.  */
5843  /* First reverse the list.  */
5844  opts->pending = nreverse_pending (opts->pending);
5845
5846  for (pend = opts->pending;  pend;  pend = pend->next)
5847    {
5848      if (pend->cmd != NULL && pend->cmd[0] == '-')
5849        {
5850          switch (pend->cmd[1])
5851            {
5852            case 'U':
5853              if (opts->debug_output)
5854                output_line_command (pfile, 0, same_file);
5855              do_undef (pfile, NULL, pend->arg, pend->arg + strlen (pend->arg));
5856              break;
5857            case 'D':
5858              if (opts->debug_output)
5859                output_line_command (pfile, 0, same_file);
5860              cpp_define (pfile, pend->arg);
5861              break;
5862            case 'A':
5863              make_assertion (pfile, "-A", pend->arg);
5864              break;
5865            }
5866        }
5867    }
5868
5869  opts->done_initializing = 1;
5870
5871  { /* Read the appropriate environment variable and if it exists
5872       replace include_defaults with the listed path.  */
5873    char *epath = 0;
5874    switch ((opts->objc << 1) + opts->cplusplus)
5875      {
5876      case 0:
5877        epath = getenv ("C_INCLUDE_PATH");
5878        break;
5879      case 1:
5880        epath = getenv ("CPLUS_INCLUDE_PATH");
5881        break;
5882      case 2:
5883        epath = getenv ("OBJC_INCLUDE_PATH");
5884        break;
5885      case 3:
5886        epath = getenv ("OBJCPLUS_INCLUDE_PATH");
5887        break;
5888      }
5889    /* If the environment var for this language is set,
5890       add to the default list of include directories.  */
5891    if (epath) {
5892      char *nstore = (char *) alloca (strlen (epath) + 2);
5893      int num_dirs;
5894      char *startp, *endp;
5895
5896      for (num_dirs = 1, startp = epath; *startp; startp++)
5897        if (*startp == PATH_SEPARATOR)
5898          num_dirs++;
5899      include_defaults
5900        = (struct default_include *) xmalloc ((num_dirs
5901                                               * sizeof (struct default_include))
5902                                              + sizeof (include_defaults_array));
5903      startp = endp = epath;
5904      num_dirs = 0;
5905      while (1) {
5906        /* Handle cases like c:/usr/lib:d:/gcc/lib */
5907        if ((*endp == PATH_SEPARATOR)
5908            || *endp == 0) {
5909          strncpy (nstore, startp, endp-startp);
5910          if (endp == startp)
5911            strcpy (nstore, ".");
5912          else
5913            nstore[endp-startp] = '\0';
5914
5915          include_defaults[num_dirs].fname = savestring (nstore);
5916          include_defaults[num_dirs].component = 0;
5917          include_defaults[num_dirs].cplusplus = opts->cplusplus;
5918          include_defaults[num_dirs].cxx_aware = 1;
5919          num_dirs++;
5920          if (*endp == '\0')
5921            break;
5922          endp = startp = endp + 1;
5923        } else
5924          endp++;
5925      }
5926      /* Put the usual defaults back in at the end.  */
5927      bcopy ((char *) include_defaults_array,
5928             (char *) &include_defaults[num_dirs],
5929             sizeof (include_defaults_array));
5930    }
5931  }
5932
5933  append_include_chain (pfile, opts->before_system, opts->last_before_system);
5934  opts->first_system_include = opts->before_system;
5935
5936  /* Unless -fnostdinc,
5937     tack on the standard include file dirs to the specified list */
5938  if (!opts->no_standard_includes) {
5939    struct default_include *p = include_defaults;
5940    char *specd_prefix = opts->include_prefix;
5941    char *default_prefix = savestring (GCC_INCLUDE_DIR);
5942    int default_len = 0;
5943    /* Remove the `include' from /usr/local/lib/gcc.../include.  */
5944    if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
5945      default_len = strlen (default_prefix) - 7;
5946      default_prefix[default_len] = 0;
5947    }
5948    /* Search "translated" versions of GNU directories.
5949       These have /usr/local/lib/gcc... replaced by specd_prefix.  */
5950    if (specd_prefix != 0 && default_len != 0)
5951      for (p = include_defaults; p->fname; p++) {
5952        /* Some standard dirs are only for C++.  */
5953        if (!p->cplusplus
5954            || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
5955          /* Does this dir start with the prefix?  */
5956          if (!strncmp (p->fname, default_prefix, default_len)) {
5957            /* Yes; change prefix and add to search list.  */
5958            struct file_name_list *new
5959              = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
5960            int this_len = strlen (specd_prefix) + strlen (p->fname) - default_len;
5961            char *str = (char *) xmalloc (this_len + 1);
5962            strcpy (str, specd_prefix);
5963            strcat (str, p->fname + default_len);
5964            new->fname = str;
5965            new->control_macro = 0;
5966            new->c_system_include_path = !p->cxx_aware;
5967            new->got_name_map = 0;
5968            append_include_chain (pfile, new, new);
5969            if (opts->first_system_include == 0)
5970              opts->first_system_include = new;
5971          }
5972        }
5973      }
5974    /* Search ordinary names for GNU include directories.  */
5975    for (p = include_defaults; p->fname; p++) {
5976      /* Some standard dirs are only for C++.  */
5977      if (!p->cplusplus
5978          || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
5979        struct file_name_list *new
5980          = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
5981        new->control_macro = 0;
5982        new->c_system_include_path = !p->cxx_aware;
5983        new->fname = update_path (p->fname, p->component);
5984        new->got_name_map = 0;
5985        append_include_chain (pfile, new, new);
5986        if (opts->first_system_include == 0)
5987          opts->first_system_include = new;
5988      }
5989    }
5990  }
5991
5992  /* Tack the after_include chain at the end of the include chain.  */
5993  append_include_chain (pfile, opts->after_include, opts->last_after_include);
5994  if (opts->first_system_include == 0)
5995    opts->first_system_include = opts->after_include;
5996
5997  /* With -v, print the list of dirs to search.  */
5998  if (opts->verbose) {
5999    struct file_name_list *p;
6000    fprintf (stderr, "#include \"...\" search starts here:\n");
6001    for (p = opts->include; p; p = p->next) {
6002      if (p == opts->first_bracket_include)
6003        fprintf (stderr, "#include <...> search starts here:\n");
6004      fprintf (stderr, " %s\n", p->fname);
6005    }
6006    fprintf (stderr, "End of search list.\n");
6007  }
6008
6009  /* Scan the -imacros files before the main input.
6010     Much like #including them, but with no_output set
6011     so that only their macro definitions matter.  */
6012
6013  opts->no_output++; pfile->no_record_file++;
6014  for (pend = opts->pending;  pend;  pend = pend->next)
6015    {
6016      if (pend->cmd != NULL && strcmp (pend->cmd, "-imacros") == 0)
6017        {
6018          int fd = open (pend->arg, O_RDONLY, 0666);
6019          if (fd < 0)
6020            {
6021              cpp_perror_with_name (pfile, pend->arg);
6022              return 0;
6023            }
6024          if (!cpp_push_buffer (pfile, NULL, 0))
6025              return 0;
6026          finclude (pfile, fd, pend->arg, 0, NULL_PTR);
6027          cpp_scan_buffer (pfile);
6028        }
6029    }
6030  opts->no_output--; pfile->no_record_file--;
6031
6032  /* Copy the entire contents of the main input file into
6033     the stacked input buffer previously allocated for it.  */
6034  if (fname == NULL || *fname == 0) {
6035    fname = "";
6036    f = 0;
6037  } else if ((f = open (fname, O_RDONLY, 0666)) < 0)
6038    cpp_pfatal_with_name (pfile, fname);
6039
6040  /* -MG doesn't select the form of output and must be specified with one of
6041     -M or -MM.  -MG doesn't make sense with -MD or -MMD since they don't
6042     inhibit compilation.  */
6043  if (opts->print_deps_missing_files
6044      && (opts->print_deps == 0 || !opts->no_output))
6045    {
6046      cpp_fatal (pfile, "-MG must be specified with one of -M or -MM");
6047      return 0;
6048    }
6049
6050  /* Either of two environment variables can specify output of deps.
6051     Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
6052     where OUTPUT_FILE is the file to write deps info to
6053     and DEPS_TARGET is the target to mention in the deps.  */
6054
6055  if (opts->print_deps == 0
6056      && (getenv ("SUNPRO_DEPENDENCIES") != 0
6057          || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
6058    char *spec = getenv ("DEPENDENCIES_OUTPUT");
6059    char *s;
6060    char *output_file;
6061
6062    if (spec == 0)
6063      {
6064        spec = getenv ("SUNPRO_DEPENDENCIES");
6065        opts->print_deps = 2;
6066      }
6067    else
6068      opts->print_deps = 1;
6069
6070    s = spec;
6071    /* Find the space before the DEPS_TARGET, if there is one.  */
6072    /* This should use index.  (mrs) */
6073    while (*s != 0 && *s != ' ') s++;
6074    if (*s != 0)
6075      {
6076        opts->deps_target = s + 1;
6077        output_file = (char *) xmalloc (s - spec + 1);
6078        bcopy (spec, output_file, s - spec);
6079        output_file[s - spec] = 0;
6080      }
6081    else
6082      {
6083        opts->deps_target = 0;
6084        output_file = spec;
6085      }
6086
6087    opts->deps_file = output_file;
6088    opts->print_deps_append = 1;
6089  }
6090
6091  /* For -M, print the expected object file name
6092     as the target of this Make-rule.  */
6093  if (opts->print_deps)
6094    {
6095      pfile->deps_allocated_size = 200;
6096      pfile->deps_buffer = (char *) xmalloc (pfile->deps_allocated_size);
6097      pfile->deps_buffer[0] = 0;
6098      pfile->deps_size = 0;
6099      pfile->deps_column = 0;
6100
6101      if (opts->deps_target)
6102        deps_output (pfile, opts->deps_target, ':');
6103      else if (*opts->in_fname == 0)
6104        deps_output (pfile, "-", ':');
6105      else
6106        {
6107          char *p, *q, *r;
6108          int len, x;
6109          static char *known_suffixes[] = { ".c", ".C", ".s", ".S", ".m",
6110                                     ".cc", ".cxx", ".cpp", ".cp",
6111                                     ".c++", 0
6112                                   };
6113
6114          /* Discard all directory prefixes from filename.  */
6115          if ((q = rindex (opts->in_fname, '/')) != NULL
6116#ifdef DIR_SEPARATOR
6117              && (q = rindex (opts->in_fname, DIR_SEPARATOR)) != NULL
6118#endif
6119              )
6120            ++q;
6121          else
6122            q = opts->in_fname;
6123
6124          /* Copy remainder to mungable area.  */
6125          p = (char *) alloca (strlen(q) + 8);
6126          strcpy (p, q);
6127
6128          /* Output P, but remove known suffixes.  */
6129          len = strlen (p);
6130          q = p + len;
6131          /* Point to the filename suffix.  */
6132          r = rindex (p, '.');
6133          /* Compare against the known suffixes.  */
6134          x = 0;
6135          while (known_suffixes[x] != 0)
6136            {
6137              if (strncmp (known_suffixes[x], r, q - r) == 0)
6138                {
6139                  /* Make q point to the bit we're going to overwrite
6140                     with an object suffix.  */
6141                  q = r;
6142                  break;
6143                }
6144              x++;
6145            }
6146
6147          /* Supply our own suffix.  */
6148#ifndef VMS
6149          strcpy (q, ".o");
6150#else
6151          strcpy (q, ".obj");
6152#endif
6153
6154          deps_output (pfile, p, ':');
6155          deps_output (pfile, opts->in_fname, ' ');
6156        }
6157    }
6158
6159#if 0
6160  /* Make sure data ends with a newline.  And put a null after it.  */
6161
6162  if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
6163      /* Backslash-newline at end is not good enough.  */
6164      || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
6165    fp->buf[fp->length++] = '\n';
6166    missing_newline = 1;
6167  }
6168  fp->buf[fp->length] = '\0';
6169
6170  /* Unless inhibited, convert trigraphs in the input.  */
6171
6172  if (!no_trigraphs)
6173    trigraph_pcp (fp);
6174#endif
6175
6176  /* Scan the -include files before the main input.
6177   We push these in reverse order, so that the first one is handled first.  */
6178
6179  pfile->no_record_file++;
6180  opts->pending = nreverse_pending (opts->pending);
6181  for (pend = opts->pending;  pend;  pend = pend->next)
6182    {
6183      if (pend->cmd != NULL && strcmp (pend->cmd, "-include") == 0)
6184        {
6185          int fd = open (pend->arg, O_RDONLY, 0666);
6186          if (fd < 0)
6187            {
6188              cpp_perror_with_name (pfile, pend->arg);
6189              return 0;
6190            }
6191          if (!cpp_push_buffer (pfile, NULL, 0))
6192            return 0;
6193          finclude (pfile, fd, pend->arg, 0, NULL_PTR);
6194        }
6195    }
6196  pfile->no_record_file--;
6197
6198  /* Free the pending list.  */
6199  for (pend = opts->pending;  pend; )
6200    {
6201      struct cpp_pending *next = pend->next;
6202      free (pend);
6203      pend = next;
6204    }
6205  opts->pending = NULL;
6206
6207#if 0
6208  /* Scan the input, processing macros and directives.  */
6209
6210  rescan (&outbuf, 0);
6211
6212  if (missing_newline)
6213    fp->lineno--;
6214
6215  if (CPP_PEDANTIC (pfile) && missing_newline)
6216    pedwarn ("file does not end in newline");
6217
6218#endif
6219  if (finclude (pfile, f, fname, 0, NULL_PTR))
6220    output_line_command (pfile, 0, same_file);
6221  return 1;
6222}
6223
6224void
6225cpp_reader_init (pfile)
6226     cpp_reader *pfile;
6227{
6228  bzero ((char *) pfile, sizeof (cpp_reader));
6229  pfile->get_token = cpp_get_token;
6230
6231  pfile->token_buffer_size = 200;
6232  pfile->token_buffer = (U_CHAR *) xmalloc (pfile->token_buffer_size);
6233  CPP_SET_WRITTEN (pfile, 0);
6234
6235  pfile->system_include_depth = 0;
6236  pfile->dont_repeat_files = 0;
6237  pfile->all_include_files = 0;
6238  pfile->max_include_len = 0;
6239  pfile->timebuf = NULL;
6240  pfile->only_seen_white = 1;
6241  pfile->buffer = CPP_NULL_BUFFER(pfile);
6242}
6243
6244static struct cpp_pending *
6245nreverse_pending (list)
6246     struct cpp_pending *list;
6247     
6248{
6249  register struct cpp_pending *prev = 0, *next, *pend;
6250  for (pend = list;  pend;  pend = next)
6251    {
6252      next = pend->next;
6253      pend->next = prev;
6254      prev = pend;
6255    }
6256  return prev;
6257}
6258
6259static void
6260push_pending (pfile, cmd, arg)
6261     cpp_reader *pfile;
6262     char *cmd;
6263     char *arg;
6264{
6265  struct cpp_pending *pend
6266    = (struct cpp_pending *) xmalloc (sizeof (struct cpp_pending));
6267  pend->cmd = cmd;
6268  pend->arg = arg;
6269  pend->next = CPP_OPTIONS (pfile)->pending;
6270  CPP_OPTIONS (pfile)->pending = pend;
6271}
6272
6273/* Handle command-line options in (argc, argv).
6274   Can be called multiple times, to handle multiple sets of options.
6275   Returns if an unrecognized option is seen.
6276   Returns number of handled arguments.  */
6277
6278int
6279cpp_handle_options (pfile, argc, argv)
6280     cpp_reader *pfile;
6281     int argc;
6282     char **argv;
6283{
6284  int i;
6285  struct cpp_options *opts = CPP_OPTIONS (pfile);
6286  for (i = 0; i < argc; i++) {
6287    if (argv[i][0] != '-') {
6288      if (opts->out_fname != NULL)
6289        {
6290          cpp_fatal (pfile, "Usage: %s [switches] input output", argv[0]);
6291          return argc;
6292        }
6293      else if (opts->in_fname != NULL)
6294        opts->out_fname = argv[i];
6295      else
6296        opts->in_fname = argv[i];
6297    } else {
6298      switch (argv[i][1]) {
6299
6300      missing_filename:
6301        cpp_fatal (pfile, "Filename missing after `%s' option", argv[i]);
6302        return argc;
6303      missing_dirname:
6304        cpp_fatal (pfile, "Directory name missing after `%s' option", argv[i]);
6305        return argc;
6306
6307      case 'i':
6308        if (!strcmp (argv[i], "-include")
6309            || !strcmp (argv[i], "-imacros")) {
6310          if (i + 1 == argc)
6311            goto missing_filename;
6312          else
6313            push_pending (pfile, argv[i], argv[i+1]), i++;
6314        }
6315        if (!strcmp (argv[i], "-iprefix")) {
6316          if (i + 1 == argc)
6317            goto missing_filename;
6318          else
6319            opts->include_prefix = argv[++i];
6320        }
6321        if (!strcmp (argv[i], "-ifoutput")) {
6322          opts->output_conditionals = 1;
6323        }
6324        if (!strcmp (argv[i], "-isystem")) {
6325          struct file_name_list *dirtmp;
6326
6327          if (i + 1 == argc)
6328            goto missing_filename;
6329
6330          dirtmp = (struct file_name_list *)
6331            xmalloc (sizeof (struct file_name_list));
6332          dirtmp->next = 0;
6333          dirtmp->control_macro = 0;
6334          dirtmp->c_system_include_path = 1;
6335          dirtmp->fname = (char *) xmalloc (strlen (argv[i+1]) + 1);
6336          strcpy (dirtmp->fname, argv[++i]);
6337          dirtmp->got_name_map = 0;
6338
6339          if (opts->before_system == 0)
6340            opts->before_system = dirtmp;
6341          else
6342            opts->last_before_system->next = dirtmp;
6343          opts->last_before_system = dirtmp; /* Tail follows the last one */
6344        }
6345        /* Add directory to end of path for includes,
6346           with the default prefix at the front of its name.  */
6347        if (!strcmp (argv[i], "-iwithprefix")) {
6348          struct file_name_list *dirtmp;
6349          char *prefix;
6350
6351          if (opts->include_prefix != 0)
6352            prefix = opts->include_prefix;
6353          else {
6354            prefix = savestring (GCC_INCLUDE_DIR);
6355            /* Remove the `include' from /usr/local/lib/gcc.../include.  */
6356            if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
6357              prefix[strlen (prefix) - 7] = 0;
6358          }
6359
6360          dirtmp = (struct file_name_list *)
6361            xmalloc (sizeof (struct file_name_list));
6362          dirtmp->next = 0;     /* New one goes on the end */
6363          dirtmp->control_macro = 0;
6364          dirtmp->c_system_include_path = 0;
6365          if (i + 1 == argc)
6366            goto missing_dirname;
6367
6368          dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
6369                                            + strlen (prefix) + 1);
6370          strcpy (dirtmp->fname, prefix);
6371          strcat (dirtmp->fname, argv[++i]);
6372          dirtmp->got_name_map = 0;
6373
6374          if (opts->after_include == 0)
6375            opts->after_include = dirtmp;
6376          else
6377            opts->last_after_include->next = dirtmp;
6378          opts->last_after_include = dirtmp; /* Tail follows the last one */
6379        }
6380        /* Add directory to main path for includes,
6381           with the default prefix at the front of its name.  */
6382        if (!strcmp (argv[i], "-iwithprefixbefore")) {
6383          struct file_name_list *dirtmp;
6384          char *prefix;
6385
6386          if (opts->include_prefix != 0)
6387            prefix = opts->include_prefix;
6388          else {
6389            prefix = savestring (GCC_INCLUDE_DIR);
6390            /* Remove the `include' from /usr/local/lib/gcc.../include.  */
6391            if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
6392              prefix[strlen (prefix) - 7] = 0;
6393          }
6394
6395          dirtmp = (struct file_name_list *)
6396            xmalloc (sizeof (struct file_name_list));
6397          dirtmp->next = 0;     /* New one goes on the end */
6398          dirtmp->control_macro = 0;
6399          dirtmp->c_system_include_path = 0;
6400          if (i + 1 == argc)
6401            goto missing_dirname;
6402
6403          dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
6404                                            + strlen (prefix) + 1);
6405          strcpy (dirtmp->fname, prefix);
6406          strcat (dirtmp->fname, argv[++i]);
6407          dirtmp->got_name_map = 0;
6408
6409          append_include_chain (pfile, dirtmp, dirtmp);
6410        }
6411        /* Add directory to end of path for includes.  */
6412        if (!strcmp (argv[i], "-idirafter")) {
6413          struct file_name_list *dirtmp;
6414
6415          dirtmp = (struct file_name_list *)
6416            xmalloc (sizeof (struct file_name_list));
6417          dirtmp->next = 0;     /* New one goes on the end */
6418          dirtmp->control_macro = 0;
6419          dirtmp->c_system_include_path = 0;
6420          if (i + 1 == argc)
6421            goto missing_dirname;
6422          else
6423            dirtmp->fname = argv[++i];
6424          dirtmp->got_name_map = 0;
6425
6426          if (opts->after_include == 0)
6427            opts->after_include = dirtmp;
6428          else
6429            opts->last_after_include->next = dirtmp;
6430          opts->last_after_include = dirtmp; /* Tail follows the last one */
6431        }
6432        break;
6433
6434      case 'o':
6435        if (opts->out_fname != NULL)
6436          {
6437            cpp_fatal (pfile, "Output filename specified twice");
6438            return argc;
6439          }
6440        if (i + 1 == argc)
6441          goto missing_filename;
6442        opts->out_fname = argv[++i];
6443        if (!strcmp (opts->out_fname, "-"))
6444          opts->out_fname = "";
6445        break;
6446
6447      case 'p':
6448        if (!strcmp (argv[i], "-pedantic"))
6449          CPP_PEDANTIC (pfile) = 1;
6450        else if (!strcmp (argv[i], "-pedantic-errors")) {
6451          CPP_PEDANTIC (pfile) = 1;
6452          opts->pedantic_errors = 1;
6453        }
6454#if 0
6455        else if (!strcmp (argv[i], "-pcp")) {
6456          char *pcp_fname = argv[++i];
6457          pcp_outfile = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
6458                         ? fopen (pcp_fname, "w")
6459                         : fdopen (dup (fileno (stdout)), "w"));
6460          if (pcp_outfile == 0)
6461            cpp_pfatal_with_name (pfile, pcp_fname);
6462          no_precomp = 1;
6463        }
6464#endif
6465        break;
6466
6467      case 't':
6468        if (!strcmp (argv[i], "-traditional")) {
6469          opts->traditional = 1;
6470        } else if (!strcmp (argv[i], "-trigraphs")) {
6471          if (!opts->chill)
6472            opts->no_trigraphs = 0;
6473        }
6474        break;
6475
6476      case 'l':
6477        if (! strcmp (argv[i], "-lang-c"))
6478          opts->cplusplus = 0, opts->cplusplus_comments = 1, opts->c89 = 0,
6479          opts->objc = 0;
6480        if (! strcmp (argv[i], "-lang-c89"))
6481          opts->cplusplus = 0, opts->cplusplus_comments = 0, opts->c89 = 1,
6482          opts->objc = 0;
6483        if (! strcmp (argv[i], "-lang-c++"))
6484          opts->cplusplus = 1, opts->cplusplus_comments = 1, opts->c89 = 0,
6485          opts->objc = 0;
6486        if (! strcmp (argv[i], "-lang-objc"))
6487          opts->cplusplus = 0, opts->cplusplus_comments = 1, opts->c89 = 0,
6488          opts->objc = 1;
6489        if (! strcmp (argv[i], "-lang-objc++"))
6490          opts->cplusplus = 1, opts->cplusplus_comments = 1, opts->c89 = 0,
6491          opts->objc = 1;
6492        if (! strcmp (argv[i], "-lang-asm"))
6493          opts->lang_asm = 1;
6494        if (! strcmp (argv[i], "-lint"))
6495          opts->for_lint = 1;
6496        if (! strcmp (argv[i], "-lang-chill"))
6497          opts->objc = 0, opts->cplusplus = 0, opts->chill = 1,
6498          opts->traditional = 1, opts->no_trigraphs = 1;
6499        break;
6500
6501      case '+':
6502        opts->cplusplus = 1, opts->cplusplus_comments = 1;
6503        break;
6504
6505      case 'w':
6506        opts->inhibit_warnings = 1;
6507        break;
6508
6509      case 'W':
6510        if (!strcmp (argv[i], "-Wtrigraphs"))
6511          opts->warn_trigraphs = 1;
6512        else if (!strcmp (argv[i], "-Wno-trigraphs"))
6513          opts->warn_trigraphs = 0;
6514        else if (!strcmp (argv[i], "-Wcomment"))
6515          opts->warn_comments = 1;
6516        else if (!strcmp (argv[i], "-Wno-comment"))
6517          opts->warn_comments = 0;
6518        else if (!strcmp (argv[i], "-Wcomments"))
6519          opts->warn_comments = 1;
6520        else if (!strcmp (argv[i], "-Wno-comments"))
6521          opts->warn_comments = 0;
6522        else if (!strcmp (argv[i], "-Wtraditional"))
6523          opts->warn_stringify = 1;
6524        else if (!strcmp (argv[i], "-Wno-traditional"))
6525          opts->warn_stringify = 0;
6526        else if (!strcmp (argv[i], "-Wundef"))
6527          opts->warn_undef = 1;
6528        else if (!strcmp (argv[i], "-Wno-undef"))
6529          opts->warn_undef = 0;
6530        else if (!strcmp (argv[i], "-Wimport"))
6531          opts->warn_import = 1;
6532        else if (!strcmp (argv[i], "-Wno-import"))
6533          opts->warn_import = 0;
6534        else if (!strcmp (argv[i], "-Werror"))
6535          opts->warnings_are_errors = 1;
6536        else if (!strcmp (argv[i], "-Wno-error"))
6537          opts->warnings_are_errors = 0;
6538        else if (!strcmp (argv[i], "-Wall"))
6539          {
6540            opts->warn_trigraphs = 1;
6541            opts->warn_comments = 1;
6542          }
6543        break;
6544
6545      case 'M':
6546        /* The style of the choices here is a bit mixed.
6547           The chosen scheme is a hybrid of keeping all options in one string
6548           and specifying each option in a separate argument:
6549           -M|-MM|-MD file|-MMD file [-MG].  An alternative is:
6550           -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
6551           -M[M][G][D file].  This is awkward to handle in specs, and is not
6552           as extensible.  */
6553        /* ??? -MG must be specified in addition to one of -M or -MM.
6554           This can be relaxed in the future without breaking anything.
6555           The converse isn't true.  */
6556
6557        /* -MG isn't valid with -MD or -MMD.  This is checked for later.  */
6558        if (!strcmp (argv[i], "-MG"))
6559          {
6560            opts->print_deps_missing_files = 1;
6561            break;
6562          }
6563        if (!strcmp (argv[i], "-M"))
6564          opts->print_deps = 2;
6565        else if (!strcmp (argv[i], "-MM"))
6566          opts->print_deps = 1;
6567        else if (!strcmp (argv[i], "-MD"))
6568          opts->print_deps = 2;
6569        else if (!strcmp (argv[i], "-MMD"))
6570          opts->print_deps = 1;
6571        /* For -MD and -MMD options, write deps on file named by next arg.  */
6572        if (!strcmp (argv[i], "-MD") || !strcmp (argv[i], "-MMD"))
6573          {
6574            if (i+1 == argc)
6575              goto missing_filename;
6576            opts->deps_file = argv[++i];
6577          }
6578        else
6579          {
6580            /* For -M and -MM, write deps on standard output
6581               and suppress the usual output.  */
6582            opts->no_output = 1;
6583          }       
6584        break;
6585
6586      case 'd':
6587        {
6588          char *p = argv[i] + 2;
6589          char c;
6590          while ((c = *p++) != 0) {
6591            /* Arg to -d specifies what parts of macros to dump */
6592            switch (c) {
6593            case 'M':
6594              opts->dump_macros = dump_only;
6595              opts->no_output = 1;
6596              break;
6597            case 'N':
6598              opts->dump_macros = dump_names;
6599              break;
6600            case 'D':
6601              opts->dump_macros = dump_definitions;
6602              break;
6603            case 'I':
6604              opts->dump_includes = 1;
6605              break;
6606            }
6607          }
6608        }
6609        break;
6610
6611      case 'g':
6612        if (argv[i][2] == '3')
6613          opts->debug_output = 1;
6614        break;
6615
6616      case 'v':
6617        fprintf (stderr, "GNU CPP version %s", version_string);
6618#ifdef TARGET_VERSION
6619        TARGET_VERSION;
6620#endif
6621        fprintf (stderr, "\n");
6622        opts->verbose = 1;
6623        break;
6624
6625      case 'H':
6626        opts->print_include_names = 1;
6627        break;
6628
6629      case 'D':
6630        if (argv[i][2] != 0)
6631          push_pending (pfile, "-D", argv[i] + 2);
6632        else if (i + 1 == argc)
6633          {
6634            cpp_fatal (pfile, "Macro name missing after -D option");
6635            return argc;
6636          }
6637        else
6638          i++, push_pending (pfile, "-D", argv[i]);
6639        break;
6640
6641      case 'A':
6642        {
6643          char *p;
6644
6645          if (argv[i][2] != 0)
6646            p = argv[i] + 2;
6647          else if (i + 1 == argc)
6648            {
6649              cpp_fatal (pfile, "Assertion missing after -A option");
6650              return argc;
6651            }
6652          else
6653            p = argv[++i];
6654
6655          if (!strcmp (p, "-")) {
6656            struct cpp_pending **ptr;
6657            /* -A- eliminates all predefined macros and assertions.
6658               Let's include also any that were specified earlier
6659               on the command line.  That way we can get rid of any
6660               that were passed automatically in from GCC.  */
6661            int j;
6662            opts->inhibit_predefs = 1;
6663            for (ptr = &opts->pending; *ptr != NULL; )
6664              {
6665                struct cpp_pending *pend = *ptr;
6666                if (pend->cmd && pend->cmd[0] == '-'
6667                    && (pend->cmd[1] == 'D' || pend->cmd[1] == 'A'))
6668                  {
6669                    *ptr = pend->next;
6670                    free (pend);
6671                  }
6672                else
6673                  ptr = &pend->next;
6674              }
6675          } else {
6676            push_pending (pfile, "-A", p);
6677          }
6678        }
6679        break;
6680
6681      case 'U':         /* JF #undef something */
6682        if (argv[i][2] != 0)
6683          push_pending (pfile, "-U", argv[i] + 2);
6684        else if (i + 1 == argc)
6685          {
6686            cpp_fatal (pfile, "Macro name missing after -U option", NULL);
6687            return argc;
6688          }
6689        else
6690          push_pending (pfile, "-U", argv[i+1]), i++;
6691        break;
6692
6693      case 'C':
6694        opts->put_out_comments = 1;
6695        break;
6696
6697      case 'E':                 /* -E comes from cc -E; ignore it.  */
6698        break;
6699
6700      case 'P':
6701        opts->no_line_commands = 1;
6702        break;
6703
6704      case '$':                 /* Don't include $ in identifiers.  */
6705        opts->dollars_in_ident = 0;
6706        break;
6707
6708      case 'I':                 /* Add directory to path for includes.  */
6709        {
6710          struct file_name_list *dirtmp;
6711
6712          if (! CPP_OPTIONS(pfile)->ignore_srcdir
6713              && !strcmp (argv[i] + 2, "-")) {
6714            CPP_OPTIONS (pfile)->ignore_srcdir = 1;
6715            /* Don't use any preceding -I directories for #include <...>.  */
6716            CPP_OPTIONS (pfile)->first_bracket_include = 0;
6717          }
6718          else {
6719            dirtmp = (struct file_name_list *)
6720              xmalloc (sizeof (struct file_name_list));
6721            dirtmp->next = 0;           /* New one goes on the end */
6722            dirtmp->control_macro = 0;
6723            dirtmp->c_system_include_path = 0;
6724            if (argv[i][2] != 0)
6725              dirtmp->fname = argv[i] + 2;
6726            else if (i + 1 == argc)
6727              goto missing_dirname;
6728            else
6729              dirtmp->fname = argv[++i];
6730            dirtmp->got_name_map = 0;
6731            append_include_chain (pfile, dirtmp, dirtmp);
6732          }
6733        }
6734        break;
6735
6736      case 'n':
6737        if (!strcmp (argv[i], "-nostdinc"))
6738          /* -nostdinc causes no default include directories.
6739             You must specify all include-file directories with -I.  */
6740          opts->no_standard_includes = 1;
6741        else if (!strcmp (argv[i], "-nostdinc++"))
6742          /* -nostdinc++ causes no default C++-specific include directories. */
6743          opts->no_standard_cplusplus_includes = 1;
6744#if 0
6745        else if (!strcmp (argv[i], "-noprecomp"))
6746          no_precomp = 1;
6747#endif
6748        break;
6749
6750      case 'r':
6751        if (!strcmp (argv[i], "-remap"))
6752          opts->remap = 1;
6753        break;
6754
6755      case 'u':
6756        /* Sun compiler passes undocumented switch "-undef".
6757           Let's assume it means to inhibit the predefined symbols.  */
6758        opts->inhibit_predefs = 1;
6759        break;
6760
6761      case '\0': /* JF handle '-' as file name meaning stdin or stdout */
6762        if (opts->in_fname == NULL) {
6763          opts->in_fname = "";
6764          break;
6765        } else if (opts->out_fname == NULL) {
6766          opts->out_fname = "";
6767          break;
6768        }       /* else fall through into error */
6769
6770      default:
6771        return i;
6772      }
6773    }
6774  }
6775  return i;
6776}
6777
6778void
6779cpp_finish (pfile)
6780     cpp_reader *pfile;
6781{
6782  struct cpp_options *opts = CPP_OPTIONS (pfile);
6783 
6784  if (opts->print_deps)
6785    {
6786      /* Stream on which to print the dependency information.  */
6787      FILE *deps_stream;
6788
6789      /* Don't actually write the deps file if compilation has failed.  */
6790      if (pfile->errors == 0)
6791        {
6792          char *deps_mode = opts->print_deps_append ? "a" : "w";
6793          if (opts->deps_file == 0)
6794            deps_stream = stdout;
6795          else if ((deps_stream = fopen (opts->deps_file, deps_mode)) == 0)
6796            cpp_pfatal_with_name (pfile, opts->deps_file);
6797          fputs (pfile->deps_buffer, deps_stream);
6798          putc ('\n', deps_stream);
6799          if (opts->deps_file)
6800            {
6801              if (ferror (deps_stream) || fclose (deps_stream) != 0)
6802                cpp_fatal (pfile, "I/O error on output");
6803            }
6804        }
6805    }
6806}
6807
6808/* Free resources used by PFILE.
6809   This is the cpp_reader 'finalizer' or 'destructor' (in C++ terminology).  */
6810
6811void
6812cpp_cleanup (pfile)
6813     cpp_reader *pfile;
6814{
6815  int i;
6816  while ( CPP_BUFFER (pfile) != CPP_NULL_BUFFER (pfile))
6817    cpp_pop_buffer (pfile);
6818
6819  if (pfile->token_buffer)
6820    {
6821      free (pfile->token_buffer);
6822      pfile->token_buffer = NULL;
6823    }
6824
6825  if (pfile->deps_buffer)
6826    {
6827      free (pfile->deps_buffer);
6828      pfile->deps_buffer = NULL;
6829      pfile->deps_allocated_size = 0;
6830    }
6831
6832  while (pfile->if_stack)
6833    {
6834      IF_STACK_FRAME *temp = pfile->if_stack;
6835      pfile->if_stack = temp->next;
6836      free (temp);
6837    }
6838
6839  while (pfile->dont_repeat_files)
6840    {
6841      struct file_name_list *temp = pfile->dont_repeat_files;
6842      pfile->dont_repeat_files = temp->next;
6843      free (temp->fname);
6844      free (temp);
6845    }
6846
6847  while (pfile->all_include_files)
6848    {
6849      struct file_name_list *temp = pfile->all_include_files;
6850      pfile->all_include_files = temp->next;
6851      free (temp->fname);
6852      free (temp);
6853    }
6854
6855  for (i = IMPORT_HASH_SIZE; --i >= 0; )
6856    {
6857      register struct import_file *imp = pfile->import_hash_table[i];
6858      while (imp)
6859        {
6860          struct import_file *next = imp->next;
6861          free (imp->name);
6862          free (imp);
6863          imp = next;
6864        }
6865      pfile->import_hash_table[i] = 0;
6866    }
6867
6868  for (i = ASSERTION_HASHSIZE; --i >= 0; )
6869    {
6870      while (pfile->assertion_hashtab[i])
6871        delete_assertion (pfile->assertion_hashtab[i]);
6872    }
6873
6874  cpp_hash_cleanup (pfile);
6875}
6876
6877static int
6878do_assert (pfile, keyword, buf, limit)
6879     cpp_reader *pfile;
6880     struct directive *keyword;
6881     U_CHAR *buf, *limit;
6882{
6883  long symstart;                /* remember where symbol name starts */
6884  int c;
6885  int sym_length;               /* and how long it is */
6886  struct arglist *tokens = NULL;
6887
6888  if (CPP_PEDANTIC (pfile) && CPP_OPTIONS (pfile)->done_initializing
6889      && !CPP_BUFFER (pfile)->system_header_p)
6890    cpp_pedwarn (pfile, "ANSI C does not allow `#assert'");
6891
6892  cpp_skip_hspace (pfile);
6893  symstart = CPP_WRITTEN (pfile);       /* remember where it starts */
6894  parse_name (pfile, GETC());
6895  sym_length = check_macro_name (pfile, pfile->token_buffer + symstart,
6896                                 "assertion");
6897
6898  cpp_skip_hspace (pfile);
6899  if (PEEKC() != '(') {
6900    cpp_error (pfile, "missing token-sequence in `#assert'");
6901    goto error;
6902  }
6903
6904  {
6905    int error_flag = 0;
6906    tokens = read_token_list (pfile, &error_flag);
6907    if (error_flag)
6908      goto error;
6909    if (tokens == 0) {
6910      cpp_error (pfile, "empty token-sequence in `#assert'");
6911      goto error;
6912    }
6913  cpp_skip_hspace (pfile);
6914  c = PEEKC ();
6915  if (c != EOF && c != '\n')
6916      cpp_pedwarn (pfile, "junk at end of `#assert'");
6917  skip_rest_of_line (pfile);
6918  }
6919
6920  /* If this name isn't already an assertion name, make it one.
6921     Error if it was already in use in some other way.  */
6922
6923  {
6924    ASSERTION_HASHNODE *hp;
6925    U_CHAR *symname = pfile->token_buffer + symstart;
6926    int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6927    struct tokenlist_list *value
6928      = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6929
6930    hp = assertion_lookup (pfile, symname, sym_length, hashcode);
6931    if (hp == NULL) {
6932      if (sym_length == 7 && ! strncmp (symname, "defined", sym_length))
6933        cpp_error (pfile, "`defined' redefined as assertion");
6934      hp = assertion_install (pfile, symname, sym_length, hashcode);
6935    }
6936
6937    /* Add the spec'd token-sequence to the list of such.  */
6938    value->tokens = tokens;
6939    value->next = hp->value;
6940    hp->value = value;
6941  }
6942  CPP_SET_WRITTEN (pfile, symstart); /* Pop */
6943  return 0;
6944 error:
6945  CPP_SET_WRITTEN (pfile, symstart); /* Pop */
6946  skip_rest_of_line (pfile);
6947  return 1;
6948}
6949
6950static int
6951do_unassert (pfile, keyword, buf, limit)
6952     cpp_reader *pfile;
6953     struct directive *keyword;
6954     U_CHAR *buf, *limit;
6955{
6956  long symstart;                /* remember where symbol name starts */
6957  int sym_length;       /* and how long it is */
6958  int c;
6959
6960  struct arglist *tokens = NULL;
6961  int tokens_specified = 0;
6962
6963  if (CPP_PEDANTIC (pfile) && CPP_OPTIONS (pfile)->done_initializing
6964      && !CPP_BUFFER (pfile)->system_header_p)
6965    cpp_pedwarn (pfile, "ANSI C does not allow `#unassert'");
6966
6967  cpp_skip_hspace (pfile);
6968
6969  symstart = CPP_WRITTEN (pfile);       /* remember where it starts */
6970  parse_name (pfile, GETC());
6971  sym_length = check_macro_name (pfile, pfile->token_buffer + symstart,
6972                                 "assertion");
6973
6974  cpp_skip_hspace (pfile);
6975  if (PEEKC() == '(') {
6976    int error_flag = 0;
6977
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 list in `#unassert'");
6983      goto error;
6984    }
6985
6986    tokens_specified = 1;
6987  }
6988
6989  cpp_skip_hspace (pfile);
6990  c = PEEKC ();
6991  if (c != EOF && c != '\n')
6992      cpp_error (pfile, "junk at end of `#unassert'");
6993  skip_rest_of_line (pfile);
6994
6995  {
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 *tail, *prev;
7000
7001    hp = assertion_lookup (pfile, symname, sym_length, hashcode);
7002    if (hp == NULL)
7003      return 1;
7004
7005    /* If no token list was specified, then eliminate this assertion
7006       entirely.  */
7007    if (! tokens_specified)
7008      delete_assertion (hp);
7009    else {
7010      /* If a list of tokens was given, then delete any matching list.  */
7011
7012      tail = hp->value;
7013      prev = 0;
7014      while (tail) {
7015        struct tokenlist_list *next = tail->next;
7016        if (compare_token_lists (tail->tokens, tokens)) {
7017          if (prev)
7018            prev->next = next;
7019          else
7020            hp->value = tail->next;
7021          free_token_list (tail->tokens);
7022          free (tail);
7023        } else {
7024          prev = tail;
7025        }
7026        tail = next;
7027      }
7028    }
7029  }
7030
7031  CPP_SET_WRITTEN (pfile, symstart); /* Pop */
7032  return 0;
7033 error:
7034  CPP_SET_WRITTEN (pfile, symstart); /* Pop */
7035  skip_rest_of_line (pfile);
7036  return 1;
7037}
7038
7039/* Test whether there is an assertion named NAME
7040   and optionally whether it has an asserted token list TOKENS.
7041   NAME is not null terminated; its length is SYM_LENGTH.
7042   If TOKENS_SPECIFIED is 0, then don't check for any token list.  */
7043
7044int
7045check_assertion (pfile, name, sym_length, tokens_specified, tokens)
7046     cpp_reader *pfile;
7047     U_CHAR *name;
7048     int sym_length;
7049     int tokens_specified;
7050     struct arglist *tokens;
7051{
7052  ASSERTION_HASHNODE *hp;
7053  int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
7054
7055  if (CPP_PEDANTIC (pfile) && !CPP_BUFFER (pfile)->system_header_p)
7056    cpp_pedwarn (pfile, "ANSI C does not allow testing assertions");
7057
7058  hp = assertion_lookup (pfile, name, sym_length, hashcode);
7059  if (hp == NULL)
7060    /* It is not an assertion; just return false.  */
7061    return 0;
7062
7063  /* If no token list was specified, then value is 1.  */
7064  if (! tokens_specified)
7065    return 1;
7066
7067  {
7068    struct tokenlist_list *tail;
7069
7070    tail = hp->value;
7071
7072    /* If a list of tokens was given,
7073       then succeed if the assertion records a matching list.  */
7074
7075    while (tail) {
7076      if (compare_token_lists (tail->tokens, tokens))
7077        return 1;
7078      tail = tail->next;
7079    }
7080
7081    /* Fail if the assertion has no matching list.  */
7082    return 0;
7083  }
7084}
7085
7086/* Compare two lists of tokens for equality including order of tokens.  */
7087
7088static int
7089compare_token_lists (l1, l2)
7090     struct arglist *l1, *l2;
7091{
7092  while (l1 && l2) {
7093    if (l1->length != l2->length)
7094      return 0;
7095    if (strncmp (l1->name, l2->name, l1->length))
7096      return 0;
7097    l1 = l1->next;
7098    l2 = l2->next;
7099  }
7100
7101  /* Succeed if both lists end at the same time.  */
7102  return l1 == l2;
7103}
7104
7105struct arglist *
7106reverse_token_list (tokens)
7107     struct arglist *tokens;
7108{
7109  register struct arglist *prev = 0, *this, *next;
7110  for (this = tokens; this; this = next)
7111    {
7112      next = this->next;
7113      this->next = prev;
7114      prev = this;
7115    }
7116  return prev;
7117}
7118
7119/* Read a space-separated list of tokens ending in a close parenthesis.
7120   Return a list of strings, in the order they were written.
7121   (In case of error, return 0 and store -1 in *ERROR_FLAG.) */
7122
7123static struct arglist *
7124read_token_list (pfile, error_flag)
7125     cpp_reader *pfile;
7126     int *error_flag;
7127{
7128  struct arglist *token_ptrs = 0;
7129  int depth = 1;
7130  int length;
7131
7132  *error_flag = 0;
7133  FORWARD (1);  /* Skip '(' */
7134
7135  /* Loop over the assertion value tokens.  */
7136  while (depth > 0)
7137    {
7138      struct arglist *temp;
7139      long name_written = CPP_WRITTEN (pfile);
7140      int eofp = 0;  int c;
7141
7142      cpp_skip_hspace (pfile);
7143
7144      c = GETC ();
7145         
7146      /* Find the end of the token.  */
7147      if (c == '(')
7148        {
7149          CPP_PUTC (pfile, c);
7150          depth++;
7151        }
7152      else if (c == ')')
7153        {
7154          depth--;
7155          if (depth == 0)
7156            break;
7157          CPP_PUTC (pfile, c);
7158        }
7159      else if (c == '"' || c == '\'')
7160        {
7161          FORWARD(-1);
7162          cpp_get_token (pfile);
7163        }
7164      else if (c == '\n')
7165        break;
7166      else
7167        {
7168          while (c != EOF && ! is_space[c] && c != '(' && c != ')'
7169                 && c != '"' && c != '\'')
7170            {
7171              CPP_PUTC (pfile, c);
7172              c = GETC();
7173            }
7174          if (c != EOF)  FORWARD(-1);
7175        }
7176
7177      length = CPP_WRITTEN (pfile) - name_written;
7178      temp = (struct arglist *)
7179          xmalloc (sizeof (struct arglist) + length + 1);
7180      temp->name = (U_CHAR *) (temp + 1);
7181      bcopy ((char *) (pfile->token_buffer + name_written),
7182             (char *) temp->name, length);
7183      temp->name[length] = 0;
7184      temp->next = token_ptrs;
7185      token_ptrs = temp;
7186      temp->length = length;
7187
7188      CPP_ADJUST_WRITTEN (pfile, -length); /* pop */
7189
7190      if (c == EOF || c == '\n')
7191        { /* FIXME */
7192          cpp_error (pfile,
7193                     "unterminated token sequence following  `#' operator");
7194          return 0;
7195        }
7196    }
7197
7198  /* We accumulated the names in reverse order.
7199     Now reverse them to get the proper order.  */
7200  return reverse_token_list (token_ptrs);
7201}
7202
7203static void
7204free_token_list (tokens)
7205     struct arglist *tokens;
7206{
7207  while (tokens) {
7208    struct arglist *next = tokens->next;
7209    free (tokens->name);
7210    free (tokens);
7211    tokens = next;
7212  }
7213}
7214
7215/* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
7216   retrying if necessary.  If MAX_READ_LEN is defined, read at most
7217   that bytes at a time.  Return a negative value if an error occurs,
7218   otherwise return the actual number of bytes read,
7219   which must be LEN unless end-of-file was reached.  */
7220
7221static int
7222safe_read (desc, ptr, len)
7223     int desc;
7224     char *ptr;
7225     int len;
7226{
7227  int left, rcount, nchars;
7228
7229  left = len;
7230  while (left > 0) {
7231    rcount = left;
7232#ifdef MAX_READ_LEN
7233    if (rcount > MAX_READ_LEN)
7234      rcount = MAX_READ_LEN;
7235#endif
7236    nchars = read (desc, ptr, rcount);
7237    if (nchars < 0)
7238      {
7239#ifdef EINTR
7240        if (errno == EINTR)
7241          continue;
7242#endif
7243        return nchars;
7244      }
7245    if (nchars == 0)
7246      break;
7247    ptr += nchars;
7248    left -= nchars;
7249  }
7250  return len - left;
7251}
7252
7253static char *
7254xcalloc (number, size)
7255     unsigned number, size;
7256{
7257  register unsigned total = number * size;
7258  register char *ptr = (char *) xmalloc (total);
7259  bzero (ptr, total);
7260  return ptr;
7261}
7262
7263static char *
7264savestring (input)
7265     char *input;
7266{
7267  unsigned size = strlen (input);
7268  char *output = xmalloc (size + 1);
7269  strcpy (output, input);
7270  return output;
7271}
7272
7273/* Initialize PMARK to remember the current position of PFILE.  */
7274
7275void
7276parse_set_mark (pmark, pfile)
7277     struct parse_marker *pmark;
7278     cpp_reader *pfile;
7279{
7280  cpp_buffer *pbuf = CPP_BUFFER (pfile);
7281  pmark->next = pbuf->marks;
7282  pbuf->marks = pmark;
7283  pmark->buf = pbuf;
7284  pmark->position = pbuf->cur - pbuf->buf;
7285}
7286
7287/* Cleanup PMARK - we no longer need it.  */
7288
7289void
7290parse_clear_mark (pmark)
7291     struct parse_marker *pmark;
7292{
7293  struct parse_marker **pp = &pmark->buf->marks;
7294  for (; ; pp = &(*pp)->next) {
7295    if (*pp == NULL) abort ();
7296    if (*pp == pmark) break;
7297  }
7298  *pp = pmark->next;
7299}
7300
7301/* Backup the current position of PFILE to that saved in PMARK.  */
7302
7303void
7304parse_goto_mark (pmark, pfile)
7305     struct parse_marker *pmark;
7306     cpp_reader *pfile;
7307{
7308  cpp_buffer *pbuf = CPP_BUFFER (pfile);
7309  if (pbuf != pmark->buf)
7310    cpp_fatal (pfile, "internal error %s", "parse_goto_mark");
7311  pbuf->cur = pbuf->buf + pmark->position;
7312}
7313
7314/* Reset PMARK to point to the current position of PFILE.  (Same
7315   as parse_clear_mark (PMARK), parse_set_mark (PMARK, PFILE) but faster.  */
7316
7317void
7318parse_move_mark (pmark, pfile)
7319     struct parse_marker *pmark;
7320     cpp_reader *pfile;
7321{
7322  cpp_buffer *pbuf = CPP_BUFFER (pfile);
7323  if (pbuf != pmark->buf)
7324    cpp_fatal (pfile, "internal error %s", "parse_move_mark");
7325  pmark->position = pbuf->cur - pbuf->buf;
7326}
7327
7328int
7329cpp_read_check_assertion (pfile)
7330     cpp_reader *pfile;
7331{
7332  int name_start = CPP_WRITTEN (pfile);
7333  int name_length, name_written;
7334  int result;
7335  FORWARD (1);  /* Skip '#' */
7336  cpp_skip_hspace (pfile);
7337  parse_name (pfile, GETC ());
7338  name_written = CPP_WRITTEN (pfile);
7339  name_length = name_written - name_start;
7340  cpp_skip_hspace (pfile);
7341  if (CPP_BUF_PEEK (CPP_BUFFER (pfile)) == '(')
7342    {
7343      int error_flag;
7344      struct arglist *token_ptrs = read_token_list (pfile, &error_flag);
7345      result = check_assertion (pfile,
7346                                pfile->token_buffer + name_start, name_length,
7347                                1, token_ptrs);
7348    }
7349  else
7350    result = check_assertion (pfile,
7351                              pfile->token_buffer + name_start, name_length,
7352                              0, NULL_PTR);
7353  CPP_ADJUST_WRITTEN (pfile, - name_length);  /* pop */
7354  return result;
7355}
7356
7357void
7358cpp_print_file_and_line (pfile)
7359     cpp_reader *pfile;
7360{
7361  cpp_buffer *ip = cpp_file_buffer (pfile);
7362
7363  if (ip != NULL)
7364    {
7365      long line, col;
7366      cpp_buf_line_and_col (ip, &line, &col);
7367      cpp_file_line_for_message (pfile, ip->nominal_fname,
7368                                 line, pfile->show_column ? col : -1);
7369    }
7370}
7371
7372void
7373cpp_error (pfile, msg, arg1, arg2, arg3)
7374     cpp_reader *pfile;
7375     char *msg;
7376     char *arg1, *arg2, *arg3;
7377{
7378  cpp_print_containing_files (pfile);
7379  cpp_print_file_and_line (pfile);
7380  cpp_message (pfile, 1, msg, arg1, arg2, arg3);
7381}
7382
7383/* Print error message but don't count it.  */
7384
7385void
7386cpp_warning (pfile, msg, arg1, arg2, arg3)
7387     cpp_reader *pfile;
7388     char *msg;
7389     char *arg1, *arg2, *arg3;
7390{
7391  if (CPP_OPTIONS (pfile)->inhibit_warnings)
7392    return;
7393
7394  if (CPP_OPTIONS (pfile)->warnings_are_errors)
7395    pfile->errors++;
7396
7397  cpp_print_containing_files (pfile);
7398  cpp_print_file_and_line (pfile);
7399  cpp_message (pfile, 0, msg, arg1, arg2, arg3);
7400}
7401
7402/* Print an error message and maybe count it.  */
7403
7404void
7405cpp_pedwarn (pfile, msg, arg1, arg2, arg3)
7406     cpp_reader *pfile;
7407     char *msg;
7408     char *arg1, *arg2, *arg3;
7409{
7410  if (CPP_OPTIONS (pfile)->pedantic_errors)
7411    cpp_error (pfile, msg, arg1, arg2, arg3);
7412  else
7413    cpp_warning (pfile, msg, arg1, arg2, arg3);
7414}
7415
7416void
7417cpp_error_with_line (pfile, line, column, msg, arg1, arg2, arg3)
7418     cpp_reader *pfile;
7419     int line, column;
7420     char *msg;
7421     char *arg1, *arg2, *arg3;
7422{
7423  int i;
7424  cpp_buffer *ip = cpp_file_buffer (pfile);
7425
7426  cpp_print_containing_files (pfile);
7427
7428  if (ip != NULL)
7429    cpp_file_line_for_message (pfile, ip->nominal_fname, line, column);
7430
7431  cpp_message (pfile, 1, msg, arg1, arg2, arg3);
7432}
7433
7434static void
7435cpp_warning_with_line (pfile, line, column, msg, arg1, arg2, arg3)
7436     cpp_reader *pfile;
7437     int line, column;
7438     char *msg;
7439     char *arg1, *arg2, *arg3;
7440{
7441  int i;
7442  cpp_buffer *ip;
7443
7444  if (CPP_OPTIONS (pfile)->inhibit_warnings)
7445    return;
7446
7447  if (CPP_OPTIONS (pfile)->warnings_are_errors)
7448    pfile->errors++;
7449
7450  cpp_print_containing_files (pfile);
7451
7452  ip = cpp_file_buffer (pfile);
7453
7454  if (ip != NULL)
7455    cpp_file_line_for_message (pfile, ip->nominal_fname, line, column);
7456
7457  cpp_message (pfile, 0, msg, arg1, arg2, arg3);
7458}
7459
7460void
7461cpp_pedwarn_with_line (pfile, line, column, msg, arg1, arg2, arg3)
7462     cpp_reader *pfile;
7463     int line;
7464     char *msg;
7465     char *arg1, *arg2, *arg3;
7466{
7467  if (CPP_OPTIONS (pfile)->pedantic_errors)
7468    cpp_error_with_line (pfile, column, line, msg, arg1, arg2, arg3);
7469  else
7470    cpp_warning_with_line (pfile, line, column, msg, arg1, arg2, arg3);
7471}
7472
7473/* Report a warning (or an error if pedantic_errors)
7474   giving specified file name and line number, not current.  */
7475
7476void
7477cpp_pedwarn_with_file_and_line (pfile, file, line, msg, arg1, arg2, arg3)
7478     cpp_reader *pfile;
7479     char *file;
7480     int line;
7481     char *msg;
7482     char *arg1, *arg2, *arg3;
7483{
7484  if (!CPP_OPTIONS (pfile)->pedantic_errors
7485      && CPP_OPTIONS (pfile)->inhibit_warnings)
7486    return;
7487  if (file != NULL)
7488    cpp_file_line_for_message (pfile, file, line, -1);
7489  cpp_message (pfile, CPP_OPTIONS (pfile)->pedantic_errors,
7490               msg, arg1, arg2, arg3);
7491}
7492
7493/* This defines "errno" properly for VMS, and gives us EACCES.  */
7494#include <errno.h>
7495#ifndef errno
7496extern int errno;
7497#endif
7498
7499#ifndef VMS
7500#ifndef HAVE_STRERROR
7501extern int sys_nerr;
7502extern char *sys_errlist[];
7503#else   /* HAVE_STRERROR */
7504char *strerror ();
7505#endif
7506#else   /* VMS */
7507char *strerror (int,...);
7508#endif
7509
7510/* my_strerror - return the descriptive text associated with an
7511   `errno' code.  */
7512
7513char *
7514my_strerror (errnum)
7515     int errnum;
7516{
7517  char *result;
7518
7519#ifndef VMS
7520#ifndef HAVE_STRERROR
7521  result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
7522#else
7523  result = strerror (errnum);
7524#endif
7525#else   /* VMS */
7526  /* VAXCRTL's strerror() takes an optional second argument, which only
7527     matters when the first argument is EVMSERR.  However, it's simplest
7528     just to pass it unconditionally.  `vaxc$errno' is declared in
7529     <errno.h>, and maintained by the library in parallel with `errno'.
7530     We assume that caller's `errnum' either matches the last setting of
7531     `errno' by the library or else does not have the value `EVMSERR'.  */
7532
7533  result = strerror (errnum, vaxc$errno);
7534#endif
7535
7536  if (!result)
7537    result = "undocumented I/O error";
7538
7539  return result;
7540}
7541
7542/* Error including a message from `errno'.  */
7543
7544void
7545cpp_error_from_errno (pfile, name)
7546     cpp_reader *pfile;
7547     char *name;
7548{
7549  int e = errno;
7550  int i;
7551  cpp_buffer *ip = cpp_file_buffer (pfile);
7552
7553  cpp_print_containing_files (pfile);
7554
7555  if (ip != NULL)
7556    cpp_file_line_for_message (pfile, ip->nominal_fname, ip->lineno, -1);
7557
7558  cpp_message (pfile, 1, "%s: %s", name, my_strerror (e));
7559}
7560
7561void
7562cpp_perror_with_name (pfile, name)
7563     cpp_reader *pfile;
7564     char *name;
7565{
7566  cpp_message (pfile, 1, "%s: %s: %s", progname, name, my_strerror (errno));
7567}
7568
7569/* TODO:
7570 * No pre-compiled header file support.
7571 *
7572 * Possibly different enum token codes for each C/C++ token.
7573 *
7574 * Should clean up remaining directives to that do_XXX functions
7575 *   only take two arguments and all have command_reads_line.
7576 *
7577 * Find and cleanup remaining uses of static variables,
7578 *
7579 * Support for trigraphs.
7580 *
7581 * Support -dM flag (dump_all_macros).
7582 *
7583 * Support for_lint flag.
7584 */
Note: See TracBrowser for help on using the repository browser.