reverse a previous patch
[tinycc.git] / tccpp.c
blob7ec0d441188dc2a0945cb1153d8801674278ccb4
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 ST_DATA int tok_flags;
27 ST_DATA int parse_flags;
29 ST_DATA struct BufferedFile *file;
30 ST_DATA int ch, tok;
31 ST_DATA CValue tokc;
32 ST_DATA const int *macro_ptr;
33 ST_DATA CString tokcstr; /* current parsed string, if any */
35 /* display benchmark infos */
36 ST_DATA int total_lines;
37 ST_DATA int total_bytes;
38 ST_DATA int tok_ident;
39 ST_DATA TokenSym **table_ident;
41 /* ------------------------------------------------------------------------- */
43 static TokenSym *hash_ident[TOK_HASH_SIZE];
44 static char token_buf[STRING_MAX_SIZE + 1];
45 static unsigned char isidnum_table[256 - CH_EOF];
46 /* isidnum_table flags: */
47 #define IS_SPC 1
48 #define IS_ID 2
49 #define IS_NUM 4
51 static TokenString *macro_stack;
53 static const char tcc_keywords[] =
54 #define DEF(id, str) str "\0"
55 #include "tcctok.h"
56 #undef DEF
59 /* WARNING: the content of this string encodes token numbers */
60 static const unsigned char tok_two_chars[] =
61 /* outdated -- gr
62 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
63 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
64 */{
65 '<','=', TOK_LE,
66 '>','=', TOK_GE,
67 '!','=', TOK_NE,
68 '&','&', TOK_LAND,
69 '|','|', TOK_LOR,
70 '+','+', TOK_INC,
71 '-','-', TOK_DEC,
72 '=','=', TOK_EQ,
73 '<','<', TOK_SHL,
74 '>','>', TOK_SAR,
75 '+','=', TOK_A_ADD,
76 '-','=', TOK_A_SUB,
77 '*','=', TOK_A_MUL,
78 '/','=', TOK_A_DIV,
79 '%','=', TOK_A_MOD,
80 '&','=', TOK_A_AND,
81 '^','=', TOK_A_XOR,
82 '|','=', TOK_A_OR,
83 '-','>', TOK_ARROW,
84 '.','.', 0xa8, // C++ token ?
85 '#','#', TOK_TWOSHARPS,
89 static void next_nomacro_spc(void);
91 ST_FUNC void skip(int c)
93 if (tok != c)
94 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
95 next();
98 ST_FUNC void expect(const char *msg)
100 tcc_error("%s expected", msg);
103 ST_FUNC void begin_macro(TokenString *str, int alloc)
105 str->alloc = alloc;
106 str->prev = macro_stack;
107 str->prev_ptr = macro_ptr;
108 macro_ptr = str->str;
109 macro_stack = str;
112 ST_FUNC void end_macro(void)
114 TokenString *str = macro_stack;
115 macro_stack = str->prev;
116 macro_ptr = str->prev_ptr;
117 if (str->alloc == 2) {
118 str->alloc = 3; /* just mark as finished */
119 } else {
120 tok_str_free(str->str);
121 if (str->alloc == 1)
122 tcc_free(str);
126 /* ------------------------------------------------------------------------- */
127 /* CString handling */
128 static void cstr_realloc(CString *cstr, int new_size)
130 int size;
131 void *data;
133 size = cstr->size_allocated;
134 if (size == 0)
135 size = 8; /* no need to allocate a too small first string */
136 while (size < new_size)
137 size = size * 2;
138 data = tcc_realloc(cstr->data_allocated, size);
139 cstr->data_allocated = data;
140 cstr->size_allocated = size;
141 cstr->data = data;
144 /* add a byte */
145 ST_FUNC void cstr_ccat(CString *cstr, int ch)
147 int size;
148 size = cstr->size + 1;
149 if (size > cstr->size_allocated)
150 cstr_realloc(cstr, size);
151 ((unsigned char *)cstr->data)[size - 1] = ch;
152 cstr->size = size;
155 ST_FUNC void cstr_cat(CString *cstr, const char *str)
157 int c;
158 for(;;) {
159 c = *str;
160 if (c == '\0')
161 break;
162 cstr_ccat(cstr, c);
163 str++;
167 /* add a wide char */
168 ST_FUNC void cstr_wccat(CString *cstr, int ch)
170 int size;
171 size = cstr->size + sizeof(nwchar_t);
172 if (size > cstr->size_allocated)
173 cstr_realloc(cstr, size);
174 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
175 cstr->size = size;
178 ST_FUNC void cstr_new(CString *cstr)
180 memset(cstr, 0, sizeof(CString));
183 /* free string and reset it to NULL */
184 ST_FUNC void cstr_free(CString *cstr)
186 tcc_free(cstr->data_allocated);
187 cstr_new(cstr);
190 /* reset string to empty */
191 ST_FUNC void cstr_reset(CString *cstr)
193 cstr->size = 0;
196 /* XXX: unicode ? */
197 static void add_char(CString *cstr, int c)
199 if (c == '\'' || c == '\"' || c == '\\') {
200 /* XXX: could be more precise if char or string */
201 cstr_ccat(cstr, '\\');
203 if (c >= 32 && c <= 126) {
204 cstr_ccat(cstr, c);
205 } else {
206 cstr_ccat(cstr, '\\');
207 if (c == '\n') {
208 cstr_ccat(cstr, 'n');
209 } else {
210 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
211 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
212 cstr_ccat(cstr, '0' + (c & 7));
217 /* ------------------------------------------------------------------------- */
218 /* allocate a new token */
219 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
221 TokenSym *ts, **ptable;
222 int i;
224 if (tok_ident >= SYM_FIRST_ANOM)
225 tcc_error("memory full (symbols)");
227 /* expand token table if needed */
228 i = tok_ident - TOK_IDENT;
229 if ((i % TOK_ALLOC_INCR) == 0) {
230 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
231 table_ident = ptable;
234 ts = tcc_malloc(sizeof(TokenSym) + len);
235 table_ident[i] = ts;
236 ts->tok = tok_ident++;
237 ts->sym_define = NULL;
238 ts->sym_label = NULL;
239 ts->sym_struct = NULL;
240 ts->sym_identifier = NULL;
241 ts->len = len;
242 ts->hash_next = NULL;
243 memcpy(ts->str, str, len);
244 ts->str[len] = '\0';
245 *pts = ts;
246 return ts;
249 #define TOK_HASH_INIT 1
250 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
252 /* find a token and add it if not found */
253 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
255 TokenSym *ts, **pts;
256 int i;
257 unsigned int h;
259 h = TOK_HASH_INIT;
260 for(i=0;i<len;i++)
261 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
262 h &= (TOK_HASH_SIZE - 1);
264 pts = &hash_ident[h];
265 for(;;) {
266 ts = *pts;
267 if (!ts)
268 break;
269 if (ts->len == len && !memcmp(ts->str, str, len))
270 return ts;
271 pts = &(ts->hash_next);
273 return tok_alloc_new(pts, str, len);
276 /* XXX: buffer overflow */
277 /* XXX: float tokens */
278 ST_FUNC const char *get_tok_str(int v, CValue *cv)
280 static char buf[STRING_MAX_SIZE + 1];
281 static CString cstr_buf;
282 CString *cstr;
283 char *p;
284 int i, len;
286 /* NOTE: to go faster, we give a fixed buffer for small strings */
287 cstr_reset(&cstr_buf);
288 cstr_buf.data = buf;
289 cstr_buf.size_allocated = sizeof(buf);
290 p = buf;
292 switch(v) {
293 case TOK_CINT:
294 case TOK_CUINT:
295 /* XXX: not quite exact, but only useful for testing */
296 sprintf(p, "%u", cv->ui);
297 break;
298 case TOK_CLLONG:
299 case TOK_CULLONG:
300 /* XXX: not quite exact, but only useful for testing */
301 #ifdef _WIN32
302 sprintf(p, "%u", (unsigned)cv->ull);
303 #else
304 sprintf(p, "%llu", cv->ull);
305 #endif
306 break;
307 case TOK_LCHAR:
308 cstr_ccat(&cstr_buf, 'L');
309 case TOK_CCHAR:
310 cstr_ccat(&cstr_buf, '\'');
311 add_char(&cstr_buf, cv->i);
312 cstr_ccat(&cstr_buf, '\'');
313 cstr_ccat(&cstr_buf, '\0');
314 break;
315 case TOK_PPNUM:
316 case TOK_PPSTR:
317 return (char*)cv->cstr->data;
318 case TOK_LSTR:
319 cstr_ccat(&cstr_buf, 'L');
320 case TOK_STR:
321 cstr = cv->cstr;
322 cstr_ccat(&cstr_buf, '\"');
323 if (v == TOK_STR) {
324 len = cstr->size - 1;
325 for(i=0;i<len;i++)
326 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
327 } else {
328 len = (cstr->size / sizeof(nwchar_t)) - 1;
329 for(i=0;i<len;i++)
330 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
332 cstr_ccat(&cstr_buf, '\"');
333 cstr_ccat(&cstr_buf, '\0');
334 break;
336 case TOK_CFLOAT:
337 case TOK_CDOUBLE:
338 case TOK_CLDOUBLE:
339 case TOK_LINENUM:
340 return NULL; /* should not happen */
342 /* above tokens have value, the ones below don't */
344 case TOK_LT:
345 v = '<';
346 goto addv;
347 case TOK_GT:
348 v = '>';
349 goto addv;
350 case TOK_DOTS:
351 return strcpy(p, "...");
352 case TOK_A_SHL:
353 return strcpy(p, "<<=");
354 case TOK_A_SAR:
355 return strcpy(p, ">>=");
356 default:
357 if (v < TOK_IDENT) {
358 /* search in two bytes table */
359 const unsigned char *q = tok_two_chars;
360 while (*q) {
361 if (q[2] == v) {
362 *p++ = q[0];
363 *p++ = q[1];
364 *p = '\0';
365 return buf;
367 q += 3;
369 if (v >= 127) {
370 sprintf(buf, "<%02x>", v);
371 return buf;
373 addv:
374 *p++ = v;
375 *p = '\0';
376 } else if (v < tok_ident) {
377 return table_ident[v - TOK_IDENT]->str;
378 } else if (v >= SYM_FIRST_ANOM) {
379 /* special name for anonymous symbol */
380 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
381 } else {
382 /* should never happen */
383 return NULL;
385 break;
387 return cstr_buf.data;
390 /* return the current character, handling end of block if necessary
391 (but not stray) */
392 ST_FUNC int handle_eob(void)
394 BufferedFile *bf = file;
395 int len;
397 /* only tries to read if really end of buffer */
398 if (bf->buf_ptr >= bf->buf_end) {
399 if (bf->fd != -1) {
400 #if defined(PARSE_DEBUG)
401 len = 1;
402 #else
403 len = IO_BUF_SIZE;
404 #endif
405 len = read(bf->fd, bf->buffer, len);
406 if (len < 0)
407 len = 0;
408 } else {
409 len = 0;
411 total_bytes += len;
412 bf->buf_ptr = bf->buffer;
413 bf->buf_end = bf->buffer + len;
414 *bf->buf_end = CH_EOB;
416 if (bf->buf_ptr < bf->buf_end) {
417 return bf->buf_ptr[0];
418 } else {
419 bf->buf_ptr = bf->buf_end;
420 return CH_EOF;
424 /* read next char from current input file and handle end of input buffer */
425 ST_INLN void inp(void)
427 ch = *(++(file->buf_ptr));
428 /* end of buffer/file handling */
429 if (ch == CH_EOB)
430 ch = handle_eob();
433 /* handle '\[\r]\n' */
434 static int handle_stray_noerror(void)
436 while (ch == '\\') {
437 inp();
438 if (ch == '\n') {
439 file->line_num++;
440 inp();
441 } else if (ch == '\r') {
442 inp();
443 if (ch != '\n')
444 goto fail;
445 file->line_num++;
446 inp();
447 } else {
448 fail:
449 return 1;
452 return 0;
455 static void handle_stray(void)
457 if (handle_stray_noerror())
458 tcc_error("stray '\\' in program");
461 /* skip the stray and handle the \\n case. Output an error if
462 incorrect char after the stray */
463 static int handle_stray1(uint8_t *p)
465 int c;
467 file->buf_ptr = p;
468 if (p >= file->buf_end) {
469 c = handle_eob();
470 if (c != '\\')
471 return c;
472 p = file->buf_ptr;
474 ch = *p;
475 if (handle_stray_noerror()) {
476 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
477 tcc_error("stray '\\' in program");
478 *--file->buf_ptr = '\\';
480 p = file->buf_ptr;
481 c = *p;
482 return c;
485 /* handle just the EOB case, but not stray */
486 #define PEEKC_EOB(c, p)\
488 p++;\
489 c = *p;\
490 if (c == '\\') {\
491 file->buf_ptr = p;\
492 c = handle_eob();\
493 p = file->buf_ptr;\
497 /* handle the complicated stray case */
498 #define PEEKC(c, p)\
500 p++;\
501 c = *p;\
502 if (c == '\\') {\
503 c = handle_stray1(p);\
504 p = file->buf_ptr;\
508 /* input with '\[\r]\n' handling. Note that this function cannot
509 handle other characters after '\', so you cannot call it inside
510 strings or comments */
511 ST_FUNC void minp(void)
513 inp();
514 if (ch == '\\')
515 handle_stray();
519 /* single line C++ comments */
520 static uint8_t *parse_line_comment(uint8_t *p)
522 int c;
524 p++;
525 for(;;) {
526 c = *p;
527 redo:
528 if (c == '\n' || c == CH_EOF) {
529 break;
530 } else if (c == '\\') {
531 file->buf_ptr = p;
532 c = handle_eob();
533 p = file->buf_ptr;
534 if (c == '\\') {
535 PEEKC_EOB(c, p);
536 if (c == '\n') {
537 file->line_num++;
538 PEEKC_EOB(c, p);
539 } else if (c == '\r') {
540 PEEKC_EOB(c, p);
541 if (c == '\n') {
542 file->line_num++;
543 PEEKC_EOB(c, p);
546 } else {
547 goto redo;
549 } else {
550 p++;
553 return p;
556 /* C comments */
557 ST_FUNC uint8_t *parse_comment(uint8_t *p)
559 int c;
561 p++;
562 for(;;) {
563 /* fast skip loop */
564 for(;;) {
565 c = *p;
566 if (c == '\n' || c == '*' || c == '\\')
567 break;
568 p++;
569 c = *p;
570 if (c == '\n' || c == '*' || c == '\\')
571 break;
572 p++;
574 /* now we can handle all the cases */
575 if (c == '\n') {
576 file->line_num++;
577 p++;
578 } else if (c == '*') {
579 p++;
580 for(;;) {
581 c = *p;
582 if (c == '*') {
583 p++;
584 } else if (c == '/') {
585 goto end_of_comment;
586 } else if (c == '\\') {
587 file->buf_ptr = p;
588 c = handle_eob();
589 p = file->buf_ptr;
590 if (c == CH_EOF)
591 tcc_error("unexpected end of file in comment");
592 if (c == '\\') {
593 /* skip '\[\r]\n', otherwise just skip the stray */
594 while (c == '\\') {
595 PEEKC_EOB(c, p);
596 if (c == '\n') {
597 file->line_num++;
598 PEEKC_EOB(c, p);
599 } else if (c == '\r') {
600 PEEKC_EOB(c, p);
601 if (c == '\n') {
602 file->line_num++;
603 PEEKC_EOB(c, p);
605 } else {
606 goto after_star;
610 } else {
611 break;
614 after_star: ;
615 } else {
616 /* stray, eob or eof */
617 file->buf_ptr = p;
618 c = handle_eob();
619 p = file->buf_ptr;
620 if (c == CH_EOF) {
621 tcc_error("unexpected end of file in comment");
622 } else if (c == '\\') {
623 p++;
627 end_of_comment:
628 p++;
629 return p;
632 #define cinp minp
634 static inline void skip_spaces(void)
636 while (isidnum_table[ch - CH_EOF] & IS_SPC)
637 cinp();
640 static inline int check_space(int t, int *spc)
642 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
643 if (*spc)
644 return 1;
645 *spc = 1;
646 } else
647 *spc = 0;
648 return 0;
651 /* parse a string without interpreting escapes */
652 static uint8_t *parse_pp_string(uint8_t *p,
653 int sep, CString *str)
655 int c;
656 p++;
657 for(;;) {
658 c = *p;
659 if (c == sep) {
660 break;
661 } else if (c == '\\') {
662 file->buf_ptr = p;
663 c = handle_eob();
664 p = file->buf_ptr;
665 if (c == CH_EOF) {
666 unterminated_string:
667 /* XXX: indicate line number of start of string */
668 tcc_error("missing terminating %c character", sep);
669 } else if (c == '\\') {
670 /* escape : just skip \[\r]\n */
671 PEEKC_EOB(c, p);
672 if (c == '\n') {
673 file->line_num++;
674 p++;
675 } else if (c == '\r') {
676 PEEKC_EOB(c, p);
677 if (c != '\n')
678 expect("'\n' after '\r'");
679 file->line_num++;
680 p++;
681 } else if (c == CH_EOF) {
682 goto unterminated_string;
683 } else {
684 if (str) {
685 cstr_ccat(str, '\\');
686 cstr_ccat(str, c);
688 p++;
691 } else if (c == '\n') {
692 file->line_num++;
693 goto add_char;
694 } else if (c == '\r') {
695 PEEKC_EOB(c, p);
696 if (c != '\n') {
697 if (str)
698 cstr_ccat(str, '\r');
699 } else {
700 file->line_num++;
701 goto add_char;
703 } else {
704 add_char:
705 if (str)
706 cstr_ccat(str, c);
707 p++;
710 p++;
711 return p;
714 /* skip block of text until #else, #elif or #endif. skip also pairs of
715 #if/#endif */
716 static void preprocess_skip(void)
718 int a, start_of_line, c, in_warn_or_error;
719 uint8_t *p;
721 p = file->buf_ptr;
722 a = 0;
723 redo_start:
724 start_of_line = 1;
725 in_warn_or_error = 0;
726 for(;;) {
727 redo_no_start:
728 c = *p;
729 switch(c) {
730 case ' ':
731 case '\t':
732 case '\f':
733 case '\v':
734 case '\r':
735 p++;
736 goto redo_no_start;
737 case '\n':
738 file->line_num++;
739 p++;
740 goto redo_start;
741 case '\\':
742 file->buf_ptr = p;
743 c = handle_eob();
744 if (c == CH_EOF) {
745 expect("#endif");
746 } else if (c == '\\') {
747 ch = file->buf_ptr[0];
748 handle_stray_noerror();
750 p = file->buf_ptr;
751 goto redo_no_start;
752 /* skip strings */
753 case '\"':
754 case '\'':
755 if (in_warn_or_error)
756 goto _default;
757 p = parse_pp_string(p, c, NULL);
758 break;
759 /* skip comments */
760 case '/':
761 if (in_warn_or_error)
762 goto _default;
763 file->buf_ptr = p;
764 ch = *p;
765 minp();
766 p = file->buf_ptr;
767 if (ch == '*') {
768 p = parse_comment(p);
769 } else if (ch == '/') {
770 p = parse_line_comment(p);
772 break;
773 case '#':
774 p++;
775 if (start_of_line) {
776 file->buf_ptr = p;
777 next_nomacro();
778 p = file->buf_ptr;
779 if (a == 0 &&
780 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
781 goto the_end;
782 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
783 a++;
784 else if (tok == TOK_ENDIF)
785 a--;
786 else if( tok == TOK_ERROR || tok == TOK_WARNING)
787 in_warn_or_error = 1;
788 else if (tok == TOK_LINEFEED)
789 goto redo_start;
790 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
791 p = parse_line_comment(p);
792 break;
793 _default:
794 default:
795 p++;
796 break;
798 start_of_line = 0;
800 the_end: ;
801 file->buf_ptr = p;
804 /* ParseState handling */
806 /* XXX: currently, no include file info is stored. Thus, we cannot display
807 accurate messages if the function or data definition spans multiple
808 files */
810 /* save current parse state in 's' */
811 ST_FUNC void save_parse_state(ParseState *s)
813 s->line_num = file->line_num;
814 s->macro_ptr = macro_ptr;
815 s->tok = tok;
816 s->tokc = tokc;
819 /* restore parse state from 's' */
820 ST_FUNC void restore_parse_state(ParseState *s)
822 file->line_num = s->line_num;
823 macro_ptr = s->macro_ptr;
824 tok = s->tok;
825 tokc = s->tokc;
828 /* return the number of additional 'ints' necessary to store the
829 token */
830 static inline int tok_size(const int *p)
832 switch(*p) {
833 /* 4 bytes */
834 case TOK_CINT:
835 case TOK_CUINT:
836 case TOK_CCHAR:
837 case TOK_LCHAR:
838 case TOK_CFLOAT:
839 case TOK_LINENUM:
840 return 1 + 1;
841 case TOK_STR:
842 case TOK_LSTR:
843 case TOK_PPNUM:
844 case TOK_PPSTR:
845 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
846 case TOK_CDOUBLE:
847 case TOK_CLLONG:
848 case TOK_CULLONG:
849 return 1 + 2;
850 case TOK_CLDOUBLE:
851 return 1 + LDOUBLE_SIZE / 4;
852 default:
853 return 1 + 0;
857 /* token string handling */
859 ST_INLN void tok_str_new(TokenString *s)
861 s->str = NULL;
862 s->len = 0;
863 s->allocated_len = 0;
864 s->last_line_num = -1;
867 ST_FUNC void tok_str_free(int *str)
869 tcc_free(str);
872 static int *tok_str_realloc(TokenString *s)
874 int *str, len;
876 if (s->allocated_len == 0) {
877 len = 8;
878 } else {
879 len = s->allocated_len * 2;
881 str = tcc_realloc(s->str, len * sizeof(int));
882 s->allocated_len = len;
883 s->str = str;
884 return str;
887 ST_FUNC void tok_str_add(TokenString *s, int t)
889 int len, *str;
891 len = s->len;
892 str = s->str;
893 if (len >= s->allocated_len)
894 str = tok_str_realloc(s);
895 str[len++] = t;
896 s->len = len;
899 static void tok_str_add2(TokenString *s, int t, CValue *cv)
901 int len, *str;
903 len = s->len;
904 str = s->str;
906 /* allocate space for worst case */
907 if (len + TOK_MAX_SIZE > s->allocated_len)
908 str = tok_str_realloc(s);
909 str[len++] = t;
910 switch(t) {
911 case TOK_CINT:
912 case TOK_CUINT:
913 case TOK_CCHAR:
914 case TOK_LCHAR:
915 case TOK_CFLOAT:
916 case TOK_LINENUM:
917 str[len++] = cv->tab[0];
918 break;
919 case TOK_PPNUM:
920 case TOK_PPSTR:
921 case TOK_STR:
922 case TOK_LSTR:
924 int nb_words;
925 CString *cstr;
927 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
928 while ((len + nb_words) > s->allocated_len)
929 str = tok_str_realloc(s);
930 cstr = (CString *)(str + len);
931 cstr->data = NULL;
932 cstr->size = cv->cstr->size;
933 cstr->data_allocated = NULL;
934 cstr->size_allocated = cstr->size;
935 memcpy((char *)cstr + sizeof(CString),
936 cv->cstr->data, cstr->size);
937 len += nb_words;
939 break;
940 case TOK_CDOUBLE:
941 case TOK_CLLONG:
942 case TOK_CULLONG:
943 #if LDOUBLE_SIZE == 8
944 case TOK_CLDOUBLE:
945 #endif
946 str[len++] = cv->tab[0];
947 str[len++] = cv->tab[1];
948 break;
949 #if LDOUBLE_SIZE == 12
950 case TOK_CLDOUBLE:
951 str[len++] = cv->tab[0];
952 str[len++] = cv->tab[1];
953 str[len++] = cv->tab[2];
954 #elif LDOUBLE_SIZE == 16
955 case TOK_CLDOUBLE:
956 str[len++] = cv->tab[0];
957 str[len++] = cv->tab[1];
958 str[len++] = cv->tab[2];
959 str[len++] = cv->tab[3];
960 #elif LDOUBLE_SIZE != 8
961 #error add long double size support
962 #endif
963 break;
964 default:
965 break;
967 s->len = len;
970 /* add the current parse token in token string 's' */
971 ST_FUNC void tok_str_add_tok(TokenString *s)
973 CValue cval;
975 /* save line number info */
976 if (file->line_num != s->last_line_num) {
977 s->last_line_num = file->line_num;
978 cval.i = s->last_line_num;
979 tok_str_add2(s, TOK_LINENUM, &cval);
981 tok_str_add2(s, tok, &tokc);
984 /* get a token from an integer array and increment pointer
985 accordingly. we code it as a macro to avoid pointer aliasing. */
986 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
988 const int *p = *pp;
989 int n, *tab;
991 tab = cv->tab;
992 switch(*t = *p++) {
993 case TOK_CINT:
994 case TOK_CUINT:
995 case TOK_CCHAR:
996 case TOK_LCHAR:
997 case TOK_CFLOAT:
998 case TOK_LINENUM:
999 tab[0] = *p++;
1000 break;
1001 case TOK_STR:
1002 case TOK_LSTR:
1003 case TOK_PPNUM:
1004 case TOK_PPSTR:
1005 cv->cstr = (CString *)p;
1006 cv->cstr->data = (char *)p + sizeof(CString);
1007 p += (sizeof(CString) + cv->cstr->size + 3) >> 2;
1008 break;
1009 case TOK_CDOUBLE:
1010 case TOK_CLLONG:
1011 case TOK_CULLONG:
1012 n = 2;
1013 goto copy;
1014 case TOK_CLDOUBLE:
1015 #if LDOUBLE_SIZE == 16
1016 n = 4;
1017 #elif LDOUBLE_SIZE == 12
1018 n = 3;
1019 #elif LDOUBLE_SIZE == 8
1020 n = 2;
1021 #else
1022 # error add long double size support
1023 #endif
1024 copy:
1026 *tab++ = *p++;
1027 while (--n);
1028 break;
1029 default:
1030 break;
1032 *pp = p;
1035 static int macro_is_equal(const int *a, const int *b)
1037 char buf[STRING_MAX_SIZE + 1];
1038 CValue cv;
1039 int t;
1040 while (*a && *b) {
1041 TOK_GET(&t, &a, &cv);
1042 pstrcpy(buf, sizeof buf, get_tok_str(t, &cv));
1043 TOK_GET(&t, &b, &cv);
1044 if (strcmp(buf, get_tok_str(t, &cv)))
1045 return 0;
1047 return !(*a || *b);
1050 static void pp_line(TCCState *s1, BufferedFile *f, int level)
1052 int d = f->line_num - f->line_ref;
1053 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE
1054 || (level == 0 && f->line_ref && d < 8))
1056 while (d > 0)
1057 fputs("\n", s1->ppfp), --d;
1059 else
1060 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
1061 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
1063 else {
1064 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
1065 level > 0 ? " 1" : level < 0 ? " 2" : "");
1067 f->line_ref = f->line_num;
1070 static void tok_print(const char *msg, const int *str)
1072 FILE *pr = tcc_state->ppfp;
1073 int t;
1074 CValue cval;
1076 fprintf(pr, "%s ", msg);
1077 while (str) {
1078 TOK_GET(&t, &str, &cval);
1079 if (!t)
1080 break;
1081 fprintf(pr,"%s", get_tok_str(t, &cval));
1083 fprintf(pr, "\n");
1086 static int define_print_prepared(Sym *s)
1088 if (!s || !tcc_state->ppfp || tcc_state->dflag == 0)
1089 return 0;
1091 if (s->v < TOK_IDENT || s->v >= tok_ident)
1092 return 0;
1094 if (file) {
1095 file->line_num--;
1096 pp_line(tcc_state, file, 0);
1097 file->line_ref = ++file->line_num;
1099 return 1;
1102 static void define_print(int v)
1104 FILE *pr = tcc_state->ppfp;
1105 Sym *s, *a;
1107 s = define_find(v);
1108 if (define_print_prepared(s) == 0)
1109 return;
1111 fprintf(pr, "// #define %s", get_tok_str(v, NULL));
1112 if (s->type.t == MACRO_FUNC) {
1113 a = s->next;
1114 fprintf(pr,"(");
1115 if (a)
1116 for (;;) {
1117 fprintf(pr,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
1118 if (!(a = a->next))
1119 break;
1120 fprintf(pr,",");
1122 fprintf(pr,")");
1124 tok_print("", s->d);
1127 static void undef_print(int v)
1129 FILE *pr = tcc_state->ppfp;
1130 Sym *s;
1132 s = define_find(v);
1133 if (define_print_prepared(s) == 0)
1134 return;
1136 fprintf(pr, "// #undef %s\n", get_tok_str(s->v, NULL));
1139 ST_FUNC void print_defines(void)
1141 Sym *top = define_stack;
1142 while (top) {
1143 define_print(top->v);
1144 top = top->prev;
1148 /* defines handling */
1149 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1151 Sym *s;
1153 s = define_find(v);
1154 if (s && !macro_is_equal(s->d, str))
1155 tcc_warning("%s redefined", get_tok_str(v, NULL));
1157 s = sym_push2(&define_stack, v, macro_type, 0);
1158 s->d = str;
1159 s->next = first_arg;
1160 table_ident[v - TOK_IDENT]->sym_define = s;
1163 /* undefined a define symbol. Its name is just set to zero */
1164 ST_FUNC void define_undef(Sym *s)
1166 int v = s->v;
1167 undef_print(v);
1168 if (v >= TOK_IDENT && v < tok_ident)
1169 table_ident[v - TOK_IDENT]->sym_define = NULL;
1172 ST_INLN Sym *define_find(int v)
1174 v -= TOK_IDENT;
1175 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1176 return NULL;
1177 return table_ident[v]->sym_define;
1180 /* free define stack until top reaches 'b' */
1181 ST_FUNC void free_defines(Sym *b)
1183 Sym *top, *top1;
1184 int v;
1186 top = define_stack;
1187 while (top != b) {
1188 top1 = top->prev;
1189 /* do not free args or predefined defines */
1190 if (top->d)
1191 tok_str_free(top->d);
1192 v = top->v;
1193 if (v >= TOK_IDENT && v < tok_ident)
1194 table_ident[v - TOK_IDENT]->sym_define = NULL;
1195 sym_free(top);
1196 top = top1;
1198 define_stack = b;
1201 /* label lookup */
1202 ST_FUNC Sym *label_find(int v)
1204 v -= TOK_IDENT;
1205 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1206 return NULL;
1207 return table_ident[v]->sym_label;
1210 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1212 Sym *s, **ps;
1213 s = sym_push2(ptop, v, 0, 0);
1214 s->r = flags;
1215 ps = &table_ident[v - TOK_IDENT]->sym_label;
1216 if (ptop == &global_label_stack) {
1217 /* modify the top most local identifier, so that
1218 sym_identifier will point to 's' when popped */
1219 while (*ps != NULL)
1220 ps = &(*ps)->prev_tok;
1222 s->prev_tok = *ps;
1223 *ps = s;
1224 return s;
1227 /* pop labels until element last is reached. Look if any labels are
1228 undefined. Define symbols if '&&label' was used. */
1229 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1231 Sym *s, *s1;
1232 for(s = *ptop; s != slast; s = s1) {
1233 s1 = s->prev;
1234 if (s->r == LABEL_DECLARED) {
1235 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1236 } else if (s->r == LABEL_FORWARD) {
1237 tcc_error("label '%s' used but not defined",
1238 get_tok_str(s->v, NULL));
1239 } else {
1240 if (s->c) {
1241 /* define corresponding symbol. A size of
1242 1 is put. */
1243 put_extern_sym(s, cur_text_section, s->jnext, 1);
1246 /* remove label */
1247 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1248 sym_free(s);
1250 *ptop = slast;
1253 /* eval an expression for #if/#elif */
1254 static int expr_preprocess(void)
1256 int c, t;
1257 TokenString str;
1259 tok_str_new(&str);
1260 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1261 next(); /* do macro subst */
1262 if (tok == TOK_DEFINED) {
1263 next_nomacro();
1264 t = tok;
1265 if (t == '(')
1266 next_nomacro();
1267 c = define_find(tok) != 0;
1268 if (t == '(')
1269 next_nomacro();
1270 tok = TOK_CINT;
1271 tokc.i = c;
1272 } else if (tok >= TOK_IDENT) {
1273 /* if undefined macro */
1274 tok = TOK_CINT;
1275 tokc.i = 0;
1277 tok_str_add_tok(&str);
1279 tok_str_add(&str, -1); /* simulate end of file */
1280 tok_str_add(&str, 0);
1281 /* now evaluate C constant expression */
1282 begin_macro(&str, 0);
1283 next();
1284 c = expr_const();
1285 end_macro();
1286 return c != 0;
1290 /* parse after #define */
1291 ST_FUNC void parse_define(void)
1293 Sym *s, *first, **ps;
1294 int v, t, varg, is_vaargs, spc;
1295 int saved_parse_flags = parse_flags;
1296 TokenString str;
1298 v = tok;
1299 if (v < TOK_IDENT)
1300 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1301 /* XXX: should check if same macro (ANSI) */
1302 first = NULL;
1303 t = MACRO_OBJ;
1304 /* '(' must be just after macro definition for MACRO_FUNC */
1305 parse_flags |= PARSE_FLAG_SPACES;
1306 next_nomacro_spc();
1307 if (tok == '(') {
1308 next_nomacro();
1309 ps = &first;
1310 if (tok != ')') for (;;) {
1311 varg = tok;
1312 next_nomacro();
1313 is_vaargs = 0;
1314 if (varg == TOK_DOTS) {
1315 varg = TOK___VA_ARGS__;
1316 is_vaargs = 1;
1317 } else if (tok == TOK_DOTS && gnu_ext) {
1318 is_vaargs = 1;
1319 next_nomacro();
1321 if (varg < TOK_IDENT)
1322 bad_list:
1323 tcc_error("bad macro parameter list");
1324 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1325 *ps = s;
1326 ps = &s->next;
1327 if (tok == ')')
1328 break;
1329 if (tok != ',' || is_vaargs)
1330 goto bad_list;
1331 next_nomacro();
1333 next_nomacro_spc();
1334 t = MACRO_FUNC;
1336 tok_str_new(&str);
1337 spc = 2;
1338 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1339 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1340 /* remove spaces around ## and after '#' */
1341 if (TOK_TWOSHARPS == tok) {
1342 if (2 == spc)
1343 goto bad_twosharp;
1344 if (1 == spc)
1345 --str.len;
1346 spc = 3;
1347 } else if ('#' == tok) {
1348 spc = 4;
1349 } else if (check_space(tok, &spc)) {
1350 goto skip;
1352 tok_str_add2(&str, tok, &tokc);
1353 skip:
1354 next_nomacro_spc();
1357 parse_flags = saved_parse_flags;
1358 if (spc == 1)
1359 --str.len; /* remove trailing space */
1360 tok_str_add(&str, 0);
1361 if (3 == spc)
1362 bad_twosharp:
1363 tcc_error("'##' cannot appear at either end of macro");
1364 define_push(v, t, str.str, first);
1365 define_print(v);
1368 static inline int hash_cached_include(const char *filename)
1370 const unsigned char *s;
1371 unsigned int h;
1373 h = TOK_HASH_INIT;
1374 s = (unsigned char *) filename;
1375 while (*s) {
1376 h = TOK_HASH_FUNC(h, *s);
1377 s++;
1379 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1380 return h;
1383 static CachedInclude *search_cached_include(TCCState *s1, const char *filename)
1385 CachedInclude *e;
1386 int i, h;
1387 h = hash_cached_include(filename);
1388 i = s1->cached_includes_hash[h];
1389 for(;;) {
1390 if (i == 0)
1391 break;
1392 e = s1->cached_includes[i - 1];
1393 if (0 == PATHCMP(e->filename, filename))
1394 return e;
1395 i = e->hash_next;
1397 return NULL;
1400 static inline void add_cached_include(TCCState *s1, const char *filename, int ifndef_macro)
1402 CachedInclude *e;
1403 int h;
1405 if (search_cached_include(s1, filename))
1406 return;
1407 #ifdef INC_DEBUG
1408 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
1409 #endif
1410 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1411 strcpy(e->filename, filename);
1412 e->ifndef_macro = ifndef_macro;
1413 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1414 /* add in hash table */
1415 h = hash_cached_include(filename);
1416 e->hash_next = s1->cached_includes_hash[h];
1417 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1420 static void pragma_parse(TCCState *s1)
1422 next_nomacro();
1423 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1424 int t = tok, v;
1425 Sym *s;
1427 if (next(), tok != '(')
1428 goto pragma_err;
1429 if (next(), tok != TOK_STR)
1430 goto pragma_err;
1431 v = tok_alloc(tokc.cstr->data, tokc.cstr->size - 1)->tok;
1432 if (next(), tok != ')')
1433 goto pragma_err;
1434 if (t == TOK_push_macro) {
1435 while (NULL == (s = define_find(v)))
1436 define_push(v, 0, NULL, NULL);
1437 s->type.ref = s; /* set push boundary */
1438 } else {
1439 for (s = define_stack; s; s = s->prev)
1440 if (s->v == v && s->type.ref == s) {
1441 s->type.ref = NULL;
1442 break;
1445 if (s)
1446 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1447 else
1448 tcc_warning("unbalanced #pragma pop_macro");
1450 } else if (tok == TOK_once) {
1451 add_cached_include(s1, file->filename, TOK_once);
1453 } else if (s1->ppfp) {
1454 /* tcc -E: keep pragmas below unchanged */
1455 unget_tok(' ');
1456 unget_tok(TOK_PRAGMA);
1457 unget_tok('#');
1458 unget_tok(TOK_LINEFEED);
1460 } else if (tok == TOK_pack) {
1461 /* This may be:
1462 #pragma pack(1) // set
1463 #pragma pack() // reset to default
1464 #pragma pack(push,1) // push & set
1465 #pragma pack(pop) // restore previous */
1466 next();
1467 skip('(');
1468 if (tok == TOK_ASM_pop) {
1469 next();
1470 if (s1->pack_stack_ptr <= s1->pack_stack) {
1471 stk_error:
1472 tcc_error("out of pack stack");
1474 s1->pack_stack_ptr--;
1475 } else {
1476 int val = 0;
1477 if (tok != ')') {
1478 if (tok == TOK_ASM_push) {
1479 next();
1480 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1481 goto stk_error;
1482 s1->pack_stack_ptr++;
1483 skip(',');
1485 if (tok != TOK_CINT)
1486 goto pragma_err;
1487 val = tokc.i;
1488 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1489 goto pragma_err;
1490 next();
1492 *s1->pack_stack_ptr = val;
1494 if (tok != ')')
1495 goto pragma_err;
1497 } else if (tok == TOK_comment) {
1498 char *file;
1499 next();
1500 skip('(');
1501 if (tok != TOK_lib)
1502 goto pragma_warn;
1503 next();
1504 skip(',');
1505 if (tok != TOK_STR)
1506 goto pragma_err;
1507 file = tcc_strdup((char *)tokc.cstr->data);
1508 dynarray_add((void ***)&s1->pragma_libs, &s1->nb_pragma_libs, file);
1509 next();
1510 if (tok != ')')
1511 goto pragma_err;
1512 } else {
1513 pragma_warn:
1514 if (s1->warn_unsupported)
1515 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1517 return;
1519 pragma_err:
1520 tcc_error("malformed #pragma directive");
1521 return;
1524 /* is_bof is true if first non space token at beginning of file */
1525 ST_FUNC void preprocess(int is_bof)
1527 TCCState *s1 = tcc_state;
1528 int i, c, n, saved_parse_flags;
1529 char buf[1024], *q;
1530 Sym *s;
1532 saved_parse_flags = parse_flags;
1533 parse_flags = PARSE_FLAG_PREPROCESS
1534 | PARSE_FLAG_TOK_NUM
1535 | PARSE_FLAG_TOK_STR
1536 | PARSE_FLAG_LINEFEED
1537 | (parse_flags & PARSE_FLAG_ASM_FILE)
1540 next_nomacro();
1541 redo:
1542 switch(tok) {
1543 case TOK_DEFINE:
1544 next_nomacro();
1545 parse_define();
1546 break;
1547 case TOK_UNDEF:
1548 next_nomacro();
1549 s = define_find(tok);
1550 /* undefine symbol by putting an invalid name */
1551 if (s)
1552 define_undef(s);
1553 break;
1554 case TOK_INCLUDE:
1555 case TOK_INCLUDE_NEXT:
1556 ch = file->buf_ptr[0];
1557 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1558 skip_spaces();
1559 if (ch == '<') {
1560 c = '>';
1561 goto read_name;
1562 } else if (ch == '\"') {
1563 c = ch;
1564 read_name:
1565 inp();
1566 q = buf;
1567 while (ch != c && ch != '\n' && ch != CH_EOF) {
1568 if ((q - buf) < sizeof(buf) - 1)
1569 *q++ = ch;
1570 if (ch == '\\') {
1571 if (handle_stray_noerror() == 0)
1572 --q;
1573 } else
1574 inp();
1576 *q = '\0';
1577 minp();
1578 #if 0
1579 /* eat all spaces and comments after include */
1580 /* XXX: slightly incorrect */
1581 while (ch1 != '\n' && ch1 != CH_EOF)
1582 inp();
1583 #endif
1584 } else {
1585 /* computed #include : either we have only strings or
1586 we have anything enclosed in '<>' */
1587 next();
1588 buf[0] = '\0';
1589 if (tok == TOK_STR) {
1590 while (tok != TOK_LINEFEED) {
1591 if (tok != TOK_STR) {
1592 include_syntax:
1593 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1595 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
1596 next();
1598 c = '\"';
1599 } else {
1600 int len;
1601 while (tok != TOK_LINEFEED) {
1602 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1603 next();
1605 len = strlen(buf);
1606 /* check syntax and remove '<>' */
1607 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1608 goto include_syntax;
1609 memmove(buf, buf + 1, len - 2);
1610 buf[len - 2] = '\0';
1611 c = '>';
1615 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1616 tcc_error("#include recursion too deep");
1617 /* store current file in stack, but increment stack later below */
1618 *s1->include_stack_ptr = file;
1620 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
1621 for (i = -2; i < n; ++i) {
1622 char buf1[sizeof file->filename];
1623 CachedInclude *e;
1624 BufferedFile **f;
1625 const char *path;
1627 if (i == -2) {
1628 /* check absolute include path */
1629 if (!IS_ABSPATH(buf))
1630 continue;
1631 buf1[0] = 0;
1632 i = n; /* force end loop */
1634 } else if (i == -1) {
1635 /* search in current dir if "header.h" */
1636 if (c != '\"')
1637 continue;
1638 path = file->filename;
1639 pstrncpy(buf1, path, tcc_basename(path) - path);
1641 } else {
1642 /* search in all the include paths */
1643 if (i < s1->nb_include_paths)
1644 path = s1->include_paths[i];
1645 else
1646 path = s1->sysinclude_paths[i - s1->nb_include_paths];
1647 pstrcpy(buf1, sizeof(buf1), path);
1648 pstrcat(buf1, sizeof(buf1), "/");
1651 pstrcat(buf1, sizeof(buf1), buf);
1653 if (tok == TOK_INCLUDE_NEXT)
1654 for (f = s1->include_stack_ptr; f >= s1->include_stack; --f)
1655 if (0 == PATHCMP((*f)->filename, buf1)) {
1656 #ifdef INC_DEBUG
1657 printf("%s: #include_next skipping %s\n", file->filename, buf1);
1658 #endif
1659 goto include_trynext;
1662 e = search_cached_include(s1, buf1);
1663 if (e && (define_find(e->ifndef_macro) || e->ifndef_macro == TOK_once)) {
1664 /* no need to parse the include because the 'ifndef macro'
1665 is defined */
1666 #ifdef INC_DEBUG
1667 printf("%s: skipping cached %s\n", file->filename, buf1);
1668 #endif
1669 goto include_done;
1672 if (tcc_open(s1, buf1) < 0)
1673 include_trynext:
1674 continue;
1676 #ifdef INC_DEBUG
1677 printf("%s: including %s\n", file->prev->filename, file->filename);
1678 #endif
1679 /* update target deps */
1680 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1681 tcc_strdup(buf1));
1682 /* push current file in stack */
1683 ++s1->include_stack_ptr;
1684 /* add include file debug info */
1685 if (s1->do_debug)
1686 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1687 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1688 ch = file->buf_ptr[0];
1689 goto the_end;
1691 tcc_error("include file '%s' not found", buf);
1692 include_done:
1693 break;
1694 case TOK_IFNDEF:
1695 c = 1;
1696 goto do_ifdef;
1697 case TOK_IF:
1698 c = expr_preprocess();
1699 goto do_if;
1700 case TOK_IFDEF:
1701 c = 0;
1702 do_ifdef:
1703 next_nomacro();
1704 if (tok < TOK_IDENT)
1705 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1706 if (is_bof) {
1707 if (c) {
1708 #ifdef INC_DEBUG
1709 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1710 #endif
1711 file->ifndef_macro = tok;
1714 c = (define_find(tok) != 0) ^ c;
1715 do_if:
1716 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1717 tcc_error("memory full (ifdef)");
1718 *s1->ifdef_stack_ptr++ = c;
1719 goto test_skip;
1720 case TOK_ELSE:
1721 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1722 tcc_error("#else without matching #if");
1723 if (s1->ifdef_stack_ptr[-1] & 2)
1724 tcc_error("#else after #else");
1725 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1726 goto test_else;
1727 case TOK_ELIF:
1728 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1729 tcc_error("#elif without matching #if");
1730 c = s1->ifdef_stack_ptr[-1];
1731 if (c > 1)
1732 tcc_error("#elif after #else");
1733 /* last #if/#elif expression was true: we skip */
1734 if (c == 1)
1735 goto skip;
1736 c = expr_preprocess();
1737 s1->ifdef_stack_ptr[-1] = c;
1738 test_else:
1739 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1740 file->ifndef_macro = 0;
1741 test_skip:
1742 if (!(c & 1)) {
1743 skip:
1744 preprocess_skip();
1745 is_bof = 0;
1746 goto redo;
1748 break;
1749 case TOK_ENDIF:
1750 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1751 tcc_error("#endif without matching #if");
1752 s1->ifdef_stack_ptr--;
1753 /* '#ifndef macro' was at the start of file. Now we check if
1754 an '#endif' is exactly at the end of file */
1755 if (file->ifndef_macro &&
1756 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1757 file->ifndef_macro_saved = file->ifndef_macro;
1758 /* need to set to zero to avoid false matches if another
1759 #ifndef at middle of file */
1760 file->ifndef_macro = 0;
1761 while (tok != TOK_LINEFEED)
1762 next_nomacro();
1763 tok_flags |= TOK_FLAG_ENDIF;
1764 goto the_end;
1766 break;
1767 case TOK_PPNUM:
1768 n = strtoul((char*)tokc.cstr->data, &q, 10);
1769 goto _line_num;
1770 case TOK_LINE:
1771 next();
1772 if (tok != TOK_CINT)
1773 _line_err:
1774 tcc_error("wrong #line format");
1775 n = tokc.i;
1776 _line_num:
1777 next();
1778 if (tok != TOK_LINEFEED) {
1779 if (tok == TOK_STR)
1780 pstrcpy(file->filename, sizeof(file->filename), (char *)tokc.cstr->data);
1781 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1782 break;
1783 else
1784 goto _line_err;
1785 --n;
1787 if (file->fd > 0)
1788 total_lines += file->line_num - n;
1789 file->line_num = n;
1790 if (s1->do_debug)
1791 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1792 break;
1793 case TOK_ERROR:
1794 case TOK_WARNING:
1795 c = tok;
1796 ch = file->buf_ptr[0];
1797 skip_spaces();
1798 q = buf;
1799 while (ch != '\n' && ch != CH_EOF) {
1800 if ((q - buf) < sizeof(buf) - 1)
1801 *q++ = ch;
1802 if (ch == '\\') {
1803 if (handle_stray_noerror() == 0)
1804 --q;
1805 } else
1806 inp();
1808 *q = '\0';
1809 if (c == TOK_ERROR)
1810 tcc_error("#error %s", buf);
1811 else
1812 tcc_warning("#warning %s", buf);
1813 break;
1814 case TOK_PRAGMA:
1815 pragma_parse(s1);
1816 break;
1817 case TOK_LINEFEED:
1818 goto the_end;
1819 default:
1820 /* ignore gas line comment in an 'S' file. */
1821 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1822 goto ignore;
1823 if (tok == '!' && is_bof)
1824 /* '!' is ignored at beginning to allow C scripts. */
1825 goto ignore;
1826 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1827 ignore:
1828 file->buf_ptr = parse_line_comment(file->buf_ptr);
1829 goto the_end;
1831 /* ignore other preprocess commands or #! for C scripts */
1832 while (tok != TOK_LINEFEED)
1833 next_nomacro();
1834 the_end:
1835 parse_flags = saved_parse_flags;
1838 /* evaluate escape codes in a string. */
1839 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1841 int c, n;
1842 const uint8_t *p;
1844 p = buf;
1845 for(;;) {
1846 c = *p;
1847 if (c == '\0')
1848 break;
1849 if (c == '\\') {
1850 p++;
1851 /* escape */
1852 c = *p;
1853 switch(c) {
1854 case '0': case '1': case '2': case '3':
1855 case '4': case '5': case '6': case '7':
1856 /* at most three octal digits */
1857 n = c - '0';
1858 p++;
1859 c = *p;
1860 if (isoct(c)) {
1861 n = n * 8 + c - '0';
1862 p++;
1863 c = *p;
1864 if (isoct(c)) {
1865 n = n * 8 + c - '0';
1866 p++;
1869 c = n;
1870 goto add_char_nonext;
1871 case 'x':
1872 case 'u':
1873 case 'U':
1874 p++;
1875 n = 0;
1876 for(;;) {
1877 c = *p;
1878 if (c >= 'a' && c <= 'f')
1879 c = c - 'a' + 10;
1880 else if (c >= 'A' && c <= 'F')
1881 c = c - 'A' + 10;
1882 else if (isnum(c))
1883 c = c - '0';
1884 else
1885 break;
1886 n = n * 16 + c;
1887 p++;
1889 c = n;
1890 goto add_char_nonext;
1891 case 'a':
1892 c = '\a';
1893 break;
1894 case 'b':
1895 c = '\b';
1896 break;
1897 case 'f':
1898 c = '\f';
1899 break;
1900 case 'n':
1901 c = '\n';
1902 break;
1903 case 'r':
1904 c = '\r';
1905 break;
1906 case 't':
1907 c = '\t';
1908 break;
1909 case 'v':
1910 c = '\v';
1911 break;
1912 case 'e':
1913 if (!gnu_ext)
1914 goto invalid_escape;
1915 c = 27;
1916 break;
1917 case '\'':
1918 case '\"':
1919 case '\\':
1920 case '?':
1921 break;
1922 default:
1923 invalid_escape:
1924 if (c >= '!' && c <= '~')
1925 tcc_warning("unknown escape sequence: \'\\%c\'", c);
1926 else
1927 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
1928 break;
1931 p++;
1932 add_char_nonext:
1933 if (!is_long)
1934 cstr_ccat(outstr, c);
1935 else
1936 cstr_wccat(outstr, c);
1938 /* add a trailing '\0' */
1939 if (!is_long)
1940 cstr_ccat(outstr, '\0');
1941 else
1942 cstr_wccat(outstr, '\0');
1945 void parse_string(const char *s, int len)
1947 uint8_t buf[1000], *p = buf;
1948 int is_long, sep;
1950 if ((is_long = *s == 'L'))
1951 ++s, --len;
1952 sep = *s++;
1953 len -= 2;
1954 if (len >= sizeof buf)
1955 p = tcc_malloc(len + 1);
1956 memcpy(p, s, len);
1957 p[len] = 0;
1959 cstr_reset(&tokcstr);
1960 parse_escape_string(&tokcstr, p, is_long);
1961 if (p != buf)
1962 tcc_free(p);
1964 if (sep == '\'') {
1965 int char_size;
1966 /* XXX: make it portable */
1967 if (!is_long)
1968 char_size = 1;
1969 else
1970 char_size = sizeof(nwchar_t);
1971 if (tokcstr.size <= char_size)
1972 tcc_error("empty character constant");
1973 if (tokcstr.size > 2 * char_size)
1974 tcc_warning("multi-character character constant");
1975 if (!is_long) {
1976 tokc.i = *(int8_t *)tokcstr.data;
1977 tok = TOK_CCHAR;
1978 } else {
1979 tokc.i = *(nwchar_t *)tokcstr.data;
1980 tok = TOK_LCHAR;
1982 } else {
1983 tokc.cstr = &tokcstr;
1984 if (!is_long)
1985 tok = TOK_STR;
1986 else
1987 tok = TOK_LSTR;
1991 /* we use 64 bit numbers */
1992 #define BN_SIZE 2
1994 /* bn = (bn << shift) | or_val */
1995 static void bn_lshift(unsigned int *bn, int shift, int or_val)
1997 int i;
1998 unsigned int v;
1999 for(i=0;i<BN_SIZE;i++) {
2000 v = bn[i];
2001 bn[i] = (v << shift) | or_val;
2002 or_val = v >> (32 - shift);
2006 static void bn_zero(unsigned int *bn)
2008 int i;
2009 for(i=0;i<BN_SIZE;i++) {
2010 bn[i] = 0;
2014 /* parse number in null terminated string 'p' and return it in the
2015 current token */
2016 static void parse_number(const char *p)
2018 int b, t, shift, frac_bits, s, exp_val, ch;
2019 char *q;
2020 unsigned int bn[BN_SIZE];
2021 double d;
2023 /* number */
2024 q = token_buf;
2025 ch = *p++;
2026 t = ch;
2027 ch = *p++;
2028 *q++ = t;
2029 b = 10;
2030 if (t == '.') {
2031 goto float_frac_parse;
2032 } else if (t == '0') {
2033 if (ch == 'x' || ch == 'X') {
2034 q--;
2035 ch = *p++;
2036 b = 16;
2037 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
2038 q--;
2039 ch = *p++;
2040 b = 2;
2043 /* parse all digits. cannot check octal numbers at this stage
2044 because of floating point constants */
2045 while (1) {
2046 if (ch >= 'a' && ch <= 'f')
2047 t = ch - 'a' + 10;
2048 else if (ch >= 'A' && ch <= 'F')
2049 t = ch - 'A' + 10;
2050 else if (isnum(ch))
2051 t = ch - '0';
2052 else
2053 break;
2054 if (t >= b)
2055 break;
2056 if (q >= token_buf + STRING_MAX_SIZE) {
2057 num_too_long:
2058 tcc_error("number too long");
2060 *q++ = ch;
2061 ch = *p++;
2063 if (ch == '.' ||
2064 ((ch == 'e' || ch == 'E') && b == 10) ||
2065 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2066 if (b != 10) {
2067 /* NOTE: strtox should support that for hexa numbers, but
2068 non ISOC99 libcs do not support it, so we prefer to do
2069 it by hand */
2070 /* hexadecimal or binary floats */
2071 /* XXX: handle overflows */
2072 *q = '\0';
2073 if (b == 16)
2074 shift = 4;
2075 else
2076 shift = 1;
2077 bn_zero(bn);
2078 q = token_buf;
2079 while (1) {
2080 t = *q++;
2081 if (t == '\0') {
2082 break;
2083 } else if (t >= 'a') {
2084 t = t - 'a' + 10;
2085 } else if (t >= 'A') {
2086 t = t - 'A' + 10;
2087 } else {
2088 t = t - '0';
2090 bn_lshift(bn, shift, t);
2092 frac_bits = 0;
2093 if (ch == '.') {
2094 ch = *p++;
2095 while (1) {
2096 t = ch;
2097 if (t >= 'a' && t <= 'f') {
2098 t = t - 'a' + 10;
2099 } else if (t >= 'A' && t <= 'F') {
2100 t = t - 'A' + 10;
2101 } else if (t >= '0' && t <= '9') {
2102 t = t - '0';
2103 } else {
2104 break;
2106 if (t >= b)
2107 tcc_error("invalid digit");
2108 bn_lshift(bn, shift, t);
2109 frac_bits += shift;
2110 ch = *p++;
2113 if (ch != 'p' && ch != 'P')
2114 expect("exponent");
2115 ch = *p++;
2116 s = 1;
2117 exp_val = 0;
2118 if (ch == '+') {
2119 ch = *p++;
2120 } else if (ch == '-') {
2121 s = -1;
2122 ch = *p++;
2124 if (ch < '0' || ch > '9')
2125 expect("exponent digits");
2126 while (ch >= '0' && ch <= '9') {
2127 exp_val = exp_val * 10 + ch - '0';
2128 ch = *p++;
2130 exp_val = exp_val * s;
2132 /* now we can generate the number */
2133 /* XXX: should patch directly float number */
2134 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2135 d = ldexp(d, exp_val - frac_bits);
2136 t = toup(ch);
2137 if (t == 'F') {
2138 ch = *p++;
2139 tok = TOK_CFLOAT;
2140 /* float : should handle overflow */
2141 tokc.f = (float)d;
2142 } else if (t == 'L') {
2143 ch = *p++;
2144 #ifdef TCC_TARGET_PE
2145 tok = TOK_CDOUBLE;
2146 tokc.d = d;
2147 #else
2148 tok = TOK_CLDOUBLE;
2149 /* XXX: not large enough */
2150 tokc.ld = (long double)d;
2151 #endif
2152 } else {
2153 tok = TOK_CDOUBLE;
2154 tokc.d = d;
2156 } else {
2157 /* decimal floats */
2158 if (ch == '.') {
2159 if (q >= token_buf + STRING_MAX_SIZE)
2160 goto num_too_long;
2161 *q++ = ch;
2162 ch = *p++;
2163 float_frac_parse:
2164 while (ch >= '0' && ch <= '9') {
2165 if (q >= token_buf + STRING_MAX_SIZE)
2166 goto num_too_long;
2167 *q++ = ch;
2168 ch = *p++;
2171 if (ch == 'e' || ch == 'E') {
2172 if (q >= token_buf + STRING_MAX_SIZE)
2173 goto num_too_long;
2174 *q++ = ch;
2175 ch = *p++;
2176 if (ch == '-' || ch == '+') {
2177 if (q >= token_buf + STRING_MAX_SIZE)
2178 goto num_too_long;
2179 *q++ = ch;
2180 ch = *p++;
2182 if (ch < '0' || ch > '9')
2183 expect("exponent digits");
2184 while (ch >= '0' && ch <= '9') {
2185 if (q >= token_buf + STRING_MAX_SIZE)
2186 goto num_too_long;
2187 *q++ = ch;
2188 ch = *p++;
2191 *q = '\0';
2192 t = toup(ch);
2193 errno = 0;
2194 if (t == 'F') {
2195 ch = *p++;
2196 tok = TOK_CFLOAT;
2197 tokc.f = strtof(token_buf, NULL);
2198 } else if (t == 'L') {
2199 ch = *p++;
2200 #ifdef TCC_TARGET_PE
2201 tok = TOK_CDOUBLE;
2202 tokc.d = strtod(token_buf, NULL);
2203 #else
2204 tok = TOK_CLDOUBLE;
2205 tokc.ld = strtold(token_buf, NULL);
2206 #endif
2207 } else {
2208 tok = TOK_CDOUBLE;
2209 tokc.d = strtod(token_buf, NULL);
2212 } else {
2213 unsigned long long n, n1;
2214 int lcount, ucount, must_64bit;
2215 const char *p1;
2217 /* integer number */
2218 *q = '\0';
2219 q = token_buf;
2220 if (b == 10 && *q == '0') {
2221 b = 8;
2222 q++;
2224 n = 0;
2225 while(1) {
2226 t = *q++;
2227 /* no need for checks except for base 10 / 8 errors */
2228 if (t == '\0')
2229 break;
2230 else if (t >= 'a')
2231 t = t - 'a' + 10;
2232 else if (t >= 'A')
2233 t = t - 'A' + 10;
2234 else
2235 t = t - '0';
2236 if (t >= b)
2237 tcc_error("invalid digit");
2238 n1 = n;
2239 n = n * b + t;
2240 /* detect overflow */
2241 /* XXX: this test is not reliable */
2242 if (n < n1)
2243 tcc_error("integer constant overflow");
2246 /* Determine the characteristics (unsigned and/or 64bit) the type of
2247 the constant must have according to the constant suffix(es) */
2248 lcount = ucount = must_64bit = 0;
2249 p1 = p;
2250 for(;;) {
2251 t = toup(ch);
2252 if (t == 'L') {
2253 if (lcount >= 2)
2254 tcc_error("three 'l's in integer constant");
2255 if (lcount && *(p - 1) != ch)
2256 tcc_error("incorrect integer suffix: %s", p1);
2257 lcount++;
2258 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2259 if (lcount == 2)
2260 #endif
2261 must_64bit = 1;
2262 ch = *p++;
2263 } else if (t == 'U') {
2264 if (ucount >= 1)
2265 tcc_error("two 'u's in integer constant");
2266 ucount++;
2267 ch = *p++;
2268 } else {
2269 break;
2273 /* Whether 64 bits are needed to hold the constant's value */
2274 if (n & 0xffffffff00000000LL || must_64bit) {
2275 tok = TOK_CLLONG;
2276 n1 = n >> 32;
2277 } else {
2278 tok = TOK_CINT;
2279 n1 = n;
2282 /* Whether type must be unsigned to hold the constant's value */
2283 if (ucount || ((n1 >> 31) && (b != 10))) {
2284 if (tok == TOK_CLLONG)
2285 tok = TOK_CULLONG;
2286 else
2287 tok = TOK_CUINT;
2288 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2289 } else if (n1 >> 31) {
2290 if (tok == TOK_CINT)
2291 tok = TOK_CLLONG;
2292 else
2293 tcc_error("integer constant overflow");
2296 if (tok == TOK_CINT || tok == TOK_CUINT)
2297 tokc.ui = n;
2298 else
2299 tokc.ull = n;
2301 if (ch)
2302 tcc_error("invalid number\n");
2306 #define PARSE2(c1, tok1, c2, tok2) \
2307 case c1: \
2308 PEEKC(c, p); \
2309 if (c == c2) { \
2310 p++; \
2311 tok = tok2; \
2312 } else { \
2313 tok = tok1; \
2315 break;
2317 /* return next token without macro substitution */
2318 static inline void next_nomacro1(void)
2320 int t, c, is_long;
2321 TokenSym *ts;
2322 uint8_t *p, *p1;
2323 unsigned int h;
2325 p = file->buf_ptr;
2326 redo_no_start:
2327 c = *p;
2328 switch(c) {
2329 case ' ':
2330 case '\t':
2331 tok = c;
2332 p++;
2333 if (parse_flags & PARSE_FLAG_SPACES)
2334 goto keep_tok_flags;
2335 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2336 ++p;
2337 goto redo_no_start;
2338 case '\f':
2339 case '\v':
2340 case '\r':
2341 p++;
2342 goto redo_no_start;
2343 case '\\':
2344 /* first look if it is in fact an end of buffer */
2345 c = handle_stray1(p);
2346 p = file->buf_ptr;
2347 if (c == '\\')
2348 goto parse_simple;
2349 if (c != CH_EOF)
2350 goto redo_no_start;
2352 TCCState *s1 = tcc_state;
2353 if ((parse_flags & PARSE_FLAG_LINEFEED)
2354 && !(tok_flags & TOK_FLAG_EOF)) {
2355 tok_flags |= TOK_FLAG_EOF;
2356 tok = TOK_LINEFEED;
2357 goto keep_tok_flags;
2358 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2359 tok = TOK_EOF;
2360 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2361 tcc_error("missing #endif");
2362 } else if (s1->include_stack_ptr == s1->include_stack) {
2363 /* no include left : end of file. */
2364 tok = TOK_EOF;
2365 } else {
2366 tok_flags &= ~TOK_FLAG_EOF;
2367 /* pop include file */
2369 /* test if previous '#endif' was after a #ifdef at
2370 start of file */
2371 if (tok_flags & TOK_FLAG_ENDIF) {
2372 #ifdef INC_DEBUG
2373 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2374 #endif
2375 add_cached_include(s1, file->filename, file->ifndef_macro_saved);
2376 tok_flags &= ~TOK_FLAG_ENDIF;
2379 /* add end of include file debug info */
2380 if (tcc_state->do_debug) {
2381 put_stabd(N_EINCL, 0, 0);
2383 /* pop include stack */
2384 tcc_close();
2385 s1->include_stack_ptr--;
2386 p = file->buf_ptr;
2387 goto redo_no_start;
2390 break;
2392 case '\n':
2393 file->line_num++;
2394 tok_flags |= TOK_FLAG_BOL;
2395 p++;
2396 maybe_newline:
2397 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2398 goto redo_no_start;
2399 tok = TOK_LINEFEED;
2400 goto keep_tok_flags;
2402 case '#':
2403 /* XXX: simplify */
2404 PEEKC(c, p);
2405 if ((tok_flags & TOK_FLAG_BOL) &&
2406 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2407 file->buf_ptr = p;
2408 preprocess(tok_flags & TOK_FLAG_BOF);
2409 p = file->buf_ptr;
2410 goto maybe_newline;
2411 } else {
2412 if (c == '#') {
2413 p++;
2414 tok = TOK_TWOSHARPS;
2415 } else {
2416 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2417 p = parse_line_comment(p - 1);
2418 goto redo_no_start;
2419 } else {
2420 tok = '#';
2424 break;
2426 /* dollar is allowed to start identifiers when not parsing asm */
2427 case '$':
2428 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2429 || (parse_flags & PARSE_FLAG_ASM_FILE))
2430 goto parse_simple;
2432 case 'a': case 'b': case 'c': case 'd':
2433 case 'e': case 'f': case 'g': case 'h':
2434 case 'i': case 'j': case 'k': case 'l':
2435 case 'm': case 'n': case 'o': case 'p':
2436 case 'q': case 'r': case 's': case 't':
2437 case 'u': case 'v': case 'w': case 'x':
2438 case 'y': case 'z':
2439 case 'A': case 'B': case 'C': case 'D':
2440 case 'E': case 'F': case 'G': case 'H':
2441 case 'I': case 'J': case 'K':
2442 case 'M': case 'N': case 'O': case 'P':
2443 case 'Q': case 'R': case 'S': case 'T':
2444 case 'U': case 'V': case 'W': case 'X':
2445 case 'Y': case 'Z':
2446 case '_':
2447 parse_ident_fast:
2448 p1 = p;
2449 h = TOK_HASH_INIT;
2450 h = TOK_HASH_FUNC(h, c);
2451 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2452 h = TOK_HASH_FUNC(h, c);
2453 if (c != '\\') {
2454 TokenSym **pts;
2455 int len;
2457 /* fast case : no stray found, so we have the full token
2458 and we have already hashed it */
2459 len = p - p1;
2460 h &= (TOK_HASH_SIZE - 1);
2461 pts = &hash_ident[h];
2462 for(;;) {
2463 ts = *pts;
2464 if (!ts)
2465 break;
2466 if (ts->len == len && !memcmp(ts->str, p1, len))
2467 goto token_found;
2468 pts = &(ts->hash_next);
2470 ts = tok_alloc_new(pts, (char *) p1, len);
2471 token_found: ;
2472 } else {
2473 /* slower case */
2474 cstr_reset(&tokcstr);
2476 while (p1 < p) {
2477 cstr_ccat(&tokcstr, *p1);
2478 p1++;
2480 p--;
2481 PEEKC(c, p);
2482 parse_ident_slow:
2483 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM)) {
2484 cstr_ccat(&tokcstr, c);
2485 PEEKC(c, p);
2487 ts = tok_alloc(tokcstr.data, tokcstr.size);
2489 tok = ts->tok;
2490 break;
2491 case 'L':
2492 t = p[1];
2493 if (t != '\\' && t != '\'' && t != '\"') {
2494 /* fast case */
2495 goto parse_ident_fast;
2496 } else {
2497 PEEKC(c, p);
2498 if (c == '\'' || c == '\"') {
2499 is_long = 1;
2500 goto str_const;
2501 } else {
2502 cstr_reset(&tokcstr);
2503 cstr_ccat(&tokcstr, 'L');
2504 goto parse_ident_slow;
2507 break;
2509 case '0': case '1': case '2': case '3':
2510 case '4': case '5': case '6': case '7':
2511 case '8': case '9':
2512 cstr_reset(&tokcstr);
2513 /* after the first digit, accept digits, alpha, '.' or sign if
2514 prefixed by 'eEpP' */
2515 parse_num:
2516 for(;;) {
2517 t = c;
2518 cstr_ccat(&tokcstr, c);
2519 PEEKC(c, p);
2520 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2521 || c == '.'
2522 || ((c == '+' || c == '-')
2523 && (t == 'e' || t == 'E' || t == 'p' || t == 'P')
2525 break;
2527 /* We add a trailing '\0' to ease parsing */
2528 cstr_ccat(&tokcstr, '\0');
2529 tokc.cstr = &tokcstr;
2530 tok = TOK_PPNUM;
2531 break;
2533 case '.':
2534 /* special dot handling because it can also start a number */
2535 PEEKC(c, p);
2536 if (isnum(c)) {
2537 cstr_reset(&tokcstr);
2538 cstr_ccat(&tokcstr, '.');
2539 goto parse_num;
2540 } else if ((c == '.') && (p[1] == '.')){
2541 PEEKC(c, p);
2542 PEEKC(c, p);
2543 tok = TOK_DOTS;
2544 } else {
2545 tok = '.';
2547 break;
2548 case '\'':
2549 case '\"':
2550 is_long = 0;
2551 str_const:
2552 cstr_reset(&tokcstr);
2553 if (is_long)
2554 cstr_ccat(&tokcstr, 'L');
2555 cstr_ccat(&tokcstr, c);
2556 p = parse_pp_string(p, c, &tokcstr);
2557 cstr_ccat(&tokcstr, c);
2558 cstr_ccat(&tokcstr, '\0');
2559 tokc.cstr = &tokcstr;
2560 tok = TOK_PPSTR;
2561 break;
2563 case '<':
2564 PEEKC(c, p);
2565 if (c == '=') {
2566 p++;
2567 tok = TOK_LE;
2568 } else if (c == '<') {
2569 PEEKC(c, p);
2570 if (c == '=') {
2571 p++;
2572 tok = TOK_A_SHL;
2573 } else {
2574 tok = TOK_SHL;
2576 } else {
2577 tok = TOK_LT;
2579 break;
2580 case '>':
2581 PEEKC(c, p);
2582 if (c == '=') {
2583 p++;
2584 tok = TOK_GE;
2585 } else if (c == '>') {
2586 PEEKC(c, p);
2587 if (c == '=') {
2588 p++;
2589 tok = TOK_A_SAR;
2590 } else {
2591 tok = TOK_SAR;
2593 } else {
2594 tok = TOK_GT;
2596 break;
2598 case '&':
2599 PEEKC(c, p);
2600 if (c == '&') {
2601 p++;
2602 tok = TOK_LAND;
2603 } else if (c == '=') {
2604 p++;
2605 tok = TOK_A_AND;
2606 } else {
2607 tok = '&';
2609 break;
2611 case '|':
2612 PEEKC(c, p);
2613 if (c == '|') {
2614 p++;
2615 tok = TOK_LOR;
2616 } else if (c == '=') {
2617 p++;
2618 tok = TOK_A_OR;
2619 } else {
2620 tok = '|';
2622 break;
2624 case '+':
2625 PEEKC(c, p);
2626 if (c == '+') {
2627 p++;
2628 tok = TOK_INC;
2629 } else if (c == '=') {
2630 p++;
2631 tok = TOK_A_ADD;
2632 } else {
2633 tok = '+';
2635 break;
2637 case '-':
2638 PEEKC(c, p);
2639 if (c == '-') {
2640 p++;
2641 tok = TOK_DEC;
2642 } else if (c == '=') {
2643 p++;
2644 tok = TOK_A_SUB;
2645 } else if (c == '>') {
2646 p++;
2647 tok = TOK_ARROW;
2648 } else {
2649 tok = '-';
2651 break;
2653 PARSE2('!', '!', '=', TOK_NE)
2654 PARSE2('=', '=', '=', TOK_EQ)
2655 PARSE2('*', '*', '=', TOK_A_MUL)
2656 PARSE2('%', '%', '=', TOK_A_MOD)
2657 PARSE2('^', '^', '=', TOK_A_XOR)
2659 /* comments or operator */
2660 case '/':
2661 PEEKC(c, p);
2662 if (c == '*') {
2663 p = parse_comment(p);
2664 /* comments replaced by a blank */
2665 tok = ' ';
2666 goto keep_tok_flags;
2667 } else if (c == '/') {
2668 p = parse_line_comment(p);
2669 tok = ' ';
2670 goto keep_tok_flags;
2671 } else if (c == '=') {
2672 p++;
2673 tok = TOK_A_DIV;
2674 } else {
2675 tok = '/';
2677 break;
2679 /* simple tokens */
2680 case '(':
2681 case ')':
2682 case '[':
2683 case ']':
2684 case '{':
2685 case '}':
2686 case ',':
2687 case ';':
2688 case ':':
2689 case '?':
2690 case '~':
2691 case '@': /* only used in assembler */
2692 parse_simple:
2693 tok = c;
2694 p++;
2695 break;
2696 default:
2697 tcc_error("unrecognized character \\x%02x", c);
2698 break;
2700 tok_flags = 0;
2701 keep_tok_flags:
2702 file->buf_ptr = p;
2703 #if defined(PARSE_DEBUG)
2704 printf("token = %s\n", get_tok_str(tok, &tokc));
2705 #endif
2708 /* return next token without macro substitution. Can read input from
2709 macro_ptr buffer */
2710 static void next_nomacro_spc(void)
2712 if (macro_ptr) {
2713 redo:
2714 tok = *macro_ptr;
2715 if (tok) {
2716 TOK_GET(&tok, &macro_ptr, &tokc);
2717 if (tok == TOK_LINENUM) {
2718 file->line_num = tokc.i;
2719 goto redo;
2722 } else {
2723 next_nomacro1();
2727 ST_FUNC void next_nomacro(void)
2729 do {
2730 next_nomacro_spc();
2731 } while (tok < 256 && (isidnum_table[tok - CH_EOF] & IS_SPC));
2735 static void macro_subst(
2736 TokenString *tok_str,
2737 Sym **nested_list,
2738 const int *macro_str,
2739 int can_read_stream
2742 /* substitute arguments in replacement lists in macro_str by the values in
2743 args (field d) and return allocated string */
2744 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2746 int t, t0, t1, spc;
2747 const int *st;
2748 Sym *s;
2749 CValue cval;
2750 TokenString str;
2751 CString cstr;
2753 tok_str_new(&str);
2754 t0 = t1 = 0;
2755 while(1) {
2756 TOK_GET(&t, &macro_str, &cval);
2757 if (!t)
2758 break;
2759 if (t == '#') {
2760 /* stringize */
2761 TOK_GET(&t, &macro_str, &cval);
2762 if (!t)
2763 goto bad_stringy;
2764 s = sym_find2(args, t);
2765 if (s) {
2766 cstr_new(&cstr);
2767 cstr_ccat(&cstr, '\"');
2768 st = s->d;
2769 spc = 0;
2770 while (*st) {
2771 TOK_GET(&t, &st, &cval);
2772 if (t != TOK_PLCHLDR
2773 && t != TOK_NOSUBST
2774 && 0 == check_space(t, &spc)) {
2775 const char *s = get_tok_str(t, &cval);
2776 while (*s) {
2777 if (t == TOK_PPSTR && *s != '\'')
2778 add_char(&cstr, *s);
2779 else
2780 cstr_ccat(&cstr, *s);
2781 ++s;
2785 cstr.size -= spc;
2786 cstr_ccat(&cstr, '\"');
2787 cstr_ccat(&cstr, '\0');
2788 #ifdef PP_DEBUG
2789 printf("\nstringize: <%s>\n", (char *)cstr.data);
2790 #endif
2791 /* add string */
2792 cval.cstr = &cstr;
2793 tok_str_add2(&str, TOK_PPSTR, &cval);
2794 cstr_free(cval.cstr);
2795 } else {
2796 bad_stringy:
2797 expect("macro parameter after '#'");
2799 } else if (t >= TOK_IDENT) {
2800 s = sym_find2(args, t);
2801 if (s) {
2802 int l0 = str.len;
2803 st = s->d;
2804 /* if '##' is present before or after, no arg substitution */
2805 if (*macro_str == TOK_TWOSHARPS || t1 == TOK_TWOSHARPS) {
2806 /* special case for var arg macros : ## eats the ','
2807 if empty VA_ARGS variable. */
2808 if (t1 == TOK_TWOSHARPS && t0 == ',' && gnu_ext && s->type.t) {
2809 if (*st == 0) {
2810 /* suppress ',' '##' */
2811 str.len -= 2;
2812 } else {
2813 /* suppress '##' and add variable */
2814 str.len--;
2815 goto add_var;
2817 } else {
2818 for(;;) {
2819 int t1;
2820 TOK_GET(&t1, &st, &cval);
2821 if (!t1)
2822 break;
2823 tok_str_add2(&str, t1, &cval);
2827 } else {
2828 add_var:
2829 /* NOTE: the stream cannot be read when macro
2830 substituing an argument */
2831 macro_subst(&str, nested_list, st, 0);
2833 if (str.len == l0) /* exanded to empty string */
2834 tok_str_add(&str, TOK_PLCHLDR);
2835 } else {
2836 tok_str_add(&str, t);
2838 } else {
2839 tok_str_add2(&str, t, &cval);
2841 t0 = t1, t1 = t;
2843 tok_str_add(&str, 0);
2844 return str.str;
2847 static char const ab_month_name[12][4] =
2849 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2850 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2853 /* peek or read [ws_str == NULL] next token from function macro call,
2854 walking up macro levels up to the file if necessary */
2855 static int next_argstream(Sym **nested_list, int can_read_stream, TokenString *ws_str)
2857 int t;
2858 const int *p;
2859 Sym *sa;
2861 for (;;) {
2862 if (macro_ptr) {
2863 p = macro_ptr, t = *p;
2864 if (ws_str) {
2865 while (is_space(t) || TOK_LINEFEED == t)
2866 tok_str_add(ws_str, t), t = *++p;
2868 if (t == 0 && can_read_stream) {
2869 end_macro();
2870 /* also, end of scope for nested defined symbol */
2871 sa = *nested_list;
2872 while (sa && sa->v == -1)
2873 sa = sa->prev;
2874 if (sa)
2875 sa->v = -1;
2876 continue;
2878 } else {
2879 ch = handle_eob();
2880 if (ws_str) {
2881 while (is_space(ch) || ch == '\n' || ch == '/') {
2882 if (ch == '/') {
2883 int c;
2884 uint8_t *p = file->buf_ptr;
2885 PEEKC(c, p);
2886 if (c == '*') {
2887 p = parse_comment(p);
2888 file->buf_ptr = p - 1;
2889 } else if (c == '/') {
2890 p = parse_line_comment(p);
2891 file->buf_ptr = p - 1;
2892 } else
2893 break;
2894 ch = ' ';
2896 tok_str_add(ws_str, ch);
2897 cinp();
2900 t = ch;
2903 if (ws_str)
2904 return t;
2905 next_nomacro_spc();
2906 return tok;
2910 /* do macro substitution of current token with macro 's' and add
2911 result to (tok_str,tok_len). 'nested_list' is the list of all
2912 macros we got inside to avoid recursing. Return non zero if no
2913 substitution needs to be done */
2914 static int macro_subst_tok(
2915 TokenString *tok_str,
2916 Sym **nested_list,
2917 Sym *s,
2918 int can_read_stream)
2920 Sym *args, *sa, *sa1;
2921 int parlevel, *mstr, t, t1, spc;
2922 TokenString str;
2923 char *cstrval;
2924 CValue cval;
2925 CString cstr;
2926 char buf[32];
2928 /* if symbol is a macro, prepare substitution */
2929 /* special macros */
2930 if (tok == TOK___LINE__) {
2931 snprintf(buf, sizeof(buf), "%d", file->line_num);
2932 cstrval = buf;
2933 t1 = TOK_PPNUM;
2934 goto add_cstr1;
2935 } else if (tok == TOK___FILE__) {
2936 cstrval = file->filename;
2937 goto add_cstr;
2938 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
2939 time_t ti;
2940 struct tm *tm;
2942 time(&ti);
2943 tm = localtime(&ti);
2944 if (tok == TOK___DATE__) {
2945 snprintf(buf, sizeof(buf), "%s %2d %d",
2946 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
2947 } else {
2948 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
2949 tm->tm_hour, tm->tm_min, tm->tm_sec);
2951 cstrval = buf;
2952 add_cstr:
2953 t1 = TOK_STR;
2954 add_cstr1:
2955 cstr_new(&cstr);
2956 cstr_cat(&cstr, cstrval);
2957 cstr_ccat(&cstr, '\0');
2958 cval.cstr = &cstr;
2959 tok_str_add2(tok_str, t1, &cval);
2960 cstr_free(&cstr);
2961 } else {
2962 int saved_parse_flags = parse_flags;
2964 mstr = s->d;
2965 if (s->type.t == MACRO_FUNC) {
2966 /* whitespace between macro name and argument list */
2967 TokenString ws_str;
2968 tok_str_new(&ws_str);
2970 spc = 0;
2971 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
2972 | PARSE_FLAG_ACCEPT_STRAYS;
2974 /* get next token from argument stream */
2975 t = next_argstream(nested_list, can_read_stream, &ws_str);
2976 if (t != '(') {
2977 /* not a macro substitution after all, restore the
2978 * macro token plus all whitespace we've read.
2979 * whitespace is intentionally not merged to preserve
2980 * newlines. */
2981 parse_flags = saved_parse_flags;
2982 tok_str_add(tok_str, tok);
2983 if (parse_flags & PARSE_FLAG_SPACES) {
2984 int i;
2985 for (i = 0; i < ws_str.len; i++)
2986 tok_str_add(tok_str, ws_str.str[i]);
2988 tok_str_free(ws_str.str);
2989 return 0;
2990 } else {
2991 tok_str_free(ws_str.str);
2993 next_nomacro(); /* eat '(' */
2995 /* argument macro */
2996 args = NULL;
2997 sa = s->next;
2998 /* NOTE: empty args are allowed, except if no args */
2999 for(;;) {
3000 do {
3001 next_argstream(nested_list, can_read_stream, NULL);
3002 } while (is_space(tok) || TOK_LINEFEED == tok);
3003 empty_arg:
3004 /* handle '()' case */
3005 if (!args && !sa && tok == ')')
3006 break;
3007 if (!sa)
3008 tcc_error("macro '%s' used with too many args",
3009 get_tok_str(s->v, 0));
3010 tok_str_new(&str);
3011 parlevel = spc = 0;
3012 /* NOTE: non zero sa->t indicates VA_ARGS */
3013 while ((parlevel > 0 ||
3014 (tok != ')' &&
3015 (tok != ',' || sa->type.t)))) {
3016 if (tok == TOK_EOF || tok == 0)
3017 break;
3018 if (tok == '(')
3019 parlevel++;
3020 else if (tok == ')')
3021 parlevel--;
3022 if (tok == TOK_LINEFEED)
3023 tok = ' ';
3024 if (!check_space(tok, &spc))
3025 tok_str_add2(&str, tok, &tokc);
3026 next_argstream(nested_list, can_read_stream, NULL);
3028 if (parlevel)
3029 expect(")");
3030 str.len -= spc;
3031 tok_str_add(&str, 0);
3032 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3033 sa1->d = str.str;
3034 sa = sa->next;
3035 if (tok == ')') {
3036 /* special case for gcc var args: add an empty
3037 var arg argument if it is omitted */
3038 if (sa && sa->type.t && gnu_ext)
3039 goto empty_arg;
3040 break;
3042 if (tok != ',')
3043 expect(",");
3045 if (sa) {
3046 tcc_error("macro '%s' used with too few args",
3047 get_tok_str(s->v, 0));
3050 parse_flags = saved_parse_flags;
3052 /* now subst each arg */
3053 mstr = macro_arg_subst(nested_list, mstr, args);
3054 /* free memory */
3055 sa = args;
3056 while (sa) {
3057 sa1 = sa->prev;
3058 tok_str_free(sa->d);
3059 sym_free(sa);
3060 sa = sa1;
3064 sym_push2(nested_list, s->v, 0, 0);
3065 parse_flags = saved_parse_flags;
3066 macro_subst(tok_str, nested_list, mstr, can_read_stream);
3068 /* pop nested defined symbol */
3069 sa1 = *nested_list;
3070 *nested_list = sa1->prev;
3071 sym_free(sa1);
3072 if (mstr != s->d)
3073 tok_str_free(mstr);
3075 return 0;
3078 int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3080 CString cstr;
3081 int n;
3083 cstr_new(&cstr);
3084 if (t1 != TOK_PLCHLDR)
3085 cstr_cat(&cstr, get_tok_str(t1, v1));
3086 n = cstr.size;
3087 if (t2 != TOK_PLCHLDR)
3088 cstr_cat(&cstr, get_tok_str(t2, v2));
3089 cstr_ccat(&cstr, '\0');
3091 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3092 memcpy(file->buffer, cstr.data, cstr.size);
3093 for (;;) {
3094 next_nomacro1();
3095 if (0 == *file->buf_ptr)
3096 break;
3097 if (is_space(tok))
3098 continue;
3099 tcc_warning("pasting <%.*s> and <%s> does not give a valid preprocessing token",
3100 n, cstr.data, (char*)cstr.data + n);
3101 break;
3103 tcc_close();
3105 //printf("paste <%s>\n", (char*)cstr.data);
3106 cstr_free(&cstr);
3107 return 0;
3110 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3111 return the resulting string (which must be freed). */
3112 static inline int *macro_twosharps(const int *ptr0)
3114 int t;
3115 CValue cval;
3116 TokenString macro_str1;
3117 int start_of_nosubsts = -1;
3118 const int *ptr;
3120 /* we search the first '##' */
3121 for (ptr = ptr0;;) {
3122 TOK_GET(&t, &ptr, &cval);
3123 if (t == TOK_TWOSHARPS)
3124 break;
3125 if (t == 0)
3126 return NULL;
3129 tok_str_new(&macro_str1);
3131 //tok_print(" $$$", ptr0);
3132 for (ptr = ptr0;;) {
3133 TOK_GET(&t, &ptr, &cval);
3134 if (t == 0)
3135 break;
3136 if (t == TOK_TWOSHARPS)
3137 continue;
3138 while (*ptr == TOK_TWOSHARPS) {
3139 int t1; CValue cv1;
3140 /* given 'a##b', remove nosubsts preceding 'a' */
3141 if (start_of_nosubsts >= 0)
3142 macro_str1.len = start_of_nosubsts;
3143 /* given 'a##b', remove nosubsts preceding 'b' */
3144 while ((t1 = *++ptr) == TOK_NOSUBST)
3146 if (t1 && t1 != TOK_TWOSHARPS
3147 && t1 != ':') /* 'a##:' don't build a new token */
3149 TOK_GET(&t1, &ptr, &cv1);
3150 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3151 paste_tokens(t, &cval, t1, &cv1);
3152 t = tok, cval = tokc;
3156 if (t == TOK_NOSUBST) {
3157 if (start_of_nosubsts < 0)
3158 start_of_nosubsts = macro_str1.len;
3159 } else {
3160 start_of_nosubsts = -1;
3162 tok_str_add2(&macro_str1, t, &cval);
3164 tok_str_add(&macro_str1, 0);
3165 //tok_print(" ###", macro_str1.str);
3166 return macro_str1.str;
3169 /* do macro substitution of macro_str and add result to
3170 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3171 inside to avoid recursing. */
3172 static void macro_subst(
3173 TokenString *tok_str,
3174 Sym **nested_list,
3175 const int *macro_str,
3176 int can_read_stream
3179 Sym *s;
3180 const int *ptr;
3181 int t, spc, nosubst;
3182 CValue cval;
3183 int *macro_str1 = NULL;
3185 /* first scan for '##' operator handling */
3186 ptr = macro_str;
3187 spc = nosubst = 0;
3189 /* first scan for '##' operator handling */
3190 if (can_read_stream) {
3191 macro_str1 = macro_twosharps(ptr);
3192 if (macro_str1)
3193 ptr = macro_str1;
3196 while (1) {
3197 TOK_GET(&t, &ptr, &cval);
3198 if (t == 0)
3199 break;
3201 if (t >= TOK_IDENT && 0 == nosubst) {
3202 s = define_find(t);
3203 if (s == NULL)
3204 goto no_subst;
3206 /* if nested substitution, do nothing */
3207 if (sym_find2(*nested_list, t)) {
3208 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3209 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3210 goto no_subst;
3214 TokenString str;
3215 str.str = (int*)ptr;
3216 begin_macro(&str, 2);
3218 tok = t;
3219 macro_subst_tok(tok_str, nested_list, s, can_read_stream);
3221 if (str.alloc == 3) {
3222 /* already finished by reading function macro arguments */
3223 break;
3226 ptr = macro_ptr;
3227 end_macro ();
3230 spc = tok_str->len && is_space(tok_str->str[tok_str->len-1]);
3232 } else {
3234 if (t == '\\' && !(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3235 tcc_error("stray '\\' in program");
3237 no_subst:
3238 if (!check_space(t, &spc))
3239 tok_str_add2(tok_str, t, &cval);
3240 nosubst = 0;
3241 if (t == TOK_NOSUBST)
3242 nosubst = 1;
3245 if (macro_str1)
3246 tok_str_free(macro_str1);
3250 /* return next token with macro substitution */
3251 ST_FUNC void next(void)
3253 redo:
3254 if (parse_flags & PARSE_FLAG_SPACES)
3255 next_nomacro_spc();
3256 else
3257 next_nomacro();
3259 if (macro_ptr) {
3260 if (tok == TOK_NOSUBST || tok == TOK_PLCHLDR) {
3261 /* discard preprocessor markers */
3262 goto redo;
3263 } else if (tok == 0) {
3264 /* end of macro or unget token string */
3265 end_macro();
3266 goto redo;
3268 } else if (tok >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3269 Sym *s;
3270 /* if reading from file, try to substitute macros */
3271 s = define_find(tok);
3272 if (s) {
3273 static TokenString str; /* using static string for speed */
3274 Sym *nested_list = NULL;
3275 tok_str_new(&str);
3276 nested_list = NULL;
3277 macro_subst_tok(&str, &nested_list, s, 1);
3278 tok_str_add(&str, 0);
3279 begin_macro(&str, 0);
3280 goto redo;
3283 /* convert preprocessor tokens into C tokens */
3284 if (tok == TOK_PPNUM) {
3285 if (parse_flags & PARSE_FLAG_TOK_NUM)
3286 parse_number((char *)tokc.cstr->data);
3287 } else if (tok == TOK_PPSTR) {
3288 if (parse_flags & PARSE_FLAG_TOK_STR)
3289 parse_string((char *)tokc.cstr->data, tokc.cstr->size - 1);
3293 /* push back current token and set current token to 'last_tok'. Only
3294 identifier case handled for labels. */
3295 ST_INLN void unget_tok(int last_tok)
3297 TokenString *str = tcc_malloc(sizeof *str);
3298 tok_str_new(str);
3299 tok_str_add2(str, tok, &tokc);
3300 tok_str_add(str, 0);
3301 begin_macro(str, 1);
3302 tok = last_tok;
3305 /* better than nothing, but needs extension to handle '-E' option
3306 correctly too */
3307 ST_FUNC void preprocess_init(TCCState *s1)
3309 s1->include_stack_ptr = s1->include_stack;
3310 /* XXX: move that before to avoid having to initialize
3311 file->ifdef_stack_ptr ? */
3312 s1->ifdef_stack_ptr = s1->ifdef_stack;
3313 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3315 pvtop = vtop = vstack - 1;
3316 s1->pack_stack[0] = 0;
3317 s1->pack_stack_ptr = s1->pack_stack;
3319 isidnum_table['$' - CH_EOF] =
3320 tcc_state->dollars_in_identifiers ? IS_ID : 0;
3323 ST_FUNC void preprocess_new(void)
3325 int i, c;
3326 const char *p, *r;
3328 /* init isid table */
3329 for(i = CH_EOF; i<256; i++)
3330 isidnum_table[i - CH_EOF]
3331 = is_space(i) ? IS_SPC
3332 : isid(i) ? IS_ID
3333 : isnum(i) ? IS_NUM
3334 : 0;
3336 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3338 tok_ident = TOK_IDENT;
3339 p = tcc_keywords;
3340 while (*p) {
3341 r = p;
3342 for(;;) {
3343 c = *r++;
3344 if (c == '\0')
3345 break;
3347 tok_alloc(p, r - p - 1);
3348 p = r;
3352 ST_FUNC void preprocess_delete(void)
3354 int i, n;
3356 /* free -D and compiler defines */
3357 free_defines(NULL);
3359 /* cleanup from error/setjmp */
3360 while (macro_stack)
3361 end_macro();
3362 macro_ptr = NULL;
3364 /* free tokens */
3365 n = tok_ident - TOK_IDENT;
3366 for(i = 0; i < n; i++)
3367 tcc_free(table_ident[i]);
3368 tcc_free(table_ident);
3369 table_ident = NULL;
3372 /* Preprocess the current file */
3373 ST_FUNC int tcc_preprocess(TCCState *s1)
3375 BufferedFile **iptr;
3376 int token_seen, spcs, level;
3378 preprocess_init(s1);
3379 ch = file->buf_ptr[0];
3380 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3381 parse_flags = PARSE_FLAG_PREPROCESS
3382 | (parse_flags & PARSE_FLAG_ASM_FILE)
3383 | PARSE_FLAG_LINEFEED
3384 | PARSE_FLAG_SPACES
3385 | PARSE_FLAG_ACCEPT_STRAYS
3388 #ifdef PP_BENCH
3389 do next(); while (tok != TOK_EOF); return 0;
3390 #endif
3392 token_seen = spcs = 0;
3393 pp_line(s1, file, 0);
3395 for (;;) {
3396 iptr = s1->include_stack_ptr;
3397 next();
3398 if (tok == TOK_EOF)
3399 break;
3400 level = s1->include_stack_ptr - iptr;
3401 if (level) {
3402 if (level > 0)
3403 pp_line(s1, *iptr, 0);
3404 pp_line(s1, file, level);
3407 if (0 == token_seen) {
3408 if (tok == ' ') {
3409 ++spcs;
3410 continue;
3412 if (tok == TOK_LINEFEED) {
3413 spcs = 0;
3414 continue;
3416 pp_line(s1, file, 0);
3417 while (spcs)
3418 fputs(" ", s1->ppfp), --spcs;
3419 token_seen = 1;
3421 } else if (tok == TOK_LINEFEED) {
3422 ++file->line_ref;
3423 token_seen = 0;
3426 fputs(get_tok_str(tok, &tokc), s1->ppfp);
3429 return 0;