mutiples fix for _Generic
[tinycc.git] / tccpp.c
blob5209b39afdd36e307b90f298274d3b5578ecc522
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 ST_DATA int tok_flags;
27 ST_DATA int parse_flags;
29 ST_DATA struct BufferedFile *file;
30 ST_DATA int ch, tok;
31 ST_DATA CValue tokc;
32 ST_DATA const int *macro_ptr;
33 ST_DATA CString tokcstr; /* current parsed string, if any */
35 /* display benchmark infos */
36 ST_DATA int total_lines;
37 ST_DATA int total_bytes;
38 ST_DATA int tok_ident;
39 ST_DATA TokenSym **table_ident;
41 /* ------------------------------------------------------------------------- */
43 static TokenSym *hash_ident[TOK_HASH_SIZE];
44 static char token_buf[STRING_MAX_SIZE + 1];
45 static CString cstr_buf;
46 static CString macro_equal_buf;
47 static TokenString tokstr_buf;
48 static unsigned char isidnum_table[256 - CH_EOF];
49 static int pp_debug_tok, pp_debug_symv;
50 static int pp_once;
51 static int pp_expr;
52 static void tok_print(const char *msg, const int *str);
54 static struct TinyAlloc *toksym_alloc;
55 static struct TinyAlloc *tokstr_alloc;
56 static struct TinyAlloc *cstr_alloc;
58 static TokenString *macro_stack;
60 static const char tcc_keywords[] =
61 #define DEF(id, str) str "\0"
62 #include "tcctok.h"
63 #undef DEF
66 /* WARNING: the content of this string encodes token numbers */
67 static const unsigned char tok_two_chars[] =
68 /* outdated -- gr
69 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
70 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
71 */{
72 '<','=', TOK_LE,
73 '>','=', TOK_GE,
74 '!','=', TOK_NE,
75 '&','&', TOK_LAND,
76 '|','|', TOK_LOR,
77 '+','+', TOK_INC,
78 '-','-', TOK_DEC,
79 '=','=', TOK_EQ,
80 '<','<', TOK_SHL,
81 '>','>', TOK_SAR,
82 '+','=', TOK_A_ADD,
83 '-','=', TOK_A_SUB,
84 '*','=', TOK_A_MUL,
85 '/','=', TOK_A_DIV,
86 '%','=', TOK_A_MOD,
87 '&','=', TOK_A_AND,
88 '^','=', TOK_A_XOR,
89 '|','=', TOK_A_OR,
90 '-','>', TOK_ARROW,
91 '.','.', 0xa8, // C++ token ?
92 '#','#', TOK_TWOSHARPS,
96 static void next_nomacro_spc(void);
98 ST_FUNC void skip(int c)
100 if (tok != c)
101 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
102 next();
105 ST_FUNC void expect(const char *msg)
107 tcc_error("%s expected", msg);
110 /* ------------------------------------------------------------------------- */
111 /* Custom allocator for tiny objects */
113 #define USE_TAL
115 #ifndef USE_TAL
116 #define tal_free(al, p) tcc_free(p)
117 #define tal_realloc(al, p, size) tcc_realloc(p, size)
118 #define tal_new(a,b,c)
119 #define tal_delete(a)
120 #else
121 #if !defined(MEM_DEBUG)
122 #define tal_free(al, p) tal_free_impl(al, p)
123 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
124 #define TAL_DEBUG_PARAMS
125 #else
126 #define TAL_DEBUG 1
127 //#define TAL_INFO 1 /* collect and dump allocators stats */
128 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
129 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
130 #define TAL_DEBUG_PARAMS , const char *file, int line
131 #define TAL_DEBUG_FILE_LEN 40
132 #endif
134 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
135 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
136 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
137 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
138 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
139 #define CSTR_TAL_LIMIT 1024
141 typedef struct TinyAlloc {
142 unsigned limit;
143 unsigned size;
144 uint8_t *buffer;
145 uint8_t *p;
146 unsigned nb_allocs;
147 struct TinyAlloc *next, *top;
148 #ifdef TAL_INFO
149 unsigned nb_peak;
150 unsigned nb_total;
151 unsigned nb_missed;
152 uint8_t *peak_p;
153 #endif
154 } TinyAlloc;
156 typedef struct tal_header_t {
157 unsigned size;
158 #ifdef TAL_DEBUG
159 int line_num; /* negative line_num used for double free check */
160 char file_name[TAL_DEBUG_FILE_LEN + 1];
161 #endif
162 } tal_header_t;
164 /* ------------------------------------------------------------------------- */
166 static TinyAlloc *tal_new(TinyAlloc **pal, unsigned limit, unsigned size)
168 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
169 al->p = al->buffer = tcc_malloc(size);
170 al->limit = limit;
171 al->size = size;
172 if (pal) *pal = al;
173 return al;
176 static void tal_delete(TinyAlloc *al)
178 TinyAlloc *next;
180 tail_call:
181 if (!al)
182 return;
183 #ifdef TAL_INFO
184 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
185 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
186 (al->peak_p - al->buffer) * 100.0 / al->size);
187 #endif
188 #ifdef TAL_DEBUG
189 if (al->nb_allocs > 0) {
190 uint8_t *p;
191 fprintf(stderr, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
192 al->nb_allocs, al->limit);
193 p = al->buffer;
194 while (p < al->p) {
195 tal_header_t *header = (tal_header_t *)p;
196 if (header->line_num > 0) {
197 fprintf(stderr, "%s:%d: chunk of %d bytes leaked\n",
198 header->file_name, header->line_num, header->size);
200 p += header->size + sizeof(tal_header_t);
202 #if MEM_DEBUG-0 == 2
203 exit(2);
204 #endif
206 #endif
207 next = al->next;
208 tcc_free(al->buffer);
209 tcc_free(al);
210 al = next;
211 goto tail_call;
214 static void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
216 if (!p)
217 return;
218 tail_call:
219 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
220 #ifdef TAL_DEBUG
221 tal_header_t *header = (((tal_header_t *)p) - 1);
222 if (header->line_num < 0) {
223 fprintf(stderr, "%s:%d: TAL_DEBUG: double frees chunk from\n",
224 file, line);
225 fprintf(stderr, "%s:%d: %d bytes\n",
226 header->file_name, (int)-header->line_num, (int)header->size);
227 } else
228 header->line_num = -header->line_num;
229 #endif
230 al->nb_allocs--;
231 if (!al->nb_allocs)
232 al->p = al->buffer;
233 } else if (al->next) {
234 al = al->next;
235 goto tail_call;
237 else
238 tcc_free(p);
241 static void *tal_realloc_impl(TinyAlloc **pal, void *p, unsigned size TAL_DEBUG_PARAMS)
243 tal_header_t *header;
244 void *ret;
245 int is_own;
246 unsigned adj_size = (size + 3) & -4;
247 TinyAlloc *al = *pal;
249 tail_call:
250 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
251 if ((!p || is_own) && size <= al->limit) {
252 if (al->p + adj_size + sizeof(tal_header_t) < al->buffer + al->size) {
253 header = (tal_header_t *)al->p;
254 header->size = adj_size;
255 #ifdef TAL_DEBUG
256 { int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
257 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
258 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
259 header->line_num = line; }
260 #endif
261 ret = al->p + sizeof(tal_header_t);
262 al->p += adj_size + sizeof(tal_header_t);
263 if (is_own) {
264 header = (((tal_header_t *)p) - 1);
265 memcpy(ret, p, header->size);
266 #ifdef TAL_DEBUG
267 header->line_num = -header->line_num;
268 #endif
269 } else {
270 al->nb_allocs++;
272 #ifdef TAL_INFO
273 if (al->nb_peak < al->nb_allocs)
274 al->nb_peak = al->nb_allocs;
275 if (al->peak_p < al->p)
276 al->peak_p = al->p;
277 al->nb_total++;
278 #endif
279 return ret;
280 } else if (is_own) {
281 al->nb_allocs--;
282 ret = tal_realloc(*pal, 0, size);
283 header = (((tal_header_t *)p) - 1);
284 memcpy(ret, p, header->size);
285 #ifdef TAL_DEBUG
286 header->line_num = -header->line_num;
287 #endif
288 return ret;
290 if (al->next) {
291 al = al->next;
292 } else {
293 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
295 al = tal_new(pal, next->limit, next->size * 2);
296 al->next = next;
297 bottom->top = al;
299 goto tail_call;
301 if (is_own) {
302 al->nb_allocs--;
303 ret = tcc_malloc(size);
304 header = (((tal_header_t *)p) - 1);
305 memcpy(ret, p, header->size);
306 #ifdef TAL_DEBUG
307 header->line_num = -header->line_num;
308 #endif
309 } else if (al->next) {
310 al = al->next;
311 goto tail_call;
312 } else
313 ret = tcc_realloc(p, size);
314 #ifdef TAL_INFO
315 al->nb_missed++;
316 #endif
317 return ret;
320 #endif /* USE_TAL */
322 /* ------------------------------------------------------------------------- */
323 /* CString handling */
324 static void cstr_realloc(CString *cstr, int new_size)
326 int size;
328 size = cstr->size_allocated;
329 if (size < 8)
330 size = 8; /* no need to allocate a too small first string */
331 while (size < new_size)
332 size = size * 2;
333 cstr->data = tal_realloc(cstr_alloc, cstr->data, size);
334 cstr->size_allocated = size;
337 /* add a byte */
338 ST_INLN void cstr_ccat(CString *cstr, int ch)
340 int size;
341 size = cstr->size + 1;
342 if (size > cstr->size_allocated)
343 cstr_realloc(cstr, size);
344 ((unsigned char *)cstr->data)[size - 1] = ch;
345 cstr->size = size;
348 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
350 int size;
351 if (len <= 0)
352 len = strlen(str) + 1 + len;
353 size = cstr->size + len;
354 if (size > cstr->size_allocated)
355 cstr_realloc(cstr, size);
356 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
357 cstr->size = size;
360 /* add a wide char */
361 ST_FUNC void cstr_wccat(CString *cstr, int ch)
363 int size;
364 size = cstr->size + sizeof(nwchar_t);
365 if (size > cstr->size_allocated)
366 cstr_realloc(cstr, size);
367 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
368 cstr->size = size;
371 ST_FUNC void cstr_new(CString *cstr)
373 memset(cstr, 0, sizeof(CString));
376 /* free string and reset it to NULL */
377 ST_FUNC void cstr_free(CString *cstr)
379 tal_free(cstr_alloc, cstr->data);
380 cstr_new(cstr);
383 /* reset string to empty */
384 ST_FUNC void cstr_reset(CString *cstr)
386 cstr->size = 0;
389 /* XXX: unicode ? */
390 static void add_char(CString *cstr, int c)
392 if (c == '\'' || c == '\"' || c == '\\') {
393 /* XXX: could be more precise if char or string */
394 cstr_ccat(cstr, '\\');
396 if (c >= 32 && c <= 126) {
397 cstr_ccat(cstr, c);
398 } else {
399 cstr_ccat(cstr, '\\');
400 if (c == '\n') {
401 cstr_ccat(cstr, 'n');
402 } else {
403 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
404 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
405 cstr_ccat(cstr, '0' + (c & 7));
410 /* ------------------------------------------------------------------------- */
411 /* allocate a new token */
412 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
414 TokenSym *ts, **ptable;
415 int i;
417 if (tok_ident >= SYM_FIRST_ANOM)
418 tcc_error("memory full (symbols)");
420 /* expand token table if needed */
421 i = tok_ident - TOK_IDENT;
422 if ((i % TOK_ALLOC_INCR) == 0) {
423 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
424 table_ident = ptable;
427 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
428 table_ident[i] = ts;
429 ts->tok = tok_ident++;
430 ts->sym_define = NULL;
431 ts->sym_label = NULL;
432 ts->sym_struct = NULL;
433 ts->sym_identifier = NULL;
434 ts->len = len;
435 ts->hash_next = NULL;
436 memcpy(ts->str, str, len);
437 ts->str[len] = '\0';
438 *pts = ts;
439 return ts;
442 #define TOK_HASH_INIT 1
443 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
446 /* find a token and add it if not found */
447 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
449 TokenSym *ts, **pts;
450 int i;
451 unsigned int h;
453 h = TOK_HASH_INIT;
454 for(i=0;i<len;i++)
455 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
456 h &= (TOK_HASH_SIZE - 1);
458 pts = &hash_ident[h];
459 for(;;) {
460 ts = *pts;
461 if (!ts)
462 break;
463 if (ts->len == len && !memcmp(ts->str, str, len))
464 return ts;
465 pts = &(ts->hash_next);
467 return tok_alloc_new(pts, str, len);
470 /* XXX: buffer overflow */
471 /* XXX: float tokens */
472 ST_FUNC const char *get_tok_str(int v, CValue *cv)
474 char *p;
475 int i, len;
477 cstr_reset(&cstr_buf);
478 p = cstr_buf.data;
480 switch(v) {
481 case TOK_CINT:
482 case TOK_CUINT:
483 case TOK_CLONG:
484 case TOK_CULONG:
485 case TOK_CLLONG:
486 case TOK_CULLONG:
487 /* XXX: not quite exact, but only useful for testing */
488 #ifdef _WIN32
489 sprintf(p, "%u", (unsigned)cv->i);
490 #else
491 sprintf(p, "%llu", (unsigned long long)cv->i);
492 #endif
493 break;
494 case TOK_LCHAR:
495 cstr_ccat(&cstr_buf, 'L');
496 case TOK_CCHAR:
497 cstr_ccat(&cstr_buf, '\'');
498 add_char(&cstr_buf, cv->i);
499 cstr_ccat(&cstr_buf, '\'');
500 cstr_ccat(&cstr_buf, '\0');
501 break;
502 case TOK_PPNUM:
503 case TOK_PPSTR:
504 return (char*)cv->str.data;
505 case TOK_LSTR:
506 cstr_ccat(&cstr_buf, 'L');
507 case TOK_STR:
508 cstr_ccat(&cstr_buf, '\"');
509 if (v == TOK_STR) {
510 len = cv->str.size - 1;
511 for(i=0;i<len;i++)
512 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
513 } else {
514 len = (cv->str.size / sizeof(nwchar_t)) - 1;
515 for(i=0;i<len;i++)
516 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
518 cstr_ccat(&cstr_buf, '\"');
519 cstr_ccat(&cstr_buf, '\0');
520 break;
522 case TOK_CFLOAT:
523 cstr_cat(&cstr_buf, "<float>", 0);
524 break;
525 case TOK_CDOUBLE:
526 cstr_cat(&cstr_buf, "<double>", 0);
527 break;
528 case TOK_CLDOUBLE:
529 cstr_cat(&cstr_buf, "<long double>", 0);
530 break;
531 case TOK_LINENUM:
532 cstr_cat(&cstr_buf, "<linenumber>", 0);
533 break;
535 /* above tokens have value, the ones below don't */
536 case TOK_LT:
537 v = '<';
538 goto addv;
539 case TOK_GT:
540 v = '>';
541 goto addv;
542 case TOK_DOTS:
543 return strcpy(p, "...");
544 case TOK_A_SHL:
545 return strcpy(p, "<<=");
546 case TOK_A_SAR:
547 return strcpy(p, ">>=");
548 case TOK_EOF:
549 return strcpy(p, "<eof>");
550 default:
551 if (v < TOK_IDENT) {
552 /* search in two bytes table */
553 const unsigned char *q = tok_two_chars;
554 while (*q) {
555 if (q[2] == v) {
556 *p++ = q[0];
557 *p++ = q[1];
558 *p = '\0';
559 return cstr_buf.data;
561 q += 3;
563 if (v >= 127) {
564 sprintf(cstr_buf.data, "<%02x>", v);
565 return cstr_buf.data;
567 addv:
568 *p++ = v;
569 *p = '\0';
570 } else if (v < tok_ident) {
571 return table_ident[v - TOK_IDENT]->str;
572 } else if (v >= SYM_FIRST_ANOM) {
573 /* special name for anonymous symbol */
574 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
575 } else {
576 /* should never happen */
577 return NULL;
579 break;
581 return cstr_buf.data;
584 /* return the current character, handling end of block if necessary
585 (but not stray) */
586 ST_FUNC int handle_eob(void)
588 BufferedFile *bf = file;
589 int len;
591 /* only tries to read if really end of buffer */
592 if (bf->buf_ptr >= bf->buf_end) {
593 if (bf->fd != -1) {
594 #if defined(PARSE_DEBUG)
595 len = 1;
596 #else
597 len = IO_BUF_SIZE;
598 #endif
599 len = read(bf->fd, bf->buffer, len);
600 if (len < 0)
601 len = 0;
602 } else {
603 len = 0;
605 total_bytes += len;
606 bf->buf_ptr = bf->buffer;
607 bf->buf_end = bf->buffer + len;
608 *bf->buf_end = CH_EOB;
610 if (bf->buf_ptr < bf->buf_end) {
611 return bf->buf_ptr[0];
612 } else {
613 bf->buf_ptr = bf->buf_end;
614 return CH_EOF;
618 /* read next char from current input file and handle end of input buffer */
619 ST_INLN void inp(void)
621 ch = *(++(file->buf_ptr));
622 /* end of buffer/file handling */
623 if (ch == CH_EOB)
624 ch = handle_eob();
627 /* handle '\[\r]\n' */
628 static int handle_stray_noerror(void)
630 while (ch == '\\') {
631 inp();
632 if (ch == '\n') {
633 file->line_num++;
634 inp();
635 } else if (ch == '\r') {
636 inp();
637 if (ch != '\n')
638 goto fail;
639 file->line_num++;
640 inp();
641 } else {
642 fail:
643 return 1;
646 return 0;
649 static void handle_stray(void)
651 if (handle_stray_noerror())
652 tcc_error("stray '\\' in program");
655 /* skip the stray and handle the \\n case. Output an error if
656 incorrect char after the stray */
657 static int handle_stray1(uint8_t *p)
659 int c;
661 file->buf_ptr = p;
662 if (p >= file->buf_end) {
663 c = handle_eob();
664 if (c != '\\')
665 return c;
666 p = file->buf_ptr;
668 ch = *p;
669 if (handle_stray_noerror()) {
670 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
671 tcc_error("stray '\\' in program");
672 *--file->buf_ptr = '\\';
674 p = file->buf_ptr;
675 c = *p;
676 return c;
679 /* handle just the EOB case, but not stray */
680 #define PEEKC_EOB(c, p)\
682 p++;\
683 c = *p;\
684 if (c == '\\') {\
685 file->buf_ptr = p;\
686 c = handle_eob();\
687 p = file->buf_ptr;\
691 /* handle the complicated stray case */
692 #define PEEKC(c, p)\
694 p++;\
695 c = *p;\
696 if (c == '\\') {\
697 c = handle_stray1(p);\
698 p = file->buf_ptr;\
702 /* input with '\[\r]\n' handling. Note that this function cannot
703 handle other characters after '\', so you cannot call it inside
704 strings or comments */
705 ST_FUNC void minp(void)
707 inp();
708 if (ch == '\\')
709 handle_stray();
712 /* single line C++ comments */
713 static uint8_t *parse_line_comment(uint8_t *p)
715 int c;
717 p++;
718 for(;;) {
719 c = *p;
720 redo:
721 if (c == '\n' || c == CH_EOF) {
722 break;
723 } else if (c == '\\') {
724 file->buf_ptr = p;
725 c = handle_eob();
726 p = file->buf_ptr;
727 if (c == '\\') {
728 PEEKC_EOB(c, p);
729 if (c == '\n') {
730 file->line_num++;
731 PEEKC_EOB(c, p);
732 } else if (c == '\r') {
733 PEEKC_EOB(c, p);
734 if (c == '\n') {
735 file->line_num++;
736 PEEKC_EOB(c, p);
739 } else {
740 goto redo;
742 } else {
743 p++;
746 return p;
749 /* C comments */
750 ST_FUNC uint8_t *parse_comment(uint8_t *p)
752 int c;
754 p++;
755 for(;;) {
756 /* fast skip loop */
757 for(;;) {
758 c = *p;
759 if (c == '\n' || c == '*' || c == '\\')
760 break;
761 p++;
762 c = *p;
763 if (c == '\n' || c == '*' || c == '\\')
764 break;
765 p++;
767 /* now we can handle all the cases */
768 if (c == '\n') {
769 file->line_num++;
770 p++;
771 } else if (c == '*') {
772 p++;
773 for(;;) {
774 c = *p;
775 if (c == '*') {
776 p++;
777 } else if (c == '/') {
778 goto end_of_comment;
779 } else if (c == '\\') {
780 file->buf_ptr = p;
781 c = handle_eob();
782 p = file->buf_ptr;
783 if (c == CH_EOF)
784 tcc_error("unexpected end of file in comment");
785 if (c == '\\') {
786 /* skip '\[\r]\n', otherwise just skip the stray */
787 while (c == '\\') {
788 PEEKC_EOB(c, p);
789 if (c == '\n') {
790 file->line_num++;
791 PEEKC_EOB(c, p);
792 } else if (c == '\r') {
793 PEEKC_EOB(c, p);
794 if (c == '\n') {
795 file->line_num++;
796 PEEKC_EOB(c, p);
798 } else {
799 goto after_star;
803 } else {
804 break;
807 after_star: ;
808 } else {
809 /* stray, eob or eof */
810 file->buf_ptr = p;
811 c = handle_eob();
812 p = file->buf_ptr;
813 if (c == CH_EOF) {
814 tcc_error("unexpected end of file in comment");
815 } else if (c == '\\') {
816 p++;
820 end_of_comment:
821 p++;
822 return p;
825 ST_FUNC int set_idnum(int c, int val)
827 int prev = isidnum_table[c - CH_EOF];
828 isidnum_table[c - CH_EOF] = val;
829 return prev;
832 #define cinp minp
834 static inline void skip_spaces(void)
836 while (isidnum_table[ch - CH_EOF] & IS_SPC)
837 cinp();
840 static inline int check_space(int t, int *spc)
842 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
843 if (*spc)
844 return 1;
845 *spc = 1;
846 } else
847 *spc = 0;
848 return 0;
851 /* parse a string without interpreting escapes */
852 static uint8_t *parse_pp_string(uint8_t *p,
853 int sep, CString *str)
855 int c;
856 p++;
857 for(;;) {
858 c = *p;
859 if (c == sep) {
860 break;
861 } else if (c == '\\') {
862 file->buf_ptr = p;
863 c = handle_eob();
864 p = file->buf_ptr;
865 if (c == CH_EOF) {
866 unterminated_string:
867 /* XXX: indicate line number of start of string */
868 tcc_error("missing terminating %c character", sep);
869 } else if (c == '\\') {
870 /* escape : just skip \[\r]\n */
871 PEEKC_EOB(c, p);
872 if (c == '\n') {
873 file->line_num++;
874 p++;
875 } else if (c == '\r') {
876 PEEKC_EOB(c, p);
877 if (c != '\n')
878 expect("'\n' after '\r'");
879 file->line_num++;
880 p++;
881 } else if (c == CH_EOF) {
882 goto unterminated_string;
883 } else {
884 if (str) {
885 cstr_ccat(str, '\\');
886 cstr_ccat(str, c);
888 p++;
891 } else if (c == '\n') {
892 file->line_num++;
893 goto add_char;
894 } else if (c == '\r') {
895 PEEKC_EOB(c, p);
896 if (c != '\n') {
897 if (str)
898 cstr_ccat(str, '\r');
899 } else {
900 file->line_num++;
901 goto add_char;
903 } else {
904 add_char:
905 if (str)
906 cstr_ccat(str, c);
907 p++;
910 p++;
911 return p;
914 /* skip block of text until #else, #elif or #endif. skip also pairs of
915 #if/#endif */
916 static void preprocess_skip(void)
918 int a, start_of_line, c, in_warn_or_error;
919 uint8_t *p;
921 p = file->buf_ptr;
922 a = 0;
923 redo_start:
924 start_of_line = 1;
925 in_warn_or_error = 0;
926 for(;;) {
927 redo_no_start:
928 c = *p;
929 switch(c) {
930 case ' ':
931 case '\t':
932 case '\f':
933 case '\v':
934 case '\r':
935 p++;
936 goto redo_no_start;
937 case '\n':
938 file->line_num++;
939 p++;
940 goto redo_start;
941 case '\\':
942 file->buf_ptr = p;
943 c = handle_eob();
944 if (c == CH_EOF) {
945 expect("#endif");
946 } else if (c == '\\') {
947 ch = file->buf_ptr[0];
948 handle_stray_noerror();
950 p = file->buf_ptr;
951 goto redo_no_start;
952 /* skip strings */
953 case '\"':
954 case '\'':
955 if (in_warn_or_error)
956 goto _default;
957 p = parse_pp_string(p, c, NULL);
958 break;
959 /* skip comments */
960 case '/':
961 if (in_warn_or_error)
962 goto _default;
963 file->buf_ptr = p;
964 ch = *p;
965 minp();
966 p = file->buf_ptr;
967 if (ch == '*') {
968 p = parse_comment(p);
969 } else if (ch == '/') {
970 p = parse_line_comment(p);
972 break;
973 case '#':
974 p++;
975 if (start_of_line) {
976 file->buf_ptr = p;
977 next_nomacro();
978 p = file->buf_ptr;
979 if (a == 0 &&
980 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
981 goto the_end;
982 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
983 a++;
984 else if (tok == TOK_ENDIF)
985 a--;
986 else if( tok == TOK_ERROR || tok == TOK_WARNING)
987 in_warn_or_error = 1;
988 else if (tok == TOK_LINEFEED)
989 goto redo_start;
990 else if (parse_flags & PARSE_FLAG_ASM_FILE)
991 p = parse_line_comment(p - 1);
992 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
993 p = parse_line_comment(p - 1);
994 break;
995 _default:
996 default:
997 p++;
998 break;
1000 start_of_line = 0;
1002 the_end: ;
1003 file->buf_ptr = p;
1006 #if 0
1007 /* return the number of additional 'ints' necessary to store the
1008 token */
1009 static inline int tok_size(const int *p)
1011 switch(*p) {
1012 /* 4 bytes */
1013 case TOK_CINT:
1014 case TOK_CUINT:
1015 case TOK_CCHAR:
1016 case TOK_LCHAR:
1017 case TOK_CFLOAT:
1018 case TOK_LINENUM:
1019 #ifndef TCC_LONG_ARE_64_BIT
1020 case TOK_CLONG;
1021 case TOK_CULONG;
1022 #endif
1023 return 1 + 1;
1024 case TOK_STR:
1025 case TOK_LSTR:
1026 case TOK_PPNUM:
1027 case TOK_PPSTR:
1028 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1029 case TOK_CDOUBLE:
1030 case TOK_CLLONG:
1031 case TOK_CULLONG:
1032 #ifdef TCC_LONG_ARE_64_BIT
1033 case TOK_CLONG;
1034 case TOK_CULONG;
1035 #endif
1036 return 1 + 2;
1037 case TOK_CLDOUBLE:
1038 return 1 + LDOUBLE_SIZE / 4;
1039 default:
1040 return 1 + 0;
1043 #endif
1045 /* token string handling */
1046 ST_INLN void tok_str_new(TokenString *s)
1048 s->str = NULL;
1049 s->len = s->lastlen = 0;
1050 s->allocated_len = 0;
1051 s->last_line_num = -1;
1054 ST_FUNC TokenString *tok_str_alloc(void)
1056 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1057 tok_str_new(str);
1058 return str;
1061 ST_FUNC int *tok_str_dup(TokenString *s)
1063 int *str;
1065 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1066 memcpy(str, s->str, s->len * sizeof(int));
1067 return str;
1070 ST_FUNC void tok_str_free_str(int *str)
1072 tal_free(tokstr_alloc, str);
1075 ST_FUNC void tok_str_free(TokenString *str)
1077 tok_str_free_str(str->str);
1078 tal_free(tokstr_alloc, str);
1081 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1083 int *str, size;
1085 size = s->allocated_len;
1086 if (size < 16)
1087 size = 16;
1088 while (size < new_size)
1089 size = size * 2;
1090 if (size > s->allocated_len) {
1091 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1092 s->allocated_len = size;
1093 s->str = str;
1095 return s->str;
1098 ST_FUNC void tok_str_add(TokenString *s, int t)
1100 int len, *str;
1102 len = s->len;
1103 str = s->str;
1104 if (len >= s->allocated_len)
1105 str = tok_str_realloc(s, len + 1);
1106 str[len++] = t;
1107 s->len = len;
1110 ST_FUNC void begin_macro(TokenString *str, int alloc)
1112 str->alloc = alloc;
1113 str->prev = macro_stack;
1114 str->prev_ptr = macro_ptr;
1115 str->save_line_num = file->line_num;
1116 macro_ptr = str->str;
1117 macro_stack = str;
1120 ST_FUNC void end_macro(void)
1122 TokenString *str = macro_stack;
1123 macro_stack = str->prev;
1124 macro_ptr = str->prev_ptr;
1125 file->line_num = str->save_line_num;
1126 if (str->alloc == 2) {
1127 str->alloc = 3; /* just mark as finished */
1128 } else {
1129 tok_str_free(str);
1133 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1135 int len, *str;
1137 len = s->lastlen = s->len;
1138 str = s->str;
1140 /* allocate space for worst case */
1141 if (len + TOK_MAX_SIZE >= s->allocated_len)
1142 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1143 str[len++] = t;
1144 switch(t) {
1145 case TOK_CINT:
1146 case TOK_CUINT:
1147 case TOK_CCHAR:
1148 case TOK_LCHAR:
1149 case TOK_CFLOAT:
1150 case TOK_LINENUM:
1151 #ifndef TCC_LONG_ARE_64_BIT
1152 case TOK_CLONG:
1153 case TOK_CULONG:
1154 #endif
1155 str[len++] = cv->tab[0];
1156 break;
1157 case TOK_PPNUM:
1158 case TOK_PPSTR:
1159 case TOK_STR:
1160 case TOK_LSTR:
1162 /* Insert the string into the int array. */
1163 size_t nb_words =
1164 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1165 if (len + nb_words >= s->allocated_len)
1166 str = tok_str_realloc(s, len + nb_words + 1);
1167 str[len] = cv->str.size;
1168 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1169 len += nb_words;
1171 break;
1172 case TOK_CDOUBLE:
1173 case TOK_CLLONG:
1174 case TOK_CULLONG:
1175 #ifdef TCC_LONG_ARE_64_BIT
1176 case TOK_CLONG:
1177 case TOK_CULONG:
1178 #endif
1179 #if LDOUBLE_SIZE == 8
1180 case TOK_CLDOUBLE:
1181 #endif
1182 str[len++] = cv->tab[0];
1183 str[len++] = cv->tab[1];
1184 break;
1185 #if LDOUBLE_SIZE == 12
1186 case TOK_CLDOUBLE:
1187 str[len++] = cv->tab[0];
1188 str[len++] = cv->tab[1];
1189 str[len++] = cv->tab[2];
1190 #elif LDOUBLE_SIZE == 16
1191 case TOK_CLDOUBLE:
1192 str[len++] = cv->tab[0];
1193 str[len++] = cv->tab[1];
1194 str[len++] = cv->tab[2];
1195 str[len++] = cv->tab[3];
1196 #elif LDOUBLE_SIZE != 8
1197 #error add long double size support
1198 #endif
1199 break;
1200 default:
1201 break;
1203 s->len = len;
1206 /* add the current parse token in token string 's' */
1207 ST_FUNC void tok_str_add_tok(TokenString *s)
1209 CValue cval;
1211 /* save line number info */
1212 if (file->line_num != s->last_line_num) {
1213 s->last_line_num = file->line_num;
1214 cval.i = s->last_line_num;
1215 tok_str_add2(s, TOK_LINENUM, &cval);
1217 tok_str_add2(s, tok, &tokc);
1220 /* get a token from an integer array and increment pointer
1221 accordingly. we code it as a macro to avoid pointer aliasing. */
1222 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
1224 const int *p = *pp;
1225 int n, *tab;
1227 tab = cv->tab;
1228 switch(*t = *p++) {
1229 case TOK_CINT:
1230 case TOK_CUINT:
1231 case TOK_CCHAR:
1232 case TOK_LCHAR:
1233 case TOK_LINENUM:
1234 #ifndef TCC_LONG_ARE_64_BIT
1235 case TOK_CLONG:
1236 case TOK_CULONG:
1237 #endif
1238 tab[0] = *p++;
1239 cv->i = (*t == TOK_CUINT) ? (unsigned)cv->i : (int)cv->i;
1240 break;
1241 case TOK_CFLOAT:
1242 tab[0] = *p++;
1243 break;
1244 case TOK_STR:
1245 case TOK_LSTR:
1246 case TOK_PPNUM:
1247 case TOK_PPSTR:
1248 cv->str.size = *p++;
1249 cv->str.data = p;
1250 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1251 break;
1252 case TOK_CDOUBLE:
1253 case TOK_CLLONG:
1254 case TOK_CULLONG:
1255 #ifdef TCC_LONG_ARE_64_BIT
1256 case TOK_CLONG:
1257 case TOK_CULONG:
1258 #endif
1259 n = 2;
1260 goto copy;
1261 case TOK_CLDOUBLE:
1262 #if LDOUBLE_SIZE == 16
1263 n = 4;
1264 #elif LDOUBLE_SIZE == 12
1265 n = 3;
1266 #elif LDOUBLE_SIZE == 8
1267 n = 2;
1268 #else
1269 # error add long double size support
1270 #endif
1271 copy:
1273 *tab++ = *p++;
1274 while (--n);
1275 break;
1276 default:
1277 break;
1279 *pp = p;
1282 static int macro_is_equal(const int *a, const int *b)
1284 CValue cv;
1285 int t;
1287 if (!a || !b)
1288 return 1;
1290 while (*a && *b) {
1291 /* first time preallocate macro_equal_buf, next time only reset position to start */
1292 cstr_reset(&macro_equal_buf);
1293 TOK_GET(&t, &a, &cv);
1294 cstr_cat(&macro_equal_buf, get_tok_str(t, &cv), 0);
1295 TOK_GET(&t, &b, &cv);
1296 if (strcmp(macro_equal_buf.data, get_tok_str(t, &cv)))
1297 return 0;
1299 return !(*a || *b);
1302 /* defines handling */
1303 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1305 Sym *s, *o;
1307 o = define_find(v);
1308 s = sym_push2(&define_stack, v, macro_type, 0);
1309 s->d = str;
1310 s->next = first_arg;
1311 table_ident[v - TOK_IDENT]->sym_define = s;
1313 if (o && !macro_is_equal(o->d, s->d))
1314 tcc_warning("%s redefined", get_tok_str(v, NULL));
1317 /* undefined a define symbol. Its name is just set to zero */
1318 ST_FUNC void define_undef(Sym *s)
1320 int v = s->v;
1321 if (v >= TOK_IDENT && v < tok_ident)
1322 table_ident[v - TOK_IDENT]->sym_define = NULL;
1325 ST_INLN Sym *define_find(int v)
1327 v -= TOK_IDENT;
1328 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1329 return NULL;
1330 return table_ident[v]->sym_define;
1333 /* free define stack until top reaches 'b' */
1334 ST_FUNC void free_defines(Sym *b)
1336 while (define_stack != b) {
1337 Sym *top = define_stack;
1338 define_stack = top->prev;
1339 tok_str_free_str(top->d);
1340 define_undef(top);
1341 sym_free(top);
1344 /* restore remaining (-D or predefined) symbols if they were
1345 #undef'd in the file */
1346 while (b) {
1347 int v = b->v;
1348 if (v >= TOK_IDENT && v < tok_ident) {
1349 Sym **d = &table_ident[v - TOK_IDENT]->sym_define;
1350 if (!*d)
1351 *d = b;
1353 b = b->prev;
1357 /* label lookup */
1358 ST_FUNC Sym *label_find(int v)
1360 v -= TOK_IDENT;
1361 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1362 return NULL;
1363 return table_ident[v]->sym_label;
1366 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1368 Sym *s, **ps;
1369 s = sym_push2(ptop, v, 0, 0);
1370 s->r = flags;
1371 ps = &table_ident[v - TOK_IDENT]->sym_label;
1372 if (ptop == &global_label_stack) {
1373 /* modify the top most local identifier, so that
1374 sym_identifier will point to 's' when popped */
1375 while (*ps != NULL)
1376 ps = &(*ps)->prev_tok;
1378 s->prev_tok = *ps;
1379 *ps = s;
1380 return s;
1383 /* pop labels until element last is reached. Look if any labels are
1384 undefined. Define symbols if '&&label' was used. */
1385 ST_FUNC void label_pop(Sym **ptop, Sym *slast, int keep)
1387 Sym *s, *s1;
1388 for(s = *ptop; s != slast; s = s1) {
1389 s1 = s->prev;
1390 if (s->r == LABEL_DECLARED) {
1391 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1392 } else if (s->r == LABEL_FORWARD) {
1393 tcc_error("label '%s' used but not defined",
1394 get_tok_str(s->v, NULL));
1395 } else {
1396 if (s->c) {
1397 /* define corresponding symbol. A size of
1398 1 is put. */
1399 put_extern_sym(s, cur_text_section, s->jnext, 1);
1402 /* remove label */
1403 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1404 if (!keep)
1405 sym_free(s);
1407 if (!keep)
1408 *ptop = slast;
1411 /* fake the nth "#if defined test_..." for tcc -dt -run */
1412 static void maybe_run_test(TCCState *s, int *c)
1414 const char *p;
1415 if (s->include_stack_ptr != s->include_stack)
1416 return;
1417 p = get_tok_str(tok, NULL);
1418 if (0 != memcmp(p, "test_", 5))
1419 return;
1420 if (0 != --s->run_test)
1421 return;
1422 fprintf(s->ppfp, "\n[%s]\n" + !(s->dflag & 32), p), fflush(s->ppfp);
1423 *c = 1;
1426 /* eval an expression for #if/#elif */
1427 static int expr_preprocess(void)
1429 int c, t;
1430 TokenString *str;
1432 str = tok_str_alloc();
1433 pp_expr = 1;
1434 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1435 next(); /* do macro subst */
1436 if (tok == TOK_DEFINED) {
1437 next_nomacro();
1438 t = tok;
1439 if (t == '(')
1440 next_nomacro();
1441 if (tok < TOK_IDENT)
1442 expect("identifier");
1443 c = define_find(tok) != 0;
1444 if (tcc_state->run_test)
1445 maybe_run_test(tcc_state, &c);
1446 if (t == '(') {
1447 next_nomacro();
1448 if (tok != ')')
1449 expect("')'");
1451 tok = TOK_CINT;
1452 tokc.i = c;
1453 } else if (tok >= TOK_IDENT) {
1454 /* if undefined macro */
1455 tok = TOK_CINT;
1456 tokc.i = 0;
1458 tok_str_add_tok(str);
1460 pp_expr = 0;
1461 tok_str_add(str, -1); /* simulate end of file */
1462 tok_str_add(str, 0);
1463 /* now evaluate C constant expression */
1464 begin_macro(str, 1);
1465 next();
1466 c = expr_const();
1467 end_macro();
1468 return c != 0;
1472 /* parse after #define */
1473 ST_FUNC void parse_define(void)
1475 Sym *s, *first, **ps;
1476 int v, t, varg, is_vaargs, spc;
1477 int saved_parse_flags = parse_flags;
1479 v = tok;
1480 if (v < TOK_IDENT || v == TOK_DEFINED)
1481 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1482 /* XXX: should check if same macro (ANSI) */
1483 first = NULL;
1484 t = MACRO_OBJ;
1485 /* We have to parse the whole define as if not in asm mode, in particular
1486 no line comment with '#' must be ignored. Also for function
1487 macros the argument list must be parsed without '.' being an ID
1488 character. */
1489 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1490 /* '(' must be just after macro definition for MACRO_FUNC */
1491 next_nomacro_spc();
1492 if (tok == '(') {
1493 int dotid = set_idnum('.', 0);
1494 next_nomacro();
1495 ps = &first;
1496 if (tok != ')') for (;;) {
1497 varg = tok;
1498 next_nomacro();
1499 is_vaargs = 0;
1500 if (varg == TOK_DOTS) {
1501 varg = TOK___VA_ARGS__;
1502 is_vaargs = 1;
1503 } else if (tok == TOK_DOTS && gnu_ext) {
1504 is_vaargs = 1;
1505 next_nomacro();
1507 if (varg < TOK_IDENT)
1508 bad_list:
1509 tcc_error("bad macro parameter list");
1510 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1511 *ps = s;
1512 ps = &s->next;
1513 if (tok == ')')
1514 break;
1515 if (tok != ',' || is_vaargs)
1516 goto bad_list;
1517 next_nomacro();
1519 next_nomacro_spc();
1520 t = MACRO_FUNC;
1521 set_idnum('.', dotid);
1524 tokstr_buf.len = 0;
1525 spc = 2;
1526 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1527 /* The body of a macro definition should be parsed such that identifiers
1528 are parsed like the file mode determines (i.e. with '.' being an
1529 ID character in asm mode). But '#' should be retained instead of
1530 regarded as line comment leader, so still don't set ASM_FILE
1531 in parse_flags. */
1532 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1533 /* remove spaces around ## and after '#' */
1534 if (TOK_TWOSHARPS == tok) {
1535 if (2 == spc)
1536 goto bad_twosharp;
1537 if (1 == spc)
1538 --tokstr_buf.len;
1539 spc = 3;
1540 tok = TOK_PPJOIN;
1541 } else if ('#' == tok) {
1542 spc = 4;
1543 } else if (check_space(tok, &spc)) {
1544 goto skip;
1546 tok_str_add2(&tokstr_buf, tok, &tokc);
1547 skip:
1548 next_nomacro_spc();
1551 parse_flags = saved_parse_flags;
1552 if (spc == 1)
1553 --tokstr_buf.len; /* remove trailing space */
1554 tok_str_add(&tokstr_buf, 0);
1555 if (3 == spc)
1556 bad_twosharp:
1557 tcc_error("'##' cannot appear at either end of macro");
1558 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1561 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1563 const unsigned char *s;
1564 unsigned int h;
1565 CachedInclude *e;
1566 int i;
1568 h = TOK_HASH_INIT;
1569 s = (unsigned char *) filename;
1570 while (*s) {
1571 #ifdef _WIN32
1572 h = TOK_HASH_FUNC(h, toup(*s));
1573 #else
1574 h = TOK_HASH_FUNC(h, *s);
1575 #endif
1576 s++;
1578 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1580 i = s1->cached_includes_hash[h];
1581 for(;;) {
1582 if (i == 0)
1583 break;
1584 e = s1->cached_includes[i - 1];
1585 if (0 == PATHCMP(e->filename, filename))
1586 return e;
1587 i = e->hash_next;
1589 if (!add)
1590 return NULL;
1592 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1593 strcpy(e->filename, filename);
1594 e->ifndef_macro = e->once = 0;
1595 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1596 /* add in hash table */
1597 e->hash_next = s1->cached_includes_hash[h];
1598 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1599 #ifdef INC_DEBUG
1600 printf("adding cached '%s'\n", filename);
1601 #endif
1602 return e;
1605 static void pragma_parse(TCCState *s1)
1607 next_nomacro();
1608 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1609 int t = tok, v;
1610 Sym *s;
1612 if (next(), tok != '(')
1613 goto pragma_err;
1614 if (next(), tok != TOK_STR)
1615 goto pragma_err;
1616 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1617 if (next(), tok != ')')
1618 goto pragma_err;
1619 if (t == TOK_push_macro) {
1620 while (NULL == (s = define_find(v)))
1621 define_push(v, 0, NULL, NULL);
1622 s->type.ref = s; /* set push boundary */
1623 } else {
1624 for (s = define_stack; s; s = s->prev)
1625 if (s->v == v && s->type.ref == s) {
1626 s->type.ref = NULL;
1627 break;
1630 if (s)
1631 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1632 else
1633 tcc_warning("unbalanced #pragma pop_macro");
1634 pp_debug_tok = t, pp_debug_symv = v;
1636 } else if (tok == TOK_once) {
1637 search_cached_include(s1, file->filename, 1)->once = pp_once;
1639 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1640 /* tcc -E: keep pragmas below unchanged */
1641 unget_tok(' ');
1642 unget_tok(TOK_PRAGMA);
1643 unget_tok('#');
1644 unget_tok(TOK_LINEFEED);
1646 } else if (tok == TOK_pack) {
1647 /* This may be:
1648 #pragma pack(1) // set
1649 #pragma pack() // reset to default
1650 #pragma pack(push,1) // push & set
1651 #pragma pack(pop) // restore previous */
1652 next();
1653 skip('(');
1654 if (tok == TOK_ASM_pop) {
1655 next();
1656 if (s1->pack_stack_ptr <= s1->pack_stack) {
1657 stk_error:
1658 tcc_error("out of pack stack");
1660 s1->pack_stack_ptr--;
1661 } else {
1662 int val = 0;
1663 if (tok != ')') {
1664 if (tok == TOK_ASM_push) {
1665 next();
1666 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1667 goto stk_error;
1668 s1->pack_stack_ptr++;
1669 skip(',');
1671 if (tok != TOK_CINT)
1672 goto pragma_err;
1673 val = tokc.i;
1674 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1675 goto pragma_err;
1676 next();
1678 *s1->pack_stack_ptr = val;
1680 if (tok != ')')
1681 goto pragma_err;
1683 } else if (tok == TOK_comment) {
1684 char *p; int t;
1685 next();
1686 skip('(');
1687 t = tok;
1688 next();
1689 skip(',');
1690 if (tok != TOK_STR)
1691 goto pragma_err;
1692 p = tcc_strdup((char *)tokc.str.data);
1693 next();
1694 if (tok != ')')
1695 goto pragma_err;
1696 if (t == TOK_lib) {
1697 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1698 } else {
1699 if (t == TOK_option)
1700 tcc_set_options(s1, p);
1701 tcc_free(p);
1704 } else if (s1->warn_unsupported) {
1705 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1707 return;
1709 pragma_err:
1710 tcc_error("malformed #pragma directive");
1711 return;
1714 /* is_bof is true if first non space token at beginning of file */
1715 ST_FUNC void preprocess(int is_bof)
1717 TCCState *s1 = tcc_state;
1718 int i, c, n, saved_parse_flags;
1719 char buf[1024], *q;
1720 Sym *s;
1722 saved_parse_flags = parse_flags;
1723 parse_flags = PARSE_FLAG_PREPROCESS
1724 | PARSE_FLAG_TOK_NUM
1725 | PARSE_FLAG_TOK_STR
1726 | PARSE_FLAG_LINEFEED
1727 | (parse_flags & PARSE_FLAG_ASM_FILE)
1730 next_nomacro();
1731 redo:
1732 switch(tok) {
1733 case TOK_DEFINE:
1734 pp_debug_tok = tok;
1735 next_nomacro();
1736 pp_debug_symv = tok;
1737 parse_define();
1738 break;
1739 case TOK_UNDEF:
1740 pp_debug_tok = tok;
1741 next_nomacro();
1742 pp_debug_symv = tok;
1743 s = define_find(tok);
1744 /* undefine symbol by putting an invalid name */
1745 if (s)
1746 define_undef(s);
1747 break;
1748 case TOK_INCLUDE:
1749 case TOK_INCLUDE_NEXT:
1750 ch = file->buf_ptr[0];
1751 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1752 skip_spaces();
1753 if (ch == '<') {
1754 c = '>';
1755 goto read_name;
1756 } else if (ch == '\"') {
1757 c = ch;
1758 read_name:
1759 inp();
1760 q = buf;
1761 while (ch != c && ch != '\n' && ch != CH_EOF) {
1762 if ((q - buf) < sizeof(buf) - 1)
1763 *q++ = ch;
1764 if (ch == '\\') {
1765 if (handle_stray_noerror() == 0)
1766 --q;
1767 } else
1768 inp();
1770 *q = '\0';
1771 minp();
1772 #if 0
1773 /* eat all spaces and comments after include */
1774 /* XXX: slightly incorrect */
1775 while (ch1 != '\n' && ch1 != CH_EOF)
1776 inp();
1777 #endif
1778 } else {
1779 int len;
1780 /* computed #include : concatenate everything up to linefeed,
1781 the result must be one of the two accepted forms.
1782 Don't convert pp-tokens to tokens here. */
1783 parse_flags = (PARSE_FLAG_PREPROCESS
1784 | PARSE_FLAG_LINEFEED
1785 | (parse_flags & PARSE_FLAG_ASM_FILE));
1786 next();
1787 buf[0] = '\0';
1788 while (tok != TOK_LINEFEED) {
1789 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1790 next();
1792 len = strlen(buf);
1793 /* check syntax and remove '<>|""' */
1794 if ((len < 2 || ((buf[0] != '"' || buf[len-1] != '"') &&
1795 (buf[0] != '<' || buf[len-1] != '>'))))
1796 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1797 c = buf[len-1];
1798 memmove(buf, buf + 1, len - 2);
1799 buf[len - 2] = '\0';
1802 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1803 tcc_error("#include recursion too deep");
1804 /* store current file in stack, but increment stack later below */
1805 *s1->include_stack_ptr = file;
1806 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index : 0;
1807 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1808 for (; i < n; ++i) {
1809 char buf1[sizeof file->filename];
1810 CachedInclude *e;
1811 const char *path;
1813 if (i == 0) {
1814 /* check absolute include path */
1815 if (!IS_ABSPATH(buf))
1816 continue;
1817 buf1[0] = 0;
1819 } else if (i == 1) {
1820 /* search in file's dir if "header.h" */
1821 if (c != '\"')
1822 continue;
1823 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1824 path = file->true_filename;
1825 pstrncpy(buf1, path, tcc_basename(path) - path);
1827 } else {
1828 /* search in all the include paths */
1829 int j = i - 2, k = j - s1->nb_include_paths;
1830 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1831 pstrcpy(buf1, sizeof(buf1), path);
1832 pstrcat(buf1, sizeof(buf1), "/");
1835 pstrcat(buf1, sizeof(buf1), buf);
1836 e = search_cached_include(s1, buf1, 0);
1837 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1838 /* no need to parse the include because the 'ifndef macro'
1839 is defined (or had #pragma once) */
1840 #ifdef INC_DEBUG
1841 printf("%s: skipping cached %s\n", file->filename, buf1);
1842 #endif
1843 goto include_done;
1846 if (tcc_open(s1, buf1) < 0)
1847 continue;
1849 file->include_next_index = i + 1;
1850 #ifdef INC_DEBUG
1851 printf("%s: including %s\n", file->prev->filename, file->filename);
1852 #endif
1853 /* update target deps */
1854 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1855 tcc_strdup(buf1));
1856 /* push current file in stack */
1857 ++s1->include_stack_ptr;
1858 /* add include file debug info */
1859 if (s1->do_debug)
1860 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1861 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1862 ch = file->buf_ptr[0];
1863 goto the_end;
1865 tcc_error("include file '%s' not found", buf);
1866 include_done:
1867 break;
1868 case TOK_IFNDEF:
1869 c = 1;
1870 goto do_ifdef;
1871 case TOK_IF:
1872 c = expr_preprocess();
1873 goto do_if;
1874 case TOK_IFDEF:
1875 c = 0;
1876 do_ifdef:
1877 next_nomacro();
1878 if (tok < TOK_IDENT)
1879 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1880 if (is_bof) {
1881 if (c) {
1882 #ifdef INC_DEBUG
1883 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1884 #endif
1885 file->ifndef_macro = tok;
1888 c = (define_find(tok) != 0) ^ c;
1889 do_if:
1890 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1891 tcc_error("memory full (ifdef)");
1892 *s1->ifdef_stack_ptr++ = c;
1893 goto test_skip;
1894 case TOK_ELSE:
1895 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1896 tcc_error("#else without matching #if");
1897 if (s1->ifdef_stack_ptr[-1] & 2)
1898 tcc_error("#else after #else");
1899 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1900 goto test_else;
1901 case TOK_ELIF:
1902 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1903 tcc_error("#elif without matching #if");
1904 c = s1->ifdef_stack_ptr[-1];
1905 if (c > 1)
1906 tcc_error("#elif after #else");
1907 /* last #if/#elif expression was true: we skip */
1908 if (c == 1) {
1909 c = 0;
1910 } else {
1911 c = expr_preprocess();
1912 s1->ifdef_stack_ptr[-1] = c;
1914 test_else:
1915 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1916 file->ifndef_macro = 0;
1917 test_skip:
1918 if (!(c & 1)) {
1919 preprocess_skip();
1920 is_bof = 0;
1921 goto redo;
1923 break;
1924 case TOK_ENDIF:
1925 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1926 tcc_error("#endif without matching #if");
1927 s1->ifdef_stack_ptr--;
1928 /* '#ifndef macro' was at the start of file. Now we check if
1929 an '#endif' is exactly at the end of file */
1930 if (file->ifndef_macro &&
1931 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1932 file->ifndef_macro_saved = file->ifndef_macro;
1933 /* need to set to zero to avoid false matches if another
1934 #ifndef at middle of file */
1935 file->ifndef_macro = 0;
1936 while (tok != TOK_LINEFEED)
1937 next_nomacro();
1938 tok_flags |= TOK_FLAG_ENDIF;
1939 goto the_end;
1941 break;
1942 case TOK_PPNUM:
1943 n = strtoul((char*)tokc.str.data, &q, 10);
1944 goto _line_num;
1945 case TOK_LINE:
1946 next();
1947 if (tok != TOK_CINT)
1948 _line_err:
1949 tcc_error("wrong #line format");
1950 n = tokc.i;
1951 _line_num:
1952 next();
1953 if (tok != TOK_LINEFEED) {
1954 if (tok == TOK_STR) {
1955 if (file->true_filename == file->filename)
1956 file->true_filename = tcc_strdup(file->filename);
1957 pstrcpy(file->filename, sizeof(file->filename), (char *)tokc.str.data);
1958 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
1959 break;
1960 else
1961 goto _line_err;
1962 --n;
1964 if (file->fd > 0)
1965 total_lines += file->line_num - n;
1966 file->line_num = n;
1967 if (s1->do_debug)
1968 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1969 break;
1970 case TOK_ERROR:
1971 case TOK_WARNING:
1972 c = tok;
1973 ch = file->buf_ptr[0];
1974 skip_spaces();
1975 q = buf;
1976 while (ch != '\n' && ch != CH_EOF) {
1977 if ((q - buf) < sizeof(buf) - 1)
1978 *q++ = ch;
1979 if (ch == '\\') {
1980 if (handle_stray_noerror() == 0)
1981 --q;
1982 } else
1983 inp();
1985 *q = '\0';
1986 if (c == TOK_ERROR)
1987 tcc_error("#error %s", buf);
1988 else
1989 tcc_warning("#warning %s", buf);
1990 break;
1991 case TOK_PRAGMA:
1992 pragma_parse(s1);
1993 break;
1994 case TOK_LINEFEED:
1995 goto the_end;
1996 default:
1997 /* ignore gas line comment in an 'S' file. */
1998 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1999 goto ignore;
2000 if (tok == '!' && is_bof)
2001 /* '!' is ignored at beginning to allow C scripts. */
2002 goto ignore;
2003 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
2004 ignore:
2005 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
2006 goto the_end;
2008 /* ignore other preprocess commands or #! for C scripts */
2009 while (tok != TOK_LINEFEED)
2010 next_nomacro();
2011 the_end:
2012 parse_flags = saved_parse_flags;
2015 /* evaluate escape codes in a string. */
2016 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
2018 int c, n;
2019 const uint8_t *p;
2021 p = buf;
2022 for(;;) {
2023 c = *p;
2024 if (c == '\0')
2025 break;
2026 if (c == '\\') {
2027 p++;
2028 /* escape */
2029 c = *p;
2030 switch(c) {
2031 case '0': case '1': case '2': case '3':
2032 case '4': case '5': case '6': case '7':
2033 /* at most three octal digits */
2034 n = c - '0';
2035 p++;
2036 c = *p;
2037 if (isoct(c)) {
2038 n = n * 8 + c - '0';
2039 p++;
2040 c = *p;
2041 if (isoct(c)) {
2042 n = n * 8 + c - '0';
2043 p++;
2046 c = n;
2047 goto add_char_nonext;
2048 case 'x':
2049 case 'u':
2050 case 'U':
2051 p++;
2052 n = 0;
2053 for(;;) {
2054 c = *p;
2055 if (c >= 'a' && c <= 'f')
2056 c = c - 'a' + 10;
2057 else if (c >= 'A' && c <= 'F')
2058 c = c - 'A' + 10;
2059 else if (isnum(c))
2060 c = c - '0';
2061 else
2062 break;
2063 n = n * 16 + c;
2064 p++;
2066 c = n;
2067 goto add_char_nonext;
2068 case 'a':
2069 c = '\a';
2070 break;
2071 case 'b':
2072 c = '\b';
2073 break;
2074 case 'f':
2075 c = '\f';
2076 break;
2077 case 'n':
2078 c = '\n';
2079 break;
2080 case 'r':
2081 c = '\r';
2082 break;
2083 case 't':
2084 c = '\t';
2085 break;
2086 case 'v':
2087 c = '\v';
2088 break;
2089 case 'e':
2090 if (!gnu_ext)
2091 goto invalid_escape;
2092 c = 27;
2093 break;
2094 case '\'':
2095 case '\"':
2096 case '\\':
2097 case '?':
2098 break;
2099 default:
2100 invalid_escape:
2101 if (c >= '!' && c <= '~')
2102 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2103 else
2104 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2105 break;
2108 p++;
2109 add_char_nonext:
2110 if (!is_long)
2111 cstr_ccat(outstr, c);
2112 else
2113 cstr_wccat(outstr, c);
2115 /* add a trailing '\0' */
2116 if (!is_long)
2117 cstr_ccat(outstr, '\0');
2118 else
2119 cstr_wccat(outstr, '\0');
2122 static void parse_string(const char *s, int len)
2124 uint8_t buf[1000], *p = buf;
2125 int is_long, sep;
2127 if ((is_long = *s == 'L'))
2128 ++s, --len;
2129 sep = *s++;
2130 len -= 2;
2131 if (len >= sizeof buf)
2132 p = tcc_malloc(len + 1);
2133 memcpy(p, s, len);
2134 p[len] = 0;
2136 cstr_reset(&tokcstr);
2137 parse_escape_string(&tokcstr, p, is_long);
2138 if (p != buf)
2139 tcc_free(p);
2141 if (sep == '\'') {
2142 int char_size;
2143 /* XXX: make it portable */
2144 if (!is_long)
2145 char_size = 1;
2146 else
2147 char_size = sizeof(nwchar_t);
2148 if (tokcstr.size <= char_size)
2149 tcc_error("empty character constant");
2150 if (tokcstr.size > 2 * char_size)
2151 tcc_warning("multi-character character constant");
2152 if (!is_long) {
2153 tokc.i = *(int8_t *)tokcstr.data;
2154 tok = TOK_CCHAR;
2155 } else {
2156 tokc.i = *(nwchar_t *)tokcstr.data;
2157 tok = TOK_LCHAR;
2159 } else {
2160 tokc.str.size = tokcstr.size;
2161 tokc.str.data = tokcstr.data;
2162 if (!is_long)
2163 tok = TOK_STR;
2164 else
2165 tok = TOK_LSTR;
2169 /* we use 64 bit numbers */
2170 #define BN_SIZE 2
2172 /* bn = (bn << shift) | or_val */
2173 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2175 int i;
2176 unsigned int v;
2177 for(i=0;i<BN_SIZE;i++) {
2178 v = bn[i];
2179 bn[i] = (v << shift) | or_val;
2180 or_val = v >> (32 - shift);
2184 static void bn_zero(unsigned int *bn)
2186 int i;
2187 for(i=0;i<BN_SIZE;i++) {
2188 bn[i] = 0;
2192 /* parse number in null terminated string 'p' and return it in the
2193 current token */
2194 static void parse_number(const char *p)
2196 int b, t, shift, frac_bits, s, exp_val, ch;
2197 char *q;
2198 unsigned int bn[BN_SIZE];
2199 double d;
2201 /* number */
2202 q = token_buf;
2203 ch = *p++;
2204 t = ch;
2205 ch = *p++;
2206 *q++ = t;
2207 b = 10;
2208 if (t == '.') {
2209 goto float_frac_parse;
2210 } else if (t == '0') {
2211 if (ch == 'x' || ch == 'X') {
2212 q--;
2213 ch = *p++;
2214 b = 16;
2215 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
2216 q--;
2217 ch = *p++;
2218 b = 2;
2221 /* parse all digits. cannot check octal numbers at this stage
2222 because of floating point constants */
2223 while (1) {
2224 if (ch >= 'a' && ch <= 'f')
2225 t = ch - 'a' + 10;
2226 else if (ch >= 'A' && ch <= 'F')
2227 t = ch - 'A' + 10;
2228 else if (isnum(ch))
2229 t = ch - '0';
2230 else
2231 break;
2232 if (t >= b)
2233 break;
2234 if (q >= token_buf + STRING_MAX_SIZE) {
2235 num_too_long:
2236 tcc_error("number too long");
2238 *q++ = ch;
2239 ch = *p++;
2241 if (ch == '.' ||
2242 ((ch == 'e' || ch == 'E') && b == 10) ||
2243 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2244 if (b != 10) {
2245 /* NOTE: strtox should support that for hexa numbers, but
2246 non ISOC99 libcs do not support it, so we prefer to do
2247 it by hand */
2248 /* hexadecimal or binary floats */
2249 /* XXX: handle overflows */
2250 *q = '\0';
2251 if (b == 16)
2252 shift = 4;
2253 else
2254 shift = 1;
2255 bn_zero(bn);
2256 q = token_buf;
2257 while (1) {
2258 t = *q++;
2259 if (t == '\0') {
2260 break;
2261 } else if (t >= 'a') {
2262 t = t - 'a' + 10;
2263 } else if (t >= 'A') {
2264 t = t - 'A' + 10;
2265 } else {
2266 t = t - '0';
2268 bn_lshift(bn, shift, t);
2270 frac_bits = 0;
2271 if (ch == '.') {
2272 ch = *p++;
2273 while (1) {
2274 t = ch;
2275 if (t >= 'a' && t <= 'f') {
2276 t = t - 'a' + 10;
2277 } else if (t >= 'A' && t <= 'F') {
2278 t = t - 'A' + 10;
2279 } else if (t >= '0' && t <= '9') {
2280 t = t - '0';
2281 } else {
2282 break;
2284 if (t >= b)
2285 tcc_error("invalid digit");
2286 bn_lshift(bn, shift, t);
2287 frac_bits += shift;
2288 ch = *p++;
2291 if (ch != 'p' && ch != 'P')
2292 expect("exponent");
2293 ch = *p++;
2294 s = 1;
2295 exp_val = 0;
2296 if (ch == '+') {
2297 ch = *p++;
2298 } else if (ch == '-') {
2299 s = -1;
2300 ch = *p++;
2302 if (ch < '0' || ch > '9')
2303 expect("exponent digits");
2304 while (ch >= '0' && ch <= '9') {
2305 exp_val = exp_val * 10 + ch - '0';
2306 ch = *p++;
2308 exp_val = exp_val * s;
2310 /* now we can generate the number */
2311 /* XXX: should patch directly float number */
2312 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2313 d = ldexp(d, exp_val - frac_bits);
2314 t = toup(ch);
2315 if (t == 'F') {
2316 ch = *p++;
2317 tok = TOK_CFLOAT;
2318 /* float : should handle overflow */
2319 tokc.f = (float)d;
2320 } else if (t == 'L') {
2321 ch = *p++;
2322 #ifdef TCC_TARGET_PE
2323 tok = TOK_CDOUBLE;
2324 tokc.d = d;
2325 #else
2326 tok = TOK_CLDOUBLE;
2327 /* XXX: not large enough */
2328 tokc.ld = (long double)d;
2329 #endif
2330 } else {
2331 tok = TOK_CDOUBLE;
2332 tokc.d = d;
2334 } else {
2335 /* decimal floats */
2336 if (ch == '.') {
2337 if (q >= token_buf + STRING_MAX_SIZE)
2338 goto num_too_long;
2339 *q++ = ch;
2340 ch = *p++;
2341 float_frac_parse:
2342 while (ch >= '0' && ch <= '9') {
2343 if (q >= token_buf + STRING_MAX_SIZE)
2344 goto num_too_long;
2345 *q++ = ch;
2346 ch = *p++;
2349 if (ch == 'e' || ch == 'E') {
2350 if (q >= token_buf + STRING_MAX_SIZE)
2351 goto num_too_long;
2352 *q++ = ch;
2353 ch = *p++;
2354 if (ch == '-' || ch == '+') {
2355 if (q >= token_buf + STRING_MAX_SIZE)
2356 goto num_too_long;
2357 *q++ = ch;
2358 ch = *p++;
2360 if (ch < '0' || ch > '9')
2361 expect("exponent digits");
2362 while (ch >= '0' && ch <= '9') {
2363 if (q >= token_buf + STRING_MAX_SIZE)
2364 goto num_too_long;
2365 *q++ = ch;
2366 ch = *p++;
2369 *q = '\0';
2370 t = toup(ch);
2371 errno = 0;
2372 if (t == 'F') {
2373 ch = *p++;
2374 tok = TOK_CFLOAT;
2375 tokc.f = strtof(token_buf, NULL);
2376 } else if (t == 'L') {
2377 ch = *p++;
2378 #ifdef TCC_TARGET_PE
2379 tok = TOK_CDOUBLE;
2380 tokc.d = strtod(token_buf, NULL);
2381 #else
2382 tok = TOK_CLDOUBLE;
2383 tokc.ld = strtold(token_buf, NULL);
2384 #endif
2385 } else {
2386 tok = TOK_CDOUBLE;
2387 tokc.d = strtod(token_buf, NULL);
2390 } else {
2391 unsigned long long n, n1;
2392 int lcount, ucount, must_64bit;
2393 const char *p1;
2395 /* integer number */
2396 *q = '\0';
2397 q = token_buf;
2398 if (b == 10 && *q == '0') {
2399 b = 8;
2400 q++;
2402 n = 0;
2403 while(1) {
2404 t = *q++;
2405 /* no need for checks except for base 10 / 8 errors */
2406 if (t == '\0')
2407 break;
2408 else if (t >= 'a')
2409 t = t - 'a' + 10;
2410 else if (t >= 'A')
2411 t = t - 'A' + 10;
2412 else
2413 t = t - '0';
2414 if (t >= b)
2415 tcc_error("invalid digit");
2416 n1 = n;
2417 n = n * b + t;
2418 /* detect overflow */
2419 /* XXX: this test is not reliable */
2420 if (n < n1)
2421 tcc_error("integer constant overflow");
2424 /* Determine the characteristics (unsigned and/or 64bit) the type of
2425 the constant must have according to the constant suffix(es) */
2426 lcount = ucount = must_64bit = 0;
2427 p1 = p;
2428 for(;;) {
2429 t = toup(ch);
2430 if (t == 'L') {
2431 if (lcount >= 2)
2432 tcc_error("three 'l's in integer constant");
2433 if (lcount && *(p - 1) != ch)
2434 tcc_error("incorrect integer suffix: %s", p1);
2435 lcount++;
2436 if (lcount == 2)
2437 must_64bit = 1;
2438 ch = *p++;
2439 } else if (t == 'U') {
2440 if (ucount >= 1)
2441 tcc_error("two 'u's in integer constant");
2442 ucount++;
2443 ch = *p++;
2444 } else {
2445 break;
2449 /* Whether 64 bits are needed to hold the constant's value */
2450 if (n & 0xffffffff00000000LL || must_64bit) {
2451 tok = TOK_CLLONG;
2452 n1 = n >> 32;
2453 } else if (lcount) {
2454 #ifdef TCC_LONG_ARE_64_BIT
2455 n1 = n >> 32;
2456 #else
2457 n1 = n;
2458 #endif
2459 tok = TOK_CLONG;
2460 } else {
2461 tok = TOK_CINT;
2462 n1 = n;
2465 /* Whether type must be unsigned to hold the constant's value */
2466 if (ucount || ((n1 >> 31) && (b != 10))) {
2467 if (tok == TOK_CLLONG)
2468 tok = TOK_CULLONG;
2469 else if (tok == TOK_CLONG)
2470 tok = TOK_CULONG;
2471 else
2472 tok = TOK_CUINT;
2473 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2474 } else if (n1 >> 31) {
2475 if (tok == TOK_CINT)
2476 tok = TOK_CLLONG;
2477 else
2478 tcc_error("integer constant overflow");
2481 tokc.i = n;
2483 if (ch)
2484 tcc_error("invalid number\n");
2488 #define PARSE2(c1, tok1, c2, tok2) \
2489 case c1: \
2490 PEEKC(c, p); \
2491 if (c == c2) { \
2492 p++; \
2493 tok = tok2; \
2494 } else { \
2495 tok = tok1; \
2497 break;
2499 /* return next token without macro substitution */
2500 static inline void next_nomacro1(void)
2502 int t, c, is_long, len;
2503 TokenSym *ts;
2504 uint8_t *p, *p1;
2505 unsigned int h;
2507 p = file->buf_ptr;
2508 redo_no_start:
2509 c = *p;
2510 switch(c) {
2511 case ' ':
2512 case '\t':
2513 tok = c;
2514 p++;
2515 if (parse_flags & PARSE_FLAG_SPACES)
2516 goto keep_tok_flags;
2517 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2518 ++p;
2519 goto redo_no_start;
2520 case '\f':
2521 case '\v':
2522 case '\r':
2523 p++;
2524 goto redo_no_start;
2525 case '\\':
2526 /* first look if it is in fact an end of buffer */
2527 c = handle_stray1(p);
2528 p = file->buf_ptr;
2529 if (c == '\\')
2530 goto parse_simple;
2531 if (c != CH_EOF)
2532 goto redo_no_start;
2534 TCCState *s1 = tcc_state;
2535 if ((parse_flags & PARSE_FLAG_LINEFEED)
2536 && !(tok_flags & TOK_FLAG_EOF)) {
2537 tok_flags |= TOK_FLAG_EOF;
2538 tok = TOK_LINEFEED;
2539 goto keep_tok_flags;
2540 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2541 tok = TOK_EOF;
2542 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2543 tcc_error("missing #endif");
2544 } else if (s1->include_stack_ptr == s1->include_stack) {
2545 /* no include left : end of file. */
2546 tok = TOK_EOF;
2547 } else {
2548 tok_flags &= ~TOK_FLAG_EOF;
2549 /* pop include file */
2551 /* test if previous '#endif' was after a #ifdef at
2552 start of file */
2553 if (tok_flags & TOK_FLAG_ENDIF) {
2554 #ifdef INC_DEBUG
2555 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2556 #endif
2557 search_cached_include(s1, file->filename, 1)
2558 ->ifndef_macro = file->ifndef_macro_saved;
2559 tok_flags &= ~TOK_FLAG_ENDIF;
2562 /* add end of include file debug info */
2563 if (tcc_state->do_debug) {
2564 put_stabd(N_EINCL, 0, 0);
2566 /* pop include stack */
2567 tcc_close();
2568 s1->include_stack_ptr--;
2569 p = file->buf_ptr;
2570 goto redo_no_start;
2573 break;
2575 case '\n':
2576 file->line_num++;
2577 tok_flags |= TOK_FLAG_BOL;
2578 p++;
2579 maybe_newline:
2580 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2581 goto redo_no_start;
2582 tok = TOK_LINEFEED;
2583 goto keep_tok_flags;
2585 case '#':
2586 /* XXX: simplify */
2587 PEEKC(c, p);
2588 if ((tok_flags & TOK_FLAG_BOL) &&
2589 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2590 file->buf_ptr = p;
2591 preprocess(tok_flags & TOK_FLAG_BOF);
2592 p = file->buf_ptr;
2593 goto maybe_newline;
2594 } else {
2595 if (c == '#') {
2596 p++;
2597 tok = TOK_TWOSHARPS;
2598 } else {
2599 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2600 p = parse_line_comment(p - 1);
2601 goto redo_no_start;
2602 } else {
2603 tok = '#';
2607 break;
2609 /* dollar is allowed to start identifiers when not parsing asm */
2610 case '$':
2611 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2612 || (parse_flags & PARSE_FLAG_ASM_FILE))
2613 goto parse_simple;
2615 case 'a': case 'b': case 'c': case 'd':
2616 case 'e': case 'f': case 'g': case 'h':
2617 case 'i': case 'j': case 'k': case 'l':
2618 case 'm': case 'n': case 'o': case 'p':
2619 case 'q': case 'r': case 's': case 't':
2620 case 'u': case 'v': case 'w': case 'x':
2621 case 'y': case 'z':
2622 case 'A': case 'B': case 'C': case 'D':
2623 case 'E': case 'F': case 'G': case 'H':
2624 case 'I': case 'J': case 'K':
2625 case 'M': case 'N': case 'O': case 'P':
2626 case 'Q': case 'R': case 'S': case 'T':
2627 case 'U': case 'V': case 'W': case 'X':
2628 case 'Y': case 'Z':
2629 case '_':
2630 parse_ident_fast:
2631 p1 = p;
2632 h = TOK_HASH_INIT;
2633 h = TOK_HASH_FUNC(h, c);
2634 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2635 h = TOK_HASH_FUNC(h, c);
2636 len = p - p1;
2637 if (c != '\\') {
2638 TokenSym **pts;
2640 /* fast case : no stray found, so we have the full token
2641 and we have already hashed it */
2642 h &= (TOK_HASH_SIZE - 1);
2643 pts = &hash_ident[h];
2644 for(;;) {
2645 ts = *pts;
2646 if (!ts)
2647 break;
2648 if (ts->len == len && !memcmp(ts->str, p1, len))
2649 goto token_found;
2650 pts = &(ts->hash_next);
2652 ts = tok_alloc_new(pts, (char *) p1, len);
2653 token_found: ;
2654 } else {
2655 /* slower case */
2656 cstr_reset(&tokcstr);
2657 cstr_cat(&tokcstr, (char *) p1, len);
2658 p--;
2659 PEEKC(c, p);
2660 parse_ident_slow:
2661 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2663 cstr_ccat(&tokcstr, c);
2664 PEEKC(c, p);
2666 ts = tok_alloc(tokcstr.data, tokcstr.size);
2668 tok = ts->tok;
2669 break;
2670 case 'L':
2671 t = p[1];
2672 if (t != '\\' && t != '\'' && t != '\"') {
2673 /* fast case */
2674 goto parse_ident_fast;
2675 } else {
2676 PEEKC(c, p);
2677 if (c == '\'' || c == '\"') {
2678 is_long = 1;
2679 goto str_const;
2680 } else {
2681 cstr_reset(&tokcstr);
2682 cstr_ccat(&tokcstr, 'L');
2683 goto parse_ident_slow;
2686 break;
2688 case '0': case '1': case '2': case '3':
2689 case '4': case '5': case '6': case '7':
2690 case '8': case '9':
2691 t = c;
2692 PEEKC(c, p);
2693 /* after the first digit, accept digits, alpha, '.' or sign if
2694 prefixed by 'eEpP' */
2695 parse_num:
2696 cstr_reset(&tokcstr);
2697 for(;;) {
2698 cstr_ccat(&tokcstr, t);
2699 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2700 || c == '.'
2701 || ((c == '+' || c == '-')
2702 && (((t == 'e' || t == 'E')
2703 && !(parse_flags & PARSE_FLAG_ASM_FILE
2704 /* 0xe+1 is 3 tokens in asm */
2705 && ((char*)tokcstr.data)[0] == '0'
2706 && toup(((char*)tokcstr.data)[1]) == 'X'))
2707 || t == 'p' || t == 'P'))))
2708 break;
2709 t = c;
2710 PEEKC(c, p);
2712 /* We add a trailing '\0' to ease parsing */
2713 cstr_ccat(&tokcstr, '\0');
2714 tokc.str.size = tokcstr.size;
2715 tokc.str.data = tokcstr.data;
2716 tok = TOK_PPNUM;
2717 break;
2719 case '.':
2720 /* special dot handling because it can also start a number */
2721 PEEKC(c, p);
2722 if (isnum(c)) {
2723 t = '.';
2724 goto parse_num;
2725 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2726 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2727 *--p = c = '.';
2728 goto parse_ident_fast;
2729 } else if (c == '.') {
2730 PEEKC(c, p);
2731 if (c == '.') {
2732 p++;
2733 tok = TOK_DOTS;
2734 } else {
2735 *--p = '.'; /* may underflow into file->unget[] */
2736 tok = '.';
2738 } else {
2739 tok = '.';
2741 break;
2742 case '\'':
2743 case '\"':
2744 is_long = 0;
2745 str_const:
2746 cstr_reset(&tokcstr);
2747 if (is_long)
2748 cstr_ccat(&tokcstr, 'L');
2749 cstr_ccat(&tokcstr, c);
2750 p = parse_pp_string(p, c, &tokcstr);
2751 cstr_ccat(&tokcstr, c);
2752 cstr_ccat(&tokcstr, '\0');
2753 tokc.str.size = tokcstr.size;
2754 tokc.str.data = tokcstr.data;
2755 tok = TOK_PPSTR;
2756 break;
2758 case '<':
2759 PEEKC(c, p);
2760 if (c == '=') {
2761 p++;
2762 tok = TOK_LE;
2763 } else if (c == '<') {
2764 PEEKC(c, p);
2765 if (c == '=') {
2766 p++;
2767 tok = TOK_A_SHL;
2768 } else {
2769 tok = TOK_SHL;
2771 } else {
2772 tok = TOK_LT;
2774 break;
2775 case '>':
2776 PEEKC(c, p);
2777 if (c == '=') {
2778 p++;
2779 tok = TOK_GE;
2780 } else if (c == '>') {
2781 PEEKC(c, p);
2782 if (c == '=') {
2783 p++;
2784 tok = TOK_A_SAR;
2785 } else {
2786 tok = TOK_SAR;
2788 } else {
2789 tok = TOK_GT;
2791 break;
2793 case '&':
2794 PEEKC(c, p);
2795 if (c == '&') {
2796 p++;
2797 tok = TOK_LAND;
2798 } else if (c == '=') {
2799 p++;
2800 tok = TOK_A_AND;
2801 } else {
2802 tok = '&';
2804 break;
2806 case '|':
2807 PEEKC(c, p);
2808 if (c == '|') {
2809 p++;
2810 tok = TOK_LOR;
2811 } else if (c == '=') {
2812 p++;
2813 tok = TOK_A_OR;
2814 } else {
2815 tok = '|';
2817 break;
2819 case '+':
2820 PEEKC(c, p);
2821 if (c == '+') {
2822 p++;
2823 tok = TOK_INC;
2824 } else if (c == '=') {
2825 p++;
2826 tok = TOK_A_ADD;
2827 } else {
2828 tok = '+';
2830 break;
2832 case '-':
2833 PEEKC(c, p);
2834 if (c == '-') {
2835 p++;
2836 tok = TOK_DEC;
2837 } else if (c == '=') {
2838 p++;
2839 tok = TOK_A_SUB;
2840 } else if (c == '>') {
2841 p++;
2842 tok = TOK_ARROW;
2843 } else {
2844 tok = '-';
2846 break;
2848 PARSE2('!', '!', '=', TOK_NE)
2849 PARSE2('=', '=', '=', TOK_EQ)
2850 PARSE2('*', '*', '=', TOK_A_MUL)
2851 PARSE2('%', '%', '=', TOK_A_MOD)
2852 PARSE2('^', '^', '=', TOK_A_XOR)
2854 /* comments or operator */
2855 case '/':
2856 PEEKC(c, p);
2857 if (c == '*') {
2858 p = parse_comment(p);
2859 /* comments replaced by a blank */
2860 tok = ' ';
2861 goto keep_tok_flags;
2862 } else if (c == '/') {
2863 p = parse_line_comment(p);
2864 tok = ' ';
2865 goto keep_tok_flags;
2866 } else if (c == '=') {
2867 p++;
2868 tok = TOK_A_DIV;
2869 } else {
2870 tok = '/';
2872 break;
2874 /* simple tokens */
2875 case '(':
2876 case ')':
2877 case '[':
2878 case ']':
2879 case '{':
2880 case '}':
2881 case ',':
2882 case ';':
2883 case ':':
2884 case '?':
2885 case '~':
2886 case '@': /* only used in assembler */
2887 parse_simple:
2888 tok = c;
2889 p++;
2890 break;
2891 default:
2892 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2893 goto parse_ident_fast;
2894 if (parse_flags & PARSE_FLAG_ASM_FILE)
2895 goto parse_simple;
2896 tcc_error("unrecognized character \\x%02x", c);
2897 break;
2899 tok_flags = 0;
2900 keep_tok_flags:
2901 file->buf_ptr = p;
2902 #if defined(PARSE_DEBUG)
2903 printf("token = %s\n", get_tok_str(tok, &tokc));
2904 #endif
2907 /* return next token without macro substitution. Can read input from
2908 macro_ptr buffer */
2909 static void next_nomacro_spc(void)
2911 if (macro_ptr) {
2912 redo:
2913 tok = *macro_ptr;
2914 if (tok) {
2915 TOK_GET(&tok, &macro_ptr, &tokc);
2916 if (tok == TOK_LINENUM) {
2917 file->line_num = tokc.i;
2918 goto redo;
2921 } else {
2922 next_nomacro1();
2924 //printf("token = %s\n", get_tok_str(tok, &tokc));
2927 ST_FUNC void next_nomacro(void)
2929 do {
2930 next_nomacro_spc();
2931 } while (tok < 256 && (isidnum_table[tok - CH_EOF] & IS_SPC));
2935 static void macro_subst(
2936 TokenString *tok_str,
2937 Sym **nested_list,
2938 const int *macro_str
2941 /* substitute arguments in replacement lists in macro_str by the values in
2942 args (field d) and return allocated string */
2943 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2945 int t, t0, t1, spc;
2946 const int *st;
2947 Sym *s;
2948 CValue cval;
2949 TokenString str;
2950 CString cstr;
2952 tok_str_new(&str);
2953 t0 = t1 = 0;
2954 while(1) {
2955 TOK_GET(&t, &macro_str, &cval);
2956 if (!t)
2957 break;
2958 if (t == '#') {
2959 /* stringize */
2960 TOK_GET(&t, &macro_str, &cval);
2961 if (!t)
2962 goto bad_stringy;
2963 s = sym_find2(args, t);
2964 if (s) {
2965 cstr_new(&cstr);
2966 cstr_ccat(&cstr, '\"');
2967 st = s->d;
2968 spc = 0;
2969 while (*st >= 0) {
2970 TOK_GET(&t, &st, &cval);
2971 if (t != TOK_PLCHLDR
2972 && t != TOK_NOSUBST
2973 && 0 == check_space(t, &spc)) {
2974 const char *s = get_tok_str(t, &cval);
2975 while (*s) {
2976 if (t == TOK_PPSTR && *s != '\'')
2977 add_char(&cstr, *s);
2978 else
2979 cstr_ccat(&cstr, *s);
2980 ++s;
2984 cstr.size -= spc;
2985 cstr_ccat(&cstr, '\"');
2986 cstr_ccat(&cstr, '\0');
2987 #ifdef PP_DEBUG
2988 printf("\nstringize: <%s>\n", (char *)cstr.data);
2989 #endif
2990 /* add string */
2991 cval.str.size = cstr.size;
2992 cval.str.data = cstr.data;
2993 tok_str_add2(&str, TOK_PPSTR, &cval);
2994 cstr_free(&cstr);
2995 } else {
2996 bad_stringy:
2997 expect("macro parameter after '#'");
2999 } else if (t >= TOK_IDENT) {
3000 s = sym_find2(args, t);
3001 if (s) {
3002 int l0 = str.len;
3003 st = s->d;
3004 /* if '##' is present before or after, no arg substitution */
3005 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
3006 /* special case for var arg macros : ## eats the ','
3007 if empty VA_ARGS variable. */
3008 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
3009 if (*st <= 0) {
3010 /* suppress ',' '##' */
3011 str.len -= 2;
3012 } else {
3013 /* suppress '##' and add variable */
3014 str.len--;
3015 goto add_var;
3018 } else {
3019 add_var:
3020 if (!s->next) {
3021 /* Expand arguments tokens and store them. In most
3022 cases we could also re-expand each argument if
3023 used multiple times, but not if the argument
3024 contains the __COUNTER__ macro. */
3025 TokenString str2;
3026 sym_push2(&s->next, s->v, s->type.t, 0);
3027 tok_str_new(&str2);
3028 macro_subst(&str2, nested_list, st);
3029 tok_str_add(&str2, 0);
3030 s->next->d = str2.str;
3032 st = s->next->d;
3034 for(;;) {
3035 int t2;
3036 TOK_GET(&t2, &st, &cval);
3037 if (t2 <= 0)
3038 break;
3039 tok_str_add2(&str, t2, &cval);
3041 if (str.len == l0) /* expanded to empty string */
3042 tok_str_add(&str, TOK_PLCHLDR);
3043 } else {
3044 tok_str_add(&str, t);
3046 } else {
3047 tok_str_add2(&str, t, &cval);
3049 t0 = t1, t1 = t;
3051 tok_str_add(&str, 0);
3052 return str.str;
3055 static char const ab_month_name[12][4] =
3057 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3058 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3061 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3063 CString cstr;
3064 int n, ret = 1;
3066 cstr_new(&cstr);
3067 if (t1 != TOK_PLCHLDR)
3068 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3069 n = cstr.size;
3070 if (t2 != TOK_PLCHLDR)
3071 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3072 cstr_ccat(&cstr, '\0');
3074 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3075 memcpy(file->buffer, cstr.data, cstr.size);
3076 tok_flags = 0;
3077 for (;;) {
3078 next_nomacro1();
3079 if (0 == *file->buf_ptr)
3080 break;
3081 if (is_space(tok))
3082 continue;
3083 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3084 " preprocessing token", n, cstr.data, (char*)cstr.data + n);
3085 ret = 0;
3086 break;
3088 tcc_close();
3089 //printf("paste <%s>\n", (char*)cstr.data);
3090 cstr_free(&cstr);
3091 return ret;
3094 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3095 return the resulting string (which must be freed). */
3096 static inline int *macro_twosharps(const int *ptr0)
3098 int t;
3099 CValue cval;
3100 TokenString macro_str1;
3101 int start_of_nosubsts = -1;
3102 const int *ptr;
3104 /* we search the first '##' */
3105 for (ptr = ptr0;;) {
3106 TOK_GET(&t, &ptr, &cval);
3107 if (t == TOK_PPJOIN)
3108 break;
3109 if (t == 0)
3110 return NULL;
3113 tok_str_new(&macro_str1);
3115 //tok_print(" $$$", ptr0);
3116 for (ptr = ptr0;;) {
3117 TOK_GET(&t, &ptr, &cval);
3118 if (t == 0)
3119 break;
3120 if (t == TOK_PPJOIN)
3121 continue;
3122 while (*ptr == TOK_PPJOIN) {
3123 int t1; CValue cv1;
3124 /* given 'a##b', remove nosubsts preceding 'a' */
3125 if (start_of_nosubsts >= 0)
3126 macro_str1.len = start_of_nosubsts;
3127 /* given 'a##b', remove nosubsts preceding 'b' */
3128 while ((t1 = *++ptr) == TOK_NOSUBST)
3130 if (t1 && t1 != TOK_PPJOIN) {
3131 TOK_GET(&t1, &ptr, &cv1);
3132 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3133 if (paste_tokens(t, &cval, t1, &cv1)) {
3134 t = tok, cval = tokc;
3135 } else {
3136 tok_str_add2(&macro_str1, t, &cval);
3137 t = t1, cval = cv1;
3142 if (t == TOK_NOSUBST) {
3143 if (start_of_nosubsts < 0)
3144 start_of_nosubsts = macro_str1.len;
3145 } else {
3146 start_of_nosubsts = -1;
3148 tok_str_add2(&macro_str1, t, &cval);
3150 tok_str_add(&macro_str1, 0);
3151 //tok_print(" ###", macro_str1.str);
3152 return macro_str1.str;
3155 /* peek or read [ws_str == NULL] next token from function macro call,
3156 walking up macro levels up to the file if necessary */
3157 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3159 int t;
3160 const int *p;
3161 Sym *sa;
3163 for (;;) {
3164 if (macro_ptr) {
3165 p = macro_ptr, t = *p;
3166 if (ws_str) {
3167 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3168 tok_str_add(ws_str, t), t = *++p;
3170 if (t == 0) {
3171 end_macro();
3172 /* also, end of scope for nested defined symbol */
3173 sa = *nested_list;
3174 while (sa && sa->v == 0)
3175 sa = sa->prev;
3176 if (sa)
3177 sa->v = 0;
3178 continue;
3180 } else {
3181 ch = handle_eob();
3182 if (ws_str) {
3183 while (is_space(ch) || ch == '\n' || ch == '/') {
3184 if (ch == '/') {
3185 int c;
3186 uint8_t *p = file->buf_ptr;
3187 PEEKC(c, p);
3188 if (c == '*') {
3189 p = parse_comment(p);
3190 file->buf_ptr = p - 1;
3191 } else if (c == '/') {
3192 p = parse_line_comment(p);
3193 file->buf_ptr = p - 1;
3194 } else
3195 break;
3196 ch = ' ';
3198 if (ch == '\n')
3199 file->line_num++;
3200 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3201 tok_str_add(ws_str, ch);
3202 cinp();
3205 t = ch;
3208 if (ws_str)
3209 return t;
3210 next_nomacro_spc();
3211 return tok;
3215 /* do macro substitution of current token with macro 's' and add
3216 result to (tok_str,tok_len). 'nested_list' is the list of all
3217 macros we got inside to avoid recursing. Return non zero if no
3218 substitution needs to be done */
3219 static int macro_subst_tok(
3220 TokenString *tok_str,
3221 Sym **nested_list,
3222 Sym *s)
3224 Sym *args, *sa, *sa1;
3225 int parlevel, *mstr, t, t1, spc;
3226 TokenString str;
3227 char *cstrval;
3228 CValue cval;
3229 CString cstr;
3230 char buf[32];
3231 static int counter;
3233 /* if symbol is a macro, prepare substitution */
3234 /* special macros */
3235 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3236 t = tok == TOK___LINE__ ? file->line_num : counter++;
3237 snprintf(buf, sizeof(buf), "%d", t);
3238 cstrval = buf;
3239 t1 = TOK_PPNUM;
3240 goto add_cstr1;
3241 } else if (tok == TOK___FILE__) {
3242 cstrval = file->filename;
3243 goto add_cstr;
3244 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3245 time_t ti;
3246 struct tm *tm;
3248 time(&ti);
3249 tm = localtime(&ti);
3250 if (tok == TOK___DATE__) {
3251 snprintf(buf, sizeof(buf), "%s %2d %d",
3252 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3253 } else {
3254 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3255 tm->tm_hour, tm->tm_min, tm->tm_sec);
3257 cstrval = buf;
3258 add_cstr:
3259 t1 = TOK_STR;
3260 add_cstr1:
3261 cstr_new(&cstr);
3262 cstr_cat(&cstr, cstrval, 0);
3263 cval.str.size = cstr.size;
3264 cval.str.data = cstr.data;
3265 tok_str_add2(tok_str, t1, &cval);
3266 cstr_free(&cstr);
3267 } else {
3268 int saved_parse_flags = parse_flags;
3269 int *joined_str = NULL;
3271 mstr = s->d;
3272 if (s->type.t == MACRO_FUNC) {
3273 /* whitespace between macro name and argument list */
3274 TokenString ws_str;
3275 tok_str_new(&ws_str);
3277 spc = 0;
3278 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3279 | PARSE_FLAG_ACCEPT_STRAYS;
3281 /* get next token from argument stream */
3282 t = next_argstream(nested_list, &ws_str);
3283 if (t != '(') {
3284 /* not a macro substitution after all, restore the
3285 * macro token plus all whitespace we've read.
3286 * whitespace is intentionally not merged to preserve
3287 * newlines. */
3288 parse_flags = saved_parse_flags;
3289 tok_str_add(tok_str, tok);
3290 if (parse_flags & PARSE_FLAG_SPACES) {
3291 int i;
3292 for (i = 0; i < ws_str.len; i++)
3293 tok_str_add(tok_str, ws_str.str[i]);
3295 tok_str_free_str(ws_str.str);
3296 return 0;
3297 } else {
3298 tok_str_free_str(ws_str.str);
3300 do {
3301 next_nomacro(); /* eat '(' */
3302 } while (tok == TOK_PLCHLDR);
3304 /* argument macro */
3305 args = NULL;
3306 sa = s->next;
3307 /* NOTE: empty args are allowed, except if no args */
3308 for(;;) {
3309 do {
3310 next_argstream(nested_list, NULL);
3311 } while (is_space(tok) || TOK_LINEFEED == tok);
3312 empty_arg:
3313 /* handle '()' case */
3314 if (!args && !sa && tok == ')')
3315 break;
3316 if (!sa)
3317 tcc_error("macro '%s' used with too many args",
3318 get_tok_str(s->v, 0));
3319 tok_str_new(&str);
3320 parlevel = spc = 0;
3321 /* NOTE: non zero sa->t indicates VA_ARGS */
3322 while ((parlevel > 0 ||
3323 (tok != ')' &&
3324 (tok != ',' || sa->type.t)))) {
3325 if (tok == TOK_EOF || tok == 0)
3326 break;
3327 if (tok == '(')
3328 parlevel++;
3329 else if (tok == ')')
3330 parlevel--;
3331 if (tok == TOK_LINEFEED)
3332 tok = ' ';
3333 if (!check_space(tok, &spc))
3334 tok_str_add2(&str, tok, &tokc);
3335 next_argstream(nested_list, NULL);
3337 if (parlevel)
3338 expect(")");
3339 str.len -= spc;
3340 tok_str_add(&str, -1);
3341 tok_str_add(&str, 0);
3342 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3343 sa1->d = str.str;
3344 sa = sa->next;
3345 if (tok == ')') {
3346 /* special case for gcc var args: add an empty
3347 var arg argument if it is omitted */
3348 if (sa && sa->type.t && gnu_ext)
3349 goto empty_arg;
3350 break;
3352 if (tok != ',')
3353 expect(",");
3355 if (sa) {
3356 tcc_error("macro '%s' used with too few args",
3357 get_tok_str(s->v, 0));
3360 parse_flags = saved_parse_flags;
3362 /* now subst each arg */
3363 mstr = macro_arg_subst(nested_list, mstr, args);
3364 /* free memory */
3365 sa = args;
3366 while (sa) {
3367 sa1 = sa->prev;
3368 tok_str_free_str(sa->d);
3369 if (sa->next) {
3370 tok_str_free_str(sa->next->d);
3371 sym_free(sa->next);
3373 sym_free(sa);
3374 sa = sa1;
3378 sym_push2(nested_list, s->v, 0, 0);
3379 parse_flags = saved_parse_flags;
3380 joined_str = macro_twosharps(mstr);
3381 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3383 /* pop nested defined symbol */
3384 sa1 = *nested_list;
3385 *nested_list = sa1->prev;
3386 sym_free(sa1);
3387 if (joined_str)
3388 tok_str_free_str(joined_str);
3389 if (mstr != s->d)
3390 tok_str_free_str(mstr);
3392 return 0;
3395 /* do macro substitution of macro_str and add result to
3396 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3397 inside to avoid recursing. */
3398 static void macro_subst(
3399 TokenString *tok_str,
3400 Sym **nested_list,
3401 const int *macro_str
3404 Sym *s;
3405 int t, spc, nosubst;
3406 CValue cval;
3408 spc = nosubst = 0;
3410 while (1) {
3411 TOK_GET(&t, &macro_str, &cval);
3412 if (t <= 0)
3413 break;
3415 if (t >= TOK_IDENT && 0 == nosubst) {
3416 s = define_find(t);
3417 if (s == NULL)
3418 goto no_subst;
3420 /* if nested substitution, do nothing */
3421 if (sym_find2(*nested_list, t)) {
3422 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3423 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3424 goto no_subst;
3428 TokenString str;
3429 str.str = (int*)macro_str;
3430 begin_macro(&str, 2);
3432 tok = t;
3433 macro_subst_tok(tok_str, nested_list, s);
3435 if (str.alloc == 3) {
3436 /* already finished by reading function macro arguments */
3437 break;
3440 macro_str = macro_ptr;
3441 end_macro ();
3443 if (tok_str->len)
3444 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3445 } else {
3446 if (t == '\\' && !(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3447 tcc_error("stray '\\' in program");
3448 no_subst:
3449 if (!check_space(t, &spc))
3450 tok_str_add2(tok_str, t, &cval);
3452 if (nosubst) {
3453 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3454 continue;
3455 nosubst = 0;
3457 if (t == TOK_NOSUBST)
3458 nosubst = 1;
3460 /* GCC supports 'defined' as result of a macto substitution */
3461 if (t == TOK_DEFINED && pp_expr)
3462 nosubst = 2;
3466 /* return next token with macro substitution */
3467 ST_FUNC void next(void)
3469 redo:
3470 if (parse_flags & PARSE_FLAG_SPACES)
3471 next_nomacro_spc();
3472 else
3473 next_nomacro();
3475 if (macro_ptr) {
3476 if (tok == TOK_NOSUBST || tok == TOK_PLCHLDR) {
3477 /* discard preprocessor markers */
3478 goto redo;
3479 } else if (tok == 0) {
3480 /* end of macro or unget token string */
3481 end_macro();
3482 goto redo;
3484 } else if (tok >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3485 Sym *s;
3486 /* if reading from file, try to substitute macros */
3487 s = define_find(tok);
3488 if (s) {
3489 Sym *nested_list = NULL;
3490 tokstr_buf.len = 0;
3491 macro_subst_tok(&tokstr_buf, &nested_list, s);
3492 tok_str_add(&tokstr_buf, 0);
3493 begin_macro(&tokstr_buf, 2);
3494 goto redo;
3497 /* convert preprocessor tokens into C tokens */
3498 if (tok == TOK_PPNUM) {
3499 if (parse_flags & PARSE_FLAG_TOK_NUM)
3500 parse_number((char *)tokc.str.data);
3501 } else if (tok == TOK_PPSTR) {
3502 if (parse_flags & PARSE_FLAG_TOK_STR)
3503 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3507 /* push back current token and set current token to 'last_tok'. Only
3508 identifier case handled for labels. */
3509 ST_INLN void unget_tok(int last_tok)
3512 TokenString *str = tok_str_alloc();
3513 tok_str_add2(str, tok, &tokc);
3514 tok_str_add(str, 0);
3515 begin_macro(str, 1);
3516 tok = last_tok;
3519 ST_FUNC void preprocess_start(TCCState *s1, int is_asm)
3521 char *buf;
3523 s1->include_stack_ptr = s1->include_stack;
3524 s1->ifdef_stack_ptr = s1->ifdef_stack;
3525 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3526 pp_once++;
3527 pvtop = vtop = vstack - 1;
3528 s1->pack_stack[0] = 0;
3529 s1->pack_stack_ptr = s1->pack_stack;
3531 set_idnum('$', s1->dollars_in_identifiers ? IS_ID : 0);
3532 set_idnum('.', is_asm ? IS_ID : 0);
3534 buf = tcc_malloc(3 + strlen(file->filename));
3535 sprintf(buf, "\"%s\"", file->filename);
3536 tcc_define_symbol(s1, "__BASE_FILE__", buf);
3537 tcc_free(buf);
3539 if (s1->nb_cmd_include_files) {
3540 CString cstr;
3541 int i;
3542 cstr_new(&cstr);
3543 for (i = 0; i < s1->nb_cmd_include_files; i++) {
3544 cstr_cat(&cstr, "#include \"", -1);
3545 cstr_cat(&cstr, s1->cmd_include_files[i], -1);
3546 cstr_cat(&cstr, "\"\n", -1);
3548 *s1->include_stack_ptr++ = file;
3549 tcc_open_bf(s1, "<command line>", cstr.size);
3550 memcpy(file->buffer, cstr.data, cstr.size);
3551 cstr_free(&cstr);
3554 if (is_asm)
3555 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
3557 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3558 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3561 /* cleanup from error/setjmp */
3562 ST_FUNC void preprocess_end(TCCState *s1)
3564 while (macro_stack)
3565 end_macro();
3566 macro_ptr = NULL;
3569 ST_FUNC void tccpp_new(TCCState *s)
3571 int i, c;
3572 const char *p, *r;
3574 /* might be used in error() before preprocess_start() */
3575 s->include_stack_ptr = s->include_stack;
3576 s->ppfp = stdout;
3578 /* init isid table */
3579 for(i = CH_EOF; i<128; i++)
3580 set_idnum(i,
3581 is_space(i) ? IS_SPC
3582 : isid(i) ? IS_ID
3583 : isnum(i) ? IS_NUM
3584 : 0);
3586 for(i = 128; i<256; i++)
3587 set_idnum(i, IS_ID);
3589 /* init allocators */
3590 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3591 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3592 tal_new(&cstr_alloc, CSTR_TAL_LIMIT, CSTR_TAL_SIZE);
3594 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3595 cstr_new(&cstr_buf);
3596 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3597 tok_str_new(&tokstr_buf);
3598 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3600 tok_ident = TOK_IDENT;
3601 p = tcc_keywords;
3602 while (*p) {
3603 r = p;
3604 for(;;) {
3605 c = *r++;
3606 if (c == '\0')
3607 break;
3609 tok_alloc(p, r - p - 1);
3610 p = r;
3614 ST_FUNC void tccpp_delete(TCCState *s)
3616 int i, n;
3618 /* free -D and compiler defines */
3619 free_defines(NULL);
3621 /* free tokens */
3622 n = tok_ident - TOK_IDENT;
3623 for(i = 0; i < n; i++)
3624 tal_free(toksym_alloc, table_ident[i]);
3625 tcc_free(table_ident);
3626 table_ident = NULL;
3628 /* free static buffers */
3629 cstr_free(&tokcstr);
3630 cstr_free(&cstr_buf);
3631 cstr_free(&macro_equal_buf);
3632 tok_str_free_str(tokstr_buf.str);
3634 /* free allocators */
3635 tal_delete(toksym_alloc);
3636 toksym_alloc = NULL;
3637 tal_delete(tokstr_alloc);
3638 tokstr_alloc = NULL;
3639 tal_delete(cstr_alloc);
3640 cstr_alloc = NULL;
3643 /* ------------------------------------------------------------------------- */
3644 /* tcc -E [-P[1]] [-dD} support */
3646 static void tok_print(const char *msg, const int *str)
3648 FILE *fp;
3649 int t, s = 0;
3650 CValue cval;
3652 fp = tcc_state->ppfp;
3653 fprintf(fp, "%s", msg);
3654 while (str) {
3655 TOK_GET(&t, &str, &cval);
3656 if (!t)
3657 break;
3658 fprintf(fp, " %s" + s, get_tok_str(t, &cval)), s = 1;
3660 fprintf(fp, "\n");
3663 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3665 int d = f->line_num - f->line_ref;
3667 if (s1->dflag & 4)
3668 return;
3670 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3672 } else if (level == 0 && f->line_ref && d < 8) {
3673 while (d > 0)
3674 fputs("\n", s1->ppfp), --d;
3675 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3676 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3677 } else {
3678 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3679 level > 0 ? " 1" : level < 0 ? " 2" : "");
3681 f->line_ref = f->line_num;
3684 static void define_print(TCCState *s1, int v)
3686 FILE *fp;
3687 Sym *s;
3689 s = define_find(v);
3690 if (NULL == s || NULL == s->d)
3691 return;
3693 fp = s1->ppfp;
3694 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3695 if (s->type.t == MACRO_FUNC) {
3696 Sym *a = s->next;
3697 fprintf(fp,"(");
3698 if (a)
3699 for (;;) {
3700 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3701 if (!(a = a->next))
3702 break;
3703 fprintf(fp,",");
3705 fprintf(fp,")");
3707 tok_print("", s->d);
3710 static void pp_debug_defines(TCCState *s1)
3712 int v, t;
3713 const char *vs;
3714 FILE *fp;
3716 t = pp_debug_tok;
3717 if (t == 0)
3718 return;
3720 file->line_num--;
3721 pp_line(s1, file, 0);
3722 file->line_ref = ++file->line_num;
3724 fp = s1->ppfp;
3725 v = pp_debug_symv;
3726 vs = get_tok_str(v, NULL);
3727 if (t == TOK_DEFINE) {
3728 define_print(s1, v);
3729 } else if (t == TOK_UNDEF) {
3730 fprintf(fp, "#undef %s\n", vs);
3731 } else if (t == TOK_push_macro) {
3732 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3733 } else if (t == TOK_pop_macro) {
3734 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3736 pp_debug_tok = 0;
3739 static void pp_debug_builtins(TCCState *s1)
3741 int v;
3742 for (v = TOK_IDENT; v < tok_ident; ++v)
3743 define_print(s1, v);
3746 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3747 static int pp_need_space(int a, int b)
3749 return 'E' == a ? '+' == b || '-' == b
3750 : '+' == a ? TOK_INC == b || '+' == b
3751 : '-' == a ? TOK_DEC == b || '-' == b
3752 : a >= TOK_IDENT ? b >= TOK_IDENT
3753 : a == TOK_PPNUM ? b >= TOK_IDENT
3754 : 0;
3757 /* maybe hex like 0x1e */
3758 static int pp_check_he0xE(int t, const char *p)
3760 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3761 return 'E';
3762 return t;
3765 /* Preprocess the current file */
3766 ST_FUNC int tcc_preprocess(TCCState *s1)
3768 BufferedFile **iptr;
3769 int token_seen, spcs, level;
3770 const char *p;
3771 char white[400];
3773 parse_flags = PARSE_FLAG_PREPROCESS
3774 | (parse_flags & PARSE_FLAG_ASM_FILE)
3775 | PARSE_FLAG_LINEFEED
3776 | PARSE_FLAG_SPACES
3777 | PARSE_FLAG_ACCEPT_STRAYS
3779 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3780 capability to compile and run itself, provided all numbers are
3781 given as decimals. tcc -E -P10 will do. */
3782 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3783 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3785 #ifdef PP_BENCH
3786 /* for PP benchmarks */
3787 do next(); while (tok != TOK_EOF);
3788 return 0;
3789 #endif
3791 if (s1->dflag & 1) {
3792 pp_debug_builtins(s1);
3793 s1->dflag &= ~1;
3796 token_seen = TOK_LINEFEED, spcs = 0;
3797 pp_line(s1, file, 0);
3798 for (;;) {
3799 iptr = s1->include_stack_ptr;
3800 next();
3801 if (tok == TOK_EOF)
3802 break;
3804 level = s1->include_stack_ptr - iptr;
3805 if (level) {
3806 if (level > 0)
3807 pp_line(s1, *iptr, 0);
3808 pp_line(s1, file, level);
3810 if (s1->dflag & 7) {
3811 pp_debug_defines(s1);
3812 if (s1->dflag & 4)
3813 continue;
3816 if (is_space(tok)) {
3817 if (spcs < sizeof white - 1)
3818 white[spcs++] = tok;
3819 continue;
3820 } else if (tok == TOK_LINEFEED) {
3821 spcs = 0;
3822 if (token_seen == TOK_LINEFEED)
3823 continue;
3824 ++file->line_ref;
3825 } else if (token_seen == TOK_LINEFEED) {
3826 pp_line(s1, file, 0);
3827 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
3828 white[spcs++] = ' ';
3831 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
3832 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
3833 token_seen = pp_check_he0xE(tok, p);
3835 return 0;
3838 /* ------------------------------------------------------------------------- */