Fix include SHT_NOTE sections everywhere
[tinycc/self_contained.git] / tccpp.c
blob449035dbb6c00cb5a26df8c26e0d4434dd6fa6a9
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #define USING_GLOBALS
22 #include "tcc.h"
24 /********************************************************/
25 /* global variables */
27 ST_DATA int tok_flags;
28 ST_DATA int parse_flags;
30 ST_DATA struct BufferedFile *file;
31 ST_DATA int ch, tok;
32 ST_DATA CValue tokc;
33 ST_DATA const int *macro_ptr;
34 ST_DATA CString tokcstr; /* current parsed string, if any */
36 /* display benchmark infos */
37 ST_DATA int tok_ident;
38 ST_DATA TokenSym **table_ident;
40 /* ------------------------------------------------------------------------- */
42 static TokenSym *hash_ident[TOK_HASH_SIZE];
43 static char token_buf[STRING_MAX_SIZE + 1];
44 static CString cstr_buf;
45 static CString macro_equal_buf;
46 static TokenString tokstr_buf;
47 static unsigned char isidnum_table[256 - CH_EOF];
48 static int pp_debug_tok, pp_debug_symv;
49 static int pp_once;
50 static int pp_expr;
51 static int pp_counter;
52 static void tok_print(const char *msg, const int *str);
54 static struct TinyAlloc *toksym_alloc;
55 static struct TinyAlloc *tokstr_alloc;
57 static TokenString *macro_stack;
59 static const char tcc_keywords[] =
60 #define DEF(id, str) str "\0"
61 #include "tcctok.h"
62 #undef DEF
65 /* WARNING: the content of this string encodes token numbers */
66 static const unsigned char tok_two_chars[] =
67 /* outdated -- gr
68 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
69 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
70 */{
71 '<','=', TOK_LE,
72 '>','=', TOK_GE,
73 '!','=', TOK_NE,
74 '&','&', TOK_LAND,
75 '|','|', TOK_LOR,
76 '+','+', TOK_INC,
77 '-','-', TOK_DEC,
78 '=','=', TOK_EQ,
79 '<','<', TOK_SHL,
80 '>','>', TOK_SAR,
81 '+','=', TOK_A_ADD,
82 '-','=', TOK_A_SUB,
83 '*','=', TOK_A_MUL,
84 '/','=', TOK_A_DIV,
85 '%','=', TOK_A_MOD,
86 '&','=', TOK_A_AND,
87 '^','=', TOK_A_XOR,
88 '|','=', TOK_A_OR,
89 '-','>', TOK_ARROW,
90 '.','.', TOK_TWODOTS,
91 '#','#', TOK_TWOSHARPS,
92 '#','#', TOK_PPJOIN,
96 static void next_nomacro(void);
98 ST_FUNC void skip(int c)
100 if (tok != c)
101 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
102 next();
105 ST_FUNC void expect(const char *msg)
107 tcc_error("%s expected", msg);
110 /* ------------------------------------------------------------------------- */
111 /* Custom allocator for tiny objects */
113 #define USE_TAL
115 #ifndef USE_TAL
116 #define tal_free(al, p) tcc_free(p)
117 #define tal_realloc(al, p, size) tcc_realloc(p, size)
118 #define tal_new(a,b,c)
119 #define tal_delete(a)
120 #else
121 #if !defined(MEM_DEBUG)
122 #define tal_free(al, p) tal_free_impl(al, p)
123 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
124 #define TAL_DEBUG_PARAMS
125 #else
126 #define TAL_DEBUG 1
127 //#define TAL_INFO 1 /* collect and dump allocators stats */
128 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
129 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
130 #define TAL_DEBUG_PARAMS , const char *file, int line
131 #define TAL_DEBUG_FILE_LEN 40
132 #endif
134 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
135 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
136 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
137 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
138 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
139 #define CSTR_TAL_LIMIT 1024
141 typedef struct TinyAlloc {
142 unsigned limit;
143 unsigned size;
144 uint8_t *buffer;
145 uint8_t *p;
146 unsigned nb_allocs;
147 struct TinyAlloc *next, *top;
148 #ifdef TAL_INFO
149 unsigned nb_peak;
150 unsigned nb_total;
151 unsigned nb_missed;
152 uint8_t *peak_p;
153 #endif
154 } TinyAlloc;
156 typedef struct tal_header_t {
157 unsigned size;
158 #ifdef TAL_DEBUG
159 int line_num; /* negative line_num used for double free check */
160 char file_name[TAL_DEBUG_FILE_LEN + 1];
161 #endif
162 } tal_header_t;
164 /* ------------------------------------------------------------------------- */
166 static TinyAlloc *tal_new(TinyAlloc **pal, unsigned limit, unsigned size)
168 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
169 al->p = al->buffer = tcc_malloc(size);
170 al->limit = limit;
171 al->size = size;
172 if (pal) *pal = al;
173 return al;
176 static void tal_delete(TinyAlloc *al)
178 TinyAlloc *next;
180 tail_call:
181 if (!al)
182 return;
183 #ifdef TAL_INFO
184 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
185 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
186 (al->peak_p - al->buffer) * 100.0 / al->size);
187 #endif
188 #ifdef TAL_DEBUG
189 if (al->nb_allocs > 0) {
190 uint8_t *p;
191 fprintf(stderr, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
192 al->nb_allocs, al->limit);
193 p = al->buffer;
194 while (p < al->p) {
195 tal_header_t *header = (tal_header_t *)p;
196 if (header->line_num > 0) {
197 fprintf(stderr, "%s:%d: chunk of %d bytes leaked\n",
198 header->file_name, header->line_num, header->size);
200 p += header->size + sizeof(tal_header_t);
202 #if MEM_DEBUG-0 == 2
203 exit(2);
204 #endif
206 #endif
207 next = al->next;
208 tcc_free(al->buffer);
209 tcc_free(al);
210 al = next;
211 goto tail_call;
214 static void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
216 if (!p)
217 return;
218 tail_call:
219 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
220 #ifdef TAL_DEBUG
221 tal_header_t *header = (((tal_header_t *)p) - 1);
222 if (header->line_num < 0) {
223 fprintf(stderr, "%s:%d: TAL_DEBUG: double frees chunk from\n",
224 file, line);
225 fprintf(stderr, "%s:%d: %d bytes\n",
226 header->file_name, (int)-header->line_num, (int)header->size);
227 } else
228 header->line_num = -header->line_num;
229 #endif
230 al->nb_allocs--;
231 if (!al->nb_allocs)
232 al->p = al->buffer;
233 } else if (al->next) {
234 al = al->next;
235 goto tail_call;
237 else
238 tcc_free(p);
241 static void *tal_realloc_impl(TinyAlloc **pal, void *p, unsigned size TAL_DEBUG_PARAMS)
243 tal_header_t *header;
244 void *ret;
245 int is_own;
246 unsigned adj_size = (size + 3) & -4;
247 TinyAlloc *al = *pal;
249 tail_call:
250 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
251 if ((!p || is_own) && size <= al->limit) {
252 if (al->p - al->buffer + adj_size + sizeof(tal_header_t) < al->size) {
253 header = (tal_header_t *)al->p;
254 header->size = adj_size;
255 #ifdef TAL_DEBUG
256 { int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
257 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
258 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
259 header->line_num = line; }
260 #endif
261 ret = al->p + sizeof(tal_header_t);
262 al->p += adj_size + sizeof(tal_header_t);
263 if (is_own) {
264 header = (((tal_header_t *)p) - 1);
265 if (p) memcpy(ret, p, header->size);
266 #ifdef TAL_DEBUG
267 header->line_num = -header->line_num;
268 #endif
269 } else {
270 al->nb_allocs++;
272 #ifdef TAL_INFO
273 if (al->nb_peak < al->nb_allocs)
274 al->nb_peak = al->nb_allocs;
275 if (al->peak_p < al->p)
276 al->peak_p = al->p;
277 al->nb_total++;
278 #endif
279 return ret;
280 } else if (is_own) {
281 al->nb_allocs--;
282 ret = tal_realloc(*pal, 0, size);
283 header = (((tal_header_t *)p) - 1);
284 if (p) memcpy(ret, p, header->size);
285 #ifdef TAL_DEBUG
286 header->line_num = -header->line_num;
287 #endif
288 return ret;
290 if (al->next) {
291 al = al->next;
292 } else {
293 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
295 al = tal_new(pal, next->limit, next->size * 2);
296 al->next = next;
297 bottom->top = al;
299 goto tail_call;
301 if (is_own) {
302 al->nb_allocs--;
303 ret = tcc_malloc(size);
304 header = (((tal_header_t *)p) - 1);
305 if (p) memcpy(ret, p, header->size);
306 #ifdef TAL_DEBUG
307 header->line_num = -header->line_num;
308 #endif
309 } else if (al->next) {
310 al = al->next;
311 goto tail_call;
312 } else
313 ret = tcc_realloc(p, size);
314 #ifdef TAL_INFO
315 al->nb_missed++;
316 #endif
317 return ret;
320 #endif /* USE_TAL */
322 /* ------------------------------------------------------------------------- */
323 /* CString handling */
324 static void cstr_realloc(CString *cstr, int new_size)
326 int size;
328 size = cstr->size_allocated;
329 if (size < 8)
330 size = 8; /* no need to allocate a too small first string */
331 while (size < new_size)
332 size = size * 2;
333 cstr->data = tcc_realloc(cstr->data, size);
334 cstr->size_allocated = size;
337 /* add a byte */
338 ST_INLN void cstr_ccat(CString *cstr, int ch)
340 int size;
341 size = cstr->size + 1;
342 if (size > cstr->size_allocated)
343 cstr_realloc(cstr, size);
344 ((unsigned char *)cstr->data)[size - 1] = ch;
345 cstr->size = size;
348 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
350 int size;
351 if (len <= 0)
352 len = strlen(str) + 1 + len;
353 size = cstr->size + len;
354 if (size > cstr->size_allocated)
355 cstr_realloc(cstr, size);
356 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
357 cstr->size = size;
360 /* add a wide char */
361 ST_FUNC void cstr_wccat(CString *cstr, int ch)
363 int size;
364 size = cstr->size + sizeof(nwchar_t);
365 if (size > cstr->size_allocated)
366 cstr_realloc(cstr, size);
367 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
368 cstr->size = size;
371 ST_FUNC void cstr_new(CString *cstr)
373 memset(cstr, 0, sizeof(CString));
376 /* free string and reset it to NULL */
377 ST_FUNC void cstr_free(CString *cstr)
379 tcc_free(cstr->data);
380 cstr_new(cstr);
383 /* reset string to empty */
384 ST_FUNC void cstr_reset(CString *cstr)
386 cstr->size = 0;
389 ST_FUNC int cstr_printf(CString *cstr, const char *fmt, ...)
391 va_list v;
392 int len, size = 80;
393 for (;;) {
394 size += cstr->size;
395 if (size > cstr->size_allocated)
396 cstr_realloc(cstr, size);
397 size = cstr->size_allocated - cstr->size;
398 va_start(v, fmt);
399 len = vsnprintf((char*)cstr->data + cstr->size, size, fmt, v);
400 va_end(v);
401 if (len > 0 && len < size)
402 break;
403 size *= 2;
405 cstr->size += len;
406 return len;
409 /* XXX: unicode ? */
410 static void add_char(CString *cstr, int c)
412 if (c == '\'' || c == '\"' || c == '\\') {
413 /* XXX: could be more precise if char or string */
414 cstr_ccat(cstr, '\\');
416 if (c >= 32 && c <= 126) {
417 cstr_ccat(cstr, c);
418 } else {
419 cstr_ccat(cstr, '\\');
420 if (c == '\n') {
421 cstr_ccat(cstr, 'n');
422 } else {
423 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
424 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
425 cstr_ccat(cstr, '0' + (c & 7));
430 /* ------------------------------------------------------------------------- */
431 /* allocate a new token */
432 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
434 TokenSym *ts, **ptable;
435 int i;
437 if (tok_ident >= SYM_FIRST_ANOM)
438 tcc_error("memory full (symbols)");
440 /* expand token table if needed */
441 i = tok_ident - TOK_IDENT;
442 if ((i % TOK_ALLOC_INCR) == 0) {
443 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
444 table_ident = ptable;
447 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
448 table_ident[i] = ts;
449 ts->tok = tok_ident++;
450 ts->sym_define = NULL;
451 ts->sym_label = NULL;
452 ts->sym_struct = NULL;
453 ts->sym_identifier = NULL;
454 ts->len = len;
455 ts->hash_next = NULL;
456 memcpy(ts->str, str, len);
457 ts->str[len] = '\0';
458 *pts = ts;
459 return ts;
462 #define TOK_HASH_INIT 1
463 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
466 /* find a token and add it if not found */
467 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
469 TokenSym *ts, **pts;
470 int i;
471 unsigned int h;
473 h = TOK_HASH_INIT;
474 for(i=0;i<len;i++)
475 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
476 h &= (TOK_HASH_SIZE - 1);
478 pts = &hash_ident[h];
479 for(;;) {
480 ts = *pts;
481 if (!ts)
482 break;
483 if (ts->len == len && !memcmp(ts->str, str, len))
484 return ts;
485 pts = &(ts->hash_next);
487 return tok_alloc_new(pts, str, len);
490 /* XXX: buffer overflow */
491 /* XXX: float tokens */
492 ST_FUNC const char *get_tok_str(int v, CValue *cv)
494 char *p;
495 int i, len;
497 cstr_reset(&cstr_buf);
498 p = cstr_buf.data;
500 switch(v) {
501 case TOK_CINT:
502 case TOK_CUINT:
503 case TOK_CLONG:
504 case TOK_CULONG:
505 case TOK_CLLONG:
506 case TOK_CULLONG:
507 /* XXX: not quite exact, but only useful for testing */
508 #ifdef _WIN32
509 sprintf(p, "%u", (unsigned)cv->i);
510 #else
511 sprintf(p, "%llu", (unsigned long long)cv->i);
512 #endif
513 break;
514 case TOK_LCHAR:
515 cstr_ccat(&cstr_buf, 'L');
516 case TOK_CCHAR:
517 cstr_ccat(&cstr_buf, '\'');
518 add_char(&cstr_buf, cv->i);
519 cstr_ccat(&cstr_buf, '\'');
520 cstr_ccat(&cstr_buf, '\0');
521 break;
522 case TOK_PPNUM:
523 case TOK_PPSTR:
524 return (char*)cv->str.data;
525 case TOK_LSTR:
526 cstr_ccat(&cstr_buf, 'L');
527 case TOK_STR:
528 cstr_ccat(&cstr_buf, '\"');
529 if (v == TOK_STR) {
530 len = cv->str.size - 1;
531 for(i=0;i<len;i++)
532 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
533 } else {
534 len = (cv->str.size / sizeof(nwchar_t)) - 1;
535 for(i=0;i<len;i++)
536 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
538 cstr_ccat(&cstr_buf, '\"');
539 cstr_ccat(&cstr_buf, '\0');
540 break;
542 case TOK_CFLOAT:
543 cstr_cat(&cstr_buf, "<float>", 0);
544 break;
545 case TOK_CDOUBLE:
546 cstr_cat(&cstr_buf, "<double>", 0);
547 break;
548 case TOK_CLDOUBLE:
549 cstr_cat(&cstr_buf, "<long double>", 0);
550 break;
551 case TOK_LINENUM:
552 cstr_cat(&cstr_buf, "<linenumber>", 0);
553 break;
555 /* above tokens have value, the ones below don't */
556 case TOK_LT:
557 v = '<';
558 goto addv;
559 case TOK_GT:
560 v = '>';
561 goto addv;
562 case TOK_DOTS:
563 return strcpy(p, "...");
564 case TOK_A_SHL:
565 return strcpy(p, "<<=");
566 case TOK_A_SAR:
567 return strcpy(p, ">>=");
568 case TOK_EOF:
569 return strcpy(p, "<eof>");
570 default:
571 if (v < TOK_IDENT) {
572 /* search in two bytes table */
573 const unsigned char *q = tok_two_chars;
574 while (*q) {
575 if (q[2] == v) {
576 *p++ = q[0];
577 *p++ = q[1];
578 *p = '\0';
579 return cstr_buf.data;
581 q += 3;
583 if (v >= 127) {
584 sprintf(cstr_buf.data, "<%02x>", v);
585 return cstr_buf.data;
587 addv:
588 *p++ = v;
589 *p = '\0';
590 } else if (v < tok_ident) {
591 return table_ident[v - TOK_IDENT]->str;
592 } else if (v >= SYM_FIRST_ANOM) {
593 /* special name for anonymous symbol */
594 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
595 } else {
596 /* should never happen */
597 return NULL;
599 break;
601 return cstr_buf.data;
604 /* return the current character, handling end of block if necessary
605 (but not stray) */
606 static int handle_eob(void)
608 BufferedFile *bf = file;
609 int len;
611 /* only tries to read if really end of buffer */
612 if (bf->buf_ptr >= bf->buf_end) {
613 if (bf->fd >= 0) {
614 #if defined(PARSE_DEBUG)
615 len = 1;
616 #else
617 len = IO_BUF_SIZE;
618 #endif
619 len = read(bf->fd, bf->buffer, len);
620 if (len < 0)
621 len = 0;
622 } else {
623 len = 0;
625 total_bytes += len;
626 bf->buf_ptr = bf->buffer;
627 bf->buf_end = bf->buffer + len;
628 *bf->buf_end = CH_EOB;
630 if (bf->buf_ptr < bf->buf_end) {
631 return bf->buf_ptr[0];
632 } else {
633 bf->buf_ptr = bf->buf_end;
634 return CH_EOF;
638 /* read next char from current input file and handle end of input buffer */
639 static inline void inp(void)
641 ch = *(++(file->buf_ptr));
642 /* end of buffer/file handling */
643 if (ch == CH_EOB)
644 ch = handle_eob();
647 /* handle '\[\r]\n' */
648 static int handle_stray_noerror(void)
650 while (ch == '\\') {
651 inp();
652 if (ch == '\n') {
653 file->line_num++;
654 inp();
655 } else if (ch == '\r') {
656 inp();
657 if (ch != '\n')
658 goto fail;
659 file->line_num++;
660 inp();
661 } else {
662 fail:
663 return 1;
666 return 0;
669 static void handle_stray(void)
671 if (handle_stray_noerror())
672 tcc_error("stray '\\' in program");
675 /* skip the stray and handle the \\n case. Output an error if
676 incorrect char after the stray */
677 static int handle_stray1(uint8_t *p)
679 int c;
681 file->buf_ptr = p;
682 if (p >= file->buf_end) {
683 c = handle_eob();
684 if (c != '\\')
685 return c;
686 p = file->buf_ptr;
688 ch = *p;
689 if (handle_stray_noerror()) {
690 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
691 tcc_error("stray '\\' in program");
692 *--file->buf_ptr = '\\';
694 p = file->buf_ptr;
695 c = *p;
696 return c;
699 /* handle just the EOB case, but not stray */
700 #define PEEKC_EOB(c, p)\
702 p++;\
703 c = *p;\
704 if (c == '\\') {\
705 file->buf_ptr = p;\
706 c = handle_eob();\
707 p = file->buf_ptr;\
711 /* handle the complicated stray case */
712 #define PEEKC(c, p)\
714 p++;\
715 c = *p;\
716 if (c == '\\') {\
717 c = handle_stray1(p);\
718 p = file->buf_ptr;\
722 /* input with '\[\r]\n' handling. Note that this function cannot
723 handle other characters after '\', so you cannot call it inside
724 strings or comments */
725 static void minp(void)
727 inp();
728 if (ch == '\\')
729 handle_stray();
732 /* single line C++ comments */
733 static uint8_t *parse_line_comment(uint8_t *p)
735 int c;
737 p++;
738 for(;;) {
739 c = *p;
740 redo:
741 if (c == '\n' || c == CH_EOF) {
742 break;
743 } else if (c == '\\') {
744 file->buf_ptr = p;
745 c = handle_eob();
746 p = file->buf_ptr;
747 if (c == '\\') {
748 PEEKC_EOB(c, p);
749 if (c == '\n') {
750 file->line_num++;
751 PEEKC_EOB(c, p);
752 } else if (c == '\r') {
753 PEEKC_EOB(c, p);
754 if (c == '\n') {
755 file->line_num++;
756 PEEKC_EOB(c, p);
759 } else {
760 goto redo;
762 } else {
763 p++;
766 return p;
769 /* C comments */
770 static uint8_t *parse_comment(uint8_t *p)
772 int c;
774 p++;
775 for(;;) {
776 /* fast skip loop */
777 for(;;) {
778 c = *p;
779 if (c == '\n' || c == '*' || c == '\\')
780 break;
781 p++;
782 c = *p;
783 if (c == '\n' || c == '*' || c == '\\')
784 break;
785 p++;
787 /* now we can handle all the cases */
788 if (c == '\n') {
789 file->line_num++;
790 p++;
791 } else if (c == '*') {
792 p++;
793 for(;;) {
794 c = *p;
795 if (c == '*') {
796 p++;
797 } else if (c == '/') {
798 goto end_of_comment;
799 } else if (c == '\\') {
800 file->buf_ptr = p;
801 c = handle_eob();
802 p = file->buf_ptr;
803 if (c == CH_EOF)
804 tcc_error("unexpected end of file in comment");
805 if (c == '\\') {
806 /* skip '\[\r]\n', otherwise just skip the stray */
807 while (c == '\\') {
808 PEEKC_EOB(c, p);
809 if (c == '\n') {
810 file->line_num++;
811 PEEKC_EOB(c, p);
812 } else if (c == '\r') {
813 PEEKC_EOB(c, p);
814 if (c == '\n') {
815 file->line_num++;
816 PEEKC_EOB(c, p);
818 } else {
819 goto after_star;
823 } else {
824 break;
827 after_star: ;
828 } else {
829 /* stray, eob or eof */
830 file->buf_ptr = p;
831 c = handle_eob();
832 p = file->buf_ptr;
833 if (c == CH_EOF) {
834 tcc_error("unexpected end of file in comment");
835 } else if (c == '\\') {
836 p++;
840 end_of_comment:
841 p++;
842 return p;
845 ST_FUNC int set_idnum(int c, int val)
847 int prev = isidnum_table[c - CH_EOF];
848 isidnum_table[c - CH_EOF] = val;
849 return prev;
852 #define cinp minp
854 static inline void skip_spaces(void)
856 while (isidnum_table[ch - CH_EOF] & IS_SPC)
857 cinp();
860 static inline int check_space(int t, int *spc)
862 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
863 if (*spc)
864 return 1;
865 *spc = 1;
866 } else
867 *spc = 0;
868 return 0;
871 /* parse a string without interpreting escapes */
872 static uint8_t *parse_pp_string(uint8_t *p,
873 int sep, CString *str)
875 int c;
876 p++;
877 for(;;) {
878 c = *p;
879 if (c == sep) {
880 break;
881 } else if (c == '\\') {
882 file->buf_ptr = p;
883 c = handle_eob();
884 p = file->buf_ptr;
885 if (c == CH_EOF) {
886 unterminated_string:
887 /* XXX: indicate line number of start of string */
888 tcc_error("missing terminating %c character", sep);
889 } else if (c == '\\') {
890 /* escape : just skip \[\r]\n */
891 PEEKC_EOB(c, p);
892 if (c == '\n') {
893 file->line_num++;
894 p++;
895 } else if (c == '\r') {
896 PEEKC_EOB(c, p);
897 if (c != '\n')
898 expect("'\n' after '\r'");
899 file->line_num++;
900 p++;
901 } else if (c == CH_EOF) {
902 goto unterminated_string;
903 } else {
904 if (str) {
905 cstr_ccat(str, '\\');
906 cstr_ccat(str, c);
908 p++;
911 } else if (c == '\n') {
912 file->line_num++;
913 goto add_char;
914 } else if (c == '\r') {
915 PEEKC_EOB(c, p);
916 if (c != '\n') {
917 if (str)
918 cstr_ccat(str, '\r');
919 } else {
920 file->line_num++;
921 goto add_char;
923 } else {
924 add_char:
925 if (str)
926 cstr_ccat(str, c);
927 p++;
930 p++;
931 return p;
934 /* skip block of text until #else, #elif or #endif. skip also pairs of
935 #if/#endif */
936 static void preprocess_skip(void)
938 int a, start_of_line, c, in_warn_or_error;
939 uint8_t *p;
941 p = file->buf_ptr;
942 a = 0;
943 redo_start:
944 start_of_line = 1;
945 in_warn_or_error = 0;
946 for(;;) {
947 redo_no_start:
948 c = *p;
949 switch(c) {
950 case ' ':
951 case '\t':
952 case '\f':
953 case '\v':
954 case '\r':
955 p++;
956 goto redo_no_start;
957 case '\n':
958 file->line_num++;
959 p++;
960 goto redo_start;
961 case '\\':
962 file->buf_ptr = p;
963 c = handle_eob();
964 if (c == CH_EOF) {
965 expect("#endif");
966 } else if (c == '\\') {
967 ch = file->buf_ptr[0];
968 handle_stray_noerror();
970 p = file->buf_ptr;
971 goto redo_no_start;
972 /* skip strings */
973 case '\"':
974 case '\'':
975 if (in_warn_or_error)
976 goto _default;
977 p = parse_pp_string(p, c, NULL);
978 break;
979 /* skip comments */
980 case '/':
981 if (in_warn_or_error)
982 goto _default;
983 file->buf_ptr = p;
984 ch = *p;
985 minp();
986 p = file->buf_ptr;
987 if (ch == '*') {
988 p = parse_comment(p);
989 } else if (ch == '/') {
990 p = parse_line_comment(p);
992 break;
993 case '#':
994 p++;
995 if (start_of_line) {
996 file->buf_ptr = p;
997 next_nomacro();
998 p = file->buf_ptr;
999 if (a == 0 &&
1000 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
1001 goto the_end;
1002 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
1003 a++;
1004 else if (tok == TOK_ENDIF)
1005 a--;
1006 else if( tok == TOK_ERROR || tok == TOK_WARNING)
1007 in_warn_or_error = 1;
1008 else if (tok == TOK_LINEFEED)
1009 goto redo_start;
1010 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1011 p = parse_line_comment(p - 1);
1012 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
1013 p = parse_line_comment(p - 1);
1014 break;
1015 _default:
1016 default:
1017 p++;
1018 break;
1020 start_of_line = 0;
1022 the_end: ;
1023 file->buf_ptr = p;
1026 #if 0
1027 /* return the number of additional 'ints' necessary to store the
1028 token */
1029 static inline int tok_size(const int *p)
1031 switch(*p) {
1032 /* 4 bytes */
1033 case TOK_CINT:
1034 case TOK_CUINT:
1035 case TOK_CCHAR:
1036 case TOK_LCHAR:
1037 case TOK_CFLOAT:
1038 case TOK_LINENUM:
1039 return 1 + 1;
1040 case TOK_STR:
1041 case TOK_LSTR:
1042 case TOK_PPNUM:
1043 case TOK_PPSTR:
1044 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1045 case TOK_CLONG:
1046 case TOK_CULONG:
1047 return 1 + LONG_SIZE / 4;
1048 case TOK_CDOUBLE:
1049 case TOK_CLLONG:
1050 case TOK_CULLONG:
1051 return 1 + 2;
1052 case TOK_CLDOUBLE:
1053 return 1 + LDOUBLE_SIZE / 4;
1054 default:
1055 return 1 + 0;
1058 #endif
1060 /* token string handling */
1061 ST_INLN void tok_str_new(TokenString *s)
1063 s->str = NULL;
1064 s->len = s->lastlen = 0;
1065 s->allocated_len = 0;
1066 s->last_line_num = -1;
1069 ST_FUNC TokenString *tok_str_alloc(void)
1071 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1072 tok_str_new(str);
1073 return str;
1076 ST_FUNC int *tok_str_dup(TokenString *s)
1078 int *str;
1080 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1081 memcpy(str, s->str, s->len * sizeof(int));
1082 return str;
1085 ST_FUNC void tok_str_free_str(int *str)
1087 tal_free(tokstr_alloc, str);
1090 ST_FUNC void tok_str_free(TokenString *str)
1092 tok_str_free_str(str->str);
1093 tal_free(tokstr_alloc, str);
1096 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1098 int *str, size;
1100 size = s->allocated_len;
1101 if (size < 16)
1102 size = 16;
1103 while (size < new_size)
1104 size = size * 2;
1105 if (size > s->allocated_len) {
1106 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1107 s->allocated_len = size;
1108 s->str = str;
1110 return s->str;
1113 ST_FUNC void tok_str_add(TokenString *s, int t)
1115 int len, *str;
1117 len = s->len;
1118 str = s->str;
1119 if (len >= s->allocated_len)
1120 str = tok_str_realloc(s, len + 1);
1121 str[len++] = t;
1122 s->len = len;
1125 ST_FUNC void begin_macro(TokenString *str, int alloc)
1127 str->alloc = alloc;
1128 str->prev = macro_stack;
1129 str->prev_ptr = macro_ptr;
1130 str->save_line_num = file->line_num;
1131 macro_ptr = str->str;
1132 macro_stack = str;
1135 ST_FUNC void end_macro(void)
1137 TokenString *str = macro_stack;
1138 macro_stack = str->prev;
1139 macro_ptr = str->prev_ptr;
1140 file->line_num = str->save_line_num;
1141 if (str->alloc != 0) {
1142 if (str->alloc == 2)
1143 str->str = NULL; /* don't free */
1144 tok_str_free(str);
1148 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1150 int len, *str;
1152 len = s->lastlen = s->len;
1153 str = s->str;
1155 /* allocate space for worst case */
1156 if (len + TOK_MAX_SIZE >= s->allocated_len)
1157 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1158 str[len++] = t;
1159 switch(t) {
1160 case TOK_CINT:
1161 case TOK_CUINT:
1162 case TOK_CCHAR:
1163 case TOK_LCHAR:
1164 case TOK_CFLOAT:
1165 case TOK_LINENUM:
1166 #if LONG_SIZE == 4
1167 case TOK_CLONG:
1168 case TOK_CULONG:
1169 #endif
1170 str[len++] = cv->tab[0];
1171 break;
1172 case TOK_PPNUM:
1173 case TOK_PPSTR:
1174 case TOK_STR:
1175 case TOK_LSTR:
1177 /* Insert the string into the int array. */
1178 size_t nb_words =
1179 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1180 if (len + nb_words >= s->allocated_len)
1181 str = tok_str_realloc(s, len + nb_words + 1);
1182 str[len] = cv->str.size;
1183 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1184 len += nb_words;
1186 break;
1187 case TOK_CDOUBLE:
1188 case TOK_CLLONG:
1189 case TOK_CULLONG:
1190 #if LONG_SIZE == 8
1191 case TOK_CLONG:
1192 case TOK_CULONG:
1193 #endif
1194 #if LDOUBLE_SIZE == 8
1195 case TOK_CLDOUBLE:
1196 #endif
1197 str[len++] = cv->tab[0];
1198 str[len++] = cv->tab[1];
1199 break;
1200 #if LDOUBLE_SIZE == 12
1201 case TOK_CLDOUBLE:
1202 str[len++] = cv->tab[0];
1203 str[len++] = cv->tab[1];
1204 str[len++] = cv->tab[2];
1205 #elif LDOUBLE_SIZE == 16
1206 case TOK_CLDOUBLE:
1207 str[len++] = cv->tab[0];
1208 str[len++] = cv->tab[1];
1209 str[len++] = cv->tab[2];
1210 str[len++] = cv->tab[3];
1211 #elif LDOUBLE_SIZE != 8
1212 #error add long double size support
1213 #endif
1214 break;
1215 default:
1216 break;
1218 s->len = len;
1221 /* add the current parse token in token string 's' */
1222 ST_FUNC void tok_str_add_tok(TokenString *s)
1224 CValue cval;
1226 /* save line number info */
1227 if (file->line_num != s->last_line_num) {
1228 s->last_line_num = file->line_num;
1229 cval.i = s->last_line_num;
1230 tok_str_add2(s, TOK_LINENUM, &cval);
1232 tok_str_add2(s, tok, &tokc);
1235 /* get a token from an integer array and increment pointer. */
1236 static inline void tok_get(int *t, const int **pp, CValue *cv)
1238 const int *p = *pp;
1239 int n, *tab;
1241 tab = cv->tab;
1242 switch(*t = *p++) {
1243 #if LONG_SIZE == 4
1244 case TOK_CLONG:
1245 #endif
1246 case TOK_CINT:
1247 case TOK_CCHAR:
1248 case TOK_LCHAR:
1249 case TOK_LINENUM:
1250 cv->i = *p++;
1251 break;
1252 #if LONG_SIZE == 4
1253 case TOK_CULONG:
1254 #endif
1255 case TOK_CUINT:
1256 cv->i = (unsigned)*p++;
1257 break;
1258 case TOK_CFLOAT:
1259 tab[0] = *p++;
1260 break;
1261 case TOK_STR:
1262 case TOK_LSTR:
1263 case TOK_PPNUM:
1264 case TOK_PPSTR:
1265 cv->str.size = *p++;
1266 cv->str.data = p;
1267 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1268 break;
1269 case TOK_CDOUBLE:
1270 case TOK_CLLONG:
1271 case TOK_CULLONG:
1272 #if LONG_SIZE == 8
1273 case TOK_CLONG:
1274 case TOK_CULONG:
1275 #endif
1276 n = 2;
1277 goto copy;
1278 case TOK_CLDOUBLE:
1279 #if LDOUBLE_SIZE == 16
1280 n = 4;
1281 #elif LDOUBLE_SIZE == 12
1282 n = 3;
1283 #elif LDOUBLE_SIZE == 8
1284 n = 2;
1285 #else
1286 # error add long double size support
1287 #endif
1288 copy:
1290 *tab++ = *p++;
1291 while (--n);
1292 break;
1293 default:
1294 break;
1296 *pp = p;
1299 #if 0
1300 # define TOK_GET(t,p,c) tok_get(t,p,c)
1301 #else
1302 # define TOK_GET(t,p,c) do { \
1303 int _t = **(p); \
1304 if (TOK_HAS_VALUE(_t)) \
1305 tok_get(t, p, c); \
1306 else \
1307 *(t) = _t, ++*(p); \
1308 } while (0)
1309 #endif
1311 static int macro_is_equal(const int *a, const int *b)
1313 CValue cv;
1314 int t;
1316 if (!a || !b)
1317 return 1;
1319 while (*a && *b) {
1320 /* first time preallocate macro_equal_buf, next time only reset position to start */
1321 cstr_reset(&macro_equal_buf);
1322 TOK_GET(&t, &a, &cv);
1323 cstr_cat(&macro_equal_buf, get_tok_str(t, &cv), 0);
1324 TOK_GET(&t, &b, &cv);
1325 if (strcmp(macro_equal_buf.data, get_tok_str(t, &cv)))
1326 return 0;
1328 return !(*a || *b);
1331 /* defines handling */
1332 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1334 Sym *s, *o;
1336 o = define_find(v);
1337 s = sym_push2(&define_stack, v, macro_type, 0);
1338 s->d = str;
1339 s->next = first_arg;
1340 table_ident[v - TOK_IDENT]->sym_define = s;
1342 if (o && !macro_is_equal(o->d, s->d))
1343 tcc_warning("%s redefined", get_tok_str(v, NULL));
1346 /* undefined a define symbol. Its name is just set to zero */
1347 ST_FUNC void define_undef(Sym *s)
1349 int v = s->v;
1350 if (v >= TOK_IDENT && v < tok_ident)
1351 table_ident[v - TOK_IDENT]->sym_define = NULL;
1354 ST_INLN Sym *define_find(int v)
1356 v -= TOK_IDENT;
1357 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1358 return NULL;
1359 return table_ident[v]->sym_define;
1362 /* free define stack until top reaches 'b' */
1363 ST_FUNC void free_defines(Sym *b)
1365 while (define_stack != b) {
1366 Sym *top = define_stack;
1367 define_stack = top->prev;
1368 tok_str_free_str(top->d);
1369 define_undef(top);
1370 sym_free(top);
1374 /* label lookup */
1375 ST_FUNC Sym *label_find(int v)
1377 v -= TOK_IDENT;
1378 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1379 return NULL;
1380 return table_ident[v]->sym_label;
1383 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1385 Sym *s, **ps;
1386 s = sym_push2(ptop, v, 0, 0);
1387 s->r = flags;
1388 ps = &table_ident[v - TOK_IDENT]->sym_label;
1389 if (ptop == &global_label_stack) {
1390 /* modify the top most local identifier, so that
1391 sym_identifier will point to 's' when popped */
1392 while (*ps != NULL)
1393 ps = &(*ps)->prev_tok;
1395 s->prev_tok = *ps;
1396 *ps = s;
1397 return s;
1400 /* pop labels until element last is reached. Look if any labels are
1401 undefined. Define symbols if '&&label' was used. */
1402 ST_FUNC void label_pop(Sym **ptop, Sym *slast, int keep)
1404 Sym *s, *s1;
1405 for(s = *ptop; s != slast; s = s1) {
1406 s1 = s->prev;
1407 if (s->r == LABEL_DECLARED) {
1408 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1409 } else if (s->r == LABEL_FORWARD) {
1410 tcc_error("label '%s' used but not defined",
1411 get_tok_str(s->v, NULL));
1412 } else {
1413 if (s->c) {
1414 /* define corresponding symbol. A size of
1415 1 is put. */
1416 put_extern_sym(s, cur_text_section, s->jnext, 1);
1419 /* remove label */
1420 if (s->r != LABEL_GONE)
1421 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1422 if (!keep)
1423 sym_free(s);
1424 else
1425 s->r = LABEL_GONE;
1427 if (!keep)
1428 *ptop = slast;
1431 /* fake the nth "#if defined test_..." for tcc -dt -run */
1432 static void maybe_run_test(TCCState *s)
1434 const char *p;
1435 if (s->include_stack_ptr != s->include_stack)
1436 return;
1437 p = get_tok_str(tok, NULL);
1438 if (0 != memcmp(p, "test_", 5))
1439 return;
1440 if (0 != --s->run_test)
1441 return;
1442 fprintf(s->ppfp, &"\n[%s]\n"[!(s->dflag & 32)], p), fflush(s->ppfp);
1443 define_push(tok, MACRO_OBJ, NULL, NULL);
1446 /* eval an expression for #if/#elif */
1447 static int expr_preprocess(void)
1449 int c, t;
1450 TokenString *str;
1452 str = tok_str_alloc();
1453 pp_expr = 1;
1454 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1455 next(); /* do macro subst */
1456 redo:
1457 if (tok == TOK_DEFINED) {
1458 next_nomacro();
1459 t = tok;
1460 if (t == '(')
1461 next_nomacro();
1462 if (tok < TOK_IDENT)
1463 expect("identifier");
1464 if (tcc_state->run_test)
1465 maybe_run_test(tcc_state);
1466 c = define_find(tok) != 0;
1467 if (t == '(') {
1468 next_nomacro();
1469 if (tok != ')')
1470 expect("')'");
1472 tok = TOK_CINT;
1473 tokc.i = c;
1474 } else if (1 && tok == TOK___HAS_INCLUDE) {
1475 next(); /* XXX check if correct to use expansion */
1476 skip('(');
1477 while (tok != ')' && tok != TOK_EOF)
1478 next();
1479 if (tok != ')')
1480 expect("')'");
1481 tok = TOK_CINT;
1482 tokc.i = 0;
1483 } else if (tok >= TOK_IDENT) {
1484 /* if undefined macro, replace with zero, check for func-like */
1485 t = tok;
1486 tok = TOK_CINT;
1487 tokc.i = 0;
1488 tok_str_add_tok(str);
1489 next();
1490 if (tok == '(')
1491 tcc_error("function-like macro '%s' is not defined",
1492 get_tok_str(t, NULL));
1493 goto redo;
1495 tok_str_add_tok(str);
1497 pp_expr = 0;
1498 tok_str_add(str, -1); /* simulate end of file */
1499 tok_str_add(str, 0);
1500 /* now evaluate C constant expression */
1501 begin_macro(str, 1);
1502 next();
1503 c = expr_const();
1504 end_macro();
1505 return c != 0;
1509 /* parse after #define */
1510 ST_FUNC void parse_define(void)
1512 Sym *s, *first, **ps;
1513 int v, t, varg, is_vaargs, spc;
1514 int saved_parse_flags = parse_flags;
1516 v = tok;
1517 if (v < TOK_IDENT || v == TOK_DEFINED)
1518 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1519 /* XXX: should check if same macro (ANSI) */
1520 first = NULL;
1521 t = MACRO_OBJ;
1522 /* We have to parse the whole define as if not in asm mode, in particular
1523 no line comment with '#' must be ignored. Also for function
1524 macros the argument list must be parsed without '.' being an ID
1525 character. */
1526 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1527 /* '(' must be just after macro definition for MACRO_FUNC */
1528 next_nomacro();
1529 parse_flags &= ~PARSE_FLAG_SPACES;
1530 if (tok == '(') {
1531 int dotid = set_idnum('.', 0);
1532 next_nomacro();
1533 ps = &first;
1534 if (tok != ')') for (;;) {
1535 varg = tok;
1536 next_nomacro();
1537 is_vaargs = 0;
1538 if (varg == TOK_DOTS) {
1539 varg = TOK___VA_ARGS__;
1540 is_vaargs = 1;
1541 } else if (tok == TOK_DOTS && gnu_ext) {
1542 is_vaargs = 1;
1543 next_nomacro();
1545 if (varg < TOK_IDENT)
1546 bad_list:
1547 tcc_error("bad macro parameter list");
1548 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1549 *ps = s;
1550 ps = &s->next;
1551 if (tok == ')')
1552 break;
1553 if (tok != ',' || is_vaargs)
1554 goto bad_list;
1555 next_nomacro();
1557 parse_flags |= PARSE_FLAG_SPACES;
1558 next_nomacro();
1559 t = MACRO_FUNC;
1560 set_idnum('.', dotid);
1563 tokstr_buf.len = 0;
1564 spc = 2;
1565 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1566 /* The body of a macro definition should be parsed such that identifiers
1567 are parsed like the file mode determines (i.e. with '.' being an
1568 ID character in asm mode). But '#' should be retained instead of
1569 regarded as line comment leader, so still don't set ASM_FILE
1570 in parse_flags. */
1571 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1572 /* remove spaces around ## and after '#' */
1573 if (TOK_TWOSHARPS == tok) {
1574 if (2 == spc)
1575 goto bad_twosharp;
1576 if (1 == spc)
1577 --tokstr_buf.len;
1578 spc = 3;
1579 tok = TOK_PPJOIN;
1580 } else if ('#' == tok) {
1581 spc = 4;
1582 } else if (check_space(tok, &spc)) {
1583 goto skip;
1585 tok_str_add2(&tokstr_buf, tok, &tokc);
1586 skip:
1587 next_nomacro();
1590 parse_flags = saved_parse_flags;
1591 if (spc == 1)
1592 --tokstr_buf.len; /* remove trailing space */
1593 tok_str_add(&tokstr_buf, 0);
1594 if (3 == spc)
1595 bad_twosharp:
1596 tcc_error("'##' cannot appear at either end of macro");
1597 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1600 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1602 const unsigned char *s;
1603 unsigned int h;
1604 CachedInclude *e;
1605 int i;
1607 h = TOK_HASH_INIT;
1608 s = (unsigned char *) filename;
1609 while (*s) {
1610 #ifdef _WIN32
1611 h = TOK_HASH_FUNC(h, toup(*s));
1612 #else
1613 h = TOK_HASH_FUNC(h, *s);
1614 #endif
1615 s++;
1617 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1619 i = s1->cached_includes_hash[h];
1620 for(;;) {
1621 if (i == 0)
1622 break;
1623 e = s1->cached_includes[i - 1];
1624 if (0 == PATHCMP(e->filename, filename))
1625 return e;
1626 i = e->hash_next;
1628 if (!add)
1629 return NULL;
1631 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1632 strcpy(e->filename, filename);
1633 e->ifndef_macro = e->once = 0;
1634 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1635 /* add in hash table */
1636 e->hash_next = s1->cached_includes_hash[h];
1637 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1638 #ifdef INC_DEBUG
1639 printf("adding cached '%s'\n", filename);
1640 #endif
1641 return e;
1644 static void pragma_parse(TCCState *s1)
1646 next_nomacro();
1647 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1648 int t = tok, v;
1649 Sym *s;
1651 if (next(), tok != '(')
1652 goto pragma_err;
1653 if (next(), tok != TOK_STR)
1654 goto pragma_err;
1655 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1656 if (next(), tok != ')')
1657 goto pragma_err;
1658 if (t == TOK_push_macro) {
1659 while (NULL == (s = define_find(v)))
1660 define_push(v, 0, NULL, NULL);
1661 s->type.ref = s; /* set push boundary */
1662 } else {
1663 for (s = define_stack; s; s = s->prev)
1664 if (s->v == v && s->type.ref == s) {
1665 s->type.ref = NULL;
1666 break;
1669 if (s)
1670 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1671 else
1672 tcc_warning("unbalanced #pragma pop_macro");
1673 pp_debug_tok = t, pp_debug_symv = v;
1675 } else if (tok == TOK_once) {
1676 search_cached_include(s1, file->filename, 1)->once = pp_once;
1678 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1679 /* tcc -E: keep pragmas below unchanged */
1680 unget_tok(' ');
1681 unget_tok(TOK_PRAGMA);
1682 unget_tok('#');
1683 unget_tok(TOK_LINEFEED);
1685 } else if (tok == TOK_pack) {
1686 /* This may be:
1687 #pragma pack(1) // set
1688 #pragma pack() // reset to default
1689 #pragma pack(push,1) // push & set
1690 #pragma pack(pop) // restore previous */
1691 next();
1692 skip('(');
1693 if (tok == TOK_ASM_pop) {
1694 next();
1695 if (s1->pack_stack_ptr <= s1->pack_stack) {
1696 stk_error:
1697 tcc_error("out of pack stack");
1699 s1->pack_stack_ptr--;
1700 } else {
1701 int val = 0;
1702 if (tok != ')') {
1703 if (tok == TOK_ASM_push) {
1704 next();
1705 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1706 goto stk_error;
1707 s1->pack_stack_ptr++;
1708 skip(',');
1710 if (tok != TOK_CINT)
1711 goto pragma_err;
1712 val = tokc.i;
1713 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1714 goto pragma_err;
1715 next();
1717 *s1->pack_stack_ptr = val;
1719 if (tok != ')')
1720 goto pragma_err;
1722 } else if (tok == TOK_comment) {
1723 char *p; int t;
1724 next();
1725 skip('(');
1726 t = tok;
1727 next();
1728 skip(',');
1729 if (tok != TOK_STR)
1730 goto pragma_err;
1731 p = tcc_strdup((char *)tokc.str.data);
1732 next();
1733 if (tok != ')')
1734 goto pragma_err;
1735 if (t == TOK_lib) {
1736 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1737 } else {
1738 if (t == TOK_option)
1739 tcc_set_options(s1, p);
1740 tcc_free(p);
1743 } else if (s1->warn_unsupported) {
1744 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1746 return;
1748 pragma_err:
1749 tcc_error("malformed #pragma directive");
1750 return;
1753 /* is_bof is true if first non space token at beginning of file */
1754 ST_FUNC void preprocess(int is_bof)
1756 TCCState *s1 = tcc_state;
1757 int i, c, n, saved_parse_flags;
1758 char buf[1024], *q;
1759 Sym *s;
1761 saved_parse_flags = parse_flags;
1762 parse_flags = PARSE_FLAG_PREPROCESS
1763 | PARSE_FLAG_TOK_NUM
1764 | PARSE_FLAG_TOK_STR
1765 | PARSE_FLAG_LINEFEED
1766 | (parse_flags & PARSE_FLAG_ASM_FILE)
1769 next_nomacro();
1770 redo:
1771 switch(tok) {
1772 case TOK_DEFINE:
1773 pp_debug_tok = tok;
1774 next_nomacro();
1775 pp_debug_symv = tok;
1776 parse_define();
1777 break;
1778 case TOK_UNDEF:
1779 pp_debug_tok = tok;
1780 next_nomacro();
1781 pp_debug_symv = tok;
1782 s = define_find(tok);
1783 /* undefine symbol by putting an invalid name */
1784 if (s)
1785 define_undef(s);
1786 break;
1787 case TOK_INCLUDE:
1788 case TOK_INCLUDE_NEXT:
1789 ch = file->buf_ptr[0];
1790 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1791 skip_spaces();
1792 if (ch == '<') {
1793 c = '>';
1794 goto read_name;
1795 } else if (ch == '\"') {
1796 c = ch;
1797 read_name:
1798 inp();
1799 q = buf;
1800 while (ch != c && ch != '\n' && ch != CH_EOF) {
1801 if ((q - buf) < sizeof(buf) - 1)
1802 *q++ = ch;
1803 if (ch == '\\') {
1804 if (handle_stray_noerror() == 0)
1805 --q;
1806 } else
1807 inp();
1809 *q = '\0';
1810 minp();
1811 #if 0
1812 /* eat all spaces and comments after include */
1813 /* XXX: slightly incorrect */
1814 while (ch1 != '\n' && ch1 != CH_EOF)
1815 inp();
1816 #endif
1817 } else {
1818 int len;
1819 /* computed #include : concatenate everything up to linefeed,
1820 the result must be one of the two accepted forms.
1821 Don't convert pp-tokens to tokens here. */
1822 parse_flags = (PARSE_FLAG_PREPROCESS
1823 | PARSE_FLAG_LINEFEED
1824 | (parse_flags & PARSE_FLAG_ASM_FILE));
1825 next();
1826 buf[0] = '\0';
1827 while (tok != TOK_LINEFEED) {
1828 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1829 next();
1831 len = strlen(buf);
1832 /* check syntax and remove '<>|""' */
1833 if ((len < 2 || ((buf[0] != '"' || buf[len-1] != '"') &&
1834 (buf[0] != '<' || buf[len-1] != '>'))))
1835 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1836 c = buf[len-1];
1837 memmove(buf, buf + 1, len - 2);
1838 buf[len - 2] = '\0';
1841 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1842 tcc_error("#include recursion too deep");
1843 /* push current file on stack */
1844 *s1->include_stack_ptr++ = file;
1845 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index + 1 : 0;
1846 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1847 for (; i < n; ++i) {
1848 char buf1[sizeof file->filename];
1849 CachedInclude *e;
1850 const char *path;
1852 if (i == 0) {
1853 /* check absolute include path */
1854 if (!IS_ABSPATH(buf))
1855 continue;
1856 buf1[0] = 0;
1858 } else if (i == 1) {
1859 /* search in file's dir if "header.h" */
1860 if (c != '\"')
1861 continue;
1862 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1863 path = file->true_filename;
1864 pstrncpy(buf1, path, tcc_basename(path) - path);
1866 } else {
1867 /* search in all the include paths */
1868 int j = i - 2, k = j - s1->nb_include_paths;
1869 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1870 pstrcpy(buf1, sizeof(buf1), path);
1871 pstrcat(buf1, sizeof(buf1), "/");
1874 pstrcat(buf1, sizeof(buf1), buf);
1875 e = search_cached_include(s1, buf1, 0);
1876 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1877 /* no need to parse the include because the 'ifndef macro'
1878 is defined (or had #pragma once) */
1879 #ifdef INC_DEBUG
1880 printf("%s: skipping cached %s\n", file->filename, buf1);
1881 #endif
1882 goto include_done;
1885 if (tcc_open(s1, buf1) < 0)
1886 continue;
1888 file->include_next_index = i;
1889 #ifdef INC_DEBUG
1890 printf("%s: including %s\n", file->prev->filename, file->filename);
1891 #endif
1892 /* update target deps */
1893 if (s1->gen_deps) {
1894 BufferedFile *bf = file;
1895 while (i == 1 && (bf = bf->prev))
1896 i = bf->include_next_index;
1897 /* skip system include files */
1898 if (n - i > s1->nb_sysinclude_paths)
1899 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1900 tcc_strdup(buf1));
1902 /* add include file debug info */
1903 tcc_debug_bincl(tcc_state);
1904 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1905 ch = file->buf_ptr[0];
1906 goto the_end;
1908 tcc_error("include file '%s' not found", buf);
1909 include_done:
1910 --s1->include_stack_ptr;
1911 break;
1912 case TOK_IFNDEF:
1913 c = 1;
1914 goto do_ifdef;
1915 case TOK_IF:
1916 c = expr_preprocess();
1917 goto do_if;
1918 case TOK_IFDEF:
1919 c = 0;
1920 do_ifdef:
1921 next_nomacro();
1922 if (tok < TOK_IDENT)
1923 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1924 if (is_bof) {
1925 if (c) {
1926 #ifdef INC_DEBUG
1927 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1928 #endif
1929 file->ifndef_macro = tok;
1932 c = (define_find(tok) != 0) ^ c;
1933 do_if:
1934 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1935 tcc_error("memory full (ifdef)");
1936 *s1->ifdef_stack_ptr++ = c;
1937 goto test_skip;
1938 case TOK_ELSE:
1939 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1940 tcc_error("#else without matching #if");
1941 if (s1->ifdef_stack_ptr[-1] & 2)
1942 tcc_error("#else after #else");
1943 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1944 goto test_else;
1945 case TOK_ELIF:
1946 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1947 tcc_error("#elif without matching #if");
1948 c = s1->ifdef_stack_ptr[-1];
1949 if (c > 1)
1950 tcc_error("#elif after #else");
1951 /* last #if/#elif expression was true: we skip */
1952 if (c == 1) {
1953 c = 0;
1954 } else {
1955 c = expr_preprocess();
1956 s1->ifdef_stack_ptr[-1] = c;
1958 test_else:
1959 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1960 file->ifndef_macro = 0;
1961 test_skip:
1962 if (!(c & 1)) {
1963 preprocess_skip();
1964 is_bof = 0;
1965 goto redo;
1967 break;
1968 case TOK_ENDIF:
1969 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1970 tcc_error("#endif without matching #if");
1971 s1->ifdef_stack_ptr--;
1972 /* '#ifndef macro' was at the start of file. Now we check if
1973 an '#endif' is exactly at the end of file */
1974 if (file->ifndef_macro &&
1975 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1976 file->ifndef_macro_saved = file->ifndef_macro;
1977 /* need to set to zero to avoid false matches if another
1978 #ifndef at middle of file */
1979 file->ifndef_macro = 0;
1980 while (tok != TOK_LINEFEED)
1981 next_nomacro();
1982 tok_flags |= TOK_FLAG_ENDIF;
1983 goto the_end;
1985 break;
1986 case TOK_PPNUM:
1987 n = strtoul((char*)tokc.str.data, &q, 10);
1988 goto _line_num;
1989 case TOK_LINE:
1990 next();
1991 if (tok != TOK_CINT)
1992 _line_err:
1993 tcc_error("wrong #line format");
1994 n = tokc.i;
1995 _line_num:
1996 next();
1997 if (tok != TOK_LINEFEED) {
1998 if (tok == TOK_STR) {
1999 if (file->true_filename == file->filename)
2000 file->true_filename = tcc_strdup(file->filename);
2001 /* prepend directory from real file */
2002 pstrcpy(buf, sizeof buf, file->true_filename);
2003 *tcc_basename(buf) = 0;
2004 pstrcat(buf, sizeof buf, (char *)tokc.str.data);
2005 tcc_debug_putfile(s1, buf);
2006 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
2007 break;
2008 else
2009 goto _line_err;
2010 --n;
2012 if (file->fd > 0)
2013 total_lines += file->line_num - n;
2014 file->line_num = n;
2015 break;
2016 case TOK_ERROR:
2017 case TOK_WARNING:
2018 c = tok;
2019 ch = file->buf_ptr[0];
2020 skip_spaces();
2021 q = buf;
2022 while (ch != '\n' && ch != CH_EOF) {
2023 if ((q - buf) < sizeof(buf) - 1)
2024 *q++ = ch;
2025 if (ch == '\\') {
2026 if (handle_stray_noerror() == 0)
2027 --q;
2028 } else
2029 inp();
2031 *q = '\0';
2032 if (c == TOK_ERROR)
2033 tcc_error("#error %s", buf);
2034 else
2035 tcc_warning("#warning %s", buf);
2036 break;
2037 case TOK_PRAGMA:
2038 pragma_parse(s1);
2039 break;
2040 case TOK_LINEFEED:
2041 goto the_end;
2042 default:
2043 /* ignore gas line comment in an 'S' file. */
2044 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
2045 goto ignore;
2046 if (tok == '!' && is_bof)
2047 /* '!' is ignored at beginning to allow C scripts. */
2048 goto ignore;
2049 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
2050 ignore:
2051 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
2052 goto the_end;
2054 /* ignore other preprocess commands or #! for C scripts */
2055 while (tok != TOK_LINEFEED)
2056 next_nomacro();
2057 the_end:
2058 parse_flags = saved_parse_flags;
2061 /* evaluate escape codes in a string. */
2062 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
2064 int c, n;
2065 const uint8_t *p;
2067 p = buf;
2068 for(;;) {
2069 c = *p;
2070 if (c == '\0')
2071 break;
2072 if (c == '\\') {
2073 p++;
2074 /* escape */
2075 c = *p;
2076 switch(c) {
2077 case '0': case '1': case '2': case '3':
2078 case '4': case '5': case '6': case '7':
2079 /* at most three octal digits */
2080 n = c - '0';
2081 p++;
2082 c = *p;
2083 if (isoct(c)) {
2084 n = n * 8 + c - '0';
2085 p++;
2086 c = *p;
2087 if (isoct(c)) {
2088 n = n * 8 + c - '0';
2089 p++;
2092 c = n;
2093 goto add_char_nonext;
2094 case 'x':
2095 case 'u':
2096 case 'U':
2097 p++;
2098 n = 0;
2099 for(;;) {
2100 c = *p;
2101 if (c >= 'a' && c <= 'f')
2102 c = c - 'a' + 10;
2103 else if (c >= 'A' && c <= 'F')
2104 c = c - 'A' + 10;
2105 else if (isnum(c))
2106 c = c - '0';
2107 else
2108 break;
2109 n = n * 16 + c;
2110 p++;
2112 c = n;
2113 goto add_char_nonext;
2114 case 'a':
2115 c = '\a';
2116 break;
2117 case 'b':
2118 c = '\b';
2119 break;
2120 case 'f':
2121 c = '\f';
2122 break;
2123 case 'n':
2124 c = '\n';
2125 break;
2126 case 'r':
2127 c = '\r';
2128 break;
2129 case 't':
2130 c = '\t';
2131 break;
2132 case 'v':
2133 c = '\v';
2134 break;
2135 case 'e':
2136 if (!gnu_ext)
2137 goto invalid_escape;
2138 c = 27;
2139 break;
2140 case '\'':
2141 case '\"':
2142 case '\\':
2143 case '?':
2144 break;
2145 default:
2146 invalid_escape:
2147 if (c >= '!' && c <= '~')
2148 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2149 else
2150 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2151 break;
2153 } else if (is_long && c >= 0x80) {
2154 /* assume we are processing UTF-8 sequence */
2155 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2157 int cont; /* count of continuation bytes */
2158 int skip; /* how many bytes should skip when error occurred */
2159 int i;
2161 /* decode leading byte */
2162 if (c < 0xC2) {
2163 skip = 1; goto invalid_utf8_sequence;
2164 } else if (c <= 0xDF) {
2165 cont = 1; n = c & 0x1f;
2166 } else if (c <= 0xEF) {
2167 cont = 2; n = c & 0xf;
2168 } else if (c <= 0xF4) {
2169 cont = 3; n = c & 0x7;
2170 } else {
2171 skip = 1; goto invalid_utf8_sequence;
2174 /* decode continuation bytes */
2175 for (i = 1; i <= cont; i++) {
2176 int l = 0x80, h = 0xBF;
2178 /* adjust limit for second byte */
2179 if (i == 1) {
2180 switch (c) {
2181 case 0xE0: l = 0xA0; break;
2182 case 0xED: h = 0x9F; break;
2183 case 0xF0: l = 0x90; break;
2184 case 0xF4: h = 0x8F; break;
2188 if (p[i] < l || p[i] > h) {
2189 skip = i; goto invalid_utf8_sequence;
2192 n = (n << 6) | (p[i] & 0x3f);
2195 /* advance pointer */
2196 p += 1 + cont;
2197 c = n;
2198 goto add_char_nonext;
2200 /* error handling */
2201 invalid_utf8_sequence:
2202 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2203 c = 0xFFFD;
2204 p += skip;
2205 goto add_char_nonext;
2208 p++;
2209 add_char_nonext:
2210 if (!is_long)
2211 cstr_ccat(outstr, c);
2212 else {
2213 #ifdef TCC_TARGET_PE
2214 /* store as UTF-16 */
2215 if (c < 0x10000) {
2216 cstr_wccat(outstr, c);
2217 } else {
2218 c -= 0x10000;
2219 cstr_wccat(outstr, (c >> 10) + 0xD800);
2220 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2222 #else
2223 cstr_wccat(outstr, c);
2224 #endif
2227 /* add a trailing '\0' */
2228 if (!is_long)
2229 cstr_ccat(outstr, '\0');
2230 else
2231 cstr_wccat(outstr, '\0');
2234 static void parse_string(const char *s, int len)
2236 uint8_t buf[1000], *p = buf;
2237 int is_long, sep;
2239 if ((is_long = *s == 'L'))
2240 ++s, --len;
2241 sep = *s++;
2242 len -= 2;
2243 if (len >= sizeof buf)
2244 p = tcc_malloc(len + 1);
2245 memcpy(p, s, len);
2246 p[len] = 0;
2248 cstr_reset(&tokcstr);
2249 parse_escape_string(&tokcstr, p, is_long);
2250 if (p != buf)
2251 tcc_free(p);
2253 if (sep == '\'') {
2254 int char_size, i, n, c;
2255 /* XXX: make it portable */
2256 if (!is_long)
2257 tok = TOK_CCHAR, char_size = 1;
2258 else
2259 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2260 n = tokcstr.size / char_size - 1;
2261 if (n < 1)
2262 tcc_error("empty character constant");
2263 if (n > 1)
2264 tcc_warning("multi-character character constant");
2265 for (c = i = 0; i < n; ++i) {
2266 if (is_long)
2267 c = ((nwchar_t *)tokcstr.data)[i];
2268 else
2269 c = (c << 8) | ((char *)tokcstr.data)[i];
2271 tokc.i = c;
2272 } else {
2273 tokc.str.size = tokcstr.size;
2274 tokc.str.data = tokcstr.data;
2275 if (!is_long)
2276 tok = TOK_STR;
2277 else
2278 tok = TOK_LSTR;
2282 /* we use 64 bit numbers */
2283 #define BN_SIZE 2
2285 /* bn = (bn << shift) | or_val */
2286 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2288 int i;
2289 unsigned int v;
2290 for(i=0;i<BN_SIZE;i++) {
2291 v = bn[i];
2292 bn[i] = (v << shift) | or_val;
2293 or_val = v >> (32 - shift);
2297 static void bn_zero(unsigned int *bn)
2299 int i;
2300 for(i=0;i<BN_SIZE;i++) {
2301 bn[i] = 0;
2305 /* parse number in null terminated string 'p' and return it in the
2306 current token */
2307 static void parse_number(const char *p)
2309 int b, t, shift, frac_bits, s, exp_val, ch;
2310 char *q;
2311 unsigned int bn[BN_SIZE];
2312 double d;
2314 /* number */
2315 q = token_buf;
2316 ch = *p++;
2317 t = ch;
2318 ch = *p++;
2319 *q++ = t;
2320 b = 10;
2321 if (t == '.') {
2322 goto float_frac_parse;
2323 } else if (t == '0') {
2324 if (ch == 'x' || ch == 'X') {
2325 q--;
2326 ch = *p++;
2327 b = 16;
2328 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2329 q--;
2330 ch = *p++;
2331 b = 2;
2334 /* parse all digits. cannot check octal numbers at this stage
2335 because of floating point constants */
2336 while (1) {
2337 if (ch >= 'a' && ch <= 'f')
2338 t = ch - 'a' + 10;
2339 else if (ch >= 'A' && ch <= 'F')
2340 t = ch - 'A' + 10;
2341 else if (isnum(ch))
2342 t = ch - '0';
2343 else
2344 break;
2345 if (t >= b)
2346 break;
2347 if (q >= token_buf + STRING_MAX_SIZE) {
2348 num_too_long:
2349 tcc_error("number too long");
2351 *q++ = ch;
2352 ch = *p++;
2354 if (ch == '.' ||
2355 ((ch == 'e' || ch == 'E') && b == 10) ||
2356 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2357 if (b != 10) {
2358 /* NOTE: strtox should support that for hexa numbers, but
2359 non ISOC99 libcs do not support it, so we prefer to do
2360 it by hand */
2361 /* hexadecimal or binary floats */
2362 /* XXX: handle overflows */
2363 *q = '\0';
2364 if (b == 16)
2365 shift = 4;
2366 else
2367 shift = 1;
2368 bn_zero(bn);
2369 q = token_buf;
2370 while (1) {
2371 t = *q++;
2372 if (t == '\0') {
2373 break;
2374 } else if (t >= 'a') {
2375 t = t - 'a' + 10;
2376 } else if (t >= 'A') {
2377 t = t - 'A' + 10;
2378 } else {
2379 t = t - '0';
2381 bn_lshift(bn, shift, t);
2383 frac_bits = 0;
2384 if (ch == '.') {
2385 ch = *p++;
2386 while (1) {
2387 t = ch;
2388 if (t >= 'a' && t <= 'f') {
2389 t = t - 'a' + 10;
2390 } else if (t >= 'A' && t <= 'F') {
2391 t = t - 'A' + 10;
2392 } else if (t >= '0' && t <= '9') {
2393 t = t - '0';
2394 } else {
2395 break;
2397 if (t >= b)
2398 tcc_error("invalid digit");
2399 bn_lshift(bn, shift, t);
2400 frac_bits += shift;
2401 ch = *p++;
2404 if (ch != 'p' && ch != 'P')
2405 expect("exponent");
2406 ch = *p++;
2407 s = 1;
2408 exp_val = 0;
2409 if (ch == '+') {
2410 ch = *p++;
2411 } else if (ch == '-') {
2412 s = -1;
2413 ch = *p++;
2415 if (ch < '0' || ch > '9')
2416 expect("exponent digits");
2417 while (ch >= '0' && ch <= '9') {
2418 exp_val = exp_val * 10 + ch - '0';
2419 ch = *p++;
2421 exp_val = exp_val * s;
2423 /* now we can generate the number */
2424 /* XXX: should patch directly float number */
2425 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2426 d = ldexp(d, exp_val - frac_bits);
2427 t = toup(ch);
2428 if (t == 'F') {
2429 ch = *p++;
2430 tok = TOK_CFLOAT;
2431 /* float : should handle overflow */
2432 tokc.f = (float)d;
2433 } else if (t == 'L') {
2434 ch = *p++;
2435 #ifdef TCC_TARGET_PE
2436 tok = TOK_CDOUBLE;
2437 tokc.d = d;
2438 #else
2439 tok = TOK_CLDOUBLE;
2440 /* XXX: not large enough */
2441 tokc.ld = (long double)d;
2442 #endif
2443 } else {
2444 tok = TOK_CDOUBLE;
2445 tokc.d = d;
2447 } else {
2448 /* decimal floats */
2449 if (ch == '.') {
2450 if (q >= token_buf + STRING_MAX_SIZE)
2451 goto num_too_long;
2452 *q++ = ch;
2453 ch = *p++;
2454 float_frac_parse:
2455 while (ch >= '0' && ch <= '9') {
2456 if (q >= token_buf + STRING_MAX_SIZE)
2457 goto num_too_long;
2458 *q++ = ch;
2459 ch = *p++;
2462 if (ch == 'e' || ch == 'E') {
2463 if (q >= token_buf + STRING_MAX_SIZE)
2464 goto num_too_long;
2465 *q++ = ch;
2466 ch = *p++;
2467 if (ch == '-' || ch == '+') {
2468 if (q >= token_buf + STRING_MAX_SIZE)
2469 goto num_too_long;
2470 *q++ = ch;
2471 ch = *p++;
2473 if (ch < '0' || ch > '9')
2474 expect("exponent digits");
2475 while (ch >= '0' && ch <= '9') {
2476 if (q >= token_buf + STRING_MAX_SIZE)
2477 goto num_too_long;
2478 *q++ = ch;
2479 ch = *p++;
2482 *q = '\0';
2483 t = toup(ch);
2484 errno = 0;
2485 if (t == 'F') {
2486 ch = *p++;
2487 tok = TOK_CFLOAT;
2488 tokc.f = strtof(token_buf, NULL);
2489 } else if (t == 'L') {
2490 ch = *p++;
2491 #ifdef TCC_TARGET_PE
2492 tok = TOK_CDOUBLE;
2493 tokc.d = strtod(token_buf, NULL);
2494 #else
2495 tok = TOK_CLDOUBLE;
2496 tokc.ld = strtold(token_buf, NULL);
2497 #endif
2498 } else {
2499 tok = TOK_CDOUBLE;
2500 tokc.d = strtod(token_buf, NULL);
2503 } else {
2504 unsigned long long n, n1;
2505 int lcount, ucount, ov = 0;
2506 const char *p1;
2508 /* integer number */
2509 *q = '\0';
2510 q = token_buf;
2511 if (b == 10 && *q == '0') {
2512 b = 8;
2513 q++;
2515 n = 0;
2516 while(1) {
2517 t = *q++;
2518 /* no need for checks except for base 10 / 8 errors */
2519 if (t == '\0')
2520 break;
2521 else if (t >= 'a')
2522 t = t - 'a' + 10;
2523 else if (t >= 'A')
2524 t = t - 'A' + 10;
2525 else
2526 t = t - '0';
2527 if (t >= b)
2528 tcc_error("invalid digit");
2529 n1 = n;
2530 n = n * b + t;
2531 /* detect overflow */
2532 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2533 ov = 1;
2536 /* Determine the characteristics (unsigned and/or 64bit) the type of
2537 the constant must have according to the constant suffix(es) */
2538 lcount = ucount = 0;
2539 p1 = p;
2540 for(;;) {
2541 t = toup(ch);
2542 if (t == 'L') {
2543 if (lcount >= 2)
2544 tcc_error("three 'l's in integer constant");
2545 if (lcount && *(p - 1) != ch)
2546 tcc_error("incorrect integer suffix: %s", p1);
2547 lcount++;
2548 ch = *p++;
2549 } else if (t == 'U') {
2550 if (ucount >= 1)
2551 tcc_error("two 'u's in integer constant");
2552 ucount++;
2553 ch = *p++;
2554 } else {
2555 break;
2559 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2560 if (ucount == 0 && b == 10) {
2561 if (lcount <= (LONG_SIZE == 4)) {
2562 if (n >= 0x80000000U)
2563 lcount = (LONG_SIZE == 4) + 1;
2565 if (n >= 0x8000000000000000ULL)
2566 ov = 1, ucount = 1;
2567 } else {
2568 if (lcount <= (LONG_SIZE == 4)) {
2569 if (n >= 0x100000000ULL)
2570 lcount = (LONG_SIZE == 4) + 1;
2571 else if (n >= 0x80000000U)
2572 ucount = 1;
2574 if (n >= 0x8000000000000000ULL)
2575 ucount = 1;
2578 if (ov)
2579 tcc_warning("integer constant overflow");
2581 tok = TOK_CINT;
2582 if (lcount) {
2583 tok = TOK_CLONG;
2584 if (lcount == 2)
2585 tok = TOK_CLLONG;
2587 if (ucount)
2588 ++tok; /* TOK_CU... */
2589 tokc.i = n;
2591 if (ch)
2592 tcc_error("invalid number");
2596 #define PARSE2(c1, tok1, c2, tok2) \
2597 case c1: \
2598 PEEKC(c, p); \
2599 if (c == c2) { \
2600 p++; \
2601 tok = tok2; \
2602 } else { \
2603 tok = tok1; \
2605 break;
2607 /* return next token without macro substitution */
2608 static inline void next_nomacro1(void)
2610 int t, c, is_long, len;
2611 TokenSym *ts;
2612 uint8_t *p, *p1;
2613 unsigned int h;
2615 p = file->buf_ptr;
2616 redo_no_start:
2617 c = *p;
2618 switch(c) {
2619 case ' ':
2620 case '\t':
2621 tok = c;
2622 p++;
2623 maybe_space:
2624 if (parse_flags & PARSE_FLAG_SPACES)
2625 goto keep_tok_flags;
2626 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2627 ++p;
2628 goto redo_no_start;
2629 case '\f':
2630 case '\v':
2631 case '\r':
2632 p++;
2633 goto redo_no_start;
2634 case '\\':
2635 /* first look if it is in fact an end of buffer */
2636 c = handle_stray1(p);
2637 p = file->buf_ptr;
2638 if (c == '\\')
2639 goto parse_simple;
2640 if (c != CH_EOF)
2641 goto redo_no_start;
2643 TCCState *s1 = tcc_state;
2644 if ((parse_flags & PARSE_FLAG_LINEFEED)
2645 && !(tok_flags & TOK_FLAG_EOF)) {
2646 tok_flags |= TOK_FLAG_EOF;
2647 tok = TOK_LINEFEED;
2648 goto keep_tok_flags;
2649 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2650 tok = TOK_EOF;
2651 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2652 tcc_error("missing #endif");
2653 } else if (s1->include_stack_ptr == s1->include_stack) {
2654 /* no include left : end of file. */
2655 tok = TOK_EOF;
2656 } else {
2657 tok_flags &= ~TOK_FLAG_EOF;
2658 /* pop include file */
2660 /* test if previous '#endif' was after a #ifdef at
2661 start of file */
2662 if (tok_flags & TOK_FLAG_ENDIF) {
2663 #ifdef INC_DEBUG
2664 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2665 #endif
2666 search_cached_include(s1, file->filename, 1)
2667 ->ifndef_macro = file->ifndef_macro_saved;
2668 tok_flags &= ~TOK_FLAG_ENDIF;
2671 /* add end of include file debug info */
2672 tcc_debug_eincl(tcc_state);
2673 /* pop include stack */
2674 tcc_close();
2675 s1->include_stack_ptr--;
2676 p = file->buf_ptr;
2677 if (p == file->buffer)
2678 tok_flags = TOK_FLAG_BOF|TOK_FLAG_BOL;
2679 goto redo_no_start;
2682 break;
2684 case '\n':
2685 file->line_num++;
2686 tok_flags |= TOK_FLAG_BOL;
2687 p++;
2688 maybe_newline:
2689 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2690 goto redo_no_start;
2691 tok = TOK_LINEFEED;
2692 goto keep_tok_flags;
2694 case '#':
2695 /* XXX: simplify */
2696 PEEKC(c, p);
2697 if ((tok_flags & TOK_FLAG_BOL) &&
2698 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2699 file->buf_ptr = p;
2700 preprocess(tok_flags & TOK_FLAG_BOF);
2701 p = file->buf_ptr;
2702 goto maybe_newline;
2703 } else {
2704 if (c == '#') {
2705 p++;
2706 tok = TOK_TWOSHARPS;
2707 } else {
2708 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2709 p = parse_line_comment(p - 1);
2710 goto redo_no_start;
2711 } else {
2712 tok = '#';
2716 break;
2718 /* dollar is allowed to start identifiers when not parsing asm */
2719 case '$':
2720 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2721 || (parse_flags & PARSE_FLAG_ASM_FILE))
2722 goto parse_simple;
2724 case 'a': case 'b': case 'c': case 'd':
2725 case 'e': case 'f': case 'g': case 'h':
2726 case 'i': case 'j': case 'k': case 'l':
2727 case 'm': case 'n': case 'o': case 'p':
2728 case 'q': case 'r': case 's': case 't':
2729 case 'u': case 'v': case 'w': case 'x':
2730 case 'y': case 'z':
2731 case 'A': case 'B': case 'C': case 'D':
2732 case 'E': case 'F': case 'G': case 'H':
2733 case 'I': case 'J': case 'K':
2734 case 'M': case 'N': case 'O': case 'P':
2735 case 'Q': case 'R': case 'S': case 'T':
2736 case 'U': case 'V': case 'W': case 'X':
2737 case 'Y': case 'Z':
2738 case '_':
2739 parse_ident_fast:
2740 p1 = p;
2741 h = TOK_HASH_INIT;
2742 h = TOK_HASH_FUNC(h, c);
2743 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2744 h = TOK_HASH_FUNC(h, c);
2745 len = p - p1;
2746 if (c != '\\') {
2747 TokenSym **pts;
2749 /* fast case : no stray found, so we have the full token
2750 and we have already hashed it */
2751 h &= (TOK_HASH_SIZE - 1);
2752 pts = &hash_ident[h];
2753 for(;;) {
2754 ts = *pts;
2755 if (!ts)
2756 break;
2757 if (ts->len == len && !memcmp(ts->str, p1, len))
2758 goto token_found;
2759 pts = &(ts->hash_next);
2761 ts = tok_alloc_new(pts, (char *) p1, len);
2762 token_found: ;
2763 } else {
2764 /* slower case */
2765 cstr_reset(&tokcstr);
2766 cstr_cat(&tokcstr, (char *) p1, len);
2767 p--;
2768 PEEKC(c, p);
2769 parse_ident_slow:
2770 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2772 cstr_ccat(&tokcstr, c);
2773 PEEKC(c, p);
2775 ts = tok_alloc(tokcstr.data, tokcstr.size);
2777 tok = ts->tok;
2778 break;
2779 case 'L':
2780 t = p[1];
2781 if (t != '\\' && t != '\'' && t != '\"') {
2782 /* fast case */
2783 goto parse_ident_fast;
2784 } else {
2785 PEEKC(c, p);
2786 if (c == '\'' || c == '\"') {
2787 is_long = 1;
2788 goto str_const;
2789 } else {
2790 cstr_reset(&tokcstr);
2791 cstr_ccat(&tokcstr, 'L');
2792 goto parse_ident_slow;
2795 break;
2797 case '0': case '1': case '2': case '3':
2798 case '4': case '5': case '6': case '7':
2799 case '8': case '9':
2800 t = c;
2801 PEEKC(c, p);
2802 /* after the first digit, accept digits, alpha, '.' or sign if
2803 prefixed by 'eEpP' */
2804 parse_num:
2805 cstr_reset(&tokcstr);
2806 for(;;) {
2807 cstr_ccat(&tokcstr, t);
2808 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2809 || c == '.'
2810 || ((c == '+' || c == '-')
2811 && (((t == 'e' || t == 'E')
2812 && !(parse_flags & PARSE_FLAG_ASM_FILE
2813 /* 0xe+1 is 3 tokens in asm */
2814 && ((char*)tokcstr.data)[0] == '0'
2815 && toup(((char*)tokcstr.data)[1]) == 'X'))
2816 || t == 'p' || t == 'P'))))
2817 break;
2818 t = c;
2819 PEEKC(c, p);
2821 /* We add a trailing '\0' to ease parsing */
2822 cstr_ccat(&tokcstr, '\0');
2823 tokc.str.size = tokcstr.size;
2824 tokc.str.data = tokcstr.data;
2825 tok = TOK_PPNUM;
2826 break;
2828 case '.':
2829 /* special dot handling because it can also start a number */
2830 PEEKC(c, p);
2831 if (isnum(c)) {
2832 t = '.';
2833 goto parse_num;
2834 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2835 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2836 *--p = c = '.';
2837 goto parse_ident_fast;
2838 } else if (c == '.') {
2839 PEEKC(c, p);
2840 if (c == '.') {
2841 p++;
2842 tok = TOK_DOTS;
2843 } else {
2844 *--p = '.'; /* may underflow into file->unget[] */
2845 tok = '.';
2847 } else {
2848 tok = '.';
2850 break;
2851 case '\'':
2852 case '\"':
2853 is_long = 0;
2854 str_const:
2855 cstr_reset(&tokcstr);
2856 if (is_long)
2857 cstr_ccat(&tokcstr, 'L');
2858 cstr_ccat(&tokcstr, c);
2859 p = parse_pp_string(p, c, &tokcstr);
2860 cstr_ccat(&tokcstr, c);
2861 cstr_ccat(&tokcstr, '\0');
2862 tokc.str.size = tokcstr.size;
2863 tokc.str.data = tokcstr.data;
2864 tok = TOK_PPSTR;
2865 break;
2867 case '<':
2868 PEEKC(c, p);
2869 if (c == '=') {
2870 p++;
2871 tok = TOK_LE;
2872 } else if (c == '<') {
2873 PEEKC(c, p);
2874 if (c == '=') {
2875 p++;
2876 tok = TOK_A_SHL;
2877 } else {
2878 tok = TOK_SHL;
2880 } else {
2881 tok = TOK_LT;
2883 break;
2884 case '>':
2885 PEEKC(c, p);
2886 if (c == '=') {
2887 p++;
2888 tok = TOK_GE;
2889 } else if (c == '>') {
2890 PEEKC(c, p);
2891 if (c == '=') {
2892 p++;
2893 tok = TOK_A_SAR;
2894 } else {
2895 tok = TOK_SAR;
2897 } else {
2898 tok = TOK_GT;
2900 break;
2902 case '&':
2903 PEEKC(c, p);
2904 if (c == '&') {
2905 p++;
2906 tok = TOK_LAND;
2907 } else if (c == '=') {
2908 p++;
2909 tok = TOK_A_AND;
2910 } else {
2911 tok = '&';
2913 break;
2915 case '|':
2916 PEEKC(c, p);
2917 if (c == '|') {
2918 p++;
2919 tok = TOK_LOR;
2920 } else if (c == '=') {
2921 p++;
2922 tok = TOK_A_OR;
2923 } else {
2924 tok = '|';
2926 break;
2928 case '+':
2929 PEEKC(c, p);
2930 if (c == '+') {
2931 p++;
2932 tok = TOK_INC;
2933 } else if (c == '=') {
2934 p++;
2935 tok = TOK_A_ADD;
2936 } else {
2937 tok = '+';
2939 break;
2941 case '-':
2942 PEEKC(c, p);
2943 if (c == '-') {
2944 p++;
2945 tok = TOK_DEC;
2946 } else if (c == '=') {
2947 p++;
2948 tok = TOK_A_SUB;
2949 } else if (c == '>') {
2950 p++;
2951 tok = TOK_ARROW;
2952 } else {
2953 tok = '-';
2955 break;
2957 PARSE2('!', '!', '=', TOK_NE)
2958 PARSE2('=', '=', '=', TOK_EQ)
2959 PARSE2('*', '*', '=', TOK_A_MUL)
2960 PARSE2('%', '%', '=', TOK_A_MOD)
2961 PARSE2('^', '^', '=', TOK_A_XOR)
2963 /* comments or operator */
2964 case '/':
2965 PEEKC(c, p);
2966 if (c == '*') {
2967 p = parse_comment(p);
2968 /* comments replaced by a blank */
2969 tok = ' ';
2970 goto maybe_space;
2971 } else if (c == '/') {
2972 p = parse_line_comment(p);
2973 tok = ' ';
2974 goto maybe_space;
2975 } else if (c == '=') {
2976 p++;
2977 tok = TOK_A_DIV;
2978 } else {
2979 tok = '/';
2981 break;
2983 /* simple tokens */
2984 case '(':
2985 case ')':
2986 case '[':
2987 case ']':
2988 case '{':
2989 case '}':
2990 case ',':
2991 case ';':
2992 case ':':
2993 case '?':
2994 case '~':
2995 case '@': /* only used in assembler */
2996 parse_simple:
2997 tok = c;
2998 p++;
2999 break;
3000 default:
3001 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
3002 goto parse_ident_fast;
3003 if (parse_flags & PARSE_FLAG_ASM_FILE)
3004 goto parse_simple;
3005 tcc_error("unrecognized character \\x%02x", c);
3006 break;
3008 tok_flags = 0;
3009 keep_tok_flags:
3010 file->buf_ptr = p;
3011 #if defined(PARSE_DEBUG)
3012 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
3013 #endif
3016 static void macro_subst(
3017 TokenString *tok_str,
3018 Sym **nested_list,
3019 const int *macro_str
3022 /* substitute arguments in replacement lists in macro_str by the values in
3023 args (field d) and return allocated string */
3024 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
3026 int t, t0, t1, spc;
3027 const int *st;
3028 Sym *s;
3029 CValue cval;
3030 TokenString str;
3031 CString cstr;
3033 tok_str_new(&str);
3034 t0 = t1 = 0;
3035 while(1) {
3036 TOK_GET(&t, &macro_str, &cval);
3037 if (!t)
3038 break;
3039 if (t == '#') {
3040 /* stringize */
3041 TOK_GET(&t, &macro_str, &cval);
3042 if (!t)
3043 goto bad_stringy;
3044 s = sym_find2(args, t);
3045 if (s) {
3046 cstr_new(&cstr);
3047 cstr_ccat(&cstr, '\"');
3048 st = s->d;
3049 spc = 0;
3050 while (*st >= 0) {
3051 TOK_GET(&t, &st, &cval);
3052 if (t != TOK_PLCHLDR
3053 && t != TOK_NOSUBST
3054 && 0 == check_space(t, &spc)) {
3055 const char *s = get_tok_str(t, &cval);
3056 while (*s) {
3057 if (t == TOK_PPSTR && *s != '\'')
3058 add_char(&cstr, *s);
3059 else
3060 cstr_ccat(&cstr, *s);
3061 ++s;
3065 cstr.size -= spc;
3066 cstr_ccat(&cstr, '\"');
3067 cstr_ccat(&cstr, '\0');
3068 #ifdef PP_DEBUG
3069 printf("\nstringize: <%s>\n", (char *)cstr.data);
3070 #endif
3071 /* add string */
3072 cval.str.size = cstr.size;
3073 cval.str.data = cstr.data;
3074 tok_str_add2(&str, TOK_PPSTR, &cval);
3075 cstr_free(&cstr);
3076 } else {
3077 bad_stringy:
3078 expect("macro parameter after '#'");
3080 } else if (t >= TOK_IDENT) {
3081 s = sym_find2(args, t);
3082 if (s) {
3083 int l0 = str.len;
3084 st = s->d;
3085 /* if '##' is present before or after, no arg substitution */
3086 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
3087 /* special case for var arg macros : ## eats the ','
3088 if empty VA_ARGS variable. */
3089 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
3090 if (*st <= 0) {
3091 /* suppress ',' '##' */
3092 str.len -= 2;
3093 } else {
3094 /* suppress '##' and add variable */
3095 str.len--;
3096 goto add_var;
3099 } else {
3100 add_var:
3101 if (!s->next) {
3102 /* Expand arguments tokens and store them. In most
3103 cases we could also re-expand each argument if
3104 used multiple times, but not if the argument
3105 contains the __COUNTER__ macro. */
3106 TokenString str2;
3107 sym_push2(&s->next, s->v, s->type.t, 0);
3108 tok_str_new(&str2);
3109 macro_subst(&str2, nested_list, st);
3110 tok_str_add(&str2, 0);
3111 s->next->d = str2.str;
3113 st = s->next->d;
3115 for(;;) {
3116 int t2;
3117 TOK_GET(&t2, &st, &cval);
3118 if (t2 <= 0)
3119 break;
3120 tok_str_add2(&str, t2, &cval);
3122 if (str.len == l0) /* expanded to empty string */
3123 tok_str_add(&str, TOK_PLCHLDR);
3124 } else {
3125 tok_str_add(&str, t);
3127 } else {
3128 tok_str_add2(&str, t, &cval);
3130 t0 = t1, t1 = t;
3132 tok_str_add(&str, 0);
3133 return str.str;
3136 static char const ab_month_name[12][4] =
3138 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3139 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3142 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3144 CString cstr;
3145 int n, ret = 1;
3147 cstr_new(&cstr);
3148 if (t1 != TOK_PLCHLDR)
3149 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3150 n = cstr.size;
3151 if (t2 != TOK_PLCHLDR)
3152 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3153 cstr_ccat(&cstr, '\0');
3155 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3156 memcpy(file->buffer, cstr.data, cstr.size);
3157 tok_flags = 0;
3158 for (;;) {
3159 next_nomacro1();
3160 if (0 == *file->buf_ptr)
3161 break;
3162 if (is_space(tok))
3163 continue;
3164 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3165 " preprocessing token", n, (char *)cstr.data, (char*)cstr.data + n);
3166 ret = 0;
3167 break;
3169 tcc_close();
3170 //printf("paste <%s>\n", (char*)cstr.data);
3171 cstr_free(&cstr);
3172 return ret;
3175 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3176 return the resulting string (which must be freed). */
3177 static inline int *macro_twosharps(const int *ptr0)
3179 int t;
3180 CValue cval;
3181 TokenString macro_str1;
3182 int start_of_nosubsts = -1;
3183 const int *ptr;
3185 /* we search the first '##' */
3186 for (ptr = ptr0;;) {
3187 TOK_GET(&t, &ptr, &cval);
3188 if (t == TOK_PPJOIN)
3189 break;
3190 if (t == 0)
3191 return NULL;
3194 tok_str_new(&macro_str1);
3196 //tok_print(" $$$", ptr0);
3197 for (ptr = ptr0;;) {
3198 TOK_GET(&t, &ptr, &cval);
3199 if (t == 0)
3200 break;
3201 if (t == TOK_PPJOIN)
3202 continue;
3203 while (*ptr == TOK_PPJOIN) {
3204 int t1; CValue cv1;
3205 /* given 'a##b', remove nosubsts preceding 'a' */
3206 if (start_of_nosubsts >= 0)
3207 macro_str1.len = start_of_nosubsts;
3208 /* given 'a##b', remove nosubsts preceding 'b' */
3209 while ((t1 = *++ptr) == TOK_NOSUBST)
3211 if (t1 && t1 != TOK_PPJOIN) {
3212 TOK_GET(&t1, &ptr, &cv1);
3213 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3214 if (paste_tokens(t, &cval, t1, &cv1)) {
3215 t = tok, cval = tokc;
3216 } else {
3217 tok_str_add2(&macro_str1, t, &cval);
3218 t = t1, cval = cv1;
3223 if (t == TOK_NOSUBST) {
3224 if (start_of_nosubsts < 0)
3225 start_of_nosubsts = macro_str1.len;
3226 } else {
3227 start_of_nosubsts = -1;
3229 tok_str_add2(&macro_str1, t, &cval);
3231 tok_str_add(&macro_str1, 0);
3232 //tok_print(" ###", macro_str1.str);
3233 return macro_str1.str;
3236 /* peek or read [ws_str == NULL] next token from function macro call,
3237 walking up macro levels up to the file if necessary */
3238 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3240 int t;
3241 const int *p;
3242 Sym *sa;
3244 for (;;) {
3245 if (macro_ptr) {
3246 p = macro_ptr, t = *p;
3247 if (ws_str) {
3248 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3249 tok_str_add(ws_str, t), t = *++p;
3251 if (t == 0) {
3252 end_macro();
3253 /* also, end of scope for nested defined symbol */
3254 sa = *nested_list;
3255 while (sa && sa->v == 0)
3256 sa = sa->prev;
3257 if (sa)
3258 sa->v = 0;
3259 continue;
3261 } else {
3262 ch = handle_eob();
3263 if (ws_str) {
3264 while (is_space(ch) || ch == '\n' || ch == '/') {
3265 if (ch == '/') {
3266 int c;
3267 uint8_t *p = file->buf_ptr;
3268 PEEKC(c, p);
3269 if (c == '*') {
3270 p = parse_comment(p);
3271 file->buf_ptr = p - 1;
3272 } else if (c == '/') {
3273 p = parse_line_comment(p);
3274 file->buf_ptr = p - 1;
3275 } else
3276 break;
3277 ch = ' ';
3279 if (ch == '\n')
3280 file->line_num++;
3281 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3282 tok_str_add(ws_str, ch);
3283 cinp();
3286 t = ch;
3289 if (ws_str)
3290 return t;
3291 next_nomacro();
3292 return tok;
3296 /* do macro substitution of current token with macro 's' and add
3297 result to (tok_str,tok_len). 'nested_list' is the list of all
3298 macros we got inside to avoid recursing. Return non zero if no
3299 substitution needs to be done */
3300 static int macro_subst_tok(
3301 TokenString *tok_str,
3302 Sym **nested_list,
3303 Sym *s)
3305 Sym *args, *sa, *sa1;
3306 int parlevel, t, t1, spc;
3307 TokenString str;
3308 char *cstrval;
3309 CValue cval;
3310 CString cstr;
3311 char buf[32];
3313 /* if symbol is a macro, prepare substitution */
3314 /* special macros */
3315 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3316 t = tok == TOK___LINE__ ? file->line_num : pp_counter++;
3317 snprintf(buf, sizeof(buf), "%d", t);
3318 cstrval = buf;
3319 t1 = TOK_PPNUM;
3320 goto add_cstr1;
3321 } else if (tok == TOK___FILE__) {
3322 cstrval = file->filename;
3323 goto add_cstr;
3324 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3325 time_t ti;
3326 struct tm *tm;
3328 time(&ti);
3329 tm = localtime(&ti);
3330 if (tok == TOK___DATE__) {
3331 snprintf(buf, sizeof(buf), "%s %2d %d",
3332 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3333 } else {
3334 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3335 tm->tm_hour, tm->tm_min, tm->tm_sec);
3337 cstrval = buf;
3338 add_cstr:
3339 t1 = TOK_STR;
3340 add_cstr1:
3341 cstr_new(&cstr);
3342 cstr_cat(&cstr, cstrval, 0);
3343 cval.str.size = cstr.size;
3344 cval.str.data = cstr.data;
3345 tok_str_add2(tok_str, t1, &cval);
3346 cstr_free(&cstr);
3347 } else if (s->d) {
3348 int saved_parse_flags = parse_flags;
3349 int *joined_str = NULL;
3350 int *mstr = s->d;
3352 if (s->type.t == MACRO_FUNC) {
3353 /* whitespace between macro name and argument list */
3354 TokenString ws_str;
3355 tok_str_new(&ws_str);
3357 spc = 0;
3358 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3359 | PARSE_FLAG_ACCEPT_STRAYS;
3361 /* get next token from argument stream */
3362 t = next_argstream(nested_list, &ws_str);
3363 if (t != '(') {
3364 /* not a macro substitution after all, restore the
3365 * macro token plus all whitespace we've read.
3366 * whitespace is intentionally not merged to preserve
3367 * newlines. */
3368 parse_flags = saved_parse_flags;
3369 tok_str_add(tok_str, tok);
3370 if (parse_flags & PARSE_FLAG_SPACES) {
3371 int i;
3372 for (i = 0; i < ws_str.len; i++)
3373 tok_str_add(tok_str, ws_str.str[i]);
3375 tok_str_free_str(ws_str.str);
3376 return 0;
3377 } else {
3378 tok_str_free_str(ws_str.str);
3380 do {
3381 next_nomacro(); /* eat '(' */
3382 } while (tok == TOK_PLCHLDR || is_space(tok));
3384 /* argument macro */
3385 args = NULL;
3386 sa = s->next;
3387 /* NOTE: empty args are allowed, except if no args */
3388 for(;;) {
3389 do {
3390 next_argstream(nested_list, NULL);
3391 } while (is_space(tok) || TOK_LINEFEED == tok);
3392 empty_arg:
3393 /* handle '()' case */
3394 if (!args && !sa && tok == ')')
3395 break;
3396 if (!sa)
3397 tcc_error("macro '%s' used with too many args",
3398 get_tok_str(s->v, 0));
3399 tok_str_new(&str);
3400 parlevel = spc = 0;
3401 /* NOTE: non zero sa->t indicates VA_ARGS */
3402 while ((parlevel > 0 ||
3403 (tok != ')' &&
3404 (tok != ',' || sa->type.t)))) {
3405 if (tok == TOK_EOF || tok == 0)
3406 break;
3407 if (tok == '(')
3408 parlevel++;
3409 else if (tok == ')')
3410 parlevel--;
3411 if (tok == TOK_LINEFEED)
3412 tok = ' ';
3413 if (!check_space(tok, &spc))
3414 tok_str_add2(&str, tok, &tokc);
3415 next_argstream(nested_list, NULL);
3417 if (parlevel)
3418 expect(")");
3419 str.len -= spc;
3420 tok_str_add(&str, -1);
3421 tok_str_add(&str, 0);
3422 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3423 sa1->d = str.str;
3424 sa = sa->next;
3425 if (tok == ')') {
3426 /* special case for gcc var args: add an empty
3427 var arg argument if it is omitted */
3428 if (sa && sa->type.t && gnu_ext)
3429 goto empty_arg;
3430 break;
3432 if (tok != ',')
3433 expect(",");
3435 if (sa) {
3436 tcc_error("macro '%s' used with too few args",
3437 get_tok_str(s->v, 0));
3440 /* now subst each arg */
3441 mstr = macro_arg_subst(nested_list, mstr, args);
3442 /* free memory */
3443 sa = args;
3444 while (sa) {
3445 sa1 = sa->prev;
3446 tok_str_free_str(sa->d);
3447 if (sa->next) {
3448 tok_str_free_str(sa->next->d);
3449 sym_free(sa->next);
3451 sym_free(sa);
3452 sa = sa1;
3454 parse_flags = saved_parse_flags;
3457 sym_push2(nested_list, s->v, 0, 0);
3458 parse_flags = saved_parse_flags;
3459 joined_str = macro_twosharps(mstr);
3460 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3462 /* pop nested defined symbol */
3463 sa1 = *nested_list;
3464 *nested_list = sa1->prev;
3465 sym_free(sa1);
3466 if (joined_str)
3467 tok_str_free_str(joined_str);
3468 if (mstr != s->d)
3469 tok_str_free_str(mstr);
3471 return 0;
3474 /* do macro substitution of macro_str and add result to
3475 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3476 inside to avoid recursing. */
3477 static void macro_subst(
3478 TokenString *tok_str,
3479 Sym **nested_list,
3480 const int *macro_str
3483 Sym *s;
3484 int t, spc, nosubst;
3485 CValue cval;
3487 spc = nosubst = 0;
3489 while (1) {
3490 TOK_GET(&t, &macro_str, &cval);
3491 if (t <= 0)
3492 break;
3494 if (t >= TOK_IDENT && 0 == nosubst) {
3495 s = define_find(t);
3496 if (s == NULL)
3497 goto no_subst;
3499 /* if nested substitution, do nothing */
3500 if (sym_find2(*nested_list, t)) {
3501 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3502 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3503 goto no_subst;
3507 TokenString *str = tok_str_alloc();
3508 str->str = (int*)macro_str;
3509 begin_macro(str, 2);
3511 tok = t;
3512 macro_subst_tok(tok_str, nested_list, s);
3514 if (macro_stack != str) {
3515 /* already finished by reading function macro arguments */
3516 break;
3519 macro_str = macro_ptr;
3520 end_macro ();
3522 if (tok_str->len)
3523 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3524 } else {
3525 no_subst:
3526 if (!check_space(t, &spc))
3527 tok_str_add2(tok_str, t, &cval);
3529 if (nosubst) {
3530 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3531 continue;
3532 nosubst = 0;
3534 if (t == TOK_NOSUBST)
3535 nosubst = 1;
3537 /* GCC supports 'defined' as result of a macro substitution */
3538 if (t == TOK_DEFINED && pp_expr)
3539 nosubst = 2;
3543 /* return next token without macro substitution. Can read input from
3544 macro_ptr buffer */
3545 static void next_nomacro(void)
3547 int t;
3548 if (macro_ptr) {
3549 redo:
3550 t = *macro_ptr;
3551 if (TOK_HAS_VALUE(t)) {
3552 tok_get(&tok, &macro_ptr, &tokc);
3553 if (t == TOK_LINENUM) {
3554 file->line_num = tokc.i;
3555 goto redo;
3557 } else {
3558 macro_ptr++;
3559 if (t < TOK_IDENT) {
3560 if (!(parse_flags & PARSE_FLAG_SPACES)
3561 && (isidnum_table[t - CH_EOF] & IS_SPC))
3562 goto redo;
3564 tok = t;
3566 } else {
3567 next_nomacro1();
3571 /* return next token with macro substitution */
3572 ST_FUNC void next(void)
3574 int t;
3575 redo:
3576 next_nomacro();
3577 t = tok;
3578 if (macro_ptr) {
3579 if (!TOK_HAS_VALUE(t)) {
3580 if (t == TOK_NOSUBST || t == TOK_PLCHLDR) {
3581 /* discard preprocessor markers */
3582 goto redo;
3583 } else if (t == 0) {
3584 /* end of macro or unget token string */
3585 end_macro();
3586 goto redo;
3587 } else if (t == '\\') {
3588 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3589 tcc_error("stray '\\' in program");
3591 return;
3593 } else if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3594 /* if reading from file, try to substitute macros */
3595 Sym *s = define_find(t);
3596 if (s) {
3597 Sym *nested_list = NULL;
3598 tokstr_buf.len = 0;
3599 macro_subst_tok(&tokstr_buf, &nested_list, s);
3600 tok_str_add(&tokstr_buf, 0);
3601 begin_macro(&tokstr_buf, 0);
3602 goto redo;
3604 return;
3606 /* convert preprocessor tokens into C tokens */
3607 if (t == TOK_PPNUM) {
3608 if (parse_flags & PARSE_FLAG_TOK_NUM)
3609 parse_number((char *)tokc.str.data);
3610 } else if (t == TOK_PPSTR) {
3611 if (parse_flags & PARSE_FLAG_TOK_STR)
3612 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3616 /* push back current token and set current token to 'last_tok'. Only
3617 identifier case handled for labels. */
3618 ST_INLN void unget_tok(int last_tok)
3621 TokenString *str = tok_str_alloc();
3622 tok_str_add2(str, tok, &tokc);
3623 tok_str_add(str, 0);
3624 begin_macro(str, 1);
3625 tok = last_tok;
3628 static void tcc_predefs(TCCState *s1, CString *cs, int is_asm)
3630 int a,b,c;
3632 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
3633 cstr_printf(cs, "#define __TINYC__ %d\n", a*10000 + b*100 + c);
3634 cstr_cat(cs,
3635 /* target machine */
3636 #if defined TCC_TARGET_I386
3637 "#define __i386__ 1\n"
3638 "#define __i386 1\n"
3639 #elif defined TCC_TARGET_X86_64
3640 "#define __x86_64__ 1\n"
3641 "#define __amd64__ 1\n"
3642 #elif defined TCC_TARGET_ARM
3643 "#define __ARM_ARCH_4__ 1\n"
3644 "#define __arm_elf__ 1\n"
3645 "#define __arm_elf 1\n"
3646 "#define arm_elf 1\n"
3647 "#define __arm__ 1\n"
3648 "#define __arm 1\n"
3649 "#define arm 1\n"
3650 "#define __APCS_32__ 1\n"
3651 "#define __ARMEL__ 1\n"
3652 # if defined TCC_ARM_EABI
3653 "#define __ARM_EABI__ 1\n"
3654 # endif
3655 #elif defined TCC_TARGET_ARM64
3656 "#define __aarch64__ 1\n"
3657 #elif defined TCC_TARGET_C67
3658 "#define __C67__ 1\n"
3659 #elif defined TCC_TARGET_RISCV64
3660 "#define __riscv 1\n"
3661 "#define __riscv_xlen 64\n"
3662 "#define __riscv_flen 64\n"
3663 "#define __riscv_div 1\n"
3664 "#define __riscv_mul 1\n"
3665 "#define __riscv_fdiv 1\n"
3666 "#define __riscv_fsqrt 1\n"
3667 "#define __riscv_float_abi_double 1\n"
3668 #endif
3669 , -1);
3670 #ifdef TCC_TARGET_ARM
3671 if (s1->float_abi == ARM_HARD_FLOAT)
3672 cstr_printf(cs, "#define __ARM_PCS_VFP 1\n");
3673 #endif
3674 cstr_cat(cs,
3675 /* target platform */
3676 #ifdef TCC_TARGET_PE
3677 "#define _WIN32 1\n"
3678 #else
3679 "#define __unix__ 1\n"
3680 "#define __unix 1\n"
3681 # if defined TCC_TARGET_MACHO
3682 "#define __APPLE__ 1\n"
3683 # elif TARGETOS_FreeBSD
3684 "#define __FreeBSD__ 12\n"
3685 # elif TARGETOS_FreeBSD_kernel
3686 "#define __FreeBSD_kernel__ 1\n"
3687 # elif TARGETOS_NetBSD
3688 "#define __NetBSD__ 1\n"
3689 # elif TARGETOS_OpenBSD
3690 "#define __OpenBSD__ 1\n"
3691 # else
3692 "#define __linux__ 1\n"
3693 "#define __linux 1\n"
3694 # endif
3695 #endif
3696 , -1);
3697 if (is_asm)
3698 cstr_printf(cs, "#define __ASSEMBLER__ 1\n");
3699 if (s1->output_type == TCC_OUTPUT_PREPROCESS)
3700 cstr_printf(cs, "#define __TCC_PP__ 1\n");
3701 if (s1->output_type == TCC_OUTPUT_MEMORY)
3702 cstr_printf(cs, "#define __TCC_RUN__ 1\n");
3703 if (s1->char_is_unsigned)
3704 cstr_printf(cs, "#define __CHAR_UNSIGNED__ 1\n");
3705 if (s1->optimize > 0)
3706 cstr_printf(cs, "#define __OPTIMIZE__ 1\n");
3707 if (s1->option_pthread)
3708 cstr_printf(cs, "#define _REENTRANT 1\n");
3709 if (s1->leading_underscore)
3710 cstr_printf(cs, "#define __leading_underscore 1\n");
3711 #ifdef CONFIG_TCC_BCHECK
3712 if (s1->do_bounds_check)
3713 cstr_printf(cs, "#define __BOUNDS_CHECKING_ON 1\n");
3714 #endif
3715 cstr_printf(cs, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE);
3716 cstr_printf(cs, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE);
3717 if (!is_asm) {
3718 cstr_printf(cs, "#define __STDC__ 1\n");
3719 cstr_printf(cs, "#define __STDC_VERSION__ %dL\n", s1->cversion);
3720 cstr_cat(cs,
3721 /* load more predefs and __builtins */
3722 #if CONFIG_TCC_PREDEFS
3723 #include "tccdefs_.h" /* include as strings */
3724 #else
3725 "#include <tccdefs.h>\n" /* load at runtime */
3726 #endif
3727 , -1);
3729 cstr_printf(cs, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3732 ST_FUNC void preprocess_start(TCCState *s1, int filetype)
3734 int is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
3735 CString cstr;
3737 tccpp_new(s1);
3739 s1->include_stack_ptr = s1->include_stack;
3740 s1->ifdef_stack_ptr = s1->ifdef_stack;
3741 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3742 pp_expr = 0;
3743 pp_counter = 0;
3744 pp_debug_tok = pp_debug_symv = 0;
3745 pp_once++;
3746 s1->pack_stack[0] = 0;
3747 s1->pack_stack_ptr = s1->pack_stack;
3749 set_idnum('$', !is_asm && s1->dollars_in_identifiers ? IS_ID : 0);
3750 set_idnum('.', is_asm ? IS_ID : 0);
3752 if (!(filetype & AFF_TYPE_ASM)) {
3753 cstr_new(&cstr);
3754 tcc_predefs(s1, &cstr, is_asm);
3755 if (s1->cmdline_defs.size)
3756 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3757 if (s1->cmdline_incl.size)
3758 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3759 //printf("%s\n", (char*)cstr.data);
3760 *s1->include_stack_ptr++ = file;
3761 tcc_open_bf(s1, "<command line>", cstr.size);
3762 memcpy(file->buffer, cstr.data, cstr.size);
3763 cstr_free(&cstr);
3766 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3767 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3770 /* cleanup from error/setjmp */
3771 ST_FUNC void preprocess_end(TCCState *s1)
3773 while (macro_stack)
3774 end_macro();
3775 macro_ptr = NULL;
3776 while (file)
3777 tcc_close();
3778 tccpp_delete(s1);
3781 ST_FUNC void tccpp_new(TCCState *s)
3783 int i, c;
3784 const char *p, *r;
3786 /* init isid table */
3787 for(i = CH_EOF; i<128; i++)
3788 set_idnum(i,
3789 is_space(i) ? IS_SPC
3790 : isid(i) ? IS_ID
3791 : isnum(i) ? IS_NUM
3792 : 0);
3794 for(i = 128; i<256; i++)
3795 set_idnum(i, IS_ID);
3797 /* init allocators */
3798 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3799 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3801 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3802 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3804 cstr_new(&cstr_buf);
3805 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3806 tok_str_new(&tokstr_buf);
3807 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3809 tok_ident = TOK_IDENT;
3810 p = tcc_keywords;
3811 while (*p) {
3812 r = p;
3813 for(;;) {
3814 c = *r++;
3815 if (c == '\0')
3816 break;
3818 tok_alloc(p, r - p - 1);
3819 p = r;
3822 /* we add dummy defines for some special macros to speed up tests
3823 and to have working defined() */
3824 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3825 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3826 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3827 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3828 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3831 ST_FUNC void tccpp_delete(TCCState *s)
3833 int i, n;
3835 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3837 /* free tokens */
3838 n = tok_ident - TOK_IDENT;
3839 if (n > total_idents)
3840 total_idents = n;
3841 for(i = 0; i < n; i++)
3842 tal_free(toksym_alloc, table_ident[i]);
3843 tcc_free(table_ident);
3844 table_ident = NULL;
3846 /* free static buffers */
3847 cstr_free(&tokcstr);
3848 cstr_free(&cstr_buf);
3849 cstr_free(&macro_equal_buf);
3850 tok_str_free_str(tokstr_buf.str);
3852 /* free allocators */
3853 tal_delete(toksym_alloc);
3854 toksym_alloc = NULL;
3855 tal_delete(tokstr_alloc);
3856 tokstr_alloc = NULL;
3859 /* ------------------------------------------------------------------------- */
3860 /* tcc -E [-P[1]] [-dD} support */
3862 static void tok_print(const char *msg, const int *str)
3864 FILE *fp;
3865 int t, s = 0;
3866 CValue cval;
3868 fp = tcc_state->ppfp;
3869 fprintf(fp, "%s", msg);
3870 while (str) {
3871 TOK_GET(&t, &str, &cval);
3872 if (!t)
3873 break;
3874 fprintf(fp, &" %s"[s], get_tok_str(t, &cval)), s = 1;
3876 fprintf(fp, "\n");
3879 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3881 int d = f->line_num - f->line_ref;
3883 if (s1->dflag & 4)
3884 return;
3886 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3888 } else if (level == 0 && f->line_ref && d < 8) {
3889 while (d > 0)
3890 fputs("\n", s1->ppfp), --d;
3891 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3892 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3893 } else {
3894 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3895 level > 0 ? " 1" : level < 0 ? " 2" : "");
3897 f->line_ref = f->line_num;
3900 static void define_print(TCCState *s1, int v)
3902 FILE *fp;
3903 Sym *s;
3905 s = define_find(v);
3906 if (NULL == s || NULL == s->d)
3907 return;
3909 fp = s1->ppfp;
3910 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3911 if (s->type.t == MACRO_FUNC) {
3912 Sym *a = s->next;
3913 fprintf(fp,"(");
3914 if (a)
3915 for (;;) {
3916 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3917 if (!(a = a->next))
3918 break;
3919 fprintf(fp,",");
3921 fprintf(fp,")");
3923 tok_print("", s->d);
3926 static void pp_debug_defines(TCCState *s1)
3928 int v, t;
3929 const char *vs;
3930 FILE *fp;
3932 t = pp_debug_tok;
3933 if (t == 0)
3934 return;
3936 file->line_num--;
3937 pp_line(s1, file, 0);
3938 file->line_ref = ++file->line_num;
3940 fp = s1->ppfp;
3941 v = pp_debug_symv;
3942 vs = get_tok_str(v, NULL);
3943 if (t == TOK_DEFINE) {
3944 define_print(s1, v);
3945 } else if (t == TOK_UNDEF) {
3946 fprintf(fp, "#undef %s\n", vs);
3947 } else if (t == TOK_push_macro) {
3948 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3949 } else if (t == TOK_pop_macro) {
3950 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3952 pp_debug_tok = 0;
3955 static void pp_debug_builtins(TCCState *s1)
3957 int v;
3958 for (v = TOK_IDENT; v < tok_ident; ++v)
3959 define_print(s1, v);
3962 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3963 static int pp_need_space(int a, int b)
3965 return 'E' == a ? '+' == b || '-' == b
3966 : '+' == a ? TOK_INC == b || '+' == b
3967 : '-' == a ? TOK_DEC == b || '-' == b
3968 : a >= TOK_IDENT ? b >= TOK_IDENT
3969 : a == TOK_PPNUM ? b >= TOK_IDENT
3970 : 0;
3973 /* maybe hex like 0x1e */
3974 static int pp_check_he0xE(int t, const char *p)
3976 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3977 return 'E';
3978 return t;
3981 /* Preprocess the current file */
3982 ST_FUNC int tcc_preprocess(TCCState *s1)
3984 BufferedFile **iptr;
3985 int token_seen, spcs, level;
3986 const char *p;
3987 char white[400];
3989 parse_flags = PARSE_FLAG_PREPROCESS
3990 | (parse_flags & PARSE_FLAG_ASM_FILE)
3991 | PARSE_FLAG_LINEFEED
3992 | PARSE_FLAG_SPACES
3993 | PARSE_FLAG_ACCEPT_STRAYS
3995 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3996 capability to compile and run itself, provided all numbers are
3997 given as decimals. tcc -E -P10 will do. */
3998 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3999 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
4001 if (s1->do_bench) {
4002 /* for PP benchmarks */
4003 do next(); while (tok != TOK_EOF);
4004 return 0;
4007 if (s1->dflag & 1) {
4008 pp_debug_builtins(s1);
4009 s1->dflag &= ~1;
4012 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
4013 if (file->prev)
4014 pp_line(s1, file->prev, level++);
4015 pp_line(s1, file, level);
4016 for (;;) {
4017 iptr = s1->include_stack_ptr;
4018 next();
4019 if (tok == TOK_EOF)
4020 break;
4022 level = s1->include_stack_ptr - iptr;
4023 if (level) {
4024 if (level > 0)
4025 pp_line(s1, *iptr, 0);
4026 pp_line(s1, file, level);
4028 if (s1->dflag & 7) {
4029 pp_debug_defines(s1);
4030 if (s1->dflag & 4)
4031 continue;
4034 if (is_space(tok)) {
4035 if (spcs < sizeof white - 1)
4036 white[spcs++] = tok;
4037 continue;
4038 } else if (tok == TOK_LINEFEED) {
4039 spcs = 0;
4040 if (token_seen == TOK_LINEFEED)
4041 continue;
4042 ++file->line_ref;
4043 } else if (token_seen == TOK_LINEFEED) {
4044 pp_line(s1, file, 0);
4045 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
4046 white[spcs++] = ' ';
4049 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
4050 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
4051 token_seen = pp_check_he0xE(tok, p);
4053 return 0;
4056 /* ------------------------------------------------------------------------- */