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__)
75 # include <sys/utime.h> /* for __DATE__ and __TIME__ */
82 ** evans 2002-07-03: exception for WATCOM 10.6 compiler suggest by Adam Clarke
84 # if !defined (USG) && !defined (__WATCOMC__)
85 # include <time.h> /* Reported by Paul Smith */
86 # include <sys/time.h>
87 # include <sys/resource.h>
89 # include <sys/times.h>
94 # endif /* not WIN32 */
96 /* This defines "errno" properly for VMS, and gives us EACCES. */
99 # include "splintMacros.nf"
103 # include "cpperror.h"
104 # include "cpphash.h"
106 # include "version.h"
110 ** This is really kludgey code...
116 /* Warnings for using sprintf - suppress them all for now... */
117 /*@-bufferoverflowhigh@*/
120 #define NO_SHORTNAMES
128 /*@constant int IMPORT_FOUND@*/
129 # define IMPORT_FOUND -2
131 /*@constant int SKIP_INCLUDE@*/
132 # define SKIP_INCLUDE IMPORT_FOUND
134 /*@constant unused int IMPORT_NOT_FOUND@*/
135 # define IMPORT_NOT_FOUND -1
138 /*@constant unused int STDC_VALUE@*/
142 /* By default, colon separates directories in a path. */
143 #ifndef PATH_SEPARATOR
144 /*@constant char PATH_SEPARATOR@*/
145 #define PATH_SEPARATOR ':'
148 static void parse_name (cppReader *, int);
150 static int cpp_openIncludeFile (char *p_filename)
151 /*@modifies fileSystem @*/ ;
153 static void cpp_setLocation (cppReader *p_pfile)
154 /*@modifies g_currentloc@*/ ;
156 static enum cpp_token cpp_handleComment (cppReader *p_pfile,
157 struct parse_marker *p_smark)
158 /*@modifies p_pfile, p_smark@*/;
160 static bool cpp_shouldCheckMacro (cppReader *p_pfile, char *p_p) /*@modifies p_p@*/ ;
162 static size_t cppReader_checkMacroNameLoc (fileloc p_loc, char *p_symname, cstring p_usage) ;
164 static bool cpp_skipIncludeFile (cstring p_fname) /*@*/ ;
170 /* Symbols to predefine. */
172 #ifdef CPP_PREDEFINES
173 static /*@observer@*/ char *predefs = CPP_PREDEFINES;
175 static /*@observer@*/ char *predefs = "";
178 /* We let tm.h override the types used here, to handle trivial differences
179 such as the choice of unsigned int or long unsigned int for size_t.
180 When machines start needing nontrivial differences in the size type,
181 it would be best to do something here to figure out automatically
182 from other information what type to use. */
184 /* The string value for __SIZE_TYPE__. */
187 /*@constant observer char *SIZE_TYPE@*/
188 #define SIZE_TYPE "long unsigned int"
191 /* The string value for __PTRDIFF_TYPE__. */
194 /*@constant observer char *PTRDIFF_TYPE@*/
195 #define PTRDIFF_TYPE "long int"
198 /* The string value for __WCHAR_TYPE__. */
201 /*@constant observer char *WCHAR_TYPE@*/
202 #define WCHAR_TYPE "int"
205 /* The string value for __USER_LABEL_PREFIX__ */
207 #ifndef USER_LABEL_PREFIX
208 /*@constant observer char *USER_LABEL_PREFIX@*/
209 #define USER_LABEL_PREFIX ""
212 /* The string value for __REGISTER_PREFIX__ */
214 #ifndef REGISTER_PREFIX
215 /*@constant observer char *REGISTER_PREFIX@*/
216 #define REGISTER_PREFIX ""
219 /* table to tell if char can be part of a C identifier. */
220 static bool is_idchar[256];
221 /* table to tell if char can be first char of a c identifier. */
222 static bool is_idstart[256];
223 /* table to tell if c is horizontal space. */
224 static bool is_hor_space[256];
225 /* table to tell if c is horizontal or vertical space. */
226 static bool is_space[256];
228 static /*@exposed@*/ /*@null@*/ cppBuffer *
229 cppReader_getBuffer (/*@special@*/ cppReader *p_pfile)
230 /*@uses p_pfile->buffer@*/
231 /*@modifies nothing@*/ ;
234 # define SKIP_WHITE_SPACE(p) do { /*@access cstring@*/ while (is_hor_space[(int) *(p)]) { (p)++; } } /*@noaccess cstring@*/ while (0)
237 # define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*(p)]) { (p)++; } } while (0)
239 static int cpp_peekN (cppReader *p_pfile, int p_n) /*@*/ ;
241 /*@function static int cppBuffer_get (sef cppBuffer *p_b) modifies *p_b ; @*/
242 # define cppBuffer_get(BUFFER) \
243 ((BUFFER)->cur < (BUFFER)->rlimit ? *(BUFFER)->cur++ : EOF)
245 /*@function static int cppBuffer_reachedEOF (sef cppBuffer *p_b) modifies nothing; @*/
246 # define cppBuffer_reachedEOF(b) \
247 ((b)->cur < (b)->rlimit ? FALSE : TRUE)
249 /* Append string STR (of length N) to PFILE's output buffer. Make space. */
250 /*@function static void cppReader_puts (sef cppReader *p_file, char *p_str, sef size_t p_n)
251 modifies *p_file; @*/
252 # define cppReader_puts(PFILE, STR, N) \
253 cpplib_reserve(PFILE, N), cppReader_putStrN (PFILE, STR,N)
255 /* Append character CH to PFILE's output buffer. Assume sufficient space. */
257 /*@function static void cppReader_putCharQ (cppReader *p_file, char p_ch)
258 modifies *p_file; @*/
259 # define cppReader_putCharQ(PFILE, CH) (*(PFILE)->limit++ = (CH))
261 static void cppReader_putCharQ (cppReader *p_file, char p_ch)
263 fprintf (stderr, "put char: %c\n", p_ch);
264 (*(p_file)->limit++ = (p_ch));
267 /* Append character CH to PFILE's output buffer. Make space if need be. */
269 /*@function static void cppReader_putChar (sef cppReader *p_file, char p_ch)
270 modifies *p_file; @*/
271 #define cppReader_putChar(PFILE, CH) (cpplib_reserve (PFILE, (size_t) 1), cppReader_putCharQ (PFILE, CH))
273 /* Make sure PFILE->limit is followed by '\0'. */
274 /*@function static void cppReader_nullTerminateQ (cppReader *p_file)
275 modifies *p_file; @*/
277 #define cppReader_nullTerminateQ(PFILE) (*(PFILE)->limit = 0)
279 /*@function static void cppReader_nullTerminate (sef cppReader *p_file)
280 modifies *p_file; @*/
281 # define cppReader_nullTerminate(PFILE) \
282 (cpplib_reserve (PFILE, (size_t) 1), *(PFILE)->limit = 0)
284 /*@function static void cppReader_adjustWritten (cppReader *p_file, size_t)
285 modifies *p_file; @*/
286 #define cppReader_adjustWritten(PFILE,DELTA) ((PFILE)->limit += (DELTA))
288 /*@function static bool cppReader_isC89 (cppReader *) modifies nothing; @*/
289 #define cppReader_isC89(PFILE) (CPPOPTIONS(PFILE)->c89)
291 /*@function static observer char *cppReader_wcharType (cppReader *)
292 modifies nothing; @*/
294 # define cppReader_wcharType(PFILE) \
295 (CPPOPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
297 static void cppBuffer_forward (cppBuffer *p_buf, int p_n) /*@modifies *p_buf@*/ ;
299 /*@function static void cppReader_forward (cppReader *p_pfile, int) modifies *p_pfile; @*/
300 # define cppReader_forward(pfile, N) \
301 (cppBuffer_forward (cppReader_getBufferSafe (pfile), (N)))
303 /*@function static int cppReader_getC (cppReader *p_pfile) modifies *p_pfile; @*/
304 # define cppReader_getC(pfile) (cppBuffer_get (cppReader_getBufferSafe (pfile)))
306 /*@function static int cppReader_reachedEOF (sef cppReader *p_pfile) modifies *p_pfile; @*/
307 # define cppReader_reachedEOF(pfile) (cppBuffer_reachedEOF (cppReader_getBufferSafe (pfile)))
309 /*@function static int cppReader_peekC (cppReader *) modifies nothing;@*/
310 # define cppReader_peekC(pfile) (cpplib_bufPeek (cppReader_getBufferSafe (pfile)))
312 /* Move all backslash-newline pairs out of embarrassing places.
313 Exchange all such pairs following BP
314 with any potentially-embarrassing characters that follow them.
315 Potentially-embarrassing characters are / and *
316 (because a backslash-newline inside a comment delimiter
317 would cause it not to be recognized). */
320 # define NEWLINE_FIX \
321 do { while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n') { cppReader_forward (pfile, 2); } } while(FALSE)
323 /* Same, but assume we've already read the potential '\\' into C. */
325 # define NEWLINE_FIX1(C) do { \
326 while ((C) == '\\' && cppReader_peekC (pfile) == '\n') { cppReader_forward (pfile, 1); (C) = cppReader_getC (pfile); }\
329 static void parseSetMark (/*@out@*/ struct parse_marker *,
331 static void parseClearMark (struct parse_marker *);
332 static void parseGotoMark (struct parse_marker *, cppReader *);
333 static void parseMoveMark (struct parse_marker *, cppReader *);
335 /* If we have a huge buffer, may need to cache more recent counts */
336 static /*@exposed@*/ char *cppLineBase (/*@sef@*/ cppBuffer *);
338 static /*@exposed@*/ /*@null@*/ cppBuffer *
339 cppReader_pushBuffer (cppReader *p_pfile,
340 /*@owned@*/ /*@null@*/ char *, size_t)
341 /*@modifies p_pfile@*/ ;
343 static void cppReader_appendIncludeChain
345 /*@keep@*/ struct file_name_list *p_first,
346 /*@dependent@*/ struct file_name_list *p_last);
348 static void cppReader_macroCleanup (cppBuffer *p_pbuf, cppReader *p_pfile);
349 static enum cpp_token cppReader_nullUnderflow (/*@unused@*/ cppReader *p_pfile);
351 static void cppReader_nullCleanup (/*@unused@*/ cppBuffer *p_pbuf,
352 /*@unused@*/ cppReader *p_pfile);
354 static void cppReader_fileCleanup (cppBuffer *p_pbuf,
355 /*@unused@*/ cppReader *p_pfile);
357 static int cppReader_handleDirective (cppReader *p_pfile);
359 static void cppReader_scanBuffer (cppReader *p_pfile);
361 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
366 ** WIN32 (at least the VC++ include files) does not define mode_t.
369 /*@-incondefs@*/ /*@-czechtypes@*/
370 typedef unsigned int mode_t;
371 /*@=incondefs@*/ /*@=czechtypes@*/
376 static int file_size_and_mode (int p_fd, /*@out@*/ mode_t *p_mode_pointer,
377 /*@out@*/ size_t *p_size_pointer);
378 static int safe_read (int p_desc, /*@out@*/ char *p_ptr, int p_len);
382 ** cppBuffer_isMacro is true if the buffer contains macro expansion.
383 ** (Note that it is false while we're expanding marco *arguments*.)
386 static bool cppBuffer_isMacro (/*@null@*/ cppBuffer *) /*@*/ ;
388 static void path_include (cppReader *p_pfile, char *p_path)
389 /*@modifies p_pfile@*/ ;
391 static void initialize_builtins (cppReader *p_pfile)
392 /*@modifies p_pfile@*/ ;
394 static void initialize_char_syntax (struct cppOptions *p_opts) ;
396 static int /*@alt void@*/ finclude (cppReader *p_pfile, int p_f,
398 bool p_system_header_p,
399 /*@dependent@*/ /*@null@*/ struct file_name_list *p_dirptr);
401 static void validate_else (cppReader *p_pfile, cstring p_directive);
403 static void conditional_skip (cppReader *p_pfile, int p_skip,
404 enum node_type p_type,
405 /*@dependent@*/ /*@null@*/ char *p_control_macro);
407 static HOST_WIDE_INT eval_if_expression (cppReader *p_pfile,
411 static void skip_if_group (cppReader *p_pfile, int p_any);
413 static bool comp_def_part (bool p_first, char *p_beg1, int p_len1,
414 char *p_beg2, int p_len2, bool p_last);
417 extern void fancy_abort ();
420 static bool redundant_include_p (cppReader *p_pfile, /*@null@*/ cstring p_name);
421 static bool is_system_include (cppReader *p_pfile, cstring p_filename);
423 static /*@observer@*/ /*@null@*/ struct file_name_map *
424 read_name_map (cppReader *p_pfile, cstring p_dirname);
426 static cstring read_filename_string (int p_ch, /*:open:*/ FILE *p_f);
428 static int open_include_file (cppReader *p_pfile,
429 /*@owned@*/ cstring p_fname,
430 /*@null@*/ struct file_name_list *p_searchptr);
432 static void push_macro_expansion (cppReader *,
433 /*@owned@*/ char *, size_t,
434 /*@dependent@*/ hashNode);
436 /* Last arg to output_line_command. */
437 enum file_change_code {
438 same_file, enter_file, leave_file
441 /* `struct directive' defines one #-directive, including how to handle it. */
444 int length; /* Length of name */
445 /*@null@*/ int (*func)(); /* Function to handle directive */
446 /*@observer@*/ cstring name; /* Name of directive */
447 enum node_type type; /* Code which describes which directive. */
448 bool command_reads_line; /* One if rest of line is read by func. */
449 bool traditional_comments; /* Nonzero: keep comments if -traditional. */
450 bool pass_thru; /* Copy preprocessed directive to output file.*/
453 /* These functions are declared to return int instead of void since they
454 are going to be placed in a table and some old compilers have trouble with
455 pointers to functions returning void. */
457 static int do_define (cppReader *, /*@null@*/ struct directive *,
458 /*@exposed@*/ char *, char *);
459 static int do_defineAux (cppReader *, /*@null@*/ struct directive *,
460 /*@exposed@*/ char *, char *, bool);
462 static int do_line (cppReader *, /*@null@*/ struct directive *);
463 static int do_include (cppReader *, struct directive *, char *, char *);
464 static int do_undef (cppReader *, struct directive *, char *, char *);
465 static int do_error (cppReader *, struct directive *, char *, char *);
466 static int do_pragma (cppReader *, struct directive *, char *, char *);
467 static int do_ident (cppReader *, struct directive *, char *, char *);
468 static int do_if (cppReader *, struct directive *, char *, char *);
469 static int do_xifdef (cppReader *, struct directive *, char *, char *);
470 static int do_else (cppReader *, struct directive *, char *, char *);
471 static int do_elif (cppReader *, struct directive *, char *, char *);
472 static int do_endif (cppReader *, struct directive *, char *, char *);
473 static int do_warning (cppReader *, struct directive *, char *, char *);
475 /* If a buffer's dir field is SELF_DIR_DUMMY, it means the file was found
476 via the same directory as the file that #included it. */
478 /*@constant observer struct file_name_list *SELF_DIR_DUMMY@*/
479 #define SELF_DIR_DUMMY ((struct file_name_list *) (~0))
481 /* #include "file" looks in source file dir, then stack. */
482 /* #include <file> just looks in the stack. */
483 /* -I directories are added to the end, then the defaults are added. */
487 static struct default_include {
488 /*@dependent@*/ /*@observer@*/ cstring fname; /* The name of the directory. */
489 int cplusplus; /* Only look here if we're compiling C++. */
490 int cxx_aware; /* Includes in this directory don't need to
491 be wrapped in extern "C" when compiling
493 } include_defaults_array[]
495 /* This is the dir for fixincludes. Put it just before
496 the files that we fix. */
497 { GCC_INCLUDE_DIR, 0, 0 },
498 { GCC_INCLUDE_DIR2, 0, 0 },
499 { cstring_undefined, 0, 0 }
502 /*@noaccess cstring@*/
504 /* Here is the actual list of #-directives, most-often-used first.
505 The initialize_builtins function assumes #define is the very first. */
509 static struct directive directive_table[] = {
510 { 6, do_define, "define", T_DEFINE, FALSE, TRUE, FALSE },
511 { 5, do_xifdef, "ifdef", T_IFDEF, TRUE, FALSE, FALSE },
512 { 6, do_xifdef, "ifndef", T_IFNDEF, TRUE, FALSE, FALSE },
513 { 7, do_include, "include", T_INCLUDE, TRUE, FALSE, FALSE },
514 { 5, do_endif, "endif", T_ENDIF, TRUE, FALSE, FALSE },
515 { 4, do_else, "else", T_ELSE, TRUE, FALSE, FALSE },
516 { 2, do_if, "if", T_IF, TRUE, FALSE, FALSE },
517 { 4, do_elif, "elif", T_ELIF, TRUE, FALSE, FALSE },
518 { 5, do_undef, "undef", T_UNDEF, FALSE, FALSE, FALSE },
519 { 5, do_error, "error", T_ERROR, FALSE, FALSE, FALSE },
520 { 7, do_warning, "warning", T_WARNING, FALSE, FALSE, FALSE },
521 { 6, do_pragma, "pragma", T_PRAGMA, FALSE, FALSE, TRUE},
522 { 4, do_line, "line", T_LINE, TRUE, FALSE, FALSE },
523 { 5, do_ident, "ident", T_IDENT, TRUE, FALSE, TRUE },
524 /* { 8, do_unassert, "unassert", T_UNASSERT, TRUE, FALSE, FALSE }, */
525 { -1, NULL, "", T_UNUSED, FALSE, FALSE, FALSE },
527 /*@noaccess cstring@*/
529 static cstring searchPath_unparse (struct file_name_list *search_start)
531 cstring res = cstring_newEmpty ();
532 struct file_name_list *searchptr = NULL;
534 for (searchptr = search_start; searchptr != NULL;
535 searchptr = searchptr->next)
537 if (!cstring_isEmpty (searchptr->fname)) {
538 res = cstring_concatFree1 (res, searchptr->fname);
539 if (searchptr->next != NULL) {
540 res = cstring_appendChar (res, ';');
550 initialize_char_syntax (struct cppOptions *opts)
555 * Set up is_idchar and is_idstart tables. These should be
556 * faster than saying (is_alpha (c) || c == '_'), etc.
557 * Set up these things before calling any routines tthat
561 for (i = 'a'; i <= 'z'; i++) {
562 is_idchar[i - 'a' + 'A'] = TRUE;
563 is_idchar[(int) i] = TRUE;
564 is_idstart[i - 'a' + 'A'] = TRUE;
565 is_idstart[(int) i] = TRUE;
568 for (i = '0'; i <= '9'; i++)
570 is_idchar[(int) i] = TRUE;
573 is_idchar['_'] = TRUE;
574 is_idstart['_'] = TRUE;
575 is_idchar['$'] = opts->dollars_in_ident;
576 is_idstart['$'] = opts->dollars_in_ident;
578 /* horizontal space table */
579 is_hor_space[' '] = TRUE;
580 is_hor_space['\t'] = TRUE;
581 is_hor_space['\v'] = TRUE;
582 is_hor_space['\f'] = TRUE;
583 is_hor_space['\r'] = TRUE;
585 is_space[' '] = TRUE;
586 is_space['\t'] = TRUE;
587 is_space['\v'] = TRUE;
588 is_space['\f'] = TRUE;
589 is_space['\n'] = TRUE;
590 is_space['\r'] = TRUE;
593 bool isIdentifierChar (char c)
595 return is_idchar[(int) c];
598 /* Place into P_PFILE a quoted string representing the string SRC.
599 Caller must reserve enough space in pfile->token_buffer. */
602 quote_string (cppReader *pfile, char *src)
606 cppReader_putCharQ (pfile, '\"');
609 switch ((c = *src++))
613 cppReader_putCharQ (pfile, c);
616 sprintf (cpplib_getPWritten (pfile), "\\%03o",
618 cppReader_adjustWritten (pfile, (size_t) 4);
620 /*@switchbreak@*/ break;
624 cppReader_putCharQ (pfile, '\\');
625 cppReader_putCharQ (pfile, c);
626 /*@switchbreak@*/ break;
629 cppReader_putCharQ (pfile, '\"');
630 cppReader_nullTerminateQ (pfile);
636 /* Re-allocates PFILE->token_buffer so it will hold at least N more chars. */
639 cppReader_growBuffer (cppReader *pfile, size_t n)
641 size_t old_written = cpplib_getWritten (pfile);
642 pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
643 pfile->token_buffer = (char *)
644 drealloc (pfile->token_buffer, pfile->token_buffer_size);
645 cppReader_setWritten (pfile, old_written);
649 * process a given definition string, for initialization
650 * If STR is just an identifier, define it with value 1.
651 * If STR has anything after the identifier, then it should
652 * be identifier=definition.
656 cppReader_define (cppReader *pfile, char *str)
661 DPRINTF (("Cpp reader define: %s", str));
663 if (!is_idstart[(int) *p])
665 DPRINTF (("ERROR 1"));
666 cppReader_error (pfile,
667 message ("Malformed option `-D%s'",
668 cstring_fromChars (str)));
675 DPRINTF (("Here 2"));
677 while (is_idchar[(int) *p])
684 while (*p != ')' && *p != '\0') {
693 message ("Malformed option: -D%s (no closing parenthesis)",
694 cstring_fromChars (str)));
698 DPRINTF (("Here 2"));
702 buf = (char *) dmalloc (size_fromInt (p - str + 4));
703 strcpy ((char *) buf, str);
704 strcat ((char *) buf, " 1");
708 DPRINTF (("ERROR 2"));
709 cppReader_error (pfile,
710 message ("Malformed option: -D%s (expected '=', found '%c')",
711 cstring_fromChars (str),
718 /* Copy the entire option so we can modify it. */
719 DPRINTF (("Copying..."));
720 buf = (char *) dmalloc (2 * strlen (str) + 1);
721 strncpy (buf, str, size_fromInt (p - str));
723 /* Change the = to a space. */
725 /* Scan for any backslash-newline and remove it. */
731 if (*p == '\\' && p[1] == '\n')
737 DPRINTF (("Here we are..."));
741 llassert (buf != NULL);
742 DPRINTF (("Do define: %s / %ld", buf, size_toLong (strlen (buf))));
743 (void) do_define (pfile, NULL, buf, buf + strlen (buf));
747 /* Append a chain of `struct file_name_list's
748 to the end of the main include chain.
749 FIRST is gthe beginning of the chain to append, and LAST is the end. */
752 cppReader_appendIncludeChain (cppReader *pfile,
753 struct file_name_list *first,
754 struct file_name_list *last)
756 struct cppOptions *opts = CPPOPTIONS (pfile);
757 struct file_name_list *dir;
759 if (first == NULL || last == NULL)
764 if (opts->include == 0)
766 opts->include = first;
770 llassert (opts->last_include->next == NULL);
771 opts->last_include->next = first;
774 if (opts->first_bracket_include == 0)
776 opts->first_bracket_include = first;
778 for (dir = first; ; dir = dir->next) {
779 size_t len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
781 if (len > pfile->max_include_len)
783 pfile->max_include_len = len;
793 llassert (last->next == NULL);
794 /* last->next = NULL; */
795 opts->last_include = last;
799 static /*@unused@*/ void
800 cppReader_showIncludeChain (cppReader *pfile)
802 struct file_name_list *dirs = CPPOPTIONS (pfile)->include;
808 fprintf (stderr, "*%s*:", cstring_toCharsSafe (dirs->fname));
812 fprintf (stderr, "\n");
816 fprintf (stderr, "No includes\n");
822 cppReader_getIncludePath ()
824 cppReader *pfile = &g_cppState;
825 struct file_name_list *dirs = CPPOPTIONS (pfile)->include;
826 cstring res = cstring_undefined;
832 res = message ("%q%c%s", res, PATH_SEPARATOR, dirs->fname);
838 res = cstring_makeLiteral ("<no include path>");
845 cppReader_addIncludeChain (cppReader *pfile, /*@only@*/ struct file_name_list *dir)
847 struct cppOptions *opts = CPPOPTIONS (pfile);
854 if (opts->include == 0)
860 llassert (opts->last_include->next == NULL);
861 opts->last_include->next = dir;
864 if (opts->first_bracket_include == 0)
866 size_t len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
867 opts->first_bracket_include = dir;
869 if (len > pfile->max_include_len)
871 pfile->max_include_len = len;
876 opts->last_include = dir;
877 /* cppReader_showIncludeChain (pfile); */
880 /* Given a colon-separated list of file names PATH,
881 add all the names to the search path for include files. */
884 path_include (cppReader *pfile, char *path)
891 /* if we have a posix path list, convert to win32 path list */
892 win32temp = (char *) dmalloc /*@i4@*/
893 (cygwin32_posix_to_win32_path_list_buf_size (path));
894 cygwin32_posix_to_win32_path_list (path, win32temp);
904 struct file_name_list *dirtmp;
906 /* Find the end of this name. */
907 while (*q != '\0' && *q != PATH_SEPARATOR)
914 /* An empty name in the path stands for the current directory. */
915 name = (char *) dmalloc ((size_t) 2);
921 /* Otherwise use the directory that is named. */
922 name = (char *) dmalloc (size_fromInt (q - p + 1));
923 memcpy (name, p, size_fromInt (q - p));
927 dirtmp = (struct file_name_list *) dmalloc (sizeof (*dirtmp));
928 dirtmp->next = 0; /* New one goes on the end */
929 dirtmp->control_macro = 0;
930 dirtmp->c_system_include_path = 0;
931 dirtmp->fname = cstring_fromChars (name);
932 dirtmp->got_name_map = 0;
933 cppReader_addIncludeChain (pfile, dirtmp);
935 /* Advance past this name. */
939 /* Skip the colon. */
945 cppOptions_init (cppOptions *opts)
947 memset ((char *) opts, 0, sizeof *opts);
950 opts->in_fname = NULL;
951 opts->out_fname = NULL;
953 /* Initialize is_idchar to allow $. */
954 opts->dollars_in_ident = TRUE;
956 opts->no_line_commands = 0;
957 opts->no_trigraphs = TRUE;
958 opts->put_out_comments = 1;
959 opts->print_include_names = 0;
960 opts->dump_macros = DUMP_DEFINITIONS; /* DUMP_NONE; */
964 opts->cplusplus_comments = 1;
969 opts->pedantic_errors = 0;
970 opts->warn_comments = 0;
971 opts->warnings_are_errors = 0;
973 /* Added 2003-07-10: */
974 opts->traditional = FALSE;
976 initialize_char_syntax (opts);
980 cppReader_nullUnderflow (/*@unused@*/ cppReader *pfile)
986 cppReader_nullCleanup (/*@unused@*/ cppBuffer *pbuf,
987 /*@unused@*/ cppReader *pfile)
993 cppReader_macroCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
995 hashNode macro = pbuf->hnode;
997 if (macro->type == T_DISABLED)
999 macro->type = T_MACRO;
1002 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
1010 cppReader_fileCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
1012 if (pbuf->buf != NULL)
1019 /* Assuming we have read '/'.
1020 If this is the start of a comment (followed by '*' or '/'),
1021 skip to the end of the comment, and return ' '.
1022 Return EOF if we reached the end of file before the end of the comment.
1023 If not the start of a comment, return '/'. */
1026 skip_comment (cppReader *pfile, /*@null@*/ long *linep)
1030 llassert (pfile->buffer != NULL);
1031 llassert (pfile->buffer->cur != NULL);
1033 while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n')
1040 cppReader_forward (pfile, 2);
1043 if (cppReader_peekC (pfile) == '*')
1045 cppReader_forward (pfile, 1);
1050 c = cppReader_getC (pfile);
1057 while (c == (int) '\\' && cppReader_peekC (pfile) == (int) '\n')
1064 cppReader_forward (pfile, 1), c = cppReader_getC (pfile);
1067 if (prev_c == (int) '*' && c == (int) '/')
1072 if (c == (int) '\n' && (linep != NULL))
1078 else if (cppReader_peekC (pfile) == '/'
1079 && CPPOPTIONS (pfile)->cplusplus_comments)
1082 (void) cppoptgenerror
1083 (FLG_SLASHSLASHCOMMENT,
1084 message ("C++ style // comment"
1088 cppReader_forward (pfile, 1);
1092 c = cppReader_getC (pfile);
1096 /* Allow hash comment to be terminated by EOF. */
1100 while (c == (int) '\\' && cppReader_peekC (pfile) == '\n')
1102 cppReader_forward (pfile, 1);
1103 c = cppReader_getC (pfile);
1111 if (c == (int) '\n')
1113 /* Don't consider final '\n' to be part of comment. */
1114 cppReader_forward (pfile, -1);
1125 /* Skip whitespace \-newline and comments. Does not macro-expand. */
1127 cppSkipHspace (cppReader *pfile)
1135 llassert (pfile->buffer != NULL);
1137 c = cppReader_peekC (pfile);
1141 return 0; /* FIXME */
1144 if (is_hor_space[c])
1146 if ((c == '\f' || c == '\v') && cppReader_isPedantic (pfile))
1147 cppReader_pedwarn (pfile,
1148 message ("%s in preprocessing directive",
1150 ? cstring_makeLiteralTemp ("formfeed")
1151 : cstring_makeLiteralTemp ("vertical tab")));
1154 cppReader_forward (pfile, 1);
1158 cppReader_forward (pfile, 1);
1159 c = skip_comment (pfile, NULL);
1163 cppReader_forward (pfile, -1);
1166 if (c == EOF || c == '/')
1171 else if (c == '\\' && cpp_peekN (pfile, 1) == '\n')
1173 cppReader_forward (pfile, 2);
1175 else if (c == '@' && CPPBUFFER (pfile)->has_escapes
1176 && is_hor_space [cpp_peekN (pfile, 1)])
1178 cppReader_forward (pfile, 2);
1187 /* Read the rest of the current line.
1188 The line is appended to PFILE's output buffer. */
1191 copy_rest_of_line (cppReader *pfile)
1193 struct cppOptions *opts = CPPOPTIONS (pfile);
1200 llassert (pfile->buffer != NULL);
1202 c = cppReader_getC (pfile);
1210 ** Patch from Brian St. Pierre for handling MS-DOS files.
1213 DPRINTF (("Reading directive: %d", (int) c));
1215 if (cppReader_peekC (pfile) == '\n'
1216 || cppReader_peekC (pfile) == '\r')
1218 DPRINTF (("Reading directive..."));
1219 if (cppReader_peekC (pfile) == '\r')
1221 DPRINTF (("Reading directive..."));
1222 cppReader_forward (pfile, 1);
1225 DPRINTF (("Reading directive..."));
1226 cppReader_forward (pfile, 1);
1230 DPRINTF (("Falling..."));
1231 /*@fallthrough@*/ case '\'': case '\"':
1232 goto scan_directive_token;
1235 nextc = cppReader_peekC (pfile);
1238 ** was (opts->cplusplus_comments && nextc == '*')
1243 || (opts->cplusplus_comments && nextc == '/'))
1245 goto scan_directive_token;
1247 /*@switchbreak@*/ break;
1250 if (cppReader_isPedantic (pfile))
1251 cppReader_pedwarn (pfile,
1252 message ("%s in preprocessing directive",
1254 ? cstring_makeLiteralTemp ("formfeed")
1255 : cstring_makeLiteralTemp ("vertical tab")));
1256 /*@switchbreak@*/ break;
1259 cppReader_forward (pfile, -1);
1261 scan_directive_token:
1262 cppReader_forward (pfile, -1);
1263 (void) cpplib_getToken (pfile);
1266 cppReader_putChar (pfile, c);
1269 cppReader_nullTerminate (pfile);
1273 cppReader_skipRestOfLine (cppReader *pfile)
1275 size_t old = cpplib_getWritten (pfile);
1276 copy_rest_of_line (pfile);
1277 cppReader_setWritten (pfile, old);
1280 /* Handle a possible # directive.
1281 '#' has already been read. */
1284 cppReader_handleDirective (cppReader *pfile)
1287 struct directive *kt = NULL;
1289 size_t after_ident = 0;
1291 char *line_end = NULL;
1292 size_t old_written = cpplib_getWritten (pfile);
1293 int nspaces = cppSkipHspace (pfile);
1295 c = cppReader_peekC (pfile);
1297 if (c >= '0' && c <= '9')
1299 /* Handle # followed by a line number. */
1300 if (cppReader_isPedantic (pfile))
1302 cppReader_pedwarnLit
1304 cstring_makeLiteralTemp ("`#' followed by integer"));
1307 (void) do_line (pfile, NULL);
1308 goto done_a_directive;
1312 /* Now find the directive name. */
1314 cppReader_putChar (pfile, '#');
1316 parse_name (pfile, cppReader_getC (pfile));
1318 llassert (pfile->token_buffer != NULL);
1319 ident = pfile->token_buffer + old_written + 1;
1321 ident_length = cpplib_getPWritten (pfile) - ident;
1323 if (ident_length == 0 && cppReader_peekC (pfile) == '\n')
1325 /* A line of just `#' becomes blank. */
1329 for (kt = directive_table; ; kt++)
1331 if (kt->length <= 0)
1333 return 0; /* goto not_a_directive; */
1336 if (kt->length == ident_length
1337 && (cstring_equalPrefix (kt->name, cstring_fromChars (ident))))
1343 if (kt->command_reads_line)
1349 /* Nonzero means do not delete comments within the directive.
1350 #define needs this when -traditional. */
1351 bool comments = 1; /*cppReader_isTraditional (pfile) && kt->traditional_comments; */
1352 int save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
1353 CPPOPTIONS (pfile)->put_out_comments = comments;
1354 after_ident = cpplib_getWritten (pfile);
1355 copy_rest_of_line (pfile);
1356 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
1360 /* For #pragma and #define, we may want to pass through the directive.
1361 Other directives may create output, but we don't want the directive
1362 itself out, so we pop it now. For example #include may write a #line
1363 command (see comment in do_include), and conditionals may emit
1364 #failed ... #endfailed stuff. But note that popping the buffer
1365 means the parameters to kt->func may point after pfile->limit
1366 so these parameters are invalid as soon as something gets appended
1367 to the token_buffer. */
1369 line_end = cpplib_getPWritten (pfile);
1372 if (!kt->pass_thru && kt->type != T_DEFINE)
1374 cppReader_setWritten (pfile, old_written);
1377 llassert (pfile->token_buffer != NULL);
1379 /* was kt->pass_thru || */
1381 if (kt->type == T_DEFINE
1382 && cpp_shouldCheckMacro (pfile, pfile->token_buffer + old_written))
1384 char *p = pfile->token_buffer + old_written;
1387 ** Still need to record value for preprocessing, so
1388 ** #ifdef's, etc. using the value behave correctly.
1391 (void) do_defineAux (pfile, kt,
1392 pfile->token_buffer + after_ident,
1401 SKIP_WHITE_SPACE (p);
1403 llassert (*p == 'd');
1406 llassert (*p == 'e');
1409 llassert (*p == 'f');
1412 llassert (*p == 'i');
1415 llassert (*p == 'n');
1418 llassert (*p == 'e');
1421 ** This is way-bogus. We use the last char to record the number of
1422 ** spaces. Its too hard to get them back into the input stream.
1425 if (nspaces > 9) nspaces = 9;
1427 *p++ = '0' + nspaces;
1429 return 0; /* not_a_directive */
1431 else if (kt->pass_thru)
1433 /* Just leave the entire #define in the output stack. */
1434 return 0; /* not_a_directive */
1437 else if (kt->type == T_DEFINE
1438 && CPPOPTIONS (pfile)->dump_macros == DUMP_NAMES)
1440 char *p = pfile->token_buffer + old_written + 7; /* Skip "#define". */
1441 SKIP_WHITE_SPACE (p);
1443 while (is_idchar[(int) *p])
1449 cppReader_putChar (pfile, '\n');
1451 else if (kt->type == T_DEFINE)
1453 cppReader_setWritten (pfile, old_written);
1464 llassert (kt->func != NULL);
1465 (void) (kt->func) (pfile, kt, pfile->token_buffer + after_ident, line_end);
1470 /* Pass a directive through to the output file.
1471 BUF points to the contents of the directive, as a contiguous string.
1472 LIMIT points to the first character past the end of the directive.
1473 KEYWORD is the keyword-table entry for the directive. */
1476 pass_thru_directive (char *buf, char *limit,
1478 struct directive *keyword)
1480 int keyword_length = keyword->length;
1482 cpplib_reserve (pfile,
1483 size_fromInt (2 + keyword_length + (limit - buf)));
1484 cppReader_putCharQ (pfile, '#');
1485 /*@-observertrans@*/
1486 cppReader_putStrN (pfile, cstring_toCharsSafe (keyword->name),
1487 size_fromInt (keyword_length));
1488 /*:=observertrans@*/
1490 if (limit != buf && buf[0] != ' ')
1492 /* Was a bug, since reserve only used 1 + ... */
1493 cppReader_putCharQ (pfile, ' ');
1496 cppReader_putStrN (pfile, buf, size_fromInt (limit - buf));
1499 /* Read a replacement list for a macro with parameters.
1500 Build the DEFINITION structure.
1501 Reads characters of text starting at BUF until END.
1502 ARGLIST specifies the formal parameters to look for
1503 in the text of the definition; NARGS is the number of args
1504 in that list, or -1 for a macro name that wants no argument list.
1505 MACRONAME is the macro name itself (so we can avoid recursive expansion)
1506 and NAMELEN is its length in characters.
1508 Note that comments, backslash-newlines, and leading white space
1509 have already been deleted from the argument. */
1512 collect_expansion (cppReader *pfile, char *buf, char *limit,
1513 int nargs, /*@null@*/ struct arglist *arglist)
1516 char *p, *lastp, *exp_p;
1517 struct reflist *endpat = NULL;
1518 /* Pointer to first nonspace after last ## seen. */
1520 /* Pointer to first nonspace after last single-# seen. */
1521 char *stringify = 0;
1523 char expected_delimiter = '\0';
1526 /* Scan thru the replacement list, ignoring comments and quoted
1527 strings, picking up on the macro calls. It does a linear search
1528 thru the arg list on every potential symbol. Profiling might say
1529 that something smarter should happen. */
1534 /* Find the beginning of the trailing whitespace. */
1537 while (p < limit && is_space[(int) limit[-1]])
1542 /* Allocate space for the text in the macro definition.
1543 Leading and trailing whitespace chars need 2 bytes each.
1544 Each other input char may or may not need 1 byte,
1545 so this is an upper bound. The extra 5 are for invented
1546 leading and trailing newline-marker and final null. */
1547 maxsize = (sizeof (*defn) + (limit - p) + 5);
1549 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1558 defn = (DEFINITION *) dmalloc (maxsize);
1559 defn->noExpand = FALSE;
1561 defn->pattern = NULL;
1562 defn->nargs = nargs;
1563 defn->predefined = NULL;
1565 exp_p = defn->expansion = (char *) defn + sizeof (*defn);
1566 *defn->expansion = '\0'; /* convince splint it is initialized */
1569 defn->rest_args = NULL;
1570 defn->args.argnames = NULL;
1576 /* Add one initial space escape-marker to prevent accidental
1577 token-pasting (often removed by cpplib_macroExpand). */
1581 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1582 cppReader_errorLit (pfile,
1583 cstring_makeLiteralTemp ("`##' at start of macro definition"));
1587 /* Process the main body of the definition. */
1589 int skipped_arg = 0;
1590 register char c = *p++;
1594 if (!cppReader_isTraditional (pfile)) {
1598 if (expected_delimiter != '\0')
1600 if (c == expected_delimiter)
1601 expected_delimiter = '\0';
1605 expected_delimiter = c;
1607 /*@switchbreak@*/ break;
1610 if (p < limit && (expected_delimiter != '\0'))
1612 /* In a string, backslash goes through
1613 and makes next char ordinary. */
1616 /*@switchbreak@*/ break;
1619 /* An '@' in a string or character constant stands for itself,
1620 and does not need to be escaped. */
1621 if (expected_delimiter == '\0')
1626 /*@switchbreak@*/ break;
1629 /* # is ordinary inside a string. */
1630 if (expected_delimiter != '\0')
1632 /*@switchbreak@*/ break;
1635 if (p < limit && *p == '#') {
1636 /* ##: concatenate preceding and following tokens. */
1637 /* Take out the first #, discard preceding whitespace. */
1641 while (exp_p > lastp && is_hor_space[(int) exp_p[-1]])
1647 /* Skip the second #. */
1649 /* Discard following whitespace. */
1650 SKIP_WHITE_SPACE (p);
1654 cppReader_errorLit (pfile,
1655 cstring_makeLiteralTemp ("`##' at end of macro definition"));
1657 } else if (nargs >= 0) {
1658 /* Single #: stringify following argument ref.
1659 Don't leave the # in the expansion. */
1661 SKIP_WHITE_SPACE (p);
1662 if (p == limit || ! is_idstart[(int) *p]
1663 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '\"')))
1664 cppReader_errorLit (pfile,
1665 cstring_makeLiteralTemp ("`#' operator is not followed by a macro argument name"));
1672 /*@switchbreak@*/ break;
1675 /* In -traditional mode, recognize arguments inside strings and
1676 and character constants, and ignore special properties of #.
1677 Arguments inside strings are considered "stringified", but no
1678 extra quote marks are supplied. */
1682 if (expected_delimiter != '\0') {
1683 if (c == expected_delimiter)
1684 expected_delimiter = '\0';
1686 expected_delimiter = c;
1687 /*@switchbreak@*/ break;
1690 /* Backslash quotes delimiters and itself, but not macro args. */
1691 if (expected_delimiter != '\0' && p < limit
1692 && (*p == expected_delimiter || *p == '\\')) {
1696 /*@switchbreak@*/ break;
1699 if (expected_delimiter != '\0') /* No comments inside strings. */
1700 /*@switchbreak@*/ break;
1702 /* If we find a comment that wasn't removed by cppReader_handleDirective,
1703 this must be -traditional. So replace the comment with
1707 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
1712 /*@switchbreak@*/ break;
1716 /* Handle the start of a symbol. */
1717 if (is_idchar[(int) c] && nargs > 0) {
1718 char *id_beg = p - 1;
1722 while (p != limit && is_idchar[(int) *p])
1727 id_len = size_fromInt (p - id_beg);
1729 if (is_idstart[(int) c]
1730 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '\"'))) {
1731 register struct arglist *arg;
1733 for (arg = arglist; arg != NULL; arg = arg->next) {
1734 struct reflist *tpat;
1736 if (arg->name[0] == c
1737 && arg->length == id_len
1738 && strncmp (arg->name, id_beg, id_len) == 0) {
1741 if (expected_delimiter && CPPOPTIONS (pfile)->warn_stringify) {
1742 if (cppReader_isTraditional (pfile)) {
1743 cppReader_warning (pfile,
1744 message ("macro argument `%x' is stringified.",
1745 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1747 cppReader_warning (pfile,
1748 message ("macro arg `%x' would be stringified with -traditional.",
1749 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1752 /* If ANSI, don't actually substitute inside a string. */
1753 if (!cppReader_isTraditional (pfile) && expected_delimiter)
1754 /*@innerbreak@*/ break;
1755 /* make a pat node for this arg and append it to the end of
1757 tpat = (struct reflist *) dmalloc (sizeof (*tpat));
1759 tpat->raw_before = (concat == id_beg);
1760 tpat->raw_after = 0;
1761 tpat->rest_args = arg->rest_args;
1762 tpat->stringify = (cppReader_isTraditional (pfile)
1763 ? expected_delimiter != '\0'
1764 : stringify == id_beg);
1768 defn->pattern = tpat;
1772 endpat->next = tpat;
1774 } /*@=branchstate@*/ /* evs 2000 was =branchstate */
1778 tpat->argno = arg->argno;
1779 tpat->nchars = exp_p - lastp;
1783 SKIP_WHITE_SPACE (p1);
1785 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
1787 tpat->raw_after = 1;
1790 lastp = exp_p; /* place to start copying from next time */
1793 /*@innerbreak@*/ break;
1798 /* If this was not a macro arg, copy it into the expansion. */
1799 if (skipped_arg == 0) {
1800 register char *lim1 = p;
1808 if (stringify == id_beg)
1809 cppReader_errorLit (pfile,
1810 cstring_makeLiteralTemp ("`#' operator should be followed by a macro argument name"));
1815 if (!cppReader_isTraditional (pfile) && expected_delimiter == '\0')
1817 /* If ANSI, put in a "@ " marker to prevent token pasting.
1818 But not if "inside a string" (which in ANSI mode
1819 happens only for -D option). */
1826 defn->length = size_fromInt (exp_p - defn->expansion);
1828 /* Crash now if we overrun the allocated size. */
1829 if (defn->length + 1 > maxsize)
1831 llfatalbug (cstring_makeLiteral ("Maximum definition size exceeded."));
1834 return defn; /* Spurious warning here */
1839 ** Gasp...cut-and-pasted from above to deal with pfile (should replace throughout with this...)
1843 collect_expansionLoc (fileloc loc, char *buf, char *limit,
1844 int nargs, /*@null@*/ struct arglist *arglist)
1847 char *p, *lastp, *exp_p;
1848 struct reflist *endpat = NULL;
1849 /* Pointer to first nonspace after last ## seen. */
1851 /* Pointer to first nonspace after last single-# seen. */
1852 char *stringify = 0;
1854 char expected_delimiter = '\0';
1857 /* Scan thru the replacement list, ignoring comments and quoted
1858 strings, picking up on the macro calls. It does a linear search
1859 thru the arg list on every potential symbol. Profiling might say
1860 that something smarter should happen. */
1864 llfatalbug (message ("%q: Limit is less than initial buffer pointer",
1865 fileloc_unparse (loc)));
1868 /* Find the beginning of the trailing whitespace. */
1871 while (p < limit && is_space[(int) limit[-1]])
1876 /* Allocate space for the text in the macro definition.
1877 Leading and trailing whitespace chars need 2 bytes each.
1878 Each other input char may or may not need 1 byte,
1879 so this is an upper bound. The extra 5 are for invented
1880 leading and trailing newline-marker and final null. */
1881 maxsize = (sizeof (*defn) + (limit - p) + 5);
1883 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1892 defn = (DEFINITION *) dmalloc (maxsize);
1893 defn->noExpand = FALSE;
1895 defn->pattern = NULL;
1896 defn->nargs = nargs;
1897 defn->predefined = NULL;
1898 exp_p = defn->expansion = (char *) defn + sizeof (*defn);
1901 defn->rest_args = NULL;
1902 defn->args.argnames = NULL;
1908 /* Add one initial space escape-marker to prevent accidental
1909 token-pasting (often removed by cpplib_macroExpand). */
1913 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1914 voptgenerror (FLG_PREPROC,
1915 cstring_makeLiteral ("Paste marker ## at start of macro definition"),
1920 /* Process the main body of the definition. */
1922 int skipped_arg = 0;
1923 register char c = *p++;
1927 if (TRUE) { /* !cppReader_isTraditional (pfile)) { */
1931 if (expected_delimiter != '\0')
1933 if (c == expected_delimiter)
1934 expected_delimiter = '\0';
1938 expected_delimiter = c;
1940 /*@switchbreak@*/ break;
1943 if (p < limit && (expected_delimiter != '\0'))
1945 /* In a string, backslash goes through
1946 and makes next char ordinary. */
1949 /*@switchbreak@*/ break;
1952 /* An '@' in a string or character constant stands for itself,
1953 and does not need to be escaped. */
1954 if (expected_delimiter == '\0')
1959 /*@switchbreak@*/ break;
1962 /* # is ordinary inside a string. */
1963 if (expected_delimiter != '\0')
1965 /*@switchbreak@*/ break;
1968 if (p < limit && *p == '#') {
1969 /* ##: concatenate preceding and following tokens. */
1970 /* Take out the first #, discard preceding whitespace. */
1974 while (exp_p > lastp && is_hor_space[(int) exp_p[-1]])
1980 /* Skip the second #. */
1982 /* Discard following whitespace. */
1983 SKIP_WHITE_SPACE (p);
1987 voptgenerror (FLG_PREPROC,
1988 cstring_makeLiteral ("`##' at end of macro definition"),
1991 } else if (nargs >= 0) {
1992 /* Single #: stringify following argument ref.
1993 Don't leave the # in the expansion. */
1995 SKIP_WHITE_SPACE (p);
1996 if (p == limit || ! is_idstart[(int) *p]
1997 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '\"')))
2001 cstring_makeLiteral ("`#' operator is not followed by a macro argument name"),
2010 /*@switchbreak@*/ break;
2013 /* In -traditional mode, recognize arguments inside strings and
2014 and character constants, and ignore special properties of #.
2015 Arguments inside strings are considered "stringified", but no
2016 extra quote marks are supplied. */
2020 if (expected_delimiter != '\0') {
2021 if (c == expected_delimiter)
2022 expected_delimiter = '\0';
2024 expected_delimiter = c;
2025 /*@switchbreak@*/ break;
2028 /* Backslash quotes delimiters and itself, but not macro args. */
2029 if (expected_delimiter != '\0' && p < limit
2030 && (*p == expected_delimiter || *p == '\\')) {
2034 /*@switchbreak@*/ break;
2037 if (expected_delimiter != '\0') /* No comments inside strings. */
2038 /*@switchbreak@*/ break;
2040 /* If we find a comment that wasn't removed by cppReader_handleDirective,
2041 this must be -traditional. So replace the comment with
2045 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
2050 /*@switchbreak@*/ break;
2054 /* Handle the start of a symbol. */
2055 if (is_idchar[(int) c] && nargs > 0) {
2056 char *id_beg = p - 1;
2060 while (p != limit && is_idchar[(int) *p])
2065 id_len = size_fromInt (p - id_beg);
2067 if (is_idstart[(int) c]
2068 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '\"'))) {
2069 register struct arglist *arg;
2071 for (arg = arglist; arg != NULL; arg = arg->next) {
2072 struct reflist *tpat;
2074 if (arg->name[0] == c
2075 && arg->length == id_len
2076 && strncmp (arg->name, id_beg, id_len) == 0) {
2079 if (expected_delimiter) { /* && CPPOPTIONS (pfile)->warn_stringify) { */
2080 if (FALSE) { /* cppReader_isTraditional (pfile)) { */
2081 voptgenerror (FLG_PREPROC,
2082 message ("macro argument `%x' is stringified.",
2083 cstring_prefix (cstring_fromChars (arg->name), id_len)),
2087 voptgenerror (FLG_PREPROC,
2088 message ("Macro arg `%x' would be stringified with -traditional.",
2089 cstring_prefix (cstring_fromChars (arg->name), id_len)),
2094 /* If ANSI, don't actually substitute inside a string. */
2095 if (TRUE /* !cppReader_isTraditional (pfile) */ && expected_delimiter)
2096 /*@innerbreak@*/ break;
2097 /* make a pat node for this arg and append it to the end of
2099 tpat = (struct reflist *) dmalloc (sizeof (*tpat));
2101 tpat->raw_before = (concat == id_beg);
2102 tpat->raw_after = 0;
2103 tpat->rest_args = arg->rest_args;
2104 tpat->stringify = (FALSE /* cppReader_isTraditional (pfile) */
2105 ? expected_delimiter != '\0'
2106 : stringify == id_beg);
2110 defn->pattern = tpat;
2114 endpat->next = tpat;
2116 } /*@=branchstate@*/ /* evs 2000 was =branchstate */
2120 tpat->argno = arg->argno;
2121 tpat->nchars = exp_p - lastp;
2125 SKIP_WHITE_SPACE (p1);
2127 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
2129 tpat->raw_after = 1;
2132 lastp = exp_p; /* place to start copying from next time */
2135 /*@innerbreak@*/ break;
2140 /* If this was not a macro arg, copy it into the expansion. */
2141 if (skipped_arg == 0) {
2142 register char *lim1 = p;
2150 if (stringify == id_beg)
2154 cstring_makeLiteral ("# operator should be followed by a macro argument name"),
2161 if (/*!cppReader_isTraditional (pfile) && */ expected_delimiter == '\0')
2163 /* If ANSI, put in a "@ " marker to prevent token pasting.
2164 But not if "inside a string" (which in ANSI mode
2165 happens only for -D option). */
2172 defn->length = size_fromInt (exp_p - defn->expansion);
2174 /* Crash now if we overrun the allocated size. */
2175 if (defn->length + 1 > maxsize)
2177 llfatalbug (cstring_makeLiteral ("Maximum definition size exceeded."));
2180 /*@-compdef@*/ /* defn->expansion defined? */
2186 * special extension string that can be added to the last macro argument to
2187 * allow it to absorb the "rest" of the arguments when expanded. Ex:
2188 * #define wow(a, b...) process (b, a, b)
2189 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
2190 * { wow (one, two); } -> { process (two, one, two); }
2191 * if this "rest_arg" is used with the concat token '##' and if it is not
2192 * supplied then the token attached to with ## will not be outputted. Ex:
2193 * #define wow (a, b...) process (b ## , a, ## b)
2194 * { wow (1, 2); } -> { process (2, 1, 2); }
2195 * { wow (one); } -> { process (one); {
2198 /*@-readonlytrans@*/
2199 static char rest_extension[] = "...";
2200 /*:=readonlytrans@*/
2203 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
2205 /* Create a DEFINITION node from a #define directive. Arguments are
2206 as for do_define. */
2209 static /*@null@*/ macroDef
2210 create_definition (/*@exposed@*/ char *buf, char *limit,
2211 cppReader *pfile, bool predefinition,
2214 char *bp; /* temp ptr into input buffer */
2215 char *symname; /* remember where symbol name starts */
2216 size_t sym_length; /* and how long it is */
2217 int rest_args = 0; /* really int! */
2220 cstring file = (CPPBUFFER (pfile) != NULL)
2221 ? CPPBUFFER (pfile)->nominal_fname : cstring_makeLiteralTemp ("");
2223 int arglengths = 0; /* Accumulate lengths of arg names
2224 plus number of args. */
2228 DPRINTF (("Create definition: %s", buf));
2231 cppBuffer_getLineAndColumn (CPPBUFFER (pfile), &line, &col);
2235 while (is_hor_space[(int) *bp])
2240 symname = bp; /* remember where it starts */
2242 sym_length = cppReader_checkMacroName (pfile, bp, cstring_makeLiteralTemp ("macro"));
2246 /* Lossage will occur if identifiers or control keywords are broken
2247 across lines using backslash. This is not the right place to take
2251 struct arglist *arg_ptrs = NULL;
2254 bp++; /* skip '(' */
2255 SKIP_WHITE_SPACE (bp);
2257 /* Loop over macro argument names. */
2260 struct arglist *temp = (struct arglist *) dmalloc (sizeof (*temp));
2262 temp->next = arg_ptrs;
2263 temp->argno = argno++;
2264 temp->rest_args = 0;
2270 cppReader_pedwarn (pfile,
2271 message ("another parameter follows `%s'",
2272 cstring_fromChars (rest_extension)));
2275 if (!is_idstart[(int) *bp])
2277 cppReader_pedwarnLit (pfile,
2278 cstring_makeLiteralTemp ("Invalid character in macro parameter name"));
2281 /* Find the end of the arg name. */
2282 while (is_idchar[(int) *bp])
2285 /* do we have a "special" rest-args extension here? */
2286 if (limit - bp > size_toInt (REST_EXTENSION_LENGTH)
2287 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
2290 temp->rest_args = 1;
2291 /*@innerbreak@*/ break;
2295 temp->length = size_fromInt (bp - temp->name);
2299 bp += REST_EXTENSION_LENGTH;
2302 arglengths += temp->length + 2;
2303 SKIP_WHITE_SPACE (bp);
2305 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
2306 cppReader_errorLit (pfile,
2307 cstring_makeLiteralTemp ("Parameter list for #define is not parseable"));
2313 SKIP_WHITE_SPACE (bp);
2316 cppReader_errorLit (pfile,
2317 cstring_makeLiteralTemp ("unterminated parameter list in `#define'"));
2321 struct arglist *otemp;
2323 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
2325 if (temp->length == otemp->length &&
2326 strncmp (temp->name, otemp->name, temp->length) == 0) {
2327 cstring name = cstring_copyLength (temp->name, temp->length);
2328 cppReader_error (pfile,
2329 message ("duplicate argument name `%x' in `#define'", name));
2336 ++bp; /* skip paren */
2337 SKIP_WHITE_SPACE (bp);
2338 /* now everything from bp before limit is the definition. */
2339 defn = collect_expansion (pfile, bp, limit, argno, arg_ptrs);
2340 defn->rest_args = rest_args;
2342 /* Now set defn->args.argnames to the result of concatenating
2343 the argument names in reverse order
2344 with comma-space between them. */
2345 defn->args.argnames = (char *) dmalloc (size_fromInt (arglengths + 1));
2348 struct arglist *temp;
2350 for (temp = arg_ptrs; temp != NULL; temp = temp->next)
2352 memcpy (&defn->args.argnames[i], temp->name, temp->length);
2354 if (temp->next != 0)
2356 defn->args.argnames[i++] = ',';
2357 defn->args.argnames[i++] = ' ';
2361 defn->args.argnames[i] = '\0';
2366 /* Simple expansion or empty definition. */
2370 if (is_hor_space[(int) *bp]) {
2372 SKIP_WHITE_SPACE (bp);
2375 case '!': case '\"': case '#': case '%': case '&': case '\'':
2376 case ')': case '*': case '+': case ',': case '-': case '.':
2377 case '/': case ':': case ';': case '<': case '=': case '>':
2378 case '?': case '[': case '\\': case ']': case '^': case '{':
2379 case '|': case '}': case '~':
2380 cppReader_warning (pfile,
2381 message ("Missing white space after #define %x",
2382 cstring_prefix (cstring_fromChars (symname),
2387 cppReader_pedwarn (pfile,
2388 message ("Missing white space after #define %x",
2389 cstring_prefix (cstring_fromChars (symname),
2395 /* now everything from bp before limit is the definition. */
2396 defn = collect_expansion (pfile, bp, limit, -1, NULL);
2397 defn->args.argnames = mstring_createEmpty ();
2400 defn->noExpand = noExpand;
2401 DPRINTF (("No expand: %d", noExpand));
2405 /* not: llassert (cstring_isUndefined (defn->file)); */
2408 /* OP is null if this is a predefinition */
2409 defn->predefined = predefinition;
2411 mdef.symnam = symname;
2412 mdef.symlen = sym_length;
2423 cpplib_createDefinition (cstring def,
2428 char *buf = cstring_toCharsSafe (def);
2429 char *limit = buf + cstring_length (def);
2430 char *bp; /* temp ptr into input buffer */
2431 char *symname; /* remember where symbol name starts */
2432 size_t sym_length; /* and how long it is */
2433 int rest_args = 0; /* really int! */
2434 int line = fileloc_lineno (loc);
2435 cstring file = fileloc_filename (loc);
2437 int arglengths = 0; /* Accumulate lengths of arg names
2438 plus number of args. */
2443 DPRINTF (("Creating definition: %s", buf));
2445 while (is_hor_space[(int) *bp])
2450 symname = bp; /* remember where it starts */
2452 sym_length = cppReader_checkMacroNameLoc (loc, symname, cstring_makeLiteralTemp ("macro"));
2454 DPRINTF (("length: %d", sym_length));
2458 DPRINTF (("Here: %s", bp));
2460 /* Lossage will occur if identifiers or control keywords are broken
2461 across lines using backslash. This is not the right place to take
2465 struct arglist *arg_ptrs = NULL;
2468 bp++; /* skip '(' */
2469 SKIP_WHITE_SPACE (bp);
2471 /* Loop over macro argument names. */
2474 struct arglist *temp = (struct arglist *) dmalloc (sizeof (*temp));
2476 temp->next = arg_ptrs;
2477 temp->argno = argno++;
2478 temp->rest_args = 0;
2484 voptgenerror (FLG_PREPROC,
2485 message ("Another parameter follows %s",
2486 cstring_fromChars (rest_extension)),
2490 if (!is_idstart[(int) *bp])
2492 voptgenerror (FLG_PREPROC,
2493 message ("Invalid character in macro parameter name: %c", *bp),
2497 /* Find the end of the arg name. */
2498 while (is_idchar[(int) *bp])
2501 /* do we have a "special" rest-args extension here? */
2502 if (limit - bp > size_toInt (REST_EXTENSION_LENGTH)
2503 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
2506 temp->rest_args = 1;
2507 /*@innerbreak@*/ break;
2511 temp->length = size_fromInt (bp - temp->name);
2515 bp += REST_EXTENSION_LENGTH;
2518 arglengths += temp->length + 2;
2519 SKIP_WHITE_SPACE (bp);
2521 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
2522 voptgenerror (FLG_PREPROC,
2523 cstring_makeLiteral ("Parameter list for #define is not parseable"),
2530 SKIP_WHITE_SPACE (bp);
2533 voptgenerror (FLG_PREPROC,
2534 cstring_makeLiteral ("Unterminated parameter list in #define'"),
2539 struct arglist *otemp;
2541 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
2543 if (temp->length == otemp->length &&
2544 strncmp (temp->name, otemp->name, temp->length) == 0) {
2545 cstring name = cstring_copyLength (temp->name, temp->length);
2547 voptgenerror (FLG_PREPROC,
2548 message ("Duplicate argument name in #define: %s", name),
2556 ++bp; /* skip paren */
2557 SKIP_WHITE_SPACE (bp);
2558 /* now everything from bp before limit is the definition. */
2559 defn = collect_expansionLoc (loc, bp, limit, argno, arg_ptrs);
2560 defn->rest_args = rest_args;
2562 /* Now set defn->args.argnames to the result of concatenating
2563 the argument names in reverse order
2564 with comma-space between them. */
2565 defn->args.argnames = (char *) dmalloc (size_fromInt (arglengths + 1));
2568 struct arglist *temp;
2570 for (temp = arg_ptrs; temp != NULL; temp = temp->next) {
2571 memcpy (&defn->args.argnames[i], temp->name, temp->length);
2573 if (temp->next != 0) {
2574 defn->args.argnames[i++] = ',';
2575 defn->args.argnames[i++] = ' ';
2579 defn->args.argnames[i] = '\0';
2584 /* Simple expansion or empty definition. */
2588 if (is_hor_space[(int) *bp]) {
2590 SKIP_WHITE_SPACE (bp);
2593 case '!': case '\"': case '#': case '%': case '&': case '\'':
2594 case ')': case '*': case '+': case ',': case '-': case '.':
2595 case '/': case ':': case ';': case '<': case '=': case '>':
2596 case '?': case '[': case '\\': case ']': case '^': case '{':
2597 case '|': case '}': case '~':
2598 voptgenerror (FLG_PREPROC,
2599 message ("Missing white space after #define %x",
2600 cstring_prefix (cstring_fromChars (symname),
2606 voptgenerror (FLG_PREPROC,
2607 message ("Missing white space after #define %x",
2608 cstring_prefix (cstring_fromChars (symname),
2616 /* now everything from bp before limit is the definition. */
2617 llassert (limit > bp);
2618 defn = collect_expansionLoc (loc, bp, limit, -1, NULL);
2619 defn->args.argnames = mstring_createEmpty ();
2622 defn->noExpand = noExpand;
2623 DPRINTF (("No expand: %d", noExpand));
2627 /* not: llassert (cstring_isUndefined (defn->file)); */
2630 /* OP is null if this is a predefinition */
2631 defn->predefined = predefinition;
2634 mdef.symnam = symname;
2635 mdef.symlen = sym_length;
2645 /* Check a purported macro name SYMNAME, and yield its length.
2646 USAGE is the kind of name this is intended for. */
2648 size_t cppReader_checkMacroName (cppReader *pfile, char *symname, cstring usage)
2653 for (p = symname; is_idchar[(int) *p]; p++)
2658 sym_length = size_fromInt (p - symname);
2661 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '\"')))
2663 cppReader_error (pfile, message ("invalid %s name", usage));
2665 else if (!is_idstart[(int) *symname])
2667 char *msg = (char *) dmalloc (sym_length + 1);
2668 memcpy (msg, symname, sym_length);
2669 msg[sym_length] = '\0';
2670 cppReader_error (pfile, message ("invalid %s name `%s'", usage,
2671 cstring_fromChars (msg)));
2676 if ((strncmp (symname, "defined", 7) == 0) && sym_length == 7)
2678 cppReader_error (pfile, message ("invalid %s name `defined'", usage));
2687 ** Gasp...cut-and-pasted from above to deal with pfile (should replace throughout with this...)
2690 size_t cppReader_checkMacroNameLoc (fileloc loc, char *symname, cstring usage)
2695 for (p = symname; is_idchar[(int) *p]; p++)
2700 sym_length = size_fromInt (p - symname);
2703 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '\"')))
2705 voptgenerror (FLG_PREPROC, message ("Invalid %s name: %s", usage,
2706 cstring_fromChars (symname)), loc);
2708 else if (!is_idstart[(int) *symname])
2710 char *msg = (char *) dmalloc (sym_length + 1);
2711 memcpy (msg, symname, sym_length);
2712 msg[sym_length] = '\0';
2713 voptgenerror (FLG_PREPROC, message ("Invalid %s name: %s", usage,
2714 cstring_fromChars (msg)),
2720 if ((strncmp (symname, "defined", 7) == 0) && sym_length == 7)
2722 voptgenerror (FLG_PREPROC, message ("Invalid %s name: defined", usage), loc);
2729 /* Return zero if two DEFINITIONs are isomorphic. */
2732 compare_defs (DEFINITION *d1, DEFINITION *d2)
2734 register struct reflist *a1, *a2;
2735 register char *p1 = d1->expansion;
2736 register char *p2 = d2->expansion;
2739 if (d1->nargs != d2->nargs)
2744 llassert (d1->args.argnames != NULL);
2745 llassert (d2->args.argnames != NULL);
2747 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames) != 0)
2752 for (a1 = d1->pattern, a2 = d2->pattern;
2753 (a1 != NULL) && (a2 != NULL);
2754 a1 = a1->next, a2 = a2->next) {
2755 if (!((a1->nchars == a2->nchars
2756 && (strncmp (p1, p2, size_fromInt (a1->nchars)) == 0))
2757 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
2758 || a1->argno != a2->argno
2759 || a1->stringify != a2->stringify
2760 || a1->raw_before != a2->raw_before
2761 || a1->raw_after != a2->raw_after)
2770 if (comp_def_part (first, p1, size_toInt (d1->length - (p1 - d1->expansion)),
2771 p2, size_toInt (d2->length - (p2 - d2->expansion)), 1))
2778 ** Return TRUE if two parts of two macro definitions are effectively different.
2779 ** One of the parts starts at BEG1 and has LEN1 chars;
2780 ** the other has LEN2 chars at BEG2.
2781 ** Any sequence of whitespace matches any other sequence of whitespace.
2782 ** FIRST means these parts are the first of a macro definition;
2783 ** so ignore leading whitespace entirely.
2784 ** LAST means these parts are the last of a macro definition;
2785 ** so ignore trailing whitespace entirely.
2789 comp_def_part (bool first, char *beg1, int len1, char *beg2, int len2, bool last)
2791 char *end1 = beg1 + len1;
2792 char *end2 = beg2 + len2;
2795 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2796 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2799 while (beg1 != end1 && is_space[(int) end1[-1]]) { end1--; }
2800 while (beg2 != end2 && is_space[(int) end2[-1]]) { end2--; }
2802 while (beg1 != end1 && beg2 != end2) {
2803 if (is_space[(int) *beg1] && is_space[(int) *beg2]) {
2804 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2805 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2806 } else if (*beg1 == *beg2) {
2810 return (beg1 != end1) || (beg2 != end2);
2814 ** Process a #define command.
2815 ** BUF points to the contents of the #define command, as a contiguous string.
2816 ** LIMIT points to the first character past the end of the definition.
2817 ** KEYWORD is the keyword-table entry for #define,
2818 ** or NULL for a "predefined" macro.
2822 do_defineAux (cppReader *pfile, struct directive *keyword,
2823 /*@exposed@*/ char *buf, char *limit, bool noExpand)
2829 mdef = create_definition (buf, limit, pfile, keyword == NULL, noExpand);
2834 hashcode = cpphash_hashCode (mdef.symnam, mdef.symlen, CPP_HASHSIZE);
2836 if ((hp = cpphash_lookup (mdef.symnam, size_toInt (mdef.symlen), hashcode)) != NULL)
2840 /* Redefining a precompiled key is ok. */
2841 if (hp->type == T_PCSTRING)
2843 /* Redefining a macro is ok if the definitions are the same. */
2844 else if (hp->type == T_MACRO)
2845 ok = !compare_defs (mdef.defn, hp->value.defn);
2846 /* Redefining a constant is ok with -D. */
2847 else if (hp->type == T_CONST)
2848 ok = !CPPOPTIONS (pfile)->done_initializing;
2850 ok = FALSE; /* Redefining anything else is bad. */
2853 /* Print the warning if it's not ok. */
2857 ** If we are passing through #define and #undef directives, do
2858 ** that for this re-definition now.
2861 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2863 /* llassert (keyword != NULL); */
2864 pass_thru_directive (buf, limit, pfile, keyword);
2867 cpp_setLocation (pfile);
2869 if (hp->type == T_MACRO)
2871 if (hp->value.defn->noExpand)
2873 ; /* error will be reported checking macros */
2879 message ("Macro %q already defined",
2880 cstring_copyLength (mdef.symnam, mdef.symlen)),
2881 message ("%q: Previous definition of %q",
2882 fileloc_unparseRaw (hp->value.defn->file,
2883 (int) hp->value.defn->line),
2884 cstring_copyLength (mdef.symnam, mdef.symlen)));
2889 genppllerror (FLG_MACROREDEF,
2890 message ("Macro %q already defined",
2891 cstring_copyLength (mdef.symnam,
2896 /* Replace the old definition. */
2898 hp->value.defn = mdef.defn;
2903 ** If we are passing through #define and #undef directives, do
2904 ** that for this new definition now.
2909 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2911 pass_thru_directive (buf, limit, pfile, keyword);
2914 DPRINTF (("Define macro: %s / %d",
2915 mdef.symnam, mdef.defn->noExpand));
2917 hn = cpphash_installMacro (mdef.symnam, mdef.symlen, mdef.defn, hashcode);
2919 } /*@=branchstate@*/
2928 do_define (cppReader *pfile, struct directive *keyword,
2929 /*@exposed@*/ char *buf, char *limit)
2931 DPRINTF (("Regular do define"));
2932 return do_defineAux (pfile, keyword, buf, limit, FALSE);
2936 ** This structure represents one parsed argument in a macro call.
2937 ** `raw' points to the argument text as written (`raw_length' is its length).
2938 ** `expanded' points to the argument's macro-expansion
2939 ** (its length is `expand_length').
2940 ** `stringified_length' is the length the argument would have
2942 ** `use_count' is the number of times this macro arg is substituted
2943 ** into the macro. If the actual use count exceeds 10,
2944 ** the value stored is 10.
2947 /* raw and expanded are relative to ARG_BASE */
2949 #define ARG_BASE ((pfile)->token_buffer)
2952 /* Strings relative to pfile->token_buffer */
2958 int stringified_length;
2964 ** Allocate a new cppBuffer for PFILE, and push it on the input buffer stack.
2965 ** If BUFFER != NULL, then use the LENGTH characters in BUFFER
2966 ** as the new input buffer.
2967 ** Return the new buffer, or NULL on failure.
2970 /*@null@*/ /*@exposed@*/ cppBuffer *
2971 cppReader_pushBuffer (cppReader *pfile, char *buffer, size_t length)
2973 cppBuffer *buf = cppReader_getBufferSafe (pfile);
2975 if (buf == pfile->buffer_stack)
2977 cppReader_fatalError
2979 message ("%s: macro or `#include' recursion too deep",
2980 (buf->fname != NULL)
2982 : cstring_makeLiteral ("<no name>")));
2983 sfreeEventually (buffer);
2987 llassert (buf != NULL);
2990 memset ((char *) buf, 0, sizeof (*buf));
2991 DPRINTF (("Pushing buffer: %s", cstring_copyLength (buffer, length)));
2992 CPPBUFFER (pfile) = buf;
2994 buf->if_stack = pfile->if_stack;
2995 buf->cleanup = cppReader_nullCleanup;
2996 buf->underflow = cppReader_nullUnderflow;
2998 buf->cur = buf->buf;
3002 buf->alimit = buf->rlimit = buffer + length;
3006 buf->alimit = buf->rlimit = NULL;
3013 cppReader_popBuffer (cppReader *pfile)
3015 cppBuffer *buf = CPPBUFFER (pfile);
3017 llassert (buf != NULL);
3019 (void) (*buf->cleanup) (buf, pfile);
3020 return ++CPPBUFFER (pfile);
3024 ** Scan until CPPBUFFER (PFILE) is exhausted into PFILE->token_buffer.
3025 ** Pop the buffer when done.
3029 cppReader_scanBuffer (cppReader *pfile)
3031 cppBuffer *buffer = CPPBUFFER (pfile);
3034 enum cpp_token token;
3036 token = cpplib_getToken (pfile);
3038 if (token == CPP_EOF) /* Should not happen ... */
3043 if (token == CPP_POP && CPPBUFFER (pfile) == buffer)
3045 (void) cppReader_popBuffer (pfile);
3052 * Rescan a string (which may have escape marks) into pfile's buffer.
3053 * Place the result in pfile->token_buffer.
3055 * The input is copied before it is scanned, so it is safe to pass
3056 * it something from the token_buffer that will get overwritten
3057 * (because it follows cpplib_getWritten). This is used by do_include.
3061 cpp_expand_to_buffer (cppReader *pfile, char *buf, size_t length)
3063 register cppBuffer *ip;
3064 char *limit = buf + length;
3065 char *buf1, *p1, *p2;
3067 DPRINTF (("Expand to buffer: %s", cstring_copyLength (buf, length)));
3069 /* evans - 2001-08-26
3070 ** length is unsigned - this doesn't make sense
3076 /* Set up the input on the input stack. */
3078 buf1 = (char *) dmalloc (length + 1);
3088 buf1[length] = '\0';
3090 ip = cppReader_pushBuffer (pfile, buf1, length);
3095 ip->has_escapes = TRUE;
3097 /* Scan the input, create the output. */
3098 cppReader_scanBuffer (pfile);
3100 cppReader_nullTerminate (pfile);
3104 adjust_position (char *buf, char *limit, int *linep, int *colp)
3110 (*linep)++, (*colp) = 1;
3116 /* Move line_base forward, updating lineno and colno. */
3119 update_position (cppBuffer *pbuf)
3122 char *new_pos = pbuf->cur;
3123 register struct parse_marker *mark;
3125 llassert (pbuf->buf != NULL);
3126 old_pos = pbuf->buf + pbuf->line_base;
3128 for (mark = pbuf->marks; mark != NULL; mark = mark->next)
3130 if (pbuf->buf + mark->position < new_pos)
3131 new_pos = pbuf->buf + mark->position;
3133 pbuf->line_base += new_pos - old_pos;
3135 llassert (old_pos != NULL);
3136 llassert (new_pos != NULL);
3138 adjust_position (old_pos, new_pos, &pbuf->lineno, &pbuf->colno);
3142 cppBuffer_getLineAndColumn (/*@null@*/ cppBuffer *pbuf, /*@out@*/ int *linep,
3143 /*@null@*/ /*@out@*/ int *colp)
3151 } /*@=branchstate@*/
3155 *linep = pbuf->lineno;
3156 *colp = pbuf->colno;
3158 llassert (pbuf->buf != NULL);
3159 llassert (pbuf->cur != NULL);
3161 adjust_position (pbuf->buf + pbuf->line_base, pbuf->cur, linep, colp);
3170 /* Return the cppBuffer that corresponds to a file (not a macro). */
3172 /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_fileBuffer (cppReader *pfile)
3174 cppBuffer *ip = cppReader_getBuffer (pfile);
3177 ip != NULL && ip != cppReader_nullBuffer (pfile);
3178 ip = cppBuffer_prevBuffer (ip))
3180 if (ip->fname != NULL)
3190 count_newlines (char *buf, char *limit)
3192 register long count = 0;
3204 * write out a #line command, for instance, after an #include file.
3205 * If CONDITIONAL is nonzero, we can omit the #line if it would
3206 * appear to be a no-op, and we can output a few newlines instead
3207 * if we want to increase the line number by a small amount.
3208 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
3212 output_line_command (cppReader *pfile, bool conditional,
3213 enum file_change_code file_change)
3216 cppBuffer *ip = CPPBUFFER (pfile);
3219 llassert (ip != NULL);
3221 if (ip->fname == NULL)
3224 update_position (ip);
3226 if (CPPOPTIONS (pfile)->no_line_commands
3227 || CPPOPTIONS (pfile)->no_output)
3230 buf = CPPBUFFER (pfile);
3232 llassert (buf != NULL);
3237 llassert (ip->cur != NULL);
3239 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
3241 if (CPPOPTIONS (pfile)->no_line_commands)
3245 if (line == pfile->lineno)
3248 /* If the inherited line number is a little too small,
3249 output some newlines instead of a #line command. */
3251 if (line > pfile->lineno && line < pfile->lineno + 8)
3253 cpplib_reserve (pfile, 20);
3254 while (line > pfile->lineno)
3256 cppReader_putCharQ (pfile, '\n');
3264 cpplib_reserve (pfile, 4 * cstring_length (ip->nominal_fname) + 50);
3267 #ifdef OUTPUT_LINE_COMMANDS
3268 static char sharp_line[] = "#line ";
3270 static char sharp_line[] = "# ";
3272 cppReader_putStrN (pfile, sharp_line, sizeof(sharp_line)-1);
3275 sprintf (cpplib_getPWritten (pfile), "%d ", line);
3276 cppReader_adjustWritten (pfile, strlen (cpplib_getPWritten (pfile)));
3278 quote_string (pfile, cstring_toCharsSafe (ip->nominal_fname));
3280 if (file_change != same_file) {
3281 cppReader_putCharQ (pfile, ' ');
3282 cppReader_putCharQ (pfile, file_change == enter_file ? '1' : '2');
3284 /* Tell cc1 if following text comes from a system header file. */
3285 if (ip->system_header_p != '\0') {
3286 cppReader_putCharQ (pfile, ' ');
3287 cppReader_putCharQ (pfile, '3');
3289 #ifndef NO_IMPLICIT_EXTERN_C
3290 /* Tell cc1plus if following text should be treated as C. */
3291 if (ip->system_header_p == (char) 2 && CPPOPTIONS (pfile)->cplusplus) {
3292 cppReader_putCharQ (pfile, ' ');
3293 cppReader_putCharQ (pfile, '4');
3296 cppReader_putCharQ (pfile, '\n');
3297 pfile->lineno = line;
3302 * Parse a macro argument and append the info on PFILE's token_buffer.
3303 * REST_ARGS means to absorb the rest of the args.
3304 * Return nonzero to indicate a syntax error.
3307 static enum cpp_token
3308 macarg (cppReader *pfile, int rest_args)
3311 enum cpp_token token;
3312 char save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
3313 bool oldexpand = pfile->no_macro_expand;
3314 CPPOPTIONS (pfile)->put_out_comments = 1;
3316 /* Try to parse as much of the argument as exists at this
3317 input stack level. */
3319 pfile->no_macro_expand = TRUE;
3323 token = cpplib_getToken (pfile);
3330 /* If we've hit end of file, it's an error (reported by caller).
3331 Ditto if it's the end of cpp_expand_to_buffer text.
3332 If we've hit end of macro, just continue. */
3333 if (!cppBuffer_isMacro (CPPBUFFER (pfile)))
3335 /*@switchbreak@*/ break;
3338 /*@switchbreak@*/ break;
3342 /*@switchbreak@*/ break;
3344 /* if we've returned to lowest level and
3345 we aren't absorbing all args */
3346 if (paren == 0 && rest_args == 0)
3348 /*@switchbreak@*/ break;
3350 /* Remove ',' or ')' from argument buffer. */
3351 cppReader_adjustWritten (pfile, -1);
3359 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
3360 pfile->no_macro_expand = oldexpand;
3366 /* Turn newlines to spaces in the string of length LENGTH at START,
3367 except inside of string constants.
3368 The string is copied into itself with its beginning staying fixed. */
3371 change_newlines (char *start, int length)
3375 register char *limit;
3379 limit = start + length;
3382 while (ibp < limit) {
3383 *obp++ = c = *ibp++;
3388 /* Notice and skip strings, so that we don't delete newlines in them. */
3391 while (ibp < limit) {
3392 *obp++ = c = *ibp++;
3394 /*@innerbreak@*/ break;
3395 if (c == '\n' && quotec == '\'')
3396 /*@innerbreak@*/ break;
3399 /*@switchbreak@*/ break;
3406 static /*@observer@*/ struct tm *
3407 timestamp (/*@returned@*/ cppReader *pfile)
3409 if (pfile->timebuf == NULL)
3411 time_t t = time ((time_t *) 0);
3412 pfile->timebuf = localtime (&t);
3415 llassert (pfile->timebuf != NULL);
3417 return pfile->timebuf;
3420 static ob_mstring monthnames[] = {
3421 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3422 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3426 * expand things like __FILE__. Place the expansion into the output
3427 * buffer *without* rescanning.
3431 special_symbol (hashNode hp, cppReader *pfile)
3433 cstring buf = cstring_undefined;
3439 int paren = 0; /* For special `defined' keyword */
3441 for (ip = cppReader_getBuffer (pfile); ip != NULL; ip = cppBuffer_prevBuffer (ip))
3443 if (ip == cppReader_nullBuffer (pfile))
3445 cppReader_errorLit (pfile,
3446 cstring_makeLiteralTemp ("cccp error: not in any file?!"));
3447 return; /* the show must go on */
3450 if (ip != NULL && ip->fname != NULL)
3462 if (hp->type == T_BASE_FILE)
3464 while (cppBuffer_prevBuffer (ip) != cppReader_nullBuffer (pfile))
3466 ip = cppBuffer_prevBuffer (ip);
3470 llassert (ip != NULL);
3471 string = cstring_toCharsSafe (ip->nominal_fname);
3478 cpplib_reserve (pfile, 3 + 4 * strlen (string));
3479 quote_string (pfile, string);
3482 case T_FUNC: /* added in ISO C99 */
3484 /* We don't know the actual name of the function, but it doesn't matter */
3485 char *string = "** function-name **";
3486 cpplib_reserve (pfile, 3 + 4 * strlen (string));
3487 quote_string (pfile, string);
3491 case T_INCLUDE_LEVEL:
3493 ip = cppReader_getBuffer (pfile);
3495 for (; ip != cppReader_nullBuffer (pfile) && ip != NULL;
3496 ip = cppBuffer_prevBuffer (ip))
3498 if (ip != NULL && ip->fname != NULL)
3504 buf = message ("%d", true_indepth - 1);
3508 buf = cstring_makeLiteral ("\"--- cpp version---\"");
3511 #ifndef NO_BUILTIN_SIZE_TYPE
3513 buf = cstring_makeLiteral (SIZE_TYPE);
3517 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3518 case T_PTRDIFF_TYPE:
3519 buf = cstring_makeLiteral (PTRDIFF_TYPE);
3524 buf = cstring_makeLiteral (cppReader_wcharType (pfile));
3527 case T_USER_LABEL_PREFIX_TYPE:
3528 buf = cstring_makeLiteral (USER_LABEL_PREFIX);
3531 case T_REGISTER_PREFIX_TYPE:
3532 buf = cstring_makeLiteral (REGISTER_PREFIX);
3536 buf = message ("%d", hp->value.ival);
3543 int line = ip->lineno;
3544 int col = ip->colno;
3546 llassert (ip->cur != NULL);
3547 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
3549 buf = message ("%d", (int) line);
3561 char *sbuf = (char *) dmalloc (20);
3562 timebuf = timestamp (pfile);
3563 if (hp->type == T_DATE)
3565 sprintf (sbuf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
3566 timebuf->tm_mday, timebuf->tm_year + 1900);
3570 sprintf (sbuf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
3574 buf = cstring_fromCharsNew (sbuf);
3579 case T_SPEC_DEFINED:
3580 buf = cstring_makeLiteral (" 0 "); /* Assume symbol is not defined */
3581 ip = cppReader_getBuffer (pfile);
3582 llassert (ip != NULL);
3583 llassert (ip->cur != NULL);
3584 SKIP_WHITE_SPACE (ip->cur);
3586 if (*ip->cur == '(')
3589 ip->cur++; /* Skip over the paren */
3590 SKIP_WHITE_SPACE (ip->cur);
3593 if (!is_idstart[(int) *ip->cur])
3595 if (ip->cur[0] == 'L' && (ip->cur[1] == '\'' || ip->cur[1] == '\"'))
3598 if ((hp = cpphash_lookup (ip->cur, -1, -1)) != 0)
3601 buf = cstring_makeLiteral (" 1 ");
3604 while (is_idchar[(int) *ip->cur])
3609 SKIP_WHITE_SPACE (ip->cur);
3613 if (*ip->cur != ')')
3621 cppReader_errorLit (pfile,
3622 cstring_makeLiteralTemp ("`defined' without an identifier"));
3626 cpp_setLocation (pfile);
3627 llfatalerror (message ("Pre-processing error: invalid special hash type"));
3630 len = cstring_length (buf);
3632 cpplib_reserve (pfile, len + 1);
3633 cppReader_putStrN (pfile, cstring_toCharsSafe (buf), len);
3634 cppReader_nullTerminateQ (pfile);
3640 /* Write out a #define command for the special named MACRO_NAME
3641 to PFILE's token_buffer. */
3644 dump_special_to_buffer (cppReader *pfile, char *macro_name)
3646 static char define_directive[] = "#define ";
3647 size_t macro_name_length = strlen (macro_name);
3648 output_line_command (pfile, 0, same_file);
3649 cpplib_reserve (pfile, sizeof(define_directive) + macro_name_length);
3650 cppReader_putStrN (pfile, define_directive, sizeof(define_directive)-1);
3651 cppReader_putStrN (pfile, macro_name, macro_name_length);
3652 cppReader_putCharQ (pfile, ' ');
3653 cpp_expand_to_buffer (pfile, macro_name, macro_name_length);
3654 cppReader_putChar (pfile, '\n');
3657 /* Initialize the built-in macros. */
3660 cpplib_installBuiltin (/*@observer@*/ char *name, ctype ctyp,
3661 int len, enum node_type type,
3662 int ivalue, /*@null@*/ /*@only@*/ char *value,
3665 cstring sname = cstring_fromCharsNew (name);
3667 llassert (usymtab_inGlobalScope ());
3670 ** Be careful here: this is done before the ctype table has
3671 ** been initialized.
3674 if (!usymtab_exists (sname))
3676 uentry ue = uentry_makeConstant (sname, ctyp, fileloc_createBuiltin ());
3678 if (ctype_equal (ctyp, ctype_string))
3680 qualList ql = qualList_new ();
3681 ql = qualList_add (ql, qual_createObserver ());
3682 uentry_reflectQualifiers (ue, ql);
3686 usymtab_addGlobalEntry (ue);
3693 (void) cpphash_install (name, len, type, ivalue, value, hash);
3694 cstring_free (sname);
3698 cpplib_installBuiltinType (/*@observer@*/ char *name, ctype ctyp,
3699 int len, enum node_type type,
3701 /*@only@*/ /*@null@*/ char *value, int hash)
3703 cstring sname = cstring_fromChars (name);
3704 /* evs 2000 07 10 - removed a memory leak, detected by splint */
3706 llassert (usymtab_inGlobalScope ());
3708 if (!usymtab_existsTypeEither (sname))
3710 uentry ue = uentry_makeDatatype (sname, ctyp,
3711 NO, qual_createConcrete (),
3712 fileloc_createBuiltin ());
3713 llassert (!usymtab_existsEither (sname));
3714 usymtab_addGlobalEntry (ue);
3717 (void) cpphash_install (name, len, type, ivalue, value, hash);
3721 initialize_builtins (cppReader *pfile)
3723 cpplib_installBuiltin ("__LINE__", ctype_int, -1, T_SPECLINE, 0, NULL, -1);
3724 cpplib_installBuiltin ("__DATE__", ctype_string, -1, T_DATE, 0, NULL, -1);
3725 cpplib_installBuiltin ("__FILE__", ctype_string, -1, T_FILE, 0, NULL, -1);
3726 cpplib_installBuiltin ("__BASE_FILE__", ctype_string, -1, T_BASE_FILE, 0, NULL, -1);
3727 cpplib_installBuiltin ("__func__", ctype_string, -1, T_FUNC, 0, NULL, -1);
3728 cpplib_installBuiltin ("__INCLUDE_LEVEL__", ctype_int, -1, T_INCLUDE_LEVEL, 0, NULL, -1);
3729 cpplib_installBuiltin ("__VERSION__", ctype_string, -1, T_VERSION, 0, NULL, -1);
3730 #ifndef NO_BUILTIN_SIZE_TYPE
3731 cpplib_installBuiltinType ("__SIZE_TYPE__", ctype_anyintegral, -1, T_SIZE_TYPE, 0, NULL, -1);
3733 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3734 cpplib_installBuiltinType ("__PTRDIFF_TYPE__", ctype_anyintegral, -1, T_PTRDIFF_TYPE, 0, NULL, -1);
3736 cpplib_installBuiltinType ("__WCHAR_TYPE__", ctype_anyintegral, -1, T_WCHAR_TYPE, 0, NULL, -1);
3737 cpplib_installBuiltin ("__USER_LABEL_PREFIX__", ctype_string, -1, T_USER_LABEL_PREFIX_TYPE, 0, NULL, -1);
3738 cpplib_installBuiltin ("__REGISTER_PREFIX__", ctype_string, -1, T_REGISTER_PREFIX_TYPE, 0, NULL, -1);
3739 cpplib_installBuiltin ("__TIME__", ctype_string, -1, T_TIME, 0, NULL, -1);
3741 if (!cppReader_isTraditional (pfile))
3743 cpplib_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3747 cpplib_installBuiltin ("_WIN32", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3751 ** This is supplied using a -D by the compiler driver
3752 ** so that it is present only when truly compiling with GNU C.
3755 /* cpplib_install ("__GNUC__", -1, T_CONST, 2, 0, -1); */
3757 cpplib_installBuiltin ("S_SPLINT_S", ctype_int, -1, T_CONST, 2, NULL, -1);
3758 cpplib_installBuiltin ("__LCLINT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3760 /*drl 1/9/2001/ try to define the right symbol for the architecture
3761 We use autoconf to determine the target cpu
3764 cpplib_installBuiltin ("__" TARGET_CPU, ctype_int, -1, T_CONST, 2, NULL, -1);
3767 /*drl 1/2/2002 set some flags based on uname
3768 I'd like to be able to do this with autoconf macro instead...
3771 /*Thanks to Nelson Beebe for suggesting possible values for these */
3773 if (! strcmp (UNAME, "Linux"))
3776 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3780 else if(! strcmp (UNAME, "Darwin"))
3782 cpplib_installBuiltin ("__ppc__", ctype_int, -1, T_CONST, 2, NULL, -1);
3783 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3785 else if(! strcmp (UNAME, "HP-UX"))
3787 cpplib_installBuiltin ("PWB", ctype_int, -1, T_CONST, 2, NULL, -1);
3788 cpplib_installBuiltin ("_HIUX_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3789 cpplib_installBuiltin ("_HPUX_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3790 cpplib_installBuiltin ("_PA_RISC1_1", ctype_int, -1, T_CONST, 2, NULL, -1);
3791 cpplib_installBuiltin ("__PWB", ctype_int, -1, T_CONST, 2, NULL, -1);
3792 cpplib_installBuiltin ("__PWB__", ctype_int, -1, T_CONST, 2, NULL, -1);
3793 cpplib_installBuiltin ("__STDC_EXT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3794 cpplib_installBuiltin ("__hp9000s700", ctype_int, -1, T_CONST, 2, NULL, -1);
3795 cpplib_installBuiltin ("__hp9000s800", ctype_int, -1, T_CONST, 2, NULL, -1);
3796 cpplib_installBuiltin ("__hp9000s800__", ctype_int, -1, T_CONST, 2, NULL, -1);
3797 cpplib_installBuiltin ("__hp9k8", ctype_int, -1, T_CONST, 2, NULL, -1);
3798 cpplib_installBuiltin ("__hp9k8__", ctype_int, -1, T_CONST, 2, NULL, -1);
3799 cpplib_installBuiltin ("__hppa", ctype_int, -1, T_CONST, 2, NULL, -1);
3800 cpplib_installBuiltin ("__hppa__", ctype_int, -1, T_CONST, 2, NULL, -1);
3801 cpplib_installBuiltin ("__hpux", ctype_int, -1, T_CONST, 2, NULL, -1);
3802 cpplib_installBuiltin ("__hpux__", ctype_int, -1, T_CONST, 2, NULL, -1);
3803 cpplib_installBuiltin ("__unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3804 cpplib_installBuiltin ("__unix__", ctype_int, -1, T_CONST, 2, NULL, -1);
3805 cpplib_installBuiltin ("hp9000s800", ctype_int, -1, T_CONST, 2, NULL, -1);
3806 cpplib_installBuiltin ("hp9k8", ctype_int, -1, T_CONST, 2, NULL, -1);
3807 cpplib_installBuiltin ("hppa", ctype_int, -1, T_CONST, 2, NULL, -1);
3808 cpplib_installBuiltin ("hpux", ctype_int, -1, T_CONST, 2, NULL, -1);
3809 cpplib_installBuiltin ("unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3811 else if(! strcmp (UNAME, "IRIX64"))
3813 cpplib_installBuiltin ("LANGUAGE_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3814 cpplib_installBuiltin ("MIPSEB", ctype_int, -1, T_CONST, 2, NULL, -1);
3815 cpplib_installBuiltin ("_ABIN32", ctype_int, -1, T_CONST, 2, NULL, -1);
3816 cpplib_installBuiltin ("_COMPILER_VERSION", ctype_int, -1, T_CONST, 730, NULL, -1);
3817 cpplib_installBuiltin ("_LANGUAGE_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3818 cpplib_installBuiltin ("_LONGLONG", ctype_int, -1, T_CONST, 2, NULL, -1);
3819 cpplib_installBuiltin ("_MIPSEB", ctype_int, -1, T_CONST, 2, NULL, -1);
3820 cpplib_installBuiltin ("_MIPS_FPSET", ctype_int, -1, T_CONST, 32, NULL, -1);
3821 cpplib_installBuiltin ("_MIPS_ISA", ctype_int, -1, T_CONST, 3, NULL, -1);
3822 /*_MIPS_SIM=_ABIN32*/
3823 cpplib_installBuiltin ("_MIPS_SIM", ctype_int, -1, T_CONST, 2, NULL , -1);
3824 cpplib_installBuiltin ("_MIPS_SZINT", ctype_int, -1, T_CONST, 32, NULL, -1);
3825 cpplib_installBuiltin ("_MIPS_SZLONG", ctype_int, -1, T_CONST, 32, NULL, -1);
3826 cpplib_installBuiltin ("_MIPS_SZPTR", ctype_int, -1, T_CONST, 32, NULL, -1);
3827 cpplib_installBuiltin ("_MODERN_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3828 cpplib_installBuiltin ("_PIC", ctype_int, -1, T_CONST, 2, NULL, -1);
3829 cpplib_installBuiltin ("_SGI_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3830 cpplib_installBuiltin ("_SIZE_INT", ctype_int, -1, T_CONST, 32, NULL, -1);
3831 cpplib_installBuiltin ("_SIZE_LONG", ctype_int, -1, T_CONST, 32, NULL, -1);
3832 cpplib_installBuiltin ("_SIZE_PTR", ctype_int, -1, T_CONST, 32, NULL, -1);
3833 cpplib_installBuiltin ("_SVR4_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3834 cpplib_installBuiltin ("_SYSTYPE_SVR4", ctype_int, -1, T_CONST, 2, NULL, -1);
3835 cpplib_installBuiltin ("__DSO__", ctype_int, -1, T_CONST, 2, NULL, -1);
3836 cpplib_installBuiltin ("__EXTENSIONS__", ctype_int, -1, T_CONST, 2, NULL, -1);
3837 cpplib_installBuiltin ("__INLINE_INTRINSICS", ctype_int, -1, T_CONST, 2, NULL, -1);
3838 cpplib_installBuiltin ("__MATH_HAS_NO_SIDE_EFFECTS", ctype_int, -1, T_CONST, 2, NULL, -1);
3839 cpplib_installBuiltin ("__host_mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3840 cpplib_installBuiltin ("__mips", ctype_int, -1, T_CONST, 3, NULL, -1);
3841 cpplib_installBuiltin ("__sgi", ctype_int, -1, T_CONST, 2, NULL, -1);
3842 cpplib_installBuiltin ("__unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3843 cpplib_installBuiltin ("host_mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3844 cpplib_installBuiltin ("mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3845 cpplib_installBuiltin ("sgi", ctype_int, -1, T_CONST, 2, NULL, -1);
3846 cpplib_installBuiltin ("unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3848 else if(! strcmp (UNAME, "OSF1"))
3850 cpplib_installBuiltin ("__alpha", ctype_int, -1, T_CONST, 2, NULL, -1);
3852 else if (!strcmp (UNAME, "Rhapsody"))
3854 cpplib_installBuiltin ("__ppc__", ctype_int, -1, T_CONST, 2, NULL, -1);
3855 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3858 else if (!strcmp (UNAME, "SunOS"))
3860 cpplib_installBuiltin ("__OPEN_MAX", ctype_int, -1, T_CONST, 20, NULL, -1);
3861 cpplib_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, 2, NULL, -1);
3862 cpplib_installBuiltin ("__sparc", ctype_int, -1, T_CONST, 2, NULL, -1);
3863 /* This define "-Dfileno(f)=0" should be inserted but we're going to stick to deinfe constants for now...*/
3868 types which we have not explictedly handled.
3869 AIX, FreeBSD, IRIX, Mach
3874 if (CPPOPTIONS (pfile)->debug_output)
3876 dump_special_to_buffer (pfile, "__BASE_FILE__");
3877 dump_special_to_buffer (pfile, "__VERSION__");
3878 #ifndef NO_BUILTIN_SIZE_TYPE
3879 dump_special_to_buffer (pfile, "__SIZE_TYPE__");
3881 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3882 dump_special_to_buffer (pfile, "__PTRDIFF_TYPE__");
3884 dump_special_to_buffer (pfile, "__WCHAR_TYPE__");
3885 dump_special_to_buffer (pfile, "__DATE__");
3886 dump_special_to_buffer (pfile, "__TIME__");
3887 if (!cppReader_isTraditional (pfile))
3888 dump_special_to_buffer (pfile, "__STDC__");
3893 /* Return 1 iff a token ending in C1 followed directly by a token C2
3894 could cause mis-tokenization. */
3897 unsafe_chars (char c1, char c2)
3902 if (c2 == c1 || c2 == '=')
3906 case '0': case '1': case '2': case '3': case '4':
3907 case '5': case '6': case '7': case '8': case '9':
3908 case 'e': case 'E': case 'p': case 'P':
3909 if (c2 == '-' || c2 == '+')
3910 return 1; /* could extend a pre-processing number */
3913 if (c2 == '\'' || c2 == '\"')
3914 return 1; /* Could turn into L"xxx" or L'xxx'. */
3918 case 'a': case 'b': case 'c': case 'd': case 'f':
3919 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3920 case 'm': case 'n': case 'o': case 'q': case 'r':
3921 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3923 case 'A': case 'B': case 'C': case 'D': case 'F':
3924 case 'G': case 'H': case 'I': case 'J': case 'K':
3925 case 'M': case 'N': case 'O': case 'Q': case 'R':
3926 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3928 /* We're in the middle of either a name or a pre-processing number. */
3929 return (is_idchar[(int) c2] || c2 == '.');
3930 case '<': case '>': case '!': case '%': case '#': case ':':
3931 case '^': case '&': case '|': case '*': case '/': case '=':
3932 return (c2 == c1 || c2 == '=');
3937 /* Expand a macro call.
3938 HP points to the symbol that is the macro being called.
3939 Put the result of expansion onto the input stack
3940 so that subsequent input by our caller will use it.
3942 If macro wants arguments, caller has already verified that
3943 an argument list follows; arguments come from the input stack. */
3946 cpplib_macroExpand (cppReader *pfile, /*@dependent@*/ hashNode hp)
3949 DEFINITION *defn = hp->value.defn;
3957 size_t old_written = cpplib_getWritten (pfile);
3961 struct argdata *args = NULL;
3963 pfile->output_escapes++;
3964 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile), &start_line, &start_column);
3965 DPRINTF (("Expand macro: %d:%d", start_line, start_column));
3967 nargs = defn->nargs;
3971 enum cpp_token token = CPP_EOF;
3973 args = (struct argdata *) dmalloc ((nargs + 1) * sizeof (*args));
3975 for (i = 0; i < nargs; i++)
3977 args[i].expanded = 0;
3979 args[i].raw_length = 0;
3980 args[i].expand_length = args[i].stringified_length = -1;
3981 args[i].use_count = 0;
3985 ** Parse all the macro args that are supplied. I counts them.
3986 ** The first NARGS args are stored in ARGS.
3987 ** The rest are discarded. If rest_args is set then we assume
3988 ** macarg absorbed the rest of the args.
3994 cppReader_forward (pfile, 1); /* Discard the open-parenthesis before the first arg. */
4002 if (i < nargs || (nargs == 0 && i == 0))
4004 /* if we are working on last arg which absorbs rest of args... */
4005 if (i == nargs - 1 && defn->rest_args)
4010 args[i].raw = size_toLong (cpplib_getWritten (pfile));
4011 token = macarg (pfile, rest_args);
4012 args[i].raw_length = size_toInt (cpplib_getWritten (pfile) - args[i].raw);
4013 args[i].newlines = FALSE; /* FIXME */
4017 token = macarg (pfile, 0);
4020 if (token == CPP_EOF || token == CPP_POP)
4022 cppReader_errorWithLine (pfile, start_line, start_column,
4023 cstring_fromCharsNew ("unterminated macro call"));
4028 } while (token == CPP_COMMA);
4030 /* If we got one arg but it was just whitespace, call that 0 args. */
4038 bp = ARG_BASE + args[0].raw;
4039 lim = bp + args[0].raw_length;
4041 /* cpp.texi says for foo ( ) we provide one argument.
4042 However, if foo wants just 0 arguments, treat this as 0. */
4046 while (bp != lim && is_space[(int) *bp])
4056 /* Don't output an error message if we have already output one for
4057 a parse error above. */
4060 if (nargs == 0 && i > 0)
4062 cppReader_error (pfile,
4063 message ("arguments given to macro `%s'", hp->name));
4067 /* traditional C allows foo() if foo wants one argument. */
4068 if (nargs == 1 && i == 0 && cppReader_isTraditional (pfile))
4072 /* the rest args token is allowed to absorb 0 tokens */
4073 else if (i == nargs - 1 && defn->rest_args)
4076 cppReader_error (pfile,
4077 message ("macro `%s' used without args", hp->name));
4079 cppReader_error (pfile,
4080 message ("macro `%s' used with just one arg", hp->name));
4083 cppReader_error (pfile,
4084 message ("macro `%s' used with only %d args",
4090 cppReader_error (pfile,
4091 message ("macro `%s' used with too many (%d) args", hp->name, i));
4100 ** If the agrument list was multiple lines, need to insert new lines to keep line
4101 ** numbers accurate.
4104 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile), &end_line, &end_column);
4105 DPRINTF (("Expand macro: %d:%d", end_line, end_column));
4107 /* If macro wants zero args, we parsed the arglist for checking only.
4108 Read directly from the macro definition. */
4112 xbuf = defn->expansion;
4113 xbuf_len = defn->length;
4117 char *exp = defn->expansion;
4118 int offset; /* offset in expansion,
4119 copied a piece at a time */
4120 size_t totlen; /* total amount of exp buffer filled so far */
4122 register struct reflist *ap, *last_ap;
4124 assertSet (args); /* args is defined since the nargs > 0 path was taken */
4126 /* Macro really takes args. Compute the expansion of this call. */
4128 /* Compute length in characters of the macro's expansion.
4129 Also count number of times each arg is used. */
4130 xbuf_len = defn->length;
4132 llassert (args != NULL);
4134 for (ap = defn->pattern; ap != NULL; ap = ap->next)
4138 struct argdata *arg = &args[ap->argno];
4140 /* Stringify it it hasn't already been */
4143 if (arg->stringified_length < 0)
4145 int arglen = arg->raw_length;
4146 bool escaped = FALSE;
4147 char in_string = '\0';
4150 /* Initially need_space is -1. Otherwise, 1 means the
4151 previous character was a space, but we suppressed it;
4152 0 means the previous character was a non-space. */
4153 int need_space = -1;
4156 arg->stringified = cpplib_getWritten (pfile);
4157 if (!cppReader_isTraditional (pfile))
4158 cppReader_putChar (pfile, '\"'); /* insert beginning quote */
4159 for (; i < arglen; i++)
4161 c = (ARG_BASE + arg->raw)[i];
4163 if (in_string == '\0')
4165 /* Internal sequences of whitespace are replaced by
4166 one space except within an string or char token.*/
4167 if (is_space[(int) c])
4169 if (cpplib_getWritten (pfile) > arg->stringified
4170 && (cpplib_getPWritten (pfile))[-1] == '@')
4172 /* "@ " escape markers are removed */
4173 cppReader_adjustWritten (pfile, -1);
4174 /*@innercontinue@*/ continue;
4176 if (need_space == 0)
4178 /*@innercontinue@*/ continue;
4180 else if (need_space > 0)
4181 cppReader_putChar (pfile, ' ');
4197 if (in_string != '\0')
4202 else if (c == '\"' || c == '\'')
4212 /* Escape these chars */
4213 if (c == '\"' || (in_string != '\0' && c == '\\'))
4214 cppReader_putChar (pfile, '\\');
4216 cppReader_putChar (pfile, c);
4219 cpplib_reserve (pfile, 4);
4220 sprintf (cpplib_getPWritten (pfile), "\\%03o",
4222 cppReader_adjustWritten (pfile, 4);
4225 if (!cppReader_isTraditional (pfile))
4226 cppReader_putChar (pfile, '\"'); /* insert ending quote */
4227 arg->stringified_length
4228 = size_toInt (cpplib_getWritten (pfile) - arg->stringified);
4231 xbuf_len += args[ap->argno].stringified_length;
4233 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
4235 /* Add 4 for two newline-space markers to prevent token concatenation. */
4236 assertSet (args); /* Splint shouldn't need this */
4237 xbuf_len += args[ap->argno].raw_length + 4;
4241 /* We have an ordinary (expanded) occurrence of the arg.
4242 So compute its expansion, if we have not already. */
4244 assertSet (args); /* shouldn't need this */
4246 if (args[ap->argno].expand_length < 0)
4248 args[ap->argno].expanded = cpplib_getWritten (pfile);
4249 cpp_expand_to_buffer (pfile,
4250 ARG_BASE + args[ap->argno].raw,
4251 size_fromInt (args[ap->argno].raw_length));
4253 args[ap->argno].expand_length
4254 = size_toInt (cpplib_getWritten (pfile) - args[ap->argno].expanded);
4257 /* Add 4 for two newline-space markers to prevent
4258 token concatenation. */
4259 xbuf_len += args[ap->argno].expand_length + 4;
4261 if (args[ap->argno].use_count < 10)
4262 args[ap->argno].use_count++;
4265 xbuf = (char *) dmalloc (xbuf_len + 1);
4269 ** Generate in XBUF the complete expansion
4270 ** with arguments substituted in.
4271 ** TOTLEN is the total size generated so far.
4272 ** OFFSET is the index in the definition
4273 ** of where we are copying from.
4279 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
4280 last_ap = ap, ap = ap->next)
4282 register struct argdata *arg = &args[ap->argno];
4283 size_t count_before = totlen;
4285 /* Add chars to XBUF. */
4286 for (i = 0; i < ap->nchars; i++, offset++)
4288 xbuf[totlen++] = exp[offset];
4291 /* If followed by an empty rest arg with concatenation,
4292 delete the last run of nonwhite chars. */
4293 if (rest_zero && totlen > count_before
4294 && ((ap->rest_args && ap->raw_before)
4295 || (last_ap != NULL && last_ap->rest_args
4296 && last_ap->raw_after)))
4298 /* Delete final whitespace. */
4299 while (totlen > count_before && is_space[(int) xbuf[totlen - 1]])
4304 /* Delete the nonwhites before them. */
4305 while (totlen > count_before && ! is_space[(int) xbuf[totlen - 1]])
4311 if (ap->stringify != 0)
4314 memcpy (xbuf + totlen,
4315 ARG_BASE + arg->stringified,
4316 size_fromInt (arg->stringified_length));
4317 totlen += arg->stringified_length;
4319 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
4326 p1 = ARG_BASE + arg->raw;
4327 l1 = p1 + arg->raw_length;
4331 while (p1 != l1 && is_space[(int) *p1])
4336 while (p1 != l1 && is_idchar[(int) *p1])
4338 xbuf[totlen++] = *p1++;
4341 /* Delete any no-reexpansion marker that follows
4342 an identifier at the beginning of the argument
4343 if the argument is concatenated with what precedes it. */
4344 if (p1[0] == '@' && p1[1] == '-')
4349 /* Arg is concatenated after: delete trailing whitespace,
4350 whitespace markers, and no-reexpansion markers. */
4353 if (is_space[(int) l1[-1]]) l1--;
4354 else if (l1[-1] == '-')
4357 /* If a `-' is preceded by an odd number of newlines then it
4358 and the last newline are a no-reexpansion marker. */
4359 while (p2 != p1 && p2[-1] == '\n')
4364 if (((l1 - 1 - p2) & 1) != 0)
4370 /*@innerbreak@*/ break;
4375 /*@innerbreak@*/ break;
4380 memcpy (xbuf + totlen, p1, size_fromInt (l1 - p1));
4388 expanded = ARG_BASE + arg->expanded;
4390 if (!ap->raw_before && totlen > 0
4391 && (arg->expand_length != 0)
4392 && !cppReader_isTraditional(pfile)
4393 && unsafe_chars (xbuf[totlen-1], expanded[0]))
4395 xbuf[totlen++] = '@';
4396 xbuf[totlen++] = ' ';
4399 memcpy (xbuf + totlen, expanded,
4400 size_fromInt (arg->expand_length));
4401 totlen += arg->expand_length;
4403 if (!ap->raw_after && totlen > 0
4404 && offset < size_toInt (defn->length)
4405 && !cppReader_isTraditional(pfile)
4406 && unsafe_chars (xbuf[totlen-1], exp[offset]))
4408 xbuf[totlen++] = '@';
4409 xbuf[totlen++] = ' ';
4412 /* If a macro argument with newlines is used multiple times,
4413 then only expand the newlines once. This avoids creating
4414 output lines which don't correspond to any input line,
4415 which confuses gdb and gcov. */
4416 if (arg->use_count > 1 && arg->newlines > 0)
4418 /* Don't bother doing change_newlines for subsequent
4422 = change_newlines (expanded, arg->expand_length);
4426 if (totlen > xbuf_len)
4430 /* if there is anything left of the definition
4431 after handling the arg list, copy that in too. */
4433 for (i = offset; i < size_toInt (defn->length); i++)
4435 /* if we've reached the end of the macro */
4438 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
4439 && last_ap->raw_after))
4440 xbuf[totlen++] = exp[i];
4443 xbuf[totlen] = '\0';
4447 pfile->output_escapes--;
4449 /* Now put the expansion on the input stack
4450 so our caller will commence reading from it. */
4451 DPRINTF (("Pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4453 if (end_line != start_line)
4455 /* xbuf must have enough newlines */
4456 int newlines = end_line - start_line;
4457 int foundnewlines = 0;
4458 char *xbufptr = xbuf;
4460 while ((xbufptr = strchr (xbufptr, '\n')) != NULL && foundnewlines <= newlines)
4465 if (*xbufptr == '\0')
4471 if (foundnewlines < newlines)
4473 cstring newbuf = cstring_copyLength (xbuf, xbuf_len);
4475 while (foundnewlines < newlines)
4477 newbuf = cstring_appendChar (newbuf, '\n');
4482 xbuf = cstring_toCharsSafe (newbuf);
4483 xbuf_len = cstring_length (newbuf);
4485 } /*@=branchstate@*/
4488 DPRINTF (("Pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4490 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
4491 DPRINTF (("After pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4492 cppReader_getBufferSafe (pfile)->has_escapes = 1;
4494 /* Pop the space we've used in the token_buffer for argument expansion. */
4495 cppReader_setWritten (pfile, old_written);
4496 DPRINTF (("Done set written"));
4498 /* Recursive macro use sometimes works traditionally.
4499 #define foo(x,y) bar (x (y,0), y)
4502 if (!cppReader_isTraditional (pfile))
4503 hp->type = T_DISABLED;
4509 push_macro_expansion (cppReader *pfile, char *xbuf, size_t xbuf_len,
4510 /*@dependent@*/ hashNode hp)
4512 cppBuffer *mbuf = cppReader_pushBuffer (pfile, xbuf, xbuf_len);
4519 mbuf->cleanup = cppReader_macroCleanup;
4521 llassert (mbuf->hnode == NULL);
4524 /* The first chars of the expansion should be a "@ " added by
4525 collect_expansion. This is to prevent accidental token-pasting
4526 between the text preceding the macro invocation, and the macro
4529 We would like to avoid adding unneeded spaces (for the sake of
4530 tools that use cpp, such as imake). In some common cases we can
4531 tell that it is safe to omit the space.
4533 The character before the macro invocation cannot have been an
4534 idchar (or else it would have been pasted with the idchars of
4535 the macro name). Therefore, if the first non-space character
4536 of the expansion is an idchar, we do not need the extra space
4537 to prevent token pasting.
4539 Also, we don't need the extra space if the first char is '(',
4540 or some other (less common) characters. */
4542 if (xbuf[0] == '@' && xbuf[1] == ' '
4543 && (is_idchar[(int) xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
4544 || xbuf[2] == '\"'))
4546 llassert (mbuf->cur != NULL);
4547 DPRINTF (("Eating: %c", xbuf[2]));
4554 /* Like cpplib_getToken, except that it does not read past end-of-line.
4555 Also, horizontal space is skipped, and macros are popped. */
4557 static enum cpp_token
4558 get_directive_token (cppReader *pfile)
4562 size_t old_written = cpplib_getWritten (pfile);
4563 enum cpp_token token;
4564 cppSkipHspace (pfile);
4565 if (cppReader_peekC (pfile) == '\n')
4570 token = cpplib_getToken (pfile);
4575 if (!cppBuffer_isMacro (cppReader_getBuffer (pfile)))
4580 cppReader_setWritten (pfile, old_written);
4581 /*@switchbreak@*/ break;
4589 /* Handle #include and #import.
4590 This function expects to see "fname" or <fname> on the input.
4592 The input is normally in part of the output_buffer following
4593 cpplib_getWritten, and will get overwritten by output_line_command.
4594 I.e. in input file specification has been popped by cppReader_handleDirective.
4598 do_include (cppReader *pfile, struct directive *keyword,
4599 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
4601 bool skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4603 char *fbeg, *fend; /* Beginning and end of fname */
4604 enum cpp_token token;
4606 /* Chain of dirs to search */
4607 struct file_name_list *search_start = CPPOPTIONS (pfile)->include;
4608 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
4609 struct file_name_list *searchptr = NULL;
4610 size_t old_written = cpplib_getWritten (pfile);
4613 int f; /* file number */
4614 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4615 f= -1; /* JF we iz paranoid! */
4617 pfile->parsing_include_directive++;
4618 token = get_directive_token (pfile);
4619 pfile->parsing_include_directive--;
4621 if (token == CPP_STRING)
4623 /* FIXME - check no trailing garbage */
4624 fbeg = pfile->token_buffer + old_written + 1;
4625 fend = cpplib_getPWritten (pfile) - 1;
4626 if (fbeg[-1] == '<')
4629 /* If -I-, start with the first -I dir after the -I-. */
4630 if (CPPOPTIONS (pfile)->first_bracket_include != NULL)
4631 search_start = CPPOPTIONS (pfile)->first_bracket_include;
4633 /* If -I- was specified, don't search current dir, only spec'd ones. */
4634 else if (!CPPOPTIONS (pfile)->ignore_srcdir)
4636 cppBuffer *fp = CPPBUFFER (pfile);
4637 /* We have "filename". Figure out directory this source
4638 file is coming from and put it on the front of the list. */
4640 for ( ; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
4645 llassert (fp != NULL);
4649 if (cstring_isDefined (fp->nominal_fname))
4651 nam = cstring_toCharsSafe (fp->nominal_fname);
4653 /* Found a named file. Figure out dir of the file,
4654 and put it in front of the search list. */
4655 dsp[0].next = search_start;
4659 ep = strrchr (nam, CONNECTCHAR);
4661 ep = strrchr (nam, ']');
4662 if (ep == NULL) ep = strrchr (nam, '>');
4663 if (ep == NULL) ep = strrchr (nam, ':');
4664 if (ep != NULL) ep++;
4674 /*@-onlytrans@*/ /* This looks like a memory leak... */
4675 dsp[0].fname = cstring_fromCharsNew (nam); /* evs 2000-07-20: was fromChars */
4679 if (n + INCLUDE_LEN_FUDGE > size_toInt (pfile->max_include_len))
4680 pfile->max_include_len = size_fromInt (n + INCLUDE_LEN_FUDGE);
4684 dsp[0].fname = cstring_undefined; /* Current directory */
4687 dsp[0].got_name_map = 0;
4698 else if (token == CPP_NAME)
4701 * Support '#include xyz' like VAX-C to allow for easy use of all the
4702 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4703 * code from case '<' is repeated here) and generates a warning.
4705 cppReader_warning (pfile,
4706 "VAX-C-style include specification found, use '#include <filename.h>' !");
4708 /* If -I-, start with the first -I dir after the -I-. */
4709 if (CPPOPTIONS (pfile)->first_bracket_include)
4710 search_start = CPPOPTIONS (pfile)->first_bracket_include;
4711 fbeg = pfile->token_buffer + old_written;
4712 fend = cpplib_getPWritten (pfile);
4717 cppReader_error (pfile,
4718 message ("Preprocessor command #%s expects \"FILENAME\" or <FILENAME>",
4721 cppReader_setWritten (pfile, old_written);
4722 cppReader_skipRestOfLine (pfile);
4728 token = get_directive_token (pfile);
4729 if (token != CPP_VSPACE)
4731 cppReader_errorLit (pfile,
4732 cstring_makeLiteralTemp ("Junk at end of #include"));
4734 while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
4736 token = get_directive_token (pfile);
4741 ** For #include_next, skip in the search path
4742 ** past the dir in which the containing file was found.
4747 cppBuffer *fp = CPPBUFFER (pfile);
4749 for (; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
4751 llassert (fp != NULL);
4753 if (fp->fname != NULL)
4755 /* fp->dir is null if the containing file was specified with
4756 an absolute file name. In that case, don't skip anything. */
4757 if (fp->dir == SELF_DIR_DUMMY)
4759 search_start = CPPOPTIONS (pfile)->include;
4761 else if (fp->dir != NULL)
4763 search_start = fp->dir->next;
4775 cppReader_setWritten (pfile, old_written);
4777 flen = size_fromInt (fend - fbeg);
4779 DPRINTF (("fbeg: %s", fbeg));
4783 cppReader_error (pfile,
4784 message ("Empty file name in #%s", keyword->name));
4789 ** Allocate this permanently, because it gets stored in the definitions
4793 fname = cstring_undefined;
4795 /* + 2 above for slash and terminating null. */
4796 /* + 2 added for '.h' on VMS (to support '#include filename') */
4798 /* If specified file name is absolute, just open it. */
4800 if (osd_isConnectChar (*fbeg)
4801 # if defined (WIN32) || defined (OS2)
4802 || (*(fbeg + 1) == ':')
4806 fname = cstring_copyLength (fbeg, flen);
4808 if (redundant_include_p (pfile, fname))
4810 cstring_free (fname);
4814 f = open_include_file (pfile, fname, NULL);
4816 if (f == IMPORT_FOUND)
4818 return 0; /* Already included this file */
4823 /* Search directory path, trying to open the file.
4824 Copy each filename tried into FNAME. */
4826 for (searchptr = search_start; searchptr != NULL;
4827 searchptr = searchptr->next)
4829 if (!cstring_isEmpty (searchptr->fname))
4831 /* The empty string in a search path is ignored.
4832 This makes it possible to turn off entirely
4833 a standard piece of the list. */
4834 if (cstring_isEmpty (searchptr->fname))
4837 fname = cstring_copy (searchptr->fname);
4838 fname = cstring_appendChar (fname, CONNECTCHAR);
4839 DPRINTF (("Here: %s", fname));
4846 fname = cstring_concatLength (fname, fbeg, flen);
4848 DPRINTF (("fname: %s", fname));
4850 /* Win32 directory fix from Kay Buschner. */
4851 #if defined (WIN32) || defined (OS2)
4852 /* Fix all unixdir slashes to win dir slashes */
4853 if (searchptr->fname && (searchptr->fname[0] != 0))
4855 cstring_replaceAll (fname, '/', '\\');
4860 /* Change this 1/2 Unix 1/2 VMS file specification into a
4861 full VMS file specification */
4862 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4863 /* Fix up the filename */
4864 hack_vms_include_specification (fname);
4866 /* This is a normal VMS filespec, so use it unchanged. */
4867 strncpy (fname, fbeg, flen);
4869 /* if it's '#include filename', add the missing .h */
4870 if (strchr (fname,'.') == NULL) {
4871 strcat (fname, ".h");
4875 /* ??? There are currently 3 separate mechanisms for avoiding processing
4876 of redundant include files: #import, #pragma once, and
4877 redundant_include_p. It would be nice if they were unified. */
4879 if (redundant_include_p (pfile, fname))
4881 cstring_free (fname);
4885 DPRINTF (("Trying: %s", fname));
4887 f = open_include_file (pfile, fname, searchptr);
4889 if (f == IMPORT_FOUND)
4891 return 0; /* Already included this file */
4894 else if (f == IMPORT_NOT_FOUND && errno == EACCES)
4896 cppReader_warning (pfile,
4897 message ("Header file %s exists, but is not readable", fname));
4910 /* A file that was not found. */
4911 fname = cstring_copyLength (fbeg, flen);
4913 if (search_start != NULL)
4915 cppReader_error (pfile,
4916 message ("Cannot find include file %s on search path: %x",
4918 searchPath_unparse (search_start)));
4922 cppReader_error (pfile,
4923 message ("No include path in which to find %s", fname));
4928 ** Check to see if this include file is a once-only include file.
4932 struct file_name_list *ptr;
4934 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
4936 if (cstring_equal (ptr->fname, fname))
4938 /* This file was included before. */
4945 /* This is the first time for this file. */
4946 /* Add it to list of files included. */
4948 ptr = (struct file_name_list *) dmalloc (sizeof (*ptr));
4949 ptr->control_macro = NULL;
4950 ptr->c_system_include_path = NULL;
4951 ptr->next = pfile->all_include_files;
4953 ptr->got_name_map = NULL;
4955 DPRINTF (("Including file: %s", fname));
4956 pfile->all_include_files = ptr;
4957 assertSet (pfile->all_include_files);
4960 if (angle_brackets != 0)
4962 pfile->system_include_depth++;
4965 /* Actually process the file */
4966 if (cppReader_pushBuffer (pfile, NULL, 0) == NULL)
4968 cstring_free (fname);
4972 if (finclude (pfile, f, fname, is_system_include (pfile, fname),
4973 searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
4975 output_line_command (pfile, 0, enter_file);
4976 pfile->only_seen_white = 2;
4981 pfile->system_include_depth--;
4984 } /*@=branchstate@*/
4989 /* Return nonzero if there is no need to include file NAME
4990 because it has already been included and it contains a conditional
4991 to make a repeated include do nothing. */
4994 redundant_include_p (cppReader *pfile, cstring name)
4996 struct file_name_list *l = pfile->all_include_files;
4998 for (; l != NULL; l = l->next)
5000 if (cstring_equal (name, l->fname)
5001 && (l->control_macro != NULL)
5002 && (cpphash_lookup (l->control_macro, -1, -1) != NULL))
5011 /* Return nonzero if the given FILENAME is an absolute pathname which
5012 designates a file within one of the known "system" include file
5013 directories. We assume here that if the given FILENAME looks like
5014 it is the name of a file which resides either directly in a "system"
5015 include file directory, or within any subdirectory thereof, then the
5016 given file must be a "system" include file. This function tells us
5017 if we should suppress pedantic errors/warnings for the given FILENAME.
5019 The value is 2 if the file is a C-language system header file
5020 for which C++ should (on most systems) assume `extern "C"'. */
5023 is_system_include (cppReader *pfile, cstring filename)
5025 struct file_name_list *searchptr;
5027 for (searchptr = CPPOPTIONS (pfile)->first_system_include;
5029 searchptr = searchptr->next)
5031 if (!cstring_isEmpty (searchptr->fname))
5033 cstring sys_dir = searchptr->fname;
5034 size_t length = cstring_length (sys_dir);
5036 if (cstring_equalLen (sys_dir, filename, length)
5037 && osd_isConnectChar (cstring_getChar (filename, length)))
5039 if (searchptr->c_system_include_path)
5050 /* Convert a character string literal into a nul-terminated string.
5051 The input string is [IN ... LIMIT).
5052 The result is placed in RESULT. RESULT can be the same as IN.
5053 The value returned in the end of the string written to RESULT,
5054 or NULL on error. */
5056 static /*@null@*/ char *
5057 convert_string (cppReader *pfile, /*@returned@*/ char *result,
5058 char *in, char *limit, int handle_escapes)
5078 /*@switchbreak@*/ break;
5082 char *bpc = (char *) in;
5083 int i = (char) cppReader_parseEscape (pfile, &bpc);
5086 *result++ = (char) c;
5087 /*@switchbreak@*/ break;
5101 * interpret #line command. Remembers previously seen fnames
5102 * in its very own hash table.
5105 /*@constant int FNAME_HASHSIZE@*/
5106 #define FNAME_HASHSIZE 37
5109 do_line (cppReader *pfile, /*@unused@*/ struct directive *keyword)
5111 cppBuffer *ip = cppReader_getBuffer (pfile);
5113 size_t old_written = cpplib_getWritten (pfile);
5114 enum file_change_code file_change = same_file;
5115 enum cpp_token token;
5117 llassert (ip != NULL);
5118 token = get_directive_token (pfile);
5120 if (token != CPP_NUMBER
5121 || !isdigit(pfile->token_buffer[old_written]))
5123 cppReader_errorLit (pfile,
5124 cstring_makeLiteralTemp ("invalid format `#line' command"));
5126 goto bad_line_directive;
5129 /* The Newline at the end of this line remains to be processed.
5130 To put the next line at the specified line number,
5131 we must store a line number now that is one less. */
5132 new_lineno = atoi (pfile->token_buffer + old_written) - 1;
5133 cppReader_setWritten (pfile, old_written);
5135 /* NEW_LINENO is one less than the actual line number here. */
5136 if (cppReader_isPedantic (pfile) && new_lineno < 0)
5137 cppReader_pedwarnLit (pfile,
5138 cstring_makeLiteralTemp ("line number out of range in `#line' command"));
5140 token = get_directive_token (pfile);
5142 if (token == CPP_STRING) {
5143 char *fname = pfile->token_buffer + old_written;
5145 static hashNode fname_table[FNAME_HASHSIZE];
5147 hashNode *hash_bucket;
5150 size_t fname_length;
5152 /* Turn the file name, which is a character string literal,
5153 into a null-terminated string. Do this in place. */
5154 end_name = convert_string (pfile, fname, fname, cpplib_getPWritten (pfile), 1);
5155 if (end_name == NULL)
5157 cppReader_errorLit (pfile,
5158 cstring_makeLiteralTemp ("invalid format `#line' command"));
5159 goto bad_line_directive;
5162 fname_length = size_fromInt (end_name - fname);
5163 num_start = cpplib_getWritten (pfile);
5165 token = get_directive_token (pfile);
5166 if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP) {
5167 p = pfile->token_buffer + num_start;
5168 if (cppReader_isPedantic (pfile))
5169 cppReader_pedwarnLit (pfile,
5170 cstring_makeLiteralTemp ("garbage at end of `#line' command"));
5172 if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
5174 cppReader_errorLit (pfile,
5175 cstring_makeLiteralTemp ("invalid format `#line' command"));
5176 goto bad_line_directive;
5179 file_change = enter_file;
5181 file_change = leave_file;
5183 ip->system_header_p = 1;
5184 else /* if (*p == 4) */
5185 ip->system_header_p = 2;
5187 cppReader_setWritten (pfile, num_start);
5188 token = get_directive_token (pfile);
5189 p = pfile->token_buffer + num_start;
5190 if (token == CPP_NUMBER && p[1] == '\0' && (*p == '3' || *p== '4')) {
5191 ip->system_header_p = *p == 3 ? 1 : 2;
5192 token = get_directive_token (pfile);
5194 if (token != CPP_VSPACE) {
5195 cppReader_errorLit (pfile,
5196 cstring_makeLiteralTemp ("invalid format `#line' command"));
5198 goto bad_line_directive;
5203 &fname_table[cpphash_hashCode (fname, fname_length, FNAME_HASHSIZE)];
5205 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
5207 if (hp->length == fname_length)
5209 llassert (hp->value.cpval != NULL);
5211 if (strncmp (hp->value.cpval, fname, fname_length) == 0)
5213 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
5220 /* Didn't find it; cons up a new one. */
5221 hp = (hashNode) dmalloc (sizeof (*hp));
5224 hp->bucket_hdr = NULL;
5226 hp->name = cstring_undefined;
5227 hp->next = *hash_bucket;
5231 hp->length = fname_length;
5232 hp->value.cpval = dmalloc (sizeof (*hp->value.cpval) * (fname_length + 1));
5233 memcpy (hp->value.cpval, fname, fname_length);
5234 hp->value.cpval[fname_length] = '\0';
5235 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
5238 else if (token != CPP_VSPACE && token != CPP_EOF)
5240 cppReader_errorLit (pfile,
5241 cstring_makeLiteralTemp ("invalid format `#line' command"));
5242 goto bad_line_directive;
5249 ip->lineno = new_lineno;
5251 cppReader_skipRestOfLine (pfile);
5252 cppReader_setWritten (pfile, old_written);
5253 output_line_command (pfile, 0, file_change);
5258 * remove the definition of a symbol from the symbol table.
5259 * according to un*x /lib/cpp, it is not an error to undef
5260 * something that has no definitions, so it isn't one here either.
5264 do_undef (cppReader *pfile, struct directive *keyword, char *buf, char *limit)
5269 char *orig_buf = buf;
5271 SKIP_WHITE_SPACE (buf);
5273 sym_length = cppReader_checkMacroName (pfile, buf, cstring_makeLiteralTemp ("macro"));
5275 while ((hp = cpphash_lookup (buf, size_toInt (sym_length), -1)) != NULL)
5277 /* If we are generating additional info for debugging (with -g) we
5278 need to pass through all effective #undef commands. */
5279 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
5281 pass_thru_directive (orig_buf, limit, pfile, keyword);
5284 if (hp->type != T_MACRO)
5286 cppReader_warning (pfile,
5287 message ("Undefining preprocessor builtin: %s",
5291 cppReader_deleteMacro (hp);
5294 if (cppReader_isPedantic (pfile)) {
5296 SKIP_WHITE_SPACE (buf);
5299 cppReader_pedwarnLit (pfile,
5300 cstring_makeLiteralTemp ("garbage after `#undef' directive"));
5309 * Report an error detected by the program we are processing.
5310 * Use the text of the line in the error message.
5311 * (We use error because it prints the filename & line#.)
5315 do_error (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5316 char *buf, char *limit)
5318 size_t length = size_fromInt (limit - buf);
5319 cstring copy = cstring_copyLength (buf, length);
5320 cstring adv = cstring_advanceWhiteSpace (copy);
5322 cppReader_error (pfile, message ("#error %s", adv));
5323 cstring_free (copy);
5328 * Report a warning detected by the program we are processing.
5329 * Use the text of the line in the warning message, then continue.
5330 * (We use error because it prints the filename & line#.)
5334 do_warning (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5335 char *buf, char *limit)
5337 size_t length = size_fromInt (limit - buf);
5338 cstring copy = cstring_copyLength (buf, length);
5339 cstring adv = cstring_advanceWhiteSpace (copy);
5340 cppReader_warning (pfile, message ("#warning %s", adv));
5341 cstring_free (copy);
5346 /* #ident has already been copied to the output file, so just ignore it. */
5349 do_ident (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5350 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5352 /* Allow #ident in system headers, since that's not user's fault. */
5353 if (cppReader_isPedantic (pfile)
5354 && !cppReader_getBufferSafe (pfile)->system_header_p)
5355 cppReader_pedwarnLit (pfile,
5356 cstring_makeLiteralTemp ("ANSI C does not allow `#ident'"));
5358 /* Leave rest of line to be read by later calls to cpplib_getToken. */
5363 /* #pragma and its argument line have already been copied to the output file.
5364 Just check for some recognized pragmas that need validation here. */
5367 do_pragma (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5368 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5370 while (*buf == ' ' || *buf == '\t')
5375 if (!strncmp (buf, "implementation", 14)) {
5376 /* Be quiet about `#pragma implementation' for a file only if it hasn't
5377 been included yet. */
5378 struct file_name_list *ptr;
5379 char *p = buf + 14, *fname, *inc_fname;
5381 SKIP_WHITE_SPACE (p);
5382 if (*p == '\n' || *p != '\"')
5386 p = (char *) strchr (fname, '\"');
5387 fname_len = p != NULL ? size_fromInt (p - fname) : mstring_length (fname);
5389 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
5391 inc_fname = (char *) strrchr (cstring_toCharsSafe (ptr->fname), CONNECTCHAR);
5392 inc_fname = (inc_fname != NULL)
5393 ? inc_fname + 1 : cstring_toCharsSafe (ptr->fname);
5395 if ((inc_fname != NULL)
5396 && (strncmp (inc_fname, fname, fname_len) == 0))
5398 cpp_setLocation (pfile);
5400 ppllerror (message ("`#pragma implementation' for `%s' appears "
5401 "after file is included",
5402 cstring_fromChars (fname)));
5411 * handle #if command by
5412 * 1) inserting special `defined' keyword into the hash table
5413 * that gets turned into 0 or 1 by special_symbol (thus,
5414 * if the luser has a symbol called `defined' already, it won't
5415 * work inside the #if command)
5416 * 2) rescan the input into a temporary output buffer
5417 * 3) pass the output buffer to the yacc parser and collect a value
5418 * 4) clean up the mess left from steps 1 and 2.
5419 * 5) call conditional_skip to skip til the next #endif (etc.),
5420 * or not, depending on the value from step 3.
5424 do_if (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5425 char *buf, char *limit)
5427 HOST_WIDE_INT value;
5428 DPRINTF (("Do if: %s", buf));
5429 value = eval_if_expression (pfile, buf, limit - buf);
5430 conditional_skip (pfile, value == 0, T_IF, NULL);
5435 * handle a #elif directive by not changing if_stack either.
5436 * see the comment above do_else.
5439 static int do_elif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5440 char *buf, char *limit)
5442 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5444 cppReader_errorLit (pfile,
5445 cstring_makeLiteralTemp ("Preprocessor command #elif is not within a conditional"));
5450 llassert (pfile->if_stack != NULL);
5452 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
5454 cppReader_errorLit (pfile,
5455 cstring_makeLiteralTemp ("`#elif' after `#else'"));
5457 if (pfile->if_stack->fname != NULL
5458 && cppReader_getBufferSafe (pfile)->fname != NULL
5459 && !cstring_equal (pfile->if_stack->fname,
5460 cppReader_getBufferSafe (pfile)->nominal_fname))
5461 fprintf (stderr, ", file %s", cstring_toCharsSafe (pfile->if_stack->fname));
5462 fprintf (stderr, ")\n");
5464 pfile->if_stack->type = T_ELIF;
5467 if (pfile->if_stack->if_succeeded)
5469 skip_if_group (pfile, 0);
5473 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
5475 skip_if_group (pfile, 0);
5478 ++pfile->if_stack->if_succeeded; /* continue processing input */
5479 output_line_command (pfile, 1, same_file);
5487 * evaluate a #if expression in BUF, of length LENGTH,
5488 * then parse the result as a C expression and return the value as an int.
5491 static HOST_WIDE_INT
5492 eval_if_expression (cppReader *pfile,
5493 /*@unused@*/ char *buf,
5494 /*@unused@*/ int length)
5496 hashNode save_defined;
5497 HOST_WIDE_INT value;
5498 size_t old_written = cpplib_getWritten (pfile);
5500 DPRINTF (("Saving defined..."));
5501 save_defined = cpphash_install ("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
5502 pfile->pcp_inside_if = 1;
5504 value = cppReader_parseExpression (pfile);
5505 pfile->pcp_inside_if = 0;
5507 /* Clean up special symbol */
5508 DPRINTF (("Removing defined..."));
5509 cppReader_deleteMacro (save_defined);
5510 cppReader_setWritten (pfile, old_written); /* Pop */
5516 * routine to handle ifdef/ifndef. Try to look up the symbol,
5517 * then do or don't skip to the #endif/#else/#elif depending
5518 * on what directive is actually being processed.
5522 do_xifdef (cppReader *pfile, struct directive *keyword,
5523 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
5526 cppBuffer *ip = cppReader_getBufferSafe (pfile);
5528 size_t ident_length;
5529 enum cpp_token token;
5530 int start_of_file = 0;
5531 char *control_macro = 0;
5532 size_t old_written = cpplib_getWritten (pfile);
5534 DPRINTF (("do xifdef: %d",
5535 keyword->type == T_IFNDEF));
5537 /* Detect a #ifndef at start of file (not counting comments). */
5538 if (cstring_isDefined (ip->fname) && keyword->type == T_IFNDEF)
5540 start_of_file = pfile->only_seen_white == 2;
5543 pfile->no_macro_expand++;
5544 token = get_directive_token (pfile);
5545 pfile->no_macro_expand--;
5547 ident = pfile->token_buffer + old_written;
5548 DPRINTF (("Ident: %s", ident));
5550 ident_length = cpplib_getWritten (pfile) - old_written;
5551 cppReader_setWritten (pfile, old_written); /* Pop */
5553 if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
5555 skip = (keyword->type == T_IFDEF);
5556 if (! cppReader_isTraditional (pfile))
5558 cppReader_pedwarn (pfile,
5559 message ("`#%s' with no argument", keyword->name));
5562 else if (token == CPP_NAME)
5564 hashNode hp = cpphash_lookup (ident, size_toInt (ident_length), -1);
5566 skip = (keyword->type == T_IFDEF) ? (hp == NULL) : (hp != NULL);
5568 DPRINTF (("hp null: %d / %d / %d", hp == NULL, keyword->type == T_IFNDEF, skip));
5570 if (start_of_file && !skip)
5572 DPRINTF (("Not skipping!"));
5573 control_macro = (char *) dmalloc (ident_length + 1);
5574 memcpy (control_macro, ident, ident_length + 1);
5579 skip = (keyword->type == T_IFDEF);
5580 if (! cppReader_isTraditional (pfile))
5582 cppReader_error (pfile,
5583 message ("`#%s' with invalid argument", keyword->name));
5587 if (!cppReader_isTraditional (pfile))
5590 cppSkipHspace (pfile);
5591 c = cppReader_peekC (pfile);
5592 if (c != EOF && c != '\n')
5594 cppReader_pedwarn (pfile,
5595 message ("garbage at end of `#%s' argument", keyword->name));
5599 cppReader_skipRestOfLine (pfile);
5601 DPRINTF (("Conditional skip: %d", skip));
5602 conditional_skip (pfile, skip, T_IF, control_macro);
5606 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
5607 If this is a #ifndef starting at the beginning of a file,
5608 CONTROL_MACRO is the macro name tested by the #ifndef.
5609 Otherwise, CONTROL_MACRO is 0. */
5612 conditional_skip (cppReader *pfile, int skip,
5613 enum node_type type,
5614 /*@dependent@*/ char *control_macro)
5616 cppIfStackFrame *temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
5618 temp->fname = cppReader_getBufferSafe (pfile)->nominal_fname;
5619 temp->next = pfile->if_stack;
5620 temp->control_macro = control_macro;
5622 temp->if_succeeded = 0;
5624 pfile->if_stack = temp;
5625 pfile->if_stack->type = type;
5629 skip_if_group (pfile, 0);
5634 ++pfile->if_stack->if_succeeded;
5635 output_line_command (pfile, 1, same_file);
5640 * skip to #endif, #else, or #elif. adjust line numbers, etc.
5641 * leaves input ptr at the sharp sign found.
5642 * If ANY is nonzero, return at next directive of any sort.
5646 skip_if_group (cppReader *pfile, int any)
5649 struct directive *kt;
5650 cppIfStackFrame *save_if_stack = pfile->if_stack; /* don't pop past here */
5651 register int ident_length;
5653 struct parse_marker line_start_mark;
5655 parseSetMark (&line_start_mark, pfile);
5657 if (CPPOPTIONS (pfile)->output_conditionals) {
5658 static char failed[] = "#failed\n";
5659 cppReader_puts (pfile, failed, sizeof(failed)-1);
5661 output_line_command (pfile, 1, same_file);
5665 if (CPPOPTIONS (pfile)->output_conditionals)
5667 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
5670 llassert (pbuf->buf != NULL);
5672 start_line = pbuf->buf + line_start_mark.position;
5673 cppReader_puts (pfile, start_line, size_fromInt (pbuf->cur - start_line));
5676 parseMoveMark (&line_start_mark, pfile);
5678 if (!cppReader_isTraditional (pfile))
5680 cppSkipHspace (pfile);
5683 c = cppReader_getC (pfile);
5686 size_t old_written = cpplib_getWritten (pfile);
5687 cppSkipHspace (pfile);
5689 parse_name (pfile, cppReader_getC (pfile));
5690 ident_length = size_toInt (cpplib_getWritten (pfile) - old_written);
5691 ident = pfile->token_buffer + old_written;
5692 pfile->limit = ident;
5694 for (kt = directive_table; kt->length >= 0; kt++)
5696 cppIfStackFrame *temp;
5697 if (ident_length == kt->length
5698 && cstring_equalPrefix (kt->name, cstring_fromChars (ident)))
5700 /* If we are asked to return on next directive, do so now. */
5711 temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
5712 temp->next = pfile->if_stack;
5713 temp->fname = cppReader_getBufferSafe (pfile)->nominal_fname;
5714 temp->type = kt->type;
5716 temp->if_succeeded = 0;
5717 temp->control_macro = NULL;
5719 pfile->if_stack = temp;
5720 /*@switchbreak@*/ break;
5723 if (cppReader_isPedantic (pfile) && pfile->if_stack != save_if_stack)
5724 validate_else (pfile,
5725 cstring_makeLiteralTemp (kt->type == T_ELSE ? "#else" : "#endif"));
5728 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5730 cppReader_error (pfile,
5731 message ("Preprocessor command #%s is not within a conditional", kt->name));
5732 /*@switchbreak@*/ break;
5734 else if (pfile->if_stack == save_if_stack)
5736 goto done; /* found what we came for */
5743 if (kt->type != T_ENDIF)
5745 llassert (pfile->if_stack != NULL);
5747 if (pfile->if_stack->type == T_ELSE)
5749 cppReader_errorLit (pfile,
5750 cstring_makeLiteralTemp ("`#else' or `#elif' after `#else'"));
5753 pfile->if_stack->type = kt->type;
5754 /*@switchbreak@*/ break;
5757 temp = pfile->if_stack;
5758 llassert (temp != NULL);
5759 pfile->if_stack = temp->next;
5761 /*@switchbreak@*/ break;
5764 #if defined (OS2) && defined (__IBMC__)
5765 /* Dummy code to eleminate optimization problems with icc */
5774 /* Don't let erroneous code go by. */
5776 if (kt->length < 0 && !CPPOPTIONS (pfile)->lang_asm
5777 && cppReader_isPedantic (pfile))
5779 cppReader_pedwarnLit (pfile,
5780 cstring_makeLiteralTemp ("Invalid preprocessor directive name"));
5784 c = cppReader_getC (pfile);
5786 /* We're in the middle of a line. Skip the rest of it. */
5794 case '/': /* possible comment */
5795 c = skip_comment (pfile, NULL);
5798 /*@switchbreak@*/ break;
5801 cppReader_forward (pfile, -1);
5802 old = cpplib_getWritten (pfile);
5803 (void) cpplib_getToken (pfile);
5804 cppReader_setWritten (pfile, old);
5805 /*@switchbreak@*/ break;
5807 /* Char after backslash loses its special meaning. */
5808 if (cppReader_peekC (pfile) == '\n')
5810 cppReader_forward (pfile, 1);
5813 /*@switchbreak@*/ break;
5817 c = cppReader_getC (pfile);
5820 if (CPPOPTIONS (pfile)->output_conditionals) {
5821 static char end_failed[] = "#endfailed\n";
5822 cppReader_puts (pfile, end_failed, sizeof(end_failed)-1);
5825 pfile->only_seen_white = 1;
5827 parseGotoMark (&line_start_mark, pfile);
5828 parseClearMark (&line_start_mark);
5832 * handle a #else directive. Do this by just continuing processing
5833 * without changing if_stack ; this is so that the error message
5834 * for missing #endif's etc. will point to the original #if. It
5835 * is possible that something different would be better.
5839 do_else (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5840 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5842 if (cppReader_isPedantic (pfile))
5844 validate_else (pfile, cstring_makeLiteralTemp ("#else"));
5847 cppReader_skipRestOfLine (pfile);
5849 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack) {
5850 cppReader_errorLit (pfile,
5851 cstring_makeLiteralTemp ("Preprocessor command #else is not within a conditional"));
5854 /* #ifndef can't have its special treatment for containing the whole file
5855 if it has a #else clause. */
5857 llassert (pfile->if_stack != NULL);
5859 pfile->if_stack->control_macro = 0;
5861 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
5863 cpp_setLocation (pfile);
5864 genppllerrorhint (FLG_PREPROC,
5865 message ("Pre-processor directive #else after #else"),
5866 message ("%q: Location of match",
5867 fileloc_unparseRaw (pfile->if_stack->fname,
5868 pfile->if_stack->lineno)));
5871 pfile->if_stack->type = T_ELSE;
5874 if (pfile->if_stack->if_succeeded)
5875 skip_if_group (pfile, 0);
5877 ++pfile->if_stack->if_succeeded; /* continue processing input */
5878 output_line_command (pfile, 1, same_file);
5885 * unstack after #endif command
5889 do_endif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5890 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5892 if (cppReader_isPedantic (pfile))
5894 validate_else (pfile, cstring_makeLiteralTemp ("#endif"));
5897 cppReader_skipRestOfLine (pfile);
5899 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5901 cppReader_errorLit (pfile, cstring_makeLiteralTemp ("Unbalanced #endif"));
5905 cppIfStackFrame *temp = pfile->if_stack;
5907 llassert (temp != NULL);
5909 pfile->if_stack = temp->next;
5910 if (temp->control_macro != 0)
5912 /* This #endif matched a #ifndef at the start of the file.
5913 See if it is at the end of the file. */
5914 struct parse_marker start_mark;
5917 parseSetMark (&start_mark, pfile);
5921 cppSkipHspace (pfile);
5922 c = cppReader_getC (pfile);
5928 parseGotoMark (&start_mark, pfile);
5929 parseClearMark (&start_mark);
5933 /* If we get here, this #endif ends a #ifndef
5934 that contains all of the file (aside from whitespace).
5935 Arrange not to include the file again
5936 if the macro that was tested is defined.
5938 Do not do this for the top-level file in a -include or any
5939 file in a -imacros. */
5940 struct file_name_list *ifile = pfile->all_include_files;
5942 for ( ; ifile != NULL; ifile = ifile->next)
5944 if (cstring_equal (ifile->fname, cppReader_getBufferSafe (pfile)->fname))
5946 ifile->control_macro = temp->control_macro;
5954 output_line_command (pfile, 1, same_file);
5959 /* When an #else or #endif is found while skipping failed conditional,
5960 if -pedantic was specified, this is called to warn about text after
5961 the command name. P points to the first char after the command name. */
5964 validate_else (cppReader *pfile, cstring directive)
5967 cppSkipHspace (pfile);
5968 c = cppReader_peekC (pfile);
5969 if (c != EOF && c != '\n')
5971 cppReader_pedwarn (pfile,
5972 message ("text following `%s' violates ANSI standard", directive));
5977 ** Get the next token, and add it to the text in pfile->token_buffer.
5978 ** Return the kind of token we got.
5982 cpplib_getToken (cppReader *pfile)
5984 return cpplib_getTokenAux (pfile, FALSE);
5988 cpplib_getTokenForceExpand (cppReader *pfile)
5990 return cpplib_getTokenAux (pfile, TRUE);
5994 cpplib_getTokenAux (cppReader *pfile, bool forceExpand)
5997 size_t old_written = 0;
5998 int start_line, start_column;
5999 enum cpp_token token;
6000 struct cppOptions *opts = CPPOPTIONS (pfile);
6001 cppReader_getBufferSafe (pfile)->prev = cppReader_getBufferSafe (pfile)->cur;
6004 c = cppReader_getC (pfile);
6005 DPRINTF (("Get next token: %c", c));
6010 if (cppReader_getBufferSafe (pfile)->seen_eof)
6012 cppBuffer *buf = cppReader_popBuffer (pfile);
6014 if (buf != cppReader_nullBuffer (pfile))
6025 cppBuffer *next_buf = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6026 cppReader_getBufferSafe (pfile)->seen_eof = 1;
6028 if (cstring_isDefined (cppReader_getBufferSafe (pfile)->nominal_fname)
6029 && next_buf != cppReader_nullBuffer (pfile))
6031 /* We're about to return from an #include file.
6032 Emit #line information now (as part of the CPP_POP) result.
6033 But the #line refers to the file we will pop to. */
6034 cppBuffer *cur_buffer = CPPBUFFER (pfile);
6035 CPPBUFFER (pfile) = next_buf;
6036 pfile->input_stack_listing_current = 0;
6037 output_line_command (pfile, 0, leave_file);
6038 CPPBUFFER (pfile) = cur_buffer;
6046 struct parse_marker start_mark;
6051 if (cppReader_peekC (pfile) == '=')
6056 if (opts->put_out_comments)
6058 parseSetMark (&start_mark, pfile);
6062 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile),
6063 &start_line, &start_column);
6064 c = skip_comment (pfile, &newlines);
6065 DPRINTF (("c = %c", c));
6066 if (opts->put_out_comments && (c == '/' || c == EOF))
6068 assertSet (&start_mark);
6069 parseClearMark (&start_mark);
6076 cppReader_errorWithLine (pfile, start_line, start_column,
6077 cstring_makeLiteral ("Unterminated comment"));
6080 c = '/'; /* Initial letter of comment. */
6082 /* Comments are equivalent to spaces.
6083 For -traditional, a comment is equivalent to nothing. */
6085 if (opts->put_out_comments)
6089 assertSet (&start_mark);
6090 res = cpp_handleComment (pfile, &start_mark);
6091 pfile->lineno += newlines;
6094 else if (cppReader_isTraditional (pfile))
6100 cpplib_reserve(pfile, 1);
6101 cppReader_putCharQ (pfile, ' ');
6106 if (!pfile->only_seen_white)
6111 if (cppReader_handleDirective (pfile))
6113 return CPP_DIRECTIVE;
6116 pfile->only_seen_white = 0;
6121 /* A single quoted string is treated like a double -- some
6122 programs (e.g., troff) are perverse this way */
6123 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile),
6124 &start_line, &start_column);
6125 old_written = cpplib_getWritten (pfile);
6127 DPRINTF (("Reading string: %c", c));
6128 cppReader_putChar (pfile, c);
6132 ** Because of ISO8859-1 characters in string literals, we need a special test here.
6135 if (cppReader_reachedEOF (pfile))
6138 DPRINTF (("Matches EOF!"));
6139 if (cppBuffer_isMacro (CPPBUFFER (pfile)))
6141 /* try harder: this string crosses a macro expansion
6142 boundary. This can happen naturally if -traditional.
6143 Otherwise, only -D can make a macro with an unmatched
6146 = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6147 (*cppReader_getBufferSafe (pfile)->cleanup)
6148 (cppReader_getBufferSafe (pfile), pfile);
6149 CPPBUFFER (pfile) = next_buf;
6153 if (!cppReader_isTraditional (pfile))
6155 cpp_setLocation (pfile);
6157 setLine (long_toInt (start_line));
6158 setColumn (long_toInt (start_column));
6160 if (pfile->multiline_string_line != long_toInt (start_line)
6161 && pfile->multiline_string_line != 0)
6165 message ("Unterminated string or character constant"),
6166 message ("%q: Possible real start of unterminated constant",
6168 (fileloc_filename (g_currentloc),
6169 pfile->multiline_string_line)));
6170 pfile->multiline_string_line = 0;
6176 message ("Unterminated string or character constant"));
6179 /*@loopbreak@*/ break;
6183 int cc = cppReader_getC (pfile);
6184 DPRINTF (("cc: %c [%d] [%d]", cc, cc, EOF));
6185 DPRINTF (("putting char: %c", cc));
6186 cppReader_putChar (pfile, cc);
6190 /* Traditionally, end of line ends a string constant with
6191 no error. So exit the loop and record the new line. */
6192 if (cppReader_isTraditional (pfile))
6198 if (cppReader_isPedantic (pfile)
6199 && pfile->multiline_string_line == 0)
6201 cppReader_pedwarnWithLine
6202 (pfile, long_toInt (start_line),
6203 long_toInt (start_column),
6204 cstring_makeLiteral ("String constant runs past end of line"));
6206 if (pfile->multiline_string_line == 0)
6208 pfile->multiline_string_line = start_line;
6211 /*@switchbreak@*/ break;
6214 cc = cppReader_getC (pfile);
6217 /* Backslash newline is replaced by nothing at all. */
6218 pfile->lineno++; /* 2003-11-03: AMiller suggested adding this, but
6219 its not clear why it is needed. */
6220 cppReader_adjustWritten (pfile, -1);
6225 /* ANSI stupidly requires that in \\ the second \
6226 is *not* prevented from combining with a newline. */
6229 cppReader_putChar (pfile, cc);
6231 /*@switchbreak@*/ break;
6237 /*@switchbreak@*/ break;
6242 pfile->lineno += count_newlines (pfile->token_buffer + old_written,
6243 cpplib_getPWritten (pfile));
6244 pfile->only_seen_white = 0;
6245 return c == '\'' ? CPP_CHAR : CPP_STRING;
6248 if (!opts->dollars_in_ident)
6253 if (opts->cplusplus && cppReader_peekC (pfile) == ':')
6261 c2 = cppReader_peekC (pfile);
6262 if (c2 == c || c2 == '=')
6272 if (cppReader_peekC (pfile) == '=')
6278 c2 = cppReader_peekC (pfile);
6279 if (c2 == '-' && opts->chill)
6281 /* Chill style comment */
6282 if (opts->put_out_comments)
6284 parseSetMark (&start_mark, pfile);
6287 cppReader_forward (pfile, 1); /* Skip second '-'. */
6291 c = cppReader_getC (pfile);
6293 /*@loopbreak@*/ break;
6296 /* Don't consider final '\n' to be part of comment. */
6297 cppReader_forward (pfile, -1);
6298 /*@loopbreak@*/ break;
6302 goto return_comment;
6304 if (c2 == '-' || c2 == '=' || c2 == '>')
6309 if (pfile->parsing_include_directive)
6313 cppReader_putChar (pfile, c);
6315 /*@loopbreak@*/ break;
6316 c = cppReader_getC (pfile);
6318 if (c == '\n' || c == EOF)
6320 cppReader_errorLit (pfile,
6321 cstring_makeLiteralTemp ("Missing '>' in \"#include <FILENAME>\""));
6322 /*@loopbreak@*/ break;
6330 c2 = cppReader_peekC (pfile);
6335 cppReader_forward (pfile, 1);
6336 cpplib_reserve (pfile, 4);
6337 cppReader_putChar (pfile, c);
6338 cppReader_putChar (pfile, c2);
6340 c3 = cppReader_peekC (pfile);
6342 cppReader_putCharQ (pfile, cppReader_getC (pfile));
6343 cppReader_nullTerminateQ (pfile);
6344 pfile->only_seen_white = 0;
6348 DPRINTF (("Macro @!"));
6349 if (cppReader_getBufferSafe (pfile)->has_escapes)
6351 c = cppReader_getC (pfile);
6352 DPRINTF (("got c: %c", c));
6355 if (pfile->output_escapes)
6356 cppReader_puts (pfile, "@-", 2);
6357 parse_name (pfile, cppReader_getC (pfile));
6360 else if (is_space [c])
6362 cpplib_reserve (pfile, 2);
6363 if (pfile->output_escapes)
6364 cppReader_putCharQ (pfile, '@');
6365 cppReader_putCharQ (pfile, c);
6373 if (pfile->output_escapes)
6375 cppReader_puts (pfile, "@@", 2);
6381 c2 = cppReader_peekC (pfile);
6384 cpplib_reserve(pfile, 2);
6385 cppReader_putCharQ (pfile, '.');
6386 c = cppReader_getC (pfile);
6390 /* FIXME - misses the case "..\\\n." */
6391 if (c2 == '.' && cpp_peekN (pfile, 1) == '.')
6393 cpplib_reserve(pfile, 4);
6394 cppReader_putCharQ (pfile, '.');
6395 cppReader_putCharQ (pfile, '.');
6396 cppReader_putCharQ (pfile, '.');
6397 cppReader_forward (pfile, 2);
6398 cppReader_nullTerminateQ (pfile);
6399 pfile->only_seen_white = 0;
6405 pfile->only_seen_white = 0;
6406 op2any: /* jumped to for \ continuations */
6407 cpplib_reserve(pfile, 3);
6408 cppReader_putCharQ (pfile, c);
6410 /* evans 2003-08-24: This is a hack to fix line output for \
6411 continuations. Someday I really should get a decent pre-processor!
6415 (void) cppReader_getC (pfile); /* skip the newline to avoid extra lines */
6417 cppReader_putCharQ (pfile, cppReader_getC (pfile));
6420 cppReader_nullTerminateQ (pfile);
6425 c2 = cppReader_peekC (pfile);
6426 if ((c2 == '\'' || c2 == '\"') && !cppReader_isTraditional (pfile))
6428 cppReader_putChar (pfile, c);
6429 c = cppReader_getC (pfile);
6434 case '0': case '1': case '2': case '3': case '4':
6435 case '5': case '6': case '7': case '8': case '9':
6440 cpplib_reserve (pfile, 2);
6441 cppReader_putCharQ (pfile, c);
6443 c = cppReader_peekC (pfile);
6445 /*@loopbreak@*/ break;
6446 if (!is_idchar[c] && c != '.'
6447 && ((c2 != 'e' && c2 != 'E'
6448 && ((c2 != 'p' && c2 != 'P') || cppReader_isC89 (pfile)))
6449 || (c != '+' && c != '-')))
6450 /*@loopbreak@*/ break;
6451 cppReader_forward (pfile, 1);
6455 cppReader_nullTerminateQ (pfile);
6456 pfile->only_seen_white = 0;
6459 case 'b': case 'c': case 'd': case 'h': case 'o':
6460 case 'B': case 'C': case 'D': case 'H': case 'O':
6461 if (opts->chill && cppReader_peekC (pfile) == '\'')
6463 pfile->only_seen_white = 0;
6464 cpplib_reserve (pfile, 2);
6465 cppReader_putCharQ (pfile, c);
6466 cppReader_putCharQ (pfile, '\'');
6467 cppReader_forward (pfile, 1);
6470 c = cppReader_getC (pfile);
6472 goto chill_number_eof;
6475 if (c == '\\' && cppReader_peekC (pfile) == '\n')
6477 cppReader_forward (pfile, 2);
6480 /*@loopbreak@*/ break;
6482 cppReader_putChar (pfile, c);
6486 cpplib_reserve (pfile, 2);
6487 cppReader_putCharQ (pfile, c);
6488 cppReader_nullTerminateQ (pfile);
6493 cppReader_forward (pfile, -1);
6495 cppReader_nullTerminate (pfile);
6502 case 'a': case 'e': case 'f': case 'g': case 'i': case 'j':
6503 case 'k': case 'l': case 'm': case 'n': case 'p': case 'q':
6504 case 'r': case 's': case 't': case 'u': case 'v': case 'w':
6505 case 'x': case 'y': case 'z':
6506 case 'A': case 'E': case 'F': case 'G': case 'I': case 'J':
6507 case 'K': case 'M': case 'N': case 'P': case 'Q': case 'R':
6508 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
6514 size_t before_name_written = cpplib_getWritten (pfile);
6516 parse_name (pfile, c);
6517 pfile->only_seen_white = 0;
6519 if (pfile->no_macro_expand)
6521 DPRINTF (("Not expanding: %s", pfile->token_buffer));
6525 ident = pfile->token_buffer + before_name_written;
6526 DPRINTF (("Ident: %s", ident));
6528 ident_len = size_fromInt ((cpplib_getPWritten (pfile)) - ident);
6530 hp = cpphash_lookupExpand (ident, size_toInt (ident_len), -1, forceExpand);
6534 DPRINTF (("No expand: %s %d", ident, ident_len));
6538 if (hp->type == T_DISABLED)
6540 DPRINTF (("Disabled!"));
6542 if (pfile->output_escapes)
6543 { /* Return "@-IDENT", followed by '\0'. */
6545 cpplib_reserve (pfile, 3);
6546 ident = pfile->token_buffer + before_name_written;
6547 cppReader_adjustWritten (pfile, 2);
6549 for (i = size_toInt (ident_len); i >= 0; i--)
6551 ident[i+2] = ident[i];
6561 ** If macro wants an arglist, verify that a '(' follows.
6562 ** first skip all whitespace, copying it to the output
6563 ** after the macro name. Then, if there is no '(',
6564 ** decide this is not a macro call and leave things that way.
6567 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
6569 struct parse_marker macro_mark;
6572 DPRINTF (("Arglist macro!"));
6575 ** evans 2002-07-03: Moved this here (from below).
6576 ** This bug caused necessary whitespace to be lost
6577 ** when parsing parameterized macros without parameters.
6580 parseSetMark (¯o_mark, pfile);
6582 while (cppBuffer_isMacro (CPPBUFFER (pfile)))
6584 cppBuffer *next_buf;
6585 cppSkipHspace (pfile);
6586 if (cppReader_peekC (pfile) != EOF)
6588 DPRINTF (("Peeking!"));
6589 /*@loopbreak@*/ break;
6592 next_buf = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6593 (*cppReader_getBufferSafe (pfile)->cleanup) (cppReader_getBufferSafe (pfile), pfile);
6594 CPPBUFFER (pfile) = next_buf;
6597 /* parseSetMark (¯o_mark, pfile); */
6601 cppSkipHspace (pfile);
6602 c = cppReader_peekC (pfile);
6603 DPRINTF (("c: %c", c));
6604 is_macro_call = c == '(';
6606 /*@loopbreak@*/ break;
6607 cppReader_forward (pfile, 1);
6612 parseGotoMark (¯o_mark, pfile);
6615 parseClearMark (¯o_mark);
6619 DPRINTF (("not macro call!"));
6624 /* This is now known to be a macro call. */
6626 /* it might not actually be a macro. */
6627 if (hp->type != T_MACRO)
6632 cppReader_setWritten (pfile, before_name_written);
6633 special_symbol (hp, pfile);
6634 xbuf_len = cpplib_getWritten (pfile) - before_name_written;
6635 xbuf = (char *) dmalloc (xbuf_len + 1);
6636 cppReader_setWritten (pfile, before_name_written);
6637 memcpy (xbuf, cpplib_getPWritten (pfile), xbuf_len + 1);
6638 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
6643 ** Expand the macro, reading arguments as needed,
6644 ** and push the expansion on the input stack.
6647 cpplib_macroExpand (pfile, hp);
6648 cppReader_setWritten (pfile, before_name_written);
6651 /* An extra "@ " is added to the end of a macro expansion
6652 to prevent accidental token pasting. We prefer to avoid
6653 unneeded extra spaces (for the sake of cpp-using tools like
6654 imake). Here we remove the space if it is safe to do so. */
6656 llassert (pfile->buffer->rlimit != NULL);
6658 if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
6659 && pfile->buffer->rlimit[-2] == '@'
6660 && pfile->buffer->rlimit[-1] == ' ')
6662 int c1 = pfile->buffer->rlimit[-3];
6663 int cl2 = cpplib_bufPeek (cppBuffer_prevBuffer (CPPBUFFER (pfile)));
6665 if (cl2 == EOF || !unsafe_chars ((char) c1, (char) cl2))
6666 pfile->buffer->rlimit -= 2;
6672 case ' ': case '\t': case '\v': case '\r':
6675 cppReader_putChar (pfile, c);
6676 c = cppReader_peekC (pfile);
6677 if (c == EOF || !is_hor_space[c])
6678 /*@loopbreak@*/ break;
6679 cppReader_forward (pfile, 1);
6684 c2 = cppReader_peekC (pfile);
6685 /* allow other stuff here if a flag is set? */
6686 DPRINTF (("Got continuation!"));
6693 cppReader_putChar (pfile, c);
6694 if (pfile->only_seen_white == 0)
6695 pfile->only_seen_white = 1;
6697 output_line_command (pfile, 1, same_file);
6700 case '(': token = CPP_LPAREN; goto char1;
6701 case ')': token = CPP_RPAREN; goto char1;
6702 case '{': token = CPP_LBRACE; goto char1;
6703 case '}': token = CPP_RBRACE; goto char1;
6704 case ',': token = CPP_COMMA; goto char1;
6705 case ';': token = CPP_SEMICOLON; goto char1;
6711 pfile->only_seen_white = 0;
6712 cppReader_putChar (pfile, c);
6721 /* Parse an identifier starting with C. */
6724 parse_name (cppReader *pfile, int c)
6730 if (c == '\\' && cppReader_peekC (pfile) == '\n')
6732 cppReader_forward (pfile, 2);
6736 cppReader_forward (pfile, -1);
6740 if (c == '$' && cppReader_isPedantic (pfile))
6742 cppReader_pedwarnLit (pfile,
6743 cstring_makeLiteralTemp ("`$' in identifier"));
6746 cpplib_reserve(pfile, 2); /* One more for final NUL. */
6747 cppReader_putCharQ (pfile, c);
6748 c = cppReader_getC (pfile);
6754 cppReader_nullTerminateQ (pfile);
6757 /* The file_name_map structure holds a mapping of file names for a
6758 particular directory. This mapping is read from the file named
6759 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
6760 map filenames on a file system with severe filename restrictions,
6761 such as DOS. The format of the file name map file is just a series
6762 of lines with two tokens on each line. The first token is the name
6763 to map, and the second token is the actual name to use. */
6765 struct file_name_map
6767 struct file_name_map *map_next;
6772 /*@constant observer char *FILE_NAME_MAP_FILE*/
6773 #define FILE_NAME_MAP_FILE "header.gcc"
6775 /* Read a space delimited string of unlimited length from a stdio
6778 static cstring read_filename_string (int ch, /*:open:*/ FILE *f)
6784 set = alloc = dmalloc (len + 1);
6789 while ((ch = getc (f)) != EOF && ! is_space[ch])
6791 if (set - alloc == size_toInt (len))
6794 alloc = drealloc (alloc, len + 1);
6795 set = alloc + len / 2;
6796 /*@-branchstate@*/ }
6799 } /*@=branchstate@*/
6802 check (ungetc (ch, f) != EOF);
6804 return cstring_fromChars (alloc);
6807 /* This structure holds a linked list of file name maps, one per directory. */
6809 struct file_name_map_list
6811 /*@only@*/ struct file_name_map_list *map_list_next;
6812 /*@only@*/ cstring map_list_name;
6813 /*@null@*/ struct file_name_map *map_list_map;
6816 /* Read the file name map file for DIRNAME. */
6818 static struct file_name_map *
6819 read_name_map (cppReader *pfile, cstring dirname)
6821 struct file_name_map_list *map_list_ptr;
6825 for (map_list_ptr = CPPOPTIONS (pfile)->map_list;
6826 map_list_ptr != NULL;
6827 map_list_ptr = map_list_ptr->map_list_next)
6829 if (cstring_equal (map_list_ptr->map_list_name, dirname))
6831 return map_list_ptr->map_list_map;
6835 map_list_ptr = (struct file_name_map_list *) dmalloc (sizeof (*map_list_ptr));
6836 map_list_ptr->map_list_name = cstring_copy (dirname);
6837 map_list_ptr->map_list_map = NULL;
6839 name = cstring_copy (dirname);
6841 if (cstring_length (dirname) > 0)
6843 name = cstring_appendChar (name, CONNECTCHAR);
6846 name = cstring_concatFree1 (name, cstring_makeLiteralTemp (FILE_NAME_MAP_FILE));
6848 f = fileTable_openReadFile (context_fileTable (), name);
6849 cstring_free (name);
6853 map_list_ptr->map_list_map = NULL;
6859 while ((ch = getc (f)) != EOF)
6862 struct file_name_map *ptr;
6869 from = read_filename_string (ch, f);
6870 while ((ch = getc (f)) != EOF && is_hor_space[ch])
6875 to = read_filename_string (ch, f);
6877 ptr = (struct file_name_map *) dmalloc (sizeof (*ptr));
6878 ptr->map_from = from;
6880 /* Make the real filename absolute. */
6881 if (cstring_length (to) > 1
6882 && osd_isConnectChar (cstring_firstChar (to)))
6888 ptr->map_to = cstring_copy (dirname);
6889 ptr->map_to = cstring_appendChar (ptr->map_to, CONNECTCHAR);
6890 ptr->map_to = cstring_concatFree (ptr->map_to, to);
6893 ptr->map_next = map_list_ptr->map_list_map;
6894 map_list_ptr->map_list_map = ptr;
6896 while ((ch = getc (f)) != '\n')
6900 /*@innerbreak@*/ break;
6905 assertSet (map_list_ptr->map_list_map);
6906 check (fileTable_closeFile (context_fileTable (),f) == 0);
6909 map_list_ptr->map_list_next = pfile->opts->map_list;
6910 pfile->opts->map_list = map_list_ptr;
6912 return map_list_ptr->map_list_map;
6915 /* Try to open include file FILENAME. SEARCHPTR is the directory
6916 being tried from the include file search path. This function maps
6917 filenames on file systems based on information read by
6921 open_include_file (cppReader *pfile,
6923 struct file_name_list *searchptr)
6925 char *filename = cstring_toCharsSafe (fname);
6926 struct file_name_map *map;
6930 cstring_markOwned (fname);
6932 cpp_setLocation (pfile);
6934 if (context_getFlag (FLG_NEVERINCLUDE))
6936 if (isHeaderFile (fname))
6938 return SKIP_INCLUDE;
6942 if ((searchptr != NULL) && ! searchptr->got_name_map)
6944 searchptr->name_map = read_name_map (pfile,
6945 !cstring_isEmpty (searchptr->fname)
6946 ? searchptr->fname :
6947 cstring_makeLiteralTemp ("."));
6948 searchptr->got_name_map = 1;
6951 /* First check the mapping for the directory we are using. */
6953 if ((searchptr != NULL)
6954 && (searchptr->name_map != NULL))
6958 if (!cstring_isEmpty (searchptr->fname))
6960 from += cstring_length (searchptr->fname) + 1;
6963 for (map = searchptr->name_map;
6965 map = map->map_next)
6967 if (cstring_equal (map->map_from, cstring_fromChars (from)))
6970 ** Found a match. Check if the file should be skipped
6973 if (cpp_skipIncludeFile (map->map_to))
6975 return SKIP_INCLUDE;
6979 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
6986 ** Try to find a mapping file for the particular directory we are
6987 ** looking in. Thus #include <sys/types.h> will look up sys/types.h
6988 ** in /usr/include/header.gcc and look up types.h in
6989 ** /usr/include/sys/header.gcc.
6992 p = strrchr (filename, CONNECTCHAR);
6999 if ((searchptr != NULL)
7000 && (cstring_isDefined (searchptr->fname))
7001 && (size_toInt (cstring_length (searchptr->fname)) == p - filename)
7002 && !strncmp (cstring_toCharsSafe (searchptr->fname),
7004 size_fromInt (p - filename)))
7006 /* filename is in SEARCHPTR, which we've already checked. */
7008 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
7010 return SKIP_INCLUDE;
7014 return cpp_openIncludeFile (filename);
7020 dir = mstring_copy (".");
7025 dir = (char *) dmalloc (size_fromInt (p - filename + 1));
7026 memcpy (dir, filename, size_fromInt (p - filename));
7027 dir[p - filename] = '\0';
7031 for (map = read_name_map (pfile, cstring_fromChars (dir));
7033 map = map->map_next)
7035 if (cstring_equal (map->map_from, cstring_fromChars (from)))
7039 if (cpp_skipIncludeFile (map->map_to))
7041 return SKIP_INCLUDE;
7045 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
7052 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
7054 return SKIP_INCLUDE;
7058 return cpp_openIncludeFile (filename);
7062 /* Process the contents of include file FNAME, already open on descriptor F,
7064 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
7065 "system" include directories (as decided by the `is_system_include'
7067 DIRPTR is the link in the dir path through which this file was found,
7068 or 0 if the file name was absolute or via the current directory.
7069 Return 1 on success, 0 on failure.
7071 The caller is responsible for the cppReader_pushBuffer. */
7074 finclude (cppReader *pfile, int f,
7076 bool system_header_p,
7077 /*@dependent@*/ struct file_name_list *dirptr)
7079 mode_t st_mode; /* was __mode_t */
7083 cppBuffer *fp; /* For input stack frame */
7085 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
7087 cppReader_perrorWithName (pfile, fname);
7088 check (close (f) == 0);
7089 (void) cppReader_popBuffer (pfile);
7095 fp = cppReader_getBufferSafe (pfile);
7097 /*@-temptrans@*/ /* fname shouldn't really be temp */
7098 fp->nominal_fname = fp->fname = fname;
7102 fp->system_header_p = system_header_p;
7105 fp->cleanup = cppReader_fileCleanup;
7107 if (S_ISREG (st_mode))
7110 fp->buf = (char *) dmalloc (st_size + 2);
7111 fp->alimit = fp->buf + st_size + 2;
7114 /* Read the file contents, knowing that st_size is an upper bound
7115 on the number of bytes we can read. */
7116 length = safe_read (f, fp->buf, size_toInt (st_size));
7117 fp->rlimit = fp->buf + length;
7118 if (length < 0) goto nope;
7120 else if (S_ISDIR (st_mode))
7122 cppReader_error (pfile,
7123 message ("Directory specified where file is expected: %s", fname));
7124 check (close (f) == 0);
7130 ** Cannot count its file size before reading.
7131 ** First read the entire file into heap and
7132 ** copy them into buffer on stack.
7135 size_t bsize = 2000;
7140 fp->buf = (char *) dmalloc (bsize + 2);
7143 i = safe_read (f, fp->buf + st_size, size_toInt (bsize - st_size));
7146 goto nope; /* error! */
7149 if (st_size != bsize)
7151 break; /* End of file */
7155 fp->buf = (char *) drealloc (fp->buf, bsize + 2);
7159 length = size_toInt (st_size);
7162 if ((length > 0 && fp->buf[length - 1] != '\n')
7163 /* Backslash-newline at end is not good enough. */
7164 || (length > 1 && fp->buf[length - 2] == '\\')) {
7165 fp->buf[length++] = '\n';
7168 fp->buf[length] = '\0';
7169 fp->rlimit = fp->buf + length;
7171 /* Close descriptor now, so nesting does not use lots of descriptors. */
7172 check (close (f) == 0);
7174 /* Must do this before calling trigraph_pcp, so that the correct file name
7175 will be printed in warning messages. */
7177 pfile->input_stack_listing_current = 0;
7182 cppReader_perrorWithName (pfile, fname);
7183 check (close (f) == 0);
7189 cpplib_init (cppReader *pfile)
7191 memset ((char *) pfile, 0, sizeof (*pfile));
7193 pfile->get_token = cpplib_getToken;
7194 pfile->token_buffer_size = 200;
7195 pfile->token_buffer = (char *) dmalloc (pfile->token_buffer_size);
7196 pfile->all_include_files = NULL;
7200 cppReader_setWritten (pfile, 0);
7202 pfile->system_include_depth = 0;
7203 pfile->max_include_len = 0;
7204 pfile->timebuf = NULL;
7205 pfile->only_seen_white = 1;
7207 pfile->buffer = cppReader_nullBuffer (pfile);
7211 cppReader_finish (/*@unused@*/ cppReader *pfile)
7216 /* Free resources used by PFILE.
7217 This is the cppReader 'finalizer' or 'destructor' (in C++ terminology). */
7220 cppCleanup (/*@special@*/ cppReader *pfile)
7222 /*@releases pfile@*/
7224 DPRINTF (("cppCleanup!"));
7226 while (CPPBUFFER (pfile) != cppReader_nullBuffer (pfile))
7228 (void) cppReader_popBuffer (pfile);
7231 if (pfile->token_buffer != NULL)
7233 sfree (pfile->token_buffer);
7234 pfile->token_buffer = NULL;
7237 while (pfile->if_stack != NULL)
7239 cppIfStackFrame *temp = pfile->if_stack;
7240 pfile->if_stack = temp->next;
7244 while (pfile->all_include_files != NULL)
7246 struct file_name_list *temp = pfile->all_include_files;
7247 pfile->all_include_files = temp->next;
7248 /*@-dependenttrans@*/
7249 cstring_free (temp->fname);
7250 /*@=dependenttrans@*/
7254 /* evans 2002-07-12 */
7255 while (pfile->opts->map_list != NULL)
7257 struct file_name_map_list *temp = pfile->opts->map_list;
7258 pfile->opts->map_list = pfile->opts->map_list->map_list_next;
7259 cstring_free (temp->map_list_name);
7263 while (pfile->opts->include != NULL)
7265 struct file_name_list *temp = pfile->opts->include;
7266 pfile->opts->include = pfile->opts->include->next;
7267 /* cstring_free (temp->fname); */
7271 sfree (pfile->opts);
7273 cppReader_hashCleanup ();
7277 ** Get the file-mode and data size of the file open on FD
7278 ** and store them in *MODE_POINTER and *SIZE_POINTER.
7282 file_size_and_mode (int fd, mode_t *mode_pointer, size_t *size_pointer)
7286 if (fstat (fd, &sbuf) < 0) {
7289 /*@-compdestroy@*/ /* possibly spurious warnings here (or memory leak) */
7294 if (mode_pointer != NULL)
7296 /*@-type@*/ /* confusion between __mode_t and mode_t types */
7297 *mode_pointer = sbuf.st_mode;
7301 if (size_pointer != NULL)
7303 *size_pointer = (size_t) sbuf.st_size;
7306 /*@-compdestroy@*/ /* possibly spurious warnings here (or memory leak) */
7311 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
7312 retrying if necessary. Return a negative value if an error occurs,
7313 otherwise return the actual number of bytes read,
7314 which must be LEN unless end-of-file was reached. */
7316 static int safe_read (int desc, char *ptr, int len)
7322 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
7323 /*@-compdef@*/ /* ptr is an out parameter */
7324 int nchars = _read (desc, ptr, (unsigned) left);
7327 ssize_t nchars = read (desc, ptr, size_fromInt (left));
7336 return (int) nchars;
7350 /* Initialize PMARK to remember the current position of PFILE. */
7353 parseSetMark (struct parse_marker *pmark, cppReader *pfile)
7355 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7357 pmark->next = pbuf->marks;
7359 pbuf->marks = pmark;
7363 pmark->position = pbuf->cur - pbuf->buf;
7364 DPRINTF (("set mark: %d / %s", pmark->position, pbuf->cur));
7367 /* Cleanup PMARK - we no longer need it. */
7369 void parseClearMark (struct parse_marker *pmark)
7371 struct parse_marker **pp = &pmark->buf->marks;
7373 for (; ; pp = &(*pp)->next)
7375 llassert (*pp != NULL);
7376 if (*pp == pmark) break;
7382 /* Backup the current position of PFILE to that saved in PMARK. */
7385 parseGotoMark (struct parse_marker *pmark, cppReader *pfile)
7387 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7389 if (pbuf != pmark->buf)
7391 cpp_setLocation (pfile);
7392 llfatalbug (cstring_makeLiteral ("Internal error parseGotoMark"));
7395 llassert (pbuf->buf != NULL);
7396 pbuf->cur = pbuf->buf + pmark->position;
7397 DPRINTF (("goto mark: %d / %s", pmark->position, pbuf->cur));
7400 /* Reset PMARK to point to the current position of PFILE. (Same
7401 as parseClearMark (PMARK), parseSetMark (PMARK, PFILE) but faster. */
7404 parseMoveMark (struct parse_marker *pmark, cppReader *pfile)
7406 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7408 if (pbuf != pmark->buf)
7410 cpp_setLocation (pfile);
7411 llfatalerror (cstring_makeLiteral ("Internal error parseMoveMark"));
7414 pmark->position = pbuf->cur - pbuf->buf;
7415 DPRINTF (("move mark: %d", pmark->position));
7418 void cpplib_initializeReader (cppReader *pfile) /* Must be done after library is loaded. */
7420 struct cppOptions *opts = CPPOPTIONS (pfile);
7423 /* The code looks at the defaults through this pointer, rather than through
7424 the constant structure above. This pointer gets changed if an environment
7425 variable specifies other defaults. */
7427 struct default_include *include_defaults = include_defaults_array;
7429 /* Add dirs from INCLUDEPATH_VAR after dirs from -I. */
7430 /* There seems to be confusion about what CPATH should do,
7431 so for the moment it is not documented. */
7432 /* Some people say that CPATH should replace the standard include dirs,
7433 but that seems pointless: it comes before them, so it overrides them
7436 xp = osd_getEnvironmentVariable (INCLUDEPATH_VAR);
7438 if (cstring_isDefined (xp) && !opts->no_standard_includes)
7440 path_include (pfile, cstring_toCharsSafe (xp));
7443 /* Now that dollars_in_ident is known, initialize is_idchar. */
7444 initialize_char_syntax (opts);
7446 /* CppReader_Install __LINE__, etc. Must follow initialize_char_syntax
7447 and option processing. */
7449 initialize_builtins (pfile);
7451 /* Do standard #defines and assertions
7452 that identify system and machine type. */
7454 if (!opts->inhibit_predefs) {
7455 char *p = (char *) dmalloc (strlen (predefs) + 1);
7456 strcpy (p, predefs);
7462 while (*p == ' ' || *p == '\t')
7467 /* Handle -D options. */
7468 if (p[0] == '-' && p[1] == 'D')
7472 while (*p && *p != ' ' && *p != '\t')
7482 if (opts->debug_output)
7484 output_line_command (pfile, 0, same_file);
7487 cppReader_define (pfile, q);
7489 while (*p == ' ' || *p == '\t')
7503 opts->done_initializing = 1;
7505 { /* Read the appropriate environment variable and if it exists
7506 replace include_defaults with the listed path. */
7510 int win32_buf_size = 0; /* memory we need to allocate */
7513 if (opts->cplusplus)
7515 epath = getenv ("CPLUS_INCLUDE_PATH");
7519 epath = getenv ("C_INCLUDE_PATH");
7523 ** If the environment var for this language is set,
7524 ** add to the default list of include directories.
7527 if (epath != NULL) {
7528 char *nstore = (char *) dmalloc (strlen (epath) + 2);
7530 char *startp, *endp;
7533 /* if we have a posix path list, convert to win32 path list */
7534 if (cygwin32_posix_path_list_p (epath))
7536 win32_buf_size = cygwin32_posix_to_win32_path_list_buf_size (epath);
7537 win32epath = (char *) dmalloc /*@i4@*/ (win32_buf_size);
7538 cygwin32_posix_to_win32_path_list (epath, win32epath);
7542 for (num_dirs = 1, startp = epath; *startp; startp++)
7544 if (*startp == PATH_SEPARATOR)
7550 = (struct default_include *) dmalloc ((num_dirs
7551 * sizeof (struct default_include))
7552 + sizeof (include_defaults_array));
7555 startp = endp = epath;
7558 /* Handle cases like c:/usr/lib:d:/gcc/lib */
7559 if ((*endp == PATH_SEPARATOR) || *endp == 0)
7561 strncpy (nstore, startp, size_fromInt (endp - startp));
7564 strcpy (nstore, ".");
7568 nstore[endp-startp] = '\0';
7571 include_defaults[num_dirs].fname = cstring_fromCharsNew (nstore);
7572 include_defaults[num_dirs].cplusplus = opts->cplusplus;
7573 include_defaults[num_dirs].cxx_aware = 1;
7580 endp = startp = endp + 1;
7587 /* Put the usual defaults back in at the end. */
7588 memcpy ((char *) &include_defaults[num_dirs],
7589 (char *) include_defaults_array,
7590 sizeof (include_defaults_array));
7593 /*@-branchstate@*/ } /*@=branchstate@*/
7596 cppReader_appendIncludeChain (pfile, opts->before_system,
7597 opts->last_before_system);
7599 opts->first_system_include = opts->before_system;
7601 /* Unless -fnostdinc,
7602 tack on the standard include file dirs to the specified list */
7604 if (!opts->no_standard_includes) {
7605 struct default_include *p = include_defaults;
7606 char *specd_prefix = opts->include_prefix;
7607 char *default_prefix = mstring_copy (GCC_INCLUDE_DIR);
7608 size_t default_len = 0;
7610 /* Remove the `include' from /usr/local/lib/gcc.../include. */
7611 if (default_prefix != NULL) {
7612 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
7613 default_len = strlen (default_prefix) - 7;
7614 default_prefix[default_len] = 0;
7618 /* Search "translated" versions of GNU directories.
7619 These have /usr/local/lib/gcc... replaced by specd_prefix. */
7620 if (specd_prefix != 0 && default_len != 0)
7621 for (p = include_defaults; p->fname != NULL; p++) {
7622 /* Some standard dirs are only for C++. */
7624 || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
7625 /* Does this dir start with the prefix? */
7626 llassert (default_prefix != NULL);
7628 if (!strncmp (cstring_toCharsSafe (p->fname), default_prefix, default_len))
7630 /* Yes; change prefix and add to search list. */
7631 struct file_name_list *nlist
7632 = (struct file_name_list *) dmalloc (sizeof (*nlist));
7633 size_t this_len = strlen (specd_prefix) + cstring_length (p->fname) - default_len;
7634 char *str = (char *) dmalloc (this_len + 1);
7635 strcpy (str, specd_prefix);
7636 strcat (str, cstring_toCharsSafe (p->fname) + default_len);
7639 nlist->fname = cstring_fromChars (str);
7640 nlist->control_macro = 0;
7641 nlist->c_system_include_path = !p->cxx_aware;
7642 nlist->got_name_map = 0;
7644 if (opts->first_system_include == 0)
7646 opts->first_system_include = nlist;
7649 cppReader_addIncludeChain (pfile, nlist);
7654 /* Search ordinary names for GNU include directories. */
7656 for (p = include_defaults; p->fname != NULL; p++)
7658 /* Some standard dirs are only for C++. */
7660 || (opts->cplusplus && !opts->no_standard_cplusplus_includes))
7662 struct file_name_list *nlist
7663 = (struct file_name_list *) dmalloc (sizeof (*nlist));
7664 nlist->control_macro = 0;
7665 nlist->c_system_include_path = !p->cxx_aware;
7666 nlist->fname = p->fname;
7667 nlist->got_name_map = 0;
7670 /* Spurious warning reported for opts->first_system_include */
7671 /*@-usereleased@*/ if (opts->first_system_include == NULL)
7673 opts->first_system_include = nlist;
7677 cppReader_addIncludeChain (pfile, nlist);
7680 sfree (default_prefix);
7683 /* Tack the after_include chain at the end of the include chain. */
7684 cppReader_appendIncludeChain (pfile, opts->after_include,
7685 opts->last_after_include);
7687 /* Spurious warnings for opts->first_system_include */
7689 if (opts->first_system_include == NULL)
7691 opts->first_system_include = opts->after_include;
7695 /* With -v, print the list of dirs to search. */
7696 if (opts->verbose) {
7697 struct file_name_list *p;
7698 fprintf (stderr, "#include \"...\" search starts here:\n");
7700 for (p = opts->include; p != NULL; p = p->next) {
7701 if (p == opts->first_bracket_include)
7702 fprintf (stderr, "#include <...> search starts here:\n");
7704 fprintf (stderr, " %s\n", cstring_toCharsSafe (p->fname));
7706 fprintf (stderr, "End of search list.\n");
7710 int cppReader_startProcess (cppReader *pfile, cstring fname)
7714 struct cppOptions *opts = CPPOPTIONS (pfile);
7716 fp = cppReader_pushBuffer (pfile, NULL, 0);
7723 if (opts->in_fname == NULL)
7725 opts->in_fname = cstring_makeLiteralTemp ("");
7728 fp->fname = opts->in_fname;
7729 fp->nominal_fname = fp->fname;
7732 /* Copy the entire contents of the main input file into
7733 the stacked input buffer previously allocated for it. */
7735 if (cstring_isEmpty (fname))
7737 fname = cstring_makeLiteralTemp ("");
7740 else if ((f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666)) < 0)
7742 cppReader_error (pfile,
7743 message ("Error opening %s for reading: %s",
7744 fname, lldecodeerror (errno)));
7753 if (finclude (pfile, f, fname, 0, NULL))
7755 output_line_command (pfile, 0, same_file);
7761 static /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_getBuffer (cppReader *pfile)
7763 return pfile->buffer;
7766 /*@exposed@*/ cppBuffer *cppReader_getBufferSafe (cppReader *pfile)
7768 llassert (pfile->buffer != NULL);
7769 return pfile->buffer;
7772 /*@exposed@*/ char *cppLineBase (cppBuffer *buf)
7774 llassert (buf->buf != NULL);
7775 return (buf->buf + buf->line_base);
7778 int cpplib_bufPeek (cppBuffer *buf)
7780 if (buf->cur == NULL || buf->rlimit == NULL) {
7784 if (buf->cur < buf->rlimit) {
7791 bool cppBuffer_isMacro (cppBuffer *buf)
7795 return (buf->cleanup == cppReader_macroCleanup);
7802 ** Returns true if the macro should be checked, false
7803 ** if it should be expanded normally.
7806 static bool notparseable = FALSE; /* preceeded by @notparseable@ */
7807 static bool notfunction = FALSE; /* preceeded by @notfunction@ */
7808 static bool expectiter = FALSE; /* preceeded by @iter@ */
7809 static bool expectenditer = FALSE; /* second after @iter@ */
7810 static bool expectfunction = FALSE; /* preceeded by @function@ */
7811 static bool expectconstant = FALSE; /* preceeded by @constant@ */
7812 static bool expectmacro = FALSE; /* preceeded by notfunction or notparseable */
7814 static void cpp_setLocation (cppReader *pfile)
7819 if (pfile->buffer != NULL)
7821 if (cstring_isDefined (cppReader_getBufferSafe (pfile)->nominal_fname))
7823 cstring fname = cppReader_getBufferSafe (pfile)->nominal_fname;
7825 DPRINTF (("Looking up: %s", fname));
7827 if (fileTable_exists (context_fileTable (), fname))
7829 fid = fileTable_lookup (context_fileTable (), fname);
7833 DPRINTF (("Trying %s", cppReader_getBuffer (pfile)->fname));
7835 fid = fileTable_lookup (context_fileTable (),
7836 cppReader_getBufferSafe (pfile)->fname);
7841 fid = fileTable_lookup (context_fileTable (),
7842 cppReader_getBufferSafe (pfile)->fname);
7845 line = cppReader_getBufferSafe (pfile)->lineno;
7846 fileloc_free (g_currentloc);
7848 if (fileId_isValid (fid))
7850 g_currentloc = fileloc_create (fid, line, 1);
7854 g_currentloc = fileloc_createBuiltin ();
7859 fileloc_free (g_currentloc);
7860 g_currentloc = fileloc_createBuiltin ();
7864 static bool cpp_shouldCheckMacro (cppReader *pfile, char *p) /*@modifies p*/
7866 bool checkmacro = FALSE;
7867 bool hasParams = FALSE;
7871 cpp_setLocation (pfile);
7873 DPRINTF (("Should check macro? %s", p));
7875 if (expectiter || expectconstant || expectenditer)
7880 expectenditer = TRUE;
7885 expectconstant = FALSE;
7886 expectenditer = FALSE;
7889 if (notfunction || notparseable)
7891 notfunction = FALSE;
7892 notparseable = FALSE;
7901 llassert (*p == '#');
7904 while (*p == ' ' || *p == '\t')
7909 llassert (*p == 'd'); /* define starts */
7913 while (*p == ' ' || *p == '\t')
7918 sname = cstring_fromChars (p);
7919 DPRINTF (("Check macro: %s", sname));
7921 while (((c = *p) != ' ')
7922 && c != '\0' && c != '('
7923 && c != '\t' && c != '\\' && c != '\n'
7929 hasParams = (c == '(');
7934 notparseable = FALSE;
7936 else if (notfunction || fileloc_isStandardLib (g_currentloc))
7938 DPRINTF (("Clear notfunction"));
7939 notfunction = FALSE;
7943 if (usymtab_existsReal (sname))
7945 uentry ue = usymtab_lookup (sname);
7947 DPRINTF (("Lookup macro: %s", uentry_unparse (ue)));
7949 if (fileloc_isPreproc (uentry_whereLast (ue)))
7955 if (uentry_isSpecified (ue))
7957 checkmacro = context_getFlag (FLG_SPECMACROS);
7963 checkmacro = context_getFlag (FLG_LIBMACROS)
7964 || context_getFlag (FLG_FCNMACROS);
7972 DPRINTF (("Macro doesn't exist: %s", bool_unparse (checkmacro)));
7974 if (fileloc_isSystemFile (g_currentloc)
7975 && context_getFlag (FLG_SYSTEMDIREXPAND))
7977 ; /* don't check this macro */
7978 DPRINTF (("Don't check 1"));
7986 DPRINTF (("Has params..."));
7988 if (context_getFlag (FLG_FCNMACROS))
7990 if (usymtab_exists (sname))
7993 ** only get here is macro is redefined
7994 ** error reported elsewhere
7997 DPRINTF (("It exists!"));
8002 ** We make it a forward function, since it might be declared elsewhere.
8003 ** After all headers have been processed, we should check the forward
8007 fileloc loc = fileloc_makePreproc (g_currentloc);
8009 /* the line is off-by-one, since the newline was already read */
8014 expectfunction = FALSE;
8017 le = uentry_makeForwardFunction (sname,
8018 typeId_invalid, loc);
8024 /* Do not define here! */
8026 (void) usymtab_addEntry (le);
8030 DPRINTF (("Check: TRUE"));
8034 DPRINTF (("Flag FCN_MACROS not set!"));
8039 DPRINTF (("No params"));
8041 if (context_getFlag (FLG_CONSTMACROS))
8043 bool nocontent = FALSE;
8056 ** Check if there is nothing after the define.
8059 while ((*rest) != '\0' && isspace (*rest))
8066 nocontent = TRUE; /* empty macro, don't check */
8071 if (usymtab_exists (sname))
8077 fileloc loc = fileloc_makePreproc (g_currentloc);
8078 DPRINTF (("Make constant: %s", sname));
8079 le = uentry_makeMacroConstant (sname, ctype_unknown, loc);
8080 (void) usymtab_addEntry (le);
8083 checkmacro = !nocontent;
8088 if (checkmacro && usymtab_existsType (sname))
8090 DPRINTF (("Making false..."));
8092 ppllerror (message ("Specified type implemented as macro: %s", sname));
8101 if (usymtab_exists (sname))
8103 uentry ue = usymtab_lookupExpose (sname);
8104 fileloc tloc = fileloc_makePreproc (g_currentloc);
8106 uentry_setDefined (ue, tloc);
8107 fileloc_free (tloc);
8108 uentry_setUsed (ue, fileloc_undefined);
8112 fileloc tloc = fileloc_makePreproc (g_currentloc);
8113 uentry ue = uentry_makeExpandedMacro (sname, tloc);
8114 DPRINTF (("Make expanded macro: %s", sname));
8115 DPRINTF (("Not in symbol table: %s", sname));
8117 (void) usymtab_addGlobalEntry (ue);
8118 fileloc_free (tloc);
8123 DPRINTF (("Returning: %s", bool_unparse (checkmacro)));
8127 static enum cpp_token
8128 cpp_handleComment (cppReader *pfile, struct parse_marker *smark)
8130 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
8134 bool eliminateComment = FALSE;
8136 llassert (pbuf->buf != NULL);
8138 start = pbuf->buf + smark->position;
8140 llassert (pbuf->cur != NULL);
8141 len = pbuf->cur - start;
8144 && start[1] == context_getCommentMarkerChar ())
8148 char *scomment = start + 2;
8149 char savec = start[len];
8151 cpp_setLocation (pfile);
8152 loc = fileloc_copy (g_currentloc);
8154 start[0] = BEFORE_COMMENT_MARKER[0];
8155 start[1] = BEFORE_COMMENT_MARKER[1];
8157 llassert (start[len - 2] == '*');
8158 start[len - 2] = AFTER_COMMENT_MARKER[0];
8160 llassert (start[len - 1] == '/');
8161 start[len - 1] = AFTER_COMMENT_MARKER[1];
8163 cpplib_reserve(pfile, size_fromInt (1 + len));
8164 cppReader_putCharQ (pfile, c);
8166 cpp_setLocation (pfile);
8170 if (mstring_containsString (scomment, "/*"))
8172 (void) cppoptgenerror
8174 message ("Comment starts inside syntactic comment: %s",
8175 cstring_fromChars (scomment)),
8181 if (mstring_equalPrefix (scomment, "ignore"))
8183 if (!context_getFlag (FLG_NOCOMMENTS))
8185 context_enterSuppressRegion (loc);
8188 else if (mstring_equalPrefix (scomment, "end"))
8190 if (!context_getFlag (FLG_NOCOMMENTS))
8192 context_exitSuppressRegion (loc);
8195 else if (mstring_equalPrefix (scomment, "notparseable"))
8197 notparseable = TRUE;
8199 eliminateComment = TRUE;
8201 else if (mstring_equalPrefix (scomment, "notfunction"))
8205 eliminateComment = TRUE;
8207 else if (mstring_equalPrefix (scomment, "iter"))
8211 else if (mstring_equalPrefix (scomment, "function"))
8213 expectfunction = TRUE;
8215 else if (mstring_equalPrefix (scomment, "constant"))
8217 expectconstant = TRUE;
8221 char sChar = *scomment;
8227 char *rest = scomment + 1;
8229 if (mstring_equalPrefix (rest, "commentchar"))
8231 eliminateComment = TRUE;
8235 ppllerror (cstring_makeLiteral
8236 ("Cannot restore commentchar"));
8240 char *next = scomment + 12; /* strlen commentchar = 12 */
8242 if (*next != ' ' && *next != '\t' && *next != '\n')
8246 ("Syntactic commentchar comment is not followed by a "
8247 "whitespace character: %c",
8252 char cchar = *(next + 1);
8257 (cstring_makeLiteral
8258 ("Cannot set commentchar to NUL"));
8262 context_setCommentMarkerChar (cchar);
8263 /* setComment = TRUE; */
8268 else if (mstring_equalPrefix (scomment, "nestcomment"))
8270 /* fix from Mike Miller <MikeM@xata.com> */
8271 context_fileSetFlag (FLG_NESTCOMMENT,
8272 ynm_fromCodeChar (sChar),
8275 else if (mstring_equalPrefix (rest, "namechecks"))
8277 context_fileSetFlag (FLG_NAMECHECKS,
8278 ynm_fromCodeChar (sChar),
8281 else if (mstring_equalPrefix (rest, "macroredef"))
8283 context_fileSetFlag (FLG_MACROREDEF,
8284 ynm_fromCodeChar (sChar),
8287 else if (mstring_equalPrefix (rest, "usevarargs"))
8289 context_fileSetFlag (FLG_USEVARARGS,
8290 ynm_fromCodeChar (sChar),
8293 else if (mstring_equalPrefix (rest, "nextlinemacros"))
8295 context_fileSetFlag (FLG_MACRONEXTLINE,
8296 ynm_fromCodeChar (sChar),
8299 else if (mstring_equalPrefix (rest, "allmacros")
8300 || mstring_equalPrefix (rest, "fcnmacros")
8301 || mstring_equalPrefix (rest, "constmacros"))
8305 if (mstring_equalPrefix (rest, "allmacros"))
8309 else if (mstring_equalPrefix (rest, "fcnmacros"))
8315 llassert (mstring_equalPrefix (rest, "constmacros"));
8316 fl = FLG_CONSTMACROS;
8319 context_fileSetFlag (fl, ynm_fromCodeChar (sChar), loc);
8320 notfunction = FALSE;
8333 if (eliminateComment)
8338 /* Replaces comment char's in start with spaces */
8340 for (i = 2; i < len - 2; i++)
8342 if (start[i] == BEFORE_COMMENT_MARKER[0]
8343 || start[i] == BEFORE_COMMENT_MARKER[1]
8344 || start[i] == context_getCommentMarkerChar ())
8350 cppReader_putStrN (pfile, start, size_fromInt (len));
8351 parseClearMark (smark);
8361 ** Output the comment as all spaces so line/column
8362 ** in output file is still correct.
8366 cstring lintcomment = cstring_undefined;
8368 if (context_getFlag (FLG_LINTCOMMENTS))
8370 if (mstring_equalPrefix (start, "*NOTREACHED*/"))
8372 lintcomment = cstring_makeLiteralTemp ("l_notreach");
8374 else if (mstring_equalPrefix (start, "*PRINTFLIKE*/"))
8376 lintcomment = cstring_makeLiteralTemp ("l_printfli");
8378 else if (mstring_equalPrefix (start, "*FALLTHROUGH*/"))
8380 lintcomment = cstring_makeLiteralTemp ("l_fallthrou");
8382 else if (mstring_equalPrefix (start, "*ARGSUSED*/"))
8384 lintcomment = cstring_makeLiteralTemp ("l_argsus");
8386 else if (mstring_equalPrefix (start, "*FALLTHRU*/"))
8388 lintcomment = cstring_makeLiteralTemp ("l_fallth");
8392 lintcomment = cstring_undefined;
8397 lintcomment = cstring_undefined;
8400 if (cstring_isDefined (lintcomment))
8402 c = BEFORE_COMMENT_MARKER[0];
8403 start[0] = BEFORE_COMMENT_MARKER[1];
8405 llassert (size_toLong (cstring_length (lintcomment)) == len - 3);
8407 for (i = 1; i < len - 2; i++)
8409 start[i] = cstring_getChar (lintcomment, size_fromInt (i));
8412 start[len - 2] = AFTER_COMMENT_MARKER[0];
8413 start[len - 1] = AFTER_COMMENT_MARKER[1];
8417 /* Replaces char's in start with spaces */
8418 for (i = 0; i < len; i++)
8422 && start[i + 1] == '*') {
8423 (void) cppoptgenerror
8425 message ("Comment starts inside comment"),
8429 if (start[i] != '\n')
8436 cpplib_reserve (pfile, size_fromInt (1 + len));
8437 cppReader_putCharQ (pfile, c);
8438 cppReader_putStrN (pfile, start, size_fromInt (len));
8439 parseClearMark (smark);
8445 static int cpp_openIncludeFile (char *filename)
8447 int res = open (filename, O_RDONLY, 0666);
8449 /* evans 2001-08-23: was (res) - open returns -1 on error! reported by Robin Watts */
8452 if (!fileTable_exists (context_fileTable (),
8453 cstring_fromChars (filename)))
8455 if (fileloc_isXHFile (g_currentloc))
8458 ** Files includes by XH files are also XH files
8461 (void) fileTable_addXHFile (context_fileTable (),
8462 cstring_fromChars (filename));
8466 (void) fileTable_addHeaderFile (context_fileTable (),
8467 cstring_fromChars (filename));
8472 DPRINTF (("File already exists: %s", filename));
8479 static bool cpp_skipIncludeFile (cstring fname)
8481 if (context_isSystemDir (fname))
8483 DPRINTF (("System dir: %s", fname));
8485 if (lcllib_isSkipHeader (fname))
8487 DPRINTF (("Skip include TRUE: %s", fname));
8491 if (context_getFlag (FLG_SKIPSYSHEADERS))
8494 ** 2003-04-18: Patch from Randal Parsons
8498 ** Don't skip include file unless the file actually exists.
8499 ** It may be in a different directory.
8502 int f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666);
8506 check (close (f) == 0);
8507 DPRINTF (("Skip include TRUE: %s", fname));
8512 /* Keep looking... */
8517 if (context_getFlag (FLG_SINGLEINCLUDE))
8519 fname = removePreDirs (fname);
8521 # if defined (WIN32) || defined (OS2)
8522 cstring_replaceAll (fname, '\\', '/');
8525 if (fileTable_exists (context_fileTable (), fname))
8527 DPRINTF (("Skip include TRUE: %s", fname));
8532 DPRINTF (("Skip include FALSE: %s", fname));
8536 static int cpp_peekN (cppReader *pfile, int n)
8538 cppBuffer *buf = cppReader_getBufferSafe (pfile);
8540 llassert (buf->cur != NULL);
8542 return (buf->rlimit - buf->cur >= (n)
8547 cppBuffer *cppBuffer_prevBuffer (cppBuffer *buf)
8552 void cppBuffer_forward (cppBuffer *buf, int n)
8554 llassert (buf->cur != NULL);
8558 /*@=bufferoverflowhigh@*/