2 ** LCLint - annotation-assisted static program checker
3 ** Copyright (C) 1994-2000 University of Virginia,
4 ** Massachusetts Institute of Technology
6 ** This program is free software; you can redistribute it and/or modify it
7 ** under the terms of the GNU General Public License as published by the
8 ** Free Software Foundation; either version 2 of the License, or (at your
9 ** option) any later version.
11 ** This program is distributed in the hope that it will be useful, but
12 ** WITHOUT ANY WARRANTY; without even the implied warranty of
13 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ** General Public License for more details.
16 ** The GNU General Public License is available from http://www.gnu.org/ or
17 ** the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
18 ** MA 02111-1307, USA.
20 ** For information on lclint: lclint-request@cs.virginia.edu
21 ** To report a bug: lclint-bug@cs.virginia.edu
22 ** For more information: http://lclint.cs.virginia.edu
28 Copyright (C) 1986, 87, 89, 92-6, 1997 Free Software Foundation, Inc.
29 Contributed by Per Bothner, 1994-95.
30 Based on CCCP program by Paul Rubin, June 1986
31 Adapted to ANSI C, Richard Stallman, Jan 1987
33 This program is free software; you can redistribute it and/or modify it
34 under the terms of the GNU General Public License as published by the
35 Free Software Foundation; either version 2, or (at your option) any
38 This program is distributed in the hope that it will be useful,
39 but WITHOUT ANY WARRANTY; without even the implied warranty of
40 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 GNU General Public License for more details.
43 You should have received a copy of the GNU General Public License
44 along with this program; if not, write to the Free Software
45 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 In other words, you are welcome to use, share and improve this program.
48 You are forbidden to forbid anyone else to use, share and improve
49 what you give them. Help stamp out software-hoarding! */
64 # include <sys/types.h>
65 # include <sys/stat.h>
70 # include <sys/utime.h> /* for __DATE__ and __TIME__ */
75 # include <sys/time.h>
76 # include <sys/resource.h>
78 # include <sys/times.h>
83 # endif /* not WIN32 */
85 /* This defines "errno" properly for VMS, and gives us EACCES. */
88 # include "lclintMacros.nf"
93 # include "cpperror.h"
101 ** This is really kludgey code...
107 #define NO_SHORTNAMES
115 /*@constant int IMPORT_FOUND@*/
116 # define IMPORT_FOUND -2
118 /*@constant int SKIP_INCLUDE@*/
119 # define SKIP_INCLUDE IMPORT_FOUND
121 /*@constant unused int IMPORT_NOT_FOUND@*/
122 # define IMPORT_NOT_FOUND -1
125 /*@constant unused int STDC_VALUE@*/
129 /* By default, colon separates directories in a path. */
130 #ifndef PATH_SEPARATOR
131 /*@constant char PATH_SEPARATOR@*/
132 #define PATH_SEPARATOR ':'
135 static void parse_name (cppReader *, int);
137 static int cpp_openIncludeFile (char *p_filename)
138 /*@modifies fileSystem @*/ ;
140 static void cpp_setLocation (cppReader *p_pfile)
141 /*@modifies g_currentloc@*/ ;
143 static enum cpp_token cpp_handleComment (cppReader *p_pfile,
144 struct parse_marker *p_smark)
145 /*@modifies *p_pfile, *p_smark@*/;
147 static bool cpp_shouldCheckMacro (cppReader *p_pfile, char *p_p) /*@*/ ;
149 static bool cpp_skipIncludeFile (cstring p_fname) /*@*/ ;
155 /* Symbols to predefine. */
157 #ifdef CPP_PREDEFINES
158 static /*@observer@*/ char *predefs = CPP_PREDEFINES;
160 static /*@observer@*/ char *predefs = "";
163 /* We let tm.h override the types used here, to handle trivial differences
164 such as the choice of unsigned int or long unsigned int for size_t.
165 When machines start needing nontrivial differences in the size type,
166 it would be best to do something here to figure out automatically
167 from other information what type to use. */
169 /* The string value for __SIZE_TYPE__. */
172 /*@constant observer char *SIZE_TYPE@*/
173 #define SIZE_TYPE "long unsigned int"
176 /* The string value for __PTRDIFF_TYPE__. */
179 /*@constant observer char *PTRDIFF_TYPE@*/
180 #define PTRDIFF_TYPE "long int"
183 /* The string value for __WCHAR_TYPE__. */
186 /*@constant observer char *WCHAR_TYPE@*/
187 #define WCHAR_TYPE "int"
190 /* The string value for __USER_LABEL_PREFIX__ */
192 #ifndef USER_LABEL_PREFIX
193 /*@constant observer char *USER_LABEL_PREFIX@*/
194 #define USER_LABEL_PREFIX ""
197 /* The string value for __REGISTER_PREFIX__ */
199 #ifndef REGISTER_PREFIX
200 /*@constant observer char *REGISTER_PREFIX@*/
201 #define REGISTER_PREFIX ""
204 /* table to tell if char can be part of a C identifier. */
205 static bool is_idchar[256];
206 /* table to tell if char can be first char of a c identifier. */
207 static bool is_idstart[256];
208 /* table to tell if c is horizontal space. */
209 static bool is_hor_space[256];
210 /* table to tell if c is horizontal or vertical space. */
211 static bool is_space[256];
213 static /*@exposed@*/ /*@null@*/ cppBuffer *
214 cppReader_getBuffer (/*@special@*/ cppReader *p_pfile)
215 /*@uses p_pfile->buffer@*/
216 /*@modifies nothing@*/ ;
219 # define SKIP_WHITE_SPACE(p) do { /*@access cstring@*/ while (is_hor_space[(int) *(p)]) { (p)++; } } /*@noaccess cstring@*/ while (0)
222 # define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*(p)]) { (p)++; } } while (0)
224 static int cpp_peekN (cppReader *p_pfile, int p_n) /*@*/ ;
226 /*@function static int cppBuffer_get (sef cppBuffer *p_b) modifies *p_b ; @*/
227 # define cppBuffer_get(BUFFER) \
228 ((BUFFER)->cur < (BUFFER)->rlimit ? *(BUFFER)->cur++ : EOF)
230 /* Append string STR (of length N) to PFILE's output buffer. Make space. */
231 /*@function static void cppReader_puts (sef cppReader *p_file, char *p_str, sef size_t p_n)
232 modifies *p_file; @*/
233 # define cppReader_puts(PFILE, STR, N) \
234 cppReader_reserve(PFILE, N), cppReader_putStrN (PFILE, STR,N)
236 /* Append character CH to PFILE's output buffer. Assume sufficient space. */
238 /*@function static void cppReader_putCharQ (cppReader *p_file, char p_ch)
239 modifies *p_file; @*/
240 # define cppReader_putCharQ(PFILE, CH) (*(PFILE)->limit++ = (CH))
242 /* Append character CH to PFILE's output buffer. Make space if need be. */
244 /*@function static void cppReader_putChar (sef cppReader *p_file, char p_ch)
245 modifies *p_file; @*/
246 #define cppReader_putChar(PFILE, CH) (cppReader_reserve (PFILE, (size_t) 1), cppReader_putCharQ (PFILE, CH))
248 /* Make sure PFILE->limit is followed by '\0'. */
249 /*@function static void cppReader_nullTerminateQ (cppReader *p_file)
250 modifies *p_file; @*/
252 #define cppReader_nullTerminateQ(PFILE) (*(PFILE)->limit = 0)
254 /*@function static void cppReader_nullTerminate (sef cppReader *p_file)
255 modifies *p_file; @*/
256 # define cppReader_nullTerminate(PFILE) \
257 (cppReader_reserve (PFILE, (size_t) 1), *(PFILE)->limit = 0)
259 /*@function static void cppReader_adjustWritten (cppReader *p_file, size_t)
260 modifies *p_file; @*/
261 #define cppReader_adjustWritten(PFILE,DELTA) ((PFILE)->limit += (DELTA))
263 /*@function static bool cppReader_isC89 (cppReader *) modifies nothing; @*/
264 #define cppReader_isC89(PFILE) (CPPOPTIONS(PFILE)->c89)
266 /*@function static observer char *cppReader_wcharType (cppReader *)
267 modifies nothing; @*/
269 # define cppReader_wcharType(PFILE) \
270 (CPPOPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
272 static void cppBuffer_forward (cppBuffer *p_buf, int p_n) /*@modifies *p_buf@*/ ;
274 /*@function static void cppReader_forward (cppReader *p_pfile, int) modifies *p_pfile; @*/
275 # define cppReader_forward(pfile, N) \
276 (cppBuffer_forward (cppReader_getBufferSafe (pfile), (N)))
278 /*@function static int cppReader_getC (cppReader *p_pfile) modifies *p_pfile; @*/
279 # define cppReader_getC(pfile) (cppBuffer_get (cppReader_getBufferSafe (pfile)))
281 /*@function static int cppReader_peekC (cppReader *) modifies nothing;@*/
282 # define cppReader_peekC(pfile) (cppBufPeek (cppReader_getBufferSafe (pfile)))
284 /* Move all backslash-newline pairs out of embarrassing places.
285 Exchange all such pairs following BP
286 with any potentially-embarrassing characters that follow them.
287 Potentially-embarrassing characters are / and *
288 (because a backslash-newline inside a comment delimiter
289 would cause it not to be recognized). */
292 # define NEWLINE_FIX \
293 do { while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n') { cppReader_forward (pfile, 2); } } while(FALSE)
295 /* Same, but assume we've already read the potential '\\' into C. */
297 # define NEWLINE_FIX1(C) do { \
298 while ((C) == '\\' && cppReader_peekC (pfile) == '\n') { cppReader_forward (pfile, 1); (C) = cppReader_getC (pfile); }\
301 static void parseSetMark (/*@out@*/ struct parse_marker *,
303 static void parseClearMark (struct parse_marker *);
304 static void parseGotoMark (struct parse_marker *, cppReader *);
305 static void parseMoveMark (struct parse_marker *, cppReader *);
307 /* If we have a huge buffer, may need to cache more recent counts */
308 static /*@exposed@*/ char *cppLineBase (/*@sef@*/ cppBuffer *);
310 static /*@exposed@*/ /*@null@*/ cppBuffer *
311 cppReader_pushBuffer (cppReader *p_pfile,
312 /*@owned@*/ /*@null@*/ char *, size_t)
313 /*@modifies p_pfile@*/ ;
315 static void cppReader_appendIncludeChain
317 /*@keep@*/ struct file_name_list *p_first,
318 /*@dependent@*/ struct file_name_list *p_last);
320 static void cppReader_macroCleanup (cppBuffer *p_pbuf, cppReader *p_pfile);
321 static enum cpp_token cppReader_nullUnderflow (/*@unused@*/ cppReader *p_pfile);
323 static void cppReader_nullCleanup (/*@unused@*/ cppBuffer *p_pbuf,
324 /*@unused@*/ cppReader *p_pfile);
326 static void cppReader_fileCleanup (cppBuffer *p_pbuf,
327 /*@unused@*/ cppReader *p_pfile);
329 static int cppReader_handleDirective (cppReader *p_pfile);
331 static void cppReader_scanBuffer (cppReader *p_pfile);
336 ** WIN32 (at least the VC++ include files) does not define mode_t.
339 /*@-incondefs@*/ /*@-czechtypes@*/
340 typedef unsigned int mode_t;
341 /*@=incondefs@*/ /*@=czechtypes@*/
345 static int file_size_and_mode (int p_fd, /*@out@*/ mode_t *p_mode_pointer,
346 /*@out@*/ size_t *p_size_pointer);
347 static int safe_read (int p_desc, /*@out@*/ char *p_ptr, int p_len);
351 ** cppBuffer_isMacro is true if the buffer contains macro expansion.
352 ** (Note that it is false while we're expanding marco *arguments*.)
355 static bool cppBuffer_isMacro (/*@null@*/ cppBuffer *) /*@*/ ;
357 static void path_include (cppReader *p_pfile, char *p_path)
358 /*@modifies p_pfile@*/ ;
360 static void initialize_builtins (cppReader *p_pfile)
361 /*@modifies p_pfile@*/ ;
363 static void initialize_char_syntax (struct cppOptions *p_opts) ;
365 static int /*@alt void@*/ finclude (cppReader *p_pfile, int p_f,
367 bool p_system_header_p,
368 /*@dependent@*/ /*@null@*/ struct file_name_list *p_dirptr);
370 static void validate_else (cppReader *p_pfile, cstring p_directive);
372 static void conditional_skip (cppReader *p_pfile, int p_skip,
373 enum node_type p_type,
374 /*@dependent@*/ /*@null@*/ char *p_control_macro);
376 static HOST_WIDE_INT eval_if_expression (cppReader *p_pfile,
380 static void skip_if_group (cppReader *p_pfile, int p_any);
382 static bool comp_def_part (bool p_first, char *p_beg1, int p_len1,
383 char *p_beg2, int p_len2, bool p_last);
386 extern void fancy_abort ();
389 static bool redundant_include_p (cppReader *p_pfile, /*@null@*/ cstring p_name);
390 static bool is_system_include (cppReader *p_pfile, cstring p_filename);
392 static /*@observer@*/ /*@null@*/ struct file_name_map *
393 read_name_map (cppReader *p_pfile, cstring p_dirname);
395 static cstring read_filename_string (int p_ch, FILE *p_f);
397 static int open_include_file (cppReader *p_pfile,
398 /*@owned@*/ cstring p_fname,
399 /*@null@*/ struct file_name_list *p_searchptr);
401 static void push_macro_expansion (cppReader *,
402 /*@owned@*/ char *, size_t,
403 /*@dependent@*/ HASHNODE *);
405 /* Last arg to output_line_command. */
406 enum file_change_code {
407 same_file, enter_file, leave_file
410 /* `struct directive' defines one #-directive, including how to handle it. */
413 int length; /* Length of name */
414 /*@null@*/ int (*func)(); /* Function to handle directive */
415 /*@observer@*/ cstring name; /* Name of directive */
416 enum node_type type; /* Code which describes which directive. */
417 bool command_reads_line; /* One if rest of line is read by func. */
418 bool traditional_comments; /* Nonzero: keep comments if -traditional. */
419 bool pass_thru; /* Copy preprocessed directive to output file.*/
422 /* These functions are declared to return int instead of void since they
423 are going to be placed in a table and some old compilers have trouble with
424 pointers to functions returning void. */
426 static int do_define (cppReader *, /*@null@*/ struct directive *,
428 static int do_defineAux (cppReader *, /*@null@*/ struct directive *,
429 char *, char *, bool);
431 static int do_line (cppReader *, /*@null@*/ struct directive *);
432 static int do_include (cppReader *, struct directive *, char *, char *);
433 static int do_undef (cppReader *, struct directive *, char *, char *);
434 static int do_error (cppReader *, struct directive *, char *, char *);
435 static int do_pragma (cppReader *, struct directive *, char *, char *);
436 static int do_ident (cppReader *, struct directive *, char *, char *);
437 static int do_if (cppReader *, struct directive *, char *, char *);
438 static int do_xifdef (cppReader *, struct directive *, char *, char *);
439 static int do_else (cppReader *, struct directive *, char *, char *);
440 static int do_elif (cppReader *, struct directive *, char *, char *);
441 static int do_endif (cppReader *, struct directive *, char *, char *);
442 static int do_warning (cppReader *, struct directive *, char *, char *);
444 /* If a buffer's dir field is SELF_DIR_DUMMY, it means the file was found
445 via the same directory as the file that #included it. */
447 /*@constant observer struct file_name_list *SELF_DIR_DUMMY@*/
448 #define SELF_DIR_DUMMY ((struct file_name_list *) (~0))
450 /* #include "file" looks in source file dir, then stack. */
451 /* #include <file> just looks in the stack. */
452 /* -I directories are added to the end, then the defaults are added. */
456 static struct default_include {
457 /*@dependent@*/ /*@observer@*/ cstring fname; /* The name of the directory. */
458 int cplusplus; /* Only look here if we're compiling C++. */
459 int cxx_aware; /* Includes in this directory don't need to
460 be wrapped in extern "C" when compiling
462 } include_defaults_array[]
464 /* This is the dir for fixincludes. Put it just before
465 the files that we fix. */
466 { GCC_INCLUDE_DIR, 0, 0 },
467 { GCC_INCLUDE_DIR2, 0, 0 },
468 { cstring_undefined, 0, 0 }
471 /*@noaccess cstring@*/
473 /* Here is the actual list of #-directives, most-often-used first.
474 The initialize_builtins function assumes #define is the very first. */
478 static struct directive directive_table[] = {
479 { 6, do_define, "define", T_DEFINE, FALSE, TRUE, FALSE },
480 { 5, do_xifdef, "ifdef", T_IFDEF, TRUE, FALSE, FALSE },
481 { 6, do_xifdef, "ifndef", T_IFNDEF, TRUE, FALSE, FALSE },
482 { 7, do_include, "include", T_INCLUDE, TRUE, FALSE, FALSE },
483 { 5, do_endif, "endif", T_ENDIF, TRUE, FALSE, FALSE },
484 { 4, do_else, "else", T_ELSE, TRUE, FALSE, FALSE },
485 { 2, do_if, "if", T_IF, TRUE, FALSE, FALSE },
486 { 4, do_elif, "elif", T_ELIF, TRUE, FALSE, FALSE },
487 { 5, do_undef, "undef", T_UNDEF, FALSE, FALSE, FALSE },
488 { 5, do_error, "error", T_ERROR, FALSE, FALSE, FALSE },
489 { 7, do_warning, "warning", T_WARNING, FALSE, FALSE, FALSE },
490 { 6, do_pragma, "pragma", T_PRAGMA, FALSE, FALSE, TRUE},
491 { 4, do_line, "line", T_LINE, TRUE, FALSE, FALSE },
492 { 5, do_ident, "ident", T_IDENT, TRUE, FALSE, TRUE },
493 /* { 8, do_unassert, "unassert", T_UNASSERT, TRUE, FALSE, FALSE }, */
494 { -1, 0, "", T_UNUSED, FALSE, FALSE, FALSE },
497 /*@noaccess cstring@*/
501 initialize_char_syntax (struct cppOptions *opts)
506 * Set up is_idchar and is_idstart tables. These should be
507 * faster than saying (is_alpha (c) || c == '_'), etc.
508 * Set up these things before calling any routines tthat
512 for (i = 'a'; i <= 'z'; i++) {
513 is_idchar[i - 'a' + 'A'] = TRUE;
514 is_idchar[(int) i] = TRUE;
515 is_idstart[i - 'a' + 'A'] = TRUE;
516 is_idstart[(int) i] = TRUE;
519 for (i = '0'; i <= '9'; i++)
521 is_idchar[(int) i] = TRUE;
524 is_idchar['_'] = TRUE;
525 is_idstart['_'] = TRUE;
526 is_idchar['$'] = opts->dollars_in_ident;
527 is_idstart['$'] = opts->dollars_in_ident;
529 /* horizontal space table */
530 is_hor_space[' '] = TRUE;
531 is_hor_space['\t'] = TRUE;
532 is_hor_space['\v'] = TRUE;
533 is_hor_space['\f'] = TRUE;
534 is_hor_space['\r'] = TRUE;
536 is_space[' '] = TRUE;
537 is_space['\t'] = TRUE;
538 is_space['\v'] = TRUE;
539 is_space['\f'] = TRUE;
540 is_space['\n'] = TRUE;
541 is_space['\r'] = TRUE;
544 bool isIdentifierChar (char c)
546 return is_idchar[(int) c];
549 /* Place into P_PFILE a quoted string representing the string SRC.
550 Caller must reserve enough space in pfile->token_buffer. */
553 quote_string (cppReader *pfile, char *src)
557 cppReader_putCharQ (pfile, '\"');
560 switch ((c = *src++))
564 cppReader_putCharQ (pfile, c);
567 sprintf (cppReader_getPWritten (pfile), "\\%03o",
569 cppReader_adjustWritten (pfile, (size_t) 4);
571 /*@switchbreak@*/ break;
575 cppReader_putCharQ (pfile, '\\');
576 cppReader_putCharQ (pfile, c);
577 /*@switchbreak@*/ break;
580 cppReader_putCharQ (pfile, '\"');
581 cppReader_nullTerminateQ (pfile);
587 /* Re-allocates PFILE->token_buffer so it will hold at least N more chars. */
590 cppReader_growBuffer (cppReader *pfile, size_t n)
592 size_t old_written = cppReader_getWritten (pfile);
593 pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
594 pfile->token_buffer = (char *)
595 drealloc (pfile->token_buffer, pfile->token_buffer_size);
596 cppReader_setWritten (pfile, old_written);
600 * process a given definition string, for initialization
601 * If STR is just an identifier, define it with value 1.
602 * If STR has anything after the identifier, then it should
603 * be identifier=definition.
607 cppReader_define (cppReader *pfile, char *str)
612 DPRINTF (("Cpp reader define: %s", str));
614 if (!is_idstart[(int) *p])
616 DPRINTF (("ERROR 1"));
617 cppReader_error (pfile,
618 message ("Malformed option `-D%s'",
619 cstring_fromChars (str)));
626 DPRINTF (("Here 2"));
628 while (is_idchar[(int) *p])
635 while (*p != ')' && *p != '\0') {
644 message ("Malformed option: -D%s (no closing parenthesis)",
645 cstring_fromChars (str)));
649 DPRINTF (("Here 2"));
653 buf = (char *) dmalloc (size_fromInt (p - str + 4));
654 strcpy ((char *) buf, str);
655 strcat ((char *) buf, " 1");
659 DPRINTF (("ERROR 2"));
660 cppReader_error (pfile,
661 message ("Malformed option: -D%s (expected '=', found '%c')",
662 cstring_fromChars (str),
669 /* Copy the entire option so we can modify it. */
670 DPRINTF (("Copying..."));
671 buf = (char *) dmalloc (2 * strlen (str) + 1);
672 strncpy (buf, str, size_fromInt (p - str));
674 /* Change the = to a space. */
676 /* Scan for any backslash-newline and remove it. */
682 if (*p == '\\' && p[1] == '\n')
688 DPRINTF (("Here we are..."));
692 llassert (buf != NULL);
693 DPRINTF (("Do define: %s / %ld", buf, size_toLong (strlen (buf))));
694 (void) do_define (pfile, NULL, buf, buf + strlen (buf));
698 /* Append a chain of `struct file_name_list's
699 to the end of the main include chain.
700 FIRST is the beginning of the chain to append, and LAST is the end. */
703 cppReader_appendIncludeChain (cppReader *pfile,
704 struct file_name_list *first,
705 struct file_name_list *last)
707 struct cppOptions *opts = CPPOPTIONS (pfile);
708 struct file_name_list *dir;
710 if (first == NULL || last == NULL)
715 if (opts->include == 0)
717 opts->include = first;
721 llassert (opts->last_include->next == NULL);
722 opts->last_include->next = first;
725 if (opts->first_bracket_include == 0)
727 opts->first_bracket_include = first;
729 for (dir = first; ; dir = dir->next) {
730 int len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
731 if (len > pfile->max_include_len)
732 pfile->max_include_len = len;
738 llassert (last->next == NULL);
739 /* last->next = NULL; */
740 opts->last_include = last;
743 static /*@unused@*/ void
744 cppReader_showIncludeChain (cppReader *pfile)
746 struct file_name_list *dirs = CPPOPTIONS (pfile)->include;
752 fprintf (stderr, "*%s*:", cstring_toCharsSafe (dirs->fname));
756 fprintf (stderr, "\n");
760 fprintf (stderr, "No includes\n");
765 cppReader_addIncludeChain (cppReader *pfile, struct file_name_list *dir)
767 struct cppOptions *opts = CPPOPTIONS (pfile);
774 if (opts->include == 0)
780 llassert (opts->last_include->next == NULL);
781 opts->last_include->next = dir;
784 if (opts->first_bracket_include == 0)
786 int len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
787 opts->first_bracket_include = dir;
788 if (len > pfile->max_include_len)
790 pfile->max_include_len = len;
795 opts->last_include = dir;
796 /* cppReader_showIncludeChain (pfile); */
799 /* Given a colon-separated list of file names PATH,
800 add all the names to the search path for include files. */
803 path_include (cppReader *pfile, char *path)
810 /* if we have a posix path list, convert to win32 path list */
811 win32temp = (char *) dmalloc /*@i4@*/
812 (cygwin32_posix_to_win32_path_list_buf_size (path));
813 cygwin32_posix_to_win32_path_list (path, win32temp);
823 struct file_name_list *dirtmp;
825 /* Find the end of this name. */
826 while (*q != '\0' && *q != PATH_SEPARATOR)
833 /* An empty name in the path stands for the current directory. */
834 name = (char *) dmalloc ((size_t) 2);
840 /* Otherwise use the directory that is named. */
841 name = (char *) dmalloc (size_fromInt (q - p + 1));
842 memcpy (name, p, size_fromInt (q - p));
846 dirtmp = (struct file_name_list *) dmalloc (sizeof (*dirtmp));
847 dirtmp->next = 0; /* New one goes on the end */
848 dirtmp->control_macro = 0;
849 dirtmp->c_system_include_path = 0;
850 dirtmp->fname = cstring_fromChars (name);
851 dirtmp->got_name_map = 0;
852 cppReader_addIncludeChain (pfile, dirtmp);
854 /* Advance past this name. */
858 /* Skip the colon. */
864 cppOptions_init (cppOptions *opts)
866 memset ((char *) opts, 0, sizeof *opts);
869 opts->in_fname = NULL;
870 opts->out_fname = NULL;
872 /* Initialize is_idchar to allow $. */
873 opts->dollars_in_ident = TRUE;
875 opts->no_line_commands = 0;
876 opts->no_trigraphs = TRUE;
877 opts->put_out_comments = 1;
878 opts->print_include_names = 0;
879 opts->dump_macros = DUMP_DEFINITIONS; /* DUMP_NONE; */
883 opts->cplusplus_comments = 1;
888 opts->pedantic_errors = 0;
889 opts->inhibit_warnings = 0;
890 opts->warn_comments = 0;
891 opts->warnings_are_errors = 0;
893 initialize_char_syntax (opts);
897 cppReader_nullUnderflow (/*@unused@*/ cppReader *pfile)
903 cppReader_nullCleanup (/*@unused@*/ cppBuffer *pbuf,
904 /*@unused@*/ cppReader *pfile)
910 cppReader_macroCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
912 HASHNODE *macro = pbuf->hnode;
914 if (macro->type == T_DISABLED)
916 macro->type = T_MACRO;
919 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
927 cppReader_fileCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
929 if (pbuf->buf != NULL)
936 /* Assuming we have read '/'.
937 If this is the start of a comment (followed by '*' or '/'),
938 skip to the end of the comment, and return ' '.
939 Return EOF if we reached the end of file before the end of the comment.
940 If not the start of a comment, return '/'. */
943 skip_comment (cppReader *pfile, /*@null@*/ long *linep)
947 llassert (pfile->buffer != NULL);
948 llassert (pfile->buffer->cur != NULL);
950 while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n')
957 cppReader_forward (pfile, 2);
960 if (cppReader_peekC (pfile) == '*')
962 cppReader_forward (pfile, 1);
967 c = cppReader_getC (pfile);
974 while (c == (int) '\\' && cppReader_peekC (pfile) == (int) '\n')
981 cppReader_forward (pfile, 1), c = cppReader_getC (pfile);
984 if (prev_c == (int) '*' && c == (int) '/')
989 if (c == (int) '\n' && (linep != NULL))
995 else if (cppReader_peekC (pfile) == '/'
996 && CPPOPTIONS (pfile)->cplusplus_comments)
998 cppReader_forward (pfile, 1);
1002 c = cppReader_getC (pfile);
1006 /* Allow hash comment to be terminated by EOF. */
1010 while (c == (int) '\\' && cppReader_peekC (pfile) == '\n')
1012 cppReader_forward (pfile, 1);
1013 c = cppReader_getC (pfile);
1021 if (c == (int) '\n')
1023 /* Don't consider final '\n' to be part of comment. */
1024 cppReader_forward (pfile, -1);
1035 /* Skip whitespace \-newline and comments. Does not macro-expand. */
1037 cppSkipHspace (cppReader *pfile)
1045 llassert (pfile->buffer != NULL);
1047 c = cppReader_peekC (pfile);
1051 return 0; /* FIXME */
1054 if (is_hor_space[c])
1056 if ((c == '\f' || c == '\v') && cppReader_isPedantic (pfile))
1057 cppReader_pedwarn (pfile,
1058 message ("%s in preprocessing directive",
1060 ? cstring_makeLiteralTemp ("formfeed")
1061 : cstring_makeLiteralTemp ("vertical tab")));
1064 cppReader_forward (pfile, 1);
1068 cppReader_forward (pfile, 1);
1069 c = skip_comment (pfile, NULL);
1073 cppReader_forward (pfile, -1);
1076 if (c == EOF || c == '/')
1081 else if (c == '\\' && cpp_peekN (pfile, 1) == '\n')
1083 cppReader_forward (pfile, 2);
1085 else if (c == '@' && CPPBUFFER (pfile)->has_escapes
1086 && is_hor_space [cpp_peekN (pfile, 1)])
1088 cppReader_forward (pfile, 2);
1097 /* Read the rest of the current line.
1098 The line is appended to PFILE's output buffer. */
1101 copy_rest_of_line (cppReader *pfile)
1103 struct cppOptions *opts = CPPOPTIONS (pfile);
1110 llassert (pfile->buffer != NULL);
1112 c = cppReader_getC (pfile);
1118 if (cppReader_peekC (pfile) == '\n')
1120 cppReader_forward (pfile, 1);
1124 /*@fallthrough@*/ case '\'': case '\"':
1125 goto scan_directive_token;
1128 nextc = cppReader_peekC (pfile);
1131 ** was (opts->cplusplus_comments && nextc == '*')
1136 || (opts->cplusplus_comments && nextc == '/'))
1138 goto scan_directive_token;
1140 /*@switchbreak@*/ break;
1143 if (cppReader_isPedantic (pfile))
1144 cppReader_pedwarn (pfile,
1145 message ("%s in preprocessing directive",
1147 ? cstring_makeLiteralTemp ("formfeed")
1148 : cstring_makeLiteralTemp ("vertical tab")));
1149 /*@switchbreak@*/ break;
1152 cppReader_forward (pfile, -1);
1154 scan_directive_token:
1155 cppReader_forward (pfile, -1);
1156 (void) cppGetToken (pfile);
1159 cppReader_putChar (pfile, c);
1162 cppReader_nullTerminate (pfile);
1166 cppReader_skipRestOfLine (cppReader *pfile)
1168 size_t old = cppReader_getWritten (pfile);
1169 copy_rest_of_line (pfile);
1170 cppReader_setWritten (pfile, old);
1173 /* Handle a possible # directive.
1174 '#' has already been read. */
1177 cppReader_handleDirective (cppReader *pfile)
1180 struct directive *kt = NULL;
1182 size_t after_ident = 0;
1183 char *ident, *line_end = NULL;
1184 size_t old_written = cppReader_getWritten (pfile);
1185 int nspaces = cppSkipHspace (pfile);
1187 c = cppReader_peekC (pfile);
1189 if (c >= '0' && c <= '9')
1191 /* Handle # followed by a line number. */
1192 if (cppReader_isPedantic (pfile))
1194 cppReader_pedwarnLit
1196 cstring_makeLiteralTemp ("`#' followed by integer"));
1199 (void) do_line (pfile, NULL);
1200 goto done_a_directive;
1204 /* Now find the directive name. */
1206 cppReader_putChar (pfile, '#');
1208 parse_name (pfile, cppReader_getC (pfile));
1210 llassert (pfile->token_buffer != NULL);
1211 ident = pfile->token_buffer + old_written + 1;
1213 ident_length = cppReader_getPWritten (pfile) - ident;
1215 if (ident_length == 0 && cppReader_peekC (pfile) == '\n')
1217 /* A line of just `#' becomes blank. */
1221 for (kt = directive_table; ; kt++)
1223 if (kt->length <= 0)
1225 return 0; /* goto not_a_directive; */
1228 if (kt->length == ident_length
1229 && (cstring_equalPrefix (kt->name, ident)))
1235 if (kt->command_reads_line)
1241 /* Nonzero means do not delete comments within the directive.
1242 #define needs this when -traditional. */
1243 bool comments = 1; /*cppReader_isTraditional (pfile) && kt->traditional_comments; */
1244 int save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
1245 CPPOPTIONS (pfile)->put_out_comments = comments;
1246 after_ident = cppReader_getWritten (pfile);
1247 copy_rest_of_line (pfile);
1248 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
1252 /* For #pragma and #define, we may want to pass through the directive.
1253 Other directives may create output, but we don't want the directive
1254 itself out, so we pop it now. For example #include may write a #line
1255 command (see comment in do_include), and conditionals may emit
1256 #failed ... #endfailed stuff. But note that popping the buffer
1257 means the parameters to kt->func may point after pfile->limit
1258 so these parameters are invalid as soon as something gets appended
1259 to the token_buffer. */
1261 line_end = cppReader_getPWritten (pfile);
1264 if (!kt->pass_thru && kt->type != T_DEFINE)
1266 cppReader_setWritten (pfile, old_written);
1269 llassert (pfile->token_buffer != NULL);
1271 /* was kt->pass_thru || */
1273 if (kt->type == T_DEFINE
1274 && cpp_shouldCheckMacro (pfile, pfile->token_buffer + old_written))
1276 char *p = pfile->token_buffer + old_written;
1279 ** Still need to record value for preprocessing, so
1280 ** #ifdef's, etc. using the value behave correctly.
1283 (void) do_defineAux (pfile, kt,
1284 pfile->token_buffer + after_ident,
1293 SKIP_WHITE_SPACE (p);
1295 llassert (*p == 'd');
1298 llassert (*p == 'e');
1301 llassert (*p == 'f');
1304 llassert (*p == 'i');
1307 llassert (*p == 'n');
1310 llassert (*p == 'e');
1313 ** This is way-bogus. We use the last char to record the number of
1314 ** spaces. Its too hard to get them back into the input stream.
1317 if (nspaces > 9) nspaces = 9;
1319 *p++ = '0' + nspaces;
1321 return 0; /* not_a_directive */
1323 else if (kt->pass_thru)
1325 /* Just leave the entire #define in the output stack. */
1326 return 0; /* not_a_directive */
1329 else if (kt->type == T_DEFINE
1330 && CPPOPTIONS (pfile)->dump_macros == DUMP_NAMES)
1332 char *p = pfile->token_buffer + old_written + 7; /* Skip "#define". */
1333 SKIP_WHITE_SPACE (p);
1335 while (is_idchar[(int) *p])
1341 cppReader_putChar (pfile, '\n');
1343 else if (kt->type == T_DEFINE)
1345 cppReader_setWritten (pfile, old_written);
1356 llassert (kt->func != NULL);
1357 (void) (*kt->func) (pfile, kt, pfile->token_buffer + after_ident, line_end);
1362 /* Pass a directive through to the output file.
1363 BUF points to the contents of the directive, as a contiguous string.
1364 LIMIT points to the first character past the end of the directive.
1365 KEYWORD is the keyword-table entry for the directive. */
1368 pass_thru_directive (char *buf, char *limit,
1370 struct directive *keyword)
1372 int keyword_length = keyword->length;
1374 cppReader_reserve (pfile,
1375 size_fromInt (2 + keyword_length + (limit - buf)));
1376 cppReader_putCharQ (pfile, '#');
1377 /*@-observertrans@*/
1378 cppReader_putStrN (pfile, cstring_toCharsSafe (keyword->name),
1379 size_fromInt (keyword_length));
1380 /*:=observertrans@*/
1382 if (limit != buf && buf[0] != ' ')
1384 /* Was a bug, since reserve only used 1 + ... */
1385 cppReader_putCharQ (pfile, ' ');
1388 cppReader_putStrN (pfile, buf, size_fromInt (limit - buf));
1391 /* Read a replacement list for a macro with parameters.
1392 Build the DEFINITION structure.
1393 Reads characters of text starting at BUF until END.
1394 ARGLIST specifies the formal parameters to look for
1395 in the text of the definition; NARGS is the number of args
1396 in that list, or -1 for a macro name that wants no argument list.
1397 MACRONAME is the macro name itself (so we can avoid recursive expansion)
1398 and NAMELEN is its length in characters.
1400 Note that comments, backslash-newlines, and leading white space
1401 have already been deleted from the argument. */
1404 collect_expansion (cppReader *pfile, char *buf, char *limit,
1405 int nargs, /*@null@*/ struct arglist *arglist)
1408 char *p, *lastp, *exp_p;
1409 struct reflist *endpat = NULL;
1410 /* Pointer to first nonspace after last ## seen. */
1412 /* Pointer to first nonspace after last single-# seen. */
1413 char *stringify = 0;
1415 char expected_delimiter = '\0';
1418 /* Scan thru the replacement list, ignoring comments and quoted
1419 strings, picking up on the macro calls. It does a linear search
1420 thru the arg list on every potential symbol. Profiling might say
1421 that something smarter should happen. */
1426 /* Find the beginning of the trailing whitespace. */
1429 while (p < limit && is_space[(int) limit[-1]])
1434 /* Allocate space for the text in the macro definition.
1435 Leading and trailing whitespace chars need 2 bytes each.
1436 Each other input char may or may not need 1 byte,
1437 so this is an upper bound. The extra 5 are for invented
1438 leading and trailing newline-marker and final null. */
1439 maxsize = (sizeof (*defn) + (limit - p) + 5);
1441 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1450 defn = (DEFINITION *) dmalloc (maxsize);
1451 defn->noExpand = FALSE;
1453 defn->pattern = NULL;
1454 defn->nargs = nargs;
1455 defn->predefined = NULL;
1457 exp_p = defn->expansion = (char *) defn + sizeof (*defn);
1460 defn->rest_args = NULL;
1461 defn->args.argnames = NULL;
1467 /* Add one initial space escape-marker to prevent accidental
1468 token-pasting (often removed by macroexpand). */
1472 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1473 cppReader_errorLit (pfile,
1474 cstring_makeLiteralTemp ("`##' at start of macro definition"));
1478 /* Process the main body of the definition. */
1480 int skipped_arg = 0;
1481 register char c = *p++;
1485 if (!cppReader_isTraditional (pfile)) {
1489 if (expected_delimiter != '\0')
1491 if (c == expected_delimiter)
1492 expected_delimiter = '\0';
1496 expected_delimiter = c;
1498 /*@switchbreak@*/ break;
1501 if (p < limit && (expected_delimiter != '\0'))
1503 /* In a string, backslash goes through
1504 and makes next char ordinary. */
1507 /*@switchbreak@*/ break;
1510 /* An '@' in a string or character constant stands for itself,
1511 and does not need to be escaped. */
1512 if (expected_delimiter == '\0')
1517 /*@switchbreak@*/ break;
1520 /* # is ordinary inside a string. */
1521 if (expected_delimiter != '\0')
1523 /*@switchbreak@*/ break;
1526 if (p < limit && *p == '#') {
1527 /* ##: concatenate preceding and following tokens. */
1528 /* Take out the first #, discard preceding whitespace. */
1532 while (exp_p > lastp && is_hor_space[(int) exp_p[-1]])
1538 /* Skip the second #. */
1540 /* Discard following whitespace. */
1541 SKIP_WHITE_SPACE (p);
1545 cppReader_errorLit (pfile,
1546 cstring_makeLiteralTemp ("`##' at end of macro definition"));
1548 } else if (nargs >= 0) {
1549 /* Single #: stringify following argument ref.
1550 Don't leave the # in the expansion. */
1552 SKIP_WHITE_SPACE (p);
1553 if (p == limit || ! is_idstart[(int) *p]
1554 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '"')))
1555 cppReader_errorLit (pfile,
1556 cstring_makeLiteralTemp ("`#' operator is not followed by a macro argument name"));
1563 /*@switchbreak@*/ break;
1566 /* In -traditional mode, recognize arguments inside strings and
1567 and character constants, and ignore special properties of #.
1568 Arguments inside strings are considered "stringified", but no
1569 extra quote marks are supplied. */
1573 if (expected_delimiter != '\0') {
1574 if (c == expected_delimiter)
1575 expected_delimiter = '\0';
1577 expected_delimiter = c;
1578 /*@switchbreak@*/ break;
1581 /* Backslash quotes delimiters and itself, but not macro args. */
1582 if (expected_delimiter != '\0' && p < limit
1583 && (*p == expected_delimiter || *p == '\\')) {
1587 /*@switchbreak@*/ break;
1590 if (expected_delimiter != '\0') /* No comments inside strings. */
1591 /*@switchbreak@*/ break;
1593 /* If we find a comment that wasn't removed by cppReader_handleDirective,
1594 this must be -traditional. So replace the comment with
1598 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
1603 /*@switchbreak@*/ break;
1607 /* Handle the start of a symbol. */
1608 if (is_idchar[(int) c] && nargs > 0) {
1609 char *id_beg = p - 1;
1613 while (p != limit && is_idchar[(int) *p])
1618 id_len = p - id_beg;
1620 if (is_idstart[(int) c]
1621 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
1622 register struct arglist *arg;
1624 for (arg = arglist; arg != NULL; arg = arg->next) {
1625 struct reflist *tpat;
1627 if (arg->name[0] == c
1628 && arg->length == id_len
1629 && strncmp (arg->name, id_beg, size_fromInt (id_len)) == 0) {
1632 if (expected_delimiter && CPPOPTIONS (pfile)->warn_stringify) {
1633 if (cppReader_isTraditional (pfile)) {
1634 cppReader_warning (pfile,
1635 message ("macro argument `%x' is stringified.",
1636 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1638 cppReader_warning (pfile,
1639 message ("macro arg `%x' would be stringified with -traditional.",
1640 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1643 /* If ANSI, don't actually substitute inside a string. */
1644 if (!cppReader_isTraditional (pfile) && expected_delimiter)
1645 /*@innerbreak@*/ break;
1646 /* make a pat node for this arg and append it to the end of
1648 tpat = (struct reflist *) dmalloc (sizeof (*tpat));
1650 tpat->raw_before = (concat == id_beg);
1651 tpat->raw_after = 0;
1652 tpat->rest_args = arg->rest_args;
1653 tpat->stringify = (cppReader_isTraditional (pfile)
1654 ? expected_delimiter != '\0'
1655 : stringify == id_beg);
1659 defn->pattern = tpat;
1663 endpat->next = tpat;
1665 } /*:=branchstate@*/
1669 tpat->argno = arg->argno;
1670 tpat->nchars = exp_p - lastp;
1674 SKIP_WHITE_SPACE (p1);
1676 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
1678 tpat->raw_after = 1;
1681 lastp = exp_p; /* place to start copying from next time */
1684 /*@innerbreak@*/ break;
1689 /* If this was not a macro arg, copy it into the expansion. */
1690 if (skipped_arg == 0) {
1691 register char *lim1 = p;
1699 if (stringify == id_beg)
1700 cppReader_errorLit (pfile,
1701 cstring_makeLiteralTemp ("`#' operator should be followed by a macro argument name"));
1706 if (!cppReader_isTraditional (pfile) && expected_delimiter == '\0')
1708 /* If ANSI, put in a "@ " marker to prevent token pasting.
1709 But not if "inside a string" (which in ANSI mode
1710 happens only for -D option). */
1717 defn->length = size_fromInt (exp_p - defn->expansion);
1719 /* Crash now if we overrun the allocated size. */
1720 if (defn->length + 1 > maxsize)
1722 llfatalbug (cstring_makeLiteral ("Maximum definition size exceeded."));
1729 * special extension string that can be added to the last macro argument to
1730 * allow it to absorb the "rest" of the arguments when expanded. Ex:
1731 * #define wow(a, b...) process (b, a, b)
1732 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
1733 * { wow (one, two); } -> { process (two, one, two); }
1734 * if this "rest_arg" is used with the concat token '##' and if it is not
1735 * supplied then the token attached to with ## will not be outputted. Ex:
1736 * #define wow (a, b...) process (b ## , a, ## b)
1737 * { wow (1, 2); } -> { process (2, 1, 2); }
1738 * { wow (one); } -> { process (one); {
1741 /*@-readonlytrans@*/
1742 static char rest_extension[] = "...";
1743 /*:=readonlytrans@*/
1746 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
1748 /* Create a DEFINITION node from a #define directive. Arguments are
1749 as for do_define. */
1751 static /*@null@*/ MACRODEF
1752 create_definition (char *buf, char *limit,
1753 cppReader *pfile, bool predefinition,
1756 char *bp; /* temp ptr into input buffer */
1757 char *symname; /* remember where symbol name starts */
1758 int sym_length; /* and how long it is */
1759 int rest_args = 0; /* really int! */
1762 cstring file = (CPPBUFFER (pfile) != NULL)
1763 ? CPPBUFFER (pfile)->nominal_fname : cstring_makeLiteralTemp ("");
1765 int arglengths = 0; /* Accumulate lengths of arg names
1766 plus number of args. */
1769 cppBuffer_lineAndColumn (CPPBUFFER (pfile), &line, &col);
1773 while (is_hor_space[(int) *bp])
1778 symname = bp; /* remember where it starts */
1780 sym_length = cppReader_checkMacroName (pfile, bp, cstring_makeLiteralTemp ("macro"));
1784 /* Lossage will occur if identifiers or control keywords are broken
1785 across lines using backslash. This is not the right place to take
1789 struct arglist *arg_ptrs = NULL;
1792 bp++; /* skip '(' */
1793 SKIP_WHITE_SPACE (bp);
1795 /* Loop over macro argument names. */
1798 struct arglist *temp = (struct arglist *) dmalloc (sizeof (*temp));
1800 temp->next = arg_ptrs;
1801 temp->argno = argno++;
1802 temp->rest_args = 0;
1808 cppReader_pedwarn (pfile,
1809 message ("another parameter follows `%s'",
1810 cstring_fromChars (rest_extension)));
1813 if (!is_idstart[(int) *bp])
1815 cppReader_pedwarnLit (pfile,
1816 cstring_makeLiteralTemp ("invalid character in macro parameter name"));
1819 /* Find the end of the arg name. */
1820 while (is_idchar[(int) *bp])
1823 /* do we have a "special" rest-args extension here? */
1824 if (limit - bp > size_toInt (REST_EXTENSION_LENGTH)
1825 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
1828 temp->rest_args = 1;
1829 /*@innerbreak@*/ break;
1833 temp->length = bp - temp->name;
1837 bp += REST_EXTENSION_LENGTH;
1840 arglengths += temp->length + 2;
1841 SKIP_WHITE_SPACE (bp);
1843 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
1844 cppReader_errorLit (pfile,
1845 cstring_makeLiteralTemp ("Parameter list for #define is not parseable"));
1851 SKIP_WHITE_SPACE (bp);
1854 cppReader_errorLit (pfile,
1855 cstring_makeLiteralTemp ("unterminated parameter list in `#define'"));
1859 struct arglist *otemp;
1861 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
1863 if (temp->length == otemp->length &&
1864 strncmp (temp->name, otemp->name, size_fromInt (temp->length)) == 0) {
1865 cstring name = cstring_copyLength (temp->name, temp->length);
1866 cppReader_error (pfile,
1867 message ("duplicate argument name `%x' in `#define'", name));
1874 ++bp; /* skip paren */
1875 SKIP_WHITE_SPACE (bp);
1876 /* now everything from bp before limit is the definition. */
1877 defn = collect_expansion (pfile, bp, limit, argno, arg_ptrs);
1878 defn->rest_args = rest_args;
1880 /* Now set defn->args.argnames to the result of concatenating
1881 the argument names in reverse order
1882 with comma-space between them. */
1883 defn->args.argnames = (char *) dmalloc (size_fromInt (arglengths + 1));
1886 struct arglist *temp;
1888 for (temp = arg_ptrs; temp != NULL; temp = temp->next) {
1889 memcpy (&defn->args.argnames[i], temp->name, size_fromInt (temp->length));
1891 if (temp->next != 0) {
1892 defn->args.argnames[i++] = ',';
1893 defn->args.argnames[i++] = ' ';
1897 defn->args.argnames[i] = '\0';
1902 /* Simple expansion or empty definition. */
1906 if (is_hor_space[(int) *bp]) {
1908 SKIP_WHITE_SPACE (bp);
1911 case '!': case '"': case '#': case '%': case '&': case '\'':
1912 case ')': case '*': case '+': case ',': case '-': case '.':
1913 case '/': case ':': case ';': case '<': case '=': case '>':
1914 case '?': case '[': case '\\': case ']': case '^': case '{':
1915 case '|': case '}': case '~':
1916 cppReader_warning (pfile,
1917 message ("Missing white space after #define %x",
1918 cstring_prefix (cstring_fromChars (symname),
1923 cppReader_pedwarn (pfile,
1924 message ("Missing white space after #define %x",
1925 cstring_prefix (cstring_fromChars (symname),
1931 /* now everything from bp before limit is the definition. */
1932 defn = collect_expansion (pfile, bp, limit, -1, NULL);
1933 defn->args.argnames = mstring_createEmpty ();
1936 defn->noExpand = noExpand;
1937 DPRINTF (("No expand: %d", noExpand));
1941 /* not: llassert (cstring_isUndefined (defn->file)); */
1944 /* OP is null if this is a predefinition */
1945 defn->predefined = predefinition;
1947 mdef.symnam = symname;
1948 mdef.symlen = sym_length;
1958 /* Check a purported macro name SYMNAME, and yield its length.
1959 USAGE is the kind of name this is intended for. */
1961 int cppReader_checkMacroName (cppReader *pfile,
1968 for (p = symname; is_idchar[(int) *p]; p++)
1973 sym_length = size_fromInt (p - symname);
1976 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
1977 cppReader_error (pfile, message ("invalid %s name", usage));
1978 else if (!is_idstart[(int) *symname])
1980 char *msg = (char *) dmalloc (sym_length + 1);
1981 memcpy (msg, symname, sym_length);
1982 msg[sym_length] = '\0';
1983 cppReader_error (pfile, message ("invalid %s name `%s'", usage,
1984 cstring_fromChars (msg)));
1989 if ((strncmp (symname, "defined", 7) == 0) && sym_length == 7)
1991 cppReader_error (pfile, message ("invalid %s name `defined'", usage));
1995 return size_toInt (sym_length);
1998 /* Return zero if two DEFINITIONs are isomorphic. */
2001 compare_defs (DEFINITION *d1, DEFINITION *d2)
2003 register struct reflist *a1, *a2;
2004 register char *p1 = d1->expansion;
2005 register char *p2 = d2->expansion;
2008 if (d1->nargs != d2->nargs)
2013 llassert (d1->args.argnames != NULL);
2014 llassert (d2->args.argnames != NULL);
2016 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames) != 0)
2021 for (a1 = d1->pattern, a2 = d2->pattern;
2022 (a1 != NULL) && (a2 != NULL);
2023 a1 = a1->next, a2 = a2->next) {
2024 if (!((a1->nchars == a2->nchars
2025 && (strncmp (p1, p2, size_fromInt (a1->nchars)) == 0))
2026 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
2027 || a1->argno != a2->argno
2028 || a1->stringify != a2->stringify
2029 || a1->raw_before != a2->raw_before
2030 || a1->raw_after != a2->raw_after)
2039 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
2040 p2, d2->length - (p2 - d2->expansion), 1))
2046 /* Return TRUE if two parts of two macro definitions are effectively different.
2047 One of the parts starts at BEG1 and has LEN1 chars;
2048 the other has LEN2 chars at BEG2.
2049 Any sequence of whitespace matches any other sequence of whitespace.
2050 FIRST means these parts are the first of a macro definition;
2051 so ignore leading whitespace entirely.
2052 LAST means these parts are the last of a macro definition;
2053 so ignore trailing whitespace entirely. */
2056 comp_def_part (bool first, char *beg1, int len1, char *beg2, int len2, bool last)
2058 char *end1 = beg1 + len1;
2059 char *end2 = beg2 + len2;
2062 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2063 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2066 while (beg1 != end1 && is_space[(int) end1[-1]]) { end1--; }
2067 while (beg2 != end2 && is_space[(int) end2[-1]]) { end2--; }
2069 while (beg1 != end1 && beg2 != end2) {
2070 if (is_space[(int) *beg1] && is_space[(int) *beg2]) {
2071 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2072 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2073 } else if (*beg1 == *beg2) {
2077 return (beg1 != end1) || (beg2 != end2);
2080 /* Process a #define command.
2081 BUF points to the contents of the #define command, as a contiguous string.
2082 LIMIT points to the first character past the end of the definition.
2083 KEYWORD is the keyword-table entry for #define,
2084 or NULL for a "predefined" macro. */
2087 do_defineAux (cppReader *pfile, struct directive *keyword,
2088 char *buf, char *limit, bool noExpand)
2094 DPRINTF (("Define aux: %d", noExpand));
2096 mdef = create_definition (buf, limit, pfile, keyword == NULL, noExpand);
2101 hashcode = hashf (mdef.symnam, mdef.symlen, CPP_HASHSIZE);
2103 DPRINTF (("Macro: %s / %s",
2104 cstring_copyLength (mdef.symnam, mdef.symlen),
2105 bool_unparse (noExpand)));
2107 if ((hp = cppReader_lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL)
2111 /* Redefining a precompiled key is ok. */
2112 if (hp->type == T_PCSTRING)
2114 /* Redefining a macro is ok if the definitions are the same. */
2115 else if (hp->type == T_MACRO)
2116 ok = !compare_defs (mdef.defn, hp->value.defn);
2117 /* Redefining a constant is ok with -D. */
2118 else if (hp->type == T_CONST)
2119 ok = !CPPOPTIONS (pfile)->done_initializing;
2124 /* Print the warning if it's not ok. */
2128 ** If we are passing through #define and #undef directives, do
2129 ** that for this re-definition now.
2132 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2134 /* llassert (keyword != NULL); */
2135 pass_thru_directive (buf, limit, pfile, keyword);
2138 cpp_setLocation (pfile);
2140 if (hp->type == T_MACRO)
2142 if (hp->value.defn->noExpand)
2144 ; /* error will be reported checking macros */
2150 message ("Macro %q already defined",
2151 cstring_copyLength (mdef.symnam, mdef.symlen)),
2152 message ("%q: Previous definition of %q",
2153 fileloc_unparseRaw (hp->value.defn->file,
2154 (int) hp->value.defn->line),
2155 cstring_copyLength (mdef.symnam, mdef.symlen)));
2160 genppllerror (FLG_MACROREDEF,
2161 message ("Macro %q already defined",
2162 cstring_copyLength (mdef.symnam,
2168 /* Replace the old definition. */
2170 hp->value.defn = mdef.defn;
2175 ** If we are passing through #define and #undef directives, do
2176 ** that for this new definition now.
2181 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2183 pass_thru_directive (buf, limit, pfile, keyword);
2186 DPRINTF (("Define macro: %s / %d",
2187 mdef.symnam, mdef.defn->noExpand));
2189 hn = cppReader_installMacro (mdef.symnam, mdef.symlen, mdef.defn, hashcode);
2191 } /*:=branchstate@*/
2201 do_define (cppReader *pfile, struct directive *keyword,
2202 char *buf, char *limit)
2204 DPRINTF (("Regular do define"));
2205 return do_defineAux (pfile, keyword, buf, limit, FALSE);
2208 /* This structure represents one parsed argument in a macro call.
2209 `raw' points to the argument text as written (`raw_length' is its length).
2210 `expanded' points to the argument's macro-expansion
2211 (its length is `expand_length').
2212 `stringified_length' is the length the argument would have
2214 `use_count' is the number of times this macro arg is substituted
2215 into the macro. If the actual use count exceeds 10,
2216 the value stored is 10. */
2218 /* raw and expanded are relative to ARG_BASE */
2220 #define ARG_BASE ((pfile)->token_buffer)
2223 /* Strings relative to pfile->token_buffer */
2229 int stringified_length;
2234 /* Allocate a new cppBuffer for PFILE, and push it on the input buffer stack.
2235 If BUFFER != NULL, then use the LENGTH characters in BUFFER
2236 as the new input buffer.
2237 Return the new buffer, or NULL on failure. */
2239 /*@null@*/ /*@exposed@*/ cppBuffer *
2240 cppReader_pushBuffer (cppReader *pfile, char *buffer, size_t length)
2242 cppBuffer *buf = cppReader_getBuffer (pfile);
2244 if (buf == pfile->buffer_stack)
2246 cppReader_fatalError
2248 message ("%s: macro or `#include' recursion too deep",
2249 (buf->fname != NULL)
2251 : cstring_makeLiteral ("<no name>")));
2252 sfreeEventually (buffer);
2256 llassert (buf != NULL);
2259 memset ((char *) buf, 0, sizeof (*buf));
2260 CPPBUFFER (pfile) = buf;
2262 buf->if_stack = pfile->if_stack;
2263 buf->cleanup = cppReader_nullCleanup;
2264 buf->underflow = cppReader_nullUnderflow;
2266 buf->cur = buf->buf;
2270 buf->alimit = buf->rlimit = buffer + length;
2274 buf->alimit = buf->rlimit = NULL;
2281 cppReader_popBuffer (cppReader *pfile)
2283 cppBuffer *buf = CPPBUFFER (pfile);
2285 llassert (buf != NULL);
2287 (void) (*buf->cleanup) (buf, pfile);
2288 return ++CPPBUFFER (pfile);
2291 /* Scan until CPPBUFFER (PFILE) is exhausted into PFILE->token_buffer.
2292 Pop the buffer when done. */
2295 cppReader_scanBuffer (cppReader *pfile)
2297 cppBuffer *buffer = CPPBUFFER (pfile);
2300 enum cpp_token token;
2302 token = cppGetToken (pfile);
2304 if (token == CPP_EOF) /* Should not happen ... */
2309 if (token == CPP_POP && CPPBUFFER (pfile) == buffer)
2311 (void) cppReader_popBuffer (pfile);
2318 * Rescan a string (which may have escape marks) into pfile's buffer.
2319 * Place the result in pfile->token_buffer.
2321 * The input is copied before it is scanned, so it is safe to pass
2322 * it something from the token_buffer that will get overwritten
2323 * (because it follows cppReader_getWritten). This is used by do_include.
2327 cpp_expand_to_buffer (cppReader *pfile, char *buf, size_t length)
2329 register cppBuffer *ip;
2330 char *limit = buf + length;
2331 char *buf1, *p1, *p2;
2336 /* Set up the input on the input stack. */
2338 buf1 = (char *) dmalloc (length + 1);
2348 buf1[length] = '\0';
2350 ip = cppReader_pushBuffer (pfile, buf1, length);
2355 ip->has_escapes = TRUE;
2357 /* Scan the input, create the output. */
2358 cppReader_scanBuffer (pfile);
2360 cppReader_nullTerminate (pfile);
2364 adjust_position (char *buf, char *limit, int *linep, int *colp)
2370 (*linep)++, (*colp) = 1;
2376 /* Move line_base forward, updating lineno and colno. */
2379 update_position (cppBuffer *pbuf)
2382 char *new_pos = pbuf->cur;
2383 register struct parse_marker *mark;
2385 llassert (pbuf->buf != NULL);
2386 old_pos = pbuf->buf + pbuf->line_base;
2388 for (mark = pbuf->marks; mark != NULL; mark = mark->next)
2390 if (pbuf->buf + mark->position < new_pos)
2391 new_pos = pbuf->buf + mark->position;
2393 pbuf->line_base += new_pos - old_pos;
2395 llassert (old_pos != NULL);
2396 llassert (new_pos != NULL);
2398 adjust_position (old_pos, new_pos, &pbuf->lineno, &pbuf->colno);
2402 cppBuffer_lineAndColumn (/*@null@*/ cppBuffer *pbuf, /*@out@*/ int *linep,
2403 /*@null@*/ /*@out@*/ int *colp)
2411 } /*:=branchstate@*/
2415 *linep = pbuf->lineno;
2416 *colp = pbuf->colno;
2418 llassert (pbuf->buf != NULL);
2419 llassert (pbuf->cur != NULL);
2421 adjust_position (pbuf->buf + pbuf->line_base, pbuf->cur, linep, colp);
2430 /* Return the cppBuffer that corresponds to a file (not a macro). */
2432 /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_fileBuffer (cppReader *pfile)
2434 cppBuffer *ip = cppReader_getBuffer (pfile);
2437 ip != NULL && ip != cppReader_nullBuffer (pfile);
2438 ip = cppBuffer_prevBuffer (ip))
2440 if (ip->fname != NULL)
2450 count_newlines (char *buf, char *limit)
2452 register long count = 0;
2464 * write out a #line command, for instance, after an #include file.
2465 * If CONDITIONAL is nonzero, we can omit the #line if it would
2466 * appear to be a no-op, and we can output a few newlines instead
2467 * if we want to increase the line number by a small amount.
2468 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
2472 output_line_command (cppReader *pfile, bool conditional,
2473 enum file_change_code file_change)
2476 cppBuffer *ip = CPPBUFFER (pfile);
2479 llassert (ip != NULL);
2481 if (ip->fname == NULL)
2484 update_position (ip);
2486 if (CPPOPTIONS (pfile)->no_line_commands
2487 || CPPOPTIONS (pfile)->no_output)
2490 buf = CPPBUFFER (pfile);
2492 llassert (buf != NULL);
2497 llassert (ip->cur != NULL);
2499 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
2501 if (CPPOPTIONS (pfile)->no_line_commands)
2505 if (line == pfile->lineno)
2508 /* If the inherited line number is a little too small,
2509 output some newlines instead of a #line command. */
2511 if (line > pfile->lineno && line < pfile->lineno + 8)
2513 cppReader_reserve (pfile, 20);
2514 while (line > pfile->lineno)
2516 cppReader_putCharQ (pfile, '\n');
2524 cppReader_reserve (pfile,
2525 size_fromInt (4 * cstring_length (ip->nominal_fname) + 50));
2528 #ifdef OUTPUT_LINE_COMMANDS
2529 static char sharp_line[] = "#line ";
2531 static char sharp_line[] = "# ";
2533 cppReader_putStrN (pfile, sharp_line, sizeof(sharp_line)-1);
2536 sprintf (cppReader_getPWritten (pfile), "%d ", line);
2537 cppReader_adjustWritten (pfile, strlen (cppReader_getPWritten (pfile)));
2539 quote_string (pfile, cstring_toCharsSafe (ip->nominal_fname));
2541 if (file_change != same_file) {
2542 cppReader_putCharQ (pfile, ' ');
2543 cppReader_putCharQ (pfile, file_change == enter_file ? '1' : '2');
2545 /* Tell cc1 if following text comes from a system header file. */
2546 if (ip->system_header_p != '\0') {
2547 cppReader_putCharQ (pfile, ' ');
2548 cppReader_putCharQ (pfile, '3');
2550 #ifndef NO_IMPLICIT_EXTERN_C
2551 /* Tell cc1plus if following text should be treated as C. */
2552 if (ip->system_header_p == (char) 2 && CPPOPTIONS (pfile)->cplusplus) {
2553 cppReader_putCharQ (pfile, ' ');
2554 cppReader_putCharQ (pfile, '4');
2557 cppReader_putCharQ (pfile, '\n');
2558 pfile->lineno = line;
2563 * Parse a macro argument and append the info on PFILE's token_buffer.
2564 * REST_ARGS means to absorb the rest of the args.
2565 * Return nonzero to indicate a syntax error.
2568 static enum cpp_token
2569 macarg (cppReader *pfile, int rest_args)
2572 enum cpp_token token;
2573 char save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
2574 bool oldexpand = pfile->no_macro_expand;
2575 CPPOPTIONS (pfile)->put_out_comments = 1;
2577 /* Try to parse as much of the argument as exists at this
2578 input stack level. */
2580 pfile->no_macro_expand = TRUE;
2584 token = cppGetToken (pfile);
2591 /* If we've hit end of file, it's an error (reported by caller).
2592 Ditto if it's the end of cpp_expand_to_buffer text.
2593 If we've hit end of macro, just continue. */
2594 if (!cppBuffer_isMacro (CPPBUFFER (pfile)))
2596 /*@switchbreak@*/ break;
2599 /*@switchbreak@*/ break;
2603 /*@switchbreak@*/ break;
2605 /* if we've returned to lowest level and
2606 we aren't absorbing all args */
2607 if (paren == 0 && rest_args == 0)
2609 /*@switchbreak@*/ break;
2611 /* Remove ',' or ')' from argument buffer. */
2612 cppReader_adjustWritten (pfile, -1);
2620 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
2621 pfile->no_macro_expand = oldexpand;
2627 /* Turn newlines to spaces in the string of length LENGTH at START,
2628 except inside of string constants.
2629 The string is copied into itself with its beginning staying fixed. */
2632 change_newlines (char *start, int length)
2636 register char *limit;
2640 limit = start + length;
2643 while (ibp < limit) {
2644 *obp++ = c = *ibp++;
2649 /* Notice and skip strings, so that we don't delete newlines in them. */
2652 while (ibp < limit) {
2653 *obp++ = c = *ibp++;
2655 /*@innerbreak@*/ break;
2656 if (c == '\n' && quotec == '\'')
2657 /*@innerbreak@*/ break;
2660 /*@switchbreak@*/ break;
2667 static /*@observer@*/ struct tm *
2668 timestamp (/*@returned@*/ cppReader *pfile)
2670 if (pfile->timebuf == NULL)
2672 time_t t = time ((time_t *) 0);
2673 pfile->timebuf = localtime (&t);
2676 llassert (pfile->timebuf != NULL);
2678 return pfile->timebuf;
2681 static ob_mstring monthnames[] = {
2682 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2683 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
2687 * expand things like __FILE__. Place the expansion into the output
2688 * buffer *without* rescanning.
2692 special_symbol (HASHNODE *hp, cppReader *pfile)
2694 cstring buf = cstring_undefined;
2700 int paren = 0; /* For special `defined' keyword */
2702 for (ip = cppReader_getBuffer (pfile); ip != NULL; ip = cppBuffer_prevBuffer (ip))
2704 if (ip == cppReader_nullBuffer (pfile))
2706 cppReader_errorLit (pfile,
2707 cstring_makeLiteralTemp ("cccp error: not in any file?!"));
2708 return; /* the show must go on */
2711 if (ip != NULL && ip->fname != NULL)
2723 if (hp->type == T_BASE_FILE)
2725 while (cppBuffer_prevBuffer (ip) != cppReader_nullBuffer (pfile))
2727 ip = cppBuffer_prevBuffer (ip);
2731 llassert (ip != NULL);
2732 string = cstring_toCharsSafe (ip->nominal_fname);
2739 cppReader_reserve (pfile, 3 + 4 * strlen (string));
2740 quote_string (pfile, string);
2744 case T_INCLUDE_LEVEL:
2746 ip = cppReader_getBuffer (pfile);
2748 for (; ip != cppReader_nullBuffer (pfile) && ip != NULL;
2749 ip = cppBuffer_prevBuffer (ip))
2751 if (ip != NULL && ip->fname != NULL)
2757 buf = message ("%d", true_indepth - 1);
2761 buf = message ("\"%s\"", cstring_makeLiteralTemp (CPP_VERSION));
2764 #ifndef NO_BUILTIN_SIZE_TYPE
2766 buf = cstring_makeLiteral (SIZE_TYPE);
2770 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2771 case T_PTRDIFF_TYPE:
2772 buf = cstring_makeLiteral (PTRDIFF_TYPE);
2777 buf = cstring_makeLiteral (cppReader_wcharType (pfile));
2780 case T_USER_LABEL_PREFIX_TYPE:
2781 buf = cstring_makeLiteral (USER_LABEL_PREFIX);
2784 case T_REGISTER_PREFIX_TYPE:
2785 buf = cstring_makeLiteral (REGISTER_PREFIX);
2789 buf = message ("%d", hp->value.ival);
2796 int line = ip->lineno;
2797 int col = ip->colno;
2799 llassert (ip->cur != NULL);
2800 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
2802 buf = message ("%d", (int) line);
2814 char *sbuf = (char *) dmalloc (20);
2815 timebuf = timestamp (pfile);
2816 if (hp->type == T_DATE)
2818 sprintf (sbuf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
2819 timebuf->tm_mday, timebuf->tm_year + 1900);
2823 sprintf (sbuf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
2827 buf = cstring_fromCharsNew (sbuf);
2832 case T_SPEC_DEFINED:
2833 buf = cstring_makeLiteral (" 0 "); /* Assume symbol is not defined */
2834 ip = cppReader_getBuffer (pfile);
2836 llassert (ip->cur != NULL);
2837 SKIP_WHITE_SPACE (ip->cur);
2839 if (*ip->cur == '(')
2842 ip->cur++; /* Skip over the paren */
2843 SKIP_WHITE_SPACE (ip->cur);
2846 if (!is_idstart[(int) *ip->cur])
2848 if (ip->cur[0] == 'L' && (ip->cur[1] == '\'' || ip->cur[1] == '"'))
2851 if ((hp = cppReader_lookup (ip->cur, -1, -1)) != 0)
2854 buf = cstring_makeLiteral (" 1 ");
2857 while (is_idchar[(int) *ip->cur])
2862 SKIP_WHITE_SPACE (ip->cur);
2866 if (*ip->cur != ')')
2874 cppReader_errorLit (pfile,
2875 cstring_makeLiteralTemp ("`defined' without an identifier"));
2879 cpp_setLocation (pfile);
2880 llfatalerror (message ("Pre-processing error: invalid special hash type"));
2883 len = size_fromInt (cstring_length (buf));
2885 cppReader_reserve (pfile, len + 1);
2886 cppReader_putStrN (pfile, cstring_toCharsSafe (buf), len);
2887 cppReader_nullTerminateQ (pfile);
2893 /* Write out a #define command for the special named MACRO_NAME
2894 to PFILE's token_buffer. */
2897 dump_special_to_buffer (cppReader *pfile, char *macro_name)
2899 static char define_directive[] = "#define ";
2900 size_t macro_name_length = strlen (macro_name);
2901 output_line_command (pfile, 0, same_file);
2902 cppReader_reserve (pfile, sizeof(define_directive) + macro_name_length);
2903 cppReader_putStrN (pfile, define_directive, sizeof(define_directive)-1);
2904 cppReader_putStrN (pfile, macro_name, macro_name_length);
2905 cppReader_putCharQ (pfile, ' ');
2906 cpp_expand_to_buffer (pfile, macro_name, macro_name_length);
2907 cppReader_putChar (pfile, '\n');
2910 /* Initialize the built-in macros. */
2913 cppReader_installBuiltin (/*@observer@*/ char *name, ctype ctyp,
2914 int len, enum node_type type,
2915 int ivalue, /*@null@*/ /*@only@*/ char *value,
2918 cstring sname = cstring_fromCharsNew (name);
2920 llassert (usymtab_inGlobalScope ());
2923 ** Be careful here: this is done before the ctype table has
2924 ** been initialized.
2927 if (!usymtab_exists (sname))
2929 uentry ue = uentry_makeConstant (sname, ctyp, fileloc_createBuiltin ());
2931 if (ctype_equal (ctyp, ctype_string))
2933 qualList ql = qualList_new ();
2934 ql = qualList_add (ql, QU_OBSERVER);
2935 uentry_reflectQualifiers (ue, ql);
2939 usymtab_addGlobalEntry (ue);
2946 (void) cppReader_install (name, len, type, ivalue, value, hash);
2947 cstring_free (sname);
2951 cppReader_installBuiltinType (/*@observer@*/ char *name, ctype ctyp,
2952 int len, enum node_type type,
2954 /*@only@*/ /*@null@*/ char *value, int hash)
2956 cstring sname = cstring_fromCharsNew (name);
2958 llassert (usymtab_inGlobalScope ());
2960 if (!usymtab_exists (sname))
2962 uentry ue = uentry_makeDatatype (sname, ctyp,
2964 fileloc_createBuiltin ());
2965 usymtab_addGlobalEntry (ue);
2969 cstring_free (sname);
2972 (void) cppReader_install (name, len, type, ivalue, value, hash);
2976 initialize_builtins (cppReader *pfile)
2978 cppReader_installBuiltin ("__LINE__", ctype_int, -1, T_SPECLINE, 0, NULL, -1);
2979 cppReader_installBuiltin ("__DATE__", ctype_string, -1, T_DATE, 0, NULL, -1);
2980 cppReader_installBuiltin ("__FILE__", ctype_string, -1, T_FILE, 0, NULL, -1);
2981 cppReader_installBuiltin ("__BASE_FILE__", ctype_string, -1, T_BASE_FILE, 0, NULL, -1);
2982 cppReader_installBuiltin ("__INCLUDE_LEVEL__", ctype_int, -1, T_INCLUDE_LEVEL, 0, NULL, -1);
2983 cppReader_installBuiltin ("__VERSION__", ctype_string, -1, T_VERSION, 0, NULL, -1);
2984 #ifndef NO_BUILTIN_SIZE_TYPE
2985 cppReader_installBuiltinType ("__SIZE_TYPE__", ctype_anyintegral, -1, T_SIZE_TYPE, 0, NULL, -1);
2987 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2988 cppReader_installBuiltinType ("__PTRDIFF_TYPE__ ", ctype_anyintegral, -1, T_PTRDIFF_TYPE, 0, NULL, -1);
2990 cppReader_installBuiltinType ("__WCHAR_TYPE__", ctype_anyintegral, -1, T_WCHAR_TYPE, 0, NULL, -1);
2991 cppReader_installBuiltin ("__USER_LABEL_PREFIX__", ctype_string, -1, T_USER_LABEL_PREFIX_TYPE, 0, NULL, -1);
2992 cppReader_installBuiltin ("__REGISTER_PREFIX__", ctype_string, -1, T_REGISTER_PREFIX_TYPE, 0, NULL, -1);
2993 cppReader_installBuiltin ("__TIME__", ctype_string, -1, T_TIME, 0, NULL, -1);
2996 ** No, don't define __STDC__
2999 if (!cppReader_isTraditional (pfile))
3001 cppReader_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3008 cppReader_installBuiltin ("_WIN32", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3012 ** This is supplied using a -D by the compiler driver
3013 ** so that it is present only when truly compiling with GNU C.
3016 /* cppReader_install ("__GNUC__", -1, T_CONST, 2, 0, -1); */
3018 cppReader_installBuiltin ("__LCLINT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3020 if (CPPOPTIONS (pfile)->debug_output)
3022 dump_special_to_buffer (pfile, "__BASE_FILE__");
3023 dump_special_to_buffer (pfile, "__VERSION__");
3024 #ifndef NO_BUILTIN_SIZE_TYPE
3025 dump_special_to_buffer (pfile, "__SIZE_TYPE__");
3027 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3028 dump_special_to_buffer (pfile, "__PTRDIFF_TYPE__");
3030 dump_special_to_buffer (pfile, "__WCHAR_TYPE__");
3031 dump_special_to_buffer (pfile, "__DATE__");
3032 dump_special_to_buffer (pfile, "__TIME__");
3033 if (!cppReader_isTraditional (pfile))
3034 dump_special_to_buffer (pfile, "__STDC__");
3039 /* Return 1 iff a token ending in C1 followed directly by a token C2
3040 could cause mis-tokenization. */
3043 unsafe_chars (char c1, char c2)
3048 if (c2 == c1 || c2 == '=')
3052 case '0': case '1': case '2': case '3': case '4':
3053 case '5': case '6': case '7': case '8': case '9':
3054 case 'e': case 'E': case 'p': case 'P':
3055 if (c2 == '-' || c2 == '+')
3056 return 1; /* could extend a pre-processing number */
3059 if (c2 == '\'' || c2 == '\"')
3060 return 1; /* Could turn into L"xxx" or L'xxx'. */
3064 case 'a': case 'b': case 'c': case 'd': case 'f':
3065 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3066 case 'm': case 'n': case 'o': case 'q': case 'r':
3067 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3069 case 'A': case 'B': case 'C': case 'D': case 'F':
3070 case 'G': case 'H': case 'I': case 'J': case 'K':
3071 case 'M': case 'N': case 'O': case 'Q': case 'R':
3072 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3074 /* We're in the middle of either a name or a pre-processing number. */
3075 return (is_idchar[(int) c2] || c2 == '.');
3076 case '<': case '>': case '!': case '%': case '#': case ':':
3077 case '^': case '&': case '|': case '*': case '/': case '=':
3078 return (c2 == c1 || c2 == '=');
3083 /* Expand a macro call.
3084 HP points to the symbol that is the macro being called.
3085 Put the result of expansion onto the input stack
3086 so that subsequent input by our caller will use it.
3088 If macro wants arguments, caller has already verified that
3089 an argument list follows; arguments come from the input stack. */
3092 macroexpand (cppReader *pfile, /*@dependent@*/ HASHNODE *hp)
3095 DEFINITION *defn = hp->value.defn;
3101 size_t old_written = cppReader_getWritten (pfile);
3105 struct argdata *args = NULL;
3107 pfile->output_escapes++;
3109 cppBuffer_lineAndColumn (cppReader_fileBuffer (pfile), &start_line, &start_column);
3111 nargs = defn->nargs;
3115 enum cpp_token token = CPP_EOF;
3117 args = (struct argdata *) dmalloc ((nargs + 1) * sizeof (*args));
3119 for (i = 0; i < nargs; i++)
3121 args[i].expanded = 0;
3123 args[i].raw_length = 0;
3124 args[i].expand_length = args[i].stringified_length = -1;
3125 args[i].use_count = 0;
3129 ** Parse all the macro args that are supplied. I counts them.
3130 ** The first NARGS args are stored in ARGS.
3131 ** The rest are discarded. If rest_args is set then we assume
3132 ** macarg absorbed the rest of the args.
3138 cppReader_forward (pfile, 1); /* Discard the open-parenthesis before the first arg. */
3146 if (i < nargs || (nargs == 0 && i == 0))
3148 /* if we are working on last arg which absorbs rest of args... */
3149 if (i == nargs - 1 && defn->rest_args)
3154 args[i].raw = size_toLong (cppReader_getWritten (pfile));
3155 token = macarg (pfile, rest_args);
3156 args[i].raw_length = cppReader_getWritten (pfile) - args[i].raw;
3157 args[i].newlines = FALSE; /* FIXME */
3161 token = macarg (pfile, 0);
3164 if (token == CPP_EOF || token == CPP_POP)
3166 cppReader_errorWithLine (pfile, start_line, start_column,
3167 cstring_fromCharsNew ("unterminated macro call"));
3172 } while (token == CPP_COMMA);
3174 /* If we got one arg but it was just whitespace, call that 0 args. */
3182 bp = ARG_BASE + args[0].raw;
3183 lim = bp + args[0].raw_length;
3185 /* cpp.texi says for foo ( ) we provide one argument.
3186 However, if foo wants just 0 arguments, treat this as 0. */
3190 while (bp != lim && is_space[(int) *bp])
3200 /* Don't output an error message if we have already output one for
3201 a parse error above. */
3204 if (nargs == 0 && i > 0)
3206 cppReader_error (pfile,
3207 message ("arguments given to macro `%s'", hp->name));
3211 /* traditional C allows foo() if foo wants one argument. */
3212 if (nargs == 1 && i == 0 && cppReader_isTraditional (pfile))
3216 /* the rest args token is allowed to absorb 0 tokens */
3217 else if (i == nargs - 1 && defn->rest_args)
3220 cppReader_error (pfile,
3221 message ("macro `%s' used without args", hp->name));
3223 cppReader_error (pfile,
3224 message ("macro `%s' used with just one arg", hp->name));
3227 cppReader_error (pfile,
3228 message ("macro `%s' used with only %d args",
3234 cppReader_error (pfile,
3235 message ("macro `%s' used with too many (%d) args", hp->name, i));
3243 /* If macro wants zero args, we parsed the arglist for checking only.
3244 Read directly from the macro definition. */
3248 xbuf = defn->expansion;
3249 xbuf_len = defn->length;
3253 char *exp = defn->expansion;
3254 int offset; /* offset in expansion,
3255 copied a piece at a time */
3256 size_t totlen; /* total amount of exp buffer filled so far */
3258 register struct reflist *ap, *last_ap;
3260 /* Macro really takes args. Compute the expansion of this call. */
3262 /* Compute length in characters of the macro's expansion.
3263 Also count number of times each arg is used. */
3264 xbuf_len = defn->length;
3266 llassert (args != NULL);
3268 for (ap = defn->pattern; ap != NULL; ap = ap->next)
3272 struct argdata *arg = &args[ap->argno];
3274 /* Stringify it it hasn't already been */
3277 if (arg->stringified_length < 0)
3279 int arglen = arg->raw_length;
3280 bool escaped = FALSE;
3281 char in_string = '\0';
3284 /* Initially need_space is -1. Otherwise, 1 means the
3285 previous character was a space, but we suppressed it;
3286 0 means the previous character was a non-space. */
3287 int need_space = -1;
3290 arg->stringified = cppReader_getWritten (pfile);
3291 if (!cppReader_isTraditional (pfile))
3292 cppReader_putChar (pfile, '\"'); /* insert beginning quote */
3293 for (; i < arglen; i++)
3295 c = (ARG_BASE + arg->raw)[i];
3297 if (in_string == '\0')
3299 /* Internal sequences of whitespace are replaced by
3300 one space except within an string or char token.*/
3301 if (is_space[(int) c])
3303 if (cppReader_getWritten (pfile) > arg->stringified
3304 && (cppReader_getPWritten (pfile))[-1] == '@')
3306 /* "@ " escape markers are removed */
3307 cppReader_adjustWritten (pfile, -1);
3308 /*@innercontinue@*/ continue;
3310 if (need_space == 0)
3312 /*@innercontinue@*/ continue;
3314 else if (need_space > 0)
3315 cppReader_putChar (pfile, ' ');
3331 if (in_string != '\0')
3336 else if (c == '\"' || c == '\'')
3346 /* Escape these chars */
3347 if (c == '\"' || (in_string != '\0' && c == '\\'))
3348 cppReader_putChar (pfile, '\\');
3350 cppReader_putChar (pfile, c);
3353 cppReader_reserve (pfile, 4);
3354 sprintf (cppReader_getPWritten (pfile), "\\%03o",
3356 cppReader_adjustWritten (pfile, 4);
3359 if (!cppReader_isTraditional (pfile))
3360 cppReader_putChar (pfile, '\"'); /* insert ending quote */
3361 arg->stringified_length
3362 = size_toInt (cppReader_getWritten (pfile) - arg->stringified);
3365 xbuf_len += args[ap->argno].stringified_length;
3367 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
3369 /* Add 4 for two newline-space markers to prevent
3370 token concatenation. */
3371 xbuf_len += args[ap->argno].raw_length + 4;
3375 /* We have an ordinary (expanded) occurrence of the arg.
3376 So compute its expansion, if we have not already. */
3378 if (args[ap->argno].expand_length < 0)
3380 args[ap->argno].expanded = cppReader_getWritten (pfile);
3381 cpp_expand_to_buffer (pfile,
3382 ARG_BASE + args[ap->argno].raw,
3383 size_fromInt (args[ap->argno].raw_length));
3385 args[ap->argno].expand_length
3386 = size_toInt (cppReader_getWritten (pfile) - args[ap->argno].expanded);
3389 /* Add 4 for two newline-space markers to prevent
3390 token concatenation. */
3391 xbuf_len += args[ap->argno].expand_length + 4;
3393 if (args[ap->argno].use_count < 10)
3394 args[ap->argno].use_count++;
3397 xbuf = (char *) dmalloc (xbuf_len + 1);
3401 ** Generate in XBUF the complete expansion
3402 ** with arguments substituted in.
3403 ** TOTLEN is the total size generated so far.
3404 ** OFFSET is the index in the definition
3405 ** of where we are copying from.
3411 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
3412 last_ap = ap, ap = ap->next)
3414 register struct argdata *arg = &args[ap->argno];
3415 size_t count_before = totlen;
3417 /* Add chars to XBUF. */
3418 for (i = 0; i < ap->nchars; i++, offset++)
3420 xbuf[totlen++] = exp[offset];
3423 /* If followed by an empty rest arg with concatenation,
3424 delete the last run of nonwhite chars. */
3425 if (rest_zero && totlen > count_before
3426 && ((ap->rest_args && ap->raw_before)
3427 || (last_ap != NULL && last_ap->rest_args
3428 && last_ap->raw_after)))
3430 /* Delete final whitespace. */
3431 while (totlen > count_before && is_space[(int) xbuf[totlen - 1]])
3436 /* Delete the nonwhites before them. */
3437 while (totlen > count_before && ! is_space[(int) xbuf[totlen - 1]])
3443 if (ap->stringify != 0)
3446 memcpy (xbuf + totlen,
3447 ARG_BASE + arg->stringified,
3448 size_fromInt (arg->stringified_length));
3449 totlen += arg->stringified_length;
3451 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
3458 p1 = ARG_BASE + arg->raw;
3459 l1 = p1 + arg->raw_length;
3463 while (p1 != l1 && is_space[(int) *p1])
3468 while (p1 != l1 && is_idchar[(int) *p1])
3470 xbuf[totlen++] = *p1++;
3473 /* Delete any no-reexpansion marker that follows
3474 an identifier at the beginning of the argument
3475 if the argument is concatenated with what precedes it. */
3476 if (p1[0] == '@' && p1[1] == '-')
3481 /* Arg is concatenated after: delete trailing whitespace,
3482 whitespace markers, and no-reexpansion markers. */
3485 if (is_space[(int) l1[-1]]) l1--;
3486 else if (l1[-1] == '-')
3489 /* If a `-' is preceded by an odd number of newlines then it
3490 and the last newline are a no-reexpansion marker. */
3491 while (p2 != p1 && p2[-1] == '\n')
3496 if (((l1 - 1 - p2) & 1) != 0)
3502 /*@innerbreak@*/ break;
3507 /*@innerbreak@*/ break;
3512 memcpy (xbuf + totlen, p1, size_fromInt (l1 - p1));
3520 expanded = ARG_BASE + arg->expanded;
3522 if (!ap->raw_before && totlen > 0
3523 && (arg->expand_length != 0)
3524 && !cppReader_isTraditional(pfile)
3525 && unsafe_chars (xbuf[totlen-1], expanded[0]))
3527 xbuf[totlen++] = '@';
3528 xbuf[totlen++] = ' ';
3531 memcpy (xbuf + totlen, expanded,
3532 size_fromInt (arg->expand_length));
3533 totlen += arg->expand_length;
3535 if (!ap->raw_after && totlen > 0
3536 && offset < size_toInt (defn->length)
3537 && !cppReader_isTraditional(pfile)
3538 && unsafe_chars (xbuf[totlen-1], exp[offset]))
3540 xbuf[totlen++] = '@';
3541 xbuf[totlen++] = ' ';
3544 /* If a macro argument with newlines is used multiple times,
3545 then only expand the newlines once. This avoids creating
3546 output lines which don't correspond to any input line,
3547 which confuses gdb and gcov. */
3548 if (arg->use_count > 1 && arg->newlines > 0)
3550 /* Don't bother doing change_newlines for subsequent
3554 = change_newlines (expanded, arg->expand_length);
3558 if (totlen > xbuf_len)
3562 /* if there is anything left of the definition
3563 after handling the arg list, copy that in too. */
3565 for (i = offset; i < size_toInt (defn->length); i++)
3567 /* if we've reached the end of the macro */
3570 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
3571 && last_ap->raw_after))
3572 xbuf[totlen++] = exp[i];
3575 xbuf[totlen] = '\0';
3579 pfile->output_escapes--;
3581 /* Now put the expansion on the input stack
3582 so our caller will commence reading from it. */
3583 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
3584 cppReader_getBuffer (pfile)->has_escapes = 1;
3586 /* Pop the space we've used in the token_buffer for argument expansion. */
3587 cppReader_setWritten (pfile, old_written);
3589 /* Recursive macro use sometimes works traditionally.
3590 #define foo(x,y) bar (x (y,0), y)
3593 if (!cppReader_isTraditional (pfile))
3594 hp->type = T_DISABLED;
3600 push_macro_expansion (cppReader *pfile, char *xbuf, size_t xbuf_len,
3601 /*@dependent@*/ HASHNODE *hp)
3603 cppBuffer *mbuf = cppReader_pushBuffer (pfile, xbuf, xbuf_len);
3610 mbuf->cleanup = cppReader_macroCleanup;
3612 llassert (mbuf->hnode == NULL);
3615 /* The first chars of the expansion should be a "@ " added by
3616 collect_expansion. This is to prevent accidental token-pasting
3617 between the text preceding the macro invocation, and the macro
3620 We would like to avoid adding unneeded spaces (for the sake of
3621 tools that use cpp, such as imake). In some common cases we can
3622 tell that it is safe to omit the space.
3624 The character before the macro invocation cannot have been an
3625 idchar (or else it would have been pasted with the idchars of
3626 the macro name). Therefore, if the first non-space character
3627 of the expansion is an idchar, we do not need the extra space
3628 to prevent token pasting.
3630 Also, we don't need the extra space if the first char is '(',
3631 or some other (less common) characters. */
3633 if (xbuf[0] == '@' && xbuf[1] == ' '
3634 && (is_idchar[(int) xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
3635 || xbuf[2] == '\"'))
3637 llassert (mbuf->cur != NULL);
3643 /* Like cppGetToken, except that it does not read past end-of-line.
3644 Also, horizontal space is skipped, and macros are popped. */
3646 static enum cpp_token
3647 get_directive_token (cppReader *pfile)
3651 size_t old_written = cppReader_getWritten (pfile);
3652 enum cpp_token token;
3653 cppSkipHspace (pfile);
3654 if (cppReader_peekC (pfile) == '\n')
3659 token = cppGetToken (pfile);
3664 if (!cppBuffer_isMacro (cppReader_getBuffer (pfile)))
3669 cppReader_setWritten (pfile, old_written);
3670 /*@switchbreak@*/ break;
3678 /* Handle #include and #import.
3679 This function expects to see "fname" or <fname> on the input.
3681 The input is normally in part of the output_buffer following
3682 cppReader_getWritten, and will get overwritten by output_line_command.
3683 I.e. in input file specification has been popped by cppReader_handleDirective.
3687 do_include (cppReader *pfile, struct directive *keyword,
3688 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
3690 bool skip_dirs = (keyword->type == T_INCLUDE_NEXT);
3692 char *fbeg, *fend; /* Beginning and end of fname */
3693 enum cpp_token token;
3695 /* Chain of dirs to search */
3696 struct file_name_list *search_start = CPPOPTIONS (pfile)->include;
3697 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
3698 struct file_name_list *searchptr = NULL;
3699 size_t old_written = cppReader_getWritten (pfile);
3703 int f; /* file number */
3704 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
3705 f= -1; /* JF we iz paranoid! */
3708 pfile->parsing_include_directive++;
3709 token = get_directive_token (pfile);
3710 pfile->parsing_include_directive--;
3712 if (token == CPP_STRING)
3714 /* FIXME - check no trailing garbage */
3715 fbeg = pfile->token_buffer + old_written + 1;
3716 fend = cppReader_getPWritten (pfile) - 1;
3717 if (fbeg[-1] == '<')
3720 /* If -I-, start with the first -I dir after the -I-. */
3721 if (CPPOPTIONS (pfile)->first_bracket_include != NULL)
3722 search_start = CPPOPTIONS (pfile)->first_bracket_include;
3724 /* If -I- was specified, don't search current dir, only spec'd ones. */
3725 else if (!CPPOPTIONS (pfile)->ignore_srcdir)
3727 cppBuffer *fp = CPPBUFFER (pfile);
3728 /* We have "filename". Figure out directory this source
3729 file is coming from and put it on the front of the list. */
3731 for ( ; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
3736 llassert (fp != NULL);
3740 if (cstring_isDefined (fp->nominal_fname))
3742 nam = cstring_toCharsSafe (fp->nominal_fname);
3744 /* Found a named file. Figure out dir of the file,
3745 and put it in front of the search list. */
3746 dsp[0].next = search_start;
3749 ep = strrchr (nam, CONNECTCHAR);
3751 ep = strrchr (nam, ']');
3752 if (ep == NULL) ep = strrchr (nam, '>');
3753 if (ep == NULL) ep = strrchr (nam, ':');
3754 if (ep != NULL) ep++;
3763 dsp[0].fname = cstring_fromChars (nam);
3766 if (n + INCLUDE_LEN_FUDGE > pfile->max_include_len)
3767 pfile->max_include_len = n + INCLUDE_LEN_FUDGE;
3771 dsp[0].fname = cstring_undefined; /* Current directory */
3774 dsp[0].got_name_map = 0;
3785 else if (token == CPP_NAME)
3788 * Support '#include xyz' like VAX-C to allow for easy use of all the
3789 * decwindow include files. It defaults to '#include <xyz.h>' (so the
3790 * code from case '<' is repeated here) and generates a warning.
3792 cppReader_warning (pfile,
3793 "VAX-C-style include specification found, use '#include <filename.h>' !");
3795 /* If -I-, start with the first -I dir after the -I-. */
3796 if (CPPOPTIONS (pfile)->first_bracket_include)
3797 search_start = CPPOPTIONS (pfile)->first_bracket_include;
3798 fbeg = pfile->token_buffer + old_written;
3799 fend = cppReader_getPWritten (pfile);
3804 cppReader_error (pfile,
3805 message ("Preprocessor command #%s expects \"FILENAME\" or <FILENAME>",
3808 cppReader_setWritten (pfile, old_written);
3809 cppReader_skipRestOfLine (pfile);
3815 token = get_directive_token (pfile);
3816 if (token != CPP_VSPACE)
3818 cppReader_errorLit (pfile,
3819 cstring_makeLiteralTemp ("Junk at end of #include"));
3821 while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
3823 token = get_directive_token (pfile);
3828 ** For #include_next, skip in the search path
3829 ** past the dir in which the containing file was found.
3834 cppBuffer *fp = CPPBUFFER (pfile);
3836 for (; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
3838 llassert (fp != NULL);
3840 if (fp->fname != NULL)
3842 /* fp->dir is null if the containing file was specified with
3843 an absolute file name. In that case, don't skip anything. */
3844 if (fp->dir == SELF_DIR_DUMMY)
3846 search_start = CPPOPTIONS (pfile)->include;
3848 else if (fp->dir != NULL)
3850 search_start = fp->dir->next;
3862 cppReader_setWritten (pfile, old_written);
3868 cppReader_error (pfile,
3869 message ("Empty file name in #%s", keyword->name));
3874 ** Allocate this permanently, because it gets stored in the definitions
3878 fname = cstring_undefined;
3880 /* + 2 above for slash and terminating null. */
3881 /* + 2 added for '.h' on VMS (to support '#include filename') */
3883 /* If specified file name is absolute, just open it. */
3885 if (osd_isConnectChar (*fbeg)
3887 || (*(fbeg + 1) == ':')
3891 fname = cstring_copyLength (fbeg, flen);
3893 if (redundant_include_p (pfile, fname))
3895 cstring_free (fname);
3899 f = open_include_file (pfile, fname, NULL);
3901 if (f == IMPORT_FOUND)
3903 return 0; /* Already included this file */
3908 /* Search directory path, trying to open the file.
3909 Copy each filename tried into FNAME. */
3911 for (searchptr = search_start; searchptr != NULL;
3912 searchptr = searchptr->next)
3914 if (!cstring_isEmpty (searchptr->fname))
3916 /* The empty string in a search path is ignored.
3917 This makes it possible to turn off entirely
3918 a standard piece of the list. */
3919 if (cstring_isEmpty (searchptr->fname))
3922 fname = cstring_copy (searchptr->fname);
3923 fname = cstring_appendChar (fname, CONNECTCHAR);
3930 fname = cstring_concatLength (fname, fbeg, flen);
3932 /* Change this 1/2 Unix 1/2 VMS file specification into a
3933 full VMS file specification */
3934 if (searchptr->fname && (searchptr->fname[0] != 0)) {
3935 /* Fix up the filename */
3936 hack_vms_include_specification (fname);
3938 /* This is a normal VMS filespec, so use it unchanged. */
3939 strncpy (fname, fbeg, flen);
3941 /* if it's '#include filename', add the missing .h */
3942 if (strchr (fname,'.') == NULL) {
3943 strcat (fname, ".h");
3947 /* ??? There are currently 3 separate mechanisms for avoiding processing
3948 of redundant include files: #import, #pragma once, and
3949 redundant_include_p. It would be nice if they were unified. */
3951 if (redundant_include_p (pfile, fname))
3953 cstring_free (fname);
3957 f = open_include_file (pfile, fname, searchptr);
3959 if (f == IMPORT_FOUND)
3961 return 0; /* Already included this file */
3964 else if (f == IMPORT_NOT_FOUND && errno == EACCES)
3966 cppReader_warning (pfile,
3967 message ("Header file %s exists, but is not readable", fname));
3980 /* A file that was not found. */
3981 fname = cstring_copyLength (fbeg, flen);
3983 if (search_start != NULL)
3985 cppReader_error (pfile,
3986 message ("Cannot find include file %s", fname));
3990 cppReader_error (pfile,
3991 message ("No include path in which to find %s", fname));
3996 ** Check to see if this include file is a once-only include file.
4000 struct file_name_list *ptr;
4002 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
4004 if (cstring_equal (ptr->fname, fname))
4006 /* This file was included before. */
4013 /* This is the first time for this file. */
4014 /* Add it to list of files included. */
4016 ptr = (struct file_name_list *) dmalloc (sizeof (*ptr));
4017 ptr->control_macro = NULL;
4018 ptr->c_system_include_path = NULL;
4019 ptr->next = pfile->all_include_files;
4021 ptr->got_name_map = NULL;
4023 pfile->all_include_files = ptr;
4024 assertSet (pfile->all_include_files);
4027 if (angle_brackets != 0)
4029 pfile->system_include_depth++;
4032 /* Actually process the file */
4033 if (cppReader_pushBuffer (pfile, NULL, 0) == NULL)
4035 cstring_free (fname);
4039 if (finclude (pfile, f, fname, is_system_include (pfile, fname),
4040 searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
4042 output_line_command (pfile, 0, enter_file);
4043 pfile->only_seen_white = 2;
4048 pfile->system_include_depth--;
4051 } /*:=branchstate@*/
4056 /* Return nonzero if there is no need to include file NAME
4057 because it has already been included and it contains a conditional
4058 to make a repeated include do nothing. */
4061 redundant_include_p (cppReader *pfile, cstring name)
4063 struct file_name_list *l = pfile->all_include_files;
4065 for (; l != NULL; l = l->next)
4067 if (cstring_equal (name, l->fname)
4068 && (l->control_macro != NULL)
4069 && (cppReader_lookup (l->control_macro, -1, -1) != NULL))
4078 /* Return nonzero if the given FILENAME is an absolute pathname which
4079 designates a file within one of the known "system" include file
4080 directories. We assume here that if the given FILENAME looks like
4081 it is the name of a file which resides either directly in a "system"
4082 include file directory, or within any subdirectory thereof, then the
4083 given file must be a "system" include file. This function tells us
4084 if we should suppress pedantic errors/warnings for the given FILENAME.
4086 The value is 2 if the file is a C-language system header file
4087 for which C++ should (on most systems) assume `extern "C"'. */
4090 is_system_include (cppReader *pfile, cstring filename)
4092 struct file_name_list *searchptr;
4094 for (searchptr = CPPOPTIONS (pfile)->first_system_include;
4096 searchptr = searchptr->next)
4098 if (!cstring_isEmpty (searchptr->fname)) {
4099 cstring sys_dir = searchptr->fname;
4100 int length = cstring_length (sys_dir);
4102 if (cstring_equalLen (sys_dir, filename, length)
4103 && osd_isConnectChar (cstring_getChar (filename, length)))
4105 if (searchptr->c_system_include_path)
4116 /* Convert a character string literal into a nul-terminated string.
4117 The input string is [IN ... LIMIT).
4118 The result is placed in RESULT. RESULT can be the same as IN.
4119 The value returned in the end of the string written to RESULT,
4120 or NULL on error. */
4122 static /*@null@*/ char *
4123 convert_string (cppReader *pfile, /*@returned@*/ char *result,
4124 char *in, char *limit, int handle_escapes)
4144 /*@switchbreak@*/ break;
4148 char *bpc = (char *) in;
4149 int i = (char) cppReader_parseEscape (pfile, &bpc);
4152 *result++ = (char) c;
4153 /*@switchbreak@*/ break;
4167 * interpret #line command. Remembers previously seen fnames
4168 * in its very own hash table.
4171 /*@constant int FNAME_HASHSIZE@*/
4172 #define FNAME_HASHSIZE 37
4175 do_line (cppReader *pfile, /*@unused@*/ struct directive *keyword)
4177 cppBuffer *ip = cppReader_getBuffer (pfile);
4179 size_t old_written = cppReader_getWritten (pfile);
4180 enum file_change_code file_change = same_file;
4181 enum cpp_token token;
4183 token = get_directive_token (pfile);
4185 if (token != CPP_NUMBER
4186 || !isdigit(pfile->token_buffer[old_written]))
4188 cppReader_errorLit (pfile,
4189 cstring_makeLiteralTemp ("invalid format `#line' command"));
4191 goto bad_line_directive;
4194 /* The Newline at the end of this line remains to be processed.
4195 To put the next line at the specified line number,
4196 we must store a line number now that is one less. */
4197 new_lineno = atoi (pfile->token_buffer + old_written) - 1;
4198 cppReader_setWritten (pfile, old_written);
4200 /* NEW_LINENO is one less than the actual line number here. */
4201 if (cppReader_isPedantic (pfile) && new_lineno < 0)
4202 cppReader_pedwarnLit (pfile,
4203 cstring_makeLiteralTemp ("line number out of range in `#line' command"));
4205 token = get_directive_token (pfile);
4207 if (token == CPP_STRING) {
4208 char *fname = pfile->token_buffer + old_written;
4210 static HASHNODE *fname_table[FNAME_HASHSIZE];
4211 HASHNODE *hp, **hash_bucket;
4216 /* Turn the file name, which is a character string literal,
4217 into a null-terminated string. Do this in place. */
4218 end_name = convert_string (pfile, fname, fname, cppReader_getPWritten (pfile), 1);
4219 if (end_name == NULL)
4221 cppReader_errorLit (pfile,
4222 cstring_makeLiteralTemp ("invalid format `#line' command"));
4223 goto bad_line_directive;
4226 fname_length = end_name - fname;
4227 num_start = cppReader_getWritten (pfile);
4229 token = get_directive_token (pfile);
4230 if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP) {
4231 p = pfile->token_buffer + num_start;
4232 if (cppReader_isPedantic (pfile))
4233 cppReader_pedwarnLit (pfile,
4234 cstring_makeLiteralTemp ("garbage at end of `#line' command"));
4236 if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
4238 cppReader_errorLit (pfile,
4239 cstring_makeLiteralTemp ("invalid format `#line' command"));
4240 goto bad_line_directive;
4243 file_change = enter_file;
4245 file_change = leave_file;
4247 ip->system_header_p = 1;
4248 else /* if (*p == 4) */
4249 ip->system_header_p = 2;
4251 cppReader_setWritten (pfile, num_start);
4252 token = get_directive_token (pfile);
4253 p = pfile->token_buffer + num_start;
4254 if (token == CPP_NUMBER && p[1] == '\0' && (*p == '3' || *p== '4')) {
4255 ip->system_header_p = *p == 3 ? 1 : 2;
4256 token = get_directive_token (pfile);
4258 if (token != CPP_VSPACE) {
4259 cppReader_errorLit (pfile,
4260 cstring_makeLiteralTemp ("invalid format `#line' command"));
4262 goto bad_line_directive;
4267 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
4268 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
4270 if (hp->length == fname_length &&
4271 strncmp (hp->value.cpval, fname, size_fromInt (fname_length)) == 0) {
4272 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
4278 /* Didn't find it; cons up a new one. */
4279 hp = (HASHNODE *) dmalloc (sizeof (*hp) + fname_length + 1);
4282 hp->bucket_hdr = NULL;
4284 hp->name = cstring_undefined;
4285 hp->next = *hash_bucket;
4289 hp->length = fname_length;
4290 hp->value.cpval = dmalloc (sizeof (*hp->value.cpval) * (fname_length + 1));
4291 memcpy (hp->value.cpval, fname, size_fromInt (fname_length));
4292 hp->value.cpval[fname_length] = '\0';
4293 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
4296 else if (token != CPP_VSPACE && token != CPP_EOF)
4298 cppReader_errorLit (pfile,
4299 cstring_makeLiteralTemp ("invalid format `#line' command"));
4300 goto bad_line_directive;
4307 ip->lineno = new_lineno;
4309 cppReader_skipRestOfLine (pfile);
4310 cppReader_setWritten (pfile, old_written);
4311 output_line_command (pfile, 0, file_change);
4316 * remove the definition of a symbol from the symbol table.
4317 * according to un*x /lib/cpp, it is not an error to undef
4318 * something that has no definitions, so it isn't one here either.
4322 do_undef (cppReader *pfile, struct directive *keyword, char *buf, char *limit)
4327 char *orig_buf = buf;
4329 SKIP_WHITE_SPACE (buf);
4331 sym_length = cppReader_checkMacroName (pfile, buf, cstring_makeLiteralTemp ("macro"));
4333 while ((hp = cppReader_lookup (buf, sym_length, -1)) != NULL)
4335 /* If we are generating additional info for debugging (with -g) we
4336 need to pass through all effective #undef commands. */
4337 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
4339 pass_thru_directive (orig_buf, limit, pfile, keyword);
4342 if (hp->type != T_MACRO)
4344 cppReader_warning (pfile,
4345 message ("Undefining preprocessor builtin: %s",
4349 cppReader_deleteMacro (hp);
4352 if (cppReader_isPedantic (pfile)) {
4354 SKIP_WHITE_SPACE (buf);
4357 cppReader_pedwarnLit (pfile,
4358 cstring_makeLiteralTemp ("garbage after `#undef' directive"));
4367 * Report an error detected by the program we are processing.
4368 * Use the text of the line in the error message.
4369 * (We use error because it prints the filename & line#.)
4373 do_error (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4374 char *buf, char *limit)
4376 int length = limit - buf;
4377 cstring copy = cstring_copyLength (buf, length);
4378 cstring adv = cstring_advanceWhiteSpace (copy);
4380 cppReader_error (pfile, message ("#error %s", adv));
4381 cstring_free (copy);
4386 * Report a warning detected by the program we are processing.
4387 * Use the text of the line in the warning message, then continue.
4388 * (We use error because it prints the filename & line#.)
4392 do_warning (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4393 char *buf, char *limit)
4395 int length = limit - buf;
4396 cstring copy = cstring_copyLength (buf, length);
4397 cstring adv = cstring_advanceWhiteSpace (copy);
4398 cppReader_warning (pfile, message ("#warning %s", adv));
4399 cstring_free (copy);
4404 /* #ident has already been copied to the output file, so just ignore it. */
4407 do_ident (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4408 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
4410 /* Allow #ident in system headers, since that's not user's fault. */
4411 if (cppReader_isPedantic (pfile) && !cppReader_getBuffer (pfile)->system_header_p)
4412 cppReader_pedwarnLit (pfile,
4413 cstring_makeLiteralTemp ("ANSI C does not allow `#ident'"));
4415 /* Leave rest of line to be read by later calls to cppGetToken. */
4420 /* #pragma and its argument line have already been copied to the output file.
4421 Just check for some recognized pragmas that need validation here. */
4424 do_pragma (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4425 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
4427 while (*buf == ' ' || *buf == '\t')
4432 if (!strncmp (buf, "implementation", 14)) {
4433 /* Be quiet about `#pragma implementation' for a file only if it hasn't
4434 been included yet. */
4435 struct file_name_list *ptr;
4436 char *p = buf + 14, *fname, *inc_fname;
4438 SKIP_WHITE_SPACE (p);
4439 if (*p == '\n' || *p != '\"')
4443 p = (char *) strchr (fname, '\"');
4444 fname_len = p != NULL ? p - fname : mstring_length (fname);
4446 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
4448 inc_fname = (char *) strrchr (cstring_toCharsSafe (ptr->fname), CONNECTCHAR);
4449 inc_fname = (inc_fname != NULL)
4450 ? inc_fname + 1 : cstring_toCharsSafe (ptr->fname);
4452 if ((inc_fname != NULL)
4453 && (strncmp (inc_fname, fname, size_fromInt (fname_len)) == 0))
4455 cpp_setLocation (pfile);
4457 ppllerror (message ("`#pragma implementation' for `%s' appears "
4458 "after file is included",
4459 cstring_fromChars (fname)));
4468 * handle #if command by
4469 * 1) inserting special `defined' keyword into the hash table
4470 * that gets turned into 0 or 1 by special_symbol (thus,
4471 * if the luser has a symbol called `defined' already, it won't
4472 * work inside the #if command)
4473 * 2) rescan the input into a temporary output buffer
4474 * 3) pass the output buffer to the yacc parser and collect a value
4475 * 4) clean up the mess left from steps 1 and 2.
4476 * 5) call conditional_skip to skip til the next #endif (etc.),
4477 * or not, depending on the value from step 3.
4481 do_if (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4482 char *buf, char *limit)
4484 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
4485 conditional_skip (pfile, value == 0, T_IF, NULL);
4490 * handle a #elif directive by not changing if_stack either.
4491 * see the comment above do_else.
4494 static int do_elif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4495 char *buf, char *limit)
4497 if (pfile->if_stack == cppReader_getBuffer (pfile)->if_stack)
4499 cppReader_errorLit (pfile,
4500 cstring_makeLiteralTemp ("Preprocessor command #elif is not within a conditional"));
4505 llassert (pfile->if_stack != NULL);
4507 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
4509 cppReader_errorLit (pfile,
4510 cstring_makeLiteralTemp ("`#elif' after `#else'"));
4512 if (pfile->if_stack->fname != NULL
4513 && cppReader_getBuffer (pfile)->fname != NULL
4514 && !cstring_equal (pfile->if_stack->fname,
4515 cppReader_getBuffer (pfile)->nominal_fname))
4516 fprintf (stderr, ", file %s", cstring_toCharsSafe (pfile->if_stack->fname));
4517 fprintf (stderr, ")\n");
4519 pfile->if_stack->type = T_ELIF;
4522 if (pfile->if_stack->if_succeeded)
4524 skip_if_group (pfile, 0);
4528 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
4530 skip_if_group (pfile, 0);
4533 ++pfile->if_stack->if_succeeded; /* continue processing input */
4534 output_line_command (pfile, 1, same_file);
4542 * evaluate a #if expression in BUF, of length LENGTH,
4543 * then parse the result as a C expression and return the value as an int.
4546 static HOST_WIDE_INT
4547 eval_if_expression (cppReader *pfile,
4548 /*@unused@*/ char *buf,
4549 /*@unused@*/ int length)
4551 HASHNODE *save_defined;
4552 HOST_WIDE_INT value;
4553 size_t old_written = cppReader_getWritten (pfile);
4555 save_defined = cppReader_install ("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
4556 pfile->pcp_inside_if = 1;
4558 value = cppReader_parseExpression (pfile);
4559 pfile->pcp_inside_if = 0;
4561 /* Clean up special symbol */
4562 cppReader_deleteMacro (save_defined);
4564 cppReader_setWritten (pfile, old_written); /* Pop */
4570 * routine to handle ifdef/ifndef. Try to look up the symbol,
4571 * then do or don't skip to the #endif/#else/#elif depending
4572 * on what directive is actually being processed.
4576 do_xifdef (cppReader *pfile, struct directive *keyword,
4577 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
4580 cppBuffer *ip = cppReader_getBuffer (pfile);
4583 enum cpp_token token;
4584 int start_of_file = 0;
4585 char *control_macro = 0;
4586 size_t old_written = cppReader_getWritten (pfile);
4588 DPRINTF (("do xifdef: %d",
4589 keyword->type == T_IFNDEF));
4591 /* Detect a #ifndef at start of file (not counting comments). */
4592 if (cstring_isDefined (ip->fname) && keyword->type == T_IFNDEF)
4594 start_of_file = pfile->only_seen_white == 2;
4597 pfile->no_macro_expand++;
4598 token = get_directive_token (pfile);
4599 pfile->no_macro_expand--;
4601 ident = pfile->token_buffer + old_written;
4602 ident_length = size_toInt (cppReader_getWritten (pfile) - old_written);
4603 cppReader_setWritten (pfile, old_written); /* Pop */
4605 if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
4607 skip = (keyword->type == T_IFDEF);
4608 if (! cppReader_isTraditional (pfile))
4610 cppReader_pedwarn (pfile,
4611 message ("`#%s' with no argument", keyword->name));
4614 else if (token == CPP_NAME)
4616 HASHNODE *hp = cppReader_lookup (ident, ident_length, -1);
4617 skip = (keyword->type == T_IFDEF)
4618 ? (hp == NULL) : (hp != NULL);
4620 DPRINTF (("hp null: %d / %d / %d",
4622 (keyword->type == T_IFNDEF),
4625 if (start_of_file && !skip)
4627 DPRINTF (("Not skipping!"));
4628 control_macro = (char *) dmalloc (size_fromInt (ident_length + 1));
4629 memcpy (control_macro, ident, size_fromInt (ident_length + 1));
4634 skip = (keyword->type == T_IFDEF);
4635 if (! cppReader_isTraditional (pfile))
4637 cppReader_error (pfile,
4638 message ("`#%s' with invalid argument", keyword->name));
4642 if (!cppReader_isTraditional (pfile))
4645 cppSkipHspace (pfile);
4646 c = cppReader_peekC (pfile);
4647 if (c != EOF && c != '\n')
4649 cppReader_pedwarn (pfile,
4650 message ("garbage at end of `#%s' argument", keyword->name));
4654 cppReader_skipRestOfLine (pfile);
4656 DPRINTF (("Conditional skip: %d", skip));
4657 conditional_skip (pfile, skip, T_IF, control_macro);
4661 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
4662 If this is a #ifndef starting at the beginning of a file,
4663 CONTROL_MACRO is the macro name tested by the #ifndef.
4664 Otherwise, CONTROL_MACRO is 0. */
4667 conditional_skip (cppReader *pfile, int skip,
4668 enum node_type type,
4669 /*@dependent@*/ char *control_macro)
4671 cppIfStackFrame *temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
4673 temp->fname = cppReader_getBuffer (pfile)->nominal_fname;
4674 temp->next = pfile->if_stack;
4675 temp->control_macro = control_macro;
4677 temp->if_succeeded = 0;
4679 pfile->if_stack = temp;
4680 pfile->if_stack->type = type;
4684 skip_if_group (pfile, 0);
4689 ++pfile->if_stack->if_succeeded;
4690 output_line_command (pfile, 1, same_file);
4695 * skip to #endif, #else, or #elif. adjust line numbers, etc.
4696 * leaves input ptr at the sharp sign found.
4697 * If ANY is nonzero, return at next directive of any sort.
4701 skip_if_group (cppReader *pfile, int any)
4704 struct directive *kt;
4705 cppIfStackFrame *save_if_stack = pfile->if_stack; /* don't pop past here */
4706 register int ident_length;
4708 struct parse_marker line_start_mark;
4710 parseSetMark (&line_start_mark, pfile);
4712 if (CPPOPTIONS (pfile)->output_conditionals) {
4713 static char failed[] = "#failed\n";
4714 cppReader_puts (pfile, failed, sizeof(failed)-1);
4716 output_line_command (pfile, 1, same_file);
4720 if (CPPOPTIONS (pfile)->output_conditionals)
4722 cppBuffer *pbuf = cppReader_getBuffer (pfile);
4725 llassert (pbuf->buf != NULL);
4727 start_line = pbuf->buf + line_start_mark.position;
4728 cppReader_puts (pfile, start_line, size_fromInt (pbuf->cur - start_line));
4731 parseMoveMark (&line_start_mark, pfile);
4733 if (!cppReader_isTraditional (pfile))
4735 cppSkipHspace (pfile);
4738 c = cppReader_getC (pfile);
4741 size_t old_written = cppReader_getWritten (pfile);
4742 cppSkipHspace (pfile);
4744 parse_name (pfile, cppReader_getC (pfile));
4745 ident_length = size_toInt (cppReader_getWritten (pfile) - old_written);
4746 ident = pfile->token_buffer + old_written;
4747 pfile->limit = ident;
4749 for (kt = directive_table; kt->length >= 0; kt++)
4751 cppIfStackFrame *temp;
4752 if (ident_length == kt->length
4753 && cstring_equalPrefix (kt->name, ident))
4755 /* If we are asked to return on next directive, do so now. */
4766 temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
4767 temp->next = pfile->if_stack;
4768 temp->fname = cppReader_getBuffer (pfile)->nominal_fname;
4769 temp->type = kt->type;
4771 temp->if_succeeded = 0;
4772 temp->control_macro = NULL;
4774 pfile->if_stack = temp;
4775 /*@switchbreak@*/ break;
4778 if (cppReader_isPedantic (pfile) && pfile->if_stack != save_if_stack)
4779 validate_else (pfile,
4780 cstring_makeLiteralTemp (kt->type == T_ELSE ? "#else" : "#endif"));
4783 if (pfile->if_stack == cppReader_getBuffer (pfile)->if_stack)
4785 cppReader_error (pfile,
4786 message ("Preprocessor command #%s is not within a conditional", kt->name));
4787 /*@switchbreak@*/ break;
4789 else if (pfile->if_stack == save_if_stack)
4791 goto done; /* found what we came for */
4798 if (kt->type != T_ENDIF)
4800 llassert (pfile->if_stack != NULL);
4802 if (pfile->if_stack->type == T_ELSE)
4804 cppReader_errorLit (pfile,
4805 cstring_makeLiteralTemp ("`#else' or `#elif' after `#else'"));
4808 pfile->if_stack->type = kt->type;
4809 /*@switchbreak@*/ break;
4812 temp = pfile->if_stack;
4813 llassert (temp != NULL);
4814 pfile->if_stack = temp->next;
4816 /*@switchbreak@*/ break;
4822 /* Don't let erroneous code go by. */
4824 if (kt->length < 0 && !CPPOPTIONS (pfile)->lang_asm
4825 && cppReader_isPedantic (pfile))
4827 cppReader_pedwarnLit (pfile,
4828 cstring_makeLiteralTemp ("Invalid preprocessor directive name"));
4832 c = cppReader_getC (pfile);
4834 /* We're in the middle of a line. Skip the rest of it. */
4841 case '/': /* possible comment */
4842 c = skip_comment (pfile, NULL);
4845 /*@switchbreak@*/ break;
4848 cppReader_forward (pfile, -1);
4849 old = cppReader_getWritten (pfile);
4850 (void) cppGetToken (pfile);
4851 cppReader_setWritten (pfile, old);
4852 /*@switchbreak@*/ break;
4854 /* Char after backslash loses its special meaning. */
4855 if (cppReader_peekC (pfile) == '\n')
4857 cppReader_forward (pfile, 1);
4860 /*@switchbreak@*/ break;
4864 c = cppReader_getC (pfile);
4867 if (CPPOPTIONS (pfile)->output_conditionals) {
4868 static char end_failed[] = "#endfailed\n";
4869 cppReader_puts (pfile, end_failed, sizeof(end_failed)-1);
4872 pfile->only_seen_white = 1;
4874 parseGotoMark (&line_start_mark, pfile);
4875 parseClearMark (&line_start_mark);
4879 * handle a #else directive. Do this by just continuing processing
4880 * without changing if_stack ; this is so that the error message
4881 * for missing #endif's etc. will point to the original #if. It
4882 * is possible that something different would be better.
4886 do_else (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4887 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
4889 if (cppReader_isPedantic (pfile))
4891 validate_else (pfile, cstring_makeLiteralTemp ("#else"));
4894 cppReader_skipRestOfLine (pfile);
4896 if (pfile->if_stack == cppReader_getBuffer (pfile)->if_stack) {
4897 cppReader_errorLit (pfile,
4898 cstring_makeLiteralTemp ("Preprocessor command #else is not within a conditional"));
4901 /* #ifndef can't have its special treatment for containing the whole file
4902 if it has a #else clause. */
4904 llassert (pfile->if_stack != NULL);
4906 pfile->if_stack->control_macro = 0;
4908 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
4910 cpp_setLocation (pfile);
4911 genppllerrorhint (FLG_PREPROC,
4912 message ("Pre-processor directive #else after #else"),
4913 message ("%q: Location of match",
4914 fileloc_unparseRaw (pfile->if_stack->fname,
4915 pfile->if_stack->lineno)));
4918 pfile->if_stack->type = T_ELSE;
4921 if (pfile->if_stack->if_succeeded)
4922 skip_if_group (pfile, 0);
4924 ++pfile->if_stack->if_succeeded; /* continue processing input */
4925 output_line_command (pfile, 1, same_file);
4932 * unstack after #endif command
4936 do_endif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4937 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
4939 if (cppReader_isPedantic (pfile))
4941 validate_else (pfile, cstring_makeLiteralTemp ("#endif"));
4944 cppReader_skipRestOfLine (pfile);
4946 if (pfile->if_stack == cppReader_getBuffer (pfile)->if_stack)
4948 cppReader_errorLit (pfile, cstring_makeLiteralTemp ("Unbalanced #endif"));
4952 cppIfStackFrame *temp = pfile->if_stack;
4954 llassert (temp != NULL);
4956 pfile->if_stack = temp->next;
4957 if (temp->control_macro != 0)
4959 /* This #endif matched a #ifndef at the start of the file.
4960 See if it is at the end of the file. */
4961 struct parse_marker start_mark;
4964 parseSetMark (&start_mark, pfile);
4968 cppSkipHspace (pfile);
4969 c = cppReader_getC (pfile);
4975 parseGotoMark (&start_mark, pfile);
4976 parseClearMark (&start_mark);
4980 /* If we get here, this #endif ends a #ifndef
4981 that contains all of the file (aside from whitespace).
4982 Arrange not to include the file again
4983 if the macro that was tested is defined.
4985 Do not do this for the top-level file in a -include or any
4986 file in a -imacros. */
4987 struct file_name_list *ifile = pfile->all_include_files;
4989 for ( ; ifile != NULL; ifile = ifile->next)
4991 if (cstring_equal (ifile->fname, cppReader_getBuffer (pfile)->fname))
4993 ifile->control_macro = temp->control_macro;
5001 output_line_command (pfile, 1, same_file);
5006 /* When an #else or #endif is found while skipping failed conditional,
5007 if -pedantic was specified, this is called to warn about text after
5008 the command name. P points to the first char after the command name. */
5011 validate_else (cppReader *pfile, cstring directive)
5014 cppSkipHspace (pfile);
5015 c = cppReader_peekC (pfile);
5016 if (c != EOF && c != '\n')
5018 cppReader_pedwarn (pfile,
5019 message ("text following `%s' violates ANSI standard", directive));
5024 ** Get the next token, and add it to the text in pfile->token_buffer.
5025 ** Return the kind of token we got.
5029 cppGetToken (cppReader *pfile)
5032 size_t old_written = 0;
5033 int start_line, start_column;
5034 enum cpp_token token;
5035 struct cppOptions *opts = CPPOPTIONS (pfile);
5036 cppReader_getBuffer (pfile)->prev = cppReader_getBuffer (pfile)->cur;
5039 c = cppReader_getC (pfile);
5044 if (cppReader_getBuffer (pfile)->seen_eof)
5046 cppBuffer *buf = cppReader_popBuffer (pfile);
5048 if (buf != cppReader_nullBuffer (pfile))
5059 cppBuffer *next_buf = cppBuffer_prevBuffer (cppReader_getBuffer (pfile));
5060 cppReader_getBuffer (pfile)->seen_eof = 1;
5062 if (cstring_isDefined (cppReader_getBuffer (pfile)->nominal_fname)
5063 && next_buf != cppReader_nullBuffer (pfile))
5065 /* We're about to return from an #include file.
5066 Emit #line information now (as part of the CPP_POP) result.
5067 But the #line refers to the file we will pop to. */
5068 cppBuffer *cur_buffer = CPPBUFFER (pfile);
5069 CPPBUFFER (pfile) = next_buf;
5070 pfile->input_stack_listing_current = 0;
5071 output_line_command (pfile, 0, leave_file);
5072 CPPBUFFER (pfile) = cur_buffer;
5080 struct parse_marker start_mark;
5085 if (cppReader_peekC (pfile) == '=')
5090 if (opts->put_out_comments)
5092 parseSetMark (&start_mark, pfile);
5096 cppBuffer_lineAndColumn (cppReader_fileBuffer (pfile),
5097 &start_line, &start_column);
5098 c = skip_comment (pfile, &newlines);
5100 if (opts->put_out_comments && (c == '/' || c == EOF))
5102 assertSet (&start_mark);
5103 parseClearMark (&start_mark);
5110 cppReader_errorWithLine (pfile, start_line, start_column,
5111 cstring_makeLiteral ("Unterminated comment"));
5114 c = '/'; /* Initial letter of comment. */
5116 /* Comments are equivalent to spaces.
5117 For -traditional, a comment is equivalent to nothing. */
5119 if (opts->put_out_comments)
5123 assertSet (&start_mark);
5124 res = cpp_handleComment (pfile, &start_mark);
5125 pfile->lineno += newlines;
5128 else if (cppReader_isTraditional (pfile))
5134 cppReader_reserve(pfile, 1);
5135 cppReader_putCharQ (pfile, ' ');
5140 if (!pfile->only_seen_white)
5145 if (cppReader_handleDirective (pfile))
5147 return CPP_DIRECTIVE;
5150 pfile->only_seen_white = 0;
5155 /* A single quoted string is treated like a double -- some
5156 programs (e.g., troff) are perverse this way */
5157 cppBuffer_lineAndColumn (cppReader_fileBuffer (pfile),
5158 &start_line, &start_column);
5159 old_written = cppReader_getWritten (pfile);
5161 cppReader_putChar (pfile, c);
5164 int cc = cppReader_getC (pfile);
5167 if (cppBuffer_isMacro (CPPBUFFER (pfile)))
5169 /* try harder: this string crosses a macro expansion
5170 boundary. This can happen naturally if -traditional.
5171 Otherwise, only -D can make a macro with an unmatched
5174 = cppBuffer_prevBuffer (cppReader_getBuffer (pfile));
5175 (*cppReader_getBuffer (pfile)->cleanup)
5176 (cppReader_getBuffer (pfile), pfile);
5177 CPPBUFFER (pfile) = next_buf;
5180 if (!cppReader_isTraditional (pfile))
5182 cpp_setLocation (pfile);
5184 setLine (long_toInt (start_line));
5185 setColumn (long_toInt (start_column));
5187 if (pfile->multiline_string_line != long_toInt (start_line)
5188 && pfile->multiline_string_line != 0)
5192 message ("Unterminated string or character constant"),
5193 message ("%q: Possible real start of unterminated constant",
5195 (fileloc_filename (g_currentloc),
5196 pfile->multiline_string_line)));
5197 pfile->multiline_string_line = 0;
5203 message ("Unterminated string or character constant"));
5206 /*@loopbreak@*/ break;
5208 cppReader_putChar (pfile, cc);
5212 /* Traditionally, end of line ends a string constant with
5213 no error. So exit the loop and record the new line. */
5214 if (cppReader_isTraditional (pfile))
5220 if (cppReader_isPedantic (pfile)
5221 && pfile->multiline_string_line == 0)
5223 cppReader_pedwarnWithLine
5224 (pfile, long_toInt (start_line),
5225 long_toInt (start_column),
5226 cstring_makeLiteral ("String constant runs past end of line"));
5228 if (pfile->multiline_string_line == 0)
5230 pfile->multiline_string_line = start_line;
5233 /*@switchbreak@*/ break;
5236 cc = cppReader_getC (pfile);
5239 /* Backslash newline is replaced by nothing at all. */
5240 cppReader_adjustWritten (pfile, -1);
5245 /* ANSI stupidly requires that in \\ the second \
5246 is *not* prevented from combining with a newline. */
5249 cppReader_putChar (pfile, cc);
5251 /*@switchbreak@*/ break;
5257 /*@switchbreak@*/ break;
5261 pfile->lineno += count_newlines (pfile->token_buffer + old_written,
5262 cppReader_getPWritten (pfile));
5263 pfile->only_seen_white = 0;
5264 return c == '\'' ? CPP_CHAR : CPP_STRING;
5267 if (!opts->dollars_in_ident)
5272 if (opts->cplusplus && cppReader_peekC (pfile) == ':')
5280 c2 = cppReader_peekC (pfile);
5281 if (c2 == c || c2 == '=')
5291 if (cppReader_peekC (pfile) == '=')
5297 c2 = cppReader_peekC (pfile);
5298 if (c2 == '-' && opts->chill)
5300 /* Chill style comment */
5301 if (opts->put_out_comments)
5303 parseSetMark (&start_mark, pfile);
5306 cppReader_forward (pfile, 1); /* Skip second '-'. */
5310 c = cppReader_getC (pfile);
5312 /*@loopbreak@*/ break;
5315 /* Don't consider final '\n' to be part of comment. */
5316 cppReader_forward (pfile, -1);
5317 /*@loopbreak@*/ break;
5321 goto return_comment;
5323 if (c2 == '-' || c2 == '=' || c2 == '>')
5328 if (pfile->parsing_include_directive)
5332 cppReader_putChar (pfile, c);
5334 /*@loopbreak@*/ break;
5335 c = cppReader_getC (pfile);
5337 if (c == '\n' || c == EOF)
5339 cppReader_errorLit (pfile,
5340 cstring_makeLiteralTemp ("Missing '>' in \"#include <FILENAME>\""));
5341 /*@loopbreak@*/ break;
5349 c2 = cppReader_peekC (pfile);
5354 cppReader_forward (pfile, 1);
5355 cppReader_reserve (pfile, 4);
5356 cppReader_putChar (pfile, c);
5357 cppReader_putChar (pfile, c2);
5359 c3 = cppReader_peekC (pfile);
5361 cppReader_putCharQ (pfile, cppReader_getC (pfile));
5362 cppReader_nullTerminateQ (pfile);
5363 pfile->only_seen_white = 0;
5367 if (cppReader_getBuffer (pfile)->has_escapes)
5369 c = cppReader_getC (pfile);
5372 if (pfile->output_escapes)
5373 cppReader_puts (pfile, "@-", 2);
5374 parse_name (pfile, cppReader_getC (pfile));
5377 else if (is_space [c])
5379 cppReader_reserve (pfile, 2);
5380 if (pfile->output_escapes)
5381 cppReader_putCharQ (pfile, '@');
5382 cppReader_putCharQ (pfile, c);
5390 if (pfile->output_escapes)
5392 cppReader_puts (pfile, "@@", 2);
5398 c2 = cppReader_peekC (pfile);
5401 cppReader_reserve(pfile, 2);
5402 cppReader_putCharQ (pfile, '.');
5403 c = cppReader_getC (pfile);
5407 /* FIXME - misses the case "..\\\n." */
5408 if (c2 == '.' && cpp_peekN (pfile, 1) == '.')
5410 cppReader_reserve(pfile, 4);
5411 cppReader_putCharQ (pfile, '.');
5412 cppReader_putCharQ (pfile, '.');
5413 cppReader_putCharQ (pfile, '.');
5414 cppReader_forward (pfile, 2);
5415 cppReader_nullTerminateQ (pfile);
5416 pfile->only_seen_white = 0;
5422 pfile->only_seen_white = 0;
5424 cppReader_reserve(pfile, 3);
5425 cppReader_putCharQ (pfile, c);
5426 cppReader_putCharQ (pfile, cppReader_getC (pfile));
5427 cppReader_nullTerminateQ (pfile);
5432 c2 = cppReader_peekC (pfile);
5433 if ((c2 == '\'' || c2 == '\"') && !cppReader_isTraditional (pfile))
5435 cppReader_putChar (pfile, c);
5436 c = cppReader_getC (pfile);
5441 case '0': case '1': case '2': case '3': case '4':
5442 case '5': case '6': case '7': case '8': case '9':
5447 cppReader_reserve (pfile, 2);
5448 cppReader_putCharQ (pfile, c);
5450 c = cppReader_peekC (pfile);
5452 /*@loopbreak@*/ break;
5453 if (!is_idchar[c] && c != '.'
5454 && ((c2 != 'e' && c2 != 'E'
5455 && ((c2 != 'p' && c2 != 'P') || cppReader_isC89 (pfile)))
5456 || (c != '+' && c != '-')))
5457 /*@loopbreak@*/ break;
5458 cppReader_forward (pfile, 1);
5462 cppReader_nullTerminateQ (pfile);
5463 pfile->only_seen_white = 0;
5466 case 'b': case 'c': case 'd': case 'h': case 'o':
5467 case 'B': case 'C': case 'D': case 'H': case 'O':
5468 if (opts->chill && cppReader_peekC (pfile) == '\'')
5470 pfile->only_seen_white = 0;
5471 cppReader_reserve (pfile, 2);
5472 cppReader_putCharQ (pfile, c);
5473 cppReader_putCharQ (pfile, '\'');
5474 cppReader_forward (pfile, 1);
5477 c = cppReader_getC (pfile);
5479 goto chill_number_eof;
5482 if (c == '\\' && cppReader_peekC (pfile) == '\n')
5484 cppReader_forward (pfile, 2);
5487 /*@loopbreak@*/ break;
5489 cppReader_putChar (pfile, c);
5493 cppReader_reserve (pfile, 2);
5494 cppReader_putCharQ (pfile, c);
5495 cppReader_nullTerminateQ (pfile);
5500 cppReader_forward (pfile, -1);
5502 cppReader_nullTerminate (pfile);
5509 case 'a': case 'e': case 'f': case 'g': case 'i': case 'j':
5510 case 'k': case 'l': case 'm': case 'n': case 'p': case 'q':
5511 case 'r': case 's': case 't': case 'u': case 'v': case 'w':
5512 case 'x': case 'y': case 'z':
5513 case 'A': case 'E': case 'F': case 'G': case 'I': case 'J':
5514 case 'K': case 'M': case 'N': case 'P': case 'Q': case 'R':
5515 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
5521 size_t before_name_written = cppReader_getWritten (pfile);
5523 parse_name (pfile, c);
5524 pfile->only_seen_white = 0;
5525 if (pfile->no_macro_expand)
5530 ident = pfile->token_buffer + before_name_written;
5531 ident_len = (cppReader_getPWritten (pfile)) - ident;
5533 hp = cppReader_lookupExpand (ident, ident_len, -1);
5540 if (hp->type == T_DISABLED)
5542 if (pfile->output_escapes)
5543 { /* Return "@-IDENT", followed by '\0'. */
5545 cppReader_reserve (pfile, 3);
5546 ident = pfile->token_buffer + before_name_written;
5547 cppReader_adjustWritten (pfile, 2);
5549 for (i = ident_len; i >= 0; i--)
5551 ident[i+2] = ident[i];
5560 /* If macro wants an arglist, verify that a '(' follows.
5561 first skip all whitespace, copying it to the output
5562 after the macro name. Then, if there is no '(',
5563 decide this is not a macro call and leave things that way. */
5565 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
5567 struct parse_marker macro_mark;
5570 while (cppBuffer_isMacro (CPPBUFFER (pfile)))
5572 cppBuffer *next_buf;
5573 cppSkipHspace (pfile);
5574 if (cppReader_peekC (pfile) != EOF)
5576 /*@loopbreak@*/ break;
5579 next_buf = cppBuffer_prevBuffer (cppReader_getBuffer (pfile));
5580 (*cppReader_getBuffer (pfile)->cleanup) (cppReader_getBuffer (pfile), pfile);
5581 CPPBUFFER (pfile) = next_buf;
5584 parseSetMark (¯o_mark, pfile);
5588 cppSkipHspace (pfile);
5589 c = cppReader_peekC (pfile);
5590 is_macro_call = c == '(';
5592 /*@loopbreak@*/ break;
5593 cppReader_forward (pfile, 1);
5598 parseGotoMark (¯o_mark, pfile);
5601 parseClearMark (¯o_mark);
5608 /* This is now known to be a macro call. */
5610 /* it might not actually be a macro. */
5611 if (hp->type != T_MACRO)
5616 cppReader_setWritten (pfile, before_name_written);
5617 special_symbol (hp, pfile);
5618 xbuf_len = cppReader_getWritten (pfile) - before_name_written;
5619 xbuf = (char *) dmalloc (xbuf_len + 1);
5620 cppReader_setWritten (pfile, before_name_written);
5621 memcpy (xbuf, cppReader_getPWritten (pfile), xbuf_len + 1);
5622 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
5626 /* Expand the macro, reading arguments as needed,
5627 and push the expansion on the input stack. */
5628 macroexpand (pfile, hp);
5629 cppReader_setWritten (pfile, before_name_written);
5632 /* An extra "@ " is added to the end of a macro expansion
5633 to prevent accidental token pasting. We prefer to avoid
5634 unneeded extra spaces (for the sake of cpp-using tools like
5635 imake). Here we remove the space if it is safe to do so. */
5637 llassert (pfile->buffer->rlimit != NULL);
5639 if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
5640 && pfile->buffer->rlimit[-2] == '@'
5641 && pfile->buffer->rlimit[-1] == ' ')
5643 int c1 = pfile->buffer->rlimit[-3];
5644 int cl2 = cppBufPeek (cppBuffer_prevBuffer (CPPBUFFER (pfile)));
5646 if (cl2 == EOF || !unsafe_chars ((char) c1, (char) cl2))
5647 pfile->buffer->rlimit -= 2;
5652 case ' ': case '\t': case '\v': case '\r':
5655 cppReader_putChar (pfile, c);
5656 c = cppReader_peekC (pfile);
5657 if (c == EOF || !is_hor_space[c])
5658 /*@loopbreak@*/ break;
5659 cppReader_forward (pfile, 1);
5664 c2 = cppReader_peekC (pfile);
5671 cppReader_putChar (pfile, c);
5672 if (pfile->only_seen_white == 0)
5673 pfile->only_seen_white = 1;
5675 output_line_command (pfile, 1, same_file);
5678 case '(': token = CPP_LPAREN; goto char1;
5679 case ')': token = CPP_RPAREN; goto char1;
5680 case '{': token = CPP_LBRACE; goto char1;
5681 case '}': token = CPP_RBRACE; goto char1;
5682 case ',': token = CPP_COMMA; goto char1;
5683 case ';': token = CPP_SEMICOLON; goto char1;
5689 pfile->only_seen_white = 0;
5690 cppReader_putChar (pfile, c);
5699 /* Parse an identifier starting with C. */
5702 parse_name (cppReader *pfile, int c)
5708 if (c == '\\' && cppReader_peekC (pfile) == '\n')
5710 cppReader_forward (pfile, 2);
5714 cppReader_forward (pfile, -1);
5718 if (c == '$' && cppReader_isPedantic (pfile))
5720 cppReader_pedwarnLit (pfile,
5721 cstring_makeLiteralTemp ("`$' in identifier"));
5724 cppReader_reserve(pfile, 2); /* One more for final NUL. */
5725 cppReader_putCharQ (pfile, c);
5726 c = cppReader_getC (pfile);
5732 cppReader_nullTerminateQ (pfile);
5735 /* The file_name_map structure holds a mapping of file names for a
5736 particular directory. This mapping is read from the file named
5737 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
5738 map filenames on a file system with severe filename restrictions,
5739 such as DOS. The format of the file name map file is just a series
5740 of lines with two tokens on each line. The first token is the name
5741 to map, and the second token is the actual name to use. */
5743 struct file_name_map
5745 struct file_name_map *map_next;
5750 /*@constant observer char *FILE_NAME_MAP_FILE*/
5751 #define FILE_NAME_MAP_FILE "header.gcc"
5753 /* Read a space delimited string of unlimited length from a stdio
5756 static cstring read_filename_string (int ch, FILE *f)
5762 set = alloc = dmalloc (len + 1);
5767 while ((ch = getc (f)) != EOF && ! is_space[ch])
5769 if (set - alloc == size_toInt (len))
5772 alloc = drealloc (alloc, len + 1);
5773 set = alloc + len / 2;
5780 check (ungetc (ch, f) != EOF);
5782 return cstring_fromChars (alloc);
5785 /* This structure holds a linked list of file name maps, one per directory. */
5787 struct file_name_map_list
5789 struct file_name_map_list *map_list_next;
5790 cstring map_list_name;
5791 struct file_name_map *map_list_map;
5794 /* Read the file name map file for DIRNAME. */
5796 static struct file_name_map *
5797 read_name_map (cppReader *pfile, cstring dirname)
5799 struct file_name_map_list *map_list_ptr;
5803 for (map_list_ptr = CPPOPTIONS (pfile)->map_list;
5804 map_list_ptr != NULL;
5805 map_list_ptr = map_list_ptr->map_list_next)
5807 if (cstring_equal (map_list_ptr->map_list_name, dirname))
5809 return map_list_ptr->map_list_map;
5813 map_list_ptr = (struct file_name_map_list *) dmalloc (sizeof (*map_list_ptr));
5814 map_list_ptr->map_list_name = cstring_copy (dirname);
5815 map_list_ptr->map_list_map = NULL;
5817 name = cstring_copy (dirname);
5819 if (cstring_length (dirname) > 0)
5821 name = cstring_appendChar (name, CONNECTCHAR);
5824 name = cstring_concatFree1 (name, cstring_makeLiteralTemp (FILE_NAME_MAP_FILE));
5826 f = fopen (cstring_toCharsSafe (name), "r");
5827 cstring_free (name);
5831 map_list_ptr->map_list_map = NULL;
5837 while ((ch = getc (f)) != EOF)
5840 struct file_name_map *ptr;
5847 from = read_filename_string (ch, f);
5848 while ((ch = getc (f)) != EOF && is_hor_space[ch])
5853 to = read_filename_string (ch, f);
5855 ptr = (struct file_name_map *) dmalloc (sizeof (*ptr));
5856 ptr->map_from = from;
5858 /* Make the real filename absolute. */
5859 if (cstring_length (to) > 1
5860 && osd_isConnectChar (cstring_firstChar (to)))
5866 ptr->map_to = cstring_copy (dirname);
5867 ptr->map_to = cstring_appendChar (ptr->map_to, CONNECTCHAR);
5868 ptr->map_to = cstring_concatFree (ptr->map_to, to);
5871 ptr->map_next = map_list_ptr->map_list_map;
5872 map_list_ptr->map_list_map = ptr;
5874 while ((ch = getc (f)) != '\n')
5878 /*@innerbreak@*/ break;
5883 assertSet (map_list_ptr->map_list_map);
5884 check (fclose (f) == 0);
5887 map_list_ptr->map_list_next = pfile->opts->map_list;
5888 pfile->opts->map_list = map_list_ptr;
5890 return map_list_ptr->map_list_map;
5893 /* Try to open include file FILENAME. SEARCHPTR is the directory
5894 being tried from the include file search path. This function maps
5895 filenames on file systems based on information read by
5899 open_include_file (cppReader *pfile,
5901 struct file_name_list *searchptr)
5903 char *filename = cstring_toCharsSafe (fname);
5904 struct file_name_map *map;
5908 cstring_markOwned (fname);
5910 cpp_setLocation (pfile);
5912 if (context_getFlag (FLG_NEVERINCLUDE))
5914 if (isHeaderFile (fname))
5916 return SKIP_INCLUDE;
5920 if ((searchptr != NULL) && ! searchptr->got_name_map)
5922 searchptr->name_map = read_name_map (pfile,
5923 !cstring_isEmpty (searchptr->fname)
5924 ? searchptr->fname :
5925 cstring_makeLiteralTemp ("."));
5926 searchptr->got_name_map = 1;
5929 /* First check the mapping for the directory we are using. */
5931 if ((searchptr != NULL)
5932 && (searchptr->name_map != NULL))
5936 if (!cstring_isEmpty (searchptr->fname))
5938 from += cstring_length (searchptr->fname) + 1;
5941 for (map = searchptr->name_map;
5943 map = map->map_next)
5945 if (cstring_equal (map->map_from, cstring_fromChars (from)))
5948 ** Found a match. Check if the file should be skipped
5951 if (cpp_skipIncludeFile (map->map_to))
5953 return SKIP_INCLUDE;
5957 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
5964 ** Try to find a mapping file for the particular directory we are
5965 ** looking in. Thus #include <sys/types.h> will look up sys/types.h
5966 ** in /usr/include/header.gcc and look up types.h in
5967 ** /usr/include/sys/header.gcc.
5970 p = strrchr (filename, CONNECTCHAR);
5977 if ((searchptr != NULL)
5978 && (cstring_isDefined (searchptr->fname))
5979 && (cstring_length (searchptr->fname) == p - filename)
5980 && !strncmp (cstring_toCharsSafe (searchptr->fname),
5982 size_fromInt (p - filename)))
5984 /* filename is in SEARCHPTR, which we've already checked. */
5986 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
5988 return SKIP_INCLUDE;
5992 return cpp_openIncludeFile (filename);
5998 dir = mstring_copy (".");
6003 dir = (char *) dmalloc (size_fromInt (p - filename + 1));
6004 memcpy (dir, filename, size_fromInt (p - filename));
6005 dir[p - filename] = '\0';
6009 for (map = read_name_map (pfile, cstring_fromChars (dir));
6011 map = map->map_next)
6013 if (cstring_equal (map->map_from, cstring_fromChars (from)))
6017 if (cpp_skipIncludeFile (map->map_to))
6019 return SKIP_INCLUDE;
6023 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
6030 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
6032 return SKIP_INCLUDE;
6036 return cpp_openIncludeFile (filename);
6040 /* Process the contents of include file FNAME, already open on descriptor F,
6042 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
6043 "system" include directories (as decided by the `is_system_include'
6045 DIRPTR is the link in the dir path through which this file was found,
6046 or 0 if the file name was absolute or via the current directory.
6047 Return 1 on success, 0 on failure.
6049 The caller is responsible for the cppReader_pushBuffer. */
6052 finclude (cppReader *pfile, int f,
6054 bool system_header_p,
6055 /*@dependent@*/ struct file_name_list *dirptr)
6061 cppBuffer *fp; /* For input stack frame */
6063 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
6065 cppReader_perrorWithName (pfile, fname);
6066 check (close (f) == 0);
6067 (void) cppReader_popBuffer (pfile);
6073 fp = cppReader_getBuffer (pfile);
6075 /*@-temptrans@*/ /* fname shouldn't really be temp */
6076 fp->nominal_fname = fp->fname = fname;
6080 fp->system_header_p = system_header_p;
6083 fp->cleanup = cppReader_fileCleanup;
6085 if (S_ISREG (st_mode))
6088 fp->buf = (char *) dmalloc (st_size + 2);
6089 fp->alimit = fp->buf + st_size + 2;
6092 /* Read the file contents, knowing that st_size is an upper bound
6093 on the number of bytes we can read. */
6094 length = safe_read (f, fp->buf, size_toInt (st_size));
6095 fp->rlimit = fp->buf + length;
6096 if (length < 0) goto nope;
6098 else if (S_ISDIR (st_mode))
6100 cppReader_error (pfile,
6101 message ("directory `%s' specified in #include", fname));
6102 check (close (f) == 0);
6108 ** Cannot count its file size before reading.
6109 ** First read the entire file into heap and
6110 ** copy them into buffer on stack.
6113 size_t bsize = 2000;
6118 fp->buf = (char *) dmalloc (bsize + 2);
6121 i = safe_read (f, fp->buf + st_size, size_toInt (bsize - st_size));
6124 goto nope; /* error! */
6127 if (st_size != bsize)
6129 break; /* End of file */
6133 fp->buf = (char *) drealloc (fp->buf, bsize + 2);
6137 length = size_toInt (st_size);
6140 if ((length > 0 && fp->buf[length - 1] != '\n')
6141 /* Backslash-newline at end is not good enough. */
6142 || (length > 1 && fp->buf[length - 2] == '\\')) {
6143 fp->buf[length++] = '\n';
6146 fp->buf[length] = '\0';
6147 fp->rlimit = fp->buf + length;
6150 /* Close descriptor now, so nesting does not use lots of descriptors. */
6151 check (close (f) == 0);
6153 /* Must do this before calling trigraph_pcp, so that the correct file name
6154 will be printed in warning messages. */
6156 pfile->input_stack_listing_current = 0;
6161 cppReader_perrorWithName (pfile, fname);
6162 check (close (f) == 0);
6168 cppReader_init (cppReader *pfile)
6170 memset ((char *) pfile, 0, sizeof (*pfile));
6172 pfile->get_token = cppGetToken;
6173 pfile->token_buffer_size = 200;
6174 pfile->token_buffer = (char *) dmalloc (pfile->token_buffer_size);
6175 pfile->all_include_files = NULL;
6179 cppReader_setWritten (pfile, 0);
6181 pfile->system_include_depth = 0;
6182 pfile->max_include_len = 0;
6183 pfile->timebuf = NULL;
6184 pfile->only_seen_white = 1;
6186 pfile->buffer = cppReader_nullBuffer (pfile);
6190 cppReader_finish (/*@unused@*/ cppReader *pfile)
6195 /* Free resources used by PFILE.
6196 This is the cppReader 'finalizer' or 'destructor' (in C++ terminology). */
6199 cppCleanup (cppReader *pfile)
6201 while (CPPBUFFER (pfile) != cppReader_nullBuffer (pfile))
6203 (void) cppReader_popBuffer (pfile);
6206 if (pfile->token_buffer != NULL)
6208 sfree (pfile->token_buffer);
6209 pfile->token_buffer = NULL;
6212 while (pfile->if_stack != NULL)
6214 cppIfStackFrame *temp = pfile->if_stack;
6215 pfile->if_stack = temp->next;
6219 while (pfile->all_include_files != NULL)
6221 struct file_name_list *temp = pfile->all_include_files;
6222 pfile->all_include_files = temp->next;
6223 /*@-dependenttrans@*/
6224 cstring_free (temp->fname);
6225 /*@=dependenttrans@*/
6229 cppReader_hashCleanup ();
6233 ** Get the file-mode and data size of the file open on FD
6234 ** and store them in *MODE_POINTER and *SIZE_POINTER.
6238 file_size_and_mode (int fd, mode_t *mode_pointer, size_t *size_pointer)
6242 if (fstat (fd, &sbuf) < 0) {
6246 if (mode_pointer != NULL)
6248 *mode_pointer = sbuf.st_mode;
6251 if (size_pointer != NULL)
6253 *size_pointer = (size_t) sbuf.st_size;
6259 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
6260 retrying if necessary. Return a negative value if an error occurs,
6261 otherwise return the actual number of bytes read,
6262 which must be LEN unless end-of-file was reached. */
6264 static int safe_read (int desc, char *ptr, int len)
6271 /*@-compdef@*/ /* ptr is an out parameter */
6272 int nchars = _read (desc, ptr, (unsigned) left);
6275 ssize_t nchars = read (desc, ptr, size_fromInt (left));
6284 return (int) nchars;
6298 /* Initialize PMARK to remember the current position of PFILE. */
6301 parseSetMark (struct parse_marker *pmark, cppReader *pfile)
6303 cppBuffer *pbuf = cppReader_getBuffer (pfile);
6305 pmark->next = pbuf->marks;
6307 pbuf->marks = pmark;
6311 pmark->position = pbuf->cur - pbuf->buf;
6314 /* Cleanup PMARK - we no longer need it. */
6316 void parseClearMark (struct parse_marker *pmark)
6318 struct parse_marker **pp = &pmark->buf->marks;
6320 for (; ; pp = &(*pp)->next)
6322 llassert (*pp != NULL);
6323 if (*pp == pmark) break;
6329 /* Backup the current position of PFILE to that saved in PMARK. */
6332 parseGotoMark (struct parse_marker *pmark, cppReader *pfile)
6334 cppBuffer *pbuf = cppReader_getBuffer (pfile);
6336 if (pbuf != pmark->buf)
6338 cpp_setLocation (pfile);
6339 llfatalbug (cstring_makeLiteral ("Internal error parseGotoMark"));
6342 llassert (pbuf->buf != NULL);
6343 pbuf->cur = pbuf->buf + pmark->position;
6346 /* Reset PMARK to point to the current position of PFILE. (Same
6347 as parseClearMark (PMARK), parseSetMark (PMARK, PFILE) but faster. */
6350 parseMoveMark (struct parse_marker *pmark, cppReader *pfile)
6352 cppBuffer *pbuf = cppReader_getBuffer (pfile);
6354 if (pbuf != pmark->buf)
6356 cpp_setLocation (pfile);
6357 llfatalerror (cstring_makeLiteral ("Internal error parseMoveMark"));
6360 pmark->position = pbuf->cur - pbuf->buf;
6363 void cppReader_initializeReader (cppReader *pfile)
6365 struct cppOptions *opts = CPPOPTIONS (pfile);
6368 /* The code looks at the defaults through this pointer, rather than through
6369 the constant structure above. This pointer gets changed if an environment
6370 variable specifies other defaults. */
6372 struct default_include *include_defaults = include_defaults_array;
6374 /* Add dirs from CPATH after dirs from -I. */
6375 /* There seems to be confusion about what CPATH should do,
6376 so for the moment it is not documented. */
6377 /* Some people say that CPATH should replace the standard include dirs,
6378 but that seems pointless: it comes before them, so it overrides them
6381 xp = (char *) getenv ("CPATH");
6383 if (xp != 0 && ! opts->no_standard_includes)
6385 path_include (pfile, xp);
6388 /* Now that dollars_in_ident is known, initialize is_idchar. */
6389 initialize_char_syntax (opts);
6391 /* CppReader_Install __LINE__, etc. Must follow initialize_char_syntax
6392 and option processing. */
6394 initialize_builtins (pfile);
6396 /* Do standard #defines and assertions
6397 that identify system and machine type. */
6399 if (!opts->inhibit_predefs) {
6400 char *p = (char *) dmalloc (strlen (predefs) + 1);
6401 strcpy (p, predefs);
6407 while (*p == ' ' || *p == '\t')
6412 /* Handle -D options. */
6413 if (p[0] == '-' && p[1] == 'D')
6417 while (*p && *p != ' ' && *p != '\t')
6427 if (opts->debug_output)
6429 output_line_command (pfile, 0, same_file);
6432 cppReader_define (pfile, q);
6434 while (*p == ' ' || *p == '\t')
6448 opts->done_initializing = 1;
6450 { /* Read the appropriate environment variable and if it exists
6451 replace include_defaults with the listed path. */
6455 int win32_buf_size = 0; /* memory we need to allocate */
6458 if (opts->cplusplus)
6460 epath = getenv ("CPLUS_INCLUDE_PATH");
6464 epath = getenv ("C_INCLUDE_PATH");
6468 ** If the environment var for this language is set,
6469 ** add to the default list of include directories.
6472 if (epath != NULL) {
6473 char *nstore = (char *) dmalloc (strlen (epath) + 2);
6475 char *startp, *endp;
6478 /* if we have a posix path list, convert to win32 path list */
6479 if (cygwin32_posix_path_list_p (epath))
6481 win32_buf_size = cygwin32_posix_to_win32_path_list_buf_size (epath);
6482 win32epath = (char *) dmalloc /*@i4@*/ (win32_buf_size);
6483 cygwin32_posix_to_win32_path_list (epath, win32epath);
6487 for (num_dirs = 1, startp = epath; *startp; startp++)
6489 if (*startp == PATH_SEPARATOR)
6495 = (struct default_include *) dmalloc ((num_dirs
6496 * sizeof (struct default_include))
6497 + sizeof (include_defaults_array));
6500 startp = endp = epath;
6503 /* Handle cases like c:/usr/lib:d:/gcc/lib */
6504 if ((*endp == PATH_SEPARATOR) || *endp == 0)
6506 strncpy (nstore, startp, size_fromInt (endp - startp));
6509 strcpy (nstore, ".");
6513 nstore[endp-startp] = '\0';
6516 include_defaults[num_dirs].fname = cstring_fromCharsNew (nstore);
6517 include_defaults[num_dirs].cplusplus = opts->cplusplus;
6518 include_defaults[num_dirs].cxx_aware = 1;
6525 endp = startp = endp + 1;
6532 /* Put the usual defaults back in at the end. */
6533 memcpy ((char *) &include_defaults[num_dirs],
6534 (char *) include_defaults_array,
6535 sizeof (include_defaults_array));
6541 cppReader_appendIncludeChain (pfile, opts->before_system,
6542 opts->last_before_system);
6543 opts->first_system_include = opts->before_system;
6545 /* Unless -fnostdinc,
6546 tack on the standard include file dirs to the specified list */
6547 if (!opts->no_standard_includes) {
6548 struct default_include *p = include_defaults;
6549 char *specd_prefix = opts->include_prefix;
6550 char *default_prefix = mstring_copy (GCC_INCLUDE_DIR);
6551 int default_len = 0;
6553 /* Remove the `include' from /usr/local/lib/gcc.../include. */
6554 if (default_prefix != NULL) {
6555 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
6556 default_len = strlen (default_prefix) - 7;
6557 default_prefix[default_len] = 0;
6561 /* Search "translated" versions of GNU directories.
6562 These have /usr/local/lib/gcc... replaced by specd_prefix. */
6563 if (specd_prefix != 0 && default_len != 0)
6564 for (p = include_defaults; p->fname != NULL; p++) {
6565 /* Some standard dirs are only for C++. */
6567 || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
6568 /* Does this dir start with the prefix? */
6569 if (!strncmp (cstring_toCharsSafe (p->fname), default_prefix,
6570 size_fromInt (default_len)))
6572 /* Yes; change prefix and add to search list. */
6573 struct file_name_list *nlist
6574 = (struct file_name_list *) dmalloc (sizeof (*nlist));
6575 size_t this_len = strlen (specd_prefix) + cstring_length (p->fname) - default_len;
6576 char *str = (char *) dmalloc (this_len + 1);
6577 strcpy (str, specd_prefix);
6578 strcat (str, cstring_toCharsSafe (p->fname) + default_len);
6581 nlist->fname = cstring_fromChars (str);
6582 nlist->control_macro = 0;
6583 nlist->c_system_include_path = !p->cxx_aware;
6584 nlist->got_name_map = 0;
6586 cppReader_addIncludeChain (pfile, nlist);
6587 if (opts->first_system_include == 0)
6589 opts->first_system_include = nlist;
6595 /* Search ordinary names for GNU include directories. */
6597 for (p = include_defaults; p->fname != NULL; p++)
6599 /* Some standard dirs are only for C++. */
6601 || (opts->cplusplus && !opts->no_standard_cplusplus_includes))
6603 struct file_name_list *nlist
6604 = (struct file_name_list *) dmalloc (sizeof (*nlist));
6605 nlist->control_macro = 0;
6606 nlist->c_system_include_path = !p->cxx_aware;
6607 nlist->fname = p->fname;
6608 nlist->got_name_map = 0;
6611 cppReader_addIncludeChain (pfile, nlist);
6613 if (opts->first_system_include == 0)
6615 opts->first_system_include = nlist;
6619 sfree (default_prefix);
6622 /* Tack the after_include chain at the end of the include chain. */
6623 cppReader_appendIncludeChain (pfile, opts->after_include,
6624 opts->last_after_include);
6626 if (opts->first_system_include == 0)
6628 opts->first_system_include = opts->after_include;
6631 /* With -v, print the list of dirs to search. */
6632 if (opts->verbose) {
6633 struct file_name_list *p;
6634 fprintf (stderr, "#include \"...\" search starts here:\n");
6636 for (p = opts->include; p != NULL; p = p->next) {
6637 if (p == opts->first_bracket_include)
6638 fprintf (stderr, "#include <...> search starts here:\n");
6640 fprintf (stderr, " %s\n", cstring_toCharsSafe (p->fname));
6642 fprintf (stderr, "End of search list.\n");
6646 int cppReader_startProcess (cppReader *pfile, cstring fname)
6650 struct cppOptions *opts = CPPOPTIONS (pfile);
6652 fp = cppReader_pushBuffer (pfile, NULL, 0);
6659 if (opts->in_fname == NULL)
6661 opts->in_fname = cstring_makeLiteralTemp ("");
6664 fp->fname = opts->in_fname;
6665 fp->nominal_fname = fp->fname;
6668 /* Copy the entire contents of the main input file into
6669 the stacked input buffer previously allocated for it. */
6671 if (cstring_isEmpty (fname))
6673 fname = cstring_makeLiteralTemp ("");
6676 else if ((f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666)) < 0)
6678 cppReader_pfatalWithName (pfile, fname);
6685 if (finclude (pfile, f, fname, 0, NULL))
6687 output_line_command (pfile, 0, same_file);
6693 static /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_getBuffer (cppReader *pfile)
6695 return pfile->buffer;
6698 /*@exposed@*/ cppBuffer *cppReader_getBufferSafe (cppReader *pfile)
6700 llassert (pfile->buffer != NULL);
6701 return pfile->buffer;
6704 /*@exposed@*/ char *cppLineBase (cppBuffer *buf)
6706 llassert (buf->buf != NULL);
6707 return (buf->buf + buf->line_base);
6710 int cppBufPeek (cppBuffer *buf)
6712 if (buf->cur == NULL || buf->rlimit == NULL) {
6716 if (buf->cur < buf->rlimit) {
6723 bool cppBuffer_isMacro (cppBuffer *buf)
6727 return (buf->cleanup == cppReader_macroCleanup);
6734 ** Returns true if the macro should be checked, false
6735 ** if it should be expanded normally.
6738 static bool notparseable = FALSE; /* preceeded by @notparseable@ */
6739 static bool notfunction = FALSE; /* preceeded by @notfunction@ */
6740 static bool expectiter = FALSE; /* preceeded by @iter@ */
6741 static bool expectenditer = FALSE; /* second after @iter@ */
6742 static bool expectfunction = FALSE; /* preceeded by @function@ */
6743 static bool expectconstant = FALSE; /* preceeded by @constant@ */
6744 static bool expectmacro = FALSE; /* preceeded by notfunction or notparseable */
6746 static void cpp_setLocation (cppReader *pfile)
6751 if (pfile->buffer != NULL)
6753 if (cstring_isDefined (cppReader_getBuffer (pfile)->nominal_fname))
6755 cstring fname = cppReader_getBuffer (pfile)->nominal_fname;
6757 if (fileTable_exists (context_fileTable (), fname))
6759 fid = fileTable_lookup (context_fileTable (), fname);
6763 fid = fileTable_lookup (context_fileTable (),
6764 cppReader_getBuffer (pfile)->fname);
6769 fid = fileTable_lookup (context_fileTable (),
6770 cppReader_getBuffer (pfile)->fname);
6773 line = cppReader_getBuffer (pfile)->lineno;
6774 fileloc_free (g_currentloc);
6775 g_currentloc = fileloc_create (fid, line, 1);
6779 fileloc_free (g_currentloc);
6780 g_currentloc = fileloc_createBuiltin ();
6784 static bool cpp_shouldCheckMacro (cppReader *pfile, char *p) /*@*/
6786 bool checkmacro = FALSE;
6787 bool hasParams = FALSE;
6788 bool noexpand = FALSE;
6792 cpp_setLocation (pfile);
6794 DPRINTF (("Should check macro? %s", p));
6796 if (expectiter || expectconstant || expectenditer)
6801 expectenditer = TRUE;
6806 expectconstant = FALSE;
6807 expectenditer = FALSE;
6810 if (notfunction || notparseable)
6812 notfunction = FALSE;
6813 notparseable = FALSE;
6822 llassert (*p == '#');
6825 while (*p == ' ' || *p == '\t')
6830 llassert (*p == 'd'); /* define starts */
6834 while (*p == ' ' || *p == '\t')
6839 sname = cstring_fromChars (p);
6840 DPRINTF (("Check macro: %s", sname));
6842 while (((c = *p) != ' ')
6843 && c != '\0' && c != '('
6844 && c != '\t' && c != '\\' && c != '\n'
6850 hasParams = (c == '(');
6856 notparseable = FALSE;
6858 else if (notfunction || fileloc_isStandardLib (g_currentloc))
6860 DPRINTF (("Clear notfunction"));
6861 notfunction = FALSE;
6876 if (usymtab_existsReal (sname))
6878 uentry ue = usymtab_lookup (sname);
6880 DPRINTF (("Lookup macro: %s", uentry_unparse (ue)));
6882 if (fileloc_isPreproc (uentry_whereLast (ue)))
6888 if (uentry_isSpecified (ue))
6890 checkmacro = context_getFlag (FLG_SPECMACROS);
6896 checkmacro = context_getFlag (FLG_LIBMACROS)
6897 || context_getFlag (FLG_FCNMACROS);
6905 DPRINTF (("Macro doesn't exist: %s", bool_unparse (checkmacro)));
6907 if (fileloc_isSystemFile (g_currentloc)
6908 && context_getFlag (FLG_SYSTEMDIREXPAND))
6910 ; /* don't check this macro */
6911 DPRINTF (("Don't check 1"));
6919 DPRINTF (("Has params..."));
6921 if (context_getFlag (FLG_FCNMACROS))
6923 if (usymtab_exists (sname))
6926 ** only get here is macro is redefined
6927 ** error reported elsewhere
6930 DPRINTF (("It exists!"));
6935 ** We make it a forward function, since it might be declared elsewhere.
6936 ** After all headers have been processed, we should check the forward
6940 fileloc loc = fileloc_makePreproc (g_currentloc);
6942 /* the line is off-by-one, since the newline was already read */
6947 expectfunction = FALSE;
6950 le = uentry_makeForwardFunction (sname,
6951 typeId_invalid, loc);
6957 /* Do not define here! */
6959 (void) usymtab_addEntry (le);
6963 DPRINTF (("Check: TRUE"));
6967 DPRINTF (("Flag FCN_MACROS not set!"));
6972 DPRINTF (("No params"));
6974 if (context_getFlag (FLG_CONSTMACROS))
6976 bool nocontent = FALSE;
6989 ** Check if there is nothing after the define.
6992 while ((*rest) != '\0' && isspace (*rest))
6999 nocontent = TRUE; /* empty macro, don't check */
7004 if (usymtab_exists (sname))
7010 fileloc loc = fileloc_makePreproc (g_currentloc);
7011 DPRINTF (("Make constant: %s", sname));
7012 le = uentry_makeConstant (sname,
7013 ctype_unknown, loc);
7014 (void) usymtab_addEntry (le);
7017 checkmacro = !nocontent;
7022 if (checkmacro && usymtab_existsType (sname))
7024 DPRINTF (("Making false..."));
7026 ppllerror (message ("Specified type implemented as macro: %s", sname));
7036 if (usymtab_exists (sname))
7038 uentry ue = usymtab_lookupExpose (sname);
7039 fileloc tloc = fileloc_makePreproc (g_currentloc);
7041 uentry_setDefined (ue, tloc);
7042 fileloc_free (tloc);
7043 uentry_setUsed (ue, fileloc_undefined);
7047 fileloc tloc = fileloc_makePreproc (g_currentloc);
7048 uentry ue = uentry_makeExpandedMacro (sname, tloc);
7049 DPRINTF (("Make expanded macro: %s", sname));
7050 DPRINTF (("Not in symbol table: %s", sname));
7052 (void) usymtab_addGlobalEntry (ue);
7053 fileloc_free (tloc);
7058 DPRINTF (("Returning: %s", bool_unparse (checkmacro)));
7062 static enum cpp_token
7063 cpp_handleComment (cppReader *pfile, struct parse_marker *smark)
7065 cppBuffer *pbuf = cppReader_getBuffer (pfile);
7068 bool eliminateComment = FALSE;
7070 llassert (pbuf->buf != NULL);
7072 start = pbuf->buf + smark->position;
7074 llassert (pbuf->cur != NULL);
7075 len = pbuf->cur - start;
7078 && start[1] == context_getCommentMarkerChar ())
7082 char *scomment = start + 2;
7084 start[0] = BEFORE_COMMENT_MARKER[0];
7085 start[1] = BEFORE_COMMENT_MARKER[1];
7087 llassert (start[len - 2] == '*');
7088 start[len - 2] = AFTER_COMMENT_MARKER[0];
7090 llassert (start[len - 1] == '/');
7091 start[len - 1] = AFTER_COMMENT_MARKER[1];
7093 cppReader_reserve(pfile, size_fromInt (1 + len));
7094 cppReader_putCharQ (pfile, c);
7096 cpp_setLocation (pfile);
7098 if (mstring_equalPrefix (scomment, "ignore"))
7100 if (!context_getFlag (FLG_NOCOMMENTS))
7102 context_enterSuppressRegion ();
7105 else if (mstring_equalPrefix (scomment, "end"))
7107 if (!context_getFlag (FLG_NOCOMMENTS))
7109 context_exitSuppressRegion ();
7112 else if (mstring_equalPrefix (scomment, "notparseable"))
7114 notparseable = TRUE;
7116 eliminateComment = TRUE;
7118 else if (mstring_equalPrefix (scomment, "notfunction"))
7122 eliminateComment = TRUE;
7124 else if (mstring_equalPrefix (scomment, "iter"))
7128 else if (mstring_equalPrefix (scomment, "function"))
7130 expectfunction = TRUE;
7132 else if (mstring_equalPrefix (scomment, "constant"))
7134 expectconstant = TRUE;
7138 char sChar = *scomment;
7144 char *rest = scomment + 1;
7146 if (mstring_equalPrefix (rest, "commentchar"))
7148 eliminateComment = TRUE;
7152 ppllerror (cstring_makeLiteral
7153 ("Cannot restore commentchar"));
7157 char *next = scomment + 12; /* strlen commentchar = 12 */
7159 if (*next != ' ' && *next != '\t' && *next != '\n')
7163 ("Syntactic commentchar comment is not followed by a "
7164 "whitespace character: %c",
7169 char cchar = *(next + 1);
7174 (cstring_makeLiteral
7175 ("Cannot set commentchar to NUL"));
7179 context_setCommentMarkerChar (cchar);
7180 /* setComment = TRUE; */
7185 else if (mstring_equalPrefix (rest, "namechecks"))
7187 context_fileSetFlag (FLG_NAMECHECKS,
7188 ynm_fromCodeChar (sChar));
7190 else if (mstring_equalPrefix (rest, "macroredef"))
7192 context_fileSetFlag (FLG_MACROREDEF,
7193 ynm_fromCodeChar (sChar));
7195 else if (mstring_equalPrefix (rest, "usevarargs"))
7197 context_fileSetFlag (FLG_USEVARARGS,
7198 ynm_fromCodeChar (sChar));
7200 else if (mstring_equalPrefix (rest, "nextlinemacros"))
7202 context_fileSetFlag (FLG_MACRONEXTLINE,
7203 ynm_fromCodeChar (sChar));
7205 else if (mstring_equalPrefix (rest, "allmacros")
7206 || mstring_equalPrefix (rest, "fcnmacros")
7207 || mstring_equalPrefix (rest, "constmacros"))
7211 if (mstring_equalPrefix (rest, "allmacros"))
7215 else if (mstring_equalPrefix (rest, "fcnmacros"))
7221 llassert (mstring_equalPrefix (rest, "constmacros"));
7222 fl = FLG_CONSTMACROS;
7226 context_fileSetFlag (fl, ynm_fromCodeChar (sChar));
7227 notfunction = FALSE;
7240 if (eliminateComment)
7245 /* Replaces comment char's in start with spaces */
7247 for (i = 2; i < len - 2; i++)
7249 if (start[i] == BEFORE_COMMENT_MARKER[0]
7250 || start[i] == BEFORE_COMMENT_MARKER[1]
7251 || start[i] == context_getCommentMarkerChar ())
7257 cppReader_putStrN (pfile, start, size_fromInt (len));
7258 parseClearMark (smark);
7268 ** Output the comment as all spaces so line/column
7269 ** in output file is still correct.
7273 cstring lintcomment = cstring_undefined;
7275 if (context_getFlag (FLG_LINTCOMMENTS))
7277 if (mstring_equalPrefix (start, "*NOTREACHED*/"))
7279 lintcomment = cstring_makeLiteralTemp ("l_notreach");
7281 else if (mstring_equalPrefix (start, "*PRINTFLIKE*/"))
7283 lintcomment = cstring_makeLiteralTemp ("l_printfli");
7285 else if (mstring_equalPrefix (start, "*FALLTHROUGH*/"))
7287 lintcomment = cstring_makeLiteralTemp ("l_fallthrou");
7289 else if (mstring_equalPrefix (start, "*ARGSUSED*/"))
7291 lintcomment = cstring_makeLiteralTemp ("l_argsus");
7293 else if (mstring_equalPrefix (start, "*FALLTHRU*/"))
7295 lintcomment = cstring_makeLiteralTemp ("l_fallth");
7299 lintcomment = cstring_undefined;
7304 lintcomment = cstring_undefined;
7307 if (cstring_isDefined (lintcomment))
7309 c = BEFORE_COMMENT_MARKER[0];
7310 start[0] = BEFORE_COMMENT_MARKER[1];
7312 llassert (cstring_length (lintcomment) == len - 3);
7314 for (i = 1; i < len - 2; i++)
7316 start[i] = cstring_getChar (lintcomment, i);
7319 start[len - 2] = AFTER_COMMENT_MARKER[0];
7320 start[len - 1] = AFTER_COMMENT_MARKER[1];
7324 /* Replaces char's in start with spaces */
7325 for (i = 0; i < len; i++)
7329 && start[i + 1] == '*') {
7332 message ("Start comment inside comment"));
7335 if (start[i] != '\n')
7342 cppReader_reserve (pfile, size_fromInt (1 + len));
7343 cppReader_putCharQ (pfile, c);
7344 cppReader_putStrN (pfile, start, size_fromInt (len));
7345 parseClearMark (smark);
7351 static int cpp_openIncludeFile (char *filename)
7353 int res = open (filename, O_RDONLY, 0666);
7356 && !fileTable_exists (context_fileTable (),
7357 cstring_fromChars (filename)))
7359 DPRINTF (("Add header: %s", filename));
7360 (void) fileTable_addHeaderFile (context_fileTable (),
7361 cstring_fromChars (filename));
7367 static bool cpp_skipIncludeFile (cstring fname)
7369 if (context_isSystemDir (fname))
7371 DPRINTF (("System dir: %s", fname));
7373 if (lcllib_isSkipHeader (fname))
7375 DPRINTF (("Skip include TRUE: %s", fname));
7379 if (context_getFlag (FLG_SKIPSYSHEADERS))
7381 DPRINTF (("Skip include TRUE: %s", fname));
7386 if (context_getFlag (FLG_SINGLEINCLUDE))
7388 fname = cstring_fromChars (removePreDirs (cstring_toCharsSafe (fname)));
7391 cstring_replaceAll (fname, '\\', '/');
7394 if (fileTable_exists (context_fileTable (), fname))
7396 DPRINTF (("Skip include TRUE: %s", fname));
7401 DPRINTF (("Skip include FALSE: %s", fname));
7405 static int cpp_peekN (cppReader *pfile, int n)
7407 cppBuffer *buf = cppReader_getBuffer (pfile);
7409 llassert (buf->cur != NULL);
7411 return (buf->rlimit - buf->cur >= (n)
7416 cppBuffer *cppBuffer_prevBuffer (cppBuffer *buf)
7421 void cppBuffer_forward (cppBuffer *buf, int n)
7423 llassert (buf->cur != NULL);