small scopes cleanup etc.
[tinycc.git] / tccpp.c
blob64de770fefb95280b1b1aa9fc8e851630ba63005
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 return strcpy(p, "<float>");
581 case TOK_CDOUBLE:
582 return strcpy(p, "<double>");
583 case TOK_CLDOUBLE:
584 return strcpy(p, "<long double>");
585 case TOK_LINENUM:
586 return strcpy(p, "<linenumber");
588 /* above tokens have value, the ones below don't */
589 case TOK_LT:
590 v = '<';
591 goto addv;
592 case TOK_GT:
593 v = '>';
594 goto addv;
595 case TOK_DOTS:
596 return strcpy(p, "...");
597 case TOK_A_SHL:
598 return strcpy(p, "<<=");
599 case TOK_A_SAR:
600 return strcpy(p, ">>=");
601 case TOK_EOF:
602 return strcpy(p, "<eof>");
603 case 0: /* anonymous nameless symbols */
604 return strcpy(p, "<no name>");
605 default:
606 if (v < TOK_IDENT) {
607 /* search in two bytes table */
608 const unsigned char *q = tok_two_chars;
609 while (*q) {
610 if (q[2] == v) {
611 *p++ = q[0];
612 *p++ = q[1];
613 *p = '\0';
614 return cstr_buf.data;
616 q += 3;
618 if (v >= 127 || (v < 32 && !is_space(v) && v != '\n')) {
619 sprintf(p, "<\\x%02x>", v);
620 break;
622 addv:
623 *p++ = v;
624 *p = '\0';
625 } else if (v < tok_ident) {
626 return table_ident[v - TOK_IDENT]->str;
627 } else if (v >= SYM_FIRST_ANOM) {
628 /* special name for anonymous symbol */
629 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
630 } else {
631 /* should never happen */
632 return NULL;
634 break;
636 return cstr_buf.data;
639 static inline int check_space(int t, int *spc)
641 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
642 if (*spc)
643 return 1;
644 *spc = 1;
645 } else
646 *spc = 0;
647 return 0;
650 /* return the current character, handling end of block if necessary
651 (but not stray) */
652 static int handle_eob(void)
654 BufferedFile *bf = file;
655 int len;
657 /* only tries to read if really end of buffer */
658 if (bf->buf_ptr >= bf->buf_end) {
659 if (bf->fd >= 0) {
660 #if defined(PARSE_DEBUG)
661 len = 1;
662 #else
663 len = IO_BUF_SIZE;
664 #endif
665 len = read(bf->fd, bf->buffer, len);
666 if (len < 0)
667 len = 0;
668 } else {
669 len = 0;
671 total_bytes += len;
672 bf->buf_ptr = bf->buffer;
673 bf->buf_end = bf->buffer + len;
674 *bf->buf_end = CH_EOB;
676 if (bf->buf_ptr < bf->buf_end) {
677 return bf->buf_ptr[0];
678 } else {
679 bf->buf_ptr = bf->buf_end;
680 return CH_EOF;
684 /* read next char from current input file and handle end of input buffer */
685 static int next_c(void)
687 int ch = *++file->buf_ptr;
688 /* end of buffer/file handling */
689 if (ch == CH_EOB && file->buf_ptr >= file->buf_end)
690 ch = handle_eob();
691 return ch;
694 /* input with '\[\r]\n' handling. */
695 static int handle_stray_noerror(int err)
697 int ch;
698 while ((ch = next_c()) == '\\') {
699 ch = next_c();
700 if (ch == '\n') {
701 newl:
702 file->line_num++;
703 } else {
704 if (ch == '\r') {
705 ch = next_c();
706 if (ch == '\n')
707 goto newl;
708 *--file->buf_ptr = '\r';
710 if (err)
711 tcc_error("stray '\\' in program");
712 /* may take advantage of 'BufferedFile.unget[4}' */
713 return *--file->buf_ptr = '\\';
716 return ch;
719 #define ninp() handle_stray_noerror(0)
721 /* handle '\\' in strings, comments and skipped regions */
722 static int handle_bs(uint8_t **p)
724 int c;
725 file->buf_ptr = *p - 1;
726 c = ninp();
727 *p = file->buf_ptr;
728 return c;
731 /* skip the stray and handle the \\n case. Output an error if
732 incorrect char after the stray */
733 static int handle_stray(uint8_t **p)
735 int c;
736 file->buf_ptr = *p - 1;
737 c = handle_stray_noerror(!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS));
738 *p = file->buf_ptr;
739 return c;
742 /* handle the complicated stray case */
743 #define PEEKC(c, p)\
745 c = *++p;\
746 if (c == '\\')\
747 c = handle_stray(&p); \
750 static int skip_spaces(void)
752 int ch;
753 --file->buf_ptr;
754 do {
755 ch = ninp();
756 } while (isidnum_table[ch - CH_EOF] & IS_SPC);
757 return ch;
760 /* single line C++ comments */
761 static uint8_t *parse_line_comment(uint8_t *p)
763 int c;
764 for(;;) {
765 for (;;) {
766 c = *++p;
767 redo:
768 if (c == '\n' || c == '\\')
769 break;
770 c = *++p;
771 if (c == '\n' || c == '\\')
772 break;
774 if (c == '\n')
775 break;
776 c = handle_bs(&p);
777 if (c == CH_EOF)
778 break;
779 if (c != '\\')
780 goto redo;
782 return p;
785 /* C comments */
786 static uint8_t *parse_comment(uint8_t *p)
788 int c;
789 for(;;) {
790 /* fast skip loop */
791 for(;;) {
792 c = *++p;
793 redo:
794 if (c == '\n' || c == '*' || c == '\\')
795 break;
796 c = *++p;
797 if (c == '\n' || c == '*' || c == '\\')
798 break;
800 /* now we can handle all the cases */
801 if (c == '\n') {
802 file->line_num++;
803 } else if (c == '*') {
804 do {
805 c = *++p;
806 } while (c == '*');
807 if (c == '\\')
808 c = handle_bs(&p);
809 if (c == '/')
810 break;
811 goto check_eof;
812 } else {
813 c = handle_bs(&p);
814 check_eof:
815 if (c == CH_EOF)
816 tcc_error("unexpected end of file in comment");
817 if (c != '\\')
818 goto redo;
821 return p + 1;
824 /* parse a string without interpreting escapes */
825 static uint8_t *parse_pp_string(uint8_t *p, int sep, CString *str)
827 int c;
828 for(;;) {
829 c = *++p;
830 redo:
831 if (c == sep) {
832 break;
833 } else if (c == '\\') {
834 c = handle_bs(&p);
835 if (c == CH_EOF) {
836 unterminated_string:
837 /* XXX: indicate line number of start of string */
838 tok_flags &= ~TOK_FLAG_BOL;
839 tcc_error("missing terminating %c character", sep);
840 } else if (c == '\\') {
841 if (str)
842 cstr_ccat(str, c);
843 c = *++p;
844 /* add char after '\\' unconditionally */
845 if (c == '\\') {
846 c = handle_bs(&p);
847 if (c == CH_EOF)
848 goto unterminated_string;
850 goto add_char;
851 } else {
852 goto redo;
854 } else if (c == '\n') {
855 add_lf:
856 if (ACCEPT_LF_IN_STRINGS) {
857 file->line_num++;
858 goto add_char;
859 } else if (str) { /* not skipping */
860 goto unterminated_string;
861 } else {
862 //tcc_warning("missing terminating %c character", sep);
863 return p;
865 } else if (c == '\r') {
866 c = *++p;
867 if (c == '\\')
868 c = handle_bs(&p);
869 if (c == '\n')
870 goto add_lf;
871 if (c == CH_EOF)
872 goto unterminated_string;
873 if (str)
874 cstr_ccat(str, '\r');
875 goto redo;
876 } else {
877 add_char:
878 if (str)
879 cstr_ccat(str, c);
882 p++;
883 return p;
886 /* skip block of text until #else, #elif or #endif. skip also pairs of
887 #if/#endif */
888 static void preprocess_skip(void)
890 int a, start_of_line, c, in_warn_or_error;
891 uint8_t *p;
893 p = file->buf_ptr;
894 a = 0;
895 redo_start:
896 start_of_line = 1;
897 in_warn_or_error = 0;
898 for(;;) {
899 redo_no_start:
900 c = *p;
901 switch(c) {
902 case ' ':
903 case '\t':
904 case '\f':
905 case '\v':
906 case '\r':
907 p++;
908 goto redo_no_start;
909 case '\n':
910 file->line_num++;
911 p++;
912 goto redo_start;
913 case '\\':
914 c = handle_bs(&p);
915 if (c == CH_EOF)
916 expect("#endif");
917 if (c == '\\')
918 ++p;
919 goto redo_no_start;
920 /* skip strings */
921 case '\"':
922 case '\'':
923 if (in_warn_or_error)
924 goto _default;
925 tok_flags &= ~TOK_FLAG_BOL;
926 p = parse_pp_string(p, c, NULL);
927 break;
928 /* skip comments */
929 case '/':
930 if (in_warn_or_error)
931 goto _default;
932 ++p;
933 c = handle_bs(&p);
934 if (c == '*') {
935 p = parse_comment(p);
936 } else if (c == '/') {
937 p = parse_line_comment(p);
939 break;
940 case '#':
941 p++;
942 if (start_of_line) {
943 file->buf_ptr = p;
944 next_nomacro();
945 p = file->buf_ptr;
946 if (a == 0 &&
947 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
948 goto the_end;
949 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
950 a++;
951 else if (tok == TOK_ENDIF)
952 a--;
953 else if( tok == TOK_ERROR || tok == TOK_WARNING)
954 in_warn_or_error = 1;
955 else if (tok == TOK_LINEFEED)
956 goto redo_start;
957 else if (parse_flags & PARSE_FLAG_ASM_FILE)
958 p = parse_line_comment(p - 1);
960 #if !defined(TCC_TARGET_ARM)
961 else if (parse_flags & PARSE_FLAG_ASM_FILE)
962 p = parse_line_comment(p - 1);
963 #else
964 /* ARM assembly uses '#' for constants */
965 #endif
966 break;
967 _default:
968 default:
969 p++;
970 break;
972 start_of_line = 0;
974 the_end: ;
975 file->buf_ptr = p;
978 #if 0
979 /* return the number of additional 'ints' necessary to store the
980 token */
981 static inline int tok_size(const int *p)
983 switch(*p) {
984 /* 4 bytes */
985 case TOK_CINT:
986 case TOK_CUINT:
987 case TOK_CCHAR:
988 case TOK_LCHAR:
989 case TOK_CFLOAT:
990 case TOK_LINENUM:
991 return 1 + 1;
992 case TOK_STR:
993 case TOK_LSTR:
994 case TOK_PPNUM:
995 case TOK_PPSTR:
996 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
997 case TOK_CLONG:
998 case TOK_CULONG:
999 return 1 + LONG_SIZE / 4;
1000 case TOK_CDOUBLE:
1001 case TOK_CLLONG:
1002 case TOK_CULLONG:
1003 return 1 + 2;
1004 case TOK_CLDOUBLE:
1005 return 1 + LDOUBLE_SIZE / 4;
1006 default:
1007 return 1 + 0;
1010 #endif
1012 /* token string handling */
1013 ST_INLN void tok_str_new(TokenString *s)
1015 s->str = NULL;
1016 s->len = s->lastlen = 0;
1017 s->allocated_len = 0;
1018 s->last_line_num = -1;
1021 ST_FUNC TokenString *tok_str_alloc(void)
1023 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1024 tok_str_new(str);
1025 return str;
1028 ST_FUNC int *tok_str_dup(TokenString *s)
1030 int *str;
1032 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1033 memcpy(str, s->str, s->len * sizeof(int));
1034 return str;
1037 ST_FUNC void tok_str_free_str(int *str)
1039 tal_free(tokstr_alloc, str);
1042 ST_FUNC void tok_str_free(TokenString *str)
1044 tok_str_free_str(str->str);
1045 tal_free(tokstr_alloc, str);
1048 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1050 int *str, size;
1052 size = s->allocated_len;
1053 if (size < 16)
1054 size = 16;
1055 while (size < new_size)
1056 size = size * 2;
1057 if (size > s->allocated_len) {
1058 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1059 s->allocated_len = size;
1060 s->str = str;
1062 return s->str;
1065 ST_FUNC void tok_str_add(TokenString *s, int t)
1067 int len, *str;
1069 len = s->len;
1070 str = s->str;
1071 if (len >= s->allocated_len)
1072 str = tok_str_realloc(s, len + 1);
1073 str[len++] = t;
1074 s->len = len;
1077 ST_FUNC void begin_macro(TokenString *str, int alloc)
1079 str->alloc = alloc;
1080 str->prev = macro_stack;
1081 str->prev_ptr = macro_ptr;
1082 str->save_line_num = file->line_num;
1083 macro_ptr = str->str;
1084 macro_stack = str;
1087 ST_FUNC void end_macro(void)
1089 TokenString *str = macro_stack;
1090 macro_stack = str->prev;
1091 macro_ptr = str->prev_ptr;
1092 file->line_num = str->save_line_num;
1093 str->len = 0; /* matters if str not alloced, may be tokstr_buf */
1094 if (str->alloc != 0) {
1095 if (str->alloc == 2)
1096 str->str = NULL; /* don't free */
1097 tok_str_free(str);
1101 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1103 int len, *str;
1105 len = s->lastlen = s->len;
1106 str = s->str;
1108 /* allocate space for worst case */
1109 if (len + TOK_MAX_SIZE >= s->allocated_len)
1110 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1111 str[len++] = t;
1112 switch(t) {
1113 case TOK_CINT:
1114 case TOK_CUINT:
1115 case TOK_CCHAR:
1116 case TOK_LCHAR:
1117 case TOK_CFLOAT:
1118 case TOK_LINENUM:
1119 #if LONG_SIZE == 4
1120 case TOK_CLONG:
1121 case TOK_CULONG:
1122 #endif
1123 str[len++] = cv->tab[0];
1124 break;
1125 case TOK_PPNUM:
1126 case TOK_PPSTR:
1127 case TOK_STR:
1128 case TOK_LSTR:
1130 /* Insert the string into the int array. */
1131 size_t nb_words =
1132 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1133 if (len + nb_words >= s->allocated_len)
1134 str = tok_str_realloc(s, len + nb_words + 1);
1135 str[len] = cv->str.size;
1136 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1137 len += nb_words;
1139 break;
1140 case TOK_CDOUBLE:
1141 case TOK_CLLONG:
1142 case TOK_CULLONG:
1143 #if LONG_SIZE == 8
1144 case TOK_CLONG:
1145 case TOK_CULONG:
1146 #endif
1147 #if LDOUBLE_SIZE == 8
1148 case TOK_CLDOUBLE:
1149 #endif
1150 str[len++] = cv->tab[0];
1151 str[len++] = cv->tab[1];
1152 break;
1153 #if LDOUBLE_SIZE == 12
1154 case TOK_CLDOUBLE:
1155 str[len++] = cv->tab[0];
1156 str[len++] = cv->tab[1];
1157 str[len++] = cv->tab[2];
1158 #elif LDOUBLE_SIZE == 16
1159 case TOK_CLDOUBLE:
1160 str[len++] = cv->tab[0];
1161 str[len++] = cv->tab[1];
1162 str[len++] = cv->tab[2];
1163 str[len++] = cv->tab[3];
1164 #elif LDOUBLE_SIZE != 8
1165 #error add long double size support
1166 #endif
1167 break;
1168 default:
1169 break;
1171 s->len = len;
1174 /* add the current parse token in token string 's' */
1175 ST_FUNC void tok_str_add_tok(TokenString *s)
1177 CValue cval;
1179 /* save line number info */
1180 if (file->line_num != s->last_line_num) {
1181 s->last_line_num = file->line_num;
1182 cval.i = s->last_line_num;
1183 tok_str_add2(s, TOK_LINENUM, &cval);
1185 tok_str_add2(s, tok, &tokc);
1188 /* get a token from an integer array and increment pointer. */
1189 static inline void tok_get(int *t, const int **pp, CValue *cv)
1191 const int *p = *pp;
1192 int n, *tab;
1194 tab = cv->tab;
1195 switch(*t = *p++) {
1196 #if LONG_SIZE == 4
1197 case TOK_CLONG:
1198 #endif
1199 case TOK_CINT:
1200 case TOK_CCHAR:
1201 case TOK_LCHAR:
1202 case TOK_LINENUM:
1203 cv->i = *p++;
1204 break;
1205 #if LONG_SIZE == 4
1206 case TOK_CULONG:
1207 #endif
1208 case TOK_CUINT:
1209 cv->i = (unsigned)*p++;
1210 break;
1211 case TOK_CFLOAT:
1212 tab[0] = *p++;
1213 break;
1214 case TOK_STR:
1215 case TOK_LSTR:
1216 case TOK_PPNUM:
1217 case TOK_PPSTR:
1218 cv->str.size = *p++;
1219 cv->str.data = p;
1220 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1221 break;
1222 case TOK_CDOUBLE:
1223 case TOK_CLLONG:
1224 case TOK_CULLONG:
1225 #if LONG_SIZE == 8
1226 case TOK_CLONG:
1227 case TOK_CULONG:
1228 #endif
1229 n = 2;
1230 goto copy;
1231 case TOK_CLDOUBLE:
1232 #if LDOUBLE_SIZE == 16
1233 n = 4;
1234 #elif LDOUBLE_SIZE == 12
1235 n = 3;
1236 #elif LDOUBLE_SIZE == 8
1237 n = 2;
1238 #else
1239 # error add long double size support
1240 #endif
1241 copy:
1243 *tab++ = *p++;
1244 while (--n);
1245 break;
1246 default:
1247 break;
1249 *pp = p;
1252 #if 0
1253 # define TOK_GET(t,p,c) tok_get(t,p,c)
1254 #else
1255 # define TOK_GET(t,p,c) do { \
1256 int _t = **(p); \
1257 if (TOK_HAS_VALUE(_t)) \
1258 tok_get(t, p, c); \
1259 else \
1260 *(t) = _t, ++*(p); \
1261 } while (0)
1262 #endif
1264 static int macro_is_equal(const int *a, const int *b)
1266 CValue cv;
1267 int t;
1269 if (!a || !b)
1270 return 1;
1272 while (*a && *b) {
1273 /* first time preallocate macro_equal_buf, next time only reset position to start */
1274 cstr_reset(&macro_equal_buf);
1275 TOK_GET(&t, &a, &cv);
1276 cstr_cat(&macro_equal_buf, get_tok_str(t, &cv), 0);
1277 TOK_GET(&t, &b, &cv);
1278 if (strcmp(macro_equal_buf.data, get_tok_str(t, &cv)))
1279 return 0;
1281 return !(*a || *b);
1284 /* defines handling */
1285 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1287 Sym *s, *o;
1289 o = define_find(v);
1290 s = sym_push2(&define_stack, v, macro_type, 0);
1291 s->d = str;
1292 s->next = first_arg;
1293 table_ident[v - TOK_IDENT]->sym_define = s;
1295 if (o && !macro_is_equal(o->d, s->d))
1296 tcc_warning("%s redefined", get_tok_str(v, NULL));
1299 /* undefined a define symbol. Its name is just set to zero */
1300 ST_FUNC void define_undef(Sym *s)
1302 int v = s->v;
1303 if (v >= TOK_IDENT && v < tok_ident)
1304 table_ident[v - TOK_IDENT]->sym_define = NULL;
1307 ST_INLN Sym *define_find(int v)
1309 v -= TOK_IDENT;
1310 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1311 return NULL;
1312 return table_ident[v]->sym_define;
1315 /* free define stack until top reaches 'b' */
1316 ST_FUNC void free_defines(Sym *b)
1318 while (define_stack != b) {
1319 Sym *top = define_stack;
1320 define_stack = top->prev;
1321 tok_str_free_str(top->d);
1322 define_undef(top);
1323 sym_free(top);
1327 /* fake the nth "#if defined test_..." for tcc -dt -run */
1328 static void maybe_run_test(TCCState *s)
1330 const char *p;
1331 if (s->include_stack_ptr != s->include_stack)
1332 return;
1333 p = get_tok_str(tok, NULL);
1334 if (0 != memcmp(p, "test_", 5))
1335 return;
1336 if (0 != --s->run_test)
1337 return;
1338 fprintf(s->ppfp, &"\n[%s]\n"[!(s->dflag & 32)], p), fflush(s->ppfp);
1339 define_push(tok, MACRO_OBJ, NULL, NULL);
1342 static CachedInclude *
1343 search_cached_include(TCCState *s1, const char *filename, int add);
1345 static int parse_include(TCCState *s1, int do_next, int test)
1347 int c, i;
1348 CString cs;
1349 char name[1024], buf[1024], *p;
1350 CachedInclude *e;
1352 cstr_new(&cs);
1353 c = skip_spaces();
1354 if (c == '<' || c == '\"') {
1355 file->buf_ptr = parse_pp_string(file->buf_ptr, c == '<' ? '>' : c, &cs);
1356 next_nomacro();
1357 } else {
1358 /* computed #include : concatenate tokens until result is one of
1359 the two accepted forms. Don't convert pp-tokens to tokens here. */
1360 parse_flags = PARSE_FLAG_PREPROCESS
1361 | PARSE_FLAG_LINEFEED
1362 | (parse_flags & PARSE_FLAG_ASM_FILE);
1363 for (;;) {
1364 next();
1365 p = cs.data, i = cs.size - 1;
1366 if (i > 0
1367 && ((p[0] == '"' && p[i] == '"')
1368 || (p[0] == '<' && p[i] == '>')))
1369 break;
1370 if (tok == TOK_LINEFEED)
1371 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1372 cstr_cat(&cs, get_tok_str(tok, &tokc), -1);
1374 c = p[0];
1375 /* remove '<>|""' */
1376 memmove(p, p + 1, cs.size -= 2);
1378 cstr_ccat(&cs, '\0');
1379 pstrcpy(name, sizeof name, cs.data);
1380 cstr_free(&cs);
1382 i = do_next ? file->include_next_index : -1;
1383 for (;;) {
1384 ++i;
1385 if (i == 0) {
1386 /* check absolute include path */
1387 if (!IS_ABSPATH(name))
1388 continue;
1389 buf[0] = '\0';
1390 } else if (i == 1) {
1391 /* search in file's dir if "header.h" */
1392 if (c != '\"')
1393 continue;
1394 p = file->true_filename;
1395 pstrncpy(buf, p, tcc_basename(p) - p);
1396 } else {
1397 int j = i - 2, k = j - s1->nb_include_paths;
1398 if (k < 0)
1399 p = s1->include_paths[j];
1400 else if (k < s1->nb_sysinclude_paths)
1401 p = s1->sysinclude_paths[k];
1402 else if (test)
1403 return 0;
1404 else
1405 tcc_error("include file '%s' not found", name);
1406 pstrcpy(buf, sizeof buf, p);
1407 pstrcat(buf, sizeof buf, "/");
1409 pstrcat(buf, sizeof buf, name);
1410 e = search_cached_include(s1, buf, 0);
1411 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1412 /* no need to parse the include because the 'ifndef macro'
1413 is defined (or had #pragma once) */
1414 #ifdef INC_DEBUG
1415 printf("%s: skipping cached %s\n", file->filename, buf);
1416 #endif
1417 return 1;
1419 if (tcc_open(s1, buf) >= 0)
1420 break;
1423 if (test) {
1424 tcc_close();
1425 } else {
1426 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1427 tcc_error("#include recursion too deep");
1428 /* push previous file on stack */
1429 *s1->include_stack_ptr++ = file->prev;
1430 file->include_next_index = i;
1431 #ifdef INC_DEBUG
1432 printf("%s: including %s\n", file->prev->filename, file->filename);
1433 #endif
1434 /* update target deps */
1435 if (s1->gen_deps) {
1436 BufferedFile *bf = file;
1437 while (i == 1 && (bf = bf->prev))
1438 i = bf->include_next_index;
1439 /* skip system include files */
1440 if (s1->include_sys_deps || i - 2 < s1->nb_include_paths)
1441 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1442 tcc_strdup(buf));
1444 /* add include file debug info */
1445 tcc_debug_bincl(s1);
1446 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1448 return 1;
1451 /* eval an expression for #if/#elif */
1452 static int expr_preprocess(TCCState *s1)
1454 int c, t;
1455 TokenString *str;
1457 str = tok_str_alloc();
1458 pp_expr = 1;
1459 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1460 next(); /* do macro subst */
1461 redo:
1462 if (tok == TOK_DEFINED) {
1463 next_nomacro();
1464 t = tok;
1465 if (t == '(')
1466 next_nomacro();
1467 if (tok < TOK_IDENT)
1468 expect("identifier");
1469 if (s1->run_test)
1470 maybe_run_test(s1);
1471 c = 0;
1472 if (define_find(tok)
1473 || tok == TOK___HAS_INCLUDE
1474 || tok == TOK___HAS_INCLUDE_NEXT)
1475 c = 1;
1476 if (t == '(') {
1477 next_nomacro();
1478 if (tok != ')')
1479 expect("')'");
1481 tok = TOK_CINT;
1482 tokc.i = c;
1483 } else if (tok == TOK___HAS_INCLUDE ||
1484 tok == TOK___HAS_INCLUDE_NEXT) {
1485 t = tok;
1486 next_nomacro();
1487 if (tok != '(')
1488 expect("(");
1489 c = parse_include(s1, t - TOK___HAS_INCLUDE, 1);
1490 if (tok != ')')
1491 expect("')'");
1492 tok = TOK_CINT;
1493 tokc.i = c;
1494 } else if (tok >= TOK_IDENT) {
1495 /* if undefined macro, replace with zero, check for func-like */
1496 t = tok;
1497 tok = TOK_CINT;
1498 tokc.i = 0;
1499 tok_str_add_tok(str);
1500 next();
1501 if (tok == '(')
1502 tcc_error("function-like macro '%s' is not defined",
1503 get_tok_str(t, NULL));
1504 goto redo;
1506 tok_str_add_tok(str);
1508 pp_expr = 0;
1509 tok_str_add(str, -1); /* simulate end of file */
1510 tok_str_add(str, 0);
1511 /* now evaluate C constant expression */
1512 begin_macro(str, 1);
1513 next();
1514 c = expr_const();
1515 end_macro();
1516 return c != 0;
1520 /* parse after #define */
1521 ST_FUNC void parse_define(void)
1523 Sym *s, *first, **ps;
1524 int v, t, varg, is_vaargs, spc;
1525 int saved_parse_flags = parse_flags;
1527 v = tok;
1528 if (v < TOK_IDENT || v == TOK_DEFINED)
1529 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1530 /* XXX: should check if same macro (ANSI) */
1531 first = NULL;
1532 t = MACRO_OBJ;
1533 /* We have to parse the whole define as if not in asm mode, in particular
1534 no line comment with '#' must be ignored. Also for function
1535 macros the argument list must be parsed without '.' being an ID
1536 character. */
1537 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1538 /* '(' must be just after macro definition for MACRO_FUNC */
1539 next_nomacro();
1540 parse_flags &= ~PARSE_FLAG_SPACES;
1541 if (tok == '(') {
1542 int dotid = set_idnum('.', 0);
1543 next_nomacro();
1544 ps = &first;
1545 if (tok != ')') for (;;) {
1546 varg = tok;
1547 next_nomacro();
1548 is_vaargs = 0;
1549 if (varg == TOK_DOTS) {
1550 varg = TOK___VA_ARGS__;
1551 is_vaargs = 1;
1552 } else if (tok == TOK_DOTS && gnu_ext) {
1553 is_vaargs = 1;
1554 next_nomacro();
1556 if (varg < TOK_IDENT)
1557 bad_list:
1558 tcc_error("bad macro parameter list");
1559 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1560 *ps = s;
1561 ps = &s->next;
1562 if (tok == ')')
1563 break;
1564 if (tok != ',' || is_vaargs)
1565 goto bad_list;
1566 next_nomacro();
1568 parse_flags |= PARSE_FLAG_SPACES;
1569 next_nomacro();
1570 t = MACRO_FUNC;
1571 set_idnum('.', dotid);
1574 tokstr_buf.len = 0;
1575 spc = 2;
1576 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1577 /* The body of a macro definition should be parsed such that identifiers
1578 are parsed like the file mode determines (i.e. with '.' being an
1579 ID character in asm mode). But '#' should be retained instead of
1580 regarded as line comment leader, so still don't set ASM_FILE
1581 in parse_flags. */
1582 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1583 /* remove spaces around ## and after '#' */
1584 if (TOK_TWOSHARPS == tok) {
1585 if (2 == spc)
1586 goto bad_twosharp;
1587 if (1 == spc)
1588 --tokstr_buf.len;
1589 spc = 3;
1590 tok = TOK_PPJOIN;
1591 } else if ('#' == tok) {
1592 spc = 4;
1593 } else if (check_space(tok, &spc)) {
1594 goto skip;
1596 tok_str_add2(&tokstr_buf, tok, &tokc);
1597 skip:
1598 next_nomacro();
1601 parse_flags = saved_parse_flags;
1602 if (spc == 1)
1603 --tokstr_buf.len; /* remove trailing space */
1604 tok_str_add(&tokstr_buf, 0);
1605 if (3 == spc)
1606 bad_twosharp:
1607 tcc_error("'##' cannot appear at either end of macro");
1608 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1611 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1613 const unsigned char *s;
1614 unsigned int h;
1615 CachedInclude *e;
1616 int i;
1618 h = TOK_HASH_INIT;
1619 s = (unsigned char *) filename;
1620 while (*s) {
1621 #ifdef _WIN32
1622 h = TOK_HASH_FUNC(h, toup(*s));
1623 #else
1624 h = TOK_HASH_FUNC(h, *s);
1625 #endif
1626 s++;
1628 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1630 i = s1->cached_includes_hash[h];
1631 for(;;) {
1632 if (i == 0)
1633 break;
1634 e = s1->cached_includes[i - 1];
1635 if (0 == PATHCMP(e->filename, filename))
1636 return e;
1637 i = e->hash_next;
1639 if (!add)
1640 return NULL;
1642 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1643 strcpy(e->filename, filename);
1644 e->ifndef_macro = e->once = 0;
1645 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1646 /* add in hash table */
1647 e->hash_next = s1->cached_includes_hash[h];
1648 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1649 #ifdef INC_DEBUG
1650 printf("adding cached '%s'\n", filename);
1651 #endif
1652 return e;
1655 static void pragma_parse(TCCState *s1)
1657 next_nomacro();
1658 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1659 int t = tok, v;
1660 Sym *s;
1662 if (next(), tok != '(')
1663 goto pragma_err;
1664 if (next(), tok != TOK_STR)
1665 goto pragma_err;
1666 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1667 if (next(), tok != ')')
1668 goto pragma_err;
1669 if (t == TOK_push_macro) {
1670 while (NULL == (s = define_find(v)))
1671 define_push(v, 0, NULL, NULL);
1672 s->type.ref = s; /* set push boundary */
1673 } else {
1674 for (s = define_stack; s; s = s->prev)
1675 if (s->v == v && s->type.ref == s) {
1676 s->type.ref = NULL;
1677 break;
1680 if (s)
1681 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1682 else
1683 tcc_warning("unbalanced #pragma pop_macro");
1684 pp_debug_tok = t, pp_debug_symv = v;
1686 } else if (tok == TOK_once) {
1687 search_cached_include(s1, file->filename, 1)->once = pp_once;
1689 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1690 /* tcc -E: keep pragmas below unchanged */
1691 unget_tok(' ');
1692 unget_tok(TOK_PRAGMA);
1693 unget_tok('#');
1694 unget_tok(TOK_LINEFEED);
1696 } else if (tok == TOK_pack) {
1697 /* This may be:
1698 #pragma pack(1) // set
1699 #pragma pack() // reset to default
1700 #pragma pack(push) // push current
1701 #pragma pack(push,1) // push & set
1702 #pragma pack(pop) // restore previous */
1703 next();
1704 skip('(');
1705 if (tok == TOK_ASM_pop) {
1706 next();
1707 if (s1->pack_stack_ptr <= s1->pack_stack) {
1708 stk_error:
1709 tcc_error("out of pack stack");
1711 s1->pack_stack_ptr--;
1712 } else {
1713 int val = 0;
1714 if (tok != ')') {
1715 if (tok == TOK_ASM_push) {
1716 next();
1717 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1718 goto stk_error;
1719 val = *s1->pack_stack_ptr++;
1720 if (tok != ',')
1721 goto pack_set;
1722 next();
1724 if (tok != TOK_CINT)
1725 goto pragma_err;
1726 val = tokc.i;
1727 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1728 goto pragma_err;
1729 next();
1731 pack_set:
1732 *s1->pack_stack_ptr = val;
1734 if (tok != ')')
1735 goto pragma_err;
1737 } else if (tok == TOK_comment) {
1738 char *p; int t;
1739 next();
1740 skip('(');
1741 t = tok;
1742 next();
1743 skip(',');
1744 if (tok != TOK_STR)
1745 goto pragma_err;
1746 p = tcc_strdup((char *)tokc.str.data);
1747 next();
1748 if (tok != ')')
1749 goto pragma_err;
1750 if (t == TOK_lib) {
1751 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1752 } else {
1753 if (t == TOK_option)
1754 tcc_set_options(s1, p);
1755 tcc_free(p);
1758 } else
1759 tcc_warning_c(warn_unsupported)("#pragma %s ignored", get_tok_str(tok, &tokc));
1760 return;
1762 pragma_err:
1763 tcc_error("malformed #pragma directive");
1764 return;
1767 /* is_bof is true if first non space token at beginning of file */
1768 ST_FUNC void preprocess(int is_bof)
1770 TCCState *s1 = tcc_state;
1771 int c, n, saved_parse_flags;
1772 char buf[1024], *q;
1773 Sym *s;
1775 saved_parse_flags = parse_flags;
1776 parse_flags = PARSE_FLAG_PREPROCESS
1777 | PARSE_FLAG_TOK_NUM
1778 | PARSE_FLAG_TOK_STR
1779 | PARSE_FLAG_LINEFEED
1780 | (parse_flags & PARSE_FLAG_ASM_FILE)
1783 next_nomacro();
1784 redo:
1785 switch(tok) {
1786 case TOK_DEFINE:
1787 pp_debug_tok = tok;
1788 next_nomacro();
1789 pp_debug_symv = tok;
1790 parse_define();
1791 break;
1792 case TOK_UNDEF:
1793 pp_debug_tok = tok;
1794 next_nomacro();
1795 pp_debug_symv = tok;
1796 s = define_find(tok);
1797 /* undefine symbol by putting an invalid name */
1798 if (s)
1799 define_undef(s);
1800 break;
1801 case TOK_INCLUDE:
1802 case TOK_INCLUDE_NEXT:
1803 parse_include(s1, tok - TOK_INCLUDE, 0);
1804 break;
1805 case TOK_IFNDEF:
1806 c = 1;
1807 goto do_ifdef;
1808 case TOK_IF:
1809 c = expr_preprocess(s1);
1810 goto do_if;
1811 case TOK_IFDEF:
1812 c = 0;
1813 do_ifdef:
1814 next_nomacro();
1815 if (tok < TOK_IDENT)
1816 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1817 if (is_bof) {
1818 if (c) {
1819 #ifdef INC_DEBUG
1820 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1821 #endif
1822 file->ifndef_macro = tok;
1825 if (define_find(tok)
1826 || tok == TOK___HAS_INCLUDE
1827 || tok == TOK___HAS_INCLUDE_NEXT)
1828 c ^= 1;
1829 do_if:
1830 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1831 tcc_error("memory full (ifdef)");
1832 *s1->ifdef_stack_ptr++ = c;
1833 goto test_skip;
1834 case TOK_ELSE:
1835 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1836 tcc_error("#else without matching #if");
1837 if (s1->ifdef_stack_ptr[-1] & 2)
1838 tcc_error("#else after #else");
1839 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1840 goto test_else;
1841 case TOK_ELIF:
1842 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1843 tcc_error("#elif without matching #if");
1844 c = s1->ifdef_stack_ptr[-1];
1845 if (c > 1)
1846 tcc_error("#elif after #else");
1847 /* last #if/#elif expression was true: we skip */
1848 if (c == 1) {
1849 c = 0;
1850 } else {
1851 c = expr_preprocess(s1);
1852 s1->ifdef_stack_ptr[-1] = c;
1854 test_else:
1855 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1856 file->ifndef_macro = 0;
1857 test_skip:
1858 if (!(c & 1)) {
1859 preprocess_skip();
1860 is_bof = 0;
1861 goto redo;
1863 break;
1864 case TOK_ENDIF:
1865 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1866 tcc_error("#endif without matching #if");
1867 s1->ifdef_stack_ptr--;
1868 /* '#ifndef macro' was at the start of file. Now we check if
1869 an '#endif' is exactly at the end of file */
1870 if (file->ifndef_macro &&
1871 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1872 file->ifndef_macro_saved = file->ifndef_macro;
1873 /* need to set to zero to avoid false matches if another
1874 #ifndef at middle of file */
1875 file->ifndef_macro = 0;
1876 while (tok != TOK_LINEFEED)
1877 next_nomacro();
1878 tok_flags |= TOK_FLAG_ENDIF;
1879 goto the_end;
1881 break;
1882 case TOK_PPNUM:
1883 n = strtoul((char*)tokc.str.data, &q, 10);
1884 goto _line_num;
1885 case TOK_LINE:
1886 next();
1887 if (tok != TOK_CINT)
1888 _line_err:
1889 tcc_error("wrong #line format");
1890 n = tokc.i;
1891 _line_num:
1892 next();
1893 if (tok != TOK_LINEFEED) {
1894 if (tok == TOK_STR) {
1895 if (file->true_filename == file->filename)
1896 file->true_filename = tcc_strdup(file->filename);
1897 q = (char *)tokc.str.data;
1898 buf[0] = 0;
1899 if (!IS_ABSPATH(q)) {
1900 /* prepend directory from real file */
1901 pstrcpy(buf, sizeof buf, file->true_filename);
1902 *tcc_basename(buf) = 0;
1904 pstrcat(buf, sizeof buf, q);
1905 tcc_debug_putfile(s1, buf);
1906 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
1907 break;
1908 else
1909 goto _line_err;
1910 --n;
1912 if (file->fd > 0)
1913 total_lines += file->line_num - n;
1914 file->line_num = n;
1915 break;
1916 case TOK_ERROR:
1917 case TOK_WARNING:
1918 q = buf;
1919 c = skip_spaces();
1920 while (c != '\n' && c != CH_EOF) {
1921 if ((q - buf) < sizeof(buf) - 1)
1922 *q++ = c;
1923 c = ninp();
1925 *q = '\0';
1926 if (tok == TOK_ERROR)
1927 tcc_error("#error %s", buf);
1928 else
1929 tcc_warning("#warning %s", buf);
1930 break;
1931 case TOK_PRAGMA:
1932 pragma_parse(s1);
1933 break;
1934 case TOK_LINEFEED:
1935 goto the_end;
1936 default:
1937 /* ignore gas line comment in an 'S' file. */
1938 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1939 goto ignore;
1940 if (tok == '!' && is_bof)
1941 /* '!' is ignored at beginning to allow C scripts. */
1942 goto ignore;
1943 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1944 ignore:
1945 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
1946 goto the_end;
1948 /* ignore other preprocess commands or #! for C scripts */
1949 while (tok != TOK_LINEFEED)
1950 next_nomacro();
1951 the_end:
1952 parse_flags = saved_parse_flags;
1955 /* evaluate escape codes in a string. */
1956 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1958 int c, n, i;
1959 const uint8_t *p;
1961 p = buf;
1962 for(;;) {
1963 c = *p;
1964 if (c == '\0')
1965 break;
1966 if (c == '\\') {
1967 p++;
1968 /* escape */
1969 c = *p;
1970 switch(c) {
1971 case '0': case '1': case '2': case '3':
1972 case '4': case '5': case '6': case '7':
1973 /* at most three octal digits */
1974 n = c - '0';
1975 p++;
1976 c = *p;
1977 if (isoct(c)) {
1978 n = n * 8 + c - '0';
1979 p++;
1980 c = *p;
1981 if (isoct(c)) {
1982 n = n * 8 + c - '0';
1983 p++;
1986 c = n;
1987 goto add_char_nonext;
1988 case 'x': i = 0; goto parse_hex_or_ucn;
1989 case 'u': i = 4; goto parse_hex_or_ucn;
1990 case 'U': i = 8; goto parse_hex_or_ucn;
1991 parse_hex_or_ucn:
1992 p++;
1993 n = 0;
1994 do {
1995 c = *p;
1996 if (c >= 'a' && c <= 'f')
1997 c = c - 'a' + 10;
1998 else if (c >= 'A' && c <= 'F')
1999 c = c - 'A' + 10;
2000 else if (isnum(c))
2001 c = c - '0';
2002 else if (i > 0)
2003 expect("more hex digits in universal-character-name");
2004 else
2005 goto add_hex_or_ucn;
2006 n = n * 16 + c;
2007 p++;
2008 } while (--i);
2009 if (is_long) {
2010 add_hex_or_ucn:
2011 c = n;
2012 goto add_char_nonext;
2014 cstr_u8cat(outstr, n);
2015 continue;
2016 case 'a':
2017 c = '\a';
2018 break;
2019 case 'b':
2020 c = '\b';
2021 break;
2022 case 'f':
2023 c = '\f';
2024 break;
2025 case 'n':
2026 c = '\n';
2027 break;
2028 case 'r':
2029 c = '\r';
2030 break;
2031 case 't':
2032 c = '\t';
2033 break;
2034 case 'v':
2035 c = '\v';
2036 break;
2037 case 'e':
2038 if (!gnu_ext)
2039 goto invalid_escape;
2040 c = 27;
2041 break;
2042 case '\'':
2043 case '\"':
2044 case '\\':
2045 case '?':
2046 break;
2047 default:
2048 invalid_escape:
2049 if (c >= '!' && c <= '~')
2050 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2051 else
2052 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2053 break;
2055 } else if (is_long && c >= 0x80) {
2056 /* assume we are processing UTF-8 sequence */
2057 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2059 int cont; /* count of continuation bytes */
2060 int skip; /* how many bytes should skip when error occurred */
2061 int i;
2063 /* decode leading byte */
2064 if (c < 0xC2) {
2065 skip = 1; goto invalid_utf8_sequence;
2066 } else if (c <= 0xDF) {
2067 cont = 1; n = c & 0x1f;
2068 } else if (c <= 0xEF) {
2069 cont = 2; n = c & 0xf;
2070 } else if (c <= 0xF4) {
2071 cont = 3; n = c & 0x7;
2072 } else {
2073 skip = 1; goto invalid_utf8_sequence;
2076 /* decode continuation bytes */
2077 for (i = 1; i <= cont; i++) {
2078 int l = 0x80, h = 0xBF;
2080 /* adjust limit for second byte */
2081 if (i == 1) {
2082 switch (c) {
2083 case 0xE0: l = 0xA0; break;
2084 case 0xED: h = 0x9F; break;
2085 case 0xF0: l = 0x90; break;
2086 case 0xF4: h = 0x8F; break;
2090 if (p[i] < l || p[i] > h) {
2091 skip = i; goto invalid_utf8_sequence;
2094 n = (n << 6) | (p[i] & 0x3f);
2097 /* advance pointer */
2098 p += 1 + cont;
2099 c = n;
2100 goto add_char_nonext;
2102 /* error handling */
2103 invalid_utf8_sequence:
2104 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2105 c = 0xFFFD;
2106 p += skip;
2107 goto add_char_nonext;
2110 p++;
2111 add_char_nonext:
2112 if (!is_long)
2113 cstr_ccat(outstr, c);
2114 else {
2115 #ifdef TCC_TARGET_PE
2116 /* store as UTF-16 */
2117 if (c < 0x10000) {
2118 cstr_wccat(outstr, c);
2119 } else {
2120 c -= 0x10000;
2121 cstr_wccat(outstr, (c >> 10) + 0xD800);
2122 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2124 #else
2125 cstr_wccat(outstr, c);
2126 #endif
2129 /* add a trailing '\0' */
2130 if (!is_long)
2131 cstr_ccat(outstr, '\0');
2132 else
2133 cstr_wccat(outstr, '\0');
2136 static void parse_string(const char *s, int len)
2138 uint8_t buf[1000], *p = buf;
2139 int is_long, sep;
2141 if ((is_long = *s == 'L'))
2142 ++s, --len;
2143 sep = *s++;
2144 len -= 2;
2145 if (len >= sizeof buf)
2146 p = tcc_malloc(len + 1);
2147 memcpy(p, s, len);
2148 p[len] = 0;
2150 cstr_reset(&tokcstr);
2151 parse_escape_string(&tokcstr, p, is_long);
2152 if (p != buf)
2153 tcc_free(p);
2155 if (sep == '\'') {
2156 int char_size, i, n, c;
2157 /* XXX: make it portable */
2158 if (!is_long)
2159 tok = TOK_CCHAR, char_size = 1;
2160 else
2161 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2162 n = tokcstr.size / char_size - 1;
2163 if (n < 1)
2164 tcc_error("empty character constant");
2165 if (n > 1)
2166 tcc_warning_c(warn_all)("multi-character character constant");
2167 for (c = i = 0; i < n; ++i) {
2168 if (is_long)
2169 c = ((nwchar_t *)tokcstr.data)[i];
2170 else
2171 c = (c << 8) | ((char *)tokcstr.data)[i];
2173 tokc.i = c;
2174 } else {
2175 tokc.str.size = tokcstr.size;
2176 tokc.str.data = tokcstr.data;
2177 if (!is_long)
2178 tok = TOK_STR;
2179 else
2180 tok = TOK_LSTR;
2184 /* we use 64 bit numbers */
2185 #define BN_SIZE 2
2187 /* bn = (bn << shift) | or_val */
2188 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2190 int i;
2191 unsigned int v;
2192 for(i=0;i<BN_SIZE;i++) {
2193 v = bn[i];
2194 bn[i] = (v << shift) | or_val;
2195 or_val = v >> (32 - shift);
2199 static void bn_zero(unsigned int *bn)
2201 int i;
2202 for(i=0;i<BN_SIZE;i++) {
2203 bn[i] = 0;
2207 /* parse number in null terminated string 'p' and return it in the
2208 current token */
2209 static void parse_number(const char *p)
2211 int b, t, shift, frac_bits, s, exp_val, ch;
2212 char *q;
2213 unsigned int bn[BN_SIZE];
2214 double d;
2216 /* number */
2217 q = token_buf;
2218 ch = *p++;
2219 t = ch;
2220 ch = *p++;
2221 *q++ = t;
2222 b = 10;
2223 if (t == '.') {
2224 goto float_frac_parse;
2225 } else if (t == '0') {
2226 if (ch == 'x' || ch == 'X') {
2227 q--;
2228 ch = *p++;
2229 b = 16;
2230 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2231 q--;
2232 ch = *p++;
2233 b = 2;
2236 /* parse all digits. cannot check octal numbers at this stage
2237 because of floating point constants */
2238 while (1) {
2239 if (ch >= 'a' && ch <= 'f')
2240 t = ch - 'a' + 10;
2241 else if (ch >= 'A' && ch <= 'F')
2242 t = ch - 'A' + 10;
2243 else if (isnum(ch))
2244 t = ch - '0';
2245 else
2246 break;
2247 if (t >= b)
2248 break;
2249 if (q >= token_buf + STRING_MAX_SIZE) {
2250 num_too_long:
2251 tcc_error("number too long");
2253 *q++ = ch;
2254 ch = *p++;
2256 if (ch == '.' ||
2257 ((ch == 'e' || ch == 'E') && b == 10) ||
2258 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2259 if (b != 10) {
2260 /* NOTE: strtox should support that for hexa numbers, but
2261 non ISOC99 libcs do not support it, so we prefer to do
2262 it by hand */
2263 /* hexadecimal or binary floats */
2264 /* XXX: handle overflows */
2265 *q = '\0';
2266 if (b == 16)
2267 shift = 4;
2268 else
2269 shift = 1;
2270 bn_zero(bn);
2271 q = token_buf;
2272 while (1) {
2273 t = *q++;
2274 if (t == '\0') {
2275 break;
2276 } else if (t >= 'a') {
2277 t = t - 'a' + 10;
2278 } else if (t >= 'A') {
2279 t = t - 'A' + 10;
2280 } else {
2281 t = t - '0';
2283 bn_lshift(bn, shift, t);
2285 frac_bits = 0;
2286 if (ch == '.') {
2287 ch = *p++;
2288 while (1) {
2289 t = ch;
2290 if (t >= 'a' && t <= 'f') {
2291 t = t - 'a' + 10;
2292 } else if (t >= 'A' && t <= 'F') {
2293 t = t - 'A' + 10;
2294 } else if (t >= '0' && t <= '9') {
2295 t = t - '0';
2296 } else {
2297 break;
2299 if (t >= b)
2300 tcc_error("invalid digit");
2301 bn_lshift(bn, shift, t);
2302 frac_bits += shift;
2303 ch = *p++;
2306 if (ch != 'p' && ch != 'P')
2307 expect("exponent");
2308 ch = *p++;
2309 s = 1;
2310 exp_val = 0;
2311 if (ch == '+') {
2312 ch = *p++;
2313 } else if (ch == '-') {
2314 s = -1;
2315 ch = *p++;
2317 if (ch < '0' || ch > '9')
2318 expect("exponent digits");
2319 while (ch >= '0' && ch <= '9') {
2320 exp_val = exp_val * 10 + ch - '0';
2321 ch = *p++;
2323 exp_val = exp_val * s;
2325 /* now we can generate the number */
2326 /* XXX: should patch directly float number */
2327 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2328 d = ldexp(d, exp_val - frac_bits);
2329 t = toup(ch);
2330 if (t == 'F') {
2331 ch = *p++;
2332 tok = TOK_CFLOAT;
2333 /* float : should handle overflow */
2334 tokc.f = (float)d;
2335 } else if (t == 'L') {
2336 ch = *p++;
2337 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2338 tok = TOK_CDOUBLE;
2339 tokc.d = d;
2340 #else
2341 tok = TOK_CLDOUBLE;
2342 /* XXX: not large enough */
2343 tokc.ld = (long double)d;
2344 #endif
2345 } else {
2346 tok = TOK_CDOUBLE;
2347 tokc.d = d;
2349 } else {
2350 /* decimal floats */
2351 if (ch == '.') {
2352 if (q >= token_buf + STRING_MAX_SIZE)
2353 goto num_too_long;
2354 *q++ = ch;
2355 ch = *p++;
2356 float_frac_parse:
2357 while (ch >= '0' && ch <= '9') {
2358 if (q >= token_buf + STRING_MAX_SIZE)
2359 goto num_too_long;
2360 *q++ = ch;
2361 ch = *p++;
2364 if (ch == 'e' || ch == 'E') {
2365 if (q >= token_buf + STRING_MAX_SIZE)
2366 goto num_too_long;
2367 *q++ = ch;
2368 ch = *p++;
2369 if (ch == '-' || ch == '+') {
2370 if (q >= token_buf + STRING_MAX_SIZE)
2371 goto num_too_long;
2372 *q++ = ch;
2373 ch = *p++;
2375 if (ch < '0' || ch > '9')
2376 expect("exponent digits");
2377 while (ch >= '0' && ch <= '9') {
2378 if (q >= token_buf + STRING_MAX_SIZE)
2379 goto num_too_long;
2380 *q++ = ch;
2381 ch = *p++;
2384 *q = '\0';
2385 t = toup(ch);
2386 errno = 0;
2387 if (t == 'F') {
2388 ch = *p++;
2389 tok = TOK_CFLOAT;
2390 tokc.f = strtof(token_buf, NULL);
2391 } else if (t == 'L') {
2392 ch = *p++;
2393 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2394 tok = TOK_CDOUBLE;
2395 tokc.d = strtod(token_buf, NULL);
2396 #else
2397 tok = TOK_CLDOUBLE;
2398 tokc.ld = strtold(token_buf, NULL);
2399 #endif
2400 } else {
2401 tok = TOK_CDOUBLE;
2402 tokc.d = strtod(token_buf, NULL);
2405 } else {
2406 unsigned long long n, n1;
2407 int lcount, ucount, ov = 0;
2408 const char *p1;
2410 /* integer number */
2411 *q = '\0';
2412 q = token_buf;
2413 if (b == 10 && *q == '0') {
2414 b = 8;
2415 q++;
2417 n = 0;
2418 while(1) {
2419 t = *q++;
2420 /* no need for checks except for base 10 / 8 errors */
2421 if (t == '\0')
2422 break;
2423 else if (t >= 'a')
2424 t = t - 'a' + 10;
2425 else if (t >= 'A')
2426 t = t - 'A' + 10;
2427 else
2428 t = t - '0';
2429 if (t >= b)
2430 tcc_error("invalid digit");
2431 n1 = n;
2432 n = n * b + t;
2433 /* detect overflow */
2434 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2435 ov = 1;
2438 /* Determine the characteristics (unsigned and/or 64bit) the type of
2439 the constant must have according to the constant suffix(es) */
2440 lcount = ucount = 0;
2441 p1 = p;
2442 for(;;) {
2443 t = toup(ch);
2444 if (t == 'L') {
2445 if (lcount >= 2)
2446 tcc_error("three 'l's in integer constant");
2447 if (lcount && *(p - 1) != ch)
2448 tcc_error("incorrect integer suffix: %s", p1);
2449 lcount++;
2450 ch = *p++;
2451 } else if (t == 'U') {
2452 if (ucount >= 1)
2453 tcc_error("two 'u's in integer constant");
2454 ucount++;
2455 ch = *p++;
2456 } else {
2457 break;
2461 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2462 if (ucount == 0 && b == 10) {
2463 if (lcount <= (LONG_SIZE == 4)) {
2464 if (n >= 0x80000000U)
2465 lcount = (LONG_SIZE == 4) + 1;
2467 if (n >= 0x8000000000000000ULL)
2468 ov = 1, ucount = 1;
2469 } else {
2470 if (lcount <= (LONG_SIZE == 4)) {
2471 if (n >= 0x100000000ULL)
2472 lcount = (LONG_SIZE == 4) + 1;
2473 else if (n >= 0x80000000U)
2474 ucount = 1;
2476 if (n >= 0x8000000000000000ULL)
2477 ucount = 1;
2480 if (ov)
2481 tcc_warning("integer constant overflow");
2483 tok = TOK_CINT;
2484 if (lcount) {
2485 tok = TOK_CLONG;
2486 if (lcount == 2)
2487 tok = TOK_CLLONG;
2489 if (ucount)
2490 ++tok; /* TOK_CU... */
2491 tokc.i = n;
2493 if (ch)
2494 tcc_error("invalid number");
2498 #define PARSE2(c1, tok1, c2, tok2) \
2499 case c1: \
2500 PEEKC(c, p); \
2501 if (c == c2) { \
2502 p++; \
2503 tok = tok2; \
2504 } else { \
2505 tok = tok1; \
2507 break;
2509 /* return next token without macro substitution */
2510 static inline void next_nomacro1(void)
2512 int t, c, is_long, len;
2513 TokenSym *ts;
2514 uint8_t *p, *p1;
2515 unsigned int h;
2517 p = file->buf_ptr;
2518 redo_no_start:
2519 c = *p;
2520 switch(c) {
2521 case ' ':
2522 case '\t':
2523 tok = c;
2524 p++;
2525 maybe_space:
2526 if (parse_flags & PARSE_FLAG_SPACES)
2527 goto keep_tok_flags;
2528 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2529 ++p;
2530 goto redo_no_start;
2531 case '\f':
2532 case '\v':
2533 case '\r':
2534 p++;
2535 goto redo_no_start;
2536 case '\\':
2537 /* first look if it is in fact an end of buffer */
2538 c = handle_stray(&p);
2539 if (c == '\\')
2540 goto parse_simple;
2541 if (c == CH_EOF) {
2542 TCCState *s1 = tcc_state;
2543 if ((parse_flags & PARSE_FLAG_LINEFEED)
2544 && !(tok_flags & TOK_FLAG_EOF)) {
2545 tok_flags |= TOK_FLAG_EOF;
2546 tok = TOK_LINEFEED;
2547 goto keep_tok_flags;
2548 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2549 tok = TOK_EOF;
2550 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2551 tcc_error("missing #endif");
2552 } else if (s1->include_stack_ptr == s1->include_stack) {
2553 /* no include left : end of file. */
2554 tok = TOK_EOF;
2555 } else {
2556 tok_flags &= ~TOK_FLAG_EOF;
2557 /* pop include file */
2559 /* test if previous '#endif' was after a #ifdef at
2560 start of file */
2561 if (tok_flags & TOK_FLAG_ENDIF) {
2562 #ifdef INC_DEBUG
2563 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2564 #endif
2565 search_cached_include(s1, file->filename, 1)
2566 ->ifndef_macro = file->ifndef_macro_saved;
2567 tok_flags &= ~TOK_FLAG_ENDIF;
2570 /* add end of include file debug info */
2571 tcc_debug_eincl(tcc_state);
2572 /* pop include stack */
2573 tcc_close();
2574 s1->include_stack_ptr--;
2575 p = file->buf_ptr;
2576 if (p == file->buffer)
2577 tok_flags = TOK_FLAG_BOF;
2578 tok_flags |= TOK_FLAG_BOL;
2579 goto redo_no_start;
2581 } else {
2582 goto redo_no_start;
2584 break;
2586 case '\n':
2587 file->line_num++;
2588 tok_flags |= TOK_FLAG_BOL;
2589 p++;
2590 maybe_newline:
2591 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2592 goto redo_no_start;
2593 tok = TOK_LINEFEED;
2594 goto keep_tok_flags;
2596 case '#':
2597 /* XXX: simplify */
2598 PEEKC(c, p);
2599 if ((tok_flags & TOK_FLAG_BOL) &&
2600 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2601 file->buf_ptr = p;
2602 preprocess(tok_flags & TOK_FLAG_BOF);
2603 p = file->buf_ptr;
2604 goto maybe_newline;
2605 } else {
2606 if (c == '#') {
2607 p++;
2608 tok = TOK_TWOSHARPS;
2609 } else {
2610 #if !defined(TCC_TARGET_ARM)
2611 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2612 p = parse_line_comment(p - 1);
2613 goto redo_no_start;
2614 } else
2615 #endif
2617 tok = '#';
2621 break;
2623 /* dollar is allowed to start identifiers when not parsing asm */
2624 case '$':
2625 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2626 || (parse_flags & PARSE_FLAG_ASM_FILE))
2627 goto parse_simple;
2629 case 'a': case 'b': case 'c': case 'd':
2630 case 'e': case 'f': case 'g': case 'h':
2631 case 'i': case 'j': case 'k': case 'l':
2632 case 'm': case 'n': case 'o': case 'p':
2633 case 'q': case 'r': case 's': case 't':
2634 case 'u': case 'v': case 'w': case 'x':
2635 case 'y': case 'z':
2636 case 'A': case 'B': case 'C': case 'D':
2637 case 'E': case 'F': case 'G': case 'H':
2638 case 'I': case 'J': case 'K':
2639 case 'M': case 'N': case 'O': case 'P':
2640 case 'Q': case 'R': case 'S': case 'T':
2641 case 'U': case 'V': case 'W': case 'X':
2642 case 'Y': case 'Z':
2643 case '_':
2644 parse_ident_fast:
2645 p1 = p;
2646 h = TOK_HASH_INIT;
2647 h = TOK_HASH_FUNC(h, c);
2648 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2649 h = TOK_HASH_FUNC(h, c);
2650 len = p - p1;
2651 if (c != '\\') {
2652 TokenSym **pts;
2654 /* fast case : no stray found, so we have the full token
2655 and we have already hashed it */
2656 h &= (TOK_HASH_SIZE - 1);
2657 pts = &hash_ident[h];
2658 for(;;) {
2659 ts = *pts;
2660 if (!ts)
2661 break;
2662 if (ts->len == len && !memcmp(ts->str, p1, len))
2663 goto token_found;
2664 pts = &(ts->hash_next);
2666 ts = tok_alloc_new(pts, (char *) p1, len);
2667 token_found: ;
2668 } else {
2669 /* slower case */
2670 cstr_reset(&tokcstr);
2671 cstr_cat(&tokcstr, (char *) p1, len);
2672 p--;
2673 PEEKC(c, p);
2674 parse_ident_slow:
2675 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2677 cstr_ccat(&tokcstr, c);
2678 PEEKC(c, p);
2680 ts = tok_alloc(tokcstr.data, tokcstr.size);
2682 tok = ts->tok;
2683 break;
2684 case 'L':
2685 t = p[1];
2686 if (t != '\\' && t != '\'' && t != '\"') {
2687 /* fast case */
2688 goto parse_ident_fast;
2689 } else {
2690 PEEKC(c, p);
2691 if (c == '\'' || c == '\"') {
2692 is_long = 1;
2693 goto str_const;
2694 } else {
2695 cstr_reset(&tokcstr);
2696 cstr_ccat(&tokcstr, 'L');
2697 goto parse_ident_slow;
2700 break;
2702 case '0': case '1': case '2': case '3':
2703 case '4': case '5': case '6': case '7':
2704 case '8': case '9':
2705 t = c;
2706 PEEKC(c, p);
2707 /* after the first digit, accept digits, alpha, '.' or sign if
2708 prefixed by 'eEpP' */
2709 parse_num:
2710 cstr_reset(&tokcstr);
2711 for(;;) {
2712 cstr_ccat(&tokcstr, t);
2713 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2714 || c == '.'
2715 || ((c == '+' || c == '-')
2716 && (((t == 'e' || t == 'E')
2717 && !(parse_flags & PARSE_FLAG_ASM_FILE
2718 /* 0xe+1 is 3 tokens in asm */
2719 && ((char*)tokcstr.data)[0] == '0'
2720 && toup(((char*)tokcstr.data)[1]) == 'X'))
2721 || t == 'p' || t == 'P'))))
2722 break;
2723 t = c;
2724 PEEKC(c, p);
2726 /* We add a trailing '\0' to ease parsing */
2727 cstr_ccat(&tokcstr, '\0');
2728 tokc.str.size = tokcstr.size;
2729 tokc.str.data = tokcstr.data;
2730 tok = TOK_PPNUM;
2731 break;
2733 case '.':
2734 /* special dot handling because it can also start a number */
2735 PEEKC(c, p);
2736 if (isnum(c)) {
2737 t = '.';
2738 goto parse_num;
2739 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2740 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2741 *--p = c = '.';
2742 goto parse_ident_fast;
2743 } else if (c == '.') {
2744 PEEKC(c, p);
2745 if (c == '.') {
2746 p++;
2747 tok = TOK_DOTS;
2748 } else {
2749 *--p = '.'; /* may underflow into file->unget[] */
2750 tok = '.';
2752 } else {
2753 tok = '.';
2755 break;
2756 case '\'':
2757 case '\"':
2758 is_long = 0;
2759 str_const:
2760 cstr_reset(&tokcstr);
2761 if (is_long)
2762 cstr_ccat(&tokcstr, 'L');
2763 cstr_ccat(&tokcstr, c);
2764 p = parse_pp_string(p, c, &tokcstr);
2765 cstr_ccat(&tokcstr, c);
2766 cstr_ccat(&tokcstr, '\0');
2767 tokc.str.size = tokcstr.size;
2768 tokc.str.data = tokcstr.data;
2769 tok = TOK_PPSTR;
2770 break;
2772 case '<':
2773 PEEKC(c, p);
2774 if (c == '=') {
2775 p++;
2776 tok = TOK_LE;
2777 } else if (c == '<') {
2778 PEEKC(c, p);
2779 if (c == '=') {
2780 p++;
2781 tok = TOK_A_SHL;
2782 } else {
2783 tok = TOK_SHL;
2785 } else {
2786 tok = TOK_LT;
2788 break;
2789 case '>':
2790 PEEKC(c, p);
2791 if (c == '=') {
2792 p++;
2793 tok = TOK_GE;
2794 } else if (c == '>') {
2795 PEEKC(c, p);
2796 if (c == '=') {
2797 p++;
2798 tok = TOK_A_SAR;
2799 } else {
2800 tok = TOK_SAR;
2802 } else {
2803 tok = TOK_GT;
2805 break;
2807 case '&':
2808 PEEKC(c, p);
2809 if (c == '&') {
2810 p++;
2811 tok = TOK_LAND;
2812 } else if (c == '=') {
2813 p++;
2814 tok = TOK_A_AND;
2815 } else {
2816 tok = '&';
2818 break;
2820 case '|':
2821 PEEKC(c, p);
2822 if (c == '|') {
2823 p++;
2824 tok = TOK_LOR;
2825 } else if (c == '=') {
2826 p++;
2827 tok = TOK_A_OR;
2828 } else {
2829 tok = '|';
2831 break;
2833 case '+':
2834 PEEKC(c, p);
2835 if (c == '+') {
2836 p++;
2837 tok = TOK_INC;
2838 } else if (c == '=') {
2839 p++;
2840 tok = TOK_A_ADD;
2841 } else {
2842 tok = '+';
2844 break;
2846 case '-':
2847 PEEKC(c, p);
2848 if (c == '-') {
2849 p++;
2850 tok = TOK_DEC;
2851 } else if (c == '=') {
2852 p++;
2853 tok = TOK_A_SUB;
2854 } else if (c == '>') {
2855 p++;
2856 tok = TOK_ARROW;
2857 } else {
2858 tok = '-';
2860 break;
2862 PARSE2('!', '!', '=', TOK_NE)
2863 PARSE2('=', '=', '=', TOK_EQ)
2864 PARSE2('*', '*', '=', TOK_A_MUL)
2865 PARSE2('%', '%', '=', TOK_A_MOD)
2866 PARSE2('^', '^', '=', TOK_A_XOR)
2868 /* comments or operator */
2869 case '/':
2870 PEEKC(c, p);
2871 if (c == '*') {
2872 p = parse_comment(p);
2873 /* comments replaced by a blank */
2874 tok = ' ';
2875 goto maybe_space;
2876 } else if (c == '/') {
2877 p = parse_line_comment(p);
2878 tok = ' ';
2879 goto maybe_space;
2880 } else if (c == '=') {
2881 p++;
2882 tok = TOK_A_DIV;
2883 } else {
2884 tok = '/';
2886 break;
2888 /* simple tokens */
2889 case '(':
2890 case ')':
2891 case '[':
2892 case ']':
2893 case '{':
2894 case '}':
2895 case ',':
2896 case ';':
2897 case ':':
2898 case '?':
2899 case '~':
2900 case '@': /* only used in assembler */
2901 parse_simple:
2902 tok = c;
2903 p++;
2904 break;
2905 default:
2906 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2907 goto parse_ident_fast;
2908 if (parse_flags & PARSE_FLAG_ASM_FILE)
2909 goto parse_simple;
2910 tcc_error("unrecognized character \\x%02x", c);
2911 break;
2913 tok_flags = 0;
2914 keep_tok_flags:
2915 file->buf_ptr = p;
2916 #if defined(PARSE_DEBUG)
2917 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
2918 #endif
2921 static void macro_subst(
2922 TokenString *tok_str,
2923 Sym **nested_list,
2924 const int *macro_str
2927 /* substitute arguments in replacement lists in macro_str by the values in
2928 args (field d) and return allocated string */
2929 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2931 int t, t0, t1, spc;
2932 const int *st;
2933 Sym *s;
2934 CValue cval;
2935 TokenString str;
2936 CString cstr;
2938 tok_str_new(&str);
2939 t0 = t1 = 0;
2940 while(1) {
2941 TOK_GET(&t, &macro_str, &cval);
2942 if (!t)
2943 break;
2944 if (t == '#') {
2945 /* stringize */
2946 TOK_GET(&t, &macro_str, &cval);
2947 if (!t)
2948 goto bad_stringy;
2949 s = sym_find2(args, t);
2950 if (s) {
2951 cstr_new(&cstr);
2952 cstr_ccat(&cstr, '\"');
2953 st = s->d;
2954 spc = 0;
2955 while (*st >= 0) {
2956 TOK_GET(&t, &st, &cval);
2957 if (t != TOK_PLCHLDR
2958 && t != TOK_NOSUBST
2959 && 0 == check_space(t, &spc)) {
2960 const char *s = get_tok_str(t, &cval);
2961 while (*s) {
2962 if (t == TOK_PPSTR && *s != '\'')
2963 add_char(&cstr, *s);
2964 else
2965 cstr_ccat(&cstr, *s);
2966 ++s;
2970 cstr.size -= spc;
2971 cstr_ccat(&cstr, '\"');
2972 cstr_ccat(&cstr, '\0');
2973 #ifdef PP_DEBUG
2974 printf("\nstringize: <%s>\n", (char *)cstr.data);
2975 #endif
2976 /* add string */
2977 cval.str.size = cstr.size;
2978 cval.str.data = cstr.data;
2979 tok_str_add2(&str, TOK_PPSTR, &cval);
2980 cstr_free(&cstr);
2981 } else {
2982 bad_stringy:
2983 expect("macro parameter after '#'");
2985 } else if (t >= TOK_IDENT) {
2986 s = sym_find2(args, t);
2987 if (s) {
2988 int l0 = str.len;
2989 st = s->d;
2990 /* if '##' is present before or after, no arg substitution */
2991 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
2992 /* special case for var arg macros : ## eats the ','
2993 if empty VA_ARGS variable. */
2994 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
2995 if (*st <= 0) {
2996 /* suppress ',' '##' */
2997 str.len -= 2;
2998 } else {
2999 /* suppress '##' and add variable */
3000 str.len--;
3001 goto add_var;
3004 } else {
3005 add_var:
3006 if (!s->next) {
3007 /* Expand arguments tokens and store them. In most
3008 cases we could also re-expand each argument if
3009 used multiple times, but not if the argument
3010 contains the __COUNTER__ macro. */
3011 TokenString str2;
3012 sym_push2(&s->next, s->v, s->type.t, 0);
3013 tok_str_new(&str2);
3014 macro_subst(&str2, nested_list, st);
3015 tok_str_add(&str2, 0);
3016 s->next->d = str2.str;
3018 st = s->next->d;
3020 for(;;) {
3021 int t2;
3022 TOK_GET(&t2, &st, &cval);
3023 if (t2 <= 0)
3024 break;
3025 tok_str_add2(&str, t2, &cval);
3027 if (str.len == l0) /* expanded to empty string */
3028 tok_str_add(&str, TOK_PLCHLDR);
3029 } else {
3030 tok_str_add(&str, t);
3032 } else {
3033 tok_str_add2(&str, t, &cval);
3035 t0 = t1, t1 = t;
3037 tok_str_add(&str, 0);
3038 return str.str;
3041 static char const ab_month_name[12][4] =
3043 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3044 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3047 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3049 CString cstr;
3050 int n, ret = 1;
3052 cstr_new(&cstr);
3053 if (t1 != TOK_PLCHLDR)
3054 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3055 n = cstr.size;
3056 if (t2 != TOK_PLCHLDR)
3057 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3058 cstr_ccat(&cstr, '\0');
3060 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3061 memcpy(file->buffer, cstr.data, cstr.size);
3062 tok_flags = 0;
3063 for (;;) {
3064 next_nomacro1();
3065 if (0 == *file->buf_ptr)
3066 break;
3067 if (is_space(tok))
3068 continue;
3069 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3070 " preprocessing token", n, (char *)cstr.data, (char*)cstr.data + n);
3071 ret = 0;
3072 break;
3074 tcc_close();
3075 //printf("paste <%s>\n", (char*)cstr.data);
3076 cstr_free(&cstr);
3077 return ret;
3080 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3081 return the resulting string (which must be freed). */
3082 static inline int *macro_twosharps(const int *ptr0)
3084 int t;
3085 CValue cval;
3086 TokenString macro_str1;
3087 int start_of_nosubsts = -1;
3088 const int *ptr;
3090 /* we search the first '##' */
3091 for (ptr = ptr0;;) {
3092 TOK_GET(&t, &ptr, &cval);
3093 if (t == TOK_PPJOIN)
3094 break;
3095 if (t == 0)
3096 return NULL;
3099 tok_str_new(&macro_str1);
3101 //tok_print(" $$$", ptr0);
3102 for (ptr = ptr0;;) {
3103 TOK_GET(&t, &ptr, &cval);
3104 if (t == 0)
3105 break;
3106 if (t == TOK_PPJOIN)
3107 continue;
3108 while (*ptr == TOK_PPJOIN) {
3109 int t1; CValue cv1;
3110 /* given 'a##b', remove nosubsts preceding 'a' */
3111 if (start_of_nosubsts >= 0)
3112 macro_str1.len = start_of_nosubsts;
3113 /* given 'a##b', remove nosubsts preceding 'b' */
3114 while ((t1 = *++ptr) == TOK_NOSUBST)
3116 if (t1 && t1 != TOK_PPJOIN) {
3117 TOK_GET(&t1, &ptr, &cv1);
3118 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3119 if (paste_tokens(t, &cval, t1, &cv1)) {
3120 t = tok, cval = tokc;
3121 } else {
3122 tok_str_add2(&macro_str1, t, &cval);
3123 t = t1, cval = cv1;
3128 if (t == TOK_NOSUBST) {
3129 if (start_of_nosubsts < 0)
3130 start_of_nosubsts = macro_str1.len;
3131 } else {
3132 start_of_nosubsts = -1;
3134 tok_str_add2(&macro_str1, t, &cval);
3136 tok_str_add(&macro_str1, 0);
3137 //tok_print(" ###", macro_str1.str);
3138 return macro_str1.str;
3141 /* peek or read [ws_str == NULL] next token from function macro call,
3142 walking up macro levels up to the file if necessary */
3143 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3145 int t;
3146 const int *p;
3147 Sym *sa;
3149 for (;;) {
3150 if (macro_ptr) {
3151 p = macro_ptr, t = *p;
3152 if (ws_str) {
3153 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3154 tok_str_add(ws_str, t), t = *++p;
3156 if (t == 0) {
3157 end_macro();
3158 /* also, end of scope for nested defined symbol */
3159 sa = *nested_list;
3160 while (sa && sa->v == 0)
3161 sa = sa->prev;
3162 if (sa)
3163 sa->v = 0;
3164 continue;
3166 } else {
3167 uint8_t *p = file->buf_ptr;
3168 int ch = handle_bs(&p);
3169 if (ws_str) {
3170 while (is_space(ch) || ch == '\n' || ch == '/') {
3171 if (ch == '/') {
3172 int c;
3173 PEEKC(c, p);
3174 if (c == '*') {
3175 p = parse_comment(p) - 1;
3176 } else if (c == '/') {
3177 p = parse_line_comment(p) - 1;
3178 } else {
3179 *--p = ch;
3180 break;
3182 ch = ' ';
3184 if (ch == '\n')
3185 file->line_num++;
3186 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3187 tok_str_add(ws_str, ch);
3188 PEEKC(ch, p);
3191 file->buf_ptr = p;
3192 t = ch;
3195 if (ws_str)
3196 return t;
3197 next_nomacro();
3198 return tok;
3202 /* do macro substitution of current token with macro 's' and add
3203 result to (tok_str,tok_len). 'nested_list' is the list of all
3204 macros we got inside to avoid recursing. Return non zero if no
3205 substitution needs to be done */
3206 static int macro_subst_tok(
3207 TokenString *tok_str,
3208 Sym **nested_list,
3209 Sym *s)
3211 Sym *args, *sa, *sa1;
3212 int parlevel, t, t1, spc;
3213 TokenString str;
3214 char *cstrval;
3215 CValue cval;
3216 CString cstr;
3217 char buf[32];
3219 /* if symbol is a macro, prepare substitution */
3220 /* special macros */
3221 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3222 t = tok == TOK___LINE__ ? file->line_num : pp_counter++;
3223 snprintf(buf, sizeof(buf), "%d", t);
3224 cstrval = buf;
3225 t1 = TOK_PPNUM;
3226 goto add_cstr1;
3227 } else if (tok == TOK___FILE__) {
3228 cstrval = file->filename;
3229 goto add_cstr;
3230 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3231 time_t ti;
3232 struct tm *tm;
3234 time(&ti);
3235 tm = localtime(&ti);
3236 if (tok == TOK___DATE__) {
3237 snprintf(buf, sizeof(buf), "%s %2d %d",
3238 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3239 } else {
3240 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3241 tm->tm_hour, tm->tm_min, tm->tm_sec);
3243 cstrval = buf;
3244 add_cstr:
3245 t1 = TOK_STR;
3246 add_cstr1:
3247 cstr_new(&cstr);
3248 cstr_cat(&cstr, cstrval, 0);
3249 cval.str.size = cstr.size;
3250 cval.str.data = cstr.data;
3251 tok_str_add2(tok_str, t1, &cval);
3252 cstr_free(&cstr);
3253 } else if (s->d) {
3254 int saved_parse_flags = parse_flags;
3255 int *joined_str = NULL;
3256 int *mstr = s->d;
3258 if (s->type.t == MACRO_FUNC) {
3259 /* whitespace between macro name and argument list */
3260 TokenString ws_str;
3261 tok_str_new(&ws_str);
3263 spc = 0;
3264 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3265 | PARSE_FLAG_ACCEPT_STRAYS;
3267 /* get next token from argument stream */
3268 t = next_argstream(nested_list, &ws_str);
3269 if (t != '(') {
3270 /* not a macro substitution after all, restore the
3271 * macro token plus all whitespace we've read.
3272 * whitespace is intentionally not merged to preserve
3273 * newlines. */
3274 parse_flags = saved_parse_flags;
3275 tok_str_add(tok_str, tok);
3276 if (parse_flags & PARSE_FLAG_SPACES) {
3277 int i;
3278 for (i = 0; i < ws_str.len; i++)
3279 tok_str_add(tok_str, ws_str.str[i]);
3281 if (ws_str.len && ws_str.str[ws_str.len - 1] == '\n')
3282 tok_flags |= TOK_FLAG_BOL;
3283 tok_str_free_str(ws_str.str);
3284 return 0;
3285 } else {
3286 tok_str_free_str(ws_str.str);
3288 do {
3289 next_nomacro(); /* eat '(' */
3290 } while (tok == TOK_PLCHLDR || is_space(tok));
3292 /* argument macro */
3293 args = NULL;
3294 sa = s->next;
3295 /* NOTE: empty args are allowed, except if no args */
3296 for(;;) {
3297 do {
3298 next_argstream(nested_list, NULL);
3299 } while (tok == TOK_PLCHLDR || is_space(tok) ||
3300 TOK_LINEFEED == tok);
3301 empty_arg:
3302 /* handle '()' case */
3303 if (!args && !sa && tok == ')')
3304 break;
3305 if (!sa)
3306 tcc_error("macro '%s' used with too many args",
3307 get_tok_str(s->v, 0));
3308 tok_str_new(&str);
3309 parlevel = spc = 0;
3310 /* NOTE: non zero sa->t indicates VA_ARGS */
3311 while ((parlevel > 0 ||
3312 (tok != ')' &&
3313 (tok != ',' || sa->type.t)))) {
3314 if (tok == TOK_EOF || tok == 0)
3315 break;
3316 if (tok == '(')
3317 parlevel++;
3318 else if (tok == ')')
3319 parlevel--;
3320 if (tok == TOK_LINEFEED)
3321 tok = ' ';
3322 if (!check_space(tok, &spc))
3323 tok_str_add2(&str, tok, &tokc);
3324 next_argstream(nested_list, NULL);
3326 if (parlevel)
3327 expect(")");
3328 str.len -= spc;
3329 tok_str_add(&str, -1);
3330 tok_str_add(&str, 0);
3331 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3332 sa1->d = str.str;
3333 sa = sa->next;
3334 if (tok == ')') {
3335 /* special case for gcc var args: add an empty
3336 var arg argument if it is omitted */
3337 if (sa && sa->type.t && gnu_ext)
3338 goto empty_arg;
3339 break;
3341 if (tok != ',')
3342 expect(",");
3344 if (sa) {
3345 tcc_error("macro '%s' used with too few args",
3346 get_tok_str(s->v, 0));
3349 /* now subst each arg */
3350 mstr = macro_arg_subst(nested_list, mstr, args);
3351 /* free memory */
3352 sa = args;
3353 while (sa) {
3354 sa1 = sa->prev;
3355 tok_str_free_str(sa->d);
3356 if (sa->next) {
3357 tok_str_free_str(sa->next->d);
3358 sym_free(sa->next);
3360 sym_free(sa);
3361 sa = sa1;
3363 parse_flags = saved_parse_flags;
3366 sym_push2(nested_list, s->v, 0, 0);
3367 parse_flags = saved_parse_flags;
3368 joined_str = macro_twosharps(mstr);
3369 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3371 /* pop nested defined symbol */
3372 sa1 = *nested_list;
3373 *nested_list = sa1->prev;
3374 sym_free(sa1);
3375 if (joined_str)
3376 tok_str_free_str(joined_str);
3377 if (mstr != s->d)
3378 tok_str_free_str(mstr);
3380 return 0;
3383 /* do macro substitution of macro_str and add result to
3384 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3385 inside to avoid recursing. */
3386 static void macro_subst(
3387 TokenString *tok_str,
3388 Sym **nested_list,
3389 const int *macro_str
3392 Sym *s;
3393 int t, spc, nosubst;
3394 CValue cval;
3396 spc = nosubst = 0;
3398 while (1) {
3399 TOK_GET(&t, &macro_str, &cval);
3400 if (t <= 0)
3401 break;
3403 if (t >= TOK_IDENT && 0 == nosubst) {
3404 s = define_find(t);
3405 if (s == NULL)
3406 goto no_subst;
3408 /* if nested substitution, do nothing */
3409 if (sym_find2(*nested_list, t)) {
3410 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3411 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3412 goto no_subst;
3416 TokenString *str = tok_str_alloc();
3417 str->str = (int*)macro_str;
3418 begin_macro(str, 2);
3420 tok = t;
3421 macro_subst_tok(tok_str, nested_list, s);
3423 if (macro_stack != str) {
3424 /* already finished by reading function macro arguments */
3425 break;
3428 macro_str = macro_ptr;
3429 end_macro ();
3431 if (tok_str->len)
3432 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3433 } else {
3434 no_subst:
3435 if (!check_space(t, &spc))
3436 tok_str_add2(tok_str, t, &cval);
3438 if (nosubst) {
3439 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3440 continue;
3441 nosubst = 0;
3443 if (t == TOK_NOSUBST)
3444 nosubst = 1;
3446 /* GCC supports 'defined' as result of a macro substitution */
3447 if (t == TOK_DEFINED && pp_expr)
3448 nosubst = 2;
3452 /* return next token without macro substitution. Can read input from
3453 macro_ptr buffer */
3454 static void next_nomacro(void)
3456 int t;
3457 if (macro_ptr) {
3458 redo:
3459 t = *macro_ptr;
3460 if (TOK_HAS_VALUE(t)) {
3461 tok_get(&tok, &macro_ptr, &tokc);
3462 if (t == TOK_LINENUM) {
3463 file->line_num = tokc.i;
3464 goto redo;
3466 } else {
3467 macro_ptr++;
3468 if (t < TOK_IDENT) {
3469 if (!(parse_flags & PARSE_FLAG_SPACES)
3470 && (isidnum_table[t - CH_EOF] & IS_SPC))
3471 goto redo;
3473 tok = t;
3475 } else {
3476 next_nomacro1();
3480 /* return next token with macro substitution */
3481 ST_FUNC void next(void)
3483 int t;
3484 redo:
3485 next_nomacro();
3486 t = tok;
3487 if (macro_ptr) {
3488 if (!TOK_HAS_VALUE(t)) {
3489 if (t == TOK_NOSUBST || t == TOK_PLCHLDR) {
3490 /* discard preprocessor markers */
3491 goto redo;
3492 } else if (t == 0) {
3493 /* end of macro or unget token string */
3494 end_macro();
3495 goto redo;
3496 } else if (t == '\\') {
3497 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3498 tcc_error("stray '\\' in program");
3500 return;
3502 } else if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3503 /* if reading from file, try to substitute macros */
3504 Sym *s = define_find(t);
3505 if (s) {
3506 Sym *nested_list = NULL;
3507 tokstr_buf.len = 0;
3508 macro_subst_tok(&tokstr_buf, &nested_list, s);
3509 tok_str_add(&tokstr_buf, 0);
3510 begin_macro(&tokstr_buf, 0);
3511 goto redo;
3513 return;
3515 /* convert preprocessor tokens into C tokens */
3516 if (t == TOK_PPNUM) {
3517 if (parse_flags & PARSE_FLAG_TOK_NUM)
3518 parse_number((char *)tokc.str.data);
3519 } else if (t == TOK_PPSTR) {
3520 if (parse_flags & PARSE_FLAG_TOK_STR)
3521 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3525 /* push back current token and set current token to 'last_tok'. Only
3526 identifier case handled for labels. */
3527 ST_INLN void unget_tok(int last_tok)
3530 TokenString *str = tok_str_alloc();
3531 tok_str_add2(str, tok, &tokc);
3532 tok_str_add(str, 0);
3533 begin_macro(str, 1);
3534 tok = last_tok;
3537 /* ------------------------------------------------------------------------- */
3538 /* init preprocessor */
3540 static const char * const target_os_defs =
3541 #ifdef TCC_TARGET_PE
3542 "_WIN32\0"
3543 # if PTR_SIZE == 8
3544 "_WIN64\0"
3545 # endif
3546 #else
3547 # if defined TCC_TARGET_MACHO
3548 "__APPLE__\0"
3549 # elif TARGETOS_FreeBSD
3550 "__FreeBSD__ 12\0"
3551 # elif TARGETOS_FreeBSD_kernel
3552 "__FreeBSD_kernel__\0"
3553 # elif TARGETOS_NetBSD
3554 "__NetBSD__\0"
3555 # elif TARGETOS_OpenBSD
3556 "__OpenBSD__\0"
3557 # else
3558 "__linux__\0"
3559 "__linux\0"
3560 # if TARGETOS_ANDROID
3561 "__ANDROID__\0"
3562 # endif
3563 # endif
3564 "__unix__\0"
3565 "__unix\0"
3566 #endif
3569 static void putdef(CString *cs, const char *p)
3571 cstr_printf(cs, "#define %s%s\n", p, &" 1"[!!strchr(p, ' ')*2]);
3574 static void putdefs(CString *cs, const char *p)
3576 while (*p)
3577 putdef(cs, p), p = strchr(p, 0) + 1;
3580 static void tcc_predefs(TCCState *s1, CString *cs, int is_asm)
3582 int a, b, c;
3584 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
3585 cstr_printf(cs, "#define __TINYC__ %d\n", a*10000 + b*100 + c);
3587 putdefs(cs, target_machine_defs);
3588 putdefs(cs, target_os_defs);
3590 #ifdef TCC_TARGET_ARM
3591 if (s1->float_abi == ARM_HARD_FLOAT)
3592 putdef(cs, "__ARM_PCS_VFP");
3593 #endif
3594 if (is_asm)
3595 putdef(cs, "__ASSEMBLER__");
3596 if (s1->output_type == TCC_OUTPUT_PREPROCESS)
3597 putdef(cs, "__TCC_PP__");
3598 if (s1->output_type == TCC_OUTPUT_MEMORY)
3599 putdef(cs, "__TCC_RUN__");
3600 if (s1->char_is_unsigned)
3601 putdef(cs, "__CHAR_UNSIGNED__");
3602 if (s1->optimize > 0)
3603 putdef(cs, "__OPTIMIZE__");
3604 if (s1->option_pthread)
3605 putdef(cs, "_REENTRANT");
3606 if (s1->leading_underscore)
3607 putdef(cs, "__leading_underscore");
3608 #ifdef CONFIG_TCC_BCHECK
3609 if (s1->do_bounds_check)
3610 putdef(cs, "__BOUNDS_CHECKING_ON");
3611 #endif
3612 #ifdef CONFIG_TCC_BACKTRACE
3613 if (s1->do_backtrace)
3614 putdef(cs, "__TCC_BACKTRACE_ENABLED__");
3615 #endif
3616 cstr_printf(cs, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE);
3617 cstr_printf(cs, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE);
3618 if (!is_asm) {
3619 putdef(cs, "__STDC__");
3620 cstr_printf(cs, "#define __STDC_VERSION__ %dL\n", s1->cversion);
3621 cstr_cat(cs,
3622 /* load more predefs and __builtins */
3623 #if CONFIG_TCC_PREDEFS
3624 #include "tccdefs_.h" /* include as strings */
3625 #else
3626 "#include <tccdefs.h>\n" /* load at runtime */
3627 #endif
3628 , -1);
3630 cstr_printf(cs, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3633 ST_FUNC void preprocess_start(TCCState *s1, int filetype)
3635 int is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
3636 CString cstr;
3638 tccpp_new(s1);
3640 s1->include_stack_ptr = s1->include_stack;
3641 s1->ifdef_stack_ptr = s1->ifdef_stack;
3642 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3643 pp_expr = 0;
3644 pp_counter = 0;
3645 pp_debug_tok = pp_debug_symv = 0;
3646 pp_once++;
3647 s1->pack_stack[0] = 0;
3648 s1->pack_stack_ptr = s1->pack_stack;
3650 set_idnum('$', !is_asm && s1->dollars_in_identifiers ? IS_ID : 0);
3651 set_idnum('.', is_asm ? IS_ID : 0);
3653 if (!(filetype & AFF_TYPE_ASM)) {
3654 cstr_new(&cstr);
3655 tcc_predefs(s1, &cstr, is_asm);
3656 if (s1->cmdline_defs.size)
3657 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3658 if (s1->cmdline_incl.size)
3659 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3660 //printf("%s\n", (char*)cstr.data);
3661 *s1->include_stack_ptr++ = file;
3662 tcc_open_bf(s1, "<command line>", cstr.size);
3663 memcpy(file->buffer, cstr.data, cstr.size);
3664 cstr_free(&cstr);
3667 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3668 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3671 /* cleanup from error/setjmp */
3672 ST_FUNC void preprocess_end(TCCState *s1)
3674 while (macro_stack)
3675 end_macro();
3676 macro_ptr = NULL;
3677 while (file)
3678 tcc_close();
3679 tccpp_delete(s1);
3682 ST_FUNC int set_idnum(int c, int val)
3684 int prev = isidnum_table[c - CH_EOF];
3685 isidnum_table[c - CH_EOF] = val;
3686 return prev;
3689 ST_FUNC void tccpp_new(TCCState *s)
3691 int i, c;
3692 const char *p, *r;
3694 /* init isid table */
3695 for(i = CH_EOF; i<128; i++)
3696 set_idnum(i,
3697 is_space(i) ? IS_SPC
3698 : isid(i) ? IS_ID
3699 : isnum(i) ? IS_NUM
3700 : 0);
3702 for(i = 128; i<256; i++)
3703 set_idnum(i, IS_ID);
3705 /* init allocators */
3706 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3707 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3709 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3710 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3712 cstr_new(&cstr_buf);
3713 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3714 tok_str_new(&tokstr_buf);
3715 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3717 tok_ident = TOK_IDENT;
3718 p = tcc_keywords;
3719 while (*p) {
3720 r = p;
3721 for(;;) {
3722 c = *r++;
3723 if (c == '\0')
3724 break;
3726 tok_alloc(p, r - p - 1);
3727 p = r;
3730 /* we add dummy defines for some special macros to speed up tests
3731 and to have working defined() */
3732 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3733 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3734 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3735 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3736 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3739 ST_FUNC void tccpp_delete(TCCState *s)
3741 int i, n;
3743 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3745 /* free tokens */
3746 n = tok_ident - TOK_IDENT;
3747 if (n > total_idents)
3748 total_idents = n;
3749 for(i = 0; i < n; i++)
3750 tal_free(toksym_alloc, table_ident[i]);
3751 tcc_free(table_ident);
3752 table_ident = NULL;
3754 /* free static buffers */
3755 cstr_free(&tokcstr);
3756 cstr_free(&cstr_buf);
3757 cstr_free(&macro_equal_buf);
3758 tok_str_free_str(tokstr_buf.str);
3760 /* free allocators */
3761 tal_delete(toksym_alloc);
3762 toksym_alloc = NULL;
3763 tal_delete(tokstr_alloc);
3764 tokstr_alloc = NULL;
3767 /* ------------------------------------------------------------------------- */
3768 /* tcc -E [-P[1]] [-dD} support */
3770 static void tok_print(const char *msg, const int *str)
3772 FILE *fp;
3773 int t, s = 0;
3774 CValue cval;
3776 fp = tcc_state->ppfp;
3777 fprintf(fp, "%s", msg);
3778 while (str) {
3779 TOK_GET(&t, &str, &cval);
3780 if (!t)
3781 break;
3782 fprintf(fp, &" %s"[s], get_tok_str(t, &cval)), s = 1;
3784 fprintf(fp, "\n");
3787 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3789 int d = f->line_num - f->line_ref;
3791 if (s1->dflag & 4)
3792 return;
3794 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3796 } else if (level == 0 && f->line_ref && d < 8) {
3797 while (d > 0)
3798 fputs("\n", s1->ppfp), --d;
3799 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3800 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3801 } else {
3802 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3803 level > 0 ? " 1" : level < 0 ? " 2" : "");
3805 f->line_ref = f->line_num;
3808 static void define_print(TCCState *s1, int v)
3810 FILE *fp;
3811 Sym *s;
3813 s = define_find(v);
3814 if (NULL == s || NULL == s->d)
3815 return;
3817 fp = s1->ppfp;
3818 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3819 if (s->type.t == MACRO_FUNC) {
3820 Sym *a = s->next;
3821 fprintf(fp,"(");
3822 if (a)
3823 for (;;) {
3824 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3825 if (!(a = a->next))
3826 break;
3827 fprintf(fp,",");
3829 fprintf(fp,")");
3831 tok_print("", s->d);
3834 static void pp_debug_defines(TCCState *s1)
3836 int v, t;
3837 const char *vs;
3838 FILE *fp;
3840 t = pp_debug_tok;
3841 if (t == 0)
3842 return;
3844 file->line_num--;
3845 pp_line(s1, file, 0);
3846 file->line_ref = ++file->line_num;
3848 fp = s1->ppfp;
3849 v = pp_debug_symv;
3850 vs = get_tok_str(v, NULL);
3851 if (t == TOK_DEFINE) {
3852 define_print(s1, v);
3853 } else if (t == TOK_UNDEF) {
3854 fprintf(fp, "#undef %s\n", vs);
3855 } else if (t == TOK_push_macro) {
3856 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3857 } else if (t == TOK_pop_macro) {
3858 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3860 pp_debug_tok = 0;
3863 static void pp_debug_builtins(TCCState *s1)
3865 int v;
3866 for (v = TOK_IDENT; v < tok_ident; ++v)
3867 define_print(s1, v);
3870 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3871 static int pp_need_space(int a, int b)
3873 return 'E' == a ? '+' == b || '-' == b
3874 : '+' == a ? TOK_INC == b || '+' == b
3875 : '-' == a ? TOK_DEC == b || '-' == b
3876 : a >= TOK_IDENT ? b >= TOK_IDENT
3877 : a == TOK_PPNUM ? b >= TOK_IDENT
3878 : 0;
3881 /* maybe hex like 0x1e */
3882 static int pp_check_he0xE(int t, const char *p)
3884 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3885 return 'E';
3886 return t;
3889 /* Preprocess the current file */
3890 ST_FUNC int tcc_preprocess(TCCState *s1)
3892 BufferedFile **iptr;
3893 int token_seen, spcs, level;
3894 const char *p;
3895 char white[400];
3897 parse_flags = PARSE_FLAG_PREPROCESS
3898 | (parse_flags & PARSE_FLAG_ASM_FILE)
3899 | PARSE_FLAG_LINEFEED
3900 | PARSE_FLAG_SPACES
3901 | PARSE_FLAG_ACCEPT_STRAYS
3903 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3904 capability to compile and run itself, provided all numbers are
3905 given as decimals. tcc -E -P10 will do. */
3906 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3907 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3909 if (s1->do_bench) {
3910 /* for PP benchmarks */
3911 do next(); while (tok != TOK_EOF);
3912 return 0;
3915 if (s1->dflag & 1) {
3916 pp_debug_builtins(s1);
3917 s1->dflag &= ~1;
3920 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
3921 if (file->prev)
3922 pp_line(s1, file->prev, level++);
3923 pp_line(s1, file, level);
3924 for (;;) {
3925 iptr = s1->include_stack_ptr;
3926 next();
3927 if (tok == TOK_EOF)
3928 break;
3930 level = s1->include_stack_ptr - iptr;
3931 if (level) {
3932 if (level > 0)
3933 pp_line(s1, *iptr, 0);
3934 pp_line(s1, file, level);
3936 if (s1->dflag & 7) {
3937 pp_debug_defines(s1);
3938 if (s1->dflag & 4)
3939 continue;
3942 if (is_space(tok)) {
3943 if (spcs < sizeof white - 1)
3944 white[spcs++] = tok;
3945 continue;
3946 } else if (tok == TOK_LINEFEED) {
3947 spcs = 0;
3948 if (token_seen == TOK_LINEFEED)
3949 continue;
3950 ++file->line_ref;
3951 } else if (token_seen == TOK_LINEFEED) {
3952 pp_line(s1, file, 0);
3953 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
3954 white[spcs++] = ' ';
3957 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
3958 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
3959 token_seen = pp_check_he0xE(tok, p);
3961 return 0;
3964 /* ------------------------------------------------------------------------- */