update changelog
[tinycc.git] / tccpp.c
blob6322e8b8969e9d303631209da7dab81340938098
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 /* #define to 1 to enable (see parse_pp_string()) */
25 #define ACCEPT_LF_IN_STRINGS 0
27 /********************************************************/
28 /* global variables */
30 ST_DATA int tok_flags;
31 ST_DATA int parse_flags;
33 ST_DATA struct BufferedFile *file;
34 ST_DATA int tok;
35 ST_DATA CValue tokc;
36 ST_DATA const int *macro_ptr;
37 ST_DATA CString tokcstr; /* current parsed string, if any */
39 /* display benchmark infos */
40 ST_DATA int tok_ident;
41 ST_DATA TokenSym **table_ident;
43 /* ------------------------------------------------------------------------- */
45 static TokenSym *hash_ident[TOK_HASH_SIZE];
46 static char token_buf[STRING_MAX_SIZE + 1];
47 static CString cstr_buf;
48 static CString macro_equal_buf;
49 static TokenString tokstr_buf;
50 static unsigned char isidnum_table[256 - CH_EOF];
51 static int pp_debug_tok, pp_debug_symv;
52 static int pp_once;
53 static int pp_expr;
54 static int pp_counter;
55 static void tok_print(const char *msg, const int *str);
57 static struct TinyAlloc *toksym_alloc;
58 static struct TinyAlloc *tokstr_alloc;
60 static TokenString *macro_stack;
62 static const char tcc_keywords[] =
63 #define DEF(id, str) str "\0"
64 #include "tcctok.h"
65 #undef DEF
68 /* WARNING: the content of this string encodes token numbers */
69 static const unsigned char tok_two_chars[] =
70 /* outdated -- gr
71 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
72 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
73 */{
74 '<','=', TOK_LE,
75 '>','=', TOK_GE,
76 '!','=', TOK_NE,
77 '&','&', TOK_LAND,
78 '|','|', TOK_LOR,
79 '+','+', TOK_INC,
80 '-','-', TOK_DEC,
81 '=','=', TOK_EQ,
82 '<','<', TOK_SHL,
83 '>','>', TOK_SAR,
84 '+','=', TOK_A_ADD,
85 '-','=', TOK_A_SUB,
86 '*','=', TOK_A_MUL,
87 '/','=', TOK_A_DIV,
88 '%','=', TOK_A_MOD,
89 '&','=', TOK_A_AND,
90 '^','=', TOK_A_XOR,
91 '|','=', TOK_A_OR,
92 '-','>', TOK_ARROW,
93 '.','.', TOK_TWODOTS,
94 '#','#', TOK_TWOSHARPS,
95 '#','#', TOK_PPJOIN,
99 static void next_nomacro(void);
101 ST_FUNC void skip(int c)
103 if (tok != c)
104 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
105 next();
108 ST_FUNC void expect(const char *msg)
110 tcc_error("%s expected", msg);
113 /* ------------------------------------------------------------------------- */
114 /* Custom allocator for tiny objects */
116 #define USE_TAL
118 #ifndef USE_TAL
119 #define tal_free(al, p) tcc_free(p)
120 #define tal_realloc(al, p, size) tcc_realloc(p, size)
121 #define tal_new(a,b,c)
122 #define tal_delete(a)
123 #else
124 #if !defined(MEM_DEBUG)
125 #define tal_free(al, p) tal_free_impl(al, p)
126 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
127 #define TAL_DEBUG_PARAMS
128 #else
129 #define TAL_DEBUG 1
130 //#define TAL_INFO 1 /* collect and dump allocators stats */
131 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
132 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
133 #define TAL_DEBUG_PARAMS , const char *file, int line
134 #define TAL_DEBUG_FILE_LEN 40
135 #endif
137 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
138 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
139 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
140 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
141 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
142 #define CSTR_TAL_LIMIT 1024
144 typedef struct TinyAlloc {
145 unsigned limit;
146 unsigned size;
147 uint8_t *buffer;
148 uint8_t *p;
149 unsigned nb_allocs;
150 struct TinyAlloc *next, *top;
151 #ifdef TAL_INFO
152 unsigned nb_peak;
153 unsigned nb_total;
154 unsigned nb_missed;
155 uint8_t *peak_p;
156 #endif
157 } TinyAlloc;
159 typedef struct tal_header_t {
160 unsigned size;
161 #ifdef TAL_DEBUG
162 int line_num; /* negative line_num used for double free check */
163 char file_name[TAL_DEBUG_FILE_LEN + 1];
164 #endif
165 } tal_header_t;
167 /* ------------------------------------------------------------------------- */
169 static TinyAlloc *tal_new(TinyAlloc **pal, unsigned limit, unsigned size)
171 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
172 al->p = al->buffer = tcc_malloc(size);
173 al->limit = limit;
174 al->size = size;
175 if (pal) *pal = al;
176 return al;
179 static void tal_delete(TinyAlloc *al)
181 TinyAlloc *next;
183 tail_call:
184 if (!al)
185 return;
186 #ifdef TAL_INFO
187 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
188 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
189 (al->peak_p - al->buffer) * 100.0 / al->size);
190 #endif
191 #ifdef TAL_DEBUG
192 if (al->nb_allocs > 0) {
193 uint8_t *p;
194 fprintf(stderr, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
195 al->nb_allocs, al->limit);
196 p = al->buffer;
197 while (p < al->p) {
198 tal_header_t *header = (tal_header_t *)p;
199 if (header->line_num > 0) {
200 fprintf(stderr, "%s:%d: chunk of %d bytes leaked\n",
201 header->file_name, header->line_num, header->size);
203 p += header->size + sizeof(tal_header_t);
205 #if MEM_DEBUG-0 == 2
206 exit(2);
207 #endif
209 #endif
210 next = al->next;
211 tcc_free(al->buffer);
212 tcc_free(al);
213 al = next;
214 goto tail_call;
217 static void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
219 if (!p)
220 return;
221 tail_call:
222 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
223 #ifdef TAL_DEBUG
224 tal_header_t *header = (((tal_header_t *)p) - 1);
225 if (header->line_num < 0) {
226 fprintf(stderr, "%s:%d: TAL_DEBUG: double frees chunk from\n",
227 file, line);
228 fprintf(stderr, "%s:%d: %d bytes\n",
229 header->file_name, (int)-header->line_num, (int)header->size);
230 } else
231 header->line_num = -header->line_num;
232 #endif
233 al->nb_allocs--;
234 if (!al->nb_allocs)
235 al->p = al->buffer;
236 } else if (al->next) {
237 al = al->next;
238 goto tail_call;
240 else
241 tcc_free(p);
244 static void *tal_realloc_impl(TinyAlloc **pal, void *p, unsigned size TAL_DEBUG_PARAMS)
246 tal_header_t *header;
247 void *ret;
248 int is_own;
249 unsigned adj_size = (size + 3) & -4;
250 TinyAlloc *al = *pal;
252 tail_call:
253 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
254 if ((!p || is_own) && size <= al->limit) {
255 if (al->p - al->buffer + adj_size + sizeof(tal_header_t) < al->size) {
256 header = (tal_header_t *)al->p;
257 header->size = adj_size;
258 #ifdef TAL_DEBUG
259 { int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
260 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
261 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
262 header->line_num = line; }
263 #endif
264 ret = al->p + sizeof(tal_header_t);
265 al->p += adj_size + sizeof(tal_header_t);
266 if (is_own) {
267 header = (((tal_header_t *)p) - 1);
268 if (p) memcpy(ret, p, header->size);
269 #ifdef TAL_DEBUG
270 header->line_num = -header->line_num;
271 #endif
272 } else {
273 al->nb_allocs++;
275 #ifdef TAL_INFO
276 if (al->nb_peak < al->nb_allocs)
277 al->nb_peak = al->nb_allocs;
278 if (al->peak_p < al->p)
279 al->peak_p = al->p;
280 al->nb_total++;
281 #endif
282 return ret;
283 } else if (is_own) {
284 al->nb_allocs--;
285 ret = tal_realloc(*pal, 0, size);
286 header = (((tal_header_t *)p) - 1);
287 if (p) memcpy(ret, p, header->size);
288 #ifdef TAL_DEBUG
289 header->line_num = -header->line_num;
290 #endif
291 return ret;
293 if (al->next) {
294 al = al->next;
295 } else {
296 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
298 al = tal_new(pal, next->limit, next->size * 2);
299 al->next = next;
300 bottom->top = al;
302 goto tail_call;
304 if (is_own) {
305 al->nb_allocs--;
306 ret = tcc_malloc(size);
307 header = (((tal_header_t *)p) - 1);
308 if (p) memcpy(ret, p, header->size);
309 #ifdef TAL_DEBUG
310 header->line_num = -header->line_num;
311 #endif
312 } else if (al->next) {
313 al = al->next;
314 goto tail_call;
315 } else
316 ret = tcc_realloc(p, size);
317 #ifdef TAL_INFO
318 al->nb_missed++;
319 #endif
320 return ret;
323 #endif /* USE_TAL */
325 /* ------------------------------------------------------------------------- */
326 /* CString handling */
327 static void cstr_realloc(CString *cstr, int new_size)
329 int size;
331 size = cstr->size_allocated;
332 if (size < 8)
333 size = 8; /* no need to allocate a too small first string */
334 while (size < new_size)
335 size = size * 2;
336 cstr->data = tcc_realloc(cstr->data, size);
337 cstr->size_allocated = size;
340 /* add a byte */
341 ST_INLN void cstr_ccat(CString *cstr, int ch)
343 int size;
344 size = cstr->size + 1;
345 if (size > cstr->size_allocated)
346 cstr_realloc(cstr, size);
347 ((unsigned char *)cstr->data)[size - 1] = ch;
348 cstr->size = size;
351 ST_INLN char *unicode_to_utf8 (char *b, uint32_t Uc)
353 if (Uc<0x80) *b++=Uc;
354 else if (Uc<0x800) *b++=192+Uc/64, *b++=128+Uc%64;
355 else if (Uc-0xd800u<0x800) goto error;
356 else if (Uc<0x10000) *b++=224+Uc/4096, *b++=128+Uc/64%64, *b++=128+Uc%64;
357 else if (Uc<0x110000) *b++=240+Uc/262144, *b++=128+Uc/4096%64, *b++=128+Uc/64%64, *b++=128+Uc%64;
358 else error: tcc_error("0x%x is not a valid universal character", Uc);
359 return b;
362 /* add a unicode character expanded into utf8 */
363 ST_INLN void cstr_u8cat(CString *cstr, int ch)
365 char buf[4], *e;
366 e = unicode_to_utf8(buf, (uint32_t)ch);
367 cstr_cat(cstr, buf, e - buf);
370 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
372 int size;
373 if (len <= 0)
374 len = strlen(str) + 1 + len;
375 size = cstr->size + len;
376 if (size > cstr->size_allocated)
377 cstr_realloc(cstr, size);
378 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
379 cstr->size = size;
382 /* add a wide char */
383 ST_FUNC void cstr_wccat(CString *cstr, int ch)
385 int size;
386 size = cstr->size + sizeof(nwchar_t);
387 if (size > cstr->size_allocated)
388 cstr_realloc(cstr, size);
389 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
390 cstr->size = size;
393 ST_FUNC void cstr_new(CString *cstr)
395 memset(cstr, 0, sizeof(CString));
398 /* free string and reset it to NULL */
399 ST_FUNC void cstr_free(CString *cstr)
401 tcc_free(cstr->data);
402 cstr_new(cstr);
405 /* reset string to empty */
406 ST_FUNC void cstr_reset(CString *cstr)
408 cstr->size = 0;
411 ST_FUNC int cstr_vprintf(CString *cstr, const char *fmt, va_list ap)
413 va_list v;
414 int len, size = 80;
415 for (;;) {
416 size += cstr->size;
417 if (size > cstr->size_allocated)
418 cstr_realloc(cstr, size);
419 size = cstr->size_allocated - cstr->size;
420 va_copy(v, ap);
421 len = vsnprintf((char*)cstr->data + cstr->size, size, fmt, v);
422 va_end(v);
423 if (len >= 0 && len < size)
424 break;
425 size *= 2;
427 cstr->size += len;
428 return len;
431 ST_FUNC int cstr_printf(CString *cstr, const char *fmt, ...)
433 va_list ap; int len;
434 va_start(ap, fmt);
435 len = cstr_vprintf(cstr, fmt, ap);
436 va_end(ap);
437 return len;
440 /* XXX: unicode ? */
441 static void add_char(CString *cstr, int c)
443 if (c == '\'' || c == '\"' || c == '\\') {
444 /* XXX: could be more precise if char or string */
445 cstr_ccat(cstr, '\\');
447 if (c >= 32 && c <= 126) {
448 cstr_ccat(cstr, c);
449 } else {
450 cstr_ccat(cstr, '\\');
451 if (c == '\n') {
452 cstr_ccat(cstr, 'n');
453 } else {
454 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
455 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
456 cstr_ccat(cstr, '0' + (c & 7));
461 /* ------------------------------------------------------------------------- */
462 /* allocate a new token */
463 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
465 TokenSym *ts, **ptable;
466 int i;
468 if (tok_ident >= SYM_FIRST_ANOM)
469 tcc_error("memory full (symbols)");
471 /* expand token table if needed */
472 i = tok_ident - TOK_IDENT;
473 if ((i % TOK_ALLOC_INCR) == 0) {
474 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
475 table_ident = ptable;
478 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
479 table_ident[i] = ts;
480 ts->tok = tok_ident++;
481 ts->sym_define = NULL;
482 ts->sym_label = NULL;
483 ts->sym_struct = NULL;
484 ts->sym_identifier = NULL;
485 ts->len = len;
486 ts->hash_next = NULL;
487 memcpy(ts->str, str, len);
488 ts->str[len] = '\0';
489 *pts = ts;
490 return ts;
493 #define TOK_HASH_INIT 1
494 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
497 /* find a token and add it if not found */
498 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
500 TokenSym *ts, **pts;
501 int i;
502 unsigned int h;
504 h = TOK_HASH_INIT;
505 for(i=0;i<len;i++)
506 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
507 h &= (TOK_HASH_SIZE - 1);
509 pts = &hash_ident[h];
510 for(;;) {
511 ts = *pts;
512 if (!ts)
513 break;
514 if (ts->len == len && !memcmp(ts->str, str, len))
515 return ts;
516 pts = &(ts->hash_next);
518 return tok_alloc_new(pts, str, len);
521 ST_FUNC int tok_alloc_const(const char *str)
523 return tok_alloc(str, strlen(str))->tok;
527 /* XXX: buffer overflow */
528 /* XXX: float tokens */
529 ST_FUNC const char *get_tok_str(int v, CValue *cv)
531 char *p;
532 int i, len;
534 cstr_reset(&cstr_buf);
535 p = cstr_buf.data;
537 switch(v) {
538 case TOK_CINT:
539 case TOK_CUINT:
540 case TOK_CLONG:
541 case TOK_CULONG:
542 case TOK_CLLONG:
543 case TOK_CULLONG:
544 /* XXX: not quite exact, but only useful for testing */
545 #ifdef _WIN32
546 sprintf(p, "%u", (unsigned)cv->i);
547 #else
548 sprintf(p, "%llu", (unsigned long long)cv->i);
549 #endif
550 break;
551 case TOK_LCHAR:
552 cstr_ccat(&cstr_buf, 'L');
553 case TOK_CCHAR:
554 cstr_ccat(&cstr_buf, '\'');
555 add_char(&cstr_buf, cv->i);
556 cstr_ccat(&cstr_buf, '\'');
557 cstr_ccat(&cstr_buf, '\0');
558 break;
559 case TOK_PPNUM:
560 case TOK_PPSTR:
561 return (char*)cv->str.data;
562 case TOK_LSTR:
563 cstr_ccat(&cstr_buf, 'L');
564 case TOK_STR:
565 cstr_ccat(&cstr_buf, '\"');
566 if (v == TOK_STR) {
567 len = cv->str.size - 1;
568 for(i=0;i<len;i++)
569 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
570 } else {
571 len = (cv->str.size / sizeof(nwchar_t)) - 1;
572 for(i=0;i<len;i++)
573 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
575 cstr_ccat(&cstr_buf, '\"');
576 cstr_ccat(&cstr_buf, '\0');
577 break;
579 case TOK_CFLOAT:
580 cstr_cat(&cstr_buf, "<float>", 0);
581 break;
582 case TOK_CDOUBLE:
583 cstr_cat(&cstr_buf, "<double>", 0);
584 break;
585 case TOK_CLDOUBLE:
586 cstr_cat(&cstr_buf, "<long double>", 0);
587 break;
588 case TOK_LINENUM:
589 cstr_cat(&cstr_buf, "<linenumber>", 0);
590 break;
592 /* above tokens have value, the ones below don't */
593 case TOK_LT:
594 v = '<';
595 goto addv;
596 case TOK_GT:
597 v = '>';
598 goto addv;
599 case TOK_DOTS:
600 return strcpy(p, "...");
601 case TOK_A_SHL:
602 return strcpy(p, "<<=");
603 case TOK_A_SAR:
604 return strcpy(p, ">>=");
605 case TOK_EOF:
606 return strcpy(p, "<eof>");
607 default:
608 if (v < TOK_IDENT) {
609 /* search in two bytes table */
610 const unsigned char *q = tok_two_chars;
611 while (*q) {
612 if (q[2] == v) {
613 *p++ = q[0];
614 *p++ = q[1];
615 *p = '\0';
616 return cstr_buf.data;
618 q += 3;
620 if (v >= 127) {
621 sprintf(cstr_buf.data, "<%02x>", v);
622 return cstr_buf.data;
624 addv:
625 *p++ = v;
626 case 0: /* nameless anonymous symbol */
627 *p = '\0';
628 } else if (v < tok_ident) {
629 return table_ident[v - TOK_IDENT]->str;
630 } else if (v >= SYM_FIRST_ANOM) {
631 /* special name for anonymous symbol */
632 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
633 } else {
634 /* should never happen */
635 return NULL;
637 break;
639 return cstr_buf.data;
642 static inline int check_space(int t, int *spc)
644 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
645 if (*spc)
646 return 1;
647 *spc = 1;
648 } else
649 *spc = 0;
650 return 0;
653 /* return the current character, handling end of block if necessary
654 (but not stray) */
655 static int handle_eob(void)
657 BufferedFile *bf = file;
658 int len;
660 /* only tries to read if really end of buffer */
661 if (bf->buf_ptr >= bf->buf_end) {
662 if (bf->fd >= 0) {
663 #if defined(PARSE_DEBUG)
664 len = 1;
665 #else
666 len = IO_BUF_SIZE;
667 #endif
668 len = read(bf->fd, bf->buffer, len);
669 if (len < 0)
670 len = 0;
671 } else {
672 len = 0;
674 total_bytes += len;
675 bf->buf_ptr = bf->buffer;
676 bf->buf_end = bf->buffer + len;
677 *bf->buf_end = CH_EOB;
679 if (bf->buf_ptr < bf->buf_end) {
680 return bf->buf_ptr[0];
681 } else {
682 bf->buf_ptr = bf->buf_end;
683 return CH_EOF;
687 /* read next char from current input file and handle end of input buffer */
688 static int next_c(void)
690 int ch = *++file->buf_ptr;
691 /* end of buffer/file handling */
692 if (ch == CH_EOB && file->buf_ptr >= file->buf_end)
693 ch = handle_eob();
694 return ch;
697 /* input with '\[\r]\n' handling. */
698 static int handle_stray_noerror(int err)
700 int ch;
701 while ((ch = next_c()) == '\\') {
702 ch = next_c();
703 if (ch == '\n') {
704 newl:
705 file->line_num++;
706 } else {
707 if (ch == '\r') {
708 ch = next_c();
709 if (ch == '\n')
710 goto newl;
711 *--file->buf_ptr = '\r';
713 if (err)
714 tcc_error("stray '\\' in program");
715 /* may take advantage of 'BufferedFile.unget[4}' */
716 return *--file->buf_ptr = '\\';
719 return ch;
722 #define ninp() handle_stray_noerror(0)
724 /* handle '\\' in strings, comments and skipped regions */
725 static int handle_bs(uint8_t **p)
727 int c;
728 file->buf_ptr = *p - 1;
729 c = ninp();
730 *p = file->buf_ptr;
731 return c;
734 /* skip the stray and handle the \\n case. Output an error if
735 incorrect char after the stray */
736 static int handle_stray(uint8_t **p)
738 int c;
739 file->buf_ptr = *p - 1;
740 c = handle_stray_noerror(!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS));
741 *p = file->buf_ptr;
742 return c;
745 /* handle the complicated stray case */
746 #define PEEKC(c, p)\
748 c = *++p;\
749 if (c == '\\')\
750 c = handle_stray(&p); \
753 static int skip_spaces(void)
755 int ch;
756 --file->buf_ptr;
757 do {
758 ch = ninp();
759 } while (isidnum_table[ch - CH_EOF] & IS_SPC);
760 return ch;
763 /* single line C++ comments */
764 static uint8_t *parse_line_comment(uint8_t *p)
766 int c;
767 for(;;) {
768 for (;;) {
769 c = *++p;
770 redo:
771 if (c == '\n' || c == '\\')
772 break;
773 c = *++p;
774 if (c == '\n' || c == '\\')
775 break;
777 if (c == '\n')
778 break;
779 c = handle_bs(&p);
780 if (c == CH_EOF)
781 break;
782 if (c != '\\')
783 goto redo;
785 return p;
788 /* C comments */
789 static uint8_t *parse_comment(uint8_t *p)
791 int c;
792 for(;;) {
793 /* fast skip loop */
794 for(;;) {
795 c = *++p;
796 redo:
797 if (c == '\n' || c == '*' || c == '\\')
798 break;
799 c = *++p;
800 if (c == '\n' || c == '*' || c == '\\')
801 break;
803 /* now we can handle all the cases */
804 if (c == '\n') {
805 file->line_num++;
806 } else if (c == '*') {
807 do {
808 c = *++p;
809 } while (c == '*');
810 if (c == '\\')
811 c = handle_bs(&p);
812 if (c == '/')
813 break;
814 goto check_eof;
815 } else {
816 c = handle_bs(&p);
817 check_eof:
818 if (c == CH_EOF)
819 tcc_error("unexpected end of file in comment");
820 if (c != '\\')
821 goto redo;
824 return p + 1;
827 /* parse a string without interpreting escapes */
828 static uint8_t *parse_pp_string(uint8_t *p, int sep, CString *str)
830 int c;
831 for(;;) {
832 c = *++p;
833 redo:
834 if (c == sep) {
835 break;
836 } else if (c == '\\') {
837 c = handle_bs(&p);
838 if (c == CH_EOF) {
839 unterminated_string:
840 /* XXX: indicate line number of start of string */
841 tok_flags &= ~TOK_FLAG_BOL;
842 tcc_error("missing terminating %c character", sep);
843 } else if (c == '\\') {
844 if (str)
845 cstr_ccat(str, c);
846 c = *++p;
847 /* add char after '\\' unconditionally */
848 if (c == '\\') {
849 c = handle_bs(&p);
850 if (c == CH_EOF)
851 goto unterminated_string;
853 goto add_char;
854 } else {
855 goto redo;
857 } else if (c == '\n') {
858 add_lf:
859 if (ACCEPT_LF_IN_STRINGS) {
860 file->line_num++;
861 goto add_char;
862 } else if (str) { /* not skipping */
863 goto unterminated_string;
864 } else {
865 //tcc_warning("missing terminating %c character", sep);
866 return p;
868 } else if (c == '\r') {
869 c = *++p;
870 if (c == '\\')
871 c = handle_bs(&p);
872 if (c == '\n')
873 goto add_lf;
874 if (c == CH_EOF)
875 goto unterminated_string;
876 if (str)
877 cstr_ccat(str, '\r');
878 goto redo;
879 } else {
880 add_char:
881 if (str)
882 cstr_ccat(str, c);
885 p++;
886 return p;
889 /* skip block of text until #else, #elif or #endif. skip also pairs of
890 #if/#endif */
891 static void preprocess_skip(void)
893 int a, start_of_line, c, in_warn_or_error;
894 uint8_t *p;
896 p = file->buf_ptr;
897 a = 0;
898 redo_start:
899 start_of_line = 1;
900 in_warn_or_error = 0;
901 for(;;) {
902 redo_no_start:
903 c = *p;
904 switch(c) {
905 case ' ':
906 case '\t':
907 case '\f':
908 case '\v':
909 case '\r':
910 p++;
911 goto redo_no_start;
912 case '\n':
913 file->line_num++;
914 p++;
915 goto redo_start;
916 case '\\':
917 c = handle_bs(&p);
918 if (c == CH_EOF)
919 expect("#endif");
920 if (c == '\\')
921 ++p;
922 goto redo_no_start;
923 /* skip strings */
924 case '\"':
925 case '\'':
926 if (in_warn_or_error)
927 goto _default;
928 tok_flags &= ~TOK_FLAG_BOL;
929 p = parse_pp_string(p, c, NULL);
930 break;
931 /* skip comments */
932 case '/':
933 if (in_warn_or_error)
934 goto _default;
935 ++p;
936 c = handle_bs(&p);
937 if (c == '*') {
938 p = parse_comment(p);
939 } else if (c == '/') {
940 p = parse_line_comment(p);
942 break;
943 case '#':
944 p++;
945 if (start_of_line) {
946 file->buf_ptr = p;
947 next_nomacro();
948 p = file->buf_ptr;
949 if (a == 0 &&
950 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
951 goto the_end;
952 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
953 a++;
954 else if (tok == TOK_ENDIF)
955 a--;
956 else if( tok == TOK_ERROR || tok == TOK_WARNING)
957 in_warn_or_error = 1;
958 else if (tok == TOK_LINEFEED)
959 goto redo_start;
960 else if (parse_flags & PARSE_FLAG_ASM_FILE)
961 p = parse_line_comment(p - 1);
963 #if !defined(TCC_TARGET_ARM)
964 else if (parse_flags & PARSE_FLAG_ASM_FILE)
965 p = parse_line_comment(p - 1);
966 #else
967 /* ARM assembly uses '#' for constants */
968 #endif
969 break;
970 _default:
971 default:
972 p++;
973 break;
975 start_of_line = 0;
977 the_end: ;
978 file->buf_ptr = p;
981 #if 0
982 /* return the number of additional 'ints' necessary to store the
983 token */
984 static inline int tok_size(const int *p)
986 switch(*p) {
987 /* 4 bytes */
988 case TOK_CINT:
989 case TOK_CUINT:
990 case TOK_CCHAR:
991 case TOK_LCHAR:
992 case TOK_CFLOAT:
993 case TOK_LINENUM:
994 return 1 + 1;
995 case TOK_STR:
996 case TOK_LSTR:
997 case TOK_PPNUM:
998 case TOK_PPSTR:
999 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1000 case TOK_CLONG:
1001 case TOK_CULONG:
1002 return 1 + LONG_SIZE / 4;
1003 case TOK_CDOUBLE:
1004 case TOK_CLLONG:
1005 case TOK_CULLONG:
1006 return 1 + 2;
1007 case TOK_CLDOUBLE:
1008 return 1 + LDOUBLE_SIZE / 4;
1009 default:
1010 return 1 + 0;
1013 #endif
1015 /* token string handling */
1016 ST_INLN void tok_str_new(TokenString *s)
1018 s->str = NULL;
1019 s->len = s->lastlen = 0;
1020 s->allocated_len = 0;
1021 s->last_line_num = -1;
1024 ST_FUNC TokenString *tok_str_alloc(void)
1026 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1027 tok_str_new(str);
1028 return str;
1031 ST_FUNC int *tok_str_dup(TokenString *s)
1033 int *str;
1035 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1036 memcpy(str, s->str, s->len * sizeof(int));
1037 return str;
1040 ST_FUNC void tok_str_free_str(int *str)
1042 tal_free(tokstr_alloc, str);
1045 ST_FUNC void tok_str_free(TokenString *str)
1047 tok_str_free_str(str->str);
1048 tal_free(tokstr_alloc, str);
1051 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1053 int *str, size;
1055 size = s->allocated_len;
1056 if (size < 16)
1057 size = 16;
1058 while (size < new_size)
1059 size = size * 2;
1060 if (size > s->allocated_len) {
1061 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1062 s->allocated_len = size;
1063 s->str = str;
1065 return s->str;
1068 ST_FUNC void tok_str_add(TokenString *s, int t)
1070 int len, *str;
1072 len = s->len;
1073 str = s->str;
1074 if (len >= s->allocated_len)
1075 str = tok_str_realloc(s, len + 1);
1076 str[len++] = t;
1077 s->len = len;
1080 ST_FUNC void begin_macro(TokenString *str, int alloc)
1082 str->alloc = alloc;
1083 str->prev = macro_stack;
1084 str->prev_ptr = macro_ptr;
1085 str->save_line_num = file->line_num;
1086 macro_ptr = str->str;
1087 macro_stack = str;
1090 ST_FUNC void end_macro(void)
1092 TokenString *str = macro_stack;
1093 macro_stack = str->prev;
1094 macro_ptr = str->prev_ptr;
1095 file->line_num = str->save_line_num;
1096 str->len = 0; /* matters if str not alloced, may be tokstr_buf */
1097 if (str->alloc != 0) {
1098 if (str->alloc == 2)
1099 str->str = NULL; /* don't free */
1100 tok_str_free(str);
1104 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1106 int len, *str;
1108 len = s->lastlen = s->len;
1109 str = s->str;
1111 /* allocate space for worst case */
1112 if (len + TOK_MAX_SIZE >= s->allocated_len)
1113 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1114 str[len++] = t;
1115 switch(t) {
1116 case TOK_CINT:
1117 case TOK_CUINT:
1118 case TOK_CCHAR:
1119 case TOK_LCHAR:
1120 case TOK_CFLOAT:
1121 case TOK_LINENUM:
1122 #if LONG_SIZE == 4
1123 case TOK_CLONG:
1124 case TOK_CULONG:
1125 #endif
1126 str[len++] = cv->tab[0];
1127 break;
1128 case TOK_PPNUM:
1129 case TOK_PPSTR:
1130 case TOK_STR:
1131 case TOK_LSTR:
1133 /* Insert the string into the int array. */
1134 size_t nb_words =
1135 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1136 if (len + nb_words >= s->allocated_len)
1137 str = tok_str_realloc(s, len + nb_words + 1);
1138 str[len] = cv->str.size;
1139 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1140 len += nb_words;
1142 break;
1143 case TOK_CDOUBLE:
1144 case TOK_CLLONG:
1145 case TOK_CULLONG:
1146 #if LONG_SIZE == 8
1147 case TOK_CLONG:
1148 case TOK_CULONG:
1149 #endif
1150 #if LDOUBLE_SIZE == 8
1151 case TOK_CLDOUBLE:
1152 #endif
1153 str[len++] = cv->tab[0];
1154 str[len++] = cv->tab[1];
1155 break;
1156 #if LDOUBLE_SIZE == 12
1157 case TOK_CLDOUBLE:
1158 str[len++] = cv->tab[0];
1159 str[len++] = cv->tab[1];
1160 str[len++] = cv->tab[2];
1161 #elif LDOUBLE_SIZE == 16
1162 case TOK_CLDOUBLE:
1163 str[len++] = cv->tab[0];
1164 str[len++] = cv->tab[1];
1165 str[len++] = cv->tab[2];
1166 str[len++] = cv->tab[3];
1167 #elif LDOUBLE_SIZE != 8
1168 #error add long double size support
1169 #endif
1170 break;
1171 default:
1172 break;
1174 s->len = len;
1177 /* add the current parse token in token string 's' */
1178 ST_FUNC void tok_str_add_tok(TokenString *s)
1180 CValue cval;
1182 /* save line number info */
1183 if (file->line_num != s->last_line_num) {
1184 s->last_line_num = file->line_num;
1185 cval.i = s->last_line_num;
1186 tok_str_add2(s, TOK_LINENUM, &cval);
1188 tok_str_add2(s, tok, &tokc);
1191 /* get a token from an integer array and increment pointer. */
1192 static inline void tok_get(int *t, const int **pp, CValue *cv)
1194 const int *p = *pp;
1195 int n, *tab;
1197 tab = cv->tab;
1198 switch(*t = *p++) {
1199 #if LONG_SIZE == 4
1200 case TOK_CLONG:
1201 #endif
1202 case TOK_CINT:
1203 case TOK_CCHAR:
1204 case TOK_LCHAR:
1205 case TOK_LINENUM:
1206 cv->i = *p++;
1207 break;
1208 #if LONG_SIZE == 4
1209 case TOK_CULONG:
1210 #endif
1211 case TOK_CUINT:
1212 cv->i = (unsigned)*p++;
1213 break;
1214 case TOK_CFLOAT:
1215 tab[0] = *p++;
1216 break;
1217 case TOK_STR:
1218 case TOK_LSTR:
1219 case TOK_PPNUM:
1220 case TOK_PPSTR:
1221 cv->str.size = *p++;
1222 cv->str.data = p;
1223 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1224 break;
1225 case TOK_CDOUBLE:
1226 case TOK_CLLONG:
1227 case TOK_CULLONG:
1228 #if LONG_SIZE == 8
1229 case TOK_CLONG:
1230 case TOK_CULONG:
1231 #endif
1232 n = 2;
1233 goto copy;
1234 case TOK_CLDOUBLE:
1235 #if LDOUBLE_SIZE == 16
1236 n = 4;
1237 #elif LDOUBLE_SIZE == 12
1238 n = 3;
1239 #elif LDOUBLE_SIZE == 8
1240 n = 2;
1241 #else
1242 # error add long double size support
1243 #endif
1244 copy:
1246 *tab++ = *p++;
1247 while (--n);
1248 break;
1249 default:
1250 break;
1252 *pp = p;
1255 #if 0
1256 # define TOK_GET(t,p,c) tok_get(t,p,c)
1257 #else
1258 # define TOK_GET(t,p,c) do { \
1259 int _t = **(p); \
1260 if (TOK_HAS_VALUE(_t)) \
1261 tok_get(t, p, c); \
1262 else \
1263 *(t) = _t, ++*(p); \
1264 } while (0)
1265 #endif
1267 static int macro_is_equal(const int *a, const int *b)
1269 CValue cv;
1270 int t;
1272 if (!a || !b)
1273 return 1;
1275 while (*a && *b) {
1276 /* first time preallocate macro_equal_buf, next time only reset position to start */
1277 cstr_reset(&macro_equal_buf);
1278 TOK_GET(&t, &a, &cv);
1279 cstr_cat(&macro_equal_buf, get_tok_str(t, &cv), 0);
1280 TOK_GET(&t, &b, &cv);
1281 if (strcmp(macro_equal_buf.data, get_tok_str(t, &cv)))
1282 return 0;
1284 return !(*a || *b);
1287 /* defines handling */
1288 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1290 Sym *s, *o;
1292 o = define_find(v);
1293 s = sym_push2(&define_stack, v, macro_type, 0);
1294 s->d = str;
1295 s->next = first_arg;
1296 table_ident[v - TOK_IDENT]->sym_define = s;
1298 if (o && !macro_is_equal(o->d, s->d))
1299 tcc_warning("%s redefined", get_tok_str(v, NULL));
1302 /* undefined a define symbol. Its name is just set to zero */
1303 ST_FUNC void define_undef(Sym *s)
1305 int v = s->v;
1306 if (v >= TOK_IDENT && v < tok_ident)
1307 table_ident[v - TOK_IDENT]->sym_define = NULL;
1310 ST_INLN Sym *define_find(int v)
1312 v -= TOK_IDENT;
1313 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1314 return NULL;
1315 return table_ident[v]->sym_define;
1318 /* free define stack until top reaches 'b' */
1319 ST_FUNC void free_defines(Sym *b)
1321 while (define_stack != b) {
1322 Sym *top = define_stack;
1323 define_stack = top->prev;
1324 tok_str_free_str(top->d);
1325 define_undef(top);
1326 sym_free(top);
1330 /* label lookup */
1331 ST_FUNC Sym *label_find(int v)
1333 v -= TOK_IDENT;
1334 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1335 return NULL;
1336 return table_ident[v]->sym_label;
1339 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1341 Sym *s, **ps;
1342 s = sym_push2(ptop, v, VT_STATIC, 0);
1343 s->r = flags;
1344 ps = &table_ident[v - TOK_IDENT]->sym_label;
1345 if (ptop == &global_label_stack) {
1346 /* modify the top most local identifier, so that
1347 sym_identifier will point to 's' when popped */
1348 while (*ps != NULL)
1349 ps = &(*ps)->prev_tok;
1351 s->prev_tok = *ps;
1352 *ps = s;
1353 return s;
1356 /* pop labels until element last is reached. Look if any labels are
1357 undefined. Define symbols if '&&label' was used. */
1358 ST_FUNC void label_pop(Sym **ptop, Sym *slast, int keep)
1360 Sym *s, *s1;
1361 for(s = *ptop; s != slast; s = s1) {
1362 s1 = s->prev;
1363 if (s->r == LABEL_DECLARED) {
1364 tcc_warning_c(warn_all)("label '%s' declared but not used", get_tok_str(s->v, NULL));
1365 } else if (s->r == LABEL_FORWARD) {
1366 tcc_error("label '%s' used but not defined",
1367 get_tok_str(s->v, NULL));
1368 } else {
1369 if (s->c) {
1370 /* define corresponding symbol. A size of
1371 1 is put. */
1372 put_extern_sym(s, cur_text_section, s->jnext, 1);
1375 /* remove label */
1376 if (s->r != LABEL_GONE)
1377 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1378 if (!keep)
1379 sym_free(s);
1380 else
1381 s->r = LABEL_GONE;
1383 if (!keep)
1384 *ptop = slast;
1387 /* fake the nth "#if defined test_..." for tcc -dt -run */
1388 static void maybe_run_test(TCCState *s)
1390 const char *p;
1391 if (s->include_stack_ptr != s->include_stack)
1392 return;
1393 p = get_tok_str(tok, NULL);
1394 if (0 != memcmp(p, "test_", 5))
1395 return;
1396 if (0 != --s->run_test)
1397 return;
1398 fprintf(s->ppfp, &"\n[%s]\n"[!(s->dflag & 32)], p), fflush(s->ppfp);
1399 define_push(tok, MACRO_OBJ, NULL, NULL);
1402 static CachedInclude *
1403 search_cached_include(TCCState *s1, const char *filename, int add);
1405 static int parse_include(TCCState *s1, int do_next, int test)
1407 int c, i;
1408 CString cs;
1409 char name[1024], buf[1024], *p;
1410 CachedInclude *e;
1412 cstr_new(&cs);
1413 c = skip_spaces();
1414 if (c == '<' || c == '\"') {
1415 file->buf_ptr = parse_pp_string(file->buf_ptr, c == '<' ? '>' : c, &cs);
1416 next_nomacro();
1417 } else {
1418 /* computed #include : concatenate tokens until result is one of
1419 the two accepted forms. Don't convert pp-tokens to tokens here. */
1420 parse_flags = PARSE_FLAG_PREPROCESS
1421 | PARSE_FLAG_LINEFEED
1422 | (parse_flags & PARSE_FLAG_ASM_FILE);
1423 for (;;) {
1424 next();
1425 p = cs.data, i = cs.size - 1;
1426 if (i > 0
1427 && ((p[0] == '"' && p[i] == '"')
1428 || (p[0] == '<' && p[i] == '>')))
1429 break;
1430 if (tok == TOK_LINEFEED)
1431 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1432 cstr_cat(&cs, get_tok_str(tok, &tokc), -1);
1434 c = p[0];
1435 /* remove '<>|""' */
1436 memmove(p, p + 1, cs.size -= 2);
1438 cstr_ccat(&cs, '\0');
1439 pstrcpy(name, sizeof name, cs.data);
1440 cstr_free(&cs);
1442 i = do_next ? file->include_next_index : -1;
1443 for (;;) {
1444 ++i;
1445 if (i == 0) {
1446 /* check absolute include path */
1447 if (!IS_ABSPATH(name))
1448 continue;
1449 buf[0] = '\0';
1450 } else if (i == 1) {
1451 /* search in file's dir if "header.h" */
1452 if (c != '\"')
1453 continue;
1454 p = file->true_filename;
1455 pstrncpy(buf, p, tcc_basename(p) - p);
1456 } else {
1457 int j = i - 2, k = j - s1->nb_include_paths;
1458 if (k < 0)
1459 p = s1->include_paths[j];
1460 else if (k < s1->nb_sysinclude_paths)
1461 p = s1->sysinclude_paths[k];
1462 else if (test)
1463 return 0;
1464 else
1465 tcc_error("include file '%s' not found", name);
1466 pstrcpy(buf, sizeof buf, p);
1467 pstrcat(buf, sizeof buf, "/");
1469 pstrcat(buf, sizeof buf, name);
1470 e = search_cached_include(s1, buf, 0);
1471 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1472 /* no need to parse the include because the 'ifndef macro'
1473 is defined (or had #pragma once) */
1474 #ifdef INC_DEBUG
1475 printf("%s: skipping cached %s\n", file->filename, buf);
1476 #endif
1477 return 1;
1479 if (tcc_open(s1, buf) >= 0)
1480 break;
1483 if (test) {
1484 tcc_close();
1485 } else {
1486 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1487 tcc_error("#include recursion too deep");
1488 /* push previous file on stack */
1489 *s1->include_stack_ptr++ = file->prev;
1490 file->include_next_index = i;
1491 #ifdef INC_DEBUG
1492 printf("%s: including %s\n", file->prev->filename, file->filename);
1493 #endif
1494 /* update target deps */
1495 if (s1->gen_deps) {
1496 BufferedFile *bf = file;
1497 while (i == 1 && (bf = bf->prev))
1498 i = bf->include_next_index;
1499 /* skip system include files */
1500 if (s1->include_sys_deps || i - 2 < s1->nb_include_paths)
1501 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1502 tcc_strdup(buf));
1504 /* add include file debug info */
1505 tcc_debug_bincl(s1);
1506 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1508 return 1;
1511 /* eval an expression for #if/#elif */
1512 static int expr_preprocess(TCCState *s1)
1514 int c, t;
1515 TokenString *str;
1517 str = tok_str_alloc();
1518 pp_expr = 1;
1519 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1520 next(); /* do macro subst */
1521 redo:
1522 if (tok == TOK_DEFINED) {
1523 next_nomacro();
1524 t = tok;
1525 if (t == '(')
1526 next_nomacro();
1527 if (tok < TOK_IDENT)
1528 expect("identifier");
1529 if (s1->run_test)
1530 maybe_run_test(s1);
1531 c = 0;
1532 if (define_find(tok)
1533 || tok == TOK___HAS_INCLUDE
1534 || tok == TOK___HAS_INCLUDE_NEXT)
1535 c = 1;
1536 if (t == '(') {
1537 next_nomacro();
1538 if (tok != ')')
1539 expect("')'");
1541 tok = TOK_CINT;
1542 tokc.i = c;
1543 } else if (tok == TOK___HAS_INCLUDE ||
1544 tok == TOK___HAS_INCLUDE_NEXT) {
1545 t = tok;
1546 next_nomacro();
1547 if (tok != '(')
1548 expect("(");
1549 c = parse_include(s1, t - TOK___HAS_INCLUDE, 1);
1550 if (tok != ')')
1551 expect("')'");
1552 tok = TOK_CINT;
1553 tokc.i = c;
1554 } else if (tok >= TOK_IDENT) {
1555 /* if undefined macro, replace with zero, check for func-like */
1556 t = tok;
1557 tok = TOK_CINT;
1558 tokc.i = 0;
1559 tok_str_add_tok(str);
1560 next();
1561 if (tok == '(')
1562 tcc_error("function-like macro '%s' is not defined",
1563 get_tok_str(t, NULL));
1564 goto redo;
1566 tok_str_add_tok(str);
1568 pp_expr = 0;
1569 tok_str_add(str, -1); /* simulate end of file */
1570 tok_str_add(str, 0);
1571 /* now evaluate C constant expression */
1572 begin_macro(str, 1);
1573 next();
1574 c = expr_const();
1575 end_macro();
1576 return c != 0;
1580 /* parse after #define */
1581 ST_FUNC void parse_define(void)
1583 Sym *s, *first, **ps;
1584 int v, t, varg, is_vaargs, spc;
1585 int saved_parse_flags = parse_flags;
1587 v = tok;
1588 if (v < TOK_IDENT || v == TOK_DEFINED)
1589 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1590 /* XXX: should check if same macro (ANSI) */
1591 first = NULL;
1592 t = MACRO_OBJ;
1593 /* We have to parse the whole define as if not in asm mode, in particular
1594 no line comment with '#' must be ignored. Also for function
1595 macros the argument list must be parsed without '.' being an ID
1596 character. */
1597 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1598 /* '(' must be just after macro definition for MACRO_FUNC */
1599 next_nomacro();
1600 parse_flags &= ~PARSE_FLAG_SPACES;
1601 if (tok == '(') {
1602 int dotid = set_idnum('.', 0);
1603 next_nomacro();
1604 ps = &first;
1605 if (tok != ')') for (;;) {
1606 varg = tok;
1607 next_nomacro();
1608 is_vaargs = 0;
1609 if (varg == TOK_DOTS) {
1610 varg = TOK___VA_ARGS__;
1611 is_vaargs = 1;
1612 } else if (tok == TOK_DOTS && gnu_ext) {
1613 is_vaargs = 1;
1614 next_nomacro();
1616 if (varg < TOK_IDENT)
1617 bad_list:
1618 tcc_error("bad macro parameter list");
1619 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1620 *ps = s;
1621 ps = &s->next;
1622 if (tok == ')')
1623 break;
1624 if (tok != ',' || is_vaargs)
1625 goto bad_list;
1626 next_nomacro();
1628 parse_flags |= PARSE_FLAG_SPACES;
1629 next_nomacro();
1630 t = MACRO_FUNC;
1631 set_idnum('.', dotid);
1634 tokstr_buf.len = 0;
1635 spc = 2;
1636 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1637 /* The body of a macro definition should be parsed such that identifiers
1638 are parsed like the file mode determines (i.e. with '.' being an
1639 ID character in asm mode). But '#' should be retained instead of
1640 regarded as line comment leader, so still don't set ASM_FILE
1641 in parse_flags. */
1642 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1643 /* remove spaces around ## and after '#' */
1644 if (TOK_TWOSHARPS == tok) {
1645 if (2 == spc)
1646 goto bad_twosharp;
1647 if (1 == spc)
1648 --tokstr_buf.len;
1649 spc = 3;
1650 tok = TOK_PPJOIN;
1651 } else if ('#' == tok) {
1652 spc = 4;
1653 } else if (check_space(tok, &spc)) {
1654 goto skip;
1656 tok_str_add2(&tokstr_buf, tok, &tokc);
1657 skip:
1658 next_nomacro();
1661 parse_flags = saved_parse_flags;
1662 if (spc == 1)
1663 --tokstr_buf.len; /* remove trailing space */
1664 tok_str_add(&tokstr_buf, 0);
1665 if (3 == spc)
1666 bad_twosharp:
1667 tcc_error("'##' cannot appear at either end of macro");
1668 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1671 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1673 const unsigned char *s;
1674 unsigned int h;
1675 CachedInclude *e;
1676 int i;
1678 h = TOK_HASH_INIT;
1679 s = (unsigned char *) filename;
1680 while (*s) {
1681 #ifdef _WIN32
1682 h = TOK_HASH_FUNC(h, toup(*s));
1683 #else
1684 h = TOK_HASH_FUNC(h, *s);
1685 #endif
1686 s++;
1688 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1690 i = s1->cached_includes_hash[h];
1691 for(;;) {
1692 if (i == 0)
1693 break;
1694 e = s1->cached_includes[i - 1];
1695 if (0 == PATHCMP(e->filename, filename))
1696 return e;
1697 i = e->hash_next;
1699 if (!add)
1700 return NULL;
1702 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1703 strcpy(e->filename, filename);
1704 e->ifndef_macro = e->once = 0;
1705 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1706 /* add in hash table */
1707 e->hash_next = s1->cached_includes_hash[h];
1708 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1709 #ifdef INC_DEBUG
1710 printf("adding cached '%s'\n", filename);
1711 #endif
1712 return e;
1715 static void pragma_parse(TCCState *s1)
1717 next_nomacro();
1718 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1719 int t = tok, v;
1720 Sym *s;
1722 if (next(), tok != '(')
1723 goto pragma_err;
1724 if (next(), tok != TOK_STR)
1725 goto pragma_err;
1726 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1727 if (next(), tok != ')')
1728 goto pragma_err;
1729 if (t == TOK_push_macro) {
1730 while (NULL == (s = define_find(v)))
1731 define_push(v, 0, NULL, NULL);
1732 s->type.ref = s; /* set push boundary */
1733 } else {
1734 for (s = define_stack; s; s = s->prev)
1735 if (s->v == v && s->type.ref == s) {
1736 s->type.ref = NULL;
1737 break;
1740 if (s)
1741 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1742 else
1743 tcc_warning("unbalanced #pragma pop_macro");
1744 pp_debug_tok = t, pp_debug_symv = v;
1746 } else if (tok == TOK_once) {
1747 search_cached_include(s1, file->filename, 1)->once = pp_once;
1749 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1750 /* tcc -E: keep pragmas below unchanged */
1751 unget_tok(' ');
1752 unget_tok(TOK_PRAGMA);
1753 unget_tok('#');
1754 unget_tok(TOK_LINEFEED);
1756 } else if (tok == TOK_pack) {
1757 /* This may be:
1758 #pragma pack(1) // set
1759 #pragma pack() // reset to default
1760 #pragma pack(push) // push current
1761 #pragma pack(push,1) // push & set
1762 #pragma pack(pop) // restore previous */
1763 next();
1764 skip('(');
1765 if (tok == TOK_ASM_pop) {
1766 next();
1767 if (s1->pack_stack_ptr <= s1->pack_stack) {
1768 stk_error:
1769 tcc_error("out of pack stack");
1771 s1->pack_stack_ptr--;
1772 } else {
1773 int val = 0;
1774 if (tok != ')') {
1775 if (tok == TOK_ASM_push) {
1776 next();
1777 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1778 goto stk_error;
1779 val = *s1->pack_stack_ptr++;
1780 if (tok != ',')
1781 goto pack_set;
1782 next();
1784 if (tok != TOK_CINT)
1785 goto pragma_err;
1786 val = tokc.i;
1787 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1788 goto pragma_err;
1789 next();
1791 pack_set:
1792 *s1->pack_stack_ptr = val;
1794 if (tok != ')')
1795 goto pragma_err;
1797 } else if (tok == TOK_comment) {
1798 char *p; int t;
1799 next();
1800 skip('(');
1801 t = tok;
1802 next();
1803 skip(',');
1804 if (tok != TOK_STR)
1805 goto pragma_err;
1806 p = tcc_strdup((char *)tokc.str.data);
1807 next();
1808 if (tok != ')')
1809 goto pragma_err;
1810 if (t == TOK_lib) {
1811 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1812 } else {
1813 if (t == TOK_option)
1814 tcc_set_options(s1, p);
1815 tcc_free(p);
1818 } else
1819 tcc_warning_c(warn_unsupported)("#pragma %s ignored", get_tok_str(tok, &tokc));
1820 return;
1822 pragma_err:
1823 tcc_error("malformed #pragma directive");
1824 return;
1827 /* is_bof is true if first non space token at beginning of file */
1828 ST_FUNC void preprocess(int is_bof)
1830 TCCState *s1 = tcc_state;
1831 int c, n, saved_parse_flags;
1832 char buf[1024], *q;
1833 Sym *s;
1835 saved_parse_flags = parse_flags;
1836 parse_flags = PARSE_FLAG_PREPROCESS
1837 | PARSE_FLAG_TOK_NUM
1838 | PARSE_FLAG_TOK_STR
1839 | PARSE_FLAG_LINEFEED
1840 | (parse_flags & PARSE_FLAG_ASM_FILE)
1843 next_nomacro();
1844 redo:
1845 switch(tok) {
1846 case TOK_DEFINE:
1847 pp_debug_tok = tok;
1848 next_nomacro();
1849 pp_debug_symv = tok;
1850 parse_define();
1851 break;
1852 case TOK_UNDEF:
1853 pp_debug_tok = tok;
1854 next_nomacro();
1855 pp_debug_symv = tok;
1856 s = define_find(tok);
1857 /* undefine symbol by putting an invalid name */
1858 if (s)
1859 define_undef(s);
1860 break;
1861 case TOK_INCLUDE:
1862 case TOK_INCLUDE_NEXT:
1863 parse_include(s1, tok - TOK_INCLUDE, 0);
1864 break;
1865 case TOK_IFNDEF:
1866 c = 1;
1867 goto do_ifdef;
1868 case TOK_IF:
1869 c = expr_preprocess(s1);
1870 goto do_if;
1871 case TOK_IFDEF:
1872 c = 0;
1873 do_ifdef:
1874 next_nomacro();
1875 if (tok < TOK_IDENT)
1876 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1877 if (is_bof) {
1878 if (c) {
1879 #ifdef INC_DEBUG
1880 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1881 #endif
1882 file->ifndef_macro = tok;
1885 if (define_find(tok)
1886 || tok == TOK___HAS_INCLUDE
1887 || tok == TOK___HAS_INCLUDE_NEXT)
1888 c ^= 1;
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(s1);
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 q = (char *)tokc.str.data;
1958 buf[0] = 0;
1959 if (!IS_ABSPATH(q)) {
1960 /* prepend directory from real file */
1961 pstrcpy(buf, sizeof buf, file->true_filename);
1962 *tcc_basename(buf) = 0;
1964 pstrcat(buf, sizeof buf, q);
1965 tcc_debug_putfile(s1, buf);
1966 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
1967 break;
1968 else
1969 goto _line_err;
1970 --n;
1972 if (file->fd > 0)
1973 total_lines += file->line_num - n;
1974 file->line_num = n;
1975 break;
1976 case TOK_ERROR:
1977 case TOK_WARNING:
1978 q = buf;
1979 c = skip_spaces();
1980 while (c != '\n' && c != CH_EOF) {
1981 if ((q - buf) < sizeof(buf) - 1)
1982 *q++ = c;
1983 c = ninp();
1985 *q = '\0';
1986 if (tok == 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, i;
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': i = 0; goto parse_hex_or_ucn;
2049 case 'u': i = 4; goto parse_hex_or_ucn;
2050 case 'U': i = 8; goto parse_hex_or_ucn;
2051 parse_hex_or_ucn:
2052 p++;
2053 n = 0;
2054 do {
2055 c = *p;
2056 if (c >= 'a' && c <= 'f')
2057 c = c - 'a' + 10;
2058 else if (c >= 'A' && c <= 'F')
2059 c = c - 'A' + 10;
2060 else if (isnum(c))
2061 c = c - '0';
2062 else if (i > 0)
2063 expect("more hex digits in universal-character-name");
2064 else
2065 goto add_hex_or_ucn;
2066 n = n * 16 + c;
2067 p++;
2068 } while (--i);
2069 if (is_long) {
2070 add_hex_or_ucn:
2071 c = n;
2072 goto add_char_nonext;
2074 cstr_u8cat(outstr, n);
2075 continue;
2076 case 'a':
2077 c = '\a';
2078 break;
2079 case 'b':
2080 c = '\b';
2081 break;
2082 case 'f':
2083 c = '\f';
2084 break;
2085 case 'n':
2086 c = '\n';
2087 break;
2088 case 'r':
2089 c = '\r';
2090 break;
2091 case 't':
2092 c = '\t';
2093 break;
2094 case 'v':
2095 c = '\v';
2096 break;
2097 case 'e':
2098 if (!gnu_ext)
2099 goto invalid_escape;
2100 c = 27;
2101 break;
2102 case '\'':
2103 case '\"':
2104 case '\\':
2105 case '?':
2106 break;
2107 default:
2108 invalid_escape:
2109 if (c >= '!' && c <= '~')
2110 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2111 else
2112 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2113 break;
2115 } else if (is_long && c >= 0x80) {
2116 /* assume we are processing UTF-8 sequence */
2117 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2119 int cont; /* count of continuation bytes */
2120 int skip; /* how many bytes should skip when error occurred */
2121 int i;
2123 /* decode leading byte */
2124 if (c < 0xC2) {
2125 skip = 1; goto invalid_utf8_sequence;
2126 } else if (c <= 0xDF) {
2127 cont = 1; n = c & 0x1f;
2128 } else if (c <= 0xEF) {
2129 cont = 2; n = c & 0xf;
2130 } else if (c <= 0xF4) {
2131 cont = 3; n = c & 0x7;
2132 } else {
2133 skip = 1; goto invalid_utf8_sequence;
2136 /* decode continuation bytes */
2137 for (i = 1; i <= cont; i++) {
2138 int l = 0x80, h = 0xBF;
2140 /* adjust limit for second byte */
2141 if (i == 1) {
2142 switch (c) {
2143 case 0xE0: l = 0xA0; break;
2144 case 0xED: h = 0x9F; break;
2145 case 0xF0: l = 0x90; break;
2146 case 0xF4: h = 0x8F; break;
2150 if (p[i] < l || p[i] > h) {
2151 skip = i; goto invalid_utf8_sequence;
2154 n = (n << 6) | (p[i] & 0x3f);
2157 /* advance pointer */
2158 p += 1 + cont;
2159 c = n;
2160 goto add_char_nonext;
2162 /* error handling */
2163 invalid_utf8_sequence:
2164 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2165 c = 0xFFFD;
2166 p += skip;
2167 goto add_char_nonext;
2170 p++;
2171 add_char_nonext:
2172 if (!is_long)
2173 cstr_ccat(outstr, c);
2174 else {
2175 #ifdef TCC_TARGET_PE
2176 /* store as UTF-16 */
2177 if (c < 0x10000) {
2178 cstr_wccat(outstr, c);
2179 } else {
2180 c -= 0x10000;
2181 cstr_wccat(outstr, (c >> 10) + 0xD800);
2182 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2184 #else
2185 cstr_wccat(outstr, c);
2186 #endif
2189 /* add a trailing '\0' */
2190 if (!is_long)
2191 cstr_ccat(outstr, '\0');
2192 else
2193 cstr_wccat(outstr, '\0');
2196 static void parse_string(const char *s, int len)
2198 uint8_t buf[1000], *p = buf;
2199 int is_long, sep;
2201 if ((is_long = *s == 'L'))
2202 ++s, --len;
2203 sep = *s++;
2204 len -= 2;
2205 if (len >= sizeof buf)
2206 p = tcc_malloc(len + 1);
2207 memcpy(p, s, len);
2208 p[len] = 0;
2210 cstr_reset(&tokcstr);
2211 parse_escape_string(&tokcstr, p, is_long);
2212 if (p != buf)
2213 tcc_free(p);
2215 if (sep == '\'') {
2216 int char_size, i, n, c;
2217 /* XXX: make it portable */
2218 if (!is_long)
2219 tok = TOK_CCHAR, char_size = 1;
2220 else
2221 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2222 n = tokcstr.size / char_size - 1;
2223 if (n < 1)
2224 tcc_error("empty character constant");
2225 if (n > 1)
2226 tcc_warning_c(warn_all)("multi-character character constant");
2227 for (c = i = 0; i < n; ++i) {
2228 if (is_long)
2229 c = ((nwchar_t *)tokcstr.data)[i];
2230 else
2231 c = (c << 8) | ((char *)tokcstr.data)[i];
2233 tokc.i = c;
2234 } else {
2235 tokc.str.size = tokcstr.size;
2236 tokc.str.data = tokcstr.data;
2237 if (!is_long)
2238 tok = TOK_STR;
2239 else
2240 tok = TOK_LSTR;
2244 /* we use 64 bit numbers */
2245 #define BN_SIZE 2
2247 /* bn = (bn << shift) | or_val */
2248 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2250 int i;
2251 unsigned int v;
2252 for(i=0;i<BN_SIZE;i++) {
2253 v = bn[i];
2254 bn[i] = (v << shift) | or_val;
2255 or_val = v >> (32 - shift);
2259 static void bn_zero(unsigned int *bn)
2261 int i;
2262 for(i=0;i<BN_SIZE;i++) {
2263 bn[i] = 0;
2267 /* parse number in null terminated string 'p' and return it in the
2268 current token */
2269 static void parse_number(const char *p)
2271 int b, t, shift, frac_bits, s, exp_val, ch;
2272 char *q;
2273 unsigned int bn[BN_SIZE];
2274 double d;
2276 /* number */
2277 q = token_buf;
2278 ch = *p++;
2279 t = ch;
2280 ch = *p++;
2281 *q++ = t;
2282 b = 10;
2283 if (t == '.') {
2284 goto float_frac_parse;
2285 } else if (t == '0') {
2286 if (ch == 'x' || ch == 'X') {
2287 q--;
2288 ch = *p++;
2289 b = 16;
2290 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2291 q--;
2292 ch = *p++;
2293 b = 2;
2296 /* parse all digits. cannot check octal numbers at this stage
2297 because of floating point constants */
2298 while (1) {
2299 if (ch >= 'a' && ch <= 'f')
2300 t = ch - 'a' + 10;
2301 else if (ch >= 'A' && ch <= 'F')
2302 t = ch - 'A' + 10;
2303 else if (isnum(ch))
2304 t = ch - '0';
2305 else
2306 break;
2307 if (t >= b)
2308 break;
2309 if (q >= token_buf + STRING_MAX_SIZE) {
2310 num_too_long:
2311 tcc_error("number too long");
2313 *q++ = ch;
2314 ch = *p++;
2316 if (ch == '.' ||
2317 ((ch == 'e' || ch == 'E') && b == 10) ||
2318 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2319 if (b != 10) {
2320 /* NOTE: strtox should support that for hexa numbers, but
2321 non ISOC99 libcs do not support it, so we prefer to do
2322 it by hand */
2323 /* hexadecimal or binary floats */
2324 /* XXX: handle overflows */
2325 *q = '\0';
2326 if (b == 16)
2327 shift = 4;
2328 else
2329 shift = 1;
2330 bn_zero(bn);
2331 q = token_buf;
2332 while (1) {
2333 t = *q++;
2334 if (t == '\0') {
2335 break;
2336 } else if (t >= 'a') {
2337 t = t - 'a' + 10;
2338 } else if (t >= 'A') {
2339 t = t - 'A' + 10;
2340 } else {
2341 t = t - '0';
2343 bn_lshift(bn, shift, t);
2345 frac_bits = 0;
2346 if (ch == '.') {
2347 ch = *p++;
2348 while (1) {
2349 t = ch;
2350 if (t >= 'a' && t <= 'f') {
2351 t = t - 'a' + 10;
2352 } else if (t >= 'A' && t <= 'F') {
2353 t = t - 'A' + 10;
2354 } else if (t >= '0' && t <= '9') {
2355 t = t - '0';
2356 } else {
2357 break;
2359 if (t >= b)
2360 tcc_error("invalid digit");
2361 bn_lshift(bn, shift, t);
2362 frac_bits += shift;
2363 ch = *p++;
2366 if (ch != 'p' && ch != 'P')
2367 expect("exponent");
2368 ch = *p++;
2369 s = 1;
2370 exp_val = 0;
2371 if (ch == '+') {
2372 ch = *p++;
2373 } else if (ch == '-') {
2374 s = -1;
2375 ch = *p++;
2377 if (ch < '0' || ch > '9')
2378 expect("exponent digits");
2379 while (ch >= '0' && ch <= '9') {
2380 exp_val = exp_val * 10 + ch - '0';
2381 ch = *p++;
2383 exp_val = exp_val * s;
2385 /* now we can generate the number */
2386 /* XXX: should patch directly float number */
2387 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2388 d = ldexp(d, exp_val - frac_bits);
2389 t = toup(ch);
2390 if (t == 'F') {
2391 ch = *p++;
2392 tok = TOK_CFLOAT;
2393 /* float : should handle overflow */
2394 tokc.f = (float)d;
2395 } else if (t == 'L') {
2396 ch = *p++;
2397 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2398 tok = TOK_CDOUBLE;
2399 tokc.d = d;
2400 #else
2401 tok = TOK_CLDOUBLE;
2402 /* XXX: not large enough */
2403 tokc.ld = (long double)d;
2404 #endif
2405 } else {
2406 tok = TOK_CDOUBLE;
2407 tokc.d = d;
2409 } else {
2410 /* decimal floats */
2411 if (ch == '.') {
2412 if (q >= token_buf + STRING_MAX_SIZE)
2413 goto num_too_long;
2414 *q++ = ch;
2415 ch = *p++;
2416 float_frac_parse:
2417 while (ch >= '0' && ch <= '9') {
2418 if (q >= token_buf + STRING_MAX_SIZE)
2419 goto num_too_long;
2420 *q++ = ch;
2421 ch = *p++;
2424 if (ch == 'e' || ch == 'E') {
2425 if (q >= token_buf + STRING_MAX_SIZE)
2426 goto num_too_long;
2427 *q++ = ch;
2428 ch = *p++;
2429 if (ch == '-' || ch == '+') {
2430 if (q >= token_buf + STRING_MAX_SIZE)
2431 goto num_too_long;
2432 *q++ = ch;
2433 ch = *p++;
2435 if (ch < '0' || ch > '9')
2436 expect("exponent digits");
2437 while (ch >= '0' && ch <= '9') {
2438 if (q >= token_buf + STRING_MAX_SIZE)
2439 goto num_too_long;
2440 *q++ = ch;
2441 ch = *p++;
2444 *q = '\0';
2445 t = toup(ch);
2446 errno = 0;
2447 if (t == 'F') {
2448 ch = *p++;
2449 tok = TOK_CFLOAT;
2450 tokc.f = strtof(token_buf, NULL);
2451 } else if (t == 'L') {
2452 ch = *p++;
2453 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2454 tok = TOK_CDOUBLE;
2455 tokc.d = strtod(token_buf, NULL);
2456 #else
2457 tok = TOK_CLDOUBLE;
2458 tokc.ld = strtold(token_buf, NULL);
2459 #endif
2460 } else {
2461 tok = TOK_CDOUBLE;
2462 tokc.d = strtod(token_buf, NULL);
2465 } else {
2466 unsigned long long n, n1;
2467 int lcount, ucount, ov = 0;
2468 const char *p1;
2470 /* integer number */
2471 *q = '\0';
2472 q = token_buf;
2473 if (b == 10 && *q == '0') {
2474 b = 8;
2475 q++;
2477 n = 0;
2478 while(1) {
2479 t = *q++;
2480 /* no need for checks except for base 10 / 8 errors */
2481 if (t == '\0')
2482 break;
2483 else if (t >= 'a')
2484 t = t - 'a' + 10;
2485 else if (t >= 'A')
2486 t = t - 'A' + 10;
2487 else
2488 t = t - '0';
2489 if (t >= b)
2490 tcc_error("invalid digit");
2491 n1 = n;
2492 n = n * b + t;
2493 /* detect overflow */
2494 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2495 ov = 1;
2498 /* Determine the characteristics (unsigned and/or 64bit) the type of
2499 the constant must have according to the constant suffix(es) */
2500 lcount = ucount = 0;
2501 p1 = p;
2502 for(;;) {
2503 t = toup(ch);
2504 if (t == 'L') {
2505 if (lcount >= 2)
2506 tcc_error("three 'l's in integer constant");
2507 if (lcount && *(p - 1) != ch)
2508 tcc_error("incorrect integer suffix: %s", p1);
2509 lcount++;
2510 ch = *p++;
2511 } else if (t == 'U') {
2512 if (ucount >= 1)
2513 tcc_error("two 'u's in integer constant");
2514 ucount++;
2515 ch = *p++;
2516 } else {
2517 break;
2521 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2522 if (ucount == 0 && b == 10) {
2523 if (lcount <= (LONG_SIZE == 4)) {
2524 if (n >= 0x80000000U)
2525 lcount = (LONG_SIZE == 4) + 1;
2527 if (n >= 0x8000000000000000ULL)
2528 ov = 1, ucount = 1;
2529 } else {
2530 if (lcount <= (LONG_SIZE == 4)) {
2531 if (n >= 0x100000000ULL)
2532 lcount = (LONG_SIZE == 4) + 1;
2533 else if (n >= 0x80000000U)
2534 ucount = 1;
2536 if (n >= 0x8000000000000000ULL)
2537 ucount = 1;
2540 if (ov)
2541 tcc_warning("integer constant overflow");
2543 tok = TOK_CINT;
2544 if (lcount) {
2545 tok = TOK_CLONG;
2546 if (lcount == 2)
2547 tok = TOK_CLLONG;
2549 if (ucount)
2550 ++tok; /* TOK_CU... */
2551 tokc.i = n;
2553 if (ch)
2554 tcc_error("invalid number");
2558 #define PARSE2(c1, tok1, c2, tok2) \
2559 case c1: \
2560 PEEKC(c, p); \
2561 if (c == c2) { \
2562 p++; \
2563 tok = tok2; \
2564 } else { \
2565 tok = tok1; \
2567 break;
2569 /* return next token without macro substitution */
2570 static inline void next_nomacro1(void)
2572 int t, c, is_long, len;
2573 TokenSym *ts;
2574 uint8_t *p, *p1;
2575 unsigned int h;
2577 p = file->buf_ptr;
2578 redo_no_start:
2579 c = *p;
2580 switch(c) {
2581 case ' ':
2582 case '\t':
2583 tok = c;
2584 p++;
2585 maybe_space:
2586 if (parse_flags & PARSE_FLAG_SPACES)
2587 goto keep_tok_flags;
2588 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2589 ++p;
2590 goto redo_no_start;
2591 case '\f':
2592 case '\v':
2593 case '\r':
2594 p++;
2595 goto redo_no_start;
2596 case '\\':
2597 /* first look if it is in fact an end of buffer */
2598 c = handle_stray(&p);
2599 if (c == '\\')
2600 goto parse_simple;
2601 if (c == CH_EOF) {
2602 TCCState *s1 = tcc_state;
2603 if ((parse_flags & PARSE_FLAG_LINEFEED)
2604 && !(tok_flags & TOK_FLAG_EOF)) {
2605 tok_flags |= TOK_FLAG_EOF;
2606 tok = TOK_LINEFEED;
2607 goto keep_tok_flags;
2608 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2609 tok = TOK_EOF;
2610 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2611 tcc_error("missing #endif");
2612 } else if (s1->include_stack_ptr == s1->include_stack) {
2613 /* no include left : end of file. */
2614 tok = TOK_EOF;
2615 } else {
2616 tok_flags &= ~TOK_FLAG_EOF;
2617 /* pop include file */
2619 /* test if previous '#endif' was after a #ifdef at
2620 start of file */
2621 if (tok_flags & TOK_FLAG_ENDIF) {
2622 #ifdef INC_DEBUG
2623 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2624 #endif
2625 search_cached_include(s1, file->filename, 1)
2626 ->ifndef_macro = file->ifndef_macro_saved;
2627 tok_flags &= ~TOK_FLAG_ENDIF;
2630 /* add end of include file debug info */
2631 tcc_debug_eincl(tcc_state);
2632 /* pop include stack */
2633 tcc_close();
2634 s1->include_stack_ptr--;
2635 p = file->buf_ptr;
2636 if (p == file->buffer)
2637 tok_flags = TOK_FLAG_BOF;
2638 tok_flags |= TOK_FLAG_BOL;
2639 goto redo_no_start;
2641 } else {
2642 goto redo_no_start;
2644 break;
2646 case '\n':
2647 file->line_num++;
2648 tok_flags |= TOK_FLAG_BOL;
2649 p++;
2650 maybe_newline:
2651 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2652 goto redo_no_start;
2653 tok = TOK_LINEFEED;
2654 goto keep_tok_flags;
2656 case '#':
2657 /* XXX: simplify */
2658 PEEKC(c, p);
2659 if ((tok_flags & TOK_FLAG_BOL) &&
2660 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2661 file->buf_ptr = p;
2662 preprocess(tok_flags & TOK_FLAG_BOF);
2663 p = file->buf_ptr;
2664 goto maybe_newline;
2665 } else {
2666 if (c == '#') {
2667 p++;
2668 tok = TOK_TWOSHARPS;
2669 } else {
2670 #if !defined(TCC_TARGET_ARM)
2671 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2672 p = parse_line_comment(p - 1);
2673 goto redo_no_start;
2674 } else
2675 #endif
2677 tok = '#';
2681 break;
2683 /* dollar is allowed to start identifiers when not parsing asm */
2684 case '$':
2685 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2686 || (parse_flags & PARSE_FLAG_ASM_FILE))
2687 goto parse_simple;
2689 case 'a': case 'b': case 'c': case 'd':
2690 case 'e': case 'f': case 'g': case 'h':
2691 case 'i': case 'j': case 'k': case 'l':
2692 case 'm': case 'n': case 'o': case 'p':
2693 case 'q': case 'r': case 's': case 't':
2694 case 'u': case 'v': case 'w': case 'x':
2695 case 'y': case 'z':
2696 case 'A': case 'B': case 'C': case 'D':
2697 case 'E': case 'F': case 'G': case 'H':
2698 case 'I': case 'J': case 'K':
2699 case 'M': case 'N': case 'O': case 'P':
2700 case 'Q': case 'R': case 'S': case 'T':
2701 case 'U': case 'V': case 'W': case 'X':
2702 case 'Y': case 'Z':
2703 case '_':
2704 parse_ident_fast:
2705 p1 = p;
2706 h = TOK_HASH_INIT;
2707 h = TOK_HASH_FUNC(h, c);
2708 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2709 h = TOK_HASH_FUNC(h, c);
2710 len = p - p1;
2711 if (c != '\\') {
2712 TokenSym **pts;
2714 /* fast case : no stray found, so we have the full token
2715 and we have already hashed it */
2716 h &= (TOK_HASH_SIZE - 1);
2717 pts = &hash_ident[h];
2718 for(;;) {
2719 ts = *pts;
2720 if (!ts)
2721 break;
2722 if (ts->len == len && !memcmp(ts->str, p1, len))
2723 goto token_found;
2724 pts = &(ts->hash_next);
2726 ts = tok_alloc_new(pts, (char *) p1, len);
2727 token_found: ;
2728 } else {
2729 /* slower case */
2730 cstr_reset(&tokcstr);
2731 cstr_cat(&tokcstr, (char *) p1, len);
2732 p--;
2733 PEEKC(c, p);
2734 parse_ident_slow:
2735 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2737 cstr_ccat(&tokcstr, c);
2738 PEEKC(c, p);
2740 ts = tok_alloc(tokcstr.data, tokcstr.size);
2742 tok = ts->tok;
2743 break;
2744 case 'L':
2745 t = p[1];
2746 if (t != '\\' && t != '\'' && t != '\"') {
2747 /* fast case */
2748 goto parse_ident_fast;
2749 } else {
2750 PEEKC(c, p);
2751 if (c == '\'' || c == '\"') {
2752 is_long = 1;
2753 goto str_const;
2754 } else {
2755 cstr_reset(&tokcstr);
2756 cstr_ccat(&tokcstr, 'L');
2757 goto parse_ident_slow;
2760 break;
2762 case '0': case '1': case '2': case '3':
2763 case '4': case '5': case '6': case '7':
2764 case '8': case '9':
2765 t = c;
2766 PEEKC(c, p);
2767 /* after the first digit, accept digits, alpha, '.' or sign if
2768 prefixed by 'eEpP' */
2769 parse_num:
2770 cstr_reset(&tokcstr);
2771 for(;;) {
2772 cstr_ccat(&tokcstr, t);
2773 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2774 || c == '.'
2775 || ((c == '+' || c == '-')
2776 && (((t == 'e' || t == 'E')
2777 && !(parse_flags & PARSE_FLAG_ASM_FILE
2778 /* 0xe+1 is 3 tokens in asm */
2779 && ((char*)tokcstr.data)[0] == '0'
2780 && toup(((char*)tokcstr.data)[1]) == 'X'))
2781 || t == 'p' || t == 'P'))))
2782 break;
2783 t = c;
2784 PEEKC(c, p);
2786 /* We add a trailing '\0' to ease parsing */
2787 cstr_ccat(&tokcstr, '\0');
2788 tokc.str.size = tokcstr.size;
2789 tokc.str.data = tokcstr.data;
2790 tok = TOK_PPNUM;
2791 break;
2793 case '.':
2794 /* special dot handling because it can also start a number */
2795 PEEKC(c, p);
2796 if (isnum(c)) {
2797 t = '.';
2798 goto parse_num;
2799 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2800 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2801 *--p = c = '.';
2802 goto parse_ident_fast;
2803 } else if (c == '.') {
2804 PEEKC(c, p);
2805 if (c == '.') {
2806 p++;
2807 tok = TOK_DOTS;
2808 } else {
2809 *--p = '.'; /* may underflow into file->unget[] */
2810 tok = '.';
2812 } else {
2813 tok = '.';
2815 break;
2816 case '\'':
2817 case '\"':
2818 is_long = 0;
2819 str_const:
2820 cstr_reset(&tokcstr);
2821 if (is_long)
2822 cstr_ccat(&tokcstr, 'L');
2823 cstr_ccat(&tokcstr, c);
2824 p = parse_pp_string(p, c, &tokcstr);
2825 cstr_ccat(&tokcstr, c);
2826 cstr_ccat(&tokcstr, '\0');
2827 tokc.str.size = tokcstr.size;
2828 tokc.str.data = tokcstr.data;
2829 tok = TOK_PPSTR;
2830 break;
2832 case '<':
2833 PEEKC(c, p);
2834 if (c == '=') {
2835 p++;
2836 tok = TOK_LE;
2837 } else if (c == '<') {
2838 PEEKC(c, p);
2839 if (c == '=') {
2840 p++;
2841 tok = TOK_A_SHL;
2842 } else {
2843 tok = TOK_SHL;
2845 } else {
2846 tok = TOK_LT;
2848 break;
2849 case '>':
2850 PEEKC(c, p);
2851 if (c == '=') {
2852 p++;
2853 tok = TOK_GE;
2854 } else if (c == '>') {
2855 PEEKC(c, p);
2856 if (c == '=') {
2857 p++;
2858 tok = TOK_A_SAR;
2859 } else {
2860 tok = TOK_SAR;
2862 } else {
2863 tok = TOK_GT;
2865 break;
2867 case '&':
2868 PEEKC(c, p);
2869 if (c == '&') {
2870 p++;
2871 tok = TOK_LAND;
2872 } else if (c == '=') {
2873 p++;
2874 tok = TOK_A_AND;
2875 } else {
2876 tok = '&';
2878 break;
2880 case '|':
2881 PEEKC(c, p);
2882 if (c == '|') {
2883 p++;
2884 tok = TOK_LOR;
2885 } else if (c == '=') {
2886 p++;
2887 tok = TOK_A_OR;
2888 } else {
2889 tok = '|';
2891 break;
2893 case '+':
2894 PEEKC(c, p);
2895 if (c == '+') {
2896 p++;
2897 tok = TOK_INC;
2898 } else if (c == '=') {
2899 p++;
2900 tok = TOK_A_ADD;
2901 } else {
2902 tok = '+';
2904 break;
2906 case '-':
2907 PEEKC(c, p);
2908 if (c == '-') {
2909 p++;
2910 tok = TOK_DEC;
2911 } else if (c == '=') {
2912 p++;
2913 tok = TOK_A_SUB;
2914 } else if (c == '>') {
2915 p++;
2916 tok = TOK_ARROW;
2917 } else {
2918 tok = '-';
2920 break;
2922 PARSE2('!', '!', '=', TOK_NE)
2923 PARSE2('=', '=', '=', TOK_EQ)
2924 PARSE2('*', '*', '=', TOK_A_MUL)
2925 PARSE2('%', '%', '=', TOK_A_MOD)
2926 PARSE2('^', '^', '=', TOK_A_XOR)
2928 /* comments or operator */
2929 case '/':
2930 PEEKC(c, p);
2931 if (c == '*') {
2932 p = parse_comment(p);
2933 /* comments replaced by a blank */
2934 tok = ' ';
2935 goto maybe_space;
2936 } else if (c == '/') {
2937 p = parse_line_comment(p);
2938 tok = ' ';
2939 goto maybe_space;
2940 } else if (c == '=') {
2941 p++;
2942 tok = TOK_A_DIV;
2943 } else {
2944 tok = '/';
2946 break;
2948 /* simple tokens */
2949 case '(':
2950 case ')':
2951 case '[':
2952 case ']':
2953 case '{':
2954 case '}':
2955 case ',':
2956 case ';':
2957 case ':':
2958 case '?':
2959 case '~':
2960 case '@': /* only used in assembler */
2961 parse_simple:
2962 tok = c;
2963 p++;
2964 break;
2965 default:
2966 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2967 goto parse_ident_fast;
2968 if (parse_flags & PARSE_FLAG_ASM_FILE)
2969 goto parse_simple;
2970 tcc_error("unrecognized character \\x%02x", c);
2971 break;
2973 tok_flags = 0;
2974 keep_tok_flags:
2975 file->buf_ptr = p;
2976 #if defined(PARSE_DEBUG)
2977 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
2978 #endif
2981 static void macro_subst(
2982 TokenString *tok_str,
2983 Sym **nested_list,
2984 const int *macro_str
2987 /* substitute arguments in replacement lists in macro_str by the values in
2988 args (field d) and return allocated string */
2989 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2991 int t, t0, t1, spc;
2992 const int *st;
2993 Sym *s;
2994 CValue cval;
2995 TokenString str;
2996 CString cstr;
2998 tok_str_new(&str);
2999 t0 = t1 = 0;
3000 while(1) {
3001 TOK_GET(&t, &macro_str, &cval);
3002 if (!t)
3003 break;
3004 if (t == '#') {
3005 /* stringize */
3006 TOK_GET(&t, &macro_str, &cval);
3007 if (!t)
3008 goto bad_stringy;
3009 s = sym_find2(args, t);
3010 if (s) {
3011 cstr_new(&cstr);
3012 cstr_ccat(&cstr, '\"');
3013 st = s->d;
3014 spc = 0;
3015 while (*st >= 0) {
3016 TOK_GET(&t, &st, &cval);
3017 if (t != TOK_PLCHLDR
3018 && t != TOK_NOSUBST
3019 && 0 == check_space(t, &spc)) {
3020 const char *s = get_tok_str(t, &cval);
3021 while (*s) {
3022 if (t == TOK_PPSTR && *s != '\'')
3023 add_char(&cstr, *s);
3024 else
3025 cstr_ccat(&cstr, *s);
3026 ++s;
3030 cstr.size -= spc;
3031 cstr_ccat(&cstr, '\"');
3032 cstr_ccat(&cstr, '\0');
3033 #ifdef PP_DEBUG
3034 printf("\nstringize: <%s>\n", (char *)cstr.data);
3035 #endif
3036 /* add string */
3037 cval.str.size = cstr.size;
3038 cval.str.data = cstr.data;
3039 tok_str_add2(&str, TOK_PPSTR, &cval);
3040 cstr_free(&cstr);
3041 } else {
3042 bad_stringy:
3043 expect("macro parameter after '#'");
3045 } else if (t >= TOK_IDENT) {
3046 s = sym_find2(args, t);
3047 if (s) {
3048 int l0 = str.len;
3049 st = s->d;
3050 /* if '##' is present before or after, no arg substitution */
3051 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
3052 /* special case for var arg macros : ## eats the ','
3053 if empty VA_ARGS variable. */
3054 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
3055 if (*st <= 0) {
3056 /* suppress ',' '##' */
3057 str.len -= 2;
3058 } else {
3059 /* suppress '##' and add variable */
3060 str.len--;
3061 goto add_var;
3064 } else {
3065 add_var:
3066 if (!s->next) {
3067 /* Expand arguments tokens and store them. In most
3068 cases we could also re-expand each argument if
3069 used multiple times, but not if the argument
3070 contains the __COUNTER__ macro. */
3071 TokenString str2;
3072 sym_push2(&s->next, s->v, s->type.t, 0);
3073 tok_str_new(&str2);
3074 macro_subst(&str2, nested_list, st);
3075 tok_str_add(&str2, 0);
3076 s->next->d = str2.str;
3078 st = s->next->d;
3080 for(;;) {
3081 int t2;
3082 TOK_GET(&t2, &st, &cval);
3083 if (t2 <= 0)
3084 break;
3085 tok_str_add2(&str, t2, &cval);
3087 if (str.len == l0) /* expanded to empty string */
3088 tok_str_add(&str, TOK_PLCHLDR);
3089 } else {
3090 tok_str_add(&str, t);
3092 } else {
3093 tok_str_add2(&str, t, &cval);
3095 t0 = t1, t1 = t;
3097 tok_str_add(&str, 0);
3098 return str.str;
3101 static char const ab_month_name[12][4] =
3103 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3104 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3107 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3109 CString cstr;
3110 int n, ret = 1;
3112 cstr_new(&cstr);
3113 if (t1 != TOK_PLCHLDR)
3114 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3115 n = cstr.size;
3116 if (t2 != TOK_PLCHLDR)
3117 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3118 cstr_ccat(&cstr, '\0');
3120 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3121 memcpy(file->buffer, cstr.data, cstr.size);
3122 tok_flags = 0;
3123 for (;;) {
3124 next_nomacro1();
3125 if (0 == *file->buf_ptr)
3126 break;
3127 if (is_space(tok))
3128 continue;
3129 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3130 " preprocessing token", n, (char *)cstr.data, (char*)cstr.data + n);
3131 ret = 0;
3132 break;
3134 tcc_close();
3135 //printf("paste <%s>\n", (char*)cstr.data);
3136 cstr_free(&cstr);
3137 return ret;
3140 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3141 return the resulting string (which must be freed). */
3142 static inline int *macro_twosharps(const int *ptr0)
3144 int t;
3145 CValue cval;
3146 TokenString macro_str1;
3147 int start_of_nosubsts = -1;
3148 const int *ptr;
3150 /* we search the first '##' */
3151 for (ptr = ptr0;;) {
3152 TOK_GET(&t, &ptr, &cval);
3153 if (t == TOK_PPJOIN)
3154 break;
3155 if (t == 0)
3156 return NULL;
3159 tok_str_new(&macro_str1);
3161 //tok_print(" $$$", ptr0);
3162 for (ptr = ptr0;;) {
3163 TOK_GET(&t, &ptr, &cval);
3164 if (t == 0)
3165 break;
3166 if (t == TOK_PPJOIN)
3167 continue;
3168 while (*ptr == TOK_PPJOIN) {
3169 int t1; CValue cv1;
3170 /* given 'a##b', remove nosubsts preceding 'a' */
3171 if (start_of_nosubsts >= 0)
3172 macro_str1.len = start_of_nosubsts;
3173 /* given 'a##b', remove nosubsts preceding 'b' */
3174 while ((t1 = *++ptr) == TOK_NOSUBST)
3176 if (t1 && t1 != TOK_PPJOIN) {
3177 TOK_GET(&t1, &ptr, &cv1);
3178 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3179 if (paste_tokens(t, &cval, t1, &cv1)) {
3180 t = tok, cval = tokc;
3181 } else {
3182 tok_str_add2(&macro_str1, t, &cval);
3183 t = t1, cval = cv1;
3188 if (t == TOK_NOSUBST) {
3189 if (start_of_nosubsts < 0)
3190 start_of_nosubsts = macro_str1.len;
3191 } else {
3192 start_of_nosubsts = -1;
3194 tok_str_add2(&macro_str1, t, &cval);
3196 tok_str_add(&macro_str1, 0);
3197 //tok_print(" ###", macro_str1.str);
3198 return macro_str1.str;
3201 /* peek or read [ws_str == NULL] next token from function macro call,
3202 walking up macro levels up to the file if necessary */
3203 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3205 int t;
3206 const int *p;
3207 Sym *sa;
3209 for (;;) {
3210 if (macro_ptr) {
3211 p = macro_ptr, t = *p;
3212 if (ws_str) {
3213 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3214 tok_str_add(ws_str, t), t = *++p;
3216 if (t == 0) {
3217 end_macro();
3218 /* also, end of scope for nested defined symbol */
3219 sa = *nested_list;
3220 while (sa && sa->v == 0)
3221 sa = sa->prev;
3222 if (sa)
3223 sa->v = 0;
3224 continue;
3226 } else {
3227 uint8_t *p = file->buf_ptr;
3228 int ch = handle_bs(&p);
3229 if (ws_str) {
3230 while (is_space(ch) || ch == '\n' || ch == '/') {
3231 if (ch == '/') {
3232 int c;
3233 PEEKC(c, p);
3234 if (c == '*') {
3235 p = parse_comment(p) - 1;
3236 } else if (c == '/') {
3237 p = parse_line_comment(p) - 1;
3238 } else {
3239 *--p = ch;
3240 break;
3242 ch = ' ';
3244 if (ch == '\n')
3245 file->line_num++;
3246 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3247 tok_str_add(ws_str, ch);
3248 PEEKC(ch, p);
3251 file->buf_ptr = p;
3252 t = ch;
3255 if (ws_str)
3256 return t;
3257 next_nomacro();
3258 return tok;
3262 /* do macro substitution of current token with macro 's' and add
3263 result to (tok_str,tok_len). 'nested_list' is the list of all
3264 macros we got inside to avoid recursing. Return non zero if no
3265 substitution needs to be done */
3266 static int macro_subst_tok(
3267 TokenString *tok_str,
3268 Sym **nested_list,
3269 Sym *s)
3271 Sym *args, *sa, *sa1;
3272 int parlevel, t, t1, spc;
3273 TokenString str;
3274 char *cstrval;
3275 CValue cval;
3276 CString cstr;
3277 char buf[32];
3279 /* if symbol is a macro, prepare substitution */
3280 /* special macros */
3281 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3282 t = tok == TOK___LINE__ ? file->line_num : pp_counter++;
3283 snprintf(buf, sizeof(buf), "%d", t);
3284 cstrval = buf;
3285 t1 = TOK_PPNUM;
3286 goto add_cstr1;
3287 } else if (tok == TOK___FILE__) {
3288 cstrval = file->filename;
3289 goto add_cstr;
3290 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3291 time_t ti;
3292 struct tm *tm;
3294 time(&ti);
3295 tm = localtime(&ti);
3296 if (tok == TOK___DATE__) {
3297 snprintf(buf, sizeof(buf), "%s %2d %d",
3298 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3299 } else {
3300 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3301 tm->tm_hour, tm->tm_min, tm->tm_sec);
3303 cstrval = buf;
3304 add_cstr:
3305 t1 = TOK_STR;
3306 add_cstr1:
3307 cstr_new(&cstr);
3308 cstr_cat(&cstr, cstrval, 0);
3309 cval.str.size = cstr.size;
3310 cval.str.data = cstr.data;
3311 tok_str_add2(tok_str, t1, &cval);
3312 cstr_free(&cstr);
3313 } else if (s->d) {
3314 int saved_parse_flags = parse_flags;
3315 int *joined_str = NULL;
3316 int *mstr = s->d;
3318 if (s->type.t == MACRO_FUNC) {
3319 /* whitespace between macro name and argument list */
3320 TokenString ws_str;
3321 tok_str_new(&ws_str);
3323 spc = 0;
3324 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3325 | PARSE_FLAG_ACCEPT_STRAYS;
3327 /* get next token from argument stream */
3328 t = next_argstream(nested_list, &ws_str);
3329 if (t != '(') {
3330 /* not a macro substitution after all, restore the
3331 * macro token plus all whitespace we've read.
3332 * whitespace is intentionally not merged to preserve
3333 * newlines. */
3334 parse_flags = saved_parse_flags;
3335 tok_str_add(tok_str, tok);
3336 if (parse_flags & PARSE_FLAG_SPACES) {
3337 int i;
3338 for (i = 0; i < ws_str.len; i++)
3339 tok_str_add(tok_str, ws_str.str[i]);
3341 if (ws_str.len && ws_str.str[ws_str.len - 1] == '\n')
3342 tok_flags |= TOK_FLAG_BOL;
3343 tok_str_free_str(ws_str.str);
3344 return 0;
3345 } else {
3346 tok_str_free_str(ws_str.str);
3348 do {
3349 next_nomacro(); /* eat '(' */
3350 } while (tok == TOK_PLCHLDR || is_space(tok));
3352 /* argument macro */
3353 args = NULL;
3354 sa = s->next;
3355 /* NOTE: empty args are allowed, except if no args */
3356 for(;;) {
3357 do {
3358 next_argstream(nested_list, NULL);
3359 } while (tok == TOK_PLCHLDR || is_space(tok) ||
3360 TOK_LINEFEED == tok);
3361 empty_arg:
3362 /* handle '()' case */
3363 if (!args && !sa && tok == ')')
3364 break;
3365 if (!sa)
3366 tcc_error("macro '%s' used with too many args",
3367 get_tok_str(s->v, 0));
3368 tok_str_new(&str);
3369 parlevel = spc = 0;
3370 /* NOTE: non zero sa->t indicates VA_ARGS */
3371 while ((parlevel > 0 ||
3372 (tok != ')' &&
3373 (tok != ',' || sa->type.t)))) {
3374 if (tok == TOK_EOF || tok == 0)
3375 break;
3376 if (tok == '(')
3377 parlevel++;
3378 else if (tok == ')')
3379 parlevel--;
3380 if (tok == TOK_LINEFEED)
3381 tok = ' ';
3382 if (!check_space(tok, &spc))
3383 tok_str_add2(&str, tok, &tokc);
3384 next_argstream(nested_list, NULL);
3386 if (parlevel)
3387 expect(")");
3388 str.len -= spc;
3389 tok_str_add(&str, -1);
3390 tok_str_add(&str, 0);
3391 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3392 sa1->d = str.str;
3393 sa = sa->next;
3394 if (tok == ')') {
3395 /* special case for gcc var args: add an empty
3396 var arg argument if it is omitted */
3397 if (sa && sa->type.t && gnu_ext)
3398 goto empty_arg;
3399 break;
3401 if (tok != ',')
3402 expect(",");
3404 if (sa) {
3405 tcc_error("macro '%s' used with too few args",
3406 get_tok_str(s->v, 0));
3409 /* now subst each arg */
3410 mstr = macro_arg_subst(nested_list, mstr, args);
3411 /* free memory */
3412 sa = args;
3413 while (sa) {
3414 sa1 = sa->prev;
3415 tok_str_free_str(sa->d);
3416 if (sa->next) {
3417 tok_str_free_str(sa->next->d);
3418 sym_free(sa->next);
3420 sym_free(sa);
3421 sa = sa1;
3423 parse_flags = saved_parse_flags;
3426 sym_push2(nested_list, s->v, 0, 0);
3427 parse_flags = saved_parse_flags;
3428 joined_str = macro_twosharps(mstr);
3429 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3431 /* pop nested defined symbol */
3432 sa1 = *nested_list;
3433 *nested_list = sa1->prev;
3434 sym_free(sa1);
3435 if (joined_str)
3436 tok_str_free_str(joined_str);
3437 if (mstr != s->d)
3438 tok_str_free_str(mstr);
3440 return 0;
3443 /* do macro substitution of macro_str and add result to
3444 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3445 inside to avoid recursing. */
3446 static void macro_subst(
3447 TokenString *tok_str,
3448 Sym **nested_list,
3449 const int *macro_str
3452 Sym *s;
3453 int t, spc, nosubst;
3454 CValue cval;
3456 spc = nosubst = 0;
3458 while (1) {
3459 TOK_GET(&t, &macro_str, &cval);
3460 if (t <= 0)
3461 break;
3463 if (t >= TOK_IDENT && 0 == nosubst) {
3464 s = define_find(t);
3465 if (s == NULL)
3466 goto no_subst;
3468 /* if nested substitution, do nothing */
3469 if (sym_find2(*nested_list, t)) {
3470 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3471 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3472 goto no_subst;
3476 TokenString *str = tok_str_alloc();
3477 str->str = (int*)macro_str;
3478 begin_macro(str, 2);
3480 tok = t;
3481 macro_subst_tok(tok_str, nested_list, s);
3483 if (macro_stack != str) {
3484 /* already finished by reading function macro arguments */
3485 break;
3488 macro_str = macro_ptr;
3489 end_macro ();
3491 if (tok_str->len)
3492 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3493 } else {
3494 no_subst:
3495 if (!check_space(t, &spc))
3496 tok_str_add2(tok_str, t, &cval);
3498 if (nosubst) {
3499 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3500 continue;
3501 nosubst = 0;
3503 if (t == TOK_NOSUBST)
3504 nosubst = 1;
3506 /* GCC supports 'defined' as result of a macro substitution */
3507 if (t == TOK_DEFINED && pp_expr)
3508 nosubst = 2;
3512 /* return next token without macro substitution. Can read input from
3513 macro_ptr buffer */
3514 static void next_nomacro(void)
3516 int t;
3517 if (macro_ptr) {
3518 redo:
3519 t = *macro_ptr;
3520 if (TOK_HAS_VALUE(t)) {
3521 tok_get(&tok, &macro_ptr, &tokc);
3522 if (t == TOK_LINENUM) {
3523 file->line_num = tokc.i;
3524 goto redo;
3526 } else {
3527 macro_ptr++;
3528 if (t < TOK_IDENT) {
3529 if (!(parse_flags & PARSE_FLAG_SPACES)
3530 && (isidnum_table[t - CH_EOF] & IS_SPC))
3531 goto redo;
3533 tok = t;
3535 } else {
3536 next_nomacro1();
3540 /* return next token with macro substitution */
3541 ST_FUNC void next(void)
3543 int t;
3544 redo:
3545 next_nomacro();
3546 t = tok;
3547 if (macro_ptr) {
3548 if (!TOK_HAS_VALUE(t)) {
3549 if (t == TOK_NOSUBST || t == TOK_PLCHLDR) {
3550 /* discard preprocessor markers */
3551 goto redo;
3552 } else if (t == 0) {
3553 /* end of macro or unget token string */
3554 end_macro();
3555 goto redo;
3556 } else if (t == '\\') {
3557 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3558 tcc_error("stray '\\' in program");
3560 return;
3562 } else if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3563 /* if reading from file, try to substitute macros */
3564 Sym *s = define_find(t);
3565 if (s) {
3566 Sym *nested_list = NULL;
3567 tokstr_buf.len = 0;
3568 macro_subst_tok(&tokstr_buf, &nested_list, s);
3569 tok_str_add(&tokstr_buf, 0);
3570 begin_macro(&tokstr_buf, 0);
3571 goto redo;
3573 return;
3575 /* convert preprocessor tokens into C tokens */
3576 if (t == TOK_PPNUM) {
3577 if (parse_flags & PARSE_FLAG_TOK_NUM)
3578 parse_number((char *)tokc.str.data);
3579 } else if (t == TOK_PPSTR) {
3580 if (parse_flags & PARSE_FLAG_TOK_STR)
3581 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3585 /* push back current token and set current token to 'last_tok'. Only
3586 identifier case handled for labels. */
3587 ST_INLN void unget_tok(int last_tok)
3590 TokenString *str = tok_str_alloc();
3591 tok_str_add2(str, tok, &tokc);
3592 tok_str_add(str, 0);
3593 begin_macro(str, 1);
3594 tok = last_tok;
3597 /* ------------------------------------------------------------------------- */
3598 /* init preprocessor */
3600 static const char * const target_os_defs =
3601 #ifdef TCC_TARGET_PE
3602 "_WIN32\0"
3603 # if PTR_SIZE == 8
3604 "_WIN64\0"
3605 # endif
3606 #else
3607 # if defined TCC_TARGET_MACHO
3608 "__APPLE__\0"
3609 # elif TARGETOS_FreeBSD
3610 "__FreeBSD__ 12\0"
3611 # elif TARGETOS_FreeBSD_kernel
3612 "__FreeBSD_kernel__\0"
3613 # elif TARGETOS_NetBSD
3614 "__NetBSD__\0"
3615 # elif TARGETOS_OpenBSD
3616 "__OpenBSD__\0"
3617 # else
3618 "__linux__\0"
3619 "__linux\0"
3620 # if TARGETOS_ANDROID
3621 "__ANDROID__\0"
3622 # endif
3623 # endif
3624 "__unix__\0"
3625 "__unix\0"
3626 #endif
3629 static void putdef(CString *cs, const char *p)
3631 cstr_printf(cs, "#define %s%s\n", p, &" 1"[!!strchr(p, ' ')*2]);
3634 static void putdefs(CString *cs, const char *p)
3636 while (*p)
3637 putdef(cs, p), p = strchr(p, 0) + 1;
3640 static void tcc_predefs(TCCState *s1, CString *cs, int is_asm)
3642 int a, b, c;
3644 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
3645 cstr_printf(cs, "#define __TINYC__ %d\n", a*10000 + b*100 + c);
3647 putdefs(cs, target_machine_defs);
3648 putdefs(cs, target_os_defs);
3650 #ifdef TCC_TARGET_ARM
3651 if (s1->float_abi == ARM_HARD_FLOAT)
3652 putdef(cs, "__ARM_PCS_VFP");
3653 #endif
3654 if (is_asm)
3655 putdef(cs, "__ASSEMBLER__");
3656 if (s1->output_type == TCC_OUTPUT_PREPROCESS)
3657 putdef(cs, "__TCC_PP__");
3658 if (s1->output_type == TCC_OUTPUT_MEMORY)
3659 putdef(cs, "__TCC_RUN__");
3660 if (s1->char_is_unsigned)
3661 putdef(cs, "__CHAR_UNSIGNED__");
3662 if (s1->optimize > 0)
3663 putdef(cs, "__OPTIMIZE__");
3664 if (s1->option_pthread)
3665 putdef(cs, "_REENTRANT");
3666 if (s1->leading_underscore)
3667 putdef(cs, "__leading_underscore");
3668 #ifdef CONFIG_TCC_BCHECK
3669 if (s1->do_bounds_check)
3670 putdef(cs, "__BOUNDS_CHECKING_ON");
3671 #endif
3672 #ifdef CONFIG_TCC_BACKTRACE
3673 if (s1->do_backtrace)
3674 putdef(cs, "__TCC_BACKTRACE_ENABLED__");
3675 #endif
3676 cstr_printf(cs, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE);
3677 cstr_printf(cs, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE);
3678 if (!is_asm) {
3679 putdef(cs, "__STDC__");
3680 cstr_printf(cs, "#define __STDC_VERSION__ %dL\n", s1->cversion);
3681 cstr_cat(cs,
3682 /* load more predefs and __builtins */
3683 #if CONFIG_TCC_PREDEFS
3684 #include "tccdefs_.h" /* include as strings */
3685 #else
3686 "#include <tccdefs.h>\n" /* load at runtime */
3687 #endif
3688 , -1);
3690 cstr_printf(cs, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3693 ST_FUNC void preprocess_start(TCCState *s1, int filetype)
3695 int is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
3696 CString cstr;
3698 tccpp_new(s1);
3700 s1->include_stack_ptr = s1->include_stack;
3701 s1->ifdef_stack_ptr = s1->ifdef_stack;
3702 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3703 pp_expr = 0;
3704 pp_counter = 0;
3705 pp_debug_tok = pp_debug_symv = 0;
3706 pp_once++;
3707 s1->pack_stack[0] = 0;
3708 s1->pack_stack_ptr = s1->pack_stack;
3710 set_idnum('$', !is_asm && s1->dollars_in_identifiers ? IS_ID : 0);
3711 set_idnum('.', is_asm ? IS_ID : 0);
3713 if (!(filetype & AFF_TYPE_ASM)) {
3714 cstr_new(&cstr);
3715 tcc_predefs(s1, &cstr, is_asm);
3716 if (s1->cmdline_defs.size)
3717 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3718 if (s1->cmdline_incl.size)
3719 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3720 //printf("%s\n", (char*)cstr.data);
3721 *s1->include_stack_ptr++ = file;
3722 tcc_open_bf(s1, "<command line>", cstr.size);
3723 memcpy(file->buffer, cstr.data, cstr.size);
3724 cstr_free(&cstr);
3727 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3728 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3731 /* cleanup from error/setjmp */
3732 ST_FUNC void preprocess_end(TCCState *s1)
3734 while (macro_stack)
3735 end_macro();
3736 macro_ptr = NULL;
3737 while (file)
3738 tcc_close();
3739 tccpp_delete(s1);
3742 ST_FUNC int set_idnum(int c, int val)
3744 int prev = isidnum_table[c - CH_EOF];
3745 isidnum_table[c - CH_EOF] = val;
3746 return prev;
3749 ST_FUNC void tccpp_new(TCCState *s)
3751 int i, c;
3752 const char *p, *r;
3754 /* init isid table */
3755 for(i = CH_EOF; i<128; i++)
3756 set_idnum(i,
3757 is_space(i) ? IS_SPC
3758 : isid(i) ? IS_ID
3759 : isnum(i) ? IS_NUM
3760 : 0);
3762 for(i = 128; i<256; i++)
3763 set_idnum(i, IS_ID);
3765 /* init allocators */
3766 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3767 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3769 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3770 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3772 cstr_new(&cstr_buf);
3773 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3774 tok_str_new(&tokstr_buf);
3775 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3777 tok_ident = TOK_IDENT;
3778 p = tcc_keywords;
3779 while (*p) {
3780 r = p;
3781 for(;;) {
3782 c = *r++;
3783 if (c == '\0')
3784 break;
3786 tok_alloc(p, r - p - 1);
3787 p = r;
3790 /* we add dummy defines for some special macros to speed up tests
3791 and to have working defined() */
3792 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3793 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3794 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3795 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3796 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3799 ST_FUNC void tccpp_delete(TCCState *s)
3801 int i, n;
3803 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3805 /* free tokens */
3806 n = tok_ident - TOK_IDENT;
3807 if (n > total_idents)
3808 total_idents = n;
3809 for(i = 0; i < n; i++)
3810 tal_free(toksym_alloc, table_ident[i]);
3811 tcc_free(table_ident);
3812 table_ident = NULL;
3814 /* free static buffers */
3815 cstr_free(&tokcstr);
3816 cstr_free(&cstr_buf);
3817 cstr_free(&macro_equal_buf);
3818 tok_str_free_str(tokstr_buf.str);
3820 /* free allocators */
3821 tal_delete(toksym_alloc);
3822 toksym_alloc = NULL;
3823 tal_delete(tokstr_alloc);
3824 tokstr_alloc = NULL;
3827 /* ------------------------------------------------------------------------- */
3828 /* tcc -E [-P[1]] [-dD} support */
3830 static void tok_print(const char *msg, const int *str)
3832 FILE *fp;
3833 int t, s = 0;
3834 CValue cval;
3836 fp = tcc_state->ppfp;
3837 fprintf(fp, "%s", msg);
3838 while (str) {
3839 TOK_GET(&t, &str, &cval);
3840 if (!t)
3841 break;
3842 fprintf(fp, &" %s"[s], get_tok_str(t, &cval)), s = 1;
3844 fprintf(fp, "\n");
3847 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3849 int d = f->line_num - f->line_ref;
3851 if (s1->dflag & 4)
3852 return;
3854 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3856 } else if (level == 0 && f->line_ref && d < 8) {
3857 while (d > 0)
3858 fputs("\n", s1->ppfp), --d;
3859 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3860 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3861 } else {
3862 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3863 level > 0 ? " 1" : level < 0 ? " 2" : "");
3865 f->line_ref = f->line_num;
3868 static void define_print(TCCState *s1, int v)
3870 FILE *fp;
3871 Sym *s;
3873 s = define_find(v);
3874 if (NULL == s || NULL == s->d)
3875 return;
3877 fp = s1->ppfp;
3878 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3879 if (s->type.t == MACRO_FUNC) {
3880 Sym *a = s->next;
3881 fprintf(fp,"(");
3882 if (a)
3883 for (;;) {
3884 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3885 if (!(a = a->next))
3886 break;
3887 fprintf(fp,",");
3889 fprintf(fp,")");
3891 tok_print("", s->d);
3894 static void pp_debug_defines(TCCState *s1)
3896 int v, t;
3897 const char *vs;
3898 FILE *fp;
3900 t = pp_debug_tok;
3901 if (t == 0)
3902 return;
3904 file->line_num--;
3905 pp_line(s1, file, 0);
3906 file->line_ref = ++file->line_num;
3908 fp = s1->ppfp;
3909 v = pp_debug_symv;
3910 vs = get_tok_str(v, NULL);
3911 if (t == TOK_DEFINE) {
3912 define_print(s1, v);
3913 } else if (t == TOK_UNDEF) {
3914 fprintf(fp, "#undef %s\n", vs);
3915 } else if (t == TOK_push_macro) {
3916 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3917 } else if (t == TOK_pop_macro) {
3918 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3920 pp_debug_tok = 0;
3923 static void pp_debug_builtins(TCCState *s1)
3925 int v;
3926 for (v = TOK_IDENT; v < tok_ident; ++v)
3927 define_print(s1, v);
3930 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3931 static int pp_need_space(int a, int b)
3933 return 'E' == a ? '+' == b || '-' == b
3934 : '+' == a ? TOK_INC == b || '+' == b
3935 : '-' == a ? TOK_DEC == b || '-' == b
3936 : a >= TOK_IDENT ? b >= TOK_IDENT
3937 : a == TOK_PPNUM ? b >= TOK_IDENT
3938 : 0;
3941 /* maybe hex like 0x1e */
3942 static int pp_check_he0xE(int t, const char *p)
3944 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3945 return 'E';
3946 return t;
3949 /* Preprocess the current file */
3950 ST_FUNC int tcc_preprocess(TCCState *s1)
3952 BufferedFile **iptr;
3953 int token_seen, spcs, level;
3954 const char *p;
3955 char white[400];
3957 parse_flags = PARSE_FLAG_PREPROCESS
3958 | (parse_flags & PARSE_FLAG_ASM_FILE)
3959 | PARSE_FLAG_LINEFEED
3960 | PARSE_FLAG_SPACES
3961 | PARSE_FLAG_ACCEPT_STRAYS
3963 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3964 capability to compile and run itself, provided all numbers are
3965 given as decimals. tcc -E -P10 will do. */
3966 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3967 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3969 if (s1->do_bench) {
3970 /* for PP benchmarks */
3971 do next(); while (tok != TOK_EOF);
3972 return 0;
3975 if (s1->dflag & 1) {
3976 pp_debug_builtins(s1);
3977 s1->dflag &= ~1;
3980 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
3981 if (file->prev)
3982 pp_line(s1, file->prev, level++);
3983 pp_line(s1, file, level);
3984 for (;;) {
3985 iptr = s1->include_stack_ptr;
3986 next();
3987 if (tok == TOK_EOF)
3988 break;
3990 level = s1->include_stack_ptr - iptr;
3991 if (level) {
3992 if (level > 0)
3993 pp_line(s1, *iptr, 0);
3994 pp_line(s1, file, level);
3996 if (s1->dflag & 7) {
3997 pp_debug_defines(s1);
3998 if (s1->dflag & 4)
3999 continue;
4002 if (is_space(tok)) {
4003 if (spcs < sizeof white - 1)
4004 white[spcs++] = tok;
4005 continue;
4006 } else if (tok == TOK_LINEFEED) {
4007 spcs = 0;
4008 if (token_seen == TOK_LINEFEED)
4009 continue;
4010 ++file->line_ref;
4011 } else if (token_seen == TOK_LINEFEED) {
4012 pp_line(s1, file, 0);
4013 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
4014 white[spcs++] = ' ';
4017 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
4018 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
4019 token_seen = pp_check_he0xE(tok, p);
4021 return 0;
4024 /* ------------------------------------------------------------------------- */