2 ** Splint - annotation-assisted static program checker
3 ** Copyright (C) 1994-2003 University of Virginia,
4 ** Massachusetts Institute of Technology
6 ** This program is free software; you can redistribute it and/or modify it
7 ** under the terms of the GNU General Public License as published by the
8 ** Free Software Foundation; either version 2 of the License, or (at your
9 ** option) any later version.
11 ** This program is distributed in the hope that it will be useful, but
12 ** WITHOUT ANY WARRANTY; without even the implied warranty of
13 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ** General Public License for more details.
16 ** The GNU General Public License is available from http://www.gnu.org/ or
17 ** the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
18 ** MA 02111-1307, USA.
20 ** For information on splint: info@splint.org
21 ** To report a bug: splint-bug@splint.org
22 ** For more information: http://www.splint.org
28 Copyright (C) 1986, 87, 89, 92-6, 1997 Free Software Foundation, Inc.
29 Contributed by Per Bothner, 1994-95.
30 Based on CCCP program by Paul Rubin, June 1986
31 Adapted to ANSI C, Richard Stallman, Jan 1987
33 This program is free software; you can redistribute it and/or modify it
34 under the terms of the GNU General Public License as published by the
35 Free Software Foundation; either version 2, or (at your option) any
38 This program is distributed in the hope that it will be useful,
39 but WITHOUT ANY WARRANTY; without even the implied warranty of
40 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 GNU General Public License for more details.
43 You should have received a copy of the GNU General Public License
44 along with this program; if not, write to the Free Software
45 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 In other words, you are welcome to use, share and improve this program.
48 You are forbidden to forbid anyone else to use, share and improve
49 what you give them. Help stamp out software-hoarding! */
53 * - OS2 drive specs like WIN32
54 * - Includes for IBMs OS/2 compiler
65 # if !(defined (WIN32) || defined (OS2) && defined (__IBMC__))
68 # include <sys/types.h>
69 # include <sys/stat.h>
71 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
75 # include <sys/utime.h> /* for __DATE__ and __TIME__ */
82 ** evans 2002-07-03: exception for WATCOM 10.6 compiler suggest by Adam Clarke
84 # if !defined (USG) && !defined (__WATCOMC__)
85 # include <time.h> /* Reported by Paul Smith */
86 # include <sys/time.h>
87 # include <sys/resource.h>
89 # include <sys/times.h>
94 # endif /* not WIN32 */
96 /* This defines "errno" properly for VMS, and gives us EACCES. */
99 # include "splintMacros.nf"
103 # include "cpperror.h"
104 # include "cpphash.h"
106 # include "version.h"
110 ** This is really kludgey code...
116 /* Warnings for using sprintf - suppress them all for now... */
117 /*@-bufferoverflowhigh@*/
120 #define NO_SHORTNAMES
128 /*@constant int IMPORT_FOUND@*/
129 # define IMPORT_FOUND -2
131 /*@constant int SKIP_INCLUDE@*/
132 # define SKIP_INCLUDE IMPORT_FOUND
134 /*@constant unused int IMPORT_NOT_FOUND@*/
135 # define IMPORT_NOT_FOUND -1
138 /*@constant unused int STDC_VALUE@*/
142 /* By default, colon separates directories in a path. */
143 #ifndef PATH_SEPARATOR
144 /*@constant char PATH_SEPARATOR@*/
145 #define PATH_SEPARATOR ':'
148 static void parse_name (cppReader *, int);
150 static int cpp_openIncludeFile (char *p_filename)
151 /*@modifies fileSystem @*/ ;
153 static void cpp_setLocation (cppReader *p_pfile)
154 /*@modifies g_currentloc@*/ ;
156 static enum cpp_token cpp_handleComment (cppReader *p_pfile,
157 struct parse_marker *p_smark)
158 /*@modifies p_pfile, p_smark@*/;
160 static bool cpp_shouldCheckMacro (cppReader *p_pfile, char *p_p) /*@modifies p_p@*/ ;
162 static size_t cppReader_checkMacroNameLoc (fileloc p_loc, char *p_symname, cstring p_usage) ;
164 static bool cpp_skipIncludeFile (cstring p_fname) /*@*/ ;
170 /* Symbols to predefine. */
172 #ifdef CPP_PREDEFINES
173 static /*@observer@*/ char *predefs = CPP_PREDEFINES;
175 static /*@observer@*/ char *predefs = "";
178 /* We let tm.h override the types used here, to handle trivial differences
179 such as the choice of unsigned int or long unsigned int for size_t.
180 When machines start needing nontrivial differences in the size type,
181 it would be best to do something here to figure out automatically
182 from other information what type to use. */
184 /* The string value for __SIZE_TYPE__. */
187 /*@constant observer char *SIZE_TYPE@*/
188 #define SIZE_TYPE "long unsigned int"
191 /* The string value for __PTRDIFF_TYPE__. */
194 /*@constant observer char *PTRDIFF_TYPE@*/
195 #define PTRDIFF_TYPE "long int"
198 /* The string value for __WCHAR_TYPE__. */
201 /*@constant observer char *WCHAR_TYPE@*/
202 #define WCHAR_TYPE "int"
205 /* The string value for __USER_LABEL_PREFIX__ */
207 #ifndef USER_LABEL_PREFIX
208 /*@constant observer char *USER_LABEL_PREFIX@*/
209 #define USER_LABEL_PREFIX ""
212 /* The string value for __REGISTER_PREFIX__ */
214 #ifndef REGISTER_PREFIX
215 /*@constant observer char *REGISTER_PREFIX@*/
216 #define REGISTER_PREFIX ""
219 /* table to tell if char can be part of a C identifier. */
220 static bool is_idchar[256];
221 /* table to tell if char can be first char of a c identifier. */
222 static bool is_idstart[256];
223 /* table to tell if c is horizontal space. */
224 static bool is_hor_space[256];
225 /* table to tell if c is horizontal or vertical space. */
226 static bool is_space[256];
228 static /*@exposed@*/ /*@null@*/ cppBuffer *
229 cppReader_getBuffer (/*@special@*/ cppReader *p_pfile)
230 /*@uses p_pfile->buffer@*/
231 /*@modifies nothing@*/ ;
234 # define SKIP_WHITE_SPACE(p) do { /*@access cstring@*/ while (is_hor_space[(int) *(p)]) { (p)++; } } /*@noaccess cstring@*/ while (0)
237 # define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*(p)]) { (p)++; } } while (0)
239 static int cpp_peekN (cppReader *p_pfile, int p_n) /*@*/ ;
241 /*@function static int cppBuffer_get (sef cppBuffer *p_b) modifies *p_b ; @*/
242 # define cppBuffer_get(BUFFER) \
243 ((BUFFER)->cur < (BUFFER)->rlimit ? *(BUFFER)->cur++ : EOF)
245 /*@function static int cppBuffer_reachedEOF (sef cppBuffer *p_b) modifies nothing; @*/
246 # define cppBuffer_reachedEOF(b) \
247 ((b)->cur < (b)->rlimit ? FALSE : TRUE)
249 /* Append string STR (of length N) to PFILE's output buffer. Make space. */
250 /*@function static void cppReader_puts (sef cppReader *p_file, char *p_str, sef size_t p_n)
251 modifies *p_file; @*/
252 # define cppReader_puts(PFILE, STR, N) \
253 cpplib_reserve(PFILE, N), cppReader_putStrN (PFILE, STR,N)
255 /* Append character CH to PFILE's output buffer. Assume sufficient space. */
257 /*@function static void cppReader_putCharQ (cppReader *p_file, char p_ch)
258 modifies *p_file; @*/
259 # define cppReader_putCharQ(PFILE, CH) (*(PFILE)->limit++ = (CH))
261 static void cppReader_putCharQ (cppReader *p_file, char p_ch)
263 fprintf (stderr, "put char: %c\n", p_ch);
264 (*(p_file)->limit++ = (p_ch));
267 /* Append character CH to PFILE's output buffer. Make space if need be. */
269 /*@function static void cppReader_putChar (sef cppReader *p_file, char p_ch)
270 modifies *p_file; @*/
271 #define cppReader_putChar(PFILE, CH) (cpplib_reserve (PFILE, (size_t) 1), cppReader_putCharQ (PFILE, CH))
273 /* Make sure PFILE->limit is followed by '\0'. */
274 /*@function static void cppReader_nullTerminateQ (cppReader *p_file)
275 modifies *p_file; @*/
277 #define cppReader_nullTerminateQ(PFILE) (*(PFILE)->limit = 0)
279 /*@function static void cppReader_nullTerminate (sef cppReader *p_file)
280 modifies *p_file; @*/
281 # define cppReader_nullTerminate(PFILE) \
282 (cpplib_reserve (PFILE, (size_t) 1), *(PFILE)->limit = 0)
284 /*@function static void cppReader_adjustWritten (cppReader *p_file, size_t)
285 modifies *p_file; @*/
286 #define cppReader_adjustWritten(PFILE,DELTA) ((PFILE)->limit += (DELTA))
288 /*@function static bool cppReader_isC89 (cppReader *) modifies nothing; @*/
289 #define cppReader_isC89(PFILE) (CPPOPTIONS(PFILE)->c89)
291 /*@function static observer char *cppReader_wcharType (cppReader *)
292 modifies nothing; @*/
294 # define cppReader_wcharType(PFILE) \
295 (CPPOPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
297 static void cppBuffer_forward (cppBuffer *p_buf, int p_n) /*@modifies *p_buf@*/ ;
299 /*@function static void cppReader_forward (cppReader *p_pfile, int) modifies *p_pfile; @*/
300 # define cppReader_forward(pfile, N) \
301 (cppBuffer_forward (cppReader_getBufferSafe (pfile), (N)))
303 /*@function static int cppReader_getC (cppReader *p_pfile) modifies *p_pfile; @*/
304 # define cppReader_getC(pfile) (cppBuffer_get (cppReader_getBufferSafe (pfile)))
306 /*@function static int cppReader_reachedEOF (sef cppReader *p_pfile) modifies *p_pfile; @*/
307 # define cppReader_reachedEOF(pfile) (cppBuffer_reachedEOF (cppReader_getBufferSafe (pfile)))
309 /*@function static int cppReader_peekC (cppReader *) modifies nothing;@*/
310 # define cppReader_peekC(pfile) (cpplib_bufPeek (cppReader_getBufferSafe (pfile)))
312 /* Move all backslash-newline pairs out of embarrassing places.
313 Exchange all such pairs following BP
314 with any potentially-embarrassing characters that follow them.
315 Potentially-embarrassing characters are / and *
316 (because a backslash-newline inside a comment delimiter
317 would cause it not to be recognized). */
320 # define NEWLINE_FIX \
321 do { while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n') { cppReader_forward (pfile, 2); } } while(FALSE)
323 /* Same, but assume we've already read the potential '\\' into C. */
325 # define NEWLINE_FIX1(C) do { \
326 while ((C) == '\\' && cppReader_peekC (pfile) == '\n') { cppReader_forward (pfile, 1); (C) = cppReader_getC (pfile); }\
329 static void parseSetMark (/*@out@*/ struct parse_marker *,
331 static void parseClearMark (struct parse_marker *);
332 static void parseGotoMark (struct parse_marker *, cppReader *);
333 static void parseMoveMark (struct parse_marker *, cppReader *);
335 /* If we have a huge buffer, may need to cache more recent counts */
336 static /*@exposed@*/ char *cppLineBase (/*@sef@*/ cppBuffer *);
338 static /*@exposed@*/ /*@null@*/ cppBuffer *
339 cppReader_pushBuffer (cppReader *p_pfile,
340 /*@owned@*/ /*@null@*/ char *, size_t)
341 /*@modifies p_pfile@*/ ;
343 static void cppReader_appendIncludeChain
345 /*@keep@*/ struct file_name_list *p_first,
346 /*@dependent@*/ struct file_name_list *p_last);
348 static void cppReader_macroCleanup (cppBuffer *p_pbuf, cppReader *p_pfile);
349 static enum cpp_token cppReader_nullUnderflow (/*@unused@*/ cppReader *p_pfile);
351 static void cppReader_nullCleanup (/*@unused@*/ cppBuffer *p_pbuf,
352 /*@unused@*/ cppReader *p_pfile);
354 static void cppReader_fileCleanup (cppBuffer *p_pbuf,
355 /*@unused@*/ cppReader *p_pfile);
357 static int cppReader_handleDirective (cppReader *p_pfile);
359 static void cppReader_scanBuffer (cppReader *p_pfile);
361 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
366 ** WIN32 (at least the VC++ include files) does not define mode_t.
369 /*@-incondefs@*/ /*@-czechtypes@*/
370 typedef unsigned int mode_t;
371 /*@=incondefs@*/ /*@=czechtypes@*/
376 static int file_size_and_mode (int p_fd, /*@out@*/ __mode_t *p_mode_pointer,
377 /*@out@*/ size_t *p_size_pointer);
378 static int safe_read (int p_desc, /*@out@*/ char *p_ptr, int p_len);
382 ** cppBuffer_isMacro is true if the buffer contains macro expansion.
383 ** (Note that it is false while we're expanding marco *arguments*.)
386 static bool cppBuffer_isMacro (/*@null@*/ cppBuffer *) /*@*/ ;
388 static void path_include (cppReader *p_pfile, char *p_path)
389 /*@modifies p_pfile@*/ ;
391 static void initialize_builtins (cppReader *p_pfile)
392 /*@modifies p_pfile@*/ ;
394 static void initialize_char_syntax (struct cppOptions *p_opts) ;
396 static int /*@alt void@*/ finclude (cppReader *p_pfile, int p_f,
398 bool p_system_header_p,
399 /*@dependent@*/ /*@null@*/ struct file_name_list *p_dirptr);
401 static void validate_else (cppReader *p_pfile, cstring p_directive);
403 static void conditional_skip (cppReader *p_pfile, int p_skip,
404 enum node_type p_type,
405 /*@dependent@*/ /*@null@*/ char *p_control_macro);
407 static HOST_WIDE_INT eval_if_expression (cppReader *p_pfile,
411 static void skip_if_group (cppReader *p_pfile, int p_any);
413 static bool comp_def_part (bool p_first, char *p_beg1, int p_len1,
414 char *p_beg2, int p_len2, bool p_last);
417 extern void fancy_abort ();
420 static bool redundant_include_p (cppReader *p_pfile, /*@null@*/ cstring p_name);
421 static bool is_system_include (cppReader *p_pfile, cstring p_filename);
423 static /*@observer@*/ /*@null@*/ struct file_name_map *
424 read_name_map (cppReader *p_pfile, cstring p_dirname);
426 static cstring read_filename_string (int p_ch, /*:open:*/ FILE *p_f);
428 static int open_include_file (cppReader *p_pfile,
429 /*@owned@*/ cstring p_fname,
430 /*@null@*/ struct file_name_list *p_searchptr);
432 static void push_macro_expansion (cppReader *,
433 /*@owned@*/ char *, size_t,
434 /*@dependent@*/ hashNode);
436 /* Last arg to output_line_command. */
437 enum file_change_code {
438 same_file, enter_file, leave_file
441 /* `struct directive' defines one #-directive, including how to handle it. */
444 int length; /* Length of name */
445 /*@null@*/ int (*func)(); /* Function to handle directive */
446 /*@observer@*/ cstring name; /* Name of directive */
447 enum node_type type; /* Code which describes which directive. */
448 bool command_reads_line; /* One if rest of line is read by func. */
449 bool traditional_comments; /* Nonzero: keep comments if -traditional. */
450 bool pass_thru; /* Copy preprocessed directive to output file.*/
453 /* These functions are declared to return int instead of void since they
454 are going to be placed in a table and some old compilers have trouble with
455 pointers to functions returning void. */
457 static int do_define (cppReader *, /*@null@*/ struct directive *,
458 /*@exposed@*/ char *, char *);
459 static int do_defineAux (cppReader *, /*@null@*/ struct directive *,
460 /*@exposed@*/ char *, char *, bool);
462 static int do_line (cppReader *, /*@null@*/ struct directive *);
463 static int do_include (cppReader *, struct directive *, char *, char *);
464 static int do_undef (cppReader *, struct directive *, char *, char *);
465 static int do_error (cppReader *, struct directive *, char *, char *);
466 static int do_pragma (cppReader *, struct directive *, char *, char *);
467 static int do_ident (cppReader *, struct directive *, char *, char *);
468 static int do_if (cppReader *, struct directive *, char *, char *);
469 static int do_xifdef (cppReader *, struct directive *, char *, char *);
470 static int do_else (cppReader *, struct directive *, char *, char *);
471 static int do_elif (cppReader *, struct directive *, char *, char *);
472 static int do_endif (cppReader *, struct directive *, char *, char *);
473 static int do_warning (cppReader *, struct directive *, char *, char *);
475 /* If a buffer's dir field is SELF_DIR_DUMMY, it means the file was found
476 via the same directory as the file that #included it. */
478 /*@constant observer struct file_name_list *SELF_DIR_DUMMY@*/
479 #define SELF_DIR_DUMMY ((struct file_name_list *) (~0))
481 /* #include "file" looks in source file dir, then stack. */
482 /* #include <file> just looks in the stack. */
483 /* -I directories are added to the end, then the defaults are added. */
487 static struct default_include {
488 /*@dependent@*/ /*@observer@*/ cstring fname; /* The name of the directory. */
489 int cplusplus; /* Only look here if we're compiling C++. */
490 int cxx_aware; /* Includes in this directory don't need to
491 be wrapped in extern "C" when compiling
493 } include_defaults_array[]
495 /* This is the dir for fixincludes. Put it just before
496 the files that we fix. */
497 { GCC_INCLUDE_DIR, 0, 0 },
498 { GCC_INCLUDE_DIR2, 0, 0 },
499 { cstring_undefined, 0, 0 }
502 /*@noaccess cstring@*/
504 /* Here is the actual list of #-directives, most-often-used first.
505 The initialize_builtins function assumes #define is the very first. */
509 static struct directive directive_table[] = {
510 { 6, do_define, "define", T_DEFINE, FALSE, TRUE, FALSE },
511 { 5, do_xifdef, "ifdef", T_IFDEF, TRUE, FALSE, FALSE },
512 { 6, do_xifdef, "ifndef", T_IFNDEF, TRUE, FALSE, FALSE },
513 { 7, do_include, "include", T_INCLUDE, TRUE, FALSE, FALSE },
514 { 5, do_endif, "endif", T_ENDIF, TRUE, FALSE, FALSE },
515 { 4, do_else, "else", T_ELSE, TRUE, FALSE, FALSE },
516 { 2, do_if, "if", T_IF, TRUE, FALSE, FALSE },
517 { 4, do_elif, "elif", T_ELIF, TRUE, FALSE, FALSE },
518 { 5, do_undef, "undef", T_UNDEF, FALSE, FALSE, FALSE },
519 { 5, do_error, "error", T_ERROR, FALSE, FALSE, FALSE },
520 { 7, do_warning, "warning", T_WARNING, FALSE, FALSE, FALSE },
521 { 6, do_pragma, "pragma", T_PRAGMA, FALSE, FALSE, TRUE},
522 { 4, do_line, "line", T_LINE, TRUE, FALSE, FALSE },
523 { 5, do_ident, "ident", T_IDENT, TRUE, FALSE, TRUE },
524 /* { 8, do_unassert, "unassert", T_UNASSERT, TRUE, FALSE, FALSE }, */
525 { -1, NULL, "", T_UNUSED, FALSE, FALSE, FALSE },
527 /*@noaccess cstring@*/
529 static cstring searchPath_unparse (struct file_name_list *search_start)
531 cstring res = cstring_newEmpty ();
532 struct file_name_list *searchptr = NULL;
534 for (searchptr = search_start; searchptr != NULL;
535 searchptr = searchptr->next)
537 if (!cstring_isEmpty (searchptr->fname)) {
538 res = cstring_concatFree1 (res, searchptr->fname);
539 if (searchptr->next != NULL) {
540 res = cstring_appendChar (res, ';');
550 initialize_char_syntax (struct cppOptions *opts)
555 * Set up is_idchar and is_idstart tables. These should be
556 * faster than saying (is_alpha (c) || c == '_'), etc.
557 * Set up these things before calling any routines tthat
561 for (i = 'a'; i <= 'z'; i++) {
562 is_idchar[i - 'a' + 'A'] = TRUE;
563 is_idchar[(int) i] = TRUE;
564 is_idstart[i - 'a' + 'A'] = TRUE;
565 is_idstart[(int) i] = TRUE;
568 for (i = '0'; i <= '9'; i++)
570 is_idchar[(int) i] = TRUE;
573 is_idchar['_'] = TRUE;
574 is_idstart['_'] = TRUE;
575 is_idchar['$'] = opts->dollars_in_ident;
576 is_idstart['$'] = opts->dollars_in_ident;
578 /* horizontal space table */
579 is_hor_space[' '] = TRUE;
580 is_hor_space['\t'] = TRUE;
581 is_hor_space['\v'] = TRUE;
582 is_hor_space['\f'] = TRUE;
583 is_hor_space['\r'] = TRUE;
585 is_space[' '] = TRUE;
586 is_space['\t'] = TRUE;
587 is_space['\v'] = TRUE;
588 is_space['\f'] = TRUE;
589 is_space['\n'] = TRUE;
590 is_space['\r'] = TRUE;
593 bool isIdentifierChar (char c)
595 return is_idchar[(int) c];
598 /* Place into P_PFILE a quoted string representing the string SRC.
599 Caller must reserve enough space in pfile->token_buffer. */
602 quote_string (cppReader *pfile, char *src)
606 cppReader_putCharQ (pfile, '\"');
609 switch ((c = *src++))
613 cppReader_putCharQ (pfile, c);
616 sprintf (cpplib_getPWritten (pfile), "\\%03o",
618 cppReader_adjustWritten (pfile, (size_t) 4);
620 /*@switchbreak@*/ break;
624 cppReader_putCharQ (pfile, '\\');
625 cppReader_putCharQ (pfile, c);
626 /*@switchbreak@*/ break;
629 cppReader_putCharQ (pfile, '\"');
630 cppReader_nullTerminateQ (pfile);
636 /* Re-allocates PFILE->token_buffer so it will hold at least N more chars. */
639 cppReader_growBuffer (cppReader *pfile, size_t n)
641 size_t old_written = cpplib_getWritten (pfile);
642 pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
643 pfile->token_buffer = (char *)
644 drealloc (pfile->token_buffer, pfile->token_buffer_size);
645 cppReader_setWritten (pfile, old_written);
649 * process a given definition string, for initialization
650 * If STR is just an identifier, define it with value 1.
651 * If STR has anything after the identifier, then it should
652 * be identifier=definition.
656 cppReader_define (cppReader *pfile, char *str)
661 DPRINTF (("Cpp reader define: %s", str));
663 if (!is_idstart[(int) *p])
665 DPRINTF (("ERROR 1"));
666 cppReader_error (pfile,
667 message ("Malformed option `-D%s'",
668 cstring_fromChars (str)));
675 DPRINTF (("Here 2"));
677 while (is_idchar[(int) *p])
684 while (*p != ')' && *p != '\0') {
693 message ("Malformed option: -D%s (no closing parenthesis)",
694 cstring_fromChars (str)));
698 DPRINTF (("Here 2"));
702 buf = (char *) dmalloc (size_fromInt (p - str + 4));
703 strcpy ((char *) buf, str);
704 strcat ((char *) buf, " 1");
708 DPRINTF (("ERROR 2"));
709 cppReader_error (pfile,
710 message ("Malformed option: -D%s (expected '=', found '%c')",
711 cstring_fromChars (str),
718 /* Copy the entire option so we can modify it. */
719 DPRINTF (("Copying..."));
720 buf = (char *) dmalloc (2 * strlen (str) + 1);
721 strncpy (buf, str, size_fromInt (p - str));
723 /* Change the = to a space. */
725 /* Scan for any backslash-newline and remove it. */
731 if (*p == '\\' && p[1] == '\n')
737 DPRINTF (("Here we are..."));
741 llassert (buf != NULL);
742 DPRINTF (("Do define: %s / %ld", buf, size_toLong (strlen (buf))));
743 (void) do_define (pfile, NULL, buf, buf + strlen (buf));
747 /* Append a chain of `struct file_name_list's
748 to the end of the main include chain.
749 FIRST is gthe beginning of the chain to append, and LAST is the end. */
752 cppReader_appendIncludeChain (cppReader *pfile,
753 struct file_name_list *first,
754 struct file_name_list *last)
756 struct cppOptions *opts = CPPOPTIONS (pfile);
757 struct file_name_list *dir;
759 if (first == NULL || last == NULL)
764 if (opts->include == 0)
766 opts->include = first;
770 llassert (opts->last_include->next == NULL);
771 opts->last_include->next = first;
774 if (opts->first_bracket_include == 0)
776 opts->first_bracket_include = first;
778 for (dir = first; ; dir = dir->next) {
779 size_t len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
781 if (len > pfile->max_include_len)
783 pfile->max_include_len = len;
793 llassert (last->next == NULL);
794 /* last->next = NULL; */
795 opts->last_include = last;
799 static /*@unused@*/ void
800 cppReader_showIncludeChain (cppReader *pfile)
802 struct file_name_list *dirs = CPPOPTIONS (pfile)->include;
808 fprintf (stderr, "*%s*:", cstring_toCharsSafe (dirs->fname));
812 fprintf (stderr, "\n");
816 fprintf (stderr, "No includes\n");
822 cppReader_getIncludePath ()
824 cppReader *pfile = &g_cppState;
825 struct file_name_list *dirs = CPPOPTIONS (pfile)->include;
826 cstring res = cstring_undefined;
832 res = message ("%q%c%s", res, PATH_SEPARATOR, dirs->fname);
838 res = cstring_makeLiteral ("<no include path>");
845 cppReader_addIncludeChain (cppReader *pfile, /*@only@*/ struct file_name_list *dir)
847 struct cppOptions *opts = CPPOPTIONS (pfile);
854 if (opts->include == 0)
860 llassert (opts->last_include->next == NULL);
861 opts->last_include->next = dir;
864 if (opts->first_bracket_include == 0)
866 size_t len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
867 opts->first_bracket_include = dir;
869 if (len > pfile->max_include_len)
871 pfile->max_include_len = len;
876 opts->last_include = dir;
877 /* cppReader_showIncludeChain (pfile); */
880 /* Given a colon-separated list of file names PATH,
881 add all the names to the search path for include files. */
884 path_include (cppReader *pfile, char *path)
891 /* if we have a posix path list, convert to win32 path list */
892 win32temp = (char *) dmalloc /*@i4@*/
893 (cygwin32_posix_to_win32_path_list_buf_size (path));
894 cygwin32_posix_to_win32_path_list (path, win32temp);
904 struct file_name_list *dirtmp;
906 /* Find the end of this name. */
907 while (*q != '\0' && *q != PATH_SEPARATOR)
914 /* An empty name in the path stands for the current directory. */
915 name = (char *) dmalloc ((size_t) 2);
921 /* Otherwise use the directory that is named. */
922 name = (char *) dmalloc (size_fromInt (q - p + 1));
923 memcpy (name, p, size_fromInt (q - p));
927 dirtmp = (struct file_name_list *) dmalloc (sizeof (*dirtmp));
928 dirtmp->next = 0; /* New one goes on the end */
929 dirtmp->control_macro = 0;
930 dirtmp->c_system_include_path = 0;
931 dirtmp->fname = cstring_fromChars (name);
932 dirtmp->got_name_map = 0;
933 cppReader_addIncludeChain (pfile, dirtmp);
935 /* Advance past this name. */
939 /* Skip the colon. */
945 cppOptions_init (cppOptions *opts)
947 memset ((char *) opts, 0, sizeof *opts);
950 opts->in_fname = NULL;
951 opts->out_fname = NULL;
953 /* Initialize is_idchar to allow $. */
954 opts->dollars_in_ident = TRUE;
956 opts->no_line_commands = 0;
957 opts->no_trigraphs = TRUE;
958 opts->put_out_comments = 1;
959 opts->print_include_names = 0;
960 opts->dump_macros = DUMP_DEFINITIONS; /* DUMP_NONE; */
964 opts->cplusplus_comments = 1;
969 opts->pedantic_errors = 0;
970 opts->warn_comments = 0;
971 opts->warnings_are_errors = 0;
973 /* Added 2003-07-10: */
974 opts->traditional = FALSE;
976 initialize_char_syntax (opts);
980 cppReader_nullUnderflow (/*@unused@*/ cppReader *pfile)
986 cppReader_nullCleanup (/*@unused@*/ cppBuffer *pbuf,
987 /*@unused@*/ cppReader *pfile)
993 cppReader_macroCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
995 hashNode macro = pbuf->hnode;
997 if (macro->type == T_DISABLED)
999 macro->type = T_MACRO;
1002 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
1010 cppReader_fileCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
1012 if (pbuf->buf != NULL)
1019 /* Assuming we have read '/'.
1020 If this is the start of a comment (followed by '*' or '/'),
1021 skip to the end of the comment, and return ' '.
1022 Return EOF if we reached the end of file before the end of the comment.
1023 If not the start of a comment, return '/'. */
1026 skip_comment (cppReader *pfile, /*@null@*/ long *linep)
1030 llassert (pfile->buffer != NULL);
1031 llassert (pfile->buffer->cur != NULL);
1033 while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n')
1040 cppReader_forward (pfile, 2);
1043 if (cppReader_peekC (pfile) == '*')
1045 cppReader_forward (pfile, 1);
1050 c = cppReader_getC (pfile);
1057 while (c == (int) '\\' && cppReader_peekC (pfile) == (int) '\n')
1064 cppReader_forward (pfile, 1), c = cppReader_getC (pfile);
1067 if (prev_c == (int) '*' && c == (int) '/')
1072 if (c == (int) '\n' && (linep != NULL))
1078 else if (cppReader_peekC (pfile) == '/'
1079 && CPPOPTIONS (pfile)->cplusplus_comments)
1082 (void) cppoptgenerror
1083 (FLG_SLASHSLASHCOMMENT,
1084 message ("C++ style // comment"
1088 cppReader_forward (pfile, 1);
1092 c = cppReader_getC (pfile);
1096 /* Allow hash comment to be terminated by EOF. */
1100 while (c == (int) '\\' && cppReader_peekC (pfile) == '\n')
1102 cppReader_forward (pfile, 1);
1103 c = cppReader_getC (pfile);
1111 if (c == (int) '\n')
1113 /* Don't consider final '\n' to be part of comment. */
1114 cppReader_forward (pfile, -1);
1125 /* Skip whitespace \-newline and comments. Does not macro-expand. */
1127 cppSkipHspace (cppReader *pfile)
1135 llassert (pfile->buffer != NULL);
1137 c = cppReader_peekC (pfile);
1141 return 0; /* FIXME */
1144 if (is_hor_space[c])
1146 if ((c == '\f' || c == '\v') && cppReader_isPedantic (pfile))
1147 cppReader_pedwarn (pfile,
1148 message ("%s in preprocessing directive",
1150 ? cstring_makeLiteralTemp ("formfeed")
1151 : cstring_makeLiteralTemp ("vertical tab")));
1154 cppReader_forward (pfile, 1);
1158 cppReader_forward (pfile, 1);
1159 c = skip_comment (pfile, NULL);
1163 cppReader_forward (pfile, -1);
1166 if (c == EOF || c == '/')
1171 else if (c == '\\' && cpp_peekN (pfile, 1) == '\n')
1173 cppReader_forward (pfile, 2);
1175 else if (c == '@' && CPPBUFFER (pfile)->has_escapes
1176 && is_hor_space [cpp_peekN (pfile, 1)])
1178 cppReader_forward (pfile, 2);
1187 /* Read the rest of the current line.
1188 The line is appended to PFILE's output buffer. */
1191 copy_rest_of_line (cppReader *pfile)
1193 struct cppOptions *opts = CPPOPTIONS (pfile);
1200 llassert (pfile->buffer != NULL);
1202 c = cppReader_getC (pfile);
1210 ** Patch from Brian St. Pierre for handling MS-DOS files.
1213 DPRINTF (("Reading directive: %d", (int) c));
1215 if (cppReader_peekC (pfile) == '\n'
1216 || cppReader_peekC (pfile) == '\r')
1218 DPRINTF (("Reading directive..."));
1219 if (cppReader_peekC (pfile) == '\r')
1221 DPRINTF (("Reading directive..."));
1222 cppReader_forward (pfile, 1);
1225 DPRINTF (("Reading directive..."));
1226 cppReader_forward (pfile, 1);
1230 DPRINTF (("Falling..."));
1231 /*@fallthrough@*/ case '\'': case '\"':
1232 goto scan_directive_token;
1235 nextc = cppReader_peekC (pfile);
1238 ** was (opts->cplusplus_comments && nextc == '*')
1243 || (opts->cplusplus_comments && nextc == '/'))
1245 goto scan_directive_token;
1247 /*@switchbreak@*/ break;
1250 if (cppReader_isPedantic (pfile))
1251 cppReader_pedwarn (pfile,
1252 message ("%s in preprocessing directive",
1254 ? cstring_makeLiteralTemp ("formfeed")
1255 : cstring_makeLiteralTemp ("vertical tab")));
1256 /*@switchbreak@*/ break;
1259 cppReader_forward (pfile, -1);
1261 scan_directive_token:
1262 cppReader_forward (pfile, -1);
1263 (void) cpplib_getToken (pfile);
1266 cppReader_putChar (pfile, c);
1269 cppReader_nullTerminate (pfile);
1273 cppReader_skipRestOfLine (cppReader *pfile)
1275 size_t old = cpplib_getWritten (pfile);
1276 copy_rest_of_line (pfile);
1277 cppReader_setWritten (pfile, old);
1280 /* Handle a possible # directive.
1281 '#' has already been read. */
1284 cppReader_handleDirective (cppReader *pfile)
1287 struct directive *kt = NULL;
1289 size_t after_ident = 0;
1291 char *line_end = NULL;
1292 size_t old_written = cpplib_getWritten (pfile);
1293 int nspaces = cppSkipHspace (pfile);
1295 c = cppReader_peekC (pfile);
1297 if (c >= '0' && c <= '9')
1299 /* Handle # followed by a line number. */
1300 if (cppReader_isPedantic (pfile))
1302 cppReader_pedwarnLit
1304 cstring_makeLiteralTemp ("`#' followed by integer"));
1307 (void) do_line (pfile, NULL);
1308 goto done_a_directive;
1312 /* Now find the directive name. */
1314 cppReader_putChar (pfile, '#');
1316 parse_name (pfile, cppReader_getC (pfile));
1318 llassert (pfile->token_buffer != NULL);
1319 ident = pfile->token_buffer + old_written + 1;
1321 ident_length = cpplib_getPWritten (pfile) - ident;
1323 if (ident_length == 0 && cppReader_peekC (pfile) == '\n')
1325 /* A line of just `#' becomes blank. */
1329 for (kt = directive_table; ; kt++)
1331 if (kt->length <= 0)
1333 return 0; /* goto not_a_directive; */
1336 if (kt->length == ident_length
1337 && (cstring_equalPrefix (kt->name, cstring_fromChars (ident))))
1343 if (kt->command_reads_line)
1349 /* Nonzero means do not delete comments within the directive.
1350 #define needs this when -traditional. */
1351 bool comments = 1; /*cppReader_isTraditional (pfile) && kt->traditional_comments; */
1352 int save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
1353 CPPOPTIONS (pfile)->put_out_comments = comments;
1354 after_ident = cpplib_getWritten (pfile);
1355 copy_rest_of_line (pfile);
1356 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
1360 /* For #pragma and #define, we may want to pass through the directive.
1361 Other directives may create output, but we don't want the directive
1362 itself out, so we pop it now. For example #include may write a #line
1363 command (see comment in do_include), and conditionals may emit
1364 #failed ... #endfailed stuff. But note that popping the buffer
1365 means the parameters to kt->func may point after pfile->limit
1366 so these parameters are invalid as soon as something gets appended
1367 to the token_buffer. */
1369 line_end = cpplib_getPWritten (pfile);
1372 if (!kt->pass_thru && kt->type != T_DEFINE)
1374 cppReader_setWritten (pfile, old_written);
1377 llassert (pfile->token_buffer != NULL);
1379 /* was kt->pass_thru || */
1381 if (kt->type == T_DEFINE
1382 && cpp_shouldCheckMacro (pfile, pfile->token_buffer + old_written))
1384 char *p = pfile->token_buffer + old_written;
1387 ** Still need to record value for preprocessing, so
1388 ** #ifdef's, etc. using the value behave correctly.
1391 (void) do_defineAux (pfile, kt,
1392 pfile->token_buffer + after_ident,
1401 SKIP_WHITE_SPACE (p);
1403 llassert (*p == 'd');
1406 llassert (*p == 'e');
1409 llassert (*p == 'f');
1412 llassert (*p == 'i');
1415 llassert (*p == 'n');
1418 llassert (*p == 'e');
1421 ** This is way-bogus. We use the last char to record the number of
1422 ** spaces. Its too hard to get them back into the input stream.
1425 if (nspaces > 9) nspaces = 9;
1427 *p++ = '0' + nspaces;
1429 return 0; /* not_a_directive */
1431 else if (kt->pass_thru)
1433 /* Just leave the entire #define in the output stack. */
1434 return 0; /* not_a_directive */
1437 else if (kt->type == T_DEFINE
1438 && CPPOPTIONS (pfile)->dump_macros == DUMP_NAMES)
1440 char *p = pfile->token_buffer + old_written + 7; /* Skip "#define". */
1441 SKIP_WHITE_SPACE (p);
1443 while (is_idchar[(int) *p])
1449 cppReader_putChar (pfile, '\n');
1451 else if (kt->type == T_DEFINE)
1453 cppReader_setWritten (pfile, old_written);
1464 llassert (kt->func != NULL);
1465 (void) (kt->func) (pfile, kt, pfile->token_buffer + after_ident, line_end);
1470 /* Pass a directive through to the output file.
1471 BUF points to the contents of the directive, as a contiguous string.
1472 LIMIT points to the first character past the end of the directive.
1473 KEYWORD is the keyword-table entry for the directive. */
1476 pass_thru_directive (char *buf, char *limit,
1478 struct directive *keyword)
1480 int keyword_length = keyword->length;
1482 cpplib_reserve (pfile,
1483 size_fromInt (2 + keyword_length + (limit - buf)));
1484 cppReader_putCharQ (pfile, '#');
1485 /*@-observertrans@*/
1486 cppReader_putStrN (pfile, cstring_toCharsSafe (keyword->name),
1487 size_fromInt (keyword_length));
1488 /*:=observertrans@*/
1490 if (limit != buf && buf[0] != ' ')
1492 /* Was a bug, since reserve only used 1 + ... */
1493 cppReader_putCharQ (pfile, ' ');
1496 cppReader_putStrN (pfile, buf, size_fromInt (limit - buf));
1499 /* Read a replacement list for a macro with parameters.
1500 Build the DEFINITION structure.
1501 Reads characters of text starting at BUF until END.
1502 ARGLIST specifies the formal parameters to look for
1503 in the text of the definition; NARGS is the number of args
1504 in that list, or -1 for a macro name that wants no argument list.
1505 MACRONAME is the macro name itself (so we can avoid recursive expansion)
1506 and NAMELEN is its length in characters.
1508 Note that comments, backslash-newlines, and leading white space
1509 have already been deleted from the argument. */
1512 collect_expansion (cppReader *pfile, char *buf, char *limit,
1513 int nargs, /*@null@*/ struct arglist *arglist)
1516 char *p, *lastp, *exp_p;
1517 struct reflist *endpat = NULL;
1518 /* Pointer to first nonspace after last ## seen. */
1520 /* Pointer to first nonspace after last single-# seen. */
1521 char *stringify = 0;
1523 char expected_delimiter = '\0';
1526 /* Scan thru the replacement list, ignoring comments and quoted
1527 strings, picking up on the macro calls. It does a linear search
1528 thru the arg list on every potential symbol. Profiling might say
1529 that something smarter should happen. */
1534 /* Find the beginning of the trailing whitespace. */
1537 while (p < limit && is_space[(int) limit[-1]])
1542 /* Allocate space for the text in the macro definition.
1543 Leading and trailing whitespace chars need 2 bytes each.
1544 Each other input char may or may not need 1 byte,
1545 so this is an upper bound. The extra 5 are for invented
1546 leading and trailing newline-marker and final null. */
1547 maxsize = (sizeof (*defn) + (limit - p) + 5);
1549 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1558 defn = (DEFINITION *) dmalloc (maxsize);
1559 defn->noExpand = FALSE;
1561 defn->pattern = NULL;
1562 defn->nargs = nargs;
1563 defn->predefined = NULL;
1565 exp_p = defn->expansion = (char *) defn + sizeof (*defn);
1568 defn->rest_args = NULL;
1569 defn->args.argnames = NULL;
1575 /* Add one initial space escape-marker to prevent accidental
1576 token-pasting (often removed by cpplib_macroExpand). */
1580 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1581 cppReader_errorLit (pfile,
1582 cstring_makeLiteralTemp ("`##' at start of macro definition"));
1586 /* Process the main body of the definition. */
1588 int skipped_arg = 0;
1589 register char c = *p++;
1593 if (!cppReader_isTraditional (pfile)) {
1597 if (expected_delimiter != '\0')
1599 if (c == expected_delimiter)
1600 expected_delimiter = '\0';
1604 expected_delimiter = c;
1606 /*@switchbreak@*/ break;
1609 if (p < limit && (expected_delimiter != '\0'))
1611 /* In a string, backslash goes through
1612 and makes next char ordinary. */
1615 /*@switchbreak@*/ break;
1618 /* An '@' in a string or character constant stands for itself,
1619 and does not need to be escaped. */
1620 if (expected_delimiter == '\0')
1625 /*@switchbreak@*/ break;
1628 /* # is ordinary inside a string. */
1629 if (expected_delimiter != '\0')
1631 /*@switchbreak@*/ break;
1634 if (p < limit && *p == '#') {
1635 /* ##: concatenate preceding and following tokens. */
1636 /* Take out the first #, discard preceding whitespace. */
1640 while (exp_p > lastp && is_hor_space[(int) exp_p[-1]])
1646 /* Skip the second #. */
1648 /* Discard following whitespace. */
1649 SKIP_WHITE_SPACE (p);
1653 cppReader_errorLit (pfile,
1654 cstring_makeLiteralTemp ("`##' at end of macro definition"));
1656 } else if (nargs >= 0) {
1657 /* Single #: stringify following argument ref.
1658 Don't leave the # in the expansion. */
1660 SKIP_WHITE_SPACE (p);
1661 if (p == limit || ! is_idstart[(int) *p]
1662 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '\"')))
1663 cppReader_errorLit (pfile,
1664 cstring_makeLiteralTemp ("`#' operator is not followed by a macro argument name"));
1671 /*@switchbreak@*/ break;
1674 /* In -traditional mode, recognize arguments inside strings and
1675 and character constants, and ignore special properties of #.
1676 Arguments inside strings are considered "stringified", but no
1677 extra quote marks are supplied. */
1681 if (expected_delimiter != '\0') {
1682 if (c == expected_delimiter)
1683 expected_delimiter = '\0';
1685 expected_delimiter = c;
1686 /*@switchbreak@*/ break;
1689 /* Backslash quotes delimiters and itself, but not macro args. */
1690 if (expected_delimiter != '\0' && p < limit
1691 && (*p == expected_delimiter || *p == '\\')) {
1695 /*@switchbreak@*/ break;
1698 if (expected_delimiter != '\0') /* No comments inside strings. */
1699 /*@switchbreak@*/ break;
1701 /* If we find a comment that wasn't removed by cppReader_handleDirective,
1702 this must be -traditional. So replace the comment with
1706 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
1711 /*@switchbreak@*/ break;
1715 /* Handle the start of a symbol. */
1716 if (is_idchar[(int) c] && nargs > 0) {
1717 char *id_beg = p - 1;
1721 while (p != limit && is_idchar[(int) *p])
1726 id_len = size_fromInt (p - id_beg);
1728 if (is_idstart[(int) c]
1729 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '\"'))) {
1730 register struct arglist *arg;
1732 for (arg = arglist; arg != NULL; arg = arg->next) {
1733 struct reflist *tpat;
1735 if (arg->name[0] == c
1736 && arg->length == id_len
1737 && strncmp (arg->name, id_beg, id_len) == 0) {
1740 if (expected_delimiter && CPPOPTIONS (pfile)->warn_stringify) {
1741 if (cppReader_isTraditional (pfile)) {
1742 cppReader_warning (pfile,
1743 message ("macro argument `%x' is stringified.",
1744 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1746 cppReader_warning (pfile,
1747 message ("macro arg `%x' would be stringified with -traditional.",
1748 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1751 /* If ANSI, don't actually substitute inside a string. */
1752 if (!cppReader_isTraditional (pfile) && expected_delimiter)
1753 /*@innerbreak@*/ break;
1754 /* make a pat node for this arg and append it to the end of
1756 tpat = (struct reflist *) dmalloc (sizeof (*tpat));
1758 tpat->raw_before = (concat == id_beg);
1759 tpat->raw_after = 0;
1760 tpat->rest_args = arg->rest_args;
1761 tpat->stringify = (cppReader_isTraditional (pfile)
1762 ? expected_delimiter != '\0'
1763 : stringify == id_beg);
1767 defn->pattern = tpat;
1771 endpat->next = tpat;
1773 } /*@=branchstate@*/ /* evs 2000 was =branchstate */
1777 tpat->argno = arg->argno;
1778 tpat->nchars = exp_p - lastp;
1782 SKIP_WHITE_SPACE (p1);
1784 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
1786 tpat->raw_after = 1;
1789 lastp = exp_p; /* place to start copying from next time */
1792 /*@innerbreak@*/ break;
1797 /* If this was not a macro arg, copy it into the expansion. */
1798 if (skipped_arg == 0) {
1799 register char *lim1 = p;
1807 if (stringify == id_beg)
1808 cppReader_errorLit (pfile,
1809 cstring_makeLiteralTemp ("`#' operator should be followed by a macro argument name"));
1814 if (!cppReader_isTraditional (pfile) && expected_delimiter == '\0')
1816 /* If ANSI, put in a "@ " marker to prevent token pasting.
1817 But not if "inside a string" (which in ANSI mode
1818 happens only for -D option). */
1825 defn->length = size_fromInt (exp_p - defn->expansion);
1827 /* Crash now if we overrun the allocated size. */
1828 if (defn->length + 1 > maxsize)
1830 llfatalbug (cstring_makeLiteral ("Maximum definition size exceeded."));
1833 /*@i1@*/ return defn; /* Spurious warning here */
1838 ** Gasp...cut-and-pasted from above to deal with pfile (should replace throughout with this...)
1842 collect_expansionLoc (fileloc loc, char *buf, char *limit,
1843 int nargs, /*@null@*/ struct arglist *arglist)
1846 char *p, *lastp, *exp_p;
1847 struct reflist *endpat = NULL;
1848 /* Pointer to first nonspace after last ## seen. */
1850 /* Pointer to first nonspace after last single-# seen. */
1851 char *stringify = 0;
1853 char expected_delimiter = '\0';
1856 /* Scan thru the replacement list, ignoring comments and quoted
1857 strings, picking up on the macro calls. It does a linear search
1858 thru the arg list on every potential symbol. Profiling might say
1859 that something smarter should happen. */
1863 llfatalbug (message ("%q: Limit is less than initial buffer pointer",
1864 fileloc_unparse (loc)));
1867 /* Find the beginning of the trailing whitespace. */
1870 while (p < limit && is_space[(int) limit[-1]])
1875 /* Allocate space for the text in the macro definition.
1876 Leading and trailing whitespace chars need 2 bytes each.
1877 Each other input char may or may not need 1 byte,
1878 so this is an upper bound. The extra 5 are for invented
1879 leading and trailing newline-marker and final null. */
1880 maxsize = (sizeof (*defn) + (limit - p) + 5);
1882 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1891 defn = (DEFINITION *) dmalloc (maxsize);
1892 defn->noExpand = FALSE;
1894 defn->pattern = NULL;
1895 defn->nargs = nargs;
1896 defn->predefined = NULL;
1897 exp_p = defn->expansion = (char *) defn + sizeof (*defn);
1900 defn->rest_args = NULL;
1901 defn->args.argnames = NULL;
1907 /* Add one initial space escape-marker to prevent accidental
1908 token-pasting (often removed by cpplib_macroExpand). */
1912 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1913 voptgenerror (FLG_PREPROC,
1914 cstring_makeLiteral ("Paste marker ## at start of macro definition"),
1919 /* Process the main body of the definition. */
1921 int skipped_arg = 0;
1922 register char c = *p++;
1926 if (TRUE) { /* !cppReader_isTraditional (pfile)) { */
1930 if (expected_delimiter != '\0')
1932 if (c == expected_delimiter)
1933 expected_delimiter = '\0';
1937 expected_delimiter = c;
1939 /*@switchbreak@*/ break;
1942 if (p < limit && (expected_delimiter != '\0'))
1944 /* In a string, backslash goes through
1945 and makes next char ordinary. */
1948 /*@switchbreak@*/ break;
1951 /* An '@' in a string or character constant stands for itself,
1952 and does not need to be escaped. */
1953 if (expected_delimiter == '\0')
1958 /*@switchbreak@*/ break;
1961 /* # is ordinary inside a string. */
1962 if (expected_delimiter != '\0')
1964 /*@switchbreak@*/ break;
1967 if (p < limit && *p == '#') {
1968 /* ##: concatenate preceding and following tokens. */
1969 /* Take out the first #, discard preceding whitespace. */
1973 while (exp_p > lastp && is_hor_space[(int) exp_p[-1]])
1979 /* Skip the second #. */
1981 /* Discard following whitespace. */
1982 SKIP_WHITE_SPACE (p);
1986 voptgenerror (FLG_PREPROC,
1987 cstring_makeLiteral ("`##' at end of macro definition"),
1990 } else if (nargs >= 0) {
1991 /* Single #: stringify following argument ref.
1992 Don't leave the # in the expansion. */
1994 SKIP_WHITE_SPACE (p);
1995 if (p == limit || ! is_idstart[(int) *p]
1996 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '\"')))
2000 cstring_makeLiteral ("`#' operator is not followed by a macro argument name"),
2009 /*@switchbreak@*/ break;
2012 /* In -traditional mode, recognize arguments inside strings and
2013 and character constants, and ignore special properties of #.
2014 Arguments inside strings are considered "stringified", but no
2015 extra quote marks are supplied. */
2019 if (expected_delimiter != '\0') {
2020 if (c == expected_delimiter)
2021 expected_delimiter = '\0';
2023 expected_delimiter = c;
2024 /*@switchbreak@*/ break;
2027 /* Backslash quotes delimiters and itself, but not macro args. */
2028 if (expected_delimiter != '\0' && p < limit
2029 && (*p == expected_delimiter || *p == '\\')) {
2033 /*@switchbreak@*/ break;
2036 if (expected_delimiter != '\0') /* No comments inside strings. */
2037 /*@switchbreak@*/ break;
2039 /* If we find a comment that wasn't removed by cppReader_handleDirective,
2040 this must be -traditional. So replace the comment with
2044 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
2049 /*@switchbreak@*/ break;
2053 /* Handle the start of a symbol. */
2054 if (is_idchar[(int) c] && nargs > 0) {
2055 char *id_beg = p - 1;
2059 while (p != limit && is_idchar[(int) *p])
2064 id_len = size_fromInt (p - id_beg);
2066 if (is_idstart[(int) c]
2067 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '\"'))) {
2068 register struct arglist *arg;
2070 for (arg = arglist; arg != NULL; arg = arg->next) {
2071 struct reflist *tpat;
2073 if (arg->name[0] == c
2074 && arg->length == id_len
2075 && strncmp (arg->name, id_beg, id_len) == 0) {
2078 if (expected_delimiter) { /* && CPPOPTIONS (pfile)->warn_stringify) { */
2079 if (FALSE) { /* cppReader_isTraditional (pfile)) { */
2080 voptgenerror (FLG_PREPROC,
2081 message ("macro argument `%x' is stringified.",
2082 cstring_prefix (cstring_fromChars (arg->name), id_len)),
2086 voptgenerror (FLG_PREPROC,
2087 message ("Macro arg `%x' would be stringified with -traditional.",
2088 cstring_prefix (cstring_fromChars (arg->name), id_len)),
2093 /* If ANSI, don't actually substitute inside a string. */
2094 if (TRUE /* !cppReader_isTraditional (pfile) */ && expected_delimiter)
2095 /*@innerbreak@*/ break;
2096 /* make a pat node for this arg and append it to the end of
2098 tpat = (struct reflist *) dmalloc (sizeof (*tpat));
2100 tpat->raw_before = (concat == id_beg);
2101 tpat->raw_after = 0;
2102 tpat->rest_args = arg->rest_args;
2103 tpat->stringify = (FALSE /* cppReader_isTraditional (pfile) */
2104 ? expected_delimiter != '\0'
2105 : stringify == id_beg);
2109 defn->pattern = tpat;
2113 endpat->next = tpat;
2115 } /*@=branchstate@*/ /* evs 2000 was =branchstate */
2119 tpat->argno = arg->argno;
2120 tpat->nchars = exp_p - lastp;
2124 SKIP_WHITE_SPACE (p1);
2126 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
2128 tpat->raw_after = 1;
2131 lastp = exp_p; /* place to start copying from next time */
2134 /*@innerbreak@*/ break;
2139 /* If this was not a macro arg, copy it into the expansion. */
2140 if (skipped_arg == 0) {
2141 register char *lim1 = p;
2149 if (stringify == id_beg)
2153 cstring_makeLiteral ("# operator should be followed by a macro argument name"),
2160 if (/*!cppReader_isTraditional (pfile) && */ expected_delimiter == '\0')
2162 /* If ANSI, put in a "@ " marker to prevent token pasting.
2163 But not if "inside a string" (which in ANSI mode
2164 happens only for -D option). */
2171 defn->length = size_fromInt (exp_p - defn->expansion);
2173 /* Crash now if we overrun the allocated size. */
2174 if (defn->length + 1 > maxsize)
2176 llfatalbug (cstring_makeLiteral ("Maximum definition size exceeded."));
2179 /*@i1@*/ return defn; /* Spurious warning here */
2183 * special extension string that can be added to the last macro argument to
2184 * allow it to absorb the "rest" of the arguments when expanded. Ex:
2185 * #define wow(a, b...) process (b, a, b)
2186 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
2187 * { wow (one, two); } -> { process (two, one, two); }
2188 * if this "rest_arg" is used with the concat token '##' and if it is not
2189 * supplied then the token attached to with ## will not be outputted. Ex:
2190 * #define wow (a, b...) process (b ## , a, ## b)
2191 * { wow (1, 2); } -> { process (2, 1, 2); }
2192 * { wow (one); } -> { process (one); {
2195 /*@-readonlytrans@*/
2196 static char rest_extension[] = "...";
2197 /*:=readonlytrans@*/
2200 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
2202 /* Create a DEFINITION node from a #define directive. Arguments are
2203 as for do_define. */
2206 static /*@null@*/ macroDef
2207 create_definition (/*@exposed@*/ char *buf, char *limit,
2208 cppReader *pfile, bool predefinition,
2211 char *bp; /* temp ptr into input buffer */
2212 char *symname; /* remember where symbol name starts */
2213 size_t sym_length; /* and how long it is */
2214 int rest_args = 0; /* really int! */
2217 cstring file = (CPPBUFFER (pfile) != NULL)
2218 ? CPPBUFFER (pfile)->nominal_fname : cstring_makeLiteralTemp ("");
2220 int arglengths = 0; /* Accumulate lengths of arg names
2221 plus number of args. */
2225 DPRINTF (("Create definition: %s", buf));
2228 cppBuffer_getLineAndColumn (CPPBUFFER (pfile), &line, &col);
2232 while (is_hor_space[(int) *bp])
2237 symname = bp; /* remember where it starts */
2239 sym_length = cppReader_checkMacroName (pfile, bp, cstring_makeLiteralTemp ("macro"));
2243 /* Lossage will occur if identifiers or control keywords are broken
2244 across lines using backslash. This is not the right place to take
2248 struct arglist *arg_ptrs = NULL;
2251 bp++; /* skip '(' */
2252 SKIP_WHITE_SPACE (bp);
2254 /* Loop over macro argument names. */
2257 struct arglist *temp = (struct arglist *) dmalloc (sizeof (*temp));
2259 temp->next = arg_ptrs;
2260 temp->argno = argno++;
2261 temp->rest_args = 0;
2267 cppReader_pedwarn (pfile,
2268 message ("another parameter follows `%s'",
2269 cstring_fromChars (rest_extension)));
2272 if (!is_idstart[(int) *bp])
2274 cppReader_pedwarnLit (pfile,
2275 cstring_makeLiteralTemp ("Invalid character in macro parameter name"));
2278 /* Find the end of the arg name. */
2279 while (is_idchar[(int) *bp])
2282 /* do we have a "special" rest-args extension here? */
2283 if (limit - bp > size_toInt (REST_EXTENSION_LENGTH)
2284 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
2287 temp->rest_args = 1;
2288 /*@innerbreak@*/ break;
2292 temp->length = size_fromInt (bp - temp->name);
2296 bp += REST_EXTENSION_LENGTH;
2299 arglengths += temp->length + 2;
2300 SKIP_WHITE_SPACE (bp);
2302 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
2303 cppReader_errorLit (pfile,
2304 cstring_makeLiteralTemp ("Parameter list for #define is not parseable"));
2310 SKIP_WHITE_SPACE (bp);
2313 cppReader_errorLit (pfile,
2314 cstring_makeLiteralTemp ("unterminated parameter list in `#define'"));
2318 struct arglist *otemp;
2320 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
2322 if (temp->length == otemp->length &&
2323 strncmp (temp->name, otemp->name, temp->length) == 0) {
2324 cstring name = cstring_copyLength (temp->name, temp->length);
2325 cppReader_error (pfile,
2326 message ("duplicate argument name `%x' in `#define'", name));
2333 ++bp; /* skip paren */
2334 SKIP_WHITE_SPACE (bp);
2335 /* now everything from bp before limit is the definition. */
2336 defn = collect_expansion (pfile, bp, limit, argno, arg_ptrs);
2337 defn->rest_args = rest_args;
2339 /* Now set defn->args.argnames to the result of concatenating
2340 the argument names in reverse order
2341 with comma-space between them. */
2342 defn->args.argnames = (char *) dmalloc (size_fromInt (arglengths + 1));
2345 struct arglist *temp;
2347 for (temp = arg_ptrs; temp != NULL; temp = temp->next)
2349 memcpy (&defn->args.argnames[i], temp->name, temp->length);
2351 if (temp->next != 0)
2353 defn->args.argnames[i++] = ',';
2354 defn->args.argnames[i++] = ' ';
2358 defn->args.argnames[i] = '\0';
2363 /* Simple expansion or empty definition. */
2367 if (is_hor_space[(int) *bp]) {
2369 SKIP_WHITE_SPACE (bp);
2372 case '!': case '\"': case '#': case '%': case '&': case '\'':
2373 case ')': case '*': case '+': case ',': case '-': case '.':
2374 case '/': case ':': case ';': case '<': case '=': case '>':
2375 case '?': case '[': case '\\': case ']': case '^': case '{':
2376 case '|': case '}': case '~':
2377 cppReader_warning (pfile,
2378 message ("Missing white space after #define %x",
2379 cstring_prefix (cstring_fromChars (symname),
2384 cppReader_pedwarn (pfile,
2385 message ("Missing white space after #define %x",
2386 cstring_prefix (cstring_fromChars (symname),
2392 /* now everything from bp before limit is the definition. */
2393 defn = collect_expansion (pfile, bp, limit, -1, NULL);
2394 defn->args.argnames = mstring_createEmpty ();
2397 defn->noExpand = noExpand;
2398 DPRINTF (("No expand: %d", noExpand));
2402 /* not: llassert (cstring_isUndefined (defn->file)); */
2405 /* OP is null if this is a predefinition */
2406 defn->predefined = predefinition;
2408 mdef.symnam = symname;
2409 mdef.symlen = sym_length;
2420 cpplib_createDefinition (cstring def,
2425 char *buf = cstring_toCharsSafe (def);
2426 char *limit = buf + cstring_length (def);
2427 char *bp; /* temp ptr into input buffer */
2428 char *symname; /* remember where symbol name starts */
2429 size_t sym_length; /* and how long it is */
2430 int rest_args = 0; /* really int! */
2431 int line = fileloc_lineno (loc);
2432 cstring file = fileloc_filename (loc);
2434 int arglengths = 0; /* Accumulate lengths of arg names
2435 plus number of args. */
2440 DPRINTF (("Creating definition: %s", buf));
2442 while (is_hor_space[(int) *bp])
2447 symname = bp; /* remember where it starts */
2449 sym_length = cppReader_checkMacroNameLoc (loc, symname, cstring_makeLiteralTemp ("macro"));
2451 DPRINTF (("length: %d", sym_length));
2455 DPRINTF (("Here: %s", bp));
2457 /* Lossage will occur if identifiers or control keywords are broken
2458 across lines using backslash. This is not the right place to take
2462 struct arglist *arg_ptrs = NULL;
2465 bp++; /* skip '(' */
2466 SKIP_WHITE_SPACE (bp);
2468 /* Loop over macro argument names. */
2471 struct arglist *temp = (struct arglist *) dmalloc (sizeof (*temp));
2473 temp->next = arg_ptrs;
2474 temp->argno = argno++;
2475 temp->rest_args = 0;
2481 voptgenerror (FLG_PREPROC,
2482 message ("Another parameter follows %s",
2483 cstring_fromChars (rest_extension)),
2487 if (!is_idstart[(int) *bp])
2489 voptgenerror (FLG_PREPROC,
2490 message ("Invalid character in macro parameter name: %c", *bp),
2494 /* Find the end of the arg name. */
2495 while (is_idchar[(int) *bp])
2498 /* do we have a "special" rest-args extension here? */
2499 if (limit - bp > size_toInt (REST_EXTENSION_LENGTH)
2500 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
2503 temp->rest_args = 1;
2504 /*@innerbreak@*/ break;
2508 temp->length = size_fromInt (bp - temp->name);
2512 bp += REST_EXTENSION_LENGTH;
2515 arglengths += temp->length + 2;
2516 SKIP_WHITE_SPACE (bp);
2518 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
2519 voptgenerror (FLG_PREPROC,
2520 cstring_makeLiteral ("Parameter list for #define is not parseable"),
2527 SKIP_WHITE_SPACE (bp);
2530 voptgenerror (FLG_PREPROC,
2531 cstring_makeLiteral ("Unterminated parameter list in #define'"),
2536 struct arglist *otemp;
2538 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
2540 if (temp->length == otemp->length &&
2541 strncmp (temp->name, otemp->name, temp->length) == 0) {
2542 cstring name = cstring_copyLength (temp->name, temp->length);
2544 voptgenerror (FLG_PREPROC,
2545 message ("Duplicate argument name in #define: %s", name),
2553 ++bp; /* skip paren */
2554 SKIP_WHITE_SPACE (bp);
2555 /* now everything from bp before limit is the definition. */
2556 defn = collect_expansionLoc (loc, bp, limit, argno, arg_ptrs);
2557 defn->rest_args = rest_args;
2559 /* Now set defn->args.argnames to the result of concatenating
2560 the argument names in reverse order
2561 with comma-space between them. */
2562 defn->args.argnames = (char *) dmalloc (size_fromInt (arglengths + 1));
2565 struct arglist *temp;
2567 for (temp = arg_ptrs; temp != NULL; temp = temp->next) {
2568 memcpy (&defn->args.argnames[i], temp->name, temp->length);
2570 if (temp->next != 0) {
2571 defn->args.argnames[i++] = ',';
2572 defn->args.argnames[i++] = ' ';
2576 defn->args.argnames[i] = '\0';
2581 /* Simple expansion or empty definition. */
2585 if (is_hor_space[(int) *bp]) {
2587 SKIP_WHITE_SPACE (bp);
2590 case '!': case '\"': case '#': case '%': case '&': case '\'':
2591 case ')': case '*': case '+': case ',': case '-': case '.':
2592 case '/': case ':': case ';': case '<': case '=': case '>':
2593 case '?': case '[': case '\\': case ']': case '^': case '{':
2594 case '|': case '}': case '~':
2595 voptgenerror (FLG_PREPROC,
2596 message ("Missing white space after #define %x",
2597 cstring_prefix (cstring_fromChars (symname),
2603 voptgenerror (FLG_PREPROC,
2604 message ("Missing white space after #define %x",
2605 cstring_prefix (cstring_fromChars (symname),
2613 /* now everything from bp before limit is the definition. */
2614 llassert (limit > bp);
2615 defn = collect_expansionLoc (loc, bp, limit, -1, NULL);
2616 defn->args.argnames = mstring_createEmpty ();
2619 defn->noExpand = noExpand;
2620 DPRINTF (("No expand: %d", noExpand));
2624 /* not: llassert (cstring_isUndefined (defn->file)); */
2627 /* OP is null if this is a predefinition */
2628 defn->predefined = predefinition;
2631 mdef.symnam = symname;
2632 mdef.symlen = sym_length;
2642 /* Check a purported macro name SYMNAME, and yield its length.
2643 USAGE is the kind of name this is intended for. */
2645 size_t cppReader_checkMacroName (cppReader *pfile, char *symname, cstring usage)
2650 for (p = symname; is_idchar[(int) *p]; p++)
2655 sym_length = size_fromInt (p - symname);
2658 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '\"')))
2660 cppReader_error (pfile, message ("invalid %s name", usage));
2662 else if (!is_idstart[(int) *symname])
2664 char *msg = (char *) dmalloc (sym_length + 1);
2665 memcpy (msg, symname, sym_length);
2666 msg[sym_length] = '\0';
2667 cppReader_error (pfile, message ("invalid %s name `%s'", usage,
2668 cstring_fromChars (msg)));
2673 if ((strncmp (symname, "defined", 7) == 0) && sym_length == 7)
2675 cppReader_error (pfile, message ("invalid %s name `defined'", usage));
2684 ** Gasp...cut-and-pasted from above to deal with pfile (should replace throughout with this...)
2687 size_t cppReader_checkMacroNameLoc (fileloc loc, char *symname, cstring usage)
2692 for (p = symname; is_idchar[(int) *p]; p++)
2697 sym_length = size_fromInt (p - symname);
2700 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '\"')))
2702 voptgenerror (FLG_PREPROC, message ("Invalid %s name: %s", usage,
2703 cstring_fromChars (symname)), loc);
2705 else if (!is_idstart[(int) *symname])
2707 char *msg = (char *) dmalloc (sym_length + 1);
2708 memcpy (msg, symname, sym_length);
2709 msg[sym_length] = '\0';
2710 voptgenerror (FLG_PREPROC, message ("Invalid %s name: %s", usage,
2711 cstring_fromChars (msg)),
2717 if ((strncmp (symname, "defined", 7) == 0) && sym_length == 7)
2719 voptgenerror (FLG_PREPROC, message ("Invalid %s name: defined", usage), loc);
2726 /* Return zero if two DEFINITIONs are isomorphic. */
2729 compare_defs (DEFINITION *d1, DEFINITION *d2)
2731 register struct reflist *a1, *a2;
2732 register char *p1 = d1->expansion;
2733 register char *p2 = d2->expansion;
2736 if (d1->nargs != d2->nargs)
2741 llassert (d1->args.argnames != NULL);
2742 llassert (d2->args.argnames != NULL);
2744 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames) != 0)
2749 for (a1 = d1->pattern, a2 = d2->pattern;
2750 (a1 != NULL) && (a2 != NULL);
2751 a1 = a1->next, a2 = a2->next) {
2752 if (!((a1->nchars == a2->nchars
2753 && (strncmp (p1, p2, size_fromInt (a1->nchars)) == 0))
2754 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
2755 || a1->argno != a2->argno
2756 || a1->stringify != a2->stringify
2757 || a1->raw_before != a2->raw_before
2758 || a1->raw_after != a2->raw_after)
2767 if (comp_def_part (first, p1, size_toInt (d1->length - (p1 - d1->expansion)),
2768 p2, size_toInt (d2->length - (p2 - d2->expansion)), 1))
2775 ** Return TRUE if two parts of two macro definitions are effectively different.
2776 ** One of the parts starts at BEG1 and has LEN1 chars;
2777 ** the other has LEN2 chars at BEG2.
2778 ** Any sequence of whitespace matches any other sequence of whitespace.
2779 ** FIRST means these parts are the first of a macro definition;
2780 ** so ignore leading whitespace entirely.
2781 ** LAST means these parts are the last of a macro definition;
2782 ** so ignore trailing whitespace entirely.
2786 comp_def_part (bool first, char *beg1, int len1, char *beg2, int len2, bool last)
2788 char *end1 = beg1 + len1;
2789 char *end2 = beg2 + len2;
2792 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2793 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2796 while (beg1 != end1 && is_space[(int) end1[-1]]) { end1--; }
2797 while (beg2 != end2 && is_space[(int) end2[-1]]) { end2--; }
2799 while (beg1 != end1 && beg2 != end2) {
2800 if (is_space[(int) *beg1] && is_space[(int) *beg2]) {
2801 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2802 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2803 } else if (*beg1 == *beg2) {
2807 return (beg1 != end1) || (beg2 != end2);
2811 ** Process a #define command.
2812 ** BUF points to the contents of the #define command, as a contiguous string.
2813 ** LIMIT points to the first character past the end of the definition.
2814 ** KEYWORD is the keyword-table entry for #define,
2815 ** or NULL for a "predefined" macro.
2819 do_defineAux (cppReader *pfile, struct directive *keyword,
2820 /*@exposed@*/ char *buf, char *limit, bool noExpand)
2826 mdef = create_definition (buf, limit, pfile, keyword == NULL, noExpand);
2831 hashcode = cpphash_hashCode (mdef.symnam, mdef.symlen, CPP_HASHSIZE);
2833 if ((hp = cpphash_lookup (mdef.symnam, size_toInt (mdef.symlen), hashcode)) != NULL)
2837 /* Redefining a precompiled key is ok. */
2838 if (hp->type == T_PCSTRING)
2840 /* Redefining a macro is ok if the definitions are the same. */
2841 else if (hp->type == T_MACRO)
2842 ok = !compare_defs (mdef.defn, hp->value.defn);
2843 /* Redefining a constant is ok with -D. */
2844 else if (hp->type == T_CONST)
2845 ok = !CPPOPTIONS (pfile)->done_initializing;
2847 ok = FALSE; /* Redefining anything else is bad. */
2850 /* Print the warning if it's not ok. */
2854 ** If we are passing through #define and #undef directives, do
2855 ** that for this re-definition now.
2858 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2860 /* llassert (keyword != NULL); */
2861 pass_thru_directive (buf, limit, pfile, keyword);
2864 cpp_setLocation (pfile);
2866 if (hp->type == T_MACRO)
2868 if (hp->value.defn->noExpand)
2870 ; /* error will be reported checking macros */
2876 message ("Macro %q already defined",
2877 cstring_copyLength (mdef.symnam, mdef.symlen)),
2878 message ("%q: Previous definition of %q",
2879 fileloc_unparseRaw (hp->value.defn->file,
2880 (int) hp->value.defn->line),
2881 cstring_copyLength (mdef.symnam, mdef.symlen)));
2886 genppllerror (FLG_MACROREDEF,
2887 message ("Macro %q already defined",
2888 cstring_copyLength (mdef.symnam,
2893 /* Replace the old definition. */
2895 hp->value.defn = mdef.defn;
2900 ** If we are passing through #define and #undef directives, do
2901 ** that for this new definition now.
2906 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2908 pass_thru_directive (buf, limit, pfile, keyword);
2911 DPRINTF (("Define macro: %s / %d",
2912 mdef.symnam, mdef.defn->noExpand));
2914 hn = cpphash_installMacro (mdef.symnam, mdef.symlen, mdef.defn, hashcode);
2916 } /*@=branchstate@*/
2925 do_define (cppReader *pfile, struct directive *keyword,
2926 /*@exposed@*/ char *buf, char *limit)
2928 DPRINTF (("Regular do define"));
2929 return do_defineAux (pfile, keyword, buf, limit, FALSE);
2933 ** This structure represents one parsed argument in a macro call.
2934 ** `raw' points to the argument text as written (`raw_length' is its length).
2935 ** `expanded' points to the argument's macro-expansion
2936 ** (its length is `expand_length').
2937 ** `stringified_length' is the length the argument would have
2939 ** `use_count' is the number of times this macro arg is substituted
2940 ** into the macro. If the actual use count exceeds 10,
2941 ** the value stored is 10.
2944 /* raw and expanded are relative to ARG_BASE */
2946 #define ARG_BASE ((pfile)->token_buffer)
2949 /* Strings relative to pfile->token_buffer */
2955 int stringified_length;
2961 ** Allocate a new cppBuffer for PFILE, and push it on the input buffer stack.
2962 ** If BUFFER != NULL, then use the LENGTH characters in BUFFER
2963 ** as the new input buffer.
2964 ** Return the new buffer, or NULL on failure.
2967 /*@null@*/ /*@exposed@*/ cppBuffer *
2968 cppReader_pushBuffer (cppReader *pfile, char *buffer, size_t length)
2970 cppBuffer *buf = cppReader_getBufferSafe (pfile);
2972 if (buf == pfile->buffer_stack)
2974 cppReader_fatalError
2976 message ("%s: macro or `#include' recursion too deep",
2977 (buf->fname != NULL)
2979 : cstring_makeLiteral ("<no name>")));
2980 sfreeEventually (buffer);
2984 llassert (buf != NULL);
2987 memset ((char *) buf, 0, sizeof (*buf));
2988 DPRINTF (("Pushing buffer: %s", cstring_copyLength (buffer, length)));
2989 CPPBUFFER (pfile) = buf;
2991 buf->if_stack = pfile->if_stack;
2992 buf->cleanup = cppReader_nullCleanup;
2993 buf->underflow = cppReader_nullUnderflow;
2995 buf->cur = buf->buf;
2999 buf->alimit = buf->rlimit = buffer + length;
3003 buf->alimit = buf->rlimit = NULL;
3010 cppReader_popBuffer (cppReader *pfile)
3012 cppBuffer *buf = CPPBUFFER (pfile);
3014 llassert (buf != NULL);
3016 (void) (*buf->cleanup) (buf, pfile);
3017 return ++CPPBUFFER (pfile);
3021 ** Scan until CPPBUFFER (PFILE) is exhausted into PFILE->token_buffer.
3022 ** Pop the buffer when done.
3026 cppReader_scanBuffer (cppReader *pfile)
3028 cppBuffer *buffer = CPPBUFFER (pfile);
3031 enum cpp_token token;
3033 token = cpplib_getToken (pfile);
3035 if (token == CPP_EOF) /* Should not happen ... */
3040 if (token == CPP_POP && CPPBUFFER (pfile) == buffer)
3042 (void) cppReader_popBuffer (pfile);
3049 * Rescan a string (which may have escape marks) into pfile's buffer.
3050 * Place the result in pfile->token_buffer.
3052 * The input is copied before it is scanned, so it is safe to pass
3053 * it something from the token_buffer that will get overwritten
3054 * (because it follows cpplib_getWritten). This is used by do_include.
3058 cpp_expand_to_buffer (cppReader *pfile, char *buf, size_t length)
3060 register cppBuffer *ip;
3061 char *limit = buf + length;
3062 char *buf1, *p1, *p2;
3064 DPRINTF (("Expand to buffer: %s", cstring_copyLength (buf, length)));
3066 /* evans - 2001-08-26
3067 ** length is unsigned - this doesn't make sense
3073 /* Set up the input on the input stack. */
3075 buf1 = (char *) dmalloc (length + 1);
3085 buf1[length] = '\0';
3087 ip = cppReader_pushBuffer (pfile, buf1, length);
3092 ip->has_escapes = TRUE;
3094 /* Scan the input, create the output. */
3095 cppReader_scanBuffer (pfile);
3097 cppReader_nullTerminate (pfile);
3101 adjust_position (char *buf, char *limit, int *linep, int *colp)
3107 (*linep)++, (*colp) = 1;
3113 /* Move line_base forward, updating lineno and colno. */
3116 update_position (cppBuffer *pbuf)
3119 char *new_pos = pbuf->cur;
3120 register struct parse_marker *mark;
3122 llassert (pbuf->buf != NULL);
3123 old_pos = pbuf->buf + pbuf->line_base;
3125 for (mark = pbuf->marks; mark != NULL; mark = mark->next)
3127 if (pbuf->buf + mark->position < new_pos)
3128 new_pos = pbuf->buf + mark->position;
3130 pbuf->line_base += new_pos - old_pos;
3132 llassert (old_pos != NULL);
3133 llassert (new_pos != NULL);
3135 adjust_position (old_pos, new_pos, &pbuf->lineno, &pbuf->colno);
3139 cppBuffer_getLineAndColumn (/*@null@*/ cppBuffer *pbuf, /*@out@*/ int *linep,
3140 /*@null@*/ /*@out@*/ int *colp)
3148 } /*@=branchstate@*/
3152 *linep = pbuf->lineno;
3153 *colp = pbuf->colno;
3155 llassert (pbuf->buf != NULL);
3156 llassert (pbuf->cur != NULL);
3158 adjust_position (pbuf->buf + pbuf->line_base, pbuf->cur, linep, colp);
3167 /* Return the cppBuffer that corresponds to a file (not a macro). */
3169 /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_fileBuffer (cppReader *pfile)
3171 cppBuffer *ip = cppReader_getBuffer (pfile);
3174 ip != NULL && ip != cppReader_nullBuffer (pfile);
3175 ip = cppBuffer_prevBuffer (ip))
3177 if (ip->fname != NULL)
3187 count_newlines (char *buf, char *limit)
3189 register long count = 0;
3201 * write out a #line command, for instance, after an #include file.
3202 * If CONDITIONAL is nonzero, we can omit the #line if it would
3203 * appear to be a no-op, and we can output a few newlines instead
3204 * if we want to increase the line number by a small amount.
3205 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
3209 output_line_command (cppReader *pfile, bool conditional,
3210 enum file_change_code file_change)
3213 cppBuffer *ip = CPPBUFFER (pfile);
3216 llassert (ip != NULL);
3218 if (ip->fname == NULL)
3221 update_position (ip);
3223 if (CPPOPTIONS (pfile)->no_line_commands
3224 || CPPOPTIONS (pfile)->no_output)
3227 buf = CPPBUFFER (pfile);
3229 llassert (buf != NULL);
3234 llassert (ip->cur != NULL);
3236 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
3238 if (CPPOPTIONS (pfile)->no_line_commands)
3242 if (line == pfile->lineno)
3245 /* If the inherited line number is a little too small,
3246 output some newlines instead of a #line command. */
3248 if (line > pfile->lineno && line < pfile->lineno + 8)
3250 cpplib_reserve (pfile, 20);
3251 while (line > pfile->lineno)
3253 cppReader_putCharQ (pfile, '\n');
3261 cpplib_reserve (pfile, 4 * cstring_length (ip->nominal_fname) + 50);
3264 #ifdef OUTPUT_LINE_COMMANDS
3265 static char sharp_line[] = "#line ";
3267 static char sharp_line[] = "# ";
3269 cppReader_putStrN (pfile, sharp_line, sizeof(sharp_line)-1);
3272 sprintf (cpplib_getPWritten (pfile), "%d ", line);
3273 cppReader_adjustWritten (pfile, strlen (cpplib_getPWritten (pfile)));
3275 quote_string (pfile, cstring_toCharsSafe (ip->nominal_fname));
3277 if (file_change != same_file) {
3278 cppReader_putCharQ (pfile, ' ');
3279 cppReader_putCharQ (pfile, file_change == enter_file ? '1' : '2');
3281 /* Tell cc1 if following text comes from a system header file. */
3282 if (ip->system_header_p != '\0') {
3283 cppReader_putCharQ (pfile, ' ');
3284 cppReader_putCharQ (pfile, '3');
3286 #ifndef NO_IMPLICIT_EXTERN_C
3287 /* Tell cc1plus if following text should be treated as C. */
3288 if (ip->system_header_p == (char) 2 && CPPOPTIONS (pfile)->cplusplus) {
3289 cppReader_putCharQ (pfile, ' ');
3290 cppReader_putCharQ (pfile, '4');
3293 cppReader_putCharQ (pfile, '\n');
3294 pfile->lineno = line;
3299 * Parse a macro argument and append the info on PFILE's token_buffer.
3300 * REST_ARGS means to absorb the rest of the args.
3301 * Return nonzero to indicate a syntax error.
3304 static enum cpp_token
3305 macarg (cppReader *pfile, int rest_args)
3308 enum cpp_token token;
3309 char save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
3310 bool oldexpand = pfile->no_macro_expand;
3311 CPPOPTIONS (pfile)->put_out_comments = 1;
3313 /* Try to parse as much of the argument as exists at this
3314 input stack level. */
3316 pfile->no_macro_expand = TRUE;
3320 token = cpplib_getToken (pfile);
3327 /* If we've hit end of file, it's an error (reported by caller).
3328 Ditto if it's the end of cpp_expand_to_buffer text.
3329 If we've hit end of macro, just continue. */
3330 if (!cppBuffer_isMacro (CPPBUFFER (pfile)))
3332 /*@switchbreak@*/ break;
3335 /*@switchbreak@*/ break;
3339 /*@switchbreak@*/ break;
3341 /* if we've returned to lowest level and
3342 we aren't absorbing all args */
3343 if (paren == 0 && rest_args == 0)
3345 /*@switchbreak@*/ break;
3347 /* Remove ',' or ')' from argument buffer. */
3348 cppReader_adjustWritten (pfile, -1);
3356 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
3357 pfile->no_macro_expand = oldexpand;
3363 /* Turn newlines to spaces in the string of length LENGTH at START,
3364 except inside of string constants.
3365 The string is copied into itself with its beginning staying fixed. */
3368 change_newlines (char *start, int length)
3372 register char *limit;
3376 limit = start + length;
3379 while (ibp < limit) {
3380 *obp++ = c = *ibp++;
3385 /* Notice and skip strings, so that we don't delete newlines in them. */
3388 while (ibp < limit) {
3389 *obp++ = c = *ibp++;
3391 /*@innerbreak@*/ break;
3392 if (c == '\n' && quotec == '\'')
3393 /*@innerbreak@*/ break;
3396 /*@switchbreak@*/ break;
3403 static /*@observer@*/ struct tm *
3404 timestamp (/*@returned@*/ cppReader *pfile)
3406 if (pfile->timebuf == NULL)
3408 time_t t = time ((time_t *) 0);
3409 pfile->timebuf = localtime (&t);
3412 llassert (pfile->timebuf != NULL);
3414 return pfile->timebuf;
3417 static ob_mstring monthnames[] = {
3418 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3419 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3423 * expand things like __FILE__. Place the expansion into the output
3424 * buffer *without* rescanning.
3428 special_symbol (hashNode hp, cppReader *pfile)
3430 cstring buf = cstring_undefined;
3436 int paren = 0; /* For special `defined' keyword */
3438 for (ip = cppReader_getBuffer (pfile); ip != NULL; ip = cppBuffer_prevBuffer (ip))
3440 if (ip == cppReader_nullBuffer (pfile))
3442 cppReader_errorLit (pfile,
3443 cstring_makeLiteralTemp ("cccp error: not in any file?!"));
3444 return; /* the show must go on */
3447 if (ip != NULL && ip->fname != NULL)
3459 if (hp->type == T_BASE_FILE)
3461 while (cppBuffer_prevBuffer (ip) != cppReader_nullBuffer (pfile))
3463 ip = cppBuffer_prevBuffer (ip);
3467 llassert (ip != NULL);
3468 string = cstring_toCharsSafe (ip->nominal_fname);
3475 cpplib_reserve (pfile, 3 + 4 * strlen (string));
3476 quote_string (pfile, string);
3479 case T_FUNC: /* added in ISO C99 */
3481 /* We don't know the actual name of the function, but it doesn't matter */
3482 char *string = "** function-name **";
3483 cpplib_reserve (pfile, 3 + 4 * strlen (string));
3484 quote_string (pfile, string);
3488 case T_INCLUDE_LEVEL:
3490 ip = cppReader_getBuffer (pfile);
3492 for (; ip != cppReader_nullBuffer (pfile) && ip != NULL;
3493 ip = cppBuffer_prevBuffer (ip))
3495 if (ip != NULL && ip->fname != NULL)
3501 buf = message ("%d", true_indepth - 1);
3505 buf = cstring_makeLiteral ("\"--- cpp version---\"");
3508 #ifndef NO_BUILTIN_SIZE_TYPE
3510 buf = cstring_makeLiteral (SIZE_TYPE);
3514 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3515 case T_PTRDIFF_TYPE:
3516 buf = cstring_makeLiteral (PTRDIFF_TYPE);
3521 buf = cstring_makeLiteral (cppReader_wcharType (pfile));
3524 case T_USER_LABEL_PREFIX_TYPE:
3525 buf = cstring_makeLiteral (USER_LABEL_PREFIX);
3528 case T_REGISTER_PREFIX_TYPE:
3529 buf = cstring_makeLiteral (REGISTER_PREFIX);
3533 buf = message ("%d", hp->value.ival);
3540 int line = ip->lineno;
3541 int col = ip->colno;
3543 llassert (ip->cur != NULL);
3544 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
3546 buf = message ("%d", (int) line);
3558 char *sbuf = (char *) dmalloc (20);
3559 timebuf = timestamp (pfile);
3560 if (hp->type == T_DATE)
3562 sprintf (sbuf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
3563 timebuf->tm_mday, timebuf->tm_year + 1900);
3567 sprintf (sbuf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
3571 buf = cstring_fromCharsNew (sbuf);
3576 case T_SPEC_DEFINED:
3577 buf = cstring_makeLiteral (" 0 "); /* Assume symbol is not defined */
3578 ip = cppReader_getBuffer (pfile);
3579 llassert (ip != NULL);
3580 llassert (ip->cur != NULL);
3581 SKIP_WHITE_SPACE (ip->cur);
3583 if (*ip->cur == '(')
3586 ip->cur++; /* Skip over the paren */
3587 SKIP_WHITE_SPACE (ip->cur);
3590 if (!is_idstart[(int) *ip->cur])
3592 if (ip->cur[0] == 'L' && (ip->cur[1] == '\'' || ip->cur[1] == '\"'))
3595 if ((hp = cpphash_lookup (ip->cur, -1, -1)) != 0)
3598 buf = cstring_makeLiteral (" 1 ");
3601 while (is_idchar[(int) *ip->cur])
3606 SKIP_WHITE_SPACE (ip->cur);
3610 if (*ip->cur != ')')
3618 cppReader_errorLit (pfile,
3619 cstring_makeLiteralTemp ("`defined' without an identifier"));
3623 cpp_setLocation (pfile);
3624 llfatalerror (message ("Pre-processing error: invalid special hash type"));
3627 len = cstring_length (buf);
3629 cpplib_reserve (pfile, len + 1);
3630 cppReader_putStrN (pfile, cstring_toCharsSafe (buf), len);
3631 cppReader_nullTerminateQ (pfile);
3637 /* Write out a #define command for the special named MACRO_NAME
3638 to PFILE's token_buffer. */
3641 dump_special_to_buffer (cppReader *pfile, char *macro_name)
3643 static char define_directive[] = "#define ";
3644 size_t macro_name_length = strlen (macro_name);
3645 output_line_command (pfile, 0, same_file);
3646 cpplib_reserve (pfile, sizeof(define_directive) + macro_name_length);
3647 cppReader_putStrN (pfile, define_directive, sizeof(define_directive)-1);
3648 cppReader_putStrN (pfile, macro_name, macro_name_length);
3649 cppReader_putCharQ (pfile, ' ');
3650 cpp_expand_to_buffer (pfile, macro_name, macro_name_length);
3651 cppReader_putChar (pfile, '\n');
3654 /* Initialize the built-in macros. */
3657 cpplib_installBuiltin (/*@observer@*/ char *name, ctype ctyp,
3658 int len, enum node_type type,
3659 int ivalue, /*@null@*/ /*@only@*/ char *value,
3662 cstring sname = cstring_fromCharsNew (name);
3664 llassert (usymtab_inGlobalScope ());
3667 ** Be careful here: this is done before the ctype table has
3668 ** been initialized.
3671 if (!usymtab_exists (sname))
3673 uentry ue = uentry_makeConstant (sname, ctyp, fileloc_createBuiltin ());
3675 if (ctype_equal (ctyp, ctype_string))
3677 qualList ql = qualList_new ();
3678 ql = qualList_add (ql, qual_createObserver ());
3679 uentry_reflectQualifiers (ue, ql);
3683 usymtab_addGlobalEntry (ue);
3690 (void) cpphash_install (name, len, type, ivalue, value, hash);
3691 cstring_free (sname);
3695 cpplib_installBuiltinType (/*@observer@*/ char *name, ctype ctyp,
3696 int len, enum node_type type,
3698 /*@only@*/ /*@null@*/ char *value, int hash)
3700 cstring sname = cstring_fromChars (name);
3701 /* evs 2000 07 10 - removed a memory leak, detected by splint */
3703 llassert (usymtab_inGlobalScope ());
3705 if (!usymtab_existsTypeEither (sname))
3707 uentry ue = uentry_makeDatatype (sname, ctyp,
3708 NO, qual_createConcrete (),
3709 fileloc_createBuiltin ());
3710 llassert (!usymtab_existsEither (sname));
3711 usymtab_addGlobalEntry (ue);
3714 (void) cpphash_install (name, len, type, ivalue, value, hash);
3718 initialize_builtins (cppReader *pfile)
3720 cpplib_installBuiltin ("__LINE__", ctype_int, -1, T_SPECLINE, 0, NULL, -1);
3721 cpplib_installBuiltin ("__DATE__", ctype_string, -1, T_DATE, 0, NULL, -1);
3722 cpplib_installBuiltin ("__FILE__", ctype_string, -1, T_FILE, 0, NULL, -1);
3723 cpplib_installBuiltin ("__BASE_FILE__", ctype_string, -1, T_BASE_FILE, 0, NULL, -1);
3724 cpplib_installBuiltin ("__func__", ctype_string, -1, T_FUNC, 0, NULL, -1);
3725 cpplib_installBuiltin ("__INCLUDE_LEVEL__", ctype_int, -1, T_INCLUDE_LEVEL, 0, NULL, -1);
3726 cpplib_installBuiltin ("__VERSION__", ctype_string, -1, T_VERSION, 0, NULL, -1);
3727 #ifndef NO_BUILTIN_SIZE_TYPE
3728 cpplib_installBuiltinType ("__SIZE_TYPE__", ctype_anyintegral, -1, T_SIZE_TYPE, 0, NULL, -1);
3730 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3731 cpplib_installBuiltinType ("__PTRDIFF_TYPE__", ctype_anyintegral, -1, T_PTRDIFF_TYPE, 0, NULL, -1);
3733 cpplib_installBuiltinType ("__WCHAR_TYPE__", ctype_anyintegral, -1, T_WCHAR_TYPE, 0, NULL, -1);
3734 cpplib_installBuiltin ("__USER_LABEL_PREFIX__", ctype_string, -1, T_USER_LABEL_PREFIX_TYPE, 0, NULL, -1);
3735 cpplib_installBuiltin ("__REGISTER_PREFIX__", ctype_string, -1, T_REGISTER_PREFIX_TYPE, 0, NULL, -1);
3736 cpplib_installBuiltin ("__TIME__", ctype_string, -1, T_TIME, 0, NULL, -1);
3738 if (!cppReader_isTraditional (pfile))
3740 cpplib_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3744 cpplib_installBuiltin ("_WIN32", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3748 ** This is supplied using a -D by the compiler driver
3749 ** so that it is present only when truly compiling with GNU C.
3752 /* cpplib_install ("__GNUC__", -1, T_CONST, 2, 0, -1); */
3754 cpplib_installBuiltin ("S_SPLINT_S", ctype_int, -1, T_CONST, 2, NULL, -1);
3755 cpplib_installBuiltin ("__LCLINT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3757 /*drl 1/9/2001/ try to define the right symbol for the architecture
3758 We use autoconf to determine the target cpu
3761 cpplib_installBuiltin ("__" TARGET_CPU, ctype_int, -1, T_CONST, 2, NULL, -1);
3764 /*drl 1/2/2002 set some flags based on uname
3765 I'd like to be able to do this with autoconf macro instead...
3768 /*Thanks to Nelson Beebe for suggesting possible values for these */
3770 if (! strcmp (UNAME, "Linux"))
3773 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3777 else if(! strcmp (UNAME, "Darwin"))
3779 cpplib_installBuiltin ("__ppc__", ctype_int, -1, T_CONST, 2, NULL, -1);
3780 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3782 else if(! strcmp (UNAME, "HP-UX"))
3784 cpplib_installBuiltin ("PWB", ctype_int, -1, T_CONST, 2, NULL, -1);
3785 cpplib_installBuiltin ("_HIUX_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3786 cpplib_installBuiltin ("_HPUX_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3787 cpplib_installBuiltin ("_PA_RISC1_1", ctype_int, -1, T_CONST, 2, NULL, -1);
3788 cpplib_installBuiltin ("__PWB", ctype_int, -1, T_CONST, 2, NULL, -1);
3789 cpplib_installBuiltin ("__PWB__", ctype_int, -1, T_CONST, 2, NULL, -1);
3790 cpplib_installBuiltin ("__STDC_EXT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3791 cpplib_installBuiltin ("__hp9000s700", ctype_int, -1, T_CONST, 2, NULL, -1);
3792 cpplib_installBuiltin ("__hp9000s800", ctype_int, -1, T_CONST, 2, NULL, -1);
3793 cpplib_installBuiltin ("__hp9000s800__", ctype_int, -1, T_CONST, 2, NULL, -1);
3794 cpplib_installBuiltin ("__hp9k8", ctype_int, -1, T_CONST, 2, NULL, -1);
3795 cpplib_installBuiltin ("__hp9k8__", ctype_int, -1, T_CONST, 2, NULL, -1);
3796 cpplib_installBuiltin ("__hppa", ctype_int, -1, T_CONST, 2, NULL, -1);
3797 cpplib_installBuiltin ("__hppa__", ctype_int, -1, T_CONST, 2, NULL, -1);
3798 cpplib_installBuiltin ("__hpux", ctype_int, -1, T_CONST, 2, NULL, -1);
3799 cpplib_installBuiltin ("__hpux__", ctype_int, -1, T_CONST, 2, NULL, -1);
3800 cpplib_installBuiltin ("__unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3801 cpplib_installBuiltin ("__unix__", ctype_int, -1, T_CONST, 2, NULL, -1);
3802 cpplib_installBuiltin ("hp9000s800", ctype_int, -1, T_CONST, 2, NULL, -1);
3803 cpplib_installBuiltin ("hp9k8", ctype_int, -1, T_CONST, 2, NULL, -1);
3804 cpplib_installBuiltin ("hppa", ctype_int, -1, T_CONST, 2, NULL, -1);
3805 cpplib_installBuiltin ("hpux", ctype_int, -1, T_CONST, 2, NULL, -1);
3806 cpplib_installBuiltin ("unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3808 else if(! strcmp (UNAME, "IRIX64"))
3810 cpplib_installBuiltin ("LANGUAGE_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3811 cpplib_installBuiltin ("MIPSEB", ctype_int, -1, T_CONST, 2, NULL, -1);
3812 cpplib_installBuiltin ("_ABIN32", ctype_int, -1, T_CONST, 2, NULL, -1);
3813 cpplib_installBuiltin ("_COMPILER_VERSION", ctype_int, -1, T_CONST, 730, NULL, -1);
3814 cpplib_installBuiltin ("_LANGUAGE_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3815 cpplib_installBuiltin ("_LONGLONG", ctype_int, -1, T_CONST, 2, NULL, -1);
3816 cpplib_installBuiltin ("_MIPSEB", ctype_int, -1, T_CONST, 2, NULL, -1);
3817 cpplib_installBuiltin ("_MIPS_FPSET", ctype_int, -1, T_CONST, 32, NULL, -1);
3818 cpplib_installBuiltin ("_MIPS_ISA", ctype_int, -1, T_CONST, 3, NULL, -1);
3819 /*_MIPS_SIM=_ABIN32*/
3820 cpplib_installBuiltin ("_MIPS_SIM", ctype_int, -1, T_CONST, 2, NULL , -1);
3821 cpplib_installBuiltin ("_MIPS_SZINT", ctype_int, -1, T_CONST, 32, NULL, -1);
3822 cpplib_installBuiltin ("_MIPS_SZLONG", ctype_int, -1, T_CONST, 32, NULL, -1);
3823 cpplib_installBuiltin ("_MIPS_SZPTR", ctype_int, -1, T_CONST, 32, NULL, -1);
3824 cpplib_installBuiltin ("_MODERN_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3825 cpplib_installBuiltin ("_PIC", ctype_int, -1, T_CONST, 2, NULL, -1);
3826 cpplib_installBuiltin ("_SGI_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3827 cpplib_installBuiltin ("_SIZE_INT", ctype_int, -1, T_CONST, 32, NULL, -1);
3828 cpplib_installBuiltin ("_SIZE_LONG", ctype_int, -1, T_CONST, 32, NULL, -1);
3829 cpplib_installBuiltin ("_SIZE_PTR", ctype_int, -1, T_CONST, 32, NULL, -1);
3830 cpplib_installBuiltin ("_SVR4_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3831 cpplib_installBuiltin ("_SYSTYPE_SVR4", ctype_int, -1, T_CONST, 2, NULL, -1);
3832 cpplib_installBuiltin ("__DSO__", ctype_int, -1, T_CONST, 2, NULL, -1);
3833 cpplib_installBuiltin ("__EXTENSIONS__", ctype_int, -1, T_CONST, 2, NULL, -1);
3834 cpplib_installBuiltin ("__INLINE_INTRINSICS", ctype_int, -1, T_CONST, 2, NULL, -1);
3835 cpplib_installBuiltin ("__MATH_HAS_NO_SIDE_EFFECTS", 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, 3, 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);
3840 cpplib_installBuiltin ("host_mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3841 cpplib_installBuiltin ("mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3842 cpplib_installBuiltin ("sgi", ctype_int, -1, T_CONST, 2, NULL, -1);
3843 cpplib_installBuiltin ("unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3845 else if(! strcmp (UNAME, "OSF1"))
3847 cpplib_installBuiltin ("__alpha", ctype_int, -1, T_CONST, 2, NULL, -1);
3849 else if (!strcmp (UNAME, "Rhapsody"))
3851 cpplib_installBuiltin ("__ppc__", ctype_int, -1, T_CONST, 2, NULL, -1);
3852 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3855 else if (!strcmp (UNAME, "SunOS"))
3857 cpplib_installBuiltin ("__OPEN_MAX", ctype_int, -1, T_CONST, 20, NULL, -1);
3858 cpplib_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, 2, NULL, -1);
3859 cpplib_installBuiltin ("__sparc", ctype_int, -1, T_CONST, 2, NULL, -1);
3860 /* This define "-Dfileno(f)=0" should be inserted but we're going to stick to deinfe constants for now...*/
3865 types which we have not explictedly handled.
3866 AIX, FreeBSD, IRIX, Mach
3871 if (CPPOPTIONS (pfile)->debug_output)
3873 dump_special_to_buffer (pfile, "__BASE_FILE__");
3874 dump_special_to_buffer (pfile, "__VERSION__");
3875 #ifndef NO_BUILTIN_SIZE_TYPE
3876 dump_special_to_buffer (pfile, "__SIZE_TYPE__");
3878 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3879 dump_special_to_buffer (pfile, "__PTRDIFF_TYPE__");
3881 dump_special_to_buffer (pfile, "__WCHAR_TYPE__");
3882 dump_special_to_buffer (pfile, "__DATE__");
3883 dump_special_to_buffer (pfile, "__TIME__");
3884 if (!cppReader_isTraditional (pfile))
3885 dump_special_to_buffer (pfile, "__STDC__");
3890 /* Return 1 iff a token ending in C1 followed directly by a token C2
3891 could cause mis-tokenization. */
3894 unsafe_chars (char c1, char c2)
3899 if (c2 == c1 || c2 == '=')
3903 case '0': case '1': case '2': case '3': case '4':
3904 case '5': case '6': case '7': case '8': case '9':
3905 case 'e': case 'E': case 'p': case 'P':
3906 if (c2 == '-' || c2 == '+')
3907 return 1; /* could extend a pre-processing number */
3910 if (c2 == '\'' || c2 == '\"')
3911 return 1; /* Could turn into L"xxx" or L'xxx'. */
3915 case 'a': case 'b': case 'c': case 'd': case 'f':
3916 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3917 case 'm': case 'n': case 'o': case 'q': case 'r':
3918 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3920 case 'A': case 'B': case 'C': case 'D': case 'F':
3921 case 'G': case 'H': case 'I': case 'J': case 'K':
3922 case 'M': case 'N': case 'O': case 'Q': case 'R':
3923 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3925 /* We're in the middle of either a name or a pre-processing number. */
3926 return (is_idchar[(int) c2] || c2 == '.');
3927 case '<': case '>': case '!': case '%': case '#': case ':':
3928 case '^': case '&': case '|': case '*': case '/': case '=':
3929 return (c2 == c1 || c2 == '=');
3934 /* Expand a macro call.
3935 HP points to the symbol that is the macro being called.
3936 Put the result of expansion onto the input stack
3937 so that subsequent input by our caller will use it.
3939 If macro wants arguments, caller has already verified that
3940 an argument list follows; arguments come from the input stack. */
3943 cpplib_macroExpand (cppReader *pfile, /*@dependent@*/ hashNode hp)
3946 DEFINITION *defn = hp->value.defn;
3954 size_t old_written = cpplib_getWritten (pfile);
3958 struct argdata *args = NULL;
3960 pfile->output_escapes++;
3961 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile), &start_line, &start_column);
3962 DPRINTF (("Expand macro: %d:%d", start_line, start_column));
3964 nargs = defn->nargs;
3968 enum cpp_token token = CPP_EOF;
3970 args = (struct argdata *) dmalloc ((nargs + 1) * sizeof (*args));
3972 for (i = 0; i < nargs; i++)
3974 args[i].expanded = 0;
3976 args[i].raw_length = 0;
3977 args[i].expand_length = args[i].stringified_length = -1;
3978 args[i].use_count = 0;
3982 ** Parse all the macro args that are supplied. I counts them.
3983 ** The first NARGS args are stored in ARGS.
3984 ** The rest are discarded. If rest_args is set then we assume
3985 ** macarg absorbed the rest of the args.
3991 cppReader_forward (pfile, 1); /* Discard the open-parenthesis before the first arg. */
3999 if (i < nargs || (nargs == 0 && i == 0))
4001 /* if we are working on last arg which absorbs rest of args... */
4002 if (i == nargs - 1 && defn->rest_args)
4007 args[i].raw = size_toLong (cpplib_getWritten (pfile));
4008 token = macarg (pfile, rest_args);
4009 args[i].raw_length = size_toInt (cpplib_getWritten (pfile) - args[i].raw);
4010 args[i].newlines = FALSE; /* FIXME */
4014 token = macarg (pfile, 0);
4017 if (token == CPP_EOF || token == CPP_POP)
4019 cppReader_errorWithLine (pfile, start_line, start_column,
4020 cstring_fromCharsNew ("unterminated macro call"));
4025 } while (token == CPP_COMMA);
4027 /* If we got one arg but it was just whitespace, call that 0 args. */
4035 bp = ARG_BASE + args[0].raw;
4036 lim = bp + args[0].raw_length;
4038 /* cpp.texi says for foo ( ) we provide one argument.
4039 However, if foo wants just 0 arguments, treat this as 0. */
4043 while (bp != lim && is_space[(int) *bp])
4053 /* Don't output an error message if we have already output one for
4054 a parse error above. */
4057 if (nargs == 0 && i > 0)
4059 cppReader_error (pfile,
4060 message ("arguments given to macro `%s'", hp->name));
4064 /* traditional C allows foo() if foo wants one argument. */
4065 if (nargs == 1 && i == 0 && cppReader_isTraditional (pfile))
4069 /* the rest args token is allowed to absorb 0 tokens */
4070 else if (i == nargs - 1 && defn->rest_args)
4073 cppReader_error (pfile,
4074 message ("macro `%s' used without args", hp->name));
4076 cppReader_error (pfile,
4077 message ("macro `%s' used with just one arg", hp->name));
4080 cppReader_error (pfile,
4081 message ("macro `%s' used with only %d args",
4087 cppReader_error (pfile,
4088 message ("macro `%s' used with too many (%d) args", hp->name, i));
4097 ** If the agrument list was multiple lines, need to insert new lines to keep line
4098 ** numbers accurate.
4101 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile), &end_line, &end_column);
4102 DPRINTF (("Expand macro: %d:%d", end_line, end_column));
4104 /* If macro wants zero args, we parsed the arglist for checking only.
4105 Read directly from the macro definition. */
4109 xbuf = defn->expansion;
4110 xbuf_len = defn->length;
4114 char *exp = defn->expansion;
4115 int offset; /* offset in expansion,
4116 copied a piece at a time */
4117 size_t totlen; /* total amount of exp buffer filled so far */
4119 register struct reflist *ap, *last_ap;
4121 assertSet (args); /* args is defined since the nargs > 0 path was taken */
4123 /* Macro really takes args. Compute the expansion of this call. */
4125 /* Compute length in characters of the macro's expansion.
4126 Also count number of times each arg is used. */
4127 xbuf_len = defn->length;
4129 llassert (args != NULL);
4131 for (ap = defn->pattern; ap != NULL; ap = ap->next)
4135 struct argdata *arg = &args[ap->argno];
4137 /* Stringify it it hasn't already been */
4140 if (arg->stringified_length < 0)
4142 int arglen = arg->raw_length;
4143 bool escaped = FALSE;
4144 char in_string = '\0';
4147 /* Initially need_space is -1. Otherwise, 1 means the
4148 previous character was a space, but we suppressed it;
4149 0 means the previous character was a non-space. */
4150 int need_space = -1;
4153 arg->stringified = cpplib_getWritten (pfile);
4154 if (!cppReader_isTraditional (pfile))
4155 cppReader_putChar (pfile, '\"'); /* insert beginning quote */
4156 for (; i < arglen; i++)
4158 c = (ARG_BASE + arg->raw)[i];
4160 if (in_string == '\0')
4162 /* Internal sequences of whitespace are replaced by
4163 one space except within an string or char token.*/
4164 if (is_space[(int) c])
4166 if (cpplib_getWritten (pfile) > arg->stringified
4167 && (cpplib_getPWritten (pfile))[-1] == '@')
4169 /* "@ " escape markers are removed */
4170 cppReader_adjustWritten (pfile, -1);
4171 /*@innercontinue@*/ continue;
4173 if (need_space == 0)
4175 /*@innercontinue@*/ continue;
4177 else if (need_space > 0)
4178 cppReader_putChar (pfile, ' ');
4194 if (in_string != '\0')
4199 else if (c == '\"' || c == '\'')
4209 /* Escape these chars */
4210 if (c == '\"' || (in_string != '\0' && c == '\\'))
4211 cppReader_putChar (pfile, '\\');
4213 cppReader_putChar (pfile, c);
4216 cpplib_reserve (pfile, 4);
4217 sprintf (cpplib_getPWritten (pfile), "\\%03o",
4219 cppReader_adjustWritten (pfile, 4);
4222 if (!cppReader_isTraditional (pfile))
4223 cppReader_putChar (pfile, '\"'); /* insert ending quote */
4224 arg->stringified_length
4225 = size_toInt (cpplib_getWritten (pfile) - arg->stringified);
4228 xbuf_len += args[ap->argno].stringified_length;
4230 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
4232 /* Add 4 for two newline-space markers to prevent token concatenation. */
4233 assertSet (args); /* Splint shouldn't need this */
4234 xbuf_len += args[ap->argno].raw_length + 4;
4238 /* We have an ordinary (expanded) occurrence of the arg.
4239 So compute its expansion, if we have not already. */
4241 assertSet (args); /* shouldn't need this */
4243 if (args[ap->argno].expand_length < 0)
4245 args[ap->argno].expanded = cpplib_getWritten (pfile);
4246 cpp_expand_to_buffer (pfile,
4247 ARG_BASE + args[ap->argno].raw,
4248 size_fromInt (args[ap->argno].raw_length));
4250 args[ap->argno].expand_length
4251 = size_toInt (cpplib_getWritten (pfile) - args[ap->argno].expanded);
4254 /* Add 4 for two newline-space markers to prevent
4255 token concatenation. */
4256 xbuf_len += args[ap->argno].expand_length + 4;
4258 if (args[ap->argno].use_count < 10)
4259 args[ap->argno].use_count++;
4262 xbuf = (char *) dmalloc (xbuf_len + 1);
4266 ** Generate in XBUF the complete expansion
4267 ** with arguments substituted in.
4268 ** TOTLEN is the total size generated so far.
4269 ** OFFSET is the index in the definition
4270 ** of where we are copying from.
4276 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
4277 last_ap = ap, ap = ap->next)
4279 register struct argdata *arg = &args[ap->argno];
4280 size_t count_before = totlen;
4282 /* Add chars to XBUF. */
4283 for (i = 0; i < ap->nchars; i++, offset++)
4285 xbuf[totlen++] = exp[offset];
4288 /* If followed by an empty rest arg with concatenation,
4289 delete the last run of nonwhite chars. */
4290 if (rest_zero && totlen > count_before
4291 && ((ap->rest_args && ap->raw_before)
4292 || (last_ap != NULL && last_ap->rest_args
4293 && last_ap->raw_after)))
4295 /* Delete final whitespace. */
4296 while (totlen > count_before && is_space[(int) xbuf[totlen - 1]])
4301 /* Delete the nonwhites before them. */
4302 while (totlen > count_before && ! is_space[(int) xbuf[totlen - 1]])
4308 if (ap->stringify != 0)
4311 memcpy (xbuf + totlen,
4312 ARG_BASE + arg->stringified,
4313 size_fromInt (arg->stringified_length));
4314 totlen += arg->stringified_length;
4316 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
4323 p1 = ARG_BASE + arg->raw;
4324 l1 = p1 + arg->raw_length;
4328 while (p1 != l1 && is_space[(int) *p1])
4333 while (p1 != l1 && is_idchar[(int) *p1])
4335 xbuf[totlen++] = *p1++;
4338 /* Delete any no-reexpansion marker that follows
4339 an identifier at the beginning of the argument
4340 if the argument is concatenated with what precedes it. */
4341 if (p1[0] == '@' && p1[1] == '-')
4346 /* Arg is concatenated after: delete trailing whitespace,
4347 whitespace markers, and no-reexpansion markers. */
4350 if (is_space[(int) l1[-1]]) l1--;
4351 else if (l1[-1] == '-')
4354 /* If a `-' is preceded by an odd number of newlines then it
4355 and the last newline are a no-reexpansion marker. */
4356 while (p2 != p1 && p2[-1] == '\n')
4361 if (((l1 - 1 - p2) & 1) != 0)
4367 /*@innerbreak@*/ break;
4372 /*@innerbreak@*/ break;
4377 memcpy (xbuf + totlen, p1, size_fromInt (l1 - p1));
4385 expanded = ARG_BASE + arg->expanded;
4387 if (!ap->raw_before && totlen > 0
4388 && (arg->expand_length != 0)
4389 && !cppReader_isTraditional(pfile)
4390 && unsafe_chars (xbuf[totlen-1], expanded[0]))
4392 xbuf[totlen++] = '@';
4393 xbuf[totlen++] = ' ';
4396 memcpy (xbuf + totlen, expanded,
4397 size_fromInt (arg->expand_length));
4398 totlen += arg->expand_length;
4400 if (!ap->raw_after && totlen > 0
4401 && offset < size_toInt (defn->length)
4402 && !cppReader_isTraditional(pfile)
4403 && unsafe_chars (xbuf[totlen-1], exp[offset]))
4405 xbuf[totlen++] = '@';
4406 xbuf[totlen++] = ' ';
4409 /* If a macro argument with newlines is used multiple times,
4410 then only expand the newlines once. This avoids creating
4411 output lines which don't correspond to any input line,
4412 which confuses gdb and gcov. */
4413 if (arg->use_count > 1 && arg->newlines > 0)
4415 /* Don't bother doing change_newlines for subsequent
4419 = change_newlines (expanded, arg->expand_length);
4423 if (totlen > xbuf_len)
4427 /* if there is anything left of the definition
4428 after handling the arg list, copy that in too. */
4430 for (i = offset; i < size_toInt (defn->length); i++)
4432 /* if we've reached the end of the macro */
4435 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
4436 && last_ap->raw_after))
4437 xbuf[totlen++] = exp[i];
4440 xbuf[totlen] = '\0';
4444 pfile->output_escapes--;
4446 /* Now put the expansion on the input stack
4447 so our caller will commence reading from it. */
4448 DPRINTF (("Pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4450 if (end_line != start_line)
4452 /* xbuf must have enough newlines */
4453 int newlines = end_line - start_line;
4454 int foundnewlines = 0;
4455 char *xbufptr = xbuf;
4457 while ((xbufptr = strchr (xbufptr, '\n')) != NULL && foundnewlines <= newlines)
4462 if (*xbufptr == '\0')
4468 if (foundnewlines < newlines)
4470 cstring newbuf = cstring_copyLength (xbuf, xbuf_len);
4472 while (foundnewlines < newlines)
4474 newbuf = cstring_appendChar (newbuf, '\n');
4479 xbuf = cstring_toCharsSafe (newbuf);
4480 xbuf_len = cstring_length (newbuf);
4482 } /*@=branchstate@*/
4485 DPRINTF (("Pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4487 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
4488 DPRINTF (("After pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4489 cppReader_getBufferSafe (pfile)->has_escapes = 1;
4491 /* Pop the space we've used in the token_buffer for argument expansion. */
4492 cppReader_setWritten (pfile, old_written);
4493 DPRINTF (("Done set written"));
4495 /* Recursive macro use sometimes works traditionally.
4496 #define foo(x,y) bar (x (y,0), y)
4499 if (!cppReader_isTraditional (pfile))
4500 hp->type = T_DISABLED;
4506 push_macro_expansion (cppReader *pfile, char *xbuf, size_t xbuf_len,
4507 /*@dependent@*/ hashNode hp)
4509 cppBuffer *mbuf = cppReader_pushBuffer (pfile, xbuf, xbuf_len);
4516 mbuf->cleanup = cppReader_macroCleanup;
4518 llassert (mbuf->hnode == NULL);
4521 /* The first chars of the expansion should be a "@ " added by
4522 collect_expansion. This is to prevent accidental token-pasting
4523 between the text preceding the macro invocation, and the macro
4526 We would like to avoid adding unneeded spaces (for the sake of
4527 tools that use cpp, such as imake). In some common cases we can
4528 tell that it is safe to omit the space.
4530 The character before the macro invocation cannot have been an
4531 idchar (or else it would have been pasted with the idchars of
4532 the macro name). Therefore, if the first non-space character
4533 of the expansion is an idchar, we do not need the extra space
4534 to prevent token pasting.
4536 Also, we don't need the extra space if the first char is '(',
4537 or some other (less common) characters. */
4539 if (xbuf[0] == '@' && xbuf[1] == ' '
4540 && (is_idchar[(int) xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
4541 || xbuf[2] == '\"'))
4543 llassert (mbuf->cur != NULL);
4544 DPRINTF (("Eating: %c", xbuf[2]));
4551 /* Like cpplib_getToken, except that it does not read past end-of-line.
4552 Also, horizontal space is skipped, and macros are popped. */
4554 static enum cpp_token
4555 get_directive_token (cppReader *pfile)
4559 size_t old_written = cpplib_getWritten (pfile);
4560 enum cpp_token token;
4561 cppSkipHspace (pfile);
4562 if (cppReader_peekC (pfile) == '\n')
4567 token = cpplib_getToken (pfile);
4572 if (!cppBuffer_isMacro (cppReader_getBuffer (pfile)))
4577 cppReader_setWritten (pfile, old_written);
4578 /*@switchbreak@*/ break;
4586 /* Handle #include and #import.
4587 This function expects to see "fname" or <fname> on the input.
4589 The input is normally in part of the output_buffer following
4590 cpplib_getWritten, and will get overwritten by output_line_command.
4591 I.e. in input file specification has been popped by cppReader_handleDirective.
4595 do_include (cppReader *pfile, struct directive *keyword,
4596 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
4598 bool skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4600 char *fbeg, *fend; /* Beginning and end of fname */
4601 enum cpp_token token;
4603 /* Chain of dirs to search */
4604 struct file_name_list *search_start = CPPOPTIONS (pfile)->include;
4605 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
4606 struct file_name_list *searchptr = NULL;
4607 size_t old_written = cpplib_getWritten (pfile);
4610 int f; /* file number */
4611 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4612 f= -1; /* JF we iz paranoid! */
4614 pfile->parsing_include_directive++;
4615 token = get_directive_token (pfile);
4616 pfile->parsing_include_directive--;
4618 if (token == CPP_STRING)
4620 /* FIXME - check no trailing garbage */
4621 fbeg = pfile->token_buffer + old_written + 1;
4622 fend = cpplib_getPWritten (pfile) - 1;
4623 if (fbeg[-1] == '<')
4626 /* If -I-, start with the first -I dir after the -I-. */
4627 if (CPPOPTIONS (pfile)->first_bracket_include != NULL)
4628 search_start = CPPOPTIONS (pfile)->first_bracket_include;
4630 /* If -I- was specified, don't search current dir, only spec'd ones. */
4631 else if (!CPPOPTIONS (pfile)->ignore_srcdir)
4633 cppBuffer *fp = CPPBUFFER (pfile);
4634 /* We have "filename". Figure out directory this source
4635 file is coming from and put it on the front of the list. */
4637 for ( ; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
4642 llassert (fp != NULL);
4646 if (cstring_isDefined (fp->nominal_fname))
4648 nam = cstring_toCharsSafe (fp->nominal_fname);
4650 /* Found a named file. Figure out dir of the file,
4651 and put it in front of the search list. */
4652 dsp[0].next = search_start;
4656 ep = strrchr (nam, CONNECTCHAR);
4658 ep = strrchr (nam, ']');
4659 if (ep == NULL) ep = strrchr (nam, '>');
4660 if (ep == NULL) ep = strrchr (nam, ':');
4661 if (ep != NULL) ep++;
4671 /*@-onlytrans@*/ /* This looks like a memory leak... */
4672 dsp[0].fname = cstring_fromCharsNew (nam); /* evs 2000-07-20: was fromChars */
4676 if (n + INCLUDE_LEN_FUDGE > size_toInt (pfile->max_include_len))
4677 pfile->max_include_len = size_fromInt (n + INCLUDE_LEN_FUDGE);
4681 dsp[0].fname = cstring_undefined; /* Current directory */
4684 dsp[0].got_name_map = 0;
4695 else if (token == CPP_NAME)
4698 * Support '#include xyz' like VAX-C to allow for easy use of all the
4699 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4700 * code from case '<' is repeated here) and generates a warning.
4702 cppReader_warning (pfile,
4703 "VAX-C-style include specification found, use '#include <filename.h>' !");
4705 /* If -I-, start with the first -I dir after the -I-. */
4706 if (CPPOPTIONS (pfile)->first_bracket_include)
4707 search_start = CPPOPTIONS (pfile)->first_bracket_include;
4708 fbeg = pfile->token_buffer + old_written;
4709 fend = cpplib_getPWritten (pfile);
4714 cppReader_error (pfile,
4715 message ("Preprocessor command #%s expects \"FILENAME\" or <FILENAME>",
4718 cppReader_setWritten (pfile, old_written);
4719 cppReader_skipRestOfLine (pfile);
4725 token = get_directive_token (pfile);
4726 if (token != CPP_VSPACE)
4728 cppReader_errorLit (pfile,
4729 cstring_makeLiteralTemp ("Junk at end of #include"));
4731 while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
4733 token = get_directive_token (pfile);
4738 ** For #include_next, skip in the search path
4739 ** past the dir in which the containing file was found.
4744 cppBuffer *fp = CPPBUFFER (pfile);
4746 for (; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
4748 llassert (fp != NULL);
4750 if (fp->fname != NULL)
4752 /* fp->dir is null if the containing file was specified with
4753 an absolute file name. In that case, don't skip anything. */
4754 if (fp->dir == SELF_DIR_DUMMY)
4756 search_start = CPPOPTIONS (pfile)->include;
4758 else if (fp->dir != NULL)
4760 search_start = fp->dir->next;
4772 cppReader_setWritten (pfile, old_written);
4774 flen = size_fromInt (fend - fbeg);
4776 DPRINTF (("fbeg: %s", fbeg));
4780 cppReader_error (pfile,
4781 message ("Empty file name in #%s", keyword->name));
4786 ** Allocate this permanently, because it gets stored in the definitions
4790 fname = cstring_undefined;
4792 /* + 2 above for slash and terminating null. */
4793 /* + 2 added for '.h' on VMS (to support '#include filename') */
4795 /* If specified file name is absolute, just open it. */
4797 if (osd_isConnectChar (*fbeg)
4798 # if defined (WIN32) || defined (OS2)
4799 || (*(fbeg + 1) == ':')
4803 fname = cstring_copyLength (fbeg, flen);
4805 if (redundant_include_p (pfile, fname))
4807 cstring_free (fname);
4811 f = open_include_file (pfile, fname, NULL);
4813 if (f == IMPORT_FOUND)
4815 return 0; /* Already included this file */
4820 /* Search directory path, trying to open the file.
4821 Copy each filename tried into FNAME. */
4823 for (searchptr = search_start; searchptr != NULL;
4824 searchptr = searchptr->next)
4826 if (!cstring_isEmpty (searchptr->fname))
4828 /* The empty string in a search path is ignored.
4829 This makes it possible to turn off entirely
4830 a standard piece of the list. */
4831 if (cstring_isEmpty (searchptr->fname))
4834 fname = cstring_copy (searchptr->fname);
4835 fname = cstring_appendChar (fname, CONNECTCHAR);
4836 DPRINTF (("Here: %s", fname));
4843 fname = cstring_concatLength (fname, fbeg, flen);
4845 DPRINTF (("fname: %s", fname));
4847 /* Win32 directory fix from Kay Buschner. */
4848 #if defined (WIN32) || defined (OS2)
4849 /* Fix all unixdir slashes to win dir slashes */
4850 if (searchptr->fname && (searchptr->fname[0] != 0))
4852 cstring_replaceAll (fname, '/', '\\');
4857 /* Change this 1/2 Unix 1/2 VMS file specification into a
4858 full VMS file specification */
4859 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4860 /* Fix up the filename */
4861 hack_vms_include_specification (fname);
4863 /* This is a normal VMS filespec, so use it unchanged. */
4864 strncpy (fname, fbeg, flen);
4866 /* if it's '#include filename', add the missing .h */
4867 if (strchr (fname,'.') == NULL) {
4868 strcat (fname, ".h");
4872 /* ??? There are currently 3 separate mechanisms for avoiding processing
4873 of redundant include files: #import, #pragma once, and
4874 redundant_include_p. It would be nice if they were unified. */
4876 if (redundant_include_p (pfile, fname))
4878 cstring_free (fname);
4882 DPRINTF (("Trying: %s", fname));
4884 f = open_include_file (pfile, fname, searchptr);
4886 if (f == IMPORT_FOUND)
4888 return 0; /* Already included this file */
4891 else if (f == IMPORT_NOT_FOUND && errno == EACCES)
4893 cppReader_warning (pfile,
4894 message ("Header file %s exists, but is not readable", fname));
4907 /* A file that was not found. */
4908 fname = cstring_copyLength (fbeg, flen);
4910 if (search_start != NULL)
4912 cppReader_error (pfile,
4913 message ("Cannot find include file %s on search path: %x",
4915 searchPath_unparse (search_start)));
4919 cppReader_error (pfile,
4920 message ("No include path in which to find %s", fname));
4925 ** Check to see if this include file is a once-only include file.
4929 struct file_name_list *ptr;
4931 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
4933 if (cstring_equal (ptr->fname, fname))
4935 /* This file was included before. */
4942 /* This is the first time for this file. */
4943 /* Add it to list of files included. */
4945 ptr = (struct file_name_list *) dmalloc (sizeof (*ptr));
4946 ptr->control_macro = NULL;
4947 ptr->c_system_include_path = NULL;
4948 ptr->next = pfile->all_include_files;
4950 ptr->got_name_map = NULL;
4952 DPRINTF (("Including file: %s", fname));
4953 pfile->all_include_files = ptr;
4954 assertSet (pfile->all_include_files);
4957 if (angle_brackets != 0)
4959 pfile->system_include_depth++;
4962 /* Actually process the file */
4963 if (cppReader_pushBuffer (pfile, NULL, 0) == NULL)
4965 cstring_free (fname);
4969 if (finclude (pfile, f, fname, is_system_include (pfile, fname),
4970 searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
4972 output_line_command (pfile, 0, enter_file);
4973 pfile->only_seen_white = 2;
4978 pfile->system_include_depth--;
4981 } /*@=branchstate@*/
4986 /* Return nonzero if there is no need to include file NAME
4987 because it has already been included and it contains a conditional
4988 to make a repeated include do nothing. */
4991 redundant_include_p (cppReader *pfile, cstring name)
4993 struct file_name_list *l = pfile->all_include_files;
4995 for (; l != NULL; l = l->next)
4997 if (cstring_equal (name, l->fname)
4998 && (l->control_macro != NULL)
4999 && (cpphash_lookup (l->control_macro, -1, -1) != NULL))
5008 /* Return nonzero if the given FILENAME is an absolute pathname which
5009 designates a file within one of the known "system" include file
5010 directories. We assume here that if the given FILENAME looks like
5011 it is the name of a file which resides either directly in a "system"
5012 include file directory, or within any subdirectory thereof, then the
5013 given file must be a "system" include file. This function tells us
5014 if we should suppress pedantic errors/warnings for the given FILENAME.
5016 The value is 2 if the file is a C-language system header file
5017 for which C++ should (on most systems) assume `extern "C"'. */
5020 is_system_include (cppReader *pfile, cstring filename)
5022 struct file_name_list *searchptr;
5024 for (searchptr = CPPOPTIONS (pfile)->first_system_include;
5026 searchptr = searchptr->next)
5028 if (!cstring_isEmpty (searchptr->fname))
5030 cstring sys_dir = searchptr->fname;
5031 size_t length = cstring_length (sys_dir);
5033 if (cstring_equalLen (sys_dir, filename, length)
5034 && osd_isConnectChar (cstring_getChar (filename, length)))
5036 if (searchptr->c_system_include_path)
5047 /* Convert a character string literal into a nul-terminated string.
5048 The input string is [IN ... LIMIT).
5049 The result is placed in RESULT. RESULT can be the same as IN.
5050 The value returned in the end of the string written to RESULT,
5051 or NULL on error. */
5053 static /*@null@*/ char *
5054 convert_string (cppReader *pfile, /*@returned@*/ char *result,
5055 char *in, char *limit, int handle_escapes)
5075 /*@switchbreak@*/ break;
5079 char *bpc = (char *) in;
5080 int i = (char) cppReader_parseEscape (pfile, &bpc);
5083 *result++ = (char) c;
5084 /*@switchbreak@*/ break;
5098 * interpret #line command. Remembers previously seen fnames
5099 * in its very own hash table.
5102 /*@constant int FNAME_HASHSIZE@*/
5103 #define FNAME_HASHSIZE 37
5106 do_line (cppReader *pfile, /*@unused@*/ struct directive *keyword)
5108 cppBuffer *ip = cppReader_getBuffer (pfile);
5110 size_t old_written = cpplib_getWritten (pfile);
5111 enum file_change_code file_change = same_file;
5112 enum cpp_token token;
5114 llassert (ip != NULL);
5115 token = get_directive_token (pfile);
5117 if (token != CPP_NUMBER
5118 || !isdigit(pfile->token_buffer[old_written]))
5120 cppReader_errorLit (pfile,
5121 cstring_makeLiteralTemp ("invalid format `#line' command"));
5123 goto bad_line_directive;
5126 /* The Newline at the end of this line remains to be processed.
5127 To put the next line at the specified line number,
5128 we must store a line number now that is one less. */
5129 new_lineno = atoi (pfile->token_buffer + old_written) - 1;
5130 cppReader_setWritten (pfile, old_written);
5132 /* NEW_LINENO is one less than the actual line number here. */
5133 if (cppReader_isPedantic (pfile) && new_lineno < 0)
5134 cppReader_pedwarnLit (pfile,
5135 cstring_makeLiteralTemp ("line number out of range in `#line' command"));
5137 token = get_directive_token (pfile);
5139 if (token == CPP_STRING) {
5140 char *fname = pfile->token_buffer + old_written;
5142 static hashNode fname_table[FNAME_HASHSIZE];
5144 hashNode *hash_bucket;
5147 size_t fname_length;
5149 /* Turn the file name, which is a character string literal,
5150 into a null-terminated string. Do this in place. */
5151 end_name = convert_string (pfile, fname, fname, cpplib_getPWritten (pfile), 1);
5152 if (end_name == NULL)
5154 cppReader_errorLit (pfile,
5155 cstring_makeLiteralTemp ("invalid format `#line' command"));
5156 goto bad_line_directive;
5159 fname_length = size_fromInt (end_name - fname);
5160 num_start = cpplib_getWritten (pfile);
5162 token = get_directive_token (pfile);
5163 if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP) {
5164 p = pfile->token_buffer + num_start;
5165 if (cppReader_isPedantic (pfile))
5166 cppReader_pedwarnLit (pfile,
5167 cstring_makeLiteralTemp ("garbage at end of `#line' command"));
5169 if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
5171 cppReader_errorLit (pfile,
5172 cstring_makeLiteralTemp ("invalid format `#line' command"));
5173 goto bad_line_directive;
5176 file_change = enter_file;
5178 file_change = leave_file;
5180 ip->system_header_p = 1;
5181 else /* if (*p == 4) */
5182 ip->system_header_p = 2;
5184 cppReader_setWritten (pfile, num_start);
5185 token = get_directive_token (pfile);
5186 p = pfile->token_buffer + num_start;
5187 if (token == CPP_NUMBER && p[1] == '\0' && (*p == '3' || *p== '4')) {
5188 ip->system_header_p = *p == 3 ? 1 : 2;
5189 token = get_directive_token (pfile);
5191 if (token != CPP_VSPACE) {
5192 cppReader_errorLit (pfile,
5193 cstring_makeLiteralTemp ("invalid format `#line' command"));
5195 goto bad_line_directive;
5200 &fname_table[cpphash_hashCode (fname, fname_length, FNAME_HASHSIZE)];
5202 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
5204 if (hp->length == fname_length)
5206 llassert (hp->value.cpval != NULL);
5208 if (strncmp (hp->value.cpval, fname, fname_length) == 0)
5210 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
5217 /* Didn't find it; cons up a new one. */
5218 hp = (hashNode) dmalloc (sizeof (*hp));
5221 hp->bucket_hdr = NULL;
5223 hp->name = cstring_undefined;
5224 hp->next = *hash_bucket;
5228 hp->length = fname_length;
5229 hp->value.cpval = dmalloc (sizeof (*hp->value.cpval) * (fname_length + 1));
5230 memcpy (hp->value.cpval, fname, fname_length);
5231 hp->value.cpval[fname_length] = '\0';
5232 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
5235 else if (token != CPP_VSPACE && token != CPP_EOF)
5237 cppReader_errorLit (pfile,
5238 cstring_makeLiteralTemp ("invalid format `#line' command"));
5239 goto bad_line_directive;
5246 ip->lineno = new_lineno;
5248 cppReader_skipRestOfLine (pfile);
5249 cppReader_setWritten (pfile, old_written);
5250 output_line_command (pfile, 0, file_change);
5255 * remove the definition of a symbol from the symbol table.
5256 * according to un*x /lib/cpp, it is not an error to undef
5257 * something that has no definitions, so it isn't one here either.
5261 do_undef (cppReader *pfile, struct directive *keyword, char *buf, char *limit)
5266 char *orig_buf = buf;
5268 SKIP_WHITE_SPACE (buf);
5270 sym_length = cppReader_checkMacroName (pfile, buf, cstring_makeLiteralTemp ("macro"));
5272 while ((hp = cpphash_lookup (buf, size_toInt (sym_length), -1)) != NULL)
5274 /* If we are generating additional info for debugging (with -g) we
5275 need to pass through all effective #undef commands. */
5276 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
5278 pass_thru_directive (orig_buf, limit, pfile, keyword);
5281 if (hp->type != T_MACRO)
5283 cppReader_warning (pfile,
5284 message ("Undefining preprocessor builtin: %s",
5288 cppReader_deleteMacro (hp);
5291 if (cppReader_isPedantic (pfile)) {
5293 SKIP_WHITE_SPACE (buf);
5296 cppReader_pedwarnLit (pfile,
5297 cstring_makeLiteralTemp ("garbage after `#undef' directive"));
5306 * Report an error detected by the program we are processing.
5307 * Use the text of the line in the error message.
5308 * (We use error because it prints the filename & line#.)
5312 do_error (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5313 char *buf, char *limit)
5315 size_t length = size_fromInt (limit - buf);
5316 cstring copy = cstring_copyLength (buf, length);
5317 cstring adv = cstring_advanceWhiteSpace (copy);
5319 cppReader_error (pfile, message ("#error %s", adv));
5320 cstring_free (copy);
5325 * Report a warning detected by the program we are processing.
5326 * Use the text of the line in the warning message, then continue.
5327 * (We use error because it prints the filename & line#.)
5331 do_warning (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5332 char *buf, char *limit)
5334 size_t length = size_fromInt (limit - buf);
5335 cstring copy = cstring_copyLength (buf, length);
5336 cstring adv = cstring_advanceWhiteSpace (copy);
5337 cppReader_warning (pfile, message ("#warning %s", adv));
5338 cstring_free (copy);
5343 /* #ident has already been copied to the output file, so just ignore it. */
5346 do_ident (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5347 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5349 /* Allow #ident in system headers, since that's not user's fault. */
5350 if (cppReader_isPedantic (pfile)
5351 && !cppReader_getBufferSafe (pfile)->system_header_p)
5352 cppReader_pedwarnLit (pfile,
5353 cstring_makeLiteralTemp ("ANSI C does not allow `#ident'"));
5355 /* Leave rest of line to be read by later calls to cpplib_getToken. */
5360 /* #pragma and its argument line have already been copied to the output file.
5361 Just check for some recognized pragmas that need validation here. */
5364 do_pragma (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5365 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5367 while (*buf == ' ' || *buf == '\t')
5372 if (!strncmp (buf, "implementation", 14)) {
5373 /* Be quiet about `#pragma implementation' for a file only if it hasn't
5374 been included yet. */
5375 struct file_name_list *ptr;
5376 char *p = buf + 14, *fname, *inc_fname;
5378 SKIP_WHITE_SPACE (p);
5379 if (*p == '\n' || *p != '\"')
5383 p = (char *) strchr (fname, '\"');
5384 fname_len = p != NULL ? size_fromInt (p - fname) : mstring_length (fname);
5386 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
5388 inc_fname = (char *) strrchr (cstring_toCharsSafe (ptr->fname), CONNECTCHAR);
5389 inc_fname = (inc_fname != NULL)
5390 ? inc_fname + 1 : cstring_toCharsSafe (ptr->fname);
5392 if ((inc_fname != NULL)
5393 && (strncmp (inc_fname, fname, fname_len) == 0))
5395 cpp_setLocation (pfile);
5397 ppllerror (message ("`#pragma implementation' for `%s' appears "
5398 "after file is included",
5399 cstring_fromChars (fname)));
5408 * handle #if command by
5409 * 1) inserting special `defined' keyword into the hash table
5410 * that gets turned into 0 or 1 by special_symbol (thus,
5411 * if the luser has a symbol called `defined' already, it won't
5412 * work inside the #if command)
5413 * 2) rescan the input into a temporary output buffer
5414 * 3) pass the output buffer to the yacc parser and collect a value
5415 * 4) clean up the mess left from steps 1 and 2.
5416 * 5) call conditional_skip to skip til the next #endif (etc.),
5417 * or not, depending on the value from step 3.
5421 do_if (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5422 char *buf, char *limit)
5424 HOST_WIDE_INT value;
5425 DPRINTF (("Do if: %s", buf));
5426 value = eval_if_expression (pfile, buf, limit - buf);
5427 conditional_skip (pfile, value == 0, T_IF, NULL);
5432 * handle a #elif directive by not changing if_stack either.
5433 * see the comment above do_else.
5436 static int do_elif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5437 char *buf, char *limit)
5439 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5441 cppReader_errorLit (pfile,
5442 cstring_makeLiteralTemp ("Preprocessor command #elif is not within a conditional"));
5447 llassert (pfile->if_stack != NULL);
5449 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
5451 cppReader_errorLit (pfile,
5452 cstring_makeLiteralTemp ("`#elif' after `#else'"));
5454 if (pfile->if_stack->fname != NULL
5455 && cppReader_getBufferSafe (pfile)->fname != NULL
5456 && !cstring_equal (pfile->if_stack->fname,
5457 cppReader_getBufferSafe (pfile)->nominal_fname))
5458 fprintf (stderr, ", file %s", cstring_toCharsSafe (pfile->if_stack->fname));
5459 fprintf (stderr, ")\n");
5461 pfile->if_stack->type = T_ELIF;
5464 if (pfile->if_stack->if_succeeded)
5466 skip_if_group (pfile, 0);
5470 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
5472 skip_if_group (pfile, 0);
5475 ++pfile->if_stack->if_succeeded; /* continue processing input */
5476 output_line_command (pfile, 1, same_file);
5484 * evaluate a #if expression in BUF, of length LENGTH,
5485 * then parse the result as a C expression and return the value as an int.
5488 static HOST_WIDE_INT
5489 eval_if_expression (cppReader *pfile,
5490 /*@unused@*/ char *buf,
5491 /*@unused@*/ int length)
5493 hashNode save_defined;
5494 HOST_WIDE_INT value;
5495 size_t old_written = cpplib_getWritten (pfile);
5497 DPRINTF (("Saving defined..."));
5498 save_defined = cpphash_install ("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
5499 pfile->pcp_inside_if = 1;
5501 value = cppReader_parseExpression (pfile);
5502 pfile->pcp_inside_if = 0;
5504 /* Clean up special symbol */
5505 DPRINTF (("Removing defined..."));
5506 cppReader_deleteMacro (save_defined);
5507 cppReader_setWritten (pfile, old_written); /* Pop */
5513 * routine to handle ifdef/ifndef. Try to look up the symbol,
5514 * then do or don't skip to the #endif/#else/#elif depending
5515 * on what directive is actually being processed.
5519 do_xifdef (cppReader *pfile, struct directive *keyword,
5520 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
5523 cppBuffer *ip = cppReader_getBufferSafe (pfile);
5525 size_t ident_length;
5526 enum cpp_token token;
5527 int start_of_file = 0;
5528 char *control_macro = 0;
5529 size_t old_written = cpplib_getWritten (pfile);
5531 DPRINTF (("do xifdef: %d",
5532 keyword->type == T_IFNDEF));
5534 /* Detect a #ifndef at start of file (not counting comments). */
5535 if (cstring_isDefined (ip->fname) && keyword->type == T_IFNDEF)
5537 start_of_file = pfile->only_seen_white == 2;
5540 pfile->no_macro_expand++;
5541 token = get_directive_token (pfile);
5542 pfile->no_macro_expand--;
5544 ident = pfile->token_buffer + old_written;
5545 DPRINTF (("Ident: %s", ident));
5547 ident_length = cpplib_getWritten (pfile) - old_written;
5548 cppReader_setWritten (pfile, old_written); /* Pop */
5550 if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
5552 skip = (keyword->type == T_IFDEF);
5553 if (! cppReader_isTraditional (pfile))
5555 cppReader_pedwarn (pfile,
5556 message ("`#%s' with no argument", keyword->name));
5559 else if (token == CPP_NAME)
5561 hashNode hp = cpphash_lookup (ident, size_toInt (ident_length), -1);
5563 skip = (keyword->type == T_IFDEF) ? (hp == NULL) : (hp != NULL);
5565 DPRINTF (("hp null: %d / %d / %d", hp == NULL, keyword->type == T_IFNDEF, skip));
5567 if (start_of_file && !skip)
5569 DPRINTF (("Not skipping!"));
5570 control_macro = (char *) dmalloc (ident_length + 1);
5571 memcpy (control_macro, ident, ident_length + 1);
5576 skip = (keyword->type == T_IFDEF);
5577 if (! cppReader_isTraditional (pfile))
5579 cppReader_error (pfile,
5580 message ("`#%s' with invalid argument", keyword->name));
5584 if (!cppReader_isTraditional (pfile))
5587 cppSkipHspace (pfile);
5588 c = cppReader_peekC (pfile);
5589 if (c != EOF && c != '\n')
5591 cppReader_pedwarn (pfile,
5592 message ("garbage at end of `#%s' argument", keyword->name));
5596 cppReader_skipRestOfLine (pfile);
5598 DPRINTF (("Conditional skip: %d", skip));
5599 conditional_skip (pfile, skip, T_IF, control_macro);
5603 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
5604 If this is a #ifndef starting at the beginning of a file,
5605 CONTROL_MACRO is the macro name tested by the #ifndef.
5606 Otherwise, CONTROL_MACRO is 0. */
5609 conditional_skip (cppReader *pfile, int skip,
5610 enum node_type type,
5611 /*@dependent@*/ char *control_macro)
5613 cppIfStackFrame *temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
5615 temp->fname = cppReader_getBufferSafe (pfile)->nominal_fname;
5616 temp->next = pfile->if_stack;
5617 temp->control_macro = control_macro;
5619 temp->if_succeeded = 0;
5621 pfile->if_stack = temp;
5622 pfile->if_stack->type = type;
5626 skip_if_group (pfile, 0);
5631 ++pfile->if_stack->if_succeeded;
5632 output_line_command (pfile, 1, same_file);
5637 * skip to #endif, #else, or #elif. adjust line numbers, etc.
5638 * leaves input ptr at the sharp sign found.
5639 * If ANY is nonzero, return at next directive of any sort.
5643 skip_if_group (cppReader *pfile, int any)
5646 struct directive *kt;
5647 cppIfStackFrame *save_if_stack = pfile->if_stack; /* don't pop past here */
5648 register int ident_length;
5650 struct parse_marker line_start_mark;
5652 parseSetMark (&line_start_mark, pfile);
5654 if (CPPOPTIONS (pfile)->output_conditionals) {
5655 static char failed[] = "#failed\n";
5656 cppReader_puts (pfile, failed, sizeof(failed)-1);
5658 output_line_command (pfile, 1, same_file);
5662 if (CPPOPTIONS (pfile)->output_conditionals)
5664 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
5667 llassert (pbuf->buf != NULL);
5669 start_line = pbuf->buf + line_start_mark.position;
5670 cppReader_puts (pfile, start_line, size_fromInt (pbuf->cur - start_line));
5673 parseMoveMark (&line_start_mark, pfile);
5675 if (!cppReader_isTraditional (pfile))
5677 cppSkipHspace (pfile);
5680 c = cppReader_getC (pfile);
5683 size_t old_written = cpplib_getWritten (pfile);
5684 cppSkipHspace (pfile);
5686 parse_name (pfile, cppReader_getC (pfile));
5687 ident_length = size_toInt (cpplib_getWritten (pfile) - old_written);
5688 ident = pfile->token_buffer + old_written;
5689 pfile->limit = ident;
5691 for (kt = directive_table; kt->length >= 0; kt++)
5693 cppIfStackFrame *temp;
5694 if (ident_length == kt->length
5695 && cstring_equalPrefix (kt->name, cstring_fromChars (ident)))
5697 /* If we are asked to return on next directive, do so now. */
5708 temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
5709 temp->next = pfile->if_stack;
5710 temp->fname = cppReader_getBufferSafe (pfile)->nominal_fname;
5711 temp->type = kt->type;
5713 temp->if_succeeded = 0;
5714 temp->control_macro = NULL;
5716 pfile->if_stack = temp;
5717 /*@switchbreak@*/ break;
5720 if (cppReader_isPedantic (pfile) && pfile->if_stack != save_if_stack)
5721 validate_else (pfile,
5722 cstring_makeLiteralTemp (kt->type == T_ELSE ? "#else" : "#endif"));
5725 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5727 cppReader_error (pfile,
5728 message ("Preprocessor command #%s is not within a conditional", kt->name));
5729 /*@switchbreak@*/ break;
5731 else if (pfile->if_stack == save_if_stack)
5733 goto done; /* found what we came for */
5740 if (kt->type != T_ENDIF)
5742 llassert (pfile->if_stack != NULL);
5744 if (pfile->if_stack->type == T_ELSE)
5746 cppReader_errorLit (pfile,
5747 cstring_makeLiteralTemp ("`#else' or `#elif' after `#else'"));
5750 pfile->if_stack->type = kt->type;
5751 /*@switchbreak@*/ break;
5754 temp = pfile->if_stack;
5755 llassert (temp != NULL);
5756 pfile->if_stack = temp->next;
5758 /*@switchbreak@*/ break;
5761 #if defined (OS2) && defined (__IBMC__)
5762 /* Dummy code to eleminate optimization problems with icc */
5771 /* Don't let erroneous code go by. */
5773 if (kt->length < 0 && !CPPOPTIONS (pfile)->lang_asm
5774 && cppReader_isPedantic (pfile))
5776 cppReader_pedwarnLit (pfile,
5777 cstring_makeLiteralTemp ("Invalid preprocessor directive name"));
5781 c = cppReader_getC (pfile);
5783 /* We're in the middle of a line. Skip the rest of it. */
5791 case '/': /* possible comment */
5792 c = skip_comment (pfile, NULL);
5795 /*@switchbreak@*/ break;
5798 cppReader_forward (pfile, -1);
5799 old = cpplib_getWritten (pfile);
5800 (void) cpplib_getToken (pfile);
5801 cppReader_setWritten (pfile, old);
5802 /*@switchbreak@*/ break;
5804 /* Char after backslash loses its special meaning. */
5805 if (cppReader_peekC (pfile) == '\n')
5807 cppReader_forward (pfile, 1);
5810 /*@switchbreak@*/ break;
5814 c = cppReader_getC (pfile);
5817 if (CPPOPTIONS (pfile)->output_conditionals) {
5818 static char end_failed[] = "#endfailed\n";
5819 cppReader_puts (pfile, end_failed, sizeof(end_failed)-1);
5822 pfile->only_seen_white = 1;
5824 parseGotoMark (&line_start_mark, pfile);
5825 parseClearMark (&line_start_mark);
5829 * handle a #else directive. Do this by just continuing processing
5830 * without changing if_stack ; this is so that the error message
5831 * for missing #endif's etc. will point to the original #if. It
5832 * is possible that something different would be better.
5836 do_else (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5837 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5839 if (cppReader_isPedantic (pfile))
5841 validate_else (pfile, cstring_makeLiteralTemp ("#else"));
5844 cppReader_skipRestOfLine (pfile);
5846 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack) {
5847 cppReader_errorLit (pfile,
5848 cstring_makeLiteralTemp ("Preprocessor command #else is not within a conditional"));
5851 /* #ifndef can't have its special treatment for containing the whole file
5852 if it has a #else clause. */
5854 llassert (pfile->if_stack != NULL);
5856 pfile->if_stack->control_macro = 0;
5858 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
5860 cpp_setLocation (pfile);
5861 genppllerrorhint (FLG_PREPROC,
5862 message ("Pre-processor directive #else after #else"),
5863 message ("%q: Location of match",
5864 fileloc_unparseRaw (pfile->if_stack->fname,
5865 pfile->if_stack->lineno)));
5868 pfile->if_stack->type = T_ELSE;
5871 if (pfile->if_stack->if_succeeded)
5872 skip_if_group (pfile, 0);
5874 ++pfile->if_stack->if_succeeded; /* continue processing input */
5875 output_line_command (pfile, 1, same_file);
5882 * unstack after #endif command
5886 do_endif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5887 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5889 if (cppReader_isPedantic (pfile))
5891 validate_else (pfile, cstring_makeLiteralTemp ("#endif"));
5894 cppReader_skipRestOfLine (pfile);
5896 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5898 cppReader_errorLit (pfile, cstring_makeLiteralTemp ("Unbalanced #endif"));
5902 cppIfStackFrame *temp = pfile->if_stack;
5904 llassert (temp != NULL);
5906 pfile->if_stack = temp->next;
5907 if (temp->control_macro != 0)
5909 /* This #endif matched a #ifndef at the start of the file.
5910 See if it is at the end of the file. */
5911 struct parse_marker start_mark;
5914 parseSetMark (&start_mark, pfile);
5918 cppSkipHspace (pfile);
5919 c = cppReader_getC (pfile);
5925 parseGotoMark (&start_mark, pfile);
5926 parseClearMark (&start_mark);
5930 /* If we get here, this #endif ends a #ifndef
5931 that contains all of the file (aside from whitespace).
5932 Arrange not to include the file again
5933 if the macro that was tested is defined.
5935 Do not do this for the top-level file in a -include or any
5936 file in a -imacros. */
5937 struct file_name_list *ifile = pfile->all_include_files;
5939 for ( ; ifile != NULL; ifile = ifile->next)
5941 if (cstring_equal (ifile->fname, cppReader_getBufferSafe (pfile)->fname))
5943 ifile->control_macro = temp->control_macro;
5951 output_line_command (pfile, 1, same_file);
5956 /* When an #else or #endif is found while skipping failed conditional,
5957 if -pedantic was specified, this is called to warn about text after
5958 the command name. P points to the first char after the command name. */
5961 validate_else (cppReader *pfile, cstring directive)
5964 cppSkipHspace (pfile);
5965 c = cppReader_peekC (pfile);
5966 if (c != EOF && c != '\n')
5968 cppReader_pedwarn (pfile,
5969 message ("text following `%s' violates ANSI standard", directive));
5974 ** Get the next token, and add it to the text in pfile->token_buffer.
5975 ** Return the kind of token we got.
5979 cpplib_getToken (cppReader *pfile)
5981 return cpplib_getTokenAux (pfile, FALSE);
5985 cpplib_getTokenForceExpand (cppReader *pfile)
5987 return cpplib_getTokenAux (pfile, TRUE);
5991 cpplib_getTokenAux (cppReader *pfile, bool forceExpand)
5994 size_t old_written = 0;
5995 int start_line, start_column;
5996 enum cpp_token token;
5997 struct cppOptions *opts = CPPOPTIONS (pfile);
5998 cppReader_getBufferSafe (pfile)->prev = cppReader_getBufferSafe (pfile)->cur;
6001 c = cppReader_getC (pfile);
6002 DPRINTF (("Get next token: %c", c));
6007 if (cppReader_getBufferSafe (pfile)->seen_eof)
6009 cppBuffer *buf = cppReader_popBuffer (pfile);
6011 if (buf != cppReader_nullBuffer (pfile))
6022 cppBuffer *next_buf = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6023 cppReader_getBufferSafe (pfile)->seen_eof = 1;
6025 if (cstring_isDefined (cppReader_getBufferSafe (pfile)->nominal_fname)
6026 && next_buf != cppReader_nullBuffer (pfile))
6028 /* We're about to return from an #include file.
6029 Emit #line information now (as part of the CPP_POP) result.
6030 But the #line refers to the file we will pop to. */
6031 cppBuffer *cur_buffer = CPPBUFFER (pfile);
6032 CPPBUFFER (pfile) = next_buf;
6033 pfile->input_stack_listing_current = 0;
6034 output_line_command (pfile, 0, leave_file);
6035 CPPBUFFER (pfile) = cur_buffer;
6043 struct parse_marker start_mark;
6048 if (cppReader_peekC (pfile) == '=')
6053 if (opts->put_out_comments)
6055 parseSetMark (&start_mark, pfile);
6059 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile),
6060 &start_line, &start_column);
6061 c = skip_comment (pfile, &newlines);
6062 DPRINTF (("c = %c", c));
6063 if (opts->put_out_comments && (c == '/' || c == EOF))
6065 assertSet (&start_mark);
6066 parseClearMark (&start_mark);
6073 cppReader_errorWithLine (pfile, start_line, start_column,
6074 cstring_makeLiteral ("Unterminated comment"));
6077 c = '/'; /* Initial letter of comment. */
6079 /* Comments are equivalent to spaces.
6080 For -traditional, a comment is equivalent to nothing. */
6082 if (opts->put_out_comments)
6086 assertSet (&start_mark);
6087 res = cpp_handleComment (pfile, &start_mark);
6088 pfile->lineno += newlines;
6091 else if (cppReader_isTraditional (pfile))
6097 cpplib_reserve(pfile, 1);
6098 cppReader_putCharQ (pfile, ' ');
6103 if (!pfile->only_seen_white)
6108 if (cppReader_handleDirective (pfile))
6110 return CPP_DIRECTIVE;
6113 pfile->only_seen_white = 0;
6118 /* A single quoted string is treated like a double -- some
6119 programs (e.g., troff) are perverse this way */
6120 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile),
6121 &start_line, &start_column);
6122 old_written = cpplib_getWritten (pfile);
6124 DPRINTF (("Reading string: %c", c));
6125 cppReader_putChar (pfile, c);
6129 ** Because of ISO8859-1 characters in string literals, we need a special test here.
6132 if (cppReader_reachedEOF (pfile))
6135 DPRINTF (("Matches EOF!"));
6136 if (cppBuffer_isMacro (CPPBUFFER (pfile)))
6138 /* try harder: this string crosses a macro expansion
6139 boundary. This can happen naturally if -traditional.
6140 Otherwise, only -D can make a macro with an unmatched
6143 = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6144 (*cppReader_getBufferSafe (pfile)->cleanup)
6145 (cppReader_getBufferSafe (pfile), pfile);
6146 CPPBUFFER (pfile) = next_buf;
6150 if (!cppReader_isTraditional (pfile))
6152 cpp_setLocation (pfile);
6154 setLine (long_toInt (start_line));
6155 setColumn (long_toInt (start_column));
6157 if (pfile->multiline_string_line != long_toInt (start_line)
6158 && pfile->multiline_string_line != 0)
6162 message ("Unterminated string or character constant"),
6163 message ("%q: Possible real start of unterminated constant",
6165 (fileloc_filename (g_currentloc),
6166 pfile->multiline_string_line)));
6167 pfile->multiline_string_line = 0;
6173 message ("Unterminated string or character constant"));
6176 /*@loopbreak@*/ break;
6180 int cc = cppReader_getC (pfile);
6181 DPRINTF (("cc: %c [%d] [%d]", cc, cc, EOF));
6182 DPRINTF (("putting char: %c", cc));
6183 cppReader_putChar (pfile, cc);
6187 /* Traditionally, end of line ends a string constant with
6188 no error. So exit the loop and record the new line. */
6189 if (cppReader_isTraditional (pfile))
6195 if (cppReader_isPedantic (pfile)
6196 && pfile->multiline_string_line == 0)
6198 cppReader_pedwarnWithLine
6199 (pfile, long_toInt (start_line),
6200 long_toInt (start_column),
6201 cstring_makeLiteral ("String constant runs past end of line"));
6203 if (pfile->multiline_string_line == 0)
6205 pfile->multiline_string_line = start_line;
6208 /*@switchbreak@*/ break;
6211 cc = cppReader_getC (pfile);
6214 /* Backslash newline is replaced by nothing at all. */
6215 pfile->lineno++; /* 2003-11-03: AMiller suggested adding this, but
6216 its not clear why it is needed. */
6217 cppReader_adjustWritten (pfile, -1);
6222 /* ANSI stupidly requires that in \\ the second \
6223 is *not* prevented from combining with a newline. */
6226 cppReader_putChar (pfile, cc);
6228 /*@switchbreak@*/ break;
6234 /*@switchbreak@*/ break;
6239 pfile->lineno += count_newlines (pfile->token_buffer + old_written,
6240 cpplib_getPWritten (pfile));
6241 pfile->only_seen_white = 0;
6242 return c == '\'' ? CPP_CHAR : CPP_STRING;
6245 if (!opts->dollars_in_ident)
6250 if (opts->cplusplus && cppReader_peekC (pfile) == ':')
6258 c2 = cppReader_peekC (pfile);
6259 if (c2 == c || c2 == '=')
6269 if (cppReader_peekC (pfile) == '=')
6275 c2 = cppReader_peekC (pfile);
6276 if (c2 == '-' && opts->chill)
6278 /* Chill style comment */
6279 if (opts->put_out_comments)
6281 parseSetMark (&start_mark, pfile);
6284 cppReader_forward (pfile, 1); /* Skip second '-'. */
6288 c = cppReader_getC (pfile);
6290 /*@loopbreak@*/ break;
6293 /* Don't consider final '\n' to be part of comment. */
6294 cppReader_forward (pfile, -1);
6295 /*@loopbreak@*/ break;
6299 goto return_comment;
6301 if (c2 == '-' || c2 == '=' || c2 == '>')
6306 if (pfile->parsing_include_directive)
6310 cppReader_putChar (pfile, c);
6312 /*@loopbreak@*/ break;
6313 c = cppReader_getC (pfile);
6315 if (c == '\n' || c == EOF)
6317 cppReader_errorLit (pfile,
6318 cstring_makeLiteralTemp ("Missing '>' in \"#include <FILENAME>\""));
6319 /*@loopbreak@*/ break;
6327 c2 = cppReader_peekC (pfile);
6332 cppReader_forward (pfile, 1);
6333 cpplib_reserve (pfile, 4);
6334 cppReader_putChar (pfile, c);
6335 cppReader_putChar (pfile, c2);
6337 c3 = cppReader_peekC (pfile);
6339 cppReader_putCharQ (pfile, cppReader_getC (pfile));
6340 cppReader_nullTerminateQ (pfile);
6341 pfile->only_seen_white = 0;
6345 DPRINTF (("Macro @!"));
6346 if (cppReader_getBufferSafe (pfile)->has_escapes)
6348 c = cppReader_getC (pfile);
6349 DPRINTF (("got c: %c", c));
6352 if (pfile->output_escapes)
6353 cppReader_puts (pfile, "@-", 2);
6354 parse_name (pfile, cppReader_getC (pfile));
6357 else if (is_space [c])
6359 cpplib_reserve (pfile, 2);
6360 if (pfile->output_escapes)
6361 cppReader_putCharQ (pfile, '@');
6362 cppReader_putCharQ (pfile, c);
6370 if (pfile->output_escapes)
6372 cppReader_puts (pfile, "@@", 2);
6378 c2 = cppReader_peekC (pfile);
6381 cpplib_reserve(pfile, 2);
6382 cppReader_putCharQ (pfile, '.');
6383 c = cppReader_getC (pfile);
6387 /* FIXME - misses the case "..\\\n." */
6388 if (c2 == '.' && cpp_peekN (pfile, 1) == '.')
6390 cpplib_reserve(pfile, 4);
6391 cppReader_putCharQ (pfile, '.');
6392 cppReader_putCharQ (pfile, '.');
6393 cppReader_putCharQ (pfile, '.');
6394 cppReader_forward (pfile, 2);
6395 cppReader_nullTerminateQ (pfile);
6396 pfile->only_seen_white = 0;
6402 pfile->only_seen_white = 0;
6403 op2any: /* jumped to for \ continuations */
6404 cpplib_reserve(pfile, 3);
6405 cppReader_putCharQ (pfile, c);
6407 /* evans 2003-08-24: This is a hack to fix line output for \
6408 continuations. Someday I really should get a decent pre-processor!
6412 (void) cppReader_getC (pfile); /* skip the newline to avoid extra lines */
6414 cppReader_putCharQ (pfile, cppReader_getC (pfile));
6417 cppReader_nullTerminateQ (pfile);
6422 c2 = cppReader_peekC (pfile);
6423 if ((c2 == '\'' || c2 == '\"') && !cppReader_isTraditional (pfile))
6425 cppReader_putChar (pfile, c);
6426 c = cppReader_getC (pfile);
6431 case '0': case '1': case '2': case '3': case '4':
6432 case '5': case '6': case '7': case '8': case '9':
6437 cpplib_reserve (pfile, 2);
6438 cppReader_putCharQ (pfile, c);
6440 c = cppReader_peekC (pfile);
6442 /*@loopbreak@*/ break;
6443 if (!is_idchar[c] && c != '.'
6444 && ((c2 != 'e' && c2 != 'E'
6445 && ((c2 != 'p' && c2 != 'P') || cppReader_isC89 (pfile)))
6446 || (c != '+' && c != '-')))
6447 /*@loopbreak@*/ break;
6448 cppReader_forward (pfile, 1);
6452 cppReader_nullTerminateQ (pfile);
6453 pfile->only_seen_white = 0;
6456 case 'b': case 'c': case 'd': case 'h': case 'o':
6457 case 'B': case 'C': case 'D': case 'H': case 'O':
6458 if (opts->chill && cppReader_peekC (pfile) == '\'')
6460 pfile->only_seen_white = 0;
6461 cpplib_reserve (pfile, 2);
6462 cppReader_putCharQ (pfile, c);
6463 cppReader_putCharQ (pfile, '\'');
6464 cppReader_forward (pfile, 1);
6467 c = cppReader_getC (pfile);
6469 goto chill_number_eof;
6472 if (c == '\\' && cppReader_peekC (pfile) == '\n')
6474 cppReader_forward (pfile, 2);
6477 /*@loopbreak@*/ break;
6479 cppReader_putChar (pfile, c);
6483 cpplib_reserve (pfile, 2);
6484 cppReader_putCharQ (pfile, c);
6485 cppReader_nullTerminateQ (pfile);
6490 cppReader_forward (pfile, -1);
6492 cppReader_nullTerminate (pfile);
6499 case 'a': case 'e': case 'f': case 'g': case 'i': case 'j':
6500 case 'k': case 'l': case 'm': case 'n': case 'p': case 'q':
6501 case 'r': case 's': case 't': case 'u': case 'v': case 'w':
6502 case 'x': case 'y': case 'z':
6503 case 'A': case 'E': case 'F': case 'G': case 'I': case 'J':
6504 case 'K': case 'M': case 'N': case 'P': case 'Q': case 'R':
6505 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
6511 size_t before_name_written = cpplib_getWritten (pfile);
6513 parse_name (pfile, c);
6514 pfile->only_seen_white = 0;
6516 if (pfile->no_macro_expand)
6518 DPRINTF (("Not expanding: %s", pfile->token_buffer));
6522 ident = pfile->token_buffer + before_name_written;
6523 DPRINTF (("Ident: %s", ident));
6525 ident_len = size_fromInt ((cpplib_getPWritten (pfile)) - ident);
6527 hp = cpphash_lookupExpand (ident, size_toInt (ident_len), -1, forceExpand);
6531 DPRINTF (("No expand: %s %d", ident, ident_len));
6535 if (hp->type == T_DISABLED)
6537 DPRINTF (("Disabled!"));
6539 if (pfile->output_escapes)
6540 { /* Return "@-IDENT", followed by '\0'. */
6542 cpplib_reserve (pfile, 3);
6543 ident = pfile->token_buffer + before_name_written;
6544 cppReader_adjustWritten (pfile, 2);
6546 for (i = size_toInt (ident_len); i >= 0; i--)
6548 ident[i+2] = ident[i];
6558 ** If macro wants an arglist, verify that a '(' follows.
6559 ** first skip all whitespace, copying it to the output
6560 ** after the macro name. Then, if there is no '(',
6561 ** decide this is not a macro call and leave things that way.
6564 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
6566 struct parse_marker macro_mark;
6569 DPRINTF (("Arglist macro!"));
6572 ** evans 2002-07-03: Moved this here (from below).
6573 ** This bug caused necessary whitespace to be lost
6574 ** when parsing parameterized macros without parameters.
6577 parseSetMark (¯o_mark, pfile);
6579 while (cppBuffer_isMacro (CPPBUFFER (pfile)))
6581 cppBuffer *next_buf;
6582 cppSkipHspace (pfile);
6583 if (cppReader_peekC (pfile) != EOF)
6585 DPRINTF (("Peeking!"));
6586 /*@loopbreak@*/ break;
6589 next_buf = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6590 (*cppReader_getBufferSafe (pfile)->cleanup) (cppReader_getBufferSafe (pfile), pfile);
6591 CPPBUFFER (pfile) = next_buf;
6594 /* parseSetMark (¯o_mark, pfile); */
6598 cppSkipHspace (pfile);
6599 c = cppReader_peekC (pfile);
6600 DPRINTF (("c: %c", c));
6601 is_macro_call = c == '(';
6603 /*@loopbreak@*/ break;
6604 cppReader_forward (pfile, 1);
6609 parseGotoMark (¯o_mark, pfile);
6612 parseClearMark (¯o_mark);
6616 DPRINTF (("not macro call!"));
6621 /* This is now known to be a macro call. */
6623 /* it might not actually be a macro. */
6624 if (hp->type != T_MACRO)
6629 cppReader_setWritten (pfile, before_name_written);
6630 special_symbol (hp, pfile);
6631 xbuf_len = cpplib_getWritten (pfile) - before_name_written;
6632 xbuf = (char *) dmalloc (xbuf_len + 1);
6633 cppReader_setWritten (pfile, before_name_written);
6634 memcpy (xbuf, cpplib_getPWritten (pfile), xbuf_len + 1);
6635 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
6640 ** Expand the macro, reading arguments as needed,
6641 ** and push the expansion on the input stack.
6644 cpplib_macroExpand (pfile, hp);
6645 cppReader_setWritten (pfile, before_name_written);
6648 /* An extra "@ " is added to the end of a macro expansion
6649 to prevent accidental token pasting. We prefer to avoid
6650 unneeded extra spaces (for the sake of cpp-using tools like
6651 imake). Here we remove the space if it is safe to do so. */
6653 llassert (pfile->buffer->rlimit != NULL);
6655 if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
6656 && pfile->buffer->rlimit[-2] == '@'
6657 && pfile->buffer->rlimit[-1] == ' ')
6659 int c1 = pfile->buffer->rlimit[-3];
6660 int cl2 = cpplib_bufPeek (cppBuffer_prevBuffer (CPPBUFFER (pfile)));
6662 if (cl2 == EOF || !unsafe_chars ((char) c1, (char) cl2))
6663 pfile->buffer->rlimit -= 2;
6669 case ' ': case '\t': case '\v': case '\r':
6672 cppReader_putChar (pfile, c);
6673 c = cppReader_peekC (pfile);
6674 if (c == EOF || !is_hor_space[c])
6675 /*@loopbreak@*/ break;
6676 cppReader_forward (pfile, 1);
6681 c2 = cppReader_peekC (pfile);
6682 /* allow other stuff here if a flag is set? */
6683 DPRINTF (("Got continuation!"));
6690 cppReader_putChar (pfile, c);
6691 if (pfile->only_seen_white == 0)
6692 pfile->only_seen_white = 1;
6694 output_line_command (pfile, 1, same_file);
6697 case '(': token = CPP_LPAREN; goto char1;
6698 case ')': token = CPP_RPAREN; goto char1;
6699 case '{': token = CPP_LBRACE; goto char1;
6700 case '}': token = CPP_RBRACE; goto char1;
6701 case ',': token = CPP_COMMA; goto char1;
6702 case ';': token = CPP_SEMICOLON; goto char1;
6708 pfile->only_seen_white = 0;
6709 cppReader_putChar (pfile, c);
6718 /* Parse an identifier starting with C. */
6721 parse_name (cppReader *pfile, int c)
6727 if (c == '\\' && cppReader_peekC (pfile) == '\n')
6729 cppReader_forward (pfile, 2);
6733 cppReader_forward (pfile, -1);
6737 if (c == '$' && cppReader_isPedantic (pfile))
6739 cppReader_pedwarnLit (pfile,
6740 cstring_makeLiteralTemp ("`$' in identifier"));
6743 cpplib_reserve(pfile, 2); /* One more for final NUL. */
6744 cppReader_putCharQ (pfile, c);
6745 c = cppReader_getC (pfile);
6751 cppReader_nullTerminateQ (pfile);
6754 /* The file_name_map structure holds a mapping of file names for a
6755 particular directory. This mapping is read from the file named
6756 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
6757 map filenames on a file system with severe filename restrictions,
6758 such as DOS. The format of the file name map file is just a series
6759 of lines with two tokens on each line. The first token is the name
6760 to map, and the second token is the actual name to use. */
6762 struct file_name_map
6764 struct file_name_map *map_next;
6769 /*@constant observer char *FILE_NAME_MAP_FILE*/
6770 #define FILE_NAME_MAP_FILE "header.gcc"
6772 /* Read a space delimited string of unlimited length from a stdio
6775 static cstring read_filename_string (int ch, /*:open:*/ FILE *f)
6781 set = alloc = dmalloc (len + 1);
6786 while ((ch = getc (f)) != EOF && ! is_space[ch])
6788 if (set - alloc == size_toInt (len))
6791 alloc = drealloc (alloc, len + 1);
6792 set = alloc + len / 2;
6793 /*@-branchstate@*/ }
6796 } /*@=branchstate@*/
6799 check (ungetc (ch, f) != EOF);
6801 return cstring_fromChars (alloc);
6804 /* This structure holds a linked list of file name maps, one per directory. */
6806 struct file_name_map_list
6808 /*@only@*/ struct file_name_map_list *map_list_next;
6809 /*@only@*/ cstring map_list_name;
6810 /*@null@*/ struct file_name_map *map_list_map;
6813 /* Read the file name map file for DIRNAME. */
6815 static struct file_name_map *
6816 read_name_map (cppReader *pfile, cstring dirname)
6818 struct file_name_map_list *map_list_ptr;
6822 for (map_list_ptr = CPPOPTIONS (pfile)->map_list;
6823 map_list_ptr != NULL;
6824 map_list_ptr = map_list_ptr->map_list_next)
6826 if (cstring_equal (map_list_ptr->map_list_name, dirname))
6828 return map_list_ptr->map_list_map;
6832 map_list_ptr = (struct file_name_map_list *) dmalloc (sizeof (*map_list_ptr));
6833 map_list_ptr->map_list_name = cstring_copy (dirname);
6834 map_list_ptr->map_list_map = NULL;
6836 name = cstring_copy (dirname);
6838 if (cstring_length (dirname) > 0)
6840 name = cstring_appendChar (name, CONNECTCHAR);
6843 name = cstring_concatFree1 (name, cstring_makeLiteralTemp (FILE_NAME_MAP_FILE));
6845 f = fileTable_openReadFile (context_fileTable (), name);
6846 cstring_free (name);
6850 map_list_ptr->map_list_map = NULL;
6856 while ((ch = getc (f)) != EOF)
6859 struct file_name_map *ptr;
6866 from = read_filename_string (ch, f);
6867 while ((ch = getc (f)) != EOF && is_hor_space[ch])
6872 to = read_filename_string (ch, f);
6874 ptr = (struct file_name_map *) dmalloc (sizeof (*ptr));
6875 ptr->map_from = from;
6877 /* Make the real filename absolute. */
6878 if (cstring_length (to) > 1
6879 && osd_isConnectChar (cstring_firstChar (to)))
6885 ptr->map_to = cstring_copy (dirname);
6886 ptr->map_to = cstring_appendChar (ptr->map_to, CONNECTCHAR);
6887 ptr->map_to = cstring_concatFree (ptr->map_to, to);
6890 ptr->map_next = map_list_ptr->map_list_map;
6891 map_list_ptr->map_list_map = ptr;
6893 while ((ch = getc (f)) != '\n')
6897 /*@innerbreak@*/ break;
6902 assertSet (map_list_ptr->map_list_map);
6903 check (fileTable_closeFile (context_fileTable (),f) == 0);
6906 map_list_ptr->map_list_next = pfile->opts->map_list;
6907 pfile->opts->map_list = map_list_ptr;
6909 return map_list_ptr->map_list_map;
6912 /* Try to open include file FILENAME. SEARCHPTR is the directory
6913 being tried from the include file search path. This function maps
6914 filenames on file systems based on information read by
6918 open_include_file (cppReader *pfile,
6920 struct file_name_list *searchptr)
6922 char *filename = cstring_toCharsSafe (fname);
6923 struct file_name_map *map;
6927 cstring_markOwned (fname);
6929 cpp_setLocation (pfile);
6931 if (context_getFlag (FLG_NEVERINCLUDE))
6933 if (isHeaderFile (fname))
6935 return SKIP_INCLUDE;
6939 if ((searchptr != NULL) && ! searchptr->got_name_map)
6941 searchptr->name_map = read_name_map (pfile,
6942 !cstring_isEmpty (searchptr->fname)
6943 ? searchptr->fname :
6944 cstring_makeLiteralTemp ("."));
6945 searchptr->got_name_map = 1;
6948 /* First check the mapping for the directory we are using. */
6950 if ((searchptr != NULL)
6951 && (searchptr->name_map != NULL))
6955 if (!cstring_isEmpty (searchptr->fname))
6957 from += cstring_length (searchptr->fname) + 1;
6960 for (map = searchptr->name_map;
6962 map = map->map_next)
6964 if (cstring_equal (map->map_from, cstring_fromChars (from)))
6967 ** Found a match. Check if the file should be skipped
6970 if (cpp_skipIncludeFile (map->map_to))
6972 return SKIP_INCLUDE;
6976 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
6983 ** Try to find a mapping file for the particular directory we are
6984 ** looking in. Thus #include <sys/types.h> will look up sys/types.h
6985 ** in /usr/include/header.gcc and look up types.h in
6986 ** /usr/include/sys/header.gcc.
6989 p = strrchr (filename, CONNECTCHAR);
6996 if ((searchptr != NULL)
6997 && (cstring_isDefined (searchptr->fname))
6998 && (size_toInt (cstring_length (searchptr->fname)) == p - filename)
6999 && !strncmp (cstring_toCharsSafe (searchptr->fname),
7001 size_fromInt (p - filename)))
7003 /* filename is in SEARCHPTR, which we've already checked. */
7005 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
7007 return SKIP_INCLUDE;
7011 return cpp_openIncludeFile (filename);
7017 dir = mstring_copy (".");
7022 dir = (char *) dmalloc (size_fromInt (p - filename + 1));
7023 memcpy (dir, filename, size_fromInt (p - filename));
7024 dir[p - filename] = '\0';
7028 for (map = read_name_map (pfile, cstring_fromChars (dir));
7030 map = map->map_next)
7032 if (cstring_equal (map->map_from, cstring_fromChars (from)))
7036 if (cpp_skipIncludeFile (map->map_to))
7038 return SKIP_INCLUDE;
7042 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
7049 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
7051 return SKIP_INCLUDE;
7055 return cpp_openIncludeFile (filename);
7059 /* Process the contents of include file FNAME, already open on descriptor F,
7061 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
7062 "system" include directories (as decided by the `is_system_include'
7064 DIRPTR is the link in the dir path through which this file was found,
7065 or 0 if the file name was absolute or via the current directory.
7066 Return 1 on success, 0 on failure.
7068 The caller is responsible for the cppReader_pushBuffer. */
7071 finclude (cppReader *pfile, int f,
7073 bool system_header_p,
7074 /*@dependent@*/ struct file_name_list *dirptr)
7080 cppBuffer *fp; /* For input stack frame */
7082 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
7084 cppReader_perrorWithName (pfile, fname);
7085 check (close (f) == 0);
7086 (void) cppReader_popBuffer (pfile);
7092 fp = cppReader_getBufferSafe (pfile);
7094 /*@-temptrans@*/ /* fname shouldn't really be temp */
7095 fp->nominal_fname = fp->fname = fname;
7099 fp->system_header_p = system_header_p;
7102 fp->cleanup = cppReader_fileCleanup;
7104 if (S_ISREG (st_mode))
7107 fp->buf = (char *) dmalloc (st_size + 2);
7108 fp->alimit = fp->buf + st_size + 2;
7111 /* Read the file contents, knowing that st_size is an upper bound
7112 on the number of bytes we can read. */
7113 length = safe_read (f, fp->buf, size_toInt (st_size));
7114 fp->rlimit = fp->buf + length;
7115 if (length < 0) goto nope;
7117 else if (S_ISDIR (st_mode))
7119 cppReader_error (pfile,
7120 message ("Directory specified where file is expected: %s", fname));
7121 check (close (f) == 0);
7127 ** Cannot count its file size before reading.
7128 ** First read the entire file into heap and
7129 ** copy them into buffer on stack.
7132 size_t bsize = 2000;
7137 fp->buf = (char *) dmalloc (bsize + 2);
7140 i = safe_read (f, fp->buf + st_size, size_toInt (bsize - st_size));
7143 goto nope; /* error! */
7146 if (st_size != bsize)
7148 break; /* End of file */
7152 fp->buf = (char *) drealloc (fp->buf, bsize + 2);
7156 length = size_toInt (st_size);
7159 if ((length > 0 && fp->buf[length - 1] != '\n')
7160 /* Backslash-newline at end is not good enough. */
7161 || (length > 1 && fp->buf[length - 2] == '\\')) {
7162 fp->buf[length++] = '\n';
7165 fp->buf[length] = '\0';
7166 fp->rlimit = fp->buf + length;
7168 /* Close descriptor now, so nesting does not use lots of descriptors. */
7169 check (close (f) == 0);
7171 /* Must do this before calling trigraph_pcp, so that the correct file name
7172 will be printed in warning messages. */
7174 pfile->input_stack_listing_current = 0;
7179 cppReader_perrorWithName (pfile, fname);
7180 check (close (f) == 0);
7186 cpplib_init (cppReader *pfile)
7188 memset ((char *) pfile, 0, sizeof (*pfile));
7190 pfile->get_token = cpplib_getToken;
7191 pfile->token_buffer_size = 200;
7192 pfile->token_buffer = (char *) dmalloc (pfile->token_buffer_size);
7193 pfile->all_include_files = NULL;
7197 cppReader_setWritten (pfile, 0);
7199 pfile->system_include_depth = 0;
7200 pfile->max_include_len = 0;
7201 pfile->timebuf = NULL;
7202 pfile->only_seen_white = 1;
7204 pfile->buffer = cppReader_nullBuffer (pfile);
7208 cppReader_finish (/*@unused@*/ cppReader *pfile)
7213 /* Free resources used by PFILE.
7214 This is the cppReader 'finalizer' or 'destructor' (in C++ terminology). */
7217 cppCleanup (/*@special@*/ cppReader *pfile)
7219 /*@releases pfile@*/
7221 DPRINTF (("cppCleanup!"));
7223 while (CPPBUFFER (pfile) != cppReader_nullBuffer (pfile))
7225 (void) cppReader_popBuffer (pfile);
7228 if (pfile->token_buffer != NULL)
7230 sfree (pfile->token_buffer);
7231 pfile->token_buffer = NULL;
7234 while (pfile->if_stack != NULL)
7236 cppIfStackFrame *temp = pfile->if_stack;
7237 pfile->if_stack = temp->next;
7241 while (pfile->all_include_files != NULL)
7243 struct file_name_list *temp = pfile->all_include_files;
7244 pfile->all_include_files = temp->next;
7245 /*@-dependenttrans@*/
7246 cstring_free (temp->fname);
7247 /*@=dependenttrans@*/
7251 /* evans 2002-07-12 */
7252 while (pfile->opts->map_list != NULL)
7254 struct file_name_map_list *temp = pfile->opts->map_list;
7255 pfile->opts->map_list = pfile->opts->map_list->map_list_next;
7256 cstring_free (temp->map_list_name);
7260 while (pfile->opts->include != NULL)
7262 struct file_name_list *temp = pfile->opts->include;
7263 pfile->opts->include = pfile->opts->include->next;
7264 /* cstring_free (temp->fname); */
7268 sfree (pfile->opts);
7270 cppReader_hashCleanup ();
7274 ** Get the file-mode and data size of the file open on FD
7275 ** and store them in *MODE_POINTER and *SIZE_POINTER.
7279 file_size_and_mode (int fd, __mode_t *mode_pointer, size_t *size_pointer)
7283 if (fstat (fd, &sbuf) < 0) {
7286 /*@i2@*/ return (-1); /* Spurious warnings! */
7289 if (mode_pointer != NULL)
7291 *mode_pointer = sbuf.st_mode;
7294 if (size_pointer != NULL)
7296 *size_pointer = (size_t) sbuf.st_size;
7299 /*@i4@*/ return 0; /* spurious warnings here */
7302 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
7303 retrying if necessary. Return a negative value if an error occurs,
7304 otherwise return the actual number of bytes read,
7305 which must be LEN unless end-of-file was reached. */
7307 static int safe_read (int desc, char *ptr, int len)
7313 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
7314 /*@-compdef@*/ /* ptr is an out parameter */
7315 int nchars = _read (desc, ptr, (unsigned) left);
7318 ssize_t nchars = read (desc, ptr, size_fromInt (left));
7327 return (int) nchars;
7341 /* Initialize PMARK to remember the current position of PFILE. */
7344 parseSetMark (struct parse_marker *pmark, cppReader *pfile)
7346 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7348 pmark->next = pbuf->marks;
7350 pbuf->marks = pmark;
7354 pmark->position = pbuf->cur - pbuf->buf;
7355 DPRINTF (("set mark: %d / %s", pmark->position, pbuf->cur));
7358 /* Cleanup PMARK - we no longer need it. */
7360 void parseClearMark (struct parse_marker *pmark)
7362 struct parse_marker **pp = &pmark->buf->marks;
7364 for (; ; pp = &(*pp)->next)
7366 llassert (*pp != NULL);
7367 if (*pp == pmark) break;
7373 /* Backup the current position of PFILE to that saved in PMARK. */
7376 parseGotoMark (struct parse_marker *pmark, cppReader *pfile)
7378 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7380 if (pbuf != pmark->buf)
7382 cpp_setLocation (pfile);
7383 llfatalbug (cstring_makeLiteral ("Internal error parseGotoMark"));
7386 llassert (pbuf->buf != NULL);
7387 pbuf->cur = pbuf->buf + pmark->position;
7388 DPRINTF (("goto mark: %d / %s", pmark->position, pbuf->cur));
7391 /* Reset PMARK to point to the current position of PFILE. (Same
7392 as parseClearMark (PMARK), parseSetMark (PMARK, PFILE) but faster. */
7395 parseMoveMark (struct parse_marker *pmark, cppReader *pfile)
7397 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7399 if (pbuf != pmark->buf)
7401 cpp_setLocation (pfile);
7402 llfatalerror (cstring_makeLiteral ("Internal error parseMoveMark"));
7405 pmark->position = pbuf->cur - pbuf->buf;
7406 DPRINTF (("move mark: %s", pmark->position));
7409 void cpplib_initializeReader (cppReader *pfile) /* Must be done after library is loaded. */
7411 struct cppOptions *opts = CPPOPTIONS (pfile);
7414 /* The code looks at the defaults through this pointer, rather than through
7415 the constant structure above. This pointer gets changed if an environment
7416 variable specifies other defaults. */
7418 struct default_include *include_defaults = include_defaults_array;
7420 /* Add dirs from INCLUDEPATH_VAR after dirs from -I. */
7421 /* There seems to be confusion about what CPATH should do,
7422 so for the moment it is not documented. */
7423 /* Some people say that CPATH should replace the standard include dirs,
7424 but that seems pointless: it comes before them, so it overrides them
7427 xp = osd_getEnvironmentVariable (INCLUDEPATH_VAR);
7429 if (cstring_isDefined (xp) && !opts->no_standard_includes)
7431 path_include (pfile, cstring_toCharsSafe (xp));
7434 /* Now that dollars_in_ident is known, initialize is_idchar. */
7435 initialize_char_syntax (opts);
7437 /* CppReader_Install __LINE__, etc. Must follow initialize_char_syntax
7438 and option processing. */
7440 initialize_builtins (pfile);
7442 /* Do standard #defines and assertions
7443 that identify system and machine type. */
7445 if (!opts->inhibit_predefs) {
7446 char *p = (char *) dmalloc (strlen (predefs) + 1);
7447 strcpy (p, predefs);
7453 while (*p == ' ' || *p == '\t')
7458 /* Handle -D options. */
7459 if (p[0] == '-' && p[1] == 'D')
7463 while (*p && *p != ' ' && *p != '\t')
7473 if (opts->debug_output)
7475 output_line_command (pfile, 0, same_file);
7478 cppReader_define (pfile, q);
7480 while (*p == ' ' || *p == '\t')
7494 opts->done_initializing = 1;
7496 { /* Read the appropriate environment variable and if it exists
7497 replace include_defaults with the listed path. */
7501 int win32_buf_size = 0; /* memory we need to allocate */
7504 if (opts->cplusplus)
7506 epath = getenv ("CPLUS_INCLUDE_PATH");
7510 epath = getenv ("C_INCLUDE_PATH");
7514 ** If the environment var for this language is set,
7515 ** add to the default list of include directories.
7518 if (epath != NULL) {
7519 char *nstore = (char *) dmalloc (strlen (epath) + 2);
7521 char *startp, *endp;
7524 /* if we have a posix path list, convert to win32 path list */
7525 if (cygwin32_posix_path_list_p (epath))
7527 win32_buf_size = cygwin32_posix_to_win32_path_list_buf_size (epath);
7528 win32epath = (char *) dmalloc /*@i4@*/ (win32_buf_size);
7529 cygwin32_posix_to_win32_path_list (epath, win32epath);
7533 for (num_dirs = 1, startp = epath; *startp; startp++)
7535 if (*startp == PATH_SEPARATOR)
7541 = (struct default_include *) dmalloc ((num_dirs
7542 * sizeof (struct default_include))
7543 + sizeof (include_defaults_array));
7546 startp = endp = epath;
7549 /* Handle cases like c:/usr/lib:d:/gcc/lib */
7550 if ((*endp == PATH_SEPARATOR) || *endp == 0)
7552 strncpy (nstore, startp, size_fromInt (endp - startp));
7555 strcpy (nstore, ".");
7559 nstore[endp-startp] = '\0';
7562 include_defaults[num_dirs].fname = cstring_fromCharsNew (nstore);
7563 include_defaults[num_dirs].cplusplus = opts->cplusplus;
7564 include_defaults[num_dirs].cxx_aware = 1;
7571 endp = startp = endp + 1;
7578 /* Put the usual defaults back in at the end. */
7579 memcpy ((char *) &include_defaults[num_dirs],
7580 (char *) include_defaults_array,
7581 sizeof (include_defaults_array));
7584 /*@-branchstate@*/ } /*@=branchstate@*/
7587 cppReader_appendIncludeChain (pfile, opts->before_system,
7588 opts->last_before_system);
7590 opts->first_system_include = opts->before_system;
7592 /* Unless -fnostdinc,
7593 tack on the standard include file dirs to the specified list */
7595 if (!opts->no_standard_includes) {
7596 struct default_include *p = include_defaults;
7597 char *specd_prefix = opts->include_prefix;
7598 char *default_prefix = mstring_copy (GCC_INCLUDE_DIR);
7599 size_t default_len = 0;
7601 /* Remove the `include' from /usr/local/lib/gcc.../include. */
7602 if (default_prefix != NULL) {
7603 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
7604 default_len = strlen (default_prefix) - 7;
7605 default_prefix[default_len] = 0;
7609 /* Search "translated" versions of GNU directories.
7610 These have /usr/local/lib/gcc... replaced by specd_prefix. */
7611 if (specd_prefix != 0 && default_len != 0)
7612 for (p = include_defaults; p->fname != NULL; p++) {
7613 /* Some standard dirs are only for C++. */
7615 || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
7616 /* Does this dir start with the prefix? */
7617 llassert (default_prefix != NULL);
7619 if (!strncmp (cstring_toCharsSafe (p->fname), default_prefix, default_len))
7621 /* Yes; change prefix and add to search list. */
7622 struct file_name_list *nlist
7623 = (struct file_name_list *) dmalloc (sizeof (*nlist));
7624 size_t this_len = strlen (specd_prefix) + cstring_length (p->fname) - default_len;
7625 char *str = (char *) dmalloc (this_len + 1);
7626 strcpy (str, specd_prefix);
7627 strcat (str, cstring_toCharsSafe (p->fname) + default_len);
7630 nlist->fname = cstring_fromChars (str);
7631 nlist->control_macro = 0;
7632 nlist->c_system_include_path = !p->cxx_aware;
7633 nlist->got_name_map = 0;
7635 if (opts->first_system_include == 0)
7637 opts->first_system_include = nlist;
7640 cppReader_addIncludeChain (pfile, nlist);
7645 /* Search ordinary names for GNU include directories. */
7647 for (p = include_defaults; p->fname != NULL; p++)
7649 /* Some standard dirs are only for C++. */
7651 || (opts->cplusplus && !opts->no_standard_cplusplus_includes))
7653 struct file_name_list *nlist
7654 = (struct file_name_list *) dmalloc (sizeof (*nlist));
7655 nlist->control_macro = 0;
7656 nlist->c_system_include_path = !p->cxx_aware;
7657 nlist->fname = p->fname;
7658 nlist->got_name_map = 0;
7661 /* Spurious warning reported for opts->first_system_include */
7662 /*@-usereleased@*/ if (opts->first_system_include == NULL)
7664 opts->first_system_include = nlist;
7668 cppReader_addIncludeChain (pfile, nlist);
7671 sfree (default_prefix);
7674 /* Tack the after_include chain at the end of the include chain. */
7675 cppReader_appendIncludeChain (pfile, opts->after_include,
7676 opts->last_after_include);
7678 /* Spurious warnings for opts->first_system_include */
7680 if (opts->first_system_include == NULL)
7682 opts->first_system_include = opts->after_include;
7686 /* With -v, print the list of dirs to search. */
7687 if (opts->verbose) {
7688 struct file_name_list *p;
7689 fprintf (stderr, "#include \"...\" search starts here:\n");
7691 for (p = opts->include; p != NULL; p = p->next) {
7692 if (p == opts->first_bracket_include)
7693 fprintf (stderr, "#include <...> search starts here:\n");
7695 fprintf (stderr, " %s\n", cstring_toCharsSafe (p->fname));
7697 fprintf (stderr, "End of search list.\n");
7701 int cppReader_startProcess (cppReader *pfile, cstring fname)
7705 struct cppOptions *opts = CPPOPTIONS (pfile);
7707 fp = cppReader_pushBuffer (pfile, NULL, 0);
7714 if (opts->in_fname == NULL)
7716 opts->in_fname = cstring_makeLiteralTemp ("");
7719 fp->fname = opts->in_fname;
7720 fp->nominal_fname = fp->fname;
7723 /* Copy the entire contents of the main input file into
7724 the stacked input buffer previously allocated for it. */
7726 if (cstring_isEmpty (fname))
7728 fname = cstring_makeLiteralTemp ("");
7731 else if ((f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666)) < 0)
7733 cppReader_error (pfile,
7734 message ("Error opening %s for reading: %s",
7735 fname, lldecodeerror (errno)));
7744 if (finclude (pfile, f, fname, 0, NULL))
7746 output_line_command (pfile, 0, same_file);
7752 static /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_getBuffer (cppReader *pfile)
7754 return pfile->buffer;
7757 /*@exposed@*/ cppBuffer *cppReader_getBufferSafe (cppReader *pfile)
7759 llassert (pfile->buffer != NULL);
7760 return pfile->buffer;
7763 /*@exposed@*/ char *cppLineBase (cppBuffer *buf)
7765 llassert (buf->buf != NULL);
7766 return (buf->buf + buf->line_base);
7769 int cpplib_bufPeek (cppBuffer *buf)
7771 if (buf->cur == NULL || buf->rlimit == NULL) {
7775 if (buf->cur < buf->rlimit) {
7782 bool cppBuffer_isMacro (cppBuffer *buf)
7786 return (buf->cleanup == cppReader_macroCleanup);
7793 ** Returns true if the macro should be checked, false
7794 ** if it should be expanded normally.
7797 static bool notparseable = FALSE; /* preceeded by @notparseable@ */
7798 static bool notfunction = FALSE; /* preceeded by @notfunction@ */
7799 static bool expectiter = FALSE; /* preceeded by @iter@ */
7800 static bool expectenditer = FALSE; /* second after @iter@ */
7801 static bool expectfunction = FALSE; /* preceeded by @function@ */
7802 static bool expectconstant = FALSE; /* preceeded by @constant@ */
7803 static bool expectmacro = FALSE; /* preceeded by notfunction or notparseable */
7805 static void cpp_setLocation (cppReader *pfile)
7810 if (pfile->buffer != NULL)
7812 if (cstring_isDefined (cppReader_getBufferSafe (pfile)->nominal_fname))
7814 cstring fname = cppReader_getBufferSafe (pfile)->nominal_fname;
7816 DPRINTF (("Looking up: %s", fname));
7818 if (fileTable_exists (context_fileTable (), fname))
7820 fid = fileTable_lookup (context_fileTable (), fname);
7824 DPRINTF (("Trying %s", cppReader_getBuffer (pfile)->fname));
7826 fid = fileTable_lookup (context_fileTable (),
7827 cppReader_getBufferSafe (pfile)->fname);
7832 fid = fileTable_lookup (context_fileTable (),
7833 cppReader_getBufferSafe (pfile)->fname);
7836 line = cppReader_getBufferSafe (pfile)->lineno;
7837 fileloc_free (g_currentloc);
7839 if (fileId_isValid (fid))
7841 g_currentloc = fileloc_create (fid, line, 1);
7845 g_currentloc = fileloc_createBuiltin ();
7850 fileloc_free (g_currentloc);
7851 g_currentloc = fileloc_createBuiltin ();
7855 static bool cpp_shouldCheckMacro (cppReader *pfile, char *p) /*@modifies p*/
7857 bool checkmacro = FALSE;
7858 bool hasParams = FALSE;
7859 bool noexpand = FALSE;
7863 cpp_setLocation (pfile);
7865 DPRINTF (("Should check macro? %s", p));
7867 if (expectiter || expectconstant || expectenditer)
7872 expectenditer = TRUE;
7877 expectconstant = FALSE;
7878 expectenditer = FALSE;
7881 if (notfunction || notparseable)
7883 notfunction = FALSE;
7884 notparseable = FALSE;
7893 llassert (*p == '#');
7896 while (*p == ' ' || *p == '\t')
7901 llassert (*p == 'd'); /* define starts */
7905 while (*p == ' ' || *p == '\t')
7910 sname = cstring_fromChars (p);
7911 DPRINTF (("Check macro: %s", sname));
7913 while (((c = *p) != ' ')
7914 && c != '\0' && c != '('
7915 && c != '\t' && c != '\\' && c != '\n'
7921 hasParams = (c == '(');
7926 notparseable = FALSE;
7928 else if (notfunction || fileloc_isStandardLib (g_currentloc))
7930 DPRINTF (("Clear notfunction"));
7931 notfunction = FALSE;
7946 if (usymtab_existsReal (sname))
7948 uentry ue = usymtab_lookup (sname);
7950 DPRINTF (("Lookup macro: %s", uentry_unparse (ue)));
7952 if (fileloc_isPreproc (uentry_whereLast (ue)))
7958 if (uentry_isSpecified (ue))
7960 checkmacro = context_getFlag (FLG_SPECMACROS);
7966 checkmacro = context_getFlag (FLG_LIBMACROS)
7967 || context_getFlag (FLG_FCNMACROS);
7975 DPRINTF (("Macro doesn't exist: %s", bool_unparse (checkmacro)));
7977 if (fileloc_isSystemFile (g_currentloc)
7978 && context_getFlag (FLG_SYSTEMDIREXPAND))
7980 ; /* don't check this macro */
7981 DPRINTF (("Don't check 1"));
7989 DPRINTF (("Has params..."));
7991 if (context_getFlag (FLG_FCNMACROS))
7993 if (usymtab_exists (sname))
7996 ** only get here is macro is redefined
7997 ** error reported elsewhere
8000 DPRINTF (("It exists!"));
8005 ** We make it a forward function, since it might be declared elsewhere.
8006 ** After all headers have been processed, we should check the forward
8010 fileloc loc = fileloc_makePreproc (g_currentloc);
8012 /* the line is off-by-one, since the newline was already read */
8017 expectfunction = FALSE;
8020 le = uentry_makeForwardFunction (sname,
8021 typeId_invalid, loc);
8027 /* Do not define here! */
8029 (void) usymtab_addEntry (le);
8033 DPRINTF (("Check: TRUE"));
8037 DPRINTF (("Flag FCN_MACROS not set!"));
8042 DPRINTF (("No params"));
8044 if (context_getFlag (FLG_CONSTMACROS))
8046 bool nocontent = FALSE;
8059 ** Check if there is nothing after the define.
8062 while ((*rest) != '\0' && isspace (*rest))
8069 nocontent = TRUE; /* empty macro, don't check */
8074 if (usymtab_exists (sname))
8080 fileloc loc = fileloc_makePreproc (g_currentloc);
8081 DPRINTF (("Make constant: %s", sname));
8082 le = uentry_makeMacroConstant (sname, ctype_unknown, loc);
8083 (void) usymtab_addEntry (le);
8086 checkmacro = !nocontent;
8091 if (checkmacro && usymtab_existsType (sname))
8093 DPRINTF (("Making false..."));
8095 ppllerror (message ("Specified type implemented as macro: %s", sname));
8105 if (usymtab_exists (sname))
8107 uentry ue = usymtab_lookupExpose (sname);
8108 fileloc tloc = fileloc_makePreproc (g_currentloc);
8110 uentry_setDefined (ue, tloc);
8111 fileloc_free (tloc);
8112 uentry_setUsed (ue, fileloc_undefined);
8116 fileloc tloc = fileloc_makePreproc (g_currentloc);
8117 uentry ue = uentry_makeExpandedMacro (sname, tloc);
8118 DPRINTF (("Make expanded macro: %s", sname));
8119 DPRINTF (("Not in symbol table: %s", sname));
8121 (void) usymtab_addGlobalEntry (ue);
8122 fileloc_free (tloc);
8127 DPRINTF (("Returning: %s", bool_unparse (checkmacro)));
8131 static enum cpp_token
8132 cpp_handleComment (cppReader *pfile, struct parse_marker *smark)
8134 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
8138 bool eliminateComment = FALSE;
8140 llassert (pbuf->buf != NULL);
8142 start = pbuf->buf + smark->position;
8144 llassert (pbuf->cur != NULL);
8145 len = pbuf->cur - start;
8148 && start[1] == context_getCommentMarkerChar ())
8152 char *scomment = start + 2;
8153 char savec = start[len];
8155 cpp_setLocation (pfile);
8156 loc = fileloc_copy (g_currentloc);
8158 start[0] = BEFORE_COMMENT_MARKER[0];
8159 start[1] = BEFORE_COMMENT_MARKER[1];
8161 llassert (start[len - 2] == '*');
8162 start[len - 2] = AFTER_COMMENT_MARKER[0];
8164 llassert (start[len - 1] == '/');
8165 start[len - 1] = AFTER_COMMENT_MARKER[1];
8167 cpplib_reserve(pfile, size_fromInt (1 + len));
8168 cppReader_putCharQ (pfile, c);
8170 cpp_setLocation (pfile);
8174 if (mstring_containsString (scomment, "/*"))
8176 (void) cppoptgenerror
8178 message ("Comment starts inside syntactic comment: %s",
8179 cstring_fromChars (scomment)),
8185 if (mstring_equalPrefix (scomment, "ignore"))
8187 if (!context_getFlag (FLG_NOCOMMENTS))
8189 context_enterSuppressRegion (loc);
8192 else if (mstring_equalPrefix (scomment, "end"))
8194 if (!context_getFlag (FLG_NOCOMMENTS))
8196 context_exitSuppressRegion (loc);
8199 else if (mstring_equalPrefix (scomment, "notparseable"))
8201 notparseable = TRUE;
8203 eliminateComment = TRUE;
8205 else if (mstring_equalPrefix (scomment, "notfunction"))
8209 eliminateComment = TRUE;
8211 else if (mstring_equalPrefix (scomment, "iter"))
8215 else if (mstring_equalPrefix (scomment, "function"))
8217 expectfunction = TRUE;
8219 else if (mstring_equalPrefix (scomment, "constant"))
8221 expectconstant = TRUE;
8225 char sChar = *scomment;
8231 char *rest = scomment + 1;
8233 if (mstring_equalPrefix (rest, "commentchar"))
8235 eliminateComment = TRUE;
8239 ppllerror (cstring_makeLiteral
8240 ("Cannot restore commentchar"));
8244 char *next = scomment + 12; /* strlen commentchar = 12 */
8246 if (*next != ' ' && *next != '\t' && *next != '\n')
8250 ("Syntactic commentchar comment is not followed by a "
8251 "whitespace character: %c",
8256 char cchar = *(next + 1);
8261 (cstring_makeLiteral
8262 ("Cannot set commentchar to NUL"));
8266 context_setCommentMarkerChar (cchar);
8267 /* setComment = TRUE; */
8272 else if (mstring_equalPrefix (scomment, "nestcomment"))
8274 /* fix from Mike Miller <MikeM@xata.com> */
8275 context_fileSetFlag (FLG_NESTCOMMENT,
8276 ynm_fromCodeChar (sChar),
8279 else if (mstring_equalPrefix (rest, "namechecks"))
8281 context_fileSetFlag (FLG_NAMECHECKS,
8282 ynm_fromCodeChar (sChar),
8285 else if (mstring_equalPrefix (rest, "macroredef"))
8287 context_fileSetFlag (FLG_MACROREDEF,
8288 ynm_fromCodeChar (sChar),
8291 else if (mstring_equalPrefix (rest, "usevarargs"))
8293 context_fileSetFlag (FLG_USEVARARGS,
8294 ynm_fromCodeChar (sChar),
8297 else if (mstring_equalPrefix (rest, "nextlinemacros"))
8299 context_fileSetFlag (FLG_MACRONEXTLINE,
8300 ynm_fromCodeChar (sChar),
8303 else if (mstring_equalPrefix (rest, "allmacros")
8304 || mstring_equalPrefix (rest, "fcnmacros")
8305 || mstring_equalPrefix (rest, "constmacros"))
8309 if (mstring_equalPrefix (rest, "allmacros"))
8313 else if (mstring_equalPrefix (rest, "fcnmacros"))
8319 llassert (mstring_equalPrefix (rest, "constmacros"));
8320 fl = FLG_CONSTMACROS;
8323 context_fileSetFlag (fl, ynm_fromCodeChar (sChar), loc);
8324 notfunction = FALSE;
8337 if (eliminateComment)
8342 /* Replaces comment char's in start with spaces */
8344 for (i = 2; i < len - 2; i++)
8346 if (start[i] == BEFORE_COMMENT_MARKER[0]
8347 || start[i] == BEFORE_COMMENT_MARKER[1]
8348 || start[i] == context_getCommentMarkerChar ())
8354 cppReader_putStrN (pfile, start, size_fromInt (len));
8355 parseClearMark (smark);
8365 ** Output the comment as all spaces so line/column
8366 ** in output file is still correct.
8370 cstring lintcomment = cstring_undefined;
8372 if (context_getFlag (FLG_LINTCOMMENTS))
8374 if (mstring_equalPrefix (start, "*NOTREACHED*/"))
8376 lintcomment = cstring_makeLiteralTemp ("l_notreach");
8378 else if (mstring_equalPrefix (start, "*PRINTFLIKE*/"))
8380 lintcomment = cstring_makeLiteralTemp ("l_printfli");
8382 else if (mstring_equalPrefix (start, "*FALLTHROUGH*/"))
8384 lintcomment = cstring_makeLiteralTemp ("l_fallthrou");
8386 else if (mstring_equalPrefix (start, "*ARGSUSED*/"))
8388 lintcomment = cstring_makeLiteralTemp ("l_argsus");
8390 else if (mstring_equalPrefix (start, "*FALLTHRU*/"))
8392 lintcomment = cstring_makeLiteralTemp ("l_fallth");
8396 lintcomment = cstring_undefined;
8401 lintcomment = cstring_undefined;
8404 if (cstring_isDefined (lintcomment))
8406 c = BEFORE_COMMENT_MARKER[0];
8407 start[0] = BEFORE_COMMENT_MARKER[1];
8409 llassert (size_toLong (cstring_length (lintcomment)) == len - 3);
8411 for (i = 1; i < len - 2; i++)
8413 start[i] = cstring_getChar (lintcomment, size_fromInt (i));
8416 start[len - 2] = AFTER_COMMENT_MARKER[0];
8417 start[len - 1] = AFTER_COMMENT_MARKER[1];
8421 /* Replaces char's in start with spaces */
8422 for (i = 0; i < len; i++)
8426 && start[i + 1] == '*') {
8427 (void) cppoptgenerror
8429 message ("Comment starts inside comment"),
8433 if (start[i] != '\n')
8440 cpplib_reserve (pfile, size_fromInt (1 + len));
8441 cppReader_putCharQ (pfile, c);
8442 cppReader_putStrN (pfile, start, size_fromInt (len));
8443 parseClearMark (smark);
8449 static int cpp_openIncludeFile (char *filename)
8451 int res = open (filename, O_RDONLY, 0666);
8453 /* evans 2001-08-23: was (res) - open returns -1 on error! reported by Robin Watts */
8456 if (!fileTable_exists (context_fileTable (),
8457 cstring_fromChars (filename)))
8459 if (fileloc_isXHFile (g_currentloc))
8462 ** Files includes by XH files are also XH files
8465 (void) fileTable_addXHFile (context_fileTable (),
8466 cstring_fromChars (filename));
8470 (void) fileTable_addHeaderFile (context_fileTable (),
8471 cstring_fromChars (filename));
8476 DPRINTF (("File already exists: %s", filename));
8483 static bool cpp_skipIncludeFile (cstring fname)
8485 if (context_isSystemDir (fname))
8487 DPRINTF (("System dir: %s", fname));
8489 if (lcllib_isSkipHeader (fname))
8491 DPRINTF (("Skip include TRUE: %s", fname));
8495 if (context_getFlag (FLG_SKIPSYSHEADERS))
8498 ** 2003-04-18: Patch from Randal Parsons
8502 ** Don't skip include file unless the file actually exists.
8503 ** It may be in a different directory.
8506 int f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666);
8510 check (close (f) == 0);
8511 DPRINTF (("Skip include TRUE: %s", fname));
8516 /* Keep looking... */
8521 if (context_getFlag (FLG_SINGLEINCLUDE))
8523 fname = removePreDirs (fname);
8525 # if defined (WIN32) || defined (OS2)
8526 cstring_replaceAll (fname, '\\', '/');
8529 if (fileTable_exists (context_fileTable (), fname))
8531 DPRINTF (("Skip include TRUE: %s", fname));
8536 DPRINTF (("Skip include FALSE: %s", fname));
8540 static int cpp_peekN (cppReader *pfile, int n)
8542 cppBuffer *buf = cppReader_getBufferSafe (pfile);
8544 llassert (buf->cur != NULL);
8546 return (buf->rlimit - buf->cur >= (n)
8551 cppBuffer *cppBuffer_prevBuffer (cppBuffer *buf)
8556 void cppBuffer_forward (cppBuffer *buf, int n)
8558 llassert (buf->cur != NULL);
8562 /*@=bufferoverflowhigh@*/