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
3760 cpplib_installBuiltin ("__" TARGET_CPU, ctype_int, -1, T_CONST, 2, NULL, -1);
3762 /*drl 1/2/2002 set some flags based on uname
3763 I'd like to be able to do this with autoconf macro instead...
3766 /*Thanks to Nelson Beebe for suggesting possible values for these */
3768 if (! strcmp (UNAME, "Linux"))
3771 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3775 else if(! strcmp (UNAME, "Darwin"))
3777 cpplib_installBuiltin ("__ppc__", ctype_int, -1, T_CONST, 2, NULL, -1);
3778 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3780 else if(! strcmp (UNAME, "HP-UX"))
3782 cpplib_installBuiltin ("PWB", ctype_int, -1, T_CONST, 2, NULL, -1);
3783 cpplib_installBuiltin ("_HIUX_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3784 cpplib_installBuiltin ("_HPUX_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3785 cpplib_installBuiltin ("_PA_RISC1_1", ctype_int, -1, T_CONST, 2, NULL, -1);
3786 cpplib_installBuiltin ("__PWB", ctype_int, -1, T_CONST, 2, NULL, -1);
3787 cpplib_installBuiltin ("__PWB__", ctype_int, -1, T_CONST, 2, NULL, -1);
3788 cpplib_installBuiltin ("__STDC_EXT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3789 cpplib_installBuiltin ("__hp9000s700", ctype_int, -1, T_CONST, 2, NULL, -1);
3790 cpplib_installBuiltin ("__hp9000s800", ctype_int, -1, T_CONST, 2, NULL, -1);
3791 cpplib_installBuiltin ("__hp9000s800__", ctype_int, -1, T_CONST, 2, NULL, -1);
3792 cpplib_installBuiltin ("__hp9k8", ctype_int, -1, T_CONST, 2, NULL, -1);
3793 cpplib_installBuiltin ("__hp9k8__", ctype_int, -1, T_CONST, 2, NULL, -1);
3794 cpplib_installBuiltin ("__hppa", ctype_int, -1, T_CONST, 2, NULL, -1);
3795 cpplib_installBuiltin ("__hppa__", ctype_int, -1, T_CONST, 2, NULL, -1);
3796 cpplib_installBuiltin ("__hpux", ctype_int, -1, T_CONST, 2, NULL, -1);
3797 cpplib_installBuiltin ("__hpux__", ctype_int, -1, T_CONST, 2, NULL, -1);
3798 cpplib_installBuiltin ("__unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3799 cpplib_installBuiltin ("__unix__", ctype_int, -1, T_CONST, 2, NULL, -1);
3800 cpplib_installBuiltin ("hp9000s800", ctype_int, -1, T_CONST, 2, NULL, -1);
3801 cpplib_installBuiltin ("hp9k8", ctype_int, -1, T_CONST, 2, NULL, -1);
3802 cpplib_installBuiltin ("hppa", ctype_int, -1, T_CONST, 2, NULL, -1);
3803 cpplib_installBuiltin ("hpux", ctype_int, -1, T_CONST, 2, NULL, -1);
3804 cpplib_installBuiltin ("unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3806 else if(! strcmp (UNAME, "IRIX64"))
3808 cpplib_installBuiltin ("LANGUAGE_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3809 cpplib_installBuiltin ("MIPSEB", ctype_int, -1, T_CONST, 2, NULL, -1);
3810 cpplib_installBuiltin ("_ABIN32", ctype_int, -1, T_CONST, 2, NULL, -1);
3811 cpplib_installBuiltin ("_COMPILER_VERSION", ctype_int, -1, T_CONST, 730, NULL, -1);
3812 cpplib_installBuiltin ("_LANGUAGE_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3813 cpplib_installBuiltin ("_LONGLONG", ctype_int, -1, T_CONST, 2, NULL, -1);
3814 cpplib_installBuiltin ("_MIPSEB", ctype_int, -1, T_CONST, 2, NULL, -1);
3815 cpplib_installBuiltin ("_MIPS_FPSET", ctype_int, -1, T_CONST, 32, NULL, -1);
3816 cpplib_installBuiltin ("_MIPS_ISA", ctype_int, -1, T_CONST, 3, NULL, -1);
3817 /*_MIPS_SIM=_ABIN32*/
3818 cpplib_installBuiltin ("_MIPS_SIM", ctype_int, -1, T_CONST, 2, NULL , -1);
3819 cpplib_installBuiltin ("_MIPS_SZINT", ctype_int, -1, T_CONST, 32, NULL, -1);
3820 cpplib_installBuiltin ("_MIPS_SZLONG", ctype_int, -1, T_CONST, 32, NULL, -1);
3821 cpplib_installBuiltin ("_MIPS_SZPTR", ctype_int, -1, T_CONST, 32, NULL, -1);
3822 cpplib_installBuiltin ("_MODERN_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3823 cpplib_installBuiltin ("_PIC", ctype_int, -1, T_CONST, 2, NULL, -1);
3824 cpplib_installBuiltin ("_SGI_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3825 cpplib_installBuiltin ("_SIZE_INT", ctype_int, -1, T_CONST, 32, NULL, -1);
3826 cpplib_installBuiltin ("_SIZE_LONG", ctype_int, -1, T_CONST, 32, NULL, -1);
3827 cpplib_installBuiltin ("_SIZE_PTR", ctype_int, -1, T_CONST, 32, NULL, -1);
3828 cpplib_installBuiltin ("_SVR4_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3829 cpplib_installBuiltin ("_SYSTYPE_SVR4", ctype_int, -1, T_CONST, 2, NULL, -1);
3830 cpplib_installBuiltin ("__DSO__", ctype_int, -1, T_CONST, 2, NULL, -1);
3831 cpplib_installBuiltin ("__EXTENSIONS__", ctype_int, -1, T_CONST, 2, NULL, -1);
3832 cpplib_installBuiltin ("__INLINE_INTRINSICS", ctype_int, -1, T_CONST, 2, NULL, -1);
3833 cpplib_installBuiltin ("__MATH_HAS_NO_SIDE_EFFECTS", ctype_int, -1, T_CONST, 2, NULL, -1);
3834 cpplib_installBuiltin ("__host_mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3835 cpplib_installBuiltin ("__mips", ctype_int, -1, T_CONST, 3, NULL, -1);
3836 cpplib_installBuiltin ("__sgi", ctype_int, -1, T_CONST, 2, NULL, -1);
3837 cpplib_installBuiltin ("__unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3838 cpplib_installBuiltin ("host_mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3839 cpplib_installBuiltin ("mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3840 cpplib_installBuiltin ("sgi", ctype_int, -1, T_CONST, 2, NULL, -1);
3841 cpplib_installBuiltin ("unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3843 else if(! strcmp (UNAME, "OSF1"))
3845 cpplib_installBuiltin ("__alpha", ctype_int, -1, T_CONST, 2, NULL, -1);
3847 else if (!strcmp (UNAME, "Rhapsody"))
3849 cpplib_installBuiltin ("__ppc__", ctype_int, -1, T_CONST, 2, NULL, -1);
3850 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3853 else if (!strcmp (UNAME, "SunOS"))
3855 cpplib_installBuiltin ("__OPEN_MAX", ctype_int, -1, T_CONST, 20, NULL, -1);
3856 cpplib_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, 2, NULL, -1);
3857 cpplib_installBuiltin ("__sparc", ctype_int, -1, T_CONST, 2, NULL, -1);
3858 /* This define "-Dfileno(f)=0" should be inserted but we're going to stick to deinfe constants for now...*/
3863 types which we have not explictedly handled.
3864 AIX, FreeBSD, IRIX, Mach
3869 if (CPPOPTIONS (pfile)->debug_output)
3871 dump_special_to_buffer (pfile, "__BASE_FILE__");
3872 dump_special_to_buffer (pfile, "__VERSION__");
3873 #ifndef NO_BUILTIN_SIZE_TYPE
3874 dump_special_to_buffer (pfile, "__SIZE_TYPE__");
3876 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3877 dump_special_to_buffer (pfile, "__PTRDIFF_TYPE__");
3879 dump_special_to_buffer (pfile, "__WCHAR_TYPE__");
3880 dump_special_to_buffer (pfile, "__DATE__");
3881 dump_special_to_buffer (pfile, "__TIME__");
3882 if (!cppReader_isTraditional (pfile))
3883 dump_special_to_buffer (pfile, "__STDC__");
3888 /* Return 1 iff a token ending in C1 followed directly by a token C2
3889 could cause mis-tokenization. */
3892 unsafe_chars (char c1, char c2)
3897 if (c2 == c1 || c2 == '=')
3901 case '0': case '1': case '2': case '3': case '4':
3902 case '5': case '6': case '7': case '8': case '9':
3903 case 'e': case 'E': case 'p': case 'P':
3904 if (c2 == '-' || c2 == '+')
3905 return 1; /* could extend a pre-processing number */
3908 if (c2 == '\'' || c2 == '\"')
3909 return 1; /* Could turn into L"xxx" or L'xxx'. */
3913 case 'a': case 'b': case 'c': case 'd': case 'f':
3914 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3915 case 'm': case 'n': case 'o': case 'q': case 'r':
3916 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3918 case 'A': case 'B': case 'C': case 'D': case 'F':
3919 case 'G': case 'H': case 'I': case 'J': case 'K':
3920 case 'M': case 'N': case 'O': case 'Q': case 'R':
3921 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3923 /* We're in the middle of either a name or a pre-processing number. */
3924 return (is_idchar[(int) c2] || c2 == '.');
3925 case '<': case '>': case '!': case '%': case '#': case ':':
3926 case '^': case '&': case '|': case '*': case '/': case '=':
3927 return (c2 == c1 || c2 == '=');
3932 /* Expand a macro call.
3933 HP points to the symbol that is the macro being called.
3934 Put the result of expansion onto the input stack
3935 so that subsequent input by our caller will use it.
3937 If macro wants arguments, caller has already verified that
3938 an argument list follows; arguments come from the input stack. */
3941 cpplib_macroExpand (cppReader *pfile, /*@dependent@*/ hashNode hp)
3944 DEFINITION *defn = hp->value.defn;
3952 size_t old_written = cpplib_getWritten (pfile);
3956 struct argdata *args = NULL;
3958 pfile->output_escapes++;
3959 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile), &start_line, &start_column);
3960 DPRINTF (("Expand macro: %d:%d", start_line, start_column));
3962 nargs = defn->nargs;
3966 enum cpp_token token = CPP_EOF;
3968 args = (struct argdata *) dmalloc ((nargs + 1) * sizeof (*args));
3970 for (i = 0; i < nargs; i++)
3972 args[i].expanded = 0;
3974 args[i].raw_length = 0;
3975 args[i].expand_length = args[i].stringified_length = -1;
3976 args[i].use_count = 0;
3980 ** Parse all the macro args that are supplied. I counts them.
3981 ** The first NARGS args are stored in ARGS.
3982 ** The rest are discarded. If rest_args is set then we assume
3983 ** macarg absorbed the rest of the args.
3989 cppReader_forward (pfile, 1); /* Discard the open-parenthesis before the first arg. */
3997 if (i < nargs || (nargs == 0 && i == 0))
3999 /* if we are working on last arg which absorbs rest of args... */
4000 if (i == nargs - 1 && defn->rest_args)
4005 args[i].raw = size_toLong (cpplib_getWritten (pfile));
4006 token = macarg (pfile, rest_args);
4007 args[i].raw_length = size_toInt (cpplib_getWritten (pfile) - args[i].raw);
4008 args[i].newlines = FALSE; /* FIXME */
4012 token = macarg (pfile, 0);
4015 if (token == CPP_EOF || token == CPP_POP)
4017 cppReader_errorWithLine (pfile, start_line, start_column,
4018 cstring_fromCharsNew ("unterminated macro call"));
4023 } while (token == CPP_COMMA);
4025 /* If we got one arg but it was just whitespace, call that 0 args. */
4033 bp = ARG_BASE + args[0].raw;
4034 lim = bp + args[0].raw_length;
4036 /* cpp.texi says for foo ( ) we provide one argument.
4037 However, if foo wants just 0 arguments, treat this as 0. */
4041 while (bp != lim && is_space[(int) *bp])
4051 /* Don't output an error message if we have already output one for
4052 a parse error above. */
4055 if (nargs == 0 && i > 0)
4057 cppReader_error (pfile,
4058 message ("arguments given to macro `%s'", hp->name));
4062 /* traditional C allows foo() if foo wants one argument. */
4063 if (nargs == 1 && i == 0 && cppReader_isTraditional (pfile))
4067 /* the rest args token is allowed to absorb 0 tokens */
4068 else if (i == nargs - 1 && defn->rest_args)
4071 cppReader_error (pfile,
4072 message ("macro `%s' used without args", hp->name));
4074 cppReader_error (pfile,
4075 message ("macro `%s' used with just one arg", hp->name));
4078 cppReader_error (pfile,
4079 message ("macro `%s' used with only %d args",
4085 cppReader_error (pfile,
4086 message ("macro `%s' used with too many (%d) args", hp->name, i));
4095 ** If the agrument list was multiple lines, need to insert new lines to keep line
4096 ** numbers accurate.
4099 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile), &end_line, &end_column);
4100 DPRINTF (("Expand macro: %d:%d", end_line, end_column));
4102 /* If macro wants zero args, we parsed the arglist for checking only.
4103 Read directly from the macro definition. */
4107 xbuf = defn->expansion;
4108 xbuf_len = defn->length;
4112 char *exp = defn->expansion;
4113 int offset; /* offset in expansion,
4114 copied a piece at a time */
4115 size_t totlen; /* total amount of exp buffer filled so far */
4117 register struct reflist *ap, *last_ap;
4119 assertSet (args); /* args is defined since the nargs > 0 path was taken */
4121 /* Macro really takes args. Compute the expansion of this call. */
4123 /* Compute length in characters of the macro's expansion.
4124 Also count number of times each arg is used. */
4125 xbuf_len = defn->length;
4127 llassert (args != NULL);
4129 for (ap = defn->pattern; ap != NULL; ap = ap->next)
4133 struct argdata *arg = &args[ap->argno];
4135 /* Stringify it it hasn't already been */
4138 if (arg->stringified_length < 0)
4140 int arglen = arg->raw_length;
4141 bool escaped = FALSE;
4142 char in_string = '\0';
4145 /* Initially need_space is -1. Otherwise, 1 means the
4146 previous character was a space, but we suppressed it;
4147 0 means the previous character was a non-space. */
4148 int need_space = -1;
4151 arg->stringified = cpplib_getWritten (pfile);
4152 if (!cppReader_isTraditional (pfile))
4153 cppReader_putChar (pfile, '\"'); /* insert beginning quote */
4154 for (; i < arglen; i++)
4156 c = (ARG_BASE + arg->raw)[i];
4158 if (in_string == '\0')
4160 /* Internal sequences of whitespace are replaced by
4161 one space except within an string or char token.*/
4162 if (is_space[(int) c])
4164 if (cpplib_getWritten (pfile) > arg->stringified
4165 && (cpplib_getPWritten (pfile))[-1] == '@')
4167 /* "@ " escape markers are removed */
4168 cppReader_adjustWritten (pfile, -1);
4169 /*@innercontinue@*/ continue;
4171 if (need_space == 0)
4173 /*@innercontinue@*/ continue;
4175 else if (need_space > 0)
4176 cppReader_putChar (pfile, ' ');
4192 if (in_string != '\0')
4197 else if (c == '\"' || c == '\'')
4207 /* Escape these chars */
4208 if (c == '\"' || (in_string != '\0' && c == '\\'))
4209 cppReader_putChar (pfile, '\\');
4211 cppReader_putChar (pfile, c);
4214 cpplib_reserve (pfile, 4);
4215 sprintf (cpplib_getPWritten (pfile), "\\%03o",
4217 cppReader_adjustWritten (pfile, 4);
4220 if (!cppReader_isTraditional (pfile))
4221 cppReader_putChar (pfile, '\"'); /* insert ending quote */
4222 arg->stringified_length
4223 = size_toInt (cpplib_getWritten (pfile) - arg->stringified);
4226 xbuf_len += args[ap->argno].stringified_length;
4228 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
4230 /* Add 4 for two newline-space markers to prevent token concatenation. */
4231 assertSet (args); /* Splint shouldn't need this */
4232 xbuf_len += args[ap->argno].raw_length + 4;
4236 /* We have an ordinary (expanded) occurrence of the arg.
4237 So compute its expansion, if we have not already. */
4239 assertSet (args); /* shouldn't need this */
4241 if (args[ap->argno].expand_length < 0)
4243 args[ap->argno].expanded = cpplib_getWritten (pfile);
4244 cpp_expand_to_buffer (pfile,
4245 ARG_BASE + args[ap->argno].raw,
4246 size_fromInt (args[ap->argno].raw_length));
4248 args[ap->argno].expand_length
4249 = size_toInt (cpplib_getWritten (pfile) - args[ap->argno].expanded);
4252 /* Add 4 for two newline-space markers to prevent
4253 token concatenation. */
4254 xbuf_len += args[ap->argno].expand_length + 4;
4256 if (args[ap->argno].use_count < 10)
4257 args[ap->argno].use_count++;
4260 xbuf = (char *) dmalloc (xbuf_len + 1);
4264 ** Generate in XBUF the complete expansion
4265 ** with arguments substituted in.
4266 ** TOTLEN is the total size generated so far.
4267 ** OFFSET is the index in the definition
4268 ** of where we are copying from.
4274 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
4275 last_ap = ap, ap = ap->next)
4277 register struct argdata *arg = &args[ap->argno];
4278 size_t count_before = totlen;
4280 /* Add chars to XBUF. */
4281 for (i = 0; i < ap->nchars; i++, offset++)
4283 xbuf[totlen++] = exp[offset];
4286 /* If followed by an empty rest arg with concatenation,
4287 delete the last run of nonwhite chars. */
4288 if (rest_zero && totlen > count_before
4289 && ((ap->rest_args && ap->raw_before)
4290 || (last_ap != NULL && last_ap->rest_args
4291 && last_ap->raw_after)))
4293 /* Delete final whitespace. */
4294 while (totlen > count_before && is_space[(int) xbuf[totlen - 1]])
4299 /* Delete the nonwhites before them. */
4300 while (totlen > count_before && ! is_space[(int) xbuf[totlen - 1]])
4306 if (ap->stringify != 0)
4309 memcpy (xbuf + totlen,
4310 ARG_BASE + arg->stringified,
4311 size_fromInt (arg->stringified_length));
4312 totlen += arg->stringified_length;
4314 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
4321 p1 = ARG_BASE + arg->raw;
4322 l1 = p1 + arg->raw_length;
4326 while (p1 != l1 && is_space[(int) *p1])
4331 while (p1 != l1 && is_idchar[(int) *p1])
4333 xbuf[totlen++] = *p1++;
4336 /* Delete any no-reexpansion marker that follows
4337 an identifier at the beginning of the argument
4338 if the argument is concatenated with what precedes it. */
4339 if (p1[0] == '@' && p1[1] == '-')
4344 /* Arg is concatenated after: delete trailing whitespace,
4345 whitespace markers, and no-reexpansion markers. */
4348 if (is_space[(int) l1[-1]]) l1--;
4349 else if (l1[-1] == '-')
4352 /* If a `-' is preceded by an odd number of newlines then it
4353 and the last newline are a no-reexpansion marker. */
4354 while (p2 != p1 && p2[-1] == '\n')
4359 if (((l1 - 1 - p2) & 1) != 0)
4365 /*@innerbreak@*/ break;
4370 /*@innerbreak@*/ break;
4375 memcpy (xbuf + totlen, p1, size_fromInt (l1 - p1));
4383 expanded = ARG_BASE + arg->expanded;
4385 if (!ap->raw_before && totlen > 0
4386 && (arg->expand_length != 0)
4387 && !cppReader_isTraditional(pfile)
4388 && unsafe_chars (xbuf[totlen-1], expanded[0]))
4390 xbuf[totlen++] = '@';
4391 xbuf[totlen++] = ' ';
4394 memcpy (xbuf + totlen, expanded,
4395 size_fromInt (arg->expand_length));
4396 totlen += arg->expand_length;
4398 if (!ap->raw_after && totlen > 0
4399 && offset < size_toInt (defn->length)
4400 && !cppReader_isTraditional(pfile)
4401 && unsafe_chars (xbuf[totlen-1], exp[offset]))
4403 xbuf[totlen++] = '@';
4404 xbuf[totlen++] = ' ';
4407 /* If a macro argument with newlines is used multiple times,
4408 then only expand the newlines once. This avoids creating
4409 output lines which don't correspond to any input line,
4410 which confuses gdb and gcov. */
4411 if (arg->use_count > 1 && arg->newlines > 0)
4413 /* Don't bother doing change_newlines for subsequent
4417 = change_newlines (expanded, arg->expand_length);
4421 if (totlen > xbuf_len)
4425 /* if there is anything left of the definition
4426 after handling the arg list, copy that in too. */
4428 for (i = offset; i < size_toInt (defn->length); i++)
4430 /* if we've reached the end of the macro */
4433 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
4434 && last_ap->raw_after))
4435 xbuf[totlen++] = exp[i];
4438 xbuf[totlen] = '\0';
4442 pfile->output_escapes--;
4444 /* Now put the expansion on the input stack
4445 so our caller will commence reading from it. */
4446 DPRINTF (("Pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4448 if (end_line != start_line)
4450 /* xbuf must have enough newlines */
4451 int newlines = end_line - start_line;
4452 int foundnewlines = 0;
4453 char *xbufptr = xbuf;
4455 while ((xbufptr = strchr (xbufptr, '\n')) != NULL && foundnewlines <= newlines)
4460 if (*xbufptr == '\0')
4466 if (foundnewlines < newlines)
4468 cstring newbuf = cstring_copyLength (xbuf, xbuf_len);
4470 while (foundnewlines < newlines)
4472 newbuf = cstring_appendChar (newbuf, '\n');
4477 xbuf = cstring_toCharsSafe (newbuf);
4478 xbuf_len = cstring_length (newbuf);
4480 } /*@=branchstate@*/
4483 DPRINTF (("Pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4485 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
4486 DPRINTF (("After pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4487 cppReader_getBufferSafe (pfile)->has_escapes = 1;
4489 /* Pop the space we've used in the token_buffer for argument expansion. */
4490 cppReader_setWritten (pfile, old_written);
4491 DPRINTF (("Done set written"));
4493 /* Recursive macro use sometimes works traditionally.
4494 #define foo(x,y) bar (x (y,0), y)
4497 if (!cppReader_isTraditional (pfile))
4498 hp->type = T_DISABLED;
4504 push_macro_expansion (cppReader *pfile, char *xbuf, size_t xbuf_len,
4505 /*@dependent@*/ hashNode hp)
4507 cppBuffer *mbuf = cppReader_pushBuffer (pfile, xbuf, xbuf_len);
4514 mbuf->cleanup = cppReader_macroCleanup;
4516 llassert (mbuf->hnode == NULL);
4519 /* The first chars of the expansion should be a "@ " added by
4520 collect_expansion. This is to prevent accidental token-pasting
4521 between the text preceding the macro invocation, and the macro
4524 We would like to avoid adding unneeded spaces (for the sake of
4525 tools that use cpp, such as imake). In some common cases we can
4526 tell that it is safe to omit the space.
4528 The character before the macro invocation cannot have been an
4529 idchar (or else it would have been pasted with the idchars of
4530 the macro name). Therefore, if the first non-space character
4531 of the expansion is an idchar, we do not need the extra space
4532 to prevent token pasting.
4534 Also, we don't need the extra space if the first char is '(',
4535 or some other (less common) characters. */
4537 if (xbuf[0] == '@' && xbuf[1] == ' '
4538 && (is_idchar[(int) xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
4539 || xbuf[2] == '\"'))
4541 llassert (mbuf->cur != NULL);
4542 DPRINTF (("Eating: %c", xbuf[2]));
4549 /* Like cpplib_getToken, except that it does not read past end-of-line.
4550 Also, horizontal space is skipped, and macros are popped. */
4552 static enum cpp_token
4553 get_directive_token (cppReader *pfile)
4557 size_t old_written = cpplib_getWritten (pfile);
4558 enum cpp_token token;
4559 cppSkipHspace (pfile);
4560 if (cppReader_peekC (pfile) == '\n')
4565 token = cpplib_getToken (pfile);
4570 if (!cppBuffer_isMacro (cppReader_getBuffer (pfile)))
4575 cppReader_setWritten (pfile, old_written);
4576 /*@switchbreak@*/ break;
4584 /* Handle #include and #import.
4585 This function expects to see "fname" or <fname> on the input.
4587 The input is normally in part of the output_buffer following
4588 cpplib_getWritten, and will get overwritten by output_line_command.
4589 I.e. in input file specification has been popped by cppReader_handleDirective.
4593 do_include (cppReader *pfile, struct directive *keyword,
4594 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
4596 bool skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4598 char *fbeg, *fend; /* Beginning and end of fname */
4599 enum cpp_token token;
4601 /* Chain of dirs to search */
4602 struct file_name_list *search_start = CPPOPTIONS (pfile)->include;
4603 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
4604 struct file_name_list *searchptr = NULL;
4605 size_t old_written = cpplib_getWritten (pfile);
4608 int f; /* file number */
4609 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4610 f= -1; /* JF we iz paranoid! */
4612 pfile->parsing_include_directive++;
4613 token = get_directive_token (pfile);
4614 pfile->parsing_include_directive--;
4616 if (token == CPP_STRING)
4618 /* FIXME - check no trailing garbage */
4619 fbeg = pfile->token_buffer + old_written + 1;
4620 fend = cpplib_getPWritten (pfile) - 1;
4621 if (fbeg[-1] == '<')
4624 /* If -I-, start with the first -I dir after the -I-. */
4625 if (CPPOPTIONS (pfile)->first_bracket_include != NULL)
4626 search_start = CPPOPTIONS (pfile)->first_bracket_include;
4628 /* If -I- was specified, don't search current dir, only spec'd ones. */
4629 else if (!CPPOPTIONS (pfile)->ignore_srcdir)
4631 cppBuffer *fp = CPPBUFFER (pfile);
4632 /* We have "filename". Figure out directory this source
4633 file is coming from and put it on the front of the list. */
4635 for ( ; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
4640 llassert (fp != NULL);
4644 if (cstring_isDefined (fp->nominal_fname))
4646 nam = cstring_toCharsSafe (fp->nominal_fname);
4648 /* Found a named file. Figure out dir of the file,
4649 and put it in front of the search list. */
4650 dsp[0].next = search_start;
4654 ep = strrchr (nam, CONNECTCHAR);
4656 ep = strrchr (nam, ']');
4657 if (ep == NULL) ep = strrchr (nam, '>');
4658 if (ep == NULL) ep = strrchr (nam, ':');
4659 if (ep != NULL) ep++;
4669 /*@-onlytrans@*/ /* This looks like a memory leak... */
4670 dsp[0].fname = cstring_fromCharsNew (nam); /* evs 2000-07-20: was fromChars */
4674 if (n + INCLUDE_LEN_FUDGE > size_toInt (pfile->max_include_len))
4675 pfile->max_include_len = size_fromInt (n + INCLUDE_LEN_FUDGE);
4679 dsp[0].fname = cstring_undefined; /* Current directory */
4682 dsp[0].got_name_map = 0;
4693 else if (token == CPP_NAME)
4696 * Support '#include xyz' like VAX-C to allow for easy use of all the
4697 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4698 * code from case '<' is repeated here) and generates a warning.
4700 cppReader_warning (pfile,
4701 "VAX-C-style include specification found, use '#include <filename.h>' !");
4703 /* If -I-, start with the first -I dir after the -I-. */
4704 if (CPPOPTIONS (pfile)->first_bracket_include)
4705 search_start = CPPOPTIONS (pfile)->first_bracket_include;
4706 fbeg = pfile->token_buffer + old_written;
4707 fend = cpplib_getPWritten (pfile);
4712 cppReader_error (pfile,
4713 message ("Preprocessor command #%s expects \"FILENAME\" or <FILENAME>",
4716 cppReader_setWritten (pfile, old_written);
4717 cppReader_skipRestOfLine (pfile);
4723 token = get_directive_token (pfile);
4724 if (token != CPP_VSPACE)
4726 cppReader_errorLit (pfile,
4727 cstring_makeLiteralTemp ("Junk at end of #include"));
4729 while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
4731 token = get_directive_token (pfile);
4736 ** For #include_next, skip in the search path
4737 ** past the dir in which the containing file was found.
4742 cppBuffer *fp = CPPBUFFER (pfile);
4744 for (; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
4746 llassert (fp != NULL);
4748 if (fp->fname != NULL)
4750 /* fp->dir is null if the containing file was specified with
4751 an absolute file name. In that case, don't skip anything. */
4752 if (fp->dir == SELF_DIR_DUMMY)
4754 search_start = CPPOPTIONS (pfile)->include;
4756 else if (fp->dir != NULL)
4758 search_start = fp->dir->next;
4770 cppReader_setWritten (pfile, old_written);
4772 flen = size_fromInt (fend - fbeg);
4774 DPRINTF (("fbeg: %s", fbeg));
4778 cppReader_error (pfile,
4779 message ("Empty file name in #%s", keyword->name));
4784 ** Allocate this permanently, because it gets stored in the definitions
4788 fname = cstring_undefined;
4790 /* + 2 above for slash and terminating null. */
4791 /* + 2 added for '.h' on VMS (to support '#include filename') */
4793 /* If specified file name is absolute, just open it. */
4795 if (osd_isConnectChar (*fbeg)
4796 # if defined (WIN32) || defined (OS2)
4797 || (*(fbeg + 1) == ':')
4801 fname = cstring_copyLength (fbeg, flen);
4803 if (redundant_include_p (pfile, fname))
4805 cstring_free (fname);
4809 f = open_include_file (pfile, fname, NULL);
4811 if (f == IMPORT_FOUND)
4813 return 0; /* Already included this file */
4818 /* Search directory path, trying to open the file.
4819 Copy each filename tried into FNAME. */
4821 for (searchptr = search_start; searchptr != NULL;
4822 searchptr = searchptr->next)
4824 if (!cstring_isEmpty (searchptr->fname))
4826 /* The empty string in a search path is ignored.
4827 This makes it possible to turn off entirely
4828 a standard piece of the list. */
4829 if (cstring_isEmpty (searchptr->fname))
4832 fname = cstring_copy (searchptr->fname);
4833 fname = cstring_appendChar (fname, CONNECTCHAR);
4834 DPRINTF (("Here: %s", fname));
4841 fname = cstring_concatLength (fname, fbeg, flen);
4843 DPRINTF (("fname: %s", fname));
4845 /* Win32 directory fix from Kay Buschner. */
4846 #if defined (WIN32) || defined (OS2)
4847 /* Fix all unixdir slashes to win dir slashes */
4848 if (searchptr->fname && (searchptr->fname[0] != 0))
4850 cstring_replaceAll (fname, '/', '\\');
4855 /* Change this 1/2 Unix 1/2 VMS file specification into a
4856 full VMS file specification */
4857 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4858 /* Fix up the filename */
4859 hack_vms_include_specification (fname);
4861 /* This is a normal VMS filespec, so use it unchanged. */
4862 strncpy (fname, fbeg, flen);
4864 /* if it's '#include filename', add the missing .h */
4865 if (strchr (fname,'.') == NULL) {
4866 strcat (fname, ".h");
4870 /* ??? There are currently 3 separate mechanisms for avoiding processing
4871 of redundant include files: #import, #pragma once, and
4872 redundant_include_p. It would be nice if they were unified. */
4874 if (redundant_include_p (pfile, fname))
4876 cstring_free (fname);
4880 DPRINTF (("Trying: %s", fname));
4882 f = open_include_file (pfile, fname, searchptr);
4884 if (f == IMPORT_FOUND)
4886 return 0; /* Already included this file */
4889 else if (f == IMPORT_NOT_FOUND && errno == EACCES)
4891 cppReader_warning (pfile,
4892 message ("Header file %s exists, but is not readable", fname));
4905 /* A file that was not found. */
4906 fname = cstring_copyLength (fbeg, flen);
4908 if (search_start != NULL)
4910 cppReader_error (pfile,
4911 message ("Cannot find include file %s on search path: %x",
4913 searchPath_unparse (search_start)));
4917 cppReader_error (pfile,
4918 message ("No include path in which to find %s", fname));
4923 ** Check to see if this include file is a once-only include file.
4927 struct file_name_list *ptr;
4929 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
4931 if (cstring_equal (ptr->fname, fname))
4933 /* This file was included before. */
4940 /* This is the first time for this file. */
4941 /* Add it to list of files included. */
4943 ptr = (struct file_name_list *) dmalloc (sizeof (*ptr));
4944 ptr->control_macro = NULL;
4945 ptr->c_system_include_path = NULL;
4946 ptr->next = pfile->all_include_files;
4948 ptr->got_name_map = NULL;
4950 DPRINTF (("Including file: %s", fname));
4951 pfile->all_include_files = ptr;
4952 assertSet (pfile->all_include_files);
4955 if (angle_brackets != 0)
4957 pfile->system_include_depth++;
4960 /* Actually process the file */
4961 if (cppReader_pushBuffer (pfile, NULL, 0) == NULL)
4963 cstring_free (fname);
4967 if (finclude (pfile, f, fname, is_system_include (pfile, fname),
4968 searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
4970 output_line_command (pfile, 0, enter_file);
4971 pfile->only_seen_white = 2;
4976 pfile->system_include_depth--;
4979 } /*@=branchstate@*/
4984 /* Return nonzero if there is no need to include file NAME
4985 because it has already been included and it contains a conditional
4986 to make a repeated include do nothing. */
4989 redundant_include_p (cppReader *pfile, cstring name)
4991 struct file_name_list *l = pfile->all_include_files;
4993 for (; l != NULL; l = l->next)
4995 if (cstring_equal (name, l->fname)
4996 && (l->control_macro != NULL)
4997 && (cpphash_lookup (l->control_macro, -1, -1) != NULL))
5006 /* Return nonzero if the given FILENAME is an absolute pathname which
5007 designates a file within one of the known "system" include file
5008 directories. We assume here that if the given FILENAME looks like
5009 it is the name of a file which resides either directly in a "system"
5010 include file directory, or within any subdirectory thereof, then the
5011 given file must be a "system" include file. This function tells us
5012 if we should suppress pedantic errors/warnings for the given FILENAME.
5014 The value is 2 if the file is a C-language system header file
5015 for which C++ should (on most systems) assume `extern "C"'. */
5018 is_system_include (cppReader *pfile, cstring filename)
5020 struct file_name_list *searchptr;
5022 for (searchptr = CPPOPTIONS (pfile)->first_system_include;
5024 searchptr = searchptr->next)
5026 if (!cstring_isEmpty (searchptr->fname))
5028 cstring sys_dir = searchptr->fname;
5029 size_t length = cstring_length (sys_dir);
5031 if (cstring_equalLen (sys_dir, filename, length)
5032 && osd_isConnectChar (cstring_getChar (filename, length)))
5034 if (searchptr->c_system_include_path)
5045 /* Convert a character string literal into a nul-terminated string.
5046 The input string is [IN ... LIMIT).
5047 The result is placed in RESULT. RESULT can be the same as IN.
5048 The value returned in the end of the string written to RESULT,
5049 or NULL on error. */
5051 static /*@null@*/ char *
5052 convert_string (cppReader *pfile, /*@returned@*/ char *result,
5053 char *in, char *limit, int handle_escapes)
5073 /*@switchbreak@*/ break;
5077 char *bpc = (char *) in;
5078 int i = (char) cppReader_parseEscape (pfile, &bpc);
5081 *result++ = (char) c;
5082 /*@switchbreak@*/ break;
5096 * interpret #line command. Remembers previously seen fnames
5097 * in its very own hash table.
5100 /*@constant int FNAME_HASHSIZE@*/
5101 #define FNAME_HASHSIZE 37
5104 do_line (cppReader *pfile, /*@unused@*/ struct directive *keyword)
5106 cppBuffer *ip = cppReader_getBuffer (pfile);
5108 size_t old_written = cpplib_getWritten (pfile);
5109 enum file_change_code file_change = same_file;
5110 enum cpp_token token;
5112 llassert (ip != NULL);
5113 token = get_directive_token (pfile);
5115 if (token != CPP_NUMBER
5116 || !isdigit(pfile->token_buffer[old_written]))
5118 cppReader_errorLit (pfile,
5119 cstring_makeLiteralTemp ("invalid format `#line' command"));
5121 goto bad_line_directive;
5124 /* The Newline at the end of this line remains to be processed.
5125 To put the next line at the specified line number,
5126 we must store a line number now that is one less. */
5127 new_lineno = atoi (pfile->token_buffer + old_written) - 1;
5128 cppReader_setWritten (pfile, old_written);
5130 /* NEW_LINENO is one less than the actual line number here. */
5131 if (cppReader_isPedantic (pfile) && new_lineno < 0)
5132 cppReader_pedwarnLit (pfile,
5133 cstring_makeLiteralTemp ("line number out of range in `#line' command"));
5135 token = get_directive_token (pfile);
5137 if (token == CPP_STRING) {
5138 char *fname = pfile->token_buffer + old_written;
5140 static hashNode fname_table[FNAME_HASHSIZE];
5142 hashNode *hash_bucket;
5145 size_t fname_length;
5147 /* Turn the file name, which is a character string literal,
5148 into a null-terminated string. Do this in place. */
5149 end_name = convert_string (pfile, fname, fname, cpplib_getPWritten (pfile), 1);
5150 if (end_name == NULL)
5152 cppReader_errorLit (pfile,
5153 cstring_makeLiteralTemp ("invalid format `#line' command"));
5154 goto bad_line_directive;
5157 fname_length = size_fromInt (end_name - fname);
5158 num_start = cpplib_getWritten (pfile);
5160 token = get_directive_token (pfile);
5161 if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP) {
5162 p = pfile->token_buffer + num_start;
5163 if (cppReader_isPedantic (pfile))
5164 cppReader_pedwarnLit (pfile,
5165 cstring_makeLiteralTemp ("garbage at end of `#line' command"));
5167 if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
5169 cppReader_errorLit (pfile,
5170 cstring_makeLiteralTemp ("invalid format `#line' command"));
5171 goto bad_line_directive;
5174 file_change = enter_file;
5176 file_change = leave_file;
5178 ip->system_header_p = 1;
5179 else /* if (*p == 4) */
5180 ip->system_header_p = 2;
5182 cppReader_setWritten (pfile, num_start);
5183 token = get_directive_token (pfile);
5184 p = pfile->token_buffer + num_start;
5185 if (token == CPP_NUMBER && p[1] == '\0' && (*p == '3' || *p== '4')) {
5186 ip->system_header_p = *p == 3 ? 1 : 2;
5187 token = get_directive_token (pfile);
5189 if (token != CPP_VSPACE) {
5190 cppReader_errorLit (pfile,
5191 cstring_makeLiteralTemp ("invalid format `#line' command"));
5193 goto bad_line_directive;
5198 &fname_table[cpphash_hashCode (fname, fname_length, FNAME_HASHSIZE)];
5200 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
5202 if (hp->length == fname_length)
5204 llassert (hp->value.cpval != NULL);
5206 if (strncmp (hp->value.cpval, fname, fname_length) == 0)
5208 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
5215 /* Didn't find it; cons up a new one. */
5216 hp = (hashNode) dmalloc (sizeof (*hp));
5219 hp->bucket_hdr = NULL;
5221 hp->name = cstring_undefined;
5222 hp->next = *hash_bucket;
5226 hp->length = fname_length;
5227 hp->value.cpval = dmalloc (sizeof (*hp->value.cpval) * (fname_length + 1));
5228 memcpy (hp->value.cpval, fname, fname_length);
5229 hp->value.cpval[fname_length] = '\0';
5230 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
5233 else if (token != CPP_VSPACE && token != CPP_EOF)
5235 cppReader_errorLit (pfile,
5236 cstring_makeLiteralTemp ("invalid format `#line' command"));
5237 goto bad_line_directive;
5244 ip->lineno = new_lineno;
5246 cppReader_skipRestOfLine (pfile);
5247 cppReader_setWritten (pfile, old_written);
5248 output_line_command (pfile, 0, file_change);
5253 * remove the definition of a symbol from the symbol table.
5254 * according to un*x /lib/cpp, it is not an error to undef
5255 * something that has no definitions, so it isn't one here either.
5259 do_undef (cppReader *pfile, struct directive *keyword, char *buf, char *limit)
5264 char *orig_buf = buf;
5266 SKIP_WHITE_SPACE (buf);
5268 sym_length = cppReader_checkMacroName (pfile, buf, cstring_makeLiteralTemp ("macro"));
5270 while ((hp = cpphash_lookup (buf, size_toInt (sym_length), -1)) != NULL)
5272 /* If we are generating additional info for debugging (with -g) we
5273 need to pass through all effective #undef commands. */
5274 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
5276 pass_thru_directive (orig_buf, limit, pfile, keyword);
5279 if (hp->type != T_MACRO)
5281 cppReader_warning (pfile,
5282 message ("Undefining preprocessor builtin: %s",
5286 cppReader_deleteMacro (hp);
5289 if (cppReader_isPedantic (pfile)) {
5291 SKIP_WHITE_SPACE (buf);
5294 cppReader_pedwarnLit (pfile,
5295 cstring_makeLiteralTemp ("garbage after `#undef' directive"));
5304 * Report an error detected by the program we are processing.
5305 * Use the text of the line in the error message.
5306 * (We use error because it prints the filename & line#.)
5310 do_error (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5311 char *buf, char *limit)
5313 size_t length = size_fromInt (limit - buf);
5314 cstring copy = cstring_copyLength (buf, length);
5315 cstring adv = cstring_advanceWhiteSpace (copy);
5317 cppReader_error (pfile, message ("#error %s", adv));
5318 cstring_free (copy);
5323 * Report a warning detected by the program we are processing.
5324 * Use the text of the line in the warning message, then continue.
5325 * (We use error because it prints the filename & line#.)
5329 do_warning (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5330 char *buf, char *limit)
5332 size_t length = size_fromInt (limit - buf);
5333 cstring copy = cstring_copyLength (buf, length);
5334 cstring adv = cstring_advanceWhiteSpace (copy);
5335 cppReader_warning (pfile, message ("#warning %s", adv));
5336 cstring_free (copy);
5341 /* #ident has already been copied to the output file, so just ignore it. */
5344 do_ident (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5345 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5347 /* Allow #ident in system headers, since that's not user's fault. */
5348 if (cppReader_isPedantic (pfile)
5349 && !cppReader_getBufferSafe (pfile)->system_header_p)
5350 cppReader_pedwarnLit (pfile,
5351 cstring_makeLiteralTemp ("ANSI C does not allow `#ident'"));
5353 /* Leave rest of line to be read by later calls to cpplib_getToken. */
5358 /* #pragma and its argument line have already been copied to the output file.
5359 Just check for some recognized pragmas that need validation here. */
5362 do_pragma (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5363 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5365 while (*buf == ' ' || *buf == '\t')
5370 if (!strncmp (buf, "implementation", 14)) {
5371 /* Be quiet about `#pragma implementation' for a file only if it hasn't
5372 been included yet. */
5373 struct file_name_list *ptr;
5374 char *p = buf + 14, *fname, *inc_fname;
5376 SKIP_WHITE_SPACE (p);
5377 if (*p == '\n' || *p != '\"')
5381 p = (char *) strchr (fname, '\"');
5382 fname_len = p != NULL ? size_fromInt (p - fname) : mstring_length (fname);
5384 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
5386 inc_fname = (char *) strrchr (cstring_toCharsSafe (ptr->fname), CONNECTCHAR);
5387 inc_fname = (inc_fname != NULL)
5388 ? inc_fname + 1 : cstring_toCharsSafe (ptr->fname);
5390 if ((inc_fname != NULL)
5391 && (strncmp (inc_fname, fname, fname_len) == 0))
5393 cpp_setLocation (pfile);
5395 ppllerror (message ("`#pragma implementation' for `%s' appears "
5396 "after file is included",
5397 cstring_fromChars (fname)));
5406 * handle #if command by
5407 * 1) inserting special `defined' keyword into the hash table
5408 * that gets turned into 0 or 1 by special_symbol (thus,
5409 * if the luser has a symbol called `defined' already, it won't
5410 * work inside the #if command)
5411 * 2) rescan the input into a temporary output buffer
5412 * 3) pass the output buffer to the yacc parser and collect a value
5413 * 4) clean up the mess left from steps 1 and 2.
5414 * 5) call conditional_skip to skip til the next #endif (etc.),
5415 * or not, depending on the value from step 3.
5419 do_if (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5420 char *buf, char *limit)
5422 HOST_WIDE_INT value;
5423 DPRINTF (("Do if: %s", buf));
5424 value = eval_if_expression (pfile, buf, limit - buf);
5425 conditional_skip (pfile, value == 0, T_IF, NULL);
5430 * handle a #elif directive by not changing if_stack either.
5431 * see the comment above do_else.
5434 static int do_elif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5435 char *buf, char *limit)
5437 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5439 cppReader_errorLit (pfile,
5440 cstring_makeLiteralTemp ("Preprocessor command #elif is not within a conditional"));
5445 llassert (pfile->if_stack != NULL);
5447 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
5449 cppReader_errorLit (pfile,
5450 cstring_makeLiteralTemp ("`#elif' after `#else'"));
5452 if (pfile->if_stack->fname != NULL
5453 && cppReader_getBufferSafe (pfile)->fname != NULL
5454 && !cstring_equal (pfile->if_stack->fname,
5455 cppReader_getBufferSafe (pfile)->nominal_fname))
5456 fprintf (stderr, ", file %s", cstring_toCharsSafe (pfile->if_stack->fname));
5457 fprintf (stderr, ")\n");
5459 pfile->if_stack->type = T_ELIF;
5462 if (pfile->if_stack->if_succeeded)
5464 skip_if_group (pfile, 0);
5468 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
5470 skip_if_group (pfile, 0);
5473 ++pfile->if_stack->if_succeeded; /* continue processing input */
5474 output_line_command (pfile, 1, same_file);
5482 * evaluate a #if expression in BUF, of length LENGTH,
5483 * then parse the result as a C expression and return the value as an int.
5486 static HOST_WIDE_INT
5487 eval_if_expression (cppReader *pfile,
5488 /*@unused@*/ char *buf,
5489 /*@unused@*/ int length)
5491 hashNode save_defined;
5492 HOST_WIDE_INT value;
5493 size_t old_written = cpplib_getWritten (pfile);
5495 DPRINTF (("Saving defined..."));
5496 save_defined = cpphash_install ("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
5497 pfile->pcp_inside_if = 1;
5499 value = cppReader_parseExpression (pfile);
5500 pfile->pcp_inside_if = 0;
5502 /* Clean up special symbol */
5503 DPRINTF (("Removing defined..."));
5504 cppReader_deleteMacro (save_defined);
5505 cppReader_setWritten (pfile, old_written); /* Pop */
5511 * routine to handle ifdef/ifndef. Try to look up the symbol,
5512 * then do or don't skip to the #endif/#else/#elif depending
5513 * on what directive is actually being processed.
5517 do_xifdef (cppReader *pfile, struct directive *keyword,
5518 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
5521 cppBuffer *ip = cppReader_getBufferSafe (pfile);
5523 size_t ident_length;
5524 enum cpp_token token;
5525 int start_of_file = 0;
5526 char *control_macro = 0;
5527 size_t old_written = cpplib_getWritten (pfile);
5529 DPRINTF (("do xifdef: %d",
5530 keyword->type == T_IFNDEF));
5532 /* Detect a #ifndef at start of file (not counting comments). */
5533 if (cstring_isDefined (ip->fname) && keyword->type == T_IFNDEF)
5535 start_of_file = pfile->only_seen_white == 2;
5538 pfile->no_macro_expand++;
5539 token = get_directive_token (pfile);
5540 pfile->no_macro_expand--;
5542 ident = pfile->token_buffer + old_written;
5543 DPRINTF (("Ident: %s", ident));
5545 ident_length = cpplib_getWritten (pfile) - old_written;
5546 cppReader_setWritten (pfile, old_written); /* Pop */
5548 if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
5550 skip = (keyword->type == T_IFDEF);
5551 if (! cppReader_isTraditional (pfile))
5553 cppReader_pedwarn (pfile,
5554 message ("`#%s' with no argument", keyword->name));
5557 else if (token == CPP_NAME)
5559 hashNode hp = cpphash_lookup (ident, size_toInt (ident_length), -1);
5561 skip = (keyword->type == T_IFDEF) ? (hp == NULL) : (hp != NULL);
5563 DPRINTF (("hp null: %d / %d / %d", hp == NULL, keyword->type == T_IFNDEF, skip));
5565 if (start_of_file && !skip)
5567 DPRINTF (("Not skipping!"));
5568 control_macro = (char *) dmalloc (ident_length + 1);
5569 memcpy (control_macro, ident, ident_length + 1);
5574 skip = (keyword->type == T_IFDEF);
5575 if (! cppReader_isTraditional (pfile))
5577 cppReader_error (pfile,
5578 message ("`#%s' with invalid argument", keyword->name));
5582 if (!cppReader_isTraditional (pfile))
5585 cppSkipHspace (pfile);
5586 c = cppReader_peekC (pfile);
5587 if (c != EOF && c != '\n')
5589 cppReader_pedwarn (pfile,
5590 message ("garbage at end of `#%s' argument", keyword->name));
5594 cppReader_skipRestOfLine (pfile);
5596 DPRINTF (("Conditional skip: %d", skip));
5597 conditional_skip (pfile, skip, T_IF, control_macro);
5601 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
5602 If this is a #ifndef starting at the beginning of a file,
5603 CONTROL_MACRO is the macro name tested by the #ifndef.
5604 Otherwise, CONTROL_MACRO is 0. */
5607 conditional_skip (cppReader *pfile, int skip,
5608 enum node_type type,
5609 /*@dependent@*/ char *control_macro)
5611 cppIfStackFrame *temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
5613 temp->fname = cppReader_getBufferSafe (pfile)->nominal_fname;
5614 temp->next = pfile->if_stack;
5615 temp->control_macro = control_macro;
5617 temp->if_succeeded = 0;
5619 pfile->if_stack = temp;
5620 pfile->if_stack->type = type;
5624 skip_if_group (pfile, 0);
5629 ++pfile->if_stack->if_succeeded;
5630 output_line_command (pfile, 1, same_file);
5635 * skip to #endif, #else, or #elif. adjust line numbers, etc.
5636 * leaves input ptr at the sharp sign found.
5637 * If ANY is nonzero, return at next directive of any sort.
5641 skip_if_group (cppReader *pfile, int any)
5644 struct directive *kt;
5645 cppIfStackFrame *save_if_stack = pfile->if_stack; /* don't pop past here */
5646 register int ident_length;
5648 struct parse_marker line_start_mark;
5650 parseSetMark (&line_start_mark, pfile);
5652 if (CPPOPTIONS (pfile)->output_conditionals) {
5653 static char failed[] = "#failed\n";
5654 cppReader_puts (pfile, failed, sizeof(failed)-1);
5656 output_line_command (pfile, 1, same_file);
5660 if (CPPOPTIONS (pfile)->output_conditionals)
5662 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
5665 llassert (pbuf->buf != NULL);
5667 start_line = pbuf->buf + line_start_mark.position;
5668 cppReader_puts (pfile, start_line, size_fromInt (pbuf->cur - start_line));
5671 parseMoveMark (&line_start_mark, pfile);
5673 if (!cppReader_isTraditional (pfile))
5675 cppSkipHspace (pfile);
5678 c = cppReader_getC (pfile);
5681 size_t old_written = cpplib_getWritten (pfile);
5682 cppSkipHspace (pfile);
5684 parse_name (pfile, cppReader_getC (pfile));
5685 ident_length = size_toInt (cpplib_getWritten (pfile) - old_written);
5686 ident = pfile->token_buffer + old_written;
5687 pfile->limit = ident;
5689 for (kt = directive_table; kt->length >= 0; kt++)
5691 cppIfStackFrame *temp;
5692 if (ident_length == kt->length
5693 && cstring_equalPrefix (kt->name, cstring_fromChars (ident)))
5695 /* If we are asked to return on next directive, do so now. */
5706 temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
5707 temp->next = pfile->if_stack;
5708 temp->fname = cppReader_getBufferSafe (pfile)->nominal_fname;
5709 temp->type = kt->type;
5711 temp->if_succeeded = 0;
5712 temp->control_macro = NULL;
5714 pfile->if_stack = temp;
5715 /*@switchbreak@*/ break;
5718 if (cppReader_isPedantic (pfile) && pfile->if_stack != save_if_stack)
5719 validate_else (pfile,
5720 cstring_makeLiteralTemp (kt->type == T_ELSE ? "#else" : "#endif"));
5723 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5725 cppReader_error (pfile,
5726 message ("Preprocessor command #%s is not within a conditional", kt->name));
5727 /*@switchbreak@*/ break;
5729 else if (pfile->if_stack == save_if_stack)
5731 goto done; /* found what we came for */
5738 if (kt->type != T_ENDIF)
5740 llassert (pfile->if_stack != NULL);
5742 if (pfile->if_stack->type == T_ELSE)
5744 cppReader_errorLit (pfile,
5745 cstring_makeLiteralTemp ("`#else' or `#elif' after `#else'"));
5748 pfile->if_stack->type = kt->type;
5749 /*@switchbreak@*/ break;
5752 temp = pfile->if_stack;
5753 llassert (temp != NULL);
5754 pfile->if_stack = temp->next;
5756 /*@switchbreak@*/ break;
5759 #if defined (OS2) && defined (__IBMC__)
5760 /* Dummy code to eleminate optimization problems with icc */
5769 /* Don't let erroneous code go by. */
5771 if (kt->length < 0 && !CPPOPTIONS (pfile)->lang_asm
5772 && cppReader_isPedantic (pfile))
5774 cppReader_pedwarnLit (pfile,
5775 cstring_makeLiteralTemp ("Invalid preprocessor directive name"));
5779 c = cppReader_getC (pfile);
5781 /* We're in the middle of a line. Skip the rest of it. */
5789 case '/': /* possible comment */
5790 c = skip_comment (pfile, NULL);
5793 /*@switchbreak@*/ break;
5796 cppReader_forward (pfile, -1);
5797 old = cpplib_getWritten (pfile);
5798 (void) cpplib_getToken (pfile);
5799 cppReader_setWritten (pfile, old);
5800 /*@switchbreak@*/ break;
5802 /* Char after backslash loses its special meaning. */
5803 if (cppReader_peekC (pfile) == '\n')
5805 cppReader_forward (pfile, 1);
5808 /*@switchbreak@*/ break;
5812 c = cppReader_getC (pfile);
5815 if (CPPOPTIONS (pfile)->output_conditionals) {
5816 static char end_failed[] = "#endfailed\n";
5817 cppReader_puts (pfile, end_failed, sizeof(end_failed)-1);
5820 pfile->only_seen_white = 1;
5822 parseGotoMark (&line_start_mark, pfile);
5823 parseClearMark (&line_start_mark);
5827 * handle a #else directive. Do this by just continuing processing
5828 * without changing if_stack ; this is so that the error message
5829 * for missing #endif's etc. will point to the original #if. It
5830 * is possible that something different would be better.
5834 do_else (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5835 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5837 if (cppReader_isPedantic (pfile))
5839 validate_else (pfile, cstring_makeLiteralTemp ("#else"));
5842 cppReader_skipRestOfLine (pfile);
5844 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack) {
5845 cppReader_errorLit (pfile,
5846 cstring_makeLiteralTemp ("Preprocessor command #else is not within a conditional"));
5849 /* #ifndef can't have its special treatment for containing the whole file
5850 if it has a #else clause. */
5852 llassert (pfile->if_stack != NULL);
5854 pfile->if_stack->control_macro = 0;
5856 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
5858 cpp_setLocation (pfile);
5859 genppllerrorhint (FLG_PREPROC,
5860 message ("Pre-processor directive #else after #else"),
5861 message ("%q: Location of match",
5862 fileloc_unparseRaw (pfile->if_stack->fname,
5863 pfile->if_stack->lineno)));
5866 pfile->if_stack->type = T_ELSE;
5869 if (pfile->if_stack->if_succeeded)
5870 skip_if_group (pfile, 0);
5872 ++pfile->if_stack->if_succeeded; /* continue processing input */
5873 output_line_command (pfile, 1, same_file);
5880 * unstack after #endif command
5884 do_endif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5885 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5887 if (cppReader_isPedantic (pfile))
5889 validate_else (pfile, cstring_makeLiteralTemp ("#endif"));
5892 cppReader_skipRestOfLine (pfile);
5894 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5896 cppReader_errorLit (pfile, cstring_makeLiteralTemp ("Unbalanced #endif"));
5900 cppIfStackFrame *temp = pfile->if_stack;
5902 llassert (temp != NULL);
5904 pfile->if_stack = temp->next;
5905 if (temp->control_macro != 0)
5907 /* This #endif matched a #ifndef at the start of the file.
5908 See if it is at the end of the file. */
5909 struct parse_marker start_mark;
5912 parseSetMark (&start_mark, pfile);
5916 cppSkipHspace (pfile);
5917 c = cppReader_getC (pfile);
5923 parseGotoMark (&start_mark, pfile);
5924 parseClearMark (&start_mark);
5928 /* If we get here, this #endif ends a #ifndef
5929 that contains all of the file (aside from whitespace).
5930 Arrange not to include the file again
5931 if the macro that was tested is defined.
5933 Do not do this for the top-level file in a -include or any
5934 file in a -imacros. */
5935 struct file_name_list *ifile = pfile->all_include_files;
5937 for ( ; ifile != NULL; ifile = ifile->next)
5939 if (cstring_equal (ifile->fname, cppReader_getBufferSafe (pfile)->fname))
5941 ifile->control_macro = temp->control_macro;
5949 output_line_command (pfile, 1, same_file);
5954 /* When an #else or #endif is found while skipping failed conditional,
5955 if -pedantic was specified, this is called to warn about text after
5956 the command name. P points to the first char after the command name. */
5959 validate_else (cppReader *pfile, cstring directive)
5962 cppSkipHspace (pfile);
5963 c = cppReader_peekC (pfile);
5964 if (c != EOF && c != '\n')
5966 cppReader_pedwarn (pfile,
5967 message ("text following `%s' violates ANSI standard", directive));
5972 ** Get the next token, and add it to the text in pfile->token_buffer.
5973 ** Return the kind of token we got.
5977 cpplib_getToken (cppReader *pfile)
5979 return cpplib_getTokenAux (pfile, FALSE);
5983 cpplib_getTokenForceExpand (cppReader *pfile)
5985 return cpplib_getTokenAux (pfile, TRUE);
5989 cpplib_getTokenAux (cppReader *pfile, bool forceExpand)
5992 size_t old_written = 0;
5993 int start_line, start_column;
5994 enum cpp_token token;
5995 struct cppOptions *opts = CPPOPTIONS (pfile);
5996 cppReader_getBufferSafe (pfile)->prev = cppReader_getBufferSafe (pfile)->cur;
5999 c = cppReader_getC (pfile);
6000 DPRINTF (("Get next token: %c", c));
6005 if (cppReader_getBufferSafe (pfile)->seen_eof)
6007 cppBuffer *buf = cppReader_popBuffer (pfile);
6009 if (buf != cppReader_nullBuffer (pfile))
6020 cppBuffer *next_buf = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6021 cppReader_getBufferSafe (pfile)->seen_eof = 1;
6023 if (cstring_isDefined (cppReader_getBufferSafe (pfile)->nominal_fname)
6024 && next_buf != cppReader_nullBuffer (pfile))
6026 /* We're about to return from an #include file.
6027 Emit #line information now (as part of the CPP_POP) result.
6028 But the #line refers to the file we will pop to. */
6029 cppBuffer *cur_buffer = CPPBUFFER (pfile);
6030 CPPBUFFER (pfile) = next_buf;
6031 pfile->input_stack_listing_current = 0;
6032 output_line_command (pfile, 0, leave_file);
6033 CPPBUFFER (pfile) = cur_buffer;
6041 struct parse_marker start_mark;
6046 if (cppReader_peekC (pfile) == '=')
6051 if (opts->put_out_comments)
6053 parseSetMark (&start_mark, pfile);
6057 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile),
6058 &start_line, &start_column);
6059 c = skip_comment (pfile, &newlines);
6060 DPRINTF (("c = %c", c));
6061 if (opts->put_out_comments && (c == '/' || c == EOF))
6063 assertSet (&start_mark);
6064 parseClearMark (&start_mark);
6071 cppReader_errorWithLine (pfile, start_line, start_column,
6072 cstring_makeLiteral ("Unterminated comment"));
6075 c = '/'; /* Initial letter of comment. */
6077 /* Comments are equivalent to spaces.
6078 For -traditional, a comment is equivalent to nothing. */
6080 if (opts->put_out_comments)
6084 assertSet (&start_mark);
6085 res = cpp_handleComment (pfile, &start_mark);
6086 pfile->lineno += newlines;
6089 else if (cppReader_isTraditional (pfile))
6095 cpplib_reserve(pfile, 1);
6096 cppReader_putCharQ (pfile, ' ');
6101 if (!pfile->only_seen_white)
6106 if (cppReader_handleDirective (pfile))
6108 return CPP_DIRECTIVE;
6111 pfile->only_seen_white = 0;
6116 /* A single quoted string is treated like a double -- some
6117 programs (e.g., troff) are perverse this way */
6118 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile),
6119 &start_line, &start_column);
6120 old_written = cpplib_getWritten (pfile);
6122 DPRINTF (("Reading string: %c", c));
6123 cppReader_putChar (pfile, c);
6127 ** Because of ISO8859-1 characters in string literals, we need a special test here.
6130 if (cppReader_reachedEOF (pfile))
6133 DPRINTF (("Matches EOF!"));
6134 if (cppBuffer_isMacro (CPPBUFFER (pfile)))
6136 /* try harder: this string crosses a macro expansion
6137 boundary. This can happen naturally if -traditional.
6138 Otherwise, only -D can make a macro with an unmatched
6141 = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6142 (*cppReader_getBufferSafe (pfile)->cleanup)
6143 (cppReader_getBufferSafe (pfile), pfile);
6144 CPPBUFFER (pfile) = next_buf;
6148 if (!cppReader_isTraditional (pfile))
6150 cpp_setLocation (pfile);
6152 setLine (long_toInt (start_line));
6153 setColumn (long_toInt (start_column));
6155 if (pfile->multiline_string_line != long_toInt (start_line)
6156 && pfile->multiline_string_line != 0)
6160 message ("Unterminated string or character constant"),
6161 message ("%q: Possible real start of unterminated constant",
6163 (fileloc_filename (g_currentloc),
6164 pfile->multiline_string_line)));
6165 pfile->multiline_string_line = 0;
6171 message ("Unterminated string or character constant"));
6174 /*@loopbreak@*/ break;
6178 int cc = cppReader_getC (pfile);
6179 DPRINTF (("cc: %c [%d] [%d]", cc, cc, EOF));
6180 DPRINTF (("putting char: %c", cc));
6181 cppReader_putChar (pfile, cc);
6185 /* Traditionally, end of line ends a string constant with
6186 no error. So exit the loop and record the new line. */
6187 if (cppReader_isTraditional (pfile))
6193 if (cppReader_isPedantic (pfile)
6194 && pfile->multiline_string_line == 0)
6196 cppReader_pedwarnWithLine
6197 (pfile, long_toInt (start_line),
6198 long_toInt (start_column),
6199 cstring_makeLiteral ("String constant runs past end of line"));
6201 if (pfile->multiline_string_line == 0)
6203 pfile->multiline_string_line = start_line;
6206 /*@switchbreak@*/ break;
6209 cc = cppReader_getC (pfile);
6212 /* Backslash newline is replaced by nothing at all. */
6213 pfile->lineno++; /* 2003-11-03: AMiller suggested adding this, but
6214 its not clear why it is needed. */
6215 cppReader_adjustWritten (pfile, -1);
6220 /* ANSI stupidly requires that in \\ the second \
6221 is *not* prevented from combining with a newline. */
6224 cppReader_putChar (pfile, cc);
6226 /*@switchbreak@*/ break;
6232 /*@switchbreak@*/ break;
6237 pfile->lineno += count_newlines (pfile->token_buffer + old_written,
6238 cpplib_getPWritten (pfile));
6239 pfile->only_seen_white = 0;
6240 return c == '\'' ? CPP_CHAR : CPP_STRING;
6243 if (!opts->dollars_in_ident)
6248 if (opts->cplusplus && cppReader_peekC (pfile) == ':')
6256 c2 = cppReader_peekC (pfile);
6257 if (c2 == c || c2 == '=')
6267 if (cppReader_peekC (pfile) == '=')
6273 c2 = cppReader_peekC (pfile);
6274 if (c2 == '-' && opts->chill)
6276 /* Chill style comment */
6277 if (opts->put_out_comments)
6279 parseSetMark (&start_mark, pfile);
6282 cppReader_forward (pfile, 1); /* Skip second '-'. */
6286 c = cppReader_getC (pfile);
6288 /*@loopbreak@*/ break;
6291 /* Don't consider final '\n' to be part of comment. */
6292 cppReader_forward (pfile, -1);
6293 /*@loopbreak@*/ break;
6297 goto return_comment;
6299 if (c2 == '-' || c2 == '=' || c2 == '>')
6304 if (pfile->parsing_include_directive)
6308 cppReader_putChar (pfile, c);
6310 /*@loopbreak@*/ break;
6311 c = cppReader_getC (pfile);
6313 if (c == '\n' || c == EOF)
6315 cppReader_errorLit (pfile,
6316 cstring_makeLiteralTemp ("Missing '>' in \"#include <FILENAME>\""));
6317 /*@loopbreak@*/ break;
6325 c2 = cppReader_peekC (pfile);
6330 cppReader_forward (pfile, 1);
6331 cpplib_reserve (pfile, 4);
6332 cppReader_putChar (pfile, c);
6333 cppReader_putChar (pfile, c2);
6335 c3 = cppReader_peekC (pfile);
6337 cppReader_putCharQ (pfile, cppReader_getC (pfile));
6338 cppReader_nullTerminateQ (pfile);
6339 pfile->only_seen_white = 0;
6343 DPRINTF (("Macro @!"));
6344 if (cppReader_getBufferSafe (pfile)->has_escapes)
6346 c = cppReader_getC (pfile);
6347 DPRINTF (("got c: %c", c));
6350 if (pfile->output_escapes)
6351 cppReader_puts (pfile, "@-", 2);
6352 parse_name (pfile, cppReader_getC (pfile));
6355 else if (is_space [c])
6357 cpplib_reserve (pfile, 2);
6358 if (pfile->output_escapes)
6359 cppReader_putCharQ (pfile, '@');
6360 cppReader_putCharQ (pfile, c);
6368 if (pfile->output_escapes)
6370 cppReader_puts (pfile, "@@", 2);
6376 c2 = cppReader_peekC (pfile);
6379 cpplib_reserve(pfile, 2);
6380 cppReader_putCharQ (pfile, '.');
6381 c = cppReader_getC (pfile);
6385 /* FIXME - misses the case "..\\\n." */
6386 if (c2 == '.' && cpp_peekN (pfile, 1) == '.')
6388 cpplib_reserve(pfile, 4);
6389 cppReader_putCharQ (pfile, '.');
6390 cppReader_putCharQ (pfile, '.');
6391 cppReader_putCharQ (pfile, '.');
6392 cppReader_forward (pfile, 2);
6393 cppReader_nullTerminateQ (pfile);
6394 pfile->only_seen_white = 0;
6400 pfile->only_seen_white = 0;
6401 op2any: /* jumped to for \ continuations */
6402 cpplib_reserve(pfile, 3);
6403 cppReader_putCharQ (pfile, c);
6405 /* evans 2003-08-24: This is a hack to fix line output for \
6406 continuations. Someday I really should get a decent pre-processor!
6410 (void) cppReader_getC (pfile); /* skip the newline to avoid extra lines */
6412 cppReader_putCharQ (pfile, cppReader_getC (pfile));
6415 cppReader_nullTerminateQ (pfile);
6420 c2 = cppReader_peekC (pfile);
6421 if ((c2 == '\'' || c2 == '\"') && !cppReader_isTraditional (pfile))
6423 cppReader_putChar (pfile, c);
6424 c = cppReader_getC (pfile);
6429 case '0': case '1': case '2': case '3': case '4':
6430 case '5': case '6': case '7': case '8': case '9':
6435 cpplib_reserve (pfile, 2);
6436 cppReader_putCharQ (pfile, c);
6438 c = cppReader_peekC (pfile);
6440 /*@loopbreak@*/ break;
6441 if (!is_idchar[c] && c != '.'
6442 && ((c2 != 'e' && c2 != 'E'
6443 && ((c2 != 'p' && c2 != 'P') || cppReader_isC89 (pfile)))
6444 || (c != '+' && c != '-')))
6445 /*@loopbreak@*/ break;
6446 cppReader_forward (pfile, 1);
6450 cppReader_nullTerminateQ (pfile);
6451 pfile->only_seen_white = 0;
6454 case 'b': case 'c': case 'd': case 'h': case 'o':
6455 case 'B': case 'C': case 'D': case 'H': case 'O':
6456 if (opts->chill && cppReader_peekC (pfile) == '\'')
6458 pfile->only_seen_white = 0;
6459 cpplib_reserve (pfile, 2);
6460 cppReader_putCharQ (pfile, c);
6461 cppReader_putCharQ (pfile, '\'');
6462 cppReader_forward (pfile, 1);
6465 c = cppReader_getC (pfile);
6467 goto chill_number_eof;
6470 if (c == '\\' && cppReader_peekC (pfile) == '\n')
6472 cppReader_forward (pfile, 2);
6475 /*@loopbreak@*/ break;
6477 cppReader_putChar (pfile, c);
6481 cpplib_reserve (pfile, 2);
6482 cppReader_putCharQ (pfile, c);
6483 cppReader_nullTerminateQ (pfile);
6488 cppReader_forward (pfile, -1);
6490 cppReader_nullTerminate (pfile);
6497 case 'a': case 'e': case 'f': case 'g': case 'i': case 'j':
6498 case 'k': case 'l': case 'm': case 'n': case 'p': case 'q':
6499 case 'r': case 's': case 't': case 'u': case 'v': case 'w':
6500 case 'x': case 'y': case 'z':
6501 case 'A': case 'E': case 'F': case 'G': case 'I': case 'J':
6502 case 'K': case 'M': case 'N': case 'P': case 'Q': case 'R':
6503 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
6509 size_t before_name_written = cpplib_getWritten (pfile);
6511 parse_name (pfile, c);
6512 pfile->only_seen_white = 0;
6514 if (pfile->no_macro_expand)
6516 DPRINTF (("Not expanding: %s", pfile->token_buffer));
6520 ident = pfile->token_buffer + before_name_written;
6521 DPRINTF (("Ident: %s", ident));
6523 ident_len = size_fromInt ((cpplib_getPWritten (pfile)) - ident);
6525 hp = cpphash_lookupExpand (ident, size_toInt (ident_len), -1, forceExpand);
6529 DPRINTF (("No expand: %s %d", ident, ident_len));
6533 if (hp->type == T_DISABLED)
6535 DPRINTF (("Disabled!"));
6537 if (pfile->output_escapes)
6538 { /* Return "@-IDENT", followed by '\0'. */
6540 cpplib_reserve (pfile, 3);
6541 ident = pfile->token_buffer + before_name_written;
6542 cppReader_adjustWritten (pfile, 2);
6544 for (i = size_toInt (ident_len); i >= 0; i--)
6546 ident[i+2] = ident[i];
6556 ** If macro wants an arglist, verify that a '(' follows.
6557 ** first skip all whitespace, copying it to the output
6558 ** after the macro name. Then, if there is no '(',
6559 ** decide this is not a macro call and leave things that way.
6562 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
6564 struct parse_marker macro_mark;
6567 DPRINTF (("Arglist macro!"));
6570 ** evans 2002-07-03: Moved this here (from below).
6571 ** This bug caused necessary whitespace to be lost
6572 ** when parsing parameterized macros without parameters.
6575 parseSetMark (¯o_mark, pfile);
6577 while (cppBuffer_isMacro (CPPBUFFER (pfile)))
6579 cppBuffer *next_buf;
6580 cppSkipHspace (pfile);
6581 if (cppReader_peekC (pfile) != EOF)
6583 DPRINTF (("Peeking!"));
6584 /*@loopbreak@*/ break;
6587 next_buf = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6588 (*cppReader_getBufferSafe (pfile)->cleanup) (cppReader_getBufferSafe (pfile), pfile);
6589 CPPBUFFER (pfile) = next_buf;
6592 /* parseSetMark (¯o_mark, pfile); */
6596 cppSkipHspace (pfile);
6597 c = cppReader_peekC (pfile);
6598 DPRINTF (("c: %c", c));
6599 is_macro_call = c == '(';
6601 /*@loopbreak@*/ break;
6602 cppReader_forward (pfile, 1);
6607 parseGotoMark (¯o_mark, pfile);
6610 parseClearMark (¯o_mark);
6614 DPRINTF (("not macro call!"));
6619 /* This is now known to be a macro call. */
6621 /* it might not actually be a macro. */
6622 if (hp->type != T_MACRO)
6627 cppReader_setWritten (pfile, before_name_written);
6628 special_symbol (hp, pfile);
6629 xbuf_len = cpplib_getWritten (pfile) - before_name_written;
6630 xbuf = (char *) dmalloc (xbuf_len + 1);
6631 cppReader_setWritten (pfile, before_name_written);
6632 memcpy (xbuf, cpplib_getPWritten (pfile), xbuf_len + 1);
6633 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
6638 ** Expand the macro, reading arguments as needed,
6639 ** and push the expansion on the input stack.
6642 cpplib_macroExpand (pfile, hp);
6643 cppReader_setWritten (pfile, before_name_written);
6646 /* An extra "@ " is added to the end of a macro expansion
6647 to prevent accidental token pasting. We prefer to avoid
6648 unneeded extra spaces (for the sake of cpp-using tools like
6649 imake). Here we remove the space if it is safe to do so. */
6651 llassert (pfile->buffer->rlimit != NULL);
6653 if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
6654 && pfile->buffer->rlimit[-2] == '@'
6655 && pfile->buffer->rlimit[-1] == ' ')
6657 int c1 = pfile->buffer->rlimit[-3];
6658 int cl2 = cpplib_bufPeek (cppBuffer_prevBuffer (CPPBUFFER (pfile)));
6660 if (cl2 == EOF || !unsafe_chars ((char) c1, (char) cl2))
6661 pfile->buffer->rlimit -= 2;
6667 case ' ': case '\t': case '\v': case '\r':
6670 cppReader_putChar (pfile, c);
6671 c = cppReader_peekC (pfile);
6672 if (c == EOF || !is_hor_space[c])
6673 /*@loopbreak@*/ break;
6674 cppReader_forward (pfile, 1);
6679 c2 = cppReader_peekC (pfile);
6680 /* allow other stuff here if a flag is set? */
6681 DPRINTF (("Got continuation!"));
6688 cppReader_putChar (pfile, c);
6689 if (pfile->only_seen_white == 0)
6690 pfile->only_seen_white = 1;
6692 output_line_command (pfile, 1, same_file);
6695 case '(': token = CPP_LPAREN; goto char1;
6696 case ')': token = CPP_RPAREN; goto char1;
6697 case '{': token = CPP_LBRACE; goto char1;
6698 case '}': token = CPP_RBRACE; goto char1;
6699 case ',': token = CPP_COMMA; goto char1;
6700 case ';': token = CPP_SEMICOLON; goto char1;
6706 pfile->only_seen_white = 0;
6707 cppReader_putChar (pfile, c);
6716 /* Parse an identifier starting with C. */
6719 parse_name (cppReader *pfile, int c)
6725 if (c == '\\' && cppReader_peekC (pfile) == '\n')
6727 cppReader_forward (pfile, 2);
6731 cppReader_forward (pfile, -1);
6735 if (c == '$' && cppReader_isPedantic (pfile))
6737 cppReader_pedwarnLit (pfile,
6738 cstring_makeLiteralTemp ("`$' in identifier"));
6741 cpplib_reserve(pfile, 2); /* One more for final NUL. */
6742 cppReader_putCharQ (pfile, c);
6743 c = cppReader_getC (pfile);
6749 cppReader_nullTerminateQ (pfile);
6752 /* The file_name_map structure holds a mapping of file names for a
6753 particular directory. This mapping is read from the file named
6754 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
6755 map filenames on a file system with severe filename restrictions,
6756 such as DOS. The format of the file name map file is just a series
6757 of lines with two tokens on each line. The first token is the name
6758 to map, and the second token is the actual name to use. */
6760 struct file_name_map
6762 struct file_name_map *map_next;
6767 /*@constant observer char *FILE_NAME_MAP_FILE*/
6768 #define FILE_NAME_MAP_FILE "header.gcc"
6770 /* Read a space delimited string of unlimited length from a stdio
6773 static cstring read_filename_string (int ch, /*:open:*/ FILE *f)
6779 set = alloc = dmalloc (len + 1);
6784 while ((ch = getc (f)) != EOF && ! is_space[ch])
6786 if (set - alloc == size_toInt (len))
6789 alloc = drealloc (alloc, len + 1);
6790 set = alloc + len / 2;
6791 /*@-branchstate@*/ }
6794 } /*@=branchstate@*/
6797 check (ungetc (ch, f) != EOF);
6799 return cstring_fromChars (alloc);
6802 /* This structure holds a linked list of file name maps, one per directory. */
6804 struct file_name_map_list
6806 /*@only@*/ struct file_name_map_list *map_list_next;
6807 /*@only@*/ cstring map_list_name;
6808 /*@null@*/ struct file_name_map *map_list_map;
6811 /* Read the file name map file for DIRNAME. */
6813 static struct file_name_map *
6814 read_name_map (cppReader *pfile, cstring dirname)
6816 struct file_name_map_list *map_list_ptr;
6820 for (map_list_ptr = CPPOPTIONS (pfile)->map_list;
6821 map_list_ptr != NULL;
6822 map_list_ptr = map_list_ptr->map_list_next)
6824 if (cstring_equal (map_list_ptr->map_list_name, dirname))
6826 return map_list_ptr->map_list_map;
6830 map_list_ptr = (struct file_name_map_list *) dmalloc (sizeof (*map_list_ptr));
6831 map_list_ptr->map_list_name = cstring_copy (dirname);
6832 map_list_ptr->map_list_map = NULL;
6834 name = cstring_copy (dirname);
6836 if (cstring_length (dirname) > 0)
6838 name = cstring_appendChar (name, CONNECTCHAR);
6841 name = cstring_concatFree1 (name, cstring_makeLiteralTemp (FILE_NAME_MAP_FILE));
6843 f = fileTable_openReadFile (context_fileTable (), name);
6844 cstring_free (name);
6848 map_list_ptr->map_list_map = NULL;
6854 while ((ch = getc (f)) != EOF)
6857 struct file_name_map *ptr;
6864 from = read_filename_string (ch, f);
6865 while ((ch = getc (f)) != EOF && is_hor_space[ch])
6870 to = read_filename_string (ch, f);
6872 ptr = (struct file_name_map *) dmalloc (sizeof (*ptr));
6873 ptr->map_from = from;
6875 /* Make the real filename absolute. */
6876 if (cstring_length (to) > 1
6877 && osd_isConnectChar (cstring_firstChar (to)))
6883 ptr->map_to = cstring_copy (dirname);
6884 ptr->map_to = cstring_appendChar (ptr->map_to, CONNECTCHAR);
6885 ptr->map_to = cstring_concatFree (ptr->map_to, to);
6888 ptr->map_next = map_list_ptr->map_list_map;
6889 map_list_ptr->map_list_map = ptr;
6891 while ((ch = getc (f)) != '\n')
6895 /*@innerbreak@*/ break;
6900 assertSet (map_list_ptr->map_list_map);
6901 check (fileTable_closeFile (context_fileTable (),f) == 0);
6904 map_list_ptr->map_list_next = pfile->opts->map_list;
6905 pfile->opts->map_list = map_list_ptr;
6907 return map_list_ptr->map_list_map;
6910 /* Try to open include file FILENAME. SEARCHPTR is the directory
6911 being tried from the include file search path. This function maps
6912 filenames on file systems based on information read by
6916 open_include_file (cppReader *pfile,
6918 struct file_name_list *searchptr)
6920 char *filename = cstring_toCharsSafe (fname);
6921 struct file_name_map *map;
6925 cstring_markOwned (fname);
6927 cpp_setLocation (pfile);
6929 if (context_getFlag (FLG_NEVERINCLUDE))
6931 if (isHeaderFile (fname))
6933 return SKIP_INCLUDE;
6937 if ((searchptr != NULL) && ! searchptr->got_name_map)
6939 searchptr->name_map = read_name_map (pfile,
6940 !cstring_isEmpty (searchptr->fname)
6941 ? searchptr->fname :
6942 cstring_makeLiteralTemp ("."));
6943 searchptr->got_name_map = 1;
6946 /* First check the mapping for the directory we are using. */
6948 if ((searchptr != NULL)
6949 && (searchptr->name_map != NULL))
6953 if (!cstring_isEmpty (searchptr->fname))
6955 from += cstring_length (searchptr->fname) + 1;
6958 for (map = searchptr->name_map;
6960 map = map->map_next)
6962 if (cstring_equal (map->map_from, cstring_fromChars (from)))
6965 ** Found a match. Check if the file should be skipped
6968 if (cpp_skipIncludeFile (map->map_to))
6970 return SKIP_INCLUDE;
6974 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
6981 ** Try to find a mapping file for the particular directory we are
6982 ** looking in. Thus #include <sys/types.h> will look up sys/types.h
6983 ** in /usr/include/header.gcc and look up types.h in
6984 ** /usr/include/sys/header.gcc.
6987 p = strrchr (filename, CONNECTCHAR);
6994 if ((searchptr != NULL)
6995 && (cstring_isDefined (searchptr->fname))
6996 && (size_toInt (cstring_length (searchptr->fname)) == p - filename)
6997 && !strncmp (cstring_toCharsSafe (searchptr->fname),
6999 size_fromInt (p - filename)))
7001 /* filename is in SEARCHPTR, which we've already checked. */
7003 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
7005 return SKIP_INCLUDE;
7009 return cpp_openIncludeFile (filename);
7015 dir = mstring_copy (".");
7020 dir = (char *) dmalloc (size_fromInt (p - filename + 1));
7021 memcpy (dir, filename, size_fromInt (p - filename));
7022 dir[p - filename] = '\0';
7026 for (map = read_name_map (pfile, cstring_fromChars (dir));
7028 map = map->map_next)
7030 if (cstring_equal (map->map_from, cstring_fromChars (from)))
7034 if (cpp_skipIncludeFile (map->map_to))
7036 return SKIP_INCLUDE;
7040 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
7047 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
7049 return SKIP_INCLUDE;
7053 return cpp_openIncludeFile (filename);
7057 /* Process the contents of include file FNAME, already open on descriptor F,
7059 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
7060 "system" include directories (as decided by the `is_system_include'
7062 DIRPTR is the link in the dir path through which this file was found,
7063 or 0 if the file name was absolute or via the current directory.
7064 Return 1 on success, 0 on failure.
7066 The caller is responsible for the cppReader_pushBuffer. */
7069 finclude (cppReader *pfile, int f,
7071 bool system_header_p,
7072 /*@dependent@*/ struct file_name_list *dirptr)
7078 cppBuffer *fp; /* For input stack frame */
7080 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
7082 cppReader_perrorWithName (pfile, fname);
7083 check (close (f) == 0);
7084 (void) cppReader_popBuffer (pfile);
7090 fp = cppReader_getBufferSafe (pfile);
7092 /*@-temptrans@*/ /* fname shouldn't really be temp */
7093 fp->nominal_fname = fp->fname = fname;
7097 fp->system_header_p = system_header_p;
7100 fp->cleanup = cppReader_fileCleanup;
7102 if (S_ISREG (st_mode))
7105 fp->buf = (char *) dmalloc (st_size + 2);
7106 fp->alimit = fp->buf + st_size + 2;
7109 /* Read the file contents, knowing that st_size is an upper bound
7110 on the number of bytes we can read. */
7111 length = safe_read (f, fp->buf, size_toInt (st_size));
7112 fp->rlimit = fp->buf + length;
7113 if (length < 0) goto nope;
7115 else if (S_ISDIR (st_mode))
7117 cppReader_error (pfile,
7118 message ("Directory specified where file is expected: %s", fname));
7119 check (close (f) == 0);
7125 ** Cannot count its file size before reading.
7126 ** First read the entire file into heap and
7127 ** copy them into buffer on stack.
7130 size_t bsize = 2000;
7135 fp->buf = (char *) dmalloc (bsize + 2);
7138 i = safe_read (f, fp->buf + st_size, size_toInt (bsize - st_size));
7141 goto nope; /* error! */
7144 if (st_size != bsize)
7146 break; /* End of file */
7150 fp->buf = (char *) drealloc (fp->buf, bsize + 2);
7154 length = size_toInt (st_size);
7157 if ((length > 0 && fp->buf[length - 1] != '\n')
7158 /* Backslash-newline at end is not good enough. */
7159 || (length > 1 && fp->buf[length - 2] == '\\')) {
7160 fp->buf[length++] = '\n';
7163 fp->buf[length] = '\0';
7164 fp->rlimit = fp->buf + length;
7166 /* Close descriptor now, so nesting does not use lots of descriptors. */
7167 check (close (f) == 0);
7169 /* Must do this before calling trigraph_pcp, so that the correct file name
7170 will be printed in warning messages. */
7172 pfile->input_stack_listing_current = 0;
7177 cppReader_perrorWithName (pfile, fname);
7178 check (close (f) == 0);
7184 cpplib_init (cppReader *pfile)
7186 memset ((char *) pfile, 0, sizeof (*pfile));
7188 pfile->get_token = cpplib_getToken;
7189 pfile->token_buffer_size = 200;
7190 pfile->token_buffer = (char *) dmalloc (pfile->token_buffer_size);
7191 pfile->all_include_files = NULL;
7195 cppReader_setWritten (pfile, 0);
7197 pfile->system_include_depth = 0;
7198 pfile->max_include_len = 0;
7199 pfile->timebuf = NULL;
7200 pfile->only_seen_white = 1;
7202 pfile->buffer = cppReader_nullBuffer (pfile);
7206 cppReader_finish (/*@unused@*/ cppReader *pfile)
7211 /* Free resources used by PFILE.
7212 This is the cppReader 'finalizer' or 'destructor' (in C++ terminology). */
7215 cppCleanup (/*@special@*/ cppReader *pfile)
7217 /*@releases pfile@*/
7219 DPRINTF (("cppCleanup!"));
7221 while (CPPBUFFER (pfile) != cppReader_nullBuffer (pfile))
7223 (void) cppReader_popBuffer (pfile);
7226 if (pfile->token_buffer != NULL)
7228 sfree (pfile->token_buffer);
7229 pfile->token_buffer = NULL;
7232 while (pfile->if_stack != NULL)
7234 cppIfStackFrame *temp = pfile->if_stack;
7235 pfile->if_stack = temp->next;
7239 while (pfile->all_include_files != NULL)
7241 struct file_name_list *temp = pfile->all_include_files;
7242 pfile->all_include_files = temp->next;
7243 /*@-dependenttrans@*/
7244 cstring_free (temp->fname);
7245 /*@=dependenttrans@*/
7249 /* evans 2002-07-12 */
7250 while (pfile->opts->map_list != NULL)
7252 struct file_name_map_list *temp = pfile->opts->map_list;
7253 pfile->opts->map_list = pfile->opts->map_list->map_list_next;
7254 cstring_free (temp->map_list_name);
7258 while (pfile->opts->include != NULL)
7260 struct file_name_list *temp = pfile->opts->include;
7261 pfile->opts->include = pfile->opts->include->next;
7262 /* cstring_free (temp->fname); */
7266 sfree (pfile->opts);
7268 cppReader_hashCleanup ();
7272 ** Get the file-mode and data size of the file open on FD
7273 ** and store them in *MODE_POINTER and *SIZE_POINTER.
7277 file_size_and_mode (int fd, mode_t *mode_pointer, size_t *size_pointer)
7281 if (fstat (fd, &sbuf) < 0) {
7287 if (mode_pointer != NULL)
7289 *mode_pointer = sbuf.st_mode;
7292 if (size_pointer != NULL)
7294 *size_pointer = (size_t) sbuf.st_size;
7300 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
7301 retrying if necessary. Return a negative value if an error occurs,
7302 otherwise return the actual number of bytes read,
7303 which must be LEN unless end-of-file was reached. */
7305 static int safe_read (int desc, char *ptr, int len)
7311 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
7312 /*@-compdef@*/ /* ptr is an out parameter */
7313 int nchars = _read (desc, ptr, (unsigned) left);
7316 ssize_t nchars = read (desc, ptr, size_fromInt (left));
7325 return (int) nchars;
7339 /* Initialize PMARK to remember the current position of PFILE. */
7342 parseSetMark (struct parse_marker *pmark, cppReader *pfile)
7344 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7346 pmark->next = pbuf->marks;
7348 pbuf->marks = pmark;
7352 pmark->position = pbuf->cur - pbuf->buf;
7353 DPRINTF (("set mark: %d / %s", pmark->position, pbuf->cur));
7356 /* Cleanup PMARK - we no longer need it. */
7358 void parseClearMark (struct parse_marker *pmark)
7360 struct parse_marker **pp = &pmark->buf->marks;
7362 for (; ; pp = &(*pp)->next)
7364 llassert (*pp != NULL);
7365 if (*pp == pmark) break;
7371 /* Backup the current position of PFILE to that saved in PMARK. */
7374 parseGotoMark (struct parse_marker *pmark, cppReader *pfile)
7376 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7378 if (pbuf != pmark->buf)
7380 cpp_setLocation (pfile);
7381 llfatalbug (cstring_makeLiteral ("Internal error parseGotoMark"));
7384 llassert (pbuf->buf != NULL);
7385 pbuf->cur = pbuf->buf + pmark->position;
7386 DPRINTF (("goto mark: %d / %s", pmark->position, pbuf->cur));
7389 /* Reset PMARK to point to the current position of PFILE. (Same
7390 as parseClearMark (PMARK), parseSetMark (PMARK, PFILE) but faster. */
7393 parseMoveMark (struct parse_marker *pmark, cppReader *pfile)
7395 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7397 if (pbuf != pmark->buf)
7399 cpp_setLocation (pfile);
7400 llfatalerror (cstring_makeLiteral ("Internal error parseMoveMark"));
7403 pmark->position = pbuf->cur - pbuf->buf;
7404 DPRINTF (("move mark: %s", pmark->position));
7407 void cpplib_initializeReader (cppReader *pfile) /* Must be done after library is loaded. */
7409 struct cppOptions *opts = CPPOPTIONS (pfile);
7412 /* The code looks at the defaults through this pointer, rather than through
7413 the constant structure above. This pointer gets changed if an environment
7414 variable specifies other defaults. */
7416 struct default_include *include_defaults = include_defaults_array;
7418 /* Add dirs from INCLUDEPATH_VAR after dirs from -I. */
7419 /* There seems to be confusion about what CPATH should do,
7420 so for the moment it is not documented. */
7421 /* Some people say that CPATH should replace the standard include dirs,
7422 but that seems pointless: it comes before them, so it overrides them
7425 xp = osd_getEnvironmentVariable (INCLUDEPATH_VAR);
7427 if (cstring_isDefined (xp) && !opts->no_standard_includes)
7429 path_include (pfile, cstring_toCharsSafe (xp));
7432 /* Now that dollars_in_ident is known, initialize is_idchar. */
7433 initialize_char_syntax (opts);
7435 /* CppReader_Install __LINE__, etc. Must follow initialize_char_syntax
7436 and option processing. */
7438 initialize_builtins (pfile);
7440 /* Do standard #defines and assertions
7441 that identify system and machine type. */
7443 if (!opts->inhibit_predefs) {
7444 char *p = (char *) dmalloc (strlen (predefs) + 1);
7445 strcpy (p, predefs);
7451 while (*p == ' ' || *p == '\t')
7456 /* Handle -D options. */
7457 if (p[0] == '-' && p[1] == 'D')
7461 while (*p && *p != ' ' && *p != '\t')
7471 if (opts->debug_output)
7473 output_line_command (pfile, 0, same_file);
7476 cppReader_define (pfile, q);
7478 while (*p == ' ' || *p == '\t')
7492 opts->done_initializing = 1;
7494 { /* Read the appropriate environment variable and if it exists
7495 replace include_defaults with the listed path. */
7499 int win32_buf_size = 0; /* memory we need to allocate */
7502 if (opts->cplusplus)
7504 epath = getenv ("CPLUS_INCLUDE_PATH");
7508 epath = getenv ("C_INCLUDE_PATH");
7512 ** If the environment var for this language is set,
7513 ** add to the default list of include directories.
7516 if (epath != NULL) {
7517 char *nstore = (char *) dmalloc (strlen (epath) + 2);
7519 char *startp, *endp;
7522 /* if we have a posix path list, convert to win32 path list */
7523 if (cygwin32_posix_path_list_p (epath))
7525 win32_buf_size = cygwin32_posix_to_win32_path_list_buf_size (epath);
7526 win32epath = (char *) dmalloc /*@i4@*/ (win32_buf_size);
7527 cygwin32_posix_to_win32_path_list (epath, win32epath);
7531 for (num_dirs = 1, startp = epath; *startp; startp++)
7533 if (*startp == PATH_SEPARATOR)
7539 = (struct default_include *) dmalloc ((num_dirs
7540 * sizeof (struct default_include))
7541 + sizeof (include_defaults_array));
7544 startp = endp = epath;
7547 /* Handle cases like c:/usr/lib:d:/gcc/lib */
7548 if ((*endp == PATH_SEPARATOR) || *endp == 0)
7550 strncpy (nstore, startp, size_fromInt (endp - startp));
7553 strcpy (nstore, ".");
7557 nstore[endp-startp] = '\0';
7560 include_defaults[num_dirs].fname = cstring_fromCharsNew (nstore);
7561 include_defaults[num_dirs].cplusplus = opts->cplusplus;
7562 include_defaults[num_dirs].cxx_aware = 1;
7569 endp = startp = endp + 1;
7576 /* Put the usual defaults back in at the end. */
7577 memcpy ((char *) &include_defaults[num_dirs],
7578 (char *) include_defaults_array,
7579 sizeof (include_defaults_array));
7582 /*@-branchstate@*/ } /*@=branchstate@*/
7585 cppReader_appendIncludeChain (pfile, opts->before_system,
7586 opts->last_before_system);
7588 opts->first_system_include = opts->before_system;
7590 /* Unless -fnostdinc,
7591 tack on the standard include file dirs to the specified list */
7593 if (!opts->no_standard_includes) {
7594 struct default_include *p = include_defaults;
7595 char *specd_prefix = opts->include_prefix;
7596 char *default_prefix = mstring_copy (GCC_INCLUDE_DIR);
7597 size_t default_len = 0;
7599 /* Remove the `include' from /usr/local/lib/gcc.../include. */
7600 if (default_prefix != NULL) {
7601 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
7602 default_len = strlen (default_prefix) - 7;
7603 default_prefix[default_len] = 0;
7607 /* Search "translated" versions of GNU directories.
7608 These have /usr/local/lib/gcc... replaced by specd_prefix. */
7609 if (specd_prefix != 0 && default_len != 0)
7610 for (p = include_defaults; p->fname != NULL; p++) {
7611 /* Some standard dirs are only for C++. */
7613 || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
7614 /* Does this dir start with the prefix? */
7615 llassert (default_prefix != NULL);
7617 if (!strncmp (cstring_toCharsSafe (p->fname), default_prefix, default_len))
7619 /* Yes; change prefix and add to search list. */
7620 struct file_name_list *nlist
7621 = (struct file_name_list *) dmalloc (sizeof (*nlist));
7622 size_t this_len = strlen (specd_prefix) + cstring_length (p->fname) - default_len;
7623 char *str = (char *) dmalloc (this_len + 1);
7624 strcpy (str, specd_prefix);
7625 strcat (str, cstring_toCharsSafe (p->fname) + default_len);
7628 nlist->fname = cstring_fromChars (str);
7629 nlist->control_macro = 0;
7630 nlist->c_system_include_path = !p->cxx_aware;
7631 nlist->got_name_map = 0;
7633 if (opts->first_system_include == 0)
7635 opts->first_system_include = nlist;
7638 cppReader_addIncludeChain (pfile, nlist);
7643 /* Search ordinary names for GNU include directories. */
7645 for (p = include_defaults; p->fname != NULL; p++)
7647 /* Some standard dirs are only for C++. */
7649 || (opts->cplusplus && !opts->no_standard_cplusplus_includes))
7651 struct file_name_list *nlist
7652 = (struct file_name_list *) dmalloc (sizeof (*nlist));
7653 nlist->control_macro = 0;
7654 nlist->c_system_include_path = !p->cxx_aware;
7655 nlist->fname = p->fname;
7656 nlist->got_name_map = 0;
7659 /* Spurious warning reported for opts->first_system_include */
7660 /*@-usereleased@*/ if (opts->first_system_include == NULL)
7662 opts->first_system_include = nlist;
7666 cppReader_addIncludeChain (pfile, nlist);
7669 sfree (default_prefix);
7672 /* Tack the after_include chain at the end of the include chain. */
7673 cppReader_appendIncludeChain (pfile, opts->after_include,
7674 opts->last_after_include);
7676 /* Spurious warnings for opts->first_system_include */
7678 if (opts->first_system_include == NULL)
7680 opts->first_system_include = opts->after_include;
7684 /* With -v, print the list of dirs to search. */
7685 if (opts->verbose) {
7686 struct file_name_list *p;
7687 fprintf (stderr, "#include \"...\" search starts here:\n");
7689 for (p = opts->include; p != NULL; p = p->next) {
7690 if (p == opts->first_bracket_include)
7691 fprintf (stderr, "#include <...> search starts here:\n");
7693 fprintf (stderr, " %s\n", cstring_toCharsSafe (p->fname));
7695 fprintf (stderr, "End of search list.\n");
7699 int cppReader_startProcess (cppReader *pfile, cstring fname)
7703 struct cppOptions *opts = CPPOPTIONS (pfile);
7705 fp = cppReader_pushBuffer (pfile, NULL, 0);
7712 if (opts->in_fname == NULL)
7714 opts->in_fname = cstring_makeLiteralTemp ("");
7717 fp->fname = opts->in_fname;
7718 fp->nominal_fname = fp->fname;
7721 /* Copy the entire contents of the main input file into
7722 the stacked input buffer previously allocated for it. */
7724 if (cstring_isEmpty (fname))
7726 fname = cstring_makeLiteralTemp ("");
7729 else if ((f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666)) < 0)
7731 cppReader_error (pfile,
7732 message ("Error opening %s for reading: %s",
7733 fname, lldecodeerror (errno)));
7742 if (finclude (pfile, f, fname, 0, NULL))
7744 output_line_command (pfile, 0, same_file);
7750 static /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_getBuffer (cppReader *pfile)
7752 return pfile->buffer;
7755 /*@exposed@*/ cppBuffer *cppReader_getBufferSafe (cppReader *pfile)
7757 llassert (pfile->buffer != NULL);
7758 return pfile->buffer;
7761 /*@exposed@*/ char *cppLineBase (cppBuffer *buf)
7763 llassert (buf->buf != NULL);
7764 return (buf->buf + buf->line_base);
7767 int cpplib_bufPeek (cppBuffer *buf)
7769 if (buf->cur == NULL || buf->rlimit == NULL) {
7773 if (buf->cur < buf->rlimit) {
7780 bool cppBuffer_isMacro (cppBuffer *buf)
7784 return (buf->cleanup == cppReader_macroCleanup);
7791 ** Returns true if the macro should be checked, false
7792 ** if it should be expanded normally.
7795 static bool notparseable = FALSE; /* preceeded by @notparseable@ */
7796 static bool notfunction = FALSE; /* preceeded by @notfunction@ */
7797 static bool expectiter = FALSE; /* preceeded by @iter@ */
7798 static bool expectenditer = FALSE; /* second after @iter@ */
7799 static bool expectfunction = FALSE; /* preceeded by @function@ */
7800 static bool expectconstant = FALSE; /* preceeded by @constant@ */
7801 static bool expectmacro = FALSE; /* preceeded by notfunction or notparseable */
7803 static void cpp_setLocation (cppReader *pfile)
7808 if (pfile->buffer != NULL)
7810 if (cstring_isDefined (cppReader_getBufferSafe (pfile)->nominal_fname))
7812 cstring fname = cppReader_getBufferSafe (pfile)->nominal_fname;
7814 DPRINTF (("Looking up: %s", fname));
7816 if (fileTable_exists (context_fileTable (), fname))
7818 fid = fileTable_lookup (context_fileTable (), fname);
7822 DPRINTF (("Trying %s", cppReader_getBuffer (pfile)->fname));
7824 fid = fileTable_lookup (context_fileTable (),
7825 cppReader_getBufferSafe (pfile)->fname);
7830 fid = fileTable_lookup (context_fileTable (),
7831 cppReader_getBufferSafe (pfile)->fname);
7834 line = cppReader_getBufferSafe (pfile)->lineno;
7835 fileloc_free (g_currentloc);
7837 if (fileId_isValid (fid))
7839 g_currentloc = fileloc_create (fid, line, 1);
7843 g_currentloc = fileloc_createBuiltin ();
7848 fileloc_free (g_currentloc);
7849 g_currentloc = fileloc_createBuiltin ();
7853 static bool cpp_shouldCheckMacro (cppReader *pfile, char *p) /*@modifies p*/
7855 bool checkmacro = FALSE;
7856 bool hasParams = FALSE;
7857 bool noexpand = FALSE;
7861 cpp_setLocation (pfile);
7863 DPRINTF (("Should check macro? %s", p));
7865 if (expectiter || expectconstant || expectenditer)
7870 expectenditer = TRUE;
7875 expectconstant = FALSE;
7876 expectenditer = FALSE;
7879 if (notfunction || notparseable)
7881 notfunction = FALSE;
7882 notparseable = FALSE;
7891 llassert (*p == '#');
7894 while (*p == ' ' || *p == '\t')
7899 llassert (*p == 'd'); /* define starts */
7903 while (*p == ' ' || *p == '\t')
7908 sname = cstring_fromChars (p);
7909 DPRINTF (("Check macro: %s", sname));
7911 while (((c = *p) != ' ')
7912 && c != '\0' && c != '('
7913 && c != '\t' && c != '\\' && c != '\n'
7919 hasParams = (c == '(');
7924 notparseable = FALSE;
7926 else if (notfunction || fileloc_isStandardLib (g_currentloc))
7928 DPRINTF (("Clear notfunction"));
7929 notfunction = FALSE;
7944 if (usymtab_existsReal (sname))
7946 uentry ue = usymtab_lookup (sname);
7948 DPRINTF (("Lookup macro: %s", uentry_unparse (ue)));
7950 if (fileloc_isPreproc (uentry_whereLast (ue)))
7956 if (uentry_isSpecified (ue))
7958 checkmacro = context_getFlag (FLG_SPECMACROS);
7964 checkmacro = context_getFlag (FLG_LIBMACROS)
7965 || context_getFlag (FLG_FCNMACROS);
7973 DPRINTF (("Macro doesn't exist: %s", bool_unparse (checkmacro)));
7975 if (fileloc_isSystemFile (g_currentloc)
7976 && context_getFlag (FLG_SYSTEMDIREXPAND))
7978 ; /* don't check this macro */
7979 DPRINTF (("Don't check 1"));
7987 DPRINTF (("Has params..."));
7989 if (context_getFlag (FLG_FCNMACROS))
7991 if (usymtab_exists (sname))
7994 ** only get here is macro is redefined
7995 ** error reported elsewhere
7998 DPRINTF (("It exists!"));
8003 ** We make it a forward function, since it might be declared elsewhere.
8004 ** After all headers have been processed, we should check the forward
8008 fileloc loc = fileloc_makePreproc (g_currentloc);
8010 /* the line is off-by-one, since the newline was already read */
8015 expectfunction = FALSE;
8018 le = uentry_makeForwardFunction (sname,
8019 typeId_invalid, loc);
8025 /* Do not define here! */
8027 (void) usymtab_addEntry (le);
8031 DPRINTF (("Check: TRUE"));
8035 DPRINTF (("Flag FCN_MACROS not set!"));
8040 DPRINTF (("No params"));
8042 if (context_getFlag (FLG_CONSTMACROS))
8044 bool nocontent = FALSE;
8057 ** Check if there is nothing after the define.
8060 while ((*rest) != '\0' && isspace (*rest))
8067 nocontent = TRUE; /* empty macro, don't check */
8072 if (usymtab_exists (sname))
8078 fileloc loc = fileloc_makePreproc (g_currentloc);
8079 DPRINTF (("Make constant: %s", sname));
8080 le = uentry_makeMacroConstant (sname, ctype_unknown, loc);
8081 (void) usymtab_addEntry (le);
8084 checkmacro = !nocontent;
8089 if (checkmacro && usymtab_existsType (sname))
8091 DPRINTF (("Making false..."));
8093 ppllerror (message ("Specified type implemented as macro: %s", sname));
8103 if (usymtab_exists (sname))
8105 uentry ue = usymtab_lookupExpose (sname);
8106 fileloc tloc = fileloc_makePreproc (g_currentloc);
8108 uentry_setDefined (ue, tloc);
8109 fileloc_free (tloc);
8110 uentry_setUsed (ue, fileloc_undefined);
8114 fileloc tloc = fileloc_makePreproc (g_currentloc);
8115 uentry ue = uentry_makeExpandedMacro (sname, tloc);
8116 DPRINTF (("Make expanded macro: %s", sname));
8117 DPRINTF (("Not in symbol table: %s", sname));
8119 (void) usymtab_addGlobalEntry (ue);
8120 fileloc_free (tloc);
8125 DPRINTF (("Returning: %s", bool_unparse (checkmacro)));
8129 static enum cpp_token
8130 cpp_handleComment (cppReader *pfile, struct parse_marker *smark)
8132 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
8136 bool eliminateComment = FALSE;
8138 llassert (pbuf->buf != NULL);
8140 start = pbuf->buf + smark->position;
8142 llassert (pbuf->cur != NULL);
8143 len = pbuf->cur - start;
8146 && start[1] == context_getCommentMarkerChar ())
8150 char *scomment = start + 2;
8151 char savec = start[len];
8153 cpp_setLocation (pfile);
8154 loc = fileloc_copy (g_currentloc);
8156 start[0] = BEFORE_COMMENT_MARKER[0];
8157 start[1] = BEFORE_COMMENT_MARKER[1];
8159 llassert (start[len - 2] == '*');
8160 start[len - 2] = AFTER_COMMENT_MARKER[0];
8162 llassert (start[len - 1] == '/');
8163 start[len - 1] = AFTER_COMMENT_MARKER[1];
8165 cpplib_reserve(pfile, size_fromInt (1 + len));
8166 cppReader_putCharQ (pfile, c);
8168 cpp_setLocation (pfile);
8172 if (mstring_containsString (scomment, "/*"))
8174 (void) cppoptgenerror
8176 message ("Comment starts inside syntactic comment: %s",
8177 cstring_fromChars (scomment)),
8183 if (mstring_equalPrefix (scomment, "ignore"))
8185 if (!context_getFlag (FLG_NOCOMMENTS))
8187 context_enterSuppressRegion (loc);
8190 else if (mstring_equalPrefix (scomment, "end"))
8192 if (!context_getFlag (FLG_NOCOMMENTS))
8194 context_exitSuppressRegion (loc);
8197 else if (mstring_equalPrefix (scomment, "notparseable"))
8199 notparseable = TRUE;
8201 eliminateComment = TRUE;
8203 else if (mstring_equalPrefix (scomment, "notfunction"))
8207 eliminateComment = TRUE;
8209 else if (mstring_equalPrefix (scomment, "iter"))
8213 else if (mstring_equalPrefix (scomment, "function"))
8215 expectfunction = TRUE;
8217 else if (mstring_equalPrefix (scomment, "constant"))
8219 expectconstant = TRUE;
8223 char sChar = *scomment;
8229 char *rest = scomment + 1;
8231 if (mstring_equalPrefix (rest, "commentchar"))
8233 eliminateComment = TRUE;
8237 ppllerror (cstring_makeLiteral
8238 ("Cannot restore commentchar"));
8242 char *next = scomment + 12; /* strlen commentchar = 12 */
8244 if (*next != ' ' && *next != '\t' && *next != '\n')
8248 ("Syntactic commentchar comment is not followed by a "
8249 "whitespace character: %c",
8254 char cchar = *(next + 1);
8259 (cstring_makeLiteral
8260 ("Cannot set commentchar to NUL"));
8264 context_setCommentMarkerChar (cchar);
8265 /* setComment = TRUE; */
8270 else if (mstring_equalPrefix (scomment, "nestcomment"))
8272 /* fix from Mike Miller <MikeM@xata.com> */
8273 context_fileSetFlag (FLG_NESTCOMMENT,
8274 ynm_fromCodeChar (sChar),
8277 else if (mstring_equalPrefix (rest, "namechecks"))
8279 context_fileSetFlag (FLG_NAMECHECKS,
8280 ynm_fromCodeChar (sChar),
8283 else if (mstring_equalPrefix (rest, "macroredef"))
8285 context_fileSetFlag (FLG_MACROREDEF,
8286 ynm_fromCodeChar (sChar),
8289 else if (mstring_equalPrefix (rest, "usevarargs"))
8291 context_fileSetFlag (FLG_USEVARARGS,
8292 ynm_fromCodeChar (sChar),
8295 else if (mstring_equalPrefix (rest, "nextlinemacros"))
8297 context_fileSetFlag (FLG_MACRONEXTLINE,
8298 ynm_fromCodeChar (sChar),
8301 else if (mstring_equalPrefix (rest, "allmacros")
8302 || mstring_equalPrefix (rest, "fcnmacros")
8303 || mstring_equalPrefix (rest, "constmacros"))
8307 if (mstring_equalPrefix (rest, "allmacros"))
8311 else if (mstring_equalPrefix (rest, "fcnmacros"))
8317 llassert (mstring_equalPrefix (rest, "constmacros"));
8318 fl = FLG_CONSTMACROS;
8321 context_fileSetFlag (fl, ynm_fromCodeChar (sChar), loc);
8322 notfunction = FALSE;
8335 if (eliminateComment)
8340 /* Replaces comment char's in start with spaces */
8342 for (i = 2; i < len - 2; i++)
8344 if (start[i] == BEFORE_COMMENT_MARKER[0]
8345 || start[i] == BEFORE_COMMENT_MARKER[1]
8346 || start[i] == context_getCommentMarkerChar ())
8352 cppReader_putStrN (pfile, start, size_fromInt (len));
8353 parseClearMark (smark);
8363 ** Output the comment as all spaces so line/column
8364 ** in output file is still correct.
8368 cstring lintcomment = cstring_undefined;
8370 if (context_getFlag (FLG_LINTCOMMENTS))
8372 if (mstring_equalPrefix (start, "*NOTREACHED*/"))
8374 lintcomment = cstring_makeLiteralTemp ("l_notreach");
8376 else if (mstring_equalPrefix (start, "*PRINTFLIKE*/"))
8378 lintcomment = cstring_makeLiteralTemp ("l_printfli");
8380 else if (mstring_equalPrefix (start, "*FALLTHROUGH*/"))
8382 lintcomment = cstring_makeLiteralTemp ("l_fallthrou");
8384 else if (mstring_equalPrefix (start, "*ARGSUSED*/"))
8386 lintcomment = cstring_makeLiteralTemp ("l_argsus");
8388 else if (mstring_equalPrefix (start, "*FALLTHRU*/"))
8390 lintcomment = cstring_makeLiteralTemp ("l_fallth");
8394 lintcomment = cstring_undefined;
8399 lintcomment = cstring_undefined;
8402 if (cstring_isDefined (lintcomment))
8404 c = BEFORE_COMMENT_MARKER[0];
8405 start[0] = BEFORE_COMMENT_MARKER[1];
8407 llassert (size_toLong (cstring_length (lintcomment)) == len - 3);
8409 for (i = 1; i < len - 2; i++)
8411 start[i] = cstring_getChar (lintcomment, size_fromInt (i));
8414 start[len - 2] = AFTER_COMMENT_MARKER[0];
8415 start[len - 1] = AFTER_COMMENT_MARKER[1];
8419 /* Replaces char's in start with spaces */
8420 for (i = 0; i < len; i++)
8424 && start[i + 1] == '*') {
8425 (void) cppoptgenerror
8427 message ("Comment starts inside comment"),
8431 if (start[i] != '\n')
8438 cpplib_reserve (pfile, size_fromInt (1 + len));
8439 cppReader_putCharQ (pfile, c);
8440 cppReader_putStrN (pfile, start, size_fromInt (len));
8441 parseClearMark (smark);
8447 static int cpp_openIncludeFile (char *filename)
8449 int res = open (filename, O_RDONLY, 0666);
8451 /* evans 2001-08-23: was (res) - open returns -1 on error! reported by Robin Watts */
8454 if (!fileTable_exists (context_fileTable (),
8455 cstring_fromChars (filename)))
8457 if (fileloc_isXHFile (g_currentloc))
8460 ** Files includes by XH files are also XH files
8463 (void) fileTable_addXHFile (context_fileTable (),
8464 cstring_fromChars (filename));
8468 (void) fileTable_addHeaderFile (context_fileTable (),
8469 cstring_fromChars (filename));
8474 DPRINTF (("File already exists: %s", filename));
8481 static bool cpp_skipIncludeFile (cstring fname)
8483 if (context_isSystemDir (fname))
8485 DPRINTF (("System dir: %s", fname));
8487 if (lcllib_isSkipHeader (fname))
8489 DPRINTF (("Skip include TRUE: %s", fname));
8493 if (context_getFlag (FLG_SKIPSYSHEADERS))
8496 ** 2003-04-18: Patch from Randal Parsons
8500 ** Don't skip include file unless the file actually exists.
8501 ** It may be in a different directory.
8504 int f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666);
8508 check (close (f) == 0);
8509 DPRINTF (("Skip include TRUE: %s", fname));
8514 /* Keep looking... */
8519 if (context_getFlag (FLG_SINGLEINCLUDE))
8521 fname = removePreDirs (fname);
8523 # if defined (WIN32) || defined (OS2)
8524 cstring_replaceAll (fname, '\\', '/');
8527 if (fileTable_exists (context_fileTable (), fname))
8529 DPRINTF (("Skip include TRUE: %s", fname));
8534 DPRINTF (("Skip include FALSE: %s", fname));
8538 static int cpp_peekN (cppReader *pfile, int n)
8540 cppBuffer *buf = cppReader_getBufferSafe (pfile);
8542 llassert (buf->cur != NULL);
8544 return (buf->rlimit - buf->cur >= (n)
8549 cppBuffer *cppBuffer_prevBuffer (cppBuffer *buf)
8554 void cppBuffer_forward (cppBuffer *buf, int n)
8556 llassert (buf->cur != NULL);
8560 /*@=bufferoverflowhigh@*/