2 ** Splint - annotation-assisted static program checker
3 ** Copyright (C) 1994-2003 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 splint: info@splint.org
21 ** To report a bug: splint-bug@splint.org
22 ** For more information: http://www.splint.org
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! */
53 * - OS2 drive specs like WIN32
54 * - Includes for IBMs OS/2 compiler
65 # if !(defined (WIN32) || defined (OS2) && defined (__IBMC__))
68 # include <sys/types.h>
69 # include <sys/stat.h>
71 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
73 # include <sys/utime.h> /* for __DATE__ and __TIME__ */
78 ** evans 2002-07-03: exception for WATCOM 10.6 compiler suggest by Adam Clarke
80 # if !defined (USG) && !defined (__WATCOMC__)
81 # include <time.h> /* Reported by Paul Smith */
82 # include <sys/time.h>
83 # include <sys/resource.h>
85 # include <sys/times.h>
90 # endif /* not WIN32 */
92 /* This defines "errno" properly for VMS, and gives us EACCES. */
95 # include "splintMacros.nf"
99 # include "cpperror.h"
100 # include "cpphash.h"
102 # include "version.h"
107 ** This is really kludgey code...
113 /* Warnings for using sprintf - suppress them all for now... */
114 /*@-bufferoverflowhigh@*/
117 #define NO_SHORTNAMES
125 /*@constant int IMPORT_FOUND@*/
126 # define IMPORT_FOUND -2
128 /*@constant int SKIP_INCLUDE@*/
129 # define SKIP_INCLUDE IMPORT_FOUND
131 /*@constant unused int IMPORT_NOT_FOUND@*/
132 # define IMPORT_NOT_FOUND -1
135 /*@constant unused int STDC_VALUE@*/
139 /* By default, colon separates directories in a path. */
140 #ifndef PATH_SEPARATOR
141 /*@constant char PATH_SEPARATOR@*/
142 #define PATH_SEPARATOR ':'
145 static void parse_name (cppReader *, int);
147 static int cpp_openIncludeFile (char *p_filename)
148 /*@modifies fileSystem @*/ ;
150 static void cpp_setLocation (cppReader *p_pfile)
151 /*@modifies g_currentloc@*/ ;
153 static enum cpp_token cpp_handleComment (cppReader *p_pfile,
154 struct parse_marker *p_smark)
155 /*@modifies p_pfile, p_smark@*/;
157 static bool cpp_shouldCheckMacro (cppReader *p_pfile, char *p_p) /*@modifies p_p@*/ ;
159 static size_t cppReader_checkMacroNameLoc (fileloc p_loc, char *p_symname, cstring p_usage) ;
161 static bool cpp_skipIncludeFile (cstring p_fname) /*@*/ ;
167 /* Symbols to predefine. */
169 #ifdef CPP_PREDEFINES
170 static /*@observer@*/ char *predefs = CPP_PREDEFINES;
172 static /*@observer@*/ char *predefs = "";
175 /* We let tm.h override the types used here, to handle trivial differences
176 such as the choice of unsigned int or long unsigned int for size_t.
177 When machines start needing nontrivial differences in the size type,
178 it would be best to do something here to figure out automatically
179 from other information what type to use. */
181 /* The string value for __SIZE_TYPE__. */
184 /*@constant observer char *SIZE_TYPE@*/
185 #define SIZE_TYPE "long unsigned int"
188 /* The string value for __PTRDIFF_TYPE__. */
191 /*@constant observer char *PTRDIFF_TYPE@*/
192 #define PTRDIFF_TYPE "long int"
195 /* The string value for __WCHAR_TYPE__. */
198 /*@constant observer char *WCHAR_TYPE@*/
199 #define WCHAR_TYPE "int"
202 /* The string value for __USER_LABEL_PREFIX__ */
204 #ifndef USER_LABEL_PREFIX
205 /*@constant observer char *USER_LABEL_PREFIX@*/
206 #define USER_LABEL_PREFIX ""
209 /* The string value for __REGISTER_PREFIX__ */
211 #ifndef REGISTER_PREFIX
212 /*@constant observer char *REGISTER_PREFIX@*/
213 #define REGISTER_PREFIX ""
216 /* table to tell if char can be part of a C identifier. */
217 static bool is_idchar[256];
218 /* table to tell if char can be first char of a c identifier. */
219 static bool is_idstart[256];
220 /* table to tell if c is horizontal space. */
221 static bool is_hor_space[256];
222 /* table to tell if c is horizontal or vertical space. */
223 static bool is_space[256];
225 static /*@exposed@*/ /*@null@*/ cppBuffer *
226 cppReader_getBuffer (/*@special@*/ cppReader *p_pfile)
227 /*@uses p_pfile->buffer@*/
228 /*@modifies nothing@*/ ;
231 # define SKIP_WHITE_SPACE(p) do { /*@access cstring@*/ while (is_hor_space[(int) *(p)]) { (p)++; } } /*@noaccess cstring@*/ while (0)
234 # define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*(p)]) { (p)++; } } while (0)
236 static int cpp_peekN (cppReader *p_pfile, int p_n) /*@*/ ;
238 /*@function static int cppBuffer_get (sef cppBuffer *p_b) modifies *p_b ; @*/
239 # define cppBuffer_get(BUFFER) \
240 ((BUFFER)->cur < (BUFFER)->rlimit ? *(BUFFER)->cur++ : EOF)
242 /* Append string STR (of length N) to PFILE's output buffer. Make space. */
243 /*@function static void cppReader_puts (sef cppReader *p_file, char *p_str, sef size_t p_n)
244 modifies *p_file; @*/
245 # define cppReader_puts(PFILE, STR, N) \
246 cpplib_reserve(PFILE, N), cppReader_putStrN (PFILE, STR,N)
248 /* Append character CH to PFILE's output buffer. Assume sufficient space. */
250 /*@function static void cppReader_putCharQ (cppReader *p_file, char p_ch)
251 modifies *p_file; @*/
252 # define cppReader_putCharQ(PFILE, CH) (*(PFILE)->limit++ = (CH))
254 static void cppReader_putCharQ (cppReader *p_file, char p_ch)
256 fprintf (stderr, "put char: %c\n", p_ch);
257 (*(p_file)->limit++ = (p_ch));
260 /* Append character CH to PFILE's output buffer. Make space if need be. */
262 /*@function static void cppReader_putChar (sef cppReader *p_file, char p_ch)
263 modifies *p_file; @*/
264 #define cppReader_putChar(PFILE, CH) (cpplib_reserve (PFILE, (size_t) 1), cppReader_putCharQ (PFILE, CH))
266 /* Make sure PFILE->limit is followed by '\0'. */
267 /*@function static void cppReader_nullTerminateQ (cppReader *p_file)
268 modifies *p_file; @*/
270 #define cppReader_nullTerminateQ(PFILE) (*(PFILE)->limit = 0)
272 /*@function static void cppReader_nullTerminate (sef cppReader *p_file)
273 modifies *p_file; @*/
274 # define cppReader_nullTerminate(PFILE) \
275 (cpplib_reserve (PFILE, (size_t) 1), *(PFILE)->limit = 0)
277 /*@function static void cppReader_adjustWritten (cppReader *p_file, size_t)
278 modifies *p_file; @*/
279 #define cppReader_adjustWritten(PFILE,DELTA) ((PFILE)->limit += (DELTA))
281 /*@function static bool cppReader_isC89 (cppReader *) modifies nothing; @*/
282 #define cppReader_isC89(PFILE) (CPPOPTIONS(PFILE)->c89)
284 /*@function static observer char *cppReader_wcharType (cppReader *)
285 modifies nothing; @*/
287 # define cppReader_wcharType(PFILE) \
288 (CPPOPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
290 static void cppBuffer_forward (cppBuffer *p_buf, int p_n) /*@modifies *p_buf@*/ ;
292 /*@function static void cppReader_forward (cppReader *p_pfile, int) modifies *p_pfile; @*/
293 # define cppReader_forward(pfile, N) \
294 (cppBuffer_forward (cppReader_getBufferSafe (pfile), (N)))
296 /*@function static int cppReader_getC (cppReader *p_pfile) modifies *p_pfile; @*/
297 # define cppReader_getC(pfile) (cppBuffer_get (cppReader_getBufferSafe (pfile)))
299 /*@function static int cppReader_peekC (cppReader *) modifies nothing;@*/
300 # define cppReader_peekC(pfile) (cpplib_bufPeek (cppReader_getBufferSafe (pfile)))
302 /* Move all backslash-newline pairs out of embarrassing places.
303 Exchange all such pairs following BP
304 with any potentially-embarrassing characters that follow them.
305 Potentially-embarrassing characters are / and *
306 (because a backslash-newline inside a comment delimiter
307 would cause it not to be recognized). */
310 # define NEWLINE_FIX \
311 do { while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n') { cppReader_forward (pfile, 2); } } while(FALSE)
313 /* Same, but assume we've already read the potential '\\' into C. */
315 # define NEWLINE_FIX1(C) do { \
316 while ((C) == '\\' && cppReader_peekC (pfile) == '\n') { cppReader_forward (pfile, 1); (C) = cppReader_getC (pfile); }\
319 static void parseSetMark (/*@out@*/ struct parse_marker *,
321 static void parseClearMark (struct parse_marker *);
322 static void parseGotoMark (struct parse_marker *, cppReader *);
323 static void parseMoveMark (struct parse_marker *, cppReader *);
325 /* If we have a huge buffer, may need to cache more recent counts */
326 static /*@exposed@*/ char *cppLineBase (/*@sef@*/ cppBuffer *);
328 static /*@exposed@*/ /*@null@*/ cppBuffer *
329 cppReader_pushBuffer (cppReader *p_pfile,
330 /*@owned@*/ /*@null@*/ char *, size_t)
331 /*@modifies p_pfile@*/ ;
333 static void cppReader_appendIncludeChain
335 /*@keep@*/ struct file_name_list *p_first,
336 /*@dependent@*/ struct file_name_list *p_last);
338 static void cppReader_macroCleanup (cppBuffer *p_pbuf, cppReader *p_pfile);
339 static enum cpp_token cppReader_nullUnderflow (/*@unused@*/ cppReader *p_pfile);
341 static void cppReader_nullCleanup (/*@unused@*/ cppBuffer *p_pbuf,
342 /*@unused@*/ cppReader *p_pfile);
344 static void cppReader_fileCleanup (cppBuffer *p_pbuf,
345 /*@unused@*/ cppReader *p_pfile);
347 static int cppReader_handleDirective (cppReader *p_pfile);
349 static void cppReader_scanBuffer (cppReader *p_pfile);
351 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
354 ** WIN32 (at least the VC++ include files) does not define mode_t.
357 /*@-incondefs@*/ /*@-czechtypes@*/
358 typedef unsigned int mode_t;
359 /*@=incondefs@*/ /*@=czechtypes@*/
363 static int file_size_and_mode (int p_fd, /*@out@*/ mode_t *p_mode_pointer,
364 /*@out@*/ size_t *p_size_pointer);
365 static int safe_read (int p_desc, /*@out@*/ char *p_ptr, int p_len);
369 ** cppBuffer_isMacro is true if the buffer contains macro expansion.
370 ** (Note that it is false while we're expanding marco *arguments*.)
373 static bool cppBuffer_isMacro (/*@null@*/ cppBuffer *) /*@*/ ;
375 static void path_include (cppReader *p_pfile, char *p_path)
376 /*@modifies p_pfile@*/ ;
378 static void initialize_builtins (cppReader *p_pfile)
379 /*@modifies p_pfile@*/ ;
381 static void initialize_char_syntax (struct cppOptions *p_opts) ;
383 static int /*@alt void@*/ finclude (cppReader *p_pfile, int p_f,
385 bool p_system_header_p,
386 /*@dependent@*/ /*@null@*/ struct file_name_list *p_dirptr);
388 static void validate_else (cppReader *p_pfile, cstring p_directive);
390 static void conditional_skip (cppReader *p_pfile, int p_skip,
391 enum node_type p_type,
392 /*@dependent@*/ /*@null@*/ char *p_control_macro);
394 static HOST_WIDE_INT eval_if_expression (cppReader *p_pfile,
398 static void skip_if_group (cppReader *p_pfile, int p_any);
400 static bool comp_def_part (bool p_first, char *p_beg1, int p_len1,
401 char *p_beg2, int p_len2, bool p_last);
404 extern void fancy_abort ();
407 static bool redundant_include_p (cppReader *p_pfile, /*@null@*/ cstring p_name);
408 static bool is_system_include (cppReader *p_pfile, cstring p_filename);
410 static /*@observer@*/ /*@null@*/ struct file_name_map *
411 read_name_map (cppReader *p_pfile, cstring p_dirname);
413 static cstring read_filename_string (int p_ch, /*:open:*/ FILE *p_f);
415 static int open_include_file (cppReader *p_pfile,
416 /*@owned@*/ cstring p_fname,
417 /*@null@*/ struct file_name_list *p_searchptr);
419 static void push_macro_expansion (cppReader *,
420 /*@owned@*/ char *, size_t,
421 /*@dependent@*/ hashNode);
423 /* Last arg to output_line_command. */
424 enum file_change_code {
425 same_file, enter_file, leave_file
428 /* `struct directive' defines one #-directive, including how to handle it. */
431 int length; /* Length of name */
432 /*@null@*/ int (*func)(); /* Function to handle directive */
433 /*@observer@*/ cstring name; /* Name of directive */
434 enum node_type type; /* Code which describes which directive. */
435 bool command_reads_line; /* One if rest of line is read by func. */
436 bool traditional_comments; /* Nonzero: keep comments if -traditional. */
437 bool pass_thru; /* Copy preprocessed directive to output file.*/
440 /* These functions are declared to return int instead of void since they
441 are going to be placed in a table and some old compilers have trouble with
442 pointers to functions returning void. */
444 static int do_define (cppReader *, /*@null@*/ struct directive *,
445 /*@exposed@*/ char *, char *);
446 static int do_defineAux (cppReader *, /*@null@*/ struct directive *,
447 /*@exposed@*/ char *, char *, bool);
449 static int do_line (cppReader *, /*@null@*/ struct directive *);
450 static int do_include (cppReader *, struct directive *, char *, char *);
451 static int do_undef (cppReader *, struct directive *, char *, char *);
452 static int do_error (cppReader *, struct directive *, char *, char *);
453 static int do_pragma (cppReader *, struct directive *, char *, char *);
454 static int do_ident (cppReader *, struct directive *, char *, char *);
455 static int do_if (cppReader *, struct directive *, char *, char *);
456 static int do_xifdef (cppReader *, struct directive *, char *, char *);
457 static int do_else (cppReader *, struct directive *, char *, char *);
458 static int do_elif (cppReader *, struct directive *, char *, char *);
459 static int do_endif (cppReader *, struct directive *, char *, char *);
460 static int do_warning (cppReader *, struct directive *, char *, char *);
462 /* If a buffer's dir field is SELF_DIR_DUMMY, it means the file was found
463 via the same directory as the file that #included it. */
465 /*@constant observer struct file_name_list *SELF_DIR_DUMMY@*/
466 #define SELF_DIR_DUMMY ((struct file_name_list *) (~0))
468 /* #include "file" looks in source file dir, then stack. */
469 /* #include <file> just looks in the stack. */
470 /* -I directories are added to the end, then the defaults are added. */
474 static struct default_include {
475 /*@dependent@*/ /*@observer@*/ cstring fname; /* The name of the directory. */
476 int cplusplus; /* Only look here if we're compiling C++. */
477 int cxx_aware; /* Includes in this directory don't need to
478 be wrapped in extern "C" when compiling
480 } include_defaults_array[]
482 /* This is the dir for fixincludes. Put it just before
483 the files that we fix. */
484 { GCC_INCLUDE_DIR, 0, 0 },
485 { GCC_INCLUDE_DIR2, 0, 0 },
486 { cstring_undefined, 0, 0 }
489 /*@noaccess cstring@*/
491 /* Here is the actual list of #-directives, most-often-used first.
492 The initialize_builtins function assumes #define is the very first. */
496 static struct directive directive_table[] = {
497 { 6, do_define, "define", T_DEFINE, FALSE, TRUE, FALSE },
498 { 5, do_xifdef, "ifdef", T_IFDEF, TRUE, FALSE, FALSE },
499 { 6, do_xifdef, "ifndef", T_IFNDEF, TRUE, FALSE, FALSE },
500 { 7, do_include, "include", T_INCLUDE, TRUE, FALSE, FALSE },
501 { 5, do_endif, "endif", T_ENDIF, TRUE, FALSE, FALSE },
502 { 4, do_else, "else", T_ELSE, TRUE, FALSE, FALSE },
503 { 2, do_if, "if", T_IF, TRUE, FALSE, FALSE },
504 { 4, do_elif, "elif", T_ELIF, TRUE, FALSE, FALSE },
505 { 5, do_undef, "undef", T_UNDEF, FALSE, FALSE, FALSE },
506 { 5, do_error, "error", T_ERROR, FALSE, FALSE, FALSE },
507 { 7, do_warning, "warning", T_WARNING, FALSE, FALSE, FALSE },
508 { 6, do_pragma, "pragma", T_PRAGMA, FALSE, FALSE, TRUE},
509 { 4, do_line, "line", T_LINE, TRUE, FALSE, FALSE },
510 { 5, do_ident, "ident", T_IDENT, TRUE, FALSE, TRUE },
511 /* { 8, do_unassert, "unassert", T_UNASSERT, TRUE, FALSE, FALSE }, */
512 { -1, NULL, "", T_UNUSED, FALSE, FALSE, FALSE },
514 /*@noaccess cstring@*/
516 static cstring searchPath_unparse (struct file_name_list *search_start)
518 cstring res = cstring_newEmpty ();
519 struct file_name_list *searchptr = NULL;
521 for (searchptr = search_start; searchptr != NULL;
522 searchptr = searchptr->next)
524 if (!cstring_isEmpty (searchptr->fname)) {
525 res = cstring_concatFree1 (res, searchptr->fname);
526 if (searchptr->next != NULL) {
527 res = cstring_appendChar (res, ';');
537 initialize_char_syntax (struct cppOptions *opts)
542 * Set up is_idchar and is_idstart tables. These should be
543 * faster than saying (is_alpha (c) || c == '_'), etc.
544 * Set up these things before calling any routines tthat
548 for (i = 'a'; i <= 'z'; i++) {
549 is_idchar[i - 'a' + 'A'] = TRUE;
550 is_idchar[(int) i] = TRUE;
551 is_idstart[i - 'a' + 'A'] = TRUE;
552 is_idstart[(int) i] = TRUE;
555 for (i = '0'; i <= '9'; i++)
557 is_idchar[(int) i] = TRUE;
560 is_idchar['_'] = TRUE;
561 is_idstart['_'] = TRUE;
562 is_idchar['$'] = opts->dollars_in_ident;
563 is_idstart['$'] = opts->dollars_in_ident;
565 /* horizontal space table */
566 is_hor_space[' '] = TRUE;
567 is_hor_space['\t'] = TRUE;
568 is_hor_space['\v'] = TRUE;
569 is_hor_space['\f'] = TRUE;
570 is_hor_space['\r'] = TRUE;
572 is_space[' '] = TRUE;
573 is_space['\t'] = TRUE;
574 is_space['\v'] = TRUE;
575 is_space['\f'] = TRUE;
576 is_space['\n'] = TRUE;
577 is_space['\r'] = TRUE;
580 bool isIdentifierChar (char c)
582 return is_idchar[(int) c];
585 /* Place into P_PFILE a quoted string representing the string SRC.
586 Caller must reserve enough space in pfile->token_buffer. */
589 quote_string (cppReader *pfile, char *src)
593 cppReader_putCharQ (pfile, '\"');
596 switch ((c = *src++))
600 cppReader_putCharQ (pfile, c);
603 sprintf (cpplib_getPWritten (pfile), "\\%03o",
605 cppReader_adjustWritten (pfile, (size_t) 4);
607 /*@switchbreak@*/ break;
611 cppReader_putCharQ (pfile, '\\');
612 cppReader_putCharQ (pfile, c);
613 /*@switchbreak@*/ break;
616 cppReader_putCharQ (pfile, '\"');
617 cppReader_nullTerminateQ (pfile);
623 /* Re-allocates PFILE->token_buffer so it will hold at least N more chars. */
626 cppReader_growBuffer (cppReader *pfile, size_t n)
628 size_t old_written = cpplib_getWritten (pfile);
629 pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
630 pfile->token_buffer = (char *)
631 drealloc (pfile->token_buffer, pfile->token_buffer_size);
632 cppReader_setWritten (pfile, old_written);
636 * process a given definition string, for initialization
637 * If STR is just an identifier, define it with value 1.
638 * If STR has anything after the identifier, then it should
639 * be identifier=definition.
643 cppReader_define (cppReader *pfile, char *str)
648 DPRINTF (("Cpp reader define: %s", str));
650 if (!is_idstart[(int) *p])
652 DPRINTF (("ERROR 1"));
653 cppReader_error (pfile,
654 message ("Malformed option `-D%s'",
655 cstring_fromChars (str)));
662 DPRINTF (("Here 2"));
664 while (is_idchar[(int) *p])
671 while (*p != ')' && *p != '\0') {
680 message ("Malformed option: -D%s (no closing parenthesis)",
681 cstring_fromChars (str)));
685 DPRINTF (("Here 2"));
689 buf = (char *) dmalloc (size_fromInt (p - str + 4));
690 strcpy ((char *) buf, str);
691 strcat ((char *) buf, " 1");
695 DPRINTF (("ERROR 2"));
696 cppReader_error (pfile,
697 message ("Malformed option: -D%s (expected '=', found '%c')",
698 cstring_fromChars (str),
705 /* Copy the entire option so we can modify it. */
706 DPRINTF (("Copying..."));
707 buf = (char *) dmalloc (2 * strlen (str) + 1);
708 strncpy (buf, str, size_fromInt (p - str));
710 /* Change the = to a space. */
712 /* Scan for any backslash-newline and remove it. */
718 if (*p == '\\' && p[1] == '\n')
724 DPRINTF (("Here we are..."));
728 llassert (buf != NULL);
729 DPRINTF (("Do define: %s / %ld", buf, size_toLong (strlen (buf))));
730 (void) do_define (pfile, NULL, buf, buf + strlen (buf));
734 /* Append a chain of `struct file_name_list's
735 to the end of the main include chain.
736 FIRST is gthe beginning of the chain to append, and LAST is the end. */
739 cppReader_appendIncludeChain (cppReader *pfile,
740 struct file_name_list *first,
741 struct file_name_list *last)
743 struct cppOptions *opts = CPPOPTIONS (pfile);
744 struct file_name_list *dir;
746 if (first == NULL || last == NULL)
751 if (opts->include == 0)
753 opts->include = first;
757 llassert (opts->last_include->next == NULL);
758 opts->last_include->next = first;
761 if (opts->first_bracket_include == 0)
763 opts->first_bracket_include = first;
765 for (dir = first; ; dir = dir->next) {
766 size_t len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
768 if (len > pfile->max_include_len)
770 pfile->max_include_len = len;
780 llassert (last->next == NULL);
781 /* last->next = NULL; */
782 opts->last_include = last;
786 static /*@unused@*/ void
787 cppReader_showIncludeChain (cppReader *pfile)
789 struct file_name_list *dirs = CPPOPTIONS (pfile)->include;
795 fprintf (stderr, "*%s*:", cstring_toCharsSafe (dirs->fname));
799 fprintf (stderr, "\n");
803 fprintf (stderr, "No includes\n");
809 cppReader_getIncludePath ()
811 cppReader *pfile = &g_cppState;
812 struct file_name_list *dirs = CPPOPTIONS (pfile)->include;
813 cstring res = cstring_undefined;
819 res = message ("%q%c%s", res, PATH_SEPARATOR, dirs->fname);
825 res = cstring_makeLiteral ("<no include path>");
832 cppReader_addIncludeChain (cppReader *pfile, /*@only@*/ struct file_name_list *dir)
834 struct cppOptions *opts = CPPOPTIONS (pfile);
841 if (opts->include == 0)
847 llassert (opts->last_include->next == NULL);
848 opts->last_include->next = dir;
851 if (opts->first_bracket_include == 0)
853 size_t len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
854 opts->first_bracket_include = dir;
856 if (len > pfile->max_include_len)
858 pfile->max_include_len = len;
863 opts->last_include = dir;
864 /* cppReader_showIncludeChain (pfile); */
867 /* Given a colon-separated list of file names PATH,
868 add all the names to the search path for include files. */
871 path_include (cppReader *pfile, char *path)
878 /* if we have a posix path list, convert to win32 path list */
879 win32temp = (char *) dmalloc /*@i4@*/
880 (cygwin32_posix_to_win32_path_list_buf_size (path));
881 cygwin32_posix_to_win32_path_list (path, win32temp);
891 struct file_name_list *dirtmp;
893 /* Find the end of this name. */
894 while (*q != '\0' && *q != PATH_SEPARATOR)
901 /* An empty name in the path stands for the current directory. */
902 name = (char *) dmalloc ((size_t) 2);
908 /* Otherwise use the directory that is named. */
909 name = (char *) dmalloc (size_fromInt (q - p + 1));
910 memcpy (name, p, size_fromInt (q - p));
914 dirtmp = (struct file_name_list *) dmalloc (sizeof (*dirtmp));
915 dirtmp->next = 0; /* New one goes on the end */
916 dirtmp->control_macro = 0;
917 dirtmp->c_system_include_path = 0;
918 dirtmp->fname = cstring_fromChars (name);
919 dirtmp->got_name_map = 0;
920 cppReader_addIncludeChain (pfile, dirtmp);
922 /* Advance past this name. */
926 /* Skip the colon. */
932 cppOptions_init (cppOptions *opts)
934 memset ((char *) opts, 0, sizeof *opts);
937 opts->in_fname = NULL;
938 opts->out_fname = NULL;
940 /* Initialize is_idchar to allow $. */
941 opts->dollars_in_ident = TRUE;
943 opts->no_line_commands = 0;
944 opts->no_trigraphs = TRUE;
945 opts->put_out_comments = 1;
946 opts->print_include_names = 0;
947 opts->dump_macros = DUMP_DEFINITIONS; /* DUMP_NONE; */
951 opts->cplusplus_comments = 1;
956 opts->pedantic_errors = 0;
957 opts->warn_comments = 0;
958 opts->warnings_are_errors = 0;
960 initialize_char_syntax (opts);
964 cppReader_nullUnderflow (/*@unused@*/ cppReader *pfile)
970 cppReader_nullCleanup (/*@unused@*/ cppBuffer *pbuf,
971 /*@unused@*/ cppReader *pfile)
977 cppReader_macroCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
979 hashNode macro = pbuf->hnode;
981 if (macro->type == T_DISABLED)
983 macro->type = T_MACRO;
986 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
994 cppReader_fileCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
996 if (pbuf->buf != NULL)
1003 /* Assuming we have read '/'.
1004 If this is the start of a comment (followed by '*' or '/'),
1005 skip to the end of the comment, and return ' '.
1006 Return EOF if we reached the end of file before the end of the comment.
1007 If not the start of a comment, return '/'. */
1010 skip_comment (cppReader *pfile, /*@null@*/ long *linep)
1014 llassert (pfile->buffer != NULL);
1015 llassert (pfile->buffer->cur != NULL);
1017 while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n')
1024 cppReader_forward (pfile, 2);
1027 if (cppReader_peekC (pfile) == '*')
1029 cppReader_forward (pfile, 1);
1034 c = cppReader_getC (pfile);
1041 while (c == (int) '\\' && cppReader_peekC (pfile) == (int) '\n')
1048 cppReader_forward (pfile, 1), c = cppReader_getC (pfile);
1051 if (prev_c == (int) '*' && c == (int) '/')
1056 if (c == (int) '\n' && (linep != NULL))
1062 else if (cppReader_peekC (pfile) == '/'
1063 && CPPOPTIONS (pfile)->cplusplus_comments)
1066 (void) cppoptgenerror
1067 (FLG_SLASHSLASHCOMMENT,
1068 message ("C++ style // comment"
1072 cppReader_forward (pfile, 1);
1076 c = cppReader_getC (pfile);
1080 /* Allow hash comment to be terminated by EOF. */
1084 while (c == (int) '\\' && cppReader_peekC (pfile) == '\n')
1086 cppReader_forward (pfile, 1);
1087 c = cppReader_getC (pfile);
1095 if (c == (int) '\n')
1097 /* Don't consider final '\n' to be part of comment. */
1098 cppReader_forward (pfile, -1);
1109 /* Skip whitespace \-newline and comments. Does not macro-expand. */
1111 cppSkipHspace (cppReader *pfile)
1119 llassert (pfile->buffer != NULL);
1121 c = cppReader_peekC (pfile);
1125 return 0; /* FIXME */
1128 if (is_hor_space[c])
1130 if ((c == '\f' || c == '\v') && cppReader_isPedantic (pfile))
1131 cppReader_pedwarn (pfile,
1132 message ("%s in preprocessing directive",
1134 ? cstring_makeLiteralTemp ("formfeed")
1135 : cstring_makeLiteralTemp ("vertical tab")));
1138 cppReader_forward (pfile, 1);
1142 cppReader_forward (pfile, 1);
1143 c = skip_comment (pfile, NULL);
1147 cppReader_forward (pfile, -1);
1150 if (c == EOF || c == '/')
1155 else if (c == '\\' && cpp_peekN (pfile, 1) == '\n')
1157 cppReader_forward (pfile, 2);
1159 else if (c == '@' && CPPBUFFER (pfile)->has_escapes
1160 && is_hor_space [cpp_peekN (pfile, 1)])
1162 cppReader_forward (pfile, 2);
1171 /* Read the rest of the current line.
1172 The line is appended to PFILE's output buffer. */
1175 copy_rest_of_line (cppReader *pfile)
1177 struct cppOptions *opts = CPPOPTIONS (pfile);
1184 llassert (pfile->buffer != NULL);
1186 c = cppReader_getC (pfile);
1194 ** Patch from Brian St. Pierre for handling MS-DOS files.
1197 DPRINTF (("Reading directive: %d", (int) c));
1199 if (cppReader_peekC (pfile) == '\n'
1200 || cppReader_peekC (pfile) == '\r')
1202 DPRINTF (("Reading directive..."));
1203 if (cppReader_peekC (pfile) == '\r')
1205 DPRINTF (("Reading directive..."));
1206 cppReader_forward (pfile, 1);
1209 DPRINTF (("Reading directive..."));
1210 cppReader_forward (pfile, 1);
1214 DPRINTF (("Falling..."));
1215 /*@fallthrough@*/ case '\'': case '\"':
1216 goto scan_directive_token;
1219 nextc = cppReader_peekC (pfile);
1222 ** was (opts->cplusplus_comments && nextc == '*')
1227 || (opts->cplusplus_comments && nextc == '/'))
1229 goto scan_directive_token;
1231 /*@switchbreak@*/ break;
1234 if (cppReader_isPedantic (pfile))
1235 cppReader_pedwarn (pfile,
1236 message ("%s in preprocessing directive",
1238 ? cstring_makeLiteralTemp ("formfeed")
1239 : cstring_makeLiteralTemp ("vertical tab")));
1240 /*@switchbreak@*/ break;
1243 cppReader_forward (pfile, -1);
1245 scan_directive_token:
1246 cppReader_forward (pfile, -1);
1247 (void) cpplib_getToken (pfile);
1250 cppReader_putChar (pfile, c);
1253 cppReader_nullTerminate (pfile);
1257 cppReader_skipRestOfLine (cppReader *pfile)
1259 size_t old = cpplib_getWritten (pfile);
1260 copy_rest_of_line (pfile);
1261 cppReader_setWritten (pfile, old);
1264 /* Handle a possible # directive.
1265 '#' has already been read. */
1268 cppReader_handleDirective (cppReader *pfile)
1271 struct directive *kt = NULL;
1273 size_t after_ident = 0;
1275 char *line_end = NULL;
1276 size_t old_written = cpplib_getWritten (pfile);
1277 int nspaces = cppSkipHspace (pfile);
1279 c = cppReader_peekC (pfile);
1281 if (c >= '0' && c <= '9')
1283 /* Handle # followed by a line number. */
1284 if (cppReader_isPedantic (pfile))
1286 cppReader_pedwarnLit
1288 cstring_makeLiteralTemp ("`#' followed by integer"));
1291 (void) do_line (pfile, NULL);
1292 goto done_a_directive;
1296 /* Now find the directive name. */
1298 cppReader_putChar (pfile, '#');
1300 parse_name (pfile, cppReader_getC (pfile));
1302 llassert (pfile->token_buffer != NULL);
1303 ident = pfile->token_buffer + old_written + 1;
1305 ident_length = cpplib_getPWritten (pfile) - ident;
1307 if (ident_length == 0 && cppReader_peekC (pfile) == '\n')
1309 /* A line of just `#' becomes blank. */
1313 for (kt = directive_table; ; kt++)
1315 if (kt->length <= 0)
1317 return 0; /* goto not_a_directive; */
1320 if (kt->length == ident_length
1321 && (cstring_equalPrefix (kt->name, cstring_fromChars (ident))))
1327 if (kt->command_reads_line)
1333 /* Nonzero means do not delete comments within the directive.
1334 #define needs this when -traditional. */
1335 bool comments = 1; /*cppReader_isTraditional (pfile) && kt->traditional_comments; */
1336 int save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
1337 CPPOPTIONS (pfile)->put_out_comments = comments;
1338 after_ident = cpplib_getWritten (pfile);
1339 copy_rest_of_line (pfile);
1340 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
1344 /* For #pragma and #define, we may want to pass through the directive.
1345 Other directives may create output, but we don't want the directive
1346 itself out, so we pop it now. For example #include may write a #line
1347 command (see comment in do_include), and conditionals may emit
1348 #failed ... #endfailed stuff. But note that popping the buffer
1349 means the parameters to kt->func may point after pfile->limit
1350 so these parameters are invalid as soon as something gets appended
1351 to the token_buffer. */
1353 line_end = cpplib_getPWritten (pfile);
1356 if (!kt->pass_thru && kt->type != T_DEFINE)
1358 cppReader_setWritten (pfile, old_written);
1361 llassert (pfile->token_buffer != NULL);
1363 /* was kt->pass_thru || */
1365 if (kt->type == T_DEFINE
1366 && cpp_shouldCheckMacro (pfile, pfile->token_buffer + old_written))
1368 char *p = pfile->token_buffer + old_written;
1371 ** Still need to record value for preprocessing, so
1372 ** #ifdef's, etc. using the value behave correctly.
1375 (void) do_defineAux (pfile, kt,
1376 pfile->token_buffer + after_ident,
1385 SKIP_WHITE_SPACE (p);
1387 llassert (*p == 'd');
1390 llassert (*p == 'e');
1393 llassert (*p == 'f');
1396 llassert (*p == 'i');
1399 llassert (*p == 'n');
1402 llassert (*p == 'e');
1405 ** This is way-bogus. We use the last char to record the number of
1406 ** spaces. Its too hard to get them back into the input stream.
1409 if (nspaces > 9) nspaces = 9;
1411 *p++ = '0' + nspaces;
1413 return 0; /* not_a_directive */
1415 else if (kt->pass_thru)
1417 /* Just leave the entire #define in the output stack. */
1418 return 0; /* not_a_directive */
1421 else if (kt->type == T_DEFINE
1422 && CPPOPTIONS (pfile)->dump_macros == DUMP_NAMES)
1424 char *p = pfile->token_buffer + old_written + 7; /* Skip "#define". */
1425 SKIP_WHITE_SPACE (p);
1427 while (is_idchar[(int) *p])
1433 cppReader_putChar (pfile, '\n');
1435 else if (kt->type == T_DEFINE)
1437 cppReader_setWritten (pfile, old_written);
1448 llassert (kt->func != NULL);
1449 (void) (kt->func) (pfile, kt, pfile->token_buffer + after_ident, line_end);
1454 /* Pass a directive through to the output file.
1455 BUF points to the contents of the directive, as a contiguous string.
1456 LIMIT points to the first character past the end of the directive.
1457 KEYWORD is the keyword-table entry for the directive. */
1460 pass_thru_directive (char *buf, char *limit,
1462 struct directive *keyword)
1464 int keyword_length = keyword->length;
1466 cpplib_reserve (pfile,
1467 size_fromInt (2 + keyword_length + (limit - buf)));
1468 cppReader_putCharQ (pfile, '#');
1469 /*@-observertrans@*/
1470 cppReader_putStrN (pfile, cstring_toCharsSafe (keyword->name),
1471 size_fromInt (keyword_length));
1472 /*:=observertrans@*/
1474 if (limit != buf && buf[0] != ' ')
1476 /* Was a bug, since reserve only used 1 + ... */
1477 cppReader_putCharQ (pfile, ' ');
1480 cppReader_putStrN (pfile, buf, size_fromInt (limit - buf));
1483 /* Read a replacement list for a macro with parameters.
1484 Build the DEFINITION structure.
1485 Reads characters of text starting at BUF until END.
1486 ARGLIST specifies the formal parameters to look for
1487 in the text of the definition; NARGS is the number of args
1488 in that list, or -1 for a macro name that wants no argument list.
1489 MACRONAME is the macro name itself (so we can avoid recursive expansion)
1490 and NAMELEN is its length in characters.
1492 Note that comments, backslash-newlines, and leading white space
1493 have already been deleted from the argument. */
1496 collect_expansion (cppReader *pfile, char *buf, char *limit,
1497 int nargs, /*@null@*/ struct arglist *arglist)
1500 char *p, *lastp, *exp_p;
1501 struct reflist *endpat = NULL;
1502 /* Pointer to first nonspace after last ## seen. */
1504 /* Pointer to first nonspace after last single-# seen. */
1505 char *stringify = 0;
1507 char expected_delimiter = '\0';
1510 /* Scan thru the replacement list, ignoring comments and quoted
1511 strings, picking up on the macro calls. It does a linear search
1512 thru the arg list on every potential symbol. Profiling might say
1513 that something smarter should happen. */
1518 /* Find the beginning of the trailing whitespace. */
1521 while (p < limit && is_space[(int) limit[-1]])
1526 /* Allocate space for the text in the macro definition.
1527 Leading and trailing whitespace chars need 2 bytes each.
1528 Each other input char may or may not need 1 byte,
1529 so this is an upper bound. The extra 5 are for invented
1530 leading and trailing newline-marker and final null. */
1531 maxsize = (sizeof (*defn) + (limit - p) + 5);
1533 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1542 defn = (DEFINITION *) dmalloc (maxsize);
1543 defn->noExpand = FALSE;
1545 defn->pattern = NULL;
1546 defn->nargs = nargs;
1547 defn->predefined = NULL;
1549 exp_p = defn->expansion = (char *) defn + sizeof (*defn);
1552 defn->rest_args = NULL;
1553 defn->args.argnames = NULL;
1559 /* Add one initial space escape-marker to prevent accidental
1560 token-pasting (often removed by cpplib_macroExpand). */
1564 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1565 cppReader_errorLit (pfile,
1566 cstring_makeLiteralTemp ("`##' at start of macro definition"));
1570 /* Process the main body of the definition. */
1572 int skipped_arg = 0;
1573 register char c = *p++;
1577 if (!cppReader_isTraditional (pfile)) {
1581 if (expected_delimiter != '\0')
1583 if (c == expected_delimiter)
1584 expected_delimiter = '\0';
1588 expected_delimiter = c;
1590 /*@switchbreak@*/ break;
1593 if (p < limit && (expected_delimiter != '\0'))
1595 /* In a string, backslash goes through
1596 and makes next char ordinary. */
1599 /*@switchbreak@*/ break;
1602 /* An '@' in a string or character constant stands for itself,
1603 and does not need to be escaped. */
1604 if (expected_delimiter == '\0')
1609 /*@switchbreak@*/ break;
1612 /* # is ordinary inside a string. */
1613 if (expected_delimiter != '\0')
1615 /*@switchbreak@*/ break;
1618 if (p < limit && *p == '#') {
1619 /* ##: concatenate preceding and following tokens. */
1620 /* Take out the first #, discard preceding whitespace. */
1624 while (exp_p > lastp && is_hor_space[(int) exp_p[-1]])
1630 /* Skip the second #. */
1632 /* Discard following whitespace. */
1633 SKIP_WHITE_SPACE (p);
1637 cppReader_errorLit (pfile,
1638 cstring_makeLiteralTemp ("`##' at end of macro definition"));
1640 } else if (nargs >= 0) {
1641 /* Single #: stringify following argument ref.
1642 Don't leave the # in the expansion. */
1644 SKIP_WHITE_SPACE (p);
1645 if (p == limit || ! is_idstart[(int) *p]
1646 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '\"')))
1647 cppReader_errorLit (pfile,
1648 cstring_makeLiteralTemp ("`#' operator is not followed by a macro argument name"));
1655 /*@switchbreak@*/ break;
1658 /* In -traditional mode, recognize arguments inside strings and
1659 and character constants, and ignore special properties of #.
1660 Arguments inside strings are considered "stringified", but no
1661 extra quote marks are supplied. */
1665 if (expected_delimiter != '\0') {
1666 if (c == expected_delimiter)
1667 expected_delimiter = '\0';
1669 expected_delimiter = c;
1670 /*@switchbreak@*/ break;
1673 /* Backslash quotes delimiters and itself, but not macro args. */
1674 if (expected_delimiter != '\0' && p < limit
1675 && (*p == expected_delimiter || *p == '\\')) {
1679 /*@switchbreak@*/ break;
1682 if (expected_delimiter != '\0') /* No comments inside strings. */
1683 /*@switchbreak@*/ break;
1685 /* If we find a comment that wasn't removed by cppReader_handleDirective,
1686 this must be -traditional. So replace the comment with
1690 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
1695 /*@switchbreak@*/ break;
1699 /* Handle the start of a symbol. */
1700 if (is_idchar[(int) c] && nargs > 0) {
1701 char *id_beg = p - 1;
1705 while (p != limit && is_idchar[(int) *p])
1710 id_len = size_fromInt (p - id_beg);
1712 if (is_idstart[(int) c]
1713 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '\"'))) {
1714 register struct arglist *arg;
1716 for (arg = arglist; arg != NULL; arg = arg->next) {
1717 struct reflist *tpat;
1719 if (arg->name[0] == c
1720 && arg->length == id_len
1721 && strncmp (arg->name, id_beg, id_len) == 0) {
1724 if (expected_delimiter && CPPOPTIONS (pfile)->warn_stringify) {
1725 if (cppReader_isTraditional (pfile)) {
1726 cppReader_warning (pfile,
1727 message ("macro argument `%x' is stringified.",
1728 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1730 cppReader_warning (pfile,
1731 message ("macro arg `%x' would be stringified with -traditional.",
1732 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1735 /* If ANSI, don't actually substitute inside a string. */
1736 if (!cppReader_isTraditional (pfile) && expected_delimiter)
1737 /*@innerbreak@*/ break;
1738 /* make a pat node for this arg and append it to the end of
1740 tpat = (struct reflist *) dmalloc (sizeof (*tpat));
1742 tpat->raw_before = (concat == id_beg);
1743 tpat->raw_after = 0;
1744 tpat->rest_args = arg->rest_args;
1745 tpat->stringify = (cppReader_isTraditional (pfile)
1746 ? expected_delimiter != '\0'
1747 : stringify == id_beg);
1751 defn->pattern = tpat;
1755 endpat->next = tpat;
1757 } /*@=branchstate@*/ /* evs 2000 was =branchstate */
1761 tpat->argno = arg->argno;
1762 tpat->nchars = exp_p - lastp;
1766 SKIP_WHITE_SPACE (p1);
1768 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
1770 tpat->raw_after = 1;
1773 lastp = exp_p; /* place to start copying from next time */
1776 /*@innerbreak@*/ break;
1781 /* If this was not a macro arg, copy it into the expansion. */
1782 if (skipped_arg == 0) {
1783 register char *lim1 = p;
1791 if (stringify == id_beg)
1792 cppReader_errorLit (pfile,
1793 cstring_makeLiteralTemp ("`#' operator should be followed by a macro argument name"));
1798 if (!cppReader_isTraditional (pfile) && expected_delimiter == '\0')
1800 /* If ANSI, put in a "@ " marker to prevent token pasting.
1801 But not if "inside a string" (which in ANSI mode
1802 happens only for -D option). */
1809 defn->length = size_fromInt (exp_p - defn->expansion);
1811 /* Crash now if we overrun the allocated size. */
1812 if (defn->length + 1 > maxsize)
1814 llfatalbug (cstring_makeLiteral ("Maximum definition size exceeded."));
1822 ** Gasp...cut-and-pasted from above to deal with pfile (should replace throughout with this...)
1826 collect_expansionLoc (fileloc loc, char *buf, char *limit,
1827 int nargs, /*@null@*/ struct arglist *arglist)
1830 char *p, *lastp, *exp_p;
1831 struct reflist *endpat = NULL;
1832 /* Pointer to first nonspace after last ## seen. */
1834 /* Pointer to first nonspace after last single-# seen. */
1835 char *stringify = 0;
1837 char expected_delimiter = '\0';
1840 /* Scan thru the replacement list, ignoring comments and quoted
1841 strings, picking up on the macro calls. It does a linear search
1842 thru the arg list on every potential symbol. Profiling might say
1843 that something smarter should happen. */
1847 llfatalbug (message ("%q: Limit is less than initial buffer pointer",
1848 fileloc_unparse (loc)));
1851 /* Find the beginning of the trailing whitespace. */
1854 while (p < limit && is_space[(int) limit[-1]])
1859 /* Allocate space for the text in the macro definition.
1860 Leading and trailing whitespace chars need 2 bytes each.
1861 Each other input char may or may not need 1 byte,
1862 so this is an upper bound. The extra 5 are for invented
1863 leading and trailing newline-marker and final null. */
1864 maxsize = (sizeof (*defn) + (limit - p) + 5);
1866 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1875 defn = (DEFINITION *) dmalloc (maxsize);
1876 defn->noExpand = FALSE;
1878 defn->pattern = NULL;
1879 defn->nargs = nargs;
1880 defn->predefined = NULL;
1882 exp_p = defn->expansion = (char *) defn + sizeof (*defn);
1885 defn->rest_args = NULL;
1886 defn->args.argnames = NULL;
1892 /* Add one initial space escape-marker to prevent accidental
1893 token-pasting (often removed by cpplib_macroExpand). */
1897 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1898 voptgenerror (FLG_PREPROC,
1899 cstring_makeLiteral ("Paste marker ## at start of macro definition"),
1904 /* Process the main body of the definition. */
1906 int skipped_arg = 0;
1907 register char c = *p++;
1911 if (TRUE) { /* !cppReader_isTraditional (pfile)) { */
1915 if (expected_delimiter != '\0')
1917 if (c == expected_delimiter)
1918 expected_delimiter = '\0';
1922 expected_delimiter = c;
1924 /*@switchbreak@*/ break;
1927 if (p < limit && (expected_delimiter != '\0'))
1929 /* In a string, backslash goes through
1930 and makes next char ordinary. */
1933 /*@switchbreak@*/ break;
1936 /* An '@' in a string or character constant stands for itself,
1937 and does not need to be escaped. */
1938 if (expected_delimiter == '\0')
1943 /*@switchbreak@*/ break;
1946 /* # is ordinary inside a string. */
1947 if (expected_delimiter != '\0')
1949 /*@switchbreak@*/ break;
1952 if (p < limit && *p == '#') {
1953 /* ##: concatenate preceding and following tokens. */
1954 /* Take out the first #, discard preceding whitespace. */
1958 while (exp_p > lastp && is_hor_space[(int) exp_p[-1]])
1964 /* Skip the second #. */
1966 /* Discard following whitespace. */
1967 SKIP_WHITE_SPACE (p);
1971 voptgenerror (FLG_PREPROC,
1972 cstring_makeLiteral ("`##' at end of macro definition"),
1975 } else if (nargs >= 0) {
1976 /* Single #: stringify following argument ref.
1977 Don't leave the # in the expansion. */
1979 SKIP_WHITE_SPACE (p);
1980 if (p == limit || ! is_idstart[(int) *p]
1981 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '\"')))
1985 cstring_makeLiteral ("`#' operator is not followed by a macro argument name"),
1994 /*@switchbreak@*/ break;
1997 /* In -traditional mode, recognize arguments inside strings and
1998 and character constants, and ignore special properties of #.
1999 Arguments inside strings are considered "stringified", but no
2000 extra quote marks are supplied. */
2004 if (expected_delimiter != '\0') {
2005 if (c == expected_delimiter)
2006 expected_delimiter = '\0';
2008 expected_delimiter = c;
2009 /*@switchbreak@*/ break;
2012 /* Backslash quotes delimiters and itself, but not macro args. */
2013 if (expected_delimiter != '\0' && p < limit
2014 && (*p == expected_delimiter || *p == '\\')) {
2018 /*@switchbreak@*/ break;
2021 if (expected_delimiter != '\0') /* No comments inside strings. */
2022 /*@switchbreak@*/ break;
2024 /* If we find a comment that wasn't removed by cppReader_handleDirective,
2025 this must be -traditional. So replace the comment with
2029 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
2034 /*@switchbreak@*/ break;
2038 /* Handle the start of a symbol. */
2039 if (is_idchar[(int) c] && nargs > 0) {
2040 char *id_beg = p - 1;
2044 while (p != limit && is_idchar[(int) *p])
2049 id_len = size_fromInt (p - id_beg);
2051 if (is_idstart[(int) c]
2052 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '\"'))) {
2053 register struct arglist *arg;
2055 for (arg = arglist; arg != NULL; arg = arg->next) {
2056 struct reflist *tpat;
2058 if (arg->name[0] == c
2059 && arg->length == id_len
2060 && strncmp (arg->name, id_beg, id_len) == 0) {
2063 if (expected_delimiter) { /* && CPPOPTIONS (pfile)->warn_stringify) { */
2064 if (FALSE) { /* cppReader_isTraditional (pfile)) { */
2065 voptgenerror (FLG_PREPROC,
2066 message ("macro argument `%x' is stringified.",
2067 cstring_prefix (cstring_fromChars (arg->name), id_len)),
2071 voptgenerror (FLG_PREPROC,
2072 message ("Macro arg `%x' would be stringified with -traditional.",
2073 cstring_prefix (cstring_fromChars (arg->name), id_len)),
2078 /* If ANSI, don't actually substitute inside a string. */
2079 if (TRUE /* !cppReader_isTraditional (pfile) */ && expected_delimiter)
2080 /*@innerbreak@*/ break;
2081 /* make a pat node for this arg and append it to the end of
2083 tpat = (struct reflist *) dmalloc (sizeof (*tpat));
2085 tpat->raw_before = (concat == id_beg);
2086 tpat->raw_after = 0;
2087 tpat->rest_args = arg->rest_args;
2088 tpat->stringify = (FALSE /* cppReader_isTraditional (pfile) */
2089 ? expected_delimiter != '\0'
2090 : stringify == id_beg);
2094 defn->pattern = tpat;
2098 endpat->next = tpat;
2100 } /*@=branchstate@*/ /* evs 2000 was =branchstate */
2104 tpat->argno = arg->argno;
2105 tpat->nchars = exp_p - lastp;
2109 SKIP_WHITE_SPACE (p1);
2111 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
2113 tpat->raw_after = 1;
2116 lastp = exp_p; /* place to start copying from next time */
2119 /*@innerbreak@*/ break;
2124 /* If this was not a macro arg, copy it into the expansion. */
2125 if (skipped_arg == 0) {
2126 register char *lim1 = p;
2134 if (stringify == id_beg)
2138 cstring_makeLiteral ("# operator should be followed by a macro argument name"),
2145 if (/*!cppReader_isTraditional (pfile) && */ expected_delimiter == '\0')
2147 /* If ANSI, put in a "@ " marker to prevent token pasting.
2148 But not if "inside a string" (which in ANSI mode
2149 happens only for -D option). */
2156 defn->length = size_fromInt (exp_p - defn->expansion);
2158 /* Crash now if we overrun the allocated size. */
2159 if (defn->length + 1 > maxsize)
2161 llfatalbug (cstring_makeLiteral ("Maximum definition size exceeded."));
2168 * special extension string that can be added to the last macro argument to
2169 * allow it to absorb the "rest" of the arguments when expanded. Ex:
2170 * #define wow(a, b...) process (b, a, b)
2171 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
2172 * { wow (one, two); } -> { process (two, one, two); }
2173 * if this "rest_arg" is used with the concat token '##' and if it is not
2174 * supplied then the token attached to with ## will not be outputted. Ex:
2175 * #define wow (a, b...) process (b ## , a, ## b)
2176 * { wow (1, 2); } -> { process (2, 1, 2); }
2177 * { wow (one); } -> { process (one); {
2180 /*@-readonlytrans@*/
2181 static char rest_extension[] = "...";
2182 /*:=readonlytrans@*/
2185 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
2187 /* Create a DEFINITION node from a #define directive. Arguments are
2188 as for do_define. */
2191 static /*@null@*/ macroDef
2192 create_definition (/*@exposed@*/ char *buf, char *limit,
2193 cppReader *pfile, bool predefinition,
2196 char *bp; /* temp ptr into input buffer */
2197 char *symname; /* remember where symbol name starts */
2198 size_t sym_length; /* and how long it is */
2199 int rest_args = 0; /* really int! */
2202 cstring file = (CPPBUFFER (pfile) != NULL)
2203 ? CPPBUFFER (pfile)->nominal_fname : cstring_makeLiteralTemp ("");
2205 int arglengths = 0; /* Accumulate lengths of arg names
2206 plus number of args. */
2210 DPRINTF (("Create definition: %s", buf));
2213 cppBuffer_getLineAndColumn (CPPBUFFER (pfile), &line, &col);
2217 while (is_hor_space[(int) *bp])
2222 symname = bp; /* remember where it starts */
2224 sym_length = cppReader_checkMacroName (pfile, bp, cstring_makeLiteralTemp ("macro"));
2228 /* Lossage will occur if identifiers or control keywords are broken
2229 across lines using backslash. This is not the right place to take
2233 struct arglist *arg_ptrs = NULL;
2236 bp++; /* skip '(' */
2237 SKIP_WHITE_SPACE (bp);
2239 /* Loop over macro argument names. */
2242 struct arglist *temp = (struct arglist *) dmalloc (sizeof (*temp));
2244 temp->next = arg_ptrs;
2245 temp->argno = argno++;
2246 temp->rest_args = 0;
2252 cppReader_pedwarn (pfile,
2253 message ("another parameter follows `%s'",
2254 cstring_fromChars (rest_extension)));
2257 if (!is_idstart[(int) *bp])
2259 cppReader_pedwarnLit (pfile,
2260 cstring_makeLiteralTemp ("Invalid character in macro parameter name"));
2263 /* Find the end of the arg name. */
2264 while (is_idchar[(int) *bp])
2267 /* do we have a "special" rest-args extension here? */
2268 if (limit - bp > size_toInt (REST_EXTENSION_LENGTH)
2269 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
2272 temp->rest_args = 1;
2273 /*@innerbreak@*/ break;
2277 temp->length = size_fromInt (bp - temp->name);
2281 bp += REST_EXTENSION_LENGTH;
2284 arglengths += temp->length + 2;
2285 SKIP_WHITE_SPACE (bp);
2287 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
2288 cppReader_errorLit (pfile,
2289 cstring_makeLiteralTemp ("Parameter list for #define is not parseable"));
2295 SKIP_WHITE_SPACE (bp);
2298 cppReader_errorLit (pfile,
2299 cstring_makeLiteralTemp ("unterminated parameter list in `#define'"));
2303 struct arglist *otemp;
2305 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
2307 if (temp->length == otemp->length &&
2308 strncmp (temp->name, otemp->name, temp->length) == 0) {
2309 cstring name = cstring_copyLength (temp->name, temp->length);
2310 cppReader_error (pfile,
2311 message ("duplicate argument name `%x' in `#define'", name));
2318 ++bp; /* skip paren */
2319 SKIP_WHITE_SPACE (bp);
2320 /* now everything from bp before limit is the definition. */
2321 defn = collect_expansion (pfile, bp, limit, argno, arg_ptrs);
2322 defn->rest_args = rest_args;
2324 /* Now set defn->args.argnames to the result of concatenating
2325 the argument names in reverse order
2326 with comma-space between them. */
2327 defn->args.argnames = (char *) dmalloc (size_fromInt (arglengths + 1));
2330 struct arglist *temp;
2332 for (temp = arg_ptrs; temp != NULL; temp = temp->next)
2334 memcpy (&defn->args.argnames[i], temp->name, temp->length);
2336 if (temp->next != 0)
2338 defn->args.argnames[i++] = ',';
2339 defn->args.argnames[i++] = ' ';
2343 defn->args.argnames[i] = '\0';
2348 /* Simple expansion or empty definition. */
2352 if (is_hor_space[(int) *bp]) {
2354 SKIP_WHITE_SPACE (bp);
2357 case '!': case '\"': case '#': case '%': case '&': case '\'':
2358 case ')': case '*': case '+': case ',': case '-': case '.':
2359 case '/': case ':': case ';': case '<': case '=': case '>':
2360 case '?': case '[': case '\\': case ']': case '^': case '{':
2361 case '|': case '}': case '~':
2362 cppReader_warning (pfile,
2363 message ("Missing white space after #define %x",
2364 cstring_prefix (cstring_fromChars (symname),
2369 cppReader_pedwarn (pfile,
2370 message ("Missing white space after #define %x",
2371 cstring_prefix (cstring_fromChars (symname),
2377 /* now everything from bp before limit is the definition. */
2378 defn = collect_expansion (pfile, bp, limit, -1, NULL);
2379 defn->args.argnames = mstring_createEmpty ();
2382 defn->noExpand = noExpand;
2383 DPRINTF (("No expand: %d", noExpand));
2387 /* not: llassert (cstring_isUndefined (defn->file)); */
2390 /* OP is null if this is a predefinition */
2391 defn->predefined = predefinition;
2393 mdef.symnam = symname;
2394 mdef.symlen = sym_length;
2405 cpplib_createDefinition (cstring def,
2410 char *buf = cstring_toCharsSafe (def);
2411 char *limit = buf + cstring_length (def);
2412 char *bp; /* temp ptr into input buffer */
2413 char *symname; /* remember where symbol name starts */
2414 size_t sym_length; /* and how long it is */
2415 int rest_args = 0; /* really int! */
2416 int line = fileloc_lineno (loc);
2417 cstring file = fileloc_filename (loc);
2419 int arglengths = 0; /* Accumulate lengths of arg names
2420 plus number of args. */
2425 DPRINTF (("Creating definition: %s", buf));
2427 while (is_hor_space[(int) *bp])
2432 symname = bp; /* remember where it starts */
2434 sym_length = cppReader_checkMacroNameLoc (loc, symname, cstring_makeLiteralTemp ("macro"));
2436 DPRINTF (("length: %d", sym_length));
2440 DPRINTF (("Here: %s", bp));
2442 /* Lossage will occur if identifiers or control keywords are broken
2443 across lines using backslash. This is not the right place to take
2447 struct arglist *arg_ptrs = NULL;
2450 bp++; /* skip '(' */
2451 SKIP_WHITE_SPACE (bp);
2453 /* Loop over macro argument names. */
2456 struct arglist *temp = (struct arglist *) dmalloc (sizeof (*temp));
2458 temp->next = arg_ptrs;
2459 temp->argno = argno++;
2460 temp->rest_args = 0;
2466 voptgenerror (FLG_PREPROC,
2467 message ("Another parameter follows %s",
2468 cstring_fromChars (rest_extension)),
2472 if (!is_idstart[(int) *bp])
2474 voptgenerror (FLG_PREPROC,
2475 message ("Invalid character in macro parameter name: %c", *bp),
2479 /* Find the end of the arg name. */
2480 while (is_idchar[(int) *bp])
2483 /* do we have a "special" rest-args extension here? */
2484 if (limit - bp > size_toInt (REST_EXTENSION_LENGTH)
2485 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
2488 temp->rest_args = 1;
2489 /*@innerbreak@*/ break;
2493 temp->length = size_fromInt (bp - temp->name);
2497 bp += REST_EXTENSION_LENGTH;
2500 arglengths += temp->length + 2;
2501 SKIP_WHITE_SPACE (bp);
2503 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
2504 voptgenerror (FLG_PREPROC,
2505 cstring_makeLiteral ("Parameter list for #define is not parseable"),
2512 SKIP_WHITE_SPACE (bp);
2515 voptgenerror (FLG_PREPROC,
2516 cstring_makeLiteral ("Unterminated parameter list in #define'"),
2521 struct arglist *otemp;
2523 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
2525 if (temp->length == otemp->length &&
2526 strncmp (temp->name, otemp->name, temp->length) == 0) {
2527 cstring name = cstring_copyLength (temp->name, temp->length);
2529 voptgenerror (FLG_PREPROC,
2530 message ("Duplicate argument name in #define: %s", name),
2538 ++bp; /* skip paren */
2539 SKIP_WHITE_SPACE (bp);
2540 /* now everything from bp before limit is the definition. */
2541 defn = collect_expansionLoc (loc, bp, limit, argno, arg_ptrs);
2542 defn->rest_args = rest_args;
2544 /* Now set defn->args.argnames to the result of concatenating
2545 the argument names in reverse order
2546 with comma-space between them. */
2547 defn->args.argnames = (char *) dmalloc (size_fromInt (arglengths + 1));
2550 struct arglist *temp;
2552 for (temp = arg_ptrs; temp != NULL; temp = temp->next) {
2553 memcpy (&defn->args.argnames[i], temp->name, temp->length);
2555 if (temp->next != 0) {
2556 defn->args.argnames[i++] = ',';
2557 defn->args.argnames[i++] = ' ';
2561 defn->args.argnames[i] = '\0';
2566 /* Simple expansion or empty definition. */
2570 if (is_hor_space[(int) *bp]) {
2572 SKIP_WHITE_SPACE (bp);
2575 case '!': case '\"': case '#': case '%': case '&': case '\'':
2576 case ')': case '*': case '+': case ',': case '-': case '.':
2577 case '/': case ':': case ';': case '<': case '=': case '>':
2578 case '?': case '[': case '\\': case ']': case '^': case '{':
2579 case '|': case '}': case '~':
2580 voptgenerror (FLG_PREPROC,
2581 message ("Missing white space after #define %x",
2582 cstring_prefix (cstring_fromChars (symname),
2588 voptgenerror (FLG_PREPROC,
2589 message ("Missing white space after #define %x",
2590 cstring_prefix (cstring_fromChars (symname),
2598 /* now everything from bp before limit is the definition. */
2599 llassert (limit > bp);
2600 defn = collect_expansionLoc (loc, bp, limit, -1, NULL);
2601 defn->args.argnames = mstring_createEmpty ();
2604 defn->noExpand = noExpand;
2605 DPRINTF (("No expand: %d", noExpand));
2609 /* not: llassert (cstring_isUndefined (defn->file)); */
2612 /* OP is null if this is a predefinition */
2613 defn->predefined = predefinition;
2616 mdef.symnam = symname;
2617 mdef.symlen = sym_length;
2627 /* Check a purported macro name SYMNAME, and yield its length.
2628 USAGE is the kind of name this is intended for. */
2630 size_t cppReader_checkMacroName (cppReader *pfile, char *symname, cstring usage)
2635 for (p = symname; is_idchar[(int) *p]; p++)
2640 sym_length = size_fromInt (p - symname);
2643 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '\"')))
2645 cppReader_error (pfile, message ("invalid %s name", usage));
2647 else if (!is_idstart[(int) *symname])
2649 char *msg = (char *) dmalloc (sym_length + 1);
2650 memcpy (msg, symname, sym_length);
2651 msg[sym_length] = '\0';
2652 cppReader_error (pfile, message ("invalid %s name `%s'", usage,
2653 cstring_fromChars (msg)));
2658 if ((strncmp (symname, "defined", 7) == 0) && sym_length == 7)
2660 cppReader_error (pfile, message ("invalid %s name `defined'", usage));
2669 ** Gasp...cut-and-pasted from above to deal with pfile (should replace throughout with this...)
2672 size_t cppReader_checkMacroNameLoc (fileloc loc, char *symname, cstring usage)
2677 for (p = symname; is_idchar[(int) *p]; p++)
2682 sym_length = size_fromInt (p - symname);
2685 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '\"')))
2687 voptgenerror (FLG_PREPROC, message ("Invalid %s name: %s", usage,
2688 cstring_fromChars (symname)), loc);
2690 else if (!is_idstart[(int) *symname])
2692 char *msg = (char *) dmalloc (sym_length + 1);
2693 memcpy (msg, symname, sym_length);
2694 msg[sym_length] = '\0';
2695 voptgenerror (FLG_PREPROC, message ("Invalid %s name: %s", usage,
2696 cstring_fromChars (msg)),
2702 if ((strncmp (symname, "defined", 7) == 0) && sym_length == 7)
2704 voptgenerror (FLG_PREPROC, message ("Invalid %s name: defined", usage), loc);
2711 /* Return zero if two DEFINITIONs are isomorphic. */
2714 compare_defs (DEFINITION *d1, DEFINITION *d2)
2716 register struct reflist *a1, *a2;
2717 register char *p1 = d1->expansion;
2718 register char *p2 = d2->expansion;
2721 if (d1->nargs != d2->nargs)
2726 llassert (d1->args.argnames != NULL);
2727 llassert (d2->args.argnames != NULL);
2729 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames) != 0)
2734 for (a1 = d1->pattern, a2 = d2->pattern;
2735 (a1 != NULL) && (a2 != NULL);
2736 a1 = a1->next, a2 = a2->next) {
2737 if (!((a1->nchars == a2->nchars
2738 && (strncmp (p1, p2, size_fromInt (a1->nchars)) == 0))
2739 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
2740 || a1->argno != a2->argno
2741 || a1->stringify != a2->stringify
2742 || a1->raw_before != a2->raw_before
2743 || a1->raw_after != a2->raw_after)
2752 if (comp_def_part (first, p1, size_toInt (d1->length - (p1 - d1->expansion)),
2753 p2, size_toInt (d2->length - (p2 - d2->expansion)), 1))
2759 /* Return TRUE if two parts of two macro definitions are effectively different.
2760 One of the parts starts at BEG1 and has LEN1 chars;
2761 the other has LEN2 chars at BEG2.
2762 Any sequence of whitespace matches any other sequence of whitespace.
2763 FIRST means these parts are the first of a macro definition;
2764 so ignore leading whitespace entirely.
2765 LAST means these parts are the last of a macro definition;
2766 so ignore trailing whitespace entirely. */
2769 comp_def_part (bool first, char *beg1, int len1, char *beg2, int len2, bool last)
2771 char *end1 = beg1 + len1;
2772 char *end2 = beg2 + len2;
2775 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2776 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2779 while (beg1 != end1 && is_space[(int) end1[-1]]) { end1--; }
2780 while (beg2 != end2 && is_space[(int) end2[-1]]) { end2--; }
2782 while (beg1 != end1 && beg2 != end2) {
2783 if (is_space[(int) *beg1] && is_space[(int) *beg2]) {
2784 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2785 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2786 } else if (*beg1 == *beg2) {
2790 return (beg1 != end1) || (beg2 != end2);
2793 /* Process a #define command.
2794 BUF points to the contents of the #define command, as a contiguous string.
2795 LIMIT points to the first character past the end of the definition.
2796 KEYWORD is the keyword-table entry for #define,
2797 or NULL for a "predefined" macro. */
2800 do_defineAux (cppReader *pfile, struct directive *keyword,
2801 /*@exposed@*/ char *buf, char *limit, bool noExpand)
2807 DPRINTF (("Define aux: %d", noExpand));
2809 mdef = create_definition (buf, limit, pfile, keyword == NULL, noExpand);
2814 hashcode = cpphash_hashCode (mdef.symnam, mdef.symlen, CPP_HASHSIZE);
2816 DPRINTF (("Macro: %s / %s",
2817 cstring_copyLength (mdef.symnam, mdef.symlen),
2818 bool_unparse (noExpand)));
2820 if ((hp = cpphash_lookup (mdef.symnam, size_toInt (mdef.symlen), hashcode)) != NULL)
2824 /* Redefining a precompiled key is ok. */
2825 if (hp->type == T_PCSTRING)
2827 /* Redefining a macro is ok if the definitions are the same. */
2828 else if (hp->type == T_MACRO)
2829 ok = !compare_defs (mdef.defn, hp->value.defn);
2830 /* Redefining a constant is ok with -D. */
2831 else if (hp->type == T_CONST)
2832 ok = !CPPOPTIONS (pfile)->done_initializing;
2837 /* Print the warning if it's not ok. */
2841 ** If we are passing through #define and #undef directives, do
2842 ** that for this re-definition now.
2845 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2847 /* llassert (keyword != NULL); */
2848 pass_thru_directive (buf, limit, pfile, keyword);
2851 cpp_setLocation (pfile);
2853 if (hp->type == T_MACRO)
2855 if (hp->value.defn->noExpand)
2857 ; /* error will be reported checking macros */
2863 message ("Macro %q already defined",
2864 cstring_copyLength (mdef.symnam, mdef.symlen)),
2865 message ("%q: Previous definition of %q",
2866 fileloc_unparseRaw (hp->value.defn->file,
2867 (int) hp->value.defn->line),
2868 cstring_copyLength (mdef.symnam, mdef.symlen)));
2873 genppllerror (FLG_MACROREDEF,
2874 message ("Macro %q already defined",
2875 cstring_copyLength (mdef.symnam,
2881 /* Replace the old definition. */
2883 hp->value.defn = mdef.defn;
2888 ** If we are passing through #define and #undef directives, do
2889 ** that for this new definition now.
2894 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2896 pass_thru_directive (buf, limit, pfile, keyword);
2899 DPRINTF (("Define macro: %s / %d",
2900 mdef.symnam, mdef.defn->noExpand));
2902 hn = cpphash_installMacro (mdef.symnam, mdef.symlen, mdef.defn, hashcode);
2904 } /*@=branchstate@*/
2914 do_define (cppReader *pfile, struct directive *keyword,
2915 /*@exposed@*/ char *buf, char *limit)
2917 DPRINTF (("Regular do define"));
2918 return do_defineAux (pfile, keyword, buf, limit, FALSE);
2921 /* This structure represents one parsed argument in a macro call.
2922 `raw' points to the argument text as written (`raw_length' is its length).
2923 `expanded' points to the argument's macro-expansion
2924 (its length is `expand_length').
2925 `stringified_length' is the length the argument would have
2927 `use_count' is the number of times this macro arg is substituted
2928 into the macro. If the actual use count exceeds 10,
2929 the value stored is 10. */
2931 /* raw and expanded are relative to ARG_BASE */
2933 #define ARG_BASE ((pfile)->token_buffer)
2936 /* Strings relative to pfile->token_buffer */
2942 int stringified_length;
2947 /* Allocate a new cppBuffer for PFILE, and push it on the input buffer stack.
2948 If BUFFER != NULL, then use the LENGTH characters in BUFFER
2949 as the new input buffer.
2950 Return the new buffer, or NULL on failure. */
2952 /*@null@*/ /*@exposed@*/ cppBuffer *
2953 cppReader_pushBuffer (cppReader *pfile, char *buffer, size_t length)
2955 cppBuffer *buf = cppReader_getBufferSafe (pfile);
2957 if (buf == pfile->buffer_stack)
2959 cppReader_fatalError
2961 message ("%s: macro or `#include' recursion too deep",
2962 (buf->fname != NULL)
2964 : cstring_makeLiteral ("<no name>")));
2965 sfreeEventually (buffer);
2969 llassert (buf != NULL);
2972 memset ((char *) buf, 0, sizeof (*buf));
2973 DPRINTF (("Pushing buffer: %s", cstring_copyLength (buffer, length)));
2974 CPPBUFFER (pfile) = buf;
2976 buf->if_stack = pfile->if_stack;
2977 buf->cleanup = cppReader_nullCleanup;
2978 buf->underflow = cppReader_nullUnderflow;
2980 buf->cur = buf->buf;
2984 buf->alimit = buf->rlimit = buffer + length;
2988 buf->alimit = buf->rlimit = NULL;
2995 cppReader_popBuffer (cppReader *pfile)
2997 cppBuffer *buf = CPPBUFFER (pfile);
2999 llassert (buf != NULL);
3001 (void) (*buf->cleanup) (buf, pfile);
3002 return ++CPPBUFFER (pfile);
3005 /* Scan until CPPBUFFER (PFILE) is exhausted into PFILE->token_buffer.
3006 Pop the buffer when done. */
3009 cppReader_scanBuffer (cppReader *pfile)
3011 cppBuffer *buffer = CPPBUFFER (pfile);
3014 enum cpp_token token;
3016 token = cpplib_getToken (pfile);
3018 if (token == CPP_EOF) /* Should not happen ... */
3023 if (token == CPP_POP && CPPBUFFER (pfile) == buffer)
3025 (void) cppReader_popBuffer (pfile);
3033 * Rescan a string (which may have escape marks) into pfile's buffer.
3034 * Place the result in pfile->token_buffer.
3036 * The input is copied before it is scanned, so it is safe to pass
3037 * it something from the token_buffer that will get overwritten
3038 * (because it follows cpplib_getWritten). This is used by do_include.
3042 cpp_expand_to_buffer (cppReader *pfile, char *buf, size_t length)
3044 register cppBuffer *ip;
3045 char *limit = buf + length;
3046 char *buf1, *p1, *p2;
3048 DPRINTF (("Expand to buffer: %s", cstring_copyLength (buf, length)));
3050 /* evans - 2001-08-26
3051 ** length is unsigned - this doesn't make sense
3057 /* Set up the input on the input stack. */
3059 buf1 = (char *) dmalloc (length + 1);
3069 buf1[length] = '\0';
3071 ip = cppReader_pushBuffer (pfile, buf1, length);
3076 ip->has_escapes = TRUE;
3078 /* Scan the input, create the output. */
3079 cppReader_scanBuffer (pfile);
3081 cppReader_nullTerminate (pfile);
3085 adjust_position (char *buf, char *limit, int *linep, int *colp)
3091 (*linep)++, (*colp) = 1;
3097 /* Move line_base forward, updating lineno and colno. */
3100 update_position (cppBuffer *pbuf)
3103 char *new_pos = pbuf->cur;
3104 register struct parse_marker *mark;
3106 llassert (pbuf->buf != NULL);
3107 old_pos = pbuf->buf + pbuf->line_base;
3109 for (mark = pbuf->marks; mark != NULL; mark = mark->next)
3111 if (pbuf->buf + mark->position < new_pos)
3112 new_pos = pbuf->buf + mark->position;
3114 pbuf->line_base += new_pos - old_pos;
3116 llassert (old_pos != NULL);
3117 llassert (new_pos != NULL);
3119 adjust_position (old_pos, new_pos, &pbuf->lineno, &pbuf->colno);
3123 cppBuffer_getLineAndColumn (/*@null@*/ cppBuffer *pbuf, /*@out@*/ int *linep,
3124 /*@null@*/ /*@out@*/ int *colp)
3132 } /*@=branchstate@*/
3136 *linep = pbuf->lineno;
3137 *colp = pbuf->colno;
3139 llassert (pbuf->buf != NULL);
3140 llassert (pbuf->cur != NULL);
3142 adjust_position (pbuf->buf + pbuf->line_base, pbuf->cur, linep, colp);
3151 /* Return the cppBuffer that corresponds to a file (not a macro). */
3153 /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_fileBuffer (cppReader *pfile)
3155 cppBuffer *ip = cppReader_getBuffer (pfile);
3158 ip != NULL && ip != cppReader_nullBuffer (pfile);
3159 ip = cppBuffer_prevBuffer (ip))
3161 if (ip->fname != NULL)
3171 count_newlines (char *buf, char *limit)
3173 register long count = 0;
3185 * write out a #line command, for instance, after an #include file.
3186 * If CONDITIONAL is nonzero, we can omit the #line if it would
3187 * appear to be a no-op, and we can output a few newlines instead
3188 * if we want to increase the line number by a small amount.
3189 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
3193 output_line_command (cppReader *pfile, bool conditional,
3194 enum file_change_code file_change)
3197 cppBuffer *ip = CPPBUFFER (pfile);
3200 llassert (ip != NULL);
3202 if (ip->fname == NULL)
3205 update_position (ip);
3207 if (CPPOPTIONS (pfile)->no_line_commands
3208 || CPPOPTIONS (pfile)->no_output)
3211 buf = CPPBUFFER (pfile);
3213 llassert (buf != NULL);
3218 llassert (ip->cur != NULL);
3220 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
3222 if (CPPOPTIONS (pfile)->no_line_commands)
3226 if (line == pfile->lineno)
3229 /* If the inherited line number is a little too small,
3230 output some newlines instead of a #line command. */
3232 if (line > pfile->lineno && line < pfile->lineno + 8)
3234 cpplib_reserve (pfile, 20);
3235 while (line > pfile->lineno)
3237 cppReader_putCharQ (pfile, '\n');
3245 cpplib_reserve (pfile, 4 * cstring_length (ip->nominal_fname) + 50);
3248 #ifdef OUTPUT_LINE_COMMANDS
3249 static char sharp_line[] = "#line ";
3251 static char sharp_line[] = "# ";
3253 cppReader_putStrN (pfile, sharp_line, sizeof(sharp_line)-1);
3256 sprintf (cpplib_getPWritten (pfile), "%d ", line);
3257 cppReader_adjustWritten (pfile, strlen (cpplib_getPWritten (pfile)));
3259 quote_string (pfile, cstring_toCharsSafe (ip->nominal_fname));
3261 if (file_change != same_file) {
3262 cppReader_putCharQ (pfile, ' ');
3263 cppReader_putCharQ (pfile, file_change == enter_file ? '1' : '2');
3265 /* Tell cc1 if following text comes from a system header file. */
3266 if (ip->system_header_p != '\0') {
3267 cppReader_putCharQ (pfile, ' ');
3268 cppReader_putCharQ (pfile, '3');
3270 #ifndef NO_IMPLICIT_EXTERN_C
3271 /* Tell cc1plus if following text should be treated as C. */
3272 if (ip->system_header_p == (char) 2 && CPPOPTIONS (pfile)->cplusplus) {
3273 cppReader_putCharQ (pfile, ' ');
3274 cppReader_putCharQ (pfile, '4');
3277 cppReader_putCharQ (pfile, '\n');
3278 pfile->lineno = line;
3283 * Parse a macro argument and append the info on PFILE's token_buffer.
3284 * REST_ARGS means to absorb the rest of the args.
3285 * Return nonzero to indicate a syntax error.
3288 static enum cpp_token
3289 macarg (cppReader *pfile, int rest_args)
3292 enum cpp_token token;
3293 char save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
3294 bool oldexpand = pfile->no_macro_expand;
3295 CPPOPTIONS (pfile)->put_out_comments = 1;
3297 /* Try to parse as much of the argument as exists at this
3298 input stack level. */
3300 pfile->no_macro_expand = TRUE;
3304 token = cpplib_getToken (pfile);
3311 /* If we've hit end of file, it's an error (reported by caller).
3312 Ditto if it's the end of cpp_expand_to_buffer text.
3313 If we've hit end of macro, just continue. */
3314 if (!cppBuffer_isMacro (CPPBUFFER (pfile)))
3316 /*@switchbreak@*/ break;
3319 /*@switchbreak@*/ break;
3323 /*@switchbreak@*/ break;
3325 /* if we've returned to lowest level and
3326 we aren't absorbing all args */
3327 if (paren == 0 && rest_args == 0)
3329 /*@switchbreak@*/ break;
3331 /* Remove ',' or ')' from argument buffer. */
3332 cppReader_adjustWritten (pfile, -1);
3340 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
3341 pfile->no_macro_expand = oldexpand;
3347 /* Turn newlines to spaces in the string of length LENGTH at START,
3348 except inside of string constants.
3349 The string is copied into itself with its beginning staying fixed. */
3352 change_newlines (char *start, int length)
3356 register char *limit;
3360 limit = start + length;
3363 while (ibp < limit) {
3364 *obp++ = c = *ibp++;
3369 /* Notice and skip strings, so that we don't delete newlines in them. */
3372 while (ibp < limit) {
3373 *obp++ = c = *ibp++;
3375 /*@innerbreak@*/ break;
3376 if (c == '\n' && quotec == '\'')
3377 /*@innerbreak@*/ break;
3380 /*@switchbreak@*/ break;
3387 static /*@observer@*/ struct tm *
3388 timestamp (/*@returned@*/ cppReader *pfile)
3390 if (pfile->timebuf == NULL)
3392 time_t t = time ((time_t *) 0);
3393 pfile->timebuf = localtime (&t);
3396 llassert (pfile->timebuf != NULL);
3398 return pfile->timebuf;
3401 static ob_mstring monthnames[] = {
3402 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3403 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3407 * expand things like __FILE__. Place the expansion into the output
3408 * buffer *without* rescanning.
3412 special_symbol (hashNode hp, cppReader *pfile)
3414 cstring buf = cstring_undefined;
3420 int paren = 0; /* For special `defined' keyword */
3422 for (ip = cppReader_getBuffer (pfile); ip != NULL; ip = cppBuffer_prevBuffer (ip))
3424 if (ip == cppReader_nullBuffer (pfile))
3426 cppReader_errorLit (pfile,
3427 cstring_makeLiteralTemp ("cccp error: not in any file?!"));
3428 return; /* the show must go on */
3431 if (ip != NULL && ip->fname != NULL)
3443 if (hp->type == T_BASE_FILE)
3445 while (cppBuffer_prevBuffer (ip) != cppReader_nullBuffer (pfile))
3447 ip = cppBuffer_prevBuffer (ip);
3451 llassert (ip != NULL);
3452 string = cstring_toCharsSafe (ip->nominal_fname);
3459 cpplib_reserve (pfile, 3 + 4 * strlen (string));
3460 quote_string (pfile, string);
3464 case T_INCLUDE_LEVEL:
3466 ip = cppReader_getBuffer (pfile);
3468 for (; ip != cppReader_nullBuffer (pfile) && ip != NULL;
3469 ip = cppBuffer_prevBuffer (ip))
3471 if (ip != NULL && ip->fname != NULL)
3477 buf = message ("%d", true_indepth - 1);
3481 buf = cstring_makeLiteral ("\"--- cpp version---\"");
3484 #ifndef NO_BUILTIN_SIZE_TYPE
3486 buf = cstring_makeLiteral (SIZE_TYPE);
3490 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3491 case T_PTRDIFF_TYPE:
3492 buf = cstring_makeLiteral (PTRDIFF_TYPE);
3497 buf = cstring_makeLiteral (cppReader_wcharType (pfile));
3500 case T_USER_LABEL_PREFIX_TYPE:
3501 buf = cstring_makeLiteral (USER_LABEL_PREFIX);
3504 case T_REGISTER_PREFIX_TYPE:
3505 buf = cstring_makeLiteral (REGISTER_PREFIX);
3509 buf = message ("%d", hp->value.ival);
3516 int line = ip->lineno;
3517 int col = ip->colno;
3519 llassert (ip->cur != NULL);
3520 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
3522 buf = message ("%d", (int) line);
3534 char *sbuf = (char *) dmalloc (20);
3535 timebuf = timestamp (pfile);
3536 if (hp->type == T_DATE)
3538 sprintf (sbuf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
3539 timebuf->tm_mday, timebuf->tm_year + 1900);
3543 sprintf (sbuf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
3547 buf = cstring_fromCharsNew (sbuf);
3552 case T_SPEC_DEFINED:
3553 buf = cstring_makeLiteral (" 0 "); /* Assume symbol is not defined */
3554 ip = cppReader_getBuffer (pfile);
3555 llassert (ip != NULL);
3556 llassert (ip->cur != NULL);
3557 SKIP_WHITE_SPACE (ip->cur);
3559 if (*ip->cur == '(')
3562 ip->cur++; /* Skip over the paren */
3563 SKIP_WHITE_SPACE (ip->cur);
3566 if (!is_idstart[(int) *ip->cur])
3568 if (ip->cur[0] == 'L' && (ip->cur[1] == '\'' || ip->cur[1] == '\"'))
3571 if ((hp = cpphash_lookup (ip->cur, -1, -1)) != 0)
3574 buf = cstring_makeLiteral (" 1 ");
3577 while (is_idchar[(int) *ip->cur])
3582 SKIP_WHITE_SPACE (ip->cur);
3586 if (*ip->cur != ')')
3594 cppReader_errorLit (pfile,
3595 cstring_makeLiteralTemp ("`defined' without an identifier"));
3599 cpp_setLocation (pfile);
3600 llfatalerror (message ("Pre-processing error: invalid special hash type"));
3603 len = cstring_length (buf);
3605 cpplib_reserve (pfile, len + 1);
3606 cppReader_putStrN (pfile, cstring_toCharsSafe (buf), len);
3607 cppReader_nullTerminateQ (pfile);
3613 /* Write out a #define command for the special named MACRO_NAME
3614 to PFILE's token_buffer. */
3617 dump_special_to_buffer (cppReader *pfile, char *macro_name)
3619 static char define_directive[] = "#define ";
3620 size_t macro_name_length = strlen (macro_name);
3621 output_line_command (pfile, 0, same_file);
3622 cpplib_reserve (pfile, sizeof(define_directive) + macro_name_length);
3623 cppReader_putStrN (pfile, define_directive, sizeof(define_directive)-1);
3624 cppReader_putStrN (pfile, macro_name, macro_name_length);
3625 cppReader_putCharQ (pfile, ' ');
3626 cpp_expand_to_buffer (pfile, macro_name, macro_name_length);
3627 cppReader_putChar (pfile, '\n');
3630 /* Initialize the built-in macros. */
3633 cpplib_installBuiltin (/*@observer@*/ char *name, ctype ctyp,
3634 int len, enum node_type type,
3635 int ivalue, /*@null@*/ /*@only@*/ char *value,
3638 cstring sname = cstring_fromCharsNew (name);
3640 llassert (usymtab_inGlobalScope ());
3643 ** Be careful here: this is done before the ctype table has
3644 ** been initialized.
3647 if (!usymtab_exists (sname))
3649 uentry ue = uentry_makeConstant (sname, ctyp, fileloc_createBuiltin ());
3651 if (ctype_equal (ctyp, ctype_string))
3653 qualList ql = qualList_new ();
3654 ql = qualList_add (ql, qual_createObserver ());
3655 uentry_reflectQualifiers (ue, ql);
3659 usymtab_addGlobalEntry (ue);
3666 (void) cpphash_install (name, len, type, ivalue, value, hash);
3667 cstring_free (sname);
3671 cpplib_installBuiltinType (/*@observer@*/ char *name, ctype ctyp,
3672 int len, enum node_type type,
3674 /*@only@*/ /*@null@*/ char *value, int hash)
3676 cstring sname = cstring_fromChars (name);
3677 /* evs 2000 07 10 - removed a memory leak, detected by splint */
3679 llassert (usymtab_inGlobalScope ());
3681 if (!usymtab_existsTypeEither (sname))
3683 uentry ue = uentry_makeDatatype (sname, ctyp,
3684 NO, qual_createConcrete (),
3685 fileloc_createBuiltin ());
3686 llassert (!usymtab_existsEither (sname));
3687 usymtab_addGlobalEntry (ue);
3690 (void) cpphash_install (name, len, type, ivalue, value, hash);
3694 initialize_builtins (cppReader *pfile)
3696 cpplib_installBuiltin ("__LINE__", ctype_int, -1, T_SPECLINE, 0, NULL, -1);
3697 cpplib_installBuiltin ("__DATE__", ctype_string, -1, T_DATE, 0, NULL, -1);
3698 cpplib_installBuiltin ("__FILE__", ctype_string, -1, T_FILE, 0, NULL, -1);
3699 cpplib_installBuiltin ("__BASE_FILE__", ctype_string, -1, T_BASE_FILE, 0, NULL, -1);
3700 cpplib_installBuiltin ("__INCLUDE_LEVEL__", ctype_int, -1, T_INCLUDE_LEVEL, 0, NULL, -1);
3701 cpplib_installBuiltin ("__VERSION__", ctype_string, -1, T_VERSION, 0, NULL, -1);
3702 #ifndef NO_BUILTIN_SIZE_TYPE
3703 cpplib_installBuiltinType ("__SIZE_TYPE__", ctype_anyintegral, -1, T_SIZE_TYPE, 0, NULL, -1);
3705 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3706 cpplib_installBuiltinType ("__PTRDIFF_TYPE__", ctype_anyintegral, -1, T_PTRDIFF_TYPE, 0, NULL, -1);
3708 cpplib_installBuiltinType ("__WCHAR_TYPE__", ctype_anyintegral, -1, T_WCHAR_TYPE, 0, NULL, -1);
3709 cpplib_installBuiltin ("__USER_LABEL_PREFIX__", ctype_string, -1, T_USER_LABEL_PREFIX_TYPE, 0, NULL, -1);
3710 cpplib_installBuiltin ("__REGISTER_PREFIX__", ctype_string, -1, T_REGISTER_PREFIX_TYPE, 0, NULL, -1);
3711 cpplib_installBuiltin ("__TIME__", ctype_string, -1, T_TIME, 0, NULL, -1);
3714 ** No, don't define __STDC__
3717 if (!cppReader_isTraditional (pfile))
3719 cpplib_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3726 cpplib_installBuiltin ("_WIN32", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3730 ** This is supplied using a -D by the compiler driver
3731 ** so that it is present only when truly compiling with GNU C.
3734 /* cpplib_install ("__GNUC__", -1, T_CONST, 2, 0, -1); */
3736 cpplib_installBuiltin ("S_SPLINT_S", ctype_int, -1, T_CONST, 2, NULL, -1);
3737 cpplib_installBuiltin ("__LCLINT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3739 /*drl 1/9/2001/ try to define the right symbol for the architecture
3740 We use autoconf to determine the target cpu
3742 cpplib_installBuiltin ("__" TARGET_CPU, ctype_int, -1, T_CONST, 2, NULL, -1);
3744 /*drl 1/2/2002 set some flags based on uname
3745 I'd like to be able to do this with autoconf macro instead...
3748 /*Thanks to Nelson Beebe for suggesting possible values for these */
3750 if (! strcmp (UNAME, "Linux"))
3753 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3757 else if(! strcmp (UNAME, "Darwin"))
3759 cpplib_installBuiltin ("__ppc__", ctype_int, -1, T_CONST, 2, NULL, -1);
3760 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3762 else if(! strcmp (UNAME, "HP-UX"))
3764 cpplib_installBuiltin ("PWB", ctype_int, -1, T_CONST, 2, NULL, -1);
3765 cpplib_installBuiltin ("_HIUX_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3766 cpplib_installBuiltin ("_HPUX_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3767 cpplib_installBuiltin ("_PA_RISC1_1", ctype_int, -1, T_CONST, 2, NULL, -1);
3768 cpplib_installBuiltin ("__PWB", ctype_int, -1, T_CONST, 2, NULL, -1);
3769 cpplib_installBuiltin ("__PWB__", ctype_int, -1, T_CONST, 2, NULL, -1);
3770 cpplib_installBuiltin ("__STDC_EXT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3771 cpplib_installBuiltin ("__hp9000s700", ctype_int, -1, T_CONST, 2, NULL, -1);
3772 cpplib_installBuiltin ("__hp9000s800", ctype_int, -1, T_CONST, 2, NULL, -1);
3773 cpplib_installBuiltin ("__hp9000s800__", ctype_int, -1, T_CONST, 2, NULL, -1);
3774 cpplib_installBuiltin ("__hp9k8", ctype_int, -1, T_CONST, 2, NULL, -1);
3775 cpplib_installBuiltin ("__hp9k8__", ctype_int, -1, T_CONST, 2, NULL, -1);
3776 cpplib_installBuiltin ("__hppa", ctype_int, -1, T_CONST, 2, NULL, -1);
3777 cpplib_installBuiltin ("__hppa__", ctype_int, -1, T_CONST, 2, NULL, -1);
3778 cpplib_installBuiltin ("__hpux", ctype_int, -1, T_CONST, 2, NULL, -1);
3779 cpplib_installBuiltin ("__hpux__", ctype_int, -1, T_CONST, 2, NULL, -1);
3780 cpplib_installBuiltin ("__unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3781 cpplib_installBuiltin ("__unix__", ctype_int, -1, T_CONST, 2, NULL, -1);
3782 cpplib_installBuiltin ("hp9000s800", ctype_int, -1, T_CONST, 2, NULL, -1);
3783 cpplib_installBuiltin ("hp9k8", ctype_int, -1, T_CONST, 2, NULL, -1);
3784 cpplib_installBuiltin ("hppa", ctype_int, -1, T_CONST, 2, NULL, -1);
3785 cpplib_installBuiltin ("hpux", ctype_int, -1, T_CONST, 2, NULL, -1);
3786 cpplib_installBuiltin ("unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3788 else if(! strcmp (UNAME, "IRIX64"))
3790 cpplib_installBuiltin ("LANGUAGE_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3791 cpplib_installBuiltin ("MIPSEB", ctype_int, -1, T_CONST, 2, NULL, -1);
3792 cpplib_installBuiltin ("_ABIN32", ctype_int, -1, T_CONST, 2, NULL, -1);
3793 cpplib_installBuiltin ("_COMPILER_VERSION", ctype_int, -1, T_CONST, 730, NULL, -1);
3794 cpplib_installBuiltin ("_LANGUAGE_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3795 cpplib_installBuiltin ("_LONGLONG", ctype_int, -1, T_CONST, 2, NULL, -1);
3796 cpplib_installBuiltin ("_MIPSEB", ctype_int, -1, T_CONST, 2, NULL, -1);
3797 cpplib_installBuiltin ("_MIPS_FPSET", ctype_int, -1, T_CONST, 32, NULL, -1);
3798 cpplib_installBuiltin ("_MIPS_ISA", ctype_int, -1, T_CONST, 3, NULL, -1);
3799 /*_MIPS_SIM=_ABIN32*/
3800 cpplib_installBuiltin ("_MIPS_SIM", ctype_int, -1, T_CONST, 2, NULL , -1);
3801 cpplib_installBuiltin ("_MIPS_SZINT", ctype_int, -1, T_CONST, 32, NULL, -1);
3802 cpplib_installBuiltin ("_MIPS_SZLONG", ctype_int, -1, T_CONST, 32, NULL, -1);
3803 cpplib_installBuiltin ("_MIPS_SZPTR", ctype_int, -1, T_CONST, 32, NULL, -1);
3804 cpplib_installBuiltin ("_MODERN_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3805 cpplib_installBuiltin ("_PIC", ctype_int, -1, T_CONST, 2, NULL, -1);
3806 cpplib_installBuiltin ("_SGI_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3807 cpplib_installBuiltin ("_SIZE_INT", ctype_int, -1, T_CONST, 32, NULL, -1);
3808 cpplib_installBuiltin ("_SIZE_LONG", ctype_int, -1, T_CONST, 32, NULL, -1);
3809 cpplib_installBuiltin ("_SIZE_PTR", ctype_int, -1, T_CONST, 32, NULL, -1);
3810 cpplib_installBuiltin ("_SVR4_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3811 cpplib_installBuiltin ("_SYSTYPE_SVR4", ctype_int, -1, T_CONST, 2, NULL, -1);
3812 cpplib_installBuiltin ("__DSO__", ctype_int, -1, T_CONST, 2, NULL, -1);
3813 cpplib_installBuiltin ("__EXTENSIONS__", ctype_int, -1, T_CONST, 2, NULL, -1);
3814 cpplib_installBuiltin ("__INLINE_INTRINSICS", ctype_int, -1, T_CONST, 2, NULL, -1);
3815 cpplib_installBuiltin ("__MATH_HAS_NO_SIDE_EFFECTS", ctype_int, -1, T_CONST, 2, NULL, -1);
3816 cpplib_installBuiltin ("__host_mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3817 cpplib_installBuiltin ("__mips", ctype_int, -1, T_CONST, 3, NULL, -1);
3818 cpplib_installBuiltin ("__sgi", ctype_int, -1, T_CONST, 2, NULL, -1);
3819 cpplib_installBuiltin ("__unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3820 cpplib_installBuiltin ("host_mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3821 cpplib_installBuiltin ("mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3822 cpplib_installBuiltin ("sgi", ctype_int, -1, T_CONST, 2, NULL, -1);
3823 cpplib_installBuiltin ("unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3825 else if(! strcmp (UNAME, "OSF1"))
3827 cpplib_installBuiltin ("__alpha", ctype_int, -1, T_CONST, 2, NULL, -1);
3829 else if (!strcmp (UNAME, "Rhapsody"))
3831 cpplib_installBuiltin ("__ppc__", ctype_int, -1, T_CONST, 2, NULL, -1);
3832 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3835 else if (!strcmp (UNAME, "SunOS"))
3837 cpplib_installBuiltin ("__OPEN_MAX", ctype_int, -1, T_CONST, 20, NULL, -1);
3838 cpplib_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, 2, NULL, -1);
3839 cpplib_installBuiltin ("__sparc", ctype_int, -1, T_CONST, 2, NULL, -1);
3840 /* This define "-Dfileno(f)=0" should be inserted but we're going to stick to deinfe constants for now...*/
3845 types which we have not explictedly handled.
3846 AIX, FreeBSD, IRIX, Mach
3851 if (CPPOPTIONS (pfile)->debug_output)
3853 dump_special_to_buffer (pfile, "__BASE_FILE__");
3854 dump_special_to_buffer (pfile, "__VERSION__");
3855 #ifndef NO_BUILTIN_SIZE_TYPE
3856 dump_special_to_buffer (pfile, "__SIZE_TYPE__");
3858 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3859 dump_special_to_buffer (pfile, "__PTRDIFF_TYPE__");
3861 dump_special_to_buffer (pfile, "__WCHAR_TYPE__");
3862 dump_special_to_buffer (pfile, "__DATE__");
3863 dump_special_to_buffer (pfile, "__TIME__");
3864 if (!cppReader_isTraditional (pfile))
3865 dump_special_to_buffer (pfile, "__STDC__");
3870 /* Return 1 iff a token ending in C1 followed directly by a token C2
3871 could cause mis-tokenization. */
3874 unsafe_chars (char c1, char c2)
3879 if (c2 == c1 || c2 == '=')
3883 case '0': case '1': case '2': case '3': case '4':
3884 case '5': case '6': case '7': case '8': case '9':
3885 case 'e': case 'E': case 'p': case 'P':
3886 if (c2 == '-' || c2 == '+')
3887 return 1; /* could extend a pre-processing number */
3890 if (c2 == '\'' || c2 == '\"')
3891 return 1; /* Could turn into L"xxx" or L'xxx'. */
3895 case 'a': case 'b': case 'c': case 'd': case 'f':
3896 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3897 case 'm': case 'n': case 'o': case 'q': case 'r':
3898 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3900 case 'A': case 'B': case 'C': case 'D': case 'F':
3901 case 'G': case 'H': case 'I': case 'J': case 'K':
3902 case 'M': case 'N': case 'O': case 'Q': case 'R':
3903 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3905 /* We're in the middle of either a name or a pre-processing number. */
3906 return (is_idchar[(int) c2] || c2 == '.');
3907 case '<': case '>': case '!': case '%': case '#': case ':':
3908 case '^': case '&': case '|': case '*': case '/': case '=':
3909 return (c2 == c1 || c2 == '=');
3914 /* Expand a macro call.
3915 HP points to the symbol that is the macro being called.
3916 Put the result of expansion onto the input stack
3917 so that subsequent input by our caller will use it.
3919 If macro wants arguments, caller has already verified that
3920 an argument list follows; arguments come from the input stack. */
3923 cpplib_macroExpand (cppReader *pfile, /*@dependent@*/ hashNode hp)
3926 DEFINITION *defn = hp->value.defn;
3934 size_t old_written = cpplib_getWritten (pfile);
3938 struct argdata *args = NULL;
3940 pfile->output_escapes++;
3941 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile), &start_line, &start_column);
3942 DPRINTF (("Expand macro: %d:%d", start_line, start_column));
3944 nargs = defn->nargs;
3948 enum cpp_token token = CPP_EOF;
3950 args = (struct argdata *) dmalloc ((nargs + 1) * sizeof (*args));
3952 for (i = 0; i < nargs; i++)
3954 args[i].expanded = 0;
3956 args[i].raw_length = 0;
3957 args[i].expand_length = args[i].stringified_length = -1;
3958 args[i].use_count = 0;
3962 ** Parse all the macro args that are supplied. I counts them.
3963 ** The first NARGS args are stored in ARGS.
3964 ** The rest are discarded. If rest_args is set then we assume
3965 ** macarg absorbed the rest of the args.
3971 cppReader_forward (pfile, 1); /* Discard the open-parenthesis before the first arg. */
3979 if (i < nargs || (nargs == 0 && i == 0))
3981 /* if we are working on last arg which absorbs rest of args... */
3982 if (i == nargs - 1 && defn->rest_args)
3987 args[i].raw = size_toLong (cpplib_getWritten (pfile));
3988 token = macarg (pfile, rest_args);
3989 args[i].raw_length = size_toInt (cpplib_getWritten (pfile) - args[i].raw);
3990 args[i].newlines = FALSE; /* FIXME */
3994 token = macarg (pfile, 0);
3997 if (token == CPP_EOF || token == CPP_POP)
3999 cppReader_errorWithLine (pfile, start_line, start_column,
4000 cstring_fromCharsNew ("unterminated macro call"));
4005 } while (token == CPP_COMMA);
4007 /* If we got one arg but it was just whitespace, call that 0 args. */
4015 bp = ARG_BASE + args[0].raw;
4016 lim = bp + args[0].raw_length;
4018 /* cpp.texi says for foo ( ) we provide one argument.
4019 However, if foo wants just 0 arguments, treat this as 0. */
4023 while (bp != lim && is_space[(int) *bp])
4033 /* Don't output an error message if we have already output one for
4034 a parse error above. */
4037 if (nargs == 0 && i > 0)
4039 cppReader_error (pfile,
4040 message ("arguments given to macro `%s'", hp->name));
4044 /* traditional C allows foo() if foo wants one argument. */
4045 if (nargs == 1 && i == 0 && cppReader_isTraditional (pfile))
4049 /* the rest args token is allowed to absorb 0 tokens */
4050 else if (i == nargs - 1 && defn->rest_args)
4053 cppReader_error (pfile,
4054 message ("macro `%s' used without args", hp->name));
4056 cppReader_error (pfile,
4057 message ("macro `%s' used with just one arg", hp->name));
4060 cppReader_error (pfile,
4061 message ("macro `%s' used with only %d args",
4067 cppReader_error (pfile,
4068 message ("macro `%s' used with too many (%d) args", hp->name, i));
4077 ** If the agrument list was multiple lines, need to insert new lines to keep line
4078 ** numbers accurate.
4081 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile), &end_line, &end_column);
4082 DPRINTF (("Expand macro: %d:%d", end_line, end_column));
4084 /* If macro wants zero args, we parsed the arglist for checking only.
4085 Read directly from the macro definition. */
4089 xbuf = defn->expansion;
4090 xbuf_len = defn->length;
4094 char *exp = defn->expansion;
4095 int offset; /* offset in expansion,
4096 copied a piece at a time */
4097 size_t totlen; /* total amount of exp buffer filled so far */
4099 register struct reflist *ap, *last_ap;
4101 assertSet (args); /* args is defined since the nargs > 0 path was taken */
4103 /* Macro really takes args. Compute the expansion of this call. */
4105 /* Compute length in characters of the macro's expansion.
4106 Also count number of times each arg is used. */
4107 xbuf_len = defn->length;
4109 llassert (args != NULL);
4111 for (ap = defn->pattern; ap != NULL; ap = ap->next)
4115 struct argdata *arg = &args[ap->argno];
4117 /* Stringify it it hasn't already been */
4120 if (arg->stringified_length < 0)
4122 int arglen = arg->raw_length;
4123 bool escaped = FALSE;
4124 char in_string = '\0';
4127 /* Initially need_space is -1. Otherwise, 1 means the
4128 previous character was a space, but we suppressed it;
4129 0 means the previous character was a non-space. */
4130 int need_space = -1;
4133 arg->stringified = cpplib_getWritten (pfile);
4134 if (!cppReader_isTraditional (pfile))
4135 cppReader_putChar (pfile, '\"'); /* insert beginning quote */
4136 for (; i < arglen; i++)
4138 c = (ARG_BASE + arg->raw)[i];
4140 if (in_string == '\0')
4142 /* Internal sequences of whitespace are replaced by
4143 one space except within an string or char token.*/
4144 if (is_space[(int) c])
4146 if (cpplib_getWritten (pfile) > arg->stringified
4147 && (cpplib_getPWritten (pfile))[-1] == '@')
4149 /* "@ " escape markers are removed */
4150 cppReader_adjustWritten (pfile, -1);
4151 /*@innercontinue@*/ continue;
4153 if (need_space == 0)
4155 /*@innercontinue@*/ continue;
4157 else if (need_space > 0)
4158 cppReader_putChar (pfile, ' ');
4174 if (in_string != '\0')
4179 else if (c == '\"' || c == '\'')
4189 /* Escape these chars */
4190 if (c == '\"' || (in_string != '\0' && c == '\\'))
4191 cppReader_putChar (pfile, '\\');
4193 cppReader_putChar (pfile, c);
4196 cpplib_reserve (pfile, 4);
4197 sprintf (cpplib_getPWritten (pfile), "\\%03o",
4199 cppReader_adjustWritten (pfile, 4);
4202 if (!cppReader_isTraditional (pfile))
4203 cppReader_putChar (pfile, '\"'); /* insert ending quote */
4204 arg->stringified_length
4205 = size_toInt (cpplib_getWritten (pfile) - arg->stringified);
4208 xbuf_len += args[ap->argno].stringified_length;
4210 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
4212 /* Add 4 for two newline-space markers to prevent
4213 token concatenation. */
4214 assertSet (args); /*@i534 shouldn't need this */
4215 xbuf_len += args[ap->argno].raw_length + 4;
4219 /* We have an ordinary (expanded) occurrence of the arg.
4220 So compute its expansion, if we have not already. */
4222 assertSet (args); /*@i534 shouldn't need this */
4224 if (args[ap->argno].expand_length < 0)
4226 args[ap->argno].expanded = cpplib_getWritten (pfile);
4227 cpp_expand_to_buffer (pfile,
4228 ARG_BASE + args[ap->argno].raw,
4229 size_fromInt (args[ap->argno].raw_length));
4231 args[ap->argno].expand_length
4232 = size_toInt (cpplib_getWritten (pfile) - args[ap->argno].expanded);
4235 /* Add 4 for two newline-space markers to prevent
4236 token concatenation. */
4237 xbuf_len += args[ap->argno].expand_length + 4;
4239 if (args[ap->argno].use_count < 10)
4240 args[ap->argno].use_count++;
4243 xbuf = (char *) dmalloc (xbuf_len + 1);
4247 ** Generate in XBUF the complete expansion
4248 ** with arguments substituted in.
4249 ** TOTLEN is the total size generated so far.
4250 ** OFFSET is the index in the definition
4251 ** of where we are copying from.
4257 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
4258 last_ap = ap, ap = ap->next)
4260 register struct argdata *arg = &args[ap->argno];
4261 size_t count_before = totlen;
4263 /* Add chars to XBUF. */
4264 for (i = 0; i < ap->nchars; i++, offset++)
4266 xbuf[totlen++] = exp[offset];
4269 /* If followed by an empty rest arg with concatenation,
4270 delete the last run of nonwhite chars. */
4271 if (rest_zero && totlen > count_before
4272 && ((ap->rest_args && ap->raw_before)
4273 || (last_ap != NULL && last_ap->rest_args
4274 && last_ap->raw_after)))
4276 /* Delete final whitespace. */
4277 while (totlen > count_before && is_space[(int) xbuf[totlen - 1]])
4282 /* Delete the nonwhites before them. */
4283 while (totlen > count_before && ! is_space[(int) xbuf[totlen - 1]])
4289 if (ap->stringify != 0)
4292 memcpy (xbuf + totlen,
4293 ARG_BASE + arg->stringified,
4294 size_fromInt (arg->stringified_length));
4295 totlen += arg->stringified_length;
4297 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
4304 p1 = ARG_BASE + arg->raw;
4305 l1 = p1 + arg->raw_length;
4309 while (p1 != l1 && is_space[(int) *p1])
4314 while (p1 != l1 && is_idchar[(int) *p1])
4316 xbuf[totlen++] = *p1++;
4319 /* Delete any no-reexpansion marker that follows
4320 an identifier at the beginning of the argument
4321 if the argument is concatenated with what precedes it. */
4322 if (p1[0] == '@' && p1[1] == '-')
4327 /* Arg is concatenated after: delete trailing whitespace,
4328 whitespace markers, and no-reexpansion markers. */
4331 if (is_space[(int) l1[-1]]) l1--;
4332 else if (l1[-1] == '-')
4335 /* If a `-' is preceded by an odd number of newlines then it
4336 and the last newline are a no-reexpansion marker. */
4337 while (p2 != p1 && p2[-1] == '\n')
4342 if (((l1 - 1 - p2) & 1) != 0)
4348 /*@innerbreak@*/ break;
4353 /*@innerbreak@*/ break;
4358 memcpy (xbuf + totlen, p1, size_fromInt (l1 - p1));
4366 expanded = ARG_BASE + arg->expanded;
4368 if (!ap->raw_before && totlen > 0
4369 && (arg->expand_length != 0)
4370 && !cppReader_isTraditional(pfile)
4371 && unsafe_chars (xbuf[totlen-1], expanded[0]))
4373 xbuf[totlen++] = '@';
4374 xbuf[totlen++] = ' ';
4377 memcpy (xbuf + totlen, expanded,
4378 size_fromInt (arg->expand_length));
4379 totlen += arg->expand_length;
4381 if (!ap->raw_after && totlen > 0
4382 && offset < size_toInt (defn->length)
4383 && !cppReader_isTraditional(pfile)
4384 && unsafe_chars (xbuf[totlen-1], exp[offset]))
4386 xbuf[totlen++] = '@';
4387 xbuf[totlen++] = ' ';
4390 /* If a macro argument with newlines is used multiple times,
4391 then only expand the newlines once. This avoids creating
4392 output lines which don't correspond to any input line,
4393 which confuses gdb and gcov. */
4394 if (arg->use_count > 1 && arg->newlines > 0)
4396 /* Don't bother doing change_newlines for subsequent
4400 = change_newlines (expanded, arg->expand_length);
4404 if (totlen > xbuf_len)
4408 /* if there is anything left of the definition
4409 after handling the arg list, copy that in too. */
4411 for (i = offset; i < size_toInt (defn->length); i++)
4413 /* if we've reached the end of the macro */
4416 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
4417 && last_ap->raw_after))
4418 xbuf[totlen++] = exp[i];
4421 xbuf[totlen] = '\0';
4425 pfile->output_escapes--;
4427 /* Now put the expansion on the input stack
4428 so our caller will commence reading from it. */
4429 DPRINTF (("Pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4431 if (end_line != start_line)
4433 /* xbuf must have enough newlines */
4434 int newlines = end_line - start_line;
4435 int foundnewlines = 0;
4436 char *xbufptr = xbuf;
4438 while ((xbufptr = strchr (xbufptr, '\n')) != NULL && foundnewlines <= newlines)
4443 if (*xbufptr == '\0')
4449 if (foundnewlines < newlines)
4451 cstring newbuf = cstring_copyLength (xbuf, xbuf_len);
4453 while (foundnewlines < newlines)
4455 newbuf = cstring_appendChar (newbuf, '\n');
4460 xbuf = cstring_toCharsSafe (newbuf);
4461 xbuf_len = cstring_length (newbuf);
4463 } /*@=branchstate@*/
4466 DPRINTF (("Pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4468 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
4469 DPRINTF (("After pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4470 cppReader_getBufferSafe (pfile)->has_escapes = 1;
4472 /* Pop the space we've used in the token_buffer for argument expansion. */
4473 cppReader_setWritten (pfile, old_written);
4474 DPRINTF (("Done set written"));
4476 /* Recursive macro use sometimes works traditionally.
4477 #define foo(x,y) bar (x (y,0), y)
4480 if (!cppReader_isTraditional (pfile))
4481 hp->type = T_DISABLED;
4487 push_macro_expansion (cppReader *pfile, char *xbuf, size_t xbuf_len,
4488 /*@dependent@*/ hashNode hp)
4490 cppBuffer *mbuf = cppReader_pushBuffer (pfile, xbuf, xbuf_len);
4497 mbuf->cleanup = cppReader_macroCleanup;
4499 llassert (mbuf->hnode == NULL);
4502 /* The first chars of the expansion should be a "@ " added by
4503 collect_expansion. This is to prevent accidental token-pasting
4504 between the text preceding the macro invocation, and the macro
4507 We would like to avoid adding unneeded spaces (for the sake of
4508 tools that use cpp, such as imake). In some common cases we can
4509 tell that it is safe to omit the space.
4511 The character before the macro invocation cannot have been an
4512 idchar (or else it would have been pasted with the idchars of
4513 the macro name). Therefore, if the first non-space character
4514 of the expansion is an idchar, we do not need the extra space
4515 to prevent token pasting.
4517 Also, we don't need the extra space if the first char is '(',
4518 or some other (less common) characters. */
4520 if (xbuf[0] == '@' && xbuf[1] == ' '
4521 && (is_idchar[(int) xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
4522 || xbuf[2] == '\"'))
4524 llassert (mbuf->cur != NULL);
4525 DPRINTF (("Eating: %c", xbuf[2]));
4532 /* Like cpplib_getToken, except that it does not read past end-of-line.
4533 Also, horizontal space is skipped, and macros are popped. */
4535 static enum cpp_token
4536 get_directive_token (cppReader *pfile)
4540 size_t old_written = cpplib_getWritten (pfile);
4541 enum cpp_token token;
4542 cppSkipHspace (pfile);
4543 if (cppReader_peekC (pfile) == '\n')
4548 token = cpplib_getToken (pfile);
4553 if (!cppBuffer_isMacro (cppReader_getBuffer (pfile)))
4558 cppReader_setWritten (pfile, old_written);
4559 /*@switchbreak@*/ break;
4567 /* Handle #include and #import.
4568 This function expects to see "fname" or <fname> on the input.
4570 The input is normally in part of the output_buffer following
4571 cpplib_getWritten, and will get overwritten by output_line_command.
4572 I.e. in input file specification has been popped by cppReader_handleDirective.
4576 do_include (cppReader *pfile, struct directive *keyword,
4577 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
4579 bool skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4581 char *fbeg, *fend; /* Beginning and end of fname */
4582 enum cpp_token token;
4584 /* Chain of dirs to search */
4585 struct file_name_list *search_start = CPPOPTIONS (pfile)->include;
4586 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
4587 struct file_name_list *searchptr = NULL;
4588 size_t old_written = cpplib_getWritten (pfile);
4591 int f; /* file number */
4592 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4593 f= -1; /* JF we iz paranoid! */
4595 pfile->parsing_include_directive++;
4596 token = get_directive_token (pfile);
4597 pfile->parsing_include_directive--;
4599 if (token == CPP_STRING)
4601 /* FIXME - check no trailing garbage */
4602 fbeg = pfile->token_buffer + old_written + 1;
4603 fend = cpplib_getPWritten (pfile) - 1;
4604 if (fbeg[-1] == '<')
4607 /* If -I-, start with the first -I dir after the -I-. */
4608 if (CPPOPTIONS (pfile)->first_bracket_include != NULL)
4609 search_start = CPPOPTIONS (pfile)->first_bracket_include;
4611 /* If -I- was specified, don't search current dir, only spec'd ones. */
4612 else if (!CPPOPTIONS (pfile)->ignore_srcdir)
4614 cppBuffer *fp = CPPBUFFER (pfile);
4615 /* We have "filename". Figure out directory this source
4616 file is coming from and put it on the front of the list. */
4618 for ( ; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
4623 llassert (fp != NULL);
4627 if (cstring_isDefined (fp->nominal_fname))
4629 nam = cstring_toCharsSafe (fp->nominal_fname);
4631 /* Found a named file. Figure out dir of the file,
4632 and put it in front of the search list. */
4633 dsp[0].next = search_start;
4637 ep = strrchr (nam, CONNECTCHAR);
4639 ep = strrchr (nam, ']');
4640 if (ep == NULL) ep = strrchr (nam, '>');
4641 if (ep == NULL) ep = strrchr (nam, ':');
4642 if (ep != NULL) ep++;
4652 /*@-onlytrans@*/ /* This looks like a memory leak... */
4653 dsp[0].fname = cstring_fromCharsNew (nam); /* evs 2000-07-20: was fromChars */
4657 if (n + INCLUDE_LEN_FUDGE > size_toInt (pfile->max_include_len))
4658 pfile->max_include_len = size_fromInt (n + INCLUDE_LEN_FUDGE);
4662 dsp[0].fname = cstring_undefined; /* Current directory */
4665 dsp[0].got_name_map = 0;
4676 else if (token == CPP_NAME)
4679 * Support '#include xyz' like VAX-C to allow for easy use of all the
4680 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4681 * code from case '<' is repeated here) and generates a warning.
4683 cppReader_warning (pfile,
4684 "VAX-C-style include specification found, use '#include <filename.h>' !");
4686 /* If -I-, start with the first -I dir after the -I-. */
4687 if (CPPOPTIONS (pfile)->first_bracket_include)
4688 search_start = CPPOPTIONS (pfile)->first_bracket_include;
4689 fbeg = pfile->token_buffer + old_written;
4690 fend = cpplib_getPWritten (pfile);
4695 cppReader_error (pfile,
4696 message ("Preprocessor command #%s expects \"FILENAME\" or <FILENAME>",
4699 cppReader_setWritten (pfile, old_written);
4700 cppReader_skipRestOfLine (pfile);
4706 token = get_directive_token (pfile);
4707 if (token != CPP_VSPACE)
4709 cppReader_errorLit (pfile,
4710 cstring_makeLiteralTemp ("Junk at end of #include"));
4712 while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
4714 token = get_directive_token (pfile);
4719 ** For #include_next, skip in the search path
4720 ** past the dir in which the containing file was found.
4725 cppBuffer *fp = CPPBUFFER (pfile);
4727 for (; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
4729 llassert (fp != NULL);
4731 if (fp->fname != NULL)
4733 /* fp->dir is null if the containing file was specified with
4734 an absolute file name. In that case, don't skip anything. */
4735 if (fp->dir == SELF_DIR_DUMMY)
4737 search_start = CPPOPTIONS (pfile)->include;
4739 else if (fp->dir != NULL)
4741 search_start = fp->dir->next;
4753 cppReader_setWritten (pfile, old_written);
4755 flen = size_fromInt (fend - fbeg);
4757 DPRINTF (("fbeg: %s", fbeg));
4761 cppReader_error (pfile,
4762 message ("Empty file name in #%s", keyword->name));
4767 ** Allocate this permanently, because it gets stored in the definitions
4771 fname = cstring_undefined;
4773 /* + 2 above for slash and terminating null. */
4774 /* + 2 added for '.h' on VMS (to support '#include filename') */
4776 /* If specified file name is absolute, just open it. */
4778 if (osd_isConnectChar (*fbeg)
4779 # if defined (WIN32) || defined (OS2)
4780 || (*(fbeg + 1) == ':')
4784 fname = cstring_copyLength (fbeg, flen);
4786 if (redundant_include_p (pfile, fname))
4788 cstring_free (fname);
4792 f = open_include_file (pfile, fname, NULL);
4794 if (f == IMPORT_FOUND)
4796 return 0; /* Already included this file */
4801 /* Search directory path, trying to open the file.
4802 Copy each filename tried into FNAME. */
4804 for (searchptr = search_start; searchptr != NULL;
4805 searchptr = searchptr->next)
4807 if (!cstring_isEmpty (searchptr->fname))
4809 /* The empty string in a search path is ignored.
4810 This makes it possible to turn off entirely
4811 a standard piece of the list. */
4812 if (cstring_isEmpty (searchptr->fname))
4815 fname = cstring_copy (searchptr->fname);
4816 fname = cstring_appendChar (fname, CONNECTCHAR);
4817 DPRINTF (("Here: %s", fname));
4824 fname = cstring_concatLength (fname, fbeg, flen);
4826 DPRINTF (("fname: %s", fname));
4828 /* Win32 directory fix from Kay Buschner. */
4829 #if defined (WIN32) || defined (OS2)
4830 /* Fix all unixdir slashes to win dir slashes */
4831 if (searchptr->fname && (searchptr->fname[0] != 0))
4833 cstring_replaceAll (fname, '/', '\\');
4838 /* Change this 1/2 Unix 1/2 VMS file specification into a
4839 full VMS file specification */
4840 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4841 /* Fix up the filename */
4842 hack_vms_include_specification (fname);
4844 /* This is a normal VMS filespec, so use it unchanged. */
4845 strncpy (fname, fbeg, flen);
4847 /* if it's '#include filename', add the missing .h */
4848 if (strchr (fname,'.') == NULL) {
4849 strcat (fname, ".h");
4853 /* ??? There are currently 3 separate mechanisms for avoiding processing
4854 of redundant include files: #import, #pragma once, and
4855 redundant_include_p. It would be nice if they were unified. */
4857 if (redundant_include_p (pfile, fname))
4859 cstring_free (fname);
4863 DPRINTF (("Trying: %s", fname));
4865 f = open_include_file (pfile, fname, searchptr);
4867 if (f == IMPORT_FOUND)
4869 return 0; /* Already included this file */
4872 else if (f == IMPORT_NOT_FOUND && errno == EACCES)
4874 cppReader_warning (pfile,
4875 message ("Header file %s exists, but is not readable", fname));
4888 /* A file that was not found. */
4889 fname = cstring_copyLength (fbeg, flen);
4891 if (search_start != NULL)
4893 cppReader_error (pfile,
4894 message ("Cannot find include file %s on search path: %x",
4896 searchPath_unparse (search_start)));
4900 cppReader_error (pfile,
4901 message ("No include path in which to find %s", fname));
4906 ** Check to see if this include file is a once-only include file.
4910 struct file_name_list *ptr;
4912 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
4914 if (cstring_equal (ptr->fname, fname))
4916 /* This file was included before. */
4923 /* This is the first time for this file. */
4924 /* Add it to list of files included. */
4926 ptr = (struct file_name_list *) dmalloc (sizeof (*ptr));
4927 ptr->control_macro = NULL;
4928 ptr->c_system_include_path = NULL;
4929 ptr->next = pfile->all_include_files;
4931 ptr->got_name_map = NULL;
4933 DPRINTF (("Including file: %s", fname));
4934 pfile->all_include_files = ptr;
4935 assertSet (pfile->all_include_files);
4938 if (angle_brackets != 0)
4940 pfile->system_include_depth++;
4943 /* Actually process the file */
4944 if (cppReader_pushBuffer (pfile, NULL, 0) == NULL)
4946 cstring_free (fname);
4950 if (finclude (pfile, f, fname, is_system_include (pfile, fname),
4951 searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
4953 output_line_command (pfile, 0, enter_file);
4954 pfile->only_seen_white = 2;
4959 pfile->system_include_depth--;
4962 } /*@=branchstate@*/
4967 /* Return nonzero if there is no need to include file NAME
4968 because it has already been included and it contains a conditional
4969 to make a repeated include do nothing. */
4972 redundant_include_p (cppReader *pfile, cstring name)
4974 struct file_name_list *l = pfile->all_include_files;
4976 for (; l != NULL; l = l->next)
4978 if (cstring_equal (name, l->fname)
4979 && (l->control_macro != NULL)
4980 && (cpphash_lookup (l->control_macro, -1, -1) != NULL))
4989 /* Return nonzero if the given FILENAME is an absolute pathname which
4990 designates a file within one of the known "system" include file
4991 directories. We assume here that if the given FILENAME looks like
4992 it is the name of a file which resides either directly in a "system"
4993 include file directory, or within any subdirectory thereof, then the
4994 given file must be a "system" include file. This function tells us
4995 if we should suppress pedantic errors/warnings for the given FILENAME.
4997 The value is 2 if the file is a C-language system header file
4998 for which C++ should (on most systems) assume `extern "C"'. */
5001 is_system_include (cppReader *pfile, cstring filename)
5003 struct file_name_list *searchptr;
5005 for (searchptr = CPPOPTIONS (pfile)->first_system_include;
5007 searchptr = searchptr->next)
5009 if (!cstring_isEmpty (searchptr->fname))
5011 cstring sys_dir = searchptr->fname;
5012 size_t length = cstring_length (sys_dir);
5014 if (cstring_equalLen (sys_dir, filename, length)
5015 && osd_isConnectChar (cstring_getChar (filename, length)))
5017 if (searchptr->c_system_include_path)
5028 /* Convert a character string literal into a nul-terminated string.
5029 The input string is [IN ... LIMIT).
5030 The result is placed in RESULT. RESULT can be the same as IN.
5031 The value returned in the end of the string written to RESULT,
5032 or NULL on error. */
5034 static /*@null@*/ char *
5035 convert_string (cppReader *pfile, /*@returned@*/ char *result,
5036 char *in, char *limit, int handle_escapes)
5056 /*@switchbreak@*/ break;
5060 char *bpc = (char *) in;
5061 int i = (char) cppReader_parseEscape (pfile, &bpc);
5064 *result++ = (char) c;
5065 /*@switchbreak@*/ break;
5079 * interpret #line command. Remembers previously seen fnames
5080 * in its very own hash table.
5083 /*@constant int FNAME_HASHSIZE@*/
5084 #define FNAME_HASHSIZE 37
5087 do_line (cppReader *pfile, /*@unused@*/ struct directive *keyword)
5089 cppBuffer *ip = cppReader_getBuffer (pfile);
5091 size_t old_written = cpplib_getWritten (pfile);
5092 enum file_change_code file_change = same_file;
5093 enum cpp_token token;
5095 llassert (ip != NULL);
5096 token = get_directive_token (pfile);
5098 if (token != CPP_NUMBER
5099 || !isdigit(pfile->token_buffer[old_written]))
5101 cppReader_errorLit (pfile,
5102 cstring_makeLiteralTemp ("invalid format `#line' command"));
5104 goto bad_line_directive;
5107 /* The Newline at the end of this line remains to be processed.
5108 To put the next line at the specified line number,
5109 we must store a line number now that is one less. */
5110 new_lineno = atoi (pfile->token_buffer + old_written) - 1;
5111 cppReader_setWritten (pfile, old_written);
5113 /* NEW_LINENO is one less than the actual line number here. */
5114 if (cppReader_isPedantic (pfile) && new_lineno < 0)
5115 cppReader_pedwarnLit (pfile,
5116 cstring_makeLiteralTemp ("line number out of range in `#line' command"));
5118 token = get_directive_token (pfile);
5120 if (token == CPP_STRING) {
5121 char *fname = pfile->token_buffer + old_written;
5123 static hashNode fname_table[FNAME_HASHSIZE];
5125 hashNode *hash_bucket;
5128 size_t fname_length;
5130 /* Turn the file name, which is a character string literal,
5131 into a null-terminated string. Do this in place. */
5132 end_name = convert_string (pfile, fname, fname, cpplib_getPWritten (pfile), 1);
5133 if (end_name == NULL)
5135 cppReader_errorLit (pfile,
5136 cstring_makeLiteralTemp ("invalid format `#line' command"));
5137 goto bad_line_directive;
5140 fname_length = size_fromInt (end_name - fname);
5141 num_start = cpplib_getWritten (pfile);
5143 token = get_directive_token (pfile);
5144 if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP) {
5145 p = pfile->token_buffer + num_start;
5146 if (cppReader_isPedantic (pfile))
5147 cppReader_pedwarnLit (pfile,
5148 cstring_makeLiteralTemp ("garbage at end of `#line' command"));
5150 if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
5152 cppReader_errorLit (pfile,
5153 cstring_makeLiteralTemp ("invalid format `#line' command"));
5154 goto bad_line_directive;
5157 file_change = enter_file;
5159 file_change = leave_file;
5161 ip->system_header_p = 1;
5162 else /* if (*p == 4) */
5163 ip->system_header_p = 2;
5165 cppReader_setWritten (pfile, num_start);
5166 token = get_directive_token (pfile);
5167 p = pfile->token_buffer + num_start;
5168 if (token == CPP_NUMBER && p[1] == '\0' && (*p == '3' || *p== '4')) {
5169 ip->system_header_p = *p == 3 ? 1 : 2;
5170 token = get_directive_token (pfile);
5172 if (token != CPP_VSPACE) {
5173 cppReader_errorLit (pfile,
5174 cstring_makeLiteralTemp ("invalid format `#line' command"));
5176 goto bad_line_directive;
5181 &fname_table[cpphash_hashCode (fname, fname_length, FNAME_HASHSIZE)];
5183 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
5185 if (hp->length == fname_length)
5187 llassert (hp->value.cpval != NULL);
5189 if (strncmp (hp->value.cpval, fname, fname_length) == 0)
5191 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
5198 /* Didn't find it; cons up a new one. */
5199 hp = (hashNode) dmalloc (sizeof (*hp));
5202 hp->bucket_hdr = NULL;
5204 hp->name = cstring_undefined;
5205 hp->next = *hash_bucket;
5209 hp->length = fname_length;
5210 hp->value.cpval = dmalloc (sizeof (*hp->value.cpval) * (fname_length + 1));
5211 memcpy (hp->value.cpval, fname, fname_length);
5212 hp->value.cpval[fname_length] = '\0';
5213 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
5216 else if (token != CPP_VSPACE && token != CPP_EOF)
5218 cppReader_errorLit (pfile,
5219 cstring_makeLiteralTemp ("invalid format `#line' command"));
5220 goto bad_line_directive;
5227 ip->lineno = new_lineno;
5229 cppReader_skipRestOfLine (pfile);
5230 cppReader_setWritten (pfile, old_written);
5231 output_line_command (pfile, 0, file_change);
5236 * remove the definition of a symbol from the symbol table.
5237 * according to un*x /lib/cpp, it is not an error to undef
5238 * something that has no definitions, so it isn't one here either.
5242 do_undef (cppReader *pfile, struct directive *keyword, char *buf, char *limit)
5247 char *orig_buf = buf;
5249 SKIP_WHITE_SPACE (buf);
5251 sym_length = cppReader_checkMacroName (pfile, buf, cstring_makeLiteralTemp ("macro"));
5253 while ((hp = cpphash_lookup (buf, size_toInt (sym_length), -1)) != NULL)
5255 /* If we are generating additional info for debugging (with -g) we
5256 need to pass through all effective #undef commands. */
5257 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
5259 pass_thru_directive (orig_buf, limit, pfile, keyword);
5262 if (hp->type != T_MACRO)
5264 cppReader_warning (pfile,
5265 message ("Undefining preprocessor builtin: %s",
5269 cppReader_deleteMacro (hp);
5272 if (cppReader_isPedantic (pfile)) {
5274 SKIP_WHITE_SPACE (buf);
5277 cppReader_pedwarnLit (pfile,
5278 cstring_makeLiteralTemp ("garbage after `#undef' directive"));
5287 * Report an error detected by the program we are processing.
5288 * Use the text of the line in the error message.
5289 * (We use error because it prints the filename & line#.)
5293 do_error (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5294 char *buf, char *limit)
5296 size_t length = size_fromInt (limit - buf);
5297 cstring copy = cstring_copyLength (buf, length);
5298 cstring adv = cstring_advanceWhiteSpace (copy);
5300 cppReader_error (pfile, message ("#error %s", adv));
5301 cstring_free (copy);
5306 * Report a warning detected by the program we are processing.
5307 * Use the text of the line in the warning message, then continue.
5308 * (We use error because it prints the filename & line#.)
5312 do_warning (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5313 char *buf, char *limit)
5315 size_t length = size_fromInt (limit - buf);
5316 cstring copy = cstring_copyLength (buf, length);
5317 cstring adv = cstring_advanceWhiteSpace (copy);
5318 cppReader_warning (pfile, message ("#warning %s", adv));
5319 cstring_free (copy);
5324 /* #ident has already been copied to the output file, so just ignore it. */
5327 do_ident (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5328 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5330 /* Allow #ident in system headers, since that's not user's fault. */
5331 if (cppReader_isPedantic (pfile)
5332 && !cppReader_getBufferSafe (pfile)->system_header_p)
5333 cppReader_pedwarnLit (pfile,
5334 cstring_makeLiteralTemp ("ANSI C does not allow `#ident'"));
5336 /* Leave rest of line to be read by later calls to cpplib_getToken. */
5341 /* #pragma and its argument line have already been copied to the output file.
5342 Just check for some recognized pragmas that need validation here. */
5345 do_pragma (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5346 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5348 while (*buf == ' ' || *buf == '\t')
5353 if (!strncmp (buf, "implementation", 14)) {
5354 /* Be quiet about `#pragma implementation' for a file only if it hasn't
5355 been included yet. */
5356 struct file_name_list *ptr;
5357 char *p = buf + 14, *fname, *inc_fname;
5359 SKIP_WHITE_SPACE (p);
5360 if (*p == '\n' || *p != '\"')
5364 p = (char *) strchr (fname, '\"');
5365 fname_len = p != NULL ? size_fromInt (p - fname) : mstring_length (fname);
5367 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
5369 inc_fname = (char *) strrchr (cstring_toCharsSafe (ptr->fname), CONNECTCHAR);
5370 inc_fname = (inc_fname != NULL)
5371 ? inc_fname + 1 : cstring_toCharsSafe (ptr->fname);
5373 if ((inc_fname != NULL)
5374 && (strncmp (inc_fname, fname, fname_len) == 0))
5376 cpp_setLocation (pfile);
5378 ppllerror (message ("`#pragma implementation' for `%s' appears "
5379 "after file is included",
5380 cstring_fromChars (fname)));
5389 * handle #if command by
5390 * 1) inserting special `defined' keyword into the hash table
5391 * that gets turned into 0 or 1 by special_symbol (thus,
5392 * if the luser has a symbol called `defined' already, it won't
5393 * work inside the #if command)
5394 * 2) rescan the input into a temporary output buffer
5395 * 3) pass the output buffer to the yacc parser and collect a value
5396 * 4) clean up the mess left from steps 1 and 2.
5397 * 5) call conditional_skip to skip til the next #endif (etc.),
5398 * or not, depending on the value from step 3.
5402 do_if (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5403 char *buf, char *limit)
5405 HOST_WIDE_INT value;
5406 DPRINTF (("Do if: %s", buf));
5407 value = eval_if_expression (pfile, buf, limit - buf);
5408 conditional_skip (pfile, value == 0, T_IF, NULL);
5413 * handle a #elif directive by not changing if_stack either.
5414 * see the comment above do_else.
5417 static int do_elif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5418 char *buf, char *limit)
5420 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5422 cppReader_errorLit (pfile,
5423 cstring_makeLiteralTemp ("Preprocessor command #elif is not within a conditional"));
5428 llassert (pfile->if_stack != NULL);
5430 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
5432 cppReader_errorLit (pfile,
5433 cstring_makeLiteralTemp ("`#elif' after `#else'"));
5435 if (pfile->if_stack->fname != NULL
5436 && cppReader_getBufferSafe (pfile)->fname != NULL
5437 && !cstring_equal (pfile->if_stack->fname,
5438 cppReader_getBufferSafe (pfile)->nominal_fname))
5439 fprintf (stderr, ", file %s", cstring_toCharsSafe (pfile->if_stack->fname));
5440 fprintf (stderr, ")\n");
5442 pfile->if_stack->type = T_ELIF;
5445 if (pfile->if_stack->if_succeeded)
5447 skip_if_group (pfile, 0);
5451 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
5453 skip_if_group (pfile, 0);
5456 ++pfile->if_stack->if_succeeded; /* continue processing input */
5457 output_line_command (pfile, 1, same_file);
5465 * evaluate a #if expression in BUF, of length LENGTH,
5466 * then parse the result as a C expression and return the value as an int.
5469 static HOST_WIDE_INT
5470 eval_if_expression (cppReader *pfile,
5471 /*@unused@*/ char *buf,
5472 /*@unused@*/ int length)
5474 hashNode save_defined;
5475 HOST_WIDE_INT value;
5476 size_t old_written = cpplib_getWritten (pfile);
5478 DPRINTF (("Saving defined..."));
5479 save_defined = cpphash_install ("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
5480 pfile->pcp_inside_if = 1;
5482 value = cppReader_parseExpression (pfile);
5483 pfile->pcp_inside_if = 0;
5485 /* Clean up special symbol */
5486 DPRINTF (("Removing defined..."));
5487 cppReader_deleteMacro (save_defined);
5488 cppReader_setWritten (pfile, old_written); /* Pop */
5494 * routine to handle ifdef/ifndef. Try to look up the symbol,
5495 * then do or don't skip to the #endif/#else/#elif depending
5496 * on what directive is actually being processed.
5500 do_xifdef (cppReader *pfile, struct directive *keyword,
5501 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
5504 cppBuffer *ip = cppReader_getBufferSafe (pfile);
5506 size_t ident_length;
5507 enum cpp_token token;
5508 int start_of_file = 0;
5509 char *control_macro = 0;
5510 size_t old_written = cpplib_getWritten (pfile);
5512 DPRINTF (("do xifdef: %d",
5513 keyword->type == T_IFNDEF));
5515 /* Detect a #ifndef at start of file (not counting comments). */
5516 if (cstring_isDefined (ip->fname) && keyword->type == T_IFNDEF)
5518 start_of_file = pfile->only_seen_white == 2;
5521 pfile->no_macro_expand++;
5522 token = get_directive_token (pfile);
5523 pfile->no_macro_expand--;
5525 ident = pfile->token_buffer + old_written;
5526 DPRINTF (("Ident: %s", ident));
5528 ident_length = cpplib_getWritten (pfile) - old_written;
5529 cppReader_setWritten (pfile, old_written); /* Pop */
5531 if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
5533 skip = (keyword->type == T_IFDEF);
5534 if (! cppReader_isTraditional (pfile))
5536 cppReader_pedwarn (pfile,
5537 message ("`#%s' with no argument", keyword->name));
5540 else if (token == CPP_NAME)
5542 hashNode hp = cpphash_lookup (ident, size_toInt (ident_length), -1);
5544 skip = (keyword->type == T_IFDEF) ? (hp == NULL) : (hp != NULL);
5546 DPRINTF (("hp null: %d / %d / %d", hp == NULL, keyword->type == T_IFNDEF, skip));
5548 if (start_of_file && !skip)
5550 DPRINTF (("Not skipping!"));
5551 control_macro = (char *) dmalloc (ident_length + 1);
5552 memcpy (control_macro, ident, ident_length + 1);
5557 skip = (keyword->type == T_IFDEF);
5558 if (! cppReader_isTraditional (pfile))
5560 cppReader_error (pfile,
5561 message ("`#%s' with invalid argument", keyword->name));
5565 if (!cppReader_isTraditional (pfile))
5568 cppSkipHspace (pfile);
5569 c = cppReader_peekC (pfile);
5570 if (c != EOF && c != '\n')
5572 cppReader_pedwarn (pfile,
5573 message ("garbage at end of `#%s' argument", keyword->name));
5577 cppReader_skipRestOfLine (pfile);
5579 DPRINTF (("Conditional skip: %d", skip));
5580 conditional_skip (pfile, skip, T_IF, control_macro);
5584 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
5585 If this is a #ifndef starting at the beginning of a file,
5586 CONTROL_MACRO is the macro name tested by the #ifndef.
5587 Otherwise, CONTROL_MACRO is 0. */
5590 conditional_skip (cppReader *pfile, int skip,
5591 enum node_type type,
5592 /*@dependent@*/ char *control_macro)
5594 cppIfStackFrame *temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
5596 temp->fname = cppReader_getBufferSafe (pfile)->nominal_fname;
5597 temp->next = pfile->if_stack;
5598 temp->control_macro = control_macro;
5600 temp->if_succeeded = 0;
5602 pfile->if_stack = temp;
5603 pfile->if_stack->type = type;
5607 skip_if_group (pfile, 0);
5612 ++pfile->if_stack->if_succeeded;
5613 output_line_command (pfile, 1, same_file);
5618 * skip to #endif, #else, or #elif. adjust line numbers, etc.
5619 * leaves input ptr at the sharp sign found.
5620 * If ANY is nonzero, return at next directive of any sort.
5624 skip_if_group (cppReader *pfile, int any)
5627 struct directive *kt;
5628 cppIfStackFrame *save_if_stack = pfile->if_stack; /* don't pop past here */
5629 register int ident_length;
5631 struct parse_marker line_start_mark;
5633 parseSetMark (&line_start_mark, pfile);
5635 if (CPPOPTIONS (pfile)->output_conditionals) {
5636 static char failed[] = "#failed\n";
5637 cppReader_puts (pfile, failed, sizeof(failed)-1);
5639 output_line_command (pfile, 1, same_file);
5643 if (CPPOPTIONS (pfile)->output_conditionals)
5645 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
5648 llassert (pbuf->buf != NULL);
5650 start_line = pbuf->buf + line_start_mark.position;
5651 cppReader_puts (pfile, start_line, size_fromInt (pbuf->cur - start_line));
5654 parseMoveMark (&line_start_mark, pfile);
5656 if (!cppReader_isTraditional (pfile))
5658 cppSkipHspace (pfile);
5661 c = cppReader_getC (pfile);
5664 size_t old_written = cpplib_getWritten (pfile);
5665 cppSkipHspace (pfile);
5667 parse_name (pfile, cppReader_getC (pfile));
5668 ident_length = size_toInt (cpplib_getWritten (pfile) - old_written);
5669 ident = pfile->token_buffer + old_written;
5670 pfile->limit = ident;
5672 for (kt = directive_table; kt->length >= 0; kt++)
5674 cppIfStackFrame *temp;
5675 if (ident_length == kt->length
5676 && cstring_equalPrefix (kt->name, cstring_fromChars (ident)))
5678 /* If we are asked to return on next directive, do so now. */
5689 temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
5690 temp->next = pfile->if_stack;
5691 temp->fname = cppReader_getBufferSafe (pfile)->nominal_fname;
5692 temp->type = kt->type;
5694 temp->if_succeeded = 0;
5695 temp->control_macro = NULL;
5697 pfile->if_stack = temp;
5698 /*@switchbreak@*/ break;
5701 if (cppReader_isPedantic (pfile) && pfile->if_stack != save_if_stack)
5702 validate_else (pfile,
5703 cstring_makeLiteralTemp (kt->type == T_ELSE ? "#else" : "#endif"));
5706 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5708 cppReader_error (pfile,
5709 message ("Preprocessor command #%s is not within a conditional", kt->name));
5710 /*@switchbreak@*/ break;
5712 else if (pfile->if_stack == save_if_stack)
5714 goto done; /* found what we came for */
5721 if (kt->type != T_ENDIF)
5723 llassert (pfile->if_stack != NULL);
5725 if (pfile->if_stack->type == T_ELSE)
5727 cppReader_errorLit (pfile,
5728 cstring_makeLiteralTemp ("`#else' or `#elif' after `#else'"));
5731 pfile->if_stack->type = kt->type;
5732 /*@switchbreak@*/ break;
5735 temp = pfile->if_stack;
5736 llassert (temp != NULL);
5737 pfile->if_stack = temp->next;
5739 /*@switchbreak@*/ break;
5742 #if defined (OS2) && defined (__IBMC__)
5743 /* Dummy code to eleminate optimization problems with icc */
5752 /* Don't let erroneous code go by. */
5754 if (kt->length < 0 && !CPPOPTIONS (pfile)->lang_asm
5755 && cppReader_isPedantic (pfile))
5757 cppReader_pedwarnLit (pfile,
5758 cstring_makeLiteralTemp ("Invalid preprocessor directive name"));
5762 c = cppReader_getC (pfile);
5764 /* We're in the middle of a line. Skip the rest of it. */
5772 case '/': /* possible comment */
5773 c = skip_comment (pfile, NULL);
5776 /*@switchbreak@*/ break;
5779 cppReader_forward (pfile, -1);
5780 old = cpplib_getWritten (pfile);
5781 (void) cpplib_getToken (pfile);
5782 cppReader_setWritten (pfile, old);
5783 /*@switchbreak@*/ break;
5785 /* Char after backslash loses its special meaning. */
5786 if (cppReader_peekC (pfile) == '\n')
5788 cppReader_forward (pfile, 1);
5791 /*@switchbreak@*/ break;
5795 c = cppReader_getC (pfile);
5798 if (CPPOPTIONS (pfile)->output_conditionals) {
5799 static char end_failed[] = "#endfailed\n";
5800 cppReader_puts (pfile, end_failed, sizeof(end_failed)-1);
5803 pfile->only_seen_white = 1;
5805 parseGotoMark (&line_start_mark, pfile);
5806 parseClearMark (&line_start_mark);
5810 * handle a #else directive. Do this by just continuing processing
5811 * without changing if_stack ; this is so that the error message
5812 * for missing #endif's etc. will point to the original #if. It
5813 * is possible that something different would be better.
5817 do_else (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5818 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5820 if (cppReader_isPedantic (pfile))
5822 validate_else (pfile, cstring_makeLiteralTemp ("#else"));
5825 cppReader_skipRestOfLine (pfile);
5827 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack) {
5828 cppReader_errorLit (pfile,
5829 cstring_makeLiteralTemp ("Preprocessor command #else is not within a conditional"));
5832 /* #ifndef can't have its special treatment for containing the whole file
5833 if it has a #else clause. */
5835 llassert (pfile->if_stack != NULL);
5837 pfile->if_stack->control_macro = 0;
5839 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
5841 cpp_setLocation (pfile);
5842 genppllerrorhint (FLG_PREPROC,
5843 message ("Pre-processor directive #else after #else"),
5844 message ("%q: Location of match",
5845 fileloc_unparseRaw (pfile->if_stack->fname,
5846 pfile->if_stack->lineno)));
5849 pfile->if_stack->type = T_ELSE;
5852 if (pfile->if_stack->if_succeeded)
5853 skip_if_group (pfile, 0);
5855 ++pfile->if_stack->if_succeeded; /* continue processing input */
5856 output_line_command (pfile, 1, same_file);
5863 * unstack after #endif command
5867 do_endif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5868 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5870 if (cppReader_isPedantic (pfile))
5872 validate_else (pfile, cstring_makeLiteralTemp ("#endif"));
5875 cppReader_skipRestOfLine (pfile);
5877 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5879 cppReader_errorLit (pfile, cstring_makeLiteralTemp ("Unbalanced #endif"));
5883 cppIfStackFrame *temp = pfile->if_stack;
5885 llassert (temp != NULL);
5887 pfile->if_stack = temp->next;
5888 if (temp->control_macro != 0)
5890 /* This #endif matched a #ifndef at the start of the file.
5891 See if it is at the end of the file. */
5892 struct parse_marker start_mark;
5895 parseSetMark (&start_mark, pfile);
5899 cppSkipHspace (pfile);
5900 c = cppReader_getC (pfile);
5906 parseGotoMark (&start_mark, pfile);
5907 parseClearMark (&start_mark);
5911 /* If we get here, this #endif ends a #ifndef
5912 that contains all of the file (aside from whitespace).
5913 Arrange not to include the file again
5914 if the macro that was tested is defined.
5916 Do not do this for the top-level file in a -include or any
5917 file in a -imacros. */
5918 struct file_name_list *ifile = pfile->all_include_files;
5920 for ( ; ifile != NULL; ifile = ifile->next)
5922 if (cstring_equal (ifile->fname, cppReader_getBufferSafe (pfile)->fname))
5924 ifile->control_macro = temp->control_macro;
5932 output_line_command (pfile, 1, same_file);
5937 /* When an #else or #endif is found while skipping failed conditional,
5938 if -pedantic was specified, this is called to warn about text after
5939 the command name. P points to the first char after the command name. */
5942 validate_else (cppReader *pfile, cstring directive)
5945 cppSkipHspace (pfile);
5946 c = cppReader_peekC (pfile);
5947 if (c != EOF && c != '\n')
5949 cppReader_pedwarn (pfile,
5950 message ("text following `%s' violates ANSI standard", directive));
5955 ** Get the next token, and add it to the text in pfile->token_buffer.
5956 ** Return the kind of token we got.
5960 cpplib_getToken (cppReader *pfile)
5962 return cpplib_getTokenAux (pfile, FALSE);
5966 cpplib_getTokenForceExpand (cppReader *pfile)
5968 return cpplib_getTokenAux (pfile, TRUE);
5972 cpplib_getTokenAux (cppReader *pfile, bool forceExpand)
5975 size_t old_written = 0;
5976 int start_line, start_column;
5977 enum cpp_token token;
5978 struct cppOptions *opts = CPPOPTIONS (pfile);
5979 cppReader_getBufferSafe (pfile)->prev = cppReader_getBufferSafe (pfile)->cur;
5982 c = cppReader_getC (pfile);
5983 DPRINTF (("Get next token: %c", c));
5988 if (cppReader_getBufferSafe (pfile)->seen_eof)
5990 cppBuffer *buf = cppReader_popBuffer (pfile);
5992 if (buf != cppReader_nullBuffer (pfile))
6003 cppBuffer *next_buf = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6004 cppReader_getBufferSafe (pfile)->seen_eof = 1;
6006 if (cstring_isDefined (cppReader_getBufferSafe (pfile)->nominal_fname)
6007 && next_buf != cppReader_nullBuffer (pfile))
6009 /* We're about to return from an #include file.
6010 Emit #line information now (as part of the CPP_POP) result.
6011 But the #line refers to the file we will pop to. */
6012 cppBuffer *cur_buffer = CPPBUFFER (pfile);
6013 CPPBUFFER (pfile) = next_buf;
6014 pfile->input_stack_listing_current = 0;
6015 output_line_command (pfile, 0, leave_file);
6016 CPPBUFFER (pfile) = cur_buffer;
6024 struct parse_marker start_mark;
6029 if (cppReader_peekC (pfile) == '=')
6034 if (opts->put_out_comments)
6036 parseSetMark (&start_mark, pfile);
6040 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile),
6041 &start_line, &start_column);
6042 c = skip_comment (pfile, &newlines);
6043 DPRINTF (("c = %c", c));
6044 if (opts->put_out_comments && (c == '/' || c == EOF))
6046 assertSet (&start_mark);
6047 parseClearMark (&start_mark);
6054 cppReader_errorWithLine (pfile, start_line, start_column,
6055 cstring_makeLiteral ("Unterminated comment"));
6058 c = '/'; /* Initial letter of comment. */
6060 /* Comments are equivalent to spaces.
6061 For -traditional, a comment is equivalent to nothing. */
6063 if (opts->put_out_comments)
6067 assertSet (&start_mark);
6068 res = cpp_handleComment (pfile, &start_mark);
6069 pfile->lineno += newlines;
6072 else if (cppReader_isTraditional (pfile))
6078 cpplib_reserve(pfile, 1);
6079 cppReader_putCharQ (pfile, ' ');
6084 if (!pfile->only_seen_white)
6089 if (cppReader_handleDirective (pfile))
6091 return CPP_DIRECTIVE;
6094 pfile->only_seen_white = 0;
6099 /* A single quoted string is treated like a double -- some
6100 programs (e.g., troff) are perverse this way */
6101 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile),
6102 &start_line, &start_column);
6103 old_written = cpplib_getWritten (pfile);
6105 DPRINTF (("Put char: %c", c));
6106 cppReader_putChar (pfile, c);
6109 int cc = cppReader_getC (pfile);
6110 DPRINTF (("cc: %c", c));
6113 if (cppBuffer_isMacro (CPPBUFFER (pfile)))
6115 /* try harder: this string crosses a macro expansion
6116 boundary. This can happen naturally if -traditional.
6117 Otherwise, only -D can make a macro with an unmatched
6120 = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6121 (*cppReader_getBufferSafe (pfile)->cleanup)
6122 (cppReader_getBufferSafe (pfile), pfile);
6123 CPPBUFFER (pfile) = next_buf;
6126 if (!cppReader_isTraditional (pfile))
6128 cpp_setLocation (pfile);
6130 setLine (long_toInt (start_line));
6131 setColumn (long_toInt (start_column));
6133 if (pfile->multiline_string_line != long_toInt (start_line)
6134 && pfile->multiline_string_line != 0)
6138 message ("Unterminated string or character constant"),
6139 message ("%q: Possible real start of unterminated constant",
6141 (fileloc_filename (g_currentloc),
6142 pfile->multiline_string_line)));
6143 pfile->multiline_string_line = 0;
6149 message ("Unterminated string or character constant"));
6152 /*@loopbreak@*/ break;
6154 DPRINTF (("putting char: %c", cc));
6155 cppReader_putChar (pfile, cc);
6159 /* Traditionally, end of line ends a string constant with
6160 no error. So exit the loop and record the new line. */
6161 if (cppReader_isTraditional (pfile))
6167 if (cppReader_isPedantic (pfile)
6168 && pfile->multiline_string_line == 0)
6170 cppReader_pedwarnWithLine
6171 (pfile, long_toInt (start_line),
6172 long_toInt (start_column),
6173 cstring_makeLiteral ("String constant runs past end of line"));
6175 if (pfile->multiline_string_line == 0)
6177 pfile->multiline_string_line = start_line;
6180 /*@switchbreak@*/ break;
6183 cc = cppReader_getC (pfile);
6186 /* Backslash newline is replaced by nothing at all. */
6187 cppReader_adjustWritten (pfile, -1);
6192 /* ANSI stupidly requires that in \\ the second \
6193 is *not* prevented from combining with a newline. */
6196 cppReader_putChar (pfile, cc);
6198 /*@switchbreak@*/ break;
6204 /*@switchbreak@*/ break;
6208 pfile->lineno += count_newlines (pfile->token_buffer + old_written,
6209 cpplib_getPWritten (pfile));
6210 pfile->only_seen_white = 0;
6211 return c == '\'' ? CPP_CHAR : CPP_STRING;
6214 if (!opts->dollars_in_ident)
6219 if (opts->cplusplus && cppReader_peekC (pfile) == ':')
6227 c2 = cppReader_peekC (pfile);
6228 if (c2 == c || c2 == '=')
6238 if (cppReader_peekC (pfile) == '=')
6244 c2 = cppReader_peekC (pfile);
6245 if (c2 == '-' && opts->chill)
6247 /* Chill style comment */
6248 if (opts->put_out_comments)
6250 parseSetMark (&start_mark, pfile);
6253 cppReader_forward (pfile, 1); /* Skip second '-'. */
6257 c = cppReader_getC (pfile);
6259 /*@loopbreak@*/ break;
6262 /* Don't consider final '\n' to be part of comment. */
6263 cppReader_forward (pfile, -1);
6264 /*@loopbreak@*/ break;
6268 goto return_comment;
6270 if (c2 == '-' || c2 == '=' || c2 == '>')
6275 if (pfile->parsing_include_directive)
6279 cppReader_putChar (pfile, c);
6281 /*@loopbreak@*/ break;
6282 c = cppReader_getC (pfile);
6284 if (c == '\n' || c == EOF)
6286 cppReader_errorLit (pfile,
6287 cstring_makeLiteralTemp ("Missing '>' in \"#include <FILENAME>\""));
6288 /*@loopbreak@*/ break;
6296 c2 = cppReader_peekC (pfile);
6301 cppReader_forward (pfile, 1);
6302 cpplib_reserve (pfile, 4);
6303 cppReader_putChar (pfile, c);
6304 cppReader_putChar (pfile, c2);
6306 c3 = cppReader_peekC (pfile);
6308 cppReader_putCharQ (pfile, cppReader_getC (pfile));
6309 cppReader_nullTerminateQ (pfile);
6310 pfile->only_seen_white = 0;
6314 DPRINTF (("Macro @!"));
6315 if (cppReader_getBufferSafe (pfile)->has_escapes)
6317 c = cppReader_getC (pfile);
6318 DPRINTF (("got c: %c", c));
6321 if (pfile->output_escapes)
6322 cppReader_puts (pfile, "@-", 2);
6323 parse_name (pfile, cppReader_getC (pfile));
6326 else if (is_space [c])
6328 cpplib_reserve (pfile, 2);
6329 if (pfile->output_escapes)
6330 cppReader_putCharQ (pfile, '@');
6331 cppReader_putCharQ (pfile, c);
6339 if (pfile->output_escapes)
6341 cppReader_puts (pfile, "@@", 2);
6347 c2 = cppReader_peekC (pfile);
6350 cpplib_reserve(pfile, 2);
6351 cppReader_putCharQ (pfile, '.');
6352 c = cppReader_getC (pfile);
6356 /* FIXME - misses the case "..\\\n." */
6357 if (c2 == '.' && cpp_peekN (pfile, 1) == '.')
6359 cpplib_reserve(pfile, 4);
6360 cppReader_putCharQ (pfile, '.');
6361 cppReader_putCharQ (pfile, '.');
6362 cppReader_putCharQ (pfile, '.');
6363 cppReader_forward (pfile, 2);
6364 cppReader_nullTerminateQ (pfile);
6365 pfile->only_seen_white = 0;
6371 pfile->only_seen_white = 0;
6373 cpplib_reserve(pfile, 3);
6374 cppReader_putCharQ (pfile, c);
6375 cppReader_putCharQ (pfile, cppReader_getC (pfile));
6376 cppReader_nullTerminateQ (pfile);
6381 c2 = cppReader_peekC (pfile);
6382 if ((c2 == '\'' || c2 == '\"') && !cppReader_isTraditional (pfile))
6384 cppReader_putChar (pfile, c);
6385 c = cppReader_getC (pfile);
6390 case '0': case '1': case '2': case '3': case '4':
6391 case '5': case '6': case '7': case '8': case '9':
6396 cpplib_reserve (pfile, 2);
6397 cppReader_putCharQ (pfile, c);
6399 c = cppReader_peekC (pfile);
6401 /*@loopbreak@*/ break;
6402 if (!is_idchar[c] && c != '.'
6403 && ((c2 != 'e' && c2 != 'E'
6404 && ((c2 != 'p' && c2 != 'P') || cppReader_isC89 (pfile)))
6405 || (c != '+' && c != '-')))
6406 /*@loopbreak@*/ break;
6407 cppReader_forward (pfile, 1);
6411 cppReader_nullTerminateQ (pfile);
6412 pfile->only_seen_white = 0;
6415 case 'b': case 'c': case 'd': case 'h': case 'o':
6416 case 'B': case 'C': case 'D': case 'H': case 'O':
6417 if (opts->chill && cppReader_peekC (pfile) == '\'')
6419 pfile->only_seen_white = 0;
6420 cpplib_reserve (pfile, 2);
6421 cppReader_putCharQ (pfile, c);
6422 cppReader_putCharQ (pfile, '\'');
6423 cppReader_forward (pfile, 1);
6426 c = cppReader_getC (pfile);
6428 goto chill_number_eof;
6431 if (c == '\\' && cppReader_peekC (pfile) == '\n')
6433 cppReader_forward (pfile, 2);
6436 /*@loopbreak@*/ break;
6438 cppReader_putChar (pfile, c);
6442 cpplib_reserve (pfile, 2);
6443 cppReader_putCharQ (pfile, c);
6444 cppReader_nullTerminateQ (pfile);
6449 cppReader_forward (pfile, -1);
6451 cppReader_nullTerminate (pfile);
6458 case 'a': case 'e': case 'f': case 'g': case 'i': case 'j':
6459 case 'k': case 'l': case 'm': case 'n': case 'p': case 'q':
6460 case 'r': case 's': case 't': case 'u': case 'v': case 'w':
6461 case 'x': case 'y': case 'z':
6462 case 'A': case 'E': case 'F': case 'G': case 'I': case 'J':
6463 case 'K': case 'M': case 'N': case 'P': case 'Q': case 'R':
6464 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
6470 size_t before_name_written = cpplib_getWritten (pfile);
6472 parse_name (pfile, c);
6473 pfile->only_seen_white = 0;
6475 if (pfile->no_macro_expand)
6477 DPRINTF (("Not expanding: %s", pfile->token_buffer));
6481 ident = pfile->token_buffer + before_name_written;
6482 DPRINTF (("Ident: %s", ident));
6484 ident_len = size_fromInt ((cpplib_getPWritten (pfile)) - ident);
6486 hp = cpphash_lookupExpand (ident, size_toInt (ident_len), -1, forceExpand);
6490 DPRINTF (("No expand: %s %d", ident, ident_len));
6494 if (hp->type == T_DISABLED)
6496 DPRINTF (("Disabled!"));
6498 if (pfile->output_escapes)
6499 { /* Return "@-IDENT", followed by '\0'. */
6501 cpplib_reserve (pfile, 3);
6502 ident = pfile->token_buffer + before_name_written;
6503 cppReader_adjustWritten (pfile, 2);
6505 for (i = size_toInt (ident_len); i >= 0; i--)
6507 ident[i+2] = ident[i];
6517 ** If macro wants an arglist, verify that a '(' follows.
6518 ** first skip all whitespace, copying it to the output
6519 ** after the macro name. Then, if there is no '(',
6520 ** decide this is not a macro call and leave things that way.
6523 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
6525 struct parse_marker macro_mark;
6528 DPRINTF (("Arglist macro!"));
6531 ** evans 2002-07-03: Moved this here (from below).
6532 ** This bug caused necessary whitespace to be lost
6533 ** when parsing parameterized macros without parameters.
6536 parseSetMark (¯o_mark, pfile);
6538 while (cppBuffer_isMacro (CPPBUFFER (pfile)))
6540 cppBuffer *next_buf;
6541 cppSkipHspace (pfile);
6542 if (cppReader_peekC (pfile) != EOF)
6544 DPRINTF (("Peeking!"));
6545 /*@loopbreak@*/ break;
6548 next_buf = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6549 (*cppReader_getBufferSafe (pfile)->cleanup) (cppReader_getBufferSafe (pfile), pfile);
6550 CPPBUFFER (pfile) = next_buf;
6553 /* parseSetMark (¯o_mark, pfile); */
6557 cppSkipHspace (pfile);
6558 c = cppReader_peekC (pfile);
6559 DPRINTF (("c: %c", c));
6560 is_macro_call = c == '(';
6562 /*@loopbreak@*/ break;
6563 cppReader_forward (pfile, 1);
6568 parseGotoMark (¯o_mark, pfile);
6571 parseClearMark (¯o_mark);
6575 DPRINTF (("not macro call!"));
6580 /* This is now known to be a macro call. */
6582 /* it might not actually be a macro. */
6583 if (hp->type != T_MACRO)
6588 cppReader_setWritten (pfile, before_name_written);
6589 special_symbol (hp, pfile);
6590 xbuf_len = cpplib_getWritten (pfile) - before_name_written;
6591 xbuf = (char *) dmalloc (xbuf_len + 1);
6592 cppReader_setWritten (pfile, before_name_written);
6593 memcpy (xbuf, cpplib_getPWritten (pfile), xbuf_len + 1);
6594 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
6599 ** Expand the macro, reading arguments as needed,
6600 ** and push the expansion on the input stack.
6603 cpplib_macroExpand (pfile, hp);
6604 cppReader_setWritten (pfile, before_name_written);
6607 /* An extra "@ " is added to the end of a macro expansion
6608 to prevent accidental token pasting. We prefer to avoid
6609 unneeded extra spaces (for the sake of cpp-using tools like
6610 imake). Here we remove the space if it is safe to do so. */
6612 llassert (pfile->buffer->rlimit != NULL);
6614 if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
6615 && pfile->buffer->rlimit[-2] == '@'
6616 && pfile->buffer->rlimit[-1] == ' ')
6618 int c1 = pfile->buffer->rlimit[-3];
6619 int cl2 = cpplib_bufPeek (cppBuffer_prevBuffer (CPPBUFFER (pfile)));
6621 if (cl2 == EOF || !unsafe_chars ((char) c1, (char) cl2))
6622 pfile->buffer->rlimit -= 2;
6628 case ' ': case '\t': case '\v': case '\r':
6631 cppReader_putChar (pfile, c);
6632 c = cppReader_peekC (pfile);
6633 if (c == EOF || !is_hor_space[c])
6634 /*@loopbreak@*/ break;
6635 cppReader_forward (pfile, 1);
6640 c2 = cppReader_peekC (pfile);
6647 cppReader_putChar (pfile, c);
6648 if (pfile->only_seen_white == 0)
6649 pfile->only_seen_white = 1;
6651 output_line_command (pfile, 1, same_file);
6654 case '(': token = CPP_LPAREN; goto char1;
6655 case ')': token = CPP_RPAREN; goto char1;
6656 case '{': token = CPP_LBRACE; goto char1;
6657 case '}': token = CPP_RBRACE; goto char1;
6658 case ',': token = CPP_COMMA; goto char1;
6659 case ';': token = CPP_SEMICOLON; goto char1;
6665 pfile->only_seen_white = 0;
6666 cppReader_putChar (pfile, c);
6675 /* Parse an identifier starting with C. */
6678 parse_name (cppReader *pfile, int c)
6684 if (c == '\\' && cppReader_peekC (pfile) == '\n')
6686 cppReader_forward (pfile, 2);
6690 cppReader_forward (pfile, -1);
6694 if (c == '$' && cppReader_isPedantic (pfile))
6696 cppReader_pedwarnLit (pfile,
6697 cstring_makeLiteralTemp ("`$' in identifier"));
6700 cpplib_reserve(pfile, 2); /* One more for final NUL. */
6701 cppReader_putCharQ (pfile, c);
6702 c = cppReader_getC (pfile);
6708 cppReader_nullTerminateQ (pfile);
6711 /* The file_name_map structure holds a mapping of file names for a
6712 particular directory. This mapping is read from the file named
6713 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
6714 map filenames on a file system with severe filename restrictions,
6715 such as DOS. The format of the file name map file is just a series
6716 of lines with two tokens on each line. The first token is the name
6717 to map, and the second token is the actual name to use. */
6719 struct file_name_map
6721 struct file_name_map *map_next;
6726 /*@constant observer char *FILE_NAME_MAP_FILE*/
6727 #define FILE_NAME_MAP_FILE "header.gcc"
6729 /* Read a space delimited string of unlimited length from a stdio
6732 static cstring read_filename_string (int ch, /*:open:*/ FILE *f)
6738 set = alloc = dmalloc (len + 1);
6743 while ((ch = getc (f)) != EOF && ! is_space[ch])
6745 if (set - alloc == size_toInt (len))
6748 alloc = drealloc (alloc, len + 1);
6749 set = alloc + len / 2;
6750 /*@-branchstate@*/ }
6753 } /*@=branchstate@*/
6756 check (ungetc (ch, f) != EOF);
6758 return cstring_fromChars (alloc);
6761 /* This structure holds a linked list of file name maps, one per directory. */
6763 struct file_name_map_list
6765 /*@only@*/ struct file_name_map_list *map_list_next;
6766 /*@only@*/ cstring map_list_name;
6767 /*@null@*/ struct file_name_map *map_list_map;
6770 /* Read the file name map file for DIRNAME. */
6772 static struct file_name_map *
6773 read_name_map (cppReader *pfile, cstring dirname)
6775 struct file_name_map_list *map_list_ptr;
6779 for (map_list_ptr = CPPOPTIONS (pfile)->map_list;
6780 map_list_ptr != NULL;
6781 map_list_ptr = map_list_ptr->map_list_next)
6783 if (cstring_equal (map_list_ptr->map_list_name, dirname))
6785 return map_list_ptr->map_list_map;
6789 map_list_ptr = (struct file_name_map_list *) dmalloc (sizeof (*map_list_ptr));
6790 map_list_ptr->map_list_name = cstring_copy (dirname);
6791 map_list_ptr->map_list_map = NULL;
6793 name = cstring_copy (dirname);
6795 if (cstring_length (dirname) > 0)
6797 name = cstring_appendChar (name, CONNECTCHAR);
6800 name = cstring_concatFree1 (name, cstring_makeLiteralTemp (FILE_NAME_MAP_FILE));
6802 f = fileTable_openReadFile (context_fileTable (), name);
6803 cstring_free (name);
6807 map_list_ptr->map_list_map = NULL;
6813 while ((ch = getc (f)) != EOF)
6816 struct file_name_map *ptr;
6823 from = read_filename_string (ch, f);
6824 while ((ch = getc (f)) != EOF && is_hor_space[ch])
6829 to = read_filename_string (ch, f);
6831 ptr = (struct file_name_map *) dmalloc (sizeof (*ptr));
6832 ptr->map_from = from;
6834 /* Make the real filename absolute. */
6835 if (cstring_length (to) > 1
6836 && osd_isConnectChar (cstring_firstChar (to)))
6842 ptr->map_to = cstring_copy (dirname);
6843 ptr->map_to = cstring_appendChar (ptr->map_to, CONNECTCHAR);
6844 ptr->map_to = cstring_concatFree (ptr->map_to, to);
6847 ptr->map_next = map_list_ptr->map_list_map;
6848 map_list_ptr->map_list_map = ptr;
6850 while ((ch = getc (f)) != '\n')
6854 /*@innerbreak@*/ break;
6859 assertSet (map_list_ptr->map_list_map);
6860 check (fileTable_closeFile (context_fileTable (),f) == 0);
6863 map_list_ptr->map_list_next = pfile->opts->map_list;
6864 pfile->opts->map_list = map_list_ptr;
6866 return map_list_ptr->map_list_map;
6869 /* Try to open include file FILENAME. SEARCHPTR is the directory
6870 being tried from the include file search path. This function maps
6871 filenames on file systems based on information read by
6875 open_include_file (cppReader *pfile,
6877 struct file_name_list *searchptr)
6879 char *filename = cstring_toCharsSafe (fname);
6880 struct file_name_map *map;
6884 cstring_markOwned (fname);
6886 cpp_setLocation (pfile);
6888 if (context_getFlag (FLG_NEVERINCLUDE))
6890 if (isHeaderFile (fname))
6892 return SKIP_INCLUDE;
6896 if ((searchptr != NULL) && ! searchptr->got_name_map)
6898 searchptr->name_map = read_name_map (pfile,
6899 !cstring_isEmpty (searchptr->fname)
6900 ? searchptr->fname :
6901 cstring_makeLiteralTemp ("."));
6902 searchptr->got_name_map = 1;
6905 /* First check the mapping for the directory we are using. */
6907 if ((searchptr != NULL)
6908 && (searchptr->name_map != NULL))
6912 if (!cstring_isEmpty (searchptr->fname))
6914 from += cstring_length (searchptr->fname) + 1;
6917 for (map = searchptr->name_map;
6919 map = map->map_next)
6921 if (cstring_equal (map->map_from, cstring_fromChars (from)))
6924 ** Found a match. Check if the file should be skipped
6927 if (cpp_skipIncludeFile (map->map_to))
6929 return SKIP_INCLUDE;
6933 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
6940 ** Try to find a mapping file for the particular directory we are
6941 ** looking in. Thus #include <sys/types.h> will look up sys/types.h
6942 ** in /usr/include/header.gcc and look up types.h in
6943 ** /usr/include/sys/header.gcc.
6946 p = strrchr (filename, CONNECTCHAR);
6953 if ((searchptr != NULL)
6954 && (cstring_isDefined (searchptr->fname))
6955 && (size_toInt (cstring_length (searchptr->fname)) == p - filename)
6956 && !strncmp (cstring_toCharsSafe (searchptr->fname),
6958 size_fromInt (p - filename)))
6960 /* filename is in SEARCHPTR, which we've already checked. */
6962 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
6964 return SKIP_INCLUDE;
6968 return cpp_openIncludeFile (filename);
6974 dir = mstring_copy (".");
6979 dir = (char *) dmalloc (size_fromInt (p - filename + 1));
6980 memcpy (dir, filename, size_fromInt (p - filename));
6981 dir[p - filename] = '\0';
6985 for (map = read_name_map (pfile, cstring_fromChars (dir));
6987 map = map->map_next)
6989 if (cstring_equal (map->map_from, cstring_fromChars (from)))
6993 if (cpp_skipIncludeFile (map->map_to))
6995 return SKIP_INCLUDE;
6999 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
7006 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
7008 return SKIP_INCLUDE;
7012 return cpp_openIncludeFile (filename);
7016 /* Process the contents of include file FNAME, already open on descriptor F,
7018 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
7019 "system" include directories (as decided by the `is_system_include'
7021 DIRPTR is the link in the dir path through which this file was found,
7022 or 0 if the file name was absolute or via the current directory.
7023 Return 1 on success, 0 on failure.
7025 The caller is responsible for the cppReader_pushBuffer. */
7028 finclude (cppReader *pfile, int f,
7030 bool system_header_p,
7031 /*@dependent@*/ struct file_name_list *dirptr)
7037 cppBuffer *fp; /* For input stack frame */
7039 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
7041 cppReader_perrorWithName (pfile, fname);
7042 check (close (f) == 0);
7043 (void) cppReader_popBuffer (pfile);
7049 fp = cppReader_getBufferSafe (pfile);
7051 /*@-temptrans@*/ /* fname shouldn't really be temp */
7052 fp->nominal_fname = fp->fname = fname;
7056 fp->system_header_p = system_header_p;
7059 fp->cleanup = cppReader_fileCleanup;
7061 if (S_ISREG (st_mode))
7064 fp->buf = (char *) dmalloc (st_size + 2);
7065 fp->alimit = fp->buf + st_size + 2;
7068 /* Read the file contents, knowing that st_size is an upper bound
7069 on the number of bytes we can read. */
7070 length = safe_read (f, fp->buf, size_toInt (st_size));
7071 fp->rlimit = fp->buf + length;
7072 if (length < 0) goto nope;
7074 else if (S_ISDIR (st_mode))
7076 cppReader_error (pfile,
7077 message ("Directory specified where file is expected: %s", fname));
7078 check (close (f) == 0);
7084 ** Cannot count its file size before reading.
7085 ** First read the entire file into heap and
7086 ** copy them into buffer on stack.
7089 size_t bsize = 2000;
7094 fp->buf = (char *) dmalloc (bsize + 2);
7097 i = safe_read (f, fp->buf + st_size, size_toInt (bsize - st_size));
7100 goto nope; /* error! */
7103 if (st_size != bsize)
7105 break; /* End of file */
7109 fp->buf = (char *) drealloc (fp->buf, bsize + 2);
7113 length = size_toInt (st_size);
7116 if ((length > 0 && fp->buf[length - 1] != '\n')
7117 /* Backslash-newline at end is not good enough. */
7118 || (length > 1 && fp->buf[length - 2] == '\\')) {
7119 fp->buf[length++] = '\n';
7122 fp->buf[length] = '\0';
7123 fp->rlimit = fp->buf + length;
7125 /* Close descriptor now, so nesting does not use lots of descriptors. */
7126 check (close (f) == 0);
7128 /* Must do this before calling trigraph_pcp, so that the correct file name
7129 will be printed in warning messages. */
7131 pfile->input_stack_listing_current = 0;
7136 cppReader_perrorWithName (pfile, fname);
7137 check (close (f) == 0);
7143 cpplib_init (cppReader *pfile)
7145 memset ((char *) pfile, 0, sizeof (*pfile));
7147 pfile->get_token = cpplib_getToken;
7148 pfile->token_buffer_size = 200;
7149 pfile->token_buffer = (char *) dmalloc (pfile->token_buffer_size);
7150 pfile->all_include_files = NULL;
7154 cppReader_setWritten (pfile, 0);
7156 pfile->system_include_depth = 0;
7157 pfile->max_include_len = 0;
7158 pfile->timebuf = NULL;
7159 pfile->only_seen_white = 1;
7161 pfile->buffer = cppReader_nullBuffer (pfile);
7165 cppReader_finish (/*@unused@*/ cppReader *pfile)
7170 /* Free resources used by PFILE.
7171 This is the cppReader 'finalizer' or 'destructor' (in C++ terminology). */
7174 cppCleanup (/*@special@*/ cppReader *pfile)
7176 /*@releases pfile@*/
7178 DPRINTF (("cppCleanup!"));
7180 while (CPPBUFFER (pfile) != cppReader_nullBuffer (pfile))
7182 (void) cppReader_popBuffer (pfile);
7185 if (pfile->token_buffer != NULL)
7187 sfree (pfile->token_buffer);
7188 pfile->token_buffer = NULL;
7191 while (pfile->if_stack != NULL)
7193 cppIfStackFrame *temp = pfile->if_stack;
7194 pfile->if_stack = temp->next;
7198 while (pfile->all_include_files != NULL)
7200 struct file_name_list *temp = pfile->all_include_files;
7201 pfile->all_include_files = temp->next;
7202 /*@-dependenttrans@*/
7203 cstring_free (temp->fname);
7204 /*@=dependenttrans@*/
7208 /* evans 2002-07-12 */
7209 while (pfile->opts->map_list != NULL)
7211 struct file_name_map_list *temp = pfile->opts->map_list;
7212 pfile->opts->map_list = pfile->opts->map_list->map_list_next;
7213 cstring_free (temp->map_list_name);
7217 while (pfile->opts->include != NULL)
7219 struct file_name_list *temp = pfile->opts->include;
7220 pfile->opts->include = pfile->opts->include->next;
7221 /* cstring_free (temp->fname); */
7225 sfree (pfile->opts);
7227 cppReader_hashCleanup ();
7231 ** Get the file-mode and data size of the file open on FD
7232 ** and store them in *MODE_POINTER and *SIZE_POINTER.
7236 file_size_and_mode (int fd, mode_t *mode_pointer, size_t *size_pointer)
7240 if (fstat (fd, &sbuf) < 0) {
7246 if (mode_pointer != NULL)
7248 *mode_pointer = sbuf.st_mode;
7251 if (size_pointer != NULL)
7253 *size_pointer = (size_t) sbuf.st_size;
7259 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
7260 retrying if necessary. Return a negative value if an error occurs,
7261 otherwise return the actual number of bytes read,
7262 which must be LEN unless end-of-file was reached. */
7264 static int safe_read (int desc, char *ptr, int len)
7270 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
7271 /*@-compdef@*/ /* ptr is an out parameter */
7272 int nchars = _read (desc, ptr, (unsigned) left);
7275 ssize_t nchars = read (desc, ptr, size_fromInt (left));
7284 return (int) nchars;
7298 /* Initialize PMARK to remember the current position of PFILE. */
7301 parseSetMark (struct parse_marker *pmark, cppReader *pfile)
7303 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7305 pmark->next = pbuf->marks;
7307 pbuf->marks = pmark;
7311 pmark->position = pbuf->cur - pbuf->buf;
7312 DPRINTF (("set mark: %d / %s", pmark->position, pbuf->cur));
7315 /* Cleanup PMARK - we no longer need it. */
7317 void parseClearMark (struct parse_marker *pmark)
7319 struct parse_marker **pp = &pmark->buf->marks;
7321 for (; ; pp = &(*pp)->next)
7323 llassert (*pp != NULL);
7324 if (*pp == pmark) break;
7330 /* Backup the current position of PFILE to that saved in PMARK. */
7333 parseGotoMark (struct parse_marker *pmark, cppReader *pfile)
7335 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7337 if (pbuf != pmark->buf)
7339 cpp_setLocation (pfile);
7340 llfatalbug (cstring_makeLiteral ("Internal error parseGotoMark"));
7343 llassert (pbuf->buf != NULL);
7344 pbuf->cur = pbuf->buf + pmark->position;
7345 DPRINTF (("goto mark: %d / %s", pmark->position, pbuf->cur));
7348 /* Reset PMARK to point to the current position of PFILE. (Same
7349 as parseClearMark (PMARK), parseSetMark (PMARK, PFILE) but faster. */
7352 parseMoveMark (struct parse_marker *pmark, cppReader *pfile)
7354 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7356 if (pbuf != pmark->buf)
7358 cpp_setLocation (pfile);
7359 llfatalerror (cstring_makeLiteral ("Internal error parseMoveMark"));
7362 pmark->position = pbuf->cur - pbuf->buf;
7363 DPRINTF (("move mark: %s", pmark->position));
7366 void cpplib_initializeReader (cppReader *pfile) /* Must be done after library is loaded. */
7368 struct cppOptions *opts = CPPOPTIONS (pfile);
7371 /* The code looks at the defaults through this pointer, rather than through
7372 the constant structure above. This pointer gets changed if an environment
7373 variable specifies other defaults. */
7375 struct default_include *include_defaults = include_defaults_array;
7377 /* Add dirs from INCLUDEPATH_VAR after dirs from -I. */
7378 /* There seems to be confusion about what CPATH should do,
7379 so for the moment it is not documented. */
7380 /* Some people say that CPATH should replace the standard include dirs,
7381 but that seems pointless: it comes before them, so it overrides them
7384 xp = osd_getEnvironmentVariable (INCLUDEPATH_VAR);
7386 if (cstring_isDefined (xp) && !opts->no_standard_includes)
7388 path_include (pfile, cstring_toCharsSafe (xp));
7391 /* Now that dollars_in_ident is known, initialize is_idchar. */
7392 initialize_char_syntax (opts);
7394 /* CppReader_Install __LINE__, etc. Must follow initialize_char_syntax
7395 and option processing. */
7397 initialize_builtins (pfile);
7399 /* Do standard #defines and assertions
7400 that identify system and machine type. */
7402 if (!opts->inhibit_predefs) {
7403 char *p = (char *) dmalloc (strlen (predefs) + 1);
7404 strcpy (p, predefs);
7410 while (*p == ' ' || *p == '\t')
7415 /* Handle -D options. */
7416 if (p[0] == '-' && p[1] == 'D')
7420 while (*p && *p != ' ' && *p != '\t')
7430 if (opts->debug_output)
7432 output_line_command (pfile, 0, same_file);
7435 cppReader_define (pfile, q);
7437 while (*p == ' ' || *p == '\t')
7451 opts->done_initializing = 1;
7453 { /* Read the appropriate environment variable and if it exists
7454 replace include_defaults with the listed path. */
7458 int win32_buf_size = 0; /* memory we need to allocate */
7461 if (opts->cplusplus)
7463 epath = getenv ("CPLUS_INCLUDE_PATH");
7467 epath = getenv ("C_INCLUDE_PATH");
7471 ** If the environment var for this language is set,
7472 ** add to the default list of include directories.
7475 if (epath != NULL) {
7476 char *nstore = (char *) dmalloc (strlen (epath) + 2);
7478 char *startp, *endp;
7481 /* if we have a posix path list, convert to win32 path list */
7482 if (cygwin32_posix_path_list_p (epath))
7484 win32_buf_size = cygwin32_posix_to_win32_path_list_buf_size (epath);
7485 win32epath = (char *) dmalloc /*@i4@*/ (win32_buf_size);
7486 cygwin32_posix_to_win32_path_list (epath, win32epath);
7490 for (num_dirs = 1, startp = epath; *startp; startp++)
7492 if (*startp == PATH_SEPARATOR)
7498 = (struct default_include *) dmalloc ((num_dirs
7499 * sizeof (struct default_include))
7500 + sizeof (include_defaults_array));
7503 startp = endp = epath;
7506 /* Handle cases like c:/usr/lib:d:/gcc/lib */
7507 if ((*endp == PATH_SEPARATOR) || *endp == 0)
7509 strncpy (nstore, startp, size_fromInt (endp - startp));
7512 strcpy (nstore, ".");
7516 nstore[endp-startp] = '\0';
7519 include_defaults[num_dirs].fname = cstring_fromCharsNew (nstore);
7520 include_defaults[num_dirs].cplusplus = opts->cplusplus;
7521 include_defaults[num_dirs].cxx_aware = 1;
7528 endp = startp = endp + 1;
7535 /* Put the usual defaults back in at the end. */
7536 memcpy ((char *) &include_defaults[num_dirs],
7537 (char *) include_defaults_array,
7538 sizeof (include_defaults_array));
7541 /*@-branchstate@*/ } /*@=branchstate@*/
7544 cppReader_appendIncludeChain (pfile, opts->before_system,
7545 opts->last_before_system);
7547 opts->first_system_include = opts->before_system;
7549 /* Unless -fnostdinc,
7550 tack on the standard include file dirs to the specified list */
7552 if (!opts->no_standard_includes) {
7553 struct default_include *p = include_defaults;
7554 char *specd_prefix = opts->include_prefix;
7555 char *default_prefix = mstring_copy (GCC_INCLUDE_DIR);
7556 size_t default_len = 0;
7558 /* Remove the `include' from /usr/local/lib/gcc.../include. */
7559 if (default_prefix != NULL) {
7560 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
7561 default_len = strlen (default_prefix) - 7;
7562 default_prefix[default_len] = 0;
7566 /* Search "translated" versions of GNU directories.
7567 These have /usr/local/lib/gcc... replaced by specd_prefix. */
7568 if (specd_prefix != 0 && default_len != 0)
7569 for (p = include_defaults; p->fname != NULL; p++) {
7570 /* Some standard dirs are only for C++. */
7572 || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
7573 /* Does this dir start with the prefix? */
7574 llassert (default_prefix != NULL);
7576 if (!strncmp (cstring_toCharsSafe (p->fname), default_prefix, default_len))
7578 /* Yes; change prefix and add to search list. */
7579 struct file_name_list *nlist
7580 = (struct file_name_list *) dmalloc (sizeof (*nlist));
7581 size_t this_len = strlen (specd_prefix) + cstring_length (p->fname) - default_len;
7582 char *str = (char *) dmalloc (this_len + 1);
7583 strcpy (str, specd_prefix);
7584 strcat (str, cstring_toCharsSafe (p->fname) + default_len);
7587 nlist->fname = cstring_fromChars (str);
7588 nlist->control_macro = 0;
7589 nlist->c_system_include_path = !p->cxx_aware;
7590 nlist->got_name_map = 0;
7592 if (opts->first_system_include == 0)
7594 opts->first_system_include = nlist;
7597 cppReader_addIncludeChain (pfile, nlist);
7602 /* Search ordinary names for GNU include directories. */
7604 for (p = include_defaults; p->fname != NULL; p++)
7606 /* Some standard dirs are only for C++. */
7608 || (opts->cplusplus && !opts->no_standard_cplusplus_includes))
7610 struct file_name_list *nlist
7611 = (struct file_name_list *) dmalloc (sizeof (*nlist));
7612 nlist->control_macro = 0;
7613 nlist->c_system_include_path = !p->cxx_aware;
7614 nlist->fname = p->fname;
7615 nlist->got_name_map = 0;
7618 /*@i2523@*/ if (opts->first_system_include == NULL)
7620 opts->first_system_include = nlist;
7623 cppReader_addIncludeChain (pfile, nlist);
7626 sfree (default_prefix);
7629 /* Tack the after_include chain at the end of the include chain. */
7630 cppReader_appendIncludeChain (pfile, opts->after_include,
7631 opts->last_after_include);
7633 /*@i523@*/ if (opts->first_system_include == NULL)
7635 opts->first_system_include = opts->after_include;
7638 /* With -v, print the list of dirs to search. */
7639 if (opts->verbose) {
7640 struct file_name_list *p;
7641 fprintf (stderr, "#include \"...\" search starts here:\n");
7643 for (p = opts->include; p != NULL; p = p->next) {
7644 if (p == opts->first_bracket_include)
7645 fprintf (stderr, "#include <...> search starts here:\n");
7647 fprintf (stderr, " %s\n", cstring_toCharsSafe (p->fname));
7649 fprintf (stderr, "End of search list.\n");
7653 int cppReader_startProcess (cppReader *pfile, cstring fname)
7657 struct cppOptions *opts = CPPOPTIONS (pfile);
7659 fp = cppReader_pushBuffer (pfile, NULL, 0);
7666 if (opts->in_fname == NULL)
7668 opts->in_fname = cstring_makeLiteralTemp ("");
7671 fp->fname = opts->in_fname;
7672 fp->nominal_fname = fp->fname;
7675 /* Copy the entire contents of the main input file into
7676 the stacked input buffer previously allocated for it. */
7678 if (cstring_isEmpty (fname))
7680 fname = cstring_makeLiteralTemp ("");
7683 else if ((f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666)) < 0)
7685 cppReader_error (pfile,
7686 message ("Error opening %s for reading: %s",
7687 fname, lldecodeerror (errno)));
7696 if (finclude (pfile, f, fname, 0, NULL))
7698 output_line_command (pfile, 0, same_file);
7704 static /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_getBuffer (cppReader *pfile)
7706 return pfile->buffer;
7709 /*@exposed@*/ cppBuffer *cppReader_getBufferSafe (cppReader *pfile)
7711 llassert (pfile->buffer != NULL);
7712 return pfile->buffer;
7715 /*@exposed@*/ char *cppLineBase (cppBuffer *buf)
7717 llassert (buf->buf != NULL);
7718 return (buf->buf + buf->line_base);
7721 int cpplib_bufPeek (cppBuffer *buf)
7723 if (buf->cur == NULL || buf->rlimit == NULL) {
7727 if (buf->cur < buf->rlimit) {
7734 bool cppBuffer_isMacro (cppBuffer *buf)
7738 return (buf->cleanup == cppReader_macroCleanup);
7745 ** Returns true if the macro should be checked, false
7746 ** if it should be expanded normally.
7749 static bool notparseable = FALSE; /* preceeded by @notparseable@ */
7750 static bool notfunction = FALSE; /* preceeded by @notfunction@ */
7751 static bool expectiter = FALSE; /* preceeded by @iter@ */
7752 static bool expectenditer = FALSE; /* second after @iter@ */
7753 static bool expectfunction = FALSE; /* preceeded by @function@ */
7754 static bool expectconstant = FALSE; /* preceeded by @constant@ */
7755 static bool expectmacro = FALSE; /* preceeded by notfunction or notparseable */
7757 static void cpp_setLocation (cppReader *pfile)
7762 if (pfile->buffer != NULL)
7764 if (cstring_isDefined (cppReader_getBufferSafe (pfile)->nominal_fname))
7766 cstring fname = cppReader_getBufferSafe (pfile)->nominal_fname;
7768 DPRINTF (("Looking up: %s", fname));
7770 if (fileTable_exists (context_fileTable (), fname))
7772 fid = fileTable_lookup (context_fileTable (), fname);
7776 DPRINTF (("Trying %s", cppReader_getBuffer (pfile)->fname));
7778 fid = fileTable_lookup (context_fileTable (),
7779 cppReader_getBufferSafe (pfile)->fname);
7784 fid = fileTable_lookup (context_fileTable (),
7785 cppReader_getBufferSafe (pfile)->fname);
7788 line = cppReader_getBufferSafe (pfile)->lineno;
7789 fileloc_free (g_currentloc);
7791 if (fileId_isValid (fid))
7793 g_currentloc = fileloc_create (fid, line, 1);
7797 g_currentloc = fileloc_createBuiltin ();
7802 fileloc_free (g_currentloc);
7803 g_currentloc = fileloc_createBuiltin ();
7807 static bool cpp_shouldCheckMacro (cppReader *pfile, char *p) /*@modifies p*/
7809 bool checkmacro = FALSE;
7810 bool hasParams = FALSE;
7811 bool noexpand = FALSE;
7815 cpp_setLocation (pfile);
7817 DPRINTF (("Should check macro? %s", p));
7819 if (expectiter || expectconstant || expectenditer)
7824 expectenditer = TRUE;
7829 expectconstant = FALSE;
7830 expectenditer = FALSE;
7833 if (notfunction || notparseable)
7835 notfunction = FALSE;
7836 notparseable = FALSE;
7845 llassert (*p == '#');
7848 while (*p == ' ' || *p == '\t')
7853 llassert (*p == 'd'); /* define starts */
7857 while (*p == ' ' || *p == '\t')
7862 sname = cstring_fromChars (p);
7863 DPRINTF (("Check macro: %s", sname));
7865 while (((c = *p) != ' ')
7866 && c != '\0' && c != '('
7867 && c != '\t' && c != '\\' && c != '\n'
7873 hasParams = (c == '(');
7878 notparseable = FALSE;
7880 else if (notfunction || fileloc_isStandardLib (g_currentloc))
7882 DPRINTF (("Clear notfunction"));
7883 notfunction = FALSE;
7898 if (usymtab_existsReal (sname))
7900 uentry ue = usymtab_lookup (sname);
7902 DPRINTF (("Lookup macro: %s", uentry_unparse (ue)));
7904 if (fileloc_isPreproc (uentry_whereLast (ue)))
7910 if (uentry_isSpecified (ue))
7912 checkmacro = context_getFlag (FLG_SPECMACROS);
7918 checkmacro = context_getFlag (FLG_LIBMACROS)
7919 || context_getFlag (FLG_FCNMACROS);
7927 DPRINTF (("Macro doesn't exist: %s", bool_unparse (checkmacro)));
7929 if (fileloc_isSystemFile (g_currentloc)
7930 && context_getFlag (FLG_SYSTEMDIREXPAND))
7932 ; /* don't check this macro */
7933 DPRINTF (("Don't check 1"));
7941 DPRINTF (("Has params..."));
7943 if (context_getFlag (FLG_FCNMACROS))
7945 if (usymtab_exists (sname))
7948 ** only get here is macro is redefined
7949 ** error reported elsewhere
7952 DPRINTF (("It exists!"));
7957 ** We make it a forward function, since it might be declared elsewhere.
7958 ** After all headers have been processed, we should check the forward
7962 fileloc loc = fileloc_makePreproc (g_currentloc);
7964 /* the line is off-by-one, since the newline was already read */
7969 expectfunction = FALSE;
7972 le = uentry_makeForwardFunction (sname,
7973 typeId_invalid, loc);
7979 /* Do not define here! */
7981 (void) usymtab_addEntry (le);
7985 DPRINTF (("Check: TRUE"));
7989 DPRINTF (("Flag FCN_MACROS not set!"));
7994 DPRINTF (("No params"));
7996 if (context_getFlag (FLG_CONSTMACROS))
7998 bool nocontent = FALSE;
8011 ** Check if there is nothing after the define.
8014 while ((*rest) != '\0' && isspace (*rest))
8021 nocontent = TRUE; /* empty macro, don't check */
8026 if (usymtab_exists (sname))
8032 fileloc loc = fileloc_makePreproc (g_currentloc);
8033 DPRINTF (("Make constant: %s", sname));
8034 le = uentry_makeMacroConstant (sname, ctype_unknown, loc);
8035 (void) usymtab_addEntry (le);
8038 checkmacro = !nocontent;
8043 if (checkmacro && usymtab_existsType (sname))
8045 DPRINTF (("Making false..."));
8047 ppllerror (message ("Specified type implemented as macro: %s", sname));
8057 if (usymtab_exists (sname))
8059 uentry ue = usymtab_lookupExpose (sname);
8060 fileloc tloc = fileloc_makePreproc (g_currentloc);
8062 uentry_setDefined (ue, tloc);
8063 fileloc_free (tloc);
8064 uentry_setUsed (ue, fileloc_undefined);
8068 fileloc tloc = fileloc_makePreproc (g_currentloc);
8069 uentry ue = uentry_makeExpandedMacro (sname, tloc);
8070 DPRINTF (("Make expanded macro: %s", sname));
8071 DPRINTF (("Not in symbol table: %s", sname));
8073 (void) usymtab_addGlobalEntry (ue);
8074 fileloc_free (tloc);
8079 DPRINTF (("Returning: %s", bool_unparse (checkmacro)));
8083 static enum cpp_token
8084 cpp_handleComment (cppReader *pfile, struct parse_marker *smark)
8086 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
8090 bool eliminateComment = FALSE;
8092 llassert (pbuf->buf != NULL);
8094 start = pbuf->buf + smark->position;
8096 llassert (pbuf->cur != NULL);
8097 len = pbuf->cur - start;
8100 && start[1] == context_getCommentMarkerChar ())
8104 char *scomment = start + 2;
8105 char savec = start[len];
8107 cpp_setLocation (pfile);
8108 loc = fileloc_copy (g_currentloc);
8110 start[0] = BEFORE_COMMENT_MARKER[0];
8111 start[1] = BEFORE_COMMENT_MARKER[1];
8113 llassert (start[len - 2] == '*');
8114 start[len - 2] = AFTER_COMMENT_MARKER[0];
8116 llassert (start[len - 1] == '/');
8117 start[len - 1] = AFTER_COMMENT_MARKER[1];
8119 cpplib_reserve(pfile, size_fromInt (1 + len));
8120 cppReader_putCharQ (pfile, c);
8122 cpp_setLocation (pfile);
8126 if (mstring_containsString (scomment, "/*"))
8128 (void) cppoptgenerror
8130 message ("Comment starts inside syntactic comment: %s",
8131 cstring_fromChars (scomment)),
8137 if (mstring_equalPrefix (scomment, "ignore"))
8139 if (!context_getFlag (FLG_NOCOMMENTS))
8141 context_enterSuppressRegion (loc);
8144 else if (mstring_equalPrefix (scomment, "end"))
8146 if (!context_getFlag (FLG_NOCOMMENTS))
8148 context_exitSuppressRegion (loc);
8151 else if (mstring_equalPrefix (scomment, "notparseable"))
8153 notparseable = TRUE;
8155 eliminateComment = TRUE;
8157 else if (mstring_equalPrefix (scomment, "notfunction"))
8161 eliminateComment = TRUE;
8163 else if (mstring_equalPrefix (scomment, "iter"))
8167 else if (mstring_equalPrefix (scomment, "function"))
8169 expectfunction = TRUE;
8171 else if (mstring_equalPrefix (scomment, "constant"))
8173 expectconstant = TRUE;
8177 char sChar = *scomment;
8183 char *rest = scomment + 1;
8185 if (mstring_equalPrefix (rest, "commentchar"))
8187 eliminateComment = TRUE;
8191 ppllerror (cstring_makeLiteral
8192 ("Cannot restore commentchar"));
8196 char *next = scomment + 12; /* strlen commentchar = 12 */
8198 if (*next != ' ' && *next != '\t' && *next != '\n')
8202 ("Syntactic commentchar comment is not followed by a "
8203 "whitespace character: %c",
8208 char cchar = *(next + 1);
8213 (cstring_makeLiteral
8214 ("Cannot set commentchar to NUL"));
8218 context_setCommentMarkerChar (cchar);
8219 /* setComment = TRUE; */
8224 else if (mstring_equalPrefix (scomment, "nestcomment"))
8226 /* fix from Mike Miller <MikeM@xata.com> */
8227 context_fileSetFlag (FLG_NESTCOMMENT,
8228 ynm_fromCodeChar (sChar),
8231 else if (mstring_equalPrefix (rest, "namechecks"))
8233 context_fileSetFlag (FLG_NAMECHECKS,
8234 ynm_fromCodeChar (sChar),
8237 else if (mstring_equalPrefix (rest, "macroredef"))
8239 context_fileSetFlag (FLG_MACROREDEF,
8240 ynm_fromCodeChar (sChar),
8243 else if (mstring_equalPrefix (rest, "usevarargs"))
8245 context_fileSetFlag (FLG_USEVARARGS,
8246 ynm_fromCodeChar (sChar),
8249 else if (mstring_equalPrefix (rest, "nextlinemacros"))
8251 context_fileSetFlag (FLG_MACRONEXTLINE,
8252 ynm_fromCodeChar (sChar),
8255 else if (mstring_equalPrefix (rest, "allmacros")
8256 || mstring_equalPrefix (rest, "fcnmacros")
8257 || mstring_equalPrefix (rest, "constmacros"))
8261 if (mstring_equalPrefix (rest, "allmacros"))
8265 else if (mstring_equalPrefix (rest, "fcnmacros"))
8271 llassert (mstring_equalPrefix (rest, "constmacros"));
8272 fl = FLG_CONSTMACROS;
8275 context_fileSetFlag (fl, ynm_fromCodeChar (sChar), loc);
8276 notfunction = FALSE;
8289 if (eliminateComment)
8294 /* Replaces comment char's in start with spaces */
8296 for (i = 2; i < len - 2; i++)
8298 if (start[i] == BEFORE_COMMENT_MARKER[0]
8299 || start[i] == BEFORE_COMMENT_MARKER[1]
8300 || start[i] == context_getCommentMarkerChar ())
8306 cppReader_putStrN (pfile, start, size_fromInt (len));
8307 parseClearMark (smark);
8317 ** Output the comment as all spaces so line/column
8318 ** in output file is still correct.
8322 cstring lintcomment = cstring_undefined;
8324 if (context_getFlag (FLG_LINTCOMMENTS))
8326 if (mstring_equalPrefix (start, "*NOTREACHED*/"))
8328 lintcomment = cstring_makeLiteralTemp ("l_notreach");
8330 else if (mstring_equalPrefix (start, "*PRINTFLIKE*/"))
8332 lintcomment = cstring_makeLiteralTemp ("l_printfli");
8334 else if (mstring_equalPrefix (start, "*FALLTHROUGH*/"))
8336 lintcomment = cstring_makeLiteralTemp ("l_fallthrou");
8338 else if (mstring_equalPrefix (start, "*ARGSUSED*/"))
8340 lintcomment = cstring_makeLiteralTemp ("l_argsus");
8342 else if (mstring_equalPrefix (start, "*FALLTHRU*/"))
8344 lintcomment = cstring_makeLiteralTemp ("l_fallth");
8348 lintcomment = cstring_undefined;
8353 lintcomment = cstring_undefined;
8356 if (cstring_isDefined (lintcomment))
8358 c = BEFORE_COMMENT_MARKER[0];
8359 start[0] = BEFORE_COMMENT_MARKER[1];
8361 llassert (size_toLong (cstring_length (lintcomment)) == len - 3);
8363 for (i = 1; i < len - 2; i++)
8365 start[i] = cstring_getChar (lintcomment, size_fromInt (i));
8368 start[len - 2] = AFTER_COMMENT_MARKER[0];
8369 start[len - 1] = AFTER_COMMENT_MARKER[1];
8373 /* Replaces char's in start with spaces */
8374 for (i = 0; i < len; i++)
8378 && start[i + 1] == '*') {
8379 (void) cppoptgenerror
8381 message ("Comment starts inside comment"),
8385 if (start[i] != '\n')
8392 cpplib_reserve (pfile, size_fromInt (1 + len));
8393 cppReader_putCharQ (pfile, c);
8394 cppReader_putStrN (pfile, start, size_fromInt (len));
8395 parseClearMark (smark);
8401 static int cpp_openIncludeFile (char *filename)
8403 int res = open (filename, O_RDONLY, 0666);
8405 /* evans 2001-08-23: was (res) - open returns -1 on error! reported by Robin Watts */
8408 if (!fileTable_exists (context_fileTable (),
8409 cstring_fromChars (filename)))
8411 if (fileloc_isXHFile (g_currentloc))
8414 ** Files includes by XH files are also XH files
8417 (void) fileTable_addXHFile (context_fileTable (),
8418 cstring_fromChars (filename));
8422 (void) fileTable_addHeaderFile (context_fileTable (),
8423 cstring_fromChars (filename));
8428 DPRINTF (("File already exists: %s", filename));
8435 static bool cpp_skipIncludeFile (cstring fname)
8437 if (context_isSystemDir (fname))
8439 DPRINTF (("System dir: %s", fname));
8441 if (lcllib_isSkipHeader (fname))
8443 DPRINTF (("Skip include TRUE: %s", fname));
8447 if (context_getFlag (FLG_SKIPSYSHEADERS))
8449 DPRINTF (("Skip include TRUE: %s", fname));
8454 if (context_getFlag (FLG_SINGLEINCLUDE))
8456 fname = removePreDirs (fname);
8458 # if defined (WIN32) || defined (OS2)
8459 cstring_replaceAll (fname, '\\', '/');
8462 if (fileTable_exists (context_fileTable (), fname))
8464 DPRINTF (("Skip include TRUE: %s", fname));
8469 DPRINTF (("Skip include FALSE: %s", fname));
8473 static int cpp_peekN (cppReader *pfile, int n)
8475 cppBuffer *buf = cppReader_getBufferSafe (pfile);
8477 llassert (buf->cur != NULL);
8479 return (buf->rlimit - buf->cur >= (n)
8484 cppBuffer *cppBuffer_prevBuffer (cppBuffer *buf)
8489 void cppBuffer_forward (cppBuffer *buf, int n)
8491 llassert (buf->cur != NULL);
8495 /*@=bufferoverflowhigh@*/