TODO: Add note on handling of floating-point values.
[tinycc.git] / tccpp.c
blob4dba9544000d3974688ae49f863291f981700ad8
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, "%llu", (unsigned long long)cv->i);
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->i);
303 #else
304 sprintf(p, "%llu", (unsigned long long)cv->i);
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 cstr_cat(&cstr_buf, "<float>");
338 break;
339 case TOK_CDOUBLE:
340 cstr_cat(&cstr_buf, "<double>");
341 break;
342 case TOK_CLDOUBLE:
343 cstr_cat(&cstr_buf, "<long double>");
344 break;
345 case TOK_LINENUM:
346 cstr_cat(&cstr_buf, "<linenumber>");
347 break;
348 //return NULL; /* should not happen */
350 /* above tokens have value, the ones below don't */
352 case TOK_LT:
353 v = '<';
354 goto addv;
355 case TOK_GT:
356 v = '>';
357 goto addv;
358 case TOK_DOTS:
359 return strcpy(p, "...");
360 case TOK_A_SHL:
361 return strcpy(p, "<<=");
362 case TOK_A_SAR:
363 return strcpy(p, ">>=");
364 default:
365 if (v < TOK_IDENT) {
366 /* search in two bytes table */
367 const unsigned char *q = tok_two_chars;
368 while (*q) {
369 if (q[2] == v) {
370 *p++ = q[0];
371 *p++ = q[1];
372 *p = '\0';
373 return buf;
375 q += 3;
377 if (v >= 127) {
378 sprintf(buf, "<%02x>", v);
379 return buf;
381 addv:
382 *p++ = v;
383 *p = '\0';
384 } else if (v < tok_ident) {
385 return table_ident[v - TOK_IDENT]->str;
386 } else if (v >= SYM_FIRST_ANOM) {
387 /* special name for anonymous symbol */
388 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
389 } else {
390 /* should never happen */
391 return NULL;
393 break;
395 return cstr_buf.data;
398 /* return the current character, handling end of block if necessary
399 (but not stray) */
400 ST_FUNC int handle_eob(void)
402 BufferedFile *bf = file;
403 int len;
405 /* only tries to read if really end of buffer */
406 if (bf->buf_ptr >= bf->buf_end) {
407 if (bf->fd != -1) {
408 #if defined(PARSE_DEBUG)
409 len = 1;
410 #else
411 len = IO_BUF_SIZE;
412 #endif
413 len = read(bf->fd, bf->buffer, len);
414 if (len < 0)
415 len = 0;
416 } else {
417 len = 0;
419 total_bytes += len;
420 bf->buf_ptr = bf->buffer;
421 bf->buf_end = bf->buffer + len;
422 *bf->buf_end = CH_EOB;
424 if (bf->buf_ptr < bf->buf_end) {
425 return bf->buf_ptr[0];
426 } else {
427 bf->buf_ptr = bf->buf_end;
428 return CH_EOF;
432 /* read next char from current input file and handle end of input buffer */
433 ST_INLN void inp(void)
435 ch = *(++(file->buf_ptr));
436 /* end of buffer/file handling */
437 if (ch == CH_EOB)
438 ch = handle_eob();
441 /* handle '\[\r]\n' */
442 static int handle_stray_noerror(void)
444 while (ch == '\\') {
445 inp();
446 if (ch == '\n') {
447 file->line_num++;
448 inp();
449 } else if (ch == '\r') {
450 inp();
451 if (ch != '\n')
452 goto fail;
453 file->line_num++;
454 inp();
455 } else {
456 fail:
457 return 1;
460 return 0;
463 static void handle_stray(void)
465 if (handle_stray_noerror())
466 tcc_error("stray '\\' in program");
469 /* skip the stray and handle the \\n case. Output an error if
470 incorrect char after the stray */
471 static int handle_stray1(uint8_t *p)
473 int c;
475 file->buf_ptr = p;
476 if (p >= file->buf_end) {
477 c = handle_eob();
478 if (c != '\\')
479 return c;
480 p = file->buf_ptr;
482 ch = *p;
483 if (handle_stray_noerror()) {
484 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
485 tcc_error("stray '\\' in program");
486 *--file->buf_ptr = '\\';
488 p = file->buf_ptr;
489 c = *p;
490 return c;
493 /* handle just the EOB case, but not stray */
494 #define PEEKC_EOB(c, p)\
496 p++;\
497 c = *p;\
498 if (c == '\\') {\
499 file->buf_ptr = p;\
500 c = handle_eob();\
501 p = file->buf_ptr;\
505 /* handle the complicated stray case */
506 #define PEEKC(c, p)\
508 p++;\
509 c = *p;\
510 if (c == '\\') {\
511 c = handle_stray1(p);\
512 p = file->buf_ptr;\
516 /* input with '\[\r]\n' handling. Note that this function cannot
517 handle other characters after '\', so you cannot call it inside
518 strings or comments */
519 ST_FUNC void minp(void)
521 inp();
522 if (ch == '\\')
523 handle_stray();
527 /* single line C++ comments */
528 static uint8_t *parse_line_comment(uint8_t *p)
530 int c;
532 p++;
533 for(;;) {
534 c = *p;
535 redo:
536 if (c == '\n' || c == CH_EOF) {
537 break;
538 } else if (c == '\\') {
539 file->buf_ptr = p;
540 c = handle_eob();
541 p = file->buf_ptr;
542 if (c == '\\') {
543 PEEKC_EOB(c, p);
544 if (c == '\n') {
545 file->line_num++;
546 PEEKC_EOB(c, p);
547 } else if (c == '\r') {
548 PEEKC_EOB(c, p);
549 if (c == '\n') {
550 file->line_num++;
551 PEEKC_EOB(c, p);
554 } else {
555 goto redo;
557 } else {
558 p++;
561 return p;
564 /* C comments */
565 ST_FUNC uint8_t *parse_comment(uint8_t *p)
567 int c;
569 p++;
570 for(;;) {
571 /* fast skip loop */
572 for(;;) {
573 c = *p;
574 if (c == '\n' || c == '*' || c == '\\')
575 break;
576 p++;
577 c = *p;
578 if (c == '\n' || c == '*' || c == '\\')
579 break;
580 p++;
582 /* now we can handle all the cases */
583 if (c == '\n') {
584 file->line_num++;
585 p++;
586 } else if (c == '*') {
587 p++;
588 for(;;) {
589 c = *p;
590 if (c == '*') {
591 p++;
592 } else if (c == '/') {
593 goto end_of_comment;
594 } else if (c == '\\') {
595 file->buf_ptr = p;
596 c = handle_eob();
597 p = file->buf_ptr;
598 if (c == CH_EOF)
599 tcc_error("unexpected end of file in comment");
600 if (c == '\\') {
601 /* skip '\[\r]\n', otherwise just skip the stray */
602 while (c == '\\') {
603 PEEKC_EOB(c, p);
604 if (c == '\n') {
605 file->line_num++;
606 PEEKC_EOB(c, p);
607 } else if (c == '\r') {
608 PEEKC_EOB(c, p);
609 if (c == '\n') {
610 file->line_num++;
611 PEEKC_EOB(c, p);
613 } else {
614 goto after_star;
618 } else {
619 break;
622 after_star: ;
623 } else {
624 /* stray, eob or eof */
625 file->buf_ptr = p;
626 c = handle_eob();
627 p = file->buf_ptr;
628 if (c == CH_EOF) {
629 tcc_error("unexpected end of file in comment");
630 } else if (c == '\\') {
631 p++;
635 end_of_comment:
636 p++;
637 return p;
640 #define cinp minp
642 static inline void skip_spaces(void)
644 while (isidnum_table[ch - CH_EOF] & IS_SPC)
645 cinp();
648 static inline int check_space(int t, int *spc)
650 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
651 if (*spc)
652 return 1;
653 *spc = 1;
654 } else
655 *spc = 0;
656 return 0;
659 /* parse a string without interpreting escapes */
660 static uint8_t *parse_pp_string(uint8_t *p,
661 int sep, CString *str)
663 int c;
664 p++;
665 for(;;) {
666 c = *p;
667 if (c == sep) {
668 break;
669 } else if (c == '\\') {
670 file->buf_ptr = p;
671 c = handle_eob();
672 p = file->buf_ptr;
673 if (c == CH_EOF) {
674 unterminated_string:
675 /* XXX: indicate line number of start of string */
676 tcc_error("missing terminating %c character", sep);
677 } else if (c == '\\') {
678 /* escape : just skip \[\r]\n */
679 PEEKC_EOB(c, p);
680 if (c == '\n') {
681 file->line_num++;
682 p++;
683 } else if (c == '\r') {
684 PEEKC_EOB(c, p);
685 if (c != '\n')
686 expect("'\n' after '\r'");
687 file->line_num++;
688 p++;
689 } else if (c == CH_EOF) {
690 goto unterminated_string;
691 } else {
692 if (str) {
693 cstr_ccat(str, '\\');
694 cstr_ccat(str, c);
696 p++;
699 } else if (c == '\n') {
700 file->line_num++;
701 goto add_char;
702 } else if (c == '\r') {
703 PEEKC_EOB(c, p);
704 if (c != '\n') {
705 if (str)
706 cstr_ccat(str, '\r');
707 } else {
708 file->line_num++;
709 goto add_char;
711 } else {
712 add_char:
713 if (str)
714 cstr_ccat(str, c);
715 p++;
718 p++;
719 return p;
722 /* skip block of text until #else, #elif or #endif. skip also pairs of
723 #if/#endif */
724 static void preprocess_skip(void)
726 int a, start_of_line, c, in_warn_or_error;
727 uint8_t *p;
729 p = file->buf_ptr;
730 a = 0;
731 redo_start:
732 start_of_line = 1;
733 in_warn_or_error = 0;
734 for(;;) {
735 redo_no_start:
736 c = *p;
737 switch(c) {
738 case ' ':
739 case '\t':
740 case '\f':
741 case '\v':
742 case '\r':
743 p++;
744 goto redo_no_start;
745 case '\n':
746 file->line_num++;
747 p++;
748 goto redo_start;
749 case '\\':
750 file->buf_ptr = p;
751 c = handle_eob();
752 if (c == CH_EOF) {
753 expect("#endif");
754 } else if (c == '\\') {
755 ch = file->buf_ptr[0];
756 handle_stray_noerror();
758 p = file->buf_ptr;
759 goto redo_no_start;
760 /* skip strings */
761 case '\"':
762 case '\'':
763 if (in_warn_or_error)
764 goto _default;
765 p = parse_pp_string(p, c, NULL);
766 break;
767 /* skip comments */
768 case '/':
769 if (in_warn_or_error)
770 goto _default;
771 file->buf_ptr = p;
772 ch = *p;
773 minp();
774 p = file->buf_ptr;
775 if (ch == '*') {
776 p = parse_comment(p);
777 } else if (ch == '/') {
778 p = parse_line_comment(p);
780 break;
781 case '#':
782 p++;
783 if (start_of_line) {
784 file->buf_ptr = p;
785 next_nomacro();
786 p = file->buf_ptr;
787 if (a == 0 &&
788 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
789 goto the_end;
790 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
791 a++;
792 else if (tok == TOK_ENDIF)
793 a--;
794 else if( tok == TOK_ERROR || tok == TOK_WARNING)
795 in_warn_or_error = 1;
796 else if (tok == TOK_LINEFEED)
797 goto redo_start;
798 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
799 p = parse_line_comment(p);
800 break;
801 _default:
802 default:
803 p++;
804 break;
806 start_of_line = 0;
808 the_end: ;
809 file->buf_ptr = p;
812 /* ParseState handling */
814 /* XXX: currently, no include file info is stored. Thus, we cannot display
815 accurate messages if the function or data definition spans multiple
816 files */
818 /* save current parse state in 's' */
819 ST_FUNC void save_parse_state(ParseState *s)
821 s->line_num = file->line_num;
822 s->macro_ptr = macro_ptr;
823 s->tok = tok;
824 s->tokc = tokc;
827 /* restore parse state from 's' */
828 ST_FUNC void restore_parse_state(ParseState *s)
830 file->line_num = s->line_num;
831 macro_ptr = s->macro_ptr;
832 tok = s->tok;
833 tokc = s->tokc;
836 /* return the number of additional 'ints' necessary to store the
837 token */
838 static inline int tok_size(const int *p)
840 switch(*p) {
841 /* 4 bytes */
842 case TOK_CINT:
843 case TOK_CUINT:
844 case TOK_CCHAR:
845 case TOK_LCHAR:
846 case TOK_CFLOAT:
847 case TOK_LINENUM:
848 return 1 + 1;
849 case TOK_STR:
850 case TOK_LSTR:
851 case TOK_PPNUM:
852 case TOK_PPSTR:
853 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
854 case TOK_CDOUBLE:
855 case TOK_CLLONG:
856 case TOK_CULLONG:
857 return 1 + 2;
858 case TOK_CLDOUBLE:
859 return 1 + LDOUBLE_SIZE / 4;
860 default:
861 return 1 + 0;
865 /* token string handling */
867 ST_INLN void tok_str_new(TokenString *s)
869 s->str = NULL;
870 s->len = 0;
871 s->allocated_len = 0;
872 s->last_line_num = -1;
875 ST_FUNC void tok_str_free(int *str)
877 tcc_free(str);
880 static int *tok_str_realloc(TokenString *s)
882 int *str, len;
884 if (s->allocated_len == 0) {
885 len = 8;
886 } else {
887 len = s->allocated_len * 2;
889 str = tcc_realloc(s->str, len * sizeof(int));
890 s->allocated_len = len;
891 s->str = str;
892 return str;
895 ST_FUNC void tok_str_add(TokenString *s, int t)
897 int len, *str;
899 len = s->len;
900 str = s->str;
901 if (len >= s->allocated_len)
902 str = tok_str_realloc(s);
903 str[len++] = t;
904 s->len = len;
907 static void tok_str_add2(TokenString *s, int t, CValue *cv)
909 int len, *str;
911 len = s->len;
912 str = s->str;
914 /* allocate space for worst case */
915 if (len + TOK_MAX_SIZE > s->allocated_len)
916 str = tok_str_realloc(s);
917 str[len++] = t;
918 switch(t) {
919 case TOK_CINT:
920 case TOK_CUINT:
921 case TOK_CCHAR:
922 case TOK_LCHAR:
923 case TOK_CFLOAT:
924 case TOK_LINENUM:
925 str[len++] = cv->tab[0];
926 break;
927 case TOK_PPNUM:
928 case TOK_PPSTR:
929 case TOK_STR:
930 case TOK_LSTR:
932 int nb_words;
933 CString cstr;
935 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
936 while ((len + nb_words) > s->allocated_len)
937 str = tok_str_realloc(s);
938 /* XXX: Insert the CString into the int array.
939 It may end up incorrectly aligned. */
940 cstr.data = 0;
941 cstr.size = cv->cstr->size;
942 cstr.data_allocated = 0;
943 cstr.size_allocated = cstr.size;
944 memcpy(str + len, &cstr, sizeof(CString));
945 memcpy((char *)(str + len) + sizeof(CString),
946 cv->cstr->data, cstr.size);
947 len += nb_words;
949 break;
950 case TOK_CDOUBLE:
951 case TOK_CLLONG:
952 case TOK_CULLONG:
953 #if LDOUBLE_SIZE == 8
954 case TOK_CLDOUBLE:
955 #endif
956 str[len++] = cv->tab[0];
957 str[len++] = cv->tab[1];
958 break;
959 #if LDOUBLE_SIZE == 12
960 case TOK_CLDOUBLE:
961 str[len++] = cv->tab[0];
962 str[len++] = cv->tab[1];
963 str[len++] = cv->tab[2];
964 #elif LDOUBLE_SIZE == 16
965 case TOK_CLDOUBLE:
966 str[len++] = cv->tab[0];
967 str[len++] = cv->tab[1];
968 str[len++] = cv->tab[2];
969 str[len++] = cv->tab[3];
970 #elif LDOUBLE_SIZE != 8
971 #error add long double size support
972 #endif
973 break;
974 default:
975 break;
977 s->len = len;
980 /* add the current parse token in token string 's' */
981 ST_FUNC void tok_str_add_tok(TokenString *s)
983 CValue cval;
985 /* save line number info */
986 if (file->line_num != s->last_line_num) {
987 s->last_line_num = file->line_num;
988 cval.i = s->last_line_num;
989 tok_str_add2(s, TOK_LINENUM, &cval);
991 tok_str_add2(s, tok, &tokc);
994 /* get a token from an integer array and increment pointer
995 accordingly. we code it as a macro to avoid pointer aliasing. */
996 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
998 const int *p = *pp;
999 int n, *tab;
1001 tab = cv->tab;
1002 switch(*t = *p++) {
1003 case TOK_CINT:
1004 case TOK_CUINT:
1005 case TOK_CCHAR:
1006 case TOK_LCHAR:
1007 case TOK_CFLOAT:
1008 case TOK_LINENUM:
1009 tab[0] = *p++;
1010 break;
1011 case TOK_STR:
1012 case TOK_LSTR:
1013 case TOK_PPNUM:
1014 case TOK_PPSTR:
1015 /* XXX: Illegal cast: the pointer p may not be correctly aligned! */
1016 cv->cstr = (CString *)p;
1017 cv->cstr->data = (char *)p + sizeof(CString);
1018 p += (sizeof(CString) + cv->cstr->size + 3) >> 2;
1019 break;
1020 case TOK_CDOUBLE:
1021 case TOK_CLLONG:
1022 case TOK_CULLONG:
1023 n = 2;
1024 goto copy;
1025 case TOK_CLDOUBLE:
1026 #if LDOUBLE_SIZE == 16
1027 n = 4;
1028 #elif LDOUBLE_SIZE == 12
1029 n = 3;
1030 #elif LDOUBLE_SIZE == 8
1031 n = 2;
1032 #else
1033 # error add long double size support
1034 #endif
1035 copy:
1037 *tab++ = *p++;
1038 while (--n);
1039 break;
1040 default:
1041 break;
1043 *pp = p;
1046 /* Calling this function is expensive, but it is not possible
1047 to read a token string backwards. */
1048 static int tok_last(const int *str0, const int *str1)
1050 const int *str = str0;
1051 int tok = 0;
1052 CValue cval;
1054 while (str < str1)
1055 TOK_GET(&tok, &str, &cval);
1056 return tok;
1059 static int macro_is_equal(const int *a, const int *b)
1061 char buf[STRING_MAX_SIZE + 1];
1062 CValue cv;
1063 int t;
1064 while (*a && *b) {
1065 TOK_GET(&t, &a, &cv);
1066 pstrcpy(buf, sizeof buf, get_tok_str(t, &cv));
1067 TOK_GET(&t, &b, &cv);
1068 if (strcmp(buf, get_tok_str(t, &cv)))
1069 return 0;
1071 return !(*a || *b);
1074 static void pp_line(TCCState *s1, BufferedFile *f, int level)
1076 int d = f->line_num - f->line_ref;
1077 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE
1078 || (level == 0 && f->line_ref && d < 8))
1080 while (d > 0)
1081 fputs("\n", s1->ppfp), --d;
1083 else
1084 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
1085 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
1087 else {
1088 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
1089 level > 0 ? " 1" : level < 0 ? " 2" : "");
1091 f->line_ref = f->line_num;
1094 static void tok_print(const char *msg, const int *str)
1096 FILE *pr = tcc_state->ppfp;
1097 int t;
1098 CValue cval;
1100 fprintf(pr, "%s ", msg);
1101 while (str) {
1102 TOK_GET(&t, &str, &cval);
1103 if (!t)
1104 break;
1105 fprintf(pr,"%s", get_tok_str(t, &cval));
1107 fprintf(pr, "\n");
1110 static int define_print_prepared(Sym *s)
1112 if (!s || !tcc_state->ppfp || tcc_state->dflag == 0)
1113 return 0;
1115 if (s->v < TOK_IDENT || s->v >= tok_ident)
1116 return 0;
1118 if (file) {
1119 file->line_num--;
1120 pp_line(tcc_state, file, 0);
1121 file->line_ref = ++file->line_num;
1123 return 1;
1126 static void define_print(int v)
1128 FILE *pr = tcc_state->ppfp;
1129 Sym *s, *a;
1131 s = define_find(v);
1132 if (define_print_prepared(s) == 0)
1133 return;
1135 fprintf(pr, "// #define %s", get_tok_str(v, NULL));
1136 if (s->type.t == MACRO_FUNC) {
1137 a = s->next;
1138 fprintf(pr,"(");
1139 if (a)
1140 for (;;) {
1141 fprintf(pr,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
1142 if (!(a = a->next))
1143 break;
1144 fprintf(pr,",");
1146 fprintf(pr,")");
1148 tok_print("", s->d);
1151 static void undef_print(int v)
1153 FILE *pr = tcc_state->ppfp;
1154 Sym *s;
1156 s = define_find(v);
1157 if (define_print_prepared(s) == 0)
1158 return;
1160 fprintf(pr, "// #undef %s\n", get_tok_str(s->v, NULL));
1163 ST_FUNC void print_defines(void)
1165 Sym *top = define_stack;
1166 while (top) {
1167 define_print(top->v);
1168 top = top->prev;
1172 /* defines handling */
1173 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1175 Sym *s;
1177 s = define_find(v);
1178 if (s && !macro_is_equal(s->d, str))
1179 tcc_warning("%s redefined", get_tok_str(v, NULL));
1181 s = sym_push2(&define_stack, v, macro_type, 0);
1182 s->d = str;
1183 s->next = first_arg;
1184 table_ident[v - TOK_IDENT]->sym_define = s;
1187 /* undefined a define symbol. Its name is just set to zero */
1188 ST_FUNC void define_undef(Sym *s)
1190 int v = s->v;
1191 undef_print(v);
1192 if (v >= TOK_IDENT && v < tok_ident)
1193 table_ident[v - TOK_IDENT]->sym_define = NULL;
1196 ST_INLN Sym *define_find(int v)
1198 v -= TOK_IDENT;
1199 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1200 return NULL;
1201 return table_ident[v]->sym_define;
1204 /* free define stack until top reaches 'b' */
1205 ST_FUNC void free_defines(Sym *b)
1207 Sym *top, *top1;
1208 int v;
1210 top = define_stack;
1211 while (top != b) {
1212 top1 = top->prev;
1213 /* do not free args or predefined defines */
1214 if (top->d)
1215 tok_str_free(top->d);
1216 v = top->v;
1217 if (v >= TOK_IDENT && v < tok_ident)
1218 table_ident[v - TOK_IDENT]->sym_define = NULL;
1219 sym_free(top);
1220 top = top1;
1222 define_stack = b;
1225 /* label lookup */
1226 ST_FUNC Sym *label_find(int v)
1228 v -= TOK_IDENT;
1229 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1230 return NULL;
1231 return table_ident[v]->sym_label;
1234 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1236 Sym *s, **ps;
1237 s = sym_push2(ptop, v, 0, 0);
1238 s->r = flags;
1239 ps = &table_ident[v - TOK_IDENT]->sym_label;
1240 if (ptop == &global_label_stack) {
1241 /* modify the top most local identifier, so that
1242 sym_identifier will point to 's' when popped */
1243 while (*ps != NULL)
1244 ps = &(*ps)->prev_tok;
1246 s->prev_tok = *ps;
1247 *ps = s;
1248 return s;
1251 /* pop labels until element last is reached. Look if any labels are
1252 undefined. Define symbols if '&&label' was used. */
1253 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1255 Sym *s, *s1;
1256 for(s = *ptop; s != slast; s = s1) {
1257 s1 = s->prev;
1258 if (s->r == LABEL_DECLARED) {
1259 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1260 } else if (s->r == LABEL_FORWARD) {
1261 tcc_error("label '%s' used but not defined",
1262 get_tok_str(s->v, NULL));
1263 } else {
1264 if (s->c) {
1265 /* define corresponding symbol. A size of
1266 1 is put. */
1267 put_extern_sym(s, cur_text_section, s->jnext, 1);
1270 /* remove label */
1271 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1272 sym_free(s);
1274 *ptop = slast;
1277 /* eval an expression for #if/#elif */
1278 static int expr_preprocess(void)
1280 int c, t;
1281 TokenString str;
1283 tok_str_new(&str);
1284 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1285 next(); /* do macro subst */
1286 if (tok == TOK_DEFINED) {
1287 next_nomacro();
1288 t = tok;
1289 if (t == '(')
1290 next_nomacro();
1291 c = define_find(tok) != 0;
1292 if (t == '(')
1293 next_nomacro();
1294 tok = TOK_CINT;
1295 tokc.i = c;
1296 } else if (tok >= TOK_IDENT) {
1297 /* if undefined macro */
1298 tok = TOK_CINT;
1299 tokc.i = 0;
1301 tok_str_add_tok(&str);
1303 tok_str_add(&str, -1); /* simulate end of file */
1304 tok_str_add(&str, 0);
1305 /* now evaluate C constant expression */
1306 begin_macro(&str, 0);
1307 next();
1308 c = expr_const();
1309 end_macro();
1310 return c != 0;
1314 /* parse after #define */
1315 ST_FUNC void parse_define(void)
1317 Sym *s, *first, **ps;
1318 int v, t, varg, is_vaargs, spc;
1319 int saved_parse_flags = parse_flags;
1320 TokenString str;
1322 v = tok;
1323 if (v < TOK_IDENT)
1324 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1325 /* XXX: should check if same macro (ANSI) */
1326 first = NULL;
1327 t = MACRO_OBJ;
1328 /* '(' must be just after macro definition for MACRO_FUNC */
1329 parse_flags |= PARSE_FLAG_SPACES;
1330 next_nomacro_spc();
1331 if (tok == '(') {
1332 next_nomacro();
1333 ps = &first;
1334 if (tok != ')') for (;;) {
1335 varg = tok;
1336 next_nomacro();
1337 is_vaargs = 0;
1338 if (varg == TOK_DOTS) {
1339 varg = TOK___VA_ARGS__;
1340 is_vaargs = 1;
1341 } else if (tok == TOK_DOTS && gnu_ext) {
1342 is_vaargs = 1;
1343 next_nomacro();
1345 if (varg < TOK_IDENT)
1346 bad_list:
1347 tcc_error("bad macro parameter list");
1348 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1349 *ps = s;
1350 ps = &s->next;
1351 if (tok == ')')
1352 break;
1353 if (tok != ',' || is_vaargs)
1354 goto bad_list;
1355 next_nomacro();
1357 next_nomacro_spc();
1358 t = MACRO_FUNC;
1360 tok_str_new(&str);
1361 spc = 2;
1362 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1363 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1364 /* remove spaces around ## and after '#' */
1365 if (TOK_TWOSHARPS == tok) {
1366 if (2 == spc)
1367 goto bad_twosharp;
1368 if (1 == spc)
1369 --str.len;
1370 spc = 3;
1371 } else if ('#' == tok) {
1372 spc = 4;
1373 } else if (check_space(tok, &spc)) {
1374 goto skip;
1376 tok_str_add2(&str, tok, &tokc);
1377 skip:
1378 next_nomacro_spc();
1381 parse_flags = saved_parse_flags;
1382 if (spc == 1)
1383 --str.len; /* remove trailing space */
1384 tok_str_add(&str, 0);
1385 if (3 == spc)
1386 bad_twosharp:
1387 tcc_error("'##' cannot appear at either end of macro");
1388 define_push(v, t, str.str, first);
1389 define_print(v);
1392 static inline int hash_cached_include(const char *filename)
1394 const unsigned char *s;
1395 unsigned int h;
1397 h = TOK_HASH_INIT;
1398 s = (unsigned char *) filename;
1399 while (*s) {
1400 h = TOK_HASH_FUNC(h, *s);
1401 s++;
1403 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1404 return h;
1407 static CachedInclude *search_cached_include(TCCState *s1, const char *filename)
1409 CachedInclude *e;
1410 int i, h;
1411 h = hash_cached_include(filename);
1412 i = s1->cached_includes_hash[h];
1413 for(;;) {
1414 if (i == 0)
1415 break;
1416 e = s1->cached_includes[i - 1];
1417 if (0 == PATHCMP(e->filename, filename))
1418 return e;
1419 i = e->hash_next;
1421 return NULL;
1424 static inline void add_cached_include(TCCState *s1, const char *filename, int ifndef_macro)
1426 CachedInclude *e;
1427 int h;
1429 if (search_cached_include(s1, filename))
1430 return;
1431 #ifdef INC_DEBUG
1432 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
1433 #endif
1434 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1435 strcpy(e->filename, filename);
1436 e->ifndef_macro = ifndef_macro;
1437 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1438 /* add in hash table */
1439 h = hash_cached_include(filename);
1440 e->hash_next = s1->cached_includes_hash[h];
1441 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1444 static void pragma_parse(TCCState *s1)
1446 next_nomacro();
1447 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1448 int t = tok, v;
1449 Sym *s;
1451 if (next(), tok != '(')
1452 goto pragma_err;
1453 if (next(), tok != TOK_STR)
1454 goto pragma_err;
1455 v = tok_alloc(tokc.cstr->data, tokc.cstr->size - 1)->tok;
1456 if (next(), tok != ')')
1457 goto pragma_err;
1458 if (t == TOK_push_macro) {
1459 while (NULL == (s = define_find(v)))
1460 define_push(v, 0, NULL, NULL);
1461 s->type.ref = s; /* set push boundary */
1462 } else {
1463 for (s = define_stack; s; s = s->prev)
1464 if (s->v == v && s->type.ref == s) {
1465 s->type.ref = NULL;
1466 break;
1469 if (s)
1470 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1471 else
1472 tcc_warning("unbalanced #pragma pop_macro");
1474 } else if (tok == TOK_once) {
1475 add_cached_include(s1, file->filename, TOK_once);
1477 } else if (s1->ppfp) {
1478 /* tcc -E: keep pragmas below unchanged */
1479 unget_tok(' ');
1480 unget_tok(TOK_PRAGMA);
1481 unget_tok('#');
1482 unget_tok(TOK_LINEFEED);
1484 } else if (tok == TOK_pack) {
1485 /* This may be:
1486 #pragma pack(1) // set
1487 #pragma pack() // reset to default
1488 #pragma pack(push,1) // push & set
1489 #pragma pack(pop) // restore previous */
1490 next();
1491 skip('(');
1492 if (tok == TOK_ASM_pop) {
1493 next();
1494 if (s1->pack_stack_ptr <= s1->pack_stack) {
1495 stk_error:
1496 tcc_error("out of pack stack");
1498 s1->pack_stack_ptr--;
1499 } else {
1500 int val = 0;
1501 if (tok != ')') {
1502 if (tok == TOK_ASM_push) {
1503 next();
1504 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1505 goto stk_error;
1506 s1->pack_stack_ptr++;
1507 skip(',');
1509 if (tok != TOK_CINT)
1510 goto pragma_err;
1511 val = tokc.i;
1512 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1513 goto pragma_err;
1514 next();
1516 *s1->pack_stack_ptr = val;
1518 if (tok != ')')
1519 goto pragma_err;
1521 } else if (tok == TOK_comment) {
1522 char *file;
1523 next();
1524 skip('(');
1525 if (tok != TOK_lib)
1526 goto pragma_warn;
1527 next();
1528 skip(',');
1529 if (tok != TOK_STR)
1530 goto pragma_err;
1531 file = tcc_strdup((char *)tokc.cstr->data);
1532 dynarray_add((void ***)&s1->pragma_libs, &s1->nb_pragma_libs, file);
1533 next();
1534 if (tok != ')')
1535 goto pragma_err;
1536 } else {
1537 pragma_warn:
1538 if (s1->warn_unsupported)
1539 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1541 return;
1543 pragma_err:
1544 tcc_error("malformed #pragma directive");
1545 return;
1548 /* is_bof is true if first non space token at beginning of file */
1549 ST_FUNC void preprocess(int is_bof)
1551 TCCState *s1 = tcc_state;
1552 int i, c, n, saved_parse_flags;
1553 char buf[1024], *q;
1554 Sym *s;
1556 saved_parse_flags = parse_flags;
1557 parse_flags = PARSE_FLAG_PREPROCESS
1558 | PARSE_FLAG_TOK_NUM
1559 | PARSE_FLAG_TOK_STR
1560 | PARSE_FLAG_LINEFEED
1561 | (parse_flags & PARSE_FLAG_ASM_FILE)
1564 next_nomacro();
1565 redo:
1566 switch(tok) {
1567 case TOK_DEFINE:
1568 next_nomacro();
1569 parse_define();
1570 break;
1571 case TOK_UNDEF:
1572 next_nomacro();
1573 s = define_find(tok);
1574 /* undefine symbol by putting an invalid name */
1575 if (s)
1576 define_undef(s);
1577 break;
1578 case TOK_INCLUDE:
1579 case TOK_INCLUDE_NEXT:
1580 ch = file->buf_ptr[0];
1581 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1582 skip_spaces();
1583 if (ch == '<') {
1584 c = '>';
1585 goto read_name;
1586 } else if (ch == '\"') {
1587 c = ch;
1588 read_name:
1589 inp();
1590 q = buf;
1591 while (ch != c && ch != '\n' && ch != CH_EOF) {
1592 if ((q - buf) < sizeof(buf) - 1)
1593 *q++ = ch;
1594 if (ch == '\\') {
1595 if (handle_stray_noerror() == 0)
1596 --q;
1597 } else
1598 inp();
1600 *q = '\0';
1601 minp();
1602 #if 0
1603 /* eat all spaces and comments after include */
1604 /* XXX: slightly incorrect */
1605 while (ch1 != '\n' && ch1 != CH_EOF)
1606 inp();
1607 #endif
1608 } else {
1609 /* computed #include : either we have only strings or
1610 we have anything enclosed in '<>' */
1611 next();
1612 buf[0] = '\0';
1613 if (tok == TOK_STR) {
1614 while (tok != TOK_LINEFEED) {
1615 if (tok != TOK_STR) {
1616 include_syntax:
1617 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1619 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
1620 next();
1622 c = '\"';
1623 } else {
1624 int len;
1625 while (tok != TOK_LINEFEED) {
1626 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1627 next();
1629 len = strlen(buf);
1630 /* check syntax and remove '<>' */
1631 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1632 goto include_syntax;
1633 memmove(buf, buf + 1, len - 2);
1634 buf[len - 2] = '\0';
1635 c = '>';
1639 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1640 tcc_error("#include recursion too deep");
1641 /* store current file in stack, but increment stack later below */
1642 *s1->include_stack_ptr = file;
1643 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index : 0;
1644 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1645 for (; i < n; ++i) {
1646 char buf1[sizeof file->filename];
1647 CachedInclude *e;
1648 const char *path;
1650 if (i == 0) {
1651 /* check absolute include path */
1652 if (!IS_ABSPATH(buf))
1653 continue;
1654 buf1[0] = 0;
1656 } else if (i == 1) {
1657 /* search in current dir if "header.h" */
1658 if (c != '\"')
1659 continue;
1660 path = file->filename;
1661 pstrncpy(buf1, path, tcc_basename(path) - path);
1663 } else {
1664 /* search in all the include paths */
1665 int j = i - 2, k = j - s1->nb_include_paths;
1666 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1667 pstrcpy(buf1, sizeof(buf1), path);
1668 pstrcat(buf1, sizeof(buf1), "/");
1671 pstrcat(buf1, sizeof(buf1), buf);
1672 e = search_cached_include(s1, buf1);
1673 if (e && (define_find(e->ifndef_macro) || e->ifndef_macro == TOK_once)) {
1674 /* no need to parse the include because the 'ifndef macro'
1675 is defined */
1676 #ifdef INC_DEBUG
1677 printf("%s: skipping cached %s\n", file->filename, buf1);
1678 #endif
1679 goto include_done;
1682 if (tcc_open(s1, buf1) < 0)
1683 continue;
1685 file->include_next_index = i + 1;
1686 #ifdef INC_DEBUG
1687 printf("%s: including %s\n", file->prev->filename, file->filename);
1688 #endif
1689 /* update target deps */
1690 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1691 tcc_strdup(buf1));
1692 /* push current file in stack */
1693 ++s1->include_stack_ptr;
1694 /* add include file debug info */
1695 if (s1->do_debug)
1696 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1697 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1698 ch = file->buf_ptr[0];
1699 goto the_end;
1701 tcc_error("include file '%s' not found", buf);
1702 include_done:
1703 break;
1704 case TOK_IFNDEF:
1705 c = 1;
1706 goto do_ifdef;
1707 case TOK_IF:
1708 c = expr_preprocess();
1709 goto do_if;
1710 case TOK_IFDEF:
1711 c = 0;
1712 do_ifdef:
1713 next_nomacro();
1714 if (tok < TOK_IDENT)
1715 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1716 if (is_bof) {
1717 if (c) {
1718 #ifdef INC_DEBUG
1719 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1720 #endif
1721 file->ifndef_macro = tok;
1724 c = (define_find(tok) != 0) ^ c;
1725 do_if:
1726 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1727 tcc_error("memory full (ifdef)");
1728 *s1->ifdef_stack_ptr++ = c;
1729 goto test_skip;
1730 case TOK_ELSE:
1731 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1732 tcc_error("#else without matching #if");
1733 if (s1->ifdef_stack_ptr[-1] & 2)
1734 tcc_error("#else after #else");
1735 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1736 goto test_else;
1737 case TOK_ELIF:
1738 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1739 tcc_error("#elif without matching #if");
1740 c = s1->ifdef_stack_ptr[-1];
1741 if (c > 1)
1742 tcc_error("#elif after #else");
1743 /* last #if/#elif expression was true: we skip */
1744 if (c == 1)
1745 goto skip;
1746 c = expr_preprocess();
1747 s1->ifdef_stack_ptr[-1] = c;
1748 test_else:
1749 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1750 file->ifndef_macro = 0;
1751 test_skip:
1752 if (!(c & 1)) {
1753 skip:
1754 preprocess_skip();
1755 is_bof = 0;
1756 goto redo;
1758 break;
1759 case TOK_ENDIF:
1760 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1761 tcc_error("#endif without matching #if");
1762 s1->ifdef_stack_ptr--;
1763 /* '#ifndef macro' was at the start of file. Now we check if
1764 an '#endif' is exactly at the end of file */
1765 if (file->ifndef_macro &&
1766 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1767 file->ifndef_macro_saved = file->ifndef_macro;
1768 /* need to set to zero to avoid false matches if another
1769 #ifndef at middle of file */
1770 file->ifndef_macro = 0;
1771 while (tok != TOK_LINEFEED)
1772 next_nomacro();
1773 tok_flags |= TOK_FLAG_ENDIF;
1774 goto the_end;
1776 break;
1777 case TOK_PPNUM:
1778 n = strtoul((char*)tokc.cstr->data, &q, 10);
1779 goto _line_num;
1780 case TOK_LINE:
1781 next();
1782 if (tok != TOK_CINT)
1783 _line_err:
1784 tcc_error("wrong #line format");
1785 n = tokc.i;
1786 _line_num:
1787 next();
1788 if (tok != TOK_LINEFEED) {
1789 if (tok == TOK_STR)
1790 pstrcpy(file->filename, sizeof(file->filename), (char *)tokc.cstr->data);
1791 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1792 break;
1793 else
1794 goto _line_err;
1795 --n;
1797 if (file->fd > 0)
1798 total_lines += file->line_num - n;
1799 file->line_num = n;
1800 if (s1->do_debug)
1801 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1802 break;
1803 case TOK_ERROR:
1804 case TOK_WARNING:
1805 c = tok;
1806 ch = file->buf_ptr[0];
1807 skip_spaces();
1808 q = buf;
1809 while (ch != '\n' && ch != CH_EOF) {
1810 if ((q - buf) < sizeof(buf) - 1)
1811 *q++ = ch;
1812 if (ch == '\\') {
1813 if (handle_stray_noerror() == 0)
1814 --q;
1815 } else
1816 inp();
1818 *q = '\0';
1819 if (c == TOK_ERROR)
1820 tcc_error("#error %s", buf);
1821 else
1822 tcc_warning("#warning %s", buf);
1823 break;
1824 case TOK_PRAGMA:
1825 pragma_parse(s1);
1826 break;
1827 case TOK_LINEFEED:
1828 goto the_end;
1829 default:
1830 /* ignore gas line comment in an 'S' file. */
1831 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1832 goto ignore;
1833 if (tok == '!' && is_bof)
1834 /* '!' is ignored at beginning to allow C scripts. */
1835 goto ignore;
1836 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1837 ignore:
1838 file->buf_ptr = parse_line_comment(file->buf_ptr);
1839 goto the_end;
1841 /* ignore other preprocess commands or #! for C scripts */
1842 while (tok != TOK_LINEFEED)
1843 next_nomacro();
1844 the_end:
1845 parse_flags = saved_parse_flags;
1848 /* evaluate escape codes in a string. */
1849 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1851 int c, n;
1852 const uint8_t *p;
1854 p = buf;
1855 for(;;) {
1856 c = *p;
1857 if (c == '\0')
1858 break;
1859 if (c == '\\') {
1860 p++;
1861 /* escape */
1862 c = *p;
1863 switch(c) {
1864 case '0': case '1': case '2': case '3':
1865 case '4': case '5': case '6': case '7':
1866 /* at most three octal digits */
1867 n = c - '0';
1868 p++;
1869 c = *p;
1870 if (isoct(c)) {
1871 n = n * 8 + c - '0';
1872 p++;
1873 c = *p;
1874 if (isoct(c)) {
1875 n = n * 8 + c - '0';
1876 p++;
1879 c = n;
1880 goto add_char_nonext;
1881 case 'x':
1882 case 'u':
1883 case 'U':
1884 p++;
1885 n = 0;
1886 for(;;) {
1887 c = *p;
1888 if (c >= 'a' && c <= 'f')
1889 c = c - 'a' + 10;
1890 else if (c >= 'A' && c <= 'F')
1891 c = c - 'A' + 10;
1892 else if (isnum(c))
1893 c = c - '0';
1894 else
1895 break;
1896 n = n * 16 + c;
1897 p++;
1899 c = n;
1900 goto add_char_nonext;
1901 case 'a':
1902 c = '\a';
1903 break;
1904 case 'b':
1905 c = '\b';
1906 break;
1907 case 'f':
1908 c = '\f';
1909 break;
1910 case 'n':
1911 c = '\n';
1912 break;
1913 case 'r':
1914 c = '\r';
1915 break;
1916 case 't':
1917 c = '\t';
1918 break;
1919 case 'v':
1920 c = '\v';
1921 break;
1922 case 'e':
1923 if (!gnu_ext)
1924 goto invalid_escape;
1925 c = 27;
1926 break;
1927 case '\'':
1928 case '\"':
1929 case '\\':
1930 case '?':
1931 break;
1932 default:
1933 invalid_escape:
1934 if (c >= '!' && c <= '~')
1935 tcc_warning("unknown escape sequence: \'\\%c\'", c);
1936 else
1937 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
1938 break;
1941 p++;
1942 add_char_nonext:
1943 if (!is_long)
1944 cstr_ccat(outstr, c);
1945 else
1946 cstr_wccat(outstr, c);
1948 /* add a trailing '\0' */
1949 if (!is_long)
1950 cstr_ccat(outstr, '\0');
1951 else
1952 cstr_wccat(outstr, '\0');
1955 void parse_string(const char *s, int len)
1957 uint8_t buf[1000], *p = buf;
1958 int is_long, sep;
1960 if ((is_long = *s == 'L'))
1961 ++s, --len;
1962 sep = *s++;
1963 len -= 2;
1964 if (len >= sizeof buf)
1965 p = tcc_malloc(len + 1);
1966 memcpy(p, s, len);
1967 p[len] = 0;
1969 cstr_reset(&tokcstr);
1970 parse_escape_string(&tokcstr, p, is_long);
1971 if (p != buf)
1972 tcc_free(p);
1974 if (sep == '\'') {
1975 int char_size;
1976 /* XXX: make it portable */
1977 if (!is_long)
1978 char_size = 1;
1979 else
1980 char_size = sizeof(nwchar_t);
1981 if (tokcstr.size <= char_size)
1982 tcc_error("empty character constant");
1983 if (tokcstr.size > 2 * char_size)
1984 tcc_warning("multi-character character constant");
1985 if (!is_long) {
1986 tokc.i = *(int8_t *)tokcstr.data;
1987 tok = TOK_CCHAR;
1988 } else {
1989 tokc.i = *(nwchar_t *)tokcstr.data;
1990 tok = TOK_LCHAR;
1992 } else {
1993 tokc.cstr = &tokcstr;
1994 if (!is_long)
1995 tok = TOK_STR;
1996 else
1997 tok = TOK_LSTR;
2001 /* we use 64 bit numbers */
2002 #define BN_SIZE 2
2004 /* bn = (bn << shift) | or_val */
2005 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2007 int i;
2008 unsigned int v;
2009 for(i=0;i<BN_SIZE;i++) {
2010 v = bn[i];
2011 bn[i] = (v << shift) | or_val;
2012 or_val = v >> (32 - shift);
2016 static void bn_zero(unsigned int *bn)
2018 int i;
2019 for(i=0;i<BN_SIZE;i++) {
2020 bn[i] = 0;
2024 /* parse number in null terminated string 'p' and return it in the
2025 current token */
2026 static void parse_number(const char *p)
2028 int b, t, shift, frac_bits, s, exp_val, ch;
2029 char *q;
2030 unsigned int bn[BN_SIZE];
2031 double d;
2033 /* number */
2034 q = token_buf;
2035 ch = *p++;
2036 t = ch;
2037 ch = *p++;
2038 *q++ = t;
2039 b = 10;
2040 if (t == '.') {
2041 goto float_frac_parse;
2042 } else if (t == '0') {
2043 if (ch == 'x' || ch == 'X') {
2044 q--;
2045 ch = *p++;
2046 b = 16;
2047 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
2048 q--;
2049 ch = *p++;
2050 b = 2;
2053 /* parse all digits. cannot check octal numbers at this stage
2054 because of floating point constants */
2055 while (1) {
2056 if (ch >= 'a' && ch <= 'f')
2057 t = ch - 'a' + 10;
2058 else if (ch >= 'A' && ch <= 'F')
2059 t = ch - 'A' + 10;
2060 else if (isnum(ch))
2061 t = ch - '0';
2062 else
2063 break;
2064 if (t >= b)
2065 break;
2066 if (q >= token_buf + STRING_MAX_SIZE) {
2067 num_too_long:
2068 tcc_error("number too long");
2070 *q++ = ch;
2071 ch = *p++;
2073 if (ch == '.' ||
2074 ((ch == 'e' || ch == 'E') && b == 10) ||
2075 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2076 if (b != 10) {
2077 /* NOTE: strtox should support that for hexa numbers, but
2078 non ISOC99 libcs do not support it, so we prefer to do
2079 it by hand */
2080 /* hexadecimal or binary floats */
2081 /* XXX: handle overflows */
2082 *q = '\0';
2083 if (b == 16)
2084 shift = 4;
2085 else
2086 shift = 1;
2087 bn_zero(bn);
2088 q = token_buf;
2089 while (1) {
2090 t = *q++;
2091 if (t == '\0') {
2092 break;
2093 } else if (t >= 'a') {
2094 t = t - 'a' + 10;
2095 } else if (t >= 'A') {
2096 t = t - 'A' + 10;
2097 } else {
2098 t = t - '0';
2100 bn_lshift(bn, shift, t);
2102 frac_bits = 0;
2103 if (ch == '.') {
2104 ch = *p++;
2105 while (1) {
2106 t = ch;
2107 if (t >= 'a' && t <= 'f') {
2108 t = t - 'a' + 10;
2109 } else if (t >= 'A' && t <= 'F') {
2110 t = t - 'A' + 10;
2111 } else if (t >= '0' && t <= '9') {
2112 t = t - '0';
2113 } else {
2114 break;
2116 if (t >= b)
2117 tcc_error("invalid digit");
2118 bn_lshift(bn, shift, t);
2119 frac_bits += shift;
2120 ch = *p++;
2123 if (ch != 'p' && ch != 'P')
2124 expect("exponent");
2125 ch = *p++;
2126 s = 1;
2127 exp_val = 0;
2128 if (ch == '+') {
2129 ch = *p++;
2130 } else if (ch == '-') {
2131 s = -1;
2132 ch = *p++;
2134 if (ch < '0' || ch > '9')
2135 expect("exponent digits");
2136 while (ch >= '0' && ch <= '9') {
2137 exp_val = exp_val * 10 + ch - '0';
2138 ch = *p++;
2140 exp_val = exp_val * s;
2142 /* now we can generate the number */
2143 /* XXX: should patch directly float number */
2144 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2145 d = ldexp(d, exp_val - frac_bits);
2146 t = toup(ch);
2147 if (t == 'F') {
2148 ch = *p++;
2149 tok = TOK_CFLOAT;
2150 /* float : should handle overflow */
2151 tokc.f = (float)d;
2152 } else if (t == 'L') {
2153 ch = *p++;
2154 #ifdef TCC_TARGET_PE
2155 tok = TOK_CDOUBLE;
2156 tokc.d = d;
2157 #else
2158 tok = TOK_CLDOUBLE;
2159 /* XXX: not large enough */
2160 tokc.ld = (long double)d;
2161 #endif
2162 } else {
2163 tok = TOK_CDOUBLE;
2164 tokc.d = d;
2166 } else {
2167 /* decimal floats */
2168 if (ch == '.') {
2169 if (q >= token_buf + STRING_MAX_SIZE)
2170 goto num_too_long;
2171 *q++ = ch;
2172 ch = *p++;
2173 float_frac_parse:
2174 while (ch >= '0' && ch <= '9') {
2175 if (q >= token_buf + STRING_MAX_SIZE)
2176 goto num_too_long;
2177 *q++ = ch;
2178 ch = *p++;
2181 if (ch == 'e' || ch == 'E') {
2182 if (q >= token_buf + STRING_MAX_SIZE)
2183 goto num_too_long;
2184 *q++ = ch;
2185 ch = *p++;
2186 if (ch == '-' || ch == '+') {
2187 if (q >= token_buf + STRING_MAX_SIZE)
2188 goto num_too_long;
2189 *q++ = ch;
2190 ch = *p++;
2192 if (ch < '0' || ch > '9')
2193 expect("exponent digits");
2194 while (ch >= '0' && ch <= '9') {
2195 if (q >= token_buf + STRING_MAX_SIZE)
2196 goto num_too_long;
2197 *q++ = ch;
2198 ch = *p++;
2201 *q = '\0';
2202 t = toup(ch);
2203 errno = 0;
2204 if (t == 'F') {
2205 ch = *p++;
2206 tok = TOK_CFLOAT;
2207 tokc.f = strtof(token_buf, NULL);
2208 } else if (t == 'L') {
2209 ch = *p++;
2210 #ifdef TCC_TARGET_PE
2211 tok = TOK_CDOUBLE;
2212 tokc.d = strtod(token_buf, NULL);
2213 #else
2214 tok = TOK_CLDOUBLE;
2215 tokc.ld = strtold(token_buf, NULL);
2216 #endif
2217 } else {
2218 tok = TOK_CDOUBLE;
2219 tokc.d = strtod(token_buf, NULL);
2222 } else {
2223 unsigned long long n, n1;
2224 int lcount, ucount, must_64bit;
2225 const char *p1;
2227 /* integer number */
2228 *q = '\0';
2229 q = token_buf;
2230 if (b == 10 && *q == '0') {
2231 b = 8;
2232 q++;
2234 n = 0;
2235 while(1) {
2236 t = *q++;
2237 /* no need for checks except for base 10 / 8 errors */
2238 if (t == '\0')
2239 break;
2240 else if (t >= 'a')
2241 t = t - 'a' + 10;
2242 else if (t >= 'A')
2243 t = t - 'A' + 10;
2244 else
2245 t = t - '0';
2246 if (t >= b)
2247 tcc_error("invalid digit");
2248 n1 = n;
2249 n = n * b + t;
2250 /* detect overflow */
2251 /* XXX: this test is not reliable */
2252 if (n < n1)
2253 tcc_error("integer constant overflow");
2256 /* Determine the characteristics (unsigned and/or 64bit) the type of
2257 the constant must have according to the constant suffix(es) */
2258 lcount = ucount = must_64bit = 0;
2259 p1 = p;
2260 for(;;) {
2261 t = toup(ch);
2262 if (t == 'L') {
2263 if (lcount >= 2)
2264 tcc_error("three 'l's in integer constant");
2265 if (lcount && *(p - 1) != ch)
2266 tcc_error("incorrect integer suffix: %s", p1);
2267 lcount++;
2268 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2269 if (lcount == 2)
2270 #endif
2271 must_64bit = 1;
2272 ch = *p++;
2273 } else if (t == 'U') {
2274 if (ucount >= 1)
2275 tcc_error("two 'u's in integer constant");
2276 ucount++;
2277 ch = *p++;
2278 } else {
2279 break;
2283 /* Whether 64 bits are needed to hold the constant's value */
2284 if (n & 0xffffffff00000000LL || must_64bit) {
2285 tok = TOK_CLLONG;
2286 n1 = n >> 32;
2287 } else {
2288 tok = TOK_CINT;
2289 n1 = n;
2292 /* Whether type must be unsigned to hold the constant's value */
2293 if (ucount || ((n1 >> 31) && (b != 10))) {
2294 if (tok == TOK_CLLONG)
2295 tok = TOK_CULLONG;
2296 else
2297 tok = TOK_CUINT;
2298 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2299 } else if (n1 >> 31) {
2300 if (tok == TOK_CINT)
2301 tok = TOK_CLLONG;
2302 else
2303 tcc_error("integer constant overflow");
2306 if (tok == TOK_CINT || tok == TOK_CUINT)
2307 tokc.i = n;
2308 else
2309 tokc.i = n;
2311 if (ch)
2312 tcc_error("invalid number\n");
2316 #define PARSE2(c1, tok1, c2, tok2) \
2317 case c1: \
2318 PEEKC(c, p); \
2319 if (c == c2) { \
2320 p++; \
2321 tok = tok2; \
2322 } else { \
2323 tok = tok1; \
2325 break;
2327 /* return next token without macro substitution */
2328 static inline void next_nomacro1(void)
2330 int t, c, is_long;
2331 TokenSym *ts;
2332 uint8_t *p, *p1;
2333 unsigned int h;
2335 p = file->buf_ptr;
2336 redo_no_start:
2337 c = *p;
2338 switch(c) {
2339 case ' ':
2340 case '\t':
2341 tok = c;
2342 p++;
2343 if (parse_flags & PARSE_FLAG_SPACES)
2344 goto keep_tok_flags;
2345 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2346 ++p;
2347 goto redo_no_start;
2348 case '\f':
2349 case '\v':
2350 case '\r':
2351 p++;
2352 goto redo_no_start;
2353 case '\\':
2354 /* first look if it is in fact an end of buffer */
2355 c = handle_stray1(p);
2356 p = file->buf_ptr;
2357 if (c == '\\')
2358 goto parse_simple;
2359 if (c != CH_EOF)
2360 goto redo_no_start;
2362 TCCState *s1 = tcc_state;
2363 if ((parse_flags & PARSE_FLAG_LINEFEED)
2364 && !(tok_flags & TOK_FLAG_EOF)) {
2365 tok_flags |= TOK_FLAG_EOF;
2366 tok = TOK_LINEFEED;
2367 goto keep_tok_flags;
2368 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2369 tok = TOK_EOF;
2370 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2371 tcc_error("missing #endif");
2372 } else if (s1->include_stack_ptr == s1->include_stack) {
2373 /* no include left : end of file. */
2374 tok = TOK_EOF;
2375 } else {
2376 tok_flags &= ~TOK_FLAG_EOF;
2377 /* pop include file */
2379 /* test if previous '#endif' was after a #ifdef at
2380 start of file */
2381 if (tok_flags & TOK_FLAG_ENDIF) {
2382 #ifdef INC_DEBUG
2383 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2384 #endif
2385 add_cached_include(s1, file->filename, file->ifndef_macro_saved);
2386 tok_flags &= ~TOK_FLAG_ENDIF;
2389 /* add end of include file debug info */
2390 if (tcc_state->do_debug) {
2391 put_stabd(N_EINCL, 0, 0);
2393 /* pop include stack */
2394 tcc_close();
2395 s1->include_stack_ptr--;
2396 p = file->buf_ptr;
2397 goto redo_no_start;
2400 break;
2402 case '\n':
2403 file->line_num++;
2404 tok_flags |= TOK_FLAG_BOL;
2405 p++;
2406 maybe_newline:
2407 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2408 goto redo_no_start;
2409 tok = TOK_LINEFEED;
2410 goto keep_tok_flags;
2412 case '#':
2413 /* XXX: simplify */
2414 PEEKC(c, p);
2415 if ((tok_flags & TOK_FLAG_BOL) &&
2416 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2417 file->buf_ptr = p;
2418 preprocess(tok_flags & TOK_FLAG_BOF);
2419 p = file->buf_ptr;
2420 goto maybe_newline;
2421 } else {
2422 if (c == '#') {
2423 p++;
2424 tok = TOK_TWOSHARPS;
2425 } else {
2426 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2427 p = parse_line_comment(p - 1);
2428 goto redo_no_start;
2429 } else {
2430 tok = '#';
2434 break;
2436 /* dollar is allowed to start identifiers when not parsing asm */
2437 case '$':
2438 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2439 || (parse_flags & PARSE_FLAG_ASM_FILE))
2440 goto parse_simple;
2442 case 'a': case 'b': case 'c': case 'd':
2443 case 'e': case 'f': case 'g': case 'h':
2444 case 'i': case 'j': case 'k': case 'l':
2445 case 'm': case 'n': case 'o': case 'p':
2446 case 'q': case 'r': case 's': case 't':
2447 case 'u': case 'v': case 'w': case 'x':
2448 case 'y': case 'z':
2449 case 'A': case 'B': case 'C': case 'D':
2450 case 'E': case 'F': case 'G': case 'H':
2451 case 'I': case 'J': case 'K':
2452 case 'M': case 'N': case 'O': case 'P':
2453 case 'Q': case 'R': case 'S': case 'T':
2454 case 'U': case 'V': case 'W': case 'X':
2455 case 'Y': case 'Z':
2456 case '_':
2457 parse_ident_fast:
2458 p1 = p;
2459 h = TOK_HASH_INIT;
2460 h = TOK_HASH_FUNC(h, c);
2461 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2462 h = TOK_HASH_FUNC(h, c);
2463 if (c != '\\') {
2464 TokenSym **pts;
2465 int len;
2467 /* fast case : no stray found, so we have the full token
2468 and we have already hashed it */
2469 len = p - p1;
2470 h &= (TOK_HASH_SIZE - 1);
2471 pts = &hash_ident[h];
2472 for(;;) {
2473 ts = *pts;
2474 if (!ts)
2475 break;
2476 if (ts->len == len && !memcmp(ts->str, p1, len))
2477 goto token_found;
2478 pts = &(ts->hash_next);
2480 ts = tok_alloc_new(pts, (char *) p1, len);
2481 token_found: ;
2482 } else {
2483 /* slower case */
2484 cstr_reset(&tokcstr);
2486 while (p1 < p) {
2487 cstr_ccat(&tokcstr, *p1);
2488 p1++;
2490 p--;
2491 PEEKC(c, p);
2492 parse_ident_slow:
2493 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM)) {
2494 cstr_ccat(&tokcstr, c);
2495 PEEKC(c, p);
2497 ts = tok_alloc(tokcstr.data, tokcstr.size);
2499 tok = ts->tok;
2500 break;
2501 case 'L':
2502 t = p[1];
2503 if (t != '\\' && t != '\'' && t != '\"') {
2504 /* fast case */
2505 goto parse_ident_fast;
2506 } else {
2507 PEEKC(c, p);
2508 if (c == '\'' || c == '\"') {
2509 is_long = 1;
2510 goto str_const;
2511 } else {
2512 cstr_reset(&tokcstr);
2513 cstr_ccat(&tokcstr, 'L');
2514 goto parse_ident_slow;
2517 break;
2519 case '0': case '1': case '2': case '3':
2520 case '4': case '5': case '6': case '7':
2521 case '8': case '9':
2522 cstr_reset(&tokcstr);
2523 /* after the first digit, accept digits, alpha, '.' or sign if
2524 prefixed by 'eEpP' */
2525 parse_num:
2526 for(;;) {
2527 t = c;
2528 cstr_ccat(&tokcstr, c);
2529 PEEKC(c, p);
2530 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2531 || c == '.'
2532 || ((c == '+' || c == '-')
2533 && (t == 'e' || t == 'E' || t == 'p' || t == 'P')
2535 break;
2537 /* We add a trailing '\0' to ease parsing */
2538 cstr_ccat(&tokcstr, '\0');
2539 tokc.cstr = &tokcstr;
2540 tok = TOK_PPNUM;
2541 break;
2543 case '.':
2544 /* special dot handling because it can also start a number */
2545 PEEKC(c, p);
2546 if (isnum(c)) {
2547 cstr_reset(&tokcstr);
2548 cstr_ccat(&tokcstr, '.');
2549 goto parse_num;
2550 } else if (c == '.') {
2551 PEEKC(c, p);
2552 if (c == '.') {
2553 p++;
2554 tok = TOK_DOTS;
2555 } else {
2556 *--p = '.'; /* may underflow into file->unget[] */
2557 tok = '.';
2559 } else {
2560 tok = '.';
2562 break;
2563 case '\'':
2564 case '\"':
2565 is_long = 0;
2566 str_const:
2567 cstr_reset(&tokcstr);
2568 if (is_long)
2569 cstr_ccat(&tokcstr, 'L');
2570 cstr_ccat(&tokcstr, c);
2571 p = parse_pp_string(p, c, &tokcstr);
2572 cstr_ccat(&tokcstr, c);
2573 cstr_ccat(&tokcstr, '\0');
2574 tokc.cstr = &tokcstr;
2575 tok = TOK_PPSTR;
2576 break;
2578 case '<':
2579 PEEKC(c, p);
2580 if (c == '=') {
2581 p++;
2582 tok = TOK_LE;
2583 } else if (c == '<') {
2584 PEEKC(c, p);
2585 if (c == '=') {
2586 p++;
2587 tok = TOK_A_SHL;
2588 } else {
2589 tok = TOK_SHL;
2591 } else {
2592 tok = TOK_LT;
2594 break;
2595 case '>':
2596 PEEKC(c, p);
2597 if (c == '=') {
2598 p++;
2599 tok = TOK_GE;
2600 } else if (c == '>') {
2601 PEEKC(c, p);
2602 if (c == '=') {
2603 p++;
2604 tok = TOK_A_SAR;
2605 } else {
2606 tok = TOK_SAR;
2608 } else {
2609 tok = TOK_GT;
2611 break;
2613 case '&':
2614 PEEKC(c, p);
2615 if (c == '&') {
2616 p++;
2617 tok = TOK_LAND;
2618 } else if (c == '=') {
2619 p++;
2620 tok = TOK_A_AND;
2621 } else {
2622 tok = '&';
2624 break;
2626 case '|':
2627 PEEKC(c, p);
2628 if (c == '|') {
2629 p++;
2630 tok = TOK_LOR;
2631 } else if (c == '=') {
2632 p++;
2633 tok = TOK_A_OR;
2634 } else {
2635 tok = '|';
2637 break;
2639 case '+':
2640 PEEKC(c, p);
2641 if (c == '+') {
2642 p++;
2643 tok = TOK_INC;
2644 } else if (c == '=') {
2645 p++;
2646 tok = TOK_A_ADD;
2647 } else {
2648 tok = '+';
2650 break;
2652 case '-':
2653 PEEKC(c, p);
2654 if (c == '-') {
2655 p++;
2656 tok = TOK_DEC;
2657 } else if (c == '=') {
2658 p++;
2659 tok = TOK_A_SUB;
2660 } else if (c == '>') {
2661 p++;
2662 tok = TOK_ARROW;
2663 } else {
2664 tok = '-';
2666 break;
2668 PARSE2('!', '!', '=', TOK_NE)
2669 PARSE2('=', '=', '=', TOK_EQ)
2670 PARSE2('*', '*', '=', TOK_A_MUL)
2671 PARSE2('%', '%', '=', TOK_A_MOD)
2672 PARSE2('^', '^', '=', TOK_A_XOR)
2674 /* comments or operator */
2675 case '/':
2676 PEEKC(c, p);
2677 if (c == '*') {
2678 p = parse_comment(p);
2679 /* comments replaced by a blank */
2680 tok = ' ';
2681 goto keep_tok_flags;
2682 } else if (c == '/') {
2683 p = parse_line_comment(p);
2684 tok = ' ';
2685 goto keep_tok_flags;
2686 } else if (c == '=') {
2687 p++;
2688 tok = TOK_A_DIV;
2689 } else {
2690 tok = '/';
2692 break;
2694 /* simple tokens */
2695 case '(':
2696 case ')':
2697 case '[':
2698 case ']':
2699 case '{':
2700 case '}':
2701 case ',':
2702 case ';':
2703 case ':':
2704 case '?':
2705 case '~':
2706 case '@': /* only used in assembler */
2707 parse_simple:
2708 tok = c;
2709 p++;
2710 break;
2711 default:
2712 tcc_error("unrecognized character \\x%02x", c);
2713 break;
2715 tok_flags = 0;
2716 keep_tok_flags:
2717 file->buf_ptr = p;
2718 #if defined(PARSE_DEBUG)
2719 printf("token = %s\n", get_tok_str(tok, &tokc));
2720 #endif
2723 /* return next token without macro substitution. Can read input from
2724 macro_ptr buffer */
2725 static void next_nomacro_spc(void)
2727 if (macro_ptr) {
2728 redo:
2729 tok = *macro_ptr;
2730 if (tok) {
2731 TOK_GET(&tok, &macro_ptr, &tokc);
2732 if (tok == TOK_LINENUM) {
2733 file->line_num = tokc.i;
2734 goto redo;
2737 } else {
2738 next_nomacro1();
2742 ST_FUNC void next_nomacro(void)
2744 do {
2745 next_nomacro_spc();
2746 } while (tok < 256 && (isidnum_table[tok - CH_EOF] & IS_SPC));
2750 static void macro_subst(
2751 TokenString *tok_str,
2752 Sym **nested_list,
2753 const int *macro_str,
2754 int can_read_stream
2757 /* substitute arguments in replacement lists in macro_str by the values in
2758 args (field d) and return allocated string */
2759 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2761 int t, t0, t1, spc;
2762 const int *st;
2763 Sym *s;
2764 CValue cval;
2765 TokenString str;
2766 CString cstr;
2768 tok_str_new(&str);
2769 t0 = t1 = 0;
2770 while(1) {
2771 TOK_GET(&t, &macro_str, &cval);
2772 if (!t)
2773 break;
2774 if (t == '#') {
2775 /* stringize */
2776 TOK_GET(&t, &macro_str, &cval);
2777 if (!t)
2778 goto bad_stringy;
2779 s = sym_find2(args, t);
2780 if (s) {
2781 cstr_new(&cstr);
2782 cstr_ccat(&cstr, '\"');
2783 st = s->d;
2784 spc = 0;
2785 while (*st) {
2786 TOK_GET(&t, &st, &cval);
2787 if (t != TOK_PLCHLDR
2788 && t != TOK_NOSUBST
2789 && 0 == check_space(t, &spc)) {
2790 const char *s = get_tok_str(t, &cval);
2791 while (*s) {
2792 if (t == TOK_PPSTR && *s != '\'')
2793 add_char(&cstr, *s);
2794 else
2795 cstr_ccat(&cstr, *s);
2796 ++s;
2800 cstr.size -= spc;
2801 cstr_ccat(&cstr, '\"');
2802 cstr_ccat(&cstr, '\0');
2803 #ifdef PP_DEBUG
2804 printf("\nstringize: <%s>\n", (char *)cstr.data);
2805 #endif
2806 /* add string */
2807 cval.cstr = &cstr;
2808 tok_str_add2(&str, TOK_PPSTR, &cval);
2809 cstr_free(cval.cstr);
2810 } else {
2811 bad_stringy:
2812 expect("macro parameter after '#'");
2814 } else if (t >= TOK_IDENT) {
2815 s = sym_find2(args, t);
2816 if (s) {
2817 int l0 = str.len;
2818 st = s->d;
2819 /* if '##' is present before or after, no arg substitution */
2820 if (*macro_str == TOK_TWOSHARPS || t1 == TOK_TWOSHARPS) {
2821 /* special case for var arg macros : ## eats the ','
2822 if empty VA_ARGS variable. */
2823 if (t1 == TOK_TWOSHARPS && t0 == ',' && gnu_ext && s->type.t) {
2824 if (*st == 0) {
2825 /* suppress ',' '##' */
2826 str.len -= 2;
2827 } else {
2828 /* suppress '##' and add variable */
2829 str.len--;
2830 goto add_var;
2832 } else {
2833 for(;;) {
2834 int t1;
2835 TOK_GET(&t1, &st, &cval);
2836 if (!t1)
2837 break;
2838 tok_str_add2(&str, t1, &cval);
2842 } else {
2843 add_var:
2844 /* NOTE: the stream cannot be read when macro
2845 substituing an argument */
2846 macro_subst(&str, nested_list, st, 0);
2848 if (str.len == l0) /* exanded to empty string */
2849 tok_str_add(&str, TOK_PLCHLDR);
2850 } else {
2851 tok_str_add(&str, t);
2853 } else {
2854 tok_str_add2(&str, t, &cval);
2856 t0 = t1, t1 = t;
2858 tok_str_add(&str, 0);
2859 return str.str;
2862 static char const ab_month_name[12][4] =
2864 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2865 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2868 /* peek or read [ws_str == NULL] next token from function macro call,
2869 walking up macro levels up to the file if necessary */
2870 static int next_argstream(Sym **nested_list, int can_read_stream, TokenString *ws_str)
2872 int t;
2873 const int *p;
2874 Sym *sa;
2876 for (;;) {
2877 if (macro_ptr) {
2878 p = macro_ptr, t = *p;
2879 if (ws_str) {
2880 while (is_space(t) || TOK_LINEFEED == t)
2881 tok_str_add(ws_str, t), t = *++p;
2883 if (t == 0 && can_read_stream) {
2884 end_macro();
2885 /* also, end of scope for nested defined symbol */
2886 sa = *nested_list;
2887 while (sa && sa->v == -1)
2888 sa = sa->prev;
2889 if (sa)
2890 sa->v = -1;
2891 continue;
2893 } else {
2894 ch = handle_eob();
2895 if (ws_str) {
2896 while (is_space(ch) || ch == '\n' || ch == '/') {
2897 if (ch == '/') {
2898 int c;
2899 uint8_t *p = file->buf_ptr;
2900 PEEKC(c, p);
2901 if (c == '*') {
2902 p = parse_comment(p);
2903 file->buf_ptr = p - 1;
2904 } else if (c == '/') {
2905 p = parse_line_comment(p);
2906 file->buf_ptr = p - 1;
2907 } else
2908 break;
2909 ch = ' ';
2911 tok_str_add(ws_str, ch);
2912 cinp();
2915 t = ch;
2918 if (ws_str)
2919 return t;
2920 next_nomacro_spc();
2921 return tok;
2925 /* do macro substitution of current token with macro 's' and add
2926 result to (tok_str,tok_len). 'nested_list' is the list of all
2927 macros we got inside to avoid recursing. Return non zero if no
2928 substitution needs to be done */
2929 static int macro_subst_tok(
2930 TokenString *tok_str,
2931 Sym **nested_list,
2932 Sym *s,
2933 int can_read_stream)
2935 Sym *args, *sa, *sa1;
2936 int parlevel, *mstr, t, t1, spc;
2937 TokenString str;
2938 char *cstrval;
2939 CValue cval;
2940 CString cstr;
2941 char buf[32];
2943 /* if symbol is a macro, prepare substitution */
2944 /* special macros */
2945 if (tok == TOK___LINE__) {
2946 snprintf(buf, sizeof(buf), "%d", file->line_num);
2947 cstrval = buf;
2948 t1 = TOK_PPNUM;
2949 goto add_cstr1;
2950 } else if (tok == TOK___FILE__) {
2951 cstrval = file->filename;
2952 goto add_cstr;
2953 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
2954 time_t ti;
2955 struct tm *tm;
2957 time(&ti);
2958 tm = localtime(&ti);
2959 if (tok == TOK___DATE__) {
2960 snprintf(buf, sizeof(buf), "%s %2d %d",
2961 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
2962 } else {
2963 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
2964 tm->tm_hour, tm->tm_min, tm->tm_sec);
2966 cstrval = buf;
2967 add_cstr:
2968 t1 = TOK_STR;
2969 add_cstr1:
2970 cstr_new(&cstr);
2971 cstr_cat(&cstr, cstrval);
2972 cstr_ccat(&cstr, '\0');
2973 cval.cstr = &cstr;
2974 tok_str_add2(tok_str, t1, &cval);
2975 cstr_free(&cstr);
2976 } else {
2977 int saved_parse_flags = parse_flags;
2979 mstr = s->d;
2980 if (s->type.t == MACRO_FUNC) {
2981 /* whitespace between macro name and argument list */
2982 TokenString ws_str;
2983 tok_str_new(&ws_str);
2985 spc = 0;
2986 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
2987 | PARSE_FLAG_ACCEPT_STRAYS;
2989 /* get next token from argument stream */
2990 t = next_argstream(nested_list, can_read_stream, &ws_str);
2991 if (t != '(') {
2992 /* not a macro substitution after all, restore the
2993 * macro token plus all whitespace we've read.
2994 * whitespace is intentionally not merged to preserve
2995 * newlines. */
2996 parse_flags = saved_parse_flags;
2997 tok_str_add(tok_str, tok);
2998 if (parse_flags & PARSE_FLAG_SPACES) {
2999 int i;
3000 for (i = 0; i < ws_str.len; i++)
3001 tok_str_add(tok_str, ws_str.str[i]);
3003 tok_str_free(ws_str.str);
3004 return 0;
3005 } else {
3006 tok_str_free(ws_str.str);
3008 next_nomacro(); /* eat '(' */
3010 /* argument macro */
3011 args = NULL;
3012 sa = s->next;
3013 /* NOTE: empty args are allowed, except if no args */
3014 for(;;) {
3015 do {
3016 next_argstream(nested_list, can_read_stream, NULL);
3017 } while (is_space(tok) || TOK_LINEFEED == tok);
3018 empty_arg:
3019 /* handle '()' case */
3020 if (!args && !sa && tok == ')')
3021 break;
3022 if (!sa)
3023 tcc_error("macro '%s' used with too many args",
3024 get_tok_str(s->v, 0));
3025 tok_str_new(&str);
3026 parlevel = spc = 0;
3027 /* NOTE: non zero sa->t indicates VA_ARGS */
3028 while ((parlevel > 0 ||
3029 (tok != ')' &&
3030 (tok != ',' || sa->type.t)))) {
3031 if (tok == TOK_EOF || tok == 0)
3032 break;
3033 if (tok == '(')
3034 parlevel++;
3035 else if (tok == ')')
3036 parlevel--;
3037 if (tok == TOK_LINEFEED)
3038 tok = ' ';
3039 if (!check_space(tok, &spc))
3040 tok_str_add2(&str, tok, &tokc);
3041 next_argstream(nested_list, can_read_stream, NULL);
3043 if (parlevel)
3044 expect(")");
3045 str.len -= spc;
3046 tok_str_add(&str, 0);
3047 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3048 sa1->d = str.str;
3049 sa = sa->next;
3050 if (tok == ')') {
3051 /* special case for gcc var args: add an empty
3052 var arg argument if it is omitted */
3053 if (sa && sa->type.t && gnu_ext)
3054 goto empty_arg;
3055 break;
3057 if (tok != ',')
3058 expect(",");
3060 if (sa) {
3061 tcc_error("macro '%s' used with too few args",
3062 get_tok_str(s->v, 0));
3065 parse_flags = saved_parse_flags;
3067 /* now subst each arg */
3068 mstr = macro_arg_subst(nested_list, mstr, args);
3069 /* free memory */
3070 sa = args;
3071 while (sa) {
3072 sa1 = sa->prev;
3073 tok_str_free(sa->d);
3074 sym_free(sa);
3075 sa = sa1;
3079 sym_push2(nested_list, s->v, 0, 0);
3080 parse_flags = saved_parse_flags;
3081 macro_subst(tok_str, nested_list, mstr, can_read_stream);
3083 /* pop nested defined symbol */
3084 sa1 = *nested_list;
3085 *nested_list = sa1->prev;
3086 sym_free(sa1);
3087 if (mstr != s->d)
3088 tok_str_free(mstr);
3090 return 0;
3093 int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3095 CString cstr;
3096 int n;
3098 cstr_new(&cstr);
3099 if (t1 != TOK_PLCHLDR)
3100 cstr_cat(&cstr, get_tok_str(t1, v1));
3101 n = cstr.size;
3102 if (t2 != TOK_PLCHLDR)
3103 cstr_cat(&cstr, get_tok_str(t2, v2));
3104 cstr_ccat(&cstr, '\0');
3106 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3107 memcpy(file->buffer, cstr.data, cstr.size);
3108 for (;;) {
3109 next_nomacro1();
3110 if (0 == *file->buf_ptr)
3111 break;
3112 if (is_space(tok))
3113 continue;
3114 tcc_warning("pasting <%.*s> and <%s> does not give a valid preprocessing token",
3115 n, cstr.data, (char*)cstr.data + n);
3116 break;
3118 tcc_close();
3120 //printf("paste <%s>\n", (char*)cstr.data);
3121 cstr_free(&cstr);
3122 return 0;
3125 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3126 return the resulting string (which must be freed). */
3127 static inline int *macro_twosharps(const int *ptr0)
3129 int t;
3130 CValue cval;
3131 TokenString macro_str1;
3132 int start_of_nosubsts = -1;
3133 const int *ptr;
3135 /* we search the first '##' */
3136 for (ptr = ptr0;;) {
3137 TOK_GET(&t, &ptr, &cval);
3138 if (t == TOK_TWOSHARPS)
3139 break;
3140 if (t == 0)
3141 return NULL;
3144 tok_str_new(&macro_str1);
3146 //tok_print(" $$$", ptr0);
3147 for (ptr = ptr0;;) {
3148 TOK_GET(&t, &ptr, &cval);
3149 if (t == 0)
3150 break;
3151 if (t == TOK_TWOSHARPS)
3152 continue;
3153 while (*ptr == TOK_TWOSHARPS) {
3154 int t1; CValue cv1;
3155 /* given 'a##b', remove nosubsts preceding 'a' */
3156 if (start_of_nosubsts >= 0)
3157 macro_str1.len = start_of_nosubsts;
3158 /* given 'a##b', remove nosubsts preceding 'b' */
3159 while ((t1 = *++ptr) == TOK_NOSUBST)
3161 if (t1 && t1 != TOK_TWOSHARPS
3162 && t1 != ':') /* 'a##:' don't build a new token */
3164 TOK_GET(&t1, &ptr, &cv1);
3165 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3166 paste_tokens(t, &cval, t1, &cv1);
3167 t = tok, cval = tokc;
3171 if (t == TOK_NOSUBST) {
3172 if (start_of_nosubsts < 0)
3173 start_of_nosubsts = macro_str1.len;
3174 } else {
3175 start_of_nosubsts = -1;
3177 tok_str_add2(&macro_str1, t, &cval);
3179 tok_str_add(&macro_str1, 0);
3180 //tok_print(" ###", macro_str1.str);
3181 return macro_str1.str;
3184 /* do macro substitution of macro_str and add result to
3185 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3186 inside to avoid recursing. */
3187 static void macro_subst(
3188 TokenString *tok_str,
3189 Sym **nested_list,
3190 const int *macro_str,
3191 int can_read_stream
3194 Sym *s;
3195 const int *ptr;
3196 int t, spc, nosubst;
3197 CValue cval;
3198 int *macro_str1 = NULL;
3200 /* first scan for '##' operator handling */
3201 ptr = macro_str;
3202 spc = nosubst = 0;
3204 /* first scan for '##' operator handling */
3205 if (can_read_stream) {
3206 macro_str1 = macro_twosharps(ptr);
3207 if (macro_str1)
3208 ptr = macro_str1;
3211 while (1) {
3212 TOK_GET(&t, &ptr, &cval);
3213 if (t == 0)
3214 break;
3216 if (t >= TOK_IDENT && 0 == nosubst) {
3217 s = define_find(t);
3218 if (s == NULL)
3219 goto no_subst;
3221 /* if nested substitution, do nothing */
3222 if (sym_find2(*nested_list, t)) {
3223 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3224 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3225 goto no_subst;
3229 TokenString str;
3230 str.str = (int*)ptr;
3231 begin_macro(&str, 2);
3233 tok = t;
3234 macro_subst_tok(tok_str, nested_list, s, can_read_stream);
3236 if (str.alloc == 3) {
3237 /* already finished by reading function macro arguments */
3238 break;
3241 ptr = macro_ptr;
3242 end_macro ();
3245 spc = (tok_str->len &&
3246 is_space(tok_last(tok_str->str,
3247 tok_str->str + tok_str->len)));
3249 } else {
3251 if (t == '\\' && !(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3252 tcc_error("stray '\\' in program");
3254 no_subst:
3255 if (!check_space(t, &spc))
3256 tok_str_add2(tok_str, t, &cval);
3257 nosubst = 0;
3258 if (t == TOK_NOSUBST)
3259 nosubst = 1;
3262 if (macro_str1)
3263 tok_str_free(macro_str1);
3267 /* return next token with macro substitution */
3268 ST_FUNC void next(void)
3270 redo:
3271 if (parse_flags & PARSE_FLAG_SPACES)
3272 next_nomacro_spc();
3273 else
3274 next_nomacro();
3276 if (macro_ptr) {
3277 if (tok == TOK_NOSUBST || tok == TOK_PLCHLDR) {
3278 /* discard preprocessor markers */
3279 goto redo;
3280 } else if (tok == 0) {
3281 /* end of macro or unget token string */
3282 end_macro();
3283 goto redo;
3285 } else if (tok >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3286 Sym *s;
3287 /* if reading from file, try to substitute macros */
3288 s = define_find(tok);
3289 if (s) {
3290 static TokenString str; /* using static string for speed */
3291 Sym *nested_list = NULL;
3292 tok_str_new(&str);
3293 nested_list = NULL;
3294 macro_subst_tok(&str, &nested_list, s, 1);
3295 tok_str_add(&str, 0);
3296 begin_macro(&str, 0);
3297 goto redo;
3300 /* convert preprocessor tokens into C tokens */
3301 if (tok == TOK_PPNUM) {
3302 if (parse_flags & PARSE_FLAG_TOK_NUM)
3303 parse_number((char *)tokc.cstr->data);
3304 } else if (tok == TOK_PPSTR) {
3305 if (parse_flags & PARSE_FLAG_TOK_STR)
3306 parse_string((char *)tokc.cstr->data, tokc.cstr->size - 1);
3310 /* push back current token and set current token to 'last_tok'. Only
3311 identifier case handled for labels. */
3312 ST_INLN void unget_tok(int last_tok)
3314 TokenString *str = tcc_malloc(sizeof *str);
3315 tok_str_new(str);
3316 tok_str_add2(str, tok, &tokc);
3317 tok_str_add(str, 0);
3318 begin_macro(str, 1);
3319 tok = last_tok;
3322 /* better than nothing, but needs extension to handle '-E' option
3323 correctly too */
3324 ST_FUNC void preprocess_init(TCCState *s1)
3326 s1->include_stack_ptr = s1->include_stack;
3327 /* XXX: move that before to avoid having to initialize
3328 file->ifdef_stack_ptr ? */
3329 s1->ifdef_stack_ptr = s1->ifdef_stack;
3330 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3332 pvtop = vtop = vstack - 1;
3333 s1->pack_stack[0] = 0;
3334 s1->pack_stack_ptr = s1->pack_stack;
3336 isidnum_table['$' - CH_EOF] =
3337 tcc_state->dollars_in_identifiers ? IS_ID : 0;
3340 ST_FUNC void preprocess_new(void)
3342 int i, c;
3343 const char *p, *r;
3345 /* init isid table */
3346 for(i = CH_EOF; i<256; i++)
3347 isidnum_table[i - CH_EOF]
3348 = is_space(i) ? IS_SPC
3349 : isid(i) ? IS_ID
3350 : isnum(i) ? IS_NUM
3351 : 0;
3353 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3355 tok_ident = TOK_IDENT;
3356 p = tcc_keywords;
3357 while (*p) {
3358 r = p;
3359 for(;;) {
3360 c = *r++;
3361 if (c == '\0')
3362 break;
3364 tok_alloc(p, r - p - 1);
3365 p = r;
3369 ST_FUNC void preprocess_delete(void)
3371 int i, n;
3373 /* free -D and compiler defines */
3374 free_defines(NULL);
3376 /* cleanup from error/setjmp */
3377 while (macro_stack)
3378 end_macro();
3379 macro_ptr = NULL;
3381 /* free tokens */
3382 n = tok_ident - TOK_IDENT;
3383 for(i = 0; i < n; i++)
3384 tcc_free(table_ident[i]);
3385 tcc_free(table_ident);
3386 table_ident = NULL;
3389 /* Preprocess the current file */
3390 ST_FUNC int tcc_preprocess(TCCState *s1)
3392 BufferedFile **iptr;
3393 int token_seen, spcs, level;
3395 preprocess_init(s1);
3396 ch = file->buf_ptr[0];
3397 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3398 parse_flags = PARSE_FLAG_PREPROCESS
3399 | (parse_flags & PARSE_FLAG_ASM_FILE)
3400 | PARSE_FLAG_LINEFEED
3401 | PARSE_FLAG_SPACES
3402 | PARSE_FLAG_ACCEPT_STRAYS
3405 #ifdef PP_BENCH
3406 do next(); while (tok != TOK_EOF); return 0;
3407 #endif
3409 token_seen = spcs = 0;
3410 pp_line(s1, file, 0);
3412 for (;;) {
3413 iptr = s1->include_stack_ptr;
3414 next();
3415 if (tok == TOK_EOF)
3416 break;
3417 level = s1->include_stack_ptr - iptr;
3418 if (level) {
3419 if (level > 0)
3420 pp_line(s1, *iptr, 0);
3421 pp_line(s1, file, level);
3424 if (0 == token_seen) {
3425 if (tok == ' ') {
3426 ++spcs;
3427 continue;
3429 if (tok == TOK_LINEFEED) {
3430 spcs = 0;
3431 continue;
3433 pp_line(s1, file, 0);
3434 while (spcs)
3435 fputs(" ", s1->ppfp), --spcs;
3436 token_seen = 1;
3438 } else if (tok == TOK_LINEFEED) {
3439 ++file->line_ref;
3440 token_seen = 0;
3443 fputs(get_tok_str(tok, &tokc), s1->ppfp);
3446 return 0;