2 ** LCLint - annotation-assisted static program checker
3 ** Copyright (C) 1994-2000 University of Virginia,
4 ** Massachusetts Institute of Technology
6 ** This program is free software; you can redistribute it and/or modify it
7 ** under the terms of the GNU General Public License as published by the
8 ** Free Software Foundation; either version 2 of the License, or (at your
9 ** option) any later version.
11 ** This program is distributed in the hope that it will be useful, but
12 ** WITHOUT ANY WARRANTY; without even the implied warranty of
13 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ** General Public License for more details.
16 ** The GNU General Public License is available from http://www.gnu.org/ or
17 ** the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
18 ** MA 02111-1307, USA.
20 ** For information on lclint: lclint-request@cs.virginia.edu
21 ** To report a bug: lclint-bug@cs.virginia.edu
22 ** For more information: http://lclint.cs.virginia.edu
28 Copyright (C) 1986, 87, 89, 92-6, 1997 Free Software Foundation, Inc.
29 Contributed by Per Bothner, 1994-95.
30 Based on CCCP program by Paul Rubin, June 1986
31 Adapted to ANSI C, Richard Stallman, Jan 1987
33 This program is free software; you can redistribute it and/or modify it
34 under the terms of the GNU General Public License as published by the
35 Free Software Foundation; either version 2, or (at your option) any
38 This program is distributed in the hope that it will be useful,
39 but WITHOUT ANY WARRANTY; without even the implied warranty of
40 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 GNU General Public License for more details.
43 You should have received a copy of the GNU General Public License
44 along with this program; if not, write to the Free Software
45 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 In other words, you are welcome to use, share and improve this program.
48 You are forbidden to forbid anyone else to use, share and improve
49 what you give them. Help stamp out software-hoarding! */
53 * - OS2 drive specs like WIN32
54 * - Includes for IBMs OS/2 compiler
66 # if !(defined (WIN32) || defined (OS2) && defined (__IBMC__))
70 # include <sys/types.h>
71 # include <sys/stat.h>
74 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
76 # include <sys/utime.h> /* for __DATE__ and __TIME__ */
81 # include <sys/time.h>
82 # include <sys/resource.h>
84 # include <sys/times.h>
89 # endif /* not WIN32 */
91 /* This defines "errno" properly for VMS, and gives us EACCES. */
94 # include "lclintMacros.nf"
99 # include "cpperror.h"
100 # include "cpphash.h"
102 # include "version.h"
107 ** This is really kludgey code...
113 #define NO_SHORTNAMES
121 /*@constant int IMPORT_FOUND@*/
122 # define IMPORT_FOUND -2
124 /*@constant int SKIP_INCLUDE@*/
125 # define SKIP_INCLUDE IMPORT_FOUND
127 /*@constant unused int IMPORT_NOT_FOUND@*/
128 # define IMPORT_NOT_FOUND -1
131 /*@constant unused int STDC_VALUE@*/
135 /* By default, colon separates directories in a path. */
136 #ifndef PATH_SEPARATOR
137 /*@constant char PATH_SEPARATOR@*/
138 #define PATH_SEPARATOR ':'
141 static void parse_name (cppReader *, int);
143 static int cpp_openIncludeFile (char *p_filename)
144 /*@modifies fileSystem @*/ ;
146 static void cpp_setLocation (cppReader *p_pfile)
147 /*@modifies g_currentloc@*/ ;
149 static enum cpp_token cpp_handleComment (cppReader *p_pfile,
150 struct parse_marker *p_smark)
151 /*@modifies *p_pfile, *p_smark@*/;
153 static bool cpp_shouldCheckMacro (cppReader *p_pfile, char *p_p) /*@*/ ;
155 static bool cpp_skipIncludeFile (cstring p_fname) /*@*/ ;
161 /* Symbols to predefine. */
163 #ifdef CPP_PREDEFINES
164 static /*@observer@*/ char *predefs = CPP_PREDEFINES;
166 static /*@observer@*/ char *predefs = "";
169 /* We let tm.h override the types used here, to handle trivial differences
170 such as the choice of unsigned int or long unsigned int for size_t.
171 When machines start needing nontrivial differences in the size type,
172 it would be best to do something here to figure out automatically
173 from other information what type to use. */
175 /* The string value for __SIZE_TYPE__. */
178 /*@constant observer char *SIZE_TYPE@*/
179 #define SIZE_TYPE "long unsigned int"
182 /* The string value for __PTRDIFF_TYPE__. */
185 /*@constant observer char *PTRDIFF_TYPE@*/
186 #define PTRDIFF_TYPE "long int"
189 /* The string value for __WCHAR_TYPE__. */
192 /*@constant observer char *WCHAR_TYPE@*/
193 #define WCHAR_TYPE "int"
196 /* The string value for __USER_LABEL_PREFIX__ */
198 #ifndef USER_LABEL_PREFIX
199 /*@constant observer char *USER_LABEL_PREFIX@*/
200 #define USER_LABEL_PREFIX ""
203 /* The string value for __REGISTER_PREFIX__ */
205 #ifndef REGISTER_PREFIX
206 /*@constant observer char *REGISTER_PREFIX@*/
207 #define REGISTER_PREFIX ""
210 /* table to tell if char can be part of a C identifier. */
211 static bool is_idchar[256];
212 /* table to tell if char can be first char of a c identifier. */
213 static bool is_idstart[256];
214 /* table to tell if c is horizontal space. */
215 static bool is_hor_space[256];
216 /* table to tell if c is horizontal or vertical space. */
217 static bool is_space[256];
219 static /*@exposed@*/ /*@null@*/ cppBuffer *
220 cppReader_getBuffer (/*@special@*/ cppReader *p_pfile)
221 /*@uses p_pfile->buffer@*/
222 /*@modifies nothing@*/ ;
225 # define SKIP_WHITE_SPACE(p) do { /*@access cstring@*/ while (is_hor_space[(int) *(p)]) { (p)++; } } /*@noaccess cstring@*/ while (0)
228 # define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*(p)]) { (p)++; } } while (0)
230 static int cpp_peekN (cppReader *p_pfile, int p_n) /*@*/ ;
232 /*@function static int cppBuffer_get (sef cppBuffer *p_b) modifies *p_b ; @*/
233 # define cppBuffer_get(BUFFER) \
234 ((BUFFER)->cur < (BUFFER)->rlimit ? *(BUFFER)->cur++ : EOF)
236 /* Append string STR (of length N) to PFILE's output buffer. Make space. */
237 /*@function static void cppReader_puts (sef cppReader *p_file, char *p_str, sef size_t p_n)
238 modifies *p_file; @*/
239 # define cppReader_puts(PFILE, STR, N) \
240 cppReader_reserve(PFILE, N), cppReader_putStrN (PFILE, STR,N)
242 /* Append character CH to PFILE's output buffer. Assume sufficient space. */
244 /*@function static void cppReader_putCharQ (cppReader *p_file, char p_ch)
245 modifies *p_file; @*/
246 # define cppReader_putCharQ(PFILE, CH) (*(PFILE)->limit++ = (CH))
248 /* Append character CH to PFILE's output buffer. Make space if need be. */
250 /*@function static void cppReader_putChar (sef cppReader *p_file, char p_ch)
251 modifies *p_file; @*/
252 #define cppReader_putChar(PFILE, CH) (cppReader_reserve (PFILE, (size_t) 1), cppReader_putCharQ (PFILE, CH))
254 /* Make sure PFILE->limit is followed by '\0'. */
255 /*@function static void cppReader_nullTerminateQ (cppReader *p_file)
256 modifies *p_file; @*/
258 #define cppReader_nullTerminateQ(PFILE) (*(PFILE)->limit = 0)
260 /*@function static void cppReader_nullTerminate (sef cppReader *p_file)
261 modifies *p_file; @*/
262 # define cppReader_nullTerminate(PFILE) \
263 (cppReader_reserve (PFILE, (size_t) 1), *(PFILE)->limit = 0)
265 /*@function static void cppReader_adjustWritten (cppReader *p_file, size_t)
266 modifies *p_file; @*/
267 #define cppReader_adjustWritten(PFILE,DELTA) ((PFILE)->limit += (DELTA))
269 /*@function static bool cppReader_isC89 (cppReader *) modifies nothing; @*/
270 #define cppReader_isC89(PFILE) (CPPOPTIONS(PFILE)->c89)
272 /*@function static observer char *cppReader_wcharType (cppReader *)
273 modifies nothing; @*/
275 # define cppReader_wcharType(PFILE) \
276 (CPPOPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
278 static void cppBuffer_forward (cppBuffer *p_buf, int p_n) /*@modifies *p_buf@*/ ;
280 /*@function static void cppReader_forward (cppReader *p_pfile, int) modifies *p_pfile; @*/
281 # define cppReader_forward(pfile, N) \
282 (cppBuffer_forward (cppReader_getBufferSafe (pfile), (N)))
284 /*@function static int cppReader_getC (cppReader *p_pfile) modifies *p_pfile; @*/
285 # define cppReader_getC(pfile) (cppBuffer_get (cppReader_getBufferSafe (pfile)))
287 /*@function static int cppReader_peekC (cppReader *) modifies nothing;@*/
288 # define cppReader_peekC(pfile) (cppBufPeek (cppReader_getBufferSafe (pfile)))
290 /* Move all backslash-newline pairs out of embarrassing places.
291 Exchange all such pairs following BP
292 with any potentially-embarrassing characters that follow them.
293 Potentially-embarrassing characters are / and *
294 (because a backslash-newline inside a comment delimiter
295 would cause it not to be recognized). */
298 # define NEWLINE_FIX \
299 do { while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n') { cppReader_forward (pfile, 2); } } while(FALSE)
301 /* Same, but assume we've already read the potential '\\' into C. */
303 # define NEWLINE_FIX1(C) do { \
304 while ((C) == '\\' && cppReader_peekC (pfile) == '\n') { cppReader_forward (pfile, 1); (C) = cppReader_getC (pfile); }\
307 static void parseSetMark (/*@out@*/ struct parse_marker *,
309 static void parseClearMark (struct parse_marker *);
310 static void parseGotoMark (struct parse_marker *, cppReader *);
311 static void parseMoveMark (struct parse_marker *, cppReader *);
313 /* If we have a huge buffer, may need to cache more recent counts */
314 static /*@exposed@*/ char *cppLineBase (/*@sef@*/ cppBuffer *);
316 static /*@exposed@*/ /*@null@*/ cppBuffer *
317 cppReader_pushBuffer (cppReader *p_pfile,
318 /*@owned@*/ /*@null@*/ char *, size_t)
319 /*@modifies p_pfile@*/ ;
321 static void cppReader_appendIncludeChain
323 /*@keep@*/ struct file_name_list *p_first,
324 /*@dependent@*/ struct file_name_list *p_last);
326 static void cppReader_macroCleanup (cppBuffer *p_pbuf, cppReader *p_pfile);
327 static enum cpp_token cppReader_nullUnderflow (/*@unused@*/ cppReader *p_pfile);
329 static void cppReader_nullCleanup (/*@unused@*/ cppBuffer *p_pbuf,
330 /*@unused@*/ cppReader *p_pfile);
332 static void cppReader_fileCleanup (cppBuffer *p_pbuf,
333 /*@unused@*/ cppReader *p_pfile);
335 static int cppReader_handleDirective (cppReader *p_pfile);
337 static void cppReader_scanBuffer (cppReader *p_pfile);
339 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
342 ** WIN32 (at least the VC++ include files) does not define mode_t.
345 /*@-incondefs@*/ /*@-czechtypes@*/
346 typedef unsigned int mode_t;
347 /*@=incondefs@*/ /*@=czechtypes@*/
351 static int file_size_and_mode (int p_fd, /*@out@*/ mode_t *p_mode_pointer,
352 /*@out@*/ size_t *p_size_pointer);
353 static int safe_read (int p_desc, /*@out@*/ char *p_ptr, int p_len);
357 ** cppBuffer_isMacro is true if the buffer contains macro expansion.
358 ** (Note that it is false while we're expanding marco *arguments*.)
361 static bool cppBuffer_isMacro (/*@null@*/ cppBuffer *) /*@*/ ;
363 static void path_include (cppReader *p_pfile, char *p_path)
364 /*@modifies p_pfile@*/ ;
366 static void initialize_builtins (cppReader *p_pfile)
367 /*@modifies p_pfile@*/ ;
369 static void initialize_char_syntax (struct cppOptions *p_opts) ;
371 static int /*@alt void@*/ finclude (cppReader *p_pfile, int p_f,
373 bool p_system_header_p,
374 /*@dependent@*/ /*@null@*/ struct file_name_list *p_dirptr);
376 static void validate_else (cppReader *p_pfile, cstring p_directive);
378 static void conditional_skip (cppReader *p_pfile, int p_skip,
379 enum node_type p_type,
380 /*@dependent@*/ /*@null@*/ char *p_control_macro);
382 static HOST_WIDE_INT eval_if_expression (cppReader *p_pfile,
386 static void skip_if_group (cppReader *p_pfile, int p_any);
388 static bool comp_def_part (bool p_first, char *p_beg1, int p_len1,
389 char *p_beg2, int p_len2, bool p_last);
392 extern void fancy_abort ();
395 static bool redundant_include_p (cppReader *p_pfile, /*@null@*/ cstring p_name);
396 static bool is_system_include (cppReader *p_pfile, cstring p_filename);
398 static /*@observer@*/ /*@null@*/ struct file_name_map *
399 read_name_map (cppReader *p_pfile, cstring p_dirname);
401 static cstring read_filename_string (int p_ch, FILE *p_f);
403 static int open_include_file (cppReader *p_pfile,
404 /*@owned@*/ cstring p_fname,
405 /*@null@*/ struct file_name_list *p_searchptr);
407 static void push_macro_expansion (cppReader *,
408 /*@owned@*/ char *, size_t,
409 /*@dependent@*/ HASHNODE *);
411 /* Last arg to output_line_command. */
412 enum file_change_code {
413 same_file, enter_file, leave_file
416 /* `struct directive' defines one #-directive, including how to handle it. */
419 int length; /* Length of name */
420 /*@null@*/ int (*func)(); /* Function to handle directive */
421 /*@observer@*/ cstring name; /* Name of directive */
422 enum node_type type; /* Code which describes which directive. */
423 bool command_reads_line; /* One if rest of line is read by func. */
424 bool traditional_comments; /* Nonzero: keep comments if -traditional. */
425 bool pass_thru; /* Copy preprocessed directive to output file.*/
428 /* These functions are declared to return int instead of void since they
429 are going to be placed in a table and some old compilers have trouble with
430 pointers to functions returning void. */
432 static int do_define (cppReader *, /*@null@*/ struct directive *,
434 static int do_defineAux (cppReader *, /*@null@*/ struct directive *,
435 char *, char *, bool);
437 static int do_line (cppReader *, /*@null@*/ struct directive *);
438 static int do_include (cppReader *, struct directive *, char *, char *);
439 static int do_undef (cppReader *, struct directive *, char *, char *);
440 static int do_error (cppReader *, struct directive *, char *, char *);
441 static int do_pragma (cppReader *, struct directive *, char *, char *);
442 static int do_ident (cppReader *, struct directive *, char *, char *);
443 static int do_if (cppReader *, struct directive *, char *, char *);
444 static int do_xifdef (cppReader *, struct directive *, char *, char *);
445 static int do_else (cppReader *, struct directive *, char *, char *);
446 static int do_elif (cppReader *, struct directive *, char *, char *);
447 static int do_endif (cppReader *, struct directive *, char *, char *);
448 static int do_warning (cppReader *, struct directive *, char *, char *);
450 /* If a buffer's dir field is SELF_DIR_DUMMY, it means the file was found
451 via the same directory as the file that #included it. */
453 /*@constant observer struct file_name_list *SELF_DIR_DUMMY@*/
454 #define SELF_DIR_DUMMY ((struct file_name_list *) (~0))
456 /* #include "file" looks in source file dir, then stack. */
457 /* #include <file> just looks in the stack. */
458 /* -I directories are added to the end, then the defaults are added. */
462 static struct default_include {
463 /*@dependent@*/ /*@observer@*/ cstring fname; /* The name of the directory. */
464 int cplusplus; /* Only look here if we're compiling C++. */
465 int cxx_aware; /* Includes in this directory don't need to
466 be wrapped in extern "C" when compiling
468 } include_defaults_array[]
470 /* This is the dir for fixincludes. Put it just before
471 the files that we fix. */
472 { GCC_INCLUDE_DIR, 0, 0 },
473 { GCC_INCLUDE_DIR2, 0, 0 },
474 { cstring_undefined, 0, 0 }
477 /*@noaccess cstring@*/
479 /* Here is the actual list of #-directives, most-often-used first.
480 The initialize_builtins function assumes #define is the very first. */
484 static struct directive directive_table[] = {
485 { 6, do_define, "define", T_DEFINE, FALSE, TRUE, FALSE },
486 { 5, do_xifdef, "ifdef", T_IFDEF, TRUE, FALSE, FALSE },
487 { 6, do_xifdef, "ifndef", T_IFNDEF, TRUE, FALSE, FALSE },
488 { 7, do_include, "include", T_INCLUDE, TRUE, FALSE, FALSE },
489 { 5, do_endif, "endif", T_ENDIF, TRUE, FALSE, FALSE },
490 { 4, do_else, "else", T_ELSE, TRUE, FALSE, FALSE },
491 { 2, do_if, "if", T_IF, TRUE, FALSE, FALSE },
492 { 4, do_elif, "elif", T_ELIF, TRUE, FALSE, FALSE },
493 { 5, do_undef, "undef", T_UNDEF, FALSE, FALSE, FALSE },
494 { 5, do_error, "error", T_ERROR, FALSE, FALSE, FALSE },
495 { 7, do_warning, "warning", T_WARNING, FALSE, FALSE, FALSE },
496 { 6, do_pragma, "pragma", T_PRAGMA, FALSE, FALSE, TRUE},
497 { 4, do_line, "line", T_LINE, TRUE, FALSE, FALSE },
498 { 5, do_ident, "ident", T_IDENT, TRUE, FALSE, TRUE },
499 /* { 8, do_unassert, "unassert", T_UNASSERT, TRUE, FALSE, FALSE }, */
500 { -1, 0, "", T_UNUSED, FALSE, FALSE, FALSE },
503 /*@noaccess cstring@*/
507 initialize_char_syntax (struct cppOptions *opts)
512 * Set up is_idchar and is_idstart tables. These should be
513 * faster than saying (is_alpha (c) || c == '_'), etc.
514 * Set up these things before calling any routines tthat
518 for (i = 'a'; i <= 'z'; i++) {
519 is_idchar[i - 'a' + 'A'] = TRUE;
520 is_idchar[(int) i] = TRUE;
521 is_idstart[i - 'a' + 'A'] = TRUE;
522 is_idstart[(int) i] = TRUE;
525 for (i = '0'; i <= '9'; i++)
527 is_idchar[(int) i] = TRUE;
530 is_idchar['_'] = TRUE;
531 is_idstart['_'] = TRUE;
532 is_idchar['$'] = opts->dollars_in_ident;
533 is_idstart['$'] = opts->dollars_in_ident;
535 /* horizontal space table */
536 is_hor_space[' '] = TRUE;
537 is_hor_space['\t'] = TRUE;
538 is_hor_space['\v'] = TRUE;
539 is_hor_space['\f'] = TRUE;
540 is_hor_space['\r'] = TRUE;
542 is_space[' '] = TRUE;
543 is_space['\t'] = TRUE;
544 is_space['\v'] = TRUE;
545 is_space['\f'] = TRUE;
546 is_space['\n'] = TRUE;
547 is_space['\r'] = TRUE;
550 bool isIdentifierChar (char c)
552 return is_idchar[(int) c];
555 /* Place into P_PFILE a quoted string representing the string SRC.
556 Caller must reserve enough space in pfile->token_buffer. */
559 quote_string (cppReader *pfile, char *src)
563 cppReader_putCharQ (pfile, '\"');
566 switch ((c = *src++))
570 cppReader_putCharQ (pfile, c);
573 sprintf (cppReader_getPWritten (pfile), "\\%03o",
575 cppReader_adjustWritten (pfile, (size_t) 4);
577 /*@switchbreak@*/ break;
581 cppReader_putCharQ (pfile, '\\');
582 cppReader_putCharQ (pfile, c);
583 /*@switchbreak@*/ break;
586 cppReader_putCharQ (pfile, '\"');
587 cppReader_nullTerminateQ (pfile);
593 /* Re-allocates PFILE->token_buffer so it will hold at least N more chars. */
596 cppReader_growBuffer (cppReader *pfile, size_t n)
598 size_t old_written = cppReader_getWritten (pfile);
599 pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
600 pfile->token_buffer = (char *)
601 drealloc (pfile->token_buffer, pfile->token_buffer_size);
602 cppReader_setWritten (pfile, old_written);
606 * process a given definition string, for initialization
607 * If STR is just an identifier, define it with value 1.
608 * If STR has anything after the identifier, then it should
609 * be identifier=definition.
613 cppReader_define (cppReader *pfile, char *str)
618 DPRINTF (("Cpp reader define: %s", str));
620 if (!is_idstart[(int) *p])
622 DPRINTF (("ERROR 1"));
623 cppReader_error (pfile,
624 message ("Malformed option `-D%s'",
625 cstring_fromChars (str)));
632 DPRINTF (("Here 2"));
634 while (is_idchar[(int) *p])
641 while (*p != ')' && *p != '\0') {
650 message ("Malformed option: -D%s (no closing parenthesis)",
651 cstring_fromChars (str)));
655 DPRINTF (("Here 2"));
659 buf = (char *) dmalloc (size_fromInt (p - str + 4));
660 strcpy ((char *) buf, str);
661 strcat ((char *) buf, " 1");
665 DPRINTF (("ERROR 2"));
666 cppReader_error (pfile,
667 message ("Malformed option: -D%s (expected '=', found '%c')",
668 cstring_fromChars (str),
675 /* Copy the entire option so we can modify it. */
676 DPRINTF (("Copying..."));
677 buf = (char *) dmalloc (2 * strlen (str) + 1);
678 strncpy (buf, str, size_fromInt (p - str));
680 /* Change the = to a space. */
682 /* Scan for any backslash-newline and remove it. */
688 if (*p == '\\' && p[1] == '\n')
694 DPRINTF (("Here we are..."));
698 llassert (buf != NULL);
699 DPRINTF (("Do define: %s / %ld", buf, size_toLong (strlen (buf))));
700 (void) do_define (pfile, NULL, buf, buf + strlen (buf));
704 /* Append a chain of `struct file_name_list's
705 to the end of the main include chain.
706 FIRST is the beginning of the chain to append, and LAST is the end. */
709 cppReader_appendIncludeChain (cppReader *pfile,
710 struct file_name_list *first,
711 struct file_name_list *last)
713 struct cppOptions *opts = CPPOPTIONS (pfile);
714 struct file_name_list *dir;
716 if (first == NULL || last == NULL)
721 if (opts->include == 0)
723 opts->include = first;
727 llassert (opts->last_include->next == NULL);
728 opts->last_include->next = first;
731 if (opts->first_bracket_include == 0)
733 opts->first_bracket_include = first;
735 for (dir = first; ; dir = dir->next) {
736 int len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
737 if (len > pfile->max_include_len)
738 pfile->max_include_len = len;
744 llassert (last->next == NULL);
745 /* last->next = NULL; */
746 opts->last_include = last;
749 static /*@unused@*/ void
750 cppReader_showIncludeChain (cppReader *pfile)
752 struct file_name_list *dirs = CPPOPTIONS (pfile)->include;
758 fprintf (stderr, "*%s*:", cstring_toCharsSafe (dirs->fname));
762 fprintf (stderr, "\n");
766 fprintf (stderr, "No includes\n");
771 cppReader_addIncludeChain (cppReader *pfile, struct file_name_list *dir)
773 struct cppOptions *opts = CPPOPTIONS (pfile);
780 if (opts->include == 0)
786 llassert (opts->last_include->next == NULL);
787 opts->last_include->next = dir;
790 if (opts->first_bracket_include == 0)
792 int len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
793 opts->first_bracket_include = dir;
794 if (len > pfile->max_include_len)
796 pfile->max_include_len = len;
801 opts->last_include = dir;
802 /* cppReader_showIncludeChain (pfile); */
805 /* Given a colon-separated list of file names PATH,
806 add all the names to the search path for include files. */
809 path_include (cppReader *pfile, char *path)
816 /* if we have a posix path list, convert to win32 path list */
817 win32temp = (char *) dmalloc /*@i4@*/
818 (cygwin32_posix_to_win32_path_list_buf_size (path));
819 cygwin32_posix_to_win32_path_list (path, win32temp);
829 struct file_name_list *dirtmp;
831 /* Find the end of this name. */
832 while (*q != '\0' && *q != PATH_SEPARATOR)
839 /* An empty name in the path stands for the current directory. */
840 name = (char *) dmalloc ((size_t) 2);
846 /* Otherwise use the directory that is named. */
847 name = (char *) dmalloc (size_fromInt (q - p + 1));
848 memcpy (name, p, size_fromInt (q - p));
852 dirtmp = (struct file_name_list *) dmalloc (sizeof (*dirtmp));
853 dirtmp->next = 0; /* New one goes on the end */
854 dirtmp->control_macro = 0;
855 dirtmp->c_system_include_path = 0;
856 dirtmp->fname = cstring_fromChars (name);
857 dirtmp->got_name_map = 0;
858 cppReader_addIncludeChain (pfile, dirtmp);
860 /* Advance past this name. */
864 /* Skip the colon. */
870 cppOptions_init (cppOptions *opts)
872 memset ((char *) opts, 0, sizeof *opts);
875 opts->in_fname = NULL;
876 opts->out_fname = NULL;
878 /* Initialize is_idchar to allow $. */
879 opts->dollars_in_ident = TRUE;
881 opts->no_line_commands = 0;
882 opts->no_trigraphs = TRUE;
883 opts->put_out_comments = 1;
884 opts->print_include_names = 0;
885 opts->dump_macros = DUMP_DEFINITIONS; /* DUMP_NONE; */
889 opts->cplusplus_comments = 1;
894 opts->pedantic_errors = 0;
895 opts->inhibit_warnings = 0;
896 opts->warn_comments = 0;
897 opts->warnings_are_errors = 0;
899 initialize_char_syntax (opts);
903 cppReader_nullUnderflow (/*@unused@*/ cppReader *pfile)
909 cppReader_nullCleanup (/*@unused@*/ cppBuffer *pbuf,
910 /*@unused@*/ cppReader *pfile)
916 cppReader_macroCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
918 HASHNODE *macro = pbuf->hnode;
920 if (macro->type == T_DISABLED)
922 macro->type = T_MACRO;
925 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
933 cppReader_fileCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
935 if (pbuf->buf != NULL)
942 /* Assuming we have read '/'.
943 If this is the start of a comment (followed by '*' or '/'),
944 skip to the end of the comment, and return ' '.
945 Return EOF if we reached the end of file before the end of the comment.
946 If not the start of a comment, return '/'. */
949 skip_comment (cppReader *pfile, /*@null@*/ long *linep)
953 llassert (pfile->buffer != NULL);
954 llassert (pfile->buffer->cur != NULL);
956 while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n')
963 cppReader_forward (pfile, 2);
966 if (cppReader_peekC (pfile) == '*')
968 cppReader_forward (pfile, 1);
973 c = cppReader_getC (pfile);
980 while (c == (int) '\\' && cppReader_peekC (pfile) == (int) '\n')
987 cppReader_forward (pfile, 1), c = cppReader_getC (pfile);
990 if (prev_c == (int) '*' && c == (int) '/')
995 if (c == (int) '\n' && (linep != NULL))
1001 else if (cppReader_peekC (pfile) == '/'
1002 && CPPOPTIONS (pfile)->cplusplus_comments)
1004 cppReader_forward (pfile, 1);
1008 c = cppReader_getC (pfile);
1012 /* Allow hash comment to be terminated by EOF. */
1016 while (c == (int) '\\' && cppReader_peekC (pfile) == '\n')
1018 cppReader_forward (pfile, 1);
1019 c = cppReader_getC (pfile);
1027 if (c == (int) '\n')
1029 /* Don't consider final '\n' to be part of comment. */
1030 cppReader_forward (pfile, -1);
1041 /* Skip whitespace \-newline and comments. Does not macro-expand. */
1043 cppSkipHspace (cppReader *pfile)
1051 llassert (pfile->buffer != NULL);
1053 c = cppReader_peekC (pfile);
1057 return 0; /* FIXME */
1060 if (is_hor_space[c])
1062 if ((c == '\f' || c == '\v') && cppReader_isPedantic (pfile))
1063 cppReader_pedwarn (pfile,
1064 message ("%s in preprocessing directive",
1066 ? cstring_makeLiteralTemp ("formfeed")
1067 : cstring_makeLiteralTemp ("vertical tab")));
1070 cppReader_forward (pfile, 1);
1074 cppReader_forward (pfile, 1);
1075 c = skip_comment (pfile, NULL);
1079 cppReader_forward (pfile, -1);
1082 if (c == EOF || c == '/')
1087 else if (c == '\\' && cpp_peekN (pfile, 1) == '\n')
1089 cppReader_forward (pfile, 2);
1091 else if (c == '@' && CPPBUFFER (pfile)->has_escapes
1092 && is_hor_space [cpp_peekN (pfile, 1)])
1094 cppReader_forward (pfile, 2);
1103 /* Read the rest of the current line.
1104 The line is appended to PFILE's output buffer. */
1107 copy_rest_of_line (cppReader *pfile)
1109 struct cppOptions *opts = CPPOPTIONS (pfile);
1116 llassert (pfile->buffer != NULL);
1118 c = cppReader_getC (pfile);
1124 if (cppReader_peekC (pfile) == '\n')
1126 cppReader_forward (pfile, 1);
1130 /*@fallthrough@*/ case '\'': case '\"':
1131 goto scan_directive_token;
1134 nextc = cppReader_peekC (pfile);
1137 ** was (opts->cplusplus_comments && nextc == '*')
1142 || (opts->cplusplus_comments && nextc == '/'))
1144 goto scan_directive_token;
1146 /*@switchbreak@*/ break;
1149 if (cppReader_isPedantic (pfile))
1150 cppReader_pedwarn (pfile,
1151 message ("%s in preprocessing directive",
1153 ? cstring_makeLiteralTemp ("formfeed")
1154 : cstring_makeLiteralTemp ("vertical tab")));
1155 /*@switchbreak@*/ break;
1158 cppReader_forward (pfile, -1);
1160 scan_directive_token:
1161 cppReader_forward (pfile, -1);
1162 (void) cppGetToken (pfile);
1165 cppReader_putChar (pfile, c);
1168 cppReader_nullTerminate (pfile);
1172 cppReader_skipRestOfLine (cppReader *pfile)
1174 size_t old = cppReader_getWritten (pfile);
1175 copy_rest_of_line (pfile);
1176 cppReader_setWritten (pfile, old);
1179 /* Handle a possible # directive.
1180 '#' has already been read. */
1183 cppReader_handleDirective (cppReader *pfile)
1186 struct directive *kt = NULL;
1188 size_t after_ident = 0;
1189 char *ident, *line_end = NULL;
1190 size_t old_written = cppReader_getWritten (pfile);
1191 int nspaces = cppSkipHspace (pfile);
1193 c = cppReader_peekC (pfile);
1195 if (c >= '0' && c <= '9')
1197 /* Handle # followed by a line number. */
1198 if (cppReader_isPedantic (pfile))
1200 cppReader_pedwarnLit
1202 cstring_makeLiteralTemp ("`#' followed by integer"));
1205 (void) do_line (pfile, NULL);
1206 goto done_a_directive;
1210 /* Now find the directive name. */
1212 cppReader_putChar (pfile, '#');
1214 parse_name (pfile, cppReader_getC (pfile));
1216 llassert (pfile->token_buffer != NULL);
1217 ident = pfile->token_buffer + old_written + 1;
1219 ident_length = cppReader_getPWritten (pfile) - ident;
1221 if (ident_length == 0 && cppReader_peekC (pfile) == '\n')
1223 /* A line of just `#' becomes blank. */
1227 for (kt = directive_table; ; kt++)
1229 if (kt->length <= 0)
1231 return 0; /* goto not_a_directive; */
1234 if (kt->length == ident_length
1235 && (cstring_equalPrefix (kt->name, ident)))
1241 if (kt->command_reads_line)
1247 /* Nonzero means do not delete comments within the directive.
1248 #define needs this when -traditional. */
1249 bool comments = 1; /*cppReader_isTraditional (pfile) && kt->traditional_comments; */
1250 int save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
1251 CPPOPTIONS (pfile)->put_out_comments = comments;
1252 after_ident = cppReader_getWritten (pfile);
1253 copy_rest_of_line (pfile);
1254 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
1258 /* For #pragma and #define, we may want to pass through the directive.
1259 Other directives may create output, but we don't want the directive
1260 itself out, so we pop it now. For example #include may write a #line
1261 command (see comment in do_include), and conditionals may emit
1262 #failed ... #endfailed stuff. But note that popping the buffer
1263 means the parameters to kt->func may point after pfile->limit
1264 so these parameters are invalid as soon as something gets appended
1265 to the token_buffer. */
1267 line_end = cppReader_getPWritten (pfile);
1270 if (!kt->pass_thru && kt->type != T_DEFINE)
1272 cppReader_setWritten (pfile, old_written);
1275 llassert (pfile->token_buffer != NULL);
1277 /* was kt->pass_thru || */
1279 if (kt->type == T_DEFINE
1280 && cpp_shouldCheckMacro (pfile, pfile->token_buffer + old_written))
1282 char *p = pfile->token_buffer + old_written;
1285 ** Still need to record value for preprocessing, so
1286 ** #ifdef's, etc. using the value behave correctly.
1289 (void) do_defineAux (pfile, kt,
1290 pfile->token_buffer + after_ident,
1299 SKIP_WHITE_SPACE (p);
1301 llassert (*p == 'd');
1304 llassert (*p == 'e');
1307 llassert (*p == 'f');
1310 llassert (*p == 'i');
1313 llassert (*p == 'n');
1316 llassert (*p == 'e');
1319 ** This is way-bogus. We use the last char to record the number of
1320 ** spaces. Its too hard to get them back into the input stream.
1323 if (nspaces > 9) nspaces = 9;
1325 *p++ = '0' + nspaces;
1327 return 0; /* not_a_directive */
1329 else if (kt->pass_thru)
1331 /* Just leave the entire #define in the output stack. */
1332 return 0; /* not_a_directive */
1335 else if (kt->type == T_DEFINE
1336 && CPPOPTIONS (pfile)->dump_macros == DUMP_NAMES)
1338 char *p = pfile->token_buffer + old_written + 7; /* Skip "#define". */
1339 SKIP_WHITE_SPACE (p);
1341 while (is_idchar[(int) *p])
1347 cppReader_putChar (pfile, '\n');
1349 else if (kt->type == T_DEFINE)
1351 cppReader_setWritten (pfile, old_written);
1362 llassert (kt->func != NULL);
1363 (void) (kt->func) (pfile, kt, pfile->token_buffer + after_ident, line_end);
1368 /* Pass a directive through to the output file.
1369 BUF points to the contents of the directive, as a contiguous string.
1370 LIMIT points to the first character past the end of the directive.
1371 KEYWORD is the keyword-table entry for the directive. */
1374 pass_thru_directive (char *buf, char *limit,
1376 struct directive *keyword)
1378 int keyword_length = keyword->length;
1380 cppReader_reserve (pfile,
1381 size_fromInt (2 + keyword_length + (limit - buf)));
1382 cppReader_putCharQ (pfile, '#');
1383 /*@-observertrans@*/
1384 cppReader_putStrN (pfile, cstring_toCharsSafe (keyword->name),
1385 size_fromInt (keyword_length));
1386 /*:=observertrans@*/
1388 if (limit != buf && buf[0] != ' ')
1390 /* Was a bug, since reserve only used 1 + ... */
1391 cppReader_putCharQ (pfile, ' ');
1394 cppReader_putStrN (pfile, buf, size_fromInt (limit - buf));
1397 /* Read a replacement list for a macro with parameters.
1398 Build the DEFINITION structure.
1399 Reads characters of text starting at BUF until END.
1400 ARGLIST specifies the formal parameters to look for
1401 in the text of the definition; NARGS is the number of args
1402 in that list, or -1 for a macro name that wants no argument list.
1403 MACRONAME is the macro name itself (so we can avoid recursive expansion)
1404 and NAMELEN is its length in characters.
1406 Note that comments, backslash-newlines, and leading white space
1407 have already been deleted from the argument. */
1410 collect_expansion (cppReader *pfile, char *buf, char *limit,
1411 int nargs, /*@null@*/ struct arglist *arglist)
1414 char *p, *lastp, *exp_p;
1415 struct reflist *endpat = NULL;
1416 /* Pointer to first nonspace after last ## seen. */
1418 /* Pointer to first nonspace after last single-# seen. */
1419 char *stringify = 0;
1421 char expected_delimiter = '\0';
1424 /* Scan thru the replacement list, ignoring comments and quoted
1425 strings, picking up on the macro calls. It does a linear search
1426 thru the arg list on every potential symbol. Profiling might say
1427 that something smarter should happen. */
1432 /* Find the beginning of the trailing whitespace. */
1435 while (p < limit && is_space[(int) limit[-1]])
1440 /* Allocate space for the text in the macro definition.
1441 Leading and trailing whitespace chars need 2 bytes each.
1442 Each other input char may or may not need 1 byte,
1443 so this is an upper bound. The extra 5 are for invented
1444 leading and trailing newline-marker and final null. */
1445 maxsize = (sizeof (*defn) + (limit - p) + 5);
1447 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1456 defn = (DEFINITION *) dmalloc (maxsize);
1457 defn->noExpand = FALSE;
1459 defn->pattern = NULL;
1460 defn->nargs = nargs;
1461 defn->predefined = NULL;
1463 exp_p = defn->expansion = (char *) defn + sizeof (*defn);
1466 defn->rest_args = NULL;
1467 defn->args.argnames = NULL;
1473 /* Add one initial space escape-marker to prevent accidental
1474 token-pasting (often removed by macroexpand). */
1478 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1479 cppReader_errorLit (pfile,
1480 cstring_makeLiteralTemp ("`##' at start of macro definition"));
1484 /* Process the main body of the definition. */
1486 int skipped_arg = 0;
1487 register char c = *p++;
1491 if (!cppReader_isTraditional (pfile)) {
1495 if (expected_delimiter != '\0')
1497 if (c == expected_delimiter)
1498 expected_delimiter = '\0';
1502 expected_delimiter = c;
1504 /*@switchbreak@*/ break;
1507 if (p < limit && (expected_delimiter != '\0'))
1509 /* In a string, backslash goes through
1510 and makes next char ordinary. */
1513 /*@switchbreak@*/ break;
1516 /* An '@' in a string or character constant stands for itself,
1517 and does not need to be escaped. */
1518 if (expected_delimiter == '\0')
1523 /*@switchbreak@*/ break;
1526 /* # is ordinary inside a string. */
1527 if (expected_delimiter != '\0')
1529 /*@switchbreak@*/ break;
1532 if (p < limit && *p == '#') {
1533 /* ##: concatenate preceding and following tokens. */
1534 /* Take out the first #, discard preceding whitespace. */
1538 while (exp_p > lastp && is_hor_space[(int) exp_p[-1]])
1544 /* Skip the second #. */
1546 /* Discard following whitespace. */
1547 SKIP_WHITE_SPACE (p);
1551 cppReader_errorLit (pfile,
1552 cstring_makeLiteralTemp ("`##' at end of macro definition"));
1554 } else if (nargs >= 0) {
1555 /* Single #: stringify following argument ref.
1556 Don't leave the # in the expansion. */
1558 SKIP_WHITE_SPACE (p);
1559 if (p == limit || ! is_idstart[(int) *p]
1560 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '"')))
1561 cppReader_errorLit (pfile,
1562 cstring_makeLiteralTemp ("`#' operator is not followed by a macro argument name"));
1569 /*@switchbreak@*/ break;
1572 /* In -traditional mode, recognize arguments inside strings and
1573 and character constants, and ignore special properties of #.
1574 Arguments inside strings are considered "stringified", but no
1575 extra quote marks are supplied. */
1579 if (expected_delimiter != '\0') {
1580 if (c == expected_delimiter)
1581 expected_delimiter = '\0';
1583 expected_delimiter = c;
1584 /*@switchbreak@*/ break;
1587 /* Backslash quotes delimiters and itself, but not macro args. */
1588 if (expected_delimiter != '\0' && p < limit
1589 && (*p == expected_delimiter || *p == '\\')) {
1593 /*@switchbreak@*/ break;
1596 if (expected_delimiter != '\0') /* No comments inside strings. */
1597 /*@switchbreak@*/ break;
1599 /* If we find a comment that wasn't removed by cppReader_handleDirective,
1600 this must be -traditional. So replace the comment with
1604 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
1609 /*@switchbreak@*/ break;
1613 /* Handle the start of a symbol. */
1614 if (is_idchar[(int) c] && nargs > 0) {
1615 char *id_beg = p - 1;
1619 while (p != limit && is_idchar[(int) *p])
1624 id_len = p - id_beg;
1626 if (is_idstart[(int) c]
1627 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
1628 register struct arglist *arg;
1630 for (arg = arglist; arg != NULL; arg = arg->next) {
1631 struct reflist *tpat;
1633 if (arg->name[0] == c
1634 && arg->length == id_len
1635 && strncmp (arg->name, id_beg, size_fromInt (id_len)) == 0) {
1638 if (expected_delimiter && CPPOPTIONS (pfile)->warn_stringify) {
1639 if (cppReader_isTraditional (pfile)) {
1640 cppReader_warning (pfile,
1641 message ("macro argument `%x' is stringified.",
1642 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1644 cppReader_warning (pfile,
1645 message ("macro arg `%x' would be stringified with -traditional.",
1646 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1649 /* If ANSI, don't actually substitute inside a string. */
1650 if (!cppReader_isTraditional (pfile) && expected_delimiter)
1651 /*@innerbreak@*/ break;
1652 /* make a pat node for this arg and append it to the end of
1654 tpat = (struct reflist *) dmalloc (sizeof (*tpat));
1656 tpat->raw_before = (concat == id_beg);
1657 tpat->raw_after = 0;
1658 tpat->rest_args = arg->rest_args;
1659 tpat->stringify = (cppReader_isTraditional (pfile)
1660 ? expected_delimiter != '\0'
1661 : stringify == id_beg);
1665 defn->pattern = tpat;
1669 endpat->next = tpat;
1671 } /*@=branchstate@*/ /* evs 2000 was =branchstate */
1675 tpat->argno = arg->argno;
1676 tpat->nchars = exp_p - lastp;
1680 SKIP_WHITE_SPACE (p1);
1682 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
1684 tpat->raw_after = 1;
1687 lastp = exp_p; /* place to start copying from next time */
1690 /*@innerbreak@*/ break;
1695 /* If this was not a macro arg, copy it into the expansion. */
1696 if (skipped_arg == 0) {
1697 register char *lim1 = p;
1705 if (stringify == id_beg)
1706 cppReader_errorLit (pfile,
1707 cstring_makeLiteralTemp ("`#' operator should be followed by a macro argument name"));
1712 if (!cppReader_isTraditional (pfile) && expected_delimiter == '\0')
1714 /* If ANSI, put in a "@ " marker to prevent token pasting.
1715 But not if "inside a string" (which in ANSI mode
1716 happens only for -D option). */
1723 defn->length = size_fromInt (exp_p - defn->expansion);
1725 /* Crash now if we overrun the allocated size. */
1726 if (defn->length + 1 > maxsize)
1728 llfatalbug (cstring_makeLiteral ("Maximum definition size exceeded."));
1735 * special extension string that can be added to the last macro argument to
1736 * allow it to absorb the "rest" of the arguments when expanded. Ex:
1737 * #define wow(a, b...) process (b, a, b)
1738 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
1739 * { wow (one, two); } -> { process (two, one, two); }
1740 * if this "rest_arg" is used with the concat token '##' and if it is not
1741 * supplied then the token attached to with ## will not be outputted. Ex:
1742 * #define wow (a, b...) process (b ## , a, ## b)
1743 * { wow (1, 2); } -> { process (2, 1, 2); }
1744 * { wow (one); } -> { process (one); {
1747 /*@-readonlytrans@*/
1748 static char rest_extension[] = "...";
1749 /*:=readonlytrans@*/
1752 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
1754 /* Create a DEFINITION node from a #define directive. Arguments are
1755 as for do_define. */
1757 static /*@null@*/ MACRODEF
1758 create_definition (char *buf, char *limit,
1759 cppReader *pfile, bool predefinition,
1762 char *bp; /* temp ptr into input buffer */
1763 char *symname; /* remember where symbol name starts */
1764 int sym_length; /* and how long it is */
1765 int rest_args = 0; /* really int! */
1768 cstring file = (CPPBUFFER (pfile) != NULL)
1769 ? CPPBUFFER (pfile)->nominal_fname : cstring_makeLiteralTemp ("");
1771 int arglengths = 0; /* Accumulate lengths of arg names
1772 plus number of args. */
1775 cppBuffer_lineAndColumn (CPPBUFFER (pfile), &line, &col);
1779 while (is_hor_space[(int) *bp])
1784 symname = bp; /* remember where it starts */
1786 sym_length = cppReader_checkMacroName (pfile, bp, cstring_makeLiteralTemp ("macro"));
1790 /* Lossage will occur if identifiers or control keywords are broken
1791 across lines using backslash. This is not the right place to take
1795 struct arglist *arg_ptrs = NULL;
1798 bp++; /* skip '(' */
1799 SKIP_WHITE_SPACE (bp);
1801 /* Loop over macro argument names. */
1804 struct arglist *temp = (struct arglist *) dmalloc (sizeof (*temp));
1806 temp->next = arg_ptrs;
1807 temp->argno = argno++;
1808 temp->rest_args = 0;
1814 cppReader_pedwarn (pfile,
1815 message ("another parameter follows `%s'",
1816 cstring_fromChars (rest_extension)));
1819 if (!is_idstart[(int) *bp])
1821 cppReader_pedwarnLit (pfile,
1822 cstring_makeLiteralTemp ("invalid character in macro parameter name"));
1825 /* Find the end of the arg name. */
1826 while (is_idchar[(int) *bp])
1829 /* do we have a "special" rest-args extension here? */
1830 if (limit - bp > size_toInt (REST_EXTENSION_LENGTH)
1831 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
1834 temp->rest_args = 1;
1835 /*@innerbreak@*/ break;
1839 temp->length = bp - temp->name;
1843 bp += REST_EXTENSION_LENGTH;
1846 arglengths += temp->length + 2;
1847 SKIP_WHITE_SPACE (bp);
1849 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
1850 cppReader_errorLit (pfile,
1851 cstring_makeLiteralTemp ("Parameter list for #define is not parseable"));
1857 SKIP_WHITE_SPACE (bp);
1860 cppReader_errorLit (pfile,
1861 cstring_makeLiteralTemp ("unterminated parameter list in `#define'"));
1865 struct arglist *otemp;
1867 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
1869 if (temp->length == otemp->length &&
1870 strncmp (temp->name, otemp->name, size_fromInt (temp->length)) == 0) {
1871 cstring name = cstring_copyLength (temp->name, temp->length);
1872 cppReader_error (pfile,
1873 message ("duplicate argument name `%x' in `#define'", name));
1880 ++bp; /* skip paren */
1881 SKIP_WHITE_SPACE (bp);
1882 /* now everything from bp before limit is the definition. */
1883 defn = collect_expansion (pfile, bp, limit, argno, arg_ptrs);
1884 defn->rest_args = rest_args;
1886 /* Now set defn->args.argnames to the result of concatenating
1887 the argument names in reverse order
1888 with comma-space between them. */
1889 defn->args.argnames = (char *) dmalloc (size_fromInt (arglengths + 1));
1892 struct arglist *temp;
1894 for (temp = arg_ptrs; temp != NULL; temp = temp->next) {
1895 memcpy (&defn->args.argnames[i], temp->name, size_fromInt (temp->length));
1897 if (temp->next != 0) {
1898 defn->args.argnames[i++] = ',';
1899 defn->args.argnames[i++] = ' ';
1903 defn->args.argnames[i] = '\0';
1908 /* Simple expansion or empty definition. */
1912 if (is_hor_space[(int) *bp]) {
1914 SKIP_WHITE_SPACE (bp);
1917 case '!': case '"': case '#': case '%': case '&': case '\'':
1918 case ')': case '*': case '+': case ',': case '-': case '.':
1919 case '/': case ':': case ';': case '<': case '=': case '>':
1920 case '?': case '[': case '\\': case ']': case '^': case '{':
1921 case '|': case '}': case '~':
1922 cppReader_warning (pfile,
1923 message ("Missing white space after #define %x",
1924 cstring_prefix (cstring_fromChars (symname),
1929 cppReader_pedwarn (pfile,
1930 message ("Missing white space after #define %x",
1931 cstring_prefix (cstring_fromChars (symname),
1937 /* now everything from bp before limit is the definition. */
1938 defn = collect_expansion (pfile, bp, limit, -1, NULL);
1939 defn->args.argnames = mstring_createEmpty ();
1942 defn->noExpand = noExpand;
1943 DPRINTF (("No expand: %d", noExpand));
1947 /* not: llassert (cstring_isUndefined (defn->file)); */
1950 /* OP is null if this is a predefinition */
1951 defn->predefined = predefinition;
1953 mdef.symnam = symname;
1954 mdef.symlen = sym_length;
1964 /* Check a purported macro name SYMNAME, and yield its length.
1965 USAGE is the kind of name this is intended for. */
1967 int cppReader_checkMacroName (cppReader *pfile,
1974 for (p = symname; is_idchar[(int) *p]; p++)
1979 sym_length = size_fromInt (p - symname);
1982 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
1983 cppReader_error (pfile, message ("invalid %s name", usage));
1984 else if (!is_idstart[(int) *symname])
1986 char *msg = (char *) dmalloc (sym_length + 1);
1987 memcpy (msg, symname, sym_length);
1988 msg[sym_length] = '\0';
1989 cppReader_error (pfile, message ("invalid %s name `%s'", usage,
1990 cstring_fromChars (msg)));
1995 if ((strncmp (symname, "defined", 7) == 0) && sym_length == 7)
1997 cppReader_error (pfile, message ("invalid %s name `defined'", usage));
2001 return size_toInt (sym_length);
2004 /* Return zero if two DEFINITIONs are isomorphic. */
2007 compare_defs (DEFINITION *d1, DEFINITION *d2)
2009 register struct reflist *a1, *a2;
2010 register char *p1 = d1->expansion;
2011 register char *p2 = d2->expansion;
2014 if (d1->nargs != d2->nargs)
2019 llassert (d1->args.argnames != NULL);
2020 llassert (d2->args.argnames != NULL);
2022 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames) != 0)
2027 for (a1 = d1->pattern, a2 = d2->pattern;
2028 (a1 != NULL) && (a2 != NULL);
2029 a1 = a1->next, a2 = a2->next) {
2030 if (!((a1->nchars == a2->nchars
2031 && (strncmp (p1, p2, size_fromInt (a1->nchars)) == 0))
2032 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
2033 || a1->argno != a2->argno
2034 || a1->stringify != a2->stringify
2035 || a1->raw_before != a2->raw_before
2036 || a1->raw_after != a2->raw_after)
2045 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
2046 p2, d2->length - (p2 - d2->expansion), 1))
2052 /* Return TRUE if two parts of two macro definitions are effectively different.
2053 One of the parts starts at BEG1 and has LEN1 chars;
2054 the other has LEN2 chars at BEG2.
2055 Any sequence of whitespace matches any other sequence of whitespace.
2056 FIRST means these parts are the first of a macro definition;
2057 so ignore leading whitespace entirely.
2058 LAST means these parts are the last of a macro definition;
2059 so ignore trailing whitespace entirely. */
2062 comp_def_part (bool first, char *beg1, int len1, char *beg2, int len2, bool last)
2064 char *end1 = beg1 + len1;
2065 char *end2 = beg2 + len2;
2068 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2069 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2072 while (beg1 != end1 && is_space[(int) end1[-1]]) { end1--; }
2073 while (beg2 != end2 && is_space[(int) end2[-1]]) { end2--; }
2075 while (beg1 != end1 && beg2 != end2) {
2076 if (is_space[(int) *beg1] && is_space[(int) *beg2]) {
2077 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2078 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2079 } else if (*beg1 == *beg2) {
2083 return (beg1 != end1) || (beg2 != end2);
2086 /* Process a #define command.
2087 BUF points to the contents of the #define command, as a contiguous string.
2088 LIMIT points to the first character past the end of the definition.
2089 KEYWORD is the keyword-table entry for #define,
2090 or NULL for a "predefined" macro. */
2093 do_defineAux (cppReader *pfile, struct directive *keyword,
2094 char *buf, char *limit, bool noExpand)
2100 DPRINTF (("Define aux: %d", noExpand));
2102 mdef = create_definition (buf, limit, pfile, keyword == NULL, noExpand);
2107 hashcode = hashf (mdef.symnam, mdef.symlen, CPP_HASHSIZE);
2109 DPRINTF (("Macro: %s / %s",
2110 cstring_copyLength (mdef.symnam, mdef.symlen),
2111 bool_unparse (noExpand)));
2113 if ((hp = cppReader_lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL)
2117 /* Redefining a precompiled key is ok. */
2118 if (hp->type == T_PCSTRING)
2120 /* Redefining a macro is ok if the definitions are the same. */
2121 else if (hp->type == T_MACRO)
2122 ok = !compare_defs (mdef.defn, hp->value.defn);
2123 /* Redefining a constant is ok with -D. */
2124 else if (hp->type == T_CONST)
2125 ok = !CPPOPTIONS (pfile)->done_initializing;
2130 /* Print the warning if it's not ok. */
2134 ** If we are passing through #define and #undef directives, do
2135 ** that for this re-definition now.
2138 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2140 /* llassert (keyword != NULL); */
2141 pass_thru_directive (buf, limit, pfile, keyword);
2144 cpp_setLocation (pfile);
2146 if (hp->type == T_MACRO)
2148 if (hp->value.defn->noExpand)
2150 ; /* error will be reported checking macros */
2156 message ("Macro %q already defined",
2157 cstring_copyLength (mdef.symnam, mdef.symlen)),
2158 message ("%q: Previous definition of %q",
2159 fileloc_unparseRaw (hp->value.defn->file,
2160 (int) hp->value.defn->line),
2161 cstring_copyLength (mdef.symnam, mdef.symlen)));
2166 genppllerror (FLG_MACROREDEF,
2167 message ("Macro %q already defined",
2168 cstring_copyLength (mdef.symnam,
2174 /* Replace the old definition. */
2176 hp->value.defn = mdef.defn;
2181 ** If we are passing through #define and #undef directives, do
2182 ** that for this new definition now.
2187 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2189 pass_thru_directive (buf, limit, pfile, keyword);
2192 DPRINTF (("Define macro: %s / %d",
2193 mdef.symnam, mdef.defn->noExpand));
2195 hn = cppReader_installMacro (mdef.symnam, mdef.symlen, mdef.defn, hashcode);
2197 } /*@=branchstate@*/
2207 do_define (cppReader *pfile, struct directive *keyword,
2208 char *buf, char *limit)
2210 DPRINTF (("Regular do define"));
2211 return do_defineAux (pfile, keyword, buf, limit, FALSE);
2214 /* This structure represents one parsed argument in a macro call.
2215 `raw' points to the argument text as written (`raw_length' is its length).
2216 `expanded' points to the argument's macro-expansion
2217 (its length is `expand_length').
2218 `stringified_length' is the length the argument would have
2220 `use_count' is the number of times this macro arg is substituted
2221 into the macro. If the actual use count exceeds 10,
2222 the value stored is 10. */
2224 /* raw and expanded are relative to ARG_BASE */
2226 #define ARG_BASE ((pfile)->token_buffer)
2229 /* Strings relative to pfile->token_buffer */
2235 int stringified_length;
2240 /* Allocate a new cppBuffer for PFILE, and push it on the input buffer stack.
2241 If BUFFER != NULL, then use the LENGTH characters in BUFFER
2242 as the new input buffer.
2243 Return the new buffer, or NULL on failure. */
2245 /*@null@*/ /*@exposed@*/ cppBuffer *
2246 cppReader_pushBuffer (cppReader *pfile, char *buffer, size_t length)
2248 cppBuffer *buf = cppReader_getBuffer (pfile);
2250 if (buf == pfile->buffer_stack)
2252 cppReader_fatalError
2254 message ("%s: macro or `#include' recursion too deep",
2255 (buf->fname != NULL)
2257 : cstring_makeLiteral ("<no name>")));
2258 sfreeEventually (buffer);
2262 llassert (buf != NULL);
2265 memset ((char *) buf, 0, sizeof (*buf));
2266 CPPBUFFER (pfile) = buf;
2268 buf->if_stack = pfile->if_stack;
2269 buf->cleanup = cppReader_nullCleanup;
2270 buf->underflow = cppReader_nullUnderflow;
2272 buf->cur = buf->buf;
2276 buf->alimit = buf->rlimit = buffer + length;
2280 buf->alimit = buf->rlimit = NULL;
2287 cppReader_popBuffer (cppReader *pfile)
2289 cppBuffer *buf = CPPBUFFER (pfile);
2291 llassert (buf != NULL);
2293 (void) (*buf->cleanup) (buf, pfile);
2294 return ++CPPBUFFER (pfile);
2297 /* Scan until CPPBUFFER (PFILE) is exhausted into PFILE->token_buffer.
2298 Pop the buffer when done. */
2301 cppReader_scanBuffer (cppReader *pfile)
2303 cppBuffer *buffer = CPPBUFFER (pfile);
2306 enum cpp_token token;
2308 token = cppGetToken (pfile);
2310 if (token == CPP_EOF) /* Should not happen ... */
2315 if (token == CPP_POP && CPPBUFFER (pfile) == buffer)
2317 (void) cppReader_popBuffer (pfile);
2324 * Rescan a string (which may have escape marks) into pfile's buffer.
2325 * Place the result in pfile->token_buffer.
2327 * The input is copied before it is scanned, so it is safe to pass
2328 * it something from the token_buffer that will get overwritten
2329 * (because it follows cppReader_getWritten). This is used by do_include.
2333 cpp_expand_to_buffer (cppReader *pfile, char *buf, size_t length)
2335 register cppBuffer *ip;
2336 char *limit = buf + length;
2337 char *buf1, *p1, *p2;
2342 /* Set up the input on the input stack. */
2344 buf1 = (char *) dmalloc (length + 1);
2354 buf1[length] = '\0';
2356 ip = cppReader_pushBuffer (pfile, buf1, length);
2361 ip->has_escapes = TRUE;
2363 /* Scan the input, create the output. */
2364 cppReader_scanBuffer (pfile);
2366 cppReader_nullTerminate (pfile);
2370 adjust_position (char *buf, char *limit, int *linep, int *colp)
2376 (*linep)++, (*colp) = 1;
2382 /* Move line_base forward, updating lineno and colno. */
2385 update_position (cppBuffer *pbuf)
2388 char *new_pos = pbuf->cur;
2389 register struct parse_marker *mark;
2391 llassert (pbuf->buf != NULL);
2392 old_pos = pbuf->buf + pbuf->line_base;
2394 for (mark = pbuf->marks; mark != NULL; mark = mark->next)
2396 if (pbuf->buf + mark->position < new_pos)
2397 new_pos = pbuf->buf + mark->position;
2399 pbuf->line_base += new_pos - old_pos;
2401 llassert (old_pos != NULL);
2402 llassert (new_pos != NULL);
2404 adjust_position (old_pos, new_pos, &pbuf->lineno, &pbuf->colno);
2408 cppBuffer_lineAndColumn (/*@null@*/ cppBuffer *pbuf, /*@out@*/ int *linep,
2409 /*@null@*/ /*@out@*/ int *colp)
2417 } /*@=branchstate@*/
2421 *linep = pbuf->lineno;
2422 *colp = pbuf->colno;
2424 llassert (pbuf->buf != NULL);
2425 llassert (pbuf->cur != NULL);
2427 adjust_position (pbuf->buf + pbuf->line_base, pbuf->cur, linep, colp);
2436 /* Return the cppBuffer that corresponds to a file (not a macro). */
2438 /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_fileBuffer (cppReader *pfile)
2440 cppBuffer *ip = cppReader_getBuffer (pfile);
2443 ip != NULL && ip != cppReader_nullBuffer (pfile);
2444 ip = cppBuffer_prevBuffer (ip))
2446 if (ip->fname != NULL)
2456 count_newlines (char *buf, char *limit)
2458 register long count = 0;
2470 * write out a #line command, for instance, after an #include file.
2471 * If CONDITIONAL is nonzero, we can omit the #line if it would
2472 * appear to be a no-op, and we can output a few newlines instead
2473 * if we want to increase the line number by a small amount.
2474 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
2478 output_line_command (cppReader *pfile, bool conditional,
2479 enum file_change_code file_change)
2482 cppBuffer *ip = CPPBUFFER (pfile);
2485 llassert (ip != NULL);
2487 if (ip->fname == NULL)
2490 update_position (ip);
2492 if (CPPOPTIONS (pfile)->no_line_commands
2493 || CPPOPTIONS (pfile)->no_output)
2496 buf = CPPBUFFER (pfile);
2498 llassert (buf != NULL);
2503 llassert (ip->cur != NULL);
2505 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
2507 if (CPPOPTIONS (pfile)->no_line_commands)
2511 if (line == pfile->lineno)
2514 /* If the inherited line number is a little too small,
2515 output some newlines instead of a #line command. */
2517 if (line > pfile->lineno && line < pfile->lineno + 8)
2519 cppReader_reserve (pfile, 20);
2520 while (line > pfile->lineno)
2522 cppReader_putCharQ (pfile, '\n');
2530 cppReader_reserve (pfile,
2531 size_fromInt (4 * cstring_length (ip->nominal_fname) + 50));
2534 #ifdef OUTPUT_LINE_COMMANDS
2535 static char sharp_line[] = "#line ";
2537 static char sharp_line[] = "# ";
2539 cppReader_putStrN (pfile, sharp_line, sizeof(sharp_line)-1);
2542 sprintf (cppReader_getPWritten (pfile), "%d ", line);
2543 cppReader_adjustWritten (pfile, strlen (cppReader_getPWritten (pfile)));
2545 quote_string (pfile, cstring_toCharsSafe (ip->nominal_fname));
2547 if (file_change != same_file) {
2548 cppReader_putCharQ (pfile, ' ');
2549 cppReader_putCharQ (pfile, file_change == enter_file ? '1' : '2');
2551 /* Tell cc1 if following text comes from a system header file. */
2552 if (ip->system_header_p != '\0') {
2553 cppReader_putCharQ (pfile, ' ');
2554 cppReader_putCharQ (pfile, '3');
2556 #ifndef NO_IMPLICIT_EXTERN_C
2557 /* Tell cc1plus if following text should be treated as C. */
2558 if (ip->system_header_p == (char) 2 && CPPOPTIONS (pfile)->cplusplus) {
2559 cppReader_putCharQ (pfile, ' ');
2560 cppReader_putCharQ (pfile, '4');
2563 cppReader_putCharQ (pfile, '\n');
2564 pfile->lineno = line;
2569 * Parse a macro argument and append the info on PFILE's token_buffer.
2570 * REST_ARGS means to absorb the rest of the args.
2571 * Return nonzero to indicate a syntax error.
2574 static enum cpp_token
2575 macarg (cppReader *pfile, int rest_args)
2578 enum cpp_token token;
2579 char save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
2580 bool oldexpand = pfile->no_macro_expand;
2581 CPPOPTIONS (pfile)->put_out_comments = 1;
2583 /* Try to parse as much of the argument as exists at this
2584 input stack level. */
2586 pfile->no_macro_expand = TRUE;
2590 token = cppGetToken (pfile);
2597 /* If we've hit end of file, it's an error (reported by caller).
2598 Ditto if it's the end of cpp_expand_to_buffer text.
2599 If we've hit end of macro, just continue. */
2600 if (!cppBuffer_isMacro (CPPBUFFER (pfile)))
2602 /*@switchbreak@*/ break;
2605 /*@switchbreak@*/ break;
2609 /*@switchbreak@*/ break;
2611 /* if we've returned to lowest level and
2612 we aren't absorbing all args */
2613 if (paren == 0 && rest_args == 0)
2615 /*@switchbreak@*/ break;
2617 /* Remove ',' or ')' from argument buffer. */
2618 cppReader_adjustWritten (pfile, -1);
2626 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
2627 pfile->no_macro_expand = oldexpand;
2633 /* Turn newlines to spaces in the string of length LENGTH at START,
2634 except inside of string constants.
2635 The string is copied into itself with its beginning staying fixed. */
2638 change_newlines (char *start, int length)
2642 register char *limit;
2646 limit = start + length;
2649 while (ibp < limit) {
2650 *obp++ = c = *ibp++;
2655 /* Notice and skip strings, so that we don't delete newlines in them. */
2658 while (ibp < limit) {
2659 *obp++ = c = *ibp++;
2661 /*@innerbreak@*/ break;
2662 if (c == '\n' && quotec == '\'')
2663 /*@innerbreak@*/ break;
2666 /*@switchbreak@*/ break;
2673 static /*@observer@*/ struct tm *
2674 timestamp (/*@returned@*/ cppReader *pfile)
2676 if (pfile->timebuf == NULL)
2678 time_t t = time ((time_t *) 0);
2679 pfile->timebuf = localtime (&t);
2682 llassert (pfile->timebuf != NULL);
2684 return pfile->timebuf;
2687 static ob_mstring monthnames[] = {
2688 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2689 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
2693 * expand things like __FILE__. Place the expansion into the output
2694 * buffer *without* rescanning.
2698 special_symbol (HASHNODE *hp, cppReader *pfile)
2700 cstring buf = cstring_undefined;
2706 int paren = 0; /* For special `defined' keyword */
2708 for (ip = cppReader_getBuffer (pfile); ip != NULL; ip = cppBuffer_prevBuffer (ip))
2710 if (ip == cppReader_nullBuffer (pfile))
2712 cppReader_errorLit (pfile,
2713 cstring_makeLiteralTemp ("cccp error: not in any file?!"));
2714 return; /* the show must go on */
2717 if (ip != NULL && ip->fname != NULL)
2729 if (hp->type == T_BASE_FILE)
2731 while (cppBuffer_prevBuffer (ip) != cppReader_nullBuffer (pfile))
2733 ip = cppBuffer_prevBuffer (ip);
2737 llassert (ip != NULL);
2738 string = cstring_toCharsSafe (ip->nominal_fname);
2745 cppReader_reserve (pfile, 3 + 4 * strlen (string));
2746 quote_string (pfile, string);
2750 case T_INCLUDE_LEVEL:
2752 ip = cppReader_getBuffer (pfile);
2754 for (; ip != cppReader_nullBuffer (pfile) && ip != NULL;
2755 ip = cppBuffer_prevBuffer (ip))
2757 if (ip != NULL && ip->fname != NULL)
2763 buf = message ("%d", true_indepth - 1);
2767 buf = message ("\"%s\"", cstring_makeLiteralTemp (CPP_VERSION));
2770 #ifndef NO_BUILTIN_SIZE_TYPE
2772 buf = cstring_makeLiteral (SIZE_TYPE);
2776 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2777 case T_PTRDIFF_TYPE:
2778 buf = cstring_makeLiteral (PTRDIFF_TYPE);
2783 buf = cstring_makeLiteral (cppReader_wcharType (pfile));
2786 case T_USER_LABEL_PREFIX_TYPE:
2787 buf = cstring_makeLiteral (USER_LABEL_PREFIX);
2790 case T_REGISTER_PREFIX_TYPE:
2791 buf = cstring_makeLiteral (REGISTER_PREFIX);
2795 buf = message ("%d", hp->value.ival);
2802 int line = ip->lineno;
2803 int col = ip->colno;
2805 llassert (ip->cur != NULL);
2806 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
2808 buf = message ("%d", (int) line);
2820 char *sbuf = (char *) dmalloc (20);
2821 timebuf = timestamp (pfile);
2822 if (hp->type == T_DATE)
2824 sprintf (sbuf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
2825 timebuf->tm_mday, timebuf->tm_year + 1900);
2829 sprintf (sbuf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
2833 buf = cstring_fromCharsNew (sbuf);
2838 case T_SPEC_DEFINED:
2839 buf = cstring_makeLiteral (" 0 "); /* Assume symbol is not defined */
2840 ip = cppReader_getBuffer (pfile);
2842 llassert (ip->cur != NULL);
2843 SKIP_WHITE_SPACE (ip->cur);
2845 if (*ip->cur == '(')
2848 ip->cur++; /* Skip over the paren */
2849 SKIP_WHITE_SPACE (ip->cur);
2852 if (!is_idstart[(int) *ip->cur])
2854 if (ip->cur[0] == 'L' && (ip->cur[1] == '\'' || ip->cur[1] == '"'))
2857 if ((hp = cppReader_lookup (ip->cur, -1, -1)) != 0)
2860 buf = cstring_makeLiteral (" 1 ");
2863 while (is_idchar[(int) *ip->cur])
2868 SKIP_WHITE_SPACE (ip->cur);
2872 if (*ip->cur != ')')
2880 cppReader_errorLit (pfile,
2881 cstring_makeLiteralTemp ("`defined' without an identifier"));
2885 cpp_setLocation (pfile);
2886 llfatalerror (message ("Pre-processing error: invalid special hash type"));
2889 len = size_fromInt (cstring_length (buf));
2891 cppReader_reserve (pfile, len + 1);
2892 cppReader_putStrN (pfile, cstring_toCharsSafe (buf), len);
2893 cppReader_nullTerminateQ (pfile);
2899 /* Write out a #define command for the special named MACRO_NAME
2900 to PFILE's token_buffer. */
2903 dump_special_to_buffer (cppReader *pfile, char *macro_name)
2905 static char define_directive[] = "#define ";
2906 size_t macro_name_length = strlen (macro_name);
2907 output_line_command (pfile, 0, same_file);
2908 cppReader_reserve (pfile, sizeof(define_directive) + macro_name_length);
2909 cppReader_putStrN (pfile, define_directive, sizeof(define_directive)-1);
2910 cppReader_putStrN (pfile, macro_name, macro_name_length);
2911 cppReader_putCharQ (pfile, ' ');
2912 cpp_expand_to_buffer (pfile, macro_name, macro_name_length);
2913 cppReader_putChar (pfile, '\n');
2916 /* Initialize the built-in macros. */
2919 cppReader_installBuiltin (/*@observer@*/ char *name, ctype ctyp,
2920 int len, enum node_type type,
2921 int ivalue, /*@null@*/ /*@only@*/ char *value,
2924 cstring sname = cstring_fromCharsNew (name);
2926 llassert (usymtab_inGlobalScope ());
2929 ** Be careful here: this is done before the ctype table has
2930 ** been initialized.
2933 if (!usymtab_exists (sname))
2935 uentry ue = uentry_makeConstant (sname, ctyp, fileloc_createBuiltin ());
2937 if (ctype_equal (ctyp, ctype_string))
2939 qualList ql = qualList_new ();
2940 ql = qualList_add (ql, QU_OBSERVER);
2941 uentry_reflectQualifiers (ue, ql);
2945 usymtab_addGlobalEntry (ue);
2952 (void) cppReader_install (name, len, type, ivalue, value, hash);
2953 cstring_free (sname);
2957 cppReader_installBuiltinType (/*@observer@*/ char *name, ctype ctyp,
2958 int len, enum node_type type,
2960 /*@only@*/ /*@null@*/ char *value, int hash)
2962 cstring sname = cstring_fromChars (name);
2963 /* evs 2000 07 10 - removed a memory leak, detected by lclint */
2965 llassert (usymtab_inGlobalScope ());
2967 if (!usymtab_exists (sname))
2969 uentry ue = uentry_makeDatatype (sname, ctyp,
2971 fileloc_createBuiltin ());
2972 usymtab_addGlobalEntry (ue);
2975 (void) cppReader_install (name, len, type, ivalue, value, hash);
2979 initialize_builtins (cppReader *pfile)
2981 cppReader_installBuiltin ("__LINE__", ctype_int, -1, T_SPECLINE, 0, NULL, -1);
2982 cppReader_installBuiltin ("__DATE__", ctype_string, -1, T_DATE, 0, NULL, -1);
2983 cppReader_installBuiltin ("__FILE__", ctype_string, -1, T_FILE, 0, NULL, -1);
2984 cppReader_installBuiltin ("__BASE_FILE__", ctype_string, -1, T_BASE_FILE, 0, NULL, -1);
2985 cppReader_installBuiltin ("__INCLUDE_LEVEL__", ctype_int, -1, T_INCLUDE_LEVEL, 0, NULL, -1);
2986 cppReader_installBuiltin ("__VERSION__", ctype_string, -1, T_VERSION, 0, NULL, -1);
2987 #ifndef NO_BUILTIN_SIZE_TYPE
2988 cppReader_installBuiltinType ("__SIZE_TYPE__", ctype_anyintegral, -1, T_SIZE_TYPE, 0, NULL, -1);
2990 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2991 cppReader_installBuiltinType ("__PTRDIFF_TYPE__ ", ctype_anyintegral, -1, T_PTRDIFF_TYPE, 0, NULL, -1);
2993 cppReader_installBuiltinType ("__WCHAR_TYPE__", ctype_anyintegral, -1, T_WCHAR_TYPE, 0, NULL, -1);
2994 cppReader_installBuiltin ("__USER_LABEL_PREFIX__", ctype_string, -1, T_USER_LABEL_PREFIX_TYPE, 0, NULL, -1);
2995 cppReader_installBuiltin ("__REGISTER_PREFIX__", ctype_string, -1, T_REGISTER_PREFIX_TYPE, 0, NULL, -1);
2996 cppReader_installBuiltin ("__TIME__", ctype_string, -1, T_TIME, 0, NULL, -1);
2999 ** No, don't define __STDC__
3002 if (!cppReader_isTraditional (pfile))
3004 cppReader_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3011 cppReader_installBuiltin ("_WIN32", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3015 ** This is supplied using a -D by the compiler driver
3016 ** so that it is present only when truly compiling with GNU C.
3019 /* cppReader_install ("__GNUC__", -1, T_CONST, 2, 0, -1); */
3021 cppReader_installBuiltin ("__LCLINT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3023 if (CPPOPTIONS (pfile)->debug_output)
3025 dump_special_to_buffer (pfile, "__BASE_FILE__");
3026 dump_special_to_buffer (pfile, "__VERSION__");
3027 #ifndef NO_BUILTIN_SIZE_TYPE
3028 dump_special_to_buffer (pfile, "__SIZE_TYPE__");
3030 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3031 dump_special_to_buffer (pfile, "__PTRDIFF_TYPE__");
3033 dump_special_to_buffer (pfile, "__WCHAR_TYPE__");
3034 dump_special_to_buffer (pfile, "__DATE__");
3035 dump_special_to_buffer (pfile, "__TIME__");
3036 if (!cppReader_isTraditional (pfile))
3037 dump_special_to_buffer (pfile, "__STDC__");
3042 /* Return 1 iff a token ending in C1 followed directly by a token C2
3043 could cause mis-tokenization. */
3046 unsafe_chars (char c1, char c2)
3051 if (c2 == c1 || c2 == '=')
3055 case '0': case '1': case '2': case '3': case '4':
3056 case '5': case '6': case '7': case '8': case '9':
3057 case 'e': case 'E': case 'p': case 'P':
3058 if (c2 == '-' || c2 == '+')
3059 return 1; /* could extend a pre-processing number */
3062 if (c2 == '\'' || c2 == '\"')
3063 return 1; /* Could turn into L"xxx" or L'xxx'. */
3067 case 'a': case 'b': case 'c': case 'd': case 'f':
3068 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3069 case 'm': case 'n': case 'o': case 'q': case 'r':
3070 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3072 case 'A': case 'B': case 'C': case 'D': case 'F':
3073 case 'G': case 'H': case 'I': case 'J': case 'K':
3074 case 'M': case 'N': case 'O': case 'Q': case 'R':
3075 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3077 /* We're in the middle of either a name or a pre-processing number. */
3078 return (is_idchar[(int) c2] || c2 == '.');
3079 case '<': case '>': case '!': case '%': case '#': case ':':
3080 case '^': case '&': case '|': case '*': case '/': case '=':
3081 return (c2 == c1 || c2 == '=');
3086 /* Expand a macro call.
3087 HP points to the symbol that is the macro being called.
3088 Put the result of expansion onto the input stack
3089 so that subsequent input by our caller will use it.
3091 If macro wants arguments, caller has already verified that
3092 an argument list follows; arguments come from the input stack. */
3095 macroexpand (cppReader *pfile, /*@dependent@*/ HASHNODE *hp)
3098 DEFINITION *defn = hp->value.defn;
3104 size_t old_written = cppReader_getWritten (pfile);
3108 struct argdata *args = NULL;
3110 pfile->output_escapes++;
3112 cppBuffer_lineAndColumn (cppReader_fileBuffer (pfile), &start_line, &start_column);
3114 nargs = defn->nargs;
3118 enum cpp_token token = CPP_EOF;
3120 args = (struct argdata *) dmalloc ((nargs + 1) * sizeof (*args));
3122 for (i = 0; i < nargs; i++)
3124 args[i].expanded = 0;
3126 args[i].raw_length = 0;
3127 args[i].expand_length = args[i].stringified_length = -1;
3128 args[i].use_count = 0;
3132 ** Parse all the macro args that are supplied. I counts them.
3133 ** The first NARGS args are stored in ARGS.
3134 ** The rest are discarded. If rest_args is set then we assume
3135 ** macarg absorbed the rest of the args.
3141 cppReader_forward (pfile, 1); /* Discard the open-parenthesis before the first arg. */
3149 if (i < nargs || (nargs == 0 && i == 0))
3151 /* if we are working on last arg which absorbs rest of args... */
3152 if (i == nargs - 1 && defn->rest_args)
3157 args[i].raw = size_toLong (cppReader_getWritten (pfile));
3158 token = macarg (pfile, rest_args);
3159 args[i].raw_length = cppReader_getWritten (pfile) - args[i].raw;
3160 args[i].newlines = FALSE; /* FIXME */
3164 token = macarg (pfile, 0);
3167 if (token == CPP_EOF || token == CPP_POP)
3169 cppReader_errorWithLine (pfile, start_line, start_column,
3170 cstring_fromCharsNew ("unterminated macro call"));
3175 } while (token == CPP_COMMA);
3177 /* If we got one arg but it was just whitespace, call that 0 args. */
3185 bp = ARG_BASE + args[0].raw;
3186 lim = bp + args[0].raw_length;
3188 /* cpp.texi says for foo ( ) we provide one argument.
3189 However, if foo wants just 0 arguments, treat this as 0. */
3193 while (bp != lim && is_space[(int) *bp])
3203 /* Don't output an error message if we have already output one for
3204 a parse error above. */
3207 if (nargs == 0 && i > 0)
3209 cppReader_error (pfile,
3210 message ("arguments given to macro `%s'", hp->name));
3214 /* traditional C allows foo() if foo wants one argument. */
3215 if (nargs == 1 && i == 0 && cppReader_isTraditional (pfile))
3219 /* the rest args token is allowed to absorb 0 tokens */
3220 else if (i == nargs - 1 && defn->rest_args)
3223 cppReader_error (pfile,
3224 message ("macro `%s' used without args", hp->name));
3226 cppReader_error (pfile,
3227 message ("macro `%s' used with just one arg", hp->name));
3230 cppReader_error (pfile,
3231 message ("macro `%s' used with only %d args",
3237 cppReader_error (pfile,
3238 message ("macro `%s' used with too many (%d) args", hp->name, i));
3246 /* If macro wants zero args, we parsed the arglist for checking only.
3247 Read directly from the macro definition. */
3251 xbuf = defn->expansion;
3252 xbuf_len = defn->length;
3256 char *exp = defn->expansion;
3257 int offset; /* offset in expansion,
3258 copied a piece at a time */
3259 size_t totlen; /* total amount of exp buffer filled so far */
3261 register struct reflist *ap, *last_ap;
3263 /* Macro really takes args. Compute the expansion of this call. */
3265 /* Compute length in characters of the macro's expansion.
3266 Also count number of times each arg is used. */
3267 xbuf_len = defn->length;
3269 llassert (args != NULL);
3271 for (ap = defn->pattern; ap != NULL; ap = ap->next)
3275 struct argdata *arg = &args[ap->argno];
3277 /* Stringify it it hasn't already been */
3280 if (arg->stringified_length < 0)
3282 int arglen = arg->raw_length;
3283 bool escaped = FALSE;
3284 char in_string = '\0';
3287 /* Initially need_space is -1. Otherwise, 1 means the
3288 previous character was a space, but we suppressed it;
3289 0 means the previous character was a non-space. */
3290 int need_space = -1;
3293 arg->stringified = cppReader_getWritten (pfile);
3294 if (!cppReader_isTraditional (pfile))
3295 cppReader_putChar (pfile, '\"'); /* insert beginning quote */
3296 for (; i < arglen; i++)
3298 c = (ARG_BASE + arg->raw)[i];
3300 if (in_string == '\0')
3302 /* Internal sequences of whitespace are replaced by
3303 one space except within an string or char token.*/
3304 if (is_space[(int) c])
3306 if (cppReader_getWritten (pfile) > arg->stringified
3307 && (cppReader_getPWritten (pfile))[-1] == '@')
3309 /* "@ " escape markers are removed */
3310 cppReader_adjustWritten (pfile, -1);
3311 /*@innercontinue@*/ continue;
3313 if (need_space == 0)
3315 /*@innercontinue@*/ continue;
3317 else if (need_space > 0)
3318 cppReader_putChar (pfile, ' ');
3334 if (in_string != '\0')
3339 else if (c == '\"' || c == '\'')
3349 /* Escape these chars */
3350 if (c == '\"' || (in_string != '\0' && c == '\\'))
3351 cppReader_putChar (pfile, '\\');
3353 cppReader_putChar (pfile, c);
3356 cppReader_reserve (pfile, 4);
3357 sprintf (cppReader_getPWritten (pfile), "\\%03o",
3359 cppReader_adjustWritten (pfile, 4);
3362 if (!cppReader_isTraditional (pfile))
3363 cppReader_putChar (pfile, '\"'); /* insert ending quote */
3364 arg->stringified_length
3365 = size_toInt (cppReader_getWritten (pfile) - arg->stringified);
3368 xbuf_len += args[ap->argno].stringified_length;
3370 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
3372 /* Add 4 for two newline-space markers to prevent
3373 token concatenation. */
3374 xbuf_len += args[ap->argno].raw_length + 4;
3378 /* We have an ordinary (expanded) occurrence of the arg.
3379 So compute its expansion, if we have not already. */
3381 if (args[ap->argno].expand_length < 0)
3383 args[ap->argno].expanded = cppReader_getWritten (pfile);
3384 cpp_expand_to_buffer (pfile,
3385 ARG_BASE + args[ap->argno].raw,
3386 size_fromInt (args[ap->argno].raw_length));
3388 args[ap->argno].expand_length
3389 = size_toInt (cppReader_getWritten (pfile) - args[ap->argno].expanded);
3392 /* Add 4 for two newline-space markers to prevent
3393 token concatenation. */
3394 xbuf_len += args[ap->argno].expand_length + 4;
3396 if (args[ap->argno].use_count < 10)
3397 args[ap->argno].use_count++;
3400 xbuf = (char *) dmalloc (xbuf_len + 1);
3404 ** Generate in XBUF the complete expansion
3405 ** with arguments substituted in.
3406 ** TOTLEN is the total size generated so far.
3407 ** OFFSET is the index in the definition
3408 ** of where we are copying from.
3414 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
3415 last_ap = ap, ap = ap->next)
3417 register struct argdata *arg = &args[ap->argno];
3418 size_t count_before = totlen;
3420 /* Add chars to XBUF. */
3421 for (i = 0; i < ap->nchars; i++, offset++)
3423 xbuf[totlen++] = exp[offset];
3426 /* If followed by an empty rest arg with concatenation,
3427 delete the last run of nonwhite chars. */
3428 if (rest_zero && totlen > count_before
3429 && ((ap->rest_args && ap->raw_before)
3430 || (last_ap != NULL && last_ap->rest_args
3431 && last_ap->raw_after)))
3433 /* Delete final whitespace. */
3434 while (totlen > count_before && is_space[(int) xbuf[totlen - 1]])
3439 /* Delete the nonwhites before them. */
3440 while (totlen > count_before && ! is_space[(int) xbuf[totlen - 1]])
3446 if (ap->stringify != 0)
3449 memcpy (xbuf + totlen,
3450 ARG_BASE + arg->stringified,
3451 size_fromInt (arg->stringified_length));
3452 totlen += arg->stringified_length;
3454 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
3461 p1 = ARG_BASE + arg->raw;
3462 l1 = p1 + arg->raw_length;
3466 while (p1 != l1 && is_space[(int) *p1])
3471 while (p1 != l1 && is_idchar[(int) *p1])
3473 xbuf[totlen++] = *p1++;
3476 /* Delete any no-reexpansion marker that follows
3477 an identifier at the beginning of the argument
3478 if the argument is concatenated with what precedes it. */
3479 if (p1[0] == '@' && p1[1] == '-')
3484 /* Arg is concatenated after: delete trailing whitespace,
3485 whitespace markers, and no-reexpansion markers. */
3488 if (is_space[(int) l1[-1]]) l1--;
3489 else if (l1[-1] == '-')
3492 /* If a `-' is preceded by an odd number of newlines then it
3493 and the last newline are a no-reexpansion marker. */
3494 while (p2 != p1 && p2[-1] == '\n')
3499 if (((l1 - 1 - p2) & 1) != 0)
3505 /*@innerbreak@*/ break;
3510 /*@innerbreak@*/ break;
3515 memcpy (xbuf + totlen, p1, size_fromInt (l1 - p1));
3523 expanded = ARG_BASE + arg->expanded;
3525 if (!ap->raw_before && totlen > 0
3526 && (arg->expand_length != 0)
3527 && !cppReader_isTraditional(pfile)
3528 && unsafe_chars (xbuf[totlen-1], expanded[0]))
3530 xbuf[totlen++] = '@';
3531 xbuf[totlen++] = ' ';
3534 memcpy (xbuf + totlen, expanded,
3535 size_fromInt (arg->expand_length));
3536 totlen += arg->expand_length;
3538 if (!ap->raw_after && totlen > 0
3539 && offset < size_toInt (defn->length)
3540 && !cppReader_isTraditional(pfile)
3541 && unsafe_chars (xbuf[totlen-1], exp[offset]))
3543 xbuf[totlen++] = '@';
3544 xbuf[totlen++] = ' ';
3547 /* If a macro argument with newlines is used multiple times,
3548 then only expand the newlines once. This avoids creating
3549 output lines which don't correspond to any input line,
3550 which confuses gdb and gcov. */
3551 if (arg->use_count > 1 && arg->newlines > 0)
3553 /* Don't bother doing change_newlines for subsequent
3557 = change_newlines (expanded, arg->expand_length);
3561 if (totlen > xbuf_len)
3565 /* if there is anything left of the definition
3566 after handling the arg list, copy that in too. */
3568 for (i = offset; i < size_toInt (defn->length); i++)
3570 /* if we've reached the end of the macro */
3573 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
3574 && last_ap->raw_after))
3575 xbuf[totlen++] = exp[i];
3578 xbuf[totlen] = '\0';
3582 pfile->output_escapes--;
3584 /* Now put the expansion on the input stack
3585 so our caller will commence reading from it. */
3586 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
3587 cppReader_getBuffer (pfile)->has_escapes = 1;
3589 /* Pop the space we've used in the token_buffer for argument expansion. */
3590 cppReader_setWritten (pfile, old_written);
3592 /* Recursive macro use sometimes works traditionally.
3593 #define foo(x,y) bar (x (y,0), y)
3596 if (!cppReader_isTraditional (pfile))
3597 hp->type = T_DISABLED;
3603 push_macro_expansion (cppReader *pfile, char *xbuf, size_t xbuf_len,
3604 /*@dependent@*/ HASHNODE *hp)
3606 cppBuffer *mbuf = cppReader_pushBuffer (pfile, xbuf, xbuf_len);
3613 mbuf->cleanup = cppReader_macroCleanup;
3615 llassert (mbuf->hnode == NULL);
3618 /* The first chars of the expansion should be a "@ " added by
3619 collect_expansion. This is to prevent accidental token-pasting
3620 between the text preceding the macro invocation, and the macro
3623 We would like to avoid adding unneeded spaces (for the sake of
3624 tools that use cpp, such as imake). In some common cases we can
3625 tell that it is safe to omit the space.
3627 The character before the macro invocation cannot have been an
3628 idchar (or else it would have been pasted with the idchars of
3629 the macro name). Therefore, if the first non-space character
3630 of the expansion is an idchar, we do not need the extra space
3631 to prevent token pasting.
3633 Also, we don't need the extra space if the first char is '(',
3634 or some other (less common) characters. */
3636 if (xbuf[0] == '@' && xbuf[1] == ' '
3637 && (is_idchar[(int) xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
3638 || xbuf[2] == '\"'))
3640 llassert (mbuf->cur != NULL);
3646 /* Like cppGetToken, except that it does not read past end-of-line.
3647 Also, horizontal space is skipped, and macros are popped. */
3649 static enum cpp_token
3650 get_directive_token (cppReader *pfile)
3654 size_t old_written = cppReader_getWritten (pfile);
3655 enum cpp_token token;
3656 cppSkipHspace (pfile);
3657 if (cppReader_peekC (pfile) == '\n')
3662 token = cppGetToken (pfile);
3667 if (!cppBuffer_isMacro (cppReader_getBuffer (pfile)))
3672 cppReader_setWritten (pfile, old_written);
3673 /*@switchbreak@*/ break;
3681 /* Handle #include and #import.
3682 This function expects to see "fname" or <fname> on the input.
3684 The input is normally in part of the output_buffer following
3685 cppReader_getWritten, and will get overwritten by output_line_command.
3686 I.e. in input file specification has been popped by cppReader_handleDirective.
3690 do_include (cppReader *pfile, struct directive *keyword,
3691 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
3693 bool skip_dirs = (keyword->type == T_INCLUDE_NEXT);
3695 char *fbeg, *fend; /* Beginning and end of fname */
3696 enum cpp_token token;
3698 /* Chain of dirs to search */
3699 struct file_name_list *search_start = CPPOPTIONS (pfile)->include;
3700 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
3701 struct file_name_list *searchptr = NULL;
3702 size_t old_written = cppReader_getWritten (pfile);
3706 int f; /* file number */
3707 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
3708 f= -1; /* JF we iz paranoid! */
3710 pfile->parsing_include_directive++;
3711 token = get_directive_token (pfile);
3712 pfile->parsing_include_directive--;
3714 if (token == CPP_STRING)
3716 /* FIXME - check no trailing garbage */
3717 fbeg = pfile->token_buffer + old_written + 1;
3718 fend = cppReader_getPWritten (pfile) - 1;
3719 if (fbeg[-1] == '<')
3722 /* If -I-, start with the first -I dir after the -I-. */
3723 if (CPPOPTIONS (pfile)->first_bracket_include != NULL)
3724 search_start = CPPOPTIONS (pfile)->first_bracket_include;
3726 /* If -I- was specified, don't search current dir, only spec'd ones. */
3727 else if (!CPPOPTIONS (pfile)->ignore_srcdir)
3729 cppBuffer *fp = CPPBUFFER (pfile);
3730 /* We have "filename". Figure out directory this source
3731 file is coming from and put it on the front of the list. */
3733 for ( ; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
3738 llassert (fp != NULL);
3742 if (cstring_isDefined (fp->nominal_fname))
3744 nam = cstring_toCharsSafe (fp->nominal_fname);
3746 /* Found a named file. Figure out dir of the file,
3747 and put it in front of the search list. */
3748 dsp[0].next = search_start;
3752 ep = strrchr (nam, CONNECTCHAR);
3754 ep = strrchr (nam, ']');
3755 if (ep == NULL) ep = strrchr (nam, '>');
3756 if (ep == NULL) ep = strrchr (nam, ':');
3757 if (ep != NULL) ep++;
3767 /*@-onlytrans@*/ /* This looks like a memory leak... */
3768 dsp[0].fname = cstring_fromCharsNew (nam); /* evs 2000-07-20: was fromChars */
3772 if (n + INCLUDE_LEN_FUDGE > pfile->max_include_len)
3773 pfile->max_include_len = n + INCLUDE_LEN_FUDGE;
3777 dsp[0].fname = cstring_undefined; /* Current directory */
3780 dsp[0].got_name_map = 0;
3791 else if (token == CPP_NAME)
3794 * Support '#include xyz' like VAX-C to allow for easy use of all the
3795 * decwindow include files. It defaults to '#include <xyz.h>' (so the
3796 * code from case '<' is repeated here) and generates a warning.
3798 cppReader_warning (pfile,
3799 "VAX-C-style include specification found, use '#include <filename.h>' !");
3801 /* If -I-, start with the first -I dir after the -I-. */
3802 if (CPPOPTIONS (pfile)->first_bracket_include)
3803 search_start = CPPOPTIONS (pfile)->first_bracket_include;
3804 fbeg = pfile->token_buffer + old_written;
3805 fend = cppReader_getPWritten (pfile);
3810 cppReader_error (pfile,
3811 message ("Preprocessor command #%s expects \"FILENAME\" or <FILENAME>",
3814 cppReader_setWritten (pfile, old_written);
3815 cppReader_skipRestOfLine (pfile);
3821 token = get_directive_token (pfile);
3822 if (token != CPP_VSPACE)
3824 cppReader_errorLit (pfile,
3825 cstring_makeLiteralTemp ("Junk at end of #include"));
3827 while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
3829 token = get_directive_token (pfile);
3834 ** For #include_next, skip in the search path
3835 ** past the dir in which the containing file was found.
3840 cppBuffer *fp = CPPBUFFER (pfile);
3842 for (; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
3844 llassert (fp != NULL);
3846 if (fp->fname != NULL)
3848 /* fp->dir is null if the containing file was specified with
3849 an absolute file name. In that case, don't skip anything. */
3850 if (fp->dir == SELF_DIR_DUMMY)
3852 search_start = CPPOPTIONS (pfile)->include;
3854 else if (fp->dir != NULL)
3856 search_start = fp->dir->next;
3868 cppReader_setWritten (pfile, old_written);
3872 DPRINTF (("fbeg: %s", fbeg));
3876 cppReader_error (pfile,
3877 message ("Empty file name in #%s", keyword->name));
3882 ** Allocate this permanently, because it gets stored in the definitions
3886 fname = cstring_undefined;
3888 /* + 2 above for slash and terminating null. */
3889 /* + 2 added for '.h' on VMS (to support '#include filename') */
3891 /* If specified file name is absolute, just open it. */
3893 if (osd_isConnectChar (*fbeg)
3894 # if defined (WIN32) || defined (OS2)
3895 || (*(fbeg + 1) == ':')
3899 fname = cstring_copyLength (fbeg, flen);
3901 if (redundant_include_p (pfile, fname))
3903 cstring_free (fname);
3907 f = open_include_file (pfile, fname, NULL);
3909 if (f == IMPORT_FOUND)
3911 return 0; /* Already included this file */
3916 /* Search directory path, trying to open the file.
3917 Copy each filename tried into FNAME. */
3919 for (searchptr = search_start; searchptr != NULL;
3920 searchptr = searchptr->next)
3922 if (!cstring_isEmpty (searchptr->fname))
3924 /* The empty string in a search path is ignored.
3925 This makes it possible to turn off entirely
3926 a standard piece of the list. */
3927 if (cstring_isEmpty (searchptr->fname))
3930 fname = cstring_copy (searchptr->fname);
3931 fname = cstring_appendChar (fname, CONNECTCHAR);
3932 DPRINTF (("Here: %s", fname));
3939 fname = cstring_concatLength (fname, fbeg, flen);
3941 DPRINTF (("fname: %s", fname));
3944 /* Change this 1/2 Unix 1/2 VMS file specification into a
3945 full VMS file specification */
3946 if (searchptr->fname && (searchptr->fname[0] != 0)) {
3947 /* Fix up the filename */
3948 hack_vms_include_specification (fname);
3950 /* This is a normal VMS filespec, so use it unchanged. */
3951 strncpy (fname, fbeg, flen);
3953 /* if it's '#include filename', add the missing .h */
3954 if (strchr (fname,'.') == NULL) {
3955 strcat (fname, ".h");
3959 /* ??? There are currently 3 separate mechanisms for avoiding processing
3960 of redundant include files: #import, #pragma once, and
3961 redundant_include_p. It would be nice if they were unified. */
3963 if (redundant_include_p (pfile, fname))
3965 cstring_free (fname);
3969 DPRINTF (("Trying: %s", fname));
3971 f = open_include_file (pfile, fname, searchptr);
3973 if (f == IMPORT_FOUND)
3975 return 0; /* Already included this file */
3978 else if (f == IMPORT_NOT_FOUND && errno == EACCES)
3980 cppReader_warning (pfile,
3981 message ("Header file %s exists, but is not readable", fname));
3994 /* A file that was not found. */
3995 fname = cstring_copyLength (fbeg, flen);
3997 if (search_start != NULL)
3999 cppReader_error (pfile,
4000 message ("Cannot find include file %s", fname));
4004 cppReader_error (pfile,
4005 message ("No include path in which to find %s", fname));
4010 ** Check to see if this include file is a once-only include file.
4014 struct file_name_list *ptr;
4016 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
4018 if (cstring_equal (ptr->fname, fname))
4020 /* This file was included before. */
4027 /* This is the first time for this file. */
4028 /* Add it to list of files included. */
4030 ptr = (struct file_name_list *) dmalloc (sizeof (*ptr));
4031 ptr->control_macro = NULL;
4032 ptr->c_system_include_path = NULL;
4033 ptr->next = pfile->all_include_files;
4035 ptr->got_name_map = NULL;
4037 pfile->all_include_files = ptr;
4038 assertSet (pfile->all_include_files);
4041 if (angle_brackets != 0)
4043 pfile->system_include_depth++;
4046 /* Actually process the file */
4047 if (cppReader_pushBuffer (pfile, NULL, 0) == NULL)
4049 cstring_free (fname);
4053 if (finclude (pfile, f, fname, is_system_include (pfile, fname),
4054 searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
4056 output_line_command (pfile, 0, enter_file);
4057 pfile->only_seen_white = 2;
4062 pfile->system_include_depth--;
4065 } /*@=branchstate@*/
4070 /* Return nonzero if there is no need to include file NAME
4071 because it has already been included and it contains a conditional
4072 to make a repeated include do nothing. */
4075 redundant_include_p (cppReader *pfile, cstring name)
4077 struct file_name_list *l = pfile->all_include_files;
4079 for (; l != NULL; l = l->next)
4081 if (cstring_equal (name, l->fname)
4082 && (l->control_macro != NULL)
4083 && (cppReader_lookup (l->control_macro, -1, -1) != NULL))
4092 /* Return nonzero if the given FILENAME is an absolute pathname which
4093 designates a file within one of the known "system" include file
4094 directories. We assume here that if the given FILENAME looks like
4095 it is the name of a file which resides either directly in a "system"
4096 include file directory, or within any subdirectory thereof, then the
4097 given file must be a "system" include file. This function tells us
4098 if we should suppress pedantic errors/warnings for the given FILENAME.
4100 The value is 2 if the file is a C-language system header file
4101 for which C++ should (on most systems) assume `extern "C"'. */
4104 is_system_include (cppReader *pfile, cstring filename)
4106 struct file_name_list *searchptr;
4108 for (searchptr = CPPOPTIONS (pfile)->first_system_include;
4110 searchptr = searchptr->next)
4112 if (!cstring_isEmpty (searchptr->fname)) {
4113 cstring sys_dir = searchptr->fname;
4114 int length = cstring_length (sys_dir);
4116 if (cstring_equalLen (sys_dir, filename, length)
4117 && osd_isConnectChar (cstring_getChar (filename, length)))
4119 if (searchptr->c_system_include_path)
4130 /* Convert a character string literal into a nul-terminated string.
4131 The input string is [IN ... LIMIT).
4132 The result is placed in RESULT. RESULT can be the same as IN.
4133 The value returned in the end of the string written to RESULT,
4134 or NULL on error. */
4136 static /*@null@*/ char *
4137 convert_string (cppReader *pfile, /*@returned@*/ char *result,
4138 char *in, char *limit, int handle_escapes)
4158 /*@switchbreak@*/ break;
4162 char *bpc = (char *) in;
4163 int i = (char) cppReader_parseEscape (pfile, &bpc);
4166 *result++ = (char) c;
4167 /*@switchbreak@*/ break;
4181 * interpret #line command. Remembers previously seen fnames
4182 * in its very own hash table.
4185 /*@constant int FNAME_HASHSIZE@*/
4186 #define FNAME_HASHSIZE 37
4189 do_line (cppReader *pfile, /*@unused@*/ struct directive *keyword)
4191 cppBuffer *ip = cppReader_getBuffer (pfile);
4193 size_t old_written = cppReader_getWritten (pfile);
4194 enum file_change_code file_change = same_file;
4195 enum cpp_token token;
4197 token = get_directive_token (pfile);
4199 if (token != CPP_NUMBER
4200 || !isdigit(pfile->token_buffer[old_written]))
4202 cppReader_errorLit (pfile,
4203 cstring_makeLiteralTemp ("invalid format `#line' command"));
4205 goto bad_line_directive;
4208 /* The Newline at the end of this line remains to be processed.
4209 To put the next line at the specified line number,
4210 we must store a line number now that is one less. */
4211 new_lineno = atoi (pfile->token_buffer + old_written) - 1;
4212 cppReader_setWritten (pfile, old_written);
4214 /* NEW_LINENO is one less than the actual line number here. */
4215 if (cppReader_isPedantic (pfile) && new_lineno < 0)
4216 cppReader_pedwarnLit (pfile,
4217 cstring_makeLiteralTemp ("line number out of range in `#line' command"));
4219 token = get_directive_token (pfile);
4221 if (token == CPP_STRING) {
4222 char *fname = pfile->token_buffer + old_written;
4224 static HASHNODE *fname_table[FNAME_HASHSIZE];
4225 HASHNODE *hp, **hash_bucket;
4230 /* Turn the file name, which is a character string literal,
4231 into a null-terminated string. Do this in place. */
4232 end_name = convert_string (pfile, fname, fname, cppReader_getPWritten (pfile), 1);
4233 if (end_name == NULL)
4235 cppReader_errorLit (pfile,
4236 cstring_makeLiteralTemp ("invalid format `#line' command"));
4237 goto bad_line_directive;
4240 fname_length = end_name - fname;
4241 num_start = cppReader_getWritten (pfile);
4243 token = get_directive_token (pfile);
4244 if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP) {
4245 p = pfile->token_buffer + num_start;
4246 if (cppReader_isPedantic (pfile))
4247 cppReader_pedwarnLit (pfile,
4248 cstring_makeLiteralTemp ("garbage at end of `#line' command"));
4250 if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
4252 cppReader_errorLit (pfile,
4253 cstring_makeLiteralTemp ("invalid format `#line' command"));
4254 goto bad_line_directive;
4257 file_change = enter_file;
4259 file_change = leave_file;
4261 ip->system_header_p = 1;
4262 else /* if (*p == 4) */
4263 ip->system_header_p = 2;
4265 cppReader_setWritten (pfile, num_start);
4266 token = get_directive_token (pfile);
4267 p = pfile->token_buffer + num_start;
4268 if (token == CPP_NUMBER && p[1] == '\0' && (*p == '3' || *p== '4')) {
4269 ip->system_header_p = *p == 3 ? 1 : 2;
4270 token = get_directive_token (pfile);
4272 if (token != CPP_VSPACE) {
4273 cppReader_errorLit (pfile,
4274 cstring_makeLiteralTemp ("invalid format `#line' command"));
4276 goto bad_line_directive;
4281 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
4282 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
4284 if (hp->length == fname_length &&
4285 strncmp (hp->value.cpval, fname, size_fromInt (fname_length)) == 0) {
4286 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
4292 /* Didn't find it; cons up a new one. */
4293 hp = (HASHNODE *) dmalloc (sizeof (*hp) + fname_length + 1);
4296 hp->bucket_hdr = NULL;
4298 hp->name = cstring_undefined;
4299 hp->next = *hash_bucket;
4303 hp->length = fname_length;
4304 hp->value.cpval = dmalloc (sizeof (*hp->value.cpval) * (fname_length + 1));
4305 memcpy (hp->value.cpval, fname, size_fromInt (fname_length));
4306 hp->value.cpval[fname_length] = '\0';
4307 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
4310 else if (token != CPP_VSPACE && token != CPP_EOF)
4312 cppReader_errorLit (pfile,
4313 cstring_makeLiteralTemp ("invalid format `#line' command"));
4314 goto bad_line_directive;
4321 ip->lineno = new_lineno;
4323 cppReader_skipRestOfLine (pfile);
4324 cppReader_setWritten (pfile, old_written);
4325 output_line_command (pfile, 0, file_change);
4330 * remove the definition of a symbol from the symbol table.
4331 * according to un*x /lib/cpp, it is not an error to undef
4332 * something that has no definitions, so it isn't one here either.
4336 do_undef (cppReader *pfile, struct directive *keyword, char *buf, char *limit)
4341 char *orig_buf = buf;
4343 SKIP_WHITE_SPACE (buf);
4345 sym_length = cppReader_checkMacroName (pfile, buf, cstring_makeLiteralTemp ("macro"));
4347 while ((hp = cppReader_lookup (buf, sym_length, -1)) != NULL)
4349 /* If we are generating additional info for debugging (with -g) we
4350 need to pass through all effective #undef commands. */
4351 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
4353 pass_thru_directive (orig_buf, limit, pfile, keyword);
4356 if (hp->type != T_MACRO)
4358 cppReader_warning (pfile,
4359 message ("Undefining preprocessor builtin: %s",
4363 cppReader_deleteMacro (hp);
4366 if (cppReader_isPedantic (pfile)) {
4368 SKIP_WHITE_SPACE (buf);
4371 cppReader_pedwarnLit (pfile,
4372 cstring_makeLiteralTemp ("garbage after `#undef' directive"));
4381 * Report an error detected by the program we are processing.
4382 * Use the text of the line in the error message.
4383 * (We use error because it prints the filename & line#.)
4387 do_error (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4388 char *buf, char *limit)
4390 int length = limit - buf;
4391 cstring copy = cstring_copyLength (buf, length);
4392 cstring adv = cstring_advanceWhiteSpace (copy);
4394 cppReader_error (pfile, message ("#error %s", adv));
4395 cstring_free (copy);
4400 * Report a warning detected by the program we are processing.
4401 * Use the text of the line in the warning message, then continue.
4402 * (We use error because it prints the filename & line#.)
4406 do_warning (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4407 char *buf, char *limit)
4409 int length = limit - buf;
4410 cstring copy = cstring_copyLength (buf, length);
4411 cstring adv = cstring_advanceWhiteSpace (copy);
4412 cppReader_warning (pfile, message ("#warning %s", adv));
4413 cstring_free (copy);
4418 /* #ident has already been copied to the output file, so just ignore it. */
4421 do_ident (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4422 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
4424 /* Allow #ident in system headers, since that's not user's fault. */
4425 if (cppReader_isPedantic (pfile) && !cppReader_getBuffer (pfile)->system_header_p)
4426 cppReader_pedwarnLit (pfile,
4427 cstring_makeLiteralTemp ("ANSI C does not allow `#ident'"));
4429 /* Leave rest of line to be read by later calls to cppGetToken. */
4434 /* #pragma and its argument line have already been copied to the output file.
4435 Just check for some recognized pragmas that need validation here. */
4438 do_pragma (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4439 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
4441 while (*buf == ' ' || *buf == '\t')
4446 if (!strncmp (buf, "implementation", 14)) {
4447 /* Be quiet about `#pragma implementation' for a file only if it hasn't
4448 been included yet. */
4449 struct file_name_list *ptr;
4450 char *p = buf + 14, *fname, *inc_fname;
4452 SKIP_WHITE_SPACE (p);
4453 if (*p == '\n' || *p != '\"')
4457 p = (char *) strchr (fname, '\"');
4458 fname_len = p != NULL ? p - fname : mstring_length (fname);
4460 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
4462 inc_fname = (char *) strrchr (cstring_toCharsSafe (ptr->fname), CONNECTCHAR);
4463 inc_fname = (inc_fname != NULL)
4464 ? inc_fname + 1 : cstring_toCharsSafe (ptr->fname);
4466 if ((inc_fname != NULL)
4467 && (strncmp (inc_fname, fname, size_fromInt (fname_len)) == 0))
4469 cpp_setLocation (pfile);
4471 ppllerror (message ("`#pragma implementation' for `%s' appears "
4472 "after file is included",
4473 cstring_fromChars (fname)));
4482 * handle #if command by
4483 * 1) inserting special `defined' keyword into the hash table
4484 * that gets turned into 0 or 1 by special_symbol (thus,
4485 * if the luser has a symbol called `defined' already, it won't
4486 * work inside the #if command)
4487 * 2) rescan the input into a temporary output buffer
4488 * 3) pass the output buffer to the yacc parser and collect a value
4489 * 4) clean up the mess left from steps 1 and 2.
4490 * 5) call conditional_skip to skip til the next #endif (etc.),
4491 * or not, depending on the value from step 3.
4495 do_if (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4496 char *buf, char *limit)
4498 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
4499 conditional_skip (pfile, value == 0, T_IF, NULL);
4504 * handle a #elif directive by not changing if_stack either.
4505 * see the comment above do_else.
4508 static int do_elif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4509 char *buf, char *limit)
4511 if (pfile->if_stack == cppReader_getBuffer (pfile)->if_stack)
4513 cppReader_errorLit (pfile,
4514 cstring_makeLiteralTemp ("Preprocessor command #elif is not within a conditional"));
4519 llassert (pfile->if_stack != NULL);
4521 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
4523 cppReader_errorLit (pfile,
4524 cstring_makeLiteralTemp ("`#elif' after `#else'"));
4526 if (pfile->if_stack->fname != NULL
4527 && cppReader_getBuffer (pfile)->fname != NULL
4528 && !cstring_equal (pfile->if_stack->fname,
4529 cppReader_getBuffer (pfile)->nominal_fname))
4530 fprintf (stderr, ", file %s", cstring_toCharsSafe (pfile->if_stack->fname));
4531 fprintf (stderr, ")\n");
4533 pfile->if_stack->type = T_ELIF;
4536 if (pfile->if_stack->if_succeeded)
4538 skip_if_group (pfile, 0);
4542 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
4544 skip_if_group (pfile, 0);
4547 ++pfile->if_stack->if_succeeded; /* continue processing input */
4548 output_line_command (pfile, 1, same_file);
4556 * evaluate a #if expression in BUF, of length LENGTH,
4557 * then parse the result as a C expression and return the value as an int.
4560 static HOST_WIDE_INT
4561 eval_if_expression (cppReader *pfile,
4562 /*@unused@*/ char *buf,
4563 /*@unused@*/ int length)
4565 HASHNODE *save_defined;
4566 HOST_WIDE_INT value;
4567 size_t old_written = cppReader_getWritten (pfile);
4569 save_defined = cppReader_install ("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
4570 pfile->pcp_inside_if = 1;
4572 value = cppReader_parseExpression (pfile);
4573 pfile->pcp_inside_if = 0;
4575 /* Clean up special symbol */
4576 cppReader_deleteMacro (save_defined);
4578 cppReader_setWritten (pfile, old_written); /* Pop */
4584 * routine to handle ifdef/ifndef. Try to look up the symbol,
4585 * then do or don't skip to the #endif/#else/#elif depending
4586 * on what directive is actually being processed.
4590 do_xifdef (cppReader *pfile, struct directive *keyword,
4591 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
4594 cppBuffer *ip = cppReader_getBuffer (pfile);
4597 enum cpp_token token;
4598 int start_of_file = 0;
4599 char *control_macro = 0;
4600 size_t old_written = cppReader_getWritten (pfile);
4602 DPRINTF (("do xifdef: %d",
4603 keyword->type == T_IFNDEF));
4605 /* Detect a #ifndef at start of file (not counting comments). */
4606 if (cstring_isDefined (ip->fname) && keyword->type == T_IFNDEF)
4608 start_of_file = pfile->only_seen_white == 2;
4611 pfile->no_macro_expand++;
4612 token = get_directive_token (pfile);
4613 pfile->no_macro_expand--;
4615 ident = pfile->token_buffer + old_written;
4616 ident_length = size_toInt (cppReader_getWritten (pfile) - old_written);
4617 cppReader_setWritten (pfile, old_written); /* Pop */
4619 if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
4621 skip = (keyword->type == T_IFDEF);
4622 if (! cppReader_isTraditional (pfile))
4624 cppReader_pedwarn (pfile,
4625 message ("`#%s' with no argument", keyword->name));
4628 else if (token == CPP_NAME)
4630 HASHNODE *hp = cppReader_lookup (ident, ident_length, -1);
4631 skip = (keyword->type == T_IFDEF)
4632 ? (hp == NULL) : (hp != NULL);
4634 DPRINTF (("hp null: %d / %d / %d",
4636 (keyword->type == T_IFNDEF),
4639 if (start_of_file && !skip)
4641 DPRINTF (("Not skipping!"));
4642 control_macro = (char *) dmalloc (size_fromInt (ident_length + 1));
4643 memcpy (control_macro, ident, size_fromInt (ident_length + 1));
4648 skip = (keyword->type == T_IFDEF);
4649 if (! cppReader_isTraditional (pfile))
4651 cppReader_error (pfile,
4652 message ("`#%s' with invalid argument", keyword->name));
4656 if (!cppReader_isTraditional (pfile))
4659 cppSkipHspace (pfile);
4660 c = cppReader_peekC (pfile);
4661 if (c != EOF && c != '\n')
4663 cppReader_pedwarn (pfile,
4664 message ("garbage at end of `#%s' argument", keyword->name));
4668 cppReader_skipRestOfLine (pfile);
4670 DPRINTF (("Conditional skip: %d", skip));
4671 conditional_skip (pfile, skip, T_IF, control_macro);
4675 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
4676 If this is a #ifndef starting at the beginning of a file,
4677 CONTROL_MACRO is the macro name tested by the #ifndef.
4678 Otherwise, CONTROL_MACRO is 0. */
4681 conditional_skip (cppReader *pfile, int skip,
4682 enum node_type type,
4683 /*@dependent@*/ char *control_macro)
4685 cppIfStackFrame *temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
4687 temp->fname = cppReader_getBuffer (pfile)->nominal_fname;
4688 temp->next = pfile->if_stack;
4689 temp->control_macro = control_macro;
4691 temp->if_succeeded = 0;
4693 pfile->if_stack = temp;
4694 pfile->if_stack->type = type;
4698 skip_if_group (pfile, 0);
4703 ++pfile->if_stack->if_succeeded;
4704 output_line_command (pfile, 1, same_file);
4709 * skip to #endif, #else, or #elif. adjust line numbers, etc.
4710 * leaves input ptr at the sharp sign found.
4711 * If ANY is nonzero, return at next directive of any sort.
4715 skip_if_group (cppReader *pfile, int any)
4718 struct directive *kt;
4719 cppIfStackFrame *save_if_stack = pfile->if_stack; /* don't pop past here */
4720 register int ident_length;
4722 struct parse_marker line_start_mark;
4724 parseSetMark (&line_start_mark, pfile);
4726 if (CPPOPTIONS (pfile)->output_conditionals) {
4727 static char failed[] = "#failed\n";
4728 cppReader_puts (pfile, failed, sizeof(failed)-1);
4730 output_line_command (pfile, 1, same_file);
4734 if (CPPOPTIONS (pfile)->output_conditionals)
4736 cppBuffer *pbuf = cppReader_getBuffer (pfile);
4739 llassert (pbuf->buf != NULL);
4741 start_line = pbuf->buf + line_start_mark.position;
4742 cppReader_puts (pfile, start_line, size_fromInt (pbuf->cur - start_line));
4745 parseMoveMark (&line_start_mark, pfile);
4747 if (!cppReader_isTraditional (pfile))
4749 cppSkipHspace (pfile);
4752 c = cppReader_getC (pfile);
4755 size_t old_written = cppReader_getWritten (pfile);
4756 cppSkipHspace (pfile);
4758 parse_name (pfile, cppReader_getC (pfile));
4759 ident_length = size_toInt (cppReader_getWritten (pfile) - old_written);
4760 ident = pfile->token_buffer + old_written;
4761 pfile->limit = ident;
4763 for (kt = directive_table; kt->length >= 0; kt++)
4765 cppIfStackFrame *temp;
4766 if (ident_length == kt->length
4767 && cstring_equalPrefix (kt->name, ident))
4769 /* If we are asked to return on next directive, do so now. */
4780 temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
4781 temp->next = pfile->if_stack;
4782 temp->fname = cppReader_getBuffer (pfile)->nominal_fname;
4783 temp->type = kt->type;
4785 temp->if_succeeded = 0;
4786 temp->control_macro = NULL;
4788 pfile->if_stack = temp;
4789 /*@switchbreak@*/ break;
4792 if (cppReader_isPedantic (pfile) && pfile->if_stack != save_if_stack)
4793 validate_else (pfile,
4794 cstring_makeLiteralTemp (kt->type == T_ELSE ? "#else" : "#endif"));
4797 if (pfile->if_stack == cppReader_getBuffer (pfile)->if_stack)
4799 cppReader_error (pfile,
4800 message ("Preprocessor command #%s is not within a conditional", kt->name));
4801 /*@switchbreak@*/ break;
4803 else if (pfile->if_stack == save_if_stack)
4805 goto done; /* found what we came for */
4812 if (kt->type != T_ENDIF)
4814 llassert (pfile->if_stack != NULL);
4816 if (pfile->if_stack->type == T_ELSE)
4818 cppReader_errorLit (pfile,
4819 cstring_makeLiteralTemp ("`#else' or `#elif' after `#else'"));
4822 pfile->if_stack->type = kt->type;
4823 /*@switchbreak@*/ break;
4826 temp = pfile->if_stack;
4827 llassert (temp != NULL);
4828 pfile->if_stack = temp->next;
4830 /*@switchbreak@*/ break;
4838 /* Don't let erroneous code go by. */
4840 if (kt->length < 0 && !CPPOPTIONS (pfile)->lang_asm
4841 && cppReader_isPedantic (pfile))
4843 cppReader_pedwarnLit (pfile,
4844 cstring_makeLiteralTemp ("Invalid preprocessor directive name"));
4848 c = cppReader_getC (pfile);
4850 /* We're in the middle of a line. Skip the rest of it. */
4857 case '/': /* possible comment */
4858 c = skip_comment (pfile, NULL);
4861 /*@switchbreak@*/ break;
4864 cppReader_forward (pfile, -1);
4865 old = cppReader_getWritten (pfile);
4866 (void) cppGetToken (pfile);
4867 cppReader_setWritten (pfile, old);
4868 /*@switchbreak@*/ break;
4870 /* Char after backslash loses its special meaning. */
4871 if (cppReader_peekC (pfile) == '\n')
4873 cppReader_forward (pfile, 1);
4876 /*@switchbreak@*/ break;
4880 c = cppReader_getC (pfile);
4883 if (CPPOPTIONS (pfile)->output_conditionals) {
4884 static char end_failed[] = "#endfailed\n";
4885 cppReader_puts (pfile, end_failed, sizeof(end_failed)-1);
4888 pfile->only_seen_white = 1;
4890 parseGotoMark (&line_start_mark, pfile);
4891 parseClearMark (&line_start_mark);
4895 * handle a #else directive. Do this by just continuing processing
4896 * without changing if_stack ; this is so that the error message
4897 * for missing #endif's etc. will point to the original #if. It
4898 * is possible that something different would be better.
4902 do_else (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4903 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
4905 if (cppReader_isPedantic (pfile))
4907 validate_else (pfile, cstring_makeLiteralTemp ("#else"));
4910 cppReader_skipRestOfLine (pfile);
4912 if (pfile->if_stack == cppReader_getBuffer (pfile)->if_stack) {
4913 cppReader_errorLit (pfile,
4914 cstring_makeLiteralTemp ("Preprocessor command #else is not within a conditional"));
4917 /* #ifndef can't have its special treatment for containing the whole file
4918 if it has a #else clause. */
4920 llassert (pfile->if_stack != NULL);
4922 pfile->if_stack->control_macro = 0;
4924 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
4926 cpp_setLocation (pfile);
4927 genppllerrorhint (FLG_PREPROC,
4928 message ("Pre-processor directive #else after #else"),
4929 message ("%q: Location of match",
4930 fileloc_unparseRaw (pfile->if_stack->fname,
4931 pfile->if_stack->lineno)));
4934 pfile->if_stack->type = T_ELSE;
4937 if (pfile->if_stack->if_succeeded)
4938 skip_if_group (pfile, 0);
4940 ++pfile->if_stack->if_succeeded; /* continue processing input */
4941 output_line_command (pfile, 1, same_file);
4948 * unstack after #endif command
4952 do_endif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4953 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
4955 if (cppReader_isPedantic (pfile))
4957 validate_else (pfile, cstring_makeLiteralTemp ("#endif"));
4960 cppReader_skipRestOfLine (pfile);
4962 if (pfile->if_stack == cppReader_getBuffer (pfile)->if_stack)
4964 cppReader_errorLit (pfile, cstring_makeLiteralTemp ("Unbalanced #endif"));
4968 cppIfStackFrame *temp = pfile->if_stack;
4970 llassert (temp != NULL);
4972 pfile->if_stack = temp->next;
4973 if (temp->control_macro != 0)
4975 /* This #endif matched a #ifndef at the start of the file.
4976 See if it is at the end of the file. */
4977 struct parse_marker start_mark;
4980 parseSetMark (&start_mark, pfile);
4984 cppSkipHspace (pfile);
4985 c = cppReader_getC (pfile);
4991 parseGotoMark (&start_mark, pfile);
4992 parseClearMark (&start_mark);
4996 /* If we get here, this #endif ends a #ifndef
4997 that contains all of the file (aside from whitespace).
4998 Arrange not to include the file again
4999 if the macro that was tested is defined.
5001 Do not do this for the top-level file in a -include or any
5002 file in a -imacros. */
5003 struct file_name_list *ifile = pfile->all_include_files;
5005 for ( ; ifile != NULL; ifile = ifile->next)
5007 if (cstring_equal (ifile->fname, cppReader_getBuffer (pfile)->fname))
5009 ifile->control_macro = temp->control_macro;
5017 output_line_command (pfile, 1, same_file);
5022 /* When an #else or #endif is found while skipping failed conditional,
5023 if -pedantic was specified, this is called to warn about text after
5024 the command name. P points to the first char after the command name. */
5027 validate_else (cppReader *pfile, cstring directive)
5030 cppSkipHspace (pfile);
5031 c = cppReader_peekC (pfile);
5032 if (c != EOF && c != '\n')
5034 cppReader_pedwarn (pfile,
5035 message ("text following `%s' violates ANSI standard", directive));
5040 ** Get the next token, and add it to the text in pfile->token_buffer.
5041 ** Return the kind of token we got.
5045 cppGetToken (cppReader *pfile)
5048 size_t old_written = 0;
5049 int start_line, start_column;
5050 enum cpp_token token;
5051 struct cppOptions *opts = CPPOPTIONS (pfile);
5052 cppReader_getBuffer (pfile)->prev = cppReader_getBuffer (pfile)->cur;
5055 c = cppReader_getC (pfile);
5060 if (cppReader_getBuffer (pfile)->seen_eof)
5062 cppBuffer *buf = cppReader_popBuffer (pfile);
5064 if (buf != cppReader_nullBuffer (pfile))
5075 cppBuffer *next_buf = cppBuffer_prevBuffer (cppReader_getBuffer (pfile));
5076 cppReader_getBuffer (pfile)->seen_eof = 1;
5078 if (cstring_isDefined (cppReader_getBuffer (pfile)->nominal_fname)
5079 && next_buf != cppReader_nullBuffer (pfile))
5081 /* We're about to return from an #include file.
5082 Emit #line information now (as part of the CPP_POP) result.
5083 But the #line refers to the file we will pop to. */
5084 cppBuffer *cur_buffer = CPPBUFFER (pfile);
5085 CPPBUFFER (pfile) = next_buf;
5086 pfile->input_stack_listing_current = 0;
5087 output_line_command (pfile, 0, leave_file);
5088 CPPBUFFER (pfile) = cur_buffer;
5096 struct parse_marker start_mark;
5101 if (cppReader_peekC (pfile) == '=')
5106 if (opts->put_out_comments)
5108 parseSetMark (&start_mark, pfile);
5112 cppBuffer_lineAndColumn (cppReader_fileBuffer (pfile),
5113 &start_line, &start_column);
5114 c = skip_comment (pfile, &newlines);
5116 if (opts->put_out_comments && (c == '/' || c == EOF))
5118 assertSet (&start_mark);
5119 parseClearMark (&start_mark);
5126 cppReader_errorWithLine (pfile, start_line, start_column,
5127 cstring_makeLiteral ("Unterminated comment"));
5130 c = '/'; /* Initial letter of comment. */
5132 /* Comments are equivalent to spaces.
5133 For -traditional, a comment is equivalent to nothing. */
5135 if (opts->put_out_comments)
5139 assertSet (&start_mark);
5140 res = cpp_handleComment (pfile, &start_mark);
5141 pfile->lineno += newlines;
5144 else if (cppReader_isTraditional (pfile))
5150 cppReader_reserve(pfile, 1);
5151 cppReader_putCharQ (pfile, ' ');
5156 if (!pfile->only_seen_white)
5161 if (cppReader_handleDirective (pfile))
5163 return CPP_DIRECTIVE;
5166 pfile->only_seen_white = 0;
5171 /* A single quoted string is treated like a double -- some
5172 programs (e.g., troff) are perverse this way */
5173 cppBuffer_lineAndColumn (cppReader_fileBuffer (pfile),
5174 &start_line, &start_column);
5175 old_written = cppReader_getWritten (pfile);
5177 cppReader_putChar (pfile, c);
5180 int cc = cppReader_getC (pfile);
5183 if (cppBuffer_isMacro (CPPBUFFER (pfile)))
5185 /* try harder: this string crosses a macro expansion
5186 boundary. This can happen naturally if -traditional.
5187 Otherwise, only -D can make a macro with an unmatched
5190 = cppBuffer_prevBuffer (cppReader_getBuffer (pfile));
5191 (*cppReader_getBuffer (pfile)->cleanup)
5192 (cppReader_getBuffer (pfile), pfile);
5193 CPPBUFFER (pfile) = next_buf;
5196 if (!cppReader_isTraditional (pfile))
5198 cpp_setLocation (pfile);
5200 setLine (long_toInt (start_line));
5201 setColumn (long_toInt (start_column));
5203 if (pfile->multiline_string_line != long_toInt (start_line)
5204 && pfile->multiline_string_line != 0)
5208 message ("Unterminated string or character constant"),
5209 message ("%q: Possible real start of unterminated constant",
5211 (fileloc_filename (g_currentloc),
5212 pfile->multiline_string_line)));
5213 pfile->multiline_string_line = 0;
5219 message ("Unterminated string or character constant"));
5222 /*@loopbreak@*/ break;
5224 cppReader_putChar (pfile, cc);
5228 /* Traditionally, end of line ends a string constant with
5229 no error. So exit the loop and record the new line. */
5230 if (cppReader_isTraditional (pfile))
5236 if (cppReader_isPedantic (pfile)
5237 && pfile->multiline_string_line == 0)
5239 cppReader_pedwarnWithLine
5240 (pfile, long_toInt (start_line),
5241 long_toInt (start_column),
5242 cstring_makeLiteral ("String constant runs past end of line"));
5244 if (pfile->multiline_string_line == 0)
5246 pfile->multiline_string_line = start_line;
5249 /*@switchbreak@*/ break;
5252 cc = cppReader_getC (pfile);
5255 /* Backslash newline is replaced by nothing at all. */
5256 cppReader_adjustWritten (pfile, -1);
5261 /* ANSI stupidly requires that in \\ the second \
5262 is *not* prevented from combining with a newline. */
5265 cppReader_putChar (pfile, cc);
5267 /*@switchbreak@*/ break;
5273 /*@switchbreak@*/ break;
5277 pfile->lineno += count_newlines (pfile->token_buffer + old_written,
5278 cppReader_getPWritten (pfile));
5279 pfile->only_seen_white = 0;
5280 return c == '\'' ? CPP_CHAR : CPP_STRING;
5283 if (!opts->dollars_in_ident)
5288 if (opts->cplusplus && cppReader_peekC (pfile) == ':')
5296 c2 = cppReader_peekC (pfile);
5297 if (c2 == c || c2 == '=')
5307 if (cppReader_peekC (pfile) == '=')
5313 c2 = cppReader_peekC (pfile);
5314 if (c2 == '-' && opts->chill)
5316 /* Chill style comment */
5317 if (opts->put_out_comments)
5319 parseSetMark (&start_mark, pfile);
5322 cppReader_forward (pfile, 1); /* Skip second '-'. */
5326 c = cppReader_getC (pfile);
5328 /*@loopbreak@*/ break;
5331 /* Don't consider final '\n' to be part of comment. */
5332 cppReader_forward (pfile, -1);
5333 /*@loopbreak@*/ break;
5337 goto return_comment;
5339 if (c2 == '-' || c2 == '=' || c2 == '>')
5344 if (pfile->parsing_include_directive)
5348 cppReader_putChar (pfile, c);
5350 /*@loopbreak@*/ break;
5351 c = cppReader_getC (pfile);
5353 if (c == '\n' || c == EOF)
5355 cppReader_errorLit (pfile,
5356 cstring_makeLiteralTemp ("Missing '>' in \"#include <FILENAME>\""));
5357 /*@loopbreak@*/ break;
5365 c2 = cppReader_peekC (pfile);
5370 cppReader_forward (pfile, 1);
5371 cppReader_reserve (pfile, 4);
5372 cppReader_putChar (pfile, c);
5373 cppReader_putChar (pfile, c2);
5375 c3 = cppReader_peekC (pfile);
5377 cppReader_putCharQ (pfile, cppReader_getC (pfile));
5378 cppReader_nullTerminateQ (pfile);
5379 pfile->only_seen_white = 0;
5383 if (cppReader_getBuffer (pfile)->has_escapes)
5385 c = cppReader_getC (pfile);
5388 if (pfile->output_escapes)
5389 cppReader_puts (pfile, "@-", 2);
5390 parse_name (pfile, cppReader_getC (pfile));
5393 else if (is_space [c])
5395 cppReader_reserve (pfile, 2);
5396 if (pfile->output_escapes)
5397 cppReader_putCharQ (pfile, '@');
5398 cppReader_putCharQ (pfile, c);
5406 if (pfile->output_escapes)
5408 cppReader_puts (pfile, "@@", 2);
5414 c2 = cppReader_peekC (pfile);
5417 cppReader_reserve(pfile, 2);
5418 cppReader_putCharQ (pfile, '.');
5419 c = cppReader_getC (pfile);
5423 /* FIXME - misses the case "..\\\n." */
5424 if (c2 == '.' && cpp_peekN (pfile, 1) == '.')
5426 cppReader_reserve(pfile, 4);
5427 cppReader_putCharQ (pfile, '.');
5428 cppReader_putCharQ (pfile, '.');
5429 cppReader_putCharQ (pfile, '.');
5430 cppReader_forward (pfile, 2);
5431 cppReader_nullTerminateQ (pfile);
5432 pfile->only_seen_white = 0;
5438 pfile->only_seen_white = 0;
5440 cppReader_reserve(pfile, 3);
5441 cppReader_putCharQ (pfile, c);
5442 cppReader_putCharQ (pfile, cppReader_getC (pfile));
5443 cppReader_nullTerminateQ (pfile);
5448 c2 = cppReader_peekC (pfile);
5449 if ((c2 == '\'' || c2 == '\"') && !cppReader_isTraditional (pfile))
5451 cppReader_putChar (pfile, c);
5452 c = cppReader_getC (pfile);
5457 case '0': case '1': case '2': case '3': case '4':
5458 case '5': case '6': case '7': case '8': case '9':
5463 cppReader_reserve (pfile, 2);
5464 cppReader_putCharQ (pfile, c);
5466 c = cppReader_peekC (pfile);
5468 /*@loopbreak@*/ break;
5469 if (!is_idchar[c] && c != '.'
5470 && ((c2 != 'e' && c2 != 'E'
5471 && ((c2 != 'p' && c2 != 'P') || cppReader_isC89 (pfile)))
5472 || (c != '+' && c != '-')))
5473 /*@loopbreak@*/ break;
5474 cppReader_forward (pfile, 1);
5478 cppReader_nullTerminateQ (pfile);
5479 pfile->only_seen_white = 0;
5482 case 'b': case 'c': case 'd': case 'h': case 'o':
5483 case 'B': case 'C': case 'D': case 'H': case 'O':
5484 if (opts->chill && cppReader_peekC (pfile) == '\'')
5486 pfile->only_seen_white = 0;
5487 cppReader_reserve (pfile, 2);
5488 cppReader_putCharQ (pfile, c);
5489 cppReader_putCharQ (pfile, '\'');
5490 cppReader_forward (pfile, 1);
5493 c = cppReader_getC (pfile);
5495 goto chill_number_eof;
5498 if (c == '\\' && cppReader_peekC (pfile) == '\n')
5500 cppReader_forward (pfile, 2);
5503 /*@loopbreak@*/ break;
5505 cppReader_putChar (pfile, c);
5509 cppReader_reserve (pfile, 2);
5510 cppReader_putCharQ (pfile, c);
5511 cppReader_nullTerminateQ (pfile);
5516 cppReader_forward (pfile, -1);
5518 cppReader_nullTerminate (pfile);
5525 case 'a': case 'e': case 'f': case 'g': case 'i': case 'j':
5526 case 'k': case 'l': case 'm': case 'n': case 'p': case 'q':
5527 case 'r': case 's': case 't': case 'u': case 'v': case 'w':
5528 case 'x': case 'y': case 'z':
5529 case 'A': case 'E': case 'F': case 'G': case 'I': case 'J':
5530 case 'K': case 'M': case 'N': case 'P': case 'Q': case 'R':
5531 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
5537 size_t before_name_written = cppReader_getWritten (pfile);
5539 parse_name (pfile, c);
5540 pfile->only_seen_white = 0;
5541 if (pfile->no_macro_expand)
5546 ident = pfile->token_buffer + before_name_written;
5547 ident_len = (cppReader_getPWritten (pfile)) - ident;
5549 hp = cppReader_lookupExpand (ident, ident_len, -1);
5556 if (hp->type == T_DISABLED)
5558 if (pfile->output_escapes)
5559 { /* Return "@-IDENT", followed by '\0'. */
5561 cppReader_reserve (pfile, 3);
5562 ident = pfile->token_buffer + before_name_written;
5563 cppReader_adjustWritten (pfile, 2);
5565 for (i = ident_len; i >= 0; i--)
5567 ident[i+2] = ident[i];
5576 /* If macro wants an arglist, verify that a '(' follows.
5577 first skip all whitespace, copying it to the output
5578 after the macro name. Then, if there is no '(',
5579 decide this is not a macro call and leave things that way. */
5581 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
5583 struct parse_marker macro_mark;
5586 while (cppBuffer_isMacro (CPPBUFFER (pfile)))
5588 cppBuffer *next_buf;
5589 cppSkipHspace (pfile);
5590 if (cppReader_peekC (pfile) != EOF)
5592 /*@loopbreak@*/ break;
5595 next_buf = cppBuffer_prevBuffer (cppReader_getBuffer (pfile));
5596 (*cppReader_getBuffer (pfile)->cleanup) (cppReader_getBuffer (pfile), pfile);
5597 CPPBUFFER (pfile) = next_buf;
5600 parseSetMark (¯o_mark, pfile);
5604 cppSkipHspace (pfile);
5605 c = cppReader_peekC (pfile);
5606 is_macro_call = c == '(';
5608 /*@loopbreak@*/ break;
5609 cppReader_forward (pfile, 1);
5614 parseGotoMark (¯o_mark, pfile);
5617 parseClearMark (¯o_mark);
5624 /* This is now known to be a macro call. */
5626 /* it might not actually be a macro. */
5627 if (hp->type != T_MACRO)
5632 cppReader_setWritten (pfile, before_name_written);
5633 special_symbol (hp, pfile);
5634 xbuf_len = cppReader_getWritten (pfile) - before_name_written;
5635 xbuf = (char *) dmalloc (xbuf_len + 1);
5636 cppReader_setWritten (pfile, before_name_written);
5637 memcpy (xbuf, cppReader_getPWritten (pfile), xbuf_len + 1);
5638 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
5642 /* Expand the macro, reading arguments as needed,
5643 and push the expansion on the input stack. */
5644 macroexpand (pfile, hp);
5645 cppReader_setWritten (pfile, before_name_written);
5648 /* An extra "@ " is added to the end of a macro expansion
5649 to prevent accidental token pasting. We prefer to avoid
5650 unneeded extra spaces (for the sake of cpp-using tools like
5651 imake). Here we remove the space if it is safe to do so. */
5653 llassert (pfile->buffer->rlimit != NULL);
5655 if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
5656 && pfile->buffer->rlimit[-2] == '@'
5657 && pfile->buffer->rlimit[-1] == ' ')
5659 int c1 = pfile->buffer->rlimit[-3];
5660 int cl2 = cppBufPeek (cppBuffer_prevBuffer (CPPBUFFER (pfile)));
5662 if (cl2 == EOF || !unsafe_chars ((char) c1, (char) cl2))
5663 pfile->buffer->rlimit -= 2;
5668 case ' ': case '\t': case '\v': case '\r':
5671 cppReader_putChar (pfile, c);
5672 c = cppReader_peekC (pfile);
5673 if (c == EOF || !is_hor_space[c])
5674 /*@loopbreak@*/ break;
5675 cppReader_forward (pfile, 1);
5680 c2 = cppReader_peekC (pfile);
5687 cppReader_putChar (pfile, c);
5688 if (pfile->only_seen_white == 0)
5689 pfile->only_seen_white = 1;
5691 output_line_command (pfile, 1, same_file);
5694 case '(': token = CPP_LPAREN; goto char1;
5695 case ')': token = CPP_RPAREN; goto char1;
5696 case '{': token = CPP_LBRACE; goto char1;
5697 case '}': token = CPP_RBRACE; goto char1;
5698 case ',': token = CPP_COMMA; goto char1;
5699 case ';': token = CPP_SEMICOLON; goto char1;
5705 pfile->only_seen_white = 0;
5706 cppReader_putChar (pfile, c);
5715 /* Parse an identifier starting with C. */
5718 parse_name (cppReader *pfile, int c)
5724 if (c == '\\' && cppReader_peekC (pfile) == '\n')
5726 cppReader_forward (pfile, 2);
5730 cppReader_forward (pfile, -1);
5734 if (c == '$' && cppReader_isPedantic (pfile))
5736 cppReader_pedwarnLit (pfile,
5737 cstring_makeLiteralTemp ("`$' in identifier"));
5740 cppReader_reserve(pfile, 2); /* One more for final NUL. */
5741 cppReader_putCharQ (pfile, c);
5742 c = cppReader_getC (pfile);
5748 cppReader_nullTerminateQ (pfile);
5751 /* The file_name_map structure holds a mapping of file names for a
5752 particular directory. This mapping is read from the file named
5753 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
5754 map filenames on a file system with severe filename restrictions,
5755 such as DOS. The format of the file name map file is just a series
5756 of lines with two tokens on each line. The first token is the name
5757 to map, and the second token is the actual name to use. */
5759 struct file_name_map
5761 struct file_name_map *map_next;
5766 /*@constant observer char *FILE_NAME_MAP_FILE*/
5767 #define FILE_NAME_MAP_FILE "header.gcc"
5769 /* Read a space delimited string of unlimited length from a stdio
5772 static cstring read_filename_string (int ch, FILE *f)
5778 set = alloc = dmalloc (len + 1);
5783 while ((ch = getc (f)) != EOF && ! is_space[ch])
5785 if (set - alloc == size_toInt (len))
5788 alloc = drealloc (alloc, len + 1);
5789 set = alloc + len / 2;
5790 /*@-branchstate@*/ }
5793 } /*@=branchstate@*/
5796 check (ungetc (ch, f) != EOF);
5798 return cstring_fromChars (alloc);
5801 /* This structure holds a linked list of file name maps, one per directory. */
5803 struct file_name_map_list
5805 struct file_name_map_list *map_list_next;
5806 cstring map_list_name;
5807 struct file_name_map *map_list_map;
5810 /* Read the file name map file for DIRNAME. */
5812 static struct file_name_map *
5813 read_name_map (cppReader *pfile, cstring dirname)
5815 struct file_name_map_list *map_list_ptr;
5819 for (map_list_ptr = CPPOPTIONS (pfile)->map_list;
5820 map_list_ptr != NULL;
5821 map_list_ptr = map_list_ptr->map_list_next)
5823 if (cstring_equal (map_list_ptr->map_list_name, dirname))
5825 return map_list_ptr->map_list_map;
5829 map_list_ptr = (struct file_name_map_list *) dmalloc (sizeof (*map_list_ptr));
5830 map_list_ptr->map_list_name = cstring_copy (dirname);
5831 map_list_ptr->map_list_map = NULL;
5833 name = cstring_copy (dirname);
5835 if (cstring_length (dirname) > 0)
5837 name = cstring_appendChar (name, CONNECTCHAR);
5840 name = cstring_concatFree1 (name, cstring_makeLiteralTemp (FILE_NAME_MAP_FILE));
5842 f = fopen (cstring_toCharsSafe (name), "r");
5843 cstring_free (name);
5847 map_list_ptr->map_list_map = NULL;
5853 while ((ch = getc (f)) != EOF)
5856 struct file_name_map *ptr;
5863 from = read_filename_string (ch, f);
5864 while ((ch = getc (f)) != EOF && is_hor_space[ch])
5869 to = read_filename_string (ch, f);
5871 ptr = (struct file_name_map *) dmalloc (sizeof (*ptr));
5872 ptr->map_from = from;
5874 /* Make the real filename absolute. */
5875 if (cstring_length (to) > 1
5876 && osd_isConnectChar (cstring_firstChar (to)))
5882 ptr->map_to = cstring_copy (dirname);
5883 ptr->map_to = cstring_appendChar (ptr->map_to, CONNECTCHAR);
5884 ptr->map_to = cstring_concatFree (ptr->map_to, to);
5887 ptr->map_next = map_list_ptr->map_list_map;
5888 map_list_ptr->map_list_map = ptr;
5890 while ((ch = getc (f)) != '\n')
5894 /*@innerbreak@*/ break;
5899 assertSet (map_list_ptr->map_list_map);
5900 check (fclose (f) == 0);
5903 map_list_ptr->map_list_next = pfile->opts->map_list;
5904 pfile->opts->map_list = map_list_ptr;
5906 return map_list_ptr->map_list_map;
5909 /* Try to open include file FILENAME. SEARCHPTR is the directory
5910 being tried from the include file search path. This function maps
5911 filenames on file systems based on information read by
5915 open_include_file (cppReader *pfile,
5917 struct file_name_list *searchptr)
5919 char *filename = cstring_toCharsSafe (fname);
5920 struct file_name_map *map;
5924 cstring_markOwned (fname);
5926 cpp_setLocation (pfile);
5928 if (context_getFlag (FLG_NEVERINCLUDE))
5930 if (isHeaderFile (fname))
5932 return SKIP_INCLUDE;
5936 if ((searchptr != NULL) && ! searchptr->got_name_map)
5938 searchptr->name_map = read_name_map (pfile,
5939 !cstring_isEmpty (searchptr->fname)
5940 ? searchptr->fname :
5941 cstring_makeLiteralTemp ("."));
5942 searchptr->got_name_map = 1;
5945 /* First check the mapping for the directory we are using. */
5947 if ((searchptr != NULL)
5948 && (searchptr->name_map != NULL))
5952 if (!cstring_isEmpty (searchptr->fname))
5954 from += cstring_length (searchptr->fname) + 1;
5957 for (map = searchptr->name_map;
5959 map = map->map_next)
5961 if (cstring_equal (map->map_from, cstring_fromChars (from)))
5964 ** Found a match. Check if the file should be skipped
5967 if (cpp_skipIncludeFile (map->map_to))
5969 return SKIP_INCLUDE;
5973 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
5980 ** Try to find a mapping file for the particular directory we are
5981 ** looking in. Thus #include <sys/types.h> will look up sys/types.h
5982 ** in /usr/include/header.gcc and look up types.h in
5983 ** /usr/include/sys/header.gcc.
5986 p = strrchr (filename, CONNECTCHAR);
5993 if ((searchptr != NULL)
5994 && (cstring_isDefined (searchptr->fname))
5995 && (cstring_length (searchptr->fname) == p - filename)
5996 && !strncmp (cstring_toCharsSafe (searchptr->fname),
5998 size_fromInt (p - filename)))
6000 /* filename is in SEARCHPTR, which we've already checked. */
6002 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
6004 return SKIP_INCLUDE;
6008 return cpp_openIncludeFile (filename);
6014 dir = mstring_copy (".");
6019 dir = (char *) dmalloc (size_fromInt (p - filename + 1));
6020 memcpy (dir, filename, size_fromInt (p - filename));
6021 dir[p - filename] = '\0';
6025 for (map = read_name_map (pfile, cstring_fromChars (dir));
6027 map = map->map_next)
6029 if (cstring_equal (map->map_from, cstring_fromChars (from)))
6033 if (cpp_skipIncludeFile (map->map_to))
6035 return SKIP_INCLUDE;
6039 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
6046 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
6048 return SKIP_INCLUDE;
6052 return cpp_openIncludeFile (filename);
6056 /* Process the contents of include file FNAME, already open on descriptor F,
6058 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
6059 "system" include directories (as decided by the `is_system_include'
6061 DIRPTR is the link in the dir path through which this file was found,
6062 or 0 if the file name was absolute or via the current directory.
6063 Return 1 on success, 0 on failure.
6065 The caller is responsible for the cppReader_pushBuffer. */
6068 finclude (cppReader *pfile, int f,
6070 bool system_header_p,
6071 /*@dependent@*/ struct file_name_list *dirptr)
6077 cppBuffer *fp; /* For input stack frame */
6079 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
6081 cppReader_perrorWithName (pfile, fname);
6082 check (close (f) == 0);
6083 (void) cppReader_popBuffer (pfile);
6089 fp = cppReader_getBuffer (pfile);
6091 /*@-temptrans@*/ /* fname shouldn't really be temp */
6092 fp->nominal_fname = fp->fname = fname;
6096 fp->system_header_p = system_header_p;
6099 fp->cleanup = cppReader_fileCleanup;
6101 if (S_ISREG (st_mode))
6104 fp->buf = (char *) dmalloc (st_size + 2);
6105 fp->alimit = fp->buf + st_size + 2;
6108 /* Read the file contents, knowing that st_size is an upper bound
6109 on the number of bytes we can read. */
6110 length = safe_read (f, fp->buf, size_toInt (st_size));
6111 fp->rlimit = fp->buf + length;
6112 if (length < 0) goto nope;
6114 else if (S_ISDIR (st_mode))
6116 cppReader_error (pfile,
6117 message ("directory `%s' specified in #include", fname));
6118 check (close (f) == 0);
6124 ** Cannot count its file size before reading.
6125 ** First read the entire file into heap and
6126 ** copy them into buffer on stack.
6129 size_t bsize = 2000;
6134 fp->buf = (char *) dmalloc (bsize + 2);
6137 i = safe_read (f, fp->buf + st_size, size_toInt (bsize - st_size));
6140 goto nope; /* error! */
6143 if (st_size != bsize)
6145 break; /* End of file */
6149 fp->buf = (char *) drealloc (fp->buf, bsize + 2);
6153 length = size_toInt (st_size);
6156 if ((length > 0 && fp->buf[length - 1] != '\n')
6157 /* Backslash-newline at end is not good enough. */
6158 || (length > 1 && fp->buf[length - 2] == '\\')) {
6159 fp->buf[length++] = '\n';
6162 fp->buf[length] = '\0';
6163 fp->rlimit = fp->buf + length;
6166 /* Close descriptor now, so nesting does not use lots of descriptors. */
6167 check (close (f) == 0);
6169 /* Must do this before calling trigraph_pcp, so that the correct file name
6170 will be printed in warning messages. */
6172 pfile->input_stack_listing_current = 0;
6177 cppReader_perrorWithName (pfile, fname);
6178 check (close (f) == 0);
6184 cppReader_init (cppReader *pfile)
6186 memset ((char *) pfile, 0, sizeof (*pfile));
6188 pfile->get_token = cppGetToken;
6189 pfile->token_buffer_size = 200;
6190 pfile->token_buffer = (char *) dmalloc (pfile->token_buffer_size);
6191 pfile->all_include_files = NULL;
6195 cppReader_setWritten (pfile, 0);
6197 pfile->system_include_depth = 0;
6198 pfile->max_include_len = 0;
6199 pfile->timebuf = NULL;
6200 pfile->only_seen_white = 1;
6202 pfile->buffer = cppReader_nullBuffer (pfile);
6206 cppReader_finish (/*@unused@*/ cppReader *pfile)
6211 /* Free resources used by PFILE.
6212 This is the cppReader 'finalizer' or 'destructor' (in C++ terminology). */
6215 cppCleanup (cppReader *pfile)
6217 while (CPPBUFFER (pfile) != cppReader_nullBuffer (pfile))
6219 (void) cppReader_popBuffer (pfile);
6222 if (pfile->token_buffer != NULL)
6224 sfree (pfile->token_buffer);
6225 pfile->token_buffer = NULL;
6228 while (pfile->if_stack != NULL)
6230 cppIfStackFrame *temp = pfile->if_stack;
6231 pfile->if_stack = temp->next;
6235 while (pfile->all_include_files != NULL)
6237 struct file_name_list *temp = pfile->all_include_files;
6238 pfile->all_include_files = temp->next;
6239 /*@-dependenttrans@*/
6240 cstring_free (temp->fname);
6241 /*@=dependenttrans@*/
6245 cppReader_hashCleanup ();
6249 ** Get the file-mode and data size of the file open on FD
6250 ** and store them in *MODE_POINTER and *SIZE_POINTER.
6254 file_size_and_mode (int fd, mode_t *mode_pointer, size_t *size_pointer)
6258 if (fstat (fd, &sbuf) < 0) {
6262 if (mode_pointer != NULL)
6264 *mode_pointer = sbuf.st_mode;
6267 if (size_pointer != NULL)
6269 *size_pointer = (size_t) sbuf.st_size;
6275 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
6276 retrying if necessary. Return a negative value if an error occurs,
6277 otherwise return the actual number of bytes read,
6278 which must be LEN unless end-of-file was reached. */
6280 static int safe_read (int desc, char *ptr, int len)
6286 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
6287 /*@-compdef@*/ /* ptr is an out parameter */
6288 int nchars = _read (desc, ptr, (unsigned) left);
6291 ssize_t nchars = read (desc, ptr, size_fromInt (left));
6300 return (int) nchars;
6314 /* Initialize PMARK to remember the current position of PFILE. */
6317 parseSetMark (struct parse_marker *pmark, cppReader *pfile)
6319 cppBuffer *pbuf = cppReader_getBuffer (pfile);
6321 pmark->next = pbuf->marks;
6323 pbuf->marks = pmark;
6327 pmark->position = pbuf->cur - pbuf->buf;
6330 /* Cleanup PMARK - we no longer need it. */
6332 void parseClearMark (struct parse_marker *pmark)
6334 struct parse_marker **pp = &pmark->buf->marks;
6336 for (; ; pp = &(*pp)->next)
6338 llassert (*pp != NULL);
6339 if (*pp == pmark) break;
6345 /* Backup the current position of PFILE to that saved in PMARK. */
6348 parseGotoMark (struct parse_marker *pmark, cppReader *pfile)
6350 cppBuffer *pbuf = cppReader_getBuffer (pfile);
6352 if (pbuf != pmark->buf)
6354 cpp_setLocation (pfile);
6355 llfatalbug (cstring_makeLiteral ("Internal error parseGotoMark"));
6358 llassert (pbuf->buf != NULL);
6359 pbuf->cur = pbuf->buf + pmark->position;
6362 /* Reset PMARK to point to the current position of PFILE. (Same
6363 as parseClearMark (PMARK), parseSetMark (PMARK, PFILE) but faster. */
6366 parseMoveMark (struct parse_marker *pmark, cppReader *pfile)
6368 cppBuffer *pbuf = cppReader_getBuffer (pfile);
6370 if (pbuf != pmark->buf)
6372 cpp_setLocation (pfile);
6373 llfatalerror (cstring_makeLiteral ("Internal error parseMoveMark"));
6376 pmark->position = pbuf->cur - pbuf->buf;
6379 void cppReader_initializeReader (cppReader *pfile)
6381 struct cppOptions *opts = CPPOPTIONS (pfile);
6384 /* The code looks at the defaults through this pointer, rather than through
6385 the constant structure above. This pointer gets changed if an environment
6386 variable specifies other defaults. */
6388 struct default_include *include_defaults = include_defaults_array;
6390 /* Add dirs from CPATH after dirs from -I. */
6391 /* There seems to be confusion about what CPATH should do,
6392 so for the moment it is not documented. */
6393 /* Some people say that CPATH should replace the standard include dirs,
6394 but that seems pointless: it comes before them, so it overrides them
6397 xp = (char *) getenv ("CPATH");
6399 if (xp != 0 && ! opts->no_standard_includes)
6401 path_include (pfile, xp);
6404 /* Now that dollars_in_ident is known, initialize is_idchar. */
6405 initialize_char_syntax (opts);
6407 /* CppReader_Install __LINE__, etc. Must follow initialize_char_syntax
6408 and option processing. */
6410 initialize_builtins (pfile);
6412 /* Do standard #defines and assertions
6413 that identify system and machine type. */
6415 if (!opts->inhibit_predefs) {
6416 char *p = (char *) dmalloc (strlen (predefs) + 1);
6417 strcpy (p, predefs);
6423 while (*p == ' ' || *p == '\t')
6428 /* Handle -D options. */
6429 if (p[0] == '-' && p[1] == 'D')
6433 while (*p && *p != ' ' && *p != '\t')
6443 if (opts->debug_output)
6445 output_line_command (pfile, 0, same_file);
6448 cppReader_define (pfile, q);
6450 while (*p == ' ' || *p == '\t')
6464 opts->done_initializing = 1;
6466 { /* Read the appropriate environment variable and if it exists
6467 replace include_defaults with the listed path. */
6471 int win32_buf_size = 0; /* memory we need to allocate */
6474 if (opts->cplusplus)
6476 epath = getenv ("CPLUS_INCLUDE_PATH");
6480 epath = getenv ("C_INCLUDE_PATH");
6484 ** If the environment var for this language is set,
6485 ** add to the default list of include directories.
6488 if (epath != NULL) {
6489 char *nstore = (char *) dmalloc (strlen (epath) + 2);
6491 char *startp, *endp;
6494 /* if we have a posix path list, convert to win32 path list */
6495 if (cygwin32_posix_path_list_p (epath))
6497 win32_buf_size = cygwin32_posix_to_win32_path_list_buf_size (epath);
6498 win32epath = (char *) dmalloc /*@i4@*/ (win32_buf_size);
6499 cygwin32_posix_to_win32_path_list (epath, win32epath);
6503 for (num_dirs = 1, startp = epath; *startp; startp++)
6505 if (*startp == PATH_SEPARATOR)
6511 = (struct default_include *) dmalloc ((num_dirs
6512 * sizeof (struct default_include))
6513 + sizeof (include_defaults_array));
6516 startp = endp = epath;
6519 /* Handle cases like c:/usr/lib:d:/gcc/lib */
6520 if ((*endp == PATH_SEPARATOR) || *endp == 0)
6522 strncpy (nstore, startp, size_fromInt (endp - startp));
6525 strcpy (nstore, ".");
6529 nstore[endp-startp] = '\0';
6532 include_defaults[num_dirs].fname = cstring_fromCharsNew (nstore);
6533 include_defaults[num_dirs].cplusplus = opts->cplusplus;
6534 include_defaults[num_dirs].cxx_aware = 1;
6541 endp = startp = endp + 1;
6548 /* Put the usual defaults back in at the end. */
6549 memcpy ((char *) &include_defaults[num_dirs],
6550 (char *) include_defaults_array,
6551 sizeof (include_defaults_array));
6554 /*@-branchstate@*/ } /*@=branchstate@*/
6557 cppReader_appendIncludeChain (pfile, opts->before_system,
6558 opts->last_before_system);
6559 opts->first_system_include = opts->before_system;
6561 /* Unless -fnostdinc,
6562 tack on the standard include file dirs to the specified list */
6563 if (!opts->no_standard_includes) {
6564 struct default_include *p = include_defaults;
6565 char *specd_prefix = opts->include_prefix;
6566 char *default_prefix = mstring_copy (GCC_INCLUDE_DIR);
6567 int default_len = 0;
6569 /* Remove the `include' from /usr/local/lib/gcc.../include. */
6570 if (default_prefix != NULL) {
6571 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
6572 default_len = strlen (default_prefix) - 7;
6573 default_prefix[default_len] = 0;
6577 /* Search "translated" versions of GNU directories.
6578 These have /usr/local/lib/gcc... replaced by specd_prefix. */
6579 if (specd_prefix != 0 && default_len != 0)
6580 for (p = include_defaults; p->fname != NULL; p++) {
6581 /* Some standard dirs are only for C++. */
6583 || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
6584 /* Does this dir start with the prefix? */
6585 if (!strncmp (cstring_toCharsSafe (p->fname), default_prefix,
6586 size_fromInt (default_len)))
6588 /* Yes; change prefix and add to search list. */
6589 struct file_name_list *nlist
6590 = (struct file_name_list *) dmalloc (sizeof (*nlist));
6591 size_t this_len = strlen (specd_prefix) + cstring_length (p->fname) - default_len;
6592 char *str = (char *) dmalloc (this_len + 1);
6593 strcpy (str, specd_prefix);
6594 strcat (str, cstring_toCharsSafe (p->fname) + default_len);
6597 nlist->fname = cstring_fromChars (str);
6598 nlist->control_macro = 0;
6599 nlist->c_system_include_path = !p->cxx_aware;
6600 nlist->got_name_map = 0;
6602 cppReader_addIncludeChain (pfile, nlist);
6603 if (opts->first_system_include == 0)
6605 opts->first_system_include = nlist;
6611 /* Search ordinary names for GNU include directories. */
6613 for (p = include_defaults; p->fname != NULL; p++)
6615 /* Some standard dirs are only for C++. */
6617 || (opts->cplusplus && !opts->no_standard_cplusplus_includes))
6619 struct file_name_list *nlist
6620 = (struct file_name_list *) dmalloc (sizeof (*nlist));
6621 nlist->control_macro = 0;
6622 nlist->c_system_include_path = !p->cxx_aware;
6623 nlist->fname = p->fname;
6624 nlist->got_name_map = 0;
6627 cppReader_addIncludeChain (pfile, nlist);
6629 if (opts->first_system_include == 0)
6631 opts->first_system_include = nlist;
6635 sfree (default_prefix);
6638 /* Tack the after_include chain at the end of the include chain. */
6639 cppReader_appendIncludeChain (pfile, opts->after_include,
6640 opts->last_after_include);
6642 if (opts->first_system_include == 0)
6644 opts->first_system_include = opts->after_include;
6647 /* With -v, print the list of dirs to search. */
6648 if (opts->verbose) {
6649 struct file_name_list *p;
6650 fprintf (stderr, "#include \"...\" search starts here:\n");
6652 for (p = opts->include; p != NULL; p = p->next) {
6653 if (p == opts->first_bracket_include)
6654 fprintf (stderr, "#include <...> search starts here:\n");
6656 fprintf (stderr, " %s\n", cstring_toCharsSafe (p->fname));
6658 fprintf (stderr, "End of search list.\n");
6662 int cppReader_startProcess (cppReader *pfile, cstring fname)
6666 struct cppOptions *opts = CPPOPTIONS (pfile);
6668 fp = cppReader_pushBuffer (pfile, NULL, 0);
6675 if (opts->in_fname == NULL)
6677 opts->in_fname = cstring_makeLiteralTemp ("");
6680 fp->fname = opts->in_fname;
6681 fp->nominal_fname = fp->fname;
6684 /* Copy the entire contents of the main input file into
6685 the stacked input buffer previously allocated for it. */
6687 if (cstring_isEmpty (fname))
6689 fname = cstring_makeLiteralTemp ("");
6692 else if ((f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666)) < 0)
6694 cppReader_pfatalWithName (pfile, fname);
6701 if (finclude (pfile, f, fname, 0, NULL))
6703 output_line_command (pfile, 0, same_file);
6709 static /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_getBuffer (cppReader *pfile)
6711 return pfile->buffer;
6714 /*@exposed@*/ cppBuffer *cppReader_getBufferSafe (cppReader *pfile)
6716 llassert (pfile->buffer != NULL);
6717 return pfile->buffer;
6720 /*@exposed@*/ char *cppLineBase (cppBuffer *buf)
6722 llassert (buf->buf != NULL);
6723 return (buf->buf + buf->line_base);
6726 int cppBufPeek (cppBuffer *buf)
6728 if (buf->cur == NULL || buf->rlimit == NULL) {
6732 if (buf->cur < buf->rlimit) {
6739 bool cppBuffer_isMacro (cppBuffer *buf)
6743 return (buf->cleanup == cppReader_macroCleanup);
6750 ** Returns true if the macro should be checked, false
6751 ** if it should be expanded normally.
6754 static bool notparseable = FALSE; /* preceeded by @notparseable@ */
6755 static bool notfunction = FALSE; /* preceeded by @notfunction@ */
6756 static bool expectiter = FALSE; /* preceeded by @iter@ */
6757 static bool expectenditer = FALSE; /* second after @iter@ */
6758 static bool expectfunction = FALSE; /* preceeded by @function@ */
6759 static bool expectconstant = FALSE; /* preceeded by @constant@ */
6760 static bool expectmacro = FALSE; /* preceeded by notfunction or notparseable */
6762 static void cpp_setLocation (cppReader *pfile)
6767 if (pfile->buffer != NULL)
6769 if (cstring_isDefined (cppReader_getBuffer (pfile)->nominal_fname))
6771 cstring fname = cppReader_getBuffer (pfile)->nominal_fname;
6773 if (fileTable_exists (context_fileTable (), fname))
6775 fid = fileTable_lookup (context_fileTable (), fname);
6779 fid = fileTable_lookup (context_fileTable (),
6780 cppReader_getBuffer (pfile)->fname);
6785 fid = fileTable_lookup (context_fileTable (),
6786 cppReader_getBuffer (pfile)->fname);
6789 line = cppReader_getBuffer (pfile)->lineno;
6790 fileloc_free (g_currentloc);
6791 g_currentloc = fileloc_create (fid, line, 1);
6795 fileloc_free (g_currentloc);
6796 g_currentloc = fileloc_createBuiltin ();
6800 static bool cpp_shouldCheckMacro (cppReader *pfile, char *p) /*@*/
6802 bool checkmacro = FALSE;
6803 bool hasParams = FALSE;
6804 bool noexpand = FALSE;
6808 cpp_setLocation (pfile);
6810 DPRINTF (("Should check macro? %s", p));
6812 if (expectiter || expectconstant || expectenditer)
6817 expectenditer = TRUE;
6822 expectconstant = FALSE;
6823 expectenditer = FALSE;
6826 if (notfunction || notparseable)
6828 notfunction = FALSE;
6829 notparseable = FALSE;
6838 llassert (*p == '#');
6841 while (*p == ' ' || *p == '\t')
6846 llassert (*p == 'd'); /* define starts */
6850 while (*p == ' ' || *p == '\t')
6855 sname = cstring_fromChars (p);
6856 DPRINTF (("Check macro: %s", sname));
6858 while (((c = *p) != ' ')
6859 && c != '\0' && c != '('
6860 && c != '\t' && c != '\\' && c != '\n'
6866 hasParams = (c == '(');
6872 notparseable = FALSE;
6874 else if (notfunction || fileloc_isStandardLib (g_currentloc))
6876 DPRINTF (("Clear notfunction"));
6877 notfunction = FALSE;
6892 if (usymtab_existsReal (sname))
6894 uentry ue = usymtab_lookup (sname);
6896 DPRINTF (("Lookup macro: %s", uentry_unparse (ue)));
6898 if (fileloc_isPreproc (uentry_whereLast (ue)))
6904 if (uentry_isSpecified (ue))
6906 checkmacro = context_getFlag (FLG_SPECMACROS);
6912 checkmacro = context_getFlag (FLG_LIBMACROS)
6913 || context_getFlag (FLG_FCNMACROS);
6921 DPRINTF (("Macro doesn't exist: %s", bool_unparse (checkmacro)));
6923 if (fileloc_isSystemFile (g_currentloc)
6924 && context_getFlag (FLG_SYSTEMDIREXPAND))
6926 ; /* don't check this macro */
6927 DPRINTF (("Don't check 1"));
6935 DPRINTF (("Has params..."));
6937 if (context_getFlag (FLG_FCNMACROS))
6939 if (usymtab_exists (sname))
6942 ** only get here is macro is redefined
6943 ** error reported elsewhere
6946 DPRINTF (("It exists!"));
6951 ** We make it a forward function, since it might be declared elsewhere.
6952 ** After all headers have been processed, we should check the forward
6956 fileloc loc = fileloc_makePreproc (g_currentloc);
6958 /* the line is off-by-one, since the newline was already read */
6963 expectfunction = FALSE;
6966 le = uentry_makeForwardFunction (sname,
6967 typeId_invalid, loc);
6973 /* Do not define here! */
6975 (void) usymtab_addEntry (le);
6979 DPRINTF (("Check: TRUE"));
6983 DPRINTF (("Flag FCN_MACROS not set!"));
6988 DPRINTF (("No params"));
6990 if (context_getFlag (FLG_CONSTMACROS))
6992 bool nocontent = FALSE;
7005 ** Check if there is nothing after the define.
7008 while ((*rest) != '\0' && isspace (*rest))
7015 nocontent = TRUE; /* empty macro, don't check */
7020 if (usymtab_exists (sname))
7026 fileloc loc = fileloc_makePreproc (g_currentloc);
7027 DPRINTF (("Make constant: %s", sname));
7028 le = uentry_makeConstant (sname,
7029 ctype_unknown, loc);
7030 (void) usymtab_addEntry (le);
7033 checkmacro = !nocontent;
7038 if (checkmacro && usymtab_existsType (sname))
7040 DPRINTF (("Making false..."));
7042 ppllerror (message ("Specified type implemented as macro: %s", sname));
7052 if (usymtab_exists (sname))
7054 uentry ue = usymtab_lookupExpose (sname);
7055 fileloc tloc = fileloc_makePreproc (g_currentloc);
7057 uentry_setDefined (ue, tloc);
7058 fileloc_free (tloc);
7059 uentry_setUsed (ue, fileloc_undefined);
7063 fileloc tloc = fileloc_makePreproc (g_currentloc);
7064 uentry ue = uentry_makeExpandedMacro (sname, tloc);
7065 DPRINTF (("Make expanded macro: %s", sname));
7066 DPRINTF (("Not in symbol table: %s", sname));
7068 (void) usymtab_addGlobalEntry (ue);
7069 fileloc_free (tloc);
7074 DPRINTF (("Returning: %s", bool_unparse (checkmacro)));
7078 static enum cpp_token
7079 cpp_handleComment (cppReader *pfile, struct parse_marker *smark)
7081 cppBuffer *pbuf = cppReader_getBuffer (pfile);
7084 bool eliminateComment = FALSE;
7086 llassert (pbuf->buf != NULL);
7088 start = pbuf->buf + smark->position;
7090 llassert (pbuf->cur != NULL);
7091 len = pbuf->cur - start;
7094 && start[1] == context_getCommentMarkerChar ())
7098 char *scomment = start + 2;
7100 start[0] = BEFORE_COMMENT_MARKER[0];
7101 start[1] = BEFORE_COMMENT_MARKER[1];
7103 llassert (start[len - 2] == '*');
7104 start[len - 2] = AFTER_COMMENT_MARKER[0];
7106 llassert (start[len - 1] == '/');
7107 start[len - 1] = AFTER_COMMENT_MARKER[1];
7109 cppReader_reserve(pfile, size_fromInt (1 + len));
7110 cppReader_putCharQ (pfile, c);
7112 cpp_setLocation (pfile);
7114 if (mstring_equalPrefix (scomment, "ignore"))
7116 if (!context_getFlag (FLG_NOCOMMENTS))
7118 context_enterSuppressRegion ();
7121 else if (mstring_equalPrefix (scomment, "end"))
7123 if (!context_getFlag (FLG_NOCOMMENTS))
7125 context_exitSuppressRegion ();
7128 else if (mstring_equalPrefix (scomment, "notparseable"))
7130 notparseable = TRUE;
7132 eliminateComment = TRUE;
7134 else if (mstring_equalPrefix (scomment, "notfunction"))
7138 eliminateComment = TRUE;
7140 else if (mstring_equalPrefix (scomment, "iter"))
7144 else if (mstring_equalPrefix (scomment, "function"))
7146 expectfunction = TRUE;
7148 else if (mstring_equalPrefix (scomment, "constant"))
7150 expectconstant = TRUE;
7154 char sChar = *scomment;
7160 char *rest = scomment + 1;
7162 if (mstring_equalPrefix (rest, "commentchar"))
7164 eliminateComment = TRUE;
7168 ppllerror (cstring_makeLiteral
7169 ("Cannot restore commentchar"));
7173 char *next = scomment + 12; /* strlen commentchar = 12 */
7175 if (*next != ' ' && *next != '\t' && *next != '\n')
7179 ("Syntactic commentchar comment is not followed by a "
7180 "whitespace character: %c",
7185 char cchar = *(next + 1);
7190 (cstring_makeLiteral
7191 ("Cannot set commentchar to NUL"));
7195 context_setCommentMarkerChar (cchar);
7196 /* setComment = TRUE; */
7201 else if (mstring_equalPrefix (rest, "namechecks"))
7203 context_fileSetFlag (FLG_NAMECHECKS,
7204 ynm_fromCodeChar (sChar));
7206 else if (mstring_equalPrefix (rest, "macroredef"))
7208 context_fileSetFlag (FLG_MACROREDEF,
7209 ynm_fromCodeChar (sChar));
7211 else if (mstring_equalPrefix (rest, "usevarargs"))
7213 context_fileSetFlag (FLG_USEVARARGS,
7214 ynm_fromCodeChar (sChar));
7216 else if (mstring_equalPrefix (rest, "nextlinemacros"))
7218 context_fileSetFlag (FLG_MACRONEXTLINE,
7219 ynm_fromCodeChar (sChar));
7221 else if (mstring_equalPrefix (rest, "allmacros")
7222 || mstring_equalPrefix (rest, "fcnmacros")
7223 || mstring_equalPrefix (rest, "constmacros"))
7227 if (mstring_equalPrefix (rest, "allmacros"))
7231 else if (mstring_equalPrefix (rest, "fcnmacros"))
7237 llassert (mstring_equalPrefix (rest, "constmacros"));
7238 fl = FLG_CONSTMACROS;
7242 context_fileSetFlag (fl, ynm_fromCodeChar (sChar));
7243 notfunction = FALSE;
7256 if (eliminateComment)
7261 /* Replaces comment char's in start with spaces */
7263 for (i = 2; i < len - 2; i++)
7265 if (start[i] == BEFORE_COMMENT_MARKER[0]
7266 || start[i] == BEFORE_COMMENT_MARKER[1]
7267 || start[i] == context_getCommentMarkerChar ())
7273 cppReader_putStrN (pfile, start, size_fromInt (len));
7274 parseClearMark (smark);
7284 ** Output the comment as all spaces so line/column
7285 ** in output file is still correct.
7289 cstring lintcomment = cstring_undefined;
7291 if (context_getFlag (FLG_LINTCOMMENTS))
7293 if (mstring_equalPrefix (start, "*NOTREACHED*/"))
7295 lintcomment = cstring_makeLiteralTemp ("l_notreach");
7297 else if (mstring_equalPrefix (start, "*PRINTFLIKE*/"))
7299 lintcomment = cstring_makeLiteralTemp ("l_printfli");
7301 else if (mstring_equalPrefix (start, "*FALLTHROUGH*/"))
7303 lintcomment = cstring_makeLiteralTemp ("l_fallthrou");
7305 else if (mstring_equalPrefix (start, "*ARGSUSED*/"))
7307 lintcomment = cstring_makeLiteralTemp ("l_argsus");
7309 else if (mstring_equalPrefix (start, "*FALLTHRU*/"))
7311 lintcomment = cstring_makeLiteralTemp ("l_fallth");
7315 lintcomment = cstring_undefined;
7320 lintcomment = cstring_undefined;
7323 if (cstring_isDefined (lintcomment))
7325 c = BEFORE_COMMENT_MARKER[0];
7326 start[0] = BEFORE_COMMENT_MARKER[1];
7328 llassert (cstring_length (lintcomment) == len - 3);
7330 for (i = 1; i < len - 2; i++)
7332 start[i] = cstring_getChar (lintcomment, i);
7335 start[len - 2] = AFTER_COMMENT_MARKER[0];
7336 start[len - 1] = AFTER_COMMENT_MARKER[1];
7340 /* Replaces char's in start with spaces */
7341 for (i = 0; i < len; i++)
7345 && start[i + 1] == '*') {
7348 message ("Start comment inside comment"));
7351 if (start[i] != '\n')
7358 cppReader_reserve (pfile, size_fromInt (1 + len));
7359 cppReader_putCharQ (pfile, c);
7360 cppReader_putStrN (pfile, start, size_fromInt (len));
7361 parseClearMark (smark);
7367 static int cpp_openIncludeFile (char *filename)
7369 int res = open (filename, O_RDONLY, 0666);
7372 && !fileTable_exists (context_fileTable (),
7373 cstring_fromChars (filename)))
7375 DPRINTF (("Add header: %s", filename));
7376 (void) fileTable_addHeaderFile (context_fileTable (),
7377 cstring_fromChars (filename));
7383 static bool cpp_skipIncludeFile (cstring fname)
7385 if (context_isSystemDir (fname))
7387 DPRINTF (("System dir: %s", fname));
7389 if (lcllib_isSkipHeader (fname))
7391 DPRINTF (("Skip include TRUE: %s", fname));
7395 if (context_getFlag (FLG_SKIPSYSHEADERS))
7397 DPRINTF (("Skip include TRUE: %s", fname));
7402 if (context_getFlag (FLG_SINGLEINCLUDE))
7404 fname = cstring_fromChars (removePreDirs (cstring_toCharsSafe (fname)));
7406 # if defined (WIN32) || defined (OS2)
7407 cstring_replaceAll (fname, '\\', '/');
7410 if (fileTable_exists (context_fileTable (), fname))
7412 DPRINTF (("Skip include TRUE: %s", fname));
7417 DPRINTF (("Skip include FALSE: %s", fname));
7421 static int cpp_peekN (cppReader *pfile, int n)
7423 cppBuffer *buf = cppReader_getBuffer (pfile);
7425 llassert (buf->cur != NULL);
7427 return (buf->rlimit - buf->cur >= (n)
7432 cppBuffer *cppBuffer_prevBuffer (cppBuffer *buf)
7437 void cppBuffer_forward (cppBuffer *buf, int n)
7439 llassert (buf->cur != NULL);