Moved OS dependent constants from constants.h to osd.h
[splint-patched.git] / src / cpplib.c
blob8aed1b6bf11fe85cfd384633eebacee1262368ac
1 /*
2 ** Splint - annotation-assisted static program checker
3 ** Copyright (C) 1994-2003 University of Virginia,
4 ** Massachusetts Institute of Technology
5 **
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.
10 **
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.
15 **
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
25 ** cpplib.c
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
36 later version.
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! */
52 * Herbert 06/12/2000:
53 * - OS2 drive specs like WIN32
54 * - Includes for IBMs OS/2 compiler
57 # include <ctype.h>
58 # include <stdio.h>
59 # include <signal.h>
60 # ifdef __STDC__
61 # include <stdlib.h>
62 # endif
64 # include <string.h>
65 # if !(defined (WIN32) || defined (OS2) && defined (__IBMC__))
66 # include <unistd.h>
67 # endif
68 # include <sys/types.h>
69 # include <sys/stat.h>
70 # include <fcntl.h>
71 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
72 # include <io.h>
73 /* SMF */
74 # ifndef BCC32
75 # include <sys/utime.h> /* for __DATE__ and __TIME__ */
76 # endif
78 # include <time.h>
79 # else
80 # ifndef VMS
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>
88 # else
89 # include <sys/times.h>
90 # include <time.h>
91 # include <fcntl.h>
92 # endif /* USG */
93 # endif /* not VMS */
94 # endif /* not WIN32 */
96 /* This defines "errno" properly for VMS, and gives us EACCES. */
97 # include <errno.h>
99 # include "splintMacros.nf"
100 # include "basic.h"
101 # include "lcllib.h"
102 # include "cppconf.h"
103 # include "cpplib.h"
104 # include "cpperror.h"
105 # include "cpphash.h"
106 # include "cppexp.h"
107 # include "version.h"
108 # include "osd.h"
111 ** This is really kludgey code...
114 /*@+boolint@*/
115 /*@+charint@*/
117 /* Warnings for using sprintf - suppress them all for now... */
118 /*@-bufferoverflowhigh@*/
119 /*@-bounds@*/
121 #define NO_SHORTNAMES
123 # ifdef open
124 # undef open
125 # undef read
126 # undef write
127 # endif /* open */
129 /*@constant int IMPORT_FOUND@*/
130 # define IMPORT_FOUND -2
132 /*@constant int SKIP_INCLUDE@*/
133 # define SKIP_INCLUDE IMPORT_FOUND
135 /*@constant unused int IMPORT_NOT_FOUND@*/
136 # define IMPORT_NOT_FOUND -1
138 #ifndef STDC_VALUE
139 /*@constant unused int STDC_VALUE@*/
140 #define STDC_VALUE 1
141 #endif
143 /* By default, colon separates directories in a path. */
144 #ifndef PATH_SEPARATOR
145 /*@constant char PATH_SEPARATOR@*/
146 #define PATH_SEPARATOR ':'
147 #endif
149 #ifndef INCLUDE_LEN_FUDGE
150 /*@constant int INCLUDE_LEN_FUDGE@*/
151 #define INCLUDE_LEN_FUDGE 0
152 #endif
154 static void parse_name (cppReader *, int);
156 static int cpp_openIncludeFile (char *p_filename)
157 /*@modifies fileSystem @*/ ;
159 static void cpp_setLocation (cppReader *p_pfile)
160 /*@modifies g_currentloc@*/ ;
162 static enum cpp_token cpp_handleComment (cppReader *p_pfile,
163 struct parse_marker *p_smark)
164 /*@modifies p_pfile, p_smark@*/;
166 static bool cpp_shouldCheckMacro (cppReader *p_pfile, char *p_p) /*@modifies p_p@*/ ;
168 static size_t cppReader_checkMacroNameLoc (fileloc p_loc, char *p_symname, cstring p_usage) ;
170 static bool cpp_skipIncludeFile (cstring p_fname) /*@*/ ;
172 #ifndef O_RDONLY
173 #define O_RDONLY 0
174 #endif
176 /* Symbols to predefine. */
178 #ifdef CPP_PREDEFINES
179 static /*@observer@*/ char *predefs = CPP_PREDEFINES;
180 #else
181 static /*@observer@*/ char *predefs = "";
182 #endif
184 /* We let tm.h override the types used here, to handle trivial differences
185 such as the choice of unsigned int or long unsigned int for size_t.
186 When machines start needing nontrivial differences in the size type,
187 it would be best to do something here to figure out automatically
188 from other information what type to use. */
190 /* The string value for __SIZE_TYPE__. */
192 #ifndef SIZE_TYPE
193 /*@constant observer char *SIZE_TYPE@*/
194 #define SIZE_TYPE "long unsigned int"
195 #endif
197 /* The string value for __PTRDIFF_TYPE__. */
199 #ifndef PTRDIFF_TYPE
200 /*@constant observer char *PTRDIFF_TYPE@*/
201 #define PTRDIFF_TYPE "long int"
202 #endif
204 /* The string value for __WCHAR_TYPE__. */
206 #ifndef WCHAR_TYPE
207 /*@constant observer char *WCHAR_TYPE@*/
208 #define WCHAR_TYPE "int"
209 #endif
211 /* The string value for __USER_LABEL_PREFIX__ */
213 #ifndef USER_LABEL_PREFIX
214 /*@constant observer char *USER_LABEL_PREFIX@*/
215 #define USER_LABEL_PREFIX ""
216 #endif
218 /* The string value for __REGISTER_PREFIX__ */
220 #ifndef REGISTER_PREFIX
221 /*@constant observer char *REGISTER_PREFIX@*/
222 #define REGISTER_PREFIX ""
223 #endif
225 /* table to tell if char can be part of a C identifier. */
226 static bool is_idchar[256];
227 /* table to tell if char can be first char of a c identifier. */
228 static bool is_idstart[256];
229 /* table to tell if c is horizontal space. */
230 static bool is_hor_space[256];
231 /* table to tell if c is horizontal or vertical space. */
232 static bool is_space[256];
234 static /*@exposed@*/ /*@null@*/ cppBuffer *
235 cppReader_getBuffer (/*@special@*/ cppReader *p_pfile)
236 /*@uses p_pfile->buffer@*/
237 /*@modifies nothing@*/ ;
239 /*@notfunction@*/
240 # define SKIP_WHITE_SPACE(p) do { /*@access cstring@*/ while (is_hor_space[(int) *(p)]) { (p)++; } } /*@noaccess cstring@*/ while (0)
242 /*@notfunction@*/
243 # define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*(p)]) { (p)++; } } while (0)
245 static int cpp_peekN (cppReader *p_pfile, int p_n) /*@*/ ;
247 /*@function static int cppBuffer_get (sef cppBuffer *p_b) modifies *p_b ; @*/
248 # define cppBuffer_get(BUFFER) \
249 ((BUFFER)->cur < (BUFFER)->rlimit ? *(BUFFER)->cur++ : EOF)
251 /*@function static int cppBuffer_reachedEOF (sef cppBuffer *p_b) modifies nothing; @*/
252 # define cppBuffer_reachedEOF(b) \
253 ((b)->cur < (b)->rlimit ? FALSE : TRUE)
255 /* Append string STR (of length N) to PFILE's output buffer. Make space. */
256 /*@function static void cppReader_puts (sef cppReader *p_file, char *p_str, sef size_t p_n)
257 modifies *p_file; @*/
258 # define cppReader_puts(PFILE, STR, N) \
259 cpplib_reserve(PFILE, N), cppReader_putStrN (PFILE, STR,N)
261 /* Append character CH to PFILE's output buffer. Assume sufficient space. */
263 /*@function static void cppReader_putCharQ (cppReader *p_file, char p_ch)
264 modifies *p_file; @*/
265 # define cppReader_putCharQ(PFILE, CH) (*(PFILE)->limit++ = (CH))
267 static void cppReader_putCharQ (cppReader *p_file, char p_ch)
269 fprintf (stderr, "put char: %c\n", p_ch);
270 (*(p_file)->limit++ = (p_ch));
273 /* Append character CH to PFILE's output buffer. Make space if need be. */
275 /*@function static void cppReader_putChar (sef cppReader *p_file, char p_ch)
276 modifies *p_file; @*/
277 #define cppReader_putChar(PFILE, CH) (cpplib_reserve (PFILE, (size_t) 1), cppReader_putCharQ (PFILE, CH))
279 /* Make sure PFILE->limit is followed by '\0'. */
280 /*@function static void cppReader_nullTerminateQ (cppReader *p_file)
281 modifies *p_file; @*/
283 #define cppReader_nullTerminateQ(PFILE) (*(PFILE)->limit = 0)
285 /*@function static void cppReader_nullTerminate (sef cppReader *p_file)
286 modifies *p_file; @*/
287 # define cppReader_nullTerminate(PFILE) \
288 (cpplib_reserve (PFILE, (size_t) 1), *(PFILE)->limit = 0)
290 /*@function static void cppReader_adjustWritten (cppReader *p_file, size_t)
291 modifies *p_file; @*/
292 #define cppReader_adjustWritten(PFILE,DELTA) ((PFILE)->limit += (DELTA))
294 /*@function static bool cppReader_isC89 (cppReader *) modifies nothing; @*/
295 #define cppReader_isC89(PFILE) (CPPOPTIONS(PFILE)->c89)
297 /*@function static observer char *cppReader_wcharType (cppReader *)
298 modifies nothing; @*/
300 # define cppReader_wcharType(PFILE) \
301 (CPPOPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
303 static void cppBuffer_forward (cppBuffer *p_buf, int p_n) /*@modifies *p_buf@*/ ;
305 /*@function static void cppReader_forward (cppReader *p_pfile, int) modifies *p_pfile; @*/
306 # define cppReader_forward(pfile, N) \
307 (cppBuffer_forward (cppReader_getBufferSafe (pfile), (N)))
309 /*@function static int cppReader_getC (cppReader *p_pfile) modifies *p_pfile; @*/
310 # define cppReader_getC(pfile) (cppBuffer_get (cppReader_getBufferSafe (pfile)))
312 /*@function static int cppReader_reachedEOF (sef cppReader *p_pfile) modifies *p_pfile; @*/
313 # define cppReader_reachedEOF(pfile) (cppBuffer_reachedEOF (cppReader_getBufferSafe (pfile)))
315 /*@function static int cppReader_peekC (cppReader *) modifies nothing;@*/
316 # define cppReader_peekC(pfile) (cpplib_bufPeek (cppReader_getBufferSafe (pfile)))
318 /* Move all backslash-newline pairs out of embarrassing places.
319 Exchange all such pairs following BP
320 with any potentially-embarrassing characters that follow them.
321 Potentially-embarrassing characters are / and *
322 (because a backslash-newline inside a comment delimiter
323 would cause it not to be recognized). */
325 /*@notfunction@*/
326 # define NEWLINE_FIX \
327 do { while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n') { cppReader_forward (pfile, 2); } } while(FALSE)
329 /* Same, but assume we've already read the potential '\\' into C. */
330 /*@notfunction@*/
331 # define NEWLINE_FIX1(C) do { \
332 while ((C) == '\\' && cppReader_peekC (pfile) == '\n') { cppReader_forward (pfile, 1); (C) = cppReader_getC (pfile); }\
333 } while(0)
335 static void parseSetMark (/*@out@*/ struct parse_marker *,
336 cppReader *);
337 static void parseClearMark (struct parse_marker *);
338 static void parseGotoMark (struct parse_marker *, cppReader *);
339 static void parseMoveMark (struct parse_marker *, cppReader *);
341 /* If we have a huge buffer, may need to cache more recent counts */
342 static /*@exposed@*/ char *cppLineBase (/*@sef@*/ cppBuffer *);
344 static /*@exposed@*/ /*@null@*/ cppBuffer *
345 cppReader_pushBuffer (cppReader *p_pfile,
346 /*@owned@*/ /*@null@*/ char *, size_t)
347 /*@modifies p_pfile@*/ ;
349 static void cppReader_appendIncludeChain
350 (cppReader *p_pfile,
351 /*@keep@*/ struct file_name_list *p_first,
352 /*@dependent@*/ struct file_name_list *p_last);
354 static void cppReader_macroCleanup (cppBuffer *p_pbuf, cppReader *p_pfile);
355 static enum cpp_token cppReader_nullUnderflow (/*@unused@*/ cppReader *p_pfile);
357 static void cppReader_nullCleanup (/*@unused@*/ cppBuffer *p_pbuf,
358 /*@unused@*/ cppReader *p_pfile);
360 static void cppReader_fileCleanup (cppBuffer *p_pbuf,
361 /*@unused@*/ cppReader *p_pfile);
363 static int cppReader_handleDirective (cppReader *p_pfile);
365 static void cppReader_scanBuffer (cppReader *p_pfile);
367 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
369 /* SMF */
370 # ifndef BCC32
372 ** WIN32 (at least the VC++ include files) does not define mode_t.
375 /*@-incondefs@*/ /*@-czechtypes@*/
376 typedef unsigned int mode_t;
377 /*@=incondefs@*/ /*@=czechtypes@*/
378 # endif
380 # endif
382 static int file_size_and_mode (int p_fd, /*@out@*/ mode_t *p_mode_pointer,
383 /*@out@*/ size_t *p_size_pointer);
384 static int safe_read (int p_desc, /*@out@*/ char *p_ptr, int p_len);
388 ** cppBuffer_isMacro is true if the buffer contains macro expansion.
389 ** (Note that it is false while we're expanding marco *arguments*.)
392 static bool cppBuffer_isMacro (/*@null@*/ cppBuffer *) /*@*/ ;
394 static void path_include (cppReader *p_pfile, char *p_path)
395 /*@modifies p_pfile@*/ ;
397 static void initialize_builtins (cppReader *p_pfile)
398 /*@modifies p_pfile@*/ ;
400 static void initialize_char_syntax (struct cppOptions *p_opts) ;
402 static int /*@alt void@*/ finclude (cppReader *p_pfile, int p_f,
403 cstring p_fname,
404 bool p_system_header_p,
405 /*@dependent@*/ /*@null@*/ struct file_name_list *p_dirptr);
407 static void validate_else (cppReader *p_pfile, cstring p_directive);
409 static void conditional_skip (cppReader *p_pfile, int p_skip,
410 enum node_type p_type,
411 /*@dependent@*/ /*@null@*/ char *p_control_macro);
413 static HOST_WIDE_INT eval_if_expression (cppReader *p_pfile,
414 char *p_buf,
415 int p_length);
417 static void skip_if_group (cppReader *p_pfile, int p_any);
419 static bool comp_def_part (bool p_first, char *p_beg1, int p_len1,
420 char *p_beg2, int p_len2, bool p_last);
422 #ifdef abort
423 extern void fancy_abort ();
424 #endif
426 static bool redundant_include_p (cppReader *p_pfile, /*@null@*/ cstring p_name);
427 static bool is_system_include (cppReader *p_pfile, cstring p_filename);
429 static /*@observer@*/ /*@null@*/ struct file_name_map *
430 read_name_map (cppReader *p_pfile, cstring p_dirname);
432 static cstring read_filename_string (int p_ch, /*:open:*/ FILE *p_f);
434 static int open_include_file (cppReader *p_pfile,
435 /*@owned@*/ cstring p_fname,
436 /*@null@*/ struct file_name_list *p_searchptr);
438 static void push_macro_expansion (cppReader *,
439 /*@owned@*/ char *, size_t,
440 /*@dependent@*/ hashNode);
442 /* Last arg to output_line_command. */
443 enum file_change_code {
444 same_file, enter_file, leave_file
447 /* `struct directive' defines one #-directive, including how to handle it. */
449 struct directive {
450 int length; /* Length of name */
451 /*@null@*/ int (*func)(); /* Function to handle directive */
452 /*@observer@*/ cstring name; /* Name of directive */
453 enum node_type type; /* Code which describes which directive. */
454 bool command_reads_line; /* One if rest of line is read by func. */
455 bool traditional_comments; /* Nonzero: keep comments if -traditional. */
456 bool pass_thru; /* Copy preprocessed directive to output file.*/
459 /* These functions are declared to return int instead of void since they
460 are going to be placed in a table and some old compilers have trouble with
461 pointers to functions returning void. */
463 static int do_define (cppReader *, /*@null@*/ struct directive *,
464 /*@exposed@*/ char *, char *);
465 static int do_defineAux (cppReader *, /*@null@*/ struct directive *,
466 /*@exposed@*/ char *, char *, bool);
468 static int do_line (cppReader *, /*@null@*/ struct directive *);
469 static int do_include (cppReader *, struct directive *, char *, char *);
470 static int do_undef (cppReader *, struct directive *, char *, char *);
471 static int do_error (cppReader *, struct directive *, char *, char *);
472 static int do_pragma (cppReader *, struct directive *, char *, char *);
473 static int do_ident (cppReader *, struct directive *, char *, char *);
474 static int do_if (cppReader *, struct directive *, char *, char *);
475 static int do_xifdef (cppReader *, struct directive *, char *, char *);
476 static int do_else (cppReader *, struct directive *, char *, char *);
477 static int do_elif (cppReader *, struct directive *, char *, char *);
478 static int do_endif (cppReader *, struct directive *, char *, char *);
479 static int do_warning (cppReader *, struct directive *, char *, char *);
481 /* If a buffer's dir field is SELF_DIR_DUMMY, it means the file was found
482 via the same directory as the file that #included it. */
484 /*@constant observer struct file_name_list *SELF_DIR_DUMMY@*/
485 #define SELF_DIR_DUMMY ((struct file_name_list *) (~0))
487 /* #include "file" looks in source file dir, then stack. */
488 /* #include <file> just looks in the stack. */
489 /* -I directories are added to the end, then the defaults are added. */
491 /*@access cstring@*/
493 static struct default_include {
494 /*@dependent@*/ /*@observer@*/ cstring fname; /* The name of the directory. */
495 int cplusplus; /* Only look here if we're compiling C++. */
496 int cxx_aware; /* Includes in this directory don't need to
497 be wrapped in extern "C" when compiling
498 C++. */
499 } include_defaults_array[]
501 /* This is the dir for fixincludes. Put it just before
502 the files that we fix. */
503 { GCC_INCLUDE_DIR, 0, 0 },
504 { GCC_INCLUDE_DIR2, 0, 0 },
505 { cstring_undefined, 0, 0 }
508 /*@noaccess cstring@*/
510 /* Here is the actual list of #-directives, most-often-used first.
511 The initialize_builtins function assumes #define is the very first. */
513 /*@access cstring@*/
515 static struct directive directive_table[] = {
516 { 6, do_define, "define", T_DEFINE, FALSE, TRUE, FALSE },
517 { 5, do_xifdef, "ifdef", T_IFDEF, TRUE, FALSE, FALSE },
518 { 6, do_xifdef, "ifndef", T_IFNDEF, TRUE, FALSE, FALSE },
519 { 7, do_include, "include", T_INCLUDE, TRUE, FALSE, FALSE },
520 { 5, do_endif, "endif", T_ENDIF, TRUE, FALSE, FALSE },
521 { 4, do_else, "else", T_ELSE, TRUE, FALSE, FALSE },
522 { 2, do_if, "if", T_IF, TRUE, FALSE, FALSE },
523 { 4, do_elif, "elif", T_ELIF, TRUE, FALSE, FALSE },
524 { 5, do_undef, "undef", T_UNDEF, FALSE, FALSE, FALSE },
525 { 5, do_error, "error", T_ERROR, FALSE, FALSE, FALSE },
526 { 7, do_warning, "warning", T_WARNING, FALSE, FALSE, FALSE },
527 { 6, do_pragma, "pragma", T_PRAGMA, FALSE, FALSE, TRUE},
528 { 4, do_line, "line", T_LINE, TRUE, FALSE, FALSE },
529 { 5, do_ident, "ident", T_IDENT, TRUE, FALSE, TRUE },
530 /* { 8, do_unassert, "unassert", T_UNASSERT, TRUE, FALSE, FALSE }, */
531 { -1, NULL, "", T_UNUSED, FALSE, FALSE, FALSE },
533 /*@noaccess cstring@*/
535 static cstring searchPath_unparse (struct file_name_list *search_start)
537 cstring res = cstring_newEmpty ();
538 struct file_name_list *searchptr = NULL;
540 for (searchptr = search_start; searchptr != NULL;
541 searchptr = searchptr->next)
543 if (!cstring_isEmpty (searchptr->fname)) {
544 res = cstring_concatFree1 (res, searchptr->fname);
545 if (searchptr->next != NULL) {
546 res = cstring_appendChar (res, ';');
551 return res;
554 /*@+charint@*/
555 static void
556 initialize_char_syntax (struct cppOptions *opts)
558 char i;
561 * Set up is_idchar and is_idstart tables. These should be
562 * faster than saying (is_alpha (c) || c == '_'), etc.
563 * Set up these things before calling any routines tthat
564 * refer to them.
567 for (i = 'a'; i <= 'z'; i++) {
568 is_idchar[i - 'a' + 'A'] = TRUE;
569 is_idchar[(int) i] = TRUE;
570 is_idstart[i - 'a' + 'A'] = TRUE;
571 is_idstart[(int) i] = TRUE;
574 for (i = '0'; i <= '9'; i++)
576 is_idchar[(int) i] = TRUE;
579 is_idchar['_'] = TRUE;
580 is_idstart['_'] = TRUE;
581 is_idchar['$'] = opts->dollars_in_ident;
582 is_idstart['$'] = opts->dollars_in_ident;
584 /* horizontal space table */
585 is_hor_space[' '] = TRUE;
586 is_hor_space['\t'] = TRUE;
587 is_hor_space['\v'] = TRUE;
588 is_hor_space['\f'] = TRUE;
589 is_hor_space['\r'] = TRUE;
591 is_space[' '] = TRUE;
592 is_space['\t'] = TRUE;
593 is_space['\v'] = TRUE;
594 is_space['\f'] = TRUE;
595 is_space['\n'] = TRUE;
596 is_space['\r'] = TRUE;
599 bool isIdentifierChar (char c)
601 return is_idchar[(int) c];
604 /* Place into P_PFILE a quoted string representing the string SRC.
605 Caller must reserve enough space in pfile->token_buffer. */
607 static void
608 quote_string (cppReader *pfile, char *src)
610 char c;
612 cppReader_putCharQ (pfile, '\"');
613 for (;;)
615 switch ((c = *src++))
617 default:
618 if (isprint (c))
619 cppReader_putCharQ (pfile, c);
620 else
622 sprintf (cpplib_getPWritten (pfile), "\\%03o",
623 (unsigned int) c);
624 cppReader_adjustWritten (pfile, (size_t) 4);
626 /*@switchbreak@*/ break;
628 case '\"':
629 case '\\':
630 cppReader_putCharQ (pfile, '\\');
631 cppReader_putCharQ (pfile, c);
632 /*@switchbreak@*/ break;
634 case '\0':
635 cppReader_putCharQ (pfile, '\"');
636 cppReader_nullTerminateQ (pfile);
637 return;
642 /* Re-allocates PFILE->token_buffer so it will hold at least N more chars. */
644 void
645 cppReader_growBuffer (cppReader *pfile, size_t n)
647 size_t old_written = cpplib_getWritten (pfile);
648 pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
649 pfile->token_buffer = (char *)
650 drealloc (pfile->token_buffer, pfile->token_buffer_size);
651 cppReader_setWritten (pfile, old_written);
655 * process a given definition string, for initialization
656 * If STR is just an identifier, define it with value 1.
657 * If STR has anything after the identifier, then it should
658 * be identifier=definition.
661 void
662 cppReader_define (cppReader *pfile, char *str)
664 char *buf = NULL;
665 char *p = str;
667 DPRINTF (("Cpp reader define: %s", str));
669 if (!is_idstart[(int) *p])
671 DPRINTF (("ERROR 1"));
672 cppReader_error (pfile,
673 message ("Malformed option `-D%s'",
674 cstring_fromChars (str)));
676 return;
679 p++;
681 DPRINTF (("Here 2"));
683 while (is_idchar[(int) *p])
685 p++;
688 if (*p == '(') {
689 p++;
690 while (*p != ')' && *p != '\0') {
691 p++;
694 if (*p == ')') {
695 p++;
696 } else {
697 cppReader_error
698 (pfile,
699 message ("Malformed option: -D%s (no closing parenthesis)",
700 cstring_fromChars (str)));
704 DPRINTF (("Here 2"));
706 if (*p == '\0')
708 buf = (char *) dmalloc (size_fromInt (p - str + 4));
709 strcpy ((char *) buf, str);
710 strcat ((char *) buf, " 1");
712 else if (*p != '=')
714 DPRINTF (("ERROR 2"));
715 cppReader_error (pfile,
716 message ("Malformed option: -D%s (expected '=', found '%c')",
717 cstring_fromChars (str),
718 *p));
719 return;
721 else
723 char *q;
724 /* Copy the entire option so we can modify it. */
725 DPRINTF (("Copying..."));
726 buf = (char *) dmalloc (2 * strlen (str) + 1);
727 strncpy (buf, str, size_fromInt (p - str));
729 /* Change the = to a space. */
730 buf[p - str] = ' ';
731 /* Scan for any backslash-newline and remove it. */
732 p++;
733 q = &buf[p - str];
735 while (*p != '\0')
737 if (*p == '\\' && p[1] == '\n')
738 p += 2;
739 else
740 *q++ = *p++;
743 DPRINTF (("Here we are..."));
744 *q = '\0';
747 llassert (buf != NULL);
748 DPRINTF (("Do define: %s / %ld", buf, size_toLong (strlen (buf))));
749 (void) do_define (pfile, NULL, buf, buf + strlen (buf));
750 sfree (buf);
753 /* Append a chain of `struct file_name_list's
754 to the end of the main include chain.
755 FIRST is gthe beginning of the chain to append, and LAST is the end. */
757 void
758 cppReader_appendIncludeChain (cppReader *pfile,
759 struct file_name_list *first,
760 struct file_name_list *last)
762 struct cppOptions *opts = CPPOPTIONS (pfile);
763 struct file_name_list *dir;
765 if (first == NULL || last == NULL)
767 return;
770 if (opts->include == 0)
772 opts->include = first;
774 else
776 llassert (opts->last_include->next == NULL);
777 opts->last_include->next = first;
780 if (opts->first_bracket_include == 0)
782 opts->first_bracket_include = first;
784 for (dir = first; ; dir = dir->next) {
785 size_t len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
787 if (len > pfile->max_include_len)
789 pfile->max_include_len = len;
792 if (dir == last)
794 break;
799 llassert (last->next == NULL);
800 /* last->next = NULL; */
801 opts->last_include = last;
804 # if 0
805 static /*@unused@*/ void
806 cppReader_showIncludeChain (cppReader *pfile)
808 struct file_name_list *dirs = CPPOPTIONS (pfile)->include;
810 if (dirs != NULL)
812 while (dirs != NULL)
814 fprintf (stderr, "*%s*:", cstring_toCharsSafe (dirs->fname));
815 dirs = dirs->next;
818 fprintf (stderr, "\n");
820 else
822 fprintf (stderr, "No includes\n");
825 # endif
827 cstring
828 cppReader_getIncludePath ()
830 cppReader *pfile = &g_cppState;
831 struct file_name_list *dirs = CPPOPTIONS (pfile)->include;
832 cstring res = cstring_undefined;
834 if (dirs != NULL)
836 while (dirs != NULL)
838 res = message ("%q%c%s", res, PATH_SEPARATOR, dirs->fname);
839 dirs = dirs->next;
842 else
844 res = cstring_makeLiteral ("<no include path>");
847 return res;
850 void
851 cppReader_addIncludeChain (cppReader *pfile, /*@only@*/ struct file_name_list *dir)
853 struct cppOptions *opts = CPPOPTIONS (pfile);
855 if (dir == NULL)
857 return;
860 if (opts->include == 0)
862 opts->include = dir;
864 else
866 llassert (opts->last_include->next == NULL);
867 opts->last_include->next = dir;
870 if (opts->first_bracket_include == 0)
872 size_t len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
873 opts->first_bracket_include = dir;
875 if (len > pfile->max_include_len)
877 pfile->max_include_len = len;
881 dir->next = NULL;
882 opts->last_include = dir;
883 /* cppReader_showIncludeChain (pfile); */
886 /* Given a colon-separated list of file names PATH,
887 add all the names to the search path for include files. */
889 static void
890 path_include (cppReader *pfile, char *path)
892 char *p;
894 #ifdef __CYGWIN32__
895 char *win32temp;
897 /* if we have a posix path list, convert to win32 path list */
898 win32temp = (char *) dmalloc /*@i4@*/
899 (cygwin32_posix_to_win32_path_list_buf_size (path));
900 cygwin32_posix_to_win32_path_list (path, win32temp);
901 path = win32temp;
902 #endif
904 p = path;
906 if (*p != '\0')
907 while (1) {
908 char *q = p;
909 char *name;
910 struct file_name_list *dirtmp;
912 /* Find the end of this name. */
913 while (*q != '\0' && *q != PATH_SEPARATOR)
915 q++;
918 if (p == q)
920 /* An empty name in the path stands for the current directory. */
921 name = (char *) dmalloc ((size_t) 2);
922 name[0] = '.';
923 name[1] = '\0';
925 else
927 /* Otherwise use the directory that is named. */
928 name = (char *) dmalloc (size_fromInt (q - p + 1));
929 memcpy (name, p, size_fromInt (q - p));
930 name[q - p] = '\0';
933 dirtmp = (struct file_name_list *) dmalloc (sizeof (*dirtmp));
934 dirtmp->next = 0; /* New one goes on the end */
935 dirtmp->control_macro = 0;
936 dirtmp->c_system_include_path = 0;
937 dirtmp->fname = cstring_fromChars (name);
938 dirtmp->got_name_map = 0;
939 cppReader_addIncludeChain (pfile, dirtmp);
941 /* Advance past this name. */
942 p = q;
943 if (*p == '\0')
944 break;
945 /* Skip the colon. */
946 p++;
950 void
951 cppOptions_init (cppOptions *opts)
953 memset ((char *) opts, 0, sizeof *opts);
954 assertSet (opts);
956 opts->in_fname = NULL;
957 opts->out_fname = NULL;
959 /* Initialize is_idchar to allow $. */
960 opts->dollars_in_ident = TRUE;
962 opts->no_line_commands = 0;
963 opts->no_trigraphs = TRUE;
964 opts->put_out_comments = 1;
965 opts->print_include_names = 0;
966 opts->dump_macros = DUMP_DEFINITIONS; /* DUMP_NONE; */
967 opts->no_output = 0;
968 opts->cplusplus = 0;
970 opts->cplusplus_comments = 1;
971 opts->verbose = 0;
972 opts->lang_asm = 0;
973 opts->for_lint = 0;
974 opts->chill = 0;
975 opts->pedantic_errors = 0;
976 opts->warn_comments = 0;
977 opts->warnings_are_errors = 0;
979 /* Added 2003-07-10: */
980 opts->traditional = FALSE;
981 opts->c89 = TRUE;
982 initialize_char_syntax (opts);
985 enum cpp_token
986 cppReader_nullUnderflow (/*@unused@*/ cppReader *pfile)
988 return CPP_EOF;
991 void
992 cppReader_nullCleanup (/*@unused@*/ cppBuffer *pbuf,
993 /*@unused@*/ cppReader *pfile)
998 void
999 cppReader_macroCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
1001 hashNode macro = pbuf->hnode;
1003 if (macro->type == T_DISABLED)
1005 macro->type = T_MACRO;
1008 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
1010 sfree (pbuf->buf);
1011 pbuf->buf = NULL;
1015 void
1016 cppReader_fileCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
1018 if (pbuf->buf != NULL)
1020 sfree (pbuf->buf);
1021 pbuf->buf = NULL;
1025 /* Assuming we have read '/'.
1026 If this is the start of a comment (followed by '*' or '/'),
1027 skip to the end of the comment, and return ' '.
1028 Return EOF if we reached the end of file before the end of the comment.
1029 If not the start of a comment, return '/'. */
1031 static int
1032 skip_comment (cppReader *pfile, /*@null@*/ long *linep)
1034 int c = 0;
1036 llassert (pfile->buffer != NULL);
1037 llassert (pfile->buffer->cur != NULL);
1039 while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n')
1041 if (linep != NULL)
1043 (*linep)++;
1046 cppReader_forward (pfile, 2);
1049 if (cppReader_peekC (pfile) == '*')
1051 cppReader_forward (pfile, 1);
1053 for (;;)
1055 int prev_c = c;
1056 c = cppReader_getC (pfile);
1058 if (c == EOF)
1060 return EOF;
1063 while (c == (int) '\\' && cppReader_peekC (pfile) == (int) '\n')
1065 if (linep != NULL )
1067 (*linep)++;
1070 cppReader_forward (pfile, 1), c = cppReader_getC (pfile);
1073 if (prev_c == (int) '*' && c == (int) '/')
1075 return (int) ' ';
1078 if (c == (int) '\n' && (linep != NULL))
1080 (*linep)++;
1084 else if (cppReader_peekC (pfile) == '/'
1085 && CPPOPTIONS (pfile)->cplusplus_comments)
1088 (void) cppoptgenerror
1089 (FLG_SLASHSLASHCOMMENT,
1090 message ("C++ style // comment"
1092 pfile);
1094 cppReader_forward (pfile, 1);
1096 for (;;)
1098 c = cppReader_getC (pfile);
1100 if (c == EOF)
1102 /* Allow hash comment to be terminated by EOF. */
1103 return (int) ' ';
1106 while (c == (int) '\\' && cppReader_peekC (pfile) == '\n')
1108 cppReader_forward (pfile, 1);
1109 c = cppReader_getC (pfile);
1111 if (linep != NULL)
1113 (*linep)++;
1117 if (c == (int) '\n')
1119 /* Don't consider final '\n' to be part of comment. */
1120 cppReader_forward (pfile, -1);
1121 return (int) ' ';
1125 else
1127 return (int) '/';
1131 /* Skip whitespace \-newline and comments. Does not macro-expand. */
1132 int /*@alt void@*/
1133 cppSkipHspace (cppReader *pfile)
1135 int nspaces = 0;
1137 while (TRUE)
1139 int c;
1141 llassert (pfile->buffer != NULL);
1143 c = cppReader_peekC (pfile);
1145 if (c == EOF)
1147 return 0; /* FIXME */
1150 if (is_hor_space[c])
1152 if ((c == '\f' || c == '\v') && cppReader_isPedantic (pfile))
1153 cppReader_pedwarn (pfile,
1154 message ("%s in preprocessing directive",
1155 c == '\f'
1156 ? cstring_makeLiteralTemp ("formfeed")
1157 : cstring_makeLiteralTemp ("vertical tab")));
1159 nspaces++;
1160 cppReader_forward (pfile, 1);
1162 else if (c == '/')
1164 cppReader_forward (pfile, 1);
1165 c = skip_comment (pfile, NULL);
1167 if (c == '/')
1169 cppReader_forward (pfile, -1);
1172 if (c == EOF || c == '/')
1174 return nspaces;
1177 else if (c == '\\' && cpp_peekN (pfile, 1) == '\n')
1179 cppReader_forward (pfile, 2);
1181 else if (c == '@' && CPPBUFFER (pfile)->has_escapes
1182 && is_hor_space [cpp_peekN (pfile, 1)])
1184 cppReader_forward (pfile, 2);
1186 else
1188 return nspaces;
1193 /* Read the rest of the current line.
1194 The line is appended to PFILE's output buffer. */
1196 static void
1197 copy_rest_of_line (cppReader *pfile)
1199 struct cppOptions *opts = CPPOPTIONS (pfile);
1201 for (;;)
1203 int c;
1204 int nextc;
1206 llassert (pfile->buffer != NULL);
1208 c = cppReader_getC (pfile);
1210 switch (c)
1212 case EOF:
1213 goto end_directive;
1214 case '\\':
1216 ** Patch from Brian St. Pierre for handling MS-DOS files.
1219 DPRINTF (("Reading directive: %d", (int) c));
1221 if (cppReader_peekC (pfile) == '\n'
1222 || cppReader_peekC (pfile) == '\r')
1224 DPRINTF (("Reading directive..."));
1225 if (cppReader_peekC (pfile) == '\r')
1227 DPRINTF (("Reading directive..."));
1228 cppReader_forward (pfile, 1);
1231 DPRINTF (("Reading directive..."));
1232 cppReader_forward (pfile, 1);
1233 continue;
1236 DPRINTF (("Falling..."));
1237 /*@fallthrough@*/ case '\'': case '\"':
1238 goto scan_directive_token;
1240 case '/':
1241 nextc = cppReader_peekC (pfile);
1244 ** was (opts->cplusplus_comments && nextc == '*')
1245 ** yoikes!
1248 if (nextc == '*'
1249 || (opts->cplusplus_comments && nextc == '/'))
1251 goto scan_directive_token;
1253 /*@switchbreak@*/ break;
1254 case '\f':
1255 case '\v':
1256 if (cppReader_isPedantic (pfile))
1257 cppReader_pedwarn (pfile,
1258 message ("%s in preprocessing directive",
1259 c == '\f'
1260 ? cstring_makeLiteralTemp ("formfeed")
1261 : cstring_makeLiteralTemp ("vertical tab")));
1262 /*@switchbreak@*/ break;
1264 case '\n':
1265 cppReader_forward (pfile, -1);
1266 goto end_directive;
1267 scan_directive_token:
1268 cppReader_forward (pfile, -1);
1269 (void) cpplib_getToken (pfile);
1270 continue;
1272 cppReader_putChar (pfile, c);
1274 end_directive: ;
1275 cppReader_nullTerminate (pfile);
1278 void
1279 cppReader_skipRestOfLine (cppReader *pfile)
1281 size_t old = cpplib_getWritten (pfile);
1282 copy_rest_of_line (pfile);
1283 cppReader_setWritten (pfile, old);
1286 /* Handle a possible # directive.
1287 '#' has already been read. */
1290 cppReader_handleDirective (cppReader *pfile)
1292 int c;
1293 struct directive *kt = NULL;
1294 int ident_length;
1295 size_t after_ident = 0;
1296 char *ident = NULL;
1297 char *line_end = NULL;
1298 size_t old_written = cpplib_getWritten (pfile);
1299 int nspaces = cppSkipHspace (pfile);
1301 c = cppReader_peekC (pfile);
1303 if (c >= '0' && c <= '9')
1305 /* Handle # followed by a line number. */
1306 if (cppReader_isPedantic (pfile))
1308 cppReader_pedwarnLit
1309 (pfile,
1310 cstring_makeLiteralTemp ("`#' followed by integer"));
1313 (void) do_line (pfile, NULL);
1314 goto done_a_directive;
1318 /* Now find the directive name. */
1320 cppReader_putChar (pfile, '#');
1322 parse_name (pfile, cppReader_getC (pfile));
1324 llassert (pfile->token_buffer != NULL);
1325 ident = pfile->token_buffer + old_written + 1;
1327 ident_length = cpplib_getPWritten (pfile) - ident;
1329 if (ident_length == 0 && cppReader_peekC (pfile) == '\n')
1331 /* A line of just `#' becomes blank. */
1332 return 1;
1335 for (kt = directive_table; ; kt++)
1337 if (kt->length <= 0)
1339 return 0; /* goto not_a_directive; */
1342 if (kt->length == ident_length
1343 && (cstring_equalPrefix (kt->name, cstring_fromChars (ident))))
1345 break;
1349 if (kt->command_reads_line)
1351 after_ident = 0;
1353 else
1355 /* Nonzero means do not delete comments within the directive.
1356 #define needs this when -traditional. */
1357 bool comments = 1; /*cppReader_isTraditional (pfile) && kt->traditional_comments; */
1358 int save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
1359 CPPOPTIONS (pfile)->put_out_comments = comments;
1360 after_ident = cpplib_getWritten (pfile);
1361 copy_rest_of_line (pfile);
1362 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
1366 /* For #pragma and #define, we may want to pass through the directive.
1367 Other directives may create output, but we don't want the directive
1368 itself out, so we pop it now. For example #include may write a #line
1369 command (see comment in do_include), and conditionals may emit
1370 #failed ... #endfailed stuff. But note that popping the buffer
1371 means the parameters to kt->func may point after pfile->limit
1372 so these parameters are invalid as soon as something gets appended
1373 to the token_buffer. */
1375 line_end = cpplib_getPWritten (pfile);
1378 if (!kt->pass_thru && kt->type != T_DEFINE)
1380 cppReader_setWritten (pfile, old_written);
1383 llassert (pfile->token_buffer != NULL);
1385 /* was kt->pass_thru || */
1387 if (kt->type == T_DEFINE
1388 && cpp_shouldCheckMacro (pfile, pfile->token_buffer + old_written))
1390 char *p = pfile->token_buffer + old_written;
1393 ** Still need to record value for preprocessing, so
1394 ** #ifdef's, etc. using the value behave correctly.
1397 (void) do_defineAux (pfile, kt,
1398 pfile->token_buffer + after_ident,
1399 line_end,
1400 TRUE);
1402 if (*p == '#')
1404 *p = ' ';
1407 SKIP_WHITE_SPACE (p);
1409 llassert (*p == 'd');
1410 *p++ = LLMRCODE[0];
1412 llassert (*p == 'e');
1413 *p++ = LLMRCODE[1];
1415 llassert (*p == 'f');
1416 *p++ = LLMRCODE[2];
1418 llassert (*p == 'i');
1419 *p++ = LLMRCODE[3];
1421 llassert (*p == 'n');
1422 *p++ = LLMRCODE[4];
1424 llassert (*p == 'e');
1427 ** This is way-bogus. We use the last char to record the number of
1428 ** spaces. Its too hard to get them back into the input stream.
1431 if (nspaces > 9) nspaces = 9;
1433 *p++ = '0' + nspaces;
1435 return 0; /* not_a_directive */
1437 else if (kt->pass_thru)
1439 /* Just leave the entire #define in the output stack. */
1440 return 0; /* not_a_directive */
1443 else if (kt->type == T_DEFINE
1444 && CPPOPTIONS (pfile)->dump_macros == DUMP_NAMES)
1446 char *p = pfile->token_buffer + old_written + 7; /* Skip "#define". */
1447 SKIP_WHITE_SPACE (p);
1449 while (is_idchar[(int) *p])
1451 p++;
1454 pfile->limit = p;
1455 cppReader_putChar (pfile, '\n');
1457 else if (kt->type == T_DEFINE)
1459 cppReader_setWritten (pfile, old_written);
1461 else
1466 done_a_directive:
1467 if (kt == NULL) {
1468 return 1;
1469 } else {
1470 llassert (kt->func != NULL);
1471 (void) (kt->func) (pfile, kt, pfile->token_buffer + after_ident, line_end);
1472 return 1;
1476 /* Pass a directive through to the output file.
1477 BUF points to the contents of the directive, as a contiguous string.
1478 LIMIT points to the first character past the end of the directive.
1479 KEYWORD is the keyword-table entry for the directive. */
1481 static void
1482 pass_thru_directive (char *buf, char *limit,
1483 cppReader *pfile,
1484 struct directive *keyword)
1486 int keyword_length = keyword->length;
1488 cpplib_reserve (pfile,
1489 size_fromInt (2 + keyword_length + (limit - buf)));
1490 cppReader_putCharQ (pfile, '#');
1491 /*@-observertrans@*/
1492 cppReader_putStrN (pfile, cstring_toCharsSafe (keyword->name),
1493 size_fromInt (keyword_length));
1494 /*:=observertrans@*/
1496 if (limit != buf && buf[0] != ' ')
1498 /* Was a bug, since reserve only used 1 + ... */
1499 cppReader_putCharQ (pfile, ' ');
1502 cppReader_putStrN (pfile, buf, size_fromInt (limit - buf));
1505 /* Read a replacement list for a macro with parameters.
1506 Build the DEFINITION structure.
1507 Reads characters of text starting at BUF until END.
1508 ARGLIST specifies the formal parameters to look for
1509 in the text of the definition; NARGS is the number of args
1510 in that list, or -1 for a macro name that wants no argument list.
1511 MACRONAME is the macro name itself (so we can avoid recursive expansion)
1512 and NAMELEN is its length in characters.
1514 Note that comments, backslash-newlines, and leading white space
1515 have already been deleted from the argument. */
1517 static DEFINITION *
1518 collect_expansion (cppReader *pfile, char *buf, char *limit,
1519 int nargs, /*@null@*/ struct arglist *arglist)
1521 DEFINITION *defn;
1522 char *p, *lastp, *exp_p;
1523 struct reflist *endpat = NULL;
1524 /* Pointer to first nonspace after last ## seen. */
1525 char *concat = 0;
1526 /* Pointer to first nonspace after last single-# seen. */
1527 char *stringify = 0;
1528 size_t maxsize;
1529 char expected_delimiter = '\0';
1532 /* Scan thru the replacement list, ignoring comments and quoted
1533 strings, picking up on the macro calls. It does a linear search
1534 thru the arg list on every potential symbol. Profiling might say
1535 that something smarter should happen. */
1537 if (limit < buf)
1538 abort ();
1540 /* Find the beginning of the trailing whitespace. */
1541 p = buf;
1543 while (p < limit && is_space[(int) limit[-1]])
1545 limit--;
1548 /* Allocate space for the text in the macro definition.
1549 Leading and trailing whitespace chars need 2 bytes each.
1550 Each other input char may or may not need 1 byte,
1551 so this is an upper bound. The extra 5 are for invented
1552 leading and trailing newline-marker and final null. */
1553 maxsize = (sizeof (*defn) + (limit - p) + 5);
1555 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1556 while (p < limit)
1558 if (*p++ == '@')
1560 maxsize++;
1564 defn = (DEFINITION *) dmalloc (maxsize);
1565 defn->noExpand = FALSE;
1566 defn->file = NULL;
1567 defn->pattern = NULL;
1568 defn->nargs = nargs;
1569 defn->predefined = NULL;
1571 exp_p = defn->expansion = (char *) defn + sizeof (*defn);
1572 *defn->expansion = '\0'; /* convince splint it is initialized */
1574 defn->line = 0;
1575 defn->rest_args = NULL;
1576 defn->args.argnames = NULL;
1578 lastp = exp_p;
1580 p = buf;
1582 /* Add one initial space escape-marker to prevent accidental
1583 token-pasting (often removed by cpplib_macroExpand). */
1584 *exp_p++ = '@';
1585 *exp_p++ = ' ';
1587 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1588 cppReader_errorLit (pfile,
1589 cstring_makeLiteralTemp ("`##' at start of macro definition"));
1590 p += 2;
1593 /* Process the main body of the definition. */
1594 while (p < limit) {
1595 int skipped_arg = 0;
1596 register char c = *p++;
1598 *exp_p++ = c;
1600 if (!cppReader_isTraditional (pfile)) {
1601 switch (c) {
1602 case '\'':
1603 case '\"':
1604 if (expected_delimiter != '\0')
1606 if (c == expected_delimiter)
1607 expected_delimiter = '\0';
1609 else
1611 expected_delimiter = c;
1613 /*@switchbreak@*/ break;
1615 case '\\':
1616 if (p < limit && (expected_delimiter != '\0'))
1618 /* In a string, backslash goes through
1619 and makes next char ordinary. */
1620 *exp_p++ = *p++;
1622 /*@switchbreak@*/ break;
1624 case '@':
1625 /* An '@' in a string or character constant stands for itself,
1626 and does not need to be escaped. */
1627 if (expected_delimiter == '\0')
1629 *exp_p++ = c;
1632 /*@switchbreak@*/ break;
1634 case '#':
1635 /* # is ordinary inside a string. */
1636 if (expected_delimiter != '\0')
1638 /*@switchbreak@*/ break;
1641 if (p < limit && *p == '#') {
1642 /* ##: concatenate preceding and following tokens. */
1643 /* Take out the first #, discard preceding whitespace. */
1644 exp_p--;
1646 /*@-usedef@*/
1647 while (exp_p > lastp && is_hor_space[(int) exp_p[-1]])
1649 --exp_p;
1651 /*@=usedef@*/
1653 /* Skip the second #. */
1654 p++;
1655 /* Discard following whitespace. */
1656 SKIP_WHITE_SPACE (p);
1657 concat = p;
1658 if (p == limit)
1660 cppReader_errorLit (pfile,
1661 cstring_makeLiteralTemp ("`##' at end of macro definition"));
1663 } else if (nargs >= 0) {
1664 /* Single #: stringify following argument ref.
1665 Don't leave the # in the expansion. */
1666 exp_p--;
1667 SKIP_WHITE_SPACE (p);
1668 if (p == limit || ! is_idstart[(int) *p]
1669 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '\"')))
1670 cppReader_errorLit (pfile,
1671 cstring_makeLiteralTemp ("`#' operator is not followed by a macro argument name"));
1672 else
1673 stringify = p;
1674 } else {
1675 ; /* BADBRANCH; */
1678 /*@switchbreak@*/ break;
1680 } else {
1681 /* In -traditional mode, recognize arguments inside strings and
1682 and character constants, and ignore special properties of #.
1683 Arguments inside strings are considered "stringified", but no
1684 extra quote marks are supplied. */
1685 switch (c) {
1686 case '\'':
1687 case '\"':
1688 if (expected_delimiter != '\0') {
1689 if (c == expected_delimiter)
1690 expected_delimiter = '\0';
1691 } else
1692 expected_delimiter = c;
1693 /*@switchbreak@*/ break;
1695 case '\\':
1696 /* Backslash quotes delimiters and itself, but not macro args. */
1697 if (expected_delimiter != '\0' && p < limit
1698 && (*p == expected_delimiter || *p == '\\')) {
1699 *exp_p++ = *p++;
1700 continue;
1702 /*@switchbreak@*/ break;
1704 case '/':
1705 if (expected_delimiter != '\0') /* No comments inside strings. */
1706 /*@switchbreak@*/ break;
1707 if (*p == '*') {
1708 /* If we find a comment that wasn't removed by cppReader_handleDirective,
1709 this must be -traditional. So replace the comment with
1710 nothing at all. */
1711 exp_p--;
1712 p += 1;
1713 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
1715 p++;
1718 /*@switchbreak@*/ break;
1722 /* Handle the start of a symbol. */
1723 if (is_idchar[(int) c] && nargs > 0) {
1724 char *id_beg = p - 1;
1725 size_t id_len;
1727 --exp_p;
1728 while (p != limit && is_idchar[(int) *p])
1730 p++;
1733 id_len = size_fromInt (p - id_beg);
1735 if (is_idstart[(int) c]
1736 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '\"'))) {
1737 register struct arglist *arg;
1739 for (arg = arglist; arg != NULL; arg = arg->next) {
1740 struct reflist *tpat;
1742 if (arg->name[0] == c
1743 && arg->length == id_len
1744 && strncmp (arg->name, id_beg, id_len) == 0) {
1745 char *p1;
1747 if (expected_delimiter && CPPOPTIONS (pfile)->warn_stringify) {
1748 if (cppReader_isTraditional (pfile)) {
1749 cppReader_warning (pfile,
1750 message ("macro argument `%x' is stringified.",
1751 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1752 } else {
1753 cppReader_warning (pfile,
1754 message ("macro arg `%x' would be stringified with -traditional.",
1755 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1758 /* If ANSI, don't actually substitute inside a string. */
1759 if (!cppReader_isTraditional (pfile) && expected_delimiter)
1760 /*@innerbreak@*/ break;
1761 /* make a pat node for this arg and append it to the end of
1762 the pat list */
1763 tpat = (struct reflist *) dmalloc (sizeof (*tpat));
1764 tpat->next = NULL;
1765 tpat->raw_before = (concat == id_beg);
1766 tpat->raw_after = 0;
1767 tpat->rest_args = arg->rest_args;
1768 tpat->stringify = (cppReader_isTraditional (pfile)
1769 ? expected_delimiter != '\0'
1770 : stringify == id_beg);
1772 if (endpat == NULL)
1774 defn->pattern = tpat;
1776 else
1778 endpat->next = tpat;
1779 /*@-branchstate@*/
1780 } /*@=branchstate@*/ /* evs 2000 was =branchstate */
1782 endpat = tpat;
1784 tpat->argno = arg->argno;
1785 tpat->nchars = exp_p - lastp;
1787 p1 = p;
1789 SKIP_WHITE_SPACE (p1);
1791 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
1793 tpat->raw_after = 1;
1796 lastp = exp_p; /* place to start copying from next time */
1797 skipped_arg = 1;
1799 /*@innerbreak@*/ break;
1804 /* If this was not a macro arg, copy it into the expansion. */
1805 if (skipped_arg == 0) {
1806 register char *lim1 = p;
1807 p = id_beg;
1809 while (p != lim1)
1811 *exp_p++ = *p++;
1814 if (stringify == id_beg)
1815 cppReader_errorLit (pfile,
1816 cstring_makeLiteralTemp ("`#' operator should be followed by a macro argument name"));
1821 if (!cppReader_isTraditional (pfile) && expected_delimiter == '\0')
1823 /* If ANSI, put in a "@ " marker to prevent token pasting.
1824 But not if "inside a string" (which in ANSI mode
1825 happens only for -D option). */
1826 *exp_p++ = '@';
1827 *exp_p++ = ' ';
1830 *exp_p = '\0';
1832 defn->length = size_fromInt (exp_p - defn->expansion);
1834 /* Crash now if we overrun the allocated size. */
1835 if (defn->length + 1 > maxsize)
1837 llfatalbug (cstring_makeLiteral ("Maximum definition size exceeded."));
1840 return defn; /* Spurious warning here */
1844 ** evans 2001-12-31
1845 ** Gasp...cut-and-pasted from above to deal with pfile (should replace throughout with this...)
1848 static DEFINITION *
1849 collect_expansionLoc (fileloc loc, char *buf, char *limit,
1850 int nargs, /*@null@*/ struct arglist *arglist)
1852 DEFINITION *defn;
1853 char *p, *lastp, *exp_p;
1854 struct reflist *endpat = NULL;
1855 /* Pointer to first nonspace after last ## seen. */
1856 char *concat = 0;
1857 /* Pointer to first nonspace after last single-# seen. */
1858 char *stringify = 0;
1859 size_t maxsize;
1860 char expected_delimiter = '\0';
1863 /* Scan thru the replacement list, ignoring comments and quoted
1864 strings, picking up on the macro calls. It does a linear search
1865 thru the arg list on every potential symbol. Profiling might say
1866 that something smarter should happen. */
1868 if (limit < buf)
1870 llfatalbug (message ("%q: Limit is less than initial buffer pointer",
1871 fileloc_unparse (loc)));
1874 /* Find the beginning of the trailing whitespace. */
1875 p = buf;
1877 while (p < limit && is_space[(int) limit[-1]])
1879 limit--;
1882 /* Allocate space for the text in the macro definition.
1883 Leading and trailing whitespace chars need 2 bytes each.
1884 Each other input char may or may not need 1 byte,
1885 so this is an upper bound. The extra 5 are for invented
1886 leading and trailing newline-marker and final null. */
1887 maxsize = (sizeof (*defn) + (limit - p) + 5);
1889 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1890 while (p < limit)
1892 if (*p++ == '@')
1894 maxsize++;
1898 defn = (DEFINITION *) dmalloc (maxsize);
1899 defn->noExpand = FALSE;
1900 defn->file = NULL;
1901 defn->pattern = NULL;
1902 defn->nargs = nargs;
1903 defn->predefined = NULL;
1904 exp_p = defn->expansion = (char *) defn + sizeof (*defn);
1906 defn->line = 0;
1907 defn->rest_args = NULL;
1908 defn->args.argnames = NULL;
1910 lastp = exp_p;
1912 p = buf;
1914 /* Add one initial space escape-marker to prevent accidental
1915 token-pasting (often removed by cpplib_macroExpand). */
1916 *exp_p++ = '@';
1917 *exp_p++ = ' ';
1919 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1920 voptgenerror (FLG_PREPROC,
1921 cstring_makeLiteral ("Paste marker ## at start of macro definition"),
1922 loc);
1923 p += 2;
1926 /* Process the main body of the definition. */
1927 while (p < limit) {
1928 int skipped_arg = 0;
1929 register char c = *p++;
1931 *exp_p++ = c;
1933 if (TRUE) { /* !cppReader_isTraditional (pfile)) { */
1934 switch (c) {
1935 case '\'':
1936 case '\"':
1937 if (expected_delimiter != '\0')
1939 if (c == expected_delimiter)
1940 expected_delimiter = '\0';
1942 else
1944 expected_delimiter = c;
1946 /*@switchbreak@*/ break;
1948 case '\\':
1949 if (p < limit && (expected_delimiter != '\0'))
1951 /* In a string, backslash goes through
1952 and makes next char ordinary. */
1953 *exp_p++ = *p++;
1955 /*@switchbreak@*/ break;
1957 case '@':
1958 /* An '@' in a string or character constant stands for itself,
1959 and does not need to be escaped. */
1960 if (expected_delimiter == '\0')
1962 *exp_p++ = c;
1965 /*@switchbreak@*/ break;
1967 case '#':
1968 /* # is ordinary inside a string. */
1969 if (expected_delimiter != '\0')
1971 /*@switchbreak@*/ break;
1974 if (p < limit && *p == '#') {
1975 /* ##: concatenate preceding and following tokens. */
1976 /* Take out the first #, discard preceding whitespace. */
1977 exp_p--;
1979 /*@-usedef@*/
1980 while (exp_p > lastp && is_hor_space[(int) exp_p[-1]])
1982 --exp_p;
1984 /*@=usedef@*/
1986 /* Skip the second #. */
1987 p++;
1988 /* Discard following whitespace. */
1989 SKIP_WHITE_SPACE (p);
1990 concat = p;
1991 if (p == limit)
1993 voptgenerror (FLG_PREPROC,
1994 cstring_makeLiteral ("`##' at end of macro definition"),
1995 loc);
1997 } else if (nargs >= 0) {
1998 /* Single #: stringify following argument ref.
1999 Don't leave the # in the expansion. */
2000 exp_p--;
2001 SKIP_WHITE_SPACE (p);
2002 if (p == limit || ! is_idstart[(int) *p]
2003 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '\"')))
2005 voptgenerror
2006 (FLG_PREPROC,
2007 cstring_makeLiteral ("`#' operator is not followed by a macro argument name"),
2008 loc);
2010 else
2011 stringify = p;
2012 } else {
2013 ; /* BADBRANCH; */
2016 /*@switchbreak@*/ break;
2018 } else {
2019 /* In -traditional mode, recognize arguments inside strings and
2020 and character constants, and ignore special properties of #.
2021 Arguments inside strings are considered "stringified", but no
2022 extra quote marks are supplied. */
2023 switch (c) {
2024 case '\'':
2025 case '\"':
2026 if (expected_delimiter != '\0') {
2027 if (c == expected_delimiter)
2028 expected_delimiter = '\0';
2029 } else
2030 expected_delimiter = c;
2031 /*@switchbreak@*/ break;
2033 case '\\':
2034 /* Backslash quotes delimiters and itself, but not macro args. */
2035 if (expected_delimiter != '\0' && p < limit
2036 && (*p == expected_delimiter || *p == '\\')) {
2037 *exp_p++ = *p++;
2038 continue;
2040 /*@switchbreak@*/ break;
2042 case '/':
2043 if (expected_delimiter != '\0') /* No comments inside strings. */
2044 /*@switchbreak@*/ break;
2045 if (*p == '*') {
2046 /* If we find a comment that wasn't removed by cppReader_handleDirective,
2047 this must be -traditional. So replace the comment with
2048 nothing at all. */
2049 exp_p--;
2050 p += 1;
2051 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
2053 p++;
2056 /*@switchbreak@*/ break;
2060 /* Handle the start of a symbol. */
2061 if (is_idchar[(int) c] && nargs > 0) {
2062 char *id_beg = p - 1;
2063 size_t id_len;
2065 --exp_p;
2066 while (p != limit && is_idchar[(int) *p])
2068 p++;
2071 id_len = size_fromInt (p - id_beg);
2073 if (is_idstart[(int) c]
2074 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '\"'))) {
2075 register struct arglist *arg;
2077 for (arg = arglist; arg != NULL; arg = arg->next) {
2078 struct reflist *tpat;
2080 if (arg->name[0] == c
2081 && arg->length == id_len
2082 && strncmp (arg->name, id_beg, id_len) == 0) {
2083 char *p1;
2085 if (expected_delimiter) { /* && CPPOPTIONS (pfile)->warn_stringify) { */
2086 if (FALSE) { /* cppReader_isTraditional (pfile)) { */
2087 voptgenerror (FLG_PREPROC,
2088 message ("macro argument `%x' is stringified.",
2089 cstring_prefix (cstring_fromChars (arg->name), id_len)),
2090 loc);
2092 } else {
2093 voptgenerror (FLG_PREPROC,
2094 message ("Macro arg `%x' would be stringified with -traditional.",
2095 cstring_prefix (cstring_fromChars (arg->name), id_len)),
2096 loc);
2100 /* If ANSI, don't actually substitute inside a string. */
2101 if (TRUE /* !cppReader_isTraditional (pfile) */ && expected_delimiter)
2102 /*@innerbreak@*/ break;
2103 /* make a pat node for this arg and append it to the end of
2104 the pat list */
2105 tpat = (struct reflist *) dmalloc (sizeof (*tpat));
2106 tpat->next = NULL;
2107 tpat->raw_before = (concat == id_beg);
2108 tpat->raw_after = 0;
2109 tpat->rest_args = arg->rest_args;
2110 tpat->stringify = (FALSE /* cppReader_isTraditional (pfile) */
2111 ? expected_delimiter != '\0'
2112 : stringify == id_beg);
2114 if (endpat == NULL)
2116 defn->pattern = tpat;
2118 else
2120 endpat->next = tpat;
2121 /*@-branchstate@*/
2122 } /*@=branchstate@*/ /* evs 2000 was =branchstate */
2124 endpat = tpat;
2126 tpat->argno = arg->argno;
2127 tpat->nchars = exp_p - lastp;
2129 p1 = p;
2131 SKIP_WHITE_SPACE (p1);
2133 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
2135 tpat->raw_after = 1;
2138 lastp = exp_p; /* place to start copying from next time */
2139 skipped_arg = 1;
2141 /*@innerbreak@*/ break;
2146 /* If this was not a macro arg, copy it into the expansion. */
2147 if (skipped_arg == 0) {
2148 register char *lim1 = p;
2149 p = id_beg;
2151 while (p != lim1)
2153 *exp_p++ = *p++;
2156 if (stringify == id_beg)
2158 voptgenerror
2159 (FLG_PREPROC,
2160 cstring_makeLiteral ("# operator should be followed by a macro argument name"),
2161 loc);
2167 if (/*!cppReader_isTraditional (pfile) && */ expected_delimiter == '\0')
2169 /* If ANSI, put in a "@ " marker to prevent token pasting.
2170 But not if "inside a string" (which in ANSI mode
2171 happens only for -D option). */
2172 *exp_p++ = '@';
2173 *exp_p++ = ' ';
2176 *exp_p = '\0';
2178 defn->length = size_fromInt (exp_p - defn->expansion);
2180 /* Crash now if we overrun the allocated size. */
2181 if (defn->length + 1 > maxsize)
2183 llfatalbug (cstring_makeLiteral ("Maximum definition size exceeded."));
2186 /*@-compdef@*/ /* defn->expansion defined? */
2187 return defn;
2188 /*@=compdef@*/
2192 * special extension string that can be added to the last macro argument to
2193 * allow it to absorb the "rest" of the arguments when expanded. Ex:
2194 * #define wow(a, b...) process (b, a, b)
2195 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
2196 * { wow (one, two); } -> { process (two, one, two); }
2197 * if this "rest_arg" is used with the concat token '##' and if it is not
2198 * supplied then the token attached to with ## will not be outputted. Ex:
2199 * #define wow (a, b...) process (b ## , a, ## b)
2200 * { wow (1, 2); } -> { process (2, 1, 2); }
2201 * { wow (one); } -> { process (one); {
2204 /*@-readonlytrans@*/
2205 static char rest_extension[] = "...";
2206 /*:=readonlytrans@*/
2208 /*@notfunction@*/
2209 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
2211 /* Create a DEFINITION node from a #define directive. Arguments are
2212 as for do_define. */
2215 static /*@null@*/ macroDef
2216 create_definition (/*@exposed@*/ char *buf, char *limit,
2217 cppReader *pfile, bool predefinition,
2218 bool noExpand)
2220 char *bp; /* temp ptr into input buffer */
2221 char *symname; /* remember where symbol name starts */
2222 size_t sym_length; /* and how long it is */
2223 int rest_args = 0; /* really int! */
2224 int line;
2225 int col;
2226 cstring file = (CPPBUFFER (pfile) != NULL)
2227 ? CPPBUFFER (pfile)->nominal_fname : cstring_makeLiteralTemp ("");
2228 DEFINITION *defn;
2229 int arglengths = 0; /* Accumulate lengths of arg names
2230 plus number of args. */
2231 macroDef mdef;
2232 char save = *limit;
2233 *limit = '\0';
2234 DPRINTF (("Create definition: %s", buf));
2235 *limit = save;
2237 cppBuffer_getLineAndColumn (CPPBUFFER (pfile), &line, &col);
2239 bp = buf;
2241 while (is_hor_space[(int) *bp])
2243 bp++;
2246 symname = bp; /* remember where it starts */
2248 sym_length = cppReader_checkMacroName (pfile, bp, cstring_makeLiteralTemp ("macro"));
2250 bp += sym_length;
2252 /* Lossage will occur if identifiers or control keywords are broken
2253 across lines using backslash. This is not the right place to take
2254 care of that. */
2256 if (*bp == '(') {
2257 struct arglist *arg_ptrs = NULL;
2258 int argno = 0;
2260 bp++; /* skip '(' */
2261 SKIP_WHITE_SPACE (bp);
2263 /* Loop over macro argument names. */
2264 while (*bp != ')')
2266 struct arglist *temp = (struct arglist *) dmalloc (sizeof (*temp));
2267 temp->name = bp;
2268 temp->next = arg_ptrs;
2269 temp->argno = argno++;
2270 temp->rest_args = 0;
2272 arg_ptrs = temp;
2274 if (rest_args != 0)
2276 cppReader_pedwarn (pfile,
2277 message ("another parameter follows `%s'",
2278 cstring_fromChars (rest_extension)));
2281 if (!is_idstart[(int) *bp])
2283 cppReader_pedwarnLit (pfile,
2284 cstring_makeLiteralTemp ("Invalid character in macro parameter name"));
2287 /* Find the end of the arg name. */
2288 while (is_idchar[(int) *bp])
2290 bp++;
2291 /* do we have a "special" rest-args extension here? */
2292 if (limit - bp > size_toInt (REST_EXTENSION_LENGTH)
2293 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
2295 rest_args = 1;
2296 temp->rest_args = 1;
2297 /*@innerbreak@*/ break;
2301 temp->length = size_fromInt (bp - temp->name);
2303 if (rest_args != 0)
2305 bp += REST_EXTENSION_LENGTH;
2308 arglengths += temp->length + 2;
2309 SKIP_WHITE_SPACE (bp);
2311 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
2312 cppReader_errorLit (pfile,
2313 cstring_makeLiteralTemp ("Parameter list for #define is not parseable"));
2314 goto nope;
2317 if (*bp == ',') {
2318 bp++;
2319 SKIP_WHITE_SPACE (bp);
2321 if (bp >= limit) {
2322 cppReader_errorLit (pfile,
2323 cstring_makeLiteralTemp ("unterminated parameter list in `#define'"));
2324 goto nope;
2327 struct arglist *otemp;
2329 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
2331 if (temp->length == otemp->length &&
2332 strncmp (temp->name, otemp->name, temp->length) == 0) {
2333 cstring name = cstring_copyLength (temp->name, temp->length);
2334 cppReader_error (pfile,
2335 message ("duplicate argument name `%x' in `#define'", name));
2336 goto nope;
2342 ++bp; /* skip paren */
2343 SKIP_WHITE_SPACE (bp);
2344 /* now everything from bp before limit is the definition. */
2345 defn = collect_expansion (pfile, bp, limit, argno, arg_ptrs);
2346 defn->rest_args = rest_args;
2348 /* Now set defn->args.argnames to the result of concatenating
2349 the argument names in reverse order
2350 with comma-space between them. */
2351 defn->args.argnames = (char *) dmalloc (size_fromInt (arglengths + 1));
2354 struct arglist *temp;
2355 int i = 0;
2356 for (temp = arg_ptrs; temp != NULL; temp = temp->next)
2358 memcpy (&defn->args.argnames[i], temp->name, temp->length);
2359 i += temp->length;
2360 if (temp->next != 0)
2362 defn->args.argnames[i++] = ',';
2363 defn->args.argnames[i++] = ' ';
2367 defn->args.argnames[i] = '\0';
2370 sfree (arg_ptrs);
2371 } else {
2372 /* Simple expansion or empty definition. */
2374 if (bp < limit)
2376 if (is_hor_space[(int) *bp]) {
2377 bp++;
2378 SKIP_WHITE_SPACE (bp);
2379 } else {
2380 switch (*bp) {
2381 case '!': case '\"': case '#': case '%': case '&': case '\'':
2382 case ')': case '*': case '+': case ',': case '-': case '.':
2383 case '/': case ':': case ';': case '<': case '=': case '>':
2384 case '?': case '[': case '\\': case ']': case '^': case '{':
2385 case '|': case '}': case '~':
2386 cppReader_warning (pfile,
2387 message ("Missing white space after #define %x",
2388 cstring_prefix (cstring_fromChars (symname),
2389 sym_length)));
2390 break;
2392 default:
2393 cppReader_pedwarn (pfile,
2394 message ("Missing white space after #define %x",
2395 cstring_prefix (cstring_fromChars (symname),
2396 sym_length)));
2397 break;
2401 /* now everything from bp before limit is the definition. */
2402 defn = collect_expansion (pfile, bp, limit, -1, NULL);
2403 defn->args.argnames = mstring_createEmpty ();
2406 defn->noExpand = noExpand;
2407 DPRINTF (("No expand: %d", noExpand));
2409 defn->line = line;
2411 /* not: llassert (cstring_isUndefined (defn->file)); */
2412 defn->file = file;
2414 /* OP is null if this is a predefinition */
2415 defn->predefined = predefinition;
2416 mdef.defn = defn;
2417 mdef.symnam = symname;
2418 mdef.symlen = sym_length;
2420 return mdef;
2422 nope:
2423 mdef.defn = NULL;
2424 mdef.symnam = NULL;
2425 return mdef;
2428 /*@null@*/ macroDef
2429 cpplib_createDefinition (cstring def,
2430 fileloc loc,
2431 bool predefinition,
2432 bool noExpand)
2434 char *buf = cstring_toCharsSafe (def);
2435 char *limit = buf + cstring_length (def);
2436 char *bp; /* temp ptr into input buffer */
2437 char *symname; /* remember where symbol name starts */
2438 size_t sym_length; /* and how long it is */
2439 int rest_args = 0; /* really int! */
2440 int line = fileloc_lineno (loc);
2441 cstring file = fileloc_filename (loc);
2442 DEFINITION *defn;
2443 int arglengths = 0; /* Accumulate lengths of arg names
2444 plus number of args. */
2445 macroDef mdef;
2447 bp = buf;
2449 DPRINTF (("Creating definition: %s", buf));
2451 while (is_hor_space[(int) *bp])
2453 bp++;
2456 symname = bp; /* remember where it starts */
2458 sym_length = cppReader_checkMacroNameLoc (loc, symname, cstring_makeLiteralTemp ("macro"));
2460 DPRINTF (("length: %d", sym_length));
2462 bp += sym_length;
2464 DPRINTF (("Here: %s", bp));
2466 /* Lossage will occur if identifiers or control keywords are broken
2467 across lines using backslash. This is not the right place to take
2468 care of that. */
2470 if (*bp == '(') {
2471 struct arglist *arg_ptrs = NULL;
2472 int argno = 0;
2474 bp++; /* skip '(' */
2475 SKIP_WHITE_SPACE (bp);
2477 /* Loop over macro argument names. */
2478 while (*bp != ')')
2480 struct arglist *temp = (struct arglist *) dmalloc (sizeof (*temp));
2481 temp->name = bp;
2482 temp->next = arg_ptrs;
2483 temp->argno = argno++;
2484 temp->rest_args = 0;
2486 arg_ptrs = temp;
2488 if (rest_args != 0)
2490 voptgenerror (FLG_PREPROC,
2491 message ("Another parameter follows %s",
2492 cstring_fromChars (rest_extension)),
2493 loc);
2496 if (!is_idstart[(int) *bp])
2498 voptgenerror (FLG_PREPROC,
2499 message ("Invalid character in macro parameter name: %c", *bp),
2500 loc);
2503 /* Find the end of the arg name. */
2504 while (is_idchar[(int) *bp])
2506 bp++;
2507 /* do we have a "special" rest-args extension here? */
2508 if (limit - bp > size_toInt (REST_EXTENSION_LENGTH)
2509 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
2511 rest_args = 1;
2512 temp->rest_args = 1;
2513 /*@innerbreak@*/ break;
2517 temp->length = size_fromInt (bp - temp->name);
2519 if (rest_args != 0)
2521 bp += REST_EXTENSION_LENGTH;
2524 arglengths += temp->length + 2;
2525 SKIP_WHITE_SPACE (bp);
2527 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
2528 voptgenerror (FLG_PREPROC,
2529 cstring_makeLiteral ("Parameter list for #define is not parseable"),
2530 loc);
2531 goto nope;
2534 if (*bp == ',') {
2535 bp++;
2536 SKIP_WHITE_SPACE (bp);
2538 if (bp >= limit) {
2539 voptgenerror (FLG_PREPROC,
2540 cstring_makeLiteral ("Unterminated parameter list in #define'"),
2541 loc);
2542 goto nope;
2545 struct arglist *otemp;
2547 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
2549 if (temp->length == otemp->length &&
2550 strncmp (temp->name, otemp->name, temp->length) == 0) {
2551 cstring name = cstring_copyLength (temp->name, temp->length);
2553 voptgenerror (FLG_PREPROC,
2554 message ("Duplicate argument name in #define: %s", name),
2555 loc);
2556 goto nope;
2562 ++bp; /* skip paren */
2563 SKIP_WHITE_SPACE (bp);
2564 /* now everything from bp before limit is the definition. */
2565 defn = collect_expansionLoc (loc, bp, limit, argno, arg_ptrs);
2566 defn->rest_args = rest_args;
2568 /* Now set defn->args.argnames to the result of concatenating
2569 the argument names in reverse order
2570 with comma-space between them. */
2571 defn->args.argnames = (char *) dmalloc (size_fromInt (arglengths + 1));
2574 struct arglist *temp;
2575 int i = 0;
2576 for (temp = arg_ptrs; temp != NULL; temp = temp->next) {
2577 memcpy (&defn->args.argnames[i], temp->name, temp->length);
2578 i += temp->length;
2579 if (temp->next != 0) {
2580 defn->args.argnames[i++] = ',';
2581 defn->args.argnames[i++] = ' ';
2585 defn->args.argnames[i] = '\0';
2588 sfree (arg_ptrs);
2589 } else {
2590 /* Simple expansion or empty definition. */
2592 if (bp < limit)
2594 if (is_hor_space[(int) *bp]) {
2595 bp++;
2596 SKIP_WHITE_SPACE (bp);
2597 } else {
2598 switch (*bp) {
2599 case '!': case '\"': case '#': case '%': case '&': case '\'':
2600 case ')': case '*': case '+': case ',': case '-': case '.':
2601 case '/': case ':': case ';': case '<': case '=': case '>':
2602 case '?': case '[': case '\\': case ']': case '^': case '{':
2603 case '|': case '}': case '~':
2604 voptgenerror (FLG_PREPROC,
2605 message ("Missing white space after #define %x",
2606 cstring_prefix (cstring_fromChars (symname),
2607 sym_length)),
2608 loc);
2609 break;
2611 default:
2612 voptgenerror (FLG_PREPROC,
2613 message ("Missing white space after #define %x",
2614 cstring_prefix (cstring_fromChars (symname),
2615 sym_length)),
2616 loc);
2617 break;
2622 /* now everything from bp before limit is the definition. */
2623 llassert (limit > bp);
2624 defn = collect_expansionLoc (loc, bp, limit, -1, NULL);
2625 defn->args.argnames = mstring_createEmpty ();
2628 defn->noExpand = noExpand;
2629 DPRINTF (("No expand: %d", noExpand));
2631 defn->line = line;
2633 /* not: llassert (cstring_isUndefined (defn->file)); */
2634 defn->file = file;
2636 /* OP is null if this is a predefinition */
2637 defn->predefined = predefinition;
2639 mdef.defn = defn;
2640 mdef.symnam = symname;
2641 mdef.symlen = sym_length;
2643 return mdef;
2645 nope:
2646 mdef.defn = NULL;
2647 mdef.symnam = NULL;
2648 return mdef;
2651 /* Check a purported macro name SYMNAME, and yield its length.
2652 USAGE is the kind of name this is intended for. */
2654 size_t cppReader_checkMacroName (cppReader *pfile, char *symname, cstring usage)
2656 char *p;
2657 size_t sym_length;
2659 for (p = symname; is_idchar[(int) *p]; p++)
2664 sym_length = size_fromInt (p - symname);
2666 if (sym_length == 0
2667 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '\"')))
2669 cppReader_error (pfile, message ("invalid %s name", usage));
2671 else if (!is_idstart[(int) *symname])
2673 char *msg = (char *) dmalloc (sym_length + 1);
2674 memcpy (msg, symname, sym_length);
2675 msg[sym_length] = '\0';
2676 cppReader_error (pfile, message ("invalid %s name `%s'", usage,
2677 cstring_fromChars (msg)));
2678 sfree (msg);
2680 else
2682 if ((strncmp (symname, "defined", 7) == 0) && sym_length == 7)
2684 cppReader_error (pfile, message ("invalid %s name `defined'", usage));
2688 return sym_length;
2692 ** evans 2001-12-31
2693 ** Gasp...cut-and-pasted from above to deal with pfile (should replace throughout with this...)
2696 size_t cppReader_checkMacroNameLoc (fileloc loc, char *symname, cstring usage)
2698 char *p;
2699 size_t sym_length;
2701 for (p = symname; is_idchar[(int) *p]; p++)
2706 sym_length = size_fromInt (p - symname);
2708 if (sym_length == 0
2709 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '\"')))
2711 voptgenerror (FLG_PREPROC, message ("Invalid %s name: %s", usage,
2712 cstring_fromChars (symname)), loc);
2714 else if (!is_idstart[(int) *symname])
2716 char *msg = (char *) dmalloc (sym_length + 1);
2717 memcpy (msg, symname, sym_length);
2718 msg[sym_length] = '\0';
2719 voptgenerror (FLG_PREPROC, message ("Invalid %s name: %s", usage,
2720 cstring_fromChars (msg)),
2721 loc);
2722 sfree (msg);
2724 else
2726 if ((strncmp (symname, "defined", 7) == 0) && sym_length == 7)
2728 voptgenerror (FLG_PREPROC, message ("Invalid %s name: defined", usage), loc);
2732 return sym_length;
2735 /* Return zero if two DEFINITIONs are isomorphic. */
2737 static bool
2738 compare_defs (DEFINITION *d1, DEFINITION *d2)
2740 register struct reflist *a1, *a2;
2741 register char *p1 = d1->expansion;
2742 register char *p2 = d2->expansion;
2743 bool first = TRUE;
2745 if (d1->nargs != d2->nargs)
2747 return TRUE;
2750 llassert (d1->args.argnames != NULL);
2751 llassert (d2->args.argnames != NULL);
2753 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames) != 0)
2755 return TRUE;
2758 for (a1 = d1->pattern, a2 = d2->pattern;
2759 (a1 != NULL) && (a2 != NULL);
2760 a1 = a1->next, a2 = a2->next) {
2761 if (!((a1->nchars == a2->nchars
2762 && (strncmp (p1, p2, size_fromInt (a1->nchars)) == 0))
2763 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
2764 || a1->argno != a2->argno
2765 || a1->stringify != a2->stringify
2766 || a1->raw_before != a2->raw_before
2767 || a1->raw_after != a2->raw_after)
2768 return TRUE;
2769 first = 0;
2770 p1 += a1->nchars;
2771 p2 += a2->nchars;
2773 if (a1 != a2)
2774 return TRUE;
2776 if (comp_def_part (first, p1, size_toInt (d1->length - (p1 - d1->expansion)),
2777 p2, size_toInt (d2->length - (p2 - d2->expansion)), 1))
2778 return TRUE;
2780 return FALSE;
2784 ** Return TRUE if two parts of two macro definitions are effectively different.
2785 ** One of the parts starts at BEG1 and has LEN1 chars;
2786 ** the other has LEN2 chars at BEG2.
2787 ** Any sequence of whitespace matches any other sequence of whitespace.
2788 ** FIRST means these parts are the first of a macro definition;
2789 ** so ignore leading whitespace entirely.
2790 ** LAST means these parts are the last of a macro definition;
2791 ** so ignore trailing whitespace entirely.
2794 static bool
2795 comp_def_part (bool first, char *beg1, int len1, char *beg2, int len2, bool last)
2797 char *end1 = beg1 + len1;
2798 char *end2 = beg2 + len2;
2800 if (first) {
2801 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2802 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2804 if (last) {
2805 while (beg1 != end1 && is_space[(int) end1[-1]]) { end1--; }
2806 while (beg2 != end2 && is_space[(int) end2[-1]]) { end2--; }
2808 while (beg1 != end1 && beg2 != end2) {
2809 if (is_space[(int) *beg1] && is_space[(int) *beg2]) {
2810 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2811 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2812 } else if (*beg1 == *beg2) {
2813 beg1++; beg2++;
2814 } else break;
2816 return (beg1 != end1) || (beg2 != end2);
2820 ** Process a #define command.
2821 ** BUF points to the contents of the #define command, as a contiguous string.
2822 ** LIMIT points to the first character past the end of the definition.
2823 ** KEYWORD is the keyword-table entry for #define,
2824 ** or NULL for a "predefined" macro.
2827 static int
2828 do_defineAux (cppReader *pfile, struct directive *keyword,
2829 /*@exposed@*/ char *buf, char *limit, bool noExpand)
2831 int hashcode;
2832 macroDef mdef;
2833 hashNode hp;
2835 mdef = create_definition (buf, limit, pfile, keyword == NULL, noExpand);
2837 if (mdef.defn == 0)
2838 goto nope;
2840 hashcode = cpphash_hashCode (mdef.symnam, mdef.symlen, CPP_HASHSIZE);
2842 if ((hp = cpphash_lookup (mdef.symnam, size_toInt (mdef.symlen), hashcode)) != NULL)
2844 bool ok = FALSE;
2846 /* Redefining a precompiled key is ok. */
2847 if (hp->type == T_PCSTRING)
2848 ok = TRUE;
2849 /* Redefining a macro is ok if the definitions are the same. */
2850 else if (hp->type == T_MACRO)
2851 ok = !compare_defs (mdef.defn, hp->value.defn);
2852 /* Redefining a constant is ok with -D. */
2853 else if (hp->type == T_CONST)
2854 ok = !CPPOPTIONS (pfile)->done_initializing;
2855 else {
2856 ok = FALSE; /* Redefining anything else is bad. */
2859 /* Print the warning if it's not ok. */
2860 if (!ok)
2863 ** If we are passing through #define and #undef directives, do
2864 ** that for this re-definition now.
2867 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2869 /* llassert (keyword != NULL); */
2870 pass_thru_directive (buf, limit, pfile, keyword);
2873 cpp_setLocation (pfile);
2875 if (hp->type == T_MACRO)
2877 if (hp->value.defn->noExpand)
2879 ; /* error will be reported checking macros */
2881 else
2883 genppllerrorhint
2884 (FLG_MACROREDEF,
2885 message ("Macro %q already defined",
2886 cstring_copyLength (mdef.symnam, mdef.symlen)),
2887 message ("%q: Previous definition of %q",
2888 fileloc_unparseRaw (hp->value.defn->file,
2889 (int) hp->value.defn->line),
2890 cstring_copyLength (mdef.symnam, mdef.symlen)));
2893 else
2895 genppllerror (FLG_MACROREDEF,
2896 message ("Macro %q already defined",
2897 cstring_copyLength (mdef.symnam,
2898 mdef.symlen)));
2902 /* Replace the old definition. */
2903 hp->type = T_MACRO;
2904 hp->value.defn = mdef.defn;
2906 else
2909 ** If we are passing through #define and #undef directives, do
2910 ** that for this new definition now.
2913 hashNode hn;
2915 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2917 pass_thru_directive (buf, limit, pfile, keyword);
2920 DPRINTF (("Define macro: %s / %d",
2921 mdef.symnam, mdef.defn->noExpand));
2923 hn = cpphash_installMacro (mdef.symnam, mdef.symlen, mdef.defn, hashcode);
2924 /*@-branchstate@*/
2925 } /*@=branchstate@*/
2927 return 0;
2929 nope:
2930 return 1;
2933 static int
2934 do_define (cppReader *pfile, struct directive *keyword,
2935 /*@exposed@*/ char *buf, char *limit)
2937 DPRINTF (("Regular do define"));
2938 return do_defineAux (pfile, keyword, buf, limit, FALSE);
2942 ** This structure represents one parsed argument in a macro call.
2943 ** `raw' points to the argument text as written (`raw_length' is its length).
2944 ** `expanded' points to the argument's macro-expansion
2945 ** (its length is `expand_length').
2946 ** `stringified_length' is the length the argument would have
2947 ** if stringified.
2948 ** `use_count' is the number of times this macro arg is substituted
2949 ** into the macro. If the actual use count exceeds 10,
2950 ** the value stored is 10.
2953 /* raw and expanded are relative to ARG_BASE */
2954 /*@notfunction@*/
2955 #define ARG_BASE ((pfile)->token_buffer)
2957 struct argdata {
2958 /* Strings relative to pfile->token_buffer */
2959 long raw;
2960 size_t expanded;
2961 size_t stringified;
2962 int raw_length;
2963 int expand_length;
2964 int stringified_length;
2965 bool newlines;
2966 int use_count;
2970 ** Allocate a new cppBuffer for PFILE, and push it on the input buffer stack.
2971 ** If BUFFER != NULL, then use the LENGTH characters in BUFFER
2972 ** as the new input buffer.
2973 ** Return the new buffer, or NULL on failure.
2976 /*@null@*/ /*@exposed@*/ cppBuffer *
2977 cppReader_pushBuffer (cppReader *pfile, char *buffer, size_t length)
2979 cppBuffer *buf = cppReader_getBufferSafe (pfile);
2981 if (buf == pfile->buffer_stack)
2983 cppReader_fatalError
2984 (pfile,
2985 message ("%s: macro or `#include' recursion too deep",
2986 (buf->fname != NULL)
2987 ? buf->fname
2988 : cstring_makeLiteral ("<no name>")));
2989 sfreeEventually (buffer);
2990 return NULL;
2993 llassert (buf != NULL);
2995 buf--;
2996 memset ((char *) buf, 0, sizeof (*buf));
2997 DPRINTF (("Pushing buffer: %s", cstring_copyLength (buffer, length)));
2998 CPPBUFFER (pfile) = buf;
3000 buf->if_stack = pfile->if_stack;
3001 buf->cleanup = cppReader_nullCleanup;
3002 buf->underflow = cppReader_nullUnderflow;
3003 buf->buf = buffer;
3004 buf->cur = buf->buf;
3006 if (buffer != NULL)
3008 buf->alimit = buf->rlimit = buffer + length;
3010 else
3012 buf->alimit = buf->rlimit = NULL;
3015 return buf;
3018 cppBuffer *
3019 cppReader_popBuffer (cppReader *pfile)
3021 cppBuffer *buf = CPPBUFFER (pfile);
3023 llassert (buf != NULL);
3025 (void) (*buf->cleanup) (buf, pfile);
3026 return ++CPPBUFFER (pfile);
3030 ** Scan until CPPBUFFER (PFILE) is exhausted into PFILE->token_buffer.
3031 ** Pop the buffer when done.
3034 void
3035 cppReader_scanBuffer (cppReader *pfile)
3037 cppBuffer *buffer = CPPBUFFER (pfile);
3038 for (;;)
3040 enum cpp_token token;
3042 token = cpplib_getToken (pfile);
3044 if (token == CPP_EOF) /* Should not happen ... */
3046 break;
3049 if (token == CPP_POP && CPPBUFFER (pfile) == buffer)
3051 (void) cppReader_popBuffer (pfile);
3052 break;
3058 * Rescan a string (which may have escape marks) into pfile's buffer.
3059 * Place the result in pfile->token_buffer.
3061 * The input is copied before it is scanned, so it is safe to pass
3062 * it something from the token_buffer that will get overwritten
3063 * (because it follows cpplib_getWritten). This is used by do_include.
3066 static void
3067 cpp_expand_to_buffer (cppReader *pfile, char *buf, size_t length)
3069 register cppBuffer *ip;
3070 char *limit = buf + length;
3071 char *buf1, *p1, *p2;
3073 DPRINTF (("Expand to buffer: %s", cstring_copyLength (buf, length)));
3075 /* evans - 2001-08-26
3076 ** length is unsigned - this doesn't make sense
3077 if (length < 0)
3078 abort ();
3082 /* Set up the input on the input stack. */
3084 buf1 = (char *) dmalloc (length + 1);
3086 p1 = buf;
3087 p2 = buf1;
3089 while (p1 != limit)
3091 *p2++ = *p1++;
3094 buf1[length] = '\0';
3096 ip = cppReader_pushBuffer (pfile, buf1, length);
3098 if (ip == NULL)
3099 return;
3101 ip->has_escapes = TRUE;
3103 /* Scan the input, create the output. */
3104 cppReader_scanBuffer (pfile);
3106 cppReader_nullTerminate (pfile);
3109 static void
3110 adjust_position (char *buf, char *limit, int *linep, int *colp)
3112 while (buf < limit)
3114 char ch = *buf++;
3115 if (ch == '\n')
3116 (*linep)++, (*colp) = 1;
3117 else
3118 (*colp)++;
3122 /* Move line_base forward, updating lineno and colno. */
3124 static void
3125 update_position (cppBuffer *pbuf)
3127 char *old_pos;
3128 char *new_pos = pbuf->cur;
3129 register struct parse_marker *mark;
3131 llassert (pbuf->buf != NULL);
3132 old_pos = pbuf->buf + pbuf->line_base;
3134 for (mark = pbuf->marks; mark != NULL; mark = mark->next)
3136 if (pbuf->buf + mark->position < new_pos)
3137 new_pos = pbuf->buf + mark->position;
3139 pbuf->line_base += new_pos - old_pos;
3141 llassert (old_pos != NULL);
3142 llassert (new_pos != NULL);
3144 adjust_position (old_pos, new_pos, &pbuf->lineno, &pbuf->colno);
3147 void
3148 cppBuffer_getLineAndColumn (/*@null@*/ cppBuffer *pbuf, /*@out@*/ int *linep,
3149 /*@null@*/ /*@out@*/ int *colp)
3151 int dummy;
3153 if (colp == NULL)
3155 colp = &dummy;
3156 /*@-branchstate@*/
3157 } /*@=branchstate@*/
3159 if (pbuf != NULL)
3161 *linep = pbuf->lineno;
3162 *colp = pbuf->colno;
3164 llassert (pbuf->buf != NULL);
3165 llassert (pbuf->cur != NULL);
3167 adjust_position (pbuf->buf + pbuf->line_base, pbuf->cur, linep, colp);
3169 else
3171 *linep = 0;
3172 *colp = 0;
3176 /* Return the cppBuffer that corresponds to a file (not a macro). */
3178 /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_fileBuffer (cppReader *pfile)
3180 cppBuffer *ip = cppReader_getBuffer (pfile);
3182 for ( ;
3183 ip != NULL && ip != cppReader_nullBuffer (pfile);
3184 ip = cppBuffer_prevBuffer (ip))
3186 if (ip->fname != NULL)
3188 return ip;
3192 return NULL;
3195 static long
3196 count_newlines (char *buf, char *limit)
3198 register long count = 0;
3200 while (buf < limit)
3202 char ch = *buf++;
3203 if (ch == '\n')
3204 count++;
3206 return count;
3210 * write out a #line command, for instance, after an #include file.
3211 * If CONDITIONAL is nonzero, we can omit the #line if it would
3212 * appear to be a no-op, and we can output a few newlines instead
3213 * if we want to increase the line number by a small amount.
3214 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
3217 static void
3218 output_line_command (cppReader *pfile, bool conditional,
3219 enum file_change_code file_change)
3221 int line, col;
3222 cppBuffer *ip = CPPBUFFER (pfile);
3223 cppBuffer *buf;
3225 llassert (ip != NULL);
3227 if (ip->fname == NULL)
3228 return;
3230 update_position (ip);
3232 if (CPPOPTIONS (pfile)->no_line_commands
3233 || CPPOPTIONS (pfile)->no_output)
3234 return;
3236 buf = CPPBUFFER (pfile);
3238 llassert (buf != NULL);
3240 line = buf->lineno;
3241 col = buf->colno;
3243 llassert (ip->cur != NULL);
3245 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
3247 if (CPPOPTIONS (pfile)->no_line_commands)
3248 return;
3250 if (conditional) {
3251 if (line == pfile->lineno)
3252 return;
3254 /* If the inherited line number is a little too small,
3255 output some newlines instead of a #line command. */
3257 if (line > pfile->lineno && line < pfile->lineno + 8)
3259 cpplib_reserve (pfile, 20);
3260 while (line > pfile->lineno)
3262 cppReader_putCharQ (pfile, '\n');
3263 pfile->lineno++;
3266 return;
3270 cpplib_reserve (pfile, 4 * cstring_length (ip->nominal_fname) + 50);
3273 #ifdef OUTPUT_LINE_COMMANDS
3274 static char sharp_line[] = "#line ";
3275 #else
3276 static char sharp_line[] = "# ";
3277 #endif
3278 cppReader_putStrN (pfile, sharp_line, sizeof(sharp_line)-1);
3281 sprintf (cpplib_getPWritten (pfile), "%d ", line);
3282 cppReader_adjustWritten (pfile, strlen (cpplib_getPWritten (pfile)));
3284 quote_string (pfile, cstring_toCharsSafe (ip->nominal_fname));
3286 if (file_change != same_file) {
3287 cppReader_putCharQ (pfile, ' ');
3288 cppReader_putCharQ (pfile, file_change == enter_file ? '1' : '2');
3290 /* Tell cc1 if following text comes from a system header file. */
3291 if (ip->system_header_p != '\0') {
3292 cppReader_putCharQ (pfile, ' ');
3293 cppReader_putCharQ (pfile, '3');
3295 #ifndef NO_IMPLICIT_EXTERN_C
3296 /* Tell cc1plus if following text should be treated as C. */
3297 if (ip->system_header_p == (char) 2 && CPPOPTIONS (pfile)->cplusplus) {
3298 cppReader_putCharQ (pfile, ' ');
3299 cppReader_putCharQ (pfile, '4');
3301 #endif
3302 cppReader_putCharQ (pfile, '\n');
3303 pfile->lineno = line;
3308 * Parse a macro argument and append the info on PFILE's token_buffer.
3309 * REST_ARGS means to absorb the rest of the args.
3310 * Return nonzero to indicate a syntax error.
3313 static enum cpp_token
3314 macarg (cppReader *pfile, int rest_args)
3316 int paren = 0;
3317 enum cpp_token token;
3318 char save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
3319 bool oldexpand = pfile->no_macro_expand;
3320 CPPOPTIONS (pfile)->put_out_comments = 1;
3322 /* Try to parse as much of the argument as exists at this
3323 input stack level. */
3325 pfile->no_macro_expand = TRUE;
3327 for (;;)
3329 token = cpplib_getToken (pfile);
3331 switch (token)
3333 case CPP_EOF:
3334 goto done;
3335 case CPP_POP:
3336 /* If we've hit end of file, it's an error (reported by caller).
3337 Ditto if it's the end of cpp_expand_to_buffer text.
3338 If we've hit end of macro, just continue. */
3339 if (!cppBuffer_isMacro (CPPBUFFER (pfile)))
3340 goto done;
3341 /*@switchbreak@*/ break;
3342 case CPP_LPAREN:
3343 paren++;
3344 /*@switchbreak@*/ break;
3345 case CPP_RPAREN:
3346 if (--paren < 0)
3347 goto found;
3348 /*@switchbreak@*/ break;
3349 case CPP_COMMA:
3350 /* if we've returned to lowest level and
3351 we aren't absorbing all args */
3352 if (paren == 0 && rest_args == 0)
3353 goto found;
3354 /*@switchbreak@*/ break;
3355 found:
3356 /* Remove ',' or ')' from argument buffer. */
3357 cppReader_adjustWritten (pfile, -1);
3358 goto done;
3359 default:
3364 done:
3365 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
3366 pfile->no_macro_expand = oldexpand;
3368 return token;
3372 /* Turn newlines to spaces in the string of length LENGTH at START,
3373 except inside of string constants.
3374 The string is copied into itself with its beginning staying fixed. */
3376 static int
3377 change_newlines (char *start, int length)
3379 register char *ibp;
3380 register char *obp;
3381 register char *limit;
3382 char c;
3384 ibp = start;
3385 limit = start + length;
3386 obp = start;
3388 while (ibp < limit) {
3389 *obp++ = c = *ibp++;
3390 switch (c) {
3392 case '\'':
3393 case '\"':
3394 /* Notice and skip strings, so that we don't delete newlines in them. */
3396 char quotec = c;
3397 while (ibp < limit) {
3398 *obp++ = c = *ibp++;
3399 if (c == quotec)
3400 /*@innerbreak@*/ break;
3401 if (c == '\n' && quotec == '\'')
3402 /*@innerbreak@*/ break;
3405 /*@switchbreak@*/ break;
3409 return obp - start;
3412 static /*@observer@*/ struct tm *
3413 timestamp (/*@returned@*/ cppReader *pfile)
3415 if (pfile->timebuf == NULL)
3417 time_t t = time ((time_t *) 0);
3418 pfile->timebuf = localtime (&t);
3421 llassert (pfile->timebuf != NULL);
3423 return pfile->timebuf;
3426 static ob_mstring monthnames[] = {
3427 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3428 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3432 * expand things like __FILE__. Place the expansion into the output
3433 * buffer *without* rescanning.
3436 static void
3437 special_symbol (hashNode hp, cppReader *pfile)
3439 cstring buf = cstring_undefined;
3440 size_t len;
3441 int true_indepth;
3442 cppBuffer *ip;
3443 struct tm *timebuf;
3445 int paren = 0; /* For special `defined' keyword */
3447 for (ip = cppReader_getBuffer (pfile); ip != NULL; ip = cppBuffer_prevBuffer (ip))
3449 if (ip == cppReader_nullBuffer (pfile))
3451 cppReader_errorLit (pfile,
3452 cstring_makeLiteralTemp ("cccp error: not in any file?!"));
3453 return; /* the show must go on */
3456 if (ip != NULL && ip->fname != NULL)
3458 break;
3462 switch (hp->type)
3464 case T_FILE:
3465 case T_BASE_FILE:
3467 char *string;
3468 if (hp->type == T_BASE_FILE)
3470 while (cppBuffer_prevBuffer (ip) != cppReader_nullBuffer (pfile))
3472 ip = cppBuffer_prevBuffer (ip);
3476 llassert (ip != NULL);
3477 string = cstring_toCharsSafe (ip->nominal_fname);
3479 if (string == NULL)
3481 string = "";
3484 cpplib_reserve (pfile, 3 + 4 * strlen (string));
3485 quote_string (pfile, string);
3486 return;
3488 case T_FUNC: /* added in ISO C99 */
3490 /* We don't know the actual name of the function, but it doesn't matter */
3491 char *string = "** function-name **";
3492 cpplib_reserve (pfile, 3 + 4 * strlen (string));
3493 quote_string (pfile, string);
3494 return;
3497 case T_INCLUDE_LEVEL:
3498 true_indepth = 0;
3499 ip = cppReader_getBuffer (pfile);
3501 for (; ip != cppReader_nullBuffer (pfile) && ip != NULL;
3502 ip = cppBuffer_prevBuffer (ip))
3504 if (ip != NULL && ip->fname != NULL)
3506 true_indepth++;
3510 buf = message ("%d", true_indepth - 1);
3511 break;
3513 case T_VERSION:
3514 buf = cstring_makeLiteral ("\"--- cpp version---\"");
3515 break;
3517 #ifndef NO_BUILTIN_SIZE_TYPE
3518 case T_SIZE_TYPE:
3519 buf = cstring_makeLiteral (SIZE_TYPE);
3520 break;
3521 #endif
3523 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3524 case T_PTRDIFF_TYPE:
3525 buf = cstring_makeLiteral (PTRDIFF_TYPE);
3526 break;
3527 #endif
3529 case T_WCHAR_TYPE:
3530 buf = cstring_makeLiteral (cppReader_wcharType (pfile));
3531 break;
3533 case T_USER_LABEL_PREFIX_TYPE:
3534 buf = cstring_makeLiteral (USER_LABEL_PREFIX);
3535 break;
3537 case T_REGISTER_PREFIX_TYPE:
3538 buf = cstring_makeLiteral (REGISTER_PREFIX);
3539 break;
3541 case T_CONST:
3542 buf = message ("%d", hp->value.ival);
3543 break;
3545 case T_SPECLINE:
3547 if (ip != NULL)
3549 int line = ip->lineno;
3550 int col = ip->colno;
3552 llassert (ip->cur != NULL);
3553 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
3555 buf = message ("%d", (int) line);
3557 else
3559 BADBRANCH;
3562 break;
3564 case T_DATE:
3565 case T_TIME:
3567 char *sbuf = (char *) dmalloc (20);
3568 timebuf = timestamp (pfile);
3569 if (hp->type == T_DATE)
3571 sprintf (sbuf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
3572 timebuf->tm_mday, timebuf->tm_year + 1900);
3574 else
3576 sprintf (sbuf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
3577 timebuf->tm_sec);
3580 buf = cstring_fromCharsNew (sbuf);
3581 sfree (sbuf);
3582 break;
3585 case T_SPEC_DEFINED:
3586 buf = cstring_makeLiteral (" 0 "); /* Assume symbol is not defined */
3587 ip = cppReader_getBuffer (pfile);
3588 llassert (ip != NULL);
3589 llassert (ip->cur != NULL);
3590 SKIP_WHITE_SPACE (ip->cur);
3592 if (*ip->cur == '(')
3594 paren++;
3595 ip->cur++; /* Skip over the paren */
3596 SKIP_WHITE_SPACE (ip->cur);
3599 if (!is_idstart[(int) *ip->cur])
3600 goto oops;
3601 if (ip->cur[0] == 'L' && (ip->cur[1] == '\'' || ip->cur[1] == '\"'))
3602 goto oops;
3604 if ((hp = cpphash_lookup (ip->cur, -1, -1)) != 0)
3606 cstring_free (buf);
3607 buf = cstring_makeLiteral (" 1 ");
3610 while (is_idchar[(int) *ip->cur])
3612 ++ip->cur;
3615 SKIP_WHITE_SPACE (ip->cur);
3617 if (paren != 0)
3619 if (*ip->cur != ')')
3620 goto oops;
3621 ++ip->cur;
3623 break;
3625 oops:
3627 cppReader_errorLit (pfile,
3628 cstring_makeLiteralTemp ("`defined' without an identifier"));
3629 break;
3631 default:
3632 cpp_setLocation (pfile);
3633 llfatalerror (message ("Pre-processing error: invalid special hash type"));
3636 len = cstring_length (buf);
3638 cpplib_reserve (pfile, len + 1);
3639 cppReader_putStrN (pfile, cstring_toCharsSafe (buf), len);
3640 cppReader_nullTerminateQ (pfile);
3642 cstring_free (buf);
3643 return;
3646 /* Write out a #define command for the special named MACRO_NAME
3647 to PFILE's token_buffer. */
3649 static void
3650 dump_special_to_buffer (cppReader *pfile, char *macro_name)
3652 static char define_directive[] = "#define ";
3653 size_t macro_name_length = strlen (macro_name);
3654 output_line_command (pfile, 0, same_file);
3655 cpplib_reserve (pfile, sizeof(define_directive) + macro_name_length);
3656 cppReader_putStrN (pfile, define_directive, sizeof(define_directive)-1);
3657 cppReader_putStrN (pfile, macro_name, macro_name_length);
3658 cppReader_putCharQ (pfile, ' ');
3659 cpp_expand_to_buffer (pfile, macro_name, macro_name_length);
3660 cppReader_putChar (pfile, '\n');
3663 /* Initialize the built-in macros. */
3665 static void
3666 cpplib_installBuiltin (/*@observer@*/ char *name, ctype ctyp,
3667 int len, enum node_type type,
3668 int ivalue, /*@null@*/ /*@only@*/ char *value,
3669 int hash)
3671 cstring sname = cstring_fromCharsNew (name);
3673 llassert (usymtab_inGlobalScope ());
3676 ** Be careful here: this is done before the ctype table has
3677 ** been initialized.
3680 if (!usymtab_exists (sname))
3682 uentry ue = uentry_makeConstant (sname, ctyp, fileloc_createBuiltin ());
3684 if (ctype_equal (ctyp, ctype_string))
3686 qualList ql = qualList_new ();
3687 ql = qualList_add (ql, qual_createObserver ());
3688 uentry_reflectQualifiers (ue, ql);
3689 qualList_free (ql);
3692 usymtab_addGlobalEntry (ue);
3694 else
3699 (void) cpphash_install (name, len, type, ivalue, value, hash);
3700 cstring_free (sname);
3703 static void
3704 cpplib_installBuiltinType (/*@observer@*/ char *name, ctype ctyp,
3705 int len, enum node_type type,
3706 int ivalue,
3707 /*@only@*/ /*@null@*/ char *value, int hash)
3709 cstring sname = cstring_fromChars (name);
3710 /* evs 2000 07 10 - removed a memory leak, detected by splint */
3712 llassert (usymtab_inGlobalScope ());
3714 if (!usymtab_existsTypeEither (sname))
3716 uentry ue = uentry_makeDatatype (sname, ctyp,
3717 NO, qual_createConcrete (),
3718 fileloc_createBuiltin ());
3719 llassert (!usymtab_existsEither (sname));
3720 usymtab_addGlobalEntry (ue);
3723 (void) cpphash_install (name, len, type, ivalue, value, hash);
3726 static void
3727 initialize_builtins (cppReader *pfile)
3729 cpplib_installBuiltin ("__LINE__", ctype_int, -1, T_SPECLINE, 0, NULL, -1);
3730 cpplib_installBuiltin ("__DATE__", ctype_string, -1, T_DATE, 0, NULL, -1);
3731 cpplib_installBuiltin ("__FILE__", ctype_string, -1, T_FILE, 0, NULL, -1);
3732 cpplib_installBuiltin ("__BASE_FILE__", ctype_string, -1, T_BASE_FILE, 0, NULL, -1);
3733 cpplib_installBuiltin ("__func__", ctype_string, -1, T_FUNC, 0, NULL, -1);
3734 cpplib_installBuiltin ("__INCLUDE_LEVEL__", ctype_int, -1, T_INCLUDE_LEVEL, 0, NULL, -1);
3735 cpplib_installBuiltin ("__VERSION__", ctype_string, -1, T_VERSION, 0, NULL, -1);
3736 #ifndef NO_BUILTIN_SIZE_TYPE
3737 cpplib_installBuiltinType ("__SIZE_TYPE__", ctype_anyintegral, -1, T_SIZE_TYPE, 0, NULL, -1);
3738 #endif
3739 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3740 cpplib_installBuiltinType ("__PTRDIFF_TYPE__", ctype_anyintegral, -1, T_PTRDIFF_TYPE, 0, NULL, -1);
3741 #endif
3742 cpplib_installBuiltinType ("__WCHAR_TYPE__", ctype_anyintegral, -1, T_WCHAR_TYPE, 0, NULL, -1);
3743 cpplib_installBuiltin ("__USER_LABEL_PREFIX__", ctype_string, -1, T_USER_LABEL_PREFIX_TYPE, 0, NULL, -1);
3744 cpplib_installBuiltin ("__REGISTER_PREFIX__", ctype_string, -1, T_REGISTER_PREFIX_TYPE, 0, NULL, -1);
3745 cpplib_installBuiltin ("__TIME__", ctype_string, -1, T_TIME, 0, NULL, -1);
3747 if (!cppReader_isTraditional (pfile))
3749 cpplib_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3752 # ifdef WIN32
3753 cpplib_installBuiltin ("_WIN32", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3754 # endif
3757 ** This is supplied using a -D by the compiler driver
3758 ** so that it is present only when truly compiling with GNU C.
3761 /* cpplib_install ("__GNUC__", -1, T_CONST, 2, 0, -1); */
3763 cpplib_installBuiltin ("S_SPLINT_S", ctype_int, -1, T_CONST, 2, NULL, -1);
3764 cpplib_installBuiltin ("__LCLINT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3766 /*drl 1/9/2001/ try to define the right symbol for the architecture
3767 We use autoconf to determine the host cpu
3769 # ifndef S_SPLINT_S
3770 cpplib_installBuiltin ("__" HOST_CPU, ctype_int, -1, T_CONST, 2, NULL, -1);
3771 # endif
3773 /*drl 1/2/2002 set some flags based on uname
3774 I'd like to be able to do this with autoconf macro instead...
3777 /*Thanks to Nelson Beebe for suggesting possible values for these */
3779 if (! strcmp (UNAME, "Linux"))
3781 #ifdef __ppc
3782 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3783 #endif
3786 else if(! strcmp (UNAME, "Darwin"))
3788 cpplib_installBuiltin ("__ppc__", ctype_int, -1, T_CONST, 2, NULL, -1);
3789 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3791 else if(! strcmp (UNAME, "HP-UX"))
3793 cpplib_installBuiltin ("PWB", ctype_int, -1, T_CONST, 2, NULL, -1);
3794 cpplib_installBuiltin ("_HIUX_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3795 cpplib_installBuiltin ("_HPUX_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3796 cpplib_installBuiltin ("_PA_RISC1_1", ctype_int, -1, T_CONST, 2, NULL, -1);
3797 cpplib_installBuiltin ("__PWB", ctype_int, -1, T_CONST, 2, NULL, -1);
3798 cpplib_installBuiltin ("__PWB__", ctype_int, -1, T_CONST, 2, NULL, -1);
3799 cpplib_installBuiltin ("__STDC_EXT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3800 cpplib_installBuiltin ("__hp9000s700", ctype_int, -1, T_CONST, 2, NULL, -1);
3801 cpplib_installBuiltin ("__hp9000s800", ctype_int, -1, T_CONST, 2, NULL, -1);
3802 cpplib_installBuiltin ("__hp9000s800__", ctype_int, -1, T_CONST, 2, NULL, -1);
3803 cpplib_installBuiltin ("__hp9k8", ctype_int, -1, T_CONST, 2, NULL, -1);
3804 cpplib_installBuiltin ("__hp9k8__", ctype_int, -1, T_CONST, 2, NULL, -1);
3805 cpplib_installBuiltin ("__hppa", ctype_int, -1, T_CONST, 2, NULL, -1);
3806 cpplib_installBuiltin ("__hppa__", ctype_int, -1, T_CONST, 2, NULL, -1);
3807 cpplib_installBuiltin ("__hpux", ctype_int, -1, T_CONST, 2, NULL, -1);
3808 cpplib_installBuiltin ("__hpux__", ctype_int, -1, T_CONST, 2, NULL, -1);
3809 cpplib_installBuiltin ("__unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3810 cpplib_installBuiltin ("__unix__", ctype_int, -1, T_CONST, 2, NULL, -1);
3811 cpplib_installBuiltin ("hp9000s800", ctype_int, -1, T_CONST, 2, NULL, -1);
3812 cpplib_installBuiltin ("hp9k8", ctype_int, -1, T_CONST, 2, NULL, -1);
3813 cpplib_installBuiltin ("hppa", ctype_int, -1, T_CONST, 2, NULL, -1);
3814 cpplib_installBuiltin ("hpux", ctype_int, -1, T_CONST, 2, NULL, -1);
3815 cpplib_installBuiltin ("unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3817 else if(! strcmp (UNAME, "IRIX64"))
3819 cpplib_installBuiltin ("LANGUAGE_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3820 cpplib_installBuiltin ("MIPSEB", ctype_int, -1, T_CONST, 2, NULL, -1);
3821 cpplib_installBuiltin ("_ABIN32", ctype_int, -1, T_CONST, 2, NULL, -1);
3822 cpplib_installBuiltin ("_COMPILER_VERSION", ctype_int, -1, T_CONST, 730, NULL, -1);
3823 cpplib_installBuiltin ("_LANGUAGE_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3824 cpplib_installBuiltin ("_LONGLONG", ctype_int, -1, T_CONST, 2, NULL, -1);
3825 cpplib_installBuiltin ("_MIPSEB", ctype_int, -1, T_CONST, 2, NULL, -1);
3826 cpplib_installBuiltin ("_MIPS_FPSET", ctype_int, -1, T_CONST, 32, NULL, -1);
3827 cpplib_installBuiltin ("_MIPS_ISA", ctype_int, -1, T_CONST, 3, NULL, -1);
3828 /*_MIPS_SIM=_ABIN32*/
3829 cpplib_installBuiltin ("_MIPS_SIM", ctype_int, -1, T_CONST, 2, NULL , -1);
3830 cpplib_installBuiltin ("_MIPS_SZINT", ctype_int, -1, T_CONST, 32, NULL, -1);
3831 cpplib_installBuiltin ("_MIPS_SZLONG", ctype_int, -1, T_CONST, 32, NULL, -1);
3832 cpplib_installBuiltin ("_MIPS_SZPTR", ctype_int, -1, T_CONST, 32, NULL, -1);
3833 cpplib_installBuiltin ("_MODERN_C", ctype_int, -1, T_CONST, 2, NULL, -1);
3834 cpplib_installBuiltin ("_PIC", ctype_int, -1, T_CONST, 2, NULL, -1);
3835 cpplib_installBuiltin ("_SGI_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3836 cpplib_installBuiltin ("_SIZE_INT", ctype_int, -1, T_CONST, 32, NULL, -1);
3837 cpplib_installBuiltin ("_SIZE_LONG", ctype_int, -1, T_CONST, 32, NULL, -1);
3838 cpplib_installBuiltin ("_SIZE_PTR", ctype_int, -1, T_CONST, 32, NULL, -1);
3839 cpplib_installBuiltin ("_SVR4_SOURCE", ctype_int, -1, T_CONST, 2, NULL, -1);
3840 cpplib_installBuiltin ("_SYSTYPE_SVR4", ctype_int, -1, T_CONST, 2, NULL, -1);
3841 cpplib_installBuiltin ("__DSO__", ctype_int, -1, T_CONST, 2, NULL, -1);
3842 cpplib_installBuiltin ("__EXTENSIONS__", ctype_int, -1, T_CONST, 2, NULL, -1);
3843 cpplib_installBuiltin ("__INLINE_INTRINSICS", ctype_int, -1, T_CONST, 2, NULL, -1);
3844 cpplib_installBuiltin ("__MATH_HAS_NO_SIDE_EFFECTS", ctype_int, -1, T_CONST, 2, NULL, -1);
3845 cpplib_installBuiltin ("__host_mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3846 cpplib_installBuiltin ("__mips", ctype_int, -1, T_CONST, 3, NULL, -1);
3847 cpplib_installBuiltin ("__sgi", ctype_int, -1, T_CONST, 2, NULL, -1);
3848 cpplib_installBuiltin ("__unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3849 cpplib_installBuiltin ("host_mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3850 cpplib_installBuiltin ("mips", ctype_int, -1, T_CONST, 2, NULL, -1);
3851 cpplib_installBuiltin ("sgi", ctype_int, -1, T_CONST, 2, NULL, -1);
3852 cpplib_installBuiltin ("unix", ctype_int, -1, T_CONST, 2, NULL, -1);
3854 else if(! strcmp (UNAME, "OSF1"))
3856 cpplib_installBuiltin ("__alpha", ctype_int, -1, T_CONST, 2, NULL, -1);
3858 else if (!strcmp (UNAME, "Rhapsody"))
3860 cpplib_installBuiltin ("__ppc__", ctype_int, -1, T_CONST, 2, NULL, -1);
3861 cpplib_installBuiltin ("__BIG_ENDIAN__", ctype_int, -1, T_CONST, 2, NULL, -1);
3864 else if (!strcmp (UNAME, "SunOS"))
3866 cpplib_installBuiltin ("__OPEN_MAX", ctype_int, -1, T_CONST, 20, NULL, -1);
3867 cpplib_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, 2, NULL, -1);
3868 cpplib_installBuiltin ("__sparc", ctype_int, -1, T_CONST, 2, NULL, -1);
3869 /* This define "-Dfileno(f)=0" should be inserted but we're going to stick to deinfe constants for now...*/
3871 else
3874 types which we have not explictedly handled.
3875 AIX, FreeBSD, IRIX, Mach
3880 if (CPPOPTIONS (pfile)->debug_output)
3882 dump_special_to_buffer (pfile, "__BASE_FILE__");
3883 dump_special_to_buffer (pfile, "__VERSION__");
3884 #ifndef NO_BUILTIN_SIZE_TYPE
3885 dump_special_to_buffer (pfile, "__SIZE_TYPE__");
3886 #endif
3887 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3888 dump_special_to_buffer (pfile, "__PTRDIFF_TYPE__");
3889 #endif
3890 dump_special_to_buffer (pfile, "__WCHAR_TYPE__");
3891 dump_special_to_buffer (pfile, "__DATE__");
3892 dump_special_to_buffer (pfile, "__TIME__");
3893 if (!cppReader_isTraditional (pfile))
3894 dump_special_to_buffer (pfile, "__STDC__");
3899 /* Return 1 iff a token ending in C1 followed directly by a token C2
3900 could cause mis-tokenization. */
3902 static bool
3903 unsafe_chars (char c1, char c2)
3905 switch (c1)
3907 case '+': case '-':
3908 if (c2 == c1 || c2 == '=')
3909 return 1;
3910 goto letter;
3911 case '.':
3912 case '0': case '1': case '2': case '3': case '4':
3913 case '5': case '6': case '7': case '8': case '9':
3914 case 'e': case 'E': case 'p': case 'P':
3915 if (c2 == '-' || c2 == '+')
3916 return 1; /* could extend a pre-processing number */
3917 goto letter;
3918 case 'L':
3919 if (c2 == '\'' || c2 == '\"')
3920 return 1; /* Could turn into L"xxx" or L'xxx'. */
3921 goto letter;
3922 letter:
3923 case '_':
3924 case 'a': case 'b': case 'c': case 'd': case 'f':
3925 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3926 case 'm': case 'n': case 'o': case 'q': case 'r':
3927 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3928 case 'y': case 'z':
3929 case 'A': case 'B': case 'C': case 'D': case 'F':
3930 case 'G': case 'H': case 'I': case 'J': case 'K':
3931 case 'M': case 'N': case 'O': case 'Q': case 'R':
3932 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3933 case 'Y': case 'Z':
3934 /* We're in the middle of either a name or a pre-processing number. */
3935 return (is_idchar[(int) c2] || c2 == '.');
3936 case '<': case '>': case '!': case '%': case '#': case ':':
3937 case '^': case '&': case '|': case '*': case '/': case '=':
3938 return (c2 == c1 || c2 == '=');
3940 return 0;
3943 /* Expand a macro call.
3944 HP points to the symbol that is the macro being called.
3945 Put the result of expansion onto the input stack
3946 so that subsequent input by our caller will use it.
3948 If macro wants arguments, caller has already verified that
3949 an argument list follows; arguments come from the input stack. */
3951 static void
3952 cpplib_macroExpand (cppReader *pfile, /*@dependent@*/ hashNode hp)
3954 int nargs;
3955 DEFINITION *defn = hp->value.defn;
3956 char *xbuf;
3957 char *oxbuf = NULL;
3958 int start_line;
3959 int start_column;
3960 int end_line;
3961 int end_column;
3962 size_t xbuf_len;
3963 size_t old_written = cpplib_getWritten (pfile);
3964 int rest_args;
3965 int rest_zero = 0;
3966 int i;
3967 struct argdata *args = NULL;
3969 pfile->output_escapes++;
3970 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile), &start_line, &start_column);
3971 DPRINTF (("Expand macro: %d:%d", start_line, start_column));
3973 nargs = defn->nargs;
3975 if (nargs >= 0)
3977 enum cpp_token token = CPP_EOF;
3979 args = (struct argdata *) dmalloc ((nargs + 1) * sizeof (*args));
3981 for (i = 0; i < nargs; i++)
3983 args[i].expanded = 0;
3984 args[i].raw = 0;
3985 args[i].raw_length = 0;
3986 args[i].expand_length = args[i].stringified_length = -1;
3987 args[i].use_count = 0;
3991 ** Parse all the macro args that are supplied. I counts them.
3992 ** The first NARGS args are stored in ARGS.
3993 ** The rest are discarded. If rest_args is set then we assume
3994 ** macarg absorbed the rest of the args.
3997 i = 0;
3998 rest_args = 0;
4000 cppReader_forward (pfile, 1); /* Discard the open-parenthesis before the first arg. */
4003 if (rest_args != 0)
4005 continue;
4008 if (i < nargs || (nargs == 0 && i == 0))
4010 /* if we are working on last arg which absorbs rest of args... */
4011 if (i == nargs - 1 && defn->rest_args)
4013 rest_args = 1;
4016 args[i].raw = size_toLong (cpplib_getWritten (pfile));
4017 token = macarg (pfile, rest_args);
4018 args[i].raw_length = size_toInt (cpplib_getWritten (pfile) - args[i].raw);
4019 args[i].newlines = FALSE; /* FIXME */
4021 else
4023 token = macarg (pfile, 0);
4026 if (token == CPP_EOF || token == CPP_POP)
4028 cppReader_errorWithLine (pfile, start_line, start_column,
4029 cstring_fromCharsNew ("unterminated macro call"));
4030 sfree (args);
4031 return;
4033 i++;
4034 } while (token == CPP_COMMA);
4036 /* If we got one arg but it was just whitespace, call that 0 args. */
4037 if (i == 1)
4039 char *bp;
4040 char *lim;
4042 assertSet (args);
4044 bp = ARG_BASE + args[0].raw;
4045 lim = bp + args[0].raw_length;
4047 /* cpp.texi says for foo ( ) we provide one argument.
4048 However, if foo wants just 0 arguments, treat this as 0. */
4050 if (nargs == 0)
4052 while (bp != lim && is_space[(int) *bp])
4054 bp++;
4058 if (bp == lim)
4059 i = 0;
4062 /* Don't output an error message if we have already output one for
4063 a parse error above. */
4064 rest_zero = 0;
4066 if (nargs == 0 && i > 0)
4068 cppReader_error (pfile,
4069 message ("arguments given to macro `%s'", hp->name));
4071 else if (i < nargs)
4073 /* traditional C allows foo() if foo wants one argument. */
4074 if (nargs == 1 && i == 0 && cppReader_isTraditional (pfile))
4078 /* the rest args token is allowed to absorb 0 tokens */
4079 else if (i == nargs - 1 && defn->rest_args)
4080 rest_zero = 1;
4081 else if (i == 0)
4082 cppReader_error (pfile,
4083 message ("macro `%s' used without args", hp->name));
4084 else if (i == 1)
4085 cppReader_error (pfile,
4086 message ("macro `%s' used with just one arg", hp->name));
4087 else
4089 cppReader_error (pfile,
4090 message ("macro `%s' used with only %d args",
4091 hp->name, i));
4094 else if (i > nargs)
4096 cppReader_error (pfile,
4097 message ("macro `%s' used with too many (%d) args", hp->name, i));
4099 else
4106 ** If the agrument list was multiple lines, need to insert new lines to keep line
4107 ** numbers accurate.
4110 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile), &end_line, &end_column);
4111 DPRINTF (("Expand macro: %d:%d", end_line, end_column));
4113 /* If macro wants zero args, we parsed the arglist for checking only.
4114 Read directly from the macro definition. */
4116 if (nargs <= 0)
4118 xbuf = defn->expansion;
4119 xbuf_len = defn->length;
4121 else
4123 char *exp = defn->expansion;
4124 int offset; /* offset in expansion,
4125 copied a piece at a time */
4126 size_t totlen; /* total amount of exp buffer filled so far */
4128 register struct reflist *ap, *last_ap;
4130 assertSet (args); /* args is defined since the nargs > 0 path was taken */
4132 /* Macro really takes args. Compute the expansion of this call. */
4134 /* Compute length in characters of the macro's expansion.
4135 Also count number of times each arg is used. */
4136 xbuf_len = defn->length;
4138 llassert (args != NULL);
4140 for (ap = defn->pattern; ap != NULL; ap = ap->next)
4142 if (ap->stringify)
4144 struct argdata *arg = &args[ap->argno];
4146 /* Stringify it it hasn't already been */
4147 assertSet (arg);
4149 if (arg->stringified_length < 0)
4151 int arglen = arg->raw_length;
4152 bool escaped = FALSE;
4153 char in_string = '\0';
4154 char c;
4156 /* Initially need_space is -1. Otherwise, 1 means the
4157 previous character was a space, but we suppressed it;
4158 0 means the previous character was a non-space. */
4159 int need_space = -1;
4161 i = 0;
4162 arg->stringified = cpplib_getWritten (pfile);
4163 if (!cppReader_isTraditional (pfile))
4164 cppReader_putChar (pfile, '\"'); /* insert beginning quote */
4165 for (; i < arglen; i++)
4167 c = (ARG_BASE + arg->raw)[i];
4169 if (in_string == '\0')
4171 /* Internal sequences of whitespace are replaced by
4172 one space except within an string or char token.*/
4173 if (is_space[(int) c])
4175 if (cpplib_getWritten (pfile) > arg->stringified
4176 && (cpplib_getPWritten (pfile))[-1] == '@')
4178 /* "@ " escape markers are removed */
4179 cppReader_adjustWritten (pfile, -1);
4180 /*@innercontinue@*/ continue;
4182 if (need_space == 0)
4183 need_space = 1;
4184 /*@innercontinue@*/ continue;
4186 else if (need_space > 0)
4187 cppReader_putChar (pfile, ' ');
4188 else
4193 need_space = 0;
4196 if (escaped)
4197 escaped = 0;
4198 else
4200 if (c == '\\')
4201 escaped = 1;
4203 if (in_string != '\0')
4205 if (c == in_string)
4206 in_string = '\0';
4208 else if (c == '\"' || c == '\'')
4210 in_string = c;
4212 else
4218 /* Escape these chars */
4219 if (c == '\"' || (in_string != '\0' && c == '\\'))
4220 cppReader_putChar (pfile, '\\');
4221 if (isprint (c))
4222 cppReader_putChar (pfile, c);
4223 else
4225 cpplib_reserve (pfile, 4);
4226 sprintf (cpplib_getPWritten (pfile), "\\%03o",
4227 (unsigned int) c);
4228 cppReader_adjustWritten (pfile, 4);
4231 if (!cppReader_isTraditional (pfile))
4232 cppReader_putChar (pfile, '\"'); /* insert ending quote */
4233 arg->stringified_length
4234 = size_toInt (cpplib_getWritten (pfile) - arg->stringified);
4237 xbuf_len += args[ap->argno].stringified_length;
4239 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
4241 /* Add 4 for two newline-space markers to prevent token concatenation. */
4242 assertSet (args); /* Splint shouldn't need this */
4243 xbuf_len += args[ap->argno].raw_length + 4;
4245 else
4247 /* We have an ordinary (expanded) occurrence of the arg.
4248 So compute its expansion, if we have not already. */
4250 assertSet (args); /* shouldn't need this */
4252 if (args[ap->argno].expand_length < 0)
4254 args[ap->argno].expanded = cpplib_getWritten (pfile);
4255 cpp_expand_to_buffer (pfile,
4256 ARG_BASE + args[ap->argno].raw,
4257 size_fromInt (args[ap->argno].raw_length));
4259 args[ap->argno].expand_length
4260 = size_toInt (cpplib_getWritten (pfile) - args[ap->argno].expanded);
4263 /* Add 4 for two newline-space markers to prevent
4264 token concatenation. */
4265 xbuf_len += args[ap->argno].expand_length + 4;
4267 if (args[ap->argno].use_count < 10)
4268 args[ap->argno].use_count++;
4271 xbuf = (char *) dmalloc (xbuf_len + 1);
4272 oxbuf = xbuf;
4275 ** Generate in XBUF the complete expansion
4276 ** with arguments substituted in.
4277 ** TOTLEN is the total size generated so far.
4278 ** OFFSET is the index in the definition
4279 ** of where we are copying from.
4282 offset = 0;
4283 totlen = 0;
4285 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
4286 last_ap = ap, ap = ap->next)
4288 register struct argdata *arg = &args[ap->argno];
4289 size_t count_before = totlen;
4291 /* Add chars to XBUF. */
4292 for (i = 0; i < ap->nchars; i++, offset++)
4294 xbuf[totlen++] = exp[offset];
4297 /* If followed by an empty rest arg with concatenation,
4298 delete the last run of nonwhite chars. */
4299 if (rest_zero && totlen > count_before
4300 && ((ap->rest_args && ap->raw_before)
4301 || (last_ap != NULL && last_ap->rest_args
4302 && last_ap->raw_after)))
4304 /* Delete final whitespace. */
4305 while (totlen > count_before && is_space[(int) xbuf[totlen - 1]])
4307 totlen--;
4310 /* Delete the nonwhites before them. */
4311 while (totlen > count_before && ! is_space[(int) xbuf[totlen - 1]])
4313 totlen--;
4317 if (ap->stringify != 0)
4319 assertSet(arg);
4320 memcpy (xbuf + totlen,
4321 ARG_BASE + arg->stringified,
4322 size_fromInt (arg->stringified_length));
4323 totlen += arg->stringified_length;
4325 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
4327 char *p1;
4328 char *l1;
4330 assertSet (arg);
4332 p1 = ARG_BASE + arg->raw;
4333 l1 = p1 + arg->raw_length;
4335 if (ap->raw_before)
4337 while (p1 != l1 && is_space[(int) *p1])
4339 p1++;
4342 while (p1 != l1 && is_idchar[(int) *p1])
4344 xbuf[totlen++] = *p1++;
4347 /* Delete any no-reexpansion marker that follows
4348 an identifier at the beginning of the argument
4349 if the argument is concatenated with what precedes it. */
4350 if (p1[0] == '@' && p1[1] == '-')
4351 p1 += 2;
4353 if (ap->raw_after)
4355 /* Arg is concatenated after: delete trailing whitespace,
4356 whitespace markers, and no-reexpansion markers. */
4357 while (p1 != l1)
4359 if (is_space[(int) l1[-1]]) l1--;
4360 else if (l1[-1] == '-')
4362 char *p2 = l1 - 1;
4363 /* If a `-' is preceded by an odd number of newlines then it
4364 and the last newline are a no-reexpansion marker. */
4365 while (p2 != p1 && p2[-1] == '\n')
4367 p2--;
4370 if (((l1 - 1 - p2) & 1) != 0)
4372 l1 -= 2;
4374 else
4376 /*@innerbreak@*/ break;
4379 else
4381 /*@innerbreak@*/ break;
4386 memcpy (xbuf + totlen, p1, size_fromInt (l1 - p1));
4387 totlen += l1 - p1;
4389 else
4391 char *expanded;
4393 assertSet (arg);
4394 expanded = ARG_BASE + arg->expanded;
4396 if (!ap->raw_before && totlen > 0
4397 && (arg->expand_length != 0)
4398 && !cppReader_isTraditional(pfile)
4399 && unsafe_chars (xbuf[totlen-1], expanded[0]))
4401 xbuf[totlen++] = '@';
4402 xbuf[totlen++] = ' ';
4405 memcpy (xbuf + totlen, expanded,
4406 size_fromInt (arg->expand_length));
4407 totlen += arg->expand_length;
4409 if (!ap->raw_after && totlen > 0
4410 && offset < size_toInt (defn->length)
4411 && !cppReader_isTraditional(pfile)
4412 && unsafe_chars (xbuf[totlen-1], exp[offset]))
4414 xbuf[totlen++] = '@';
4415 xbuf[totlen++] = ' ';
4418 /* If a macro argument with newlines is used multiple times,
4419 then only expand the newlines once. This avoids creating
4420 output lines which don't correspond to any input line,
4421 which confuses gdb and gcov. */
4422 if (arg->use_count > 1 && arg->newlines > 0)
4424 /* Don't bother doing change_newlines for subsequent
4425 uses of arg. */
4426 arg->use_count = 1;
4427 arg->expand_length
4428 = change_newlines (expanded, arg->expand_length);
4432 if (totlen > xbuf_len)
4433 abort ();
4436 /* if there is anything left of the definition
4437 after handling the arg list, copy that in too. */
4439 for (i = offset; i < size_toInt (defn->length); i++)
4441 /* if we've reached the end of the macro */
4442 if (exp[i] == ')')
4443 rest_zero = 0;
4444 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
4445 && last_ap->raw_after))
4446 xbuf[totlen++] = exp[i];
4449 xbuf[totlen] = '\0';
4450 xbuf_len = totlen;
4453 pfile->output_escapes--;
4455 /* Now put the expansion on the input stack
4456 so our caller will commence reading from it. */
4457 DPRINTF (("Pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4459 if (end_line != start_line)
4461 /* xbuf must have enough newlines */
4462 int newlines = end_line - start_line;
4463 int foundnewlines = 0;
4464 char *xbufptr = xbuf;
4466 while ((xbufptr = strchr (xbufptr, '\n')) != NULL && foundnewlines <= newlines)
4468 foundnewlines++;
4469 xbufptr++;
4471 if (*xbufptr == '\0')
4473 break;
4477 if (foundnewlines < newlines)
4479 cstring newbuf = cstring_copyLength (xbuf, xbuf_len);
4481 while (foundnewlines < newlines)
4483 newbuf = cstring_appendChar (newbuf, '\n');
4484 foundnewlines++;
4487 sfree (oxbuf);
4488 xbuf = cstring_toCharsSafe (newbuf);
4489 xbuf_len = cstring_length (newbuf);
4490 /*@-branchstate@*/
4491 } /*@=branchstate@*/
4494 DPRINTF (("Pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4496 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
4497 DPRINTF (("After pushing expansion: %s", cstring_copyLength (xbuf, xbuf_len)));
4498 cppReader_getBufferSafe (pfile)->has_escapes = 1;
4500 /* Pop the space we've used in the token_buffer for argument expansion. */
4501 cppReader_setWritten (pfile, old_written);
4502 DPRINTF (("Done set written"));
4504 /* Recursive macro use sometimes works traditionally.
4505 #define foo(x,y) bar (x (y,0), y)
4506 foo (foo, baz) */
4508 if (!cppReader_isTraditional (pfile))
4509 hp->type = T_DISABLED;
4511 sfree (args);
4514 static void
4515 push_macro_expansion (cppReader *pfile, char *xbuf, size_t xbuf_len,
4516 /*@dependent@*/ hashNode hp)
4518 cppBuffer *mbuf = cppReader_pushBuffer (pfile, xbuf, xbuf_len);
4520 if (mbuf == NULL)
4522 return;
4525 mbuf->cleanup = cppReader_macroCleanup;
4527 llassert (mbuf->hnode == NULL);
4528 mbuf->hnode = hp;
4530 /* The first chars of the expansion should be a "@ " added by
4531 collect_expansion. This is to prevent accidental token-pasting
4532 between the text preceding the macro invocation, and the macro
4533 expansion text.
4535 We would like to avoid adding unneeded spaces (for the sake of
4536 tools that use cpp, such as imake). In some common cases we can
4537 tell that it is safe to omit the space.
4539 The character before the macro invocation cannot have been an
4540 idchar (or else it would have been pasted with the idchars of
4541 the macro name). Therefore, if the first non-space character
4542 of the expansion is an idchar, we do not need the extra space
4543 to prevent token pasting.
4545 Also, we don't need the extra space if the first char is '(',
4546 or some other (less common) characters. */
4548 if (xbuf[0] == '@' && xbuf[1] == ' '
4549 && (is_idchar[(int) xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
4550 || xbuf[2] == '\"'))
4552 llassert (mbuf->cur != NULL);
4553 DPRINTF (("Eating: %c", xbuf[2]));
4554 mbuf->cur += 2;
4560 /* Like cpplib_getToken, except that it does not read past end-of-line.
4561 Also, horizontal space is skipped, and macros are popped. */
4563 static enum cpp_token
4564 get_directive_token (cppReader *pfile)
4566 for (;;)
4568 size_t old_written = cpplib_getWritten (pfile);
4569 enum cpp_token token;
4570 cppSkipHspace (pfile);
4571 if (cppReader_peekC (pfile) == '\n')
4573 return CPP_VSPACE;
4576 token = cpplib_getToken (pfile);
4578 switch (token)
4580 case CPP_POP:
4581 if (!cppBuffer_isMacro (cppReader_getBuffer (pfile)))
4582 return token;
4583 /*@fallthrough@*/
4584 case CPP_HSPACE:
4585 case CPP_COMMENT:
4586 cppReader_setWritten (pfile, old_written);
4587 /*@switchbreak@*/ break;
4588 default:
4589 return token;
4595 /* Handle #include and #import.
4596 This function expects to see "fname" or <fname> on the input.
4598 The input is normally in part of the output_buffer following
4599 cpplib_getWritten, and will get overwritten by output_line_command.
4600 I.e. in input file specification has been popped by cppReader_handleDirective.
4601 This is safe. */
4603 static int
4604 do_include (cppReader *pfile, struct directive *keyword,
4605 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
4607 bool skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4608 cstring fname;
4609 char *fbeg, *fend; /* Beginning and end of fname */
4610 enum cpp_token token;
4612 /* Chain of dirs to search */
4613 struct file_name_list *search_start = CPPOPTIONS (pfile)->include;
4614 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
4615 struct file_name_list *searchptr = NULL;
4616 size_t old_written = cpplib_getWritten (pfile);
4617 size_t flen;
4619 int f; /* file number */
4620 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4621 f= -1; /* JF we iz paranoid! */
4623 pfile->parsing_include_directive++;
4624 token = get_directive_token (pfile);
4625 pfile->parsing_include_directive--;
4627 if (token == CPP_STRING)
4629 /* FIXME - check no trailing garbage */
4630 fbeg = pfile->token_buffer + old_written + 1;
4631 fend = cpplib_getPWritten (pfile) - 1;
4632 if (fbeg[-1] == '<')
4634 angle_brackets = 1;
4635 /* If -I-, start with the first -I dir after the -I-. */
4636 if (CPPOPTIONS (pfile)->first_bracket_include != NULL)
4637 search_start = CPPOPTIONS (pfile)->first_bracket_include;
4639 /* If -I- was specified, don't search current dir, only spec'd ones. */
4640 else if (!CPPOPTIONS (pfile)->ignore_srcdir)
4642 cppBuffer *fp = CPPBUFFER (pfile);
4643 /* We have "filename". Figure out directory this source
4644 file is coming from and put it on the front of the list. */
4646 for ( ; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
4648 int n;
4649 char *ep,*nam;
4651 llassert (fp != NULL);
4653 nam = NULL;
4655 if (cstring_isDefined (fp->nominal_fname))
4657 nam = cstring_toCharsSafe (fp->nominal_fname);
4659 /* Found a named file. Figure out dir of the file,
4660 and put it in front of the search list. */
4661 dsp[0].next = search_start;
4662 search_start = dsp;
4664 #ifndef VMS
4665 ep = strrchr (nam, CONNECTCHAR);
4666 #else /* VMS */
4667 ep = strrchr (nam, ']');
4668 if (ep == NULL) ep = strrchr (nam, '>');
4669 if (ep == NULL) ep = strrchr (nam, ':');
4670 if (ep != NULL) ep++;
4671 #endif /* VMS */
4672 if (ep != NULL)
4674 char save;
4676 n = ep - nam;
4677 save = nam[n];
4678 nam[n] = '\0';
4680 /*@-onlytrans@*/ /* This looks like a memory leak... */
4681 dsp[0].fname = cstring_fromCharsNew (nam); /* evs 2000-07-20: was fromChars */
4682 /*@=onlytrans@*/
4683 nam[n] = save;
4685 if (n + INCLUDE_LEN_FUDGE > size_toInt (pfile->max_include_len))
4686 pfile->max_include_len = size_fromInt (n + INCLUDE_LEN_FUDGE);
4688 else
4690 dsp[0].fname = cstring_undefined; /* Current directory */
4693 dsp[0].got_name_map = 0;
4694 break;
4698 else
4703 #ifdef VMS
4704 else if (token == CPP_NAME)
4707 * Support '#include xyz' like VAX-C to allow for easy use of all the
4708 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4709 * code from case '<' is repeated here) and generates a warning.
4711 cppReader_warning (pfile,
4712 "VAX-C-style include specification found, use '#include <filename.h>' !");
4713 angle_brackets = 1;
4714 /* If -I-, start with the first -I dir after the -I-. */
4715 if (CPPOPTIONS (pfile)->first_bracket_include)
4716 search_start = CPPOPTIONS (pfile)->first_bracket_include;
4717 fbeg = pfile->token_buffer + old_written;
4718 fend = cpplib_getPWritten (pfile);
4720 #endif
4721 else
4723 cppReader_error (pfile,
4724 message ("Preprocessor command #%s expects \"FILENAME\" or <FILENAME>",
4725 keyword->name));
4727 cppReader_setWritten (pfile, old_written);
4728 cppReader_skipRestOfLine (pfile);
4729 return 0;
4732 *fend = 0;
4734 token = get_directive_token (pfile);
4735 if (token != CPP_VSPACE)
4737 cppReader_errorLit (pfile,
4738 cstring_makeLiteralTemp ("Junk at end of #include"));
4740 while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
4742 token = get_directive_token (pfile);
4747 ** For #include_next, skip in the search path
4748 ** past the dir in which the containing file was found.
4751 if (skip_dirs)
4753 cppBuffer *fp = CPPBUFFER (pfile);
4755 for (; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
4757 llassert (fp != NULL);
4759 if (fp->fname != NULL)
4761 /* fp->dir is null if the containing file was specified with
4762 an absolute file name. In that case, don't skip anything. */
4763 if (fp->dir == SELF_DIR_DUMMY)
4765 search_start = CPPOPTIONS (pfile)->include;
4767 else if (fp->dir != NULL)
4769 search_start = fp->dir->next;
4771 else
4776 break;
4781 cppReader_setWritten (pfile, old_written);
4783 flen = size_fromInt (fend - fbeg);
4785 DPRINTF (("fbeg: %s", fbeg));
4787 if (flen == 0)
4789 cppReader_error (pfile,
4790 message ("Empty file name in #%s", keyword->name));
4791 return 0;
4795 ** Allocate this permanently, because it gets stored in the definitions
4796 ** of macros.
4799 fname = cstring_undefined;
4801 /* + 2 above for slash and terminating null. */
4802 /* + 2 added for '.h' on VMS (to support '#include filename') */
4804 /* If specified file name is absolute, just open it. */
4806 if (osd_isConnectChar (*fbeg)
4807 # if defined (WIN32) || defined (OS2)
4808 || (*(fbeg + 1) == ':')
4809 # endif
4812 fname = cstring_copyLength (fbeg, flen);
4814 if (redundant_include_p (pfile, fname))
4816 cstring_free (fname);
4817 return 0;
4820 f = open_include_file (pfile, fname, NULL);
4822 if (f == IMPORT_FOUND)
4824 return 0; /* Already included this file */
4827 else
4829 /* Search directory path, trying to open the file.
4830 Copy each filename tried into FNAME. */
4832 for (searchptr = search_start; searchptr != NULL;
4833 searchptr = searchptr->next)
4835 if (!cstring_isEmpty (searchptr->fname))
4837 /* The empty string in a search path is ignored.
4838 This makes it possible to turn off entirely
4839 a standard piece of the list. */
4840 if (cstring_isEmpty (searchptr->fname))
4841 continue;
4843 fname = cstring_copy (searchptr->fname);
4844 fname = cstring_appendChar (fname, CONNECTCHAR);
4845 DPRINTF (("Here: %s", fname));
4847 else
4852 fname = cstring_concatLength (fname, fbeg, flen);
4854 DPRINTF (("fname: %s", fname));
4856 /* Win32 directory fix from Kay Buschner. */
4857 #if defined (WIN32) || defined (OS2)
4858 /* Fix all unixdir slashes to win dir slashes */
4859 if (searchptr->fname && (searchptr->fname[0] != 0))
4861 cstring_replaceAll (fname, '/', '\\');
4863 #endif /* WIN32 */
4865 #ifdef VMS
4866 /* Change this 1/2 Unix 1/2 VMS file specification into a
4867 full VMS file specification */
4868 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4869 /* Fix up the filename */
4870 hack_vms_include_specification (fname);
4871 } else {
4872 /* This is a normal VMS filespec, so use it unchanged. */
4873 strncpy (fname, fbeg, flen);
4874 fname[flen] = 0;
4875 /* if it's '#include filename', add the missing .h */
4876 if (strchr (fname,'.') == NULL) {
4877 strcat (fname, ".h");
4880 #endif /* VMS */
4881 /* ??? There are currently 3 separate mechanisms for avoiding processing
4882 of redundant include files: #import, #pragma once, and
4883 redundant_include_p. It would be nice if they were unified. */
4885 if (redundant_include_p (pfile, fname))
4887 cstring_free (fname);
4888 return 0;
4891 DPRINTF (("Trying: %s", fname));
4893 f = open_include_file (pfile, fname, searchptr);
4895 if (f == IMPORT_FOUND)
4897 return 0; /* Already included this file */
4899 #ifdef EACCES
4900 else if (f == IMPORT_NOT_FOUND && errno == EACCES)
4902 cppReader_warning (pfile,
4903 message ("Header file %s exists, but is not readable", fname));
4905 #endif
4907 if (f >= 0)
4909 break;
4914 if (f < 0)
4916 /* A file that was not found. */
4917 fname = cstring_copyLength (fbeg, flen);
4919 if (search_start != NULL)
4921 cppReader_error (pfile,
4922 message ("Cannot find include file %s on search path: %x",
4923 fname,
4924 searchPath_unparse (search_start)));
4926 else
4928 cppReader_error (pfile,
4929 message ("No include path in which to find %s", fname));
4932 else {
4934 ** Check to see if this include file is a once-only include file.
4935 ** If so, give up.
4938 struct file_name_list *ptr;
4940 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
4942 if (cstring_equal (ptr->fname, fname))
4944 /* This file was included before. */
4945 break;
4949 if (ptr == NULL)
4951 /* This is the first time for this file. */
4952 /* Add it to list of files included. */
4954 ptr = (struct file_name_list *) dmalloc (sizeof (*ptr));
4955 ptr->control_macro = NULL;
4956 ptr->c_system_include_path = NULL;
4957 ptr->next = pfile->all_include_files;
4958 ptr->fname = fname;
4959 ptr->got_name_map = NULL;
4961 DPRINTF (("Including file: %s", fname));
4962 pfile->all_include_files = ptr;
4963 assertSet (pfile->all_include_files);
4966 if (angle_brackets != 0)
4968 pfile->system_include_depth++;
4971 /* Actually process the file */
4972 if (cppReader_pushBuffer (pfile, NULL, 0) == NULL)
4974 cstring_free (fname);
4975 return 0;
4978 if (finclude (pfile, f, fname, is_system_include (pfile, fname),
4979 searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
4981 output_line_command (pfile, 0, enter_file);
4982 pfile->only_seen_white = 2;
4985 if (angle_brackets)
4987 pfile->system_include_depth--;
4989 /*@-branchstate@*/
4990 } /*@=branchstate@*/
4992 return 0;
4995 /* Return nonzero if there is no need to include file NAME
4996 because it has already been included and it contains a conditional
4997 to make a repeated include do nothing. */
4999 static bool
5000 redundant_include_p (cppReader *pfile, cstring name)
5002 struct file_name_list *l = pfile->all_include_files;
5004 for (; l != NULL; l = l->next)
5006 if (cstring_equal (name, l->fname)
5007 && (l->control_macro != NULL)
5008 && (cpphash_lookup (l->control_macro, -1, -1) != NULL))
5010 return TRUE;
5014 return FALSE;
5017 /* Return nonzero if the given FILENAME is an absolute pathname which
5018 designates a file within one of the known "system" include file
5019 directories. We assume here that if the given FILENAME looks like
5020 it is the name of a file which resides either directly in a "system"
5021 include file directory, or within any subdirectory thereof, then the
5022 given file must be a "system" include file. This function tells us
5023 if we should suppress pedantic errors/warnings for the given FILENAME.
5025 The value is 2 if the file is a C-language system header file
5026 for which C++ should (on most systems) assume `extern "C"'. */
5028 static bool
5029 is_system_include (cppReader *pfile, cstring filename)
5031 struct file_name_list *searchptr;
5033 for (searchptr = CPPOPTIONS (pfile)->first_system_include;
5034 searchptr != NULL;
5035 searchptr = searchptr->next)
5037 if (!cstring_isEmpty (searchptr->fname))
5039 cstring sys_dir = searchptr->fname;
5040 size_t length = cstring_length (sys_dir);
5042 if (cstring_equalLen (sys_dir, filename, length)
5043 && osd_isConnectChar (cstring_getChar (filename, length)))
5045 if (searchptr->c_system_include_path)
5046 return 2;
5047 else
5048 return 1;
5053 return 0;
5056 /* Convert a character string literal into a nul-terminated string.
5057 The input string is [IN ... LIMIT).
5058 The result is placed in RESULT. RESULT can be the same as IN.
5059 The value returned in the end of the string written to RESULT,
5060 or NULL on error. */
5062 static /*@null@*/ char *
5063 convert_string (cppReader *pfile, /*@returned@*/ char *result,
5064 char *in, char *limit, int handle_escapes)
5066 char c;
5067 c = *in++;
5069 if (c != '\"')
5071 return NULL;
5074 while (in < limit)
5076 c = *in++;
5078 switch (c)
5080 case '\0':
5081 return NULL;
5082 case '\"':
5083 limit = in;
5084 /*@switchbreak@*/ break;
5085 case '\\':
5086 if (handle_escapes)
5088 char *bpc = (char *) in;
5089 int i = (char) cppReader_parseEscape (pfile, &bpc);
5090 in = (char *) bpc;
5091 if (i >= 0)
5092 *result++ = (char) c;
5093 /*@switchbreak@*/ break;
5096 /*@fallthrough@*/
5097 default:
5098 *result++ = c;
5102 *result = 0;
5103 return result;
5107 * interpret #line command. Remembers previously seen fnames
5108 * in its very own hash table.
5111 /*@constant int FNAME_HASHSIZE@*/
5112 #define FNAME_HASHSIZE 37
5114 static int
5115 do_line (cppReader *pfile, /*@unused@*/ struct directive *keyword)
5117 cppBuffer *ip = cppReader_getBuffer (pfile);
5118 int new_lineno;
5119 size_t old_written = cpplib_getWritten (pfile);
5120 enum file_change_code file_change = same_file;
5121 enum cpp_token token;
5123 llassert (ip != NULL);
5124 token = get_directive_token (pfile);
5126 if (token != CPP_NUMBER
5127 || !isdigit(pfile->token_buffer[old_written]))
5129 cppReader_errorLit (pfile,
5130 cstring_makeLiteralTemp ("invalid format `#line' command"));
5132 goto bad_line_directive;
5135 /* The Newline at the end of this line remains to be processed.
5136 To put the next line at the specified line number,
5137 we must store a line number now that is one less. */
5138 new_lineno = atoi (pfile->token_buffer + old_written) - 1;
5139 cppReader_setWritten (pfile, old_written);
5141 /* NEW_LINENO is one less than the actual line number here. */
5142 if (cppReader_isPedantic (pfile) && new_lineno < 0)
5143 cppReader_pedwarnLit (pfile,
5144 cstring_makeLiteralTemp ("line number out of range in `#line' command"));
5146 token = get_directive_token (pfile);
5148 if (token == CPP_STRING) {
5149 char *fname = pfile->token_buffer + old_written;
5150 char *end_name;
5151 static hashNode fname_table[FNAME_HASHSIZE];
5152 hashNode hp;
5153 hashNode *hash_bucket;
5154 char *p;
5155 size_t num_start;
5156 size_t fname_length;
5158 /* Turn the file name, which is a character string literal,
5159 into a null-terminated string. Do this in place. */
5160 end_name = convert_string (pfile, fname, fname, cpplib_getPWritten (pfile), 1);
5161 if (end_name == NULL)
5163 cppReader_errorLit (pfile,
5164 cstring_makeLiteralTemp ("invalid format `#line' command"));
5165 goto bad_line_directive;
5168 fname_length = size_fromInt (end_name - fname);
5169 num_start = cpplib_getWritten (pfile);
5171 token = get_directive_token (pfile);
5172 if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP) {
5173 p = pfile->token_buffer + num_start;
5174 if (cppReader_isPedantic (pfile))
5175 cppReader_pedwarnLit (pfile,
5176 cstring_makeLiteralTemp ("garbage at end of `#line' command"));
5178 if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
5180 cppReader_errorLit (pfile,
5181 cstring_makeLiteralTemp ("invalid format `#line' command"));
5182 goto bad_line_directive;
5184 if (*p == '1')
5185 file_change = enter_file;
5186 else if (*p == 2)
5187 file_change = leave_file;
5188 else if (*p == 3)
5189 ip->system_header_p = 1;
5190 else /* if (*p == 4) */
5191 ip->system_header_p = 2;
5193 cppReader_setWritten (pfile, num_start);
5194 token = get_directive_token (pfile);
5195 p = pfile->token_buffer + num_start;
5196 if (token == CPP_NUMBER && p[1] == '\0' && (*p == '3' || *p== '4')) {
5197 ip->system_header_p = *p == 3 ? 1 : 2;
5198 token = get_directive_token (pfile);
5200 if (token != CPP_VSPACE) {
5201 cppReader_errorLit (pfile,
5202 cstring_makeLiteralTemp ("invalid format `#line' command"));
5204 goto bad_line_directive;
5208 hash_bucket =
5209 &fname_table[cpphash_hashCode (fname, fname_length, FNAME_HASHSIZE)];
5211 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
5213 if (hp->length == fname_length)
5215 llassert (hp->value.cpval != NULL);
5217 if (strncmp (hp->value.cpval, fname, fname_length) == 0)
5219 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
5220 break;
5225 if (hp == 0) {
5226 /* Didn't find it; cons up a new one. */
5227 hp = (hashNode) dmalloc (sizeof (*hp));
5229 hp->prev = NULL;
5230 hp->bucket_hdr = NULL;
5231 hp->type = T_NONE;
5232 hp->name = cstring_undefined;
5233 hp->next = *hash_bucket;
5235 *hash_bucket = hp;
5237 hp->length = fname_length;
5238 hp->value.cpval = dmalloc (sizeof (*hp->value.cpval) * (fname_length + 1));
5239 memcpy (hp->value.cpval, fname, fname_length);
5240 hp->value.cpval[fname_length] = '\0';
5241 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
5244 else if (token != CPP_VSPACE && token != CPP_EOF)
5246 cppReader_errorLit (pfile,
5247 cstring_makeLiteralTemp ("invalid format `#line' command"));
5248 goto bad_line_directive;
5250 else
5255 ip->lineno = new_lineno;
5256 bad_line_directive:
5257 cppReader_skipRestOfLine (pfile);
5258 cppReader_setWritten (pfile, old_written);
5259 output_line_command (pfile, 0, file_change);
5260 return 0;
5264 * remove the definition of a symbol from the symbol table.
5265 * according to un*x /lib/cpp, it is not an error to undef
5266 * something that has no definitions, so it isn't one here either.
5269 static int
5270 do_undef (cppReader *pfile, struct directive *keyword, char *buf, char *limit)
5273 size_t sym_length;
5274 hashNode hp;
5275 char *orig_buf = buf;
5277 SKIP_WHITE_SPACE (buf);
5279 sym_length = cppReader_checkMacroName (pfile, buf, cstring_makeLiteralTemp ("macro"));
5281 while ((hp = cpphash_lookup (buf, size_toInt (sym_length), -1)) != NULL)
5283 /* If we are generating additional info for debugging (with -g) we
5284 need to pass through all effective #undef commands. */
5285 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
5287 pass_thru_directive (orig_buf, limit, pfile, keyword);
5290 if (hp->type != T_MACRO)
5292 cppReader_warning (pfile,
5293 message ("Undefining preprocessor builtin: %s",
5294 hp->name));
5297 cppReader_deleteMacro (hp);
5300 if (cppReader_isPedantic (pfile)) {
5301 buf += sym_length;
5302 SKIP_WHITE_SPACE (buf);
5303 if (buf != limit)
5305 cppReader_pedwarnLit (pfile,
5306 cstring_makeLiteralTemp ("garbage after `#undef' directive"));
5310 return 0;
5315 * Report an error detected by the program we are processing.
5316 * Use the text of the line in the error message.
5317 * (We use error because it prints the filename & line#.)
5320 static int
5321 do_error (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5322 char *buf, char *limit)
5324 size_t length = size_fromInt (limit - buf);
5325 cstring copy = cstring_copyLength (buf, length);
5326 cstring adv = cstring_advanceWhiteSpace (copy);
5328 cppReader_error (pfile, message ("#error %s", adv));
5329 cstring_free (copy);
5330 return 0;
5334 * Report a warning detected by the program we are processing.
5335 * Use the text of the line in the warning message, then continue.
5336 * (We use error because it prints the filename & line#.)
5339 static int
5340 do_warning (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5341 char *buf, char *limit)
5343 size_t length = size_fromInt (limit - buf);
5344 cstring copy = cstring_copyLength (buf, length);
5345 cstring adv = cstring_advanceWhiteSpace (copy);
5346 cppReader_warning (pfile, message ("#warning %s", adv));
5347 cstring_free (copy);
5348 return 0;
5352 /* #ident has already been copied to the output file, so just ignore it. */
5354 static int
5355 do_ident (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5356 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5358 /* Allow #ident in system headers, since that's not user's fault. */
5359 if (cppReader_isPedantic (pfile)
5360 && !cppReader_getBufferSafe (pfile)->system_header_p)
5361 cppReader_pedwarnLit (pfile,
5362 cstring_makeLiteralTemp ("ANSI C does not allow `#ident'"));
5364 /* Leave rest of line to be read by later calls to cpplib_getToken. */
5366 return 0;
5369 /* #pragma and its argument line have already been copied to the output file.
5370 Just check for some recognized pragmas that need validation here. */
5372 static int
5373 do_pragma (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5374 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5376 while (*buf == ' ' || *buf == '\t')
5378 buf++;
5381 if (!strncmp (buf, "implementation", 14)) {
5382 /* Be quiet about `#pragma implementation' for a file only if it hasn't
5383 been included yet. */
5384 struct file_name_list *ptr;
5385 char *p = buf + 14, *fname, *inc_fname;
5386 size_t fname_len;
5387 SKIP_WHITE_SPACE (p);
5388 if (*p == '\n' || *p != '\"')
5389 return 0;
5391 fname = p + 1;
5392 p = (char *) strchr (fname, '\"');
5393 fname_len = p != NULL ? size_fromInt (p - fname) : mstring_length (fname);
5395 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
5397 inc_fname = (char *) strrchr (cstring_toCharsSafe (ptr->fname), CONNECTCHAR);
5398 inc_fname = (inc_fname != NULL)
5399 ? inc_fname + 1 : cstring_toCharsSafe (ptr->fname);
5401 if ((inc_fname != NULL)
5402 && (strncmp (inc_fname, fname, fname_len) == 0))
5404 cpp_setLocation (pfile);
5406 ppllerror (message ("`#pragma implementation' for `%s' appears "
5407 "after file is included",
5408 cstring_fromChars (fname)));
5413 return 0;
5417 * handle #if command by
5418 * 1) inserting special `defined' keyword into the hash table
5419 * that gets turned into 0 or 1 by special_symbol (thus,
5420 * if the luser has a symbol called `defined' already, it won't
5421 * work inside the #if command)
5422 * 2) rescan the input into a temporary output buffer
5423 * 3) pass the output buffer to the yacc parser and collect a value
5424 * 4) clean up the mess left from steps 1 and 2.
5425 * 5) call conditional_skip to skip til the next #endif (etc.),
5426 * or not, depending on the value from step 3.
5429 static int
5430 do_if (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5431 char *buf, char *limit)
5433 HOST_WIDE_INT value;
5434 DPRINTF (("Do if: %s", buf));
5435 value = eval_if_expression (pfile, buf, limit - buf);
5436 conditional_skip (pfile, value == 0, T_IF, NULL);
5437 return 0;
5441 * handle a #elif directive by not changing if_stack either.
5442 * see the comment above do_else.
5445 static int do_elif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5446 char *buf, char *limit)
5448 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5450 cppReader_errorLit (pfile,
5451 cstring_makeLiteralTemp ("Preprocessor command #elif is not within a conditional"));
5452 return 0;
5454 else
5456 llassert (pfile->if_stack != NULL);
5458 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
5460 cppReader_errorLit (pfile,
5461 cstring_makeLiteralTemp ("`#elif' after `#else'"));
5463 if (pfile->if_stack->fname != NULL
5464 && cppReader_getBufferSafe (pfile)->fname != NULL
5465 && !cstring_equal (pfile->if_stack->fname,
5466 cppReader_getBufferSafe (pfile)->nominal_fname))
5467 fprintf (stderr, ", file %s", cstring_toCharsSafe (pfile->if_stack->fname));
5468 fprintf (stderr, ")\n");
5470 pfile->if_stack->type = T_ELIF;
5473 if (pfile->if_stack->if_succeeded)
5475 skip_if_group (pfile, 0);
5477 else
5479 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
5480 if (value == 0)
5481 skip_if_group (pfile, 0);
5482 else
5484 ++pfile->if_stack->if_succeeded; /* continue processing input */
5485 output_line_command (pfile, 1, same_file);
5489 return 0;
5493 * evaluate a #if expression in BUF, of length LENGTH,
5494 * then parse the result as a C expression and return the value as an int.
5497 static HOST_WIDE_INT
5498 eval_if_expression (cppReader *pfile,
5499 /*@unused@*/ char *buf,
5500 /*@unused@*/ int length)
5502 hashNode save_defined;
5503 HOST_WIDE_INT value;
5504 size_t old_written = cpplib_getWritten (pfile);
5506 DPRINTF (("Saving defined..."));
5507 save_defined = cpphash_install ("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
5508 pfile->pcp_inside_if = 1;
5510 value = cppReader_parseExpression (pfile);
5511 pfile->pcp_inside_if = 0;
5513 /* Clean up special symbol */
5514 DPRINTF (("Removing defined..."));
5515 cppReader_deleteMacro (save_defined);
5516 cppReader_setWritten (pfile, old_written); /* Pop */
5518 return value;
5522 * routine to handle ifdef/ifndef. Try to look up the symbol,
5523 * then do or don't skip to the #endif/#else/#elif depending
5524 * on what directive is actually being processed.
5527 static int
5528 do_xifdef (cppReader *pfile, struct directive *keyword,
5529 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
5531 int skip;
5532 cppBuffer *ip = cppReader_getBufferSafe (pfile);
5533 char *ident;
5534 size_t ident_length;
5535 enum cpp_token token;
5536 int start_of_file = 0;
5537 char *control_macro = 0;
5538 size_t old_written = cpplib_getWritten (pfile);
5540 DPRINTF (("do xifdef: %d",
5541 keyword->type == T_IFNDEF));
5543 /* Detect a #ifndef at start of file (not counting comments). */
5544 if (cstring_isDefined (ip->fname) && keyword->type == T_IFNDEF)
5546 start_of_file = pfile->only_seen_white == 2;
5549 pfile->no_macro_expand++;
5550 token = get_directive_token (pfile);
5551 pfile->no_macro_expand--;
5553 ident = pfile->token_buffer + old_written;
5554 DPRINTF (("Ident: %s", ident));
5556 ident_length = cpplib_getWritten (pfile) - old_written;
5557 cppReader_setWritten (pfile, old_written); /* Pop */
5559 if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
5561 skip = (keyword->type == T_IFDEF);
5562 if (! cppReader_isTraditional (pfile))
5564 cppReader_pedwarn (pfile,
5565 message ("`#%s' with no argument", keyword->name));
5568 else if (token == CPP_NAME)
5570 hashNode hp = cpphash_lookup (ident, size_toInt (ident_length), -1);
5572 skip = (keyword->type == T_IFDEF) ? (hp == NULL) : (hp != NULL);
5574 DPRINTF (("hp null: %d / %d / %d", hp == NULL, keyword->type == T_IFNDEF, skip));
5576 if (start_of_file && !skip)
5578 DPRINTF (("Not skipping!"));
5579 control_macro = (char *) dmalloc (ident_length + 1);
5580 memcpy (control_macro, ident, ident_length + 1);
5583 else
5585 skip = (keyword->type == T_IFDEF);
5586 if (! cppReader_isTraditional (pfile))
5588 cppReader_error (pfile,
5589 message ("`#%s' with invalid argument", keyword->name));
5593 if (!cppReader_isTraditional (pfile))
5595 int c;
5596 cppSkipHspace (pfile);
5597 c = cppReader_peekC (pfile);
5598 if (c != EOF && c != '\n')
5600 cppReader_pedwarn (pfile,
5601 message ("garbage at end of `#%s' argument", keyword->name));
5605 cppReader_skipRestOfLine (pfile);
5607 DPRINTF (("Conditional skip: %d", skip));
5608 conditional_skip (pfile, skip, T_IF, control_macro);
5609 return 0;
5612 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
5613 If this is a #ifndef starting at the beginning of a file,
5614 CONTROL_MACRO is the macro name tested by the #ifndef.
5615 Otherwise, CONTROL_MACRO is 0. */
5617 static void
5618 conditional_skip (cppReader *pfile, int skip,
5619 enum node_type type,
5620 /*@dependent@*/ char *control_macro)
5622 cppIfStackFrame *temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
5624 temp->fname = cppReader_getBufferSafe (pfile)->nominal_fname;
5625 temp->next = pfile->if_stack;
5626 temp->control_macro = control_macro;
5627 temp->lineno = 0;
5628 temp->if_succeeded = 0;
5630 pfile->if_stack = temp;
5631 pfile->if_stack->type = type;
5633 if (skip != 0)
5635 skip_if_group (pfile, 0);
5636 return;
5638 else
5640 ++pfile->if_stack->if_succeeded;
5641 output_line_command (pfile, 1, same_file);
5646 * skip to #endif, #else, or #elif. adjust line numbers, etc.
5647 * leaves input ptr at the sharp sign found.
5648 * If ANY is nonzero, return at next directive of any sort.
5651 static void
5652 skip_if_group (cppReader *pfile, int any)
5654 int c;
5655 struct directive *kt;
5656 cppIfStackFrame *save_if_stack = pfile->if_stack; /* don't pop past here */
5657 register int ident_length;
5658 char *ident;
5659 struct parse_marker line_start_mark;
5661 parseSetMark (&line_start_mark, pfile);
5663 if (CPPOPTIONS (pfile)->output_conditionals) {
5664 static char failed[] = "#failed\n";
5665 cppReader_puts (pfile, failed, sizeof(failed)-1);
5666 pfile->lineno++;
5667 output_line_command (pfile, 1, same_file);
5670 beg_of_line:
5671 if (CPPOPTIONS (pfile)->output_conditionals)
5673 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
5674 char *start_line;
5676 llassert (pbuf->buf != NULL);
5678 start_line = pbuf->buf + line_start_mark.position;
5679 cppReader_puts (pfile, start_line, size_fromInt (pbuf->cur - start_line));
5682 parseMoveMark (&line_start_mark, pfile);
5684 if (!cppReader_isTraditional (pfile))
5686 cppSkipHspace (pfile);
5689 c = cppReader_getC (pfile);
5690 if (c == '#')
5692 size_t old_written = cpplib_getWritten (pfile);
5693 cppSkipHspace (pfile);
5695 parse_name (pfile, cppReader_getC (pfile));
5696 ident_length = size_toInt (cpplib_getWritten (pfile) - old_written);
5697 ident = pfile->token_buffer + old_written;
5698 pfile->limit = ident;
5700 for (kt = directive_table; kt->length >= 0; kt++)
5702 cppIfStackFrame *temp;
5703 if (ident_length == kt->length
5704 && cstring_equalPrefix (kt->name, cstring_fromChars (ident)))
5706 /* If we are asked to return on next directive, do so now. */
5707 if (any)
5709 goto done;
5712 switch (kt->type)
5714 case T_IF:
5715 case T_IFDEF:
5716 case T_IFNDEF:
5717 temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
5718 temp->next = pfile->if_stack;
5719 temp->fname = cppReader_getBufferSafe (pfile)->nominal_fname;
5720 temp->type = kt->type;
5721 temp->lineno = 0;
5722 temp->if_succeeded = 0;
5723 temp->control_macro = NULL;
5725 pfile->if_stack = temp;
5726 /*@switchbreak@*/ break;
5727 case T_ELSE:
5728 case T_ENDIF:
5729 if (cppReader_isPedantic (pfile) && pfile->if_stack != save_if_stack)
5730 validate_else (pfile,
5731 cstring_makeLiteralTemp (kt->type == T_ELSE ? "#else" : "#endif"));
5732 /*@fallthrough@*/
5733 case T_ELIF:
5734 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5736 cppReader_error (pfile,
5737 message ("Preprocessor command #%s is not within a conditional", kt->name));
5738 /*@switchbreak@*/ break;
5740 else if (pfile->if_stack == save_if_stack)
5742 goto done; /* found what we came for */
5744 else
5749 if (kt->type != T_ENDIF)
5751 llassert (pfile->if_stack != NULL);
5753 if (pfile->if_stack->type == T_ELSE)
5755 cppReader_errorLit (pfile,
5756 cstring_makeLiteralTemp ("`#else' or `#elif' after `#else'"));
5759 pfile->if_stack->type = kt->type;
5760 /*@switchbreak@*/ break;
5763 temp = pfile->if_stack;
5764 llassert (temp != NULL);
5765 pfile->if_stack = temp->next;
5766 sfree (temp);
5767 /*@switchbreak@*/ break;
5768 default: ;
5769 /*@-branchstate@*/
5770 #if defined (OS2) && defined (__IBMC__)
5771 /* Dummy code to eleminate optimization problems with icc */
5772 c = 0;
5773 # endif
5776 /*@=branchstate@*/
5777 break;
5780 /* Don't let erroneous code go by. */
5782 if (kt->length < 0 && !CPPOPTIONS (pfile)->lang_asm
5783 && cppReader_isPedantic (pfile))
5785 cppReader_pedwarnLit (pfile,
5786 cstring_makeLiteralTemp ("Invalid preprocessor directive name"));
5790 c = cppReader_getC (pfile);
5792 /* We're in the middle of a line. Skip the rest of it. */
5793 for (;;) {
5794 size_t old;
5796 switch (c)
5798 case EOF:
5799 goto done;
5800 case '/': /* possible comment */
5801 c = skip_comment (pfile, NULL);
5802 if (c == EOF)
5803 goto done;
5804 /*@switchbreak@*/ break;
5805 case '\"':
5806 case '\'':
5807 cppReader_forward (pfile, -1);
5808 old = cpplib_getWritten (pfile);
5809 (void) cpplib_getToken (pfile);
5810 cppReader_setWritten (pfile, old);
5811 /*@switchbreak@*/ break;
5812 case '\\':
5813 /* Char after backslash loses its special meaning. */
5814 if (cppReader_peekC (pfile) == '\n')
5816 cppReader_forward (pfile, 1);
5819 /*@switchbreak@*/ break;
5820 case '\n':
5821 goto beg_of_line;
5823 c = cppReader_getC (pfile);
5825 done:
5826 if (CPPOPTIONS (pfile)->output_conditionals) {
5827 static char end_failed[] = "#endfailed\n";
5828 cppReader_puts (pfile, end_failed, sizeof(end_failed)-1);
5829 pfile->lineno++;
5831 pfile->only_seen_white = 1;
5833 parseGotoMark (&line_start_mark, pfile);
5834 parseClearMark (&line_start_mark);
5838 * handle a #else directive. Do this by just continuing processing
5839 * without changing if_stack ; this is so that the error message
5840 * for missing #endif's etc. will point to the original #if. It
5841 * is possible that something different would be better.
5844 static int
5845 do_else (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5846 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5848 if (cppReader_isPedantic (pfile))
5850 validate_else (pfile, cstring_makeLiteralTemp ("#else"));
5853 cppReader_skipRestOfLine (pfile);
5855 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack) {
5856 cppReader_errorLit (pfile,
5857 cstring_makeLiteralTemp ("Preprocessor command #else is not within a conditional"));
5858 return 0;
5859 } else {
5860 /* #ifndef can't have its special treatment for containing the whole file
5861 if it has a #else clause. */
5863 llassert (pfile->if_stack != NULL);
5865 pfile->if_stack->control_macro = 0;
5867 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
5869 cpp_setLocation (pfile);
5870 genppllerrorhint (FLG_PREPROC,
5871 message ("Pre-processor directive #else after #else"),
5872 message ("%q: Location of match",
5873 fileloc_unparseRaw (pfile->if_stack->fname,
5874 pfile->if_stack->lineno)));
5877 pfile->if_stack->type = T_ELSE;
5880 if (pfile->if_stack->if_succeeded)
5881 skip_if_group (pfile, 0);
5882 else {
5883 ++pfile->if_stack->if_succeeded; /* continue processing input */
5884 output_line_command (pfile, 1, same_file);
5887 return 0;
5891 * unstack after #endif command
5894 static int
5895 do_endif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5896 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5898 if (cppReader_isPedantic (pfile))
5900 validate_else (pfile, cstring_makeLiteralTemp ("#endif"));
5903 cppReader_skipRestOfLine (pfile);
5905 if (pfile->if_stack == cppReader_getBufferSafe (pfile)->if_stack)
5907 cppReader_errorLit (pfile, cstring_makeLiteralTemp ("Unbalanced #endif"));
5909 else
5911 cppIfStackFrame *temp = pfile->if_stack;
5913 llassert (temp != NULL);
5915 pfile->if_stack = temp->next;
5916 if (temp->control_macro != 0)
5918 /* This #endif matched a #ifndef at the start of the file.
5919 See if it is at the end of the file. */
5920 struct parse_marker start_mark;
5921 int c;
5923 parseSetMark (&start_mark, pfile);
5925 for (;;)
5927 cppSkipHspace (pfile);
5928 c = cppReader_getC (pfile);
5930 if (c != '\n')
5931 break;
5934 parseGotoMark (&start_mark, pfile);
5935 parseClearMark (&start_mark);
5937 if (c == EOF)
5939 /* If we get here, this #endif ends a #ifndef
5940 that contains all of the file (aside from whitespace).
5941 Arrange not to include the file again
5942 if the macro that was tested is defined.
5944 Do not do this for the top-level file in a -include or any
5945 file in a -imacros. */
5946 struct file_name_list *ifile = pfile->all_include_files;
5948 for ( ; ifile != NULL; ifile = ifile->next)
5950 if (cstring_equal (ifile->fname, cppReader_getBufferSafe (pfile)->fname))
5952 ifile->control_macro = temp->control_macro;
5953 break;
5959 sfree (temp);
5960 output_line_command (pfile, 1, same_file);
5962 return 0;
5965 /* When an #else or #endif is found while skipping failed conditional,
5966 if -pedantic was specified, this is called to warn about text after
5967 the command name. P points to the first char after the command name. */
5969 static void
5970 validate_else (cppReader *pfile, cstring directive)
5972 int c;
5973 cppSkipHspace (pfile);
5974 c = cppReader_peekC (pfile);
5975 if (c != EOF && c != '\n')
5977 cppReader_pedwarn (pfile,
5978 message ("text following `%s' violates ANSI standard", directive));
5983 ** Get the next token, and add it to the text in pfile->token_buffer.
5984 ** Return the kind of token we got.
5987 enum cpp_token
5988 cpplib_getToken (cppReader *pfile)
5990 return cpplib_getTokenAux (pfile, FALSE);
5993 enum cpp_token
5994 cpplib_getTokenForceExpand (cppReader *pfile)
5996 return cpplib_getTokenAux (pfile, TRUE);
5999 enum cpp_token
6000 cpplib_getTokenAux (cppReader *pfile, bool forceExpand)
6002 int c, c2, c3;
6003 size_t old_written = 0;
6004 int start_line, start_column;
6005 enum cpp_token token;
6006 struct cppOptions *opts = CPPOPTIONS (pfile);
6007 cppReader_getBufferSafe (pfile)->prev = cppReader_getBufferSafe (pfile)->cur;
6009 get_next:
6010 c = cppReader_getC (pfile);
6011 DPRINTF (("Get next token: %c", c));
6013 if (c == EOF)
6015 handle_eof:
6016 if (cppReader_getBufferSafe (pfile)->seen_eof)
6018 cppBuffer *buf = cppReader_popBuffer (pfile);
6020 if (buf != cppReader_nullBuffer (pfile))
6022 goto get_next;
6024 else
6026 return CPP_EOF;
6029 else
6031 cppBuffer *next_buf = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6032 cppReader_getBufferSafe (pfile)->seen_eof = 1;
6034 if (cstring_isDefined (cppReader_getBufferSafe (pfile)->nominal_fname)
6035 && next_buf != cppReader_nullBuffer (pfile))
6037 /* We're about to return from an #include file.
6038 Emit #line information now (as part of the CPP_POP) result.
6039 But the #line refers to the file we will pop to. */
6040 cppBuffer *cur_buffer = CPPBUFFER (pfile);
6041 CPPBUFFER (pfile) = next_buf;
6042 pfile->input_stack_listing_current = 0;
6043 output_line_command (pfile, 0, leave_file);
6044 CPPBUFFER (pfile) = cur_buffer;
6046 return CPP_POP;
6049 else
6051 long newlines;
6052 struct parse_marker start_mark;
6054 switch (c)
6056 case '/':
6057 if (cppReader_peekC (pfile) == '=')
6059 goto op2;
6062 if (opts->put_out_comments)
6064 parseSetMark (&start_mark, pfile);
6067 newlines = 0;
6068 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile),
6069 &start_line, &start_column);
6070 c = skip_comment (pfile, &newlines);
6071 DPRINTF (("c = %c", c));
6072 if (opts->put_out_comments && (c == '/' || c == EOF))
6074 assertSet (&start_mark);
6075 parseClearMark (&start_mark);
6078 if (c == '/')
6079 goto randomchar;
6080 if (c == EOF)
6082 cppReader_errorWithLine (pfile, start_line, start_column,
6083 cstring_makeLiteral ("Unterminated comment"));
6084 goto handle_eof;
6086 c = '/'; /* Initial letter of comment. */
6087 return_comment:
6088 /* Comments are equivalent to spaces.
6089 For -traditional, a comment is equivalent to nothing. */
6091 if (opts->put_out_comments)
6093 enum cpp_token res;
6095 assertSet (&start_mark);
6096 res = cpp_handleComment (pfile, &start_mark);
6097 pfile->lineno += newlines;
6098 return res;
6100 else if (cppReader_isTraditional (pfile))
6102 return CPP_COMMENT;
6104 else
6106 cpplib_reserve(pfile, 1);
6107 cppReader_putCharQ (pfile, ' ');
6108 return CPP_HSPACE;
6111 case '#':
6112 if (!pfile->only_seen_white)
6114 goto randomchar;
6117 if (cppReader_handleDirective (pfile))
6119 return CPP_DIRECTIVE;
6122 pfile->only_seen_white = 0;
6123 return CPP_OTHER;
6125 case '\"':
6126 case '\'':
6127 /* A single quoted string is treated like a double -- some
6128 programs (e.g., troff) are perverse this way */
6129 cppBuffer_getLineAndColumn (cppReader_fileBuffer (pfile),
6130 &start_line, &start_column);
6131 old_written = cpplib_getWritten (pfile);
6132 string:
6133 DPRINTF (("Reading string: %c", c));
6134 cppReader_putChar (pfile, c);
6135 while (TRUE)
6137 /* evans-2003-06-07
6138 ** Because of ISO8859-1 characters in string literals, we need a special test here.
6141 if (cppReader_reachedEOF (pfile))
6144 DPRINTF (("Matches EOF!"));
6145 if (cppBuffer_isMacro (CPPBUFFER (pfile)))
6147 /* try harder: this string crosses a macro expansion
6148 boundary. This can happen naturally if -traditional.
6149 Otherwise, only -D can make a macro with an unmatched
6150 quote. */
6151 cppBuffer *next_buf
6152 = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6153 (*cppReader_getBufferSafe (pfile)->cleanup)
6154 (cppReader_getBufferSafe (pfile), pfile);
6155 CPPBUFFER (pfile) = next_buf;
6156 continue;
6159 if (!cppReader_isTraditional (pfile))
6161 cpp_setLocation (pfile);
6163 setLine (long_toInt (start_line));
6164 setColumn (long_toInt (start_column));
6166 if (pfile->multiline_string_line != long_toInt (start_line)
6167 && pfile->multiline_string_line != 0)
6169 genppllerrorhint
6170 (FLG_PREPROC,
6171 message ("Unterminated string or character constant"),
6172 message ("%q: Possible real start of unterminated constant",
6173 fileloc_unparseRaw
6174 (fileloc_filename (g_currentloc),
6175 pfile->multiline_string_line)));
6176 pfile->multiline_string_line = 0;
6178 else
6180 genppllerror
6181 (FLG_PREPROC,
6182 message ("Unterminated string or character constant"));
6185 /*@loopbreak@*/ break;
6187 else
6189 int cc = cppReader_getC (pfile);
6190 DPRINTF (("cc: %c [%d] [%d]", cc, cc, EOF));
6191 DPRINTF (("putting char: %c", cc));
6192 cppReader_putChar (pfile, cc);
6193 switch (cc)
6195 case '\n':
6196 /* Traditionally, end of line ends a string constant with
6197 no error. So exit the loop and record the new line. */
6198 if (cppReader_isTraditional (pfile))
6199 goto while2end;
6200 if (c == '\'')
6202 goto while2end;
6204 if (cppReader_isPedantic (pfile)
6205 && pfile->multiline_string_line == 0)
6207 cppReader_pedwarnWithLine
6208 (pfile, long_toInt (start_line),
6209 long_toInt (start_column),
6210 cstring_makeLiteral ("String constant runs past end of line"));
6212 if (pfile->multiline_string_line == 0)
6214 pfile->multiline_string_line = start_line;
6217 /*@switchbreak@*/ break;
6219 case '\\':
6220 cc = cppReader_getC (pfile);
6221 if (cc == '\n')
6223 /* Backslash newline is replaced by nothing at all. */
6224 pfile->lineno++; /* 2003-11-03: AMiller suggested adding this, but
6225 its not clear why it is needed. */
6226 cppReader_adjustWritten (pfile, -1);
6227 pfile->lineno++;
6229 else
6231 /* ANSI stupidly requires that in \\ the second \
6232 is *not* prevented from combining with a newline. */
6233 NEWLINE_FIX1(cc);
6234 if (cc != EOF)
6235 cppReader_putChar (pfile, cc);
6237 /*@switchbreak@*/ break;
6239 case '\"':
6240 case '\'':
6241 if (cc == c)
6242 goto while2end;
6243 /*@switchbreak@*/ break;
6247 while2end:
6248 pfile->lineno += count_newlines (pfile->token_buffer + old_written,
6249 cpplib_getPWritten (pfile));
6250 pfile->only_seen_white = 0;
6251 return c == '\'' ? CPP_CHAR : CPP_STRING;
6253 case '$':
6254 if (!opts->dollars_in_ident)
6255 goto randomchar;
6256 goto letter;
6258 case ':':
6259 if (opts->cplusplus && cppReader_peekC (pfile) == ':')
6260 goto op2;
6261 goto randomchar;
6263 case '&':
6264 case '+':
6265 case '|':
6266 NEWLINE_FIX;
6267 c2 = cppReader_peekC (pfile);
6268 if (c2 == c || c2 == '=')
6269 goto op2;
6270 goto randomchar;
6272 case '*':
6273 case '!':
6274 case '%':
6275 case '=':
6276 case '^':
6277 NEWLINE_FIX;
6278 if (cppReader_peekC (pfile) == '=')
6279 goto op2;
6280 goto randomchar;
6282 case '-':
6283 NEWLINE_FIX;
6284 c2 = cppReader_peekC (pfile);
6285 if (c2 == '-' && opts->chill)
6287 /* Chill style comment */
6288 if (opts->put_out_comments)
6290 parseSetMark (&start_mark, pfile);
6293 cppReader_forward (pfile, 1); /* Skip second '-'. */
6295 for (;;)
6297 c = cppReader_getC (pfile);
6298 if (c == EOF)
6299 /*@loopbreak@*/ break;
6300 if (c == '\n')
6302 /* Don't consider final '\n' to be part of comment. */
6303 cppReader_forward (pfile, -1);
6304 /*@loopbreak@*/ break;
6307 c = '-';
6308 goto return_comment;
6310 if (c2 == '-' || c2 == '=' || c2 == '>')
6311 goto op2;
6312 goto randomchar;
6314 case '<':
6315 if (pfile->parsing_include_directive)
6317 for (;;)
6319 cppReader_putChar (pfile, c);
6320 if (c == '>')
6321 /*@loopbreak@*/ break;
6322 c = cppReader_getC (pfile);
6323 NEWLINE_FIX1 (c);
6324 if (c == '\n' || c == EOF)
6326 cppReader_errorLit (pfile,
6327 cstring_makeLiteralTemp ("Missing '>' in \"#include <FILENAME>\""));
6328 /*@loopbreak@*/ break;
6331 return CPP_STRING;
6333 /*@fallthrough@*/
6334 case '>':
6335 NEWLINE_FIX;
6336 c2 = cppReader_peekC (pfile);
6337 if (c2 == '=')
6338 goto op2;
6339 if (c2 != c)
6340 goto randomchar;
6341 cppReader_forward (pfile, 1);
6342 cpplib_reserve (pfile, 4);
6343 cppReader_putChar (pfile, c);
6344 cppReader_putChar (pfile, c2);
6345 NEWLINE_FIX;
6346 c3 = cppReader_peekC (pfile);
6347 if (c3 == '=')
6348 cppReader_putCharQ (pfile, cppReader_getC (pfile));
6349 cppReader_nullTerminateQ (pfile);
6350 pfile->only_seen_white = 0;
6351 return CPP_OTHER;
6353 case '@':
6354 DPRINTF (("Macro @!"));
6355 if (cppReader_getBufferSafe (pfile)->has_escapes)
6357 c = cppReader_getC (pfile);
6358 DPRINTF (("got c: %c", c));
6359 if (c == '-')
6361 if (pfile->output_escapes)
6362 cppReader_puts (pfile, "@-", 2);
6363 parse_name (pfile, cppReader_getC (pfile));
6364 return CPP_NAME;
6366 else if (is_space [c])
6368 cpplib_reserve (pfile, 2);
6369 if (pfile->output_escapes)
6370 cppReader_putCharQ (pfile, '@');
6371 cppReader_putCharQ (pfile, c);
6372 return CPP_HSPACE;
6374 else
6379 if (pfile->output_escapes)
6381 cppReader_puts (pfile, "@@", 2);
6382 return CPP_OTHER;
6384 goto randomchar;
6385 case '.':
6386 NEWLINE_FIX;
6387 c2 = cppReader_peekC (pfile);
6388 if (isdigit(c2))
6390 cpplib_reserve(pfile, 2);
6391 cppReader_putCharQ (pfile, '.');
6392 c = cppReader_getC (pfile);
6393 goto number;
6396 /* FIXME - misses the case "..\\\n." */
6397 if (c2 == '.' && cpp_peekN (pfile, 1) == '.')
6399 cpplib_reserve(pfile, 4);
6400 cppReader_putCharQ (pfile, '.');
6401 cppReader_putCharQ (pfile, '.');
6402 cppReader_putCharQ (pfile, '.');
6403 cppReader_forward (pfile, 2);
6404 cppReader_nullTerminateQ (pfile);
6405 pfile->only_seen_white = 0;
6406 return CPP_3DOTS;
6408 goto randomchar;
6409 op2:
6410 token = CPP_OTHER;
6411 pfile->only_seen_white = 0;
6412 op2any: /* jumped to for \ continuations */
6413 cpplib_reserve(pfile, 3);
6414 cppReader_putCharQ (pfile, c);
6416 /* evans 2003-08-24: This is a hack to fix line output for \
6417 continuations. Someday I really should get a decent pre-processor!
6420 if (c == '\\') {
6421 (void) cppReader_getC (pfile); /* skip the newline to avoid extra lines */
6422 } else {
6423 cppReader_putCharQ (pfile, cppReader_getC (pfile));
6426 cppReader_nullTerminateQ (pfile);
6427 return token;
6429 case 'L':
6430 NEWLINE_FIX;
6431 c2 = cppReader_peekC (pfile);
6432 if ((c2 == '\'' || c2 == '\"') && !cppReader_isTraditional (pfile))
6434 cppReader_putChar (pfile, c);
6435 c = cppReader_getC (pfile);
6436 goto string;
6438 goto letter;
6440 case '0': case '1': case '2': case '3': case '4':
6441 case '5': case '6': case '7': case '8': case '9':
6442 number:
6443 c2 = '.';
6444 for (;;)
6446 cpplib_reserve (pfile, 2);
6447 cppReader_putCharQ (pfile, c);
6448 NEWLINE_FIX;
6449 c = cppReader_peekC (pfile);
6450 if (c == EOF)
6451 /*@loopbreak@*/ break;
6452 if (!is_idchar[c] && c != '.'
6453 && ((c2 != 'e' && c2 != 'E'
6454 && ((c2 != 'p' && c2 != 'P') || cppReader_isC89 (pfile)))
6455 || (c != '+' && c != '-')))
6456 /*@loopbreak@*/ break;
6457 cppReader_forward (pfile, 1);
6458 c2= c;
6461 cppReader_nullTerminateQ (pfile);
6462 pfile->only_seen_white = 0;
6463 return CPP_NUMBER;
6465 case 'b': case 'c': case 'd': case 'h': case 'o':
6466 case 'B': case 'C': case 'D': case 'H': case 'O':
6467 if (opts->chill && cppReader_peekC (pfile) == '\'')
6469 pfile->only_seen_white = 0;
6470 cpplib_reserve (pfile, 2);
6471 cppReader_putCharQ (pfile, c);
6472 cppReader_putCharQ (pfile, '\'');
6473 cppReader_forward (pfile, 1);
6474 for (;;)
6476 c = cppReader_getC (pfile);
6477 if (c == EOF)
6478 goto chill_number_eof;
6479 if (!is_idchar[c])
6481 if (c == '\\' && cppReader_peekC (pfile) == '\n')
6483 cppReader_forward (pfile, 2);
6484 continue;
6486 /*@loopbreak@*/ break;
6488 cppReader_putChar (pfile, c);
6490 if (c == '\'')
6492 cpplib_reserve (pfile, 2);
6493 cppReader_putCharQ (pfile, c);
6494 cppReader_nullTerminateQ (pfile);
6495 return CPP_STRING;
6497 else
6499 cppReader_forward (pfile, -1);
6500 chill_number_eof:
6501 cppReader_nullTerminate (pfile);
6502 return CPP_NUMBER;
6505 else
6506 goto letter;
6507 case '_':
6508 case 'a': case 'e': case 'f': case 'g': case 'i': case 'j':
6509 case 'k': case 'l': case 'm': case 'n': case 'p': case 'q':
6510 case 'r': case 's': case 't': case 'u': case 'v': case 'w':
6511 case 'x': case 'y': case 'z':
6512 case 'A': case 'E': case 'F': case 'G': case 'I': case 'J':
6513 case 'K': case 'M': case 'N': case 'P': case 'Q': case 'R':
6514 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
6515 case 'Y': case 'Z':
6516 letter:
6518 hashNode hp;
6519 char *ident;
6520 size_t before_name_written = cpplib_getWritten (pfile);
6521 size_t ident_len;
6522 parse_name (pfile, c);
6523 pfile->only_seen_white = 0;
6525 if (pfile->no_macro_expand)
6527 DPRINTF (("Not expanding: %s", pfile->token_buffer));
6528 return CPP_NAME;
6531 ident = pfile->token_buffer + before_name_written;
6532 DPRINTF (("Ident: %s", ident));
6534 ident_len = size_fromInt ((cpplib_getPWritten (pfile)) - ident);
6536 hp = cpphash_lookupExpand (ident, size_toInt (ident_len), -1, forceExpand);
6538 if (hp == NULL)
6540 DPRINTF (("No expand: %s %d", ident, ident_len));
6541 return CPP_NAME;
6544 if (hp->type == T_DISABLED)
6546 DPRINTF (("Disabled!"));
6548 if (pfile->output_escapes)
6549 { /* Return "@-IDENT", followed by '\0'. */
6550 int i;
6551 cpplib_reserve (pfile, 3);
6552 ident = pfile->token_buffer + before_name_written;
6553 cppReader_adjustWritten (pfile, 2);
6555 for (i = size_toInt (ident_len); i >= 0; i--)
6557 ident[i+2] = ident[i];
6560 ident[0] = '@';
6561 ident[1] = '-';
6563 return CPP_NAME;
6567 ** If macro wants an arglist, verify that a '(' follows.
6568 ** first skip all whitespace, copying it to the output
6569 ** after the macro name. Then, if there is no '(',
6570 ** decide this is not a macro call and leave things that way.
6573 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
6575 struct parse_marker macro_mark;
6576 int is_macro_call;
6578 DPRINTF (("Arglist macro!"));
6581 ** evans 2002-07-03: Moved this here (from below).
6582 ** This bug caused necessary whitespace to be lost
6583 ** when parsing parameterized macros without parameters.
6586 parseSetMark (&macro_mark, pfile);
6588 while (cppBuffer_isMacro (CPPBUFFER (pfile)))
6590 cppBuffer *next_buf;
6591 cppSkipHspace (pfile);
6592 if (cppReader_peekC (pfile) != EOF)
6594 DPRINTF (("Peeking!"));
6595 /*@loopbreak@*/ break;
6598 next_buf = cppBuffer_prevBuffer (cppReader_getBufferSafe (pfile));
6599 (*cppReader_getBufferSafe (pfile)->cleanup) (cppReader_getBufferSafe (pfile), pfile);
6600 CPPBUFFER (pfile) = next_buf;
6603 /* parseSetMark (&macro_mark, pfile); */
6605 for (;;)
6607 cppSkipHspace (pfile);
6608 c = cppReader_peekC (pfile);
6609 DPRINTF (("c: %c", c));
6610 is_macro_call = c == '(';
6611 if (c != '\n')
6612 /*@loopbreak@*/ break;
6613 cppReader_forward (pfile, 1);
6616 if (!is_macro_call)
6618 parseGotoMark (&macro_mark, pfile);
6621 parseClearMark (&macro_mark);
6623 if (!is_macro_call)
6625 DPRINTF (("not macro call!"));
6626 return CPP_NAME;
6630 /* This is now known to be a macro call. */
6632 /* it might not actually be a macro. */
6633 if (hp->type != T_MACRO)
6635 size_t xbuf_len;
6636 char *xbuf;
6638 cppReader_setWritten (pfile, before_name_written);
6639 special_symbol (hp, pfile);
6640 xbuf_len = cpplib_getWritten (pfile) - before_name_written;
6641 xbuf = (char *) dmalloc (xbuf_len + 1);
6642 cppReader_setWritten (pfile, before_name_written);
6643 memcpy (xbuf, cpplib_getPWritten (pfile), xbuf_len + 1);
6644 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
6646 else
6649 ** Expand the macro, reading arguments as needed,
6650 ** and push the expansion on the input stack.
6653 cpplib_macroExpand (pfile, hp);
6654 cppReader_setWritten (pfile, before_name_written);
6657 /* An extra "@ " is added to the end of a macro expansion
6658 to prevent accidental token pasting. We prefer to avoid
6659 unneeded extra spaces (for the sake of cpp-using tools like
6660 imake). Here we remove the space if it is safe to do so. */
6662 llassert (pfile->buffer->rlimit != NULL);
6664 if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
6665 && pfile->buffer->rlimit[-2] == '@'
6666 && pfile->buffer->rlimit[-1] == ' ')
6668 int c1 = pfile->buffer->rlimit[-3];
6669 int cl2 = cpplib_bufPeek (cppBuffer_prevBuffer (CPPBUFFER (pfile)));
6671 if (cl2 == EOF || !unsafe_chars ((char) c1, (char) cl2))
6672 pfile->buffer->rlimit -= 2;
6675 goto get_next;
6678 case ' ': case '\t': case '\v': case '\r':
6679 for (;;)
6681 cppReader_putChar (pfile, c);
6682 c = cppReader_peekC (pfile);
6683 if (c == EOF || !is_hor_space[c])
6684 /*@loopbreak@*/ break;
6685 cppReader_forward (pfile, 1);
6687 return CPP_HSPACE;
6689 case '\\':
6690 c2 = cppReader_peekC (pfile);
6691 /* allow other stuff here if a flag is set? */
6692 DPRINTF (("Got continuation!"));
6693 if (c2 != '\n')
6694 goto randomchar;
6695 token = CPP_HSPACE;
6696 goto op2any;
6698 case '\n':
6699 cppReader_putChar (pfile, c);
6700 if (pfile->only_seen_white == 0)
6701 pfile->only_seen_white = 1;
6702 pfile->lineno++;
6703 output_line_command (pfile, 1, same_file);
6704 return CPP_VSPACE;
6706 case '(': token = CPP_LPAREN; goto char1;
6707 case ')': token = CPP_RPAREN; goto char1;
6708 case '{': token = CPP_LBRACE; goto char1;
6709 case '}': token = CPP_RBRACE; goto char1;
6710 case ',': token = CPP_COMMA; goto char1;
6711 case ';': token = CPP_SEMICOLON; goto char1;
6713 randomchar:
6714 default:
6715 token = CPP_OTHER;
6716 char1:
6717 pfile->only_seen_white = 0;
6718 cppReader_putChar (pfile, c);
6719 return token;
6723 BADBRANCH;
6724 /*@notreached@*/
6727 /* Parse an identifier starting with C. */
6729 void
6730 parse_name (cppReader *pfile, int c)
6732 for (;;)
6734 if (!is_idchar[c])
6736 if (c == '\\' && cppReader_peekC (pfile) == '\n')
6738 cppReader_forward (pfile, 2);
6739 continue;
6742 cppReader_forward (pfile, -1);
6743 break;
6746 if (c == '$' && cppReader_isPedantic (pfile))
6748 cppReader_pedwarnLit (pfile,
6749 cstring_makeLiteralTemp ("`$' in identifier"));
6752 cpplib_reserve(pfile, 2); /* One more for final NUL. */
6753 cppReader_putCharQ (pfile, c);
6754 c = cppReader_getC (pfile);
6756 if (c == EOF)
6757 break;
6760 cppReader_nullTerminateQ (pfile);
6763 /* The file_name_map structure holds a mapping of file names for a
6764 particular directory. This mapping is read from the file named
6765 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
6766 map filenames on a file system with severe filename restrictions,
6767 such as DOS. The format of the file name map file is just a series
6768 of lines with two tokens on each line. The first token is the name
6769 to map, and the second token is the actual name to use. */
6771 struct file_name_map
6773 struct file_name_map *map_next;
6774 cstring map_from;
6775 cstring map_to;
6778 /*@constant observer char *FILE_NAME_MAP_FILE*/
6779 #define FILE_NAME_MAP_FILE "header.gcc"
6781 /* Read a space delimited string of unlimited length from a stdio
6782 file. */
6784 static cstring read_filename_string (int ch, /*:open:*/ FILE *f)
6786 char *alloc, *set;
6787 size_t len;
6789 len = 20;
6790 set = alloc = dmalloc (len + 1);
6792 if (!is_space[ch])
6794 *set++ = ch;
6795 while ((ch = getc (f)) != EOF && ! is_space[ch])
6797 if (set - alloc == size_toInt (len))
6799 len *= 2;
6800 alloc = drealloc (alloc, len + 1);
6801 set = alloc + len / 2;
6802 /*@-branchstate@*/ }
6804 *set++ = ch;
6805 } /*@=branchstate@*/
6807 *set = '\0';
6808 check (ungetc (ch, f) != EOF);
6810 return cstring_fromChars (alloc);
6813 /* This structure holds a linked list of file name maps, one per directory. */
6815 struct file_name_map_list
6817 /*@only@*/ struct file_name_map_list *map_list_next;
6818 /*@only@*/ cstring map_list_name;
6819 /*@null@*/ struct file_name_map *map_list_map;
6822 /* Read the file name map file for DIRNAME. */
6824 static struct file_name_map *
6825 read_name_map (cppReader *pfile, cstring dirname)
6827 struct file_name_map_list *map_list_ptr;
6828 cstring name;
6829 FILE *f;
6831 for (map_list_ptr = CPPOPTIONS (pfile)->map_list;
6832 map_list_ptr != NULL;
6833 map_list_ptr = map_list_ptr->map_list_next)
6835 if (cstring_equal (map_list_ptr->map_list_name, dirname))
6837 return map_list_ptr->map_list_map;
6841 map_list_ptr = (struct file_name_map_list *) dmalloc (sizeof (*map_list_ptr));
6842 map_list_ptr->map_list_name = cstring_copy (dirname);
6843 map_list_ptr->map_list_map = NULL;
6845 name = cstring_copy (dirname);
6847 if (cstring_length (dirname) > 0)
6849 name = cstring_appendChar (name, CONNECTCHAR);
6852 name = cstring_concatFree1 (name, cstring_makeLiteralTemp (FILE_NAME_MAP_FILE));
6854 f = fileTable_openReadFile (context_fileTable (), name);
6855 cstring_free (name);
6857 if (f == NULL)
6859 map_list_ptr->map_list_map = NULL;
6861 else
6863 int ch;
6865 while ((ch = getc (f)) != EOF)
6867 cstring from, to;
6868 struct file_name_map *ptr;
6870 if (is_space[ch])
6872 continue;
6875 from = read_filename_string (ch, f);
6876 while ((ch = getc (f)) != EOF && is_hor_space[ch])
6881 to = read_filename_string (ch, f);
6883 ptr = (struct file_name_map *) dmalloc (sizeof (*ptr));
6884 ptr->map_from = from;
6886 /* Make the real filename absolute. */
6887 if (cstring_length (to) > 1
6888 && osd_isConnectChar (cstring_firstChar (to)))
6890 ptr->map_to = to;
6892 else
6894 ptr->map_to = cstring_copy (dirname);
6895 ptr->map_to = cstring_appendChar (ptr->map_to, CONNECTCHAR);
6896 ptr->map_to = cstring_concatFree (ptr->map_to, to);
6899 ptr->map_next = map_list_ptr->map_list_map;
6900 map_list_ptr->map_list_map = ptr;
6902 while ((ch = getc (f)) != '\n')
6904 if (ch == EOF)
6906 /*@innerbreak@*/ break;
6911 assertSet (map_list_ptr->map_list_map);
6912 check (fileTable_closeFile (context_fileTable (),f) == 0);
6915 map_list_ptr->map_list_next = pfile->opts->map_list;
6916 pfile->opts->map_list = map_list_ptr;
6918 return map_list_ptr->map_list_map;
6921 /* Try to open include file FILENAME. SEARCHPTR is the directory
6922 being tried from the include file search path. This function maps
6923 filenames on file systems based on information read by
6924 read_name_map. */
6926 static int
6927 open_include_file (cppReader *pfile,
6928 cstring fname,
6929 struct file_name_list *searchptr)
6931 char *filename = cstring_toCharsSafe (fname);
6932 struct file_name_map *map;
6933 char *from;
6934 char *p, *dir;
6936 cstring_markOwned (fname);
6938 cpp_setLocation (pfile);
6940 if (context_getFlag (FLG_NEVERINCLUDE))
6942 if (isHeaderFile (fname))
6944 return SKIP_INCLUDE;
6948 if ((searchptr != NULL) && ! searchptr->got_name_map)
6950 searchptr->name_map = read_name_map (pfile,
6951 !cstring_isEmpty (searchptr->fname)
6952 ? searchptr->fname :
6953 cstring_makeLiteralTemp ("."));
6954 searchptr->got_name_map = 1;
6957 /* First check the mapping for the directory we are using. */
6959 if ((searchptr != NULL)
6960 && (searchptr->name_map != NULL))
6962 from = filename;
6964 if (!cstring_isEmpty (searchptr->fname))
6966 from += cstring_length (searchptr->fname) + 1;
6969 for (map = searchptr->name_map;
6970 map != NULL;
6971 map = map->map_next)
6973 if (cstring_equal (map->map_from, cstring_fromChars (from)))
6976 ** Found a match. Check if the file should be skipped
6979 if (cpp_skipIncludeFile (map->map_to))
6981 return SKIP_INCLUDE;
6983 else
6985 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
6992 ** Try to find a mapping file for the particular directory we are
6993 ** looking in. Thus #include <sys/types.h> will look up sys/types.h
6994 ** in /usr/include/header.gcc and look up types.h in
6995 ** /usr/include/sys/header.gcc.
6998 p = strrchr (filename, CONNECTCHAR);
7000 if (p == NULL)
7002 p = filename;
7005 if ((searchptr != NULL)
7006 && (cstring_isDefined (searchptr->fname))
7007 && (size_toInt (cstring_length (searchptr->fname)) == p - filename)
7008 && !strncmp (cstring_toCharsSafe (searchptr->fname),
7009 filename,
7010 size_fromInt (p - filename)))
7012 /* filename is in SEARCHPTR, which we've already checked. */
7014 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
7016 return SKIP_INCLUDE;
7018 else
7020 return cpp_openIncludeFile (filename);
7024 if (p == filename)
7026 dir = mstring_copy (".");
7027 from = filename;
7029 else
7031 dir = (char *) dmalloc (size_fromInt (p - filename + 1));
7032 memcpy (dir, filename, size_fromInt (p - filename));
7033 dir[p - filename] = '\0';
7034 from = p + 1;
7037 for (map = read_name_map (pfile, cstring_fromChars (dir));
7038 map != NULL;
7039 map = map->map_next)
7041 if (cstring_equal (map->map_from, cstring_fromChars (from)))
7043 sfree (dir);
7045 if (cpp_skipIncludeFile (map->map_to))
7047 return SKIP_INCLUDE;
7049 else
7051 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
7056 sfree (dir);
7058 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
7060 return SKIP_INCLUDE;
7062 else
7064 return cpp_openIncludeFile (filename);
7068 /* Process the contents of include file FNAME, already open on descriptor F,
7069 with output to OP.
7070 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
7071 "system" include directories (as decided by the `is_system_include'
7072 function above).
7073 DIRPTR is the link in the dir path through which this file was found,
7074 or 0 if the file name was absolute or via the current directory.
7075 Return 1 on success, 0 on failure.
7077 The caller is responsible for the cppReader_pushBuffer. */
7079 static int
7080 finclude (cppReader *pfile, int f,
7081 cstring fname,
7082 bool system_header_p,
7083 /*@dependent@*/ struct file_name_list *dirptr)
7085 mode_t st_mode; /* was __mode_t */
7086 size_t st_size;
7087 long i;
7088 int length = 0;
7089 cppBuffer *fp; /* For input stack frame */
7091 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
7093 cppReader_perrorWithName (pfile, fname);
7094 check (close (f) == 0);
7095 (void) cppReader_popBuffer (pfile);
7096 /*@-mustfree@*/
7097 return 0;
7098 /*@=mustfree@*/
7101 fp = cppReader_getBufferSafe (pfile);
7103 /*@-temptrans@*/ /* fname shouldn't really be temp */
7104 fp->nominal_fname = fp->fname = fname;
7105 /*@=temptrans@*/
7107 fp->dir = dirptr;
7108 fp->system_header_p = system_header_p;
7109 fp->lineno = 1;
7110 fp->colno = 1;
7111 fp->cleanup = cppReader_fileCleanup;
7113 if (S_ISREG (st_mode))
7115 sfree (fp->buf);
7116 fp->buf = (char *) dmalloc (st_size + 2);
7117 fp->alimit = fp->buf + st_size + 2;
7118 fp->cur = fp->buf;
7120 /* Read the file contents, knowing that st_size is an upper bound
7121 on the number of bytes we can read. */
7122 length = safe_read (f, fp->buf, size_toInt (st_size));
7123 fp->rlimit = fp->buf + length;
7124 if (length < 0) goto nope;
7126 else if (S_ISDIR (st_mode))
7128 cppReader_error (pfile,
7129 message ("Directory specified where file is expected: %s", fname));
7130 check (close (f) == 0);
7131 return 0;
7133 else
7136 ** Cannot count its file size before reading.
7137 ** First read the entire file into heap and
7138 ** copy them into buffer on stack.
7141 size_t bsize = 2000;
7143 st_size = 0;
7145 sfree (fp->buf);
7146 fp->buf = (char *) dmalloc (bsize + 2);
7148 for (;;) {
7149 i = safe_read (f, fp->buf + st_size, size_toInt (bsize - st_size));
7151 if (i < 0)
7152 goto nope; /* error! */
7153 st_size += i;
7155 if (st_size != bsize)
7157 break; /* End of file */
7160 bsize *= 2;
7161 fp->buf = (char *) drealloc (fp->buf, bsize + 2);
7164 fp->cur = fp->buf;
7165 length = size_toInt (st_size);
7168 if ((length > 0 && fp->buf[length - 1] != '\n')
7169 /* Backslash-newline at end is not good enough. */
7170 || (length > 1 && fp->buf[length - 2] == '\\')) {
7171 fp->buf[length++] = '\n';
7174 fp->buf[length] = '\0';
7175 fp->rlimit = fp->buf + length;
7177 /* Close descriptor now, so nesting does not use lots of descriptors. */
7178 check (close (f) == 0);
7180 /* Must do this before calling trigraph_pcp, so that the correct file name
7181 will be printed in warning messages. */
7183 pfile->input_stack_listing_current = 0;
7184 return 1;
7186 nope:
7188 cppReader_perrorWithName (pfile, fname);
7189 check (close (f) == 0);
7190 sfree (fp->buf);
7191 return 1;
7194 void
7195 cpplib_init (cppReader *pfile)
7197 memset ((char *) pfile, 0, sizeof (*pfile));
7199 pfile->get_token = cpplib_getToken;
7200 pfile->token_buffer_size = 200;
7201 pfile->token_buffer = (char *) dmalloc (pfile->token_buffer_size);
7202 pfile->all_include_files = NULL;
7204 assertSet (pfile);
7206 cppReader_setWritten (pfile, 0);
7208 pfile->system_include_depth = 0;
7209 pfile->max_include_len = 0;
7210 pfile->timebuf = NULL;
7211 pfile->only_seen_white = 1;
7213 pfile->buffer = cppReader_nullBuffer (pfile);
7216 void
7217 cppReader_finish (/*@unused@*/ cppReader *pfile)
7222 /* Free resources used by PFILE.
7223 This is the cppReader 'finalizer' or 'destructor' (in C++ terminology). */
7225 void
7226 cppCleanup (/*@special@*/ cppReader *pfile)
7227 /*@uses pfile@*/
7228 /*@releases pfile@*/
7230 DPRINTF (("cppCleanup!"));
7232 while (CPPBUFFER (pfile) != cppReader_nullBuffer (pfile))
7234 (void) cppReader_popBuffer (pfile);
7237 if (pfile->token_buffer != NULL)
7239 sfree (pfile->token_buffer);
7240 pfile->token_buffer = NULL;
7243 while (pfile->if_stack != NULL)
7245 cppIfStackFrame *temp = pfile->if_stack;
7246 pfile->if_stack = temp->next;
7247 sfree (temp);
7250 while (pfile->all_include_files != NULL)
7252 struct file_name_list *temp = pfile->all_include_files;
7253 pfile->all_include_files = temp->next;
7254 /*@-dependenttrans@*/
7255 cstring_free (temp->fname);
7256 /*@=dependenttrans@*/
7257 sfree (temp);
7260 /* evans 2002-07-12 */
7261 while (pfile->opts->map_list != NULL)
7263 struct file_name_map_list *temp = pfile->opts->map_list;
7264 pfile->opts->map_list = pfile->opts->map_list->map_list_next;
7265 cstring_free (temp->map_list_name);
7266 sfree (temp);
7269 while (pfile->opts->include != NULL)
7271 struct file_name_list *temp = pfile->opts->include;
7272 pfile->opts->include = pfile->opts->include->next;
7273 /* cstring_free (temp->fname); */
7274 sfree (temp);
7277 sfree (pfile->opts);
7278 pfile->opts = NULL;
7279 cppReader_hashCleanup ();
7283 ** Get the file-mode and data size of the file open on FD
7284 ** and store them in *MODE_POINTER and *SIZE_POINTER.
7287 static int
7288 file_size_and_mode (int fd, mode_t *mode_pointer, size_t *size_pointer)
7290 struct stat sbuf;
7292 if (fstat (fd, &sbuf) < 0) {
7293 *mode_pointer = 0;
7294 *size_pointer = 0;
7295 /*@-compdestroy@*/ /* possibly spurious warnings here (or memory leak) */
7296 return (-1);
7297 /*@=compdestroy@*/
7300 if (mode_pointer != NULL)
7302 /*@-type@*/ /* confusion between __mode_t and mode_t types */
7303 *mode_pointer = sbuf.st_mode;
7304 /*@=type@*/
7307 if (size_pointer != NULL)
7309 *size_pointer = (size_t) sbuf.st_size;
7312 /*@-compdestroy@*/ /* possibly spurious warnings here (or memory leak) */
7313 return 0;
7314 /*@=compdestroy@*/
7317 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
7318 retrying if necessary. Return a negative value if an error occurs,
7319 otherwise return the actual number of bytes read,
7320 which must be LEN unless end-of-file was reached. */
7322 static int safe_read (int desc, char *ptr, int len)
7324 int left = len;
7326 while (left > 0)
7328 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
7329 /*@-compdef@*/ /* ptr is an out parameter */
7330 int nchars = _read (desc, ptr, (unsigned) left);
7331 /*@=compdef@*/
7332 # else
7333 ssize_t nchars = read (desc, ptr, size_fromInt (left));
7334 # endif
7336 if (nchars < 0)
7338 #ifdef EINTR
7339 if (errno == EINTR)
7340 continue;
7341 #endif
7342 return (int) nchars;
7345 if (nchars == 0) {
7346 break;
7349 ptr += nchars;
7350 left -= nchars;
7353 return len - left;
7356 /* Initialize PMARK to remember the current position of PFILE. */
7358 void
7359 parseSetMark (struct parse_marker *pmark, cppReader *pfile)
7361 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7363 pmark->next = pbuf->marks;
7364 /*@-temptrans@*/
7365 pbuf->marks = pmark;
7366 /*@=temptrans@*/
7368 pmark->buf = pbuf;
7369 pmark->position = pbuf->cur - pbuf->buf;
7370 DPRINTF (("set mark: %d / %s", pmark->position, pbuf->cur));
7373 /* Cleanup PMARK - we no longer need it. */
7375 void parseClearMark (struct parse_marker *pmark)
7377 struct parse_marker **pp = &pmark->buf->marks;
7379 for (; ; pp = &(*pp)->next)
7381 llassert (*pp != NULL);
7382 if (*pp == pmark) break;
7385 *pp = pmark->next;
7388 /* Backup the current position of PFILE to that saved in PMARK. */
7390 void
7391 parseGotoMark (struct parse_marker *pmark, cppReader *pfile)
7393 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7395 if (pbuf != pmark->buf)
7397 cpp_setLocation (pfile);
7398 llfatalbug (cstring_makeLiteral ("Internal error parseGotoMark"));
7401 llassert (pbuf->buf != NULL);
7402 pbuf->cur = pbuf->buf + pmark->position;
7403 DPRINTF (("goto mark: %d / %s", pmark->position, pbuf->cur));
7406 /* Reset PMARK to point to the current position of PFILE. (Same
7407 as parseClearMark (PMARK), parseSetMark (PMARK, PFILE) but faster. */
7409 void
7410 parseMoveMark (struct parse_marker *pmark, cppReader *pfile)
7412 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
7414 if (pbuf != pmark->buf)
7416 cpp_setLocation (pfile);
7417 llfatalerror (cstring_makeLiteral ("Internal error parseMoveMark"));
7420 pmark->position = pbuf->cur - pbuf->buf;
7421 DPRINTF (("move mark: %d", pmark->position));
7424 void cpplib_initializeReader (cppReader *pfile) /* Must be done after library is loaded. */
7426 struct cppOptions *opts = CPPOPTIONS (pfile);
7427 cstring xp;
7429 /* The code looks at the defaults through this pointer, rather than through
7430 the constant structure above. This pointer gets changed if an environment
7431 variable specifies other defaults. */
7433 struct default_include *include_defaults = include_defaults_array;
7435 /* Add dirs from INCLUDEPATH_VAR after dirs from -I. */
7436 /* There seems to be confusion about what CPATH should do,
7437 so for the moment it is not documented. */
7438 /* Some people say that CPATH should replace the standard include dirs,
7439 but that seems pointless: it comes before them, so it overrides them
7440 anyway. */
7442 xp = osd_getEnvironmentVariable (INCLUDEPATH_VAR);
7444 if (cstring_isDefined (xp) && !opts->no_standard_includes)
7446 path_include (pfile, cstring_toCharsSafe (xp));
7449 /* Now that dollars_in_ident is known, initialize is_idchar. */
7450 initialize_char_syntax (opts);
7452 /* CppReader_Install __LINE__, etc. Must follow initialize_char_syntax
7453 and option processing. */
7455 initialize_builtins (pfile);
7457 /* Do standard #defines and assertions
7458 that identify system and machine type. */
7460 if (!opts->inhibit_predefs) {
7461 char *p = (char *) dmalloc (strlen (predefs) + 1);
7462 strcpy (p, predefs);
7464 while (*p)
7466 char *q;
7468 while (*p == ' ' || *p == '\t')
7470 p++;
7473 /* Handle -D options. */
7474 if (p[0] == '-' && p[1] == 'D')
7476 q = &p[2];
7478 while (*p && *p != ' ' && *p != '\t')
7480 p++;
7483 if (*p != 0)
7485 *p++= 0;
7488 if (opts->debug_output)
7490 output_line_command (pfile, 0, same_file);
7493 cppReader_define (pfile, q);
7495 while (*p == ' ' || *p == '\t')
7497 p++;
7500 else
7502 abort ();
7506 sfree (p);
7509 opts->done_initializing = 1;
7511 { /* Read the appropriate environment variable and if it exists
7512 replace include_defaults with the listed path. */
7513 char *epath = 0;
7514 #ifdef __CYGWIN32__
7515 char *win32epath;
7516 int win32_buf_size = 0; /* memory we need to allocate */
7517 #endif
7519 if (opts->cplusplus)
7521 epath = getenv ("CPLUS_INCLUDE_PATH");
7523 else
7525 epath = getenv ("C_INCLUDE_PATH");
7529 ** If the environment var for this language is set,
7530 ** add to the default list of include directories.
7533 if (epath != NULL) {
7534 char *nstore = (char *) dmalloc (strlen (epath) + 2);
7535 int num_dirs;
7536 char *startp, *endp;
7538 #ifdef __CYGWIN32__
7539 /* if we have a posix path list, convert to win32 path list */
7540 if (cygwin32_posix_path_list_p (epath))
7542 win32_buf_size = cygwin32_posix_to_win32_path_list_buf_size (epath);
7543 win32epath = (char *) dmalloc /*@i4@*/ (win32_buf_size);
7544 cygwin32_posix_to_win32_path_list (epath, win32epath);
7545 epath = win32epath;
7547 #endif
7548 for (num_dirs = 1, startp = epath; *startp; startp++)
7550 if (*startp == PATH_SEPARATOR)
7551 num_dirs++;
7554 /*@-sizeoftype@*/
7555 include_defaults
7556 = (struct default_include *) dmalloc ((num_dirs
7557 * sizeof (struct default_include))
7558 + sizeof (include_defaults_array));
7559 /*@=sizeoftype@*/
7561 startp = endp = epath;
7562 num_dirs = 0;
7563 while (1) {
7564 /* Handle cases like c:/usr/lib:d:/gcc/lib */
7565 if ((*endp == PATH_SEPARATOR) || *endp == 0)
7567 strncpy (nstore, startp, size_fromInt (endp - startp));
7568 if (endp == startp)
7570 strcpy (nstore, ".");
7572 else
7574 nstore[endp-startp] = '\0';
7577 include_defaults[num_dirs].fname = cstring_fromCharsNew (nstore);
7578 include_defaults[num_dirs].cplusplus = opts->cplusplus;
7579 include_defaults[num_dirs].cxx_aware = 1;
7580 num_dirs++;
7582 if (*endp == '\0')
7584 break;
7586 endp = startp = endp + 1;
7588 else
7590 endp++;
7593 /* Put the usual defaults back in at the end. */
7594 memcpy ((char *) &include_defaults[num_dirs],
7595 (char *) include_defaults_array,
7596 sizeof (include_defaults_array));
7598 sfree (nstore);
7599 /*@-branchstate@*/ } /*@=branchstate@*/
7602 cppReader_appendIncludeChain (pfile, opts->before_system,
7603 opts->last_before_system);
7605 opts->first_system_include = opts->before_system;
7607 /* Unless -fnostdinc,
7608 tack on the standard include file dirs to the specified list */
7610 if (!opts->no_standard_includes) {
7611 struct default_include *p = include_defaults;
7612 char *specd_prefix = opts->include_prefix;
7613 char *default_prefix = mstring_copy (GCC_INCLUDE_DIR);
7614 size_t default_len = 0;
7616 /* Remove the `include' from /usr/local/lib/gcc.../include. */
7617 if (default_prefix != NULL) {
7618 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
7619 default_len = strlen (default_prefix) - 7;
7620 default_prefix[default_len] = 0;
7624 /* Search "translated" versions of GNU directories.
7625 These have /usr/local/lib/gcc... replaced by specd_prefix. */
7626 if (specd_prefix != 0 && default_len != 0)
7627 for (p = include_defaults; p->fname != NULL; p++) {
7628 /* Some standard dirs are only for C++. */
7629 if (!p->cplusplus
7630 || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
7631 /* Does this dir start with the prefix? */
7632 llassert (default_prefix != NULL);
7634 if (!strncmp (cstring_toCharsSafe (p->fname), default_prefix, default_len))
7636 /* Yes; change prefix and add to search list. */
7637 struct file_name_list *nlist
7638 = (struct file_name_list *) dmalloc (sizeof (*nlist));
7639 size_t this_len = strlen (specd_prefix) + cstring_length (p->fname) - default_len;
7640 char *str = (char *) dmalloc (this_len + 1);
7641 strcpy (str, specd_prefix);
7642 strcat (str, cstring_toCharsSafe (p->fname) + default_len);
7644 nlist->next = NULL;
7645 nlist->fname = cstring_fromChars (str);
7646 nlist->control_macro = 0;
7647 nlist->c_system_include_path = !p->cxx_aware;
7648 nlist->got_name_map = 0;
7650 if (opts->first_system_include == 0)
7652 opts->first_system_include = nlist;
7655 cppReader_addIncludeChain (pfile, nlist);
7660 /* Search ordinary names for GNU include directories. */
7662 for (p = include_defaults; p->fname != NULL; p++)
7664 /* Some standard dirs are only for C++. */
7665 if (!p->cplusplus
7666 || (opts->cplusplus && !opts->no_standard_cplusplus_includes))
7668 struct file_name_list *nlist
7669 = (struct file_name_list *) dmalloc (sizeof (*nlist));
7670 nlist->control_macro = 0;
7671 nlist->c_system_include_path = !p->cxx_aware;
7672 nlist->fname = p->fname;
7673 nlist->got_name_map = 0;
7674 nlist->next = NULL;
7676 /* Spurious warning reported for opts->first_system_include */
7677 /*@-usereleased@*/ if (opts->first_system_include == NULL)
7679 opts->first_system_include = nlist;
7681 /*@=usereleased@*/
7683 cppReader_addIncludeChain (pfile, nlist);
7686 sfree (default_prefix);
7689 /* Tack the after_include chain at the end of the include chain. */
7690 cppReader_appendIncludeChain (pfile, opts->after_include,
7691 opts->last_after_include);
7693 /* Spurious warnings for opts->first_system_include */
7694 /*@-usereleased@*/
7695 if (opts->first_system_include == NULL)
7697 opts->first_system_include = opts->after_include;
7699 /*@=usereleased@*/
7701 /* With -v, print the list of dirs to search. */
7702 if (opts->verbose) {
7703 struct file_name_list *p;
7704 fprintf (stderr, "#include \"...\" search starts here:\n");
7706 for (p = opts->include; p != NULL; p = p->next) {
7707 if (p == opts->first_bracket_include)
7708 fprintf (stderr, "#include <...> search starts here:\n");
7710 fprintf (stderr, " %s\n", cstring_toCharsSafe (p->fname));
7712 fprintf (stderr, "End of search list.\n");
7716 int cppReader_startProcess (cppReader *pfile, cstring fname)
7718 cppBuffer *fp;
7719 int f;
7720 struct cppOptions *opts = CPPOPTIONS (pfile);
7722 fp = cppReader_pushBuffer (pfile, NULL, 0);
7724 if (fp == NULL)
7726 return 0;
7729 if (opts->in_fname == NULL)
7731 opts->in_fname = cstring_makeLiteralTemp ("");
7734 fp->fname = opts->in_fname;
7735 fp->nominal_fname = fp->fname;
7736 fp->lineno = 0;
7738 /* Copy the entire contents of the main input file into
7739 the stacked input buffer previously allocated for it. */
7741 if (cstring_isEmpty (fname))
7743 fname = cstring_makeLiteralTemp ("");
7744 f = 0;
7746 else if ((f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666)) < 0)
7748 cppReader_error (pfile,
7749 message ("Error opening %s for reading: %s",
7750 fname, lldecodeerror (errno)));
7752 return 0;
7754 else
7759 if (finclude (pfile, f, fname, 0, NULL))
7761 output_line_command (pfile, 0, same_file);
7764 return 1;
7767 static /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_getBuffer (cppReader *pfile)
7769 return pfile->buffer;
7772 /*@exposed@*/ cppBuffer *cppReader_getBufferSafe (cppReader *pfile)
7774 llassert (pfile->buffer != NULL);
7775 return pfile->buffer;
7778 /*@exposed@*/ char *cppLineBase (cppBuffer *buf)
7780 llassert (buf->buf != NULL);
7781 return (buf->buf + buf->line_base);
7784 int cpplib_bufPeek (cppBuffer *buf)
7786 if (buf->cur == NULL || buf->rlimit == NULL) {
7787 return EOF;
7790 if (buf->cur < buf->rlimit) {
7791 return *(buf->cur);
7794 return EOF;
7797 bool cppBuffer_isMacro (cppBuffer *buf)
7799 if (buf != NULL)
7801 return (buf->cleanup == cppReader_macroCleanup);
7804 return FALSE;
7808 ** Returns true if the macro should be checked, false
7809 ** if it should be expanded normally.
7812 static bool notparseable = FALSE; /* preceeded by @notparseable@ */
7813 static bool notfunction = FALSE; /* preceeded by @notfunction@ */
7814 static bool expectiter = FALSE; /* preceeded by @iter@ */
7815 static bool expectenditer = FALSE; /* second after @iter@ */
7816 static bool expectfunction = FALSE; /* preceeded by @function@ */
7817 static bool expectconstant = FALSE; /* preceeded by @constant@ */
7818 static bool expectmacro = FALSE; /* preceeded by notfunction or notparseable */
7820 static void cpp_setLocation (cppReader *pfile)
7822 fileId fid;
7823 int line;
7825 if (pfile->buffer != NULL)
7827 if (cstring_isDefined (cppReader_getBufferSafe (pfile)->nominal_fname))
7829 cstring fname = cppReader_getBufferSafe (pfile)->nominal_fname;
7831 DPRINTF (("Looking up: %s", fname));
7833 if (fileTable_exists (context_fileTable (), fname))
7835 fid = fileTable_lookup (context_fileTable (), fname);
7837 else
7839 DPRINTF (("Trying %s", cppReader_getBuffer (pfile)->fname));
7841 fid = fileTable_lookup (context_fileTable (),
7842 cppReader_getBufferSafe (pfile)->fname);
7845 else
7847 fid = fileTable_lookup (context_fileTable (),
7848 cppReader_getBufferSafe (pfile)->fname);
7851 line = cppReader_getBufferSafe (pfile)->lineno;
7852 fileloc_free (g_currentloc);
7854 if (fileId_isValid (fid))
7856 g_currentloc = fileloc_create (fid, line, 1);
7858 else
7860 g_currentloc = fileloc_createBuiltin ();
7863 else
7865 fileloc_free (g_currentloc);
7866 g_currentloc = fileloc_createBuiltin ();
7870 static bool cpp_shouldCheckMacro (cppReader *pfile, char *p) /*@modifies p*/
7872 bool checkmacro = FALSE;
7873 bool hasParams = FALSE;
7874 bool noexpand = FALSE;
7875 cstring sname;
7876 char c;
7878 cpp_setLocation (pfile);
7880 DPRINTF (("Should check macro? %s", p));
7882 if (expectiter || expectconstant || expectenditer)
7884 if (expectiter)
7886 expectiter = FALSE;
7887 expectenditer = TRUE;
7889 else
7891 expectiter = FALSE;
7892 expectconstant = FALSE;
7893 expectenditer = FALSE;
7896 if (notfunction || notparseable)
7898 notfunction = FALSE;
7899 notparseable = FALSE;
7900 return FALSE;
7902 else
7904 return TRUE;
7908 llassert (*p == '#');
7909 p++;
7911 while (*p == ' ' || *p == '\t')
7913 p++;
7916 llassert (*p == 'd'); /* define starts */
7918 p += 6;
7920 while (*p == ' ' || *p == '\t')
7922 p++;
7925 sname = cstring_fromChars (p);
7926 DPRINTF (("Check macro: %s", sname));
7928 while (((c = *p) != ' ')
7929 && c != '\0' && c != '('
7930 && c != '\t' && c != '\\' && c != '\n'
7931 && !iscntrl (c))
7933 p++;
7936 hasParams = (c == '(');
7937 *p = '\0';
7939 if (notparseable)
7941 notparseable = FALSE;
7943 else if (notfunction || fileloc_isStandardLib (g_currentloc))
7945 DPRINTF (("Clear notfunction"));
7946 notfunction = FALSE;
7948 else
7950 if (noexpand)
7952 checkmacro = TRUE;
7954 if (!expectenditer)
7956 noexpand = FALSE;
7959 else
7961 if (usymtab_existsReal (sname))
7963 uentry ue = usymtab_lookup (sname);
7965 DPRINTF (("Lookup macro: %s", uentry_unparse (ue)));
7967 if (fileloc_isPreproc (uentry_whereLast (ue)))
7969 goto macroDne;
7971 else
7973 if (uentry_isSpecified (ue))
7975 checkmacro = context_getFlag (FLG_SPECMACROS);
7977 else
7979 if (hasParams)
7981 checkmacro = context_getFlag (FLG_LIBMACROS)
7982 || context_getFlag (FLG_FCNMACROS);
7987 else
7989 macroDne:
7990 DPRINTF (("Macro doesn't exist: %s", bool_unparse (checkmacro)));
7992 if (fileloc_isSystemFile (g_currentloc)
7993 && context_getFlag (FLG_SYSTEMDIREXPAND))
7995 ; /* don't check this macro */
7996 DPRINTF (("Don't check 1"));
7998 else
8000 uentry le;
8002 if (hasParams)
8004 DPRINTF (("Has params..."));
8006 if (context_getFlag (FLG_FCNMACROS))
8008 if (usymtab_exists (sname))
8011 ** only get here is macro is redefined
8012 ** error reported elsewhere
8015 DPRINTF (("It exists!"));
8017 else
8020 ** We make it a forward function, since it might be declared elsewhere.
8021 ** After all headers have been processed, we should check the forward
8022 ** functions.
8025 fileloc loc = fileloc_makePreproc (g_currentloc);
8027 /* the line is off-by-one, since the newline was already read */
8028 decLine ();
8030 if (expectfunction)
8032 expectfunction = FALSE;
8035 le = uentry_makeForwardFunction (sname,
8036 typeId_invalid, loc);
8038 fileloc_free (loc);
8040 incLine ();
8042 /* Do not define here! */
8044 (void) usymtab_addEntry (le);
8047 checkmacro = TRUE;
8048 DPRINTF (("Check: TRUE"));
8050 else
8052 DPRINTF (("Flag FCN_MACROS not set!"));
8055 else
8057 DPRINTF (("No params"));
8059 if (context_getFlag (FLG_CONSTMACROS))
8061 bool nocontent = FALSE;
8063 if (c == '\0')
8065 nocontent = TRUE;
8067 else
8069 if (isspace (c))
8071 char *rest = p + 1;
8074 ** Check if there is nothing after the define.
8077 while ((*rest) != '\0' && isspace (*rest))
8079 rest++;
8082 if (*rest == '\0')
8084 nocontent = TRUE; /* empty macro, don't check */
8089 if (usymtab_exists (sname))
8093 else
8095 fileloc loc = fileloc_makePreproc (g_currentloc);
8096 DPRINTF (("Make constant: %s", sname));
8097 le = uentry_makeMacroConstant (sname, ctype_unknown, loc);
8098 (void) usymtab_addEntry (le);
8101 checkmacro = !nocontent;
8106 if (checkmacro && usymtab_existsType (sname))
8108 DPRINTF (("Making false..."));
8109 decLine ();
8110 ppllerror (message ("Specified type implemented as macro: %s", sname));
8111 checkmacro = FALSE;
8112 incLine ();
8118 if (!checkmacro)
8120 if (usymtab_exists (sname))
8122 uentry ue = usymtab_lookupExpose (sname);
8123 fileloc tloc = fileloc_makePreproc (g_currentloc);
8125 uentry_setDefined (ue, tloc);
8126 fileloc_free (tloc);
8127 uentry_setUsed (ue, fileloc_undefined);
8129 else
8131 fileloc tloc = fileloc_makePreproc (g_currentloc);
8132 uentry ue = uentry_makeExpandedMacro (sname, tloc);
8133 DPRINTF (("Make expanded macro: %s", sname));
8134 DPRINTF (("Not in symbol table: %s", sname));
8136 (void) usymtab_addGlobalEntry (ue);
8137 fileloc_free (tloc);
8141 *p = c;
8142 DPRINTF (("Returning: %s", bool_unparse (checkmacro)));
8143 return checkmacro;
8146 static enum cpp_token
8147 cpp_handleComment (cppReader *pfile, struct parse_marker *smark)
8149 cppBuffer *pbuf = cppReader_getBufferSafe (pfile);
8150 char *start;
8151 int len;
8152 fileloc loc;
8153 bool eliminateComment = FALSE;
8155 llassert (pbuf->buf != NULL);
8157 start = pbuf->buf + smark->position;
8159 llassert (pbuf->cur != NULL);
8160 len = pbuf->cur - start;
8162 if (start[0] == '*'
8163 && start[1] == context_getCommentMarkerChar ())
8165 int i;
8166 char c = ' ';
8167 char *scomment = start + 2;
8168 char savec = start[len];
8170 cpp_setLocation (pfile);
8171 loc = fileloc_copy (g_currentloc);
8173 start[0] = BEFORE_COMMENT_MARKER[0];
8174 start[1] = BEFORE_COMMENT_MARKER[1];
8176 llassert (start[len - 2] == '*');
8177 start[len - 2] = AFTER_COMMENT_MARKER[0];
8179 llassert (start[len - 1] == '/');
8180 start[len - 1] = AFTER_COMMENT_MARKER[1];
8182 cpplib_reserve(pfile, size_fromInt (1 + len));
8183 cppReader_putCharQ (pfile, c);
8185 cpp_setLocation (pfile);
8187 start[len] = '\0';
8189 if (mstring_containsString (scomment, "/*"))
8191 (void) cppoptgenerror
8192 (FLG_NESTCOMMENT,
8193 message ("Comment starts inside syntactic comment: %s",
8194 cstring_fromChars (scomment)),
8195 pfile);
8198 start[len] = savec;
8200 if (mstring_equalPrefix (scomment, "ignore"))
8202 if (!context_getFlag (FLG_NOCOMMENTS))
8204 context_enterSuppressRegion (loc);
8207 else if (mstring_equalPrefix (scomment, "end"))
8209 if (!context_getFlag (FLG_NOCOMMENTS))
8211 context_exitSuppressRegion (loc);
8214 else if (mstring_equalPrefix (scomment, "notparseable"))
8216 notparseable = TRUE;
8217 expectmacro = TRUE;
8218 eliminateComment = TRUE;
8220 else if (mstring_equalPrefix (scomment, "notfunction"))
8222 notfunction = TRUE;
8223 expectmacro = TRUE;
8224 eliminateComment = TRUE;
8226 else if (mstring_equalPrefix (scomment, "iter"))
8228 expectiter = TRUE;
8230 else if (mstring_equalPrefix (scomment, "function"))
8232 expectfunction = TRUE;
8234 else if (mstring_equalPrefix (scomment, "constant"))
8236 expectconstant = TRUE;
8238 else
8240 char sChar = *scomment;
8242 if (sChar == '='
8243 || sChar == '-'
8244 || sChar == '+')
8246 char *rest = scomment + 1;
8248 if (mstring_equalPrefix (rest, "commentchar"))
8250 eliminateComment = TRUE;
8252 if (sChar == '=')
8254 ppllerror (cstring_makeLiteral
8255 ("Cannot restore commentchar"));
8257 else
8259 char *next = scomment + 12; /* strlen commentchar = 12 */
8261 if (*next != ' ' && *next != '\t' && *next != '\n')
8263 ppllerror
8264 (message
8265 ("Syntactic commentchar comment is not followed by a "
8266 "whitespace character: %c",
8267 *next));
8269 else
8271 char cchar = *(next + 1);
8273 if (cchar == '\0')
8275 ppllerror
8276 (cstring_makeLiteral
8277 ("Cannot set commentchar to NUL"));
8279 else
8281 context_setCommentMarkerChar (cchar);
8282 /* setComment = TRUE; */
8287 else if (mstring_equalPrefix (scomment, "nestcomment"))
8289 /* fix from Mike Miller <MikeM@xata.com> */
8290 context_fileSetFlag (FLG_NESTCOMMENT,
8291 ynm_fromCodeChar (sChar),
8292 loc);
8294 else if (mstring_equalPrefix (rest, "namechecks"))
8296 context_fileSetFlag (FLG_NAMECHECKS,
8297 ynm_fromCodeChar (sChar),
8298 loc);
8300 else if (mstring_equalPrefix (rest, "macroredef"))
8302 context_fileSetFlag (FLG_MACROREDEF,
8303 ynm_fromCodeChar (sChar),
8304 loc);
8306 else if (mstring_equalPrefix (rest, "usevarargs"))
8308 context_fileSetFlag (FLG_USEVARARGS,
8309 ynm_fromCodeChar (sChar),
8310 loc);
8312 else if (mstring_equalPrefix (rest, "nextlinemacros"))
8314 context_fileSetFlag (FLG_MACRONEXTLINE,
8315 ynm_fromCodeChar (sChar),
8316 loc);
8318 else if (mstring_equalPrefix (rest, "allmacros")
8319 || mstring_equalPrefix (rest, "fcnmacros")
8320 || mstring_equalPrefix (rest, "constmacros"))
8322 flagcode fl;
8324 if (mstring_equalPrefix (rest, "allmacros"))
8326 fl = FLG_ALLMACROS;
8328 else if (mstring_equalPrefix (rest, "fcnmacros"))
8330 fl = FLG_FCNMACROS;
8332 else
8334 llassert (mstring_equalPrefix (rest, "constmacros"));
8335 fl = FLG_CONSTMACROS;
8338 context_fileSetFlag (fl, ynm_fromCodeChar (sChar), loc);
8339 notfunction = FALSE;
8341 else
8346 else
8352 if (eliminateComment)
8354 goto removeComment;
8357 /* Replaces comment char's in start with spaces */
8359 for (i = 2; i < len - 2; i++)
8361 if (start[i] == BEFORE_COMMENT_MARKER[0]
8362 || start[i] == BEFORE_COMMENT_MARKER[1]
8363 || start[i] == context_getCommentMarkerChar ())
8365 start[i] = ' ';
8369 cppReader_putStrN (pfile, start, size_fromInt (len));
8370 parseClearMark (smark);
8371 return CPP_COMMENT;
8373 else
8375 removeComment:
8377 int i;
8380 ** Output the comment as all spaces so line/column
8381 ** in output file is still correct.
8384 char c = ' ';
8385 cstring lintcomment = cstring_undefined;
8387 if (context_getFlag (FLG_LINTCOMMENTS))
8389 if (mstring_equalPrefix (start, "*NOTREACHED*/"))
8391 lintcomment = cstring_makeLiteralTemp ("l_notreach");
8393 else if (mstring_equalPrefix (start, "*PRINTFLIKE*/"))
8395 lintcomment = cstring_makeLiteralTemp ("l_printfli");
8397 else if (mstring_equalPrefix (start, "*FALLTHROUGH*/"))
8399 lintcomment = cstring_makeLiteralTemp ("l_fallthrou");
8401 else if (mstring_equalPrefix (start, "*ARGSUSED*/"))
8403 lintcomment = cstring_makeLiteralTemp ("l_argsus");
8405 else if (mstring_equalPrefix (start, "*FALLTHRU*/"))
8407 lintcomment = cstring_makeLiteralTemp ("l_fallth");
8409 else
8411 lintcomment = cstring_undefined;
8414 else
8416 lintcomment = cstring_undefined;
8419 if (cstring_isDefined (lintcomment))
8421 c = BEFORE_COMMENT_MARKER[0];
8422 start[0] = BEFORE_COMMENT_MARKER[1];
8424 llassert (size_toLong (cstring_length (lintcomment)) == len - 3);
8426 for (i = 1; i < len - 2; i++)
8428 start[i] = cstring_getChar (lintcomment, size_fromInt (i));
8431 start[len - 2] = AFTER_COMMENT_MARKER[0];
8432 start[len - 1] = AFTER_COMMENT_MARKER[1];
8434 else
8436 /* Replaces char's in start with spaces */
8437 for (i = 0; i < len; i++)
8439 if (start[i] == '/'
8440 && i < len - 1
8441 && start[i + 1] == '*') {
8442 (void) cppoptgenerror
8443 (FLG_NESTCOMMENT,
8444 message ("Comment starts inside comment"),
8445 pfile);
8448 if (start[i] != '\n')
8450 start[i] = ' ';
8455 cpplib_reserve (pfile, size_fromInt (1 + len));
8456 cppReader_putCharQ (pfile, c);
8457 cppReader_putStrN (pfile, start, size_fromInt (len));
8458 parseClearMark (smark);
8459 return CPP_COMMENT;
8464 static int cpp_openIncludeFile (char *filename)
8466 int res = open (filename, O_RDONLY, 0666);
8468 /* evans 2001-08-23: was (res) - open returns -1 on error! reported by Robin Watts */
8469 if (res >= 0)
8471 if (!fileTable_exists (context_fileTable (),
8472 cstring_fromChars (filename)))
8474 if (fileloc_isXHFile (g_currentloc))
8477 ** Files includes by XH files are also XH files
8480 (void) fileTable_addXHFile (context_fileTable (),
8481 cstring_fromChars (filename));
8483 else
8485 (void) fileTable_addHeaderFile (context_fileTable (),
8486 cstring_fromChars (filename));
8489 else
8491 DPRINTF (("File already exists: %s", filename));
8495 return res;
8498 static bool cpp_skipIncludeFile (cstring fname)
8500 if (context_isSystemDir (fname))
8502 DPRINTF (("System dir: %s", fname));
8504 if (lcllib_isSkipHeader (fname))
8506 DPRINTF (("Skip include TRUE: %s", fname));
8507 return TRUE;
8510 if (context_getFlag (FLG_SKIPSYSHEADERS))
8513 ** 2003-04-18: Patch from Randal Parsons
8517 ** Don't skip include file unless the file actually exists.
8518 ** It may be in a different directory.
8521 int f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666);
8523 if (f >= 0)
8525 check (close (f) == 0);
8526 DPRINTF (("Skip include TRUE: %s", fname));
8527 return TRUE;
8529 else
8531 /* Keep looking... */
8536 if (context_getFlag (FLG_SINGLEINCLUDE))
8538 fname = removePreDirs (fname);
8540 # if defined (WIN32) || defined (OS2)
8541 cstring_replaceAll (fname, '\\', '/');
8542 # endif
8544 if (fileTable_exists (context_fileTable (), fname))
8546 DPRINTF (("Skip include TRUE: %s", fname));
8547 return TRUE;
8551 DPRINTF (("Skip include FALSE: %s", fname));
8552 return FALSE;
8555 static int cpp_peekN (cppReader *pfile, int n)
8557 cppBuffer *buf = cppReader_getBufferSafe (pfile);
8559 llassert (buf->cur != NULL);
8561 return (buf->rlimit - buf->cur >= (n)
8562 ? buf->cur[n]
8563 : EOF);
8566 cppBuffer *cppBuffer_prevBuffer (cppBuffer *buf)
8568 return buf + 1;
8571 void cppBuffer_forward (cppBuffer *buf, int n)
8573 llassert (buf->cur != NULL);
8574 buf->cur += n;
8577 /*@=bufferoverflowhigh@*/
8578 /*@=bounds@*/