tccpp: faster next()
[tinycc.git] / tccpp.c
blob1cd6c9998a67eff3e86332d483424109ced1b11f
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 #define USING_GLOBALS
22 #include "tcc.h"
24 /********************************************************/
25 /* global variables */
27 ST_DATA int tok_flags;
28 ST_DATA int parse_flags;
30 ST_DATA struct BufferedFile *file;
31 ST_DATA int ch, tok;
32 ST_DATA CValue tokc;
33 ST_DATA const int *macro_ptr;
34 ST_DATA CString tokcstr; /* current parsed string, if any */
36 /* display benchmark infos */
37 ST_DATA int tok_ident;
38 ST_DATA TokenSym **table_ident;
40 /* ------------------------------------------------------------------------- */
42 static TokenSym *hash_ident[TOK_HASH_SIZE];
43 static char token_buf[STRING_MAX_SIZE + 1];
44 static CString cstr_buf;
45 static CString macro_equal_buf;
46 static TokenString tokstr_buf;
47 static unsigned char isidnum_table[256 - CH_EOF];
48 static int pp_debug_tok, pp_debug_symv;
49 static int pp_once;
50 static int pp_expr;
51 static int pp_counter;
52 static void tok_print(const char *msg, const int *str);
54 static struct TinyAlloc *toksym_alloc;
55 static struct TinyAlloc *tokstr_alloc;
57 static TokenString *macro_stack;
59 static const char tcc_keywords[] =
60 #define DEF(id, str) str "\0"
61 #include "tcctok.h"
62 #undef DEF
65 /* WARNING: the content of this string encodes token numbers */
66 static const unsigned char tok_two_chars[] =
67 /* outdated -- gr
68 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
69 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
70 */{
71 '<','=', TOK_LE,
72 '>','=', TOK_GE,
73 '!','=', TOK_NE,
74 '&','&', TOK_LAND,
75 '|','|', TOK_LOR,
76 '+','+', TOK_INC,
77 '-','-', TOK_DEC,
78 '=','=', TOK_EQ,
79 '<','<', TOK_SHL,
80 '>','>', TOK_SAR,
81 '+','=', TOK_A_ADD,
82 '-','=', TOK_A_SUB,
83 '*','=', TOK_A_MUL,
84 '/','=', TOK_A_DIV,
85 '%','=', TOK_A_MOD,
86 '&','=', TOK_A_AND,
87 '^','=', TOK_A_XOR,
88 '|','=', TOK_A_OR,
89 '-','>', TOK_ARROW,
90 '.','.', TOK_TWODOTS,
91 '#','#', TOK_TWOSHARPS,
95 static void next_nomacro(void);
97 ST_FUNC void skip(int c)
99 if (tok != c)
100 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
101 next();
104 ST_FUNC void expect(const char *msg)
106 tcc_error("%s expected", msg);
109 /* ------------------------------------------------------------------------- */
110 /* Custom allocator for tiny objects */
112 #define USE_TAL
114 #ifndef USE_TAL
115 #define tal_free(al, p) tcc_free(p)
116 #define tal_realloc(al, p, size) tcc_realloc(p, size)
117 #define tal_new(a,b,c)
118 #define tal_delete(a)
119 #else
120 #if !defined(MEM_DEBUG)
121 #define tal_free(al, p) tal_free_impl(al, p)
122 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
123 #define TAL_DEBUG_PARAMS
124 #else
125 #define TAL_DEBUG 1
126 //#define TAL_INFO 1 /* collect and dump allocators stats */
127 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
128 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
129 #define TAL_DEBUG_PARAMS , const char *file, int line
130 #define TAL_DEBUG_FILE_LEN 40
131 #endif
133 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
134 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
135 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
136 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
137 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
138 #define CSTR_TAL_LIMIT 1024
140 typedef struct TinyAlloc {
141 unsigned limit;
142 unsigned size;
143 uint8_t *buffer;
144 uint8_t *p;
145 unsigned nb_allocs;
146 struct TinyAlloc *next, *top;
147 #ifdef TAL_INFO
148 unsigned nb_peak;
149 unsigned nb_total;
150 unsigned nb_missed;
151 uint8_t *peak_p;
152 #endif
153 } TinyAlloc;
155 typedef struct tal_header_t {
156 unsigned size;
157 #ifdef TAL_DEBUG
158 int line_num; /* negative line_num used for double free check */
159 char file_name[TAL_DEBUG_FILE_LEN + 1];
160 #endif
161 } tal_header_t;
163 /* ------------------------------------------------------------------------- */
165 static TinyAlloc *tal_new(TinyAlloc **pal, unsigned limit, unsigned size)
167 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
168 al->p = al->buffer = tcc_malloc(size);
169 al->limit = limit;
170 al->size = size;
171 if (pal) *pal = al;
172 return al;
175 static void tal_delete(TinyAlloc *al)
177 TinyAlloc *next;
179 tail_call:
180 if (!al)
181 return;
182 #ifdef TAL_INFO
183 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
184 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
185 (al->peak_p - al->buffer) * 100.0 / al->size);
186 #endif
187 #ifdef TAL_DEBUG
188 if (al->nb_allocs > 0) {
189 uint8_t *p;
190 fprintf(stderr, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
191 al->nb_allocs, al->limit);
192 p = al->buffer;
193 while (p < al->p) {
194 tal_header_t *header = (tal_header_t *)p;
195 if (header->line_num > 0) {
196 fprintf(stderr, "%s:%d: chunk of %d bytes leaked\n",
197 header->file_name, header->line_num, header->size);
199 p += header->size + sizeof(tal_header_t);
201 #if MEM_DEBUG-0 == 2
202 exit(2);
203 #endif
205 #endif
206 next = al->next;
207 tcc_free(al->buffer);
208 tcc_free(al);
209 al = next;
210 goto tail_call;
213 static void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
215 if (!p)
216 return;
217 tail_call:
218 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
219 #ifdef TAL_DEBUG
220 tal_header_t *header = (((tal_header_t *)p) - 1);
221 if (header->line_num < 0) {
222 fprintf(stderr, "%s:%d: TAL_DEBUG: double frees chunk from\n",
223 file, line);
224 fprintf(stderr, "%s:%d: %d bytes\n",
225 header->file_name, (int)-header->line_num, (int)header->size);
226 } else
227 header->line_num = -header->line_num;
228 #endif
229 al->nb_allocs--;
230 if (!al->nb_allocs)
231 al->p = al->buffer;
232 } else if (al->next) {
233 al = al->next;
234 goto tail_call;
236 else
237 tcc_free(p);
240 static void *tal_realloc_impl(TinyAlloc **pal, void *p, unsigned size TAL_DEBUG_PARAMS)
242 tal_header_t *header;
243 void *ret;
244 int is_own;
245 unsigned adj_size = (size + 3) & -4;
246 TinyAlloc *al = *pal;
248 tail_call:
249 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
250 if ((!p || is_own) && size <= al->limit) {
251 if (al->p - al->buffer + adj_size + sizeof(tal_header_t) < al->size) {
252 header = (tal_header_t *)al->p;
253 header->size = adj_size;
254 #ifdef TAL_DEBUG
255 { int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
256 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
257 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
258 header->line_num = line; }
259 #endif
260 ret = al->p + sizeof(tal_header_t);
261 al->p += adj_size + sizeof(tal_header_t);
262 if (is_own) {
263 header = (((tal_header_t *)p) - 1);
264 if (p) memcpy(ret, p, header->size);
265 #ifdef TAL_DEBUG
266 header->line_num = -header->line_num;
267 #endif
268 } else {
269 al->nb_allocs++;
271 #ifdef TAL_INFO
272 if (al->nb_peak < al->nb_allocs)
273 al->nb_peak = al->nb_allocs;
274 if (al->peak_p < al->p)
275 al->peak_p = al->p;
276 al->nb_total++;
277 #endif
278 return ret;
279 } else if (is_own) {
280 al->nb_allocs--;
281 ret = tal_realloc(*pal, 0, size);
282 header = (((tal_header_t *)p) - 1);
283 if (p) memcpy(ret, p, header->size);
284 #ifdef TAL_DEBUG
285 header->line_num = -header->line_num;
286 #endif
287 return ret;
289 if (al->next) {
290 al = al->next;
291 } else {
292 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
294 al = tal_new(pal, next->limit, next->size * 2);
295 al->next = next;
296 bottom->top = al;
298 goto tail_call;
300 if (is_own) {
301 al->nb_allocs--;
302 ret = tcc_malloc(size);
303 header = (((tal_header_t *)p) - 1);
304 if (p) memcpy(ret, p, header->size);
305 #ifdef TAL_DEBUG
306 header->line_num = -header->line_num;
307 #endif
308 } else if (al->next) {
309 al = al->next;
310 goto tail_call;
311 } else
312 ret = tcc_realloc(p, size);
313 #ifdef TAL_INFO
314 al->nb_missed++;
315 #endif
316 return ret;
319 #endif /* USE_TAL */
321 /* ------------------------------------------------------------------------- */
322 /* CString handling */
323 static void cstr_realloc(CString *cstr, int new_size)
325 int size;
327 size = cstr->size_allocated;
328 if (size < 8)
329 size = 8; /* no need to allocate a too small first string */
330 while (size < new_size)
331 size = size * 2;
332 cstr->data = tcc_realloc(cstr->data, size);
333 cstr->size_allocated = size;
336 /* add a byte */
337 ST_INLN void cstr_ccat(CString *cstr, int ch)
339 int size;
340 size = cstr->size + 1;
341 if (size > cstr->size_allocated)
342 cstr_realloc(cstr, size);
343 ((unsigned char *)cstr->data)[size - 1] = ch;
344 cstr->size = size;
347 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
349 int size;
350 if (len <= 0)
351 len = strlen(str) + 1 + len;
352 size = cstr->size + len;
353 if (size > cstr->size_allocated)
354 cstr_realloc(cstr, size);
355 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
356 cstr->size = size;
359 /* add a wide char */
360 ST_FUNC void cstr_wccat(CString *cstr, int ch)
362 int size;
363 size = cstr->size + sizeof(nwchar_t);
364 if (size > cstr->size_allocated)
365 cstr_realloc(cstr, size);
366 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
367 cstr->size = size;
370 ST_FUNC void cstr_new(CString *cstr)
372 memset(cstr, 0, sizeof(CString));
375 /* free string and reset it to NULL */
376 ST_FUNC void cstr_free(CString *cstr)
378 tcc_free(cstr->data);
379 cstr_new(cstr);
382 /* reset string to empty */
383 ST_FUNC void cstr_reset(CString *cstr)
385 cstr->size = 0;
388 ST_FUNC int cstr_printf(CString *cstr, const char *fmt, ...)
390 va_list v;
391 int len, size;
393 va_start(v, fmt);
394 len = vsnprintf(NULL, 0, fmt, v);
395 va_end(v);
396 size = cstr->size + len + 1;
397 if (size > cstr->size_allocated)
398 cstr_realloc(cstr, size);
399 va_start(v, fmt);
400 vsnprintf((char*)cstr->data + cstr->size, size, fmt, v);
401 va_end(v);
402 cstr->size += len;
403 return len;
406 /* XXX: unicode ? */
407 static void add_char(CString *cstr, int c)
409 if (c == '\'' || c == '\"' || c == '\\') {
410 /* XXX: could be more precise if char or string */
411 cstr_ccat(cstr, '\\');
413 if (c >= 32 && c <= 126) {
414 cstr_ccat(cstr, c);
415 } else {
416 cstr_ccat(cstr, '\\');
417 if (c == '\n') {
418 cstr_ccat(cstr, 'n');
419 } else {
420 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
421 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
422 cstr_ccat(cstr, '0' + (c & 7));
427 /* ------------------------------------------------------------------------- */
428 /* allocate a new token */
429 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
431 TokenSym *ts, **ptable;
432 int i;
434 if (tok_ident >= SYM_FIRST_ANOM)
435 tcc_error("memory full (symbols)");
437 /* expand token table if needed */
438 i = tok_ident - TOK_IDENT;
439 if ((i % TOK_ALLOC_INCR) == 0) {
440 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
441 table_ident = ptable;
444 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
445 table_ident[i] = ts;
446 ts->tok = tok_ident++;
447 ts->sym_define = NULL;
448 ts->sym_label = NULL;
449 ts->sym_struct = NULL;
450 ts->sym_identifier = NULL;
451 ts->len = len;
452 ts->hash_next = NULL;
453 memcpy(ts->str, str, len);
454 ts->str[len] = '\0';
455 *pts = ts;
456 return ts;
459 #define TOK_HASH_INIT 1
460 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
463 /* find a token and add it if not found */
464 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
466 TokenSym *ts, **pts;
467 int i;
468 unsigned int h;
470 h = TOK_HASH_INIT;
471 for(i=0;i<len;i++)
472 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
473 h &= (TOK_HASH_SIZE - 1);
475 pts = &hash_ident[h];
476 for(;;) {
477 ts = *pts;
478 if (!ts)
479 break;
480 if (ts->len == len && !memcmp(ts->str, str, len))
481 return ts;
482 pts = &(ts->hash_next);
484 return tok_alloc_new(pts, str, len);
487 /* XXX: buffer overflow */
488 /* XXX: float tokens */
489 ST_FUNC const char *get_tok_str(int v, CValue *cv)
491 char *p;
492 int i, len;
494 cstr_reset(&cstr_buf);
495 p = cstr_buf.data;
497 switch(v) {
498 case TOK_CINT:
499 case TOK_CUINT:
500 case TOK_CLONG:
501 case TOK_CULONG:
502 case TOK_CLLONG:
503 case TOK_CULLONG:
504 /* XXX: not quite exact, but only useful for testing */
505 #ifdef _WIN32
506 sprintf(p, "%u", (unsigned)cv->i);
507 #else
508 sprintf(p, "%llu", (unsigned long long)cv->i);
509 #endif
510 break;
511 case TOK_LCHAR:
512 cstr_ccat(&cstr_buf, 'L');
513 case TOK_CCHAR:
514 cstr_ccat(&cstr_buf, '\'');
515 add_char(&cstr_buf, cv->i);
516 cstr_ccat(&cstr_buf, '\'');
517 cstr_ccat(&cstr_buf, '\0');
518 break;
519 case TOK_PPNUM:
520 case TOK_PPSTR:
521 return (char*)cv->str.data;
522 case TOK_LSTR:
523 cstr_ccat(&cstr_buf, 'L');
524 case TOK_STR:
525 cstr_ccat(&cstr_buf, '\"');
526 if (v == TOK_STR) {
527 len = cv->str.size - 1;
528 for(i=0;i<len;i++)
529 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
530 } else {
531 len = (cv->str.size / sizeof(nwchar_t)) - 1;
532 for(i=0;i<len;i++)
533 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
535 cstr_ccat(&cstr_buf, '\"');
536 cstr_ccat(&cstr_buf, '\0');
537 break;
539 case TOK_CFLOAT:
540 cstr_cat(&cstr_buf, "<float>", 0);
541 break;
542 case TOK_CDOUBLE:
543 cstr_cat(&cstr_buf, "<double>", 0);
544 break;
545 case TOK_CLDOUBLE:
546 cstr_cat(&cstr_buf, "<long double>", 0);
547 break;
548 case TOK_LINENUM:
549 cstr_cat(&cstr_buf, "<linenumber>", 0);
550 break;
552 /* above tokens have value, the ones below don't */
553 case TOK_LT:
554 v = '<';
555 goto addv;
556 case TOK_GT:
557 v = '>';
558 goto addv;
559 case TOK_DOTS:
560 return strcpy(p, "...");
561 case TOK_A_SHL:
562 return strcpy(p, "<<=");
563 case TOK_A_SAR:
564 return strcpy(p, ">>=");
565 case TOK_EOF:
566 return strcpy(p, "<eof>");
567 default:
568 if (v < TOK_IDENT) {
569 /* search in two bytes table */
570 const unsigned char *q = tok_two_chars;
571 while (*q) {
572 if (q[2] == v) {
573 *p++ = q[0];
574 *p++ = q[1];
575 *p = '\0';
576 return cstr_buf.data;
578 q += 3;
580 if (v >= 127) {
581 sprintf(cstr_buf.data, "<%02x>", v);
582 return cstr_buf.data;
584 addv:
585 *p++ = v;
586 *p = '\0';
587 } else if (v < tok_ident) {
588 return table_ident[v - TOK_IDENT]->str;
589 } else if (v >= SYM_FIRST_ANOM) {
590 /* special name for anonymous symbol */
591 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
592 } else {
593 /* should never happen */
594 return NULL;
596 break;
598 return cstr_buf.data;
601 /* return the current character, handling end of block if necessary
602 (but not stray) */
603 static int handle_eob(void)
605 BufferedFile *bf = file;
606 int len;
608 /* only tries to read if really end of buffer */
609 if (bf->buf_ptr >= bf->buf_end) {
610 if (bf->fd >= 0) {
611 #if defined(PARSE_DEBUG)
612 len = 1;
613 #else
614 len = IO_BUF_SIZE;
615 #endif
616 len = read(bf->fd, bf->buffer, len);
617 if (len < 0)
618 len = 0;
619 } else {
620 len = 0;
622 total_bytes += len;
623 bf->buf_ptr = bf->buffer;
624 bf->buf_end = bf->buffer + len;
625 *bf->buf_end = CH_EOB;
627 if (bf->buf_ptr < bf->buf_end) {
628 return bf->buf_ptr[0];
629 } else {
630 bf->buf_ptr = bf->buf_end;
631 return CH_EOF;
635 /* read next char from current input file and handle end of input buffer */
636 static inline void inp(void)
638 ch = *(++(file->buf_ptr));
639 /* end of buffer/file handling */
640 if (ch == CH_EOB)
641 ch = handle_eob();
644 /* handle '\[\r]\n' */
645 static int handle_stray_noerror(void)
647 while (ch == '\\') {
648 inp();
649 if (ch == '\n') {
650 file->line_num++;
651 inp();
652 } else if (ch == '\r') {
653 inp();
654 if (ch != '\n')
655 goto fail;
656 file->line_num++;
657 inp();
658 } else {
659 fail:
660 return 1;
663 return 0;
666 static void handle_stray(void)
668 if (handle_stray_noerror())
669 tcc_error("stray '\\' in program");
672 /* skip the stray and handle the \\n case. Output an error if
673 incorrect char after the stray */
674 static int handle_stray1(uint8_t *p)
676 int c;
678 file->buf_ptr = p;
679 if (p >= file->buf_end) {
680 c = handle_eob();
681 if (c != '\\')
682 return c;
683 p = file->buf_ptr;
685 ch = *p;
686 if (handle_stray_noerror()) {
687 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
688 tcc_error("stray '\\' in program");
689 *--file->buf_ptr = '\\';
691 p = file->buf_ptr;
692 c = *p;
693 return c;
696 /* handle just the EOB case, but not stray */
697 #define PEEKC_EOB(c, p)\
699 p++;\
700 c = *p;\
701 if (c == '\\') {\
702 file->buf_ptr = p;\
703 c = handle_eob();\
704 p = file->buf_ptr;\
708 /* handle the complicated stray case */
709 #define PEEKC(c, p)\
711 p++;\
712 c = *p;\
713 if (c == '\\') {\
714 c = handle_stray1(p);\
715 p = file->buf_ptr;\
719 /* input with '\[\r]\n' handling. Note that this function cannot
720 handle other characters after '\', so you cannot call it inside
721 strings or comments */
722 static void minp(void)
724 inp();
725 if (ch == '\\')
726 handle_stray();
729 /* single line C++ comments */
730 static uint8_t *parse_line_comment(uint8_t *p)
732 int c;
734 p++;
735 for(;;) {
736 c = *p;
737 redo:
738 if (c == '\n' || c == CH_EOF) {
739 break;
740 } else if (c == '\\') {
741 file->buf_ptr = p;
742 c = handle_eob();
743 p = file->buf_ptr;
744 if (c == '\\') {
745 PEEKC_EOB(c, p);
746 if (c == '\n') {
747 file->line_num++;
748 PEEKC_EOB(c, p);
749 } else if (c == '\r') {
750 PEEKC_EOB(c, p);
751 if (c == '\n') {
752 file->line_num++;
753 PEEKC_EOB(c, p);
756 } else {
757 goto redo;
759 } else {
760 p++;
763 return p;
766 /* C comments */
767 static uint8_t *parse_comment(uint8_t *p)
769 int c;
771 p++;
772 for(;;) {
773 /* fast skip loop */
774 for(;;) {
775 c = *p;
776 if (c == '\n' || c == '*' || c == '\\')
777 break;
778 p++;
779 c = *p;
780 if (c == '\n' || c == '*' || c == '\\')
781 break;
782 p++;
784 /* now we can handle all the cases */
785 if (c == '\n') {
786 file->line_num++;
787 p++;
788 } else if (c == '*') {
789 p++;
790 for(;;) {
791 c = *p;
792 if (c == '*') {
793 p++;
794 } else if (c == '/') {
795 goto end_of_comment;
796 } else if (c == '\\') {
797 file->buf_ptr = p;
798 c = handle_eob();
799 p = file->buf_ptr;
800 if (c == CH_EOF)
801 tcc_error("unexpected end of file in comment");
802 if (c == '\\') {
803 /* skip '\[\r]\n', otherwise just skip the stray */
804 while (c == '\\') {
805 PEEKC_EOB(c, p);
806 if (c == '\n') {
807 file->line_num++;
808 PEEKC_EOB(c, p);
809 } else if (c == '\r') {
810 PEEKC_EOB(c, p);
811 if (c == '\n') {
812 file->line_num++;
813 PEEKC_EOB(c, p);
815 } else {
816 goto after_star;
820 } else {
821 break;
824 after_star: ;
825 } else {
826 /* stray, eob or eof */
827 file->buf_ptr = p;
828 c = handle_eob();
829 p = file->buf_ptr;
830 if (c == CH_EOF) {
831 tcc_error("unexpected end of file in comment");
832 } else if (c == '\\') {
833 p++;
837 end_of_comment:
838 p++;
839 return p;
842 ST_FUNC int set_idnum(int c, int val)
844 int prev = isidnum_table[c - CH_EOF];
845 isidnum_table[c - CH_EOF] = val;
846 return prev;
849 #define cinp minp
851 static inline void skip_spaces(void)
853 while (isidnum_table[ch - CH_EOF] & IS_SPC)
854 cinp();
857 static inline int check_space(int t, int *spc)
859 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
860 if (*spc)
861 return 1;
862 *spc = 1;
863 } else
864 *spc = 0;
865 return 0;
868 /* parse a string without interpreting escapes */
869 static uint8_t *parse_pp_string(uint8_t *p,
870 int sep, CString *str)
872 int c;
873 p++;
874 for(;;) {
875 c = *p;
876 if (c == sep) {
877 break;
878 } else if (c == '\\') {
879 file->buf_ptr = p;
880 c = handle_eob();
881 p = file->buf_ptr;
882 if (c == CH_EOF) {
883 unterminated_string:
884 /* XXX: indicate line number of start of string */
885 tcc_error("missing terminating %c character", sep);
886 } else if (c == '\\') {
887 /* escape : just skip \[\r]\n */
888 PEEKC_EOB(c, p);
889 if (c == '\n') {
890 file->line_num++;
891 p++;
892 } else if (c == '\r') {
893 PEEKC_EOB(c, p);
894 if (c != '\n')
895 expect("'\n' after '\r'");
896 file->line_num++;
897 p++;
898 } else if (c == CH_EOF) {
899 goto unterminated_string;
900 } else {
901 if (str) {
902 cstr_ccat(str, '\\');
903 cstr_ccat(str, c);
905 p++;
908 } else if (c == '\n') {
909 file->line_num++;
910 goto add_char;
911 } else if (c == '\r') {
912 PEEKC_EOB(c, p);
913 if (c != '\n') {
914 if (str)
915 cstr_ccat(str, '\r');
916 } else {
917 file->line_num++;
918 goto add_char;
920 } else {
921 add_char:
922 if (str)
923 cstr_ccat(str, c);
924 p++;
927 p++;
928 return p;
931 /* skip block of text until #else, #elif or #endif. skip also pairs of
932 #if/#endif */
933 static void preprocess_skip(void)
935 int a, start_of_line, c, in_warn_or_error;
936 uint8_t *p;
938 p = file->buf_ptr;
939 a = 0;
940 redo_start:
941 start_of_line = 1;
942 in_warn_or_error = 0;
943 for(;;) {
944 redo_no_start:
945 c = *p;
946 switch(c) {
947 case ' ':
948 case '\t':
949 case '\f':
950 case '\v':
951 case '\r':
952 p++;
953 goto redo_no_start;
954 case '\n':
955 file->line_num++;
956 p++;
957 goto redo_start;
958 case '\\':
959 file->buf_ptr = p;
960 c = handle_eob();
961 if (c == CH_EOF) {
962 expect("#endif");
963 } else if (c == '\\') {
964 ch = file->buf_ptr[0];
965 handle_stray_noerror();
967 p = file->buf_ptr;
968 goto redo_no_start;
969 /* skip strings */
970 case '\"':
971 case '\'':
972 if (in_warn_or_error)
973 goto _default;
974 p = parse_pp_string(p, c, NULL);
975 break;
976 /* skip comments */
977 case '/':
978 if (in_warn_or_error)
979 goto _default;
980 file->buf_ptr = p;
981 ch = *p;
982 minp();
983 p = file->buf_ptr;
984 if (ch == '*') {
985 p = parse_comment(p);
986 } else if (ch == '/') {
987 p = parse_line_comment(p);
989 break;
990 case '#':
991 p++;
992 if (start_of_line) {
993 file->buf_ptr = p;
994 next_nomacro();
995 p = file->buf_ptr;
996 if (a == 0 &&
997 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
998 goto the_end;
999 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
1000 a++;
1001 else if (tok == TOK_ENDIF)
1002 a--;
1003 else if( tok == TOK_ERROR || tok == TOK_WARNING)
1004 in_warn_or_error = 1;
1005 else if (tok == TOK_LINEFEED)
1006 goto redo_start;
1007 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1008 p = parse_line_comment(p - 1);
1009 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
1010 p = parse_line_comment(p - 1);
1011 break;
1012 _default:
1013 default:
1014 p++;
1015 break;
1017 start_of_line = 0;
1019 the_end: ;
1020 file->buf_ptr = p;
1023 #if 0
1024 /* return the number of additional 'ints' necessary to store the
1025 token */
1026 static inline int tok_size(const int *p)
1028 switch(*p) {
1029 /* 4 bytes */
1030 case TOK_CINT:
1031 case TOK_CUINT:
1032 case TOK_CCHAR:
1033 case TOK_LCHAR:
1034 case TOK_CFLOAT:
1035 case TOK_LINENUM:
1036 return 1 + 1;
1037 case TOK_STR:
1038 case TOK_LSTR:
1039 case TOK_PPNUM:
1040 case TOK_PPSTR:
1041 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1042 case TOK_CLONG:
1043 case TOK_CULONG:
1044 return 1 + LONG_SIZE / 4;
1045 case TOK_CDOUBLE:
1046 case TOK_CLLONG:
1047 case TOK_CULLONG:
1048 return 1 + 2;
1049 case TOK_CLDOUBLE:
1050 return 1 + LDOUBLE_SIZE / 4;
1051 default:
1052 return 1 + 0;
1055 #endif
1057 /* token string handling */
1058 ST_INLN void tok_str_new(TokenString *s)
1060 s->str = NULL;
1061 s->len = s->lastlen = 0;
1062 s->allocated_len = 0;
1063 s->last_line_num = -1;
1066 ST_FUNC TokenString *tok_str_alloc(void)
1068 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1069 tok_str_new(str);
1070 return str;
1073 ST_FUNC int *tok_str_dup(TokenString *s)
1075 int *str;
1077 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1078 memcpy(str, s->str, s->len * sizeof(int));
1079 return str;
1082 ST_FUNC void tok_str_free_str(int *str)
1084 tal_free(tokstr_alloc, str);
1087 ST_FUNC void tok_str_free(TokenString *str)
1089 tok_str_free_str(str->str);
1090 tal_free(tokstr_alloc, str);
1093 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1095 int *str, size;
1097 size = s->allocated_len;
1098 if (size < 16)
1099 size = 16;
1100 while (size < new_size)
1101 size = size * 2;
1102 if (size > s->allocated_len) {
1103 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1104 s->allocated_len = size;
1105 s->str = str;
1107 return s->str;
1110 ST_FUNC void tok_str_add(TokenString *s, int t)
1112 int len, *str;
1114 len = s->len;
1115 str = s->str;
1116 if (len >= s->allocated_len)
1117 str = tok_str_realloc(s, len + 1);
1118 str[len++] = t;
1119 s->len = len;
1122 ST_FUNC void begin_macro(TokenString *str, int alloc)
1124 str->alloc = alloc;
1125 str->prev = macro_stack;
1126 str->prev_ptr = macro_ptr;
1127 str->save_line_num = file->line_num;
1128 macro_ptr = str->str;
1129 macro_stack = str;
1132 ST_FUNC void end_macro(void)
1134 TokenString *str = macro_stack;
1135 macro_stack = str->prev;
1136 macro_ptr = str->prev_ptr;
1137 file->line_num = str->save_line_num;
1138 if (str->alloc != 0) {
1139 if (str->alloc == 2)
1140 str->str = NULL; /* don't free */
1141 tok_str_free(str);
1145 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1147 int len, *str;
1149 len = s->lastlen = s->len;
1150 str = s->str;
1152 /* allocate space for worst case */
1153 if (len + TOK_MAX_SIZE >= s->allocated_len)
1154 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1155 str[len++] = t;
1156 switch(t) {
1157 case TOK_CINT:
1158 case TOK_CUINT:
1159 case TOK_CCHAR:
1160 case TOK_LCHAR:
1161 case TOK_CFLOAT:
1162 case TOK_LINENUM:
1163 #if LONG_SIZE == 4
1164 case TOK_CLONG:
1165 case TOK_CULONG:
1166 #endif
1167 str[len++] = cv->tab[0];
1168 break;
1169 case TOK_PPNUM:
1170 case TOK_PPSTR:
1171 case TOK_STR:
1172 case TOK_LSTR:
1174 /* Insert the string into the int array. */
1175 size_t nb_words =
1176 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1177 if (len + nb_words >= s->allocated_len)
1178 str = tok_str_realloc(s, len + nb_words + 1);
1179 str[len] = cv->str.size;
1180 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1181 len += nb_words;
1183 break;
1184 case TOK_CDOUBLE:
1185 case TOK_CLLONG:
1186 case TOK_CULLONG:
1187 #if LONG_SIZE == 8
1188 case TOK_CLONG:
1189 case TOK_CULONG:
1190 #endif
1191 #if LDOUBLE_SIZE == 8
1192 case TOK_CLDOUBLE:
1193 #endif
1194 str[len++] = cv->tab[0];
1195 str[len++] = cv->tab[1];
1196 break;
1197 #if LDOUBLE_SIZE == 12
1198 case TOK_CLDOUBLE:
1199 str[len++] = cv->tab[0];
1200 str[len++] = cv->tab[1];
1201 str[len++] = cv->tab[2];
1202 #elif LDOUBLE_SIZE == 16
1203 case TOK_CLDOUBLE:
1204 str[len++] = cv->tab[0];
1205 str[len++] = cv->tab[1];
1206 str[len++] = cv->tab[2];
1207 str[len++] = cv->tab[3];
1208 #elif LDOUBLE_SIZE != 8
1209 #error add long double size support
1210 #endif
1211 break;
1212 default:
1213 break;
1215 s->len = len;
1218 /* add the current parse token in token string 's' */
1219 ST_FUNC void tok_str_add_tok(TokenString *s)
1221 CValue cval;
1223 /* save line number info */
1224 if (file->line_num != s->last_line_num) {
1225 s->last_line_num = file->line_num;
1226 cval.i = s->last_line_num;
1227 tok_str_add2(s, TOK_LINENUM, &cval);
1229 tok_str_add2(s, tok, &tokc);
1232 /* get a token from an integer array and increment pointer. */
1233 static inline void tok_get(int *t, const int **pp, CValue *cv)
1235 const int *p = *pp;
1236 int n, *tab;
1238 tab = cv->tab;
1239 switch(*t = *p++) {
1240 #if LONG_SIZE == 4
1241 case TOK_CLONG:
1242 #endif
1243 case TOK_CINT:
1244 case TOK_CCHAR:
1245 case TOK_LCHAR:
1246 case TOK_LINENUM:
1247 cv->i = *p++;
1248 break;
1249 #if LONG_SIZE == 4
1250 case TOK_CULONG:
1251 #endif
1252 case TOK_CUINT:
1253 cv->i = (unsigned)*p++;
1254 break;
1255 case TOK_CFLOAT:
1256 tab[0] = *p++;
1257 break;
1258 case TOK_STR:
1259 case TOK_LSTR:
1260 case TOK_PPNUM:
1261 case TOK_PPSTR:
1262 cv->str.size = *p++;
1263 cv->str.data = p;
1264 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1265 break;
1266 case TOK_CDOUBLE:
1267 case TOK_CLLONG:
1268 case TOK_CULLONG:
1269 #if LONG_SIZE == 8
1270 case TOK_CLONG:
1271 case TOK_CULONG:
1272 #endif
1273 n = 2;
1274 goto copy;
1275 case TOK_CLDOUBLE:
1276 #if LDOUBLE_SIZE == 16
1277 n = 4;
1278 #elif LDOUBLE_SIZE == 12
1279 n = 3;
1280 #elif LDOUBLE_SIZE == 8
1281 n = 2;
1282 #else
1283 # error add long double size support
1284 #endif
1285 copy:
1287 *tab++ = *p++;
1288 while (--n);
1289 break;
1290 default:
1291 break;
1293 *pp = p;
1296 #if 0
1297 # define TOK_GET(t,p,c) tok_get(t,p,c)
1298 #else
1299 # define TOK_GET(t,p,c) do { \
1300 int _t = **(p); \
1301 if (TOK_HAS_VALUE(_t)) \
1302 tok_get(t, p, c); \
1303 else \
1304 *(t) = _t, ++*(p); \
1305 } while (0)
1306 #endif
1308 static int macro_is_equal(const int *a, const int *b)
1310 CValue cv;
1311 int t;
1313 if (!a || !b)
1314 return 1;
1316 while (*a && *b) {
1317 /* first time preallocate macro_equal_buf, next time only reset position to start */
1318 cstr_reset(&macro_equal_buf);
1319 TOK_GET(&t, &a, &cv);
1320 cstr_cat(&macro_equal_buf, get_tok_str(t, &cv), 0);
1321 TOK_GET(&t, &b, &cv);
1322 if (strcmp(macro_equal_buf.data, get_tok_str(t, &cv)))
1323 return 0;
1325 return !(*a || *b);
1328 /* defines handling */
1329 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1331 Sym *s, *o;
1333 o = define_find(v);
1334 s = sym_push2(&define_stack, v, macro_type, 0);
1335 s->d = str;
1336 s->next = first_arg;
1337 table_ident[v - TOK_IDENT]->sym_define = s;
1339 if (o && !macro_is_equal(o->d, s->d))
1340 tcc_warning("%s redefined", get_tok_str(v, NULL));
1343 /* undefined a define symbol. Its name is just set to zero */
1344 ST_FUNC void define_undef(Sym *s)
1346 int v = s->v;
1347 if (v >= TOK_IDENT && v < tok_ident)
1348 table_ident[v - TOK_IDENT]->sym_define = NULL;
1351 ST_INLN Sym *define_find(int v)
1353 v -= TOK_IDENT;
1354 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1355 return NULL;
1356 return table_ident[v]->sym_define;
1359 /* free define stack until top reaches 'b' */
1360 ST_FUNC void free_defines(Sym *b)
1362 while (define_stack != b) {
1363 Sym *top = define_stack;
1364 define_stack = top->prev;
1365 tok_str_free_str(top->d);
1366 define_undef(top);
1367 sym_free(top);
1371 /* label lookup */
1372 ST_FUNC Sym *label_find(int v)
1374 v -= TOK_IDENT;
1375 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1376 return NULL;
1377 return table_ident[v]->sym_label;
1380 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1382 Sym *s, **ps;
1383 s = sym_push2(ptop, v, 0, 0);
1384 s->r = flags;
1385 ps = &table_ident[v - TOK_IDENT]->sym_label;
1386 if (ptop == &global_label_stack) {
1387 /* modify the top most local identifier, so that
1388 sym_identifier will point to 's' when popped */
1389 while (*ps != NULL)
1390 ps = &(*ps)->prev_tok;
1392 s->prev_tok = *ps;
1393 *ps = s;
1394 return s;
1397 /* pop labels until element last is reached. Look if any labels are
1398 undefined. Define symbols if '&&label' was used. */
1399 ST_FUNC void label_pop(Sym **ptop, Sym *slast, int keep)
1401 Sym *s, *s1;
1402 for(s = *ptop; s != slast; s = s1) {
1403 s1 = s->prev;
1404 if (s->r == LABEL_DECLARED) {
1405 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1406 } else if (s->r == LABEL_FORWARD) {
1407 tcc_error("label '%s' used but not defined",
1408 get_tok_str(s->v, NULL));
1409 } else {
1410 if (s->c) {
1411 /* define corresponding symbol. A size of
1412 1 is put. */
1413 put_extern_sym(s, cur_text_section, s->jnext, 1);
1416 /* remove label */
1417 if (s->r != LABEL_GONE)
1418 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1419 if (!keep)
1420 sym_free(s);
1421 else
1422 s->r = LABEL_GONE;
1424 if (!keep)
1425 *ptop = slast;
1428 /* fake the nth "#if defined test_..." for tcc -dt -run */
1429 static void maybe_run_test(TCCState *s)
1431 const char *p;
1432 if (s->include_stack_ptr != s->include_stack)
1433 return;
1434 p = get_tok_str(tok, NULL);
1435 if (0 != memcmp(p, "test_", 5))
1436 return;
1437 if (0 != --s->run_test)
1438 return;
1439 fprintf(s->ppfp, "\n[%s]\n" + !(s->dflag & 32), p), fflush(s->ppfp);
1440 define_push(tok, MACRO_OBJ, NULL, NULL);
1443 /* eval an expression for #if/#elif */
1444 static int expr_preprocess(void)
1446 int c, t;
1447 TokenString *str;
1449 str = tok_str_alloc();
1450 pp_expr = 1;
1451 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1452 next(); /* do macro subst */
1453 if (tok == TOK_DEFINED) {
1454 next_nomacro();
1455 t = tok;
1456 if (t == '(')
1457 next_nomacro();
1458 if (tok < TOK_IDENT)
1459 expect("identifier");
1460 if (tcc_state->run_test)
1461 maybe_run_test(tcc_state);
1462 c = define_find(tok) != 0;
1463 if (t == '(') {
1464 next_nomacro();
1465 if (tok != ')')
1466 expect("')'");
1468 tok = TOK_CINT;
1469 tokc.i = c;
1470 } else if (tok >= TOK_IDENT) {
1471 /* if undefined macro */
1472 tok = TOK_CINT;
1473 tokc.i = 0;
1475 tok_str_add_tok(str);
1477 pp_expr = 0;
1478 tok_str_add(str, -1); /* simulate end of file */
1479 tok_str_add(str, 0);
1480 /* now evaluate C constant expression */
1481 begin_macro(str, 1);
1482 next();
1483 c = expr_const();
1484 end_macro();
1485 return c != 0;
1489 /* parse after #define */
1490 ST_FUNC void parse_define(void)
1492 Sym *s, *first, **ps;
1493 int v, t, varg, is_vaargs, spc;
1494 int saved_parse_flags = parse_flags;
1496 v = tok;
1497 if (v < TOK_IDENT || v == TOK_DEFINED)
1498 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1499 /* XXX: should check if same macro (ANSI) */
1500 first = NULL;
1501 t = MACRO_OBJ;
1502 /* We have to parse the whole define as if not in asm mode, in particular
1503 no line comment with '#' must be ignored. Also for function
1504 macros the argument list must be parsed without '.' being an ID
1505 character. */
1506 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1507 /* '(' must be just after macro definition for MACRO_FUNC */
1508 next_nomacro();
1509 parse_flags &= ~PARSE_FLAG_SPACES;
1510 if (tok == '(') {
1511 int dotid = set_idnum('.', 0);
1512 next_nomacro();
1513 ps = &first;
1514 if (tok != ')') for (;;) {
1515 varg = tok;
1516 next_nomacro();
1517 is_vaargs = 0;
1518 if (varg == TOK_DOTS) {
1519 varg = TOK___VA_ARGS__;
1520 is_vaargs = 1;
1521 } else if (tok == TOK_DOTS && gnu_ext) {
1522 is_vaargs = 1;
1523 next_nomacro();
1525 if (varg < TOK_IDENT)
1526 bad_list:
1527 tcc_error("bad macro parameter list");
1528 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1529 *ps = s;
1530 ps = &s->next;
1531 if (tok == ')')
1532 break;
1533 if (tok != ',' || is_vaargs)
1534 goto bad_list;
1535 next_nomacro();
1537 parse_flags |= PARSE_FLAG_SPACES;
1538 next_nomacro();
1539 t = MACRO_FUNC;
1540 set_idnum('.', dotid);
1543 tokstr_buf.len = 0;
1544 spc = 2;
1545 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1546 /* The body of a macro definition should be parsed such that identifiers
1547 are parsed like the file mode determines (i.e. with '.' being an
1548 ID character in asm mode). But '#' should be retained instead of
1549 regarded as line comment leader, so still don't set ASM_FILE
1550 in parse_flags. */
1551 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1552 /* remove spaces around ## and after '#' */
1553 if (TOK_TWOSHARPS == tok) {
1554 if (2 == spc)
1555 goto bad_twosharp;
1556 if (1 == spc)
1557 --tokstr_buf.len;
1558 spc = 3;
1559 tok = TOK_PPJOIN;
1560 } else if ('#' == tok) {
1561 spc = 4;
1562 } else if (check_space(tok, &spc)) {
1563 goto skip;
1565 tok_str_add2(&tokstr_buf, tok, &tokc);
1566 skip:
1567 next_nomacro();
1570 parse_flags = saved_parse_flags;
1571 if (spc == 1)
1572 --tokstr_buf.len; /* remove trailing space */
1573 tok_str_add(&tokstr_buf, 0);
1574 if (3 == spc)
1575 bad_twosharp:
1576 tcc_error("'##' cannot appear at either end of macro");
1577 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1580 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1582 const unsigned char *s;
1583 unsigned int h;
1584 CachedInclude *e;
1585 int i;
1587 h = TOK_HASH_INIT;
1588 s = (unsigned char *) filename;
1589 while (*s) {
1590 #ifdef _WIN32
1591 h = TOK_HASH_FUNC(h, toup(*s));
1592 #else
1593 h = TOK_HASH_FUNC(h, *s);
1594 #endif
1595 s++;
1597 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1599 i = s1->cached_includes_hash[h];
1600 for(;;) {
1601 if (i == 0)
1602 break;
1603 e = s1->cached_includes[i - 1];
1604 if (0 == PATHCMP(e->filename, filename))
1605 return e;
1606 i = e->hash_next;
1608 if (!add)
1609 return NULL;
1611 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1612 strcpy(e->filename, filename);
1613 e->ifndef_macro = e->once = 0;
1614 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1615 /* add in hash table */
1616 e->hash_next = s1->cached_includes_hash[h];
1617 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1618 #ifdef INC_DEBUG
1619 printf("adding cached '%s'\n", filename);
1620 #endif
1621 return e;
1624 static void pragma_parse(TCCState *s1)
1626 next_nomacro();
1627 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1628 int t = tok, v;
1629 Sym *s;
1631 if (next(), tok != '(')
1632 goto pragma_err;
1633 if (next(), tok != TOK_STR)
1634 goto pragma_err;
1635 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1636 if (next(), tok != ')')
1637 goto pragma_err;
1638 if (t == TOK_push_macro) {
1639 while (NULL == (s = define_find(v)))
1640 define_push(v, 0, NULL, NULL);
1641 s->type.ref = s; /* set push boundary */
1642 } else {
1643 for (s = define_stack; s; s = s->prev)
1644 if (s->v == v && s->type.ref == s) {
1645 s->type.ref = NULL;
1646 break;
1649 if (s)
1650 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1651 else
1652 tcc_warning("unbalanced #pragma pop_macro");
1653 pp_debug_tok = t, pp_debug_symv = v;
1655 } else if (tok == TOK_once) {
1656 search_cached_include(s1, file->filename, 1)->once = pp_once;
1658 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1659 /* tcc -E: keep pragmas below unchanged */
1660 unget_tok(' ');
1661 unget_tok(TOK_PRAGMA);
1662 unget_tok('#');
1663 unget_tok(TOK_LINEFEED);
1665 } else if (tok == TOK_pack) {
1666 /* This may be:
1667 #pragma pack(1) // set
1668 #pragma pack() // reset to default
1669 #pragma pack(push,1) // push & set
1670 #pragma pack(pop) // restore previous */
1671 next();
1672 skip('(');
1673 if (tok == TOK_ASM_pop) {
1674 next();
1675 if (s1->pack_stack_ptr <= s1->pack_stack) {
1676 stk_error:
1677 tcc_error("out of pack stack");
1679 s1->pack_stack_ptr--;
1680 } else {
1681 int val = 0;
1682 if (tok != ')') {
1683 if (tok == TOK_ASM_push) {
1684 next();
1685 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1686 goto stk_error;
1687 s1->pack_stack_ptr++;
1688 skip(',');
1690 if (tok != TOK_CINT)
1691 goto pragma_err;
1692 val = tokc.i;
1693 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1694 goto pragma_err;
1695 next();
1697 *s1->pack_stack_ptr = val;
1699 if (tok != ')')
1700 goto pragma_err;
1702 } else if (tok == TOK_comment) {
1703 char *p; int t;
1704 next();
1705 skip('(');
1706 t = tok;
1707 next();
1708 skip(',');
1709 if (tok != TOK_STR)
1710 goto pragma_err;
1711 p = tcc_strdup((char *)tokc.str.data);
1712 next();
1713 if (tok != ')')
1714 goto pragma_err;
1715 if (t == TOK_lib) {
1716 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1717 } else {
1718 if (t == TOK_option)
1719 tcc_set_options(s1, p);
1720 tcc_free(p);
1723 } else if (s1->warn_unsupported) {
1724 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1726 return;
1728 pragma_err:
1729 tcc_error("malformed #pragma directive");
1730 return;
1733 /* is_bof is true if first non space token at beginning of file */
1734 ST_FUNC void preprocess(int is_bof)
1736 TCCState *s1 = tcc_state;
1737 int i, c, n, saved_parse_flags;
1738 char buf[1024], *q;
1739 Sym *s;
1741 saved_parse_flags = parse_flags;
1742 parse_flags = PARSE_FLAG_PREPROCESS
1743 | PARSE_FLAG_TOK_NUM
1744 | PARSE_FLAG_TOK_STR
1745 | PARSE_FLAG_LINEFEED
1746 | (parse_flags & PARSE_FLAG_ASM_FILE)
1749 next_nomacro();
1750 redo:
1751 switch(tok) {
1752 case TOK_DEFINE:
1753 pp_debug_tok = tok;
1754 next_nomacro();
1755 pp_debug_symv = tok;
1756 parse_define();
1757 break;
1758 case TOK_UNDEF:
1759 pp_debug_tok = tok;
1760 next_nomacro();
1761 pp_debug_symv = tok;
1762 s = define_find(tok);
1763 /* undefine symbol by putting an invalid name */
1764 if (s)
1765 define_undef(s);
1766 break;
1767 case TOK_INCLUDE:
1768 case TOK_INCLUDE_NEXT:
1769 ch = file->buf_ptr[0];
1770 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1771 skip_spaces();
1772 if (ch == '<') {
1773 c = '>';
1774 goto read_name;
1775 } else if (ch == '\"') {
1776 c = ch;
1777 read_name:
1778 inp();
1779 q = buf;
1780 while (ch != c && ch != '\n' && ch != CH_EOF) {
1781 if ((q - buf) < sizeof(buf) - 1)
1782 *q++ = ch;
1783 if (ch == '\\') {
1784 if (handle_stray_noerror() == 0)
1785 --q;
1786 } else
1787 inp();
1789 *q = '\0';
1790 minp();
1791 #if 0
1792 /* eat all spaces and comments after include */
1793 /* XXX: slightly incorrect */
1794 while (ch1 != '\n' && ch1 != CH_EOF)
1795 inp();
1796 #endif
1797 } else {
1798 int len;
1799 /* computed #include : concatenate everything up to linefeed,
1800 the result must be one of the two accepted forms.
1801 Don't convert pp-tokens to tokens here. */
1802 parse_flags = (PARSE_FLAG_PREPROCESS
1803 | PARSE_FLAG_LINEFEED
1804 | (parse_flags & PARSE_FLAG_ASM_FILE));
1805 next();
1806 buf[0] = '\0';
1807 while (tok != TOK_LINEFEED) {
1808 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1809 next();
1811 len = strlen(buf);
1812 /* check syntax and remove '<>|""' */
1813 if ((len < 2 || ((buf[0] != '"' || buf[len-1] != '"') &&
1814 (buf[0] != '<' || buf[len-1] != '>'))))
1815 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1816 c = buf[len-1];
1817 memmove(buf, buf + 1, len - 2);
1818 buf[len - 2] = '\0';
1821 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1822 tcc_error("#include recursion too deep");
1823 /* push current file on stack */
1824 *s1->include_stack_ptr++ = file;
1825 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index + 1 : 0;
1826 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1827 for (; i < n; ++i) {
1828 char buf1[sizeof file->filename];
1829 CachedInclude *e;
1830 const char *path;
1832 if (i == 0) {
1833 /* check absolute include path */
1834 if (!IS_ABSPATH(buf))
1835 continue;
1836 buf1[0] = 0;
1838 } else if (i == 1) {
1839 /* search in file's dir if "header.h" */
1840 if (c != '\"')
1841 continue;
1842 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1843 path = file->true_filename;
1844 pstrncpy(buf1, path, tcc_basename(path) - path);
1846 } else {
1847 /* search in all the include paths */
1848 int j = i - 2, k = j - s1->nb_include_paths;
1849 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1850 pstrcpy(buf1, sizeof(buf1), path);
1851 pstrcat(buf1, sizeof(buf1), "/");
1854 pstrcat(buf1, sizeof(buf1), buf);
1855 e = search_cached_include(s1, buf1, 0);
1856 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1857 /* no need to parse the include because the 'ifndef macro'
1858 is defined (or had #pragma once) */
1859 #ifdef INC_DEBUG
1860 printf("%s: skipping cached %s\n", file->filename, buf1);
1861 #endif
1862 goto include_done;
1865 if (tcc_open(s1, buf1) < 0)
1866 continue;
1868 file->include_next_index = i;
1869 #ifdef INC_DEBUG
1870 printf("%s: including %s\n", file->prev->filename, file->filename);
1871 #endif
1872 /* update target deps */
1873 if (s1->gen_deps) {
1874 BufferedFile *bf = file;
1875 while (i == 1 && (bf = bf->prev))
1876 i = bf->include_next_index;
1877 /* skip system include files */
1878 if (n - i > s1->nb_sysinclude_paths)
1879 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1880 tcc_strdup(buf1));
1882 /* add include file debug info */
1883 tcc_debug_bincl(tcc_state);
1884 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1885 ch = file->buf_ptr[0];
1886 goto the_end;
1888 tcc_error("include file '%s' not found", buf);
1889 include_done:
1890 --s1->include_stack_ptr;
1891 break;
1892 case TOK_IFNDEF:
1893 c = 1;
1894 goto do_ifdef;
1895 case TOK_IF:
1896 c = expr_preprocess();
1897 goto do_if;
1898 case TOK_IFDEF:
1899 c = 0;
1900 do_ifdef:
1901 next_nomacro();
1902 if (tok < TOK_IDENT)
1903 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1904 if (is_bof) {
1905 if (c) {
1906 #ifdef INC_DEBUG
1907 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1908 #endif
1909 file->ifndef_macro = tok;
1912 c = (define_find(tok) != 0) ^ c;
1913 do_if:
1914 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1915 tcc_error("memory full (ifdef)");
1916 *s1->ifdef_stack_ptr++ = c;
1917 goto test_skip;
1918 case TOK_ELSE:
1919 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1920 tcc_error("#else without matching #if");
1921 if (s1->ifdef_stack_ptr[-1] & 2)
1922 tcc_error("#else after #else");
1923 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1924 goto test_else;
1925 case TOK_ELIF:
1926 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1927 tcc_error("#elif without matching #if");
1928 c = s1->ifdef_stack_ptr[-1];
1929 if (c > 1)
1930 tcc_error("#elif after #else");
1931 /* last #if/#elif expression was true: we skip */
1932 if (c == 1) {
1933 c = 0;
1934 } else {
1935 c = expr_preprocess();
1936 s1->ifdef_stack_ptr[-1] = c;
1938 test_else:
1939 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1940 file->ifndef_macro = 0;
1941 test_skip:
1942 if (!(c & 1)) {
1943 preprocess_skip();
1944 is_bof = 0;
1945 goto redo;
1947 break;
1948 case TOK_ENDIF:
1949 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1950 tcc_error("#endif without matching #if");
1951 s1->ifdef_stack_ptr--;
1952 /* '#ifndef macro' was at the start of file. Now we check if
1953 an '#endif' is exactly at the end of file */
1954 if (file->ifndef_macro &&
1955 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1956 file->ifndef_macro_saved = file->ifndef_macro;
1957 /* need to set to zero to avoid false matches if another
1958 #ifndef at middle of file */
1959 file->ifndef_macro = 0;
1960 while (tok != TOK_LINEFEED)
1961 next_nomacro();
1962 tok_flags |= TOK_FLAG_ENDIF;
1963 goto the_end;
1965 break;
1966 case TOK_PPNUM:
1967 n = strtoul((char*)tokc.str.data, &q, 10);
1968 goto _line_num;
1969 case TOK_LINE:
1970 next();
1971 if (tok != TOK_CINT)
1972 _line_err:
1973 tcc_error("wrong #line format");
1974 n = tokc.i;
1975 _line_num:
1976 next();
1977 if (tok != TOK_LINEFEED) {
1978 if (tok == TOK_STR) {
1979 if (file->true_filename == file->filename)
1980 file->true_filename = tcc_strdup(file->filename);
1981 /* prepend directory from real file */
1982 pstrcpy(buf, sizeof buf, file->true_filename);
1983 *tcc_basename(buf) = 0;
1984 pstrcat(buf, sizeof buf, (char *)tokc.str.data);
1985 tcc_debug_putfile(s1, buf);
1986 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
1987 break;
1988 else
1989 goto _line_err;
1990 --n;
1992 if (file->fd > 0)
1993 total_lines += file->line_num - n;
1994 file->line_num = n;
1995 break;
1996 case TOK_ERROR:
1997 case TOK_WARNING:
1998 c = tok;
1999 ch = file->buf_ptr[0];
2000 skip_spaces();
2001 q = buf;
2002 while (ch != '\n' && ch != CH_EOF) {
2003 if ((q - buf) < sizeof(buf) - 1)
2004 *q++ = ch;
2005 if (ch == '\\') {
2006 if (handle_stray_noerror() == 0)
2007 --q;
2008 } else
2009 inp();
2011 *q = '\0';
2012 if (c == TOK_ERROR)
2013 tcc_error("#error %s", buf);
2014 else
2015 tcc_warning("#warning %s", buf);
2016 break;
2017 case TOK_PRAGMA:
2018 pragma_parse(s1);
2019 break;
2020 case TOK_LINEFEED:
2021 goto the_end;
2022 default:
2023 /* ignore gas line comment in an 'S' file. */
2024 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
2025 goto ignore;
2026 if (tok == '!' && is_bof)
2027 /* '!' is ignored at beginning to allow C scripts. */
2028 goto ignore;
2029 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
2030 ignore:
2031 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
2032 goto the_end;
2034 /* ignore other preprocess commands or #! for C scripts */
2035 while (tok != TOK_LINEFEED)
2036 next_nomacro();
2037 the_end:
2038 parse_flags = saved_parse_flags;
2041 /* evaluate escape codes in a string. */
2042 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
2044 int c, n;
2045 const uint8_t *p;
2047 p = buf;
2048 for(;;) {
2049 c = *p;
2050 if (c == '\0')
2051 break;
2052 if (c == '\\') {
2053 p++;
2054 /* escape */
2055 c = *p;
2056 switch(c) {
2057 case '0': case '1': case '2': case '3':
2058 case '4': case '5': case '6': case '7':
2059 /* at most three octal digits */
2060 n = c - '0';
2061 p++;
2062 c = *p;
2063 if (isoct(c)) {
2064 n = n * 8 + c - '0';
2065 p++;
2066 c = *p;
2067 if (isoct(c)) {
2068 n = n * 8 + c - '0';
2069 p++;
2072 c = n;
2073 goto add_char_nonext;
2074 case 'x':
2075 case 'u':
2076 case 'U':
2077 p++;
2078 n = 0;
2079 for(;;) {
2080 c = *p;
2081 if (c >= 'a' && c <= 'f')
2082 c = c - 'a' + 10;
2083 else if (c >= 'A' && c <= 'F')
2084 c = c - 'A' + 10;
2085 else if (isnum(c))
2086 c = c - '0';
2087 else
2088 break;
2089 n = n * 16 + c;
2090 p++;
2092 c = n;
2093 goto add_char_nonext;
2094 case 'a':
2095 c = '\a';
2096 break;
2097 case 'b':
2098 c = '\b';
2099 break;
2100 case 'f':
2101 c = '\f';
2102 break;
2103 case 'n':
2104 c = '\n';
2105 break;
2106 case 'r':
2107 c = '\r';
2108 break;
2109 case 't':
2110 c = '\t';
2111 break;
2112 case 'v':
2113 c = '\v';
2114 break;
2115 case 'e':
2116 if (!gnu_ext)
2117 goto invalid_escape;
2118 c = 27;
2119 break;
2120 case '\'':
2121 case '\"':
2122 case '\\':
2123 case '?':
2124 break;
2125 default:
2126 invalid_escape:
2127 if (c >= '!' && c <= '~')
2128 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2129 else
2130 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2131 break;
2133 } else if (is_long && c >= 0x80) {
2134 /* assume we are processing UTF-8 sequence */
2135 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2137 int cont; /* count of continuation bytes */
2138 int skip; /* how many bytes should skip when error occurred */
2139 int i;
2141 /* decode leading byte */
2142 if (c < 0xC2) {
2143 skip = 1; goto invalid_utf8_sequence;
2144 } else if (c <= 0xDF) {
2145 cont = 1; n = c & 0x1f;
2146 } else if (c <= 0xEF) {
2147 cont = 2; n = c & 0xf;
2148 } else if (c <= 0xF4) {
2149 cont = 3; n = c & 0x7;
2150 } else {
2151 skip = 1; goto invalid_utf8_sequence;
2154 /* decode continuation bytes */
2155 for (i = 1; i <= cont; i++) {
2156 int l = 0x80, h = 0xBF;
2158 /* adjust limit for second byte */
2159 if (i == 1) {
2160 switch (c) {
2161 case 0xE0: l = 0xA0; break;
2162 case 0xED: h = 0x9F; break;
2163 case 0xF0: l = 0x90; break;
2164 case 0xF4: h = 0x8F; break;
2168 if (p[i] < l || p[i] > h) {
2169 skip = i; goto invalid_utf8_sequence;
2172 n = (n << 6) | (p[i] & 0x3f);
2175 /* advance pointer */
2176 p += 1 + cont;
2177 c = n;
2178 goto add_char_nonext;
2180 /* error handling */
2181 invalid_utf8_sequence:
2182 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2183 c = 0xFFFD;
2184 p += skip;
2185 goto add_char_nonext;
2188 p++;
2189 add_char_nonext:
2190 if (!is_long)
2191 cstr_ccat(outstr, c);
2192 else {
2193 #ifdef TCC_TARGET_PE
2194 /* store as UTF-16 */
2195 if (c < 0x10000) {
2196 cstr_wccat(outstr, c);
2197 } else {
2198 c -= 0x10000;
2199 cstr_wccat(outstr, (c >> 10) + 0xD800);
2200 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2202 #else
2203 cstr_wccat(outstr, c);
2204 #endif
2207 /* add a trailing '\0' */
2208 if (!is_long)
2209 cstr_ccat(outstr, '\0');
2210 else
2211 cstr_wccat(outstr, '\0');
2214 static void parse_string(const char *s, int len)
2216 uint8_t buf[1000], *p = buf;
2217 int is_long, sep;
2219 if ((is_long = *s == 'L'))
2220 ++s, --len;
2221 sep = *s++;
2222 len -= 2;
2223 if (len >= sizeof buf)
2224 p = tcc_malloc(len + 1);
2225 memcpy(p, s, len);
2226 p[len] = 0;
2228 cstr_reset(&tokcstr);
2229 parse_escape_string(&tokcstr, p, is_long);
2230 if (p != buf)
2231 tcc_free(p);
2233 if (sep == '\'') {
2234 int char_size, i, n, c;
2235 /* XXX: make it portable */
2236 if (!is_long)
2237 tok = TOK_CCHAR, char_size = 1;
2238 else
2239 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2240 n = tokcstr.size / char_size - 1;
2241 if (n < 1)
2242 tcc_error("empty character constant");
2243 if (n > 1)
2244 tcc_warning("multi-character character constant");
2245 for (c = i = 0; i < n; ++i) {
2246 if (is_long)
2247 c = ((nwchar_t *)tokcstr.data)[i];
2248 else
2249 c = (c << 8) | ((char *)tokcstr.data)[i];
2251 tokc.i = c;
2252 } else {
2253 tokc.str.size = tokcstr.size;
2254 tokc.str.data = tokcstr.data;
2255 if (!is_long)
2256 tok = TOK_STR;
2257 else
2258 tok = TOK_LSTR;
2262 /* we use 64 bit numbers */
2263 #define BN_SIZE 2
2265 /* bn = (bn << shift) | or_val */
2266 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2268 int i;
2269 unsigned int v;
2270 for(i=0;i<BN_SIZE;i++) {
2271 v = bn[i];
2272 bn[i] = (v << shift) | or_val;
2273 or_val = v >> (32 - shift);
2277 static void bn_zero(unsigned int *bn)
2279 int i;
2280 for(i=0;i<BN_SIZE;i++) {
2281 bn[i] = 0;
2285 /* parse number in null terminated string 'p' and return it in the
2286 current token */
2287 static void parse_number(const char *p)
2289 int b, t, shift, frac_bits, s, exp_val, ch;
2290 char *q;
2291 unsigned int bn[BN_SIZE];
2292 double d;
2294 /* number */
2295 q = token_buf;
2296 ch = *p++;
2297 t = ch;
2298 ch = *p++;
2299 *q++ = t;
2300 b = 10;
2301 if (t == '.') {
2302 goto float_frac_parse;
2303 } else if (t == '0') {
2304 if (ch == 'x' || ch == 'X') {
2305 q--;
2306 ch = *p++;
2307 b = 16;
2308 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2309 q--;
2310 ch = *p++;
2311 b = 2;
2314 /* parse all digits. cannot check octal numbers at this stage
2315 because of floating point constants */
2316 while (1) {
2317 if (ch >= 'a' && ch <= 'f')
2318 t = ch - 'a' + 10;
2319 else if (ch >= 'A' && ch <= 'F')
2320 t = ch - 'A' + 10;
2321 else if (isnum(ch))
2322 t = ch - '0';
2323 else
2324 break;
2325 if (t >= b)
2326 break;
2327 if (q >= token_buf + STRING_MAX_SIZE) {
2328 num_too_long:
2329 tcc_error("number too long");
2331 *q++ = ch;
2332 ch = *p++;
2334 if (ch == '.' ||
2335 ((ch == 'e' || ch == 'E') && b == 10) ||
2336 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2337 if (b != 10) {
2338 /* NOTE: strtox should support that for hexa numbers, but
2339 non ISOC99 libcs do not support it, so we prefer to do
2340 it by hand */
2341 /* hexadecimal or binary floats */
2342 /* XXX: handle overflows */
2343 *q = '\0';
2344 if (b == 16)
2345 shift = 4;
2346 else
2347 shift = 1;
2348 bn_zero(bn);
2349 q = token_buf;
2350 while (1) {
2351 t = *q++;
2352 if (t == '\0') {
2353 break;
2354 } else if (t >= 'a') {
2355 t = t - 'a' + 10;
2356 } else if (t >= 'A') {
2357 t = t - 'A' + 10;
2358 } else {
2359 t = t - '0';
2361 bn_lshift(bn, shift, t);
2363 frac_bits = 0;
2364 if (ch == '.') {
2365 ch = *p++;
2366 while (1) {
2367 t = ch;
2368 if (t >= 'a' && t <= 'f') {
2369 t = t - 'a' + 10;
2370 } else if (t >= 'A' && t <= 'F') {
2371 t = t - 'A' + 10;
2372 } else if (t >= '0' && t <= '9') {
2373 t = t - '0';
2374 } else {
2375 break;
2377 if (t >= b)
2378 tcc_error("invalid digit");
2379 bn_lshift(bn, shift, t);
2380 frac_bits += shift;
2381 ch = *p++;
2384 if (ch != 'p' && ch != 'P')
2385 expect("exponent");
2386 ch = *p++;
2387 s = 1;
2388 exp_val = 0;
2389 if (ch == '+') {
2390 ch = *p++;
2391 } else if (ch == '-') {
2392 s = -1;
2393 ch = *p++;
2395 if (ch < '0' || ch > '9')
2396 expect("exponent digits");
2397 while (ch >= '0' && ch <= '9') {
2398 exp_val = exp_val * 10 + ch - '0';
2399 ch = *p++;
2401 exp_val = exp_val * s;
2403 /* now we can generate the number */
2404 /* XXX: should patch directly float number */
2405 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2406 d = ldexp(d, exp_val - frac_bits);
2407 t = toup(ch);
2408 if (t == 'F') {
2409 ch = *p++;
2410 tok = TOK_CFLOAT;
2411 /* float : should handle overflow */
2412 tokc.f = (float)d;
2413 } else if (t == 'L') {
2414 ch = *p++;
2415 #ifdef TCC_TARGET_PE
2416 tok = TOK_CDOUBLE;
2417 tokc.d = d;
2418 #else
2419 tok = TOK_CLDOUBLE;
2420 /* XXX: not large enough */
2421 tokc.ld = (long double)d;
2422 #endif
2423 } else {
2424 tok = TOK_CDOUBLE;
2425 tokc.d = d;
2427 } else {
2428 /* decimal floats */
2429 if (ch == '.') {
2430 if (q >= token_buf + STRING_MAX_SIZE)
2431 goto num_too_long;
2432 *q++ = ch;
2433 ch = *p++;
2434 float_frac_parse:
2435 while (ch >= '0' && ch <= '9') {
2436 if (q >= token_buf + STRING_MAX_SIZE)
2437 goto num_too_long;
2438 *q++ = ch;
2439 ch = *p++;
2442 if (ch == 'e' || ch == 'E') {
2443 if (q >= token_buf + STRING_MAX_SIZE)
2444 goto num_too_long;
2445 *q++ = ch;
2446 ch = *p++;
2447 if (ch == '-' || ch == '+') {
2448 if (q >= token_buf + STRING_MAX_SIZE)
2449 goto num_too_long;
2450 *q++ = ch;
2451 ch = *p++;
2453 if (ch < '0' || ch > '9')
2454 expect("exponent digits");
2455 while (ch >= '0' && ch <= '9') {
2456 if (q >= token_buf + STRING_MAX_SIZE)
2457 goto num_too_long;
2458 *q++ = ch;
2459 ch = *p++;
2462 *q = '\0';
2463 t = toup(ch);
2464 errno = 0;
2465 if (t == 'F') {
2466 ch = *p++;
2467 tok = TOK_CFLOAT;
2468 tokc.f = strtof(token_buf, NULL);
2469 } else if (t == 'L') {
2470 ch = *p++;
2471 #ifdef TCC_TARGET_PE
2472 tok = TOK_CDOUBLE;
2473 tokc.d = strtod(token_buf, NULL);
2474 #else
2475 tok = TOK_CLDOUBLE;
2476 tokc.ld = strtold(token_buf, NULL);
2477 #endif
2478 } else {
2479 tok = TOK_CDOUBLE;
2480 tokc.d = strtod(token_buf, NULL);
2483 } else {
2484 unsigned long long n, n1;
2485 int lcount, ucount, ov = 0;
2486 const char *p1;
2488 /* integer number */
2489 *q = '\0';
2490 q = token_buf;
2491 if (b == 10 && *q == '0') {
2492 b = 8;
2493 q++;
2495 n = 0;
2496 while(1) {
2497 t = *q++;
2498 /* no need for checks except for base 10 / 8 errors */
2499 if (t == '\0')
2500 break;
2501 else if (t >= 'a')
2502 t = t - 'a' + 10;
2503 else if (t >= 'A')
2504 t = t - 'A' + 10;
2505 else
2506 t = t - '0';
2507 if (t >= b)
2508 tcc_error("invalid digit");
2509 n1 = n;
2510 n = n * b + t;
2511 /* detect overflow */
2512 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2513 ov = 1;
2516 /* Determine the characteristics (unsigned and/or 64bit) the type of
2517 the constant must have according to the constant suffix(es) */
2518 lcount = ucount = 0;
2519 p1 = p;
2520 for(;;) {
2521 t = toup(ch);
2522 if (t == 'L') {
2523 if (lcount >= 2)
2524 tcc_error("three 'l's in integer constant");
2525 if (lcount && *(p - 1) != ch)
2526 tcc_error("incorrect integer suffix: %s", p1);
2527 lcount++;
2528 ch = *p++;
2529 } else if (t == 'U') {
2530 if (ucount >= 1)
2531 tcc_error("two 'u's in integer constant");
2532 ucount++;
2533 ch = *p++;
2534 } else {
2535 break;
2539 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2540 if (ucount == 0 && b == 10) {
2541 if (lcount <= (LONG_SIZE == 4)) {
2542 if (n >= 0x80000000U)
2543 lcount = (LONG_SIZE == 4) + 1;
2545 if (n >= 0x8000000000000000ULL)
2546 ov = 1, ucount = 1;
2547 } else {
2548 if (lcount <= (LONG_SIZE == 4)) {
2549 if (n >= 0x100000000ULL)
2550 lcount = (LONG_SIZE == 4) + 1;
2551 else if (n >= 0x80000000U)
2552 ucount = 1;
2554 if (n >= 0x8000000000000000ULL)
2555 ucount = 1;
2558 if (ov)
2559 tcc_warning("integer constant overflow");
2561 tok = TOK_CINT;
2562 if (lcount) {
2563 tok = TOK_CLONG;
2564 if (lcount == 2)
2565 tok = TOK_CLLONG;
2567 if (ucount)
2568 ++tok; /* TOK_CU... */
2569 tokc.i = n;
2571 if (ch)
2572 tcc_error("invalid number\n");
2576 #define PARSE2(c1, tok1, c2, tok2) \
2577 case c1: \
2578 PEEKC(c, p); \
2579 if (c == c2) { \
2580 p++; \
2581 tok = tok2; \
2582 } else { \
2583 tok = tok1; \
2585 break;
2587 /* return next token without macro substitution */
2588 static inline void next_nomacro1(void)
2590 int t, c, is_long, len;
2591 TokenSym *ts;
2592 uint8_t *p, *p1;
2593 unsigned int h;
2595 p = file->buf_ptr;
2596 redo_no_start:
2597 c = *p;
2598 switch(c) {
2599 case ' ':
2600 case '\t':
2601 tok = c;
2602 p++;
2603 maybe_space:
2604 if (parse_flags & PARSE_FLAG_SPACES)
2605 goto keep_tok_flags;
2606 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2607 ++p;
2608 goto redo_no_start;
2609 case '\f':
2610 case '\v':
2611 case '\r':
2612 p++;
2613 goto redo_no_start;
2614 case '\\':
2615 /* first look if it is in fact an end of buffer */
2616 c = handle_stray1(p);
2617 p = file->buf_ptr;
2618 if (c == '\\')
2619 goto parse_simple;
2620 if (c != CH_EOF)
2621 goto redo_no_start;
2623 TCCState *s1 = tcc_state;
2624 if ((parse_flags & PARSE_FLAG_LINEFEED)
2625 && !(tok_flags & TOK_FLAG_EOF)) {
2626 tok_flags |= TOK_FLAG_EOF;
2627 tok = TOK_LINEFEED;
2628 goto keep_tok_flags;
2629 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2630 tok = TOK_EOF;
2631 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2632 tcc_error("missing #endif");
2633 } else if (s1->include_stack_ptr == s1->include_stack) {
2634 /* no include left : end of file. */
2635 tok = TOK_EOF;
2636 } else {
2637 tok_flags &= ~TOK_FLAG_EOF;
2638 /* pop include file */
2640 /* test if previous '#endif' was after a #ifdef at
2641 start of file */
2642 if (tok_flags & TOK_FLAG_ENDIF) {
2643 #ifdef INC_DEBUG
2644 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2645 #endif
2646 search_cached_include(s1, file->filename, 1)
2647 ->ifndef_macro = file->ifndef_macro_saved;
2648 tok_flags &= ~TOK_FLAG_ENDIF;
2651 /* add end of include file debug info */
2652 tcc_debug_eincl(tcc_state);
2653 /* pop include stack */
2654 tcc_close();
2655 s1->include_stack_ptr--;
2656 p = file->buf_ptr;
2657 if (p == file->buffer)
2658 tok_flags = TOK_FLAG_BOF|TOK_FLAG_BOL;
2659 goto redo_no_start;
2662 break;
2664 case '\n':
2665 file->line_num++;
2666 tok_flags |= TOK_FLAG_BOL;
2667 p++;
2668 maybe_newline:
2669 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2670 goto redo_no_start;
2671 tok = TOK_LINEFEED;
2672 goto keep_tok_flags;
2674 case '#':
2675 /* XXX: simplify */
2676 PEEKC(c, p);
2677 if ((tok_flags & TOK_FLAG_BOL) &&
2678 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2679 file->buf_ptr = p;
2680 preprocess(tok_flags & TOK_FLAG_BOF);
2681 p = file->buf_ptr;
2682 goto maybe_newline;
2683 } else {
2684 if (c == '#') {
2685 p++;
2686 tok = TOK_TWOSHARPS;
2687 } else {
2688 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2689 p = parse_line_comment(p - 1);
2690 goto redo_no_start;
2691 } else {
2692 tok = '#';
2696 break;
2698 /* dollar is allowed to start identifiers when not parsing asm */
2699 case '$':
2700 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2701 || (parse_flags & PARSE_FLAG_ASM_FILE))
2702 goto parse_simple;
2704 case 'a': case 'b': case 'c': case 'd':
2705 case 'e': case 'f': case 'g': case 'h':
2706 case 'i': case 'j': case 'k': case 'l':
2707 case 'm': case 'n': case 'o': case 'p':
2708 case 'q': case 'r': case 's': case 't':
2709 case 'u': case 'v': case 'w': case 'x':
2710 case 'y': case 'z':
2711 case 'A': case 'B': case 'C': case 'D':
2712 case 'E': case 'F': case 'G': case 'H':
2713 case 'I': case 'J': case 'K':
2714 case 'M': case 'N': case 'O': case 'P':
2715 case 'Q': case 'R': case 'S': case 'T':
2716 case 'U': case 'V': case 'W': case 'X':
2717 case 'Y': case 'Z':
2718 case '_':
2719 parse_ident_fast:
2720 p1 = p;
2721 h = TOK_HASH_INIT;
2722 h = TOK_HASH_FUNC(h, c);
2723 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2724 h = TOK_HASH_FUNC(h, c);
2725 len = p - p1;
2726 if (c != '\\') {
2727 TokenSym **pts;
2729 /* fast case : no stray found, so we have the full token
2730 and we have already hashed it */
2731 h &= (TOK_HASH_SIZE - 1);
2732 pts = &hash_ident[h];
2733 for(;;) {
2734 ts = *pts;
2735 if (!ts)
2736 break;
2737 if (ts->len == len && !memcmp(ts->str, p1, len))
2738 goto token_found;
2739 pts = &(ts->hash_next);
2741 ts = tok_alloc_new(pts, (char *) p1, len);
2742 token_found: ;
2743 } else {
2744 /* slower case */
2745 cstr_reset(&tokcstr);
2746 cstr_cat(&tokcstr, (char *) p1, len);
2747 p--;
2748 PEEKC(c, p);
2749 parse_ident_slow:
2750 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2752 cstr_ccat(&tokcstr, c);
2753 PEEKC(c, p);
2755 ts = tok_alloc(tokcstr.data, tokcstr.size);
2757 tok = ts->tok;
2758 break;
2759 case 'L':
2760 t = p[1];
2761 if (t != '\\' && t != '\'' && t != '\"') {
2762 /* fast case */
2763 goto parse_ident_fast;
2764 } else {
2765 PEEKC(c, p);
2766 if (c == '\'' || c == '\"') {
2767 is_long = 1;
2768 goto str_const;
2769 } else {
2770 cstr_reset(&tokcstr);
2771 cstr_ccat(&tokcstr, 'L');
2772 goto parse_ident_slow;
2775 break;
2777 case '0': case '1': case '2': case '3':
2778 case '4': case '5': case '6': case '7':
2779 case '8': case '9':
2780 t = c;
2781 PEEKC(c, p);
2782 /* after the first digit, accept digits, alpha, '.' or sign if
2783 prefixed by 'eEpP' */
2784 parse_num:
2785 cstr_reset(&tokcstr);
2786 for(;;) {
2787 cstr_ccat(&tokcstr, t);
2788 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2789 || c == '.'
2790 || ((c == '+' || c == '-')
2791 && (((t == 'e' || t == 'E')
2792 && !(parse_flags & PARSE_FLAG_ASM_FILE
2793 /* 0xe+1 is 3 tokens in asm */
2794 && ((char*)tokcstr.data)[0] == '0'
2795 && toup(((char*)tokcstr.data)[1]) == 'X'))
2796 || t == 'p' || t == 'P'))))
2797 break;
2798 t = c;
2799 PEEKC(c, p);
2801 /* We add a trailing '\0' to ease parsing */
2802 cstr_ccat(&tokcstr, '\0');
2803 tokc.str.size = tokcstr.size;
2804 tokc.str.data = tokcstr.data;
2805 tok = TOK_PPNUM;
2806 break;
2808 case '.':
2809 /* special dot handling because it can also start a number */
2810 PEEKC(c, p);
2811 if (isnum(c)) {
2812 t = '.';
2813 goto parse_num;
2814 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2815 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2816 *--p = c = '.';
2817 goto parse_ident_fast;
2818 } else if (c == '.') {
2819 PEEKC(c, p);
2820 if (c == '.') {
2821 p++;
2822 tok = TOK_DOTS;
2823 } else {
2824 *--p = '.'; /* may underflow into file->unget[] */
2825 tok = '.';
2827 } else {
2828 tok = '.';
2830 break;
2831 case '\'':
2832 case '\"':
2833 is_long = 0;
2834 str_const:
2835 cstr_reset(&tokcstr);
2836 if (is_long)
2837 cstr_ccat(&tokcstr, 'L');
2838 cstr_ccat(&tokcstr, c);
2839 p = parse_pp_string(p, c, &tokcstr);
2840 cstr_ccat(&tokcstr, c);
2841 cstr_ccat(&tokcstr, '\0');
2842 tokc.str.size = tokcstr.size;
2843 tokc.str.data = tokcstr.data;
2844 tok = TOK_PPSTR;
2845 break;
2847 case '<':
2848 PEEKC(c, p);
2849 if (c == '=') {
2850 p++;
2851 tok = TOK_LE;
2852 } else if (c == '<') {
2853 PEEKC(c, p);
2854 if (c == '=') {
2855 p++;
2856 tok = TOK_A_SHL;
2857 } else {
2858 tok = TOK_SHL;
2860 } else {
2861 tok = TOK_LT;
2863 break;
2864 case '>':
2865 PEEKC(c, p);
2866 if (c == '=') {
2867 p++;
2868 tok = TOK_GE;
2869 } else if (c == '>') {
2870 PEEKC(c, p);
2871 if (c == '=') {
2872 p++;
2873 tok = TOK_A_SAR;
2874 } else {
2875 tok = TOK_SAR;
2877 } else {
2878 tok = TOK_GT;
2880 break;
2882 case '&':
2883 PEEKC(c, p);
2884 if (c == '&') {
2885 p++;
2886 tok = TOK_LAND;
2887 } else if (c == '=') {
2888 p++;
2889 tok = TOK_A_AND;
2890 } else {
2891 tok = '&';
2893 break;
2895 case '|':
2896 PEEKC(c, p);
2897 if (c == '|') {
2898 p++;
2899 tok = TOK_LOR;
2900 } else if (c == '=') {
2901 p++;
2902 tok = TOK_A_OR;
2903 } else {
2904 tok = '|';
2906 break;
2908 case '+':
2909 PEEKC(c, p);
2910 if (c == '+') {
2911 p++;
2912 tok = TOK_INC;
2913 } else if (c == '=') {
2914 p++;
2915 tok = TOK_A_ADD;
2916 } else {
2917 tok = '+';
2919 break;
2921 case '-':
2922 PEEKC(c, p);
2923 if (c == '-') {
2924 p++;
2925 tok = TOK_DEC;
2926 } else if (c == '=') {
2927 p++;
2928 tok = TOK_A_SUB;
2929 } else if (c == '>') {
2930 p++;
2931 tok = TOK_ARROW;
2932 } else {
2933 tok = '-';
2935 break;
2937 PARSE2('!', '!', '=', TOK_NE)
2938 PARSE2('=', '=', '=', TOK_EQ)
2939 PARSE2('*', '*', '=', TOK_A_MUL)
2940 PARSE2('%', '%', '=', TOK_A_MOD)
2941 PARSE2('^', '^', '=', TOK_A_XOR)
2943 /* comments or operator */
2944 case '/':
2945 PEEKC(c, p);
2946 if (c == '*') {
2947 p = parse_comment(p);
2948 /* comments replaced by a blank */
2949 tok = ' ';
2950 goto maybe_space;
2951 } else if (c == '/') {
2952 p = parse_line_comment(p);
2953 tok = ' ';
2954 goto maybe_space;
2955 } else if (c == '=') {
2956 p++;
2957 tok = TOK_A_DIV;
2958 } else {
2959 tok = '/';
2961 break;
2963 /* simple tokens */
2964 case '(':
2965 case ')':
2966 case '[':
2967 case ']':
2968 case '{':
2969 case '}':
2970 case ',':
2971 case ';':
2972 case ':':
2973 case '?':
2974 case '~':
2975 case '@': /* only used in assembler */
2976 parse_simple:
2977 tok = c;
2978 p++;
2979 break;
2980 default:
2981 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2982 goto parse_ident_fast;
2983 if (parse_flags & PARSE_FLAG_ASM_FILE)
2984 goto parse_simple;
2985 tcc_error("unrecognized character \\x%02x", c);
2986 break;
2988 tok_flags = 0;
2989 keep_tok_flags:
2990 file->buf_ptr = p;
2991 #if defined(PARSE_DEBUG)
2992 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
2993 #endif
2996 static void macro_subst(
2997 TokenString *tok_str,
2998 Sym **nested_list,
2999 const int *macro_str
3002 /* substitute arguments in replacement lists in macro_str by the values in
3003 args (field d) and return allocated string */
3004 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
3006 int t, t0, t1, spc;
3007 const int *st;
3008 Sym *s;
3009 CValue cval;
3010 TokenString str;
3011 CString cstr;
3013 tok_str_new(&str);
3014 t0 = t1 = 0;
3015 while(1) {
3016 TOK_GET(&t, &macro_str, &cval);
3017 if (!t)
3018 break;
3019 if (t == '#') {
3020 /* stringize */
3021 TOK_GET(&t, &macro_str, &cval);
3022 if (!t)
3023 goto bad_stringy;
3024 s = sym_find2(args, t);
3025 if (s) {
3026 cstr_new(&cstr);
3027 cstr_ccat(&cstr, '\"');
3028 st = s->d;
3029 spc = 0;
3030 while (*st >= 0) {
3031 TOK_GET(&t, &st, &cval);
3032 if (t != TOK_PLCHLDR
3033 && t != TOK_NOSUBST
3034 && 0 == check_space(t, &spc)) {
3035 const char *s = get_tok_str(t, &cval);
3036 while (*s) {
3037 if (t == TOK_PPSTR && *s != '\'')
3038 add_char(&cstr, *s);
3039 else
3040 cstr_ccat(&cstr, *s);
3041 ++s;
3045 cstr.size -= spc;
3046 cstr_ccat(&cstr, '\"');
3047 cstr_ccat(&cstr, '\0');
3048 #ifdef PP_DEBUG
3049 printf("\nstringize: <%s>\n", (char *)cstr.data);
3050 #endif
3051 /* add string */
3052 cval.str.size = cstr.size;
3053 cval.str.data = cstr.data;
3054 tok_str_add2(&str, TOK_PPSTR, &cval);
3055 cstr_free(&cstr);
3056 } else {
3057 bad_stringy:
3058 expect("macro parameter after '#'");
3060 } else if (t >= TOK_IDENT) {
3061 s = sym_find2(args, t);
3062 if (s) {
3063 int l0 = str.len;
3064 st = s->d;
3065 /* if '##' is present before or after, no arg substitution */
3066 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
3067 /* special case for var arg macros : ## eats the ','
3068 if empty VA_ARGS variable. */
3069 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
3070 if (*st <= 0) {
3071 /* suppress ',' '##' */
3072 str.len -= 2;
3073 } else {
3074 /* suppress '##' and add variable */
3075 str.len--;
3076 goto add_var;
3079 } else {
3080 add_var:
3081 if (!s->next) {
3082 /* Expand arguments tokens and store them. In most
3083 cases we could also re-expand each argument if
3084 used multiple times, but not if the argument
3085 contains the __COUNTER__ macro. */
3086 TokenString str2;
3087 sym_push2(&s->next, s->v, s->type.t, 0);
3088 tok_str_new(&str2);
3089 macro_subst(&str2, nested_list, st);
3090 tok_str_add(&str2, 0);
3091 s->next->d = str2.str;
3093 st = s->next->d;
3095 for(;;) {
3096 int t2;
3097 TOK_GET(&t2, &st, &cval);
3098 if (t2 <= 0)
3099 break;
3100 tok_str_add2(&str, t2, &cval);
3102 if (str.len == l0) /* expanded to empty string */
3103 tok_str_add(&str, TOK_PLCHLDR);
3104 } else {
3105 tok_str_add(&str, t);
3107 } else {
3108 tok_str_add2(&str, t, &cval);
3110 t0 = t1, t1 = t;
3112 tok_str_add(&str, 0);
3113 return str.str;
3116 static char const ab_month_name[12][4] =
3118 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3119 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3122 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3124 CString cstr;
3125 int n, ret = 1;
3127 cstr_new(&cstr);
3128 if (t1 != TOK_PLCHLDR)
3129 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3130 n = cstr.size;
3131 if (t2 != TOK_PLCHLDR)
3132 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3133 cstr_ccat(&cstr, '\0');
3135 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3136 memcpy(file->buffer, cstr.data, cstr.size);
3137 tok_flags = 0;
3138 for (;;) {
3139 next_nomacro1();
3140 if (0 == *file->buf_ptr)
3141 break;
3142 if (is_space(tok))
3143 continue;
3144 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3145 " preprocessing token", n, (char *)cstr.data, (char*)cstr.data + n);
3146 ret = 0;
3147 break;
3149 tcc_close();
3150 //printf("paste <%s>\n", (char*)cstr.data);
3151 cstr_free(&cstr);
3152 return ret;
3155 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3156 return the resulting string (which must be freed). */
3157 static inline int *macro_twosharps(const int *ptr0)
3159 int t;
3160 CValue cval;
3161 TokenString macro_str1;
3162 int start_of_nosubsts = -1;
3163 const int *ptr;
3165 /* we search the first '##' */
3166 for (ptr = ptr0;;) {
3167 TOK_GET(&t, &ptr, &cval);
3168 if (t == TOK_PPJOIN)
3169 break;
3170 if (t == 0)
3171 return NULL;
3174 tok_str_new(&macro_str1);
3176 //tok_print(" $$$", ptr0);
3177 for (ptr = ptr0;;) {
3178 TOK_GET(&t, &ptr, &cval);
3179 if (t == 0)
3180 break;
3181 if (t == TOK_PPJOIN)
3182 continue;
3183 while (*ptr == TOK_PPJOIN) {
3184 int t1; CValue cv1;
3185 /* given 'a##b', remove nosubsts preceding 'a' */
3186 if (start_of_nosubsts >= 0)
3187 macro_str1.len = start_of_nosubsts;
3188 /* given 'a##b', remove nosubsts preceding 'b' */
3189 while ((t1 = *++ptr) == TOK_NOSUBST)
3191 if (t1 && t1 != TOK_PPJOIN) {
3192 TOK_GET(&t1, &ptr, &cv1);
3193 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3194 if (paste_tokens(t, &cval, t1, &cv1)) {
3195 t = tok, cval = tokc;
3196 } else {
3197 tok_str_add2(&macro_str1, t, &cval);
3198 t = t1, cval = cv1;
3203 if (t == TOK_NOSUBST) {
3204 if (start_of_nosubsts < 0)
3205 start_of_nosubsts = macro_str1.len;
3206 } else {
3207 start_of_nosubsts = -1;
3209 tok_str_add2(&macro_str1, t, &cval);
3211 tok_str_add(&macro_str1, 0);
3212 //tok_print(" ###", macro_str1.str);
3213 return macro_str1.str;
3216 /* peek or read [ws_str == NULL] next token from function macro call,
3217 walking up macro levels up to the file if necessary */
3218 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3220 int t;
3221 const int *p;
3222 Sym *sa;
3224 for (;;) {
3225 if (macro_ptr) {
3226 p = macro_ptr, t = *p;
3227 if (ws_str) {
3228 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3229 tok_str_add(ws_str, t), t = *++p;
3231 if (t == 0) {
3232 end_macro();
3233 /* also, end of scope for nested defined symbol */
3234 sa = *nested_list;
3235 while (sa && sa->v == 0)
3236 sa = sa->prev;
3237 if (sa)
3238 sa->v = 0;
3239 continue;
3241 } else {
3242 ch = handle_eob();
3243 if (ws_str) {
3244 while (is_space(ch) || ch == '\n' || ch == '/') {
3245 if (ch == '/') {
3246 int c;
3247 uint8_t *p = file->buf_ptr;
3248 PEEKC(c, p);
3249 if (c == '*') {
3250 p = parse_comment(p);
3251 file->buf_ptr = p - 1;
3252 } else if (c == '/') {
3253 p = parse_line_comment(p);
3254 file->buf_ptr = p - 1;
3255 } else
3256 break;
3257 ch = ' ';
3259 if (ch == '\n')
3260 file->line_num++;
3261 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3262 tok_str_add(ws_str, ch);
3263 cinp();
3266 t = ch;
3269 if (ws_str)
3270 return t;
3271 next_nomacro();
3272 return tok;
3276 /* do macro substitution of current token with macro 's' and add
3277 result to (tok_str,tok_len). 'nested_list' is the list of all
3278 macros we got inside to avoid recursing. Return non zero if no
3279 substitution needs to be done */
3280 static int macro_subst_tok(
3281 TokenString *tok_str,
3282 Sym **nested_list,
3283 Sym *s)
3285 Sym *args, *sa, *sa1;
3286 int parlevel, t, t1, spc;
3287 TokenString str;
3288 char *cstrval;
3289 CValue cval;
3290 CString cstr;
3291 char buf[32];
3293 /* if symbol is a macro, prepare substitution */
3294 /* special macros */
3295 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3296 t = tok == TOK___LINE__ ? file->line_num : pp_counter++;
3297 snprintf(buf, sizeof(buf), "%d", t);
3298 cstrval = buf;
3299 t1 = TOK_PPNUM;
3300 goto add_cstr1;
3301 } else if (tok == TOK___FILE__) {
3302 cstrval = file->filename;
3303 goto add_cstr;
3304 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3305 time_t ti;
3306 struct tm *tm;
3308 time(&ti);
3309 tm = localtime(&ti);
3310 if (tok == TOK___DATE__) {
3311 snprintf(buf, sizeof(buf), "%s %2d %d",
3312 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3313 } else {
3314 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3315 tm->tm_hour, tm->tm_min, tm->tm_sec);
3317 cstrval = buf;
3318 add_cstr:
3319 t1 = TOK_STR;
3320 add_cstr1:
3321 cstr_new(&cstr);
3322 cstr_cat(&cstr, cstrval, 0);
3323 cval.str.size = cstr.size;
3324 cval.str.data = cstr.data;
3325 tok_str_add2(tok_str, t1, &cval);
3326 cstr_free(&cstr);
3327 } else if (s->d) {
3328 int saved_parse_flags = parse_flags;
3329 int *joined_str = NULL;
3330 int *mstr = s->d;
3332 if (s->type.t == MACRO_FUNC) {
3333 /* whitespace between macro name and argument list */
3334 TokenString ws_str;
3335 tok_str_new(&ws_str);
3337 spc = 0;
3338 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3339 | PARSE_FLAG_ACCEPT_STRAYS;
3341 /* get next token from argument stream */
3342 t = next_argstream(nested_list, &ws_str);
3343 if (t != '(') {
3344 /* not a macro substitution after all, restore the
3345 * macro token plus all whitespace we've read.
3346 * whitespace is intentionally not merged to preserve
3347 * newlines. */
3348 parse_flags = saved_parse_flags;
3349 tok_str_add(tok_str, tok);
3350 if (parse_flags & PARSE_FLAG_SPACES) {
3351 int i;
3352 for (i = 0; i < ws_str.len; i++)
3353 tok_str_add(tok_str, ws_str.str[i]);
3355 tok_str_free_str(ws_str.str);
3356 return 0;
3357 } else {
3358 tok_str_free_str(ws_str.str);
3360 do {
3361 next_nomacro(); /* eat '(' */
3362 } while (tok == TOK_PLCHLDR || is_space(tok));
3364 /* argument macro */
3365 args = NULL;
3366 sa = s->next;
3367 /* NOTE: empty args are allowed, except if no args */
3368 for(;;) {
3369 do {
3370 next_argstream(nested_list, NULL);
3371 } while (is_space(tok) || TOK_LINEFEED == tok);
3372 empty_arg:
3373 /* handle '()' case */
3374 if (!args && !sa && tok == ')')
3375 break;
3376 if (!sa)
3377 tcc_error("macro '%s' used with too many args",
3378 get_tok_str(s->v, 0));
3379 tok_str_new(&str);
3380 parlevel = spc = 0;
3381 /* NOTE: non zero sa->t indicates VA_ARGS */
3382 while ((parlevel > 0 ||
3383 (tok != ')' &&
3384 (tok != ',' || sa->type.t)))) {
3385 if (tok == TOK_EOF || tok == 0)
3386 break;
3387 if (tok == '(')
3388 parlevel++;
3389 else if (tok == ')')
3390 parlevel--;
3391 if (tok == TOK_LINEFEED)
3392 tok = ' ';
3393 if (!check_space(tok, &spc))
3394 tok_str_add2(&str, tok, &tokc);
3395 next_argstream(nested_list, NULL);
3397 if (parlevel)
3398 expect(")");
3399 str.len -= spc;
3400 tok_str_add(&str, -1);
3401 tok_str_add(&str, 0);
3402 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3403 sa1->d = str.str;
3404 sa = sa->next;
3405 if (tok == ')') {
3406 /* special case for gcc var args: add an empty
3407 var arg argument if it is omitted */
3408 if (sa && sa->type.t && gnu_ext)
3409 goto empty_arg;
3410 break;
3412 if (tok != ',')
3413 expect(",");
3415 if (sa) {
3416 tcc_error("macro '%s' used with too few args",
3417 get_tok_str(s->v, 0));
3420 /* now subst each arg */
3421 mstr = macro_arg_subst(nested_list, mstr, args);
3422 /* free memory */
3423 sa = args;
3424 while (sa) {
3425 sa1 = sa->prev;
3426 tok_str_free_str(sa->d);
3427 if (sa->next) {
3428 tok_str_free_str(sa->next->d);
3429 sym_free(sa->next);
3431 sym_free(sa);
3432 sa = sa1;
3434 parse_flags = saved_parse_flags;
3437 sym_push2(nested_list, s->v, 0, 0);
3438 parse_flags = saved_parse_flags;
3439 joined_str = macro_twosharps(mstr);
3440 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3442 /* pop nested defined symbol */
3443 sa1 = *nested_list;
3444 *nested_list = sa1->prev;
3445 sym_free(sa1);
3446 if (joined_str)
3447 tok_str_free_str(joined_str);
3448 if (mstr != s->d)
3449 tok_str_free_str(mstr);
3451 return 0;
3454 /* do macro substitution of macro_str and add result to
3455 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3456 inside to avoid recursing. */
3457 static void macro_subst(
3458 TokenString *tok_str,
3459 Sym **nested_list,
3460 const int *macro_str
3463 Sym *s;
3464 int t, spc, nosubst;
3465 CValue cval;
3467 spc = nosubst = 0;
3469 while (1) {
3470 TOK_GET(&t, &macro_str, &cval);
3471 if (t <= 0)
3472 break;
3474 if (t >= TOK_IDENT && 0 == nosubst) {
3475 s = define_find(t);
3476 if (s == NULL)
3477 goto no_subst;
3479 /* if nested substitution, do nothing */
3480 if (sym_find2(*nested_list, t)) {
3481 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3482 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3483 goto no_subst;
3487 TokenString *str = tok_str_alloc();
3488 str->str = (int*)macro_str;
3489 begin_macro(str, 2);
3491 tok = t;
3492 macro_subst_tok(tok_str, nested_list, s);
3494 if (macro_stack != str) {
3495 /* already finished by reading function macro arguments */
3496 break;
3499 macro_str = macro_ptr;
3500 end_macro ();
3502 if (tok_str->len)
3503 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3504 } else {
3505 no_subst:
3506 if (!check_space(t, &spc))
3507 tok_str_add2(tok_str, t, &cval);
3509 if (nosubst) {
3510 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3511 continue;
3512 nosubst = 0;
3514 if (t == TOK_NOSUBST)
3515 nosubst = 1;
3517 /* GCC supports 'defined' as result of a macro substitution */
3518 if (t == TOK_DEFINED && pp_expr)
3519 nosubst = 2;
3523 /* return next token without macro substitution. Can read input from
3524 macro_ptr buffer */
3525 static void next_nomacro(void)
3527 int t;
3528 if (macro_ptr) {
3529 redo:
3530 t = *macro_ptr;
3531 if (TOK_HAS_VALUE(t)) {
3532 tok_get(&tok, &macro_ptr, &tokc);
3533 if (t == TOK_LINENUM) {
3534 file->line_num = tokc.i;
3535 goto redo;
3537 } else {
3538 macro_ptr++;
3539 if (t < TOK_IDENT) {
3540 if (!(parse_flags & PARSE_FLAG_SPACES)
3541 && (isidnum_table[t - CH_EOF] & IS_SPC))
3542 goto redo;
3544 tok = t;
3546 } else {
3547 next_nomacro1();
3551 /* return next token with macro substitution */
3552 ST_FUNC void next(void)
3554 int t;
3555 redo:
3556 next_nomacro();
3557 t = tok;
3558 if (macro_ptr) {
3559 if (!TOK_HAS_VALUE(t)) {
3560 if (t == TOK_NOSUBST || t == TOK_PLCHLDR) {
3561 /* discard preprocessor markers */
3562 goto redo;
3563 } else if (t == 0) {
3564 /* end of macro or unget token string */
3565 end_macro();
3566 goto redo;
3567 } else if (t == '\\') {
3568 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3569 tcc_error("stray '\\' in program");
3571 return;
3573 } else if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3574 /* if reading from file, try to substitute macros */
3575 Sym *s = define_find(t);
3576 if (s) {
3577 Sym *nested_list = NULL;
3578 tokstr_buf.len = 0;
3579 macro_subst_tok(&tokstr_buf, &nested_list, s);
3580 tok_str_add(&tokstr_buf, 0);
3581 begin_macro(&tokstr_buf, 0);
3582 goto redo;
3584 return;
3586 /* convert preprocessor tokens into C tokens */
3587 if (t == TOK_PPNUM) {
3588 if (parse_flags & PARSE_FLAG_TOK_NUM)
3589 parse_number((char *)tokc.str.data);
3590 } else if (t == TOK_PPSTR) {
3591 if (parse_flags & PARSE_FLAG_TOK_STR)
3592 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3596 /* push back current token and set current token to 'last_tok'. Only
3597 identifier case handled for labels. */
3598 ST_INLN void unget_tok(int last_tok)
3601 TokenString *str = tok_str_alloc();
3602 tok_str_add2(str, tok, &tokc);
3603 tok_str_add(str, 0);
3604 begin_macro(str, 1);
3605 tok = last_tok;
3608 static void tcc_predefs(CString *cstr)
3610 cstr_cat(cstr,
3611 #if defined TCC_TARGET_X86_64
3612 #ifndef TCC_TARGET_PE
3613 /* GCC compatible definition of va_list. This should be in sync
3614 with the declaration in our lib/libtcc1.c */
3615 "typedef struct{\n"
3616 "unsigned gp_offset,fp_offset;\n"
3617 "union{\n"
3618 "unsigned overflow_offset;\n"
3619 "char*overflow_arg_area;\n"
3620 "};\n"
3621 "char*reg_save_area;\n"
3622 "}__builtin_va_list[1];\n"
3623 "void*__va_arg(__builtin_va_list ap,int arg_type,int size,int align);\n"
3624 "#define __builtin_va_start(ap,last) (*(ap)=*(__builtin_va_list)((char*)__builtin_frame_address(0)-24))\n"
3625 "#define __builtin_va_arg(ap,t) (*(t*)(__va_arg(ap,__builtin_va_arg_types(t),sizeof(t),__alignof__(t))))\n"
3626 "#define __builtin_va_copy(dest,src) (*(dest)=*(src))\n"
3627 #else /* TCC_TARGET_PE */
3628 "typedef char*__builtin_va_list;\n"
3629 "#define __builtin_va_arg(ap,t) ((sizeof(t)>8||(sizeof(t)&(sizeof(t)-1)))?**(t**)((ap+=8)-8):*(t*)((ap+=8)-8))\n"
3630 "#define __builtin_va_copy(dest,src) (dest)=(src)\n"
3631 #endif
3632 #elif defined TCC_TARGET_ARM
3633 "typedef char*__builtin_va_list;\n"
3634 "#define _tcc_alignof(type) ((int)&((struct{char c;type x;}*)0)->x)\n"
3635 "#define _tcc_align(addr,type) (((unsigned)addr+_tcc_alignof(type)-1)&~(_tcc_alignof(type)-1))\n"
3636 "#define __builtin_va_start(ap,last) (ap=((char*)&(last))+((sizeof(last)+3)&~3))\n"
3637 "#define __builtin_va_arg(ap,type) (ap=(void*)((_tcc_align(ap,type)+sizeof(type)+3)&~3),*(type*)(ap-((sizeof(type)+3)&~3)))\n"
3638 "#define __builtin_va_copy(dest,src) (dest)=(src)\n"
3639 #elif defined TCC_TARGET_ARM64
3640 "typedef struct{\n"
3641 "void*__stack,*__gr_top,*__vr_top;\n"
3642 "int __gr_offs,__vr_offs;\n"
3643 "}__builtin_va_list;\n"
3644 "#define __builtin_va_copy(dest,src) (dest)=(src)\n"
3645 #elif defined TCC_TARGET_RISCV64
3646 "typedef char*__builtin_va_list;\n"
3647 "#define __va_reg_size (__riscv_xlen>>3)\n"
3648 "#define _tcc_align(addr,type) (((unsigned long)addr+__alignof__(type)-1)&-(__alignof__(type)))\n"
3649 "#define __builtin_va_arg(ap,type) (*(sizeof(type)>(2*__va_reg_size)?*(type**)((ap+=__va_reg_size)-__va_reg_size):(ap=(va_list)(_tcc_align(ap,type)+(sizeof(type)+__va_reg_size-1)&-__va_reg_size),(type*)(ap-((sizeof(type)+__va_reg_size-1)&-__va_reg_size)))))\n"
3650 "#define __builtin_va_copy(dest,src) (dest)=(src)\n"
3651 #else /* TCC_TARGET_I386 */
3652 "typedef char*__builtin_va_list;\n"
3653 "#define __builtin_va_start(ap,last) (ap=((char*)&(last))+((sizeof(last)+3)&~3))\n"
3654 "#define __builtin_va_arg(ap,t) (*(t*)((ap+=(sizeof(t)+3)&~3)-((sizeof(t)+3)&~3)))\n"
3655 "#define __builtin_va_copy(dest,src) (dest)=(src)\n"
3656 #endif
3657 "#define __builtin_va_end(ap) (void)(ap)\n"
3658 , -1);
3661 ST_FUNC void preprocess_start(TCCState *s1, int is_asm)
3663 CString cstr;
3665 tccpp_new(s1);
3667 s1->include_stack_ptr = s1->include_stack;
3668 s1->ifdef_stack_ptr = s1->ifdef_stack;
3669 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3670 pp_expr = 0;
3671 pp_counter = 0;
3672 pp_debug_tok = pp_debug_symv = 0;
3673 pp_once++;
3674 s1->pack_stack[0] = 0;
3675 s1->pack_stack_ptr = s1->pack_stack;
3677 set_idnum('$', s1->dollars_in_identifiers ? IS_ID : 0);
3678 set_idnum('.', is_asm ? IS_ID : 0);
3680 cstr_new(&cstr);
3681 if (s1->cmdline_defs.size)
3682 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3683 cstr_printf(&cstr, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3684 if (is_asm)
3685 cstr_printf(&cstr, "#define __ASSEMBLER__ 1\n");
3686 if (s1->output_type == TCC_OUTPUT_MEMORY)
3687 cstr_printf(&cstr, "#define __TCC_RUN__ 1\n");
3688 if (!is_asm && s1->output_type != TCC_OUTPUT_PREPROCESS)
3689 tcc_predefs(&cstr);
3690 if (s1->cmdline_incl.size)
3691 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3692 //printf("%s\n", (char*)cstr.data);
3693 *s1->include_stack_ptr++ = file;
3694 tcc_open_bf(s1, "<command line>", cstr.size);
3695 memcpy(file->buffer, cstr.data, cstr.size);
3696 cstr_free(&cstr);
3698 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3699 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3702 /* cleanup from error/setjmp */
3703 ST_FUNC void preprocess_end(TCCState *s1)
3705 while (macro_stack)
3706 end_macro();
3707 macro_ptr = NULL;
3708 while (file)
3709 tcc_close();
3710 tccpp_delete(s1);
3713 ST_FUNC void tccpp_new(TCCState *s)
3715 int i, c;
3716 const char *p, *r;
3718 /* init isid table */
3719 for(i = CH_EOF; i<128; i++)
3720 set_idnum(i,
3721 is_space(i) ? IS_SPC
3722 : isid(i) ? IS_ID
3723 : isnum(i) ? IS_NUM
3724 : 0);
3726 for(i = 128; i<256; i++)
3727 set_idnum(i, IS_ID);
3729 /* init allocators */
3730 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3731 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3733 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3734 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3736 cstr_new(&cstr_buf);
3737 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3738 tok_str_new(&tokstr_buf);
3739 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3741 tok_ident = TOK_IDENT;
3742 p = tcc_keywords;
3743 while (*p) {
3744 r = p;
3745 for(;;) {
3746 c = *r++;
3747 if (c == '\0')
3748 break;
3750 tok_alloc(p, r - p - 1);
3751 p = r;
3754 /* we add dummy defines for some special macros to speed up tests
3755 and to have working defined() */
3756 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3757 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3758 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3759 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3760 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3763 ST_FUNC void tccpp_delete(TCCState *s)
3765 int i, n;
3767 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3769 /* free tokens */
3770 n = tok_ident - TOK_IDENT;
3771 if (n > total_idents)
3772 total_idents = n;
3773 for(i = 0; i < n; i++)
3774 tal_free(toksym_alloc, table_ident[i]);
3775 tcc_free(table_ident);
3776 table_ident = NULL;
3778 /* free static buffers */
3779 cstr_free(&tokcstr);
3780 cstr_free(&cstr_buf);
3781 cstr_free(&macro_equal_buf);
3782 tok_str_free_str(tokstr_buf.str);
3784 /* free allocators */
3785 tal_delete(toksym_alloc);
3786 toksym_alloc = NULL;
3787 tal_delete(tokstr_alloc);
3788 tokstr_alloc = NULL;
3791 /* ------------------------------------------------------------------------- */
3792 /* tcc -E [-P[1]] [-dD} support */
3794 static void tok_print(const char *msg, const int *str)
3796 FILE *fp;
3797 int t, s = 0;
3798 CValue cval;
3800 fp = tcc_state->ppfp;
3801 fprintf(fp, "%s", msg);
3802 while (str) {
3803 TOK_GET(&t, &str, &cval);
3804 if (!t)
3805 break;
3806 fprintf(fp, " %s" + s, get_tok_str(t, &cval)), s = 1;
3808 fprintf(fp, "\n");
3811 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3813 int d = f->line_num - f->line_ref;
3815 if (s1->dflag & 4)
3816 return;
3818 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3820 } else if (level == 0 && f->line_ref && d < 8) {
3821 while (d > 0)
3822 fputs("\n", s1->ppfp), --d;
3823 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3824 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3825 } else {
3826 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3827 level > 0 ? " 1" : level < 0 ? " 2" : "");
3829 f->line_ref = f->line_num;
3832 static void define_print(TCCState *s1, int v)
3834 FILE *fp;
3835 Sym *s;
3837 s = define_find(v);
3838 if (NULL == s || NULL == s->d)
3839 return;
3841 fp = s1->ppfp;
3842 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3843 if (s->type.t == MACRO_FUNC) {
3844 Sym *a = s->next;
3845 fprintf(fp,"(");
3846 if (a)
3847 for (;;) {
3848 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3849 if (!(a = a->next))
3850 break;
3851 fprintf(fp,",");
3853 fprintf(fp,")");
3855 tok_print("", s->d);
3858 static void pp_debug_defines(TCCState *s1)
3860 int v, t;
3861 const char *vs;
3862 FILE *fp;
3864 t = pp_debug_tok;
3865 if (t == 0)
3866 return;
3868 file->line_num--;
3869 pp_line(s1, file, 0);
3870 file->line_ref = ++file->line_num;
3872 fp = s1->ppfp;
3873 v = pp_debug_symv;
3874 vs = get_tok_str(v, NULL);
3875 if (t == TOK_DEFINE) {
3876 define_print(s1, v);
3877 } else if (t == TOK_UNDEF) {
3878 fprintf(fp, "#undef %s\n", vs);
3879 } else if (t == TOK_push_macro) {
3880 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3881 } else if (t == TOK_pop_macro) {
3882 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3884 pp_debug_tok = 0;
3887 static void pp_debug_builtins(TCCState *s1)
3889 int v;
3890 for (v = TOK_IDENT; v < tok_ident; ++v)
3891 define_print(s1, v);
3894 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3895 static int pp_need_space(int a, int b)
3897 return 'E' == a ? '+' == b || '-' == b
3898 : '+' == a ? TOK_INC == b || '+' == b
3899 : '-' == a ? TOK_DEC == b || '-' == b
3900 : a >= TOK_IDENT ? b >= TOK_IDENT
3901 : a == TOK_PPNUM ? b >= TOK_IDENT
3902 : 0;
3905 /* maybe hex like 0x1e */
3906 static int pp_check_he0xE(int t, const char *p)
3908 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3909 return 'E';
3910 return t;
3913 /* Preprocess the current file */
3914 ST_FUNC int tcc_preprocess(TCCState *s1)
3916 BufferedFile **iptr;
3917 int token_seen, spcs, level;
3918 const char *p;
3919 char white[400];
3921 parse_flags = PARSE_FLAG_PREPROCESS
3922 | (parse_flags & PARSE_FLAG_ASM_FILE)
3923 | PARSE_FLAG_LINEFEED
3924 | PARSE_FLAG_SPACES
3925 | PARSE_FLAG_ACCEPT_STRAYS
3927 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3928 capability to compile and run itself, provided all numbers are
3929 given as decimals. tcc -E -P10 will do. */
3930 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3931 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3933 #ifdef PP_BENCH
3934 /* for PP benchmarks */
3935 do next(); while (tok != TOK_EOF);
3936 return 0;
3937 #endif
3939 if (s1->dflag & 1) {
3940 pp_debug_builtins(s1);
3941 s1->dflag &= ~1;
3944 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
3945 if (file->prev)
3946 pp_line(s1, file->prev, level++);
3947 pp_line(s1, file, level);
3948 for (;;) {
3949 iptr = s1->include_stack_ptr;
3950 next();
3951 if (tok == TOK_EOF)
3952 break;
3954 level = s1->include_stack_ptr - iptr;
3955 if (level) {
3956 if (level > 0)
3957 pp_line(s1, *iptr, 0);
3958 pp_line(s1, file, level);
3960 if (s1->dflag & 7) {
3961 pp_debug_defines(s1);
3962 if (s1->dflag & 4)
3963 continue;
3966 if (is_space(tok)) {
3967 if (spcs < sizeof white - 1)
3968 white[spcs++] = tok;
3969 continue;
3970 } else if (tok == TOK_LINEFEED) {
3971 spcs = 0;
3972 if (token_seen == TOK_LINEFEED)
3973 continue;
3974 ++file->line_ref;
3975 } else if (token_seen == TOK_LINEFEED) {
3976 pp_line(s1, file, 0);
3977 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
3978 white[spcs++] = ' ';
3981 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
3982 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
3983 token_seen = pp_check_he0xE(tok, p);
3985 return 0;
3988 /* ------------------------------------------------------------------------- */