2 ** Splint - annotation-assisted static program checker
3 ** Copyright (C) 1994-2003 University of Virginia,
4 ** Massachusetts Institute of Technology
6 ** This program is free software; you can redistribute it and/or modify it
7 ** under the terms of the GNU General Public License as published by the
8 ** Free Software Foundation; either version 2 of the License, or (at your
9 ** option) any later version.
11 ** This program is distributed in the hope that it will be useful, but
12 ** WITHOUT ANY WARRANTY; without even the implied warranty of
13 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ** General Public License for more details.
16 ** The GNU General Public License is available from http://www.gnu.org/ or
17 ** the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
18 ** MA 02111-1307, USA.
20 ** For information on splint: info@splint.org
21 ** To report a bug: splint-bug@splint.org
22 ** For more information: http://www.splint.org
28 Copyright (C) 1986, 87, 89, 92-6, 1997 Free Software Foundation, Inc.
29 Contributed by Per Bothner, 1994-95.
30 Based on CCCP program by Paul Rubin, June 1986
31 Adapted to ANSI C, Richard Stallman, Jan 1987
33 This program is free software; you can redistribute it and/or modify it
34 under the terms of the GNU General Public License as published by the
35 Free Software Foundation; either version 2, or (at your option) any
38 This program is distributed in the hope that it will be useful,
39 but WITHOUT ANY WARRANTY; without even the implied warranty of
40 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 GNU General Public License for more details.
43 You should have received a copy of the GNU General Public License
44 along with this program; if not, write to the Free Software
45 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 In other words, you are welcome to use, share and improve this program.
48 You are forbidden to forbid anyone else to use, share and improve
49 what you give them. Help stamp out software-hoarding! */
53 * - OS2 drive specs like WIN32
54 * - Includes for IBMs OS/2 compiler
65 # if !(defined (WIN32) || defined (OS2) && defined (__IBMC__))
68 # include <sys/types.h>
69 # include <sys/stat.h>
71 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
73 # include <sys/utime.h> /* for __DATE__ and __TIME__ */
78 ** evans 2002-07-03: exception for WATCOM 10.6 compiler suggest by Adam Clarke
80 # if !defined (USG) && !defined (__WATCOMC__)
81 # include <time.h> /* Reported by Paul Smith */
82 # include <sys/time.h>
83 # include <sys/resource.h>
85 # include <sys/times.h>
90 # endif /* not WIN32 */
92 /* This defines "errno" properly for VMS, and gives us EACCES. */
95 # include "splintMacros.nf"
99 # include "cpperror.h"
100 # include "cpphash.h"
102 # include "version.h"
106 ** This is really kludgey code...
112 /* Warnings for using sprintf - suppress them all for now... */
113 /*@-bufferoverflowhigh@*/
116 #define NO_SHORTNAMES
124 /*@constant int IMPORT_FOUND@*/
125 # define IMPORT_FOUND -2
127 /*@constant int SKIP_INCLUDE@*/
128 # define SKIP_INCLUDE IMPORT_FOUND
130 /*@constant unused int IMPORT_NOT_FOUND@*/
131 # define IMPORT_NOT_FOUND -1
134 /*@constant unused int STDC_VALUE@*/
138 /* By default, colon separates directories in a path. */
139 #ifndef PATH_SEPARATOR
140 /*@constant char PATH_SEPARATOR@*/
141 #define PATH_SEPARATOR ':'
144 static void parse_name (cppReader *, int);
146 static int cpp_openIncludeFile (char *p_filename)
147 /*@modifies fileSystem @*/ ;
149 static void cpp_setLocation (cppReader *p_pfile)
150 /*@modifies g_currentloc@*/ ;
152 static enum cpp_token cpp_handleComment (cppReader *p_pfile,
153 struct parse_marker *p_smark)
154 /*@modifies p_pfile, p_smark@*/;
156 static bool cpp_shouldCheckMacro (cppReader *p_pfile, char *p_p) /*@modifies p_p@*/ ;
158 static size_t cppReader_checkMacroNameLoc (fileloc p_loc, char *p_symname, cstring p_usage) ;
160 static bool cpp_skipIncludeFile (cstring p_fname) /*@*/ ;
166 /* Symbols to predefine. */
168 #ifdef CPP_PREDEFINES
169 static /*@observer@*/ char *predefs = CPP_PREDEFINES;
171 static /*@observer@*/ char *predefs = "";
174 /* We let tm.h override the types used here, to handle trivial differences
175 such as the choice of unsigned int or long unsigned int for size_t.
176 When machines start needing nontrivial differences in the size type,
177 it would be best to do something here to figure out automatically
178 from other information what type to use. */
180 /* The string value for __SIZE_TYPE__. */
183 /*@constant observer char *SIZE_TYPE@*/
184 #define SIZE_TYPE "long unsigned int"
187 /* The string value for __PTRDIFF_TYPE__. */
190 /*@constant observer char *PTRDIFF_TYPE@*/
191 #define PTRDIFF_TYPE "long int"
194 /* The string value for __WCHAR_TYPE__. */
197 /*@constant observer char *WCHAR_TYPE@*/
198 #define WCHAR_TYPE "int"
201 /* The string value for __USER_LABEL_PREFIX__ */
203 #ifndef USER_LABEL_PREFIX
204 /*@constant observer char *USER_LABEL_PREFIX@*/
205 #define USER_LABEL_PREFIX ""
208 /* The string value for __REGISTER_PREFIX__ */
210 #ifndef REGISTER_PREFIX
211 /*@constant observer char *REGISTER_PREFIX@*/
212 #define REGISTER_PREFIX ""
215 /* table to tell if char can be part of a C identifier. */
216 static bool is_idchar[256];
217 /* table to tell if char can be first char of a c identifier. */
218 static bool is_idstart[256];
219 /* table to tell if c is horizontal space. */
220 static bool is_hor_space[256];
221 /* table to tell if c is horizontal or vertical space. */
222 static bool is_space[256];
224 static /*@exposed@*/ /*@null@*/ cppBuffer *
225 cppReader_getBuffer (/*@special@*/ cppReader *p_pfile)
226 /*@uses p_pfile->buffer@*/
227 /*@modifies nothing@*/ ;
230 # define SKIP_WHITE_SPACE(p) do { /*@access cstring@*/ while (is_hor_space[(int) *(p)]) { (p)++; } } /*@noaccess cstring@*/ while (0)
233 # define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*(p)]) { (p)++; } } while (0)
235 static int cpp_peekN (cppReader *p_pfile, int p_n) /*@*/ ;
237 /*@function static int cppBuffer_get (sef cppBuffer *p_b) modifies *p_b ; @*/
238 # define cppBuffer_get(BUFFER) \
239 ((BUFFER)->cur < (BUFFER)->rlimit ? *(BUFFER)->cur++ : EOF)
241 /*@function static int cppBuffer_reachedEOF (sef cppBuffer *p_b) modifies nothing; @*/
242 # define cppBuffer_reachedEOF(b) \
243 ((b)->cur < (b)->rlimit ? FALSE : TRUE)
245 /* Append string STR (of length N) to PFILE's output buffer. Make space. */
246 /*@function static void cppReader_puts (sef cppReader *p_file, char *p_str, sef size_t p_n)
247 modifies *p_file; @*/
248 # define cppReader_puts(PFILE, STR, N) \
249 cpplib_reserve(PFILE, N), cppReader_putStrN (PFILE, STR,N)
251 /* Append character CH to PFILE's output buffer. Assume sufficient space. */
253 /*@function static void cppReader_putCharQ (cppReader *p_file, char p_ch)
254 modifies *p_file; @*/
255 # define cppReader_putCharQ(PFILE, CH) (*(PFILE)->limit++ = (CH))
257 static void cppReader_putCharQ (cppReader *p_file, char p_ch)
259 fprintf (stderr, "put char: %c\n", p_ch);
260 (*(p_file)->limit++ = (p_ch));
263 /* Append character CH to PFILE's output buffer. Make space if need be. */
265 /*@function static void cppReader_putChar (sef cppReader *p_file, char p_ch)
266 modifies *p_file; @*/
267 #define cppReader_putChar(PFILE, CH) (cpplib_reserve (PFILE, (size_t) 1), cppReader_putCharQ (PFILE, CH))
269 /* Make sure PFILE->limit is followed by '\0'. */
270 /*@function static void cppReader_nullTerminateQ (cppReader *p_file)
271 modifies *p_file; @*/
273 #define cppReader_nullTerminateQ(PFILE) (*(PFILE)->limit = 0)
275 /*@function static void cppReader_nullTerminate (sef cppReader *p_file)
276 modifies *p_file; @*/
277 # define cppReader_nullTerminate(PFILE) \
278 (cpplib_reserve (PFILE, (size_t) 1), *(PFILE)->limit = 0)
280 /*@function static void cppReader_adjustWritten (cppReader *p_file, size_t)
281 modifies *p_file; @*/
282 #define cppReader_adjustWritten(PFILE,DELTA) ((PFILE)->limit += (DELTA))
284 /*@function static bool cppReader_isC89 (cppReader *) modifies nothing; @*/
285 #define cppReader_isC89(PFILE) (CPPOPTIONS(PFILE)->c89)
287 /*@function static observer char *cppReader_wcharType (cppReader *)
288 modifies nothing; @*/
290 # define cppReader_wcharType(PFILE) \
291 (CPPOPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
293 static void cppBuffer_forward (cppBuffer *p_buf, int p_n) /*@modifies *p_buf@*/ ;
295 /*@function static void cppReader_forward (cppReader *p_pfile, int) modifies *p_pfile; @*/
296 # define cppReader_forward(pfile, N) \
297 (cppBuffer_forward (cppReader_getBufferSafe (pfile), (N)))
299 /*@function static int cppReader_getC (cppReader *p_pfile) modifies *p_pfile; @*/
300 # define cppReader_getC(pfile) (cppBuffer_get (cppReader_getBufferSafe (pfile)))
302 /*@function static int cppReader_reachedEOF (sef cppReader *p_pfile) modifies *p_pfile; @*/
303 # define cppReader_reachedEOF(pfile) (cppBuffer_reachedEOF (cppReader_getBufferSafe (pfile)))
305 /*@function static int cppReader_peekC (cppReader *) modifies nothing;@*/
306 # define cppReader_peekC(pfile) (cpplib_bufPeek (cppReader_getBufferSafe (pfile)))
308 /* Move all backslash-newline pairs out of embarrassing places.
309 Exchange all such pairs following BP
310 with any potentially-embarrassing characters that follow them.
311 Potentially-embarrassing characters are / and *
312 (because a backslash-newline inside a comment delimiter
313 would cause it not to be recognized). */
316 # define NEWLINE_FIX \
317 do { while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n') { cppReader_forward (pfile, 2); } } while(FALSE)
319 /* Same, but assume we've already read the potential '\\' into C. */
321 # define NEWLINE_FIX1(C) do { \
322 while ((C) == '\\' && cppReader_peekC (pfile) == '\n') { cppReader_forward (pfile, 1); (C) = cppReader_getC (pfile); }\
325 static void parseSetMark (/*@out@*/ struct parse_marker *,
327 static void parseClearMark (struct parse_marker *);
328 static void parseGotoMark (struct parse_marker *, cppReader *);
329 static void parseMoveMark (struct parse_marker *, cppReader *);
331 /* If we have a huge buffer, may need to cache more recent counts */
332 static /*@exposed@*/ char *cppLineBase (/*@sef@*/ cppBuffer *);
334 static /*@exposed@*/ /*@null@*/ cppBuffer *
335 cppReader_pushBuffer (cppReader *p_pfile,
336 /*@owned@*/ /*@null@*/ char *, size_t)
337 /*@modifies p_pfile@*/ ;
339 static void cppReader_appendIncludeChain
341 /*@keep@*/ struct file_name_list *p_first,
342 /*@dependent@*/ struct file_name_list *p_last);
344 static void cppReader_macroCleanup (cppBuffer *p_pbuf, cppReader *p_pfile);
345 static enum cpp_token cppReader_nullUnderflow (/*@unused@*/ cppReader *p_pfile);
347 static void cppReader_nullCleanup (/*@unused@*/ cppBuffer *p_pbuf,
348 /*@unused@*/ cppReader *p_pfile);
350 static void cppReader_fileCleanup (cppBuffer *p_pbuf,
351 /*@unused@*/ cppReader *p_pfile);
353 static int cppReader_handleDirective (cppReader *p_pfile);
355 static void cppReader_scanBuffer (cppReader *p_pfile);
357 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
360 ** WIN32 (at least the VC++ include files) does not define mode_t.
363 /*@-incondefs@*/ /*@-czechtypes@*/
364 typedef unsigned int mode_t;
365 /*@=incondefs@*/ /*@=czechtypes@*/
369 static int file_size_and_mode (int p_fd, /*@out@*/ mode_t *p_mode_pointer,
370 /*@out@*/ size_t *p_size_pointer);
371 static int safe_read (int p_desc, /*@out@*/ char *p_ptr, int p_len);
375 ** cppBuffer_isMacro is true if the buffer contains macro expansion.
376 ** (Note that it is false while we're expanding marco *arguments*.)
379 static bool cppBuffer_isMacro (/*@null@*/ cppBuffer *) /*@*/ ;
381 static void path_include (cppReader *p_pfile, char *p_path)
382 /*@modifies p_pfile@*/ ;
384 static void initialize_builtins (cppReader *p_pfile)
385 /*@modifies p_pfile@*/ ;
387 static void initialize_char_syntax (struct cppOptions *p_opts) ;
389 static int /*@alt void@*/ finclude (cppReader *p_pfile, int p_f,
391 bool p_system_header_p,
392 /*@dependent@*/ /*@null@*/ struct file_name_list *p_dirptr);
394 static void validate_else (cppReader *p_pfile, cstring p_directive);
396 static void conditional_skip (cppReader *p_pfile, int p_skip,
397 enum node_type p_type,
398 /*@dependent@*/ /*@null@*/ char *p_control_macro);
400 static HOST_WIDE_INT eval_if_expression (cppReader *p_pfile,
404 static void skip_if_group (cppReader *p_pfile, int p_any);
406 static bool comp_def_part (bool p_first, char *p_beg1, int p_len1,
407 char *p_beg2, int p_len2, bool p_last);
410 extern void fancy_abort ();
413 static bool redundant_include_p (cppReader *p_pfile, /*@null@*/ cstring p_name);
414 static bool is_system_include (cppReader *p_pfile, cstring p_filename);
416 static /*@observer@*/ /*@null@*/ struct file_name_map *
417 read_name_map (cppReader *p_pfile, cstring p_dirname);
419 static cstring read_filename_string (int p_ch, /*:open:*/ FILE *p_f);
421 static int open_include_file (cppReader *p_pfile,
422 /*@owned@*/ cstring p_fname,
423 /*@null@*/ struct file_name_list *p_searchptr);
425 static void push_macro_expansion (cppReader *,
426 /*@owned@*/ char *, size_t,
427 /*@dependent@*/ hashNode);
429 /* Last arg to output_line_command. */
430 enum file_change_code {
431 same_file, enter_file, leave_file
434 /* `struct directive' defines one #-directive, including how to handle it. */
437 int length; /* Length of name */
438 /*@null@*/ int (*func)(); /* Function to handle directive */
439 /*@observer@*/ cstring name; /* Name of directive */
440 enum node_type type; /* Code which describes which directive. */
441 bool command_reads_line; /* One if rest of line is read by func. */
442 bool traditional_comments; /* Nonzero: keep comments if -traditional. */
443 bool pass_thru; /* Copy preprocessed directive to output file.*/
446 /* These functions are declared to return int instead of void since they
447 are going to be placed in a table and some old compilers have trouble with
448 pointers to functions returning void. */
450 static int do_define (cppReader *, /*@null@*/ struct directive *,
451 /*@exposed@*/ char *, char *);
452 static int do_defineAux (cppReader *, /*@null@*/ struct directive *,
453 /*@exposed@*/ char *, char *, bool);
455 static int do_line (cppReader *, /*@null@*/ struct directive *);
456 static int do_include (cppReader *, struct directive *, char *, char *);
457 static int do_undef (cppReader *, struct directive *, char *, char *);
458 static int do_error (cppReader *, struct directive *, char *, char *);
459 static int do_pragma (cppReader *, struct directive *, char *, char *);
460 static int do_ident (cppReader *, struct directive *, char *, char *);
461 static int do_if (cppReader *, struct directive *, char *, char *);
462 static int do_xifdef (cppReader *, struct directive *, char *, char *);
463 static int do_else (cppReader *, struct directive *, char *, char *);
464 static int do_elif (cppReader *, struct directive *, char *, char *);
465 static int do_endif (cppReader *, struct directive *, char *, char *);
466 static int do_warning (cppReader *, struct directive *, char *, char *);
468 /* If a buffer's dir field is SELF_DIR_DUMMY, it means the file was found
469 via the same directory as the file that #included it. */
471 /*@constant observer struct file_name_list *SELF_DIR_DUMMY@*/
472 #define SELF_DIR_DUMMY ((struct file_name_list *) (~0))
474 /* #include "file" looks in source file dir, then stack. */
475 /* #include <file> just looks in the stack. */
476 /* -I directories are added to the end, then the defaults are added. */
480 static struct default_include {
481 /*@dependent@*/ /*@observer@*/ cstring fname; /* The name of the directory. */
482 int cplusplus; /* Only look here if we're compiling C++. */
483 int cxx_aware; /* Includes in this directory don't need to
484 be wrapped in extern "C" when compiling
486 } include_defaults_array[]
488 /* This is the dir for fixincludes. Put it just before
489 the files that we fix. */
490 { GCC_INCLUDE_DIR, 0, 0 },
491 { GCC_INCLUDE_DIR2, 0, 0 },
492 { cstring_undefined, 0, 0 }
495 /*@noaccess cstring@*/
497 /* Here is the actual list of #-directives, most-often-used first.
498 The initialize_builtins function assumes #define is the very first. */
502 static struct directive directive_table[] = {
503 { 6, do_define, "define", T_DEFINE, FALSE, TRUE, FALSE },
504 { 5, do_xifdef, "ifdef", T_IFDEF, TRUE, FALSE, FALSE },
505 { 6, do_xifdef, "ifndef", T_IFNDEF, TRUE, FALSE, FALSE },
506 { 7, do_include, "include", T_INCLUDE, TRUE, FALSE, FALSE },
507 { 5, do_endif, "endif", T_ENDIF, TRUE, FALSE, FALSE },
508 { 4, do_else, "else", T_ELSE, TRUE, FALSE, FALSE },
509 { 2, do_if, "if", T_IF, TRUE, FALSE, FALSE },
510 { 4, do_elif, "elif", T_ELIF, TRUE, FALSE, FALSE },
511 { 5, do_undef, "undef", T_UNDEF, FALSE, FALSE, FALSE },
512 { 5, do_error, "error", T_ERROR, FALSE, FALSE, FALSE },
513 { 7, do_warning, "warning", T_WARNING, FALSE, FALSE, FALSE },
514 { 6, do_pragma, "pragma", T_PRAGMA, FALSE, FALSE, TRUE},
515 { 4, do_line, "line", T_LINE, TRUE, FALSE, FALSE },
516 { 5, do_ident, "ident", T_IDENT, TRUE, FALSE, TRUE },
517 /* { 8, do_unassert, "unassert", T_UNASSERT, TRUE, FALSE, FALSE }, */
518 { -1, NULL, "", T_UNUSED, FALSE, FALSE, FALSE },
520 /*@noaccess cstring@*/
522 static cstring searchPath_unparse (struct file_name_list *search_start)
524 cstring res = cstring_newEmpty ();
525 struct file_name_list *searchptr = NULL;
527 for (searchptr = search_start; searchptr != NULL;
528 searchptr = searchptr->next)
530 if (!cstring_isEmpty (searchptr->fname)) {
531 res = cstring_concatFree1 (res, searchptr->fname);
532 if (searchptr->next != NULL) {
533 res = cstring_appendChar (res, ';');
543 initialize_char_syntax (struct cppOptions *opts)
548 * Set up is_idchar and is_idstart tables. These should be
549 * faster than saying (is_alpha (c) || c == '_'), etc.
550 * Set up these things before calling any routines tthat
554 for (i = 'a'; i <= 'z'; i++) {
555 is_idchar[i - 'a' + 'A'] = TRUE;
556 is_idchar[(int) i] = TRUE;
557 is_idstart[i - 'a' + 'A'] = TRUE;
558 is_idstart[(int) i] = TRUE;
561 for (i = '0'; i <= '9'; i++)
563 is_idchar[(int) i] = TRUE;
566 is_idchar['_'] = TRUE;
567 is_idstart['_'] = TRUE;
568 is_idchar['$'] = opts->dollars_in_ident;
569 is_idstart['$'] = opts->dollars_in_ident;
571 /* horizontal space table */
572 is_hor_space[' '] = TRUE;
573 is_hor_space['\t'] = TRUE;
574 is_hor_space['\v'] = TRUE;
575 is_hor_space['\f'] = TRUE;
576 is_hor_space['\r'] = TRUE;
578 is_space[' '] = TRUE;
579 is_space['\t'] = TRUE;
580 is_space['\v'] = TRUE;
581 is_space['\f'] = TRUE;
582 is_space['\n'] = TRUE;
583 is_space['\r'] = TRUE;
586 bool isIdentifierChar (char c)
588 return is_idchar[(int) c];
591 /* Place into P_PFILE a quoted string representing the string SRC.
592 Caller must reserve enough space in pfile->token_buffer. */
595 quote_string (cppReader *pfile, char *src)
599 cppReader_putCharQ (pfile, '\"');
602 switch ((c = *src++))
606 cppReader_putCharQ (pfile, c);
609 sprintf (cpplib_getPWritten (pfile), "\\%03o",
611 cppReader_adjustWritten (pfile, (size_t) 4);
613 /*@switchbreak@*/ break;
617 cppReader_putCharQ (pfile, '\\');
618 cppReader_putCharQ (pfile, c);
619 /*@switchbreak@*/ break;
622 cppReader_putCharQ (pfile, '\"');
623 cppReader_nullTerminateQ (pfile);
629 /* Re-allocates PFILE->token_buffer so it will hold at least N more chars. */
632 cppReader_growBuffer (cppReader *pfile, size_t n)
634 size_t old_written = cpplib_getWritten (pfile);
635 pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
636 pfile->token_buffer = (char *)
637 drealloc (pfile->token_buffer, pfile->token_buffer_size);
638 cppReader_setWritten (pfile, old_written);
642 * process a given definition string, for initialization
643 * If STR is just an identifier, define it with value 1.
644 * If STR has anything after the identifier, then it should
645 * be identifier=definition.
649 cppReader_define (cppReader *pfile, char *str)
654 DPRINTF (("Cpp reader define: %s", str));
656 if (!is_idstart[(int) *p])
658 DPRINTF (("ERROR 1"));
659 cppReader_error (pfile,
660 message ("Malformed option `-D%s'",
661 cstring_fromChars (str)));
668 DPRINTF (("Here 2"));
670 while (is_idchar[(int) *p])
677 while (*p != ')' && *p != '\0') {
686 message ("Malformed option: -D%s (no closing parenthesis)",
687 cstring_fromChars (str)));
691 DPRINTF (("Here 2"));
695 buf = (char *) dmalloc (size_fromInt (p - str + 4));
696 strcpy ((char *) buf, str);
697 strcat ((char *) buf, " 1");
701 DPRINTF (("ERROR 2"));
702 cppReader_error (pfile,
703 message ("Malformed option: -D%s (expected '=', found '%c')",
704 cstring_fromChars (str),
711 /* Copy the entire option so we can modify it. */
712 DPRINTF (("Copying..."));
713 buf = (char *) dmalloc (2 * strlen (str) + 1);
714 strncpy (buf, str, size_fromInt (p - str));
716 /* Change the = to a space. */
718 /* Scan for any backslash-newline and remove it. */
724 if (*p == '\\' && p[1] == '\n')
730 DPRINTF (("Here we are..."));
734 llassert (buf != NULL);
735 DPRINTF (("Do define: %s / %ld", buf, size_toLong (strlen (buf))));
736 (void) do_define (pfile, NULL, buf, buf + strlen (buf));
740 /* Append a chain of `struct file_name_list's
741 to the end of the main include chain.
742 FIRST is gthe beginning of the chain to append, and LAST is the end. */
745 cppReader_appendIncludeChain (cppReader *pfile,
746 struct file_name_list *first,
747 struct file_name_list *last)
749 struct cppOptions *opts = CPPOPTIONS (pfile);
750 struct file_name_list *dir;
752 if (first == NULL || last == NULL)
757 if (opts->include == 0)
759 opts->include = first;
763 llassert (opts->last_include->next == NULL);
764 opts->last_include->next = first;
767 if (opts->first_bracket_include == 0)
769 opts->first_bracket_include = first;
771 for (dir = first; ; dir = dir->next) {
772 size_t len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
774 if (len > pfile->max_include_len)
776 pfile->max_include_len = len;
786 llassert (last->next == NULL);
787 /* last->next = NULL; */
788 opts->last_include = last;
792 static /*@unused@*/ void
793 cppReader_showIncludeChain (cppReader *pfile)
795 struct file_name_list *dirs = CPPOPTIONS (pfile)->include;
801 fprintf (stderr, "*%s*:", cstring_toCharsSafe (dirs->fname));
805 fprintf (stderr, "\n");
809 fprintf (stderr, "No includes\n");
815 cppReader_getIncludePath ()
817 cppReader *pfile = &g_cppState;
818 struct file_name_list *dirs = CPPOPTIONS (pfile)->include;
819 cstring res = cstring_undefined;
825 res = message ("%q%c%s", res, PATH_SEPARATOR, dirs->fname);
831 res = cstring_makeLiteral ("<no include path>");
838 cppReader_addIncludeChain (cppReader *pfile, /*@only@*/ struct file_name_list *dir)
840 struct cppOptions *opts = CPPOPTIONS (pfile);
847 if (opts->include == 0)
853 llassert (opts->last_include->next == NULL);
854 opts->last_include->next = dir;
857 if (opts->first_bracket_include == 0)
859 size_t len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
860 opts->first_bracket_include = dir;
862 if (len > pfile->max_include_len)
864 pfile->max_include_len = len;
869 opts->last_include = dir;
870 /* cppReader_showIncludeChain (pfile); */
873 /* Given a colon-separated list of file names PATH,
874 add all the names to the search path for include files. */
877 path_include (cppReader *pfile, char *path)
884 /* if we have a posix path list, convert to win32 path list */
885 win32temp = (char *) dmalloc /*@i4@*/
886 (cygwin32_posix_to_win32_path_list_buf_size (path));
887 cygwin32_posix_to_win32_path_list (path, win32temp);
897 struct file_name_list *dirtmp;
899 /* Find the end of this name. */
900 while (*q != '\0' && *q != PATH_SEPARATOR)
907 /* An empty name in the path stands for the current directory. */
908 name = (char *) dmalloc ((size_t) 2);
914 /* Otherwise use the directory that is named. */
915 name = (char *) dmalloc (size_fromInt (q - p + 1));
916 memcpy (name, p, size_fromInt (q - p));
920 dirtmp = (struct file_name_list *) dmalloc (sizeof (*dirtmp));
921 dirtmp->next = 0; /* New one goes on the end */
922 dirtmp->control_macro = 0;
923 dirtmp->c_system_include_path = 0;
924 dirtmp->fname = cstring_fromChars (name);
925 dirtmp->got_name_map = 0;
926 cppReader_addIncludeChain (pfile, dirtmp);
928 /* Advance past this name. */
932 /* Skip the colon. */
938 cppOptions_init (cppOptions *opts)
940 memset ((char *) opts, 0, sizeof *opts);
943 opts->in_fname = NULL;
944 opts->out_fname = NULL;
946 /* Initialize is_idchar to allow $. */
947 opts->dollars_in_ident = TRUE;
949 opts->no_line_commands = 0;
950 opts->no_trigraphs = TRUE;
951 opts->put_out_comments = 1;
952 opts->print_include_names = 0;
953 opts->dump_macros = DUMP_DEFINITIONS; /* DUMP_NONE; */
957 opts->cplusplus_comments = 1;
962 opts->pedantic_errors = 0;
963 opts->warn_comments = 0;
964 opts->warnings_are_errors = 0;
966 initialize_char_syntax (opts);
970 cppReader_nullUnderflow (/*@unused@*/ cppReader *pfile)
976 cppReader_nullCleanup (/*@unused@*/ cppBuffer *pbuf,
977 /*@unused@*/ cppReader *pfile)
983 cppReader_macroCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
985 hashNode macro = pbuf->hnode;
987 if (macro->type == T_DISABLED)
989 macro->type = T_MACRO;
992 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
1000 cppReader_fileCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
1002 if (pbuf->buf != NULL)
1009 /* Assuming we have read '/'.
1010 If this is the start of a comment (followed by '*' or '/'),
1011 skip to the end of the comment, and return ' '.
1012 Return EOF if we reached the end of file before the end of the comment.
1013 If not the start of a comment, return '/'. */
1016 skip_comment (cppReader *pfile, /*@null@*/ long *linep)
1020 llassert (pfile->buffer != NULL);
1021 llassert (pfile->buffer->cur != NULL);
1023 while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n')
1030 cppReader_forward (pfile, 2);
1033 if (cppReader_peekC (pfile) == '*')
1035 cppReader_forward (pfile, 1);
1040 c = cppReader_getC (pfile);
1047 while (c == (int) '\\' && cppReader_peekC (pfile) == (int) '\n')
1054 cppReader_forward (pfile, 1), c = cppReader_getC (pfile);
1057 if (prev_c == (int) '*' && c == (int) '/')
1062 if (c == (int) '\n' && (linep != NULL))
1068 else if (cppReader_peekC (pfile) == '/'
1069 && CPPOPTIONS (pfile)->cplusplus_comments)
1072 (void) cppoptgenerror
1073 (FLG_SLASHSLASHCOMMENT,
1074 message ("C++ style // comment"
1078 cppReader_forward (pfile, 1);
1082 c = cppReader_getC (pfile);
1086 /* Allow hash comment to be terminated by EOF. */
1090 while (c == (int) '\\' && cppReader_peekC (pfile) == '\n')
1092 cppReader_forward (pfile, 1);
1093 c = cppReader_getC (pfile);
1101 if (c == (int) '\n')
1103 /* Don't consider final '\n' to be part of comment. */
1104 cppReader_forward (pfile, -1);
1115 /* Skip whitespace \-newline and comments. Does not macro-expand. */
1117 cppSkipHspace (cppReader *pfile)
1125 llassert (pfile->buffer != NULL);
1127 c = cppReader_peekC (pfile);
1131 return 0; /* FIXME */
1134 if (is_hor_space[c])
1136 if ((c == '\f' || c == '\v') && cppReader_isPedantic (pfile))
1137 cppReader_pedwarn (pfile,
1138 message ("%s in preprocessing directive",
1140 ? cstring_makeLiteralTemp ("formfeed")
1141 : cstring_makeLiteralTemp ("vertical tab")));
1144 cppReader_forward (pfile, 1);
1148 cppReader_forward (pfile, 1);
1149 c = skip_comment (pfile, NULL);
1153 cppReader_forward (pfile, -1);
1156 if (c == EOF || c == '/')
1161 else if (c == '\\' && cpp_peekN (pfile, 1) == '\n')
1163 cppReader_forward (pfile, 2);
1165 else if (c == '@' && CPPBUFFER (pfile)->has_escapes
1166 && is_hor_space [cpp_peekN (pfile, 1)])
1168 cppReader_forward (pfile, 2);
1177 /* Read the rest of the current line.
1178 The line is appended to PFILE's output buffer. */
1181 copy_rest_of_line (cppReader *pfile)
1183 struct cppOptions *opts = CPPOPTIONS (pfile);
1190 llassert (pfile->buffer != NULL);
1192 c = cppReader_getC (pfile);
1200 ** Patch from Brian St. Pierre for handling MS-DOS files.
1203 DPRINTF (("Reading directive: %d", (int) c));
1205 if (cppReader_peekC (pfile) == '\n'
1206 || cppReader_peekC (pfile) == '\r')
1208 DPRINTF (("Reading directive..."));
1209 if (cppReader_peekC (pfile) == '\r')
1211 DPRINTF (("Reading directive..."));
1212 cppReader_forward (pfile, 1);
1215 DPRINTF (("Reading directive..."));
1216 cppReader_forward (pfile, 1);
1220 DPRINTF (("Falling..."));
1221 /*@fallthrough@*/ case '\'': case '\"':
1222 goto scan_directive_token;
1225 nextc = cppReader_peekC (pfile);
1228 ** was (opts->cplusplus_comments && nextc == '*')
1233 || (opts->cplusplus_comments && nextc == '/'))
1235 goto scan_directive_token;
1237 /*@switchbreak@*/ break;
1240 if (cppReader_isPedantic (pfile))
1241 cppReader_pedwarn (pfile,
1242 message ("%s in preprocessing directive",
1244 ? cstring_makeLiteralTemp ("formfeed")
1245 : cstring_makeLiteralTemp ("vertical tab")));
1246 /*@switchbreak@*/ break;
1249 cppReader_forward (pfile, -1);
1251 scan_directive_token:
1252 cppReader_forward (pfile, -1);
1253 (void) cpplib_getToken (pfile);
1256 cppReader_putChar (pfile, c);
1259 cppReader_nullTerminate (pfile);
1263 cppReader_skipRestOfLine (cppReader *pfile)
1265 size_t old = cpplib_getWritten (pfile);
1266 copy_rest_of_line (pfile);
1267 cppReader_setWritten (pfile, old);
1270 /* Handle a possible # directive.
1271 '#' has already been read. */
1274 cppReader_handleDirective (cppReader *pfile)
1277 struct directive *kt = NULL;
1279 size_t after_ident = 0;
1281 char *line_end = NULL;
1282 size_t old_written = cpplib_getWritten (pfile);
1283 int nspaces = cppSkipHspace (pfile);
1285 c = cppReader_peekC (pfile);
1287 if (c >= '0' && c <= '9')
1289 /* Handle # followed by a line number. */
1290 if (cppReader_isPedantic (pfile))
1292 cppReader_pedwarnLit
1294 cstring_makeLiteralTemp ("`#' followed by integer"));
1297 (void) do_line (pfile, NULL);
1298 goto done_a_directive;
1302 /* Now find the directive name. */
1304 cppReader_putChar (pfile, '#');
1306 parse_name (pfile, cppReader_getC (pfile));
1308 llassert (pfile->token_buffer != NULL);
1309 ident = pfile->token_buffer + old_written + 1;
1311 ident_length = cpplib_getPWritten (pfile) - ident;
1313 if (ident_length == 0 && cppReader_peekC (pfile) == '\n')
1315 /* A line of just `#' becomes blank. */
1319 for (kt = directive_table; ; kt++)
1321 if (kt->length <= 0)
1323 return 0; /* goto not_a_directive; */
1326 if (kt->length == ident_length
1327 && (cstring_equalPrefix (kt->name, cstring_fromChars (ident))))
1333 if (kt->command_reads_line)
1339 /* Nonzero means do not delete comments within the directive.
1340 #define needs this when -traditional. */
1341 bool comments = 1; /*cppReader_isTraditional (pfile) && kt->traditional_comments; */
1342 int save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
1343 CPPOPTIONS (pfile)->put_out_comments = comments;
1344 after_ident = cpplib_getWritten (pfile);
1345 copy_rest_of_line (pfile);
1346 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
1350 /* For #pragma and #define, we may want to pass through the directive.
1351 Other directives may create output, but we don't want the directive
1352 itself out, so we pop it now. For example #include may write a #line
1353 command (see comment in do_include), and conditionals may emit
1354 #failed ... #endfailed stuff. But note that popping the buffer
1355 means the parameters to kt->func may point after pfile->limit
1356 so these parameters are invalid as soon as something gets appended
1357 to the token_buffer. */
1359 line_end = cpplib_getPWritten (pfile);
1362 if (!kt->pass_thru && kt->type != T_DEFINE)
1364 cppReader_setWritten (pfile, old_written);
1367 llassert (pfile->token_buffer != NULL);
1369 /* was kt->pass_thru || */
1371 if (kt->type == T_DEFINE
1372 && cpp_shouldCheckMacro (pfile, pfile->token_buffer + old_written))
1374 char *p = pfile->token_buffer + old_written;
1377 ** Still need to record value for preprocessing, so
1378 ** #ifdef's, etc. using the value behave correctly.
1381 (void) do_defineAux (pfile, kt,
1382 pfile->token_buffer + after_ident,
1391 SKIP_WHITE_SPACE (p);
1393 llassert (*p == 'd');
1396 llassert (*p == 'e');
1399 llassert (*p == 'f');
1402 llassert (*p == 'i');
1405 llassert (*p == 'n');
1408 llassert (*p == 'e');
1411 ** This is way-bogus. We use the last char to record the number of
1412 ** spaces. Its too hard to get them back into the input stream.
1415 if (nspaces > 9) nspaces = 9;
1417 *p++ = '0' + nspaces;
1419 return 0; /* not_a_directive */
1421 else if (kt->pass_thru)
1423 /* Just leave the entire #define in the output stack. */
1424 return 0; /* not_a_directive */
1427 else if (kt->type == T_DEFINE
1428 && CPPOPTIONS (pfile)->dump_macros == DUMP_NAMES)
1430 char *p = pfile->token_buffer + old_written + 7; /* Skip "#define". */
1431 SKIP_WHITE_SPACE (p);
1433 while (is_idchar[(int) *p])
1439 cppReader_putChar (pfile, '\n');
1441 else if (kt->type == T_DEFINE)
1443 cppReader_setWritten (pfile, old_written);
1454 llassert (kt->func != NULL);
1455 (void) (kt->func) (pfile, kt, pfile->token_buffer + after_ident, line_end);
1460 /* Pass a directive through to the output file.
1461 BUF points to the contents of the directive, as a contiguous string.
1462 LIMIT points to the first character past the end of the directive.
1463 KEYWORD is the keyword-table entry for the directive. */
1466 pass_thru_directive (char *buf, char *limit,
1468 struct directive *keyword)
1470 int keyword_length = keyword->length;
1472 cpplib_reserve (pfile,
1473 size_fromInt (2 + keyword_length + (limit - buf)));
1474 cppReader_putCharQ (pfile, '#');
1475 /*@-observertrans@*/
1476 cppReader_putStrN (pfile, cstring_toCharsSafe (keyword->name),
1477 size_fromInt (keyword_length));
1478 /*:=observertrans@*/
1480 if (limit != buf && buf[0] != ' ')
1482 /* Was a bug, since reserve only used 1 + ... */
1483 cppReader_putCharQ (pfile, ' ');
1486 cppReader_putStrN (pfile, buf, size_fromInt (limit - buf));
1489 /* Read a replacement list for a macro with parameters.
1490 Build the DEFINITION structure.
1491 Reads characters of text starting at BUF until END.
1492 ARGLIST specifies the formal parameters to look for
1493 in the text of the definition; NARGS is the number of args
1494 in that list, or -1 for a macro name that wants no argument list.
1495 MACRONAME is the macro name itself (so we can avoid recursive expansion)
1496 and NAMELEN is its length in characters.
1498 Note that comments, backslash-newlines, and leading white space
1499 have already been deleted from the argument. */
1502 collect_expansion (cppReader *pfile, char *buf, char *limit,
1503 int nargs, /*@null@*/ struct arglist *arglist)
1506 char *p, *lastp, *exp_p;
1507 struct reflist *endpat = NULL;
1508 /* Pointer to first nonspace after last ## seen. */
1510 /* Pointer to first nonspace after last single-# seen. */
1511 char *stringify = 0;
1513 char expected_delimiter = '\0';
1516 /* Scan thru the replacement list, ignoring comments and quoted
1517 strings, picking up on the macro calls. It does a linear search
1518 thru the arg list on every potential symbol. Profiling might say
1519 that something smarter should happen. */
1524 /* Find the beginning of the trailing whitespace. */
1527 while (p < limit && is_space[(int) limit[-1]])
1532 /* Allocate space for the text in the macro definition.
1533 Leading and trailing whitespace chars need 2 bytes each.
1534 Each other input char may or may not need 1 byte,
1535 so this is an upper bound. The extra 5 are for invented
1536 leading and trailing newline-marker and final null. */
1537 maxsize = (sizeof (*defn) + (limit - p) + 5);
1539 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1548 defn = (DEFINITION *) dmalloc (maxsize);
1549 defn->noExpand = FALSE;
1551 defn->pattern = NULL;
1552 defn->nargs = nargs;
1553 defn->predefined = NULL;
1555 exp_p = defn->expansion = (char *) defn + sizeof (*defn);
1558 defn->rest_args = NULL;
1559 defn->args.argnames = NULL;
1565 /* Add one initial space escape-marker to prevent accidental
1566 token-pasting (often removed by cpplib_macroExpand). */
1570 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1571 cppReader_errorLit (pfile,
1572 cstring_makeLiteralTemp ("`##' at start of macro definition"));
1576 /* Process the main body of the definition. */
1578 int skipped_arg = 0;
1579 register char c = *p++;
1583 if (!cppReader_isTraditional (pfile)) {
1587 if (expected_delimiter != '\0')
1589 if (c == expected_delimiter)
1590 expected_delimiter = '\0';
1594 expected_delimiter = c;
1596 /*@switchbreak@*/ break;
1599 if (p < limit && (expected_delimiter != '\0'))
1601 /* In a string, backslash goes through
1602 and makes next char ordinary. */
1605 /*@switchbreak@*/ break;
1608 /* An '@' in a string or character constant stands for itself,
1609 and does not need to be escaped. */
1610 if (expected_delimiter == '\0')
1615 /*@switchbreak@*/ break;
1618 /* # is ordinary inside a string. */
1619 if (expected_delimiter != '\0')
1621 /*@switchbreak@*/ break;
1624 if (p < limit && *p == '#') {
1625 /* ##: concatenate preceding and following tokens. */
1626 /* Take out the first #, discard preceding whitespace. */
1630 while (exp_p > lastp && is_hor_space[(int) exp_p[-1]])
1636 /* Skip the second #. */
1638 /* Discard following whitespace. */
1639 SKIP_WHITE_SPACE (p);
1643 cppReader_errorLit (pfile,
1644 cstring_makeLiteralTemp ("`##' at end of macro definition"));
1646 } else if (nargs >= 0) {
1647 /* Single #: stringify following argument ref.
1648 Don't leave the # in the expansion. */
1650 SKIP_WHITE_SPACE (p);
1651 if (p == limit || ! is_idstart[(int) *p]
1652 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '\"')))
1653 cppReader_errorLit (pfile,
1654 cstring_makeLiteralTemp ("`#' operator is not followed by a macro argument name"));
1661 /*@switchbreak@*/ break;
1664 /* In -traditional mode, recognize arguments inside strings and
1665 and character constants, and ignore special properties of #.
1666 Arguments inside strings are considered "stringified", but no
1667 extra quote marks are supplied. */
1671 if (expected_delimiter != '\0') {
1672 if (c == expected_delimiter)
1673 expected_delimiter = '\0';
1675 expected_delimiter = c;
1676 /*@switchbreak@*/ break;
1679 /* Backslash quotes delimiters and itself, but not macro args. */
1680 if (expected_delimiter != '\0' && p < limit
1681 && (*p == expected_delimiter || *p == '\\')) {
1685 /*@switchbreak@*/ break;
1688 if (expected_delimiter != '\0') /* No comments inside strings. */
1689 /*@switchbreak@*/ break;
1691 /* If we find a comment that wasn't removed by cppReader_handleDirective,
1692 this must be -traditional. So replace the comment with
1696 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
1701 /*@switchbreak@*/ break;
1705 /* Handle the start of a symbol. */
1706 if (is_idchar[(int) c] && nargs > 0) {
1707 char *id_beg = p - 1;
1711 while (p != limit && is_idchar[(int) *p])
1716 id_len = size_fromInt (p - id_beg);
1718 if (is_idstart[(int) c]
1719 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '\"'))) {
1720 register struct arglist *arg;
1722 for (arg = arglist; arg != NULL; arg = arg->next) {
1723 struct reflist *tpat;
1725 if (arg->name[0] == c
1726 && arg->length == id_len
1727 && strncmp (arg->name, id_beg, id_len) == 0) {
1730 if (expected_delimiter && CPPOPTIONS (pfile)->warn_stringify) {
1731 if (cppReader_isTraditional (pfile)) {
1732 cppReader_warning (pfile,
1733 message ("macro argument `%x' is stringified.",
1734 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1736 cppReader_warning (pfile,
1737 message ("macro arg `%x' would be stringified with -traditional.",
1738 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1741 /* If ANSI, don't actually substitute inside a string. */
1742 if (!cppReader_isTraditional (pfile) && expected_delimiter)
1743 /*@innerbreak@*/ break;
1744 /* make a pat node for this arg and append it to the end of
1746 tpat = (struct reflist *) dmalloc (sizeof (*tpat));
1748 tpat->raw_before = (concat == id_beg);
1749 tpat->raw_after = 0;
1750 tpat->rest_args = arg->rest_args;
1751 tpat->stringify = (cppReader_isTraditional (pfile)
1752 ? expected_delimiter != '\0'
1753 : stringify == id_beg);
1757 defn->pattern = tpat;
1761 endpat->next = tpat;
1763 } /*@=branchstate@*/ /* evs 2000 was =branchstate */
1767 tpat->argno = arg->argno;
1768 tpat->nchars = exp_p - lastp;
1772 SKIP_WHITE_SPACE (p1);
1774 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
1776 tpat->raw_after = 1;
1779 lastp = exp_p; /* place to start copying from next time */
1782 /*@innerbreak@*/ break;
1787 /* If this was not a macro arg, copy it into the expansion. */
1788 if (skipped_arg == 0) {
1789 register char *lim1 = p;
1797 if (stringify == id_beg)
1798 cppReader_errorLit (pfile,
1799 cstring_makeLiteralTemp ("`#' operator should be followed by a macro argument name"));
1804 if (!cppReader_isTraditional (pfile) && expected_delimiter == '\0')
1806 /* If ANSI, put in a "@ " marker to prevent token pasting.
1807 But not if "inside a string" (which in ANSI mode
1808 happens only for -D option). */
1815 defn->length = size_fromInt (exp_p - defn->expansion);
1817 /* Crash now if we overrun the allocated size. */
1818 if (defn->length + 1 > maxsize)
1820 llfatalbug (cstring_makeLiteral ("Maximum definition size exceeded."));
1828 ** Gasp...cut-and-pasted from above to deal with pfile (should replace throughout with this...)
1832 collect_expansionLoc (fileloc loc, char *buf, char *limit,
1833 int nargs, /*@null@*/ struct arglist *arglist)
1836 char *p, *lastp, *exp_p;
1837 struct reflist *endpat = NULL;
1838 /* Pointer to first nonspace after last ## seen. */
1840 /* Pointer to first nonspace after last single-# seen. */
1841 char *stringify = 0;
1843 char expected_delimiter = '\0';
1846 /* Scan thru the replacement list, ignoring comments and quoted
1847 strings, picking up on the macro calls. It does a linear search
1848 thru the arg list on every potential symbol. Profiling might say
1849 that something smarter should happen. */
1853 llfatalbug (message ("%q: Limit is less than initial buffer pointer",
1854 fileloc_unparse (loc)));
1857 /* Find the beginning of the trailing whitespace. */
1860 while (p < limit && is_space[(int) limit[-1]])
1865 /* Allocate space for the text in the macro definition.
1866 Leading and trailing whitespace chars need 2 bytes each.
1867 Each other input char may or may not need 1 byte,
1868 so this is an upper bound. The extra 5 are for invented
1869 leading and trailing newline-marker and final null. */
1870 maxsize = (sizeof (*defn) + (limit - p) + 5);
1872 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1881 defn = (DEFINITION *) dmalloc (maxsize);
1882 defn->noExpand = FALSE;
1884 defn->pattern = NULL;
1885 defn->nargs = nargs;
1886 defn->predefined = NULL;
1888 exp_p = defn->expansion = (char *) defn + sizeof (*defn);
1891 defn->rest_args = NULL;
1892 defn->args.argnames = NULL;
1898 /* Add one initial space escape-marker to prevent accidental
1899 token-pasting (often removed by cpplib_macroExpand). */
1903 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1904 voptgenerror (FLG_PREPROC,
1905 cstring_makeLiteral ("Paste marker ## at start of macro definition"),
1910 /* Process the main body of the definition. */
1912 int skipped_arg = 0;
1913 register char c = *p++;
1917 if (TRUE) { /* !cppReader_isTraditional (pfile)) { */
1921 if (expected_delimiter != '\0')
1923 if (c == expected_delimiter)
1924 expected_delimiter = '\0';
1928 expected_delimiter = c;
1930 /*@switchbreak@*/ break;
1933 if (p < limit && (expected_delimiter != '\0'))
1935 /* In a string, backslash goes through
1936 and makes next char ordinary. */
1939 /*@switchbreak@*/ break;
1942 /* An '@' in a string or character constant stands for itself,
1943 and does not need to be escaped. */
1944 if (expected_delimiter == '\0')
1949 /*@switchbreak@*/ break;
1952 /* # is ordinary inside a string. */
1953 if (expected_delimiter != '\0')
1955 /*@switchbreak@*/ break;
1958 if (p < limit && *p == '#') {
1959 /* ##: concatenate preceding and following tokens. */
1960 /* Take out the first #, discard preceding whitespace. */
1964 while (exp_p > lastp && is_hor_space[(int) exp_p[-1]])
1970 /* Skip the second #. */
1972 /* Discard following whitespace. */
1973 SKIP_WHITE_SPACE (p);
1977 voptgenerror (FLG_PREPROC,
1978 cstring_makeLiteral ("`##' at end of macro definition"),
1981 } else if (nargs >= 0) {
1982 /* Single #: stringify following argument ref.
1983 Don't leave the # in the expansion. */
1985 SKIP_WHITE_SPACE (p);
1986 if (p == limit || ! is_idstart[(int) *p]
1987 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '\"')))
1991 cstring_makeLiteral ("`#' operator is not followed by a macro argument name"),
2000 /*@switchbreak@*/ break;
2003 /* In -traditional mode, recognize arguments inside strings and
2004 and character constants, and ignore special properties of #.
2005 Arguments inside strings are considered "stringified", but no
2006 extra quote marks are supplied. */
2010 if (expected_delimiter != '\0') {
2011 if (c == expected_delimiter)
2012 expected_delimiter = '\0';
2014 expected_delimiter = c;
2015 /*@switchbreak@*/ break;
2018 /* Backslash quotes delimiters and itself, but not macro args. */
2019 if (expected_delimiter != '\0' && p < limit
2020 && (*p == expected_delimiter || *p == '\\')) {
2024 /*@switchbreak@*/ break;
2027 if (expected_delimiter != '\0') /* No comments inside strings. */
2028 /*@switchbreak@*/ break;
2030 /* If we find a comment that wasn't removed by cppReader_handleDirective,
2031 this must be -traditional. So replace the comment with
2035 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
2040 /*@switchbreak@*/ break;
2044 /* Handle the start of a symbol. */
2045 if (is_idchar[(int) c] && nargs > 0) {
2046 char *id_beg = p - 1;
2050 while (p != limit && is_idchar[(int) *p])
2055 id_len = size_fromInt (p - id_beg);
2057 if (is_idstart[(int) c]
2058 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '\"'))) {
2059 register struct arglist *arg;
2061 for (arg = arglist; arg != NULL; arg = arg->next) {
2062 struct reflist *tpat;
2064 if (arg->name[0] == c
2065 && arg->length == id_len
2066 && strncmp (arg->name, id_beg, id_len) == 0) {
2069 if (expected_delimiter) { /* && CPPOPTIONS (pfile)->warn_stringify) { */
2070 if (FALSE) { /* cppReader_isTraditional (pfile)) { */
2071 voptgenerror (FLG_PREPROC,
2072 message ("macro argument `%x' is stringified.",
2073 cstring_prefix (cstring_fromChars (arg->name), id_len)),
2077 voptgenerror (FLG_PREPROC,
2078 message ("Macro arg `%x' would be stringified with -traditional.",
2079 cstring_prefix (cstring_fromChars (arg->name), id_len)),
2084 /* If ANSI, don't actually substitute inside a string. */
2085 if (TRUE /* !cppReader_isTraditional (pfile) */ && expected_delimiter)
2086 /*@innerbreak@*/ break;
2087 /* make a pat node for this arg and append it to the end of
2089 tpat = (struct reflist *) dmalloc (sizeof (*tpat));
2091 tpat->raw_before = (concat == id_beg);
2092 tpat->raw_after = 0;
2093 tpat->rest_args = arg->rest_args;
2094 tpat->stringify = (FALSE /* cppReader_isTraditional (pfile) */
2095 ? expected_delimiter != '\0'
2096 : stringify == id_beg);
2100 defn->pattern = tpat;
2104 endpat->next = tpat;
2106 } /*@=branchstate@*/ /* evs 2000 was =branchstate */
2110 tpat->argno = arg->argno;
2111 tpat->nchars = exp_p - lastp;
2115 SKIP_WHITE_SPACE (p1);
2117 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
2119 tpat->raw_after = 1;
2122 lastp = exp_p; /* place to start copying from next time */
2125 /*@innerbreak@*/ break;
2130 /* If this was not a macro arg, copy it into the expansion. */
2131 if (skipped_arg == 0) {
2132 register char *lim1 = p;
2140 if (stringify == id_beg)
2144 cstring_makeLiteral ("# operator should be followed by a macro argument name"),
2151 if (/*!cppReader_isTraditional (pfile) && */ expected_delimiter == '\0')
2153 /* If ANSI, put in a "@ " marker to prevent token pasting.
2154 But not if "inside a string" (which in ANSI mode
2155 happens only for -D option). */
2162 defn->length = size_fromInt (exp_p - defn->expansion);
2164 /* Crash now if we overrun the allocated size. */
2165 if (defn->length + 1 > maxsize)
2167 llfatalbug (cstring_makeLiteral ("Maximum definition size exceeded."));
2174 * special extension string that can be added to the last macro argument to
2175 * allow it to absorb the "rest" of the arguments when expanded. Ex:
2176 * #define wow(a, b...) process (b, a, b)
2177 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
2178 * { wow (one, two); } -> { process (two, one, two); }
2179 * if this "rest_arg" is used with the concat token '##' and if it is not
2180 * supplied then the token attached to with ## will not be outputted. Ex:
2181 * #define wow (a, b...) process (b ## , a, ## b)
2182 * { wow (1, 2); } -> { process (2, 1, 2); }
2183 * { wow (one); } -> { process (one); {
2186 /*@-readonlytrans@*/
2187 static char rest_extension[] = "...";
2188 /*:=readonlytrans@*/
2191 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
2193 /* Create a DEFINITION node from a #define directive. Arguments are
2194 as for do_define. */
2197 static /*@null@*/ macroDef
2198 create_definition (/*@exposed@*/ char *buf, char *limit,
2199 cppReader *pfile, bool predefinition,
2202 char *bp; /* temp ptr into input buffer */
2203 char *symname; /* remember where symbol name starts */
2204 size_t sym_length; /* and how long it is */
2205 int rest_args = 0; /* really int! */
2208 cstring file = (CPPBUFFER (pfile) != NULL)
2209 ? CPPBUFFER (pfile)->nominal_fname : cstring_makeLiteralTemp ("");
2211 int arglengths = 0; /* Accumulate lengths of arg names
2212 plus number of args. */
2216 DPRINTF (("Create definition: %s", buf));
2219 cppBuffer_getLineAndColumn (CPPBUFFER (pfile), &line, &col);
2223 while (is_hor_space[(int) *bp])
2228 symname = bp; /* remember where it starts */
2230 sym_length = cppReader_checkMacroName (pfile, bp, cstring_makeLiteralTemp ("macro"));
2234 /* Lossage will occur if identifiers or control keywords are broken
2235 across lines using backslash. This is not the right place to take
2239 struct arglist *arg_ptrs = NULL;
2242 bp++; /* skip '(' */
2243 SKIP_WHITE_SPACE (bp);
2245 /* Loop over macro argument names. */
2248 struct arglist *temp = (struct arglist *) dmalloc (sizeof (*temp));
2250 temp->next = arg_ptrs;
2251 temp->argno = argno++;
2252 temp->rest_args = 0;
2258 cppReader_pedwarn (pfile,
2259 message ("another parameter follows `%s'",
2260 cstring_fromChars (rest_extension)));
2263 if (!is_idstart[(int) *bp])
2265 cppReader_pedwarnLit (pfile,
2266 cstring_makeLiteralTemp ("Invalid character in macro parameter name"));
2269 /* Find the end of the arg name. */
2270 while (is_idchar[(int) *bp])
2273 /* do we have a "special" rest-args extension here? */
2274 if (limit - bp > size_toInt (REST_EXTENSION_LENGTH)
2275 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
2278 temp->rest_args = 1;
2279 /*@innerbreak@*/ break;
2283 temp->length = size_fromInt (bp - temp->name);
2287 bp += REST_EXTENSION_LENGTH;
2290 arglengths += temp->length + 2;
2291 SKIP_WHITE_SPACE (bp);
2293 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
2294 cppReader_errorLit (pfile,
2295 cstring_makeLiteralTemp ("Parameter list for #define is not parseable"));
2301 SKIP_WHITE_SPACE (bp);
2304 cppReader_errorLit (pfile,
2305 cstring_makeLiteralTemp ("unterminated parameter list in `#define'"));
2309 struct arglist *otemp;
2311 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
2313 if (temp->length == otemp->length &&
2314 strncmp (temp->name, otemp->name, temp->length) == 0) {
2315 cstring name = cstring_copyLength (temp->name, temp->length);
2316 cppReader_error (pfile,
2317 message ("duplicate argument name `%x' in `#define'", name));
2324 ++bp; /* skip paren */
2325 SKIP_WHITE_SPACE (bp);
2326 /* now everything from bp before limit is the definition. */
2327 defn = collect_expansion (pfile, bp, limit, argno, arg_ptrs);
2328 defn->rest_args = rest_args;
2330 /* Now set defn->args.argnames to the result of concatenating
2331 the argument names in reverse order
2332 with comma-space between them. */
2333 defn->args.argnames = (char *) dmalloc (size_fromInt (arglengths + 1));
2336 struct arglist *temp;
2338 for (temp = arg_ptrs; temp != NULL; temp = temp->next)
2340 memcpy (&defn->args.argnames[i], temp->name, temp->length);
2342 if (temp->next != 0)
2344 defn->args.argnames[i++] = ',';
2345 defn->args.argnames[i++] = ' ';
2349 defn->args.argnames[i] = '\0';
2354 /* Simple expansion or empty definition. */
2358 if (is_hor_space[(int) *bp]) {
2360 SKIP_WHITE_SPACE (bp);
2363 case '!': case '\"': case '#': case '%': case '&': case '\'':
2364 case ')': case '*': case '+': case ',': case '-': case '.':
2365 case '/': case ':': case ';': case '<': case '=': case '>':
2366 case '?': case '[': case '\\': case ']': case '^': case '{':
2367 case '|': case '}': case '~':
2368 cppReader_warning (pfile,
2369 message ("Missing white space after #define %x",
2370 cstring_prefix (cstring_fromChars (symname),
2375 cppReader_pedwarn (pfile,
2376 message ("Missing white space after #define %x",
2377 cstring_prefix (cstring_fromChars (symname),
2383 /* now everything from bp before limit is the definition. */
2384 defn = collect_expansion (pfile, bp, limit, -1, NULL);
2385 defn->args.argnames = mstring_createEmpty ();
2388 defn->noExpand = noExpand;
2389 DPRINTF (("No expand: %d", noExpand));
2393 /* not: llassert (cstring_isUndefined (defn->file)); */
2396 /* OP is null if this is a predefinition */
2397 defn->predefined = predefinition;
2399 mdef.symnam = symname;
2400 mdef.symlen = sym_length;
2411 cpplib_createDefinition (cstring def,
2416 char *buf = cstring_toCharsSafe (def);
2417 char *limit = buf + cstring_length (def);
2418 char *bp; /* temp ptr into input buffer */
2419 char *symname; /* remember where symbol name starts */
2420 size_t sym_length; /* and how long it is */
2421 int rest_args = 0; /* really int! */
2422 int line = fileloc_lineno (loc);
2423 cstring file = fileloc_filename (loc);
2425 int arglengths = 0; /* Accumulate lengths of arg names
2426 plus number of args. */
2431 DPRINTF (("Creating definition: %s", buf));
2433 while (is_hor_space[(int) *bp])
2438 symname = bp; /* remember where it starts */
2440 sym_length = cppReader_checkMacroNameLoc (loc, symname, cstring_makeLiteralTemp ("macro"));
2442 DPRINTF (("length: %d", sym_length));
2446 DPRINTF (("Here: %s", bp));
2448 /* Lossage will occur if identifiers or control keywords are broken
2449 across lines using backslash. This is not the right place to take
2453 struct arglist *arg_ptrs = NULL;
2456 bp++; /* skip '(' */
2457 SKIP_WHITE_SPACE (bp);
2459 /* Loop over macro argument names. */
2462 struct arglist *temp = (struct arglist *) dmalloc (sizeof (*temp));
2464 temp->next = arg_ptrs;
2465 temp->argno = argno++;
2466 temp->rest_args = 0;
2472 voptgenerror (FLG_PREPROC,
2473 message ("Another parameter follows %s",
2474 cstring_fromChars (rest_extension)),
2478 if (!is_idstart[(int) *bp])
2480 voptgenerror (FLG_PREPROC,
2481 message ("Invalid character in macro parameter name: %c", *bp),
2485 /* Find the end of the arg name. */
2486 while (is_idchar[(int) *bp])
2489 /* do we have a "special" rest-args extension here? */
2490 if (limit - bp > size_toInt (REST_EXTENSION_LENGTH)
2491 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
2494 temp->rest_args = 1;
2495 /*@innerbreak@*/ break;
2499 temp->length = size_fromInt (bp - temp->name);
2503 bp += REST_EXTENSION_LENGTH;
2506 arglengths += temp->length + 2;
2507 SKIP_WHITE_SPACE (bp);
2509 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
2510 voptgenerror (FLG_PREPROC,
2511 cstring_makeLiteral ("Parameter list for #define is not parseable"),
2518 SKIP_WHITE_SPACE (bp);
2521 voptgenerror (FLG_PREPROC,
2522 cstring_makeLiteral ("Unterminated parameter list in #define'"),
2527 struct arglist *otemp;
2529 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
2531 if (temp->length == otemp->length &&
2532 strncmp (temp->name, otemp->name, temp->length) == 0) {
2533 cstring name = cstring_copyLength (temp->name, temp->length);
2535 voptgenerror (FLG_PREPROC,
2536 message ("Duplicate argument name in #define: %s", name),
2544 ++bp; /* skip paren */
2545 SKIP_WHITE_SPACE (bp);
2546 /* now everything from bp before limit is the definition. */
2547 defn = collect_expansionLoc (loc, bp, limit, argno, arg_ptrs);
2548 defn->rest_args = rest_args;
2550 /* Now set defn->args.argnames to the result of concatenating
2551 the argument names in reverse order
2552 with comma-space between them. */
2553 defn->args.argnames = (char *) dmalloc (size_fromInt (arglengths + 1));
2556 struct arglist *temp;
2558 for (temp = arg_ptrs; temp != NULL; temp = temp->next) {
2559 memcpy (&defn->args.argnames[i], temp->name, temp->length);
2561 if (temp->next != 0) {
2562 defn->args.argnames[i++] = ',';
2563 defn->args.argnames[i++] = ' ';
2567 defn->args.argnames[i] = '\0';
2572 /* Simple expansion or empty definition. */
2576 if (is_hor_space[(int) *bp]) {
2578 SKIP_WHITE_SPACE (bp);
2581 case '!': case '\"': case '#': case '%': case '&': case '\'':
2582 case ')': case '*': case '+': case ',': case '-': case '.':
2583 case '/': case ':': case ';': case '<': case '=': case '>':
2584 case '?': case '[': case '\\': case ']': case '^': case '{':
2585 case '|': case '}': case '~':
2586 voptgenerror (FLG_PREPROC,
2587 message ("Missing white space after #define %x",
2588 cstring_prefix (cstring_fromChars (symname),
2594 voptgenerror (FLG_PREPROC,
2595 message ("Missing white space after #define %x",
2596 cstring_prefix (cstring_fromChars (symname),
2604 /* now everything from bp before limit is the definition. */
2605 llassert (limit > bp);
2606 defn = collect_expansionLoc (loc, bp, limit, -1, NULL);
2607 defn->args.argnames = mstring_createEmpty ();
2610 defn->noExpand = noExpand;
2611 DPRINTF (("No expand: %d", noExpand));
2615 /* not: llassert (cstring_isUndefined (defn->file)); */
2618 /* OP is null if this is a predefinition */
2619 defn->predefined = predefinition;
2622 mdef.symnam = symname;
2623 mdef.symlen = sym_length;
2633 /* Check a purported macro name SYMNAME, and yield its length.
2634 USAGE is the kind of name this is intended for. */
2636 size_t cppReader_checkMacroName (cppReader *pfile, char *symname, cstring usage)
2641 for (p = symname; is_idchar[(int) *p]; p++)
2646 sym_length = size_fromInt (p - symname);
2649 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '\"')))
2651 cppReader_error (pfile, message ("invalid %s name", usage));
2653 else if (!is_idstart[(int) *symname])
2655 char *msg = (char *) dmalloc (sym_length + 1);
2656 memcpy (msg, symname, sym_length);
2657 msg[sym_length] = '\0';
2658 cppReader_error (pfile, message ("invalid %s name `%s'", usage,
2659 cstring_fromChars (msg)));
2664 if ((strncmp (symname, "defined", 7) == 0) && sym_length == 7)
2666 cppReader_error (pfile, message ("invalid %s name `defined'", usage));
2675 ** Gasp...cut-and-pasted from above to deal with pfile (should replace throughout with this...)
2678 size_t cppReader_checkMacroNameLoc (fileloc loc, char *symname, cstring usage)
2683 for (p = symname; is_idchar[(int) *p]; p++)
2688 sym_length = size_fromInt (p - symname);
2691 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '\"')))
2693 voptgenerror (FLG_PREPROC, message ("Invalid %s name: %s", usage,
2694 cstring_fromChars (symname)), loc);
2696 else if (!is_idstart[(int) *symname])
2698 char *msg = (char *) dmalloc (sym_length + 1);
2699 memcpy (msg, symname, sym_length);
2700 msg[sym_length] = '\0';
2701 voptgenerror (FLG_PREPROC, message ("Invalid %s name: %s", usage,
2702 cstring_fromChars (msg)),
2708 if ((strncmp (symname, "defined", 7) == 0) && sym_length == 7)
2710 voptgenerror (FLG_PREPROC, message ("Invalid %s name: defined", usage), loc);
2717 /* Return zero if two DEFINITIONs are isomorphic. */
2720 compare_defs (DEFINITION *d1, DEFINITION *d2)
2722 register struct reflist *a1, *a2;
2723 register char *p1 = d1->expansion;
2724 register char *p2 = d2->expansion;
2727 if (d1->nargs != d2->nargs)
2732 llassert (d1->args.argnames != NULL);
2733 llassert (d2->args.argnames != NULL);
2735 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames) != 0)
2740 for (a1 = d1->pattern, a2 = d2->pattern;
2741 (a1 != NULL) && (a2 != NULL);
2742 a1 = a1->next, a2 = a2->next) {
2743 if (!((a1->nchars == a2->nchars
2744 && (strncmp (p1, p2, size_fromInt (a1->nchars)) == 0))
2745 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
2746 || a1->argno != a2->argno
2747 || a1->stringify != a2->stringify
2748 || a1->raw_before != a2->raw_before
2749 || a1->raw_after != a2->raw_after)
2758 if (comp_def_part (first, p1, size_toInt (d1->length - (p1 - d1->expansion)),
2759 p2, size_toInt (d2->length - (p2 - d2->expansion)), 1))
2766 ** Return TRUE if two parts of two macro definitions are effectively different.
2767 ** One of the parts starts at BEG1 and has LEN1 chars;
2768 ** the other has LEN2 chars at BEG2.
2769 ** Any sequence of whitespace matches any other sequence of whitespace.
2770 ** FIRST means these parts are the first of a macro definition;
2771 ** so ignore leading whitespace entirely.
2772 ** LAST means these parts are the last of a macro definition;
2773 ** so ignore trailing whitespace entirely.
2777 comp_def_part (bool first, char *beg1, int len1, char *beg2, int len2, bool last)
2779 char *end1 = beg1 + len1;
2780 char *end2 = beg2 + len2;
2783 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2784 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2787 while (beg1 != end1 && is_space[(int) end1[-1]]) { end1--; }
2788 while (beg2 != end2 && is_space[(int) end2[-1]]) { end2--; }
2790 while (beg1 != end1 && beg2 != end2) {
2791 if (is_space[(int) *beg1] && is_space[(int) *beg2]) {
2792 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2793 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2794 } else if (*beg1 == *beg2) {
2798 return (beg1 != end1) || (beg2 != end2);
2802 ** Process a #define command.
2803 ** BUF points to the contents of the #define command, as a contiguous string.
2804 ** LIMIT points to the first character past the end of the definition.
2805 ** KEYWORD is the keyword-table entry for #define,
2806 ** or NULL for a "predefined" macro.
2810 do_defineAux (cppReader *pfile, struct directive *keyword,
2811 /*@exposed@*/ char *buf, char *limit, bool noExpand)
2817 mdef = create_definition (buf, limit, pfile, keyword == NULL, noExpand);
2822 hashcode = cpphash_hashCode (mdef.symnam, mdef.symlen, CPP_HASHSIZE);
2824 if ((hp = cpphash_lookup (mdef.symnam, size_toInt (mdef.symlen), hashcode)) != NULL)
2828 /* Redefining a precompiled key is ok. */
2829 if (hp->type == T_PCSTRING)
2831 /* Redefining a macro is ok if the definitions are the same. */
2832 else if (hp->type == T_MACRO)
2833 ok = !compare_defs (mdef.defn, hp->value.defn);
2834 /* Redefining a constant is ok with -D. */
2835 else if (hp->type == T_CONST)
2836 ok = !CPPOPTIONS (pfile)->done_initializing;
2841 /* Print the warning if it's not ok. */
2845 ** If we are passing through #define and #undef directives, do
2846 ** that for this re-definition now.
2849 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2851 /* llassert (keyword != NULL); */
2852 pass_thru_directive (buf, limit, pfile, keyword);
2855 cpp_setLocation (pfile);
2857 if (hp->type == T_MACRO)
2859 if (hp->value.defn->noExpand)
2861 ; /* error will be reported checking macros */
2867 message ("Macro %q already defined",
2868 cstring_copyLength (mdef.symnam, mdef.symlen)),
2869 message ("%q: Previous definition of %q",
2870 fileloc_unparseRaw (hp->value.defn->file,
2871 (int) hp->value.defn->line),
2872 cstring_copyLength (mdef.symnam, mdef.symlen)));
2877 genppllerror (FLG_MACROREDEF,
2878 message ("Macro %q already defined",
2879 cstring_copyLength (mdef.symnam,
2884 /* Replace the old definition. */
2886 hp->value.defn = mdef.defn;
2891 ** If we are passing through #define and #undef directives, do
2892 ** that for this new definition now.
2897 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2899 pass_thru_directive (buf, limit, pfile, keyword);
2902 DPRINTF (("Define macro: %s / %d",
2903 mdef.symnam, mdef.defn->noExpand));
2905 hn = cpphash_installMacro (mdef.symnam, mdef.symlen, mdef.defn, hashcode);
2907 } /*@=branchstate@*/
2916 do_define (cppReader *pfile, struct directive *keyword,
2917 /*@exposed@*/ char *buf, char *limit)
2919 DPRINTF (("Regular do define"));
2920 return do_defineAux (pfile, keyword, buf, limit, FALSE);
2924 ** This structure represents one parsed argument in a macro call.
2925 ** `raw' points to the argument text as written (`raw_length' is its length).
2926 ** `expanded' points to the argument's macro-expansion
2927 ** (its length is `expand_length').
2928 ** `stringified_length' is the length the argument would have
2930 ** `use_count' is the number of times this macro arg is substituted
2931 ** into the macro. If the actual use count exceeds 10,
2932 ** the value stored is 10.
2935 /* raw and expanded are relative to ARG_BASE */
2937 #define ARG_BASE ((pfile)->token_buffer)
2940 /* Strings relative to pfile->token_buffer */
2946 int stringified_length;
2952 ** Allocate a new cppBuffer for PFILE, and push it on the input buffer stack.
2953 ** If BUFFER != NULL, then use the LENGTH characters in BUFFER
2954 ** as the new input buffer.
2955 ** Return the new buffer, or NULL on failure.
2958 /*@null@*/ /*@exposed@*/ cppBuffer *
2959 cppReader_pushBuffer (cppReader *pfile, char *buffer, size_t length)
2961 cppBuffer *buf = cppReader_getBufferSafe (pfile);
2963 if (buf == pfile->buffer_stack)
2965 cppReader_fatalError
2967 message ("%s: macro or `#include' recursion too deep",
2968 (buf->fname != NULL)
2970 : cstring_makeLiteral ("<no name>")));
2971 sfreeEventually (buffer);
2975 llassert (buf != NULL);
2978 memset ((char *) buf, 0, sizeof (*buf));
2979 DPRINTF (("Pushing buffer: %s", cstring_copyLength (buffer, length)));
2980 CPPBUFFER (pfile) = buf;
2982 buf->if_stack = pfile->if_stack;
2983 buf->cleanup = cppReader_nullCleanup;
2984 buf->underflow = cppReader_nullUnderflow;
2986 buf->cur = buf->buf;
2990 buf->alimit = buf->rlimit = buffer + length;
2994 buf->alimit = buf->rlimit = NULL;
3001 cppReader_popBuffer (cppReader *pfile)
3003 cppBuffer *buf = CPPBUFFER (pfile);
3005 llassert (buf != NULL);
3007 (void) (*buf->cleanup) (buf, pfile);
3008 return ++CPPBUFFER (pfile);
3012 ** Scan until CPPBUFFER (PFILE) is exhausted into PFILE->token_buffer.
3013 ** Pop the buffer when done.
3017 cppReader_scanBuffer (cppReader *pfile)
3019 cppBuffer *buffer = CPPBUFFER (pfile);
3022 enum cpp_token token;
3024 token = cpplib_getToken (pfile);
3026 if (token == CPP_EOF) /* Should not happen ... */
3031 if (token == CPP_POP && CPPBUFFER (pfile) == buffer)
3033 (void) cppReader_popBuffer (pfile);
3040 * Rescan a string (which may have escape marks) into pfile's buffer.
3041 * Place the result in pfile->token_buffer.
3043 * The input is copied before it is scanned, so it is safe to pass
3044 * it something from the token_buffer that will get overwritten
3045 * (because it follows cpplib_getWritten). This is used by do_include.
3049 cpp_expand_to_buffer (cppReader *pfile, char *buf, size_t length)
3051 register cppBuffer *ip;
3052 char *limit = buf + length;
3053 char *buf1, *p1, *p2;
3055 DPRINTF (("Expand to buffer: %s", cstring_copyLength (buf, length)));
3057 /* evans - 2001-08-26
3058 ** length is unsigned - this doesn't make sense
3064 /* Set up the input on the input stack. */
3066 buf1 = (char *) dmalloc (length + 1);
3076 buf1[length] = '\0';
3078 ip = cppReader_pushBuffer (pfile, buf1, length);
3083 ip->has_escapes = TRUE;
3085 /* Scan the input, create the output. */
3086 cppReader_scanBuffer (pfile);
3088 cppReader_nullTerminate (pfile);
3092 adjust_position (char *buf, char *limit, int *linep, int *colp)
3098 (*linep)++, (*colp) = 1;
3104 /* Move line_base forward, updating lineno and colno. */
3107 update_position (cppBuffer *pbuf)
3110 char *new_pos = pbuf->cur;
3111 register struct parse_marker *mark;
3113 llassert (pbuf->buf != NULL);
3114 old_pos = pbuf->buf + pbuf->line_base;
3116 for (mark = pbuf->marks; mark != NULL; mark = mark->next)
3118 if (pbuf->buf + mark->position < new_pos)
3119 new_pos = pbuf->buf + mark->position;
3121 pbuf->line_base += new_pos - old_pos;
3123 llassert (old_pos != NULL);
3124 llassert (new_pos != NULL);
3126 adjust_position (old_pos, new_pos, &pbuf->lineno, &pbuf->colno);
3130 cppBuffer_getLineAndColumn (/*@null@*/ cppBuffer *pbuf, /*@out@*/ int *linep,
3131 /*@null@*/ /*@out@*/ int *colp)
3139 } /*@=branchstate@*/
3143 *linep = pbuf->lineno;
3144 *colp = pbuf->colno;
3146 llassert (pbuf->buf != NULL);
3147 llassert (pbuf->cur != NULL);
3149 adjust_position (pbuf->buf + pbuf->line_base, pbuf->cur, linep, colp);
3158 /* Return the cppBuffer that corresponds to a file (not a macro). */
3160 /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_fileBuffer (cppReader *pfile)
3162 cppBuffer *ip = cppReader_getBuffer (pfile);
3165 ip != NULL && ip != cppReader_nullBuffer (pfile);
3166 ip = cppBuffer_prevBuffer (ip))
3168 if (ip->fname != NULL)
3178 count_newlines (char *buf, char *limit)
3180 register long count = 0;
3192 * write out a #line command, for instance, after an #include file.
3193 * If CONDITIONAL is nonzero, we can omit the #line if it would
3194 * appear to be a no-op, and we can output a few newlines instead
3195 * if we want to increase the line number by a small amount.
3196 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
3200 output_line_command (cppReader *pfile, bool conditional,
3201 enum file_change_code file_change)
3204 cppBuffer *ip = CPPBUFFER (pfile);
3207 llassert (ip != NULL);
3209 if (ip->fname == NULL)
3212 update_position (ip);
3214 if (CPPOPTIONS (pfile)->no_line_commands
3215 || CPPOPTIONS (pfile)->no_output)
3218 buf = CPPBUFFER (pfile);
3220 llassert (buf != NULL);
3225 llassert (ip->cur != NULL);
3227 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
3229 if (CPPOPTIONS (pfile)->no_line_commands)
3233 if (line == pfile->lineno)
3236 /* If the inherited line number is a little too small,
3237 output some newlines instead of a #line command. */
3239 if (line > pfile->lineno && line < pfile->lineno + 8)
3241 cpplib_reserve (pfile, 20);
3242 while (line > pfile->lineno)
3244 cppReader_putCharQ (pfile, '\n');
3252 cpplib_reserve (pfile, 4 * cstring_length (ip->nominal_fname) + 50);
3255 #ifdef OUTPUT_LINE_COMMANDS
3256 static char sharp_line[] = "#line ";
3258 static char sharp_line[] = "# ";
3260 cppReader_putStrN (pfile, sharp_line, sizeof(sharp_line)-1);
3263 sprintf (cpplib_getPWritten (pfile), "%d ", line);
3264 cppReader_adjustWritten (pfile, strlen (cpplib_getPWritten (pfile)));
3266 quote_string (pfile, cstring_toCharsSafe (ip->nominal_fname));
3268 if (file_change != same_file) {
3269 cppReader_putCharQ (pfile, ' ');
3270 cppReader_putCharQ (pfile, file_change == enter_file ? '1' : '2');
3272 /* Tell cc1 if following text comes from a system header file. */
3273 if (ip->system_header_p != '\0') {
3274 cppReader_putCharQ (pfile, ' ');
3275 cppReader_putCharQ (pfile, '3');
3277 #ifndef NO_IMPLICIT_EXTERN_C
3278 /* Tell cc1plus if following text should be treated as C. */
3279 if (ip->system_header_p == (char) 2 && CPPOPTIONS (pfile)->cplusplus) {
3280 cppReader_putCharQ (pfile, ' ');
3281 cppReader_putCharQ (pfile, '4');
3284 cppReader_putCharQ (pfile, '\n');
3285 pfile->lineno = line;
3290 * Parse a macro argument and append the info on PFILE's token_buffer.
3291 * REST_ARGS means to absorb the rest of the args.
3292 * Return nonzero to indicate a syntax error.
3295 static enum cpp_token
3296 macarg (cppReader *pfile, int rest_args)
3299 enum cpp_token token;
3300 char save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
3301 bool oldexpand = pfile->no_macro_expand;
3302 CPPOPTIONS (pfile)->put_out_comments = 1;
3304 /* Try to parse as much of the argument as exists at this
3305 input stack level. */
3307 pfile->no_macro_expand = TRUE;
3311 token = cpplib_getToken (pfile);
3318 /* If we've hit end of file, it's an error (reported by caller).
3319 Ditto if it's the end of cpp_expand_to_buffer text.
3320 If we've hit end of macro, just continue. */
3321 if (!cppBuffer_isMacro (CPPBUFFER (pfile)))
3323 /*@switchbreak@*/ break;
3326 /*@switchbreak@*/ break;
3330 /*@switchbreak@*/ break;
3332 /* if we've returned to lowest level and
3333 we aren't absorbing all args */
3334 if (paren == 0 && rest_args == 0)
3336 /*@switchbreak@*/ break;
3338 /* Remove ',' or ')' from argument buffer. */
3339 cppReader_adjustWritten (pfile, -1);
3347 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
3348 pfile->no_macro_expand = oldexpand;
3354 /* Turn newlines to spaces in the string of length LENGTH at START,
3355 except inside of string constants.
3356 The string is copied into itself with its beginning staying fixed. */
3359 change_newlines (char *start, int length)
3363 register char *limit;
3367 limit = start + length;
3370 while (ibp < limit) {
3371 *obp++ = c = *ibp++;
3376 /* Notice and skip strings, so that we don't delete newlines in them. */
3379 while (ibp < limit) {
3380 *obp++ = c = *ibp++;
3382 /*@innerbreak@*/ break;
3383 if (c == '\n' && quotec == '\'')
3384 /*@innerbreak@*/ break;
3387 /*@switchbreak@*/ break;
3394 static /*@observer@*/ struct tm *
3395 timestamp (/*@returned@*/ cppReader *pfile)
3397 if (pfile->timebuf == NULL)
3399 time_t t = time ((time_t *) 0);
3400 pfile->timebuf = localtime (&t);
3403 llassert (pfile->timebuf != NULL);
3405 return pfile->timebuf;
3408 static ob_mstring monthnames[] = {
3409 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3410 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3414 * expand things like __FILE__. Place the expansion into the output
3415 * buffer *without* rescanning.
3419 special_symbol (hashNode hp, cppReader *pfile)
3421 cstring buf = cstring_undefined;
3427 int paren = 0; /* For special `defined' keyword */
3429 for (ip = cppReader_getBuffer (pfile); ip != NULL; ip = cppBuffer_prevBuffer (ip))
3431 if (ip == cppReader_nullBuffer (pfile))
3433 cppReader_errorLit (pfile,
3434 cstring_makeLiteralTemp ("cccp error: not in any file?!"));
3435 return; /* the show must go on */
3438 if (ip != NULL && ip->fname != NULL)
3450 if (hp->type == T_BASE_FILE)
3452 while (cppBuffer_prevBuffer (ip) != cppReader_nullBuffer (pfile))
3454 ip = cppBuffer_prevBuffer (ip);
3458 llassert (ip != NULL);
3459 string = cstring_toCharsSafe (ip->nominal_fname);
3466 cpplib_reserve (pfile, 3 + 4 * strlen (string));
3467 quote_string (pfile, string);
3470 case T_FUNC: /* added in ISO C99 */
3472 /* We don't know the actual name of the function, but it doesn't matter */
3473 char *string = "** function-name **";
3474 cpplib_reserve (pfile, 3 + 4 * strlen (string));
3475 quote_string (pfile, string);
3479 case T_INCLUDE_LEVEL:
3481 ip = cppReader_getBuffer (pfile);
3483 for (; ip != cppReader_nullBuffer (pfile) && ip != NULL;
3484 ip = cppBuffer_prevBuffer (ip))
3486 if (ip != NULL && ip->fname != NULL)
3492 buf = message ("%d", true_indepth - 1);
3496 buf = cstring_makeLiteral ("\"--- cpp version---\"");
3499 #ifndef NO_BUILTIN_SIZE_TYPE
3501 buf = cstring_makeLiteral (SIZE_TYPE);
3505 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3506 case T_PTRDIFF_TYPE:
3507 buf = cstring_makeLiteral (PTRDIFF_TYPE);
3512 buf = cstring_makeLiteral (cppReader_wcharType (pfile));
3515 case T_USER_LABEL_PREFIX_TYPE:
3516 buf = cstring_makeLiteral (USER_LABEL_PREFIX);
3519 case T_REGISTER_PREFIX_TYPE:
3520 buf = cstring_makeLiteral (REGISTER_PREFIX);
3524 buf = message ("%d", hp->value.ival);
3531 int line = ip->lineno;
3532 int col = ip->colno;
3534 llassert (ip->cur != NULL);
3535 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
3537 buf = message ("%d", (int) line);
3549 char *sbuf = (char *) dmalloc (20);
3550 timebuf = timestamp (pfile);
3551 if (hp->type == T_DATE)
3553 sprintf (sbuf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
3554 timebuf->tm_mday, timebuf->tm_year + 1900);
3558 sprintf (sbuf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
3562 buf = cstring_fromCharsNew (sbuf);
3567 case T_SPEC_DEFINED:
3568 buf = cstring_makeLiteral (" 0 "); /* Assume symbol is not defined */
3569 ip = cppReader_getBuffer (pfile);
3570 llassert (ip != NULL);
3571 llassert (ip->cur != NULL);
3572 SKIP_WHITE_SPACE (ip->cur);
3574 if (*ip->cur == '(')
3577 ip->cur++; /* Skip over the paren */
3578 SKIP_WHITE_SPACE (ip->cur);
3581 if (!is_idstart[(int) *ip->cur])
3583 if (ip->cur[0] == 'L' && (ip->cur[1] == '\'' || ip->cur[1] == '\"'))
3586 if ((hp = cpphash_lookup (ip->cur, -1, -1)) != 0)
3589 buf = cstring_makeLiteral (" 1 ");
3592 while (is_idchar[(int) *ip->cur])
3597 SKIP_WHITE_SPACE (ip->cur);
3601 if (*ip->cur != ')')
3609 cppReader_errorLit (pfile,
3610 cstring_makeLiteralTemp ("`defined' without an identifier"));
3614 cpp_setLocation (pfile);
3615 llfatalerror (message ("Pre-processing error: invalid special hash type"));
3618 len = cstring_length (buf);
3620 cpplib_reserve (pfile, len + 1);
3621 cppReader_putStrN (pfile, cstring_toCharsSafe (buf), len);
3622 cppReader_nullTerminateQ (pfile);
3628 /* Write out a #define command for the special named MACRO_NAME
3629 to PFILE's token_buffer. */
3632 dump_special_to_buffer (cppReader *pfile, char *macro_name)
3634 static char define_directive[] = "#define ";
3635 size_t macro_name_length = strlen (macro_name);
3636 output_line_command (pfile, 0, same_file);
3637 cpplib_reserve (pfile, sizeof(define_directive) + macro_name_length);
3638 cppReader_putStrN (pfile, define_directive, sizeof(define_directive)-1);
3639 cppReader_putStrN (pfile, macro_name, macro_name_length);
3640 cppReader_putCharQ (pfile, ' ');
3641 cpp_expand_to_buffer (pfile, macro_name, macro_name_length);
3642 cppReader_putChar (pfile, '\n');
3645 /* Initialize the built-in macros. */
3648 cpplib_installBuiltin (/*@observer@*/ char *name, ctype ctyp,
3649 int len, enum node_type type,
3650 int ivalue, /*@null@*/ /*@only@*/ char *value,
3653 cstring sname = cstring_fromCharsNew (name);
3655 llassert (usymtab_inGlobalScope ());
3658 ** Be careful here: this is done before the ctype table has
3659 ** been initialized.
3662 if (!usymtab_exists (sname))
3664 uentry ue = uentry_makeConstant (sname, ctyp, fileloc_createBuiltin ());
3666 if (ctype_equal (ctyp, ctype_string))
3668 qualList ql = qualList_new ();
3669 ql = qualList_add (ql, qual_createObserver ());
3670 uentry_reflectQualifiers (ue, ql);
3674 usymtab_addGlobalEntry (ue);
3681 (void) cpphash_install (name, len, type, ivalue, value, hash);
3682 cstring_free (sname);
3686 cpplib_installBuiltinType (/*@observer@*/ char *name, ctype ctyp,
3687 int len, enum node_type type,
3689 /*@only@*/ /*@null@*/ char *value, int hash)
3691 cstring sname = cstring_fromChars (name);
3692 /* evs 2000 07 10 - removed a memory leak, detected by splint */
3694 llassert (usymtab_inGlobalScope ());
3696 if (!usymtab_existsTypeEither (sname))
3698 uentry ue = uentry_makeDatatype (sname, ctyp,
3699 NO, qual_createConcrete (),
3700 fileloc_createBuiltin ());
3701 llassert (!usymtab_existsEither (sname));
3702 usymtab_addGlobalEntry (ue);
3705 (void) cpphash_install (name, len, type, ivalue, value, hash);
3709 initialize_builtins (cppReader *pfile)
3711 cpplib_installBuiltin ("__LINE__", ctype_int, -1, T_SPECLINE, 0, NULL, -1);
3712 cpplib_installBuiltin ("__DATE__", ctype_string, -1, T_DATE, 0, NULL, -1);
3713 cpplib_installBuiltin ("__FILE__", ctype_string, -1, T_FILE, 0, NULL, -1);
3714 cpplib_installBuiltin ("__BASE_FILE__", ctype_string, -1, T_BASE_FILE, 0, NULL, -1);
3715 cpplib_installBuiltin ("__func__", ctype_string, -1, T_FUNC, 0, NULL, -1);
3716 cpplib_installBuiltin ("__INCLUDE_LEVEL__", ctype_int, -1, T_INCLUDE_LEVEL, 0, NULL, -1);
3717 cpplib_installBuiltin ("__VERSION__", ctype_string, -1, T_VERSION, 0, NULL, -1);
3718 #ifndef NO_BUILTIN_SIZE_TYPE
3719 cpplib_installBuiltinType ("__SIZE_TYPE__", ctype_anyintegral, -1, T_SIZE_TYPE, 0, NULL, -1);
3721 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3722 cpplib_installBuiltinType ("__PTRDIFF_TYPE__", ctype_anyintegral, -1, T_PTRDIFF_TYPE, 0, NULL, -1);
3724 cpplib_installBuiltinType ("__WCHAR_TYPE__", ctype_anyintegral, -1, T_WCHAR_TYPE, 0, NULL, -1);
3725 cpplib_installBuiltin ("__USER_LABEL_PREFIX__", ctype_string, -1, T_USER_LABEL_PREFIX_TYPE, 0, NULL, -1);
3726 cpplib_installBuiltin ("__REGISTER_PREFIX__", ctype_string, -1, T_REGISTER_PREFIX_TYPE, 0, NULL, -1);
3727 cpplib_installBuiltin ("__TIME__", ctype_string, -1, T_TIME, 0, NULL, -1);
3730 ** No, don't define __STDC__
3733 if (!cppReader_isTraditional (pfile))
3735 cpplib_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3742 cpplib_installBuiltin ("_WIN32", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3746 ** This is supplied using a -D by the compiler driver
3747 ** so that it is present only when truly compiling with GNU C.
3750 /* cpplib_install ("__GNUC__", -1, T_CONST, 2, 0, -1); */
3752 cpplib_installBuiltin ("S_SPLINT_S", ctype_int, -1, T_CONST, 2, NULL, -1);
3753 cpplib_installBuiltin ("__LCLINT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3755 /*drl 1/9/2001/ try to define the right symbol for the architecture
3756 We use autoconf to determine the target cpu
3758 cpplib_installBuiltin ("__" TARGET_CPU, ctype_int, -1, T_CONST, 2, NULL, -1);
3760 /*drl 1/2/2002 set some flags based on uname
3761 I'd like to be able to do this with autoconf macro instead...
3764 /*Thanks to Nelson Beebe for suggesting possible values for these */
3766 if (! strcmp (UNAME, "Linux"))
3769 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3773 else if(! strcmp (UNAME, "Darwin"))
3775 cpplib_installBuiltin ("__ppc__", ctype_int, -1, T_CONST, 2, NULL, -1);
3776 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3778 else if(! strcmp (UNAME, "HP-UX"))
3780 cpplib_installBuiltin ("PWB", ctype_int, -1, T_CONST, 2, NULL, -1);
3781 cpplib_installBuiltin ("_HIUX_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3782 cpplib_installBuiltin ("_HPUX_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3783 cpplib_installBuiltin ("_PA_RISC1_1", ctype_int, -1, T_CONST, 2, NULL, -1);
3784 cpplib_installBuiltin ("__PWB", ctype_int, -1, T_CONST, 2, NULL, -1);
3785 cpplib_installBuiltin ("__PWB__", ctype_int, -1, T_CONST, 2, NULL, -1);
3786 cpplib_installBuiltin ("__STDC_EXT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3787 cpplib_installBuiltin ("__hp9000s700", ctype_int, -1, T_CONST, 2, NULL, -1);
3788 cpplib_installBuiltin ("__hp9000s800", ctype_int, -1, T_CONST, 2, NULL, -1);
3789 cpplib_installBuiltin ("__hp9000s800__", ctype_int, -1, T_CONST, 2, NULL, -1);
3790 cpplib_installBuiltin ("__hp9k8", ctype_int, -1, T_CONST, 2, NULL, -1);
3791 cpplib_installBuiltin ("__hp9k8__", ctype_int, -1, T_CONST, 2, NULL, -1);
3792 cpplib_installBuiltin ("__hppa", ctype_int, -1, T_CONST, 2, NULL, -1);
3793 cpplib_installBuiltin ("__hppa__", ctype_int, -1, T_CONST, 2, NULL, -1);
3794 cpplib_installBuiltin ("__hpux", ctype_int, -1, T_CONST, 2, NULL, -1);
3795 cpplib_installBuiltin ("__hpux__", ctype_int, -1, T_CONST, 2, NULL, -1);
3796 cpplib_installBuiltin ("__unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3797 cpplib_installBuiltin ("__unix__", ctype_int, -1, T_CONST, 2, NULL, -1);
3798 cpplib_installBuiltin ("hp9000s800", ctype_int, -1, T_CONST, 2, NULL, -1);
3799 cpplib_installBuiltin ("hp9k8", 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 ("unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3804 else if(! strcmp (UNAME, "IRIX64"))
3806 cpplib_installBuiltin ("LANGUAGE_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3807 cpplib_installBuiltin ("MIPSEB", ctype_int, -1, T_CONST, 2, NULL, -1);
3808 cpplib_installBuiltin ("_ABIN32", ctype_int, -1, T_CONST, 2, NULL, -1);
3809 cpplib_installBuiltin ("_COMPILER_VERSION", ctype_int, -1, T_CONST, 730, NULL, -1);
3810 cpplib_installBuiltin ("_LANGUAGE_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3811 cpplib_installBuiltin ("_LONGLONG", ctype_int, -1, T_CONST, 2, NULL, -1);
3812 cpplib_installBuiltin ("_MIPSEB", ctype_int, -1, T_CONST, 2, NULL, -1);
3813 cpplib_installBuiltin ("_MIPS_FPSET", ctype_int, -1, T_CONST, 32, NULL, -1);
3814 cpplib_installBuiltin ("_MIPS_ISA", ctype_int, -1, T_CONST, 3, NULL, -1);
3815 /*_MIPS_SIM=_ABIN32*/
3816 cpplib_installBuiltin ("_MIPS_SIM", ctype_int, -1, T_CONST, 2, NULL , -1);
3817 cpplib_installBuiltin ("_MIPS_SZINT", ctype_int, -1, T_CONST, 32, NULL, -1);
3818 cpplib_installBuiltin ("_MIPS_SZLONG", ctype_int, -1, T_CONST, 32, NULL, -1);
3819 cpplib_installBuiltin ("_MIPS_SZPTR", ctype_int, -1, T_CONST, 32, NULL, -1);
3820 cpplib_installBuiltin ("_MODERN_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3821 cpplib_installBuiltin ("_PIC", ctype_int, -1, T_CONST, 2, NULL, -1);
3822 cpplib_installBuiltin ("_SGI_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3823 cpplib_installBuiltin ("_SIZE_INT", ctype_int, -1, T_CONST, 32, NULL, -1);
3824 cpplib_installBuiltin ("_SIZE_LONG", ctype_int, -1, T_CONST, 32, NULL, -1);
3825 cpplib_installBuiltin ("_SIZE_PTR", ctype_int, -1, T_CONST, 32, NULL, -1);
3826 cpplib_installBuiltin ("_SVR4_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3827 cpplib_installBuiltin ("_SYSTYPE_SVR4", ctype_int, -1, T_CONST, 2, NULL, -1);
3828 cpplib_installBuiltin ("__DSO__", ctype_int, -1, T_CONST, 2, NULL, -1);
3829 cpplib_installBuiltin ("__EXTENSIONS__", ctype_int, -1, T_CONST, 2, NULL, -1);
3830 cpplib_installBuiltin ("__INLINE_INTRINSICS", ctype_int, -1, T_CONST, 2, NULL, -1);
3831 cpplib_installBuiltin ("__MATH_HAS_NO_SIDE_EFFECTS", ctype_int, -1, T_CONST, 2, NULL, -1);
3832 cpplib_installBuiltin ("__host_mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3833 cpplib_installBuiltin ("__mips", ctype_int, -1, T_CONST, 3, NULL, -1);
3834 cpplib_installBuiltin ("__sgi", ctype_int, -1, T_CONST, 2, NULL, -1);
3835 cpplib_installBuiltin ("__unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3836 cpplib_installBuiltin ("host_mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3837 cpplib_installBuiltin ("mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3838 cpplib_installBuiltin ("sgi", ctype_int, -1, T_CONST, 2, NULL, -1);
3839 cpplib_installBuiltin ("unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3841 else if(! strcmp (UNAME, "OSF1"))
3843 cpplib_installBuiltin ("__alpha", ctype_int, -1, T_CONST, 2, NULL, -1);
3845 else if (!strcmp (UNAME, "Rhapsody"))
3847 cpplib_installBuiltin ("__ppc__", ctype_int, -1, T_CONST, 2, NULL, -1);
3848 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3851 else if (!strcmp (UNAME, "SunOS"))
3853 cpplib_installBuiltin ("__OPEN_MAX", ctype_int, -1, T_CONST, 20, NULL, -1);
3854 cpplib_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, 2, NULL, -1);
3855 cpplib_installBuiltin ("__sparc", ctype_int, -1, T_CONST, 2, NULL, -1);
3856 /* This define "-Dfileno(f)=0" should be inserted but we're going to stick to deinfe constants for now...*/
3861 types which we have not explictedly handled.
3862 AIX, FreeBSD, IRIX, Mach
3867 if (CPPOPTIONS (pfile)->debug_output)
3869 dump_special_to_buffer (pfile, "__BASE_FILE__");
3870 dump_special_to_buffer (pfile, "__VERSION__");
3871 #ifndef NO_BUILTIN_SIZE_TYPE
3872 dump_special_to_buffer (pfile, "__SIZE_TYPE__");
3874 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3875 dump_special_to_buffer (pfile, "__PTRDIFF_TYPE__");
3877 dump_special_to_buffer (pfile, "__WCHAR_TYPE__");
3878 dump_special_to_buffer (pfile, "__DATE__");
3879 dump_special_to_buffer (pfile, "__TIME__");
3880 if (!cppReader_isTraditional (pfile))
3881 dump_special_to_buffer (pfile, "__STDC__");
3886 /* Return 1 iff a token ending in C1 followed directly by a token C2
3887 could cause mis-tokenization. */
3890 unsafe_chars (char c1, char c2)
3895 if (c2 == c1 || c2 == '=')
3899 case '0': case '1': case '2': case '3': case '4':
3900 case '5': case '6': case '7': case '8': case '9':
3901 case 'e': case 'E': case 'p': case 'P':
3902 if (c2 == '-' || c2 == '+')
3903 return 1; /* could extend a pre-processing number */
3906 if (c2 == '\'' || c2 == '\"')
3907 return 1; /* Could turn into L"xxx" or L'xxx'. */
3911 case 'a': case 'b': case 'c': case 'd': case 'f':
3912 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3913 case 'm': case 'n': case 'o': case 'q': case 'r':
3914 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3916 case 'A': case 'B': case 'C': case 'D': case 'F':
3917 case 'G': case 'H': case 'I': case 'J': case 'K':
3918 case 'M': case 'N': case 'O': case 'Q': case 'R':
3919 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3921 /* We're in the middle of either a name or a pre-processing number. */
3922 return (is_idchar[(int) c2] || c2 == '.');
3923 case '<': case '>': case '!': case '%': case '#': case ':':
3924 case '^': case '&': case '|': case '*': case '/': case '=':
3925 return (c2 == c1 || c2 == '=');
3930 /* Expand a macro call.
3931 HP points to the symbol that is the macro being called.
3932 Put the result of expansion onto the input stack
3933 so that subsequent input by our caller will use it.
3935 If macro wants arguments, caller has already verified that
3936 an argument list follows; arguments come from the input stack. */
3939 cpplib_macroExpand (cppReader *pfile, /*@dependent@*/ hashNode hp)
3942 DEFINITION *defn = hp->value.defn;
3950 size_t old_written = cpplib_getWritten (pfile);
3954 struct argdata *args = NULL;
3956 pfile->output_escapes++;
3957 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile), &start_line, &start_column);
3958 DPRINTF (("Expand macro: %d:%d", start_line, start_column));
3960 nargs = defn->nargs;
3964 enum cpp_token token = CPP_EOF;
3966 args = (struct argdata *) dmalloc ((nargs + 1) * sizeof (*args));
3968 for (i = 0; i < nargs; i++)
3970 args[i].expanded = 0;
3972 args[i].raw_length = 0;
3973 args[i].expand_length = args[i].stringified_length = -1;
3974 args[i].use_count = 0;
3978 ** Parse all the macro args that are supplied. I counts them.
3979 ** The first NARGS args are stored in ARGS.
3980 ** The rest are discarded. If rest_args is set then we assume
3981 ** macarg absorbed the rest of the args.
3987 cppReader_forward (pfile, 1); /* Discard the open-parenthesis before the first arg. */
3995 if (i < nargs || (nargs == 0 && i == 0))
3997 /* if we are working on last arg which absorbs rest of args... */
3998 if (i == nargs - 1 && defn->rest_args)
4003 args[i].raw = size_toLong (cpplib_getWritten (pfile));
4004 token = macarg (pfile, rest_args);
4005 args[i].raw_length = size_toInt (cpplib_getWritten (pfile) - args[i].raw);
4006 args[i].newlines = FALSE; /* FIXME */
4010 token = macarg (pfile, 0);
4013 if (token == CPP_EOF || token == CPP_POP)
4015 cppReader_errorWithLine (pfile, start_line, start_column,
4016 cstring_fromCharsNew ("unterminated macro call"));
4021 } while (token == CPP_COMMA);
4023 /* If we got one arg but it was just whitespace, call that 0 args. */
4031 bp = ARG_BASE + args[0].raw;
4032 lim = bp + args[0].raw_length;
4034 /* cpp.texi says for foo ( ) we provide one argument.
4035 However, if foo wants just 0 arguments, treat this as 0. */
4039 while (bp != lim && is_space[(int) *bp])
4049 /* Don't output an error message if we have already output one for
4050 a parse error above. */
4053 if (nargs == 0 && i > 0)
4055 cppReader_error (pfile,
4056 message ("arguments given to macro `%s'", hp->name));
4060 /* traditional C allows foo() if foo wants one argument. */
4061 if (nargs == 1 && i == 0 && cppReader_isTraditional (pfile))
4065 /* the rest args token is allowed to absorb 0 tokens */
4066 else if (i == nargs - 1 && defn->rest_args)
4069 cppReader_error (pfile,
4070 message ("macro `%s' used without args", hp->name));
4072 cppReader_error (pfile,
4073 message ("macro `%s' used with just one arg", hp->name));
4076 cppReader_error (pfile,
4077 message ("macro `%s' used with only %d args",
4083 cppReader_error (pfile,
4084 message ("macro `%s' used with too many (%d) args", hp->name, i));
4093 ** If the agrument list was multiple lines, need to insert new lines to keep line
4094 ** numbers accurate.
4097 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile), &end_line, &end_column);
4098 DPRINTF (("Expand macro: %d:%d", end_line, end_column));
4100 /* If macro wants zero args, we parsed the arglist for checking only.
4101 Read directly from the macro definition. */
4105 xbuf = defn->expansion;
4106 xbuf_len = defn->length;
4110 char *exp = defn->expansion;
4111 int offset; /* offset in expansion,
4112 copied a piece at a time */
4113 size_t totlen; /* total amount of exp buffer filled so far */
4115 register struct reflist *ap, *last_ap;
4117 assertSet (args); /* args is defined since the nargs > 0 path was taken */
4119 /* Macro really takes args. Compute the expansion of this call. */
4121 /* Compute length in characters of the macro's expansion.
4122 Also count number of times each arg is used. */
4123 xbuf_len = defn->length;
4125 llassert (args != NULL);
4127 for (ap = defn->pattern; ap != NULL; ap = ap->next)
4131 struct argdata *arg = &args[ap->argno];
4133 /* Stringify it it hasn't already been */
4136 if (arg->stringified_length < 0)
4138 int arglen = arg->raw_length;
4139 bool escaped = FALSE;
4140 char in_string = '\0';
4143 /* Initially need_space is -1. Otherwise, 1 means the
4144 previous character was a space, but we suppressed it;
4145 0 means the previous character was a non-space. */
4146 int need_space = -1;
4149 arg->stringified = cpplib_getWritten (pfile);
4150 if (!cppReader_isTraditional (pfile))
4151 cppReader_putChar (pfile, '\"'); /* insert beginning quote */
4152 for (; i < arglen; i++)
4154 c = (ARG_BASE + arg->raw)[i];
4156 if (in_string == '\0')
4158 /* Internal sequences of whitespace are replaced by
4159 one space except within an string or char token.*/
4160 if (is_space[(int) c])
4162 if (cpplib_getWritten (pfile) > arg->stringified
4163 && (cpplib_getPWritten (pfile))[-1] == '@')
4165 /* "@ " escape markers are removed */
4166 cppReader_adjustWritten (pfile, -1);
4167 /*@innercontinue@*/ continue;
4169 if (need_space == 0)
4171 /*@innercontinue@*/ continue;
4173 else if (need_space > 0)
4174 cppReader_putChar (pfile, ' ');
4190 if (in_string != '\0')
4195 else if (c == '\"' || c == '\'')
4205 /* Escape these chars */
4206 if (c == '\"' || (in_string != '\0' && c == '\\'))
4207 cppReader_putChar (pfile, '\\');
4209 cppReader_putChar (pfile, c);
4212 cpplib_reserve (pfile, 4);
4213 sprintf (cpplib_getPWritten (pfile), "\\%03o",
4215 cppReader_adjustWritten (pfile, 4);
4218 if (!cppReader_isTraditional (pfile))
4219 cppReader_putChar (pfile, '\"'); /* insert ending quote */
4220 arg->stringified_length
4221 = size_toInt (cpplib_getWritten (pfile) - arg->stringified);
4224 xbuf_len += args[ap->argno].stringified_length;
4226 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
4228 /* Add 4 for two newline-space markers to prevent token concatenation. */
4229 assertSet (args); /* Splint shouldn't need this */
4230 xbuf_len += args[ap->argno].raw_length + 4;
4234 /* We have an ordinary (expanded) occurrence of the arg.
4235 So compute its expansion, if we have not already. */
4237 assertSet (args); /* shouldn't need this */
4239 if (args[ap->argno].expand_length < 0)
4241 args[ap->argno].expanded = cpplib_getWritten (pfile);
4242 cpp_expand_to_buffer (pfile,
4243 ARG_BASE + args[ap->argno].raw,
4244 size_fromInt (args[ap->argno].raw_length));
4246 args[ap->argno].expand_length
4247 = size_toInt (cpplib_getWritten (pfile) - args[ap->argno].expanded);
4250 /* Add 4 for two newline-space markers to prevent
4251 token concatenation. */
4252 xbuf_len += args[ap->argno].expand_length + 4;
4254 if (args[ap->argno].use_count < 10)
4255 args[ap->argno].use_count++;
4258 xbuf = (char *) dmalloc (xbuf_len + 1);
4262 ** Generate in XBUF the complete expansion
4263 ** with arguments substituted in.
4264 ** TOTLEN is the total size generated so far.
4265 ** OFFSET is the index in the definition
4266 ** of where we are copying from.
4272 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
4273 last_ap = ap, ap = ap->next)
4275 register struct argdata *arg = &args[ap->argno];
4276 size_t count_before = totlen;
4278 /* Add chars to XBUF. */
4279 for (i = 0; i < ap->nchars; i++, offset++)
4281 xbuf[totlen++] = exp[offset];
4284 /* If followed by an empty rest arg with concatenation,
4285 delete the last run of nonwhite chars. */
4286 if (rest_zero && totlen > count_before
4287 && ((ap->rest_args && ap->raw_before)
4288 || (last_ap != NULL && last_ap->rest_args
4289 && last_ap->raw_after)))
4291 /* Delete final whitespace. */
4292 while (totlen > count_before && is_space[(int) xbuf[totlen - 1]])
4297 /* Delete the nonwhites before them. */
4298 while (totlen > count_before && ! is_space[(int) xbuf[totlen - 1]])
4304 if (ap->stringify != 0)
4307 memcpy (xbuf + totlen,
4308 ARG_BASE + arg->stringified,
4309 size_fromInt (arg->stringified_length));
4310 totlen += arg->stringified_length;
4312 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
4319 p1 = ARG_BASE + arg->raw;
4320 l1 = p1 + arg->raw_length;
4324 while (p1 != l1 && is_space[(int) *p1])
4329 while (p1 != l1 && is_idchar[(int) *p1])
4331 xbuf[totlen++] = *p1++;
4334 /* Delete any no-reexpansion marker that follows
4335 an identifier at the beginning of the argument
4336 if the argument is concatenated with what precedes it. */
4337 if (p1[0] == '@' && p1[1] == '-')
4342 /* Arg is concatenated after: delete trailing whitespace,
4343 whitespace markers, and no-reexpansion markers. */
4346 if (is_space[(int) l1[-1]]) l1--;
4347 else if (l1[-1] == '-')
4350 /* If a `-' is preceded by an odd number of newlines then it
4351 and the last newline are a no-reexpansion marker. */
4352 while (p2 != p1 && p2[-1] == '\n')
4357 if (((l1 - 1 - p2) & 1) != 0)
4363 /*@innerbreak@*/ break;
4368 /*@innerbreak@*/ break;
4373 memcpy (xbuf + totlen, p1, size_fromInt (l1 - p1));
4381 expanded = ARG_BASE + arg->expanded;
4383 if (!ap->raw_before && totlen > 0
4384 && (arg->expand_length != 0)
4385 && !cppReader_isTraditional(pfile)
4386 && unsafe_chars (xbuf[totlen-1], expanded[0]))
4388 xbuf[totlen++] = '@';
4389 xbuf[totlen++] = ' ';
4392 memcpy (xbuf + totlen, expanded,
4393 size_fromInt (arg->expand_length));
4394 totlen += arg->expand_length;
4396 if (!ap->raw_after && totlen > 0
4397 && offset < size_toInt (defn->length)
4398 && !cppReader_isTraditional(pfile)
4399 && unsafe_chars (xbuf[totlen-1], exp[offset]))
4401 xbuf[totlen++] = '@';
4402 xbuf[totlen++] = ' ';
4405 /* If a macro argument with newlines is used multiple times,
4406 then only expand the newlines once. This avoids creating
4407 output lines which don't correspond to any input line,
4408 which confuses gdb and gcov. */
4409 if (arg->use_count > 1 && arg->newlines > 0)
4411 /* Don't bother doing change_newlines for subsequent
4415 = change_newlines (expanded, arg->expand_length);
4419 if (totlen > xbuf_len)
4423 /* if there is anything left of the definition
4424 after handling the arg list, copy that in too. */
4426 for (i = offset; i < size_toInt (defn->length); i++)
4428 /* if we've reached the end of the macro */
4431 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
4432 && last_ap->raw_after))
4433 xbuf[totlen++] = exp[i];
4436 xbuf[totlen] = '\0';
4440 pfile->output_escapes--;
4442 /* Now put the expansion on the input stack
4443 so our caller will commence reading from it. */
4444 DPRINTF (("Pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4446 if (end_line != start_line)
4448 /* xbuf must have enough newlines */
4449 int newlines = end_line - start_line;
4450 int foundnewlines = 0;
4451 char *xbufptr = xbuf;
4453 while ((xbufptr = strchr (xbufptr, '\n')) != NULL && foundnewlines <= newlines)
4458 if (*xbufptr == '\0')
4464 if (foundnewlines < newlines)
4466 cstring newbuf = cstring_copyLength (xbuf, xbuf_len);
4468 while (foundnewlines < newlines)
4470 newbuf = cstring_appendChar (newbuf, '\n');
4475 xbuf = cstring_toCharsSafe (newbuf);
4476 xbuf_len = cstring_length (newbuf);
4478 } /*@=branchstate@*/
4481 DPRINTF (("Pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4483 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
4484 DPRINTF (("After pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4485 cppReader_getBufferSafe (pfile)->has_escapes = 1;
4487 /* Pop the space we've used in the token_buffer for argument expansion. */
4488 cppReader_setWritten (pfile, old_written);
4489 DPRINTF (("Done set written"));
4491 /* Recursive macro use sometimes works traditionally.
4492 #define foo(x,y) bar (x (y,0), y)
4495 if (!cppReader_isTraditional (pfile))
4496 hp->type = T_DISABLED;
4502 push_macro_expansion (cppReader *pfile, char *xbuf, size_t xbuf_len,
4503 /*@dependent@*/ hashNode hp)
4505 cppBuffer *mbuf = cppReader_pushBuffer (pfile, xbuf, xbuf_len);
4512 mbuf->cleanup = cppReader_macroCleanup;
4514 llassert (mbuf->hnode == NULL);
4517 /* The first chars of the expansion should be a "@ " added by
4518 collect_expansion. This is to prevent accidental token-pasting
4519 between the text preceding the macro invocation, and the macro
4522 We would like to avoid adding unneeded spaces (for the sake of
4523 tools that use cpp, such as imake). In some common cases we can
4524 tell that it is safe to omit the space.
4526 The character before the macro invocation cannot have been an
4527 idchar (or else it would have been pasted with the idchars of
4528 the macro name). Therefore, if the first non-space character
4529 of the expansion is an idchar, we do not need the extra space
4530 to prevent token pasting.
4532 Also, we don't need the extra space if the first char is '(',
4533 or some other (less common) characters. */
4535 if (xbuf[0] == '@' && xbuf[1] == ' '
4536 && (is_idchar[(int) xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
4537 || xbuf[2] == '\"'))
4539 llassert (mbuf->cur != NULL);
4540 DPRINTF (("Eating: %c", xbuf[2]));
4547 /* Like cpplib_getToken, except that it does not read past end-of-line.
4548 Also, horizontal space is skipped, and macros are popped. */
4550 static enum cpp_token
4551 get_directive_token (cppReader *pfile)
4555 size_t old_written = cpplib_getWritten (pfile);
4556 enum cpp_token token;
4557 cppSkipHspace (pfile);
4558 if (cppReader_peekC (pfile) == '\n')
4563 token = cpplib_getToken (pfile);
4568 if (!cppBuffer_isMacro (cppReader_getBuffer (pfile)))
4573 cppReader_setWritten (pfile, old_written);
4574 /*@switchbreak@*/ break;
4582 /* Handle #include and #import.
4583 This function expects to see "fname" or <fname> on the input.
4585 The input is normally in part of the output_buffer following
4586 cpplib_getWritten, and will get overwritten by output_line_command.
4587 I.e. in input file specification has been popped by cppReader_handleDirective.
4591 do_include (cppReader *pfile, struct directive *keyword,
4592 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
4594 bool skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4596 char *fbeg, *fend; /* Beginning and end of fname */
4597 enum cpp_token token;
4599 /* Chain of dirs to search */
4600 struct file_name_list *search_start = CPPOPTIONS (pfile)->include;
4601 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
4602 struct file_name_list *searchptr = NULL;
4603 size_t old_written = cpplib_getWritten (pfile);
4606 int f; /* file number */
4607 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4608 f= -1; /* JF we iz paranoid! */
4610 pfile->parsing_include_directive++;
4611 token = get_directive_token (pfile);
4612 pfile->parsing_include_directive--;
4614 if (token == CPP_STRING)
4616 /* FIXME - check no trailing garbage */
4617 fbeg = pfile->token_buffer + old_written + 1;
4618 fend = cpplib_getPWritten (pfile) - 1;
4619 if (fbeg[-1] == '<')
4622 /* If -I-, start with the first -I dir after the -I-. */
4623 if (CPPOPTIONS (pfile)->first_bracket_include != NULL)
4624 search_start = CPPOPTIONS (pfile)->first_bracket_include;
4626 /* If -I- was specified, don't search current dir, only spec'd ones. */
4627 else if (!CPPOPTIONS (pfile)->ignore_srcdir)
4629 cppBuffer *fp = CPPBUFFER (pfile);
4630 /* We have "filename". Figure out directory this source
4631 file is coming from and put it on the front of the list. */
4633 for ( ; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
4638 llassert (fp != NULL);
4642 if (cstring_isDefined (fp->nominal_fname))
4644 nam = cstring_toCharsSafe (fp->nominal_fname);
4646 /* Found a named file. Figure out dir of the file,
4647 and put it in front of the search list. */
4648 dsp[0].next = search_start;
4652 ep = strrchr (nam, CONNECTCHAR);
4654 ep = strrchr (nam, ']');
4655 if (ep == NULL) ep = strrchr (nam, '>');
4656 if (ep == NULL) ep = strrchr (nam, ':');
4657 if (ep != NULL) ep++;
4667 /*@-onlytrans@*/ /* This looks like a memory leak... */
4668 dsp[0].fname = cstring_fromCharsNew (nam); /* evs 2000-07-20: was fromChars */
4672 if (n + INCLUDE_LEN_FUDGE > size_toInt (pfile->max_include_len))
4673 pfile->max_include_len = size_fromInt (n + INCLUDE_LEN_FUDGE);
4677 dsp[0].fname = cstring_undefined; /* Current directory */
4680 dsp[0].got_name_map = 0;
4691 else if (token == CPP_NAME)
4694 * Support '#include xyz' like VAX-C to allow for easy use of all the
4695 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4696 * code from case '<' is repeated here) and generates a warning.
4698 cppReader_warning (pfile,
4699 "VAX-C-style include specification found, use '#include <filename.h>' !");
4701 /* If -I-, start with the first -I dir after the -I-. */
4702 if (CPPOPTIONS (pfile)->first_bracket_include)
4703 search_start = CPPOPTIONS (pfile)->first_bracket_include;
4704 fbeg = pfile->token_buffer + old_written;
4705 fend = cpplib_getPWritten (pfile);
4710 cppReader_error (pfile,
4711 message ("Preprocessor command #%s expects \"FILENAME\" or <FILENAME>",
4714 cppReader_setWritten (pfile, old_written);
4715 cppReader_skipRestOfLine (pfile);
4721 token = get_directive_token (pfile);
4722 if (token != CPP_VSPACE)
4724 cppReader_errorLit (pfile,
4725 cstring_makeLiteralTemp ("Junk at end of #include"));
4727 while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
4729 token = get_directive_token (pfile);
4734 ** For #include_next, skip in the search path
4735 ** past the dir in which the containing file was found.
4740 cppBuffer *fp = CPPBUFFER (pfile);
4742 for (; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
4744 llassert (fp != NULL);
4746 if (fp->fname != NULL)
4748 /* fp->dir is null if the containing file was specified with
4749 an absolute file name. In that case, don't skip anything. */
4750 if (fp->dir == SELF_DIR_DUMMY)
4752 search_start = CPPOPTIONS (pfile)->include;
4754 else if (fp->dir != NULL)
4756 search_start = fp->dir->next;
4768 cppReader_setWritten (pfile, old_written);
4770 flen = size_fromInt (fend - fbeg);
4772 DPRINTF (("fbeg: %s", fbeg));
4776 cppReader_error (pfile,
4777 message ("Empty file name in #%s", keyword->name));
4782 ** Allocate this permanently, because it gets stored in the definitions
4786 fname = cstring_undefined;
4788 /* + 2 above for slash and terminating null. */
4789 /* + 2 added for '.h' on VMS (to support '#include filename') */
4791 /* If specified file name is absolute, just open it. */
4793 if (osd_isConnectChar (*fbeg)
4794 # if defined (WIN32) || defined (OS2)
4795 || (*(fbeg + 1) == ':')
4799 fname = cstring_copyLength (fbeg, flen);
4801 if (redundant_include_p (pfile, fname))
4803 cstring_free (fname);
4807 f = open_include_file (pfile, fname, NULL);
4809 if (f == IMPORT_FOUND)
4811 return 0; /* Already included this file */
4816 /* Search directory path, trying to open the file.
4817 Copy each filename tried into FNAME. */
4819 for (searchptr = search_start; searchptr != NULL;
4820 searchptr = searchptr->next)
4822 if (!cstring_isEmpty (searchptr->fname))
4824 /* The empty string in a search path is ignored.
4825 This makes it possible to turn off entirely
4826 a standard piece of the list. */
4827 if (cstring_isEmpty (searchptr->fname))
4830 fname = cstring_copy (searchptr->fname);
4831 fname = cstring_appendChar (fname, CONNECTCHAR);
4832 DPRINTF (("Here: %s", fname));
4839 fname = cstring_concatLength (fname, fbeg, flen);
4841 DPRINTF (("fname: %s", fname));
4843 /* Win32 directory fix from Kay Buschner. */
4844 #if defined (WIN32) || defined (OS2)
4845 /* Fix all unixdir slashes to win dir slashes */
4846 if (searchptr->fname && (searchptr->fname[0] != 0))
4848 cstring_replaceAll (fname, '/', '\\');
4853 /* Change this 1/2 Unix 1/2 VMS file specification into a
4854 full VMS file specification */
4855 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4856 /* Fix up the filename */
4857 hack_vms_include_specification (fname);
4859 /* This is a normal VMS filespec, so use it unchanged. */
4860 strncpy (fname, fbeg, flen);
4862 /* if it's '#include filename', add the missing .h */
4863 if (strchr (fname,'.') == NULL) {
4864 strcat (fname, ".h");
4868 /* ??? There are currently 3 separate mechanisms for avoiding processing
4869 of redundant include files: #import, #pragma once, and
4870 redundant_include_p. It would be nice if they were unified. */
4872 if (redundant_include_p (pfile, fname))
4874 cstring_free (fname);
4878 DPRINTF (("Trying: %s", fname));
4880 f = open_include_file (pfile, fname, searchptr);
4882 if (f == IMPORT_FOUND)
4884 return 0; /* Already included this file */
4887 else if (f == IMPORT_NOT_FOUND && errno == EACCES)
4889 cppReader_warning (pfile,
4890 message ("Header file %s exists, but is not readable", fname));
4903 /* A file that was not found. */
4904 fname = cstring_copyLength (fbeg, flen);
4906 if (search_start != NULL)
4908 cppReader_error (pfile,
4909 message ("Cannot find include file %s on search path: %x",
4911 searchPath_unparse (search_start)));
4915 cppReader_error (pfile,
4916 message ("No include path in which to find %s", fname));
4921 ** Check to see if this include file is a once-only include file.
4925 struct file_name_list *ptr;
4927 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
4929 if (cstring_equal (ptr->fname, fname))
4931 /* This file was included before. */
4938 /* This is the first time for this file. */
4939 /* Add it to list of files included. */
4941 ptr = (struct file_name_list *) dmalloc (sizeof (*ptr));
4942 ptr->control_macro = NULL;
4943 ptr->c_system_include_path = NULL;
4944 ptr->next = pfile->all_include_files;
4946 ptr->got_name_map = NULL;
4948 DPRINTF (("Including file: %s", fname));
4949 pfile->all_include_files = ptr;
4950 assertSet (pfile->all_include_files);
4953 if (angle_brackets != 0)
4955 pfile->system_include_depth++;
4958 /* Actually process the file */
4959 if (cppReader_pushBuffer (pfile, NULL, 0) == NULL)
4961 cstring_free (fname);
4965 if (finclude (pfile, f, fname, is_system_include (pfile, fname),
4966 searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
4968 output_line_command (pfile, 0, enter_file);
4969 pfile->only_seen_white = 2;
4974 pfile->system_include_depth--;
4977 } /*@=branchstate@*/
4982 /* Return nonzero if there is no need to include file NAME
4983 because it has already been included and it contains a conditional
4984 to make a repeated include do nothing. */
4987 redundant_include_p (cppReader *pfile, cstring name)
4989 struct file_name_list *l = pfile->all_include_files;
4991 for (; l != NULL; l = l->next)
4993 if (cstring_equal (name, l->fname)
4994 && (l->control_macro != NULL)
4995 && (cpphash_lookup (l->control_macro, -1, -1) != NULL))
5004 /* Return nonzero if the given FILENAME is an absolute pathname which
5005 designates a file within one of the known "system" include file
5006 directories. We assume here that if the given FILENAME looks like
5007 it is the name of a file which resides either directly in a "system"
5008 include file directory, or within any subdirectory thereof, then the
5009 given file must be a "system" include file. This function tells us
5010 if we should suppress pedantic errors/warnings for the given FILENAME.
5012 The value is 2 if the file is a C-language system header file
5013 for which C++ should (on most systems) assume `extern "C"'. */
5016 is_system_include (cppReader *pfile, cstring filename)
5018 struct file_name_list *searchptr;
5020 for (searchptr = CPPOPTIONS (pfile)->first_system_include;
5022 searchptr = searchptr->next)
5024 if (!cstring_isEmpty (searchptr->fname))
5026 cstring sys_dir = searchptr->fname;
5027 size_t length = cstring_length (sys_dir);
5029 if (cstring_equalLen (sys_dir, filename, length)
5030 && osd_isConnectChar (cstring_getChar (filename, length)))
5032 if (searchptr->c_system_include_path)
5043 /* Convert a character string literal into a nul-terminated string.
5044 The input string is [IN ... LIMIT).
5045 The result is placed in RESULT. RESULT can be the same as IN.
5046 The value returned in the end of the string written to RESULT,
5047 or NULL on error. */
5049 static /*@null@*/ char *
5050 convert_string (cppReader *pfile, /*@returned@*/ char *result,
5051 char *in, char *limit, int handle_escapes)
5071 /*@switchbreak@*/ break;
5075 char *bpc = (char *) in;
5076 int i = (char) cppReader_parseEscape (pfile, &bpc);
5079 *result++ = (char) c;
5080 /*@switchbreak@*/ break;
5094 * interpret #line command. Remembers previously seen fnames
5095 * in its very own hash table.
5098 /*@constant int FNAME_HASHSIZE@*/
5099 #define FNAME_HASHSIZE 37
5102 do_line (cppReader *pfile, /*@unused@*/ struct directive *keyword)
5104 cppBuffer *ip = cppReader_getBuffer (pfile);
5106 size_t old_written = cpplib_getWritten (pfile);
5107 enum file_change_code file_change = same_file;
5108 enum cpp_token token;
5110 llassert (ip != NULL);
5111 token = get_directive_token (pfile);
5113 if (token != CPP_NUMBER
5114 || !isdigit(pfile->token_buffer[old_written]))
5116 cppReader_errorLit (pfile,
5117 cstring_makeLiteralTemp ("invalid format `#line' command"));
5119 goto bad_line_directive;
5122 /* The Newline at the end of this line remains to be processed.
5123 To put the next line at the specified line number,
5124 we must store a line number now that is one less. */
5125 new_lineno = atoi (pfile->token_buffer + old_written) - 1;
5126 cppReader_setWritten (pfile, old_written);
5128 /* NEW_LINENO is one less than the actual line number here. */
5129 if (cppReader_isPedantic (pfile) && new_lineno < 0)
5130 cppReader_pedwarnLit (pfile,
5131 cstring_makeLiteralTemp ("line number out of range in `#line' command"));
5133 token = get_directive_token (pfile);
5135 if (token == CPP_STRING) {
5136 char *fname = pfile->token_buffer + old_written;
5138 static hashNode fname_table[FNAME_HASHSIZE];
5140 hashNode *hash_bucket;
5143 size_t fname_length;
5145 /* Turn the file name, which is a character string literal,
5146 into a null-terminated string. Do this in place. */
5147 end_name = convert_string (pfile, fname, fname, cpplib_getPWritten (pfile), 1);
5148 if (end_name == NULL)
5150 cppReader_errorLit (pfile,
5151 cstring_makeLiteralTemp ("invalid format `#line' command"));
5152 goto bad_line_directive;
5155 fname_length = size_fromInt (end_name - fname);
5156 num_start = cpplib_getWritten (pfile);
5158 token = get_directive_token (pfile);
5159 if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP) {
5160 p = pfile->token_buffer + num_start;
5161 if (cppReader_isPedantic (pfile))
5162 cppReader_pedwarnLit (pfile,
5163 cstring_makeLiteralTemp ("garbage at end of `#line' command"));
5165 if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
5167 cppReader_errorLit (pfile,
5168 cstring_makeLiteralTemp ("invalid format `#line' command"));
5169 goto bad_line_directive;
5172 file_change = enter_file;
5174 file_change = leave_file;
5176 ip->system_header_p = 1;
5177 else /* if (*p == 4) */
5178 ip->system_header_p = 2;
5180 cppReader_setWritten (pfile, num_start);
5181 token = get_directive_token (pfile);
5182 p = pfile->token_buffer + num_start;
5183 if (token == CPP_NUMBER && p[1] == '\0' && (*p == '3' || *p== '4')) {
5184 ip->system_header_p = *p == 3 ? 1 : 2;
5185 token = get_directive_token (pfile);
5187 if (token != CPP_VSPACE) {
5188 cppReader_errorLit (pfile,
5189 cstring_makeLiteralTemp ("invalid format `#line' command"));
5191 goto bad_line_directive;
5196 &fname_table[cpphash_hashCode (fname, fname_length, FNAME_HASHSIZE)];
5198 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
5200 if (hp->length == fname_length)
5202 llassert (hp->value.cpval != NULL);
5204 if (strncmp (hp->value.cpval, fname, fname_length) == 0)
5206 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
5213 /* Didn't find it; cons up a new one. */
5214 hp = (hashNode) dmalloc (sizeof (*hp));
5217 hp->bucket_hdr = NULL;
5219 hp->name = cstring_undefined;
5220 hp->next = *hash_bucket;
5224 hp->length = fname_length;
5225 hp->value.cpval = dmalloc (sizeof (*hp->value.cpval) * (fname_length + 1));
5226 memcpy (hp->value.cpval, fname, fname_length);
5227 hp->value.cpval[fname_length] = '\0';
5228 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
5231 else if (token != CPP_VSPACE && token != CPP_EOF)
5233 cppReader_errorLit (pfile,
5234 cstring_makeLiteralTemp ("invalid format `#line' command"));
5235 goto bad_line_directive;
5242 ip->lineno = new_lineno;
5244 cppReader_skipRestOfLine (pfile);
5245 cppReader_setWritten (pfile, old_written);
5246 output_line_command (pfile, 0, file_change);
5251 * remove the definition of a symbol from the symbol table.
5252 * according to un*x /lib/cpp, it is not an error to undef
5253 * something that has no definitions, so it isn't one here either.
5257 do_undef (cppReader *pfile, struct directive *keyword, char *buf, char *limit)
5262 char *orig_buf = buf;
5264 SKIP_WHITE_SPACE (buf);
5266 sym_length = cppReader_checkMacroName (pfile, buf, cstring_makeLiteralTemp ("macro"));
5268 while ((hp = cpphash_lookup (buf, size_toInt (sym_length), -1)) != NULL)
5270 /* If we are generating additional info for debugging (with -g) we
5271 need to pass through all effective #undef commands. */
5272 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
5274 pass_thru_directive (orig_buf, limit, pfile, keyword);
5277 if (hp->type != T_MACRO)
5279 cppReader_warning (pfile,
5280 message ("Undefining preprocessor builtin: %s",
5284 cppReader_deleteMacro (hp);
5287 if (cppReader_isPedantic (pfile)) {
5289 SKIP_WHITE_SPACE (buf);
5292 cppReader_pedwarnLit (pfile,
5293 cstring_makeLiteralTemp ("garbage after `#undef' directive"));
5302 * Report an error detected by the program we are processing.
5303 * Use the text of the line in the error message.
5304 * (We use error because it prints the filename & line#.)
5308 do_error (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5309 char *buf, char *limit)
5311 size_t length = size_fromInt (limit - buf);
5312 cstring copy = cstring_copyLength (buf, length);
5313 cstring adv = cstring_advanceWhiteSpace (copy);
5315 cppReader_error (pfile, message ("#error %s", adv));
5316 cstring_free (copy);
5321 * Report a warning detected by the program we are processing.
5322 * Use the text of the line in the warning message, then continue.
5323 * (We use error because it prints the filename & line#.)
5327 do_warning (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5328 char *buf, char *limit)
5330 size_t length = size_fromInt (limit - buf);
5331 cstring copy = cstring_copyLength (buf, length);
5332 cstring adv = cstring_advanceWhiteSpace (copy);
5333 cppReader_warning (pfile, message ("#warning %s", adv));
5334 cstring_free (copy);
5339 /* #ident has already been copied to the output file, so just ignore it. */
5342 do_ident (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5343 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5345 /* Allow #ident in system headers, since that's not user's fault. */
5346 if (cppReader_isPedantic (pfile)
5347 && !cppReader_getBufferSafe (pfile)->system_header_p)
5348 cppReader_pedwarnLit (pfile,
5349 cstring_makeLiteralTemp ("ANSI C does not allow `#ident'"));
5351 /* Leave rest of line to be read by later calls to cpplib_getToken. */
5356 /* #pragma and its argument line have already been copied to the output file.
5357 Just check for some recognized pragmas that need validation here. */
5360 do_pragma (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5361 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5363 while (*buf == ' ' || *buf == '\t')
5368 if (!strncmp (buf, "implementation", 14)) {
5369 /* Be quiet about `#pragma implementation' for a file only if it hasn't
5370 been included yet. */
5371 struct file_name_list *ptr;
5372 char *p = buf + 14, *fname, *inc_fname;
5374 SKIP_WHITE_SPACE (p);
5375 if (*p == '\n' || *p != '\"')
5379 p = (char *) strchr (fname, '\"');
5380 fname_len = p != NULL ? size_fromInt (p - fname) : mstring_length (fname);
5382 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
5384 inc_fname = (char *) strrchr (cstring_toCharsSafe (ptr->fname), CONNECTCHAR);
5385 inc_fname = (inc_fname != NULL)
5386 ? inc_fname + 1 : cstring_toCharsSafe (ptr->fname);
5388 if ((inc_fname != NULL)
5389 && (strncmp (inc_fname, fname, fname_len) == 0))
5391 cpp_setLocation (pfile);
5393 ppllerror (message ("`#pragma implementation' for `%s' appears "
5394 "after file is included",
5395 cstring_fromChars (fname)));
5404 * handle #if command by
5405 * 1) inserting special `defined' keyword into the hash table
5406 * that gets turned into 0 or 1 by special_symbol (thus,
5407 * if the luser has a symbol called `defined' already, it won't
5408 * work inside the #if command)
5409 * 2) rescan the input into a temporary output buffer
5410 * 3) pass the output buffer to the yacc parser and collect a value
5411 * 4) clean up the mess left from steps 1 and 2.
5412 * 5) call conditional_skip to skip til the next #endif (etc.),
5413 * or not, depending on the value from step 3.
5417 do_if (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5418 char *buf, char *limit)
5420 HOST_WIDE_INT value;
5421 DPRINTF (("Do if: %s", buf));
5422 value = eval_if_expression (pfile, buf, limit - buf);
5423 conditional_skip (pfile, value == 0, T_IF, NULL);
5428 * handle a #elif directive by not changing if_stack either.
5429 * see the comment above do_else.
5432 static int do_elif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5433 char *buf, char *limit)
5435 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5437 cppReader_errorLit (pfile,
5438 cstring_makeLiteralTemp ("Preprocessor command #elif is not within a conditional"));
5443 llassert (pfile->if_stack != NULL);
5445 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
5447 cppReader_errorLit (pfile,
5448 cstring_makeLiteralTemp ("`#elif' after `#else'"));
5450 if (pfile->if_stack->fname != NULL
5451 && cppReader_getBufferSafe (pfile)->fname != NULL
5452 && !cstring_equal (pfile->if_stack->fname,
5453 cppReader_getBufferSafe (pfile)->nominal_fname))
5454 fprintf (stderr, ", file %s", cstring_toCharsSafe (pfile->if_stack->fname));
5455 fprintf (stderr, ")\n");
5457 pfile->if_stack->type = T_ELIF;
5460 if (pfile->if_stack->if_succeeded)
5462 skip_if_group (pfile, 0);
5466 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
5468 skip_if_group (pfile, 0);
5471 ++pfile->if_stack->if_succeeded; /* continue processing input */
5472 output_line_command (pfile, 1, same_file);
5480 * evaluate a #if expression in BUF, of length LENGTH,
5481 * then parse the result as a C expression and return the value as an int.
5484 static HOST_WIDE_INT
5485 eval_if_expression (cppReader *pfile,
5486 /*@unused@*/ char *buf,
5487 /*@unused@*/ int length)
5489 hashNode save_defined;
5490 HOST_WIDE_INT value;
5491 size_t old_written = cpplib_getWritten (pfile);
5493 DPRINTF (("Saving defined..."));
5494 save_defined = cpphash_install ("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
5495 pfile->pcp_inside_if = 1;
5497 value = cppReader_parseExpression (pfile);
5498 pfile->pcp_inside_if = 0;
5500 /* Clean up special symbol */
5501 DPRINTF (("Removing defined..."));
5502 cppReader_deleteMacro (save_defined);
5503 cppReader_setWritten (pfile, old_written); /* Pop */
5509 * routine to handle ifdef/ifndef. Try to look up the symbol,
5510 * then do or don't skip to the #endif/#else/#elif depending
5511 * on what directive is actually being processed.
5515 do_xifdef (cppReader *pfile, struct directive *keyword,
5516 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
5519 cppBuffer *ip = cppReader_getBufferSafe (pfile);
5521 size_t ident_length;
5522 enum cpp_token token;
5523 int start_of_file = 0;
5524 char *control_macro = 0;
5525 size_t old_written = cpplib_getWritten (pfile);
5527 DPRINTF (("do xifdef: %d",
5528 keyword->type == T_IFNDEF));
5530 /* Detect a #ifndef at start of file (not counting comments). */
5531 if (cstring_isDefined (ip->fname) && keyword->type == T_IFNDEF)
5533 start_of_file = pfile->only_seen_white == 2;
5536 pfile->no_macro_expand++;
5537 token = get_directive_token (pfile);
5538 pfile->no_macro_expand--;
5540 ident = pfile->token_buffer + old_written;
5541 DPRINTF (("Ident: %s", ident));
5543 ident_length = cpplib_getWritten (pfile) - old_written;
5544 cppReader_setWritten (pfile, old_written); /* Pop */
5546 if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
5548 skip = (keyword->type == T_IFDEF);
5549 if (! cppReader_isTraditional (pfile))
5551 cppReader_pedwarn (pfile,
5552 message ("`#%s' with no argument", keyword->name));
5555 else if (token == CPP_NAME)
5557 hashNode hp = cpphash_lookup (ident, size_toInt (ident_length), -1);
5559 skip = (keyword->type == T_IFDEF) ? (hp == NULL) : (hp != NULL);
5561 DPRINTF (("hp null: %d / %d / %d", hp == NULL, keyword->type == T_IFNDEF, skip));
5563 if (start_of_file && !skip)
5565 DPRINTF (("Not skipping!"));
5566 control_macro = (char *) dmalloc (ident_length + 1);
5567 memcpy (control_macro, ident, ident_length + 1);
5572 skip = (keyword->type == T_IFDEF);
5573 if (! cppReader_isTraditional (pfile))
5575 cppReader_error (pfile,
5576 message ("`#%s' with invalid argument", keyword->name));
5580 if (!cppReader_isTraditional (pfile))
5583 cppSkipHspace (pfile);
5584 c = cppReader_peekC (pfile);
5585 if (c != EOF && c != '\n')
5587 cppReader_pedwarn (pfile,
5588 message ("garbage at end of `#%s' argument", keyword->name));
5592 cppReader_skipRestOfLine (pfile);
5594 DPRINTF (("Conditional skip: %d", skip));
5595 conditional_skip (pfile, skip, T_IF, control_macro);
5599 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
5600 If this is a #ifndef starting at the beginning of a file,
5601 CONTROL_MACRO is the macro name tested by the #ifndef.
5602 Otherwise, CONTROL_MACRO is 0. */
5605 conditional_skip (cppReader *pfile, int skip,
5606 enum node_type type,
5607 /*@dependent@*/ char *control_macro)
5609 cppIfStackFrame *temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
5611 temp->fname = cppReader_getBufferSafe (pfile)->nominal_fname;
5612 temp->next = pfile->if_stack;
5613 temp->control_macro = control_macro;
5615 temp->if_succeeded = 0;
5617 pfile->if_stack = temp;
5618 pfile->if_stack->type = type;
5622 skip_if_group (pfile, 0);
5627 ++pfile->if_stack->if_succeeded;
5628 output_line_command (pfile, 1, same_file);
5633 * skip to #endif, #else, or #elif. adjust line numbers, etc.
5634 * leaves input ptr at the sharp sign found.
5635 * If ANY is nonzero, return at next directive of any sort.
5639 skip_if_group (cppReader *pfile, int any)
5642 struct directive *kt;
5643 cppIfStackFrame *save_if_stack = pfile->if_stack; /* don't pop past here */
5644 register int ident_length;
5646 struct parse_marker line_start_mark;
5648 parseSetMark (&line_start_mark, pfile);
5650 if (CPPOPTIONS (pfile)->output_conditionals) {
5651 static char failed[] = "#failed\n";
5652 cppReader_puts (pfile, failed, sizeof(failed)-1);
5654 output_line_command (pfile, 1, same_file);
5658 if (CPPOPTIONS (pfile)->output_conditionals)
5660 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
5663 llassert (pbuf->buf != NULL);
5665 start_line = pbuf->buf + line_start_mark.position;
5666 cppReader_puts (pfile, start_line, size_fromInt (pbuf->cur - start_line));
5669 parseMoveMark (&line_start_mark, pfile);
5671 if (!cppReader_isTraditional (pfile))
5673 cppSkipHspace (pfile);
5676 c = cppReader_getC (pfile);
5679 size_t old_written = cpplib_getWritten (pfile);
5680 cppSkipHspace (pfile);
5682 parse_name (pfile, cppReader_getC (pfile));
5683 ident_length = size_toInt (cpplib_getWritten (pfile) - old_written);
5684 ident = pfile->token_buffer + old_written;
5685 pfile->limit = ident;
5687 for (kt = directive_table; kt->length >= 0; kt++)
5689 cppIfStackFrame *temp;
5690 if (ident_length == kt->length
5691 && cstring_equalPrefix (kt->name, cstring_fromChars (ident)))
5693 /* If we are asked to return on next directive, do so now. */
5704 temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
5705 temp->next = pfile->if_stack;
5706 temp->fname = cppReader_getBufferSafe (pfile)->nominal_fname;
5707 temp->type = kt->type;
5709 temp->if_succeeded = 0;
5710 temp->control_macro = NULL;
5712 pfile->if_stack = temp;
5713 /*@switchbreak@*/ break;
5716 if (cppReader_isPedantic (pfile) && pfile->if_stack != save_if_stack)
5717 validate_else (pfile,
5718 cstring_makeLiteralTemp (kt->type == T_ELSE ? "#else" : "#endif"));
5721 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5723 cppReader_error (pfile,
5724 message ("Preprocessor command #%s is not within a conditional", kt->name));
5725 /*@switchbreak@*/ break;
5727 else if (pfile->if_stack == save_if_stack)
5729 goto done; /* found what we came for */
5736 if (kt->type != T_ENDIF)
5738 llassert (pfile->if_stack != NULL);
5740 if (pfile->if_stack->type == T_ELSE)
5742 cppReader_errorLit (pfile,
5743 cstring_makeLiteralTemp ("`#else' or `#elif' after `#else'"));
5746 pfile->if_stack->type = kt->type;
5747 /*@switchbreak@*/ break;
5750 temp = pfile->if_stack;
5751 llassert (temp != NULL);
5752 pfile->if_stack = temp->next;
5754 /*@switchbreak@*/ break;
5757 #if defined (OS2) && defined (__IBMC__)
5758 /* Dummy code to eleminate optimization problems with icc */
5767 /* Don't let erroneous code go by. */
5769 if (kt->length < 0 && !CPPOPTIONS (pfile)->lang_asm
5770 && cppReader_isPedantic (pfile))
5772 cppReader_pedwarnLit (pfile,
5773 cstring_makeLiteralTemp ("Invalid preprocessor directive name"));
5777 c = cppReader_getC (pfile);
5779 /* We're in the middle of a line. Skip the rest of it. */
5787 case '/': /* possible comment */
5788 c = skip_comment (pfile, NULL);
5791 /*@switchbreak@*/ break;
5794 cppReader_forward (pfile, -1);
5795 old = cpplib_getWritten (pfile);
5796 (void) cpplib_getToken (pfile);
5797 cppReader_setWritten (pfile, old);
5798 /*@switchbreak@*/ break;
5800 /* Char after backslash loses its special meaning. */
5801 if (cppReader_peekC (pfile) == '\n')
5803 cppReader_forward (pfile, 1);
5806 /*@switchbreak@*/ break;
5810 c = cppReader_getC (pfile);
5813 if (CPPOPTIONS (pfile)->output_conditionals) {
5814 static char end_failed[] = "#endfailed\n";
5815 cppReader_puts (pfile, end_failed, sizeof(end_failed)-1);
5818 pfile->only_seen_white = 1;
5820 parseGotoMark (&line_start_mark, pfile);
5821 parseClearMark (&line_start_mark);
5825 * handle a #else directive. Do this by just continuing processing
5826 * without changing if_stack ; this is so that the error message
5827 * for missing #endif's etc. will point to the original #if. It
5828 * is possible that something different would be better.
5832 do_else (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5833 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5835 if (cppReader_isPedantic (pfile))
5837 validate_else (pfile, cstring_makeLiteralTemp ("#else"));
5840 cppReader_skipRestOfLine (pfile);
5842 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack) {
5843 cppReader_errorLit (pfile,
5844 cstring_makeLiteralTemp ("Preprocessor command #else is not within a conditional"));
5847 /* #ifndef can't have its special treatment for containing the whole file
5848 if it has a #else clause. */
5850 llassert (pfile->if_stack != NULL);
5852 pfile->if_stack->control_macro = 0;
5854 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
5856 cpp_setLocation (pfile);
5857 genppllerrorhint (FLG_PREPROC,
5858 message ("Pre-processor directive #else after #else"),
5859 message ("%q: Location of match",
5860 fileloc_unparseRaw (pfile->if_stack->fname,
5861 pfile->if_stack->lineno)));
5864 pfile->if_stack->type = T_ELSE;
5867 if (pfile->if_stack->if_succeeded)
5868 skip_if_group (pfile, 0);
5870 ++pfile->if_stack->if_succeeded; /* continue processing input */
5871 output_line_command (pfile, 1, same_file);
5878 * unstack after #endif command
5882 do_endif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5883 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5885 if (cppReader_isPedantic (pfile))
5887 validate_else (pfile, cstring_makeLiteralTemp ("#endif"));
5890 cppReader_skipRestOfLine (pfile);
5892 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5894 cppReader_errorLit (pfile, cstring_makeLiteralTemp ("Unbalanced #endif"));
5898 cppIfStackFrame *temp = pfile->if_stack;
5900 llassert (temp != NULL);
5902 pfile->if_stack = temp->next;
5903 if (temp->control_macro != 0)
5905 /* This #endif matched a #ifndef at the start of the file.
5906 See if it is at the end of the file. */
5907 struct parse_marker start_mark;
5910 parseSetMark (&start_mark, pfile);
5914 cppSkipHspace (pfile);
5915 c = cppReader_getC (pfile);
5921 parseGotoMark (&start_mark, pfile);
5922 parseClearMark (&start_mark);
5926 /* If we get here, this #endif ends a #ifndef
5927 that contains all of the file (aside from whitespace).
5928 Arrange not to include the file again
5929 if the macro that was tested is defined.
5931 Do not do this for the top-level file in a -include or any
5932 file in a -imacros. */
5933 struct file_name_list *ifile = pfile->all_include_files;
5935 for ( ; ifile != NULL; ifile = ifile->next)
5937 if (cstring_equal (ifile->fname, cppReader_getBufferSafe (pfile)->fname))
5939 ifile->control_macro = temp->control_macro;
5947 output_line_command (pfile, 1, same_file);
5952 /* When an #else or #endif is found while skipping failed conditional,
5953 if -pedantic was specified, this is called to warn about text after
5954 the command name. P points to the first char after the command name. */
5957 validate_else (cppReader *pfile, cstring directive)
5960 cppSkipHspace (pfile);
5961 c = cppReader_peekC (pfile);
5962 if (c != EOF && c != '\n')
5964 cppReader_pedwarn (pfile,
5965 message ("text following `%s' violates ANSI standard", directive));
5970 ** Get the next token, and add it to the text in pfile->token_buffer.
5971 ** Return the kind of token we got.
5975 cpplib_getToken (cppReader *pfile)
5977 return cpplib_getTokenAux (pfile, FALSE);
5981 cpplib_getTokenForceExpand (cppReader *pfile)
5983 return cpplib_getTokenAux (pfile, TRUE);
5987 cpplib_getTokenAux (cppReader *pfile, bool forceExpand)
5990 size_t old_written = 0;
5991 int start_line, start_column;
5992 enum cpp_token token;
5993 struct cppOptions *opts = CPPOPTIONS (pfile);
5994 cppReader_getBufferSafe (pfile)->prev = cppReader_getBufferSafe (pfile)->cur;
5997 c = cppReader_getC (pfile);
5998 DPRINTF (("Get next token: %c", c));
6003 if (cppReader_getBufferSafe (pfile)->seen_eof)
6005 cppBuffer *buf = cppReader_popBuffer (pfile);
6007 if (buf != cppReader_nullBuffer (pfile))
6018 cppBuffer *next_buf = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6019 cppReader_getBufferSafe (pfile)->seen_eof = 1;
6021 if (cstring_isDefined (cppReader_getBufferSafe (pfile)->nominal_fname)
6022 && next_buf != cppReader_nullBuffer (pfile))
6024 /* We're about to return from an #include file.
6025 Emit #line information now (as part of the CPP_POP) result.
6026 But the #line refers to the file we will pop to. */
6027 cppBuffer *cur_buffer = CPPBUFFER (pfile);
6028 CPPBUFFER (pfile) = next_buf;
6029 pfile->input_stack_listing_current = 0;
6030 output_line_command (pfile, 0, leave_file);
6031 CPPBUFFER (pfile) = cur_buffer;
6039 struct parse_marker start_mark;
6044 if (cppReader_peekC (pfile) == '=')
6049 if (opts->put_out_comments)
6051 parseSetMark (&start_mark, pfile);
6055 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile),
6056 &start_line, &start_column);
6057 c = skip_comment (pfile, &newlines);
6058 DPRINTF (("c = %c", c));
6059 if (opts->put_out_comments && (c == '/' || c == EOF))
6061 assertSet (&start_mark);
6062 parseClearMark (&start_mark);
6069 cppReader_errorWithLine (pfile, start_line, start_column,
6070 cstring_makeLiteral ("Unterminated comment"));
6073 c = '/'; /* Initial letter of comment. */
6075 /* Comments are equivalent to spaces.
6076 For -traditional, a comment is equivalent to nothing. */
6078 if (opts->put_out_comments)
6082 assertSet (&start_mark);
6083 res = cpp_handleComment (pfile, &start_mark);
6084 pfile->lineno += newlines;
6087 else if (cppReader_isTraditional (pfile))
6093 cpplib_reserve(pfile, 1);
6094 cppReader_putCharQ (pfile, ' ');
6099 if (!pfile->only_seen_white)
6104 if (cppReader_handleDirective (pfile))
6106 return CPP_DIRECTIVE;
6109 pfile->only_seen_white = 0;
6114 /* A single quoted string is treated like a double -- some
6115 programs (e.g., troff) are perverse this way */
6116 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile),
6117 &start_line, &start_column);
6118 old_written = cpplib_getWritten (pfile);
6120 DPRINTF (("Reading string: %c", c));
6121 cppReader_putChar (pfile, c);
6125 ** Because of ISO8859-1 characters in string literals, we need a special test here.
6128 if (cppReader_reachedEOF (pfile))
6131 DPRINTF (("Matches EOF!"));
6132 if (cppBuffer_isMacro (CPPBUFFER (pfile)))
6134 /* try harder: this string crosses a macro expansion
6135 boundary. This can happen naturally if -traditional.
6136 Otherwise, only -D can make a macro with an unmatched
6139 = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6140 (*cppReader_getBufferSafe (pfile)->cleanup)
6141 (cppReader_getBufferSafe (pfile), pfile);
6142 CPPBUFFER (pfile) = next_buf;
6146 if (!cppReader_isTraditional (pfile))
6148 cpp_setLocation (pfile);
6150 setLine (long_toInt (start_line));
6151 setColumn (long_toInt (start_column));
6153 if (pfile->multiline_string_line != long_toInt (start_line)
6154 && pfile->multiline_string_line != 0)
6158 message ("Unterminated string or character constant"),
6159 message ("%q: Possible real start of unterminated constant",
6161 (fileloc_filename (g_currentloc),
6162 pfile->multiline_string_line)));
6163 pfile->multiline_string_line = 0;
6169 message ("Unterminated string or character constant"));
6172 /*@loopbreak@*/ break;
6176 int cc = cppReader_getC (pfile);
6177 DPRINTF (("cc: %c [%d] [%d]", cc, cc, EOF));
6178 DPRINTF (("putting char: %c", cc));
6179 cppReader_putChar (pfile, cc);
6183 /* Traditionally, end of line ends a string constant with
6184 no error. So exit the loop and record the new line. */
6185 if (cppReader_isTraditional (pfile))
6191 if (cppReader_isPedantic (pfile)
6192 && pfile->multiline_string_line == 0)
6194 cppReader_pedwarnWithLine
6195 (pfile, long_toInt (start_line),
6196 long_toInt (start_column),
6197 cstring_makeLiteral ("String constant runs past end of line"));
6199 if (pfile->multiline_string_line == 0)
6201 pfile->multiline_string_line = start_line;
6204 /*@switchbreak@*/ break;
6207 cc = cppReader_getC (pfile);
6210 /* Backslash newline is replaced by nothing at all. */
6211 cppReader_adjustWritten (pfile, -1);
6216 /* ANSI stupidly requires that in \\ the second \
6217 is *not* prevented from combining with a newline. */
6220 cppReader_putChar (pfile, cc);
6222 /*@switchbreak@*/ break;
6228 /*@switchbreak@*/ break;
6233 pfile->lineno += count_newlines (pfile->token_buffer + old_written,
6234 cpplib_getPWritten (pfile));
6235 pfile->only_seen_white = 0;
6236 return c == '\'' ? CPP_CHAR : CPP_STRING;
6239 if (!opts->dollars_in_ident)
6244 if (opts->cplusplus && cppReader_peekC (pfile) == ':')
6252 c2 = cppReader_peekC (pfile);
6253 if (c2 == c || c2 == '=')
6263 if (cppReader_peekC (pfile) == '=')
6269 c2 = cppReader_peekC (pfile);
6270 if (c2 == '-' && opts->chill)
6272 /* Chill style comment */
6273 if (opts->put_out_comments)
6275 parseSetMark (&start_mark, pfile);
6278 cppReader_forward (pfile, 1); /* Skip second '-'. */
6282 c = cppReader_getC (pfile);
6284 /*@loopbreak@*/ break;
6287 /* Don't consider final '\n' to be part of comment. */
6288 cppReader_forward (pfile, -1);
6289 /*@loopbreak@*/ break;
6293 goto return_comment;
6295 if (c2 == '-' || c2 == '=' || c2 == '>')
6300 if (pfile->parsing_include_directive)
6304 cppReader_putChar (pfile, c);
6306 /*@loopbreak@*/ break;
6307 c = cppReader_getC (pfile);
6309 if (c == '\n' || c == EOF)
6311 cppReader_errorLit (pfile,
6312 cstring_makeLiteralTemp ("Missing '>' in \"#include <FILENAME>\""));
6313 /*@loopbreak@*/ break;
6321 c2 = cppReader_peekC (pfile);
6326 cppReader_forward (pfile, 1);
6327 cpplib_reserve (pfile, 4);
6328 cppReader_putChar (pfile, c);
6329 cppReader_putChar (pfile, c2);
6331 c3 = cppReader_peekC (pfile);
6333 cppReader_putCharQ (pfile, cppReader_getC (pfile));
6334 cppReader_nullTerminateQ (pfile);
6335 pfile->only_seen_white = 0;
6339 DPRINTF (("Macro @!"));
6340 if (cppReader_getBufferSafe (pfile)->has_escapes)
6342 c = cppReader_getC (pfile);
6343 DPRINTF (("got c: %c", c));
6346 if (pfile->output_escapes)
6347 cppReader_puts (pfile, "@-", 2);
6348 parse_name (pfile, cppReader_getC (pfile));
6351 else if (is_space [c])
6353 cpplib_reserve (pfile, 2);
6354 if (pfile->output_escapes)
6355 cppReader_putCharQ (pfile, '@');
6356 cppReader_putCharQ (pfile, c);
6364 if (pfile->output_escapes)
6366 cppReader_puts (pfile, "@@", 2);
6372 c2 = cppReader_peekC (pfile);
6375 cpplib_reserve(pfile, 2);
6376 cppReader_putCharQ (pfile, '.');
6377 c = cppReader_getC (pfile);
6381 /* FIXME - misses the case "..\\\n." */
6382 if (c2 == '.' && cpp_peekN (pfile, 1) == '.')
6384 cpplib_reserve(pfile, 4);
6385 cppReader_putCharQ (pfile, '.');
6386 cppReader_putCharQ (pfile, '.');
6387 cppReader_putCharQ (pfile, '.');
6388 cppReader_forward (pfile, 2);
6389 cppReader_nullTerminateQ (pfile);
6390 pfile->only_seen_white = 0;
6396 pfile->only_seen_white = 0;
6398 cpplib_reserve(pfile, 3);
6399 cppReader_putCharQ (pfile, c);
6400 cppReader_putCharQ (pfile, cppReader_getC (pfile));
6401 cppReader_nullTerminateQ (pfile);
6406 c2 = cppReader_peekC (pfile);
6407 if ((c2 == '\'' || c2 == '\"') && !cppReader_isTraditional (pfile))
6409 cppReader_putChar (pfile, c);
6410 c = cppReader_getC (pfile);
6415 case '0': case '1': case '2': case '3': case '4':
6416 case '5': case '6': case '7': case '8': case '9':
6421 cpplib_reserve (pfile, 2);
6422 cppReader_putCharQ (pfile, c);
6424 c = cppReader_peekC (pfile);
6426 /*@loopbreak@*/ break;
6427 if (!is_idchar[c] && c != '.'
6428 && ((c2 != 'e' && c2 != 'E'
6429 && ((c2 != 'p' && c2 != 'P') || cppReader_isC89 (pfile)))
6430 || (c != '+' && c != '-')))
6431 /*@loopbreak@*/ break;
6432 cppReader_forward (pfile, 1);
6436 cppReader_nullTerminateQ (pfile);
6437 pfile->only_seen_white = 0;
6440 case 'b': case 'c': case 'd': case 'h': case 'o':
6441 case 'B': case 'C': case 'D': case 'H': case 'O':
6442 if (opts->chill && cppReader_peekC (pfile) == '\'')
6444 pfile->only_seen_white = 0;
6445 cpplib_reserve (pfile, 2);
6446 cppReader_putCharQ (pfile, c);
6447 cppReader_putCharQ (pfile, '\'');
6448 cppReader_forward (pfile, 1);
6451 c = cppReader_getC (pfile);
6453 goto chill_number_eof;
6456 if (c == '\\' && cppReader_peekC (pfile) == '\n')
6458 cppReader_forward (pfile, 2);
6461 /*@loopbreak@*/ break;
6463 cppReader_putChar (pfile, c);
6467 cpplib_reserve (pfile, 2);
6468 cppReader_putCharQ (pfile, c);
6469 cppReader_nullTerminateQ (pfile);
6474 cppReader_forward (pfile, -1);
6476 cppReader_nullTerminate (pfile);
6483 case 'a': case 'e': case 'f': case 'g': case 'i': case 'j':
6484 case 'k': case 'l': case 'm': case 'n': case 'p': case 'q':
6485 case 'r': case 's': case 't': case 'u': case 'v': case 'w':
6486 case 'x': case 'y': case 'z':
6487 case 'A': case 'E': case 'F': case 'G': case 'I': case 'J':
6488 case 'K': case 'M': case 'N': case 'P': case 'Q': case 'R':
6489 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
6495 size_t before_name_written = cpplib_getWritten (pfile);
6497 parse_name (pfile, c);
6498 pfile->only_seen_white = 0;
6500 if (pfile->no_macro_expand)
6502 DPRINTF (("Not expanding: %s", pfile->token_buffer));
6506 ident = pfile->token_buffer + before_name_written;
6507 DPRINTF (("Ident: %s", ident));
6509 ident_len = size_fromInt ((cpplib_getPWritten (pfile)) - ident);
6511 hp = cpphash_lookupExpand (ident, size_toInt (ident_len), -1, forceExpand);
6515 DPRINTF (("No expand: %s %d", ident, ident_len));
6519 if (hp->type == T_DISABLED)
6521 DPRINTF (("Disabled!"));
6523 if (pfile->output_escapes)
6524 { /* Return "@-IDENT", followed by '\0'. */
6526 cpplib_reserve (pfile, 3);
6527 ident = pfile->token_buffer + before_name_written;
6528 cppReader_adjustWritten (pfile, 2);
6530 for (i = size_toInt (ident_len); i >= 0; i--)
6532 ident[i+2] = ident[i];
6542 ** If macro wants an arglist, verify that a '(' follows.
6543 ** first skip all whitespace, copying it to the output
6544 ** after the macro name. Then, if there is no '(',
6545 ** decide this is not a macro call and leave things that way.
6548 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
6550 struct parse_marker macro_mark;
6553 DPRINTF (("Arglist macro!"));
6556 ** evans 2002-07-03: Moved this here (from below).
6557 ** This bug caused necessary whitespace to be lost
6558 ** when parsing parameterized macros without parameters.
6561 parseSetMark (¯o_mark, pfile);
6563 while (cppBuffer_isMacro (CPPBUFFER (pfile)))
6565 cppBuffer *next_buf;
6566 cppSkipHspace (pfile);
6567 if (cppReader_peekC (pfile) != EOF)
6569 DPRINTF (("Peeking!"));
6570 /*@loopbreak@*/ break;
6573 next_buf = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6574 (*cppReader_getBufferSafe (pfile)->cleanup) (cppReader_getBufferSafe (pfile), pfile);
6575 CPPBUFFER (pfile) = next_buf;
6578 /* parseSetMark (¯o_mark, pfile); */
6582 cppSkipHspace (pfile);
6583 c = cppReader_peekC (pfile);
6584 DPRINTF (("c: %c", c));
6585 is_macro_call = c == '(';
6587 /*@loopbreak@*/ break;
6588 cppReader_forward (pfile, 1);
6593 parseGotoMark (¯o_mark, pfile);
6596 parseClearMark (¯o_mark);
6600 DPRINTF (("not macro call!"));
6605 /* This is now known to be a macro call. */
6607 /* it might not actually be a macro. */
6608 if (hp->type != T_MACRO)
6613 cppReader_setWritten (pfile, before_name_written);
6614 special_symbol (hp, pfile);
6615 xbuf_len = cpplib_getWritten (pfile) - before_name_written;
6616 xbuf = (char *) dmalloc (xbuf_len + 1);
6617 cppReader_setWritten (pfile, before_name_written);
6618 memcpy (xbuf, cpplib_getPWritten (pfile), xbuf_len + 1);
6619 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
6624 ** Expand the macro, reading arguments as needed,
6625 ** and push the expansion on the input stack.
6628 cpplib_macroExpand (pfile, hp);
6629 cppReader_setWritten (pfile, before_name_written);
6632 /* An extra "@ " is added to the end of a macro expansion
6633 to prevent accidental token pasting. We prefer to avoid
6634 unneeded extra spaces (for the sake of cpp-using tools like
6635 imake). Here we remove the space if it is safe to do so. */
6637 llassert (pfile->buffer->rlimit != NULL);
6639 if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
6640 && pfile->buffer->rlimit[-2] == '@'
6641 && pfile->buffer->rlimit[-1] == ' ')
6643 int c1 = pfile->buffer->rlimit[-3];
6644 int cl2 = cpplib_bufPeek (cppBuffer_prevBuffer (CPPBUFFER (pfile)));
6646 if (cl2 == EOF || !unsafe_chars ((char) c1, (char) cl2))
6647 pfile->buffer->rlimit -= 2;
6653 case ' ': case '\t': case '\v': case '\r':
6656 cppReader_putChar (pfile, c);
6657 c = cppReader_peekC (pfile);
6658 if (c == EOF || !is_hor_space[c])
6659 /*@loopbreak@*/ break;
6660 cppReader_forward (pfile, 1);
6665 c2 = cppReader_peekC (pfile);
6672 cppReader_putChar (pfile, c);
6673 if (pfile->only_seen_white == 0)
6674 pfile->only_seen_white = 1;
6676 output_line_command (pfile, 1, same_file);
6679 case '(': token = CPP_LPAREN; goto char1;
6680 case ')': token = CPP_RPAREN; goto char1;
6681 case '{': token = CPP_LBRACE; goto char1;
6682 case '}': token = CPP_RBRACE; goto char1;
6683 case ',': token = CPP_COMMA; goto char1;
6684 case ';': token = CPP_SEMICOLON; goto char1;
6690 pfile->only_seen_white = 0;
6691 cppReader_putChar (pfile, c);
6700 /* Parse an identifier starting with C. */
6703 parse_name (cppReader *pfile, int c)
6709 if (c == '\\' && cppReader_peekC (pfile) == '\n')
6711 cppReader_forward (pfile, 2);
6715 cppReader_forward (pfile, -1);
6719 if (c == '$' && cppReader_isPedantic (pfile))
6721 cppReader_pedwarnLit (pfile,
6722 cstring_makeLiteralTemp ("`$' in identifier"));
6725 cpplib_reserve(pfile, 2); /* One more for final NUL. */
6726 cppReader_putCharQ (pfile, c);
6727 c = cppReader_getC (pfile);
6733 cppReader_nullTerminateQ (pfile);
6736 /* The file_name_map structure holds a mapping of file names for a
6737 particular directory. This mapping is read from the file named
6738 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
6739 map filenames on a file system with severe filename restrictions,
6740 such as DOS. The format of the file name map file is just a series
6741 of lines with two tokens on each line. The first token is the name
6742 to map, and the second token is the actual name to use. */
6744 struct file_name_map
6746 struct file_name_map *map_next;
6751 /*@constant observer char *FILE_NAME_MAP_FILE*/
6752 #define FILE_NAME_MAP_FILE "header.gcc"
6754 /* Read a space delimited string of unlimited length from a stdio
6757 static cstring read_filename_string (int ch, /*:open:*/ FILE *f)
6763 set = alloc = dmalloc (len + 1);
6768 while ((ch = getc (f)) != EOF && ! is_space[ch])
6770 if (set - alloc == size_toInt (len))
6773 alloc = drealloc (alloc, len + 1);
6774 set = alloc + len / 2;
6775 /*@-branchstate@*/ }
6778 } /*@=branchstate@*/
6781 check (ungetc (ch, f) != EOF);
6783 return cstring_fromChars (alloc);
6786 /* This structure holds a linked list of file name maps, one per directory. */
6788 struct file_name_map_list
6790 /*@only@*/ struct file_name_map_list *map_list_next;
6791 /*@only@*/ cstring map_list_name;
6792 /*@null@*/ struct file_name_map *map_list_map;
6795 /* Read the file name map file for DIRNAME. */
6797 static struct file_name_map *
6798 read_name_map (cppReader *pfile, cstring dirname)
6800 struct file_name_map_list *map_list_ptr;
6804 for (map_list_ptr = CPPOPTIONS (pfile)->map_list;
6805 map_list_ptr != NULL;
6806 map_list_ptr = map_list_ptr->map_list_next)
6808 if (cstring_equal (map_list_ptr->map_list_name, dirname))
6810 return map_list_ptr->map_list_map;
6814 map_list_ptr = (struct file_name_map_list *) dmalloc (sizeof (*map_list_ptr));
6815 map_list_ptr->map_list_name = cstring_copy (dirname);
6816 map_list_ptr->map_list_map = NULL;
6818 name = cstring_copy (dirname);
6820 if (cstring_length (dirname) > 0)
6822 name = cstring_appendChar (name, CONNECTCHAR);
6825 name = cstring_concatFree1 (name, cstring_makeLiteralTemp (FILE_NAME_MAP_FILE));
6827 f = fileTable_openReadFile (context_fileTable (), name);
6828 cstring_free (name);
6832 map_list_ptr->map_list_map = NULL;
6838 while ((ch = getc (f)) != EOF)
6841 struct file_name_map *ptr;
6848 from = read_filename_string (ch, f);
6849 while ((ch = getc (f)) != EOF && is_hor_space[ch])
6854 to = read_filename_string (ch, f);
6856 ptr = (struct file_name_map *) dmalloc (sizeof (*ptr));
6857 ptr->map_from = from;
6859 /* Make the real filename absolute. */
6860 if (cstring_length (to) > 1
6861 && osd_isConnectChar (cstring_firstChar (to)))
6867 ptr->map_to = cstring_copy (dirname);
6868 ptr->map_to = cstring_appendChar (ptr->map_to, CONNECTCHAR);
6869 ptr->map_to = cstring_concatFree (ptr->map_to, to);
6872 ptr->map_next = map_list_ptr->map_list_map;
6873 map_list_ptr->map_list_map = ptr;
6875 while ((ch = getc (f)) != '\n')
6879 /*@innerbreak@*/ break;
6884 assertSet (map_list_ptr->map_list_map);
6885 check (fileTable_closeFile (context_fileTable (),f) == 0);
6888 map_list_ptr->map_list_next = pfile->opts->map_list;
6889 pfile->opts->map_list = map_list_ptr;
6891 return map_list_ptr->map_list_map;
6894 /* Try to open include file FILENAME. SEARCHPTR is the directory
6895 being tried from the include file search path. This function maps
6896 filenames on file systems based on information read by
6900 open_include_file (cppReader *pfile,
6902 struct file_name_list *searchptr)
6904 char *filename = cstring_toCharsSafe (fname);
6905 struct file_name_map *map;
6909 cstring_markOwned (fname);
6911 cpp_setLocation (pfile);
6913 if (context_getFlag (FLG_NEVERINCLUDE))
6915 if (isHeaderFile (fname))
6917 return SKIP_INCLUDE;
6921 if ((searchptr != NULL) && ! searchptr->got_name_map)
6923 searchptr->name_map = read_name_map (pfile,
6924 !cstring_isEmpty (searchptr->fname)
6925 ? searchptr->fname :
6926 cstring_makeLiteralTemp ("."));
6927 searchptr->got_name_map = 1;
6930 /* First check the mapping for the directory we are using. */
6932 if ((searchptr != NULL)
6933 && (searchptr->name_map != NULL))
6937 if (!cstring_isEmpty (searchptr->fname))
6939 from += cstring_length (searchptr->fname) + 1;
6942 for (map = searchptr->name_map;
6944 map = map->map_next)
6946 if (cstring_equal (map->map_from, cstring_fromChars (from)))
6949 ** Found a match. Check if the file should be skipped
6952 if (cpp_skipIncludeFile (map->map_to))
6954 return SKIP_INCLUDE;
6958 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
6965 ** Try to find a mapping file for the particular directory we are
6966 ** looking in. Thus #include <sys/types.h> will look up sys/types.h
6967 ** in /usr/include/header.gcc and look up types.h in
6968 ** /usr/include/sys/header.gcc.
6971 p = strrchr (filename, CONNECTCHAR);
6978 if ((searchptr != NULL)
6979 && (cstring_isDefined (searchptr->fname))
6980 && (size_toInt (cstring_length (searchptr->fname)) == p - filename)
6981 && !strncmp (cstring_toCharsSafe (searchptr->fname),
6983 size_fromInt (p - filename)))
6985 /* filename is in SEARCHPTR, which we've already checked. */
6987 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
6989 return SKIP_INCLUDE;
6993 return cpp_openIncludeFile (filename);
6999 dir = mstring_copy (".");
7004 dir = (char *) dmalloc (size_fromInt (p - filename + 1));
7005 memcpy (dir, filename, size_fromInt (p - filename));
7006 dir[p - filename] = '\0';
7010 for (map = read_name_map (pfile, cstring_fromChars (dir));
7012 map = map->map_next)
7014 if (cstring_equal (map->map_from, cstring_fromChars (from)))
7018 if (cpp_skipIncludeFile (map->map_to))
7020 return SKIP_INCLUDE;
7024 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
7031 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
7033 return SKIP_INCLUDE;
7037 return cpp_openIncludeFile (filename);
7041 /* Process the contents of include file FNAME, already open on descriptor F,
7043 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
7044 "system" include directories (as decided by the `is_system_include'
7046 DIRPTR is the link in the dir path through which this file was found,
7047 or 0 if the file name was absolute or via the current directory.
7048 Return 1 on success, 0 on failure.
7050 The caller is responsible for the cppReader_pushBuffer. */
7053 finclude (cppReader *pfile, int f,
7055 bool system_header_p,
7056 /*@dependent@*/ struct file_name_list *dirptr)
7062 cppBuffer *fp; /* For input stack frame */
7064 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
7066 cppReader_perrorWithName (pfile, fname);
7067 check (close (f) == 0);
7068 (void) cppReader_popBuffer (pfile);
7074 fp = cppReader_getBufferSafe (pfile);
7076 /*@-temptrans@*/ /* fname shouldn't really be temp */
7077 fp->nominal_fname = fp->fname = fname;
7081 fp->system_header_p = system_header_p;
7084 fp->cleanup = cppReader_fileCleanup;
7086 if (S_ISREG (st_mode))
7089 fp->buf = (char *) dmalloc (st_size + 2);
7090 fp->alimit = fp->buf + st_size + 2;
7093 /* Read the file contents, knowing that st_size is an upper bound
7094 on the number of bytes we can read. */
7095 length = safe_read (f, fp->buf, size_toInt (st_size));
7096 fp->rlimit = fp->buf + length;
7097 if (length < 0) goto nope;
7099 else if (S_ISDIR (st_mode))
7101 cppReader_error (pfile,
7102 message ("Directory specified where file is expected: %s", fname));
7103 check (close (f) == 0);
7109 ** Cannot count its file size before reading.
7110 ** First read the entire file into heap and
7111 ** copy them into buffer on stack.
7114 size_t bsize = 2000;
7119 fp->buf = (char *) dmalloc (bsize + 2);
7122 i = safe_read (f, fp->buf + st_size, size_toInt (bsize - st_size));
7125 goto nope; /* error! */
7128 if (st_size != bsize)
7130 break; /* End of file */
7134 fp->buf = (char *) drealloc (fp->buf, bsize + 2);
7138 length = size_toInt (st_size);
7141 if ((length > 0 && fp->buf[length - 1] != '\n')
7142 /* Backslash-newline at end is not good enough. */
7143 || (length > 1 && fp->buf[length - 2] == '\\')) {
7144 fp->buf[length++] = '\n';
7147 fp->buf[length] = '\0';
7148 fp->rlimit = fp->buf + length;
7150 /* Close descriptor now, so nesting does not use lots of descriptors. */
7151 check (close (f) == 0);
7153 /* Must do this before calling trigraph_pcp, so that the correct file name
7154 will be printed in warning messages. */
7156 pfile->input_stack_listing_current = 0;
7161 cppReader_perrorWithName (pfile, fname);
7162 check (close (f) == 0);
7168 cpplib_init (cppReader *pfile)
7170 memset ((char *) pfile, 0, sizeof (*pfile));
7172 pfile->get_token = cpplib_getToken;
7173 pfile->token_buffer_size = 200;
7174 pfile->token_buffer = (char *) dmalloc (pfile->token_buffer_size);
7175 pfile->all_include_files = NULL;
7179 cppReader_setWritten (pfile, 0);
7181 pfile->system_include_depth = 0;
7182 pfile->max_include_len = 0;
7183 pfile->timebuf = NULL;
7184 pfile->only_seen_white = 1;
7186 pfile->buffer = cppReader_nullBuffer (pfile);
7190 cppReader_finish (/*@unused@*/ cppReader *pfile)
7195 /* Free resources used by PFILE.
7196 This is the cppReader 'finalizer' or 'destructor' (in C++ terminology). */
7199 cppCleanup (/*@special@*/ cppReader *pfile)
7201 /*@releases pfile@*/
7203 DPRINTF (("cppCleanup!"));
7205 while (CPPBUFFER (pfile) != cppReader_nullBuffer (pfile))
7207 (void) cppReader_popBuffer (pfile);
7210 if (pfile->token_buffer != NULL)
7212 sfree (pfile->token_buffer);
7213 pfile->token_buffer = NULL;
7216 while (pfile->if_stack != NULL)
7218 cppIfStackFrame *temp = pfile->if_stack;
7219 pfile->if_stack = temp->next;
7223 while (pfile->all_include_files != NULL)
7225 struct file_name_list *temp = pfile->all_include_files;
7226 pfile->all_include_files = temp->next;
7227 /*@-dependenttrans@*/
7228 cstring_free (temp->fname);
7229 /*@=dependenttrans@*/
7233 /* evans 2002-07-12 */
7234 while (pfile->opts->map_list != NULL)
7236 struct file_name_map_list *temp = pfile->opts->map_list;
7237 pfile->opts->map_list = pfile->opts->map_list->map_list_next;
7238 cstring_free (temp->map_list_name);
7242 while (pfile->opts->include != NULL)
7244 struct file_name_list *temp = pfile->opts->include;
7245 pfile->opts->include = pfile->opts->include->next;
7246 /* cstring_free (temp->fname); */
7250 sfree (pfile->opts);
7252 cppReader_hashCleanup ();
7256 ** Get the file-mode and data size of the file open on FD
7257 ** and store them in *MODE_POINTER and *SIZE_POINTER.
7261 file_size_and_mode (int fd, mode_t *mode_pointer, size_t *size_pointer)
7265 if (fstat (fd, &sbuf) < 0) {
7271 if (mode_pointer != NULL)
7273 *mode_pointer = sbuf.st_mode;
7276 if (size_pointer != NULL)
7278 *size_pointer = (size_t) sbuf.st_size;
7284 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
7285 retrying if necessary. Return a negative value if an error occurs,
7286 otherwise return the actual number of bytes read,
7287 which must be LEN unless end-of-file was reached. */
7289 static int safe_read (int desc, char *ptr, int len)
7295 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
7296 /*@-compdef@*/ /* ptr is an out parameter */
7297 int nchars = _read (desc, ptr, (unsigned) left);
7300 ssize_t nchars = read (desc, ptr, size_fromInt (left));
7309 return (int) nchars;
7323 /* Initialize PMARK to remember the current position of PFILE. */
7326 parseSetMark (struct parse_marker *pmark, cppReader *pfile)
7328 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7330 pmark->next = pbuf->marks;
7332 pbuf->marks = pmark;
7336 pmark->position = pbuf->cur - pbuf->buf;
7337 DPRINTF (("set mark: %d / %s", pmark->position, pbuf->cur));
7340 /* Cleanup PMARK - we no longer need it. */
7342 void parseClearMark (struct parse_marker *pmark)
7344 struct parse_marker **pp = &pmark->buf->marks;
7346 for (; ; pp = &(*pp)->next)
7348 llassert (*pp != NULL);
7349 if (*pp == pmark) break;
7355 /* Backup the current position of PFILE to that saved in PMARK. */
7358 parseGotoMark (struct parse_marker *pmark, cppReader *pfile)
7360 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7362 if (pbuf != pmark->buf)
7364 cpp_setLocation (pfile);
7365 llfatalbug (cstring_makeLiteral ("Internal error parseGotoMark"));
7368 llassert (pbuf->buf != NULL);
7369 pbuf->cur = pbuf->buf + pmark->position;
7370 DPRINTF (("goto mark: %d / %s", pmark->position, pbuf->cur));
7373 /* Reset PMARK to point to the current position of PFILE. (Same
7374 as parseClearMark (PMARK), parseSetMark (PMARK, PFILE) but faster. */
7377 parseMoveMark (struct parse_marker *pmark, cppReader *pfile)
7379 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7381 if (pbuf != pmark->buf)
7383 cpp_setLocation (pfile);
7384 llfatalerror (cstring_makeLiteral ("Internal error parseMoveMark"));
7387 pmark->position = pbuf->cur - pbuf->buf;
7388 DPRINTF (("move mark: %s", pmark->position));
7391 void cpplib_initializeReader (cppReader *pfile) /* Must be done after library is loaded. */
7393 struct cppOptions *opts = CPPOPTIONS (pfile);
7396 /* The code looks at the defaults through this pointer, rather than through
7397 the constant structure above. This pointer gets changed if an environment
7398 variable specifies other defaults. */
7400 struct default_include *include_defaults = include_defaults_array;
7402 /* Add dirs from INCLUDEPATH_VAR after dirs from -I. */
7403 /* There seems to be confusion about what CPATH should do,
7404 so for the moment it is not documented. */
7405 /* Some people say that CPATH should replace the standard include dirs,
7406 but that seems pointless: it comes before them, so it overrides them
7409 xp = osd_getEnvironmentVariable (INCLUDEPATH_VAR);
7411 if (cstring_isDefined (xp) && !opts->no_standard_includes)
7413 path_include (pfile, cstring_toCharsSafe (xp));
7416 /* Now that dollars_in_ident is known, initialize is_idchar. */
7417 initialize_char_syntax (opts);
7419 /* CppReader_Install __LINE__, etc. Must follow initialize_char_syntax
7420 and option processing. */
7422 initialize_builtins (pfile);
7424 /* Do standard #defines and assertions
7425 that identify system and machine type. */
7427 if (!opts->inhibit_predefs) {
7428 char *p = (char *) dmalloc (strlen (predefs) + 1);
7429 strcpy (p, predefs);
7435 while (*p == ' ' || *p == '\t')
7440 /* Handle -D options. */
7441 if (p[0] == '-' && p[1] == 'D')
7445 while (*p && *p != ' ' && *p != '\t')
7455 if (opts->debug_output)
7457 output_line_command (pfile, 0, same_file);
7460 cppReader_define (pfile, q);
7462 while (*p == ' ' || *p == '\t')
7476 opts->done_initializing = 1;
7478 { /* Read the appropriate environment variable and if it exists
7479 replace include_defaults with the listed path. */
7483 int win32_buf_size = 0; /* memory we need to allocate */
7486 if (opts->cplusplus)
7488 epath = getenv ("CPLUS_INCLUDE_PATH");
7492 epath = getenv ("C_INCLUDE_PATH");
7496 ** If the environment var for this language is set,
7497 ** add to the default list of include directories.
7500 if (epath != NULL) {
7501 char *nstore = (char *) dmalloc (strlen (epath) + 2);
7503 char *startp, *endp;
7506 /* if we have a posix path list, convert to win32 path list */
7507 if (cygwin32_posix_path_list_p (epath))
7509 win32_buf_size = cygwin32_posix_to_win32_path_list_buf_size (epath);
7510 win32epath = (char *) dmalloc /*@i4@*/ (win32_buf_size);
7511 cygwin32_posix_to_win32_path_list (epath, win32epath);
7515 for (num_dirs = 1, startp = epath; *startp; startp++)
7517 if (*startp == PATH_SEPARATOR)
7523 = (struct default_include *) dmalloc ((num_dirs
7524 * sizeof (struct default_include))
7525 + sizeof (include_defaults_array));
7528 startp = endp = epath;
7531 /* Handle cases like c:/usr/lib:d:/gcc/lib */
7532 if ((*endp == PATH_SEPARATOR) || *endp == 0)
7534 strncpy (nstore, startp, size_fromInt (endp - startp));
7537 strcpy (nstore, ".");
7541 nstore[endp-startp] = '\0';
7544 include_defaults[num_dirs].fname = cstring_fromCharsNew (nstore);
7545 include_defaults[num_dirs].cplusplus = opts->cplusplus;
7546 include_defaults[num_dirs].cxx_aware = 1;
7553 endp = startp = endp + 1;
7560 /* Put the usual defaults back in at the end. */
7561 memcpy ((char *) &include_defaults[num_dirs],
7562 (char *) include_defaults_array,
7563 sizeof (include_defaults_array));
7566 /*@-branchstate@*/ } /*@=branchstate@*/
7569 cppReader_appendIncludeChain (pfile, opts->before_system,
7570 opts->last_before_system);
7572 opts->first_system_include = opts->before_system;
7574 /* Unless -fnostdinc,
7575 tack on the standard include file dirs to the specified list */
7577 if (!opts->no_standard_includes) {
7578 struct default_include *p = include_defaults;
7579 char *specd_prefix = opts->include_prefix;
7580 char *default_prefix = mstring_copy (GCC_INCLUDE_DIR);
7581 size_t default_len = 0;
7583 /* Remove the `include' from /usr/local/lib/gcc.../include. */
7584 if (default_prefix != NULL) {
7585 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
7586 default_len = strlen (default_prefix) - 7;
7587 default_prefix[default_len] = 0;
7591 /* Search "translated" versions of GNU directories.
7592 These have /usr/local/lib/gcc... replaced by specd_prefix. */
7593 if (specd_prefix != 0 && default_len != 0)
7594 for (p = include_defaults; p->fname != NULL; p++) {
7595 /* Some standard dirs are only for C++. */
7597 || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
7598 /* Does this dir start with the prefix? */
7599 llassert (default_prefix != NULL);
7601 if (!strncmp (cstring_toCharsSafe (p->fname), default_prefix, default_len))
7603 /* Yes; change prefix and add to search list. */
7604 struct file_name_list *nlist
7605 = (struct file_name_list *) dmalloc (sizeof (*nlist));
7606 size_t this_len = strlen (specd_prefix) + cstring_length (p->fname) - default_len;
7607 char *str = (char *) dmalloc (this_len + 1);
7608 strcpy (str, specd_prefix);
7609 strcat (str, cstring_toCharsSafe (p->fname) + default_len);
7612 nlist->fname = cstring_fromChars (str);
7613 nlist->control_macro = 0;
7614 nlist->c_system_include_path = !p->cxx_aware;
7615 nlist->got_name_map = 0;
7617 if (opts->first_system_include == 0)
7619 opts->first_system_include = nlist;
7622 cppReader_addIncludeChain (pfile, nlist);
7627 /* Search ordinary names for GNU include directories. */
7629 for (p = include_defaults; p->fname != NULL; p++)
7631 /* Some standard dirs are only for C++. */
7633 || (opts->cplusplus && !opts->no_standard_cplusplus_includes))
7635 struct file_name_list *nlist
7636 = (struct file_name_list *) dmalloc (sizeof (*nlist));
7637 nlist->control_macro = 0;
7638 nlist->c_system_include_path = !p->cxx_aware;
7639 nlist->fname = p->fname;
7640 nlist->got_name_map = 0;
7643 /* Spurious warning reported for opts->first_system_include */
7644 /*@-usereleased@*/ if (opts->first_system_include == NULL)
7646 opts->first_system_include = nlist;
7650 cppReader_addIncludeChain (pfile, nlist);
7653 sfree (default_prefix);
7656 /* Tack the after_include chain at the end of the include chain. */
7657 cppReader_appendIncludeChain (pfile, opts->after_include,
7658 opts->last_after_include);
7660 /* Spurious warnings for opts->first_system_include */
7662 if (opts->first_system_include == NULL)
7664 opts->first_system_include = opts->after_include;
7668 /* With -v, print the list of dirs to search. */
7669 if (opts->verbose) {
7670 struct file_name_list *p;
7671 fprintf (stderr, "#include \"...\" search starts here:\n");
7673 for (p = opts->include; p != NULL; p = p->next) {
7674 if (p == opts->first_bracket_include)
7675 fprintf (stderr, "#include <...> search starts here:\n");
7677 fprintf (stderr, " %s\n", cstring_toCharsSafe (p->fname));
7679 fprintf (stderr, "End of search list.\n");
7683 int cppReader_startProcess (cppReader *pfile, cstring fname)
7687 struct cppOptions *opts = CPPOPTIONS (pfile);
7689 fp = cppReader_pushBuffer (pfile, NULL, 0);
7696 if (opts->in_fname == NULL)
7698 opts->in_fname = cstring_makeLiteralTemp ("");
7701 fp->fname = opts->in_fname;
7702 fp->nominal_fname = fp->fname;
7705 /* Copy the entire contents of the main input file into
7706 the stacked input buffer previously allocated for it. */
7708 if (cstring_isEmpty (fname))
7710 fname = cstring_makeLiteralTemp ("");
7713 else if ((f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666)) < 0)
7715 cppReader_error (pfile,
7716 message ("Error opening %s for reading: %s",
7717 fname, lldecodeerror (errno)));
7726 if (finclude (pfile, f, fname, 0, NULL))
7728 output_line_command (pfile, 0, same_file);
7734 static /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_getBuffer (cppReader *pfile)
7736 return pfile->buffer;
7739 /*@exposed@*/ cppBuffer *cppReader_getBufferSafe (cppReader *pfile)
7741 llassert (pfile->buffer != NULL);
7742 return pfile->buffer;
7745 /*@exposed@*/ char *cppLineBase (cppBuffer *buf)
7747 llassert (buf->buf != NULL);
7748 return (buf->buf + buf->line_base);
7751 int cpplib_bufPeek (cppBuffer *buf)
7753 if (buf->cur == NULL || buf->rlimit == NULL) {
7757 if (buf->cur < buf->rlimit) {
7764 bool cppBuffer_isMacro (cppBuffer *buf)
7768 return (buf->cleanup == cppReader_macroCleanup);
7775 ** Returns true if the macro should be checked, false
7776 ** if it should be expanded normally.
7779 static bool notparseable = FALSE; /* preceeded by @notparseable@ */
7780 static bool notfunction = FALSE; /* preceeded by @notfunction@ */
7781 static bool expectiter = FALSE; /* preceeded by @iter@ */
7782 static bool expectenditer = FALSE; /* second after @iter@ */
7783 static bool expectfunction = FALSE; /* preceeded by @function@ */
7784 static bool expectconstant = FALSE; /* preceeded by @constant@ */
7785 static bool expectmacro = FALSE; /* preceeded by notfunction or notparseable */
7787 static void cpp_setLocation (cppReader *pfile)
7792 if (pfile->buffer != NULL)
7794 if (cstring_isDefined (cppReader_getBufferSafe (pfile)->nominal_fname))
7796 cstring fname = cppReader_getBufferSafe (pfile)->nominal_fname;
7798 DPRINTF (("Looking up: %s", fname));
7800 if (fileTable_exists (context_fileTable (), fname))
7802 fid = fileTable_lookup (context_fileTable (), fname);
7806 DPRINTF (("Trying %s", cppReader_getBuffer (pfile)->fname));
7808 fid = fileTable_lookup (context_fileTable (),
7809 cppReader_getBufferSafe (pfile)->fname);
7814 fid = fileTable_lookup (context_fileTable (),
7815 cppReader_getBufferSafe (pfile)->fname);
7818 line = cppReader_getBufferSafe (pfile)->lineno;
7819 fileloc_free (g_currentloc);
7821 if (fileId_isValid (fid))
7823 g_currentloc = fileloc_create (fid, line, 1);
7827 g_currentloc = fileloc_createBuiltin ();
7832 fileloc_free (g_currentloc);
7833 g_currentloc = fileloc_createBuiltin ();
7837 static bool cpp_shouldCheckMacro (cppReader *pfile, char *p) /*@modifies p*/
7839 bool checkmacro = FALSE;
7840 bool hasParams = FALSE;
7841 bool noexpand = FALSE;
7845 cpp_setLocation (pfile);
7847 DPRINTF (("Should check macro? %s", p));
7849 if (expectiter || expectconstant || expectenditer)
7854 expectenditer = TRUE;
7859 expectconstant = FALSE;
7860 expectenditer = FALSE;
7863 if (notfunction || notparseable)
7865 notfunction = FALSE;
7866 notparseable = FALSE;
7875 llassert (*p == '#');
7878 while (*p == ' ' || *p == '\t')
7883 llassert (*p == 'd'); /* define starts */
7887 while (*p == ' ' || *p == '\t')
7892 sname = cstring_fromChars (p);
7893 DPRINTF (("Check macro: %s", sname));
7895 while (((c = *p) != ' ')
7896 && c != '\0' && c != '('
7897 && c != '\t' && c != '\\' && c != '\n'
7903 hasParams = (c == '(');
7908 notparseable = FALSE;
7910 else if (notfunction || fileloc_isStandardLib (g_currentloc))
7912 DPRINTF (("Clear notfunction"));
7913 notfunction = FALSE;
7928 if (usymtab_existsReal (sname))
7930 uentry ue = usymtab_lookup (sname);
7932 DPRINTF (("Lookup macro: %s", uentry_unparse (ue)));
7934 if (fileloc_isPreproc (uentry_whereLast (ue)))
7940 if (uentry_isSpecified (ue))
7942 checkmacro = context_getFlag (FLG_SPECMACROS);
7948 checkmacro = context_getFlag (FLG_LIBMACROS)
7949 || context_getFlag (FLG_FCNMACROS);
7957 DPRINTF (("Macro doesn't exist: %s", bool_unparse (checkmacro)));
7959 if (fileloc_isSystemFile (g_currentloc)
7960 && context_getFlag (FLG_SYSTEMDIREXPAND))
7962 ; /* don't check this macro */
7963 DPRINTF (("Don't check 1"));
7971 DPRINTF (("Has params..."));
7973 if (context_getFlag (FLG_FCNMACROS))
7975 if (usymtab_exists (sname))
7978 ** only get here is macro is redefined
7979 ** error reported elsewhere
7982 DPRINTF (("It exists!"));
7987 ** We make it a forward function, since it might be declared elsewhere.
7988 ** After all headers have been processed, we should check the forward
7992 fileloc loc = fileloc_makePreproc (g_currentloc);
7994 /* the line is off-by-one, since the newline was already read */
7999 expectfunction = FALSE;
8002 le = uentry_makeForwardFunction (sname,
8003 typeId_invalid, loc);
8009 /* Do not define here! */
8011 (void) usymtab_addEntry (le);
8015 DPRINTF (("Check: TRUE"));
8019 DPRINTF (("Flag FCN_MACROS not set!"));
8024 DPRINTF (("No params"));
8026 if (context_getFlag (FLG_CONSTMACROS))
8028 bool nocontent = FALSE;
8041 ** Check if there is nothing after the define.
8044 while ((*rest) != '\0' && isspace (*rest))
8051 nocontent = TRUE; /* empty macro, don't check */
8056 if (usymtab_exists (sname))
8062 fileloc loc = fileloc_makePreproc (g_currentloc);
8063 DPRINTF (("Make constant: %s", sname));
8064 le = uentry_makeMacroConstant (sname, ctype_unknown, loc);
8065 (void) usymtab_addEntry (le);
8068 checkmacro = !nocontent;
8073 if (checkmacro && usymtab_existsType (sname))
8075 DPRINTF (("Making false..."));
8077 ppllerror (message ("Specified type implemented as macro: %s", sname));
8087 if (usymtab_exists (sname))
8089 uentry ue = usymtab_lookupExpose (sname);
8090 fileloc tloc = fileloc_makePreproc (g_currentloc);
8092 uentry_setDefined (ue, tloc);
8093 fileloc_free (tloc);
8094 uentry_setUsed (ue, fileloc_undefined);
8098 fileloc tloc = fileloc_makePreproc (g_currentloc);
8099 uentry ue = uentry_makeExpandedMacro (sname, tloc);
8100 DPRINTF (("Make expanded macro: %s", sname));
8101 DPRINTF (("Not in symbol table: %s", sname));
8103 (void) usymtab_addGlobalEntry (ue);
8104 fileloc_free (tloc);
8109 DPRINTF (("Returning: %s", bool_unparse (checkmacro)));
8113 static enum cpp_token
8114 cpp_handleComment (cppReader *pfile, struct parse_marker *smark)
8116 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
8120 bool eliminateComment = FALSE;
8122 llassert (pbuf->buf != NULL);
8124 start = pbuf->buf + smark->position;
8126 llassert (pbuf->cur != NULL);
8127 len = pbuf->cur - start;
8130 && start[1] == context_getCommentMarkerChar ())
8134 char *scomment = start + 2;
8135 char savec = start[len];
8137 cpp_setLocation (pfile);
8138 loc = fileloc_copy (g_currentloc);
8140 start[0] = BEFORE_COMMENT_MARKER[0];
8141 start[1] = BEFORE_COMMENT_MARKER[1];
8143 llassert (start[len - 2] == '*');
8144 start[len - 2] = AFTER_COMMENT_MARKER[0];
8146 llassert (start[len - 1] == '/');
8147 start[len - 1] = AFTER_COMMENT_MARKER[1];
8149 cpplib_reserve(pfile, size_fromInt (1 + len));
8150 cppReader_putCharQ (pfile, c);
8152 cpp_setLocation (pfile);
8156 if (mstring_containsString (scomment, "/*"))
8158 (void) cppoptgenerror
8160 message ("Comment starts inside syntactic comment: %s",
8161 cstring_fromChars (scomment)),
8167 if (mstring_equalPrefix (scomment, "ignore"))
8169 if (!context_getFlag (FLG_NOCOMMENTS))
8171 context_enterSuppressRegion (loc);
8174 else if (mstring_equalPrefix (scomment, "end"))
8176 if (!context_getFlag (FLG_NOCOMMENTS))
8178 context_exitSuppressRegion (loc);
8181 else if (mstring_equalPrefix (scomment, "notparseable"))
8183 notparseable = TRUE;
8185 eliminateComment = TRUE;
8187 else if (mstring_equalPrefix (scomment, "notfunction"))
8191 eliminateComment = TRUE;
8193 else if (mstring_equalPrefix (scomment, "iter"))
8197 else if (mstring_equalPrefix (scomment, "function"))
8199 expectfunction = TRUE;
8201 else if (mstring_equalPrefix (scomment, "constant"))
8203 expectconstant = TRUE;
8207 char sChar = *scomment;
8213 char *rest = scomment + 1;
8215 if (mstring_equalPrefix (rest, "commentchar"))
8217 eliminateComment = TRUE;
8221 ppllerror (cstring_makeLiteral
8222 ("Cannot restore commentchar"));
8226 char *next = scomment + 12; /* strlen commentchar = 12 */
8228 if (*next != ' ' && *next != '\t' && *next != '\n')
8232 ("Syntactic commentchar comment is not followed by a "
8233 "whitespace character: %c",
8238 char cchar = *(next + 1);
8243 (cstring_makeLiteral
8244 ("Cannot set commentchar to NUL"));
8248 context_setCommentMarkerChar (cchar);
8249 /* setComment = TRUE; */
8254 else if (mstring_equalPrefix (scomment, "nestcomment"))
8256 /* fix from Mike Miller <MikeM@xata.com> */
8257 context_fileSetFlag (FLG_NESTCOMMENT,
8258 ynm_fromCodeChar (sChar),
8261 else if (mstring_equalPrefix (rest, "namechecks"))
8263 context_fileSetFlag (FLG_NAMECHECKS,
8264 ynm_fromCodeChar (sChar),
8267 else if (mstring_equalPrefix (rest, "macroredef"))
8269 context_fileSetFlag (FLG_MACROREDEF,
8270 ynm_fromCodeChar (sChar),
8273 else if (mstring_equalPrefix (rest, "usevarargs"))
8275 context_fileSetFlag (FLG_USEVARARGS,
8276 ynm_fromCodeChar (sChar),
8279 else if (mstring_equalPrefix (rest, "nextlinemacros"))
8281 context_fileSetFlag (FLG_MACRONEXTLINE,
8282 ynm_fromCodeChar (sChar),
8285 else if (mstring_equalPrefix (rest, "allmacros")
8286 || mstring_equalPrefix (rest, "fcnmacros")
8287 || mstring_equalPrefix (rest, "constmacros"))
8291 if (mstring_equalPrefix (rest, "allmacros"))
8295 else if (mstring_equalPrefix (rest, "fcnmacros"))
8301 llassert (mstring_equalPrefix (rest, "constmacros"));
8302 fl = FLG_CONSTMACROS;
8305 context_fileSetFlag (fl, ynm_fromCodeChar (sChar), loc);
8306 notfunction = FALSE;
8319 if (eliminateComment)
8324 /* Replaces comment char's in start with spaces */
8326 for (i = 2; i < len - 2; i++)
8328 if (start[i] == BEFORE_COMMENT_MARKER[0]
8329 || start[i] == BEFORE_COMMENT_MARKER[1]
8330 || start[i] == context_getCommentMarkerChar ())
8336 cppReader_putStrN (pfile, start, size_fromInt (len));
8337 parseClearMark (smark);
8347 ** Output the comment as all spaces so line/column
8348 ** in output file is still correct.
8352 cstring lintcomment = cstring_undefined;
8354 if (context_getFlag (FLG_LINTCOMMENTS))
8356 if (mstring_equalPrefix (start, "*NOTREACHED*/"))
8358 lintcomment = cstring_makeLiteralTemp ("l_notreach");
8360 else if (mstring_equalPrefix (start, "*PRINTFLIKE*/"))
8362 lintcomment = cstring_makeLiteralTemp ("l_printfli");
8364 else if (mstring_equalPrefix (start, "*FALLTHROUGH*/"))
8366 lintcomment = cstring_makeLiteralTemp ("l_fallthrou");
8368 else if (mstring_equalPrefix (start, "*ARGSUSED*/"))
8370 lintcomment = cstring_makeLiteralTemp ("l_argsus");
8372 else if (mstring_equalPrefix (start, "*FALLTHRU*/"))
8374 lintcomment = cstring_makeLiteralTemp ("l_fallth");
8378 lintcomment = cstring_undefined;
8383 lintcomment = cstring_undefined;
8386 if (cstring_isDefined (lintcomment))
8388 c = BEFORE_COMMENT_MARKER[0];
8389 start[0] = BEFORE_COMMENT_MARKER[1];
8391 llassert (size_toLong (cstring_length (lintcomment)) == len - 3);
8393 for (i = 1; i < len - 2; i++)
8395 start[i] = cstring_getChar (lintcomment, size_fromInt (i));
8398 start[len - 2] = AFTER_COMMENT_MARKER[0];
8399 start[len - 1] = AFTER_COMMENT_MARKER[1];
8403 /* Replaces char's in start with spaces */
8404 for (i = 0; i < len; i++)
8408 && start[i + 1] == '*') {
8409 (void) cppoptgenerror
8411 message ("Comment starts inside comment"),
8415 if (start[i] != '\n')
8422 cpplib_reserve (pfile, size_fromInt (1 + len));
8423 cppReader_putCharQ (pfile, c);
8424 cppReader_putStrN (pfile, start, size_fromInt (len));
8425 parseClearMark (smark);
8431 static int cpp_openIncludeFile (char *filename)
8433 int res = open (filename, O_RDONLY, 0666);
8435 /* evans 2001-08-23: was (res) - open returns -1 on error! reported by Robin Watts */
8438 if (!fileTable_exists (context_fileTable (),
8439 cstring_fromChars (filename)))
8441 if (fileloc_isXHFile (g_currentloc))
8444 ** Files includes by XH files are also XH files
8447 (void) fileTable_addXHFile (context_fileTable (),
8448 cstring_fromChars (filename));
8452 (void) fileTable_addHeaderFile (context_fileTable (),
8453 cstring_fromChars (filename));
8458 DPRINTF (("File already exists: %s", filename));
8465 static bool cpp_skipIncludeFile (cstring fname)
8467 if (context_isSystemDir (fname))
8469 DPRINTF (("System dir: %s", fname));
8471 if (lcllib_isSkipHeader (fname))
8473 DPRINTF (("Skip include TRUE: %s", fname));
8477 if (context_getFlag (FLG_SKIPSYSHEADERS))
8480 ** 2003-04-18: Patch from Randal Parsons
8484 ** Don't skip include file unless the file actually exists.
8485 ** It may be in a different directory.
8488 int f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666);
8492 check (close (f) == 0);
8493 DPRINTF (("Skip include TRUE: %s", fname));
8498 /* Keep looking... */
8503 if (context_getFlag (FLG_SINGLEINCLUDE))
8505 fname = removePreDirs (fname);
8507 # if defined (WIN32) || defined (OS2)
8508 cstring_replaceAll (fname, '\\', '/');
8511 if (fileTable_exists (context_fileTable (), fname))
8513 DPRINTF (("Skip include TRUE: %s", fname));
8518 DPRINTF (("Skip include FALSE: %s", fname));
8522 static int cpp_peekN (cppReader *pfile, int n)
8524 cppBuffer *buf = cppReader_getBufferSafe (pfile);
8526 llassert (buf->cur != NULL);
8528 return (buf->rlimit - buf->cur >= (n)
8533 cppBuffer *cppBuffer_prevBuffer (cppBuffer *buf)
8538 void cppBuffer_forward (cppBuffer *buf, int n)
8540 llassert (buf->cur != NULL);
8544 /*@=bufferoverflowhigh@*/