3 http://src.openresources.com/debian/src/devel/HTML/S/altgcc_2.7.2.2.orig%20altgcc-2.7.2.2.orig%20protoize.c.html
5 abspath (cwd, rel_filename)
10 *** cpplib.c.old Tue Nov 28 2000 09:04:09 AM
11 --- cpplib.c Tue Nov 28 2000 08:55:18 AM
14 c2 = cppReader_peekC (pfile)
21 c2 = cppReader_peekC (pfile)
24 ! cppReader_forward (pfile, 1)
30 cppReader_putChar (pfile, c)
33 Carl J. Appellof ( mailto:cappello@legato.com <mailto:cappello@legato.com> )
37 ** LCLint - annotation-assisted static program checker
38 ** Copyright (C) 1994-2001 University of Virginia,
39 ** Massachusetts Institute of Technology
41 ** This program is free software; you can redistribute it and/or modify it
42 ** under the terms of the GNU General Public License as published by the
43 ** Free Software Foundation; either version 2 of the License, or (at your
44 ** option) any later version.
46 ** This program is distributed in the hope that it will be useful, but
47 ** WITHOUT ANY WARRANTY; without even the implied warranty of
48 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
49 ** General Public License for more details.
51 ** The GNU General Public License is available from http://www.gnu.org/ or
52 ** the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
53 ** MA 02111-1307, USA.
55 ** For information on lclint: lclint-request@cs.virginia.edu
56 ** To report a bug: lclint-bug@cs.virginia.edu
57 ** For more information: http://lclint.cs.virginia.edu
63 Copyright (C) 1986, 87, 89, 92-6, 1997 Free Software Foundation, Inc.
64 Contributed by Per Bothner, 1994-95.
65 Based on CCCP program by Paul Rubin, June 1986
66 Adapted to ANSI C, Richard Stallman, Jan 1987
68 This program is free software; you can redistribute it and/or modify it
69 under the terms of the GNU General Public License as published by the
70 Free Software Foundation; either version 2, or (at your option) any
73 This program is distributed in the hope that it will be useful,
74 but WITHOUT ANY WARRANTY; without even the implied warranty of
75 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
76 GNU General Public License for more details.
78 You should have received a copy of the GNU General Public License
79 along with this program; if not, write to the Free Software
80 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
82 In other words, you are welcome to use, share and improve this program.
83 You are forbidden to forbid anyone else to use, share and improve
84 what you give them. Help stamp out software-hoarding! */
88 * - OS2 drive specs like WIN32
89 * - Includes for IBMs OS/2 compiler
101 # if !(defined (WIN32) || defined (OS2) && defined (__IBMC__))
105 # include <sys/types.h>
106 # include <sys/stat.h>
109 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
111 # include <sys/utime.h> /* for __DATE__ and __TIME__ */
116 # include <time.h> /* Reported by Paul Smith */
117 # include <sys/time.h>
118 # include <sys/resource.h>
120 # include <sys/times.h>
124 # endif /* not VMS */
125 # endif /* not WIN32 */
127 /* This defines "errno" properly for VMS, and gives us EACCES. */
130 # include "lclintMacros.nf"
131 # include "llbasic.h"
135 # include "cpperror.h"
136 # include "cpphash.h"
138 # include "version.h"
143 ** This is really kludgey code...
149 #define NO_SHORTNAMES
157 /*@constant int IMPORT_FOUND@*/
158 # define IMPORT_FOUND -2
160 /*@constant int SKIP_INCLUDE@*/
161 # define SKIP_INCLUDE IMPORT_FOUND
163 /*@constant unused int IMPORT_NOT_FOUND@*/
164 # define IMPORT_NOT_FOUND -1
167 /*@constant unused int STDC_VALUE@*/
171 /* By default, colon separates directories in a path. */
172 #ifndef PATH_SEPARATOR
173 /*@constant char PATH_SEPARATOR@*/
174 #define PATH_SEPARATOR ':'
177 static void parse_name (cppReader *, int);
179 static int cpp_openIncludeFile (char *p_filename)
180 /*@modifies fileSystem @*/ ;
182 static void cpp_setLocation (cppReader *p_pfile)
183 /*@modifies g_currentloc@*/ ;
185 static enum cpp_token cpp_handleComment (cppReader *p_pfile,
186 struct parse_marker *p_smark)
187 /*@modifies *p_pfile, *p_smark@*/;
189 static bool cpp_shouldCheckMacro (cppReader *p_pfile, char *p_p) /*@*/ ;
191 static bool cpp_skipIncludeFile (cstring p_fname) /*@*/ ;
197 /* Symbols to predefine. */
199 #ifdef CPP_PREDEFINES
200 static /*@observer@*/ char *predefs = CPP_PREDEFINES;
202 static /*@observer@*/ char *predefs = "";
205 /* We let tm.h override the types used here, to handle trivial differences
206 such as the choice of unsigned int or long unsigned int for size_t.
207 When machines start needing nontrivial differences in the size type,
208 it would be best to do something here to figure out automatically
209 from other information what type to use. */
211 /* The string value for __SIZE_TYPE__. */
214 /*@constant observer char *SIZE_TYPE@*/
215 #define SIZE_TYPE "long unsigned int"
218 /* The string value for __PTRDIFF_TYPE__. */
221 /*@constant observer char *PTRDIFF_TYPE@*/
222 #define PTRDIFF_TYPE "long int"
225 /* The string value for __WCHAR_TYPE__. */
228 /*@constant observer char *WCHAR_TYPE@*/
229 #define WCHAR_TYPE "int"
232 /* The string value for __USER_LABEL_PREFIX__ */
234 #ifndef USER_LABEL_PREFIX
235 /*@constant observer char *USER_LABEL_PREFIX@*/
236 #define USER_LABEL_PREFIX ""
239 /* The string value for __REGISTER_PREFIX__ */
241 #ifndef REGISTER_PREFIX
242 /*@constant observer char *REGISTER_PREFIX@*/
243 #define REGISTER_PREFIX ""
246 /* table to tell if char can be part of a C identifier. */
247 static bool is_idchar[256];
248 /* table to tell if char can be first char of a c identifier. */
249 static bool is_idstart[256];
250 /* table to tell if c is horizontal space. */
251 static bool is_hor_space[256];
252 /* table to tell if c is horizontal or vertical space. */
253 static bool is_space[256];
255 static /*@exposed@*/ /*@null@*/ cppBuffer *
256 cppReader_getBuffer (/*@special@*/ cppReader *p_pfile)
257 /*@uses p_pfile->buffer@*/
258 /*@modifies nothing@*/ ;
261 # define SKIP_WHITE_SPACE(p) do { /*@access cstring@*/ while (is_hor_space[(int) *(p)]) { (p)++; } } /*@noaccess cstring@*/ while (0)
264 # define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*(p)]) { (p)++; } } while (0)
266 static int cpp_peekN (cppReader *p_pfile, int p_n) /*@*/ ;
268 /*@function static int cppBuffer_get (sef cppBuffer *p_b) modifies *p_b ; @*/
269 # define cppBuffer_get(BUFFER) \
270 ((BUFFER)->cur < (BUFFER)->rlimit ? *(BUFFER)->cur++ : EOF)
272 /* Append string STR (of length N) to PFILE's output buffer. Make space. */
273 /*@function static void cppReader_puts (sef cppReader *p_file, char *p_str, sef size_t p_n)
274 modifies *p_file; @*/
275 # define cppReader_puts(PFILE, STR, N) \
276 cppReader_reserve(PFILE, N), cppReader_putStrN (PFILE, STR,N)
278 /* Append character CH to PFILE's output buffer. Assume sufficient space. */
280 /*@function static void cppReader_putCharQ (cppReader *p_file, char p_ch)
281 modifies *p_file; @*/
282 # define cppReader_putCharQ(PFILE, CH) (*(PFILE)->limit++ = (CH))
284 /* Append character CH to PFILE's output buffer. Make space if need be. */
286 /*@function static void cppReader_putChar (sef cppReader *p_file, char p_ch)
287 modifies *p_file; @*/
288 #define cppReader_putChar(PFILE, CH) (cppReader_reserve (PFILE, (size_t) 1), cppReader_putCharQ (PFILE, CH))
290 /* Make sure PFILE->limit is followed by '\0'. */
291 /*@function static void cppReader_nullTerminateQ (cppReader *p_file)
292 modifies *p_file; @*/
294 #define cppReader_nullTerminateQ(PFILE) (*(PFILE)->limit = 0)
296 /*@function static void cppReader_nullTerminate (sef cppReader *p_file)
297 modifies *p_file; @*/
298 # define cppReader_nullTerminate(PFILE) \
299 (cppReader_reserve (PFILE, (size_t) 1), *(PFILE)->limit = 0)
301 /*@function static void cppReader_adjustWritten (cppReader *p_file, size_t)
302 modifies *p_file; @*/
303 #define cppReader_adjustWritten(PFILE,DELTA) ((PFILE)->limit += (DELTA))
305 /*@function static bool cppReader_isC89 (cppReader *) modifies nothing; @*/
306 #define cppReader_isC89(PFILE) (CPPOPTIONS(PFILE)->c89)
308 /*@function static observer char *cppReader_wcharType (cppReader *)
309 modifies nothing; @*/
311 # define cppReader_wcharType(PFILE) \
312 (CPPOPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
314 static void cppBuffer_forward (cppBuffer *p_buf, int p_n) /*@modifies *p_buf@*/ ;
316 /*@function static void cppReader_forward (cppReader *p_pfile, int) modifies *p_pfile; @*/
317 # define cppReader_forward(pfile, N) \
318 (cppBuffer_forward (cppReader_getBufferSafe (pfile), (N)))
320 /*@function static int cppReader_getC (cppReader *p_pfile) modifies *p_pfile; @*/
321 # define cppReader_getC(pfile) (cppBuffer_get (cppReader_getBufferSafe (pfile)))
323 /*@function static int cppReader_peekC (cppReader *) modifies nothing;@*/
324 # define cppReader_peekC(pfile) (cppBufPeek (cppReader_getBufferSafe (pfile)))
326 /* Move all backslash-newline pairs out of embarrassing places.
327 Exchange all such pairs following BP
328 with any potentially-embarrassing characters that follow them.
329 Potentially-embarrassing characters are / and *
330 (because a backslash-newline inside a comment delimiter
331 would cause it not to be recognized). */
334 # define NEWLINE_FIX \
335 do { while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n') { cppReader_forward (pfile, 2); } } while(FALSE)
337 /* Same, but assume we've already read the potential '\\' into C. */
339 # define NEWLINE_FIX1(C) do { \
340 while ((C) == '\\' && cppReader_peekC (pfile) == '\n') { cppReader_forward (pfile, 1); (C) = cppReader_getC (pfile); }\
343 static void parseSetMark (/*@out@*/ struct parse_marker *,
345 static void parseClearMark (struct parse_marker *);
346 static void parseGotoMark (struct parse_marker *, cppReader *);
347 static void parseMoveMark (struct parse_marker *, cppReader *);
349 /* If we have a huge buffer, may need to cache more recent counts */
350 static /*@exposed@*/ char *cppLineBase (/*@sef@*/ cppBuffer *);
352 static /*@exposed@*/ /*@null@*/ cppBuffer *
353 cppReader_pushBuffer (cppReader *p_pfile,
354 /*@owned@*/ /*@null@*/ char *, size_t)
355 /*@modifies p_pfile@*/ ;
357 static void cppReader_appendIncludeChain
359 /*@keep@*/ struct file_name_list *p_first,
360 /*@dependent@*/ struct file_name_list *p_last);
362 static void cppReader_macroCleanup (cppBuffer *p_pbuf, cppReader *p_pfile);
363 static enum cpp_token cppReader_nullUnderflow (/*@unused@*/ cppReader *p_pfile);
365 static void cppReader_nullCleanup (/*@unused@*/ cppBuffer *p_pbuf,
366 /*@unused@*/ cppReader *p_pfile);
368 static void cppReader_fileCleanup (cppBuffer *p_pbuf,
369 /*@unused@*/ cppReader *p_pfile);
371 static int cppReader_handleDirective (cppReader *p_pfile);
373 static void cppReader_scanBuffer (cppReader *p_pfile);
375 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
378 ** WIN32 (at least the VC++ include files) does not define mode_t.
381 /*@-incondefs@*/ /*@-czechtypes@*/
382 typedef unsigned int mode_t;
383 /*@=incondefs@*/ /*@=czechtypes@*/
387 static int file_size_and_mode (int p_fd, /*@out@*/ mode_t *p_mode_pointer,
388 /*@out@*/ size_t *p_size_pointer);
389 static int safe_read (int p_desc, /*@out@*/ char *p_ptr, int p_len);
393 ** cppBuffer_isMacro is true if the buffer contains macro expansion.
394 ** (Note that it is false while we're expanding marco *arguments*.)
397 static bool cppBuffer_isMacro (/*@null@*/ cppBuffer *) /*@*/ ;
399 static void path_include (cppReader *p_pfile, char *p_path)
400 /*@modifies p_pfile@*/ ;
402 static void initialize_builtins (cppReader *p_pfile)
403 /*@modifies p_pfile@*/ ;
405 static void initialize_char_syntax (struct cppOptions *p_opts) ;
407 static int /*@alt void@*/ finclude (cppReader *p_pfile, int p_f,
409 bool p_system_header_p,
410 /*@dependent@*/ /*@null@*/ struct file_name_list *p_dirptr);
412 static void validate_else (cppReader *p_pfile, cstring p_directive);
414 static void conditional_skip (cppReader *p_pfile, int p_skip,
415 enum node_type p_type,
416 /*@dependent@*/ /*@null@*/ char *p_control_macro);
418 static HOST_WIDE_INT eval_if_expression (cppReader *p_pfile,
422 static void skip_if_group (cppReader *p_pfile, int p_any);
424 static bool comp_def_part (bool p_first, char *p_beg1, int p_len1,
425 char *p_beg2, int p_len2, bool p_last);
428 extern void fancy_abort ();
431 static bool redundant_include_p (cppReader *p_pfile, /*@null@*/ cstring p_name);
432 static bool is_system_include (cppReader *p_pfile, cstring p_filename);
434 static /*@observer@*/ /*@null@*/ struct file_name_map *
435 read_name_map (cppReader *p_pfile, cstring p_dirname);
437 static cstring read_filename_string (int p_ch, /*@open@*/ FILE *p_f);
439 static int open_include_file (cppReader *p_pfile,
440 /*@owned@*/ cstring p_fname,
441 /*@null@*/ struct file_name_list *p_searchptr);
443 static void push_macro_expansion (cppReader *,
444 /*@owned@*/ char *, size_t,
445 /*@dependent@*/ HASHNODE *);
447 /* Last arg to output_line_command. */
448 enum file_change_code {
449 same_file, enter_file, leave_file
452 /* `struct directive' defines one #-directive, including how to handle it. */
455 int length; /* Length of name */
456 /*@null@*/ int (*func)(); /* Function to handle directive */
457 /*@observer@*/ cstring name; /* Name of directive */
458 enum node_type type; /* Code which describes which directive. */
459 bool command_reads_line; /* One if rest of line is read by func. */
460 bool traditional_comments; /* Nonzero: keep comments if -traditional. */
461 bool pass_thru; /* Copy preprocessed directive to output file.*/
464 /* These functions are declared to return int instead of void since they
465 are going to be placed in a table and some old compilers have trouble with
466 pointers to functions returning void. */
468 static int do_define (cppReader *, /*@null@*/ struct directive *,
470 static int do_defineAux (cppReader *, /*@null@*/ struct directive *,
471 char *, char *, bool);
473 static int do_line (cppReader *, /*@null@*/ struct directive *);
474 static int do_include (cppReader *, struct directive *, char *, char *);
475 static int do_undef (cppReader *, struct directive *, char *, char *);
476 static int do_error (cppReader *, struct directive *, char *, char *);
477 static int do_pragma (cppReader *, struct directive *, char *, char *);
478 static int do_ident (cppReader *, struct directive *, char *, char *);
479 static int do_if (cppReader *, struct directive *, char *, char *);
480 static int do_xifdef (cppReader *, struct directive *, char *, char *);
481 static int do_else (cppReader *, struct directive *, char *, char *);
482 static int do_elif (cppReader *, struct directive *, char *, char *);
483 static int do_endif (cppReader *, struct directive *, char *, char *);
484 static int do_warning (cppReader *, struct directive *, char *, char *);
486 /* If a buffer's dir field is SELF_DIR_DUMMY, it means the file was found
487 via the same directory as the file that #included it. */
489 /*@constant observer struct file_name_list *SELF_DIR_DUMMY@*/
490 #define SELF_DIR_DUMMY ((struct file_name_list *) (~0))
492 /* #include "file" looks in source file dir, then stack. */
493 /* #include <file> just looks in the stack. */
494 /* -I directories are added to the end, then the defaults are added. */
498 static struct default_include {
499 /*@dependent@*/ /*@observer@*/ cstring fname; /* The name of the directory. */
500 int cplusplus; /* Only look here if we're compiling C++. */
501 int cxx_aware; /* Includes in this directory don't need to
502 be wrapped in extern "C" when compiling
504 } include_defaults_array[]
506 /* This is the dir for fixincludes. Put it just before
507 the files that we fix. */
508 { GCC_INCLUDE_DIR, 0, 0 },
509 { GCC_INCLUDE_DIR2, 0, 0 },
510 { cstring_undefined, 0, 0 }
513 /*@noaccess cstring@*/
515 /* Here is the actual list of #-directives, most-often-used first.
516 The initialize_builtins function assumes #define is the very first. */
520 static struct directive directive_table[] = {
521 { 6, do_define, "define", T_DEFINE, FALSE, TRUE, FALSE },
522 { 5, do_xifdef, "ifdef", T_IFDEF, TRUE, FALSE, FALSE },
523 { 6, do_xifdef, "ifndef", T_IFNDEF, TRUE, FALSE, FALSE },
524 { 7, do_include, "include", T_INCLUDE, TRUE, FALSE, FALSE },
525 { 5, do_endif, "endif", T_ENDIF, TRUE, FALSE, FALSE },
526 { 4, do_else, "else", T_ELSE, TRUE, FALSE, FALSE },
527 { 2, do_if, "if", T_IF, TRUE, FALSE, FALSE },
528 { 4, do_elif, "elif", T_ELIF, TRUE, FALSE, FALSE },
529 { 5, do_undef, "undef", T_UNDEF, FALSE, FALSE, FALSE },
530 { 5, do_error, "error", T_ERROR, FALSE, FALSE, FALSE },
531 { 7, do_warning, "warning", T_WARNING, FALSE, FALSE, FALSE },
532 { 6, do_pragma, "pragma", T_PRAGMA, FALSE, FALSE, TRUE},
533 { 4, do_line, "line", T_LINE, TRUE, FALSE, FALSE },
534 { 5, do_ident, "ident", T_IDENT, TRUE, FALSE, TRUE },
535 /* { 8, do_unassert, "unassert", T_UNASSERT, TRUE, FALSE, FALSE }, */
536 { -1, 0, "", T_UNUSED, FALSE, FALSE, FALSE },
538 /*@noaccess cstring@*/
540 static cstring searchPath_unparse (struct file_name_list *search_start)
542 cstring res = cstring_newEmpty ();
543 struct file_name_list *searchptr = NULL;
545 for (searchptr = search_start; searchptr != NULL;
546 searchptr = searchptr->next)
548 if (!cstring_isEmpty (searchptr->fname)) {
549 res = cstring_concatFree1 (res, searchptr->fname);
550 if (searchptr->next != NULL) {
551 res = cstring_appendChar (res, ';');
561 initialize_char_syntax (struct cppOptions *opts)
566 * Set up is_idchar and is_idstart tables. These should be
567 * faster than saying (is_alpha (c) || c == '_'), etc.
568 * Set up these things before calling any routines tthat
572 for (i = 'a'; i <= 'z'; i++) {
573 is_idchar[i - 'a' + 'A'] = TRUE;
574 is_idchar[(int) i] = TRUE;
575 is_idstart[i - 'a' + 'A'] = TRUE;
576 is_idstart[(int) i] = TRUE;
579 for (i = '0'; i <= '9'; i++)
581 is_idchar[(int) i] = TRUE;
584 is_idchar['_'] = TRUE;
585 is_idstart['_'] = TRUE;
586 is_idchar['$'] = opts->dollars_in_ident;
587 is_idstart['$'] = opts->dollars_in_ident;
589 /* horizontal space table */
590 is_hor_space[' '] = TRUE;
591 is_hor_space['\t'] = TRUE;
592 is_hor_space['\v'] = TRUE;
593 is_hor_space['\f'] = TRUE;
594 is_hor_space['\r'] = TRUE;
596 is_space[' '] = TRUE;
597 is_space['\t'] = TRUE;
598 is_space['\v'] = TRUE;
599 is_space['\f'] = TRUE;
600 is_space['\n'] = TRUE;
601 is_space['\r'] = TRUE;
604 bool isIdentifierChar (char c)
606 return is_idchar[(int) c];
609 /* Place into P_PFILE a quoted string representing the string SRC.
610 Caller must reserve enough space in pfile->token_buffer. */
613 quote_string (cppReader *pfile, char *src)
617 cppReader_putCharQ (pfile, '\"');
620 switch ((c = *src++))
624 cppReader_putCharQ (pfile, c);
627 sprintf (cppReader_getPWritten (pfile), "\\%03o",
629 cppReader_adjustWritten (pfile, (size_t) 4);
631 /*@switchbreak@*/ break;
635 cppReader_putCharQ (pfile, '\\');
636 cppReader_putCharQ (pfile, c);
637 /*@switchbreak@*/ break;
640 cppReader_putCharQ (pfile, '\"');
641 cppReader_nullTerminateQ (pfile);
647 /* Re-allocates PFILE->token_buffer so it will hold at least N more chars. */
650 cppReader_growBuffer (cppReader *pfile, size_t n)
652 size_t old_written = cppReader_getWritten (pfile);
653 pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
654 pfile->token_buffer = (char *)
655 drealloc (pfile->token_buffer, pfile->token_buffer_size);
656 cppReader_setWritten (pfile, old_written);
660 * process a given definition string, for initialization
661 * If STR is just an identifier, define it with value 1.
662 * If STR has anything after the identifier, then it should
663 * be identifier=definition.
667 cppReader_define (cppReader *pfile, char *str)
672 DPRINTF (("Cpp reader define: %s", str));
674 if (!is_idstart[(int) *p])
676 DPRINTF (("ERROR 1"));
677 cppReader_error (pfile,
678 message ("Malformed option `-D%s'",
679 cstring_fromChars (str)));
686 DPRINTF (("Here 2"));
688 while (is_idchar[(int) *p])
695 while (*p != ')' && *p != '\0') {
704 message ("Malformed option: -D%s (no closing parenthesis)",
705 cstring_fromChars (str)));
709 DPRINTF (("Here 2"));
713 buf = (char *) dmalloc (size_fromInt (p - str + 4));
714 strcpy ((char *) buf, str);
715 strcat ((char *) buf, " 1");
719 DPRINTF (("ERROR 2"));
720 cppReader_error (pfile,
721 message ("Malformed option: -D%s (expected '=', found '%c')",
722 cstring_fromChars (str),
729 /* Copy the entire option so we can modify it. */
730 DPRINTF (("Copying..."));
731 buf = (char *) dmalloc (2 * strlen (str) + 1);
732 strncpy (buf, str, size_fromInt (p - str));
734 /* Change the = to a space. */
736 /* Scan for any backslash-newline and remove it. */
742 if (*p == '\\' && p[1] == '\n')
748 DPRINTF (("Here we are..."));
752 llassert (buf != NULL);
753 DPRINTF (("Do define: %s / %ld", buf, size_toLong (strlen (buf))));
754 (void) do_define (pfile, NULL, buf, buf + strlen (buf));
758 /* Append a chain of `struct file_name_list's
759 to the end of the main include chain.
760 FIRST is gthe beginning of the chain to append, and LAST is the end. */
763 cppReader_appendIncludeChain (cppReader *pfile,
764 struct file_name_list *first,
765 struct file_name_list *last)
767 struct cppOptions *opts = CPPOPTIONS (pfile);
768 struct file_name_list *dir;
770 if (first == NULL || last == NULL)
775 if (opts->include == 0)
777 opts->include = first;
781 llassert (opts->last_include->next == NULL);
782 opts->last_include->next = first;
785 if (opts->first_bracket_include == 0)
787 opts->first_bracket_include = first;
789 for (dir = first; ; dir = dir->next) {
790 int len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
791 if (len > pfile->max_include_len)
792 pfile->max_include_len = len;
798 llassert (last->next == NULL);
799 /* last->next = NULL; */
800 opts->last_include = last;
803 static /*@unused@*/ void
804 cppReader_showIncludeChain (cppReader *pfile)
806 struct file_name_list *dirs = CPPOPTIONS (pfile)->include;
812 fprintf (stderr, "*%s*:", cstring_toCharsSafe (dirs->fname));
816 fprintf (stderr, "\n");
820 fprintf (stderr, "No includes\n");
825 cppReader_addIncludeChain (cppReader *pfile, struct file_name_list *dir)
827 struct cppOptions *opts = CPPOPTIONS (pfile);
834 if (opts->include == 0)
840 llassert (opts->last_include->next == NULL);
841 opts->last_include->next = dir;
844 if (opts->first_bracket_include == 0)
846 int len = cstring_length (dir->fname) + INCLUDE_LEN_FUDGE;
847 opts->first_bracket_include = dir;
848 if (len > pfile->max_include_len)
850 pfile->max_include_len = len;
855 opts->last_include = dir;
856 /* cppReader_showIncludeChain (pfile); */
859 /* Given a colon-separated list of file names PATH,
860 add all the names to the search path for include files. */
863 path_include (cppReader *pfile, char *path)
870 /* if we have a posix path list, convert to win32 path list */
871 win32temp = (char *) dmalloc /*@i4@*/
872 (cygwin32_posix_to_win32_path_list_buf_size (path));
873 cygwin32_posix_to_win32_path_list (path, win32temp);
883 struct file_name_list *dirtmp;
885 /* Find the end of this name. */
886 while (*q != '\0' && *q != PATH_SEPARATOR)
893 /* An empty name in the path stands for the current directory. */
894 name = (char *) dmalloc ((size_t) 2);
900 /* Otherwise use the directory that is named. */
901 name = (char *) dmalloc (size_fromInt (q - p + 1));
902 memcpy (name, p, size_fromInt (q - p));
906 dirtmp = (struct file_name_list *) dmalloc (sizeof (*dirtmp));
907 dirtmp->next = 0; /* New one goes on the end */
908 dirtmp->control_macro = 0;
909 dirtmp->c_system_include_path = 0;
910 dirtmp->fname = cstring_fromChars (name);
911 dirtmp->got_name_map = 0;
912 cppReader_addIncludeChain (pfile, dirtmp);
914 /* Advance past this name. */
918 /* Skip the colon. */
924 cppOptions_init (cppOptions *opts)
926 memset ((char *) opts, 0, sizeof *opts);
929 opts->in_fname = NULL;
930 opts->out_fname = NULL;
932 /* Initialize is_idchar to allow $. */
933 opts->dollars_in_ident = TRUE;
935 opts->no_line_commands = 0;
936 opts->no_trigraphs = TRUE;
937 opts->put_out_comments = 1;
938 opts->print_include_names = 0;
939 opts->dump_macros = DUMP_DEFINITIONS; /* DUMP_NONE; */
943 opts->cplusplus_comments = 1;
948 opts->pedantic_errors = 0;
949 opts->inhibit_warnings = 0;
950 opts->warn_comments = 0;
951 opts->warnings_are_errors = 0;
953 initialize_char_syntax (opts);
957 cppReader_nullUnderflow (/*@unused@*/ cppReader *pfile)
963 cppReader_nullCleanup (/*@unused@*/ cppBuffer *pbuf,
964 /*@unused@*/ cppReader *pfile)
970 cppReader_macroCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
972 HASHNODE *macro = pbuf->hnode;
974 if (macro->type == T_DISABLED)
976 macro->type = T_MACRO;
979 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
987 cppReader_fileCleanup (cppBuffer *pbuf, /*@unused@*/ cppReader *pfile)
989 if (pbuf->buf != NULL)
996 /* Assuming we have read '/'.
997 If this is the start of a comment (followed by '*' or '/'),
998 skip to the end of the comment, and return ' '.
999 Return EOF if we reached the end of file before the end of the comment.
1000 If not the start of a comment, return '/'. */
1003 skip_comment (cppReader *pfile, /*@null@*/ long *linep)
1007 llassert (pfile->buffer != NULL);
1008 llassert (pfile->buffer->cur != NULL);
1010 while (cppReader_peekC (pfile) == '\\' && cpp_peekN (pfile, 1) == '\n')
1017 cppReader_forward (pfile, 2);
1020 if (cppReader_peekC (pfile) == '*')
1022 cppReader_forward (pfile, 1);
1027 c = cppReader_getC (pfile);
1034 while (c == (int) '\\' && cppReader_peekC (pfile) == (int) '\n')
1041 cppReader_forward (pfile, 1), c = cppReader_getC (pfile);
1044 if (prev_c == (int) '*' && c == (int) '/')
1049 if (c == (int) '\n' && (linep != NULL))
1055 else if (cppReader_peekC (pfile) == '/'
1056 && CPPOPTIONS (pfile)->cplusplus_comments)
1058 cppReader_forward (pfile, 1);
1062 c = cppReader_getC (pfile);
1066 /* Allow hash comment to be terminated by EOF. */
1070 while (c == (int) '\\' && cppReader_peekC (pfile) == '\n')
1072 cppReader_forward (pfile, 1);
1073 c = cppReader_getC (pfile);
1081 if (c == (int) '\n')
1083 /* Don't consider final '\n' to be part of comment. */
1084 cppReader_forward (pfile, -1);
1095 /* Skip whitespace \-newline and comments. Does not macro-expand. */
1097 cppSkipHspace (cppReader *pfile)
1105 llassert (pfile->buffer != NULL);
1107 c = cppReader_peekC (pfile);
1111 return 0; /* FIXME */
1114 if (is_hor_space[c])
1116 if ((c == '\f' || c == '\v') && cppReader_isPedantic (pfile))
1117 cppReader_pedwarn (pfile,
1118 message ("%s in preprocessing directive",
1120 ? cstring_makeLiteralTemp ("formfeed")
1121 : cstring_makeLiteralTemp ("vertical tab")));
1124 cppReader_forward (pfile, 1);
1128 cppReader_forward (pfile, 1);
1129 c = skip_comment (pfile, NULL);
1133 cppReader_forward (pfile, -1);
1136 if (c == EOF || c == '/')
1141 else if (c == '\\' && cpp_peekN (pfile, 1) == '\n')
1143 cppReader_forward (pfile, 2);
1145 else if (c == '@' && CPPBUFFER (pfile)->has_escapes
1146 && is_hor_space [cpp_peekN (pfile, 1)])
1148 cppReader_forward (pfile, 2);
1157 /* Read the rest of the current line.
1158 The line is appended to PFILE's output buffer. */
1161 copy_rest_of_line (cppReader *pfile)
1163 struct cppOptions *opts = CPPOPTIONS (pfile);
1170 llassert (pfile->buffer != NULL);
1172 c = cppReader_getC (pfile);
1178 if (cppReader_peekC (pfile) == '\n')
1180 cppReader_forward (pfile, 1);
1184 /*@fallthrough@*/ case '\'': case '\"':
1185 goto scan_directive_token;
1188 nextc = cppReader_peekC (pfile);
1191 ** was (opts->cplusplus_comments && nextc == '*')
1196 || (opts->cplusplus_comments && nextc == '/'))
1198 goto scan_directive_token;
1200 /*@switchbreak@*/ break;
1203 if (cppReader_isPedantic (pfile))
1204 cppReader_pedwarn (pfile,
1205 message ("%s in preprocessing directive",
1207 ? cstring_makeLiteralTemp ("formfeed")
1208 : cstring_makeLiteralTemp ("vertical tab")));
1209 /*@switchbreak@*/ break;
1212 cppReader_forward (pfile, -1);
1214 scan_directive_token:
1215 cppReader_forward (pfile, -1);
1216 (void) cppGetToken (pfile);
1219 cppReader_putChar (pfile, c);
1222 cppReader_nullTerminate (pfile);
1226 cppReader_skipRestOfLine (cppReader *pfile)
1228 size_t old = cppReader_getWritten (pfile);
1229 copy_rest_of_line (pfile);
1230 cppReader_setWritten (pfile, old);
1233 /* Handle a possible # directive.
1234 '#' has already been read. */
1237 cppReader_handleDirective (cppReader *pfile)
1240 struct directive *kt = NULL;
1242 size_t after_ident = 0;
1243 char *ident, *line_end = NULL;
1244 size_t old_written = cppReader_getWritten (pfile);
1245 int nspaces = cppSkipHspace (pfile);
1247 c = cppReader_peekC (pfile);
1249 if (c >= '0' && c <= '9')
1251 /* Handle # followed by a line number. */
1252 if (cppReader_isPedantic (pfile))
1254 cppReader_pedwarnLit
1256 cstring_makeLiteralTemp ("`#' followed by integer"));
1259 (void) do_line (pfile, NULL);
1260 goto done_a_directive;
1264 /* Now find the directive name. */
1266 cppReader_putChar (pfile, '#');
1268 parse_name (pfile, cppReader_getC (pfile));
1270 llassert (pfile->token_buffer != NULL);
1271 ident = pfile->token_buffer + old_written + 1;
1273 ident_length = cppReader_getPWritten (pfile) - ident;
1275 if (ident_length == 0 && cppReader_peekC (pfile) == '\n')
1277 /* A line of just `#' becomes blank. */
1281 for (kt = directive_table; ; kt++)
1283 if (kt->length <= 0)
1285 return 0; /* goto not_a_directive; */
1288 if (kt->length == ident_length
1289 && (cstring_equalPrefix (kt->name, ident)))
1295 if (kt->command_reads_line)
1301 /* Nonzero means do not delete comments within the directive.
1302 #define needs this when -traditional. */
1303 bool comments = 1; /*cppReader_isTraditional (pfile) && kt->traditional_comments; */
1304 int save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
1305 CPPOPTIONS (pfile)->put_out_comments = comments;
1306 after_ident = cppReader_getWritten (pfile);
1307 copy_rest_of_line (pfile);
1308 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
1312 /* For #pragma and #define, we may want to pass through the directive.
1313 Other directives may create output, but we don't want the directive
1314 itself out, so we pop it now. For example #include may write a #line
1315 command (see comment in do_include), and conditionals may emit
1316 #failed ... #endfailed stuff. But note that popping the buffer
1317 means the parameters to kt->func may point after pfile->limit
1318 so these parameters are invalid as soon as something gets appended
1319 to the token_buffer. */
1321 line_end = cppReader_getPWritten (pfile);
1324 if (!kt->pass_thru && kt->type != T_DEFINE)
1326 cppReader_setWritten (pfile, old_written);
1329 llassert (pfile->token_buffer != NULL);
1331 /* was kt->pass_thru || */
1333 if (kt->type == T_DEFINE
1334 && cpp_shouldCheckMacro (pfile, pfile->token_buffer + old_written))
1336 char *p = pfile->token_buffer + old_written;
1339 ** Still need to record value for preprocessing, so
1340 ** #ifdef's, etc. using the value behave correctly.
1343 (void) do_defineAux (pfile, kt,
1344 pfile->token_buffer + after_ident,
1353 SKIP_WHITE_SPACE (p);
1355 llassert (*p == 'd');
1358 llassert (*p == 'e');
1361 llassert (*p == 'f');
1364 llassert (*p == 'i');
1367 llassert (*p == 'n');
1370 llassert (*p == 'e');
1373 ** This is way-bogus. We use the last char to record the number of
1374 ** spaces. Its too hard to get them back into the input stream.
1377 if (nspaces > 9) nspaces = 9;
1379 *p++ = '0' + nspaces;
1381 return 0; /* not_a_directive */
1383 else if (kt->pass_thru)
1385 /* Just leave the entire #define in the output stack. */
1386 return 0; /* not_a_directive */
1389 else if (kt->type == T_DEFINE
1390 && CPPOPTIONS (pfile)->dump_macros == DUMP_NAMES)
1392 char *p = pfile->token_buffer + old_written + 7; /* Skip "#define". */
1393 SKIP_WHITE_SPACE (p);
1395 while (is_idchar[(int) *p])
1401 cppReader_putChar (pfile, '\n');
1403 else if (kt->type == T_DEFINE)
1405 cppReader_setWritten (pfile, old_written);
1416 llassert (kt->func != NULL);
1417 (void) (kt->func) (pfile, kt, pfile->token_buffer + after_ident, line_end);
1422 /* Pass a directive through to the output file.
1423 BUF points to the contents of the directive, as a contiguous string.
1424 LIMIT points to the first character past the end of the directive.
1425 KEYWORD is the keyword-table entry for the directive. */
1428 pass_thru_directive (char *buf, char *limit,
1430 struct directive *keyword)
1432 int keyword_length = keyword->length;
1434 cppReader_reserve (pfile,
1435 size_fromInt (2 + keyword_length + (limit - buf)));
1436 cppReader_putCharQ (pfile, '#');
1437 /*@-observertrans@*/
1438 cppReader_putStrN (pfile, cstring_toCharsSafe (keyword->name),
1439 size_fromInt (keyword_length));
1440 /*:=observertrans@*/
1442 if (limit != buf && buf[0] != ' ')
1444 /* Was a bug, since reserve only used 1 + ... */
1445 cppReader_putCharQ (pfile, ' ');
1448 cppReader_putStrN (pfile, buf, size_fromInt (limit - buf));
1451 /* Read a replacement list for a macro with parameters.
1452 Build the DEFINITION structure.
1453 Reads characters of text starting at BUF until END.
1454 ARGLIST specifies the formal parameters to look for
1455 in the text of the definition; NARGS is the number of args
1456 in that list, or -1 for a macro name that wants no argument list.
1457 MACRONAME is the macro name itself (so we can avoid recursive expansion)
1458 and NAMELEN is its length in characters.
1460 Note that comments, backslash-newlines, and leading white space
1461 have already been deleted from the argument. */
1464 collect_expansion (cppReader *pfile, char *buf, char *limit,
1465 int nargs, /*@null@*/ struct arglist *arglist)
1468 char *p, *lastp, *exp_p;
1469 struct reflist *endpat = NULL;
1470 /* Pointer to first nonspace after last ## seen. */
1472 /* Pointer to first nonspace after last single-# seen. */
1473 char *stringify = 0;
1475 char expected_delimiter = '\0';
1478 /* Scan thru the replacement list, ignoring comments and quoted
1479 strings, picking up on the macro calls. It does a linear search
1480 thru the arg list on every potential symbol. Profiling might say
1481 that something smarter should happen. */
1486 /* Find the beginning of the trailing whitespace. */
1489 while (p < limit && is_space[(int) limit[-1]])
1494 /* Allocate space for the text in the macro definition.
1495 Leading and trailing whitespace chars need 2 bytes each.
1496 Each other input char may or may not need 1 byte,
1497 so this is an upper bound. The extra 5 are for invented
1498 leading and trailing newline-marker and final null. */
1499 maxsize = (sizeof (*defn) + (limit - p) + 5);
1501 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1510 defn = (DEFINITION *) dmalloc (maxsize);
1511 defn->noExpand = FALSE;
1513 defn->pattern = NULL;
1514 defn->nargs = nargs;
1515 defn->predefined = NULL;
1517 exp_p = defn->expansion = (char *) defn + sizeof (*defn);
1520 defn->rest_args = NULL;
1521 defn->args.argnames = NULL;
1527 /* Add one initial space escape-marker to prevent accidental
1528 token-pasting (often removed by macroexpand). */
1532 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1533 cppReader_errorLit (pfile,
1534 cstring_makeLiteralTemp ("`##' at start of macro definition"));
1538 /* Process the main body of the definition. */
1540 int skipped_arg = 0;
1541 register char c = *p++;
1545 if (!cppReader_isTraditional (pfile)) {
1549 if (expected_delimiter != '\0')
1551 if (c == expected_delimiter)
1552 expected_delimiter = '\0';
1556 expected_delimiter = c;
1558 /*@switchbreak@*/ break;
1561 if (p < limit && (expected_delimiter != '\0'))
1563 /* In a string, backslash goes through
1564 and makes next char ordinary. */
1567 /*@switchbreak@*/ break;
1570 /* An '@' in a string or character constant stands for itself,
1571 and does not need to be escaped. */
1572 if (expected_delimiter == '\0')
1577 /*@switchbreak@*/ break;
1580 /* # is ordinary inside a string. */
1581 if (expected_delimiter != '\0')
1583 /*@switchbreak@*/ break;
1586 if (p < limit && *p == '#') {
1587 /* ##: concatenate preceding and following tokens. */
1588 /* Take out the first #, discard preceding whitespace. */
1592 while (exp_p > lastp && is_hor_space[(int) exp_p[-1]])
1598 /* Skip the second #. */
1600 /* Discard following whitespace. */
1601 SKIP_WHITE_SPACE (p);
1605 cppReader_errorLit (pfile,
1606 cstring_makeLiteralTemp ("`##' at end of macro definition"));
1608 } else if (nargs >= 0) {
1609 /* Single #: stringify following argument ref.
1610 Don't leave the # in the expansion. */
1612 SKIP_WHITE_SPACE (p);
1613 if (p == limit || ! is_idstart[(int) *p]
1614 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '"')))
1615 cppReader_errorLit (pfile,
1616 cstring_makeLiteralTemp ("`#' operator is not followed by a macro argument name"));
1623 /*@switchbreak@*/ break;
1626 /* In -traditional mode, recognize arguments inside strings and
1627 and character constants, and ignore special properties of #.
1628 Arguments inside strings are considered "stringified", but no
1629 extra quote marks are supplied. */
1633 if (expected_delimiter != '\0') {
1634 if (c == expected_delimiter)
1635 expected_delimiter = '\0';
1637 expected_delimiter = c;
1638 /*@switchbreak@*/ break;
1641 /* Backslash quotes delimiters and itself, but not macro args. */
1642 if (expected_delimiter != '\0' && p < limit
1643 && (*p == expected_delimiter || *p == '\\')) {
1647 /*@switchbreak@*/ break;
1650 if (expected_delimiter != '\0') /* No comments inside strings. */
1651 /*@switchbreak@*/ break;
1653 /* If we find a comment that wasn't removed by cppReader_handleDirective,
1654 this must be -traditional. So replace the comment with
1658 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
1663 /*@switchbreak@*/ break;
1667 /* Handle the start of a symbol. */
1668 if (is_idchar[(int) c] && nargs > 0) {
1669 char *id_beg = p - 1;
1673 while (p != limit && is_idchar[(int) *p])
1678 id_len = p - id_beg;
1680 if (is_idstart[(int) c]
1681 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
1682 register struct arglist *arg;
1684 for (arg = arglist; arg != NULL; arg = arg->next) {
1685 struct reflist *tpat;
1687 if (arg->name[0] == c
1688 && arg->length == id_len
1689 && strncmp (arg->name, id_beg, size_fromInt (id_len)) == 0) {
1692 if (expected_delimiter && CPPOPTIONS (pfile)->warn_stringify) {
1693 if (cppReader_isTraditional (pfile)) {
1694 cppReader_warning (pfile,
1695 message ("macro argument `%x' is stringified.",
1696 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1698 cppReader_warning (pfile,
1699 message ("macro arg `%x' would be stringified with -traditional.",
1700 cstring_prefix (cstring_fromChars (arg->name), id_len)));
1703 /* If ANSI, don't actually substitute inside a string. */
1704 if (!cppReader_isTraditional (pfile) && expected_delimiter)
1705 /*@innerbreak@*/ break;
1706 /* make a pat node for this arg and append it to the end of
1708 tpat = (struct reflist *) dmalloc (sizeof (*tpat));
1710 tpat->raw_before = (concat == id_beg);
1711 tpat->raw_after = 0;
1712 tpat->rest_args = arg->rest_args;
1713 tpat->stringify = (cppReader_isTraditional (pfile)
1714 ? expected_delimiter != '\0'
1715 : stringify == id_beg);
1719 defn->pattern = tpat;
1723 endpat->next = tpat;
1725 } /*@=branchstate@*/ /* evs 2000 was =branchstate */
1729 tpat->argno = arg->argno;
1730 tpat->nchars = exp_p - lastp;
1734 SKIP_WHITE_SPACE (p1);
1736 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
1738 tpat->raw_after = 1;
1741 lastp = exp_p; /* place to start copying from next time */
1744 /*@innerbreak@*/ break;
1749 /* If this was not a macro arg, copy it into the expansion. */
1750 if (skipped_arg == 0) {
1751 register char *lim1 = p;
1759 if (stringify == id_beg)
1760 cppReader_errorLit (pfile,
1761 cstring_makeLiteralTemp ("`#' operator should be followed by a macro argument name"));
1766 if (!cppReader_isTraditional (pfile) && expected_delimiter == '\0')
1768 /* If ANSI, put in a "@ " marker to prevent token pasting.
1769 But not if "inside a string" (which in ANSI mode
1770 happens only for -D option). */
1777 defn->length = size_fromInt (exp_p - defn->expansion);
1779 /* Crash now if we overrun the allocated size. */
1780 if (defn->length + 1 > maxsize)
1782 llfatalbug (cstring_makeLiteral ("Maximum definition size exceeded."));
1789 * special extension string that can be added to the last macro argument to
1790 * allow it to absorb the "rest" of the arguments when expanded. Ex:
1791 * #define wow(a, b...) process (b, a, b)
1792 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
1793 * { wow (one, two); } -> { process (two, one, two); }
1794 * if this "rest_arg" is used with the concat token '##' and if it is not
1795 * supplied then the token attached to with ## will not be outputted. Ex:
1796 * #define wow (a, b...) process (b ## , a, ## b)
1797 * { wow (1, 2); } -> { process (2, 1, 2); }
1798 * { wow (one); } -> { process (one); {
1801 /*@-readonlytrans@*/
1802 static char rest_extension[] = "...";
1803 /*:=readonlytrans@*/
1806 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
1808 /* Create a DEFINITION node from a #define directive. Arguments are
1809 as for do_define. */
1811 static /*@null@*/ MACRODEF
1812 create_definition (char *buf, char *limit,
1813 cppReader *pfile, bool predefinition,
1816 char *bp; /* temp ptr into input buffer */
1817 char *symname; /* remember where symbol name starts */
1818 int sym_length; /* and how long it is */
1819 int rest_args = 0; /* really int! */
1822 cstring file = (CPPBUFFER (pfile) != NULL)
1823 ? CPPBUFFER (pfile)->nominal_fname : cstring_makeLiteralTemp ("");
1825 int arglengths = 0; /* Accumulate lengths of arg names
1826 plus number of args. */
1829 cppBuffer_lineAndColumn (CPPBUFFER (pfile), &line, &col);
1833 while (is_hor_space[(int) *bp])
1838 symname = bp; /* remember where it starts */
1840 sym_length = cppReader_checkMacroName (pfile, bp, cstring_makeLiteralTemp ("macro"));
1844 /* Lossage will occur if identifiers or control keywords are broken
1845 across lines using backslash. This is not the right place to take
1849 struct arglist *arg_ptrs = NULL;
1852 bp++; /* skip '(' */
1853 SKIP_WHITE_SPACE (bp);
1855 /* Loop over macro argument names. */
1858 struct arglist *temp = (struct arglist *) dmalloc (sizeof (*temp));
1860 temp->next = arg_ptrs;
1861 temp->argno = argno++;
1862 temp->rest_args = 0;
1868 cppReader_pedwarn (pfile,
1869 message ("another parameter follows `%s'",
1870 cstring_fromChars (rest_extension)));
1873 if (!is_idstart[(int) *bp])
1875 cppReader_pedwarnLit (pfile,
1876 cstring_makeLiteralTemp ("invalid character in macro parameter name"));
1879 /* Find the end of the arg name. */
1880 while (is_idchar[(int) *bp])
1883 /* do we have a "special" rest-args extension here? */
1884 if (limit - bp > size_toInt (REST_EXTENSION_LENGTH)
1885 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
1888 temp->rest_args = 1;
1889 /*@innerbreak@*/ break;
1893 temp->length = bp - temp->name;
1897 bp += REST_EXTENSION_LENGTH;
1900 arglengths += temp->length + 2;
1901 SKIP_WHITE_SPACE (bp);
1903 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
1904 cppReader_errorLit (pfile,
1905 cstring_makeLiteralTemp ("Parameter list for #define is not parseable"));
1911 SKIP_WHITE_SPACE (bp);
1914 cppReader_errorLit (pfile,
1915 cstring_makeLiteralTemp ("unterminated parameter list in `#define'"));
1919 struct arglist *otemp;
1921 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
1923 if (temp->length == otemp->length &&
1924 strncmp (temp->name, otemp->name, size_fromInt (temp->length)) == 0) {
1925 cstring name = cstring_copyLength (temp->name, temp->length);
1926 cppReader_error (pfile,
1927 message ("duplicate argument name `%x' in `#define'", name));
1934 ++bp; /* skip paren */
1935 SKIP_WHITE_SPACE (bp);
1936 /* now everything from bp before limit is the definition. */
1937 defn = collect_expansion (pfile, bp, limit, argno, arg_ptrs);
1938 defn->rest_args = rest_args;
1940 /* Now set defn->args.argnames to the result of concatenating
1941 the argument names in reverse order
1942 with comma-space between them. */
1943 defn->args.argnames = (char *) dmalloc (size_fromInt (arglengths + 1));
1946 struct arglist *temp;
1948 for (temp = arg_ptrs; temp != NULL; temp = temp->next) {
1949 memcpy (&defn->args.argnames[i], temp->name, size_fromInt (temp->length));
1951 if (temp->next != 0) {
1952 defn->args.argnames[i++] = ',';
1953 defn->args.argnames[i++] = ' ';
1957 defn->args.argnames[i] = '\0';
1962 /* Simple expansion or empty definition. */
1966 if (is_hor_space[(int) *bp]) {
1968 SKIP_WHITE_SPACE (bp);
1971 case '!': case '"': case '#': case '%': case '&': case '\'':
1972 case ')': case '*': case '+': case ',': case '-': case '.':
1973 case '/': case ':': case ';': case '<': case '=': case '>':
1974 case '?': case '[': case '\\': case ']': case '^': case '{':
1975 case '|': case '}': case '~':
1976 cppReader_warning (pfile,
1977 message ("Missing white space after #define %x",
1978 cstring_prefix (cstring_fromChars (symname),
1983 cppReader_pedwarn (pfile,
1984 message ("Missing white space after #define %x",
1985 cstring_prefix (cstring_fromChars (symname),
1991 /* now everything from bp before limit is the definition. */
1992 defn = collect_expansion (pfile, bp, limit, -1, NULL);
1993 defn->args.argnames = mstring_createEmpty ();
1996 defn->noExpand = noExpand;
1997 DPRINTF (("No expand: %d", noExpand));
2001 /* not: llassert (cstring_isUndefined (defn->file)); */
2004 /* OP is null if this is a predefinition */
2005 defn->predefined = predefinition;
2007 mdef.symnam = symname;
2008 mdef.symlen = sym_length;
2018 /* Check a purported macro name SYMNAME, and yield its length.
2019 USAGE is the kind of name this is intended for. */
2021 int cppReader_checkMacroName (cppReader *pfile,
2028 for (p = symname; is_idchar[(int) *p]; p++)
2033 sym_length = size_fromInt (p - symname);
2036 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
2037 cppReader_error (pfile, message ("invalid %s name", usage));
2038 else if (!is_idstart[(int) *symname])
2040 char *msg = (char *) dmalloc (sym_length + 1);
2041 memcpy (msg, symname, sym_length);
2042 msg[sym_length] = '\0';
2043 cppReader_error (pfile, message ("invalid %s name `%s'", usage,
2044 cstring_fromChars (msg)));
2049 if ((strncmp (symname, "defined", 7) == 0) && sym_length == 7)
2051 cppReader_error (pfile, message ("invalid %s name `defined'", usage));
2055 return size_toInt (sym_length);
2058 /* Return zero if two DEFINITIONs are isomorphic. */
2061 compare_defs (DEFINITION *d1, DEFINITION *d2)
2063 register struct reflist *a1, *a2;
2064 register char *p1 = d1->expansion;
2065 register char *p2 = d2->expansion;
2068 if (d1->nargs != d2->nargs)
2073 llassert (d1->args.argnames != NULL);
2074 llassert (d2->args.argnames != NULL);
2076 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames) != 0)
2081 for (a1 = d1->pattern, a2 = d2->pattern;
2082 (a1 != NULL) && (a2 != NULL);
2083 a1 = a1->next, a2 = a2->next) {
2084 if (!((a1->nchars == a2->nchars
2085 && (strncmp (p1, p2, size_fromInt (a1->nchars)) == 0))
2086 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
2087 || a1->argno != a2->argno
2088 || a1->stringify != a2->stringify
2089 || a1->raw_before != a2->raw_before
2090 || a1->raw_after != a2->raw_after)
2099 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
2100 p2, d2->length - (p2 - d2->expansion), 1))
2106 /* Return TRUE if two parts of two macro definitions are effectively different.
2107 One of the parts starts at BEG1 and has LEN1 chars;
2108 the other has LEN2 chars at BEG2.
2109 Any sequence of whitespace matches any other sequence of whitespace.
2110 FIRST means these parts are the first of a macro definition;
2111 so ignore leading whitespace entirely.
2112 LAST means these parts are the last of a macro definition;
2113 so ignore trailing whitespace entirely. */
2116 comp_def_part (bool first, char *beg1, int len1, char *beg2, int len2, bool last)
2118 char *end1 = beg1 + len1;
2119 char *end2 = beg2 + len2;
2122 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2123 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2126 while (beg1 != end1 && is_space[(int) end1[-1]]) { end1--; }
2127 while (beg2 != end2 && is_space[(int) end2[-1]]) { end2--; }
2129 while (beg1 != end1 && beg2 != end2) {
2130 if (is_space[(int) *beg1] && is_space[(int) *beg2]) {
2131 while (beg1 != end1 && is_space[(int) *beg1]) { beg1++; }
2132 while (beg2 != end2 && is_space[(int) *beg2]) { beg2++; }
2133 } else if (*beg1 == *beg2) {
2137 return (beg1 != end1) || (beg2 != end2);
2140 /* Process a #define command.
2141 BUF points to the contents of the #define command, as a contiguous string.
2142 LIMIT points to the first character past the end of the definition.
2143 KEYWORD is the keyword-table entry for #define,
2144 or NULL for a "predefined" macro. */
2147 do_defineAux (cppReader *pfile, struct directive *keyword,
2148 char *buf, char *limit, bool noExpand)
2154 DPRINTF (("Define aux: %d", noExpand));
2156 mdef = create_definition (buf, limit, pfile, keyword == NULL, noExpand);
2161 hashcode = hashf (mdef.symnam, mdef.symlen, CPP_HASHSIZE);
2163 DPRINTF (("Macro: %s / %s",
2164 cstring_copyLength (mdef.symnam, mdef.symlen),
2165 bool_unparse (noExpand)));
2167 if ((hp = cppReader_lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL)
2171 /* Redefining a precompiled key is ok. */
2172 if (hp->type == T_PCSTRING)
2174 /* Redefining a macro is ok if the definitions are the same. */
2175 else if (hp->type == T_MACRO)
2176 ok = !compare_defs (mdef.defn, hp->value.defn);
2177 /* Redefining a constant is ok with -D. */
2178 else if (hp->type == T_CONST)
2179 ok = !CPPOPTIONS (pfile)->done_initializing;
2184 /* Print the warning if it's not ok. */
2188 ** If we are passing through #define and #undef directives, do
2189 ** that for this re-definition now.
2192 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2194 /* llassert (keyword != NULL); */
2195 pass_thru_directive (buf, limit, pfile, keyword);
2198 cpp_setLocation (pfile);
2200 if (hp->type == T_MACRO)
2202 if (hp->value.defn->noExpand)
2204 ; /* error will be reported checking macros */
2210 message ("Macro %q already defined",
2211 cstring_copyLength (mdef.symnam, mdef.symlen)),
2212 message ("%q: Previous definition of %q",
2213 fileloc_unparseRaw (hp->value.defn->file,
2214 (int) hp->value.defn->line),
2215 cstring_copyLength (mdef.symnam, mdef.symlen)));
2220 genppllerror (FLG_MACROREDEF,
2221 message ("Macro %q already defined",
2222 cstring_copyLength (mdef.symnam,
2228 /* Replace the old definition. */
2230 hp->value.defn = mdef.defn;
2235 ** If we are passing through #define and #undef directives, do
2236 ** that for this new definition now.
2241 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
2243 pass_thru_directive (buf, limit, pfile, keyword);
2246 DPRINTF (("Define macro: %s / %d",
2247 mdef.symnam, mdef.defn->noExpand));
2249 hn = cppReader_installMacro (mdef.symnam, mdef.symlen, mdef.defn, hashcode);
2251 } /*@=branchstate@*/
2261 do_define (cppReader *pfile, struct directive *keyword,
2262 char *buf, char *limit)
2264 DPRINTF (("Regular do define"));
2265 return do_defineAux (pfile, keyword, buf, limit, FALSE);
2268 /* This structure represents one parsed argument in a macro call.
2269 `raw' points to the argument text as written (`raw_length' is its length).
2270 `expanded' points to the argument's macro-expansion
2271 (its length is `expand_length').
2272 `stringified_length' is the length the argument would have
2274 `use_count' is the number of times this macro arg is substituted
2275 into the macro. If the actual use count exceeds 10,
2276 the value stored is 10. */
2278 /* raw and expanded are relative to ARG_BASE */
2280 #define ARG_BASE ((pfile)->token_buffer)
2283 /* Strings relative to pfile->token_buffer */
2289 int stringified_length;
2294 /* Allocate a new cppBuffer for PFILE, and push it on the input buffer stack.
2295 If BUFFER != NULL, then use the LENGTH characters in BUFFER
2296 as the new input buffer.
2297 Return the new buffer, or NULL on failure. */
2299 /*@null@*/ /*@exposed@*/ cppBuffer *
2300 cppReader_pushBuffer (cppReader *pfile, char *buffer, size_t length)
2302 cppBuffer *buf = cppReader_getBuffer (pfile);
2304 if (buf == pfile->buffer_stack)
2306 cppReader_fatalError
2308 message ("%s: macro or `#include' recursion too deep",
2309 (buf->fname != NULL)
2311 : cstring_makeLiteral ("<no name>")));
2312 sfreeEventually (buffer);
2316 llassert (buf != NULL);
2319 memset ((char *) buf, 0, sizeof (*buf));
2320 CPPBUFFER (pfile) = buf;
2322 buf->if_stack = pfile->if_stack;
2323 buf->cleanup = cppReader_nullCleanup;
2324 buf->underflow = cppReader_nullUnderflow;
2326 buf->cur = buf->buf;
2330 buf->alimit = buf->rlimit = buffer + length;
2334 buf->alimit = buf->rlimit = NULL;
2341 cppReader_popBuffer (cppReader *pfile)
2343 cppBuffer *buf = CPPBUFFER (pfile);
2345 llassert (buf != NULL);
2347 (void) (*buf->cleanup) (buf, pfile);
2348 return ++CPPBUFFER (pfile);
2351 /* Scan until CPPBUFFER (PFILE) is exhausted into PFILE->token_buffer.
2352 Pop the buffer when done. */
2355 cppReader_scanBuffer (cppReader *pfile)
2357 cppBuffer *buffer = CPPBUFFER (pfile);
2360 enum cpp_token token;
2362 token = cppGetToken (pfile);
2364 if (token == CPP_EOF) /* Should not happen ... */
2369 if (token == CPP_POP && CPPBUFFER (pfile) == buffer)
2371 (void) cppReader_popBuffer (pfile);
2378 * Rescan a string (which may have escape marks) into pfile's buffer.
2379 * Place the result in pfile->token_buffer.
2381 * The input is copied before it is scanned, so it is safe to pass
2382 * it something from the token_buffer that will get overwritten
2383 * (because it follows cppReader_getWritten). This is used by do_include.
2387 cpp_expand_to_buffer (cppReader *pfile, char *buf, size_t length)
2389 register cppBuffer *ip;
2390 char *limit = buf + length;
2391 char *buf1, *p1, *p2;
2396 /* Set up the input on the input stack. */
2398 buf1 = (char *) dmalloc (length + 1);
2408 buf1[length] = '\0';
2410 ip = cppReader_pushBuffer (pfile, buf1, length);
2415 ip->has_escapes = TRUE;
2417 /* Scan the input, create the output. */
2418 cppReader_scanBuffer (pfile);
2420 cppReader_nullTerminate (pfile);
2424 adjust_position (char *buf, char *limit, int *linep, int *colp)
2430 (*linep)++, (*colp) = 1;
2436 /* Move line_base forward, updating lineno and colno. */
2439 update_position (cppBuffer *pbuf)
2442 char *new_pos = pbuf->cur;
2443 register struct parse_marker *mark;
2445 llassert (pbuf->buf != NULL);
2446 old_pos = pbuf->buf + pbuf->line_base;
2448 for (mark = pbuf->marks; mark != NULL; mark = mark->next)
2450 if (pbuf->buf + mark->position < new_pos)
2451 new_pos = pbuf->buf + mark->position;
2453 pbuf->line_base += new_pos - old_pos;
2455 llassert (old_pos != NULL);
2456 llassert (new_pos != NULL);
2458 adjust_position (old_pos, new_pos, &pbuf->lineno, &pbuf->colno);
2462 cppBuffer_lineAndColumn (/*@null@*/ cppBuffer *pbuf, /*@out@*/ int *linep,
2463 /*@null@*/ /*@out@*/ int *colp)
2471 } /*@=branchstate@*/
2475 *linep = pbuf->lineno;
2476 *colp = pbuf->colno;
2478 llassert (pbuf->buf != NULL);
2479 llassert (pbuf->cur != NULL);
2481 adjust_position (pbuf->buf + pbuf->line_base, pbuf->cur, linep, colp);
2490 /* Return the cppBuffer that corresponds to a file (not a macro). */
2492 /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_fileBuffer (cppReader *pfile)
2494 cppBuffer *ip = cppReader_getBuffer (pfile);
2497 ip != NULL && ip != cppReader_nullBuffer (pfile);
2498 ip = cppBuffer_prevBuffer (ip))
2500 if (ip->fname != NULL)
2510 count_newlines (char *buf, char *limit)
2512 register long count = 0;
2524 * write out a #line command, for instance, after an #include file.
2525 * If CONDITIONAL is nonzero, we can omit the #line if it would
2526 * appear to be a no-op, and we can output a few newlines instead
2527 * if we want to increase the line number by a small amount.
2528 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
2532 output_line_command (cppReader *pfile, bool conditional,
2533 enum file_change_code file_change)
2536 cppBuffer *ip = CPPBUFFER (pfile);
2539 llassert (ip != NULL);
2541 if (ip->fname == NULL)
2544 update_position (ip);
2546 if (CPPOPTIONS (pfile)->no_line_commands
2547 || CPPOPTIONS (pfile)->no_output)
2550 buf = CPPBUFFER (pfile);
2552 llassert (buf != NULL);
2557 llassert (ip->cur != NULL);
2559 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
2561 if (CPPOPTIONS (pfile)->no_line_commands)
2565 if (line == pfile->lineno)
2568 /* If the inherited line number is a little too small,
2569 output some newlines instead of a #line command. */
2571 if (line > pfile->lineno && line < pfile->lineno + 8)
2573 cppReader_reserve (pfile, 20);
2574 while (line > pfile->lineno)
2576 cppReader_putCharQ (pfile, '\n');
2584 cppReader_reserve (pfile,
2585 size_fromInt (4 * cstring_length (ip->nominal_fname) + 50));
2588 #ifdef OUTPUT_LINE_COMMANDS
2589 static char sharp_line[] = "#line ";
2591 static char sharp_line[] = "# ";
2593 cppReader_putStrN (pfile, sharp_line, sizeof(sharp_line)-1);
2596 sprintf (cppReader_getPWritten (pfile), "%d ", line);
2597 cppReader_adjustWritten (pfile, strlen (cppReader_getPWritten (pfile)));
2599 quote_string (pfile, cstring_toCharsSafe (ip->nominal_fname));
2601 if (file_change != same_file) {
2602 cppReader_putCharQ (pfile, ' ');
2603 cppReader_putCharQ (pfile, file_change == enter_file ? '1' : '2');
2605 /* Tell cc1 if following text comes from a system header file. */
2606 if (ip->system_header_p != '\0') {
2607 cppReader_putCharQ (pfile, ' ');
2608 cppReader_putCharQ (pfile, '3');
2610 #ifndef NO_IMPLICIT_EXTERN_C
2611 /* Tell cc1plus if following text should be treated as C. */
2612 if (ip->system_header_p == (char) 2 && CPPOPTIONS (pfile)->cplusplus) {
2613 cppReader_putCharQ (pfile, ' ');
2614 cppReader_putCharQ (pfile, '4');
2617 cppReader_putCharQ (pfile, '\n');
2618 pfile->lineno = line;
2623 * Parse a macro argument and append the info on PFILE's token_buffer.
2624 * REST_ARGS means to absorb the rest of the args.
2625 * Return nonzero to indicate a syntax error.
2628 static enum cpp_token
2629 macarg (cppReader *pfile, int rest_args)
2632 enum cpp_token token;
2633 char save_put_out_comments = CPPOPTIONS (pfile)->put_out_comments;
2634 bool oldexpand = pfile->no_macro_expand;
2635 CPPOPTIONS (pfile)->put_out_comments = 1;
2637 /* Try to parse as much of the argument as exists at this
2638 input stack level. */
2640 pfile->no_macro_expand = TRUE;
2644 token = cppGetToken (pfile);
2651 /* If we've hit end of file, it's an error (reported by caller).
2652 Ditto if it's the end of cpp_expand_to_buffer text.
2653 If we've hit end of macro, just continue. */
2654 if (!cppBuffer_isMacro (CPPBUFFER (pfile)))
2656 /*@switchbreak@*/ break;
2659 /*@switchbreak@*/ break;
2663 /*@switchbreak@*/ break;
2665 /* if we've returned to lowest level and
2666 we aren't absorbing all args */
2667 if (paren == 0 && rest_args == 0)
2669 /*@switchbreak@*/ break;
2671 /* Remove ',' or ')' from argument buffer. */
2672 cppReader_adjustWritten (pfile, -1);
2680 CPPOPTIONS (pfile)->put_out_comments = save_put_out_comments;
2681 pfile->no_macro_expand = oldexpand;
2687 /* Turn newlines to spaces in the string of length LENGTH at START,
2688 except inside of string constants.
2689 The string is copied into itself with its beginning staying fixed. */
2692 change_newlines (char *start, int length)
2696 register char *limit;
2700 limit = start + length;
2703 while (ibp < limit) {
2704 *obp++ = c = *ibp++;
2709 /* Notice and skip strings, so that we don't delete newlines in them. */
2712 while (ibp < limit) {
2713 *obp++ = c = *ibp++;
2715 /*@innerbreak@*/ break;
2716 if (c == '\n' && quotec == '\'')
2717 /*@innerbreak@*/ break;
2720 /*@switchbreak@*/ break;
2727 static /*@observer@*/ struct tm *
2728 timestamp (/*@returned@*/ cppReader *pfile)
2730 if (pfile->timebuf == NULL)
2732 time_t t = time ((time_t *) 0);
2733 pfile->timebuf = localtime (&t);
2736 llassert (pfile->timebuf != NULL);
2738 return pfile->timebuf;
2741 static ob_mstring monthnames[] = {
2742 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2743 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
2747 * expand things like __FILE__. Place the expansion into the output
2748 * buffer *without* rescanning.
2752 special_symbol (HASHNODE *hp, cppReader *pfile)
2754 cstring buf = cstring_undefined;
2760 int paren = 0; /* For special `defined' keyword */
2762 for (ip = cppReader_getBuffer (pfile); ip != NULL; ip = cppBuffer_prevBuffer (ip))
2764 if (ip == cppReader_nullBuffer (pfile))
2766 cppReader_errorLit (pfile,
2767 cstring_makeLiteralTemp ("cccp error: not in any file?!"));
2768 return; /* the show must go on */
2771 if (ip != NULL && ip->fname != NULL)
2783 if (hp->type == T_BASE_FILE)
2785 while (cppBuffer_prevBuffer (ip) != cppReader_nullBuffer (pfile))
2787 ip = cppBuffer_prevBuffer (ip);
2791 llassert (ip != NULL);
2792 string = cstring_toCharsSafe (ip->nominal_fname);
2799 cppReader_reserve (pfile, 3 + 4 * strlen (string));
2800 quote_string (pfile, string);
2804 case T_INCLUDE_LEVEL:
2806 ip = cppReader_getBuffer (pfile);
2808 for (; ip != cppReader_nullBuffer (pfile) && ip != NULL;
2809 ip = cppBuffer_prevBuffer (ip))
2811 if (ip != NULL && ip->fname != NULL)
2817 buf = message ("%d", true_indepth - 1);
2821 buf = message ("\"%s\"", cstring_makeLiteralTemp (CPP_VERSION));
2824 #ifndef NO_BUILTIN_SIZE_TYPE
2826 buf = cstring_makeLiteral (SIZE_TYPE);
2830 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2831 case T_PTRDIFF_TYPE:
2832 buf = cstring_makeLiteral (PTRDIFF_TYPE);
2837 buf = cstring_makeLiteral (cppReader_wcharType (pfile));
2840 case T_USER_LABEL_PREFIX_TYPE:
2841 buf = cstring_makeLiteral (USER_LABEL_PREFIX);
2844 case T_REGISTER_PREFIX_TYPE:
2845 buf = cstring_makeLiteral (REGISTER_PREFIX);
2849 buf = message ("%d", hp->value.ival);
2856 int line = ip->lineno;
2857 int col = ip->colno;
2859 llassert (ip->cur != NULL);
2860 adjust_position (cppLineBase (ip), ip->cur, &line, &col);
2862 buf = message ("%d", (int) line);
2874 char *sbuf = (char *) dmalloc (20);
2875 timebuf = timestamp (pfile);
2876 if (hp->type == T_DATE)
2878 sprintf (sbuf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
2879 timebuf->tm_mday, timebuf->tm_year + 1900);
2883 sprintf (sbuf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
2887 buf = cstring_fromCharsNew (sbuf);
2892 case T_SPEC_DEFINED:
2893 buf = cstring_makeLiteral (" 0 "); /* Assume symbol is not defined */
2894 ip = cppReader_getBuffer (pfile);
2896 llassert (ip->cur != NULL);
2897 SKIP_WHITE_SPACE (ip->cur);
2899 if (*ip->cur == '(')
2902 ip->cur++; /* Skip over the paren */
2903 SKIP_WHITE_SPACE (ip->cur);
2906 if (!is_idstart[(int) *ip->cur])
2908 if (ip->cur[0] == 'L' && (ip->cur[1] == '\'' || ip->cur[1] == '"'))
2911 if ((hp = cppReader_lookup (ip->cur, -1, -1)) != 0)
2914 buf = cstring_makeLiteral (" 1 ");
2917 while (is_idchar[(int) *ip->cur])
2922 SKIP_WHITE_SPACE (ip->cur);
2926 if (*ip->cur != ')')
2934 cppReader_errorLit (pfile,
2935 cstring_makeLiteralTemp ("`defined' without an identifier"));
2939 cpp_setLocation (pfile);
2940 llfatalerror (message ("Pre-processing error: invalid special hash type"));
2943 len = size_fromInt (cstring_length (buf));
2945 cppReader_reserve (pfile, len + 1);
2946 cppReader_putStrN (pfile, cstring_toCharsSafe (buf), len);
2947 cppReader_nullTerminateQ (pfile);
2953 /* Write out a #define command for the special named MACRO_NAME
2954 to PFILE's token_buffer. */
2957 dump_special_to_buffer (cppReader *pfile, char *macro_name)
2959 static char define_directive[] = "#define ";
2960 size_t macro_name_length = strlen (macro_name);
2961 output_line_command (pfile, 0, same_file);
2962 cppReader_reserve (pfile, sizeof(define_directive) + macro_name_length);
2963 cppReader_putStrN (pfile, define_directive, sizeof(define_directive)-1);
2964 cppReader_putStrN (pfile, macro_name, macro_name_length);
2965 cppReader_putCharQ (pfile, ' ');
2966 cpp_expand_to_buffer (pfile, macro_name, macro_name_length);
2967 cppReader_putChar (pfile, '\n');
2970 /* Initialize the built-in macros. */
2973 cppReader_installBuiltin (/*@observer@*/ char *name, ctype ctyp,
2974 int len, enum node_type type,
2975 int ivalue, /*@null@*/ /*@only@*/ char *value,
2978 cstring sname = cstring_fromCharsNew (name);
2980 llassert (usymtab_inGlobalScope ());
2983 ** Be careful here: this is done before the ctype table has
2984 ** been initialized.
2987 if (!usymtab_exists (sname))
2989 uentry ue = uentry_makeConstant (sname, ctyp, fileloc_createBuiltin ());
2991 if (ctype_equal (ctyp, ctype_string))
2993 qualList ql = qualList_new ();
2994 ql = qualList_add (ql, qual_createObserver ());
2995 uentry_reflectQualifiers (ue, ql);
2999 usymtab_addGlobalEntry (ue);
3006 (void) cppReader_install (name, len, type, ivalue, value, hash);
3007 cstring_free (sname);
3011 cppReader_installBuiltinType (/*@observer@*/ char *name, ctype ctyp,
3012 int len, enum node_type type,
3014 /*@only@*/ /*@null@*/ char *value, int hash)
3016 cstring sname = cstring_fromChars (name);
3017 /* evs 2000 07 10 - removed a memory leak, detected by lclint */
3019 llassert (usymtab_inGlobalScope ());
3021 if (!usymtab_existsTypeEither (sname))
3023 uentry ue = uentry_makeDatatype (sname, ctyp,
3025 fileloc_createBuiltin ());
3026 llassert (!usymtab_existsEither (sname));
3027 usymtab_addGlobalEntry (ue);
3030 (void) cppReader_install (name, len, type, ivalue, value, hash);
3034 initialize_builtins (cppReader *pfile)
3036 cppReader_installBuiltin ("__LINE__", ctype_int, -1, T_SPECLINE, 0, NULL, -1);
3037 cppReader_installBuiltin ("__DATE__", ctype_string, -1, T_DATE, 0, NULL, -1);
3038 cppReader_installBuiltin ("__FILE__", ctype_string, -1, T_FILE, 0, NULL, -1);
3039 cppReader_installBuiltin ("__BASE_FILE__", ctype_string, -1, T_BASE_FILE, 0, NULL, -1);
3040 cppReader_installBuiltin ("__INCLUDE_LEVEL__", ctype_int, -1, T_INCLUDE_LEVEL, 0, NULL, -1);
3041 cppReader_installBuiltin ("__VERSION__", ctype_string, -1, T_VERSION, 0, NULL, -1);
3042 #ifndef NO_BUILTIN_SIZE_TYPE
3043 cppReader_installBuiltinType ("__SIZE_TYPE__", ctype_anyintegral, -1, T_SIZE_TYPE, 0, NULL, -1);
3045 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3046 cppReader_installBuiltinType ("__PTRDIFF_TYPE__", ctype_anyintegral, -1, T_PTRDIFF_TYPE, 0, NULL, -1);
3048 cppReader_installBuiltinType ("__WCHAR_TYPE__", ctype_anyintegral, -1, T_WCHAR_TYPE, 0, NULL, -1);
3049 cppReader_installBuiltin ("__USER_LABEL_PREFIX__", ctype_string, -1, T_USER_LABEL_PREFIX_TYPE, 0, NULL, -1);
3050 cppReader_installBuiltin ("__REGISTER_PREFIX__", ctype_string, -1, T_REGISTER_PREFIX_TYPE, 0, NULL, -1);
3051 cppReader_installBuiltin ("__TIME__", ctype_string, -1, T_TIME, 0, NULL, -1);
3054 ** No, don't define __STDC__
3057 if (!cppReader_isTraditional (pfile))
3059 cppReader_installBuiltin ("__STDC__", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3066 cppReader_installBuiltin ("_WIN32", ctype_int, -1, T_CONST, STDC_VALUE, NULL, -1);
3070 ** This is supplied using a -D by the compiler driver
3071 ** so that it is present only when truly compiling with GNU C.
3074 /* cppReader_install ("__GNUC__", -1, T_CONST, 2, 0, -1); */
3076 cppReader_installBuiltin ("__LCLINT__", ctype_int, -1, T_CONST, 2, NULL, -1);
3078 if (CPPOPTIONS (pfile)->debug_output)
3080 dump_special_to_buffer (pfile, "__BASE_FILE__");
3081 dump_special_to_buffer (pfile, "__VERSION__");
3082 #ifndef NO_BUILTIN_SIZE_TYPE
3083 dump_special_to_buffer (pfile, "__SIZE_TYPE__");
3085 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3086 dump_special_to_buffer (pfile, "__PTRDIFF_TYPE__");
3088 dump_special_to_buffer (pfile, "__WCHAR_TYPE__");
3089 dump_special_to_buffer (pfile, "__DATE__");
3090 dump_special_to_buffer (pfile, "__TIME__");
3091 if (!cppReader_isTraditional (pfile))
3092 dump_special_to_buffer (pfile, "__STDC__");
3097 /* Return 1 iff a token ending in C1 followed directly by a token C2
3098 could cause mis-tokenization. */
3101 unsafe_chars (char c1, char c2)
3106 if (c2 == c1 || c2 == '=')
3110 case '0': case '1': case '2': case '3': case '4':
3111 case '5': case '6': case '7': case '8': case '9':
3112 case 'e': case 'E': case 'p': case 'P':
3113 if (c2 == '-' || c2 == '+')
3114 return 1; /* could extend a pre-processing number */
3117 if (c2 == '\'' || c2 == '\"')
3118 return 1; /* Could turn into L"xxx" or L'xxx'. */
3122 case 'a': case 'b': case 'c': case 'd': case 'f':
3123 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3124 case 'm': case 'n': case 'o': case 'q': case 'r':
3125 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3127 case 'A': case 'B': case 'C': case 'D': case 'F':
3128 case 'G': case 'H': case 'I': case 'J': case 'K':
3129 case 'M': case 'N': case 'O': case 'Q': case 'R':
3130 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3132 /* We're in the middle of either a name or a pre-processing number. */
3133 return (is_idchar[(int) c2] || c2 == '.');
3134 case '<': case '>': case '!': case '%': case '#': case ':':
3135 case '^': case '&': case '|': case '*': case '/': case '=':
3136 return (c2 == c1 || c2 == '=');
3141 /* Expand a macro call.
3142 HP points to the symbol that is the macro being called.
3143 Put the result of expansion onto the input stack
3144 so that subsequent input by our caller will use it.
3146 If macro wants arguments, caller has already verified that
3147 an argument list follows; arguments come from the input stack. */
3150 macroexpand (cppReader *pfile, /*@dependent@*/ HASHNODE *hp)
3153 DEFINITION *defn = hp->value.defn;
3159 size_t old_written = cppReader_getWritten (pfile);
3163 struct argdata *args = NULL;
3165 pfile->output_escapes++;
3167 cppBuffer_lineAndColumn (cppReader_fileBuffer (pfile), &start_line, &start_column);
3169 nargs = defn->nargs;
3173 enum cpp_token token = CPP_EOF;
3175 args = (struct argdata *) dmalloc ((nargs + 1) * sizeof (*args));
3177 for (i = 0; i < nargs; i++)
3179 args[i].expanded = 0;
3181 args[i].raw_length = 0;
3182 args[i].expand_length = args[i].stringified_length = -1;
3183 args[i].use_count = 0;
3187 ** Parse all the macro args that are supplied. I counts them.
3188 ** The first NARGS args are stored in ARGS.
3189 ** The rest are discarded. If rest_args is set then we assume
3190 ** macarg absorbed the rest of the args.
3196 cppReader_forward (pfile, 1); /* Discard the open-parenthesis before the first arg. */
3204 if (i < nargs || (nargs == 0 && i == 0))
3206 /* if we are working on last arg which absorbs rest of args... */
3207 if (i == nargs - 1 && defn->rest_args)
3212 args[i].raw = size_toLong (cppReader_getWritten (pfile));
3213 token = macarg (pfile, rest_args);
3214 args[i].raw_length = cppReader_getWritten (pfile) - args[i].raw;
3215 args[i].newlines = FALSE; /* FIXME */
3219 token = macarg (pfile, 0);
3222 if (token == CPP_EOF || token == CPP_POP)
3224 cppReader_errorWithLine (pfile, start_line, start_column,
3225 cstring_fromCharsNew ("unterminated macro call"));
3230 } while (token == CPP_COMMA);
3232 /* If we got one arg but it was just whitespace, call that 0 args. */
3240 bp = ARG_BASE + args[0].raw;
3241 lim = bp + args[0].raw_length;
3243 /* cpp.texi says for foo ( ) we provide one argument.
3244 However, if foo wants just 0 arguments, treat this as 0. */
3248 while (bp != lim && is_space[(int) *bp])
3258 /* Don't output an error message if we have already output one for
3259 a parse error above. */
3262 if (nargs == 0 && i > 0)
3264 cppReader_error (pfile,
3265 message ("arguments given to macro `%s'", hp->name));
3269 /* traditional C allows foo() if foo wants one argument. */
3270 if (nargs == 1 && i == 0 && cppReader_isTraditional (pfile))
3274 /* the rest args token is allowed to absorb 0 tokens */
3275 else if (i == nargs - 1 && defn->rest_args)
3278 cppReader_error (pfile,
3279 message ("macro `%s' used without args", hp->name));
3281 cppReader_error (pfile,
3282 message ("macro `%s' used with just one arg", hp->name));
3285 cppReader_error (pfile,
3286 message ("macro `%s' used with only %d args",
3292 cppReader_error (pfile,
3293 message ("macro `%s' used with too many (%d) args", hp->name, i));
3301 /* If macro wants zero args, we parsed the arglist for checking only.
3302 Read directly from the macro definition. */
3306 xbuf = defn->expansion;
3307 xbuf_len = defn->length;
3311 char *exp = defn->expansion;
3312 int offset; /* offset in expansion,
3313 copied a piece at a time */
3314 size_t totlen; /* total amount of exp buffer filled so far */
3316 register struct reflist *ap, *last_ap;
3318 /* Macro really takes args. Compute the expansion of this call. */
3320 /* Compute length in characters of the macro's expansion.
3321 Also count number of times each arg is used. */
3322 xbuf_len = defn->length;
3324 llassert (args != NULL);
3326 for (ap = defn->pattern; ap != NULL; ap = ap->next)
3330 struct argdata *arg = &args[ap->argno];
3332 /* Stringify it it hasn't already been */
3335 if (arg->stringified_length < 0)
3337 int arglen = arg->raw_length;
3338 bool escaped = FALSE;
3339 char in_string = '\0';
3342 /* Initially need_space is -1. Otherwise, 1 means the
3343 previous character was a space, but we suppressed it;
3344 0 means the previous character was a non-space. */
3345 int need_space = -1;
3348 arg->stringified = cppReader_getWritten (pfile);
3349 if (!cppReader_isTraditional (pfile))
3350 cppReader_putChar (pfile, '\"'); /* insert beginning quote */
3351 for (; i < arglen; i++)
3353 c = (ARG_BASE + arg->raw)[i];
3355 if (in_string == '\0')
3357 /* Internal sequences of whitespace are replaced by
3358 one space except within an string or char token.*/
3359 if (is_space[(int) c])
3361 if (cppReader_getWritten (pfile) > arg->stringified
3362 && (cppReader_getPWritten (pfile))[-1] == '@')
3364 /* "@ " escape markers are removed */
3365 cppReader_adjustWritten (pfile, -1);
3366 /*@innercontinue@*/ continue;
3368 if (need_space == 0)
3370 /*@innercontinue@*/ continue;
3372 else if (need_space > 0)
3373 cppReader_putChar (pfile, ' ');
3389 if (in_string != '\0')
3394 else if (c == '\"' || c == '\'')
3404 /* Escape these chars */
3405 if (c == '\"' || (in_string != '\0' && c == '\\'))
3406 cppReader_putChar (pfile, '\\');
3408 cppReader_putChar (pfile, c);
3411 cppReader_reserve (pfile, 4);
3412 sprintf (cppReader_getPWritten (pfile), "\\%03o",
3414 cppReader_adjustWritten (pfile, 4);
3417 if (!cppReader_isTraditional (pfile))
3418 cppReader_putChar (pfile, '\"'); /* insert ending quote */
3419 arg->stringified_length
3420 = size_toInt (cppReader_getWritten (pfile) - arg->stringified);
3423 xbuf_len += args[ap->argno].stringified_length;
3425 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
3427 /* Add 4 for two newline-space markers to prevent
3428 token concatenation. */
3429 xbuf_len += args[ap->argno].raw_length + 4;
3433 /* We have an ordinary (expanded) occurrence of the arg.
3434 So compute its expansion, if we have not already. */
3436 if (args[ap->argno].expand_length < 0)
3438 args[ap->argno].expanded = cppReader_getWritten (pfile);
3439 cpp_expand_to_buffer (pfile,
3440 ARG_BASE + args[ap->argno].raw,
3441 size_fromInt (args[ap->argno].raw_length));
3443 args[ap->argno].expand_length
3444 = size_toInt (cppReader_getWritten (pfile) - args[ap->argno].expanded);
3447 /* Add 4 for two newline-space markers to prevent
3448 token concatenation. */
3449 xbuf_len += args[ap->argno].expand_length + 4;
3451 if (args[ap->argno].use_count < 10)
3452 args[ap->argno].use_count++;
3455 xbuf = (char *) dmalloc (xbuf_len + 1);
3459 ** Generate in XBUF the complete expansion
3460 ** with arguments substituted in.
3461 ** TOTLEN is the total size generated so far.
3462 ** OFFSET is the index in the definition
3463 ** of where we are copying from.
3469 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
3470 last_ap = ap, ap = ap->next)
3472 register struct argdata *arg = &args[ap->argno];
3473 size_t count_before = totlen;
3475 /* Add chars to XBUF. */
3476 for (i = 0; i < ap->nchars; i++, offset++)
3478 xbuf[totlen++] = exp[offset];
3481 /* If followed by an empty rest arg with concatenation,
3482 delete the last run of nonwhite chars. */
3483 if (rest_zero && totlen > count_before
3484 && ((ap->rest_args && ap->raw_before)
3485 || (last_ap != NULL && last_ap->rest_args
3486 && last_ap->raw_after)))
3488 /* Delete final whitespace. */
3489 while (totlen > count_before && is_space[(int) xbuf[totlen - 1]])
3494 /* Delete the nonwhites before them. */
3495 while (totlen > count_before && ! is_space[(int) xbuf[totlen - 1]])
3501 if (ap->stringify != 0)
3504 memcpy (xbuf + totlen,
3505 ARG_BASE + arg->stringified,
3506 size_fromInt (arg->stringified_length));
3507 totlen += arg->stringified_length;
3509 else if (ap->raw_before || ap->raw_after || cppReader_isTraditional (pfile))
3516 p1 = ARG_BASE + arg->raw;
3517 l1 = p1 + arg->raw_length;
3521 while (p1 != l1 && is_space[(int) *p1])
3526 while (p1 != l1 && is_idchar[(int) *p1])
3528 xbuf[totlen++] = *p1++;
3531 /* Delete any no-reexpansion marker that follows
3532 an identifier at the beginning of the argument
3533 if the argument is concatenated with what precedes it. */
3534 if (p1[0] == '@' && p1[1] == '-')
3539 /* Arg is concatenated after: delete trailing whitespace,
3540 whitespace markers, and no-reexpansion markers. */
3543 if (is_space[(int) l1[-1]]) l1--;
3544 else if (l1[-1] == '-')
3547 /* If a `-' is preceded by an odd number of newlines then it
3548 and the last newline are a no-reexpansion marker. */
3549 while (p2 != p1 && p2[-1] == '\n')
3554 if (((l1 - 1 - p2) & 1) != 0)
3560 /*@innerbreak@*/ break;
3565 /*@innerbreak@*/ break;
3570 memcpy (xbuf + totlen, p1, size_fromInt (l1 - p1));
3578 expanded = ARG_BASE + arg->expanded;
3580 if (!ap->raw_before && totlen > 0
3581 && (arg->expand_length != 0)
3582 && !cppReader_isTraditional(pfile)
3583 && unsafe_chars (xbuf[totlen-1], expanded[0]))
3585 xbuf[totlen++] = '@';
3586 xbuf[totlen++] = ' ';
3589 memcpy (xbuf + totlen, expanded,
3590 size_fromInt (arg->expand_length));
3591 totlen += arg->expand_length;
3593 if (!ap->raw_after && totlen > 0
3594 && offset < size_toInt (defn->length)
3595 && !cppReader_isTraditional(pfile)
3596 && unsafe_chars (xbuf[totlen-1], exp[offset]))
3598 xbuf[totlen++] = '@';
3599 xbuf[totlen++] = ' ';
3602 /* If a macro argument with newlines is used multiple times,
3603 then only expand the newlines once. This avoids creating
3604 output lines which don't correspond to any input line,
3605 which confuses gdb and gcov. */
3606 if (arg->use_count > 1 && arg->newlines > 0)
3608 /* Don't bother doing change_newlines for subsequent
3612 = change_newlines (expanded, arg->expand_length);
3616 if (totlen > xbuf_len)
3620 /* if there is anything left of the definition
3621 after handling the arg list, copy that in too. */
3623 for (i = offset; i < size_toInt (defn->length); i++)
3625 /* if we've reached the end of the macro */
3628 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
3629 && last_ap->raw_after))
3630 xbuf[totlen++] = exp[i];
3633 xbuf[totlen] = '\0';
3637 pfile->output_escapes--;
3639 /* Now put the expansion on the input stack
3640 so our caller will commence reading from it. */
3641 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
3642 cppReader_getBuffer (pfile)->has_escapes = 1;
3644 /* Pop the space we've used in the token_buffer for argument expansion. */
3645 cppReader_setWritten (pfile, old_written);
3647 /* Recursive macro use sometimes works traditionally.
3648 #define foo(x,y) bar (x (y,0), y)
3651 if (!cppReader_isTraditional (pfile))
3652 hp->type = T_DISABLED;
3658 push_macro_expansion (cppReader *pfile, char *xbuf, size_t xbuf_len,
3659 /*@dependent@*/ HASHNODE *hp)
3661 cppBuffer *mbuf = cppReader_pushBuffer (pfile, xbuf, xbuf_len);
3668 mbuf->cleanup = cppReader_macroCleanup;
3670 llassert (mbuf->hnode == NULL);
3673 /* The first chars of the expansion should be a "@ " added by
3674 collect_expansion. This is to prevent accidental token-pasting
3675 between the text preceding the macro invocation, and the macro
3678 We would like to avoid adding unneeded spaces (for the sake of
3679 tools that use cpp, such as imake). In some common cases we can
3680 tell that it is safe to omit the space.
3682 The character before the macro invocation cannot have been an
3683 idchar (or else it would have been pasted with the idchars of
3684 the macro name). Therefore, if the first non-space character
3685 of the expansion is an idchar, we do not need the extra space
3686 to prevent token pasting.
3688 Also, we don't need the extra space if the first char is '(',
3689 or some other (less common) characters. */
3691 if (xbuf[0] == '@' && xbuf[1] == ' '
3692 && (is_idchar[(int) xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
3693 || xbuf[2] == '\"'))
3695 llassert (mbuf->cur != NULL);
3701 /* Like cppGetToken, except that it does not read past end-of-line.
3702 Also, horizontal space is skipped, and macros are popped. */
3704 static enum cpp_token
3705 get_directive_token (cppReader *pfile)
3709 size_t old_written = cppReader_getWritten (pfile);
3710 enum cpp_token token;
3711 cppSkipHspace (pfile);
3712 if (cppReader_peekC (pfile) == '\n')
3717 token = cppGetToken (pfile);
3722 if (!cppBuffer_isMacro (cppReader_getBuffer (pfile)))
3727 cppReader_setWritten (pfile, old_written);
3728 /*@switchbreak@*/ break;
3736 /* Handle #include and #import.
3737 This function expects to see "fname" or <fname> on the input.
3739 The input is normally in part of the output_buffer following
3740 cppReader_getWritten, and will get overwritten by output_line_command.
3741 I.e. in input file specification has been popped by cppReader_handleDirective.
3745 static void replace_unixdir_with_windir(char *filename)
3749 while(filename[i] != '\0')
3751 if(filename[i] == '/')
3759 do_include (cppReader *pfile, struct directive *keyword,
3760 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
3762 bool skip_dirs = (keyword->type == T_INCLUDE_NEXT);
3764 char *fbeg, *fend; /* Beginning and end of fname */
3765 enum cpp_token token;
3767 /* Chain of dirs to search */
3768 struct file_name_list *search_start = CPPOPTIONS (pfile)->include;
3769 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
3770 struct file_name_list *searchptr = NULL;
3771 size_t old_written = cppReader_getWritten (pfile);
3775 int f; /* file number */
3776 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
3777 f= -1; /* JF we iz paranoid! */
3779 pfile->parsing_include_directive++;
3780 token = get_directive_token (pfile);
3781 pfile->parsing_include_directive--;
3783 if (token == CPP_STRING)
3785 /* FIXME - check no trailing garbage */
3786 fbeg = pfile->token_buffer + old_written + 1;
3787 fend = cppReader_getPWritten (pfile) - 1;
3788 if (fbeg[-1] == '<')
3791 /* If -I-, start with the first -I dir after the -I-. */
3792 if (CPPOPTIONS (pfile)->first_bracket_include != NULL)
3793 search_start = CPPOPTIONS (pfile)->first_bracket_include;
3795 /* If -I- was specified, don't search current dir, only spec'd ones. */
3796 else if (!CPPOPTIONS (pfile)->ignore_srcdir)
3798 cppBuffer *fp = CPPBUFFER (pfile);
3799 /* We have "filename". Figure out directory this source
3800 file is coming from and put it on the front of the list. */
3802 for ( ; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
3807 llassert (fp != NULL);
3811 if (cstring_isDefined (fp->nominal_fname))
3813 nam = cstring_toCharsSafe (fp->nominal_fname);
3815 /* Found a named file. Figure out dir of the file,
3816 and put it in front of the search list. */
3817 dsp[0].next = search_start;
3821 ep = strrchr (nam, CONNECTCHAR);
3823 ep = strrchr (nam, ']');
3824 if (ep == NULL) ep = strrchr (nam, '>');
3825 if (ep == NULL) ep = strrchr (nam, ':');
3826 if (ep != NULL) ep++;
3836 /*@-onlytrans@*/ /* This looks like a memory leak... */
3837 dsp[0].fname = cstring_fromCharsNew (nam); /* evs 2000-07-20: was fromChars */
3841 if (n + INCLUDE_LEN_FUDGE > pfile->max_include_len)
3842 pfile->max_include_len = n + INCLUDE_LEN_FUDGE;
3846 dsp[0].fname = cstring_undefined; /* Current directory */
3849 dsp[0].got_name_map = 0;
3860 else if (token == CPP_NAME)
3863 * Support '#include xyz' like VAX-C to allow for easy use of all the
3864 * decwindow include files. It defaults to '#include <xyz.h>' (so the
3865 * code from case '<' is repeated here) and generates a warning.
3867 cppReader_warning (pfile,
3868 "VAX-C-style include specification found, use '#include <filename.h>' !");
3870 /* If -I-, start with the first -I dir after the -I-. */
3871 if (CPPOPTIONS (pfile)->first_bracket_include)
3872 search_start = CPPOPTIONS (pfile)->first_bracket_include;
3873 fbeg = pfile->token_buffer + old_written;
3874 fend = cppReader_getPWritten (pfile);
3879 cppReader_error (pfile,
3880 message ("Preprocessor command #%s expects \"FILENAME\" or <FILENAME>",
3883 cppReader_setWritten (pfile, old_written);
3884 cppReader_skipRestOfLine (pfile);
3890 token = get_directive_token (pfile);
3891 if (token != CPP_VSPACE)
3893 cppReader_errorLit (pfile,
3894 cstring_makeLiteralTemp ("Junk at end of #include"));
3896 while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
3898 token = get_directive_token (pfile);
3903 ** For #include_next, skip in the search path
3904 ** past the dir in which the containing file was found.
3909 cppBuffer *fp = CPPBUFFER (pfile);
3911 for (; fp != cppReader_nullBuffer (pfile); fp = cppBuffer_prevBuffer (fp))
3913 llassert (fp != NULL);
3915 if (fp->fname != NULL)
3917 /* fp->dir is null if the containing file was specified with
3918 an absolute file name. In that case, don't skip anything. */
3919 if (fp->dir == SELF_DIR_DUMMY)
3921 search_start = CPPOPTIONS (pfile)->include;
3923 else if (fp->dir != NULL)
3925 search_start = fp->dir->next;
3937 cppReader_setWritten (pfile, old_written);
3941 DPRINTF (("fbeg: %s", fbeg));
3945 cppReader_error (pfile,
3946 message ("Empty file name in #%s", keyword->name));
3951 ** Allocate this permanently, because it gets stored in the definitions
3955 fname = cstring_undefined;
3957 /* + 2 above for slash and terminating null. */
3958 /* + 2 added for '.h' on VMS (to support '#include filename') */
3960 /* If specified file name is absolute, just open it. */
3962 if (osd_isConnectChar (*fbeg)
3963 # if defined (WIN32) || defined (OS2)
3964 || (*(fbeg + 1) == ':')
3968 fname = cstring_copyLength (fbeg, flen);
3970 if (redundant_include_p (pfile, fname))
3972 cstring_free (fname);
3976 f = open_include_file (pfile, fname, NULL);
3978 if (f == IMPORT_FOUND)
3980 return 0; /* Already included this file */
3985 /* Search directory path, trying to open the file.
3986 Copy each filename tried into FNAME. */
3988 for (searchptr = search_start; searchptr != NULL;
3989 searchptr = searchptr->next)
3991 if (!cstring_isEmpty (searchptr->fname))
3993 /* The empty string in a search path is ignored.
3994 This makes it possible to turn off entirely
3995 a standard piece of the list. */
3996 if (cstring_isEmpty (searchptr->fname))
3999 fname = cstring_copy (searchptr->fname);
4000 fname = cstring_appendChar (fname, CONNECTCHAR);
4001 DPRINTF (("Here: %s", fname));
4008 fname = cstring_concatLength (fname, fbeg, flen);
4010 DPRINTF (("fname: %s", fname));
4012 /* Win32 directory fix from Kay Buschner. */
4014 /* Fix all unixdir slashes to win dir slashes */
4015 if (searchptr->fname && (searchptr->fname[0] != 0))
4017 replace_unixdir_with_windir(fname);
4022 /* Change this 1/2 Unix 1/2 VMS file specification into a
4023 full VMS file specification */
4024 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4025 /* Fix up the filename */
4026 hack_vms_include_specification (fname);
4028 /* This is a normal VMS filespec, so use it unchanged. */
4029 strncpy (fname, fbeg, flen);
4031 /* if it's '#include filename', add the missing .h */
4032 if (strchr (fname,'.') == NULL) {
4033 strcat (fname, ".h");
4037 /* ??? There are currently 3 separate mechanisms for avoiding processing
4038 of redundant include files: #import, #pragma once, and
4039 redundant_include_p. It would be nice if they were unified. */
4041 if (redundant_include_p (pfile, fname))
4043 cstring_free (fname);
4047 DPRINTF (("Trying: %s", fname));
4049 f = open_include_file (pfile, fname, searchptr);
4051 if (f == IMPORT_FOUND)
4053 return 0; /* Already included this file */
4056 else if (f == IMPORT_NOT_FOUND && errno == EACCES)
4058 cppReader_warning (pfile,
4059 message ("Header file %s exists, but is not readable", fname));
4072 /* A file that was not found. */
4073 fname = cstring_copyLength (fbeg, flen);
4075 if (search_start != NULL)
4077 cppReader_error (pfile,
4078 message ("Cannot find include file %s on search path: %x",
4080 searchPath_unparse (search_start)));
4084 cppReader_error (pfile,
4085 message ("No include path in which to find %s", fname));
4090 ** Check to see if this include file is a once-only include file.
4094 struct file_name_list *ptr;
4096 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
4098 if (cstring_equal (ptr->fname, fname))
4100 /* This file was included before. */
4107 /* This is the first time for this file. */
4108 /* Add it to list of files included. */
4110 ptr = (struct file_name_list *) dmalloc (sizeof (*ptr));
4111 ptr->control_macro = NULL;
4112 ptr->c_system_include_path = NULL;
4113 ptr->next = pfile->all_include_files;
4115 ptr->got_name_map = NULL;
4117 DPRINTF (("Including file: %s", fname));
4118 pfile->all_include_files = ptr;
4119 assertSet (pfile->all_include_files);
4122 if (angle_brackets != 0)
4124 pfile->system_include_depth++;
4127 /* Actually process the file */
4128 if (cppReader_pushBuffer (pfile, NULL, 0) == NULL)
4130 cstring_free (fname);
4134 if (finclude (pfile, f, fname, is_system_include (pfile, fname),
4135 searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
4137 output_line_command (pfile, 0, enter_file);
4138 pfile->only_seen_white = 2;
4143 pfile->system_include_depth--;
4146 } /*@=branchstate@*/
4151 /* Return nonzero if there is no need to include file NAME
4152 because it has already been included and it contains a conditional
4153 to make a repeated include do nothing. */
4156 redundant_include_p (cppReader *pfile, cstring name)
4158 struct file_name_list *l = pfile->all_include_files;
4160 for (; l != NULL; l = l->next)
4162 if (cstring_equal (name, l->fname)
4163 && (l->control_macro != NULL)
4164 && (cppReader_lookup (l->control_macro, -1, -1) != NULL))
4173 /* Return nonzero if the given FILENAME is an absolute pathname which
4174 designates a file within one of the known "system" include file
4175 directories. We assume here that if the given FILENAME looks like
4176 it is the name of a file which resides either directly in a "system"
4177 include file directory, or within any subdirectory thereof, then the
4178 given file must be a "system" include file. This function tells us
4179 if we should suppress pedantic errors/warnings for the given FILENAME.
4181 The value is 2 if the file is a C-language system header file
4182 for which C++ should (on most systems) assume `extern "C"'. */
4185 is_system_include (cppReader *pfile, cstring filename)
4187 struct file_name_list *searchptr;
4189 for (searchptr = CPPOPTIONS (pfile)->first_system_include;
4191 searchptr = searchptr->next)
4193 if (!cstring_isEmpty (searchptr->fname)) {
4194 cstring sys_dir = searchptr->fname;
4195 int length = cstring_length (sys_dir);
4197 if (cstring_equalLen (sys_dir, filename, length)
4198 && osd_isConnectChar (cstring_getChar (filename, length)))
4200 if (searchptr->c_system_include_path)
4211 /* Convert a character string literal into a nul-terminated string.
4212 The input string is [IN ... LIMIT).
4213 The result is placed in RESULT. RESULT can be the same as IN.
4214 The value returned in the end of the string written to RESULT,
4215 or NULL on error. */
4217 static /*@null@*/ char *
4218 convert_string (cppReader *pfile, /*@returned@*/ char *result,
4219 char *in, char *limit, int handle_escapes)
4239 /*@switchbreak@*/ break;
4243 char *bpc = (char *) in;
4244 int i = (char) cppReader_parseEscape (pfile, &bpc);
4247 *result++ = (char) c;
4248 /*@switchbreak@*/ break;
4262 * interpret #line command. Remembers previously seen fnames
4263 * in its very own hash table.
4266 /*@constant int FNAME_HASHSIZE@*/
4267 #define FNAME_HASHSIZE 37
4270 do_line (cppReader *pfile, /*@unused@*/ struct directive *keyword)
4272 cppBuffer *ip = cppReader_getBuffer (pfile);
4274 size_t old_written = cppReader_getWritten (pfile);
4275 enum file_change_code file_change = same_file;
4276 enum cpp_token token;
4278 token = get_directive_token (pfile);
4280 if (token != CPP_NUMBER
4281 || !isdigit(pfile->token_buffer[old_written]))
4283 cppReader_errorLit (pfile,
4284 cstring_makeLiteralTemp ("invalid format `#line' command"));
4286 goto bad_line_directive;
4289 /* The Newline at the end of this line remains to be processed.
4290 To put the next line at the specified line number,
4291 we must store a line number now that is one less. */
4292 new_lineno = atoi (pfile->token_buffer + old_written) - 1;
4293 cppReader_setWritten (pfile, old_written);
4295 /* NEW_LINENO is one less than the actual line number here. */
4296 if (cppReader_isPedantic (pfile) && new_lineno < 0)
4297 cppReader_pedwarnLit (pfile,
4298 cstring_makeLiteralTemp ("line number out of range in `#line' command"));
4300 token = get_directive_token (pfile);
4302 if (token == CPP_STRING) {
4303 char *fname = pfile->token_buffer + old_written;
4305 static HASHNODE *fname_table[FNAME_HASHSIZE];
4306 HASHNODE *hp, **hash_bucket;
4311 /* Turn the file name, which is a character string literal,
4312 into a null-terminated string. Do this in place. */
4313 end_name = convert_string (pfile, fname, fname, cppReader_getPWritten (pfile), 1);
4314 if (end_name == NULL)
4316 cppReader_errorLit (pfile,
4317 cstring_makeLiteralTemp ("invalid format `#line' command"));
4318 goto bad_line_directive;
4321 fname_length = end_name - fname;
4322 num_start = cppReader_getWritten (pfile);
4324 token = get_directive_token (pfile);
4325 if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP) {
4326 p = pfile->token_buffer + num_start;
4327 if (cppReader_isPedantic (pfile))
4328 cppReader_pedwarnLit (pfile,
4329 cstring_makeLiteralTemp ("garbage at end of `#line' command"));
4331 if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
4333 cppReader_errorLit (pfile,
4334 cstring_makeLiteralTemp ("invalid format `#line' command"));
4335 goto bad_line_directive;
4338 file_change = enter_file;
4340 file_change = leave_file;
4342 ip->system_header_p = 1;
4343 else /* if (*p == 4) */
4344 ip->system_header_p = 2;
4346 cppReader_setWritten (pfile, num_start);
4347 token = get_directive_token (pfile);
4348 p = pfile->token_buffer + num_start;
4349 if (token == CPP_NUMBER && p[1] == '\0' && (*p == '3' || *p== '4')) {
4350 ip->system_header_p = *p == 3 ? 1 : 2;
4351 token = get_directive_token (pfile);
4353 if (token != CPP_VSPACE) {
4354 cppReader_errorLit (pfile,
4355 cstring_makeLiteralTemp ("invalid format `#line' command"));
4357 goto bad_line_directive;
4362 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
4363 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
4365 if (hp->length == fname_length &&
4366 strncmp (hp->value.cpval, fname, size_fromInt (fname_length)) == 0) {
4367 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
4373 /* Didn't find it; cons up a new one. */
4374 hp = (HASHNODE *) dmalloc (sizeof (*hp) + fname_length + 1);
4377 hp->bucket_hdr = NULL;
4379 hp->name = cstring_undefined;
4380 hp->next = *hash_bucket;
4384 hp->length = fname_length;
4385 hp->value.cpval = dmalloc (sizeof (*hp->value.cpval) * (fname_length + 1));
4386 memcpy (hp->value.cpval, fname, size_fromInt (fname_length));
4387 hp->value.cpval[fname_length] = '\0';
4388 ip->nominal_fname = cstring_fromChars (hp->value.cpval);
4391 else if (token != CPP_VSPACE && token != CPP_EOF)
4393 cppReader_errorLit (pfile,
4394 cstring_makeLiteralTemp ("invalid format `#line' command"));
4395 goto bad_line_directive;
4402 ip->lineno = new_lineno;
4404 cppReader_skipRestOfLine (pfile);
4405 cppReader_setWritten (pfile, old_written);
4406 output_line_command (pfile, 0, file_change);
4411 * remove the definition of a symbol from the symbol table.
4412 * according to un*x /lib/cpp, it is not an error to undef
4413 * something that has no definitions, so it isn't one here either.
4417 do_undef (cppReader *pfile, struct directive *keyword, char *buf, char *limit)
4422 char *orig_buf = buf;
4424 SKIP_WHITE_SPACE (buf);
4426 sym_length = cppReader_checkMacroName (pfile, buf, cstring_makeLiteralTemp ("macro"));
4428 while ((hp = cppReader_lookup (buf, sym_length, -1)) != NULL)
4430 /* If we are generating additional info for debugging (with -g) we
4431 need to pass through all effective #undef commands. */
4432 if (CPPOPTIONS (pfile)->debug_output && (keyword != NULL))
4434 pass_thru_directive (orig_buf, limit, pfile, keyword);
4437 if (hp->type != T_MACRO)
4439 cppReader_warning (pfile,
4440 message ("Undefining preprocessor builtin: %s",
4444 cppReader_deleteMacro (hp);
4447 if (cppReader_isPedantic (pfile)) {
4449 SKIP_WHITE_SPACE (buf);
4452 cppReader_pedwarnLit (pfile,
4453 cstring_makeLiteralTemp ("garbage after `#undef' directive"));
4462 * Report an error detected by the program we are processing.
4463 * Use the text of the line in the error message.
4464 * (We use error because it prints the filename & line#.)
4468 do_error (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4469 char *buf, char *limit)
4471 int length = limit - buf;
4472 cstring copy = cstring_copyLength (buf, length);
4473 cstring adv = cstring_advanceWhiteSpace (copy);
4475 cppReader_error (pfile, message ("#error %s", adv));
4476 cstring_free (copy);
4481 * Report a warning detected by the program we are processing.
4482 * Use the text of the line in the warning message, then continue.
4483 * (We use error because it prints the filename & line#.)
4487 do_warning (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4488 char *buf, char *limit)
4490 int length = limit - buf;
4491 cstring copy = cstring_copyLength (buf, length);
4492 cstring adv = cstring_advanceWhiteSpace (copy);
4493 cppReader_warning (pfile, message ("#warning %s", adv));
4494 cstring_free (copy);
4499 /* #ident has already been copied to the output file, so just ignore it. */
4502 do_ident (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4503 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
4505 /* Allow #ident in system headers, since that's not user's fault. */
4506 if (cppReader_isPedantic (pfile) && !cppReader_getBuffer (pfile)->system_header_p)
4507 cppReader_pedwarnLit (pfile,
4508 cstring_makeLiteralTemp ("ANSI C does not allow `#ident'"));
4510 /* Leave rest of line to be read by later calls to cppGetToken. */
4515 /* #pragma and its argument line have already been copied to the output file.
4516 Just check for some recognized pragmas that need validation here. */
4519 do_pragma (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4520 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
4522 while (*buf == ' ' || *buf == '\t')
4527 if (!strncmp (buf, "implementation", 14)) {
4528 /* Be quiet about `#pragma implementation' for a file only if it hasn't
4529 been included yet. */
4530 struct file_name_list *ptr;
4531 char *p = buf + 14, *fname, *inc_fname;
4533 SKIP_WHITE_SPACE (p);
4534 if (*p == '\n' || *p != '\"')
4538 p = (char *) strchr (fname, '\"');
4539 fname_len = p != NULL ? p - fname : mstring_length (fname);
4541 for (ptr = pfile->all_include_files; ptr != NULL; ptr = ptr->next)
4543 inc_fname = (char *) strrchr (cstring_toCharsSafe (ptr->fname), CONNECTCHAR);
4544 inc_fname = (inc_fname != NULL)
4545 ? inc_fname + 1 : cstring_toCharsSafe (ptr->fname);
4547 if ((inc_fname != NULL)
4548 && (strncmp (inc_fname, fname, size_fromInt (fname_len)) == 0))
4550 cpp_setLocation (pfile);
4552 ppllerror (message ("`#pragma implementation' for `%s' appears "
4553 "after file is included",
4554 cstring_fromChars (fname)));
4563 * handle #if command by
4564 * 1) inserting special `defined' keyword into the hash table
4565 * that gets turned into 0 or 1 by special_symbol (thus,
4566 * if the luser has a symbol called `defined' already, it won't
4567 * work inside the #if command)
4568 * 2) rescan the input into a temporary output buffer
4569 * 3) pass the output buffer to the yacc parser and collect a value
4570 * 4) clean up the mess left from steps 1 and 2.
4571 * 5) call conditional_skip to skip til the next #endif (etc.),
4572 * or not, depending on the value from step 3.
4576 do_if (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4577 char *buf, char *limit)
4579 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
4580 conditional_skip (pfile, value == 0, T_IF, NULL);
4585 * handle a #elif directive by not changing if_stack either.
4586 * see the comment above do_else.
4589 static int do_elif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4590 char *buf, char *limit)
4592 if (pfile->if_stack == cppReader_getBuffer (pfile)->if_stack)
4594 cppReader_errorLit (pfile,
4595 cstring_makeLiteralTemp ("Preprocessor command #elif is not within a conditional"));
4600 llassert (pfile->if_stack != NULL);
4602 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
4604 cppReader_errorLit (pfile,
4605 cstring_makeLiteralTemp ("`#elif' after `#else'"));
4607 if (pfile->if_stack->fname != NULL
4608 && cppReader_getBuffer (pfile)->fname != NULL
4609 && !cstring_equal (pfile->if_stack->fname,
4610 cppReader_getBuffer (pfile)->nominal_fname))
4611 fprintf (stderr, ", file %s", cstring_toCharsSafe (pfile->if_stack->fname));
4612 fprintf (stderr, ")\n");
4614 pfile->if_stack->type = T_ELIF;
4617 if (pfile->if_stack->if_succeeded)
4619 skip_if_group (pfile, 0);
4623 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
4625 skip_if_group (pfile, 0);
4628 ++pfile->if_stack->if_succeeded; /* continue processing input */
4629 output_line_command (pfile, 1, same_file);
4637 * evaluate a #if expression in BUF, of length LENGTH,
4638 * then parse the result as a C expression and return the value as an int.
4641 static HOST_WIDE_INT
4642 eval_if_expression (cppReader *pfile,
4643 /*@unused@*/ char *buf,
4644 /*@unused@*/ int length)
4646 HASHNODE *save_defined;
4647 HOST_WIDE_INT value;
4648 size_t old_written = cppReader_getWritten (pfile);
4650 save_defined = cppReader_install ("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
4651 pfile->pcp_inside_if = 1;
4653 value = cppReader_parseExpression (pfile);
4654 pfile->pcp_inside_if = 0;
4656 /* Clean up special symbol */
4657 cppReader_deleteMacro (save_defined);
4659 cppReader_setWritten (pfile, old_written); /* Pop */
4665 * routine to handle ifdef/ifndef. Try to look up the symbol,
4666 * then do or don't skip to the #endif/#else/#elif depending
4667 * on what directive is actually being processed.
4671 do_xifdef (cppReader *pfile, struct directive *keyword,
4672 /*@unused@*/ char *unused1, /*@unused@*/ char *unused2)
4675 cppBuffer *ip = cppReader_getBuffer (pfile);
4678 enum cpp_token token;
4679 int start_of_file = 0;
4680 char *control_macro = 0;
4681 size_t old_written = cppReader_getWritten (pfile);
4683 DPRINTF (("do xifdef: %d",
4684 keyword->type == T_IFNDEF));
4686 /* Detect a #ifndef at start of file (not counting comments). */
4687 if (cstring_isDefined (ip->fname) && keyword->type == T_IFNDEF)
4689 start_of_file = pfile->only_seen_white == 2;
4692 pfile->no_macro_expand++;
4693 token = get_directive_token (pfile);
4694 pfile->no_macro_expand--;
4696 ident = pfile->token_buffer + old_written;
4697 ident_length = size_toInt (cppReader_getWritten (pfile) - old_written);
4698 cppReader_setWritten (pfile, old_written); /* Pop */
4700 if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
4702 skip = (keyword->type == T_IFDEF);
4703 if (! cppReader_isTraditional (pfile))
4705 cppReader_pedwarn (pfile,
4706 message ("`#%s' with no argument", keyword->name));
4709 else if (token == CPP_NAME)
4711 HASHNODE *hp = cppReader_lookup (ident, ident_length, -1);
4712 skip = (keyword->type == T_IFDEF)
4713 ? (hp == NULL) : (hp != NULL);
4715 DPRINTF (("hp null: %d / %d / %d",
4717 (keyword->type == T_IFNDEF),
4720 if (start_of_file && !skip)
4722 DPRINTF (("Not skipping!"));
4723 control_macro = (char *) dmalloc (size_fromInt (ident_length + 1));
4724 memcpy (control_macro, ident, size_fromInt (ident_length + 1));
4729 skip = (keyword->type == T_IFDEF);
4730 if (! cppReader_isTraditional (pfile))
4732 cppReader_error (pfile,
4733 message ("`#%s' with invalid argument", keyword->name));
4737 if (!cppReader_isTraditional (pfile))
4740 cppSkipHspace (pfile);
4741 c = cppReader_peekC (pfile);
4742 if (c != EOF && c != '\n')
4744 cppReader_pedwarn (pfile,
4745 message ("garbage at end of `#%s' argument", keyword->name));
4749 cppReader_skipRestOfLine (pfile);
4751 DPRINTF (("Conditional skip: %d", skip));
4752 conditional_skip (pfile, skip, T_IF, control_macro);
4756 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
4757 If this is a #ifndef starting at the beginning of a file,
4758 CONTROL_MACRO is the macro name tested by the #ifndef.
4759 Otherwise, CONTROL_MACRO is 0. */
4762 conditional_skip (cppReader *pfile, int skip,
4763 enum node_type type,
4764 /*@dependent@*/ char *control_macro)
4766 cppIfStackFrame *temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
4768 temp->fname = cppReader_getBuffer (pfile)->nominal_fname;
4769 temp->next = pfile->if_stack;
4770 temp->control_macro = control_macro;
4772 temp->if_succeeded = 0;
4774 pfile->if_stack = temp;
4775 pfile->if_stack->type = type;
4779 skip_if_group (pfile, 0);
4784 ++pfile->if_stack->if_succeeded;
4785 output_line_command (pfile, 1, same_file);
4790 * skip to #endif, #else, or #elif. adjust line numbers, etc.
4791 * leaves input ptr at the sharp sign found.
4792 * If ANY is nonzero, return at next directive of any sort.
4796 skip_if_group (cppReader *pfile, int any)
4799 struct directive *kt;
4800 cppIfStackFrame *save_if_stack = pfile->if_stack; /* don't pop past here */
4801 register int ident_length;
4803 struct parse_marker line_start_mark;
4805 parseSetMark (&line_start_mark, pfile);
4807 if (CPPOPTIONS (pfile)->output_conditionals) {
4808 static char failed[] = "#failed\n";
4809 cppReader_puts (pfile, failed, sizeof(failed)-1);
4811 output_line_command (pfile, 1, same_file);
4815 if (CPPOPTIONS (pfile)->output_conditionals)
4817 cppBuffer *pbuf = cppReader_getBuffer (pfile);
4820 llassert (pbuf->buf != NULL);
4822 start_line = pbuf->buf + line_start_mark.position;
4823 cppReader_puts (pfile, start_line, size_fromInt (pbuf->cur - start_line));
4826 parseMoveMark (&line_start_mark, pfile);
4828 if (!cppReader_isTraditional (pfile))
4830 cppSkipHspace (pfile);
4833 c = cppReader_getC (pfile);
4836 size_t old_written = cppReader_getWritten (pfile);
4837 cppSkipHspace (pfile);
4839 parse_name (pfile, cppReader_getC (pfile));
4840 ident_length = size_toInt (cppReader_getWritten (pfile) - old_written);
4841 ident = pfile->token_buffer + old_written;
4842 pfile->limit = ident;
4844 for (kt = directive_table; kt->length >= 0; kt++)
4846 cppIfStackFrame *temp;
4847 if (ident_length == kt->length
4848 && cstring_equalPrefix (kt->name, ident))
4850 /* If we are asked to return on next directive, do so now. */
4861 temp = (cppIfStackFrame *) dmalloc (sizeof (*temp));
4862 temp->next = pfile->if_stack;
4863 temp->fname = cppReader_getBuffer (pfile)->nominal_fname;
4864 temp->type = kt->type;
4866 temp->if_succeeded = 0;
4867 temp->control_macro = NULL;
4869 pfile->if_stack = temp;
4870 /*@switchbreak@*/ break;
4873 if (cppReader_isPedantic (pfile) && pfile->if_stack != save_if_stack)
4874 validate_else (pfile,
4875 cstring_makeLiteralTemp (kt->type == T_ELSE ? "#else" : "#endif"));
4878 if (pfile->if_stack == cppReader_getBuffer (pfile)->if_stack)
4880 cppReader_error (pfile,
4881 message ("Preprocessor command #%s is not within a conditional", kt->name));
4882 /*@switchbreak@*/ break;
4884 else if (pfile->if_stack == save_if_stack)
4886 goto done; /* found what we came for */
4893 if (kt->type != T_ENDIF)
4895 llassert (pfile->if_stack != NULL);
4897 if (pfile->if_stack->type == T_ELSE)
4899 cppReader_errorLit (pfile,
4900 cstring_makeLiteralTemp ("`#else' or `#elif' after `#else'"));
4903 pfile->if_stack->type = kt->type;
4904 /*@switchbreak@*/ break;
4907 temp = pfile->if_stack;
4908 llassert (temp != NULL);
4909 pfile->if_stack = temp->next;
4911 /*@switchbreak@*/ break;
4919 /* Don't let erroneous code go by. */
4921 if (kt->length < 0 && !CPPOPTIONS (pfile)->lang_asm
4922 && cppReader_isPedantic (pfile))
4924 cppReader_pedwarnLit (pfile,
4925 cstring_makeLiteralTemp ("Invalid preprocessor directive name"));
4929 c = cppReader_getC (pfile);
4931 /* We're in the middle of a line. Skip the rest of it. */
4939 case '/': /* possible comment */
4940 c = skip_comment (pfile, NULL);
4943 /*@switchbreak@*/ break;
4946 cppReader_forward (pfile, -1);
4947 old = cppReader_getWritten (pfile);
4948 (void) cppGetToken (pfile);
4949 cppReader_setWritten (pfile, old);
4950 /*@switchbreak@*/ break;
4952 /* Char after backslash loses its special meaning. */
4953 if (cppReader_peekC (pfile) == '\n')
4955 cppReader_forward (pfile, 1);
4958 /*@switchbreak@*/ break;
4962 c = cppReader_getC (pfile);
4965 if (CPPOPTIONS (pfile)->output_conditionals) {
4966 static char end_failed[] = "#endfailed\n";
4967 cppReader_puts (pfile, end_failed, sizeof(end_failed)-1);
4970 pfile->only_seen_white = 1;
4972 parseGotoMark (&line_start_mark, pfile);
4973 parseClearMark (&line_start_mark);
4977 * handle a #else directive. Do this by just continuing processing
4978 * without changing if_stack ; this is so that the error message
4979 * for missing #endif's etc. will point to the original #if. It
4980 * is possible that something different would be better.
4984 do_else (cppReader *pfile, /*@unused@*/ struct directive *keyword,
4985 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
4987 if (cppReader_isPedantic (pfile))
4989 validate_else (pfile, cstring_makeLiteralTemp ("#else"));
4992 cppReader_skipRestOfLine (pfile);
4994 if (pfile->if_stack == cppReader_getBuffer (pfile)->if_stack) {
4995 cppReader_errorLit (pfile,
4996 cstring_makeLiteralTemp ("Preprocessor command #else is not within a conditional"));
4999 /* #ifndef can't have its special treatment for containing the whole file
5000 if it has a #else clause. */
5002 llassert (pfile->if_stack != NULL);
5004 pfile->if_stack->control_macro = 0;
5006 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
5008 cpp_setLocation (pfile);
5009 genppllerrorhint (FLG_PREPROC,
5010 message ("Pre-processor directive #else after #else"),
5011 message ("%q: Location of match",
5012 fileloc_unparseRaw (pfile->if_stack->fname,
5013 pfile->if_stack->lineno)));
5016 pfile->if_stack->type = T_ELSE;
5019 if (pfile->if_stack->if_succeeded)
5020 skip_if_group (pfile, 0);
5022 ++pfile->if_stack->if_succeeded; /* continue processing input */
5023 output_line_command (pfile, 1, same_file);
5030 * unstack after #endif command
5034 do_endif (cppReader *pfile, /*@unused@*/ struct directive *keyword,
5035 /*@unused@*/ char *buf, /*@unused@*/ char *limit)
5037 if (cppReader_isPedantic (pfile))
5039 validate_else (pfile, cstring_makeLiteralTemp ("#endif"));
5042 cppReader_skipRestOfLine (pfile);
5044 if (pfile->if_stack == cppReader_getBuffer (pfile)->if_stack)
5046 cppReader_errorLit (pfile, cstring_makeLiteralTemp ("Unbalanced #endif"));
5050 cppIfStackFrame *temp = pfile->if_stack;
5052 llassert (temp != NULL);
5054 pfile->if_stack = temp->next;
5055 if (temp->control_macro != 0)
5057 /* This #endif matched a #ifndef at the start of the file.
5058 See if it is at the end of the file. */
5059 struct parse_marker start_mark;
5062 parseSetMark (&start_mark, pfile);
5066 cppSkipHspace (pfile);
5067 c = cppReader_getC (pfile);
5073 parseGotoMark (&start_mark, pfile);
5074 parseClearMark (&start_mark);
5078 /* If we get here, this #endif ends a #ifndef
5079 that contains all of the file (aside from whitespace).
5080 Arrange not to include the file again
5081 if the macro that was tested is defined.
5083 Do not do this for the top-level file in a -include or any
5084 file in a -imacros. */
5085 struct file_name_list *ifile = pfile->all_include_files;
5087 for ( ; ifile != NULL; ifile = ifile->next)
5089 if (cstring_equal (ifile->fname, cppReader_getBuffer (pfile)->fname))
5091 ifile->control_macro = temp->control_macro;
5099 output_line_command (pfile, 1, same_file);
5104 /* When an #else or #endif is found while skipping failed conditional,
5105 if -pedantic was specified, this is called to warn about text after
5106 the command name. P points to the first char after the command name. */
5109 validate_else (cppReader *pfile, cstring directive)
5112 cppSkipHspace (pfile);
5113 c = cppReader_peekC (pfile);
5114 if (c != EOF && c != '\n')
5116 cppReader_pedwarn (pfile,
5117 message ("text following `%s' violates ANSI standard", directive));
5122 ** Get the next token, and add it to the text in pfile->token_buffer.
5123 ** Return the kind of token we got.
5127 cppGetToken (cppReader *pfile)
5130 size_t old_written = 0;
5131 int start_line, start_column;
5132 enum cpp_token token;
5133 struct cppOptions *opts = CPPOPTIONS (pfile);
5134 cppReader_getBuffer (pfile)->prev = cppReader_getBuffer (pfile)->cur;
5137 c = cppReader_getC (pfile);
5142 if (cppReader_getBuffer (pfile)->seen_eof)
5144 cppBuffer *buf = cppReader_popBuffer (pfile);
5146 if (buf != cppReader_nullBuffer (pfile))
5157 cppBuffer *next_buf = cppBuffer_prevBuffer (cppReader_getBuffer (pfile));
5158 cppReader_getBuffer (pfile)->seen_eof = 1;
5160 if (cstring_isDefined (cppReader_getBuffer (pfile)->nominal_fname)
5161 && next_buf != cppReader_nullBuffer (pfile))
5163 /* We're about to return from an #include file.
5164 Emit #line information now (as part of the CPP_POP) result.
5165 But the #line refers to the file we will pop to. */
5166 cppBuffer *cur_buffer = CPPBUFFER (pfile);
5167 CPPBUFFER (pfile) = next_buf;
5168 pfile->input_stack_listing_current = 0;
5169 output_line_command (pfile, 0, leave_file);
5170 CPPBUFFER (pfile) = cur_buffer;
5178 struct parse_marker start_mark;
5183 if (cppReader_peekC (pfile) == '=')
5188 if (opts->put_out_comments)
5190 parseSetMark (&start_mark, pfile);
5194 cppBuffer_lineAndColumn (cppReader_fileBuffer (pfile),
5195 &start_line, &start_column);
5196 c = skip_comment (pfile, &newlines);
5198 if (opts->put_out_comments && (c == '/' || c == EOF))
5200 assertSet (&start_mark);
5201 parseClearMark (&start_mark);
5208 cppReader_errorWithLine (pfile, start_line, start_column,
5209 cstring_makeLiteral ("Unterminated comment"));
5212 c = '/'; /* Initial letter of comment. */
5214 /* Comments are equivalent to spaces.
5215 For -traditional, a comment is equivalent to nothing. */
5217 if (opts->put_out_comments)
5221 assertSet (&start_mark);
5222 res = cpp_handleComment (pfile, &start_mark);
5223 pfile->lineno += newlines;
5226 else if (cppReader_isTraditional (pfile))
5232 cppReader_reserve(pfile, 1);
5233 cppReader_putCharQ (pfile, ' ');
5238 if (!pfile->only_seen_white)
5243 if (cppReader_handleDirective (pfile))
5245 return CPP_DIRECTIVE;
5248 pfile->only_seen_white = 0;
5253 /* A single quoted string is treated like a double -- some
5254 programs (e.g., troff) are perverse this way */
5255 cppBuffer_lineAndColumn (cppReader_fileBuffer (pfile),
5256 &start_line, &start_column);
5257 old_written = cppReader_getWritten (pfile);
5259 cppReader_putChar (pfile, c);
5262 int cc = cppReader_getC (pfile);
5265 if (cppBuffer_isMacro (CPPBUFFER (pfile)))
5267 /* try harder: this string crosses a macro expansion
5268 boundary. This can happen naturally if -traditional.
5269 Otherwise, only -D can make a macro with an unmatched
5272 = cppBuffer_prevBuffer (cppReader_getBuffer (pfile));
5273 (*cppReader_getBuffer (pfile)->cleanup)
5274 (cppReader_getBuffer (pfile), pfile);
5275 CPPBUFFER (pfile) = next_buf;
5278 if (!cppReader_isTraditional (pfile))
5280 cpp_setLocation (pfile);
5282 setLine (long_toInt (start_line));
5283 setColumn (long_toInt (start_column));
5285 if (pfile->multiline_string_line != long_toInt (start_line)
5286 && pfile->multiline_string_line != 0)
5290 message ("Unterminated string or character constant"),
5291 message ("%q: Possible real start of unterminated constant",
5293 (fileloc_filename (g_currentloc),
5294 pfile->multiline_string_line)));
5295 pfile->multiline_string_line = 0;
5301 message ("Unterminated string or character constant"));
5304 /*@loopbreak@*/ break;
5306 cppReader_putChar (pfile, cc);
5310 /* Traditionally, end of line ends a string constant with
5311 no error. So exit the loop and record the new line. */
5312 if (cppReader_isTraditional (pfile))
5318 if (cppReader_isPedantic (pfile)
5319 && pfile->multiline_string_line == 0)
5321 cppReader_pedwarnWithLine
5322 (pfile, long_toInt (start_line),
5323 long_toInt (start_column),
5324 cstring_makeLiteral ("String constant runs past end of line"));
5326 if (pfile->multiline_string_line == 0)
5328 pfile->multiline_string_line = start_line;
5331 /*@switchbreak@*/ break;
5334 cc = cppReader_getC (pfile);
5337 /* Backslash newline is replaced by nothing at all. */
5338 cppReader_adjustWritten (pfile, -1);
5343 /* ANSI stupidly requires that in \\ the second \
5344 is *not* prevented from combining with a newline. */
5347 cppReader_putChar (pfile, cc);
5349 /*@switchbreak@*/ break;
5355 /*@switchbreak@*/ break;
5359 pfile->lineno += count_newlines (pfile->token_buffer + old_written,
5360 cppReader_getPWritten (pfile));
5361 pfile->only_seen_white = 0;
5362 return c == '\'' ? CPP_CHAR : CPP_STRING;
5365 if (!opts->dollars_in_ident)
5370 if (opts->cplusplus && cppReader_peekC (pfile) == ':')
5378 c2 = cppReader_peekC (pfile);
5379 if (c2 == c || c2 == '=')
5389 if (cppReader_peekC (pfile) == '=')
5395 c2 = cppReader_peekC (pfile);
5396 if (c2 == '-' && opts->chill)
5398 /* Chill style comment */
5399 if (opts->put_out_comments)
5401 parseSetMark (&start_mark, pfile);
5404 cppReader_forward (pfile, 1); /* Skip second '-'. */
5408 c = cppReader_getC (pfile);
5410 /*@loopbreak@*/ break;
5413 /* Don't consider final '\n' to be part of comment. */
5414 cppReader_forward (pfile, -1);
5415 /*@loopbreak@*/ break;
5419 goto return_comment;
5421 if (c2 == '-' || c2 == '=' || c2 == '>')
5426 if (pfile->parsing_include_directive)
5430 cppReader_putChar (pfile, c);
5432 /*@loopbreak@*/ break;
5433 c = cppReader_getC (pfile);
5435 if (c == '\n' || c == EOF)
5437 cppReader_errorLit (pfile,
5438 cstring_makeLiteralTemp ("Missing '>' in \"#include <FILENAME>\""));
5439 /*@loopbreak@*/ break;
5447 c2 = cppReader_peekC (pfile);
5452 cppReader_forward (pfile, 1);
5453 cppReader_reserve (pfile, 4);
5454 cppReader_putChar (pfile, c);
5455 cppReader_putChar (pfile, c2);
5457 c3 = cppReader_peekC (pfile);
5459 cppReader_putCharQ (pfile, cppReader_getC (pfile));
5460 cppReader_nullTerminateQ (pfile);
5461 pfile->only_seen_white = 0;
5465 if (cppReader_getBuffer (pfile)->has_escapes)
5467 c = cppReader_getC (pfile);
5470 if (pfile->output_escapes)
5471 cppReader_puts (pfile, "@-", 2);
5472 parse_name (pfile, cppReader_getC (pfile));
5475 else if (is_space [c])
5477 cppReader_reserve (pfile, 2);
5478 if (pfile->output_escapes)
5479 cppReader_putCharQ (pfile, '@');
5480 cppReader_putCharQ (pfile, c);
5488 if (pfile->output_escapes)
5490 cppReader_puts (pfile, "@@", 2);
5496 c2 = cppReader_peekC (pfile);
5499 cppReader_reserve(pfile, 2);
5500 cppReader_putCharQ (pfile, '.');
5501 c = cppReader_getC (pfile);
5505 /* FIXME - misses the case "..\\\n." */
5506 if (c2 == '.' && cpp_peekN (pfile, 1) == '.')
5508 cppReader_reserve(pfile, 4);
5509 cppReader_putCharQ (pfile, '.');
5510 cppReader_putCharQ (pfile, '.');
5511 cppReader_putCharQ (pfile, '.');
5512 cppReader_forward (pfile, 2);
5513 cppReader_nullTerminateQ (pfile);
5514 pfile->only_seen_white = 0;
5520 pfile->only_seen_white = 0;
5522 cppReader_reserve(pfile, 3);
5523 cppReader_putCharQ (pfile, c);
5524 cppReader_putCharQ (pfile, cppReader_getC (pfile));
5525 cppReader_nullTerminateQ (pfile);
5530 c2 = cppReader_peekC (pfile);
5531 if ((c2 == '\'' || c2 == '\"') && !cppReader_isTraditional (pfile))
5533 cppReader_putChar (pfile, c);
5534 c = cppReader_getC (pfile);
5539 case '0': case '1': case '2': case '3': case '4':
5540 case '5': case '6': case '7': case '8': case '9':
5545 cppReader_reserve (pfile, 2);
5546 cppReader_putCharQ (pfile, c);
5548 c = cppReader_peekC (pfile);
5550 /*@loopbreak@*/ break;
5551 if (!is_idchar[c] && c != '.'
5552 && ((c2 != 'e' && c2 != 'E'
5553 && ((c2 != 'p' && c2 != 'P') || cppReader_isC89 (pfile)))
5554 || (c != '+' && c != '-')))
5555 /*@loopbreak@*/ break;
5556 cppReader_forward (pfile, 1);
5560 cppReader_nullTerminateQ (pfile);
5561 pfile->only_seen_white = 0;
5564 case 'b': case 'c': case 'd': case 'h': case 'o':
5565 case 'B': case 'C': case 'D': case 'H': case 'O':
5566 if (opts->chill && cppReader_peekC (pfile) == '\'')
5568 pfile->only_seen_white = 0;
5569 cppReader_reserve (pfile, 2);
5570 cppReader_putCharQ (pfile, c);
5571 cppReader_putCharQ (pfile, '\'');
5572 cppReader_forward (pfile, 1);
5575 c = cppReader_getC (pfile);
5577 goto chill_number_eof;
5580 if (c == '\\' && cppReader_peekC (pfile) == '\n')
5582 cppReader_forward (pfile, 2);
5585 /*@loopbreak@*/ break;
5587 cppReader_putChar (pfile, c);
5591 cppReader_reserve (pfile, 2);
5592 cppReader_putCharQ (pfile, c);
5593 cppReader_nullTerminateQ (pfile);
5598 cppReader_forward (pfile, -1);
5600 cppReader_nullTerminate (pfile);
5607 case 'a': case 'e': case 'f': case 'g': case 'i': case 'j':
5608 case 'k': case 'l': case 'm': case 'n': case 'p': case 'q':
5609 case 'r': case 's': case 't': case 'u': case 'v': case 'w':
5610 case 'x': case 'y': case 'z':
5611 case 'A': case 'E': case 'F': case 'G': case 'I': case 'J':
5612 case 'K': case 'M': case 'N': case 'P': case 'Q': case 'R':
5613 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
5619 size_t before_name_written = cppReader_getWritten (pfile);
5621 parse_name (pfile, c);
5622 pfile->only_seen_white = 0;
5623 if (pfile->no_macro_expand)
5628 ident = pfile->token_buffer + before_name_written;
5629 ident_len = (cppReader_getPWritten (pfile)) - ident;
5631 hp = cppReader_lookupExpand (ident, ident_len, -1);
5638 if (hp->type == T_DISABLED)
5640 if (pfile->output_escapes)
5641 { /* Return "@-IDENT", followed by '\0'. */
5643 cppReader_reserve (pfile, 3);
5644 ident = pfile->token_buffer + before_name_written;
5645 cppReader_adjustWritten (pfile, 2);
5647 for (i = ident_len; i >= 0; i--)
5649 ident[i+2] = ident[i];
5658 /* If macro wants an arglist, verify that a '(' follows.
5659 first skip all whitespace, copying it to the output
5660 after the macro name. Then, if there is no '(',
5661 decide this is not a macro call and leave things that way. */
5663 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
5665 struct parse_marker macro_mark;
5668 while (cppBuffer_isMacro (CPPBUFFER (pfile)))
5670 cppBuffer *next_buf;
5671 cppSkipHspace (pfile);
5672 if (cppReader_peekC (pfile) != EOF)
5674 /*@loopbreak@*/ break;
5677 next_buf = cppBuffer_prevBuffer (cppReader_getBuffer (pfile));
5678 (*cppReader_getBuffer (pfile)->cleanup) (cppReader_getBuffer (pfile), pfile);
5679 CPPBUFFER (pfile) = next_buf;
5682 parseSetMark (¯o_mark, pfile);
5686 cppSkipHspace (pfile);
5687 c = cppReader_peekC (pfile);
5688 is_macro_call = c == '(';
5690 /*@loopbreak@*/ break;
5691 cppReader_forward (pfile, 1);
5696 parseGotoMark (¯o_mark, pfile);
5699 parseClearMark (¯o_mark);
5706 /* This is now known to be a macro call. */
5708 /* it might not actually be a macro. */
5709 if (hp->type != T_MACRO)
5714 cppReader_setWritten (pfile, before_name_written);
5715 special_symbol (hp, pfile);
5716 xbuf_len = cppReader_getWritten (pfile) - before_name_written;
5717 xbuf = (char *) dmalloc (xbuf_len + 1);
5718 cppReader_setWritten (pfile, before_name_written);
5719 memcpy (xbuf, cppReader_getPWritten (pfile), xbuf_len + 1);
5720 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
5724 /* Expand the macro, reading arguments as needed,
5725 and push the expansion on the input stack. */
5726 macroexpand (pfile, hp);
5727 cppReader_setWritten (pfile, before_name_written);
5730 /* An extra "@ " is added to the end of a macro expansion
5731 to prevent accidental token pasting. We prefer to avoid
5732 unneeded extra spaces (for the sake of cpp-using tools like
5733 imake). Here we remove the space if it is safe to do so. */
5735 llassert (pfile->buffer->rlimit != NULL);
5737 if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
5738 && pfile->buffer->rlimit[-2] == '@'
5739 && pfile->buffer->rlimit[-1] == ' ')
5741 int c1 = pfile->buffer->rlimit[-3];
5742 int cl2 = cppBufPeek (cppBuffer_prevBuffer (CPPBUFFER (pfile)));
5744 if (cl2 == EOF || !unsafe_chars ((char) c1, (char) cl2))
5745 pfile->buffer->rlimit -= 2;
5751 case ' ': case '\t': case '\v': case '\r':
5754 cppReader_putChar (pfile, c);
5755 c = cppReader_peekC (pfile);
5756 if (c == EOF || !is_hor_space[c])
5757 /*@loopbreak@*/ break;
5758 cppReader_forward (pfile, 1);
5763 c2 = cppReader_peekC (pfile);
5770 cppReader_putChar (pfile, c);
5771 if (pfile->only_seen_white == 0)
5772 pfile->only_seen_white = 1;
5774 output_line_command (pfile, 1, same_file);
5777 case '(': token = CPP_LPAREN; goto char1;
5778 case ')': token = CPP_RPAREN; goto char1;
5779 case '{': token = CPP_LBRACE; goto char1;
5780 case '}': token = CPP_RBRACE; goto char1;
5781 case ',': token = CPP_COMMA; goto char1;
5782 case ';': token = CPP_SEMICOLON; goto char1;
5788 pfile->only_seen_white = 0;
5789 cppReader_putChar (pfile, c);
5798 /* Parse an identifier starting with C. */
5801 parse_name (cppReader *pfile, int c)
5807 if (c == '\\' && cppReader_peekC (pfile) == '\n')
5809 cppReader_forward (pfile, 2);
5813 cppReader_forward (pfile, -1);
5817 if (c == '$' && cppReader_isPedantic (pfile))
5819 cppReader_pedwarnLit (pfile,
5820 cstring_makeLiteralTemp ("`$' in identifier"));
5823 cppReader_reserve(pfile, 2); /* One more for final NUL. */
5824 cppReader_putCharQ (pfile, c);
5825 c = cppReader_getC (pfile);
5831 cppReader_nullTerminateQ (pfile);
5834 /* The file_name_map structure holds a mapping of file names for a
5835 particular directory. This mapping is read from the file named
5836 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
5837 map filenames on a file system with severe filename restrictions,
5838 such as DOS. The format of the file name map file is just a series
5839 of lines with two tokens on each line. The first token is the name
5840 to map, and the second token is the actual name to use. */
5842 struct file_name_map
5844 struct file_name_map *map_next;
5849 /*@constant observer char *FILE_NAME_MAP_FILE*/
5850 #define FILE_NAME_MAP_FILE "header.gcc"
5852 /* Read a space delimited string of unlimited length from a stdio
5855 static cstring read_filename_string (int ch, /*@open@*/ FILE *f)
5861 set = alloc = dmalloc (len + 1);
5866 while ((ch = getc (f)) != EOF && ! is_space[ch])
5868 if (set - alloc == size_toInt (len))
5871 alloc = drealloc (alloc, len + 1);
5872 set = alloc + len / 2;
5873 /*@-branchstate@*/ }
5876 } /*@=branchstate@*/
5879 check (ungetc (ch, f) != EOF);
5881 return cstring_fromChars (alloc);
5884 /* This structure holds a linked list of file name maps, one per directory. */
5886 struct file_name_map_list
5888 struct file_name_map_list *map_list_next;
5889 cstring map_list_name;
5890 struct file_name_map *map_list_map;
5893 /* Read the file name map file for DIRNAME. */
5895 static struct file_name_map *
5896 read_name_map (cppReader *pfile, cstring dirname)
5898 struct file_name_map_list *map_list_ptr;
5902 for (map_list_ptr = CPPOPTIONS (pfile)->map_list;
5903 map_list_ptr != NULL;
5904 map_list_ptr = map_list_ptr->map_list_next)
5906 if (cstring_equal (map_list_ptr->map_list_name, dirname))
5908 return map_list_ptr->map_list_map;
5912 map_list_ptr = (struct file_name_map_list *) dmalloc (sizeof (*map_list_ptr));
5913 map_list_ptr->map_list_name = cstring_copy (dirname);
5914 map_list_ptr->map_list_map = NULL;
5916 name = cstring_copy (dirname);
5918 if (cstring_length (dirname) > 0)
5920 name = cstring_appendChar (name, CONNECTCHAR);
5923 name = cstring_concatFree1 (name, cstring_makeLiteralTemp (FILE_NAME_MAP_FILE));
5925 f = fopen (cstring_toCharsSafe (name), "r");
5926 cstring_free (name);
5930 map_list_ptr->map_list_map = NULL;
5936 while ((ch = getc (f)) != EOF)
5939 struct file_name_map *ptr;
5946 from = read_filename_string (ch, f);
5947 while ((ch = getc (f)) != EOF && is_hor_space[ch])
5952 to = read_filename_string (ch, f);
5954 ptr = (struct file_name_map *) dmalloc (sizeof (*ptr));
5955 ptr->map_from = from;
5957 /* Make the real filename absolute. */
5958 if (cstring_length (to) > 1
5959 && osd_isConnectChar (cstring_firstChar (to)))
5965 ptr->map_to = cstring_copy (dirname);
5966 ptr->map_to = cstring_appendChar (ptr->map_to, CONNECTCHAR);
5967 ptr->map_to = cstring_concatFree (ptr->map_to, to);
5970 ptr->map_next = map_list_ptr->map_list_map;
5971 map_list_ptr->map_list_map = ptr;
5973 while ((ch = getc (f)) != '\n')
5977 /*@innerbreak@*/ break;
5982 assertSet (map_list_ptr->map_list_map);
5983 check (fclose (f) == 0);
5986 map_list_ptr->map_list_next = pfile->opts->map_list;
5987 pfile->opts->map_list = map_list_ptr;
5989 return map_list_ptr->map_list_map;
5992 /* Try to open include file FILENAME. SEARCHPTR is the directory
5993 being tried from the include file search path. This function maps
5994 filenames on file systems based on information read by
5998 open_include_file (cppReader *pfile,
6000 struct file_name_list *searchptr)
6002 char *filename = cstring_toCharsSafe (fname);
6003 struct file_name_map *map;
6007 cstring_markOwned (fname);
6009 cpp_setLocation (pfile);
6011 if (context_getFlag (FLG_NEVERINCLUDE))
6013 if (isHeaderFile (fname))
6015 return SKIP_INCLUDE;
6019 if ((searchptr != NULL) && ! searchptr->got_name_map)
6021 searchptr->name_map = read_name_map (pfile,
6022 !cstring_isEmpty (searchptr->fname)
6023 ? searchptr->fname :
6024 cstring_makeLiteralTemp ("."));
6025 searchptr->got_name_map = 1;
6028 /* First check the mapping for the directory we are using. */
6030 if ((searchptr != NULL)
6031 && (searchptr->name_map != NULL))
6035 if (!cstring_isEmpty (searchptr->fname))
6037 from += cstring_length (searchptr->fname) + 1;
6040 for (map = searchptr->name_map;
6042 map = map->map_next)
6044 if (cstring_equal (map->map_from, cstring_fromChars (from)))
6047 ** Found a match. Check if the file should be skipped
6050 if (cpp_skipIncludeFile (map->map_to))
6052 return SKIP_INCLUDE;
6056 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
6063 ** Try to find a mapping file for the particular directory we are
6064 ** looking in. Thus #include <sys/types.h> will look up sys/types.h
6065 ** in /usr/include/header.gcc and look up types.h in
6066 ** /usr/include/sys/header.gcc.
6069 p = strrchr (filename, CONNECTCHAR);
6076 if ((searchptr != NULL)
6077 && (cstring_isDefined (searchptr->fname))
6078 && (cstring_length (searchptr->fname) == p - filename)
6079 && !strncmp (cstring_toCharsSafe (searchptr->fname),
6081 size_fromInt (p - filename)))
6083 /* filename is in SEARCHPTR, which we've already checked. */
6085 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
6087 return SKIP_INCLUDE;
6091 return cpp_openIncludeFile (filename);
6097 dir = mstring_copy (".");
6102 dir = (char *) dmalloc (size_fromInt (p - filename + 1));
6103 memcpy (dir, filename, size_fromInt (p - filename));
6104 dir[p - filename] = '\0';
6108 for (map = read_name_map (pfile, cstring_fromChars (dir));
6110 map = map->map_next)
6112 if (cstring_equal (map->map_from, cstring_fromChars (from)))
6116 if (cpp_skipIncludeFile (map->map_to))
6118 return SKIP_INCLUDE;
6122 return cpp_openIncludeFile (cstring_toCharsSafe (map->map_to));
6129 if (cpp_skipIncludeFile (cstring_fromChars (filename)))
6131 return SKIP_INCLUDE;
6135 return cpp_openIncludeFile (filename);
6139 /* Process the contents of include file FNAME, already open on descriptor F,
6141 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
6142 "system" include directories (as decided by the `is_system_include'
6144 DIRPTR is the link in the dir path through which this file was found,
6145 or 0 if the file name was absolute or via the current directory.
6146 Return 1 on success, 0 on failure.
6148 The caller is responsible for the cppReader_pushBuffer. */
6151 finclude (cppReader *pfile, int f,
6153 bool system_header_p,
6154 /*@dependent@*/ struct file_name_list *dirptr)
6160 cppBuffer *fp; /* For input stack frame */
6162 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
6164 cppReader_perrorWithName (pfile, fname);
6165 check (close (f) == 0);
6166 (void) cppReader_popBuffer (pfile);
6172 fp = cppReader_getBuffer (pfile);
6174 /*@-temptrans@*/ /* fname shouldn't really be temp */
6175 fp->nominal_fname = fp->fname = fname;
6179 fp->system_header_p = system_header_p;
6182 fp->cleanup = cppReader_fileCleanup;
6184 if (S_ISREG (st_mode))
6187 fp->buf = (char *) dmalloc (st_size + 2);
6188 fp->alimit = fp->buf + st_size + 2;
6191 /* Read the file contents, knowing that st_size is an upper bound
6192 on the number of bytes we can read. */
6193 length = safe_read (f, fp->buf, size_toInt (st_size));
6194 fp->rlimit = fp->buf + length;
6195 if (length < 0) goto nope;
6197 else if (S_ISDIR (st_mode))
6199 cppReader_error (pfile,
6200 message ("Directory specified in #include: %s", fname));
6201 check (close (f) == 0);
6207 ** Cannot count its file size before reading.
6208 ** First read the entire file into heap and
6209 ** copy them into buffer on stack.
6212 size_t bsize = 2000;
6217 fp->buf = (char *) dmalloc (bsize + 2);
6220 i = safe_read (f, fp->buf + st_size, size_toInt (bsize - st_size));
6223 goto nope; /* error! */
6226 if (st_size != bsize)
6228 break; /* End of file */
6232 fp->buf = (char *) drealloc (fp->buf, bsize + 2);
6236 length = size_toInt (st_size);
6239 if ((length > 0 && fp->buf[length - 1] != '\n')
6240 /* Backslash-newline at end is not good enough. */
6241 || (length > 1 && fp->buf[length - 2] == '\\')) {
6242 fp->buf[length++] = '\n';
6245 fp->buf[length] = '\0';
6246 fp->rlimit = fp->buf + length;
6248 /* Close descriptor now, so nesting does not use lots of descriptors. */
6249 check (close (f) == 0);
6251 /* Must do this before calling trigraph_pcp, so that the correct file name
6252 will be printed in warning messages. */
6254 pfile->input_stack_listing_current = 0;
6259 cppReader_perrorWithName (pfile, fname);
6260 check (close (f) == 0);
6266 cppReader_init (cppReader *pfile)
6268 memset ((char *) pfile, 0, sizeof (*pfile));
6270 pfile->get_token = cppGetToken;
6271 pfile->token_buffer_size = 200;
6272 pfile->token_buffer = (char *) dmalloc (pfile->token_buffer_size);
6273 pfile->all_include_files = NULL;
6277 cppReader_setWritten (pfile, 0);
6279 pfile->system_include_depth = 0;
6280 pfile->max_include_len = 0;
6281 pfile->timebuf = NULL;
6282 pfile->only_seen_white = 1;
6284 pfile->buffer = cppReader_nullBuffer (pfile);
6288 cppReader_finish (/*@unused@*/ cppReader *pfile)
6293 /* Free resources used by PFILE.
6294 This is the cppReader 'finalizer' or 'destructor' (in C++ terminology). */
6297 cppCleanup (cppReader *pfile)
6299 while (CPPBUFFER (pfile) != cppReader_nullBuffer (pfile))
6301 (void) cppReader_popBuffer (pfile);
6304 if (pfile->token_buffer != NULL)
6306 sfree (pfile->token_buffer);
6307 pfile->token_buffer = NULL;
6310 while (pfile->if_stack != NULL)
6312 cppIfStackFrame *temp = pfile->if_stack;
6313 pfile->if_stack = temp->next;
6317 while (pfile->all_include_files != NULL)
6319 struct file_name_list *temp = pfile->all_include_files;
6320 pfile->all_include_files = temp->next;
6321 /*@-dependenttrans@*/
6322 cstring_free (temp->fname);
6323 /*@=dependenttrans@*/
6327 cppReader_hashCleanup ();
6331 ** Get the file-mode and data size of the file open on FD
6332 ** and store them in *MODE_POINTER and *SIZE_POINTER.
6336 file_size_and_mode (int fd, mode_t *mode_pointer, size_t *size_pointer)
6340 if (fstat (fd, &sbuf) < 0) {
6344 if (mode_pointer != NULL)
6346 *mode_pointer = sbuf.st_mode;
6349 if (size_pointer != NULL)
6351 *size_pointer = (size_t) sbuf.st_size;
6357 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
6358 retrying if necessary. Return a negative value if an error occurs,
6359 otherwise return the actual number of bytes read,
6360 which must be LEN unless end-of-file was reached. */
6362 static int safe_read (int desc, char *ptr, int len)
6368 # if defined (WIN32) || defined (OS2) && defined (__IBMC__)
6369 /*@-compdef@*/ /* ptr is an out parameter */
6370 int nchars = _read (desc, ptr, (unsigned) left);
6373 ssize_t nchars = read (desc, ptr, size_fromInt (left));
6382 return (int) nchars;
6396 /* Initialize PMARK to remember the current position of PFILE. */
6399 parseSetMark (struct parse_marker *pmark, cppReader *pfile)
6401 cppBuffer *pbuf = cppReader_getBuffer (pfile);
6403 pmark->next = pbuf->marks;
6405 pbuf->marks = pmark;
6409 pmark->position = pbuf->cur - pbuf->buf;
6412 /* Cleanup PMARK - we no longer need it. */
6414 void parseClearMark (struct parse_marker *pmark)
6416 struct parse_marker **pp = &pmark->buf->marks;
6418 for (; ; pp = &(*pp)->next)
6420 llassert (*pp != NULL);
6421 if (*pp == pmark) break;
6427 /* Backup the current position of PFILE to that saved in PMARK. */
6430 parseGotoMark (struct parse_marker *pmark, cppReader *pfile)
6432 cppBuffer *pbuf = cppReader_getBuffer (pfile);
6434 if (pbuf != pmark->buf)
6436 cpp_setLocation (pfile);
6437 llfatalbug (cstring_makeLiteral ("Internal error parseGotoMark"));
6440 llassert (pbuf->buf != NULL);
6441 pbuf->cur = pbuf->buf + pmark->position;
6444 /* Reset PMARK to point to the current position of PFILE. (Same
6445 as parseClearMark (PMARK), parseSetMark (PMARK, PFILE) but faster. */
6448 parseMoveMark (struct parse_marker *pmark, cppReader *pfile)
6450 cppBuffer *pbuf = cppReader_getBuffer (pfile);
6452 if (pbuf != pmark->buf)
6454 cpp_setLocation (pfile);
6455 llfatalerror (cstring_makeLiteral ("Internal error parseMoveMark"));
6458 pmark->position = pbuf->cur - pbuf->buf;
6461 void cppReader_initializeReader (cppReader *pfile) /* Must be done after library is loaded. */
6463 struct cppOptions *opts = CPPOPTIONS (pfile);
6466 /* The code looks at the defaults through this pointer, rather than through
6467 the constant structure above. This pointer gets changed if an environment
6468 variable specifies other defaults. */
6470 struct default_include *include_defaults = include_defaults_array;
6472 /* Add dirs from CPATH after dirs from -I. */
6473 /* There seems to be confusion about what CPATH should do,
6474 so for the moment it is not documented. */
6475 /* Some people say that CPATH should replace the standard include dirs,
6476 but that seems pointless: it comes before them, so it overrides them
6479 xp = (char *) getenv ("CPATH");
6481 if (xp != 0 && ! opts->no_standard_includes)
6483 path_include (pfile, xp);
6486 /* Now that dollars_in_ident is known, initialize is_idchar. */
6487 initialize_char_syntax (opts);
6489 /* CppReader_Install __LINE__, etc. Must follow initialize_char_syntax
6490 and option processing. */
6492 initialize_builtins (pfile);
6494 /* Do standard #defines and assertions
6495 that identify system and machine type. */
6497 if (!opts->inhibit_predefs) {
6498 char *p = (char *) dmalloc (strlen (predefs) + 1);
6499 strcpy (p, predefs);
6505 while (*p == ' ' || *p == '\t')
6510 /* Handle -D options. */
6511 if (p[0] == '-' && p[1] == 'D')
6515 while (*p && *p != ' ' && *p != '\t')
6525 if (opts->debug_output)
6527 output_line_command (pfile, 0, same_file);
6530 cppReader_define (pfile, q);
6532 while (*p == ' ' || *p == '\t')
6546 opts->done_initializing = 1;
6548 { /* Read the appropriate environment variable and if it exists
6549 replace include_defaults with the listed path. */
6553 int win32_buf_size = 0; /* memory we need to allocate */
6556 if (opts->cplusplus)
6558 epath = getenv ("CPLUS_INCLUDE_PATH");
6562 epath = getenv ("C_INCLUDE_PATH");
6566 ** If the environment var for this language is set,
6567 ** add to the default list of include directories.
6570 if (epath != NULL) {
6571 char *nstore = (char *) dmalloc (strlen (epath) + 2);
6573 char *startp, *endp;
6576 /* if we have a posix path list, convert to win32 path list */
6577 if (cygwin32_posix_path_list_p (epath))
6579 win32_buf_size = cygwin32_posix_to_win32_path_list_buf_size (epath);
6580 win32epath = (char *) dmalloc /*@i4@*/ (win32_buf_size);
6581 cygwin32_posix_to_win32_path_list (epath, win32epath);
6585 for (num_dirs = 1, startp = epath; *startp; startp++)
6587 if (*startp == PATH_SEPARATOR)
6593 = (struct default_include *) dmalloc ((num_dirs
6594 * sizeof (struct default_include))
6595 + sizeof (include_defaults_array));
6598 startp = endp = epath;
6601 /* Handle cases like c:/usr/lib:d:/gcc/lib */
6602 if ((*endp == PATH_SEPARATOR) || *endp == 0)
6604 strncpy (nstore, startp, size_fromInt (endp - startp));
6607 strcpy (nstore, ".");
6611 nstore[endp-startp] = '\0';
6614 include_defaults[num_dirs].fname = cstring_fromCharsNew (nstore);
6615 include_defaults[num_dirs].cplusplus = opts->cplusplus;
6616 include_defaults[num_dirs].cxx_aware = 1;
6623 endp = startp = endp + 1;
6630 /* Put the usual defaults back in at the end. */
6631 memcpy ((char *) &include_defaults[num_dirs],
6632 (char *) include_defaults_array,
6633 sizeof (include_defaults_array));
6636 /*@-branchstate@*/ } /*@=branchstate@*/
6639 cppReader_appendIncludeChain (pfile, opts->before_system,
6640 opts->last_before_system);
6641 opts->first_system_include = opts->before_system;
6643 /* Unless -fnostdinc,
6644 tack on the standard include file dirs to the specified list */
6645 if (!opts->no_standard_includes) {
6646 struct default_include *p = include_defaults;
6647 char *specd_prefix = opts->include_prefix;
6648 char *default_prefix = mstring_copy (GCC_INCLUDE_DIR);
6649 int default_len = 0;
6651 /* Remove the `include' from /usr/local/lib/gcc.../include. */
6652 if (default_prefix != NULL) {
6653 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
6654 default_len = strlen (default_prefix) - 7;
6655 default_prefix[default_len] = 0;
6659 /* Search "translated" versions of GNU directories.
6660 These have /usr/local/lib/gcc... replaced by specd_prefix. */
6661 if (specd_prefix != 0 && default_len != 0)
6662 for (p = include_defaults; p->fname != NULL; p++) {
6663 /* Some standard dirs are only for C++. */
6665 || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
6666 /* Does this dir start with the prefix? */
6667 if (!strncmp (cstring_toCharsSafe (p->fname), default_prefix,
6668 size_fromInt (default_len)))
6670 /* Yes; change prefix and add to search list. */
6671 struct file_name_list *nlist
6672 = (struct file_name_list *) dmalloc (sizeof (*nlist));
6673 size_t this_len = strlen (specd_prefix) + cstring_length (p->fname) - default_len;
6674 char *str = (char *) dmalloc (this_len + 1);
6675 strcpy (str, specd_prefix);
6676 strcat (str, cstring_toCharsSafe (p->fname) + default_len);
6679 nlist->fname = cstring_fromChars (str);
6680 nlist->control_macro = 0;
6681 nlist->c_system_include_path = !p->cxx_aware;
6682 nlist->got_name_map = 0;
6684 cppReader_addIncludeChain (pfile, nlist);
6685 if (opts->first_system_include == 0)
6687 opts->first_system_include = nlist;
6693 /* Search ordinary names for GNU include directories. */
6695 for (p = include_defaults; p->fname != NULL; p++)
6697 /* Some standard dirs are only for C++. */
6699 || (opts->cplusplus && !opts->no_standard_cplusplus_includes))
6701 struct file_name_list *nlist
6702 = (struct file_name_list *) dmalloc (sizeof (*nlist));
6703 nlist->control_macro = 0;
6704 nlist->c_system_include_path = !p->cxx_aware;
6705 nlist->fname = p->fname;
6706 nlist->got_name_map = 0;
6709 cppReader_addIncludeChain (pfile, nlist);
6711 if (opts->first_system_include == 0)
6713 opts->first_system_include = nlist;
6717 sfree (default_prefix);
6720 /* Tack the after_include chain at the end of the include chain. */
6721 cppReader_appendIncludeChain (pfile, opts->after_include,
6722 opts->last_after_include);
6724 if (opts->first_system_include == 0)
6726 opts->first_system_include = opts->after_include;
6729 /* With -v, print the list of dirs to search. */
6730 if (opts->verbose) {
6731 struct file_name_list *p;
6732 fprintf (stderr, "#include \"...\" search starts here:\n");
6734 for (p = opts->include; p != NULL; p = p->next) {
6735 if (p == opts->first_bracket_include)
6736 fprintf (stderr, "#include <...> search starts here:\n");
6738 fprintf (stderr, " %s\n", cstring_toCharsSafe (p->fname));
6740 fprintf (stderr, "End of search list.\n");
6744 int cppReader_startProcess (cppReader *pfile, cstring fname)
6748 struct cppOptions *opts = CPPOPTIONS (pfile);
6750 fp = cppReader_pushBuffer (pfile, NULL, 0);
6757 if (opts->in_fname == NULL)
6759 opts->in_fname = cstring_makeLiteralTemp ("");
6762 fp->fname = opts->in_fname;
6763 fp->nominal_fname = fp->fname;
6766 /* Copy the entire contents of the main input file into
6767 the stacked input buffer previously allocated for it. */
6769 if (cstring_isEmpty (fname))
6771 fname = cstring_makeLiteralTemp ("");
6774 else if ((f = open (cstring_toCharsSafe (fname), O_RDONLY, 0666)) < 0)
6776 cppReader_error (pfile,
6777 message ("Error opening %s for reading: %s",
6778 fname, lldecodeerror (errno)));
6787 if (finclude (pfile, f, fname, 0, NULL))
6789 output_line_command (pfile, 0, same_file);
6795 static /*@exposed@*/ /*@null@*/ cppBuffer *cppReader_getBuffer (cppReader *pfile)
6797 return pfile->buffer;
6800 /*@exposed@*/ cppBuffer *cppReader_getBufferSafe (cppReader *pfile)
6802 llassert (pfile->buffer != NULL);
6803 return pfile->buffer;
6806 /*@exposed@*/ char *cppLineBase (cppBuffer *buf)
6808 llassert (buf->buf != NULL);
6809 return (buf->buf + buf->line_base);
6812 int cppBufPeek (cppBuffer *buf)
6814 if (buf->cur == NULL || buf->rlimit == NULL) {
6818 if (buf->cur < buf->rlimit) {
6825 bool cppBuffer_isMacro (cppBuffer *buf)
6829 return (buf->cleanup == cppReader_macroCleanup);
6836 ** Returns true if the macro should be checked, false
6837 ** if it should be expanded normally.
6840 static bool notparseable = FALSE; /* preceeded by @notparseable@ */
6841 static bool notfunction = FALSE; /* preceeded by @notfunction@ */
6842 static bool expectiter = FALSE; /* preceeded by @iter@ */
6843 static bool expectenditer = FALSE; /* second after @iter@ */
6844 static bool expectfunction = FALSE; /* preceeded by @function@ */
6845 static bool expectconstant = FALSE; /* preceeded by @constant@ */
6846 static bool expectmacro = FALSE; /* preceeded by notfunction or notparseable */
6848 static void cpp_setLocation (cppReader *pfile)
6853 if (pfile->buffer != NULL)
6855 if (cstring_isDefined (cppReader_getBuffer (pfile)->nominal_fname))
6857 cstring fname = cppReader_getBuffer (pfile)->nominal_fname;
6859 DPRINTF (("Looking up: %s", fname));
6861 if (fileTable_exists (context_fileTable (), fname))
6863 fid = fileTable_lookup (context_fileTable (), fname);
6867 DPRINTF (("Trying %s", cppReader_getBuffer (pfile)->fname));
6869 fid = fileTable_lookup (context_fileTable (),
6870 cppReader_getBuffer (pfile)->fname);
6875 fid = fileTable_lookup (context_fileTable (),
6876 cppReader_getBuffer (pfile)->fname);
6879 line = cppReader_getBuffer (pfile)->lineno;
6880 fileloc_free (g_currentloc);
6883 if (fileId_isValid (fid))
6885 g_currentloc = fileloc_create (fid, line, 1);
6889 g_currentloc = fileloc_createBuiltin ();
6894 fileloc_free (g_currentloc);
6895 g_currentloc = fileloc_createBuiltin ();
6899 static bool cpp_shouldCheckMacro (cppReader *pfile, char *p) /*@*/
6901 bool checkmacro = FALSE;
6902 bool hasParams = FALSE;
6903 bool noexpand = FALSE;
6907 cpp_setLocation (pfile);
6909 DPRINTF (("Should check macro? %s", p));
6911 if (expectiter || expectconstant || expectenditer)
6916 expectenditer = TRUE;
6921 expectconstant = FALSE;
6922 expectenditer = FALSE;
6925 if (notfunction || notparseable)
6927 notfunction = FALSE;
6928 notparseable = FALSE;
6937 llassert (*p == '#');
6940 while (*p == ' ' || *p == '\t')
6945 llassert (*p == 'd'); /* define starts */
6949 while (*p == ' ' || *p == '\t')
6954 sname = cstring_fromChars (p);
6955 DPRINTF (("Check macro: %s", sname));
6957 while (((c = *p) != ' ')
6958 && c != '\0' && c != '('
6959 && c != '\t' && c != '\\' && c != '\n'
6965 hasParams = (c == '(');
6971 notparseable = FALSE;
6973 else if (notfunction || fileloc_isStandardLib (g_currentloc))
6975 DPRINTF (("Clear notfunction"));
6976 notfunction = FALSE;
6991 if (usymtab_existsReal (sname))
6993 uentry ue = usymtab_lookup (sname);
6995 DPRINTF (("Lookup macro: %s", uentry_unparse (ue)));
6997 if (fileloc_isPreproc (uentry_whereLast (ue)))
7003 if (uentry_isSpecified (ue))
7005 checkmacro = context_getFlag (FLG_SPECMACROS);
7011 checkmacro = context_getFlag (FLG_LIBMACROS)
7012 || context_getFlag (FLG_FCNMACROS);
7020 DPRINTF (("Macro doesn't exist: %s", bool_unparse (checkmacro)));
7022 if (fileloc_isSystemFile (g_currentloc)
7023 && context_getFlag (FLG_SYSTEMDIREXPAND))
7025 ; /* don't check this macro */
7026 DPRINTF (("Don't check 1"));
7034 DPRINTF (("Has params..."));
7036 if (context_getFlag (FLG_FCNMACROS))
7038 if (usymtab_exists (sname))
7041 ** only get here is macro is redefined
7042 ** error reported elsewhere
7045 DPRINTF (("It exists!"));
7050 ** We make it a forward function, since it might be declared elsewhere.
7051 ** After all headers have been processed, we should check the forward
7055 fileloc loc = fileloc_makePreproc (g_currentloc);
7057 /* the line is off-by-one, since the newline was already read */
7062 expectfunction = FALSE;
7065 le = uentry_makeForwardFunction (sname,
7066 typeId_invalid, loc);
7072 /* Do not define here! */
7074 (void) usymtab_addEntry (le);
7078 DPRINTF (("Check: TRUE"));
7082 DPRINTF (("Flag FCN_MACROS not set!"));
7087 DPRINTF (("No params"));
7089 if (context_getFlag (FLG_CONSTMACROS))
7091 bool nocontent = FALSE;
7104 ** Check if there is nothing after the define.
7107 while ((*rest) != '\0' && isspace (*rest))
7114 nocontent = TRUE; /* empty macro, don't check */
7119 if (usymtab_exists (sname))
7125 fileloc loc = fileloc_makePreproc (g_currentloc);
7126 DPRINTF (("Make constant: %s", sname));
7127 le = uentry_makeConstant (sname,
7128 ctype_unknown, loc);
7129 (void) usymtab_addEntry (le);
7132 checkmacro = !nocontent;
7137 if (checkmacro && usymtab_existsType (sname))
7139 DPRINTF (("Making false..."));
7141 ppllerror (message ("Specified type implemented as macro: %s", sname));
7151 if (usymtab_exists (sname))
7153 uentry ue = usymtab_lookupExpose (sname);
7154 fileloc tloc = fileloc_makePreproc (g_currentloc);
7156 uentry_setDefined (ue, tloc);
7157 fileloc_free (tloc);
7158 uentry_setUsed (ue, fileloc_undefined);
7162 fileloc tloc = fileloc_makePreproc (g_currentloc);
7163 uentry ue = uentry_makeExpandedMacro (sname, tloc);
7164 DPRINTF (("Make expanded macro: %s", sname));
7165 DPRINTF (("Not in symbol table: %s", sname));
7167 (void) usymtab_addGlobalEntry (ue);
7168 fileloc_free (tloc);
7173 DPRINTF (("Returning: %s", bool_unparse (checkmacro)));
7177 static enum cpp_token
7178 cpp_handleComment (cppReader *pfile, struct parse_marker *smark)
7180 cppBuffer *pbuf = cppReader_getBuffer (pfile);
7183 bool eliminateComment = FALSE;
7185 llassert (pbuf->buf != NULL);
7187 start = pbuf->buf + smark->position;
7189 llassert (pbuf->cur != NULL);
7190 len = pbuf->cur - start;
7193 && start[1] == context_getCommentMarkerChar ())
7197 char *scomment = start + 2;
7199 start[0] = BEFORE_COMMENT_MARKER[0];
7200 start[1] = BEFORE_COMMENT_MARKER[1];
7202 llassert (start[len - 2] == '*');
7203 start[len - 2] = AFTER_COMMENT_MARKER[0];
7205 llassert (start[len - 1] == '/');
7206 start[len - 1] = AFTER_COMMENT_MARKER[1];
7208 cppReader_reserve(pfile, size_fromInt (1 + len));
7209 cppReader_putCharQ (pfile, c);
7211 cpp_setLocation (pfile);
7213 if (mstring_equalPrefix (scomment, "ignore"))
7215 if (!context_getFlag (FLG_NOCOMMENTS))
7217 context_enterSuppressRegion ();
7220 else if (mstring_equalPrefix (scomment, "end"))
7222 if (!context_getFlag (FLG_NOCOMMENTS))
7224 context_exitSuppressRegion ();
7227 else if (mstring_equalPrefix (scomment, "notparseable"))
7229 notparseable = TRUE;
7231 eliminateComment = TRUE;
7233 else if (mstring_equalPrefix (scomment, "notfunction"))
7237 eliminateComment = TRUE;
7239 else if (mstring_equalPrefix (scomment, "iter"))
7243 else if (mstring_equalPrefix (scomment, "function"))
7245 expectfunction = TRUE;
7247 else if (mstring_equalPrefix (scomment, "constant"))
7249 expectconstant = TRUE;
7253 char sChar = *scomment;
7259 char *rest = scomment + 1;
7261 if (mstring_equalPrefix (rest, "commentchar"))
7263 eliminateComment = TRUE;
7267 ppllerror (cstring_makeLiteral
7268 ("Cannot restore commentchar"));
7272 char *next = scomment + 12; /* strlen commentchar = 12 */
7274 if (*next != ' ' && *next != '\t' && *next != '\n')
7278 ("Syntactic commentchar comment is not followed by a "
7279 "whitespace character: %c",
7284 char cchar = *(next + 1);
7289 (cstring_makeLiteral
7290 ("Cannot set commentchar to NUL"));
7294 context_setCommentMarkerChar (cchar);
7295 /* setComment = TRUE; */
7300 else if (mstring_equalPrefix (scomment, "nestcomment"))
7302 /* fix from Mike Miller <MikeM@xata.com> */
7303 context_fileSetFlag (FLG_NESTCOMMENT,
7304 ynm_fromCodeChar (sChar));
7306 else if (mstring_equalPrefix (rest, "namechecks"))
7308 context_fileSetFlag (FLG_NAMECHECKS,
7309 ynm_fromCodeChar (sChar));
7311 else if (mstring_equalPrefix (rest, "macroredef"))
7313 context_fileSetFlag (FLG_MACROREDEF,
7314 ynm_fromCodeChar (sChar));
7316 else if (mstring_equalPrefix (rest, "usevarargs"))
7318 context_fileSetFlag (FLG_USEVARARGS,
7319 ynm_fromCodeChar (sChar));
7321 else if (mstring_equalPrefix (rest, "nextlinemacros"))
7323 context_fileSetFlag (FLG_MACRONEXTLINE,
7324 ynm_fromCodeChar (sChar));
7326 else if (mstring_equalPrefix (rest, "allmacros")
7327 || mstring_equalPrefix (rest, "fcnmacros")
7328 || mstring_equalPrefix (rest, "constmacros"))
7332 if (mstring_equalPrefix (rest, "allmacros"))
7336 else if (mstring_equalPrefix (rest, "fcnmacros"))
7342 llassert (mstring_equalPrefix (rest, "constmacros"));
7343 fl = FLG_CONSTMACROS;
7347 context_fileSetFlag (fl, ynm_fromCodeChar (sChar));
7348 notfunction = FALSE;
7361 if (eliminateComment)
7366 /* Replaces comment char's in start with spaces */
7368 for (i = 2; i < len - 2; i++)
7370 if (start[i] == BEFORE_COMMENT_MARKER[0]
7371 || start[i] == BEFORE_COMMENT_MARKER[1]
7372 || start[i] == context_getCommentMarkerChar ())
7378 cppReader_putStrN (pfile, start, size_fromInt (len));
7379 parseClearMark (smark);
7389 ** Output the comment as all spaces so line/column
7390 ** in output file is still correct.
7394 cstring lintcomment = cstring_undefined;
7396 if (context_getFlag (FLG_LINTCOMMENTS))
7398 if (mstring_equalPrefix (start, "*NOTREACHED*/"))
7400 lintcomment = cstring_makeLiteralTemp ("l_notreach");
7402 else if (mstring_equalPrefix (start, "*PRINTFLIKE*/"))
7404 lintcomment = cstring_makeLiteralTemp ("l_printfli");
7406 else if (mstring_equalPrefix (start, "*FALLTHROUGH*/"))
7408 lintcomment = cstring_makeLiteralTemp ("l_fallthrou");
7410 else if (mstring_equalPrefix (start, "*ARGSUSED*/"))
7412 lintcomment = cstring_makeLiteralTemp ("l_argsus");
7414 else if (mstring_equalPrefix (start, "*FALLTHRU*/"))
7416 lintcomment = cstring_makeLiteralTemp ("l_fallth");
7420 lintcomment = cstring_undefined;
7425 lintcomment = cstring_undefined;
7428 if (cstring_isDefined (lintcomment))
7430 c = BEFORE_COMMENT_MARKER[0];
7431 start[0] = BEFORE_COMMENT_MARKER[1];
7433 llassert (cstring_length (lintcomment) == len - 3);
7435 for (i = 1; i < len - 2; i++)
7437 start[i] = cstring_getChar (lintcomment, i);
7440 start[len - 2] = AFTER_COMMENT_MARKER[0];
7441 start[len - 1] = AFTER_COMMENT_MARKER[1];
7445 /* Replaces char's in start with spaces */
7446 for (i = 0; i < len; i++)
7450 && start[i + 1] == '*') {
7451 /*@i32 make vgenopterror work in cpp... @*/
7452 if (context_getFlag (FLG_NESTCOMMENT))
7456 message ("Comment starts inside comment"));
7460 if (start[i] != '\n')
7467 cppReader_reserve (pfile, size_fromInt (1 + len));
7468 cppReader_putCharQ (pfile, c);
7469 cppReader_putStrN (pfile, start, size_fromInt (len));
7470 parseClearMark (smark);
7476 static int cpp_openIncludeFile (char *filename)
7478 int res = open (filename, O_RDONLY, 0666);
7482 if (!fileTable_exists (context_fileTable (),
7483 cstring_fromChars (filename)))
7485 (void) fileTable_addHeaderFile (context_fileTable (),
7486 cstring_fromChars (filename));
7490 DPRINTF (("File already exists: %s", filename));
7498 static bool cpp_skipIncludeFile (cstring fname)
7500 if (context_isSystemDir (fname))
7502 DPRINTF (("System dir: %s", fname));
7504 if (lcllib_isSkipHeader (fname))
7506 DPRINTF (("Skip include TRUE: %s", fname));
7510 if (context_getFlag (FLG_SKIPSYSHEADERS))
7512 DPRINTF (("Skip include TRUE: %s", fname));
7517 if (context_getFlag (FLG_SINGLEINCLUDE))
7519 fname = removePreDirs (fname);
7521 # if defined (WIN32) || defined (OS2)
7522 cstring_replaceAll (fname, '\\', '/');
7525 if (fileTable_exists (context_fileTable (), fname))
7527 DPRINTF (("Skip include TRUE: %s", fname));
7532 DPRINTF (("Skip include FALSE: %s", fname));
7536 static int cpp_peekN (cppReader *pfile, int n)
7538 cppBuffer *buf = cppReader_getBuffer (pfile);
7540 llassert (buf->cur != NULL);
7542 return (buf->rlimit - buf->cur >= (n)
7547 cppBuffer *cppBuffer_prevBuffer (cppBuffer *buf)
7552 void cppBuffer_forward (cppBuffer *buf, int n)
7554 llassert (buf->cur != NULL);