NetBSD: Trying to fix reloc error 38 on arm - WIP
[tinycc.git] / tccpp.c
blobcd9bd6840f1b575cdbcab8df51a470b0e7a40a66
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 ST_FUNC int tok_alloc_const(const char *str)
492 return tok_alloc(str, strlen(str))->tok;
496 /* XXX: buffer overflow */
497 /* XXX: float tokens */
498 ST_FUNC const char *get_tok_str(int v, CValue *cv)
500 char *p;
501 int i, len;
503 cstr_reset(&cstr_buf);
504 p = cstr_buf.data;
506 switch(v) {
507 case TOK_CINT:
508 case TOK_CUINT:
509 case TOK_CLONG:
510 case TOK_CULONG:
511 case TOK_CLLONG:
512 case TOK_CULLONG:
513 /* XXX: not quite exact, but only useful for testing */
514 #ifdef _WIN32
515 sprintf(p, "%u", (unsigned)cv->i);
516 #else
517 sprintf(p, "%llu", (unsigned long long)cv->i);
518 #endif
519 break;
520 case TOK_LCHAR:
521 cstr_ccat(&cstr_buf, 'L');
522 case TOK_CCHAR:
523 cstr_ccat(&cstr_buf, '\'');
524 add_char(&cstr_buf, cv->i);
525 cstr_ccat(&cstr_buf, '\'');
526 cstr_ccat(&cstr_buf, '\0');
527 break;
528 case TOK_PPNUM:
529 case TOK_PPSTR:
530 return (char*)cv->str.data;
531 case TOK_LSTR:
532 cstr_ccat(&cstr_buf, 'L');
533 case TOK_STR:
534 cstr_ccat(&cstr_buf, '\"');
535 if (v == TOK_STR) {
536 len = cv->str.size - 1;
537 for(i=0;i<len;i++)
538 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
539 } else {
540 len = (cv->str.size / sizeof(nwchar_t)) - 1;
541 for(i=0;i<len;i++)
542 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
544 cstr_ccat(&cstr_buf, '\"');
545 cstr_ccat(&cstr_buf, '\0');
546 break;
548 case TOK_CFLOAT:
549 cstr_cat(&cstr_buf, "<float>", 0);
550 break;
551 case TOK_CDOUBLE:
552 cstr_cat(&cstr_buf, "<double>", 0);
553 break;
554 case TOK_CLDOUBLE:
555 cstr_cat(&cstr_buf, "<long double>", 0);
556 break;
557 case TOK_LINENUM:
558 cstr_cat(&cstr_buf, "<linenumber>", 0);
559 break;
561 /* above tokens have value, the ones below don't */
562 case TOK_LT:
563 v = '<';
564 goto addv;
565 case TOK_GT:
566 v = '>';
567 goto addv;
568 case TOK_DOTS:
569 return strcpy(p, "...");
570 case TOK_A_SHL:
571 return strcpy(p, "<<=");
572 case TOK_A_SAR:
573 return strcpy(p, ">>=");
574 case TOK_EOF:
575 return strcpy(p, "<eof>");
576 default:
577 if (v < TOK_IDENT) {
578 /* search in two bytes table */
579 const unsigned char *q = tok_two_chars;
580 while (*q) {
581 if (q[2] == v) {
582 *p++ = q[0];
583 *p++ = q[1];
584 *p = '\0';
585 return cstr_buf.data;
587 q += 3;
589 if (v >= 127) {
590 sprintf(cstr_buf.data, "<%02x>", v);
591 return cstr_buf.data;
593 addv:
594 *p++ = v;
595 *p = '\0';
596 } else if (v < tok_ident) {
597 return table_ident[v - TOK_IDENT]->str;
598 } else if (v >= SYM_FIRST_ANOM) {
599 /* special name for anonymous symbol */
600 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
601 } else {
602 /* should never happen */
603 return NULL;
605 break;
607 return cstr_buf.data;
610 /* return the current character, handling end of block if necessary
611 (but not stray) */
612 static int handle_eob(void)
614 BufferedFile *bf = file;
615 int len;
617 /* only tries to read if really end of buffer */
618 if (bf->buf_ptr >= bf->buf_end) {
619 if (bf->fd >= 0) {
620 #if defined(PARSE_DEBUG)
621 len = 1;
622 #else
623 len = IO_BUF_SIZE;
624 #endif
625 len = read(bf->fd, bf->buffer, len);
626 if (len < 0)
627 len = 0;
628 } else {
629 len = 0;
631 total_bytes += len;
632 bf->buf_ptr = bf->buffer;
633 bf->buf_end = bf->buffer + len;
634 *bf->buf_end = CH_EOB;
636 if (bf->buf_ptr < bf->buf_end) {
637 return bf->buf_ptr[0];
638 } else {
639 bf->buf_ptr = bf->buf_end;
640 return CH_EOF;
644 /* read next char from current input file and handle end of input buffer */
645 static inline void inp(void)
647 ch = *(++(file->buf_ptr));
648 /* end of buffer/file handling */
649 if (ch == CH_EOB)
650 ch = handle_eob();
653 /* handle '\[\r]\n' */
654 static int handle_stray_noerror(void)
656 while (ch == '\\') {
657 inp();
658 if (ch == '\n') {
659 file->line_num++;
660 inp();
661 } else if (ch == '\r') {
662 inp();
663 if (ch != '\n')
664 goto fail;
665 file->line_num++;
666 inp();
667 } else {
668 fail:
669 return 1;
672 return 0;
675 static void handle_stray(void)
677 if (handle_stray_noerror())
678 tcc_error("stray '\\' in program");
681 /* skip the stray and handle the \\n case. Output an error if
682 incorrect char after the stray */
683 static int handle_stray1(uint8_t *p)
685 int c;
687 file->buf_ptr = p;
688 if (p >= file->buf_end) {
689 c = handle_eob();
690 if (c != '\\')
691 return c;
692 p = file->buf_ptr;
694 ch = *p;
695 if (handle_stray_noerror()) {
696 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
697 tcc_error("stray '\\' in program");
698 *--file->buf_ptr = '\\';
700 p = file->buf_ptr;
701 c = *p;
702 return c;
705 /* handle just the EOB case, but not stray */
706 #define PEEKC_EOB(c, p)\
708 p++;\
709 c = *p;\
710 if (c == '\\') {\
711 file->buf_ptr = p;\
712 c = handle_eob();\
713 p = file->buf_ptr;\
717 /* handle the complicated stray case */
718 #define PEEKC(c, p)\
720 p++;\
721 c = *p;\
722 if (c == '\\') {\
723 c = handle_stray1(p);\
724 p = file->buf_ptr;\
728 /* input with '\[\r]\n' handling. Note that this function cannot
729 handle other characters after '\', so you cannot call it inside
730 strings or comments */
731 static void minp(void)
733 inp();
734 if (ch == '\\')
735 handle_stray();
738 /* single line C++ comments */
739 static uint8_t *parse_line_comment(uint8_t *p)
741 int c;
743 p++;
744 for(;;) {
745 c = *p;
746 redo:
747 if (c == '\n' || c == CH_EOF) {
748 break;
749 } else if (c == '\\') {
750 file->buf_ptr = p;
751 c = handle_eob();
752 p = file->buf_ptr;
753 if (c == '\\') {
754 PEEKC_EOB(c, p);
755 if (c == '\n') {
756 file->line_num++;
757 PEEKC_EOB(c, p);
758 } else if (c == '\r') {
759 PEEKC_EOB(c, p);
760 if (c == '\n') {
761 file->line_num++;
762 PEEKC_EOB(c, p);
765 } else {
766 goto redo;
768 } else {
769 p++;
772 return p;
775 /* C comments */
776 static uint8_t *parse_comment(uint8_t *p)
778 int c;
780 p++;
781 for(;;) {
782 /* fast skip loop */
783 for(;;) {
784 c = *p;
785 if (c == '\n' || c == '*' || c == '\\')
786 break;
787 p++;
788 c = *p;
789 if (c == '\n' || c == '*' || c == '\\')
790 break;
791 p++;
793 /* now we can handle all the cases */
794 if (c == '\n') {
795 file->line_num++;
796 p++;
797 } else if (c == '*') {
798 p++;
799 for(;;) {
800 c = *p;
801 if (c == '*') {
802 p++;
803 } else if (c == '/') {
804 goto end_of_comment;
805 } else if (c == '\\') {
806 file->buf_ptr = p;
807 c = handle_eob();
808 p = file->buf_ptr;
809 if (c == CH_EOF)
810 tcc_error("unexpected end of file in comment");
811 if (c == '\\') {
812 /* skip '\[\r]\n', otherwise just skip the stray */
813 while (c == '\\') {
814 PEEKC_EOB(c, p);
815 if (c == '\n') {
816 file->line_num++;
817 PEEKC_EOB(c, p);
818 } else if (c == '\r') {
819 PEEKC_EOB(c, p);
820 if (c == '\n') {
821 file->line_num++;
822 PEEKC_EOB(c, p);
824 } else {
825 goto after_star;
829 } else {
830 break;
833 after_star: ;
834 } else {
835 /* stray, eob or eof */
836 file->buf_ptr = p;
837 c = handle_eob();
838 p = file->buf_ptr;
839 if (c == CH_EOF) {
840 tcc_error("unexpected end of file in comment");
841 } else if (c == '\\') {
842 p++;
846 end_of_comment:
847 p++;
848 return p;
851 ST_FUNC int set_idnum(int c, int val)
853 int prev = isidnum_table[c - CH_EOF];
854 isidnum_table[c - CH_EOF] = val;
855 return prev;
858 #define cinp minp
860 static inline void skip_spaces(void)
862 while (isidnum_table[ch - CH_EOF] & IS_SPC)
863 cinp();
866 static inline int check_space(int t, int *spc)
868 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
869 if (*spc)
870 return 1;
871 *spc = 1;
872 } else
873 *spc = 0;
874 return 0;
877 /* parse a string without interpreting escapes */
878 static uint8_t *parse_pp_string(uint8_t *p,
879 int sep, CString *str)
881 int c;
882 p++;
883 for(;;) {
884 c = *p;
885 if (c == sep) {
886 break;
887 } else if (c == '\\') {
888 file->buf_ptr = p;
889 c = handle_eob();
890 p = file->buf_ptr;
891 if (c == CH_EOF) {
892 unterminated_string:
893 /* XXX: indicate line number of start of string */
894 tcc_error("missing terminating %c character", sep);
895 } else if (c == '\\') {
896 /* escape : just skip \[\r]\n */
897 PEEKC_EOB(c, p);
898 if (c == '\n') {
899 file->line_num++;
900 p++;
901 } else if (c == '\r') {
902 PEEKC_EOB(c, p);
903 if (c != '\n')
904 expect("'\n' after '\r'");
905 file->line_num++;
906 p++;
907 } else if (c == CH_EOF) {
908 goto unterminated_string;
909 } else {
910 if (str) {
911 cstr_ccat(str, '\\');
912 cstr_ccat(str, c);
914 p++;
917 } else if (c == '\n') {
918 file->line_num++;
919 goto add_char;
920 } else if (c == '\r') {
921 PEEKC_EOB(c, p);
922 if (c != '\n') {
923 if (str)
924 cstr_ccat(str, '\r');
925 } else {
926 file->line_num++;
927 goto add_char;
929 } else {
930 add_char:
931 if (str)
932 cstr_ccat(str, c);
933 p++;
936 p++;
937 return p;
940 /* skip block of text until #else, #elif or #endif. skip also pairs of
941 #if/#endif */
942 static void preprocess_skip(void)
944 int a, start_of_line, c, in_warn_or_error;
945 uint8_t *p;
947 p = file->buf_ptr;
948 a = 0;
949 redo_start:
950 start_of_line = 1;
951 in_warn_or_error = 0;
952 for(;;) {
953 redo_no_start:
954 c = *p;
955 switch(c) {
956 case ' ':
957 case '\t':
958 case '\f':
959 case '\v':
960 case '\r':
961 p++;
962 goto redo_no_start;
963 case '\n':
964 file->line_num++;
965 p++;
966 goto redo_start;
967 case '\\':
968 file->buf_ptr = p;
969 c = handle_eob();
970 if (c == CH_EOF) {
971 expect("#endif");
972 } else if (c == '\\') {
973 ch = file->buf_ptr[0];
974 handle_stray_noerror();
976 p = file->buf_ptr;
977 goto redo_no_start;
978 /* skip strings */
979 case '\"':
980 case '\'':
981 if (in_warn_or_error)
982 goto _default;
983 p = parse_pp_string(p, c, NULL);
984 break;
985 /* skip comments */
986 case '/':
987 if (in_warn_or_error)
988 goto _default;
989 file->buf_ptr = p;
990 ch = *p;
991 minp();
992 p = file->buf_ptr;
993 if (ch == '*') {
994 p = parse_comment(p);
995 } else if (ch == '/') {
996 p = parse_line_comment(p);
998 break;
999 case '#':
1000 p++;
1001 if (start_of_line) {
1002 file->buf_ptr = p;
1003 next_nomacro();
1004 p = file->buf_ptr;
1005 if (a == 0 &&
1006 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
1007 goto the_end;
1008 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
1009 a++;
1010 else if (tok == TOK_ENDIF)
1011 a--;
1012 else if( tok == TOK_ERROR || tok == TOK_WARNING)
1013 in_warn_or_error = 1;
1014 else if (tok == TOK_LINEFEED)
1015 goto redo_start;
1016 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1017 p = parse_line_comment(p - 1);
1019 #if !defined(TCC_TARGET_ARM)
1020 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1021 p = parse_line_comment(p - 1);
1022 #else
1023 /* ARM assembly uses '#' for constants */
1024 #endif
1025 break;
1026 _default:
1027 default:
1028 p++;
1029 break;
1031 start_of_line = 0;
1033 the_end: ;
1034 file->buf_ptr = p;
1037 #if 0
1038 /* return the number of additional 'ints' necessary to store the
1039 token */
1040 static inline int tok_size(const int *p)
1042 switch(*p) {
1043 /* 4 bytes */
1044 case TOK_CINT:
1045 case TOK_CUINT:
1046 case TOK_CCHAR:
1047 case TOK_LCHAR:
1048 case TOK_CFLOAT:
1049 case TOK_LINENUM:
1050 return 1 + 1;
1051 case TOK_STR:
1052 case TOK_LSTR:
1053 case TOK_PPNUM:
1054 case TOK_PPSTR:
1055 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1056 case TOK_CLONG:
1057 case TOK_CULONG:
1058 return 1 + LONG_SIZE / 4;
1059 case TOK_CDOUBLE:
1060 case TOK_CLLONG:
1061 case TOK_CULLONG:
1062 return 1 + 2;
1063 case TOK_CLDOUBLE:
1064 return 1 + LDOUBLE_SIZE / 4;
1065 default:
1066 return 1 + 0;
1069 #endif
1071 /* token string handling */
1072 ST_INLN void tok_str_new(TokenString *s)
1074 s->str = NULL;
1075 s->len = s->lastlen = 0;
1076 s->allocated_len = 0;
1077 s->last_line_num = -1;
1080 ST_FUNC TokenString *tok_str_alloc(void)
1082 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1083 tok_str_new(str);
1084 return str;
1087 ST_FUNC int *tok_str_dup(TokenString *s)
1089 int *str;
1091 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1092 memcpy(str, s->str, s->len * sizeof(int));
1093 return str;
1096 ST_FUNC void tok_str_free_str(int *str)
1098 tal_free(tokstr_alloc, str);
1101 ST_FUNC void tok_str_free(TokenString *str)
1103 tok_str_free_str(str->str);
1104 tal_free(tokstr_alloc, str);
1107 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1109 int *str, size;
1111 size = s->allocated_len;
1112 if (size < 16)
1113 size = 16;
1114 while (size < new_size)
1115 size = size * 2;
1116 if (size > s->allocated_len) {
1117 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1118 s->allocated_len = size;
1119 s->str = str;
1121 return s->str;
1124 ST_FUNC void tok_str_add(TokenString *s, int t)
1126 int len, *str;
1128 len = s->len;
1129 str = s->str;
1130 if (len >= s->allocated_len)
1131 str = tok_str_realloc(s, len + 1);
1132 str[len++] = t;
1133 s->len = len;
1136 ST_FUNC void begin_macro(TokenString *str, int alloc)
1138 str->alloc = alloc;
1139 str->prev = macro_stack;
1140 str->prev_ptr = macro_ptr;
1141 str->save_line_num = file->line_num;
1142 macro_ptr = str->str;
1143 macro_stack = str;
1146 ST_FUNC void end_macro(void)
1148 TokenString *str = macro_stack;
1149 macro_stack = str->prev;
1150 macro_ptr = str->prev_ptr;
1151 file->line_num = str->save_line_num;
1152 if (str->alloc != 0) {
1153 if (str->alloc == 2)
1154 str->str = NULL; /* don't free */
1155 tok_str_free(str);
1159 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1161 int len, *str;
1163 len = s->lastlen = s->len;
1164 str = s->str;
1166 /* allocate space for worst case */
1167 if (len + TOK_MAX_SIZE >= s->allocated_len)
1168 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1169 str[len++] = t;
1170 switch(t) {
1171 case TOK_CINT:
1172 case TOK_CUINT:
1173 case TOK_CCHAR:
1174 case TOK_LCHAR:
1175 case TOK_CFLOAT:
1176 case TOK_LINENUM:
1177 #if LONG_SIZE == 4
1178 case TOK_CLONG:
1179 case TOK_CULONG:
1180 #endif
1181 str[len++] = cv->tab[0];
1182 break;
1183 case TOK_PPNUM:
1184 case TOK_PPSTR:
1185 case TOK_STR:
1186 case TOK_LSTR:
1188 /* Insert the string into the int array. */
1189 size_t nb_words =
1190 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1191 if (len + nb_words >= s->allocated_len)
1192 str = tok_str_realloc(s, len + nb_words + 1);
1193 str[len] = cv->str.size;
1194 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1195 len += nb_words;
1197 break;
1198 case TOK_CDOUBLE:
1199 case TOK_CLLONG:
1200 case TOK_CULLONG:
1201 #if LONG_SIZE == 8
1202 case TOK_CLONG:
1203 case TOK_CULONG:
1204 #endif
1205 #if LDOUBLE_SIZE == 8
1206 case TOK_CLDOUBLE:
1207 #endif
1208 str[len++] = cv->tab[0];
1209 str[len++] = cv->tab[1];
1210 break;
1211 #if LDOUBLE_SIZE == 12
1212 case TOK_CLDOUBLE:
1213 str[len++] = cv->tab[0];
1214 str[len++] = cv->tab[1];
1215 str[len++] = cv->tab[2];
1216 #elif LDOUBLE_SIZE == 16
1217 case TOK_CLDOUBLE:
1218 str[len++] = cv->tab[0];
1219 str[len++] = cv->tab[1];
1220 str[len++] = cv->tab[2];
1221 str[len++] = cv->tab[3];
1222 #elif LDOUBLE_SIZE != 8
1223 #error add long double size support
1224 #endif
1225 break;
1226 default:
1227 break;
1229 s->len = len;
1232 /* add the current parse token in token string 's' */
1233 ST_FUNC void tok_str_add_tok(TokenString *s)
1235 CValue cval;
1237 /* save line number info */
1238 if (file->line_num != s->last_line_num) {
1239 s->last_line_num = file->line_num;
1240 cval.i = s->last_line_num;
1241 tok_str_add2(s, TOK_LINENUM, &cval);
1243 tok_str_add2(s, tok, &tokc);
1246 /* get a token from an integer array and increment pointer. */
1247 static inline void tok_get(int *t, const int **pp, CValue *cv)
1249 const int *p = *pp;
1250 int n, *tab;
1252 tab = cv->tab;
1253 switch(*t = *p++) {
1254 #if LONG_SIZE == 4
1255 case TOK_CLONG:
1256 #endif
1257 case TOK_CINT:
1258 case TOK_CCHAR:
1259 case TOK_LCHAR:
1260 case TOK_LINENUM:
1261 cv->i = *p++;
1262 break;
1263 #if LONG_SIZE == 4
1264 case TOK_CULONG:
1265 #endif
1266 case TOK_CUINT:
1267 cv->i = (unsigned)*p++;
1268 break;
1269 case TOK_CFLOAT:
1270 tab[0] = *p++;
1271 break;
1272 case TOK_STR:
1273 case TOK_LSTR:
1274 case TOK_PPNUM:
1275 case TOK_PPSTR:
1276 cv->str.size = *p++;
1277 cv->str.data = p;
1278 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1279 break;
1280 case TOK_CDOUBLE:
1281 case TOK_CLLONG:
1282 case TOK_CULLONG:
1283 #if LONG_SIZE == 8
1284 case TOK_CLONG:
1285 case TOK_CULONG:
1286 #endif
1287 n = 2;
1288 goto copy;
1289 case TOK_CLDOUBLE:
1290 #if LDOUBLE_SIZE == 16
1291 n = 4;
1292 #elif LDOUBLE_SIZE == 12
1293 n = 3;
1294 #elif LDOUBLE_SIZE == 8
1295 n = 2;
1296 #else
1297 # error add long double size support
1298 #endif
1299 copy:
1301 *tab++ = *p++;
1302 while (--n);
1303 break;
1304 default:
1305 break;
1307 *pp = p;
1310 #if 0
1311 # define TOK_GET(t,p,c) tok_get(t,p,c)
1312 #else
1313 # define TOK_GET(t,p,c) do { \
1314 int _t = **(p); \
1315 if (TOK_HAS_VALUE(_t)) \
1316 tok_get(t, p, c); \
1317 else \
1318 *(t) = _t, ++*(p); \
1319 } while (0)
1320 #endif
1322 static int macro_is_equal(const int *a, const int *b)
1324 CValue cv;
1325 int t;
1327 if (!a || !b)
1328 return 1;
1330 while (*a && *b) {
1331 /* first time preallocate macro_equal_buf, next time only reset position to start */
1332 cstr_reset(&macro_equal_buf);
1333 TOK_GET(&t, &a, &cv);
1334 cstr_cat(&macro_equal_buf, get_tok_str(t, &cv), 0);
1335 TOK_GET(&t, &b, &cv);
1336 if (strcmp(macro_equal_buf.data, get_tok_str(t, &cv)))
1337 return 0;
1339 return !(*a || *b);
1342 /* defines handling */
1343 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1345 Sym *s, *o;
1347 o = define_find(v);
1348 s = sym_push2(&define_stack, v, macro_type, 0);
1349 s->d = str;
1350 s->next = first_arg;
1351 table_ident[v - TOK_IDENT]->sym_define = s;
1353 if (o && !macro_is_equal(o->d, s->d))
1354 tcc_warning("%s redefined", get_tok_str(v, NULL));
1357 /* undefined a define symbol. Its name is just set to zero */
1358 ST_FUNC void define_undef(Sym *s)
1360 int v = s->v;
1361 if (v >= TOK_IDENT && v < tok_ident)
1362 table_ident[v - TOK_IDENT]->sym_define = NULL;
1365 ST_INLN Sym *define_find(int v)
1367 v -= TOK_IDENT;
1368 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1369 return NULL;
1370 return table_ident[v]->sym_define;
1373 /* free define stack until top reaches 'b' */
1374 ST_FUNC void free_defines(Sym *b)
1376 while (define_stack != b) {
1377 Sym *top = define_stack;
1378 define_stack = top->prev;
1379 tok_str_free_str(top->d);
1380 define_undef(top);
1381 sym_free(top);
1385 /* label lookup */
1386 ST_FUNC Sym *label_find(int v)
1388 v -= TOK_IDENT;
1389 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1390 return NULL;
1391 return table_ident[v]->sym_label;
1394 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1396 Sym *s, **ps;
1397 s = sym_push2(ptop, v, 0, 0);
1398 s->r = flags;
1399 ps = &table_ident[v - TOK_IDENT]->sym_label;
1400 if (ptop == &global_label_stack) {
1401 /* modify the top most local identifier, so that
1402 sym_identifier will point to 's' when popped */
1403 while (*ps != NULL)
1404 ps = &(*ps)->prev_tok;
1406 s->prev_tok = *ps;
1407 *ps = s;
1408 return s;
1411 /* pop labels until element last is reached. Look if any labels are
1412 undefined. Define symbols if '&&label' was used. */
1413 ST_FUNC void label_pop(Sym **ptop, Sym *slast, int keep)
1415 Sym *s, *s1;
1416 for(s = *ptop; s != slast; s = s1) {
1417 s1 = s->prev;
1418 if (s->r == LABEL_DECLARED) {
1419 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1420 } else if (s->r == LABEL_FORWARD) {
1421 tcc_error("label '%s' used but not defined",
1422 get_tok_str(s->v, NULL));
1423 } else {
1424 if (s->c) {
1425 /* define corresponding symbol. A size of
1426 1 is put. */
1427 put_extern_sym(s, cur_text_section, s->jnext, 1);
1430 /* remove label */
1431 if (s->r != LABEL_GONE)
1432 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1433 if (!keep)
1434 sym_free(s);
1435 else
1436 s->r = LABEL_GONE;
1438 if (!keep)
1439 *ptop = slast;
1442 /* fake the nth "#if defined test_..." for tcc -dt -run */
1443 static void maybe_run_test(TCCState *s)
1445 const char *p;
1446 if (s->include_stack_ptr != s->include_stack)
1447 return;
1448 p = get_tok_str(tok, NULL);
1449 if (0 != memcmp(p, "test_", 5))
1450 return;
1451 if (0 != --s->run_test)
1452 return;
1453 fprintf(s->ppfp, &"\n[%s]\n"[!(s->dflag & 32)], p), fflush(s->ppfp);
1454 define_push(tok, MACRO_OBJ, NULL, NULL);
1457 /* eval an expression for #if/#elif */
1458 static int expr_preprocess(void)
1460 int c, t;
1461 TokenString *str;
1463 str = tok_str_alloc();
1464 pp_expr = 1;
1465 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1466 next(); /* do macro subst */
1467 redo:
1468 if (tok == TOK_DEFINED) {
1469 next_nomacro();
1470 t = tok;
1471 if (t == '(')
1472 next_nomacro();
1473 if (tok < TOK_IDENT)
1474 expect("identifier");
1475 if (tcc_state->run_test)
1476 maybe_run_test(tcc_state);
1477 c = define_find(tok) != 0;
1478 if (t == '(') {
1479 next_nomacro();
1480 if (tok != ')')
1481 expect("')'");
1483 tok = TOK_CINT;
1484 tokc.i = c;
1485 } else if (1 && tok == TOK___HAS_INCLUDE) {
1486 next(); /* XXX check if correct to use expansion */
1487 skip('(');
1488 while (tok != ')' && tok != TOK_EOF)
1489 next();
1490 if (tok != ')')
1491 expect("')'");
1492 tok = TOK_CINT;
1493 tokc.i = 0;
1494 } else if (tok >= TOK_IDENT) {
1495 /* if undefined macro, replace with zero, check for func-like */
1496 t = tok;
1497 tok = TOK_CINT;
1498 tokc.i = 0;
1499 tok_str_add_tok(str);
1500 next();
1501 if (tok == '(')
1502 tcc_error("function-like macro '%s' is not defined",
1503 get_tok_str(t, NULL));
1504 goto redo;
1506 tok_str_add_tok(str);
1508 pp_expr = 0;
1509 tok_str_add(str, -1); /* simulate end of file */
1510 tok_str_add(str, 0);
1511 /* now evaluate C constant expression */
1512 begin_macro(str, 1);
1513 next();
1514 c = expr_const();
1515 end_macro();
1516 return c != 0;
1520 /* parse after #define */
1521 ST_FUNC void parse_define(void)
1523 Sym *s, *first, **ps;
1524 int v, t, varg, is_vaargs, spc;
1525 int saved_parse_flags = parse_flags;
1527 v = tok;
1528 if (v < TOK_IDENT || v == TOK_DEFINED)
1529 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1530 /* XXX: should check if same macro (ANSI) */
1531 first = NULL;
1532 t = MACRO_OBJ;
1533 /* We have to parse the whole define as if not in asm mode, in particular
1534 no line comment with '#' must be ignored. Also for function
1535 macros the argument list must be parsed without '.' being an ID
1536 character. */
1537 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1538 /* '(' must be just after macro definition for MACRO_FUNC */
1539 next_nomacro();
1540 parse_flags &= ~PARSE_FLAG_SPACES;
1541 if (tok == '(') {
1542 int dotid = set_idnum('.', 0);
1543 next_nomacro();
1544 ps = &first;
1545 if (tok != ')') for (;;) {
1546 varg = tok;
1547 next_nomacro();
1548 is_vaargs = 0;
1549 if (varg == TOK_DOTS) {
1550 varg = TOK___VA_ARGS__;
1551 is_vaargs = 1;
1552 } else if (tok == TOK_DOTS && gnu_ext) {
1553 is_vaargs = 1;
1554 next_nomacro();
1556 if (varg < TOK_IDENT)
1557 bad_list:
1558 tcc_error("bad macro parameter list");
1559 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1560 *ps = s;
1561 ps = &s->next;
1562 if (tok == ')')
1563 break;
1564 if (tok != ',' || is_vaargs)
1565 goto bad_list;
1566 next_nomacro();
1568 parse_flags |= PARSE_FLAG_SPACES;
1569 next_nomacro();
1570 t = MACRO_FUNC;
1571 set_idnum('.', dotid);
1574 tokstr_buf.len = 0;
1575 spc = 2;
1576 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1577 /* The body of a macro definition should be parsed such that identifiers
1578 are parsed like the file mode determines (i.e. with '.' being an
1579 ID character in asm mode). But '#' should be retained instead of
1580 regarded as line comment leader, so still don't set ASM_FILE
1581 in parse_flags. */
1582 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1583 /* remove spaces around ## and after '#' */
1584 if (TOK_TWOSHARPS == tok) {
1585 if (2 == spc)
1586 goto bad_twosharp;
1587 if (1 == spc)
1588 --tokstr_buf.len;
1589 spc = 3;
1590 tok = TOK_PPJOIN;
1591 } else if ('#' == tok) {
1592 spc = 4;
1593 } else if (check_space(tok, &spc)) {
1594 goto skip;
1596 tok_str_add2(&tokstr_buf, tok, &tokc);
1597 skip:
1598 next_nomacro();
1601 parse_flags = saved_parse_flags;
1602 if (spc == 1)
1603 --tokstr_buf.len; /* remove trailing space */
1604 tok_str_add(&tokstr_buf, 0);
1605 if (3 == spc)
1606 bad_twosharp:
1607 tcc_error("'##' cannot appear at either end of macro");
1608 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1611 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1613 const unsigned char *s;
1614 unsigned int h;
1615 CachedInclude *e;
1616 int i;
1618 h = TOK_HASH_INIT;
1619 s = (unsigned char *) filename;
1620 while (*s) {
1621 #ifdef _WIN32
1622 h = TOK_HASH_FUNC(h, toup(*s));
1623 #else
1624 h = TOK_HASH_FUNC(h, *s);
1625 #endif
1626 s++;
1628 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1630 i = s1->cached_includes_hash[h];
1631 for(;;) {
1632 if (i == 0)
1633 break;
1634 e = s1->cached_includes[i - 1];
1635 if (0 == PATHCMP(e->filename, filename))
1636 return e;
1637 i = e->hash_next;
1639 if (!add)
1640 return NULL;
1642 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1643 strcpy(e->filename, filename);
1644 e->ifndef_macro = e->once = 0;
1645 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1646 /* add in hash table */
1647 e->hash_next = s1->cached_includes_hash[h];
1648 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1649 #ifdef INC_DEBUG
1650 printf("adding cached '%s'\n", filename);
1651 #endif
1652 return e;
1655 static void pragma_parse(TCCState *s1)
1657 next_nomacro();
1658 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1659 int t = tok, v;
1660 Sym *s;
1662 if (next(), tok != '(')
1663 goto pragma_err;
1664 if (next(), tok != TOK_STR)
1665 goto pragma_err;
1666 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1667 if (next(), tok != ')')
1668 goto pragma_err;
1669 if (t == TOK_push_macro) {
1670 while (NULL == (s = define_find(v)))
1671 define_push(v, 0, NULL, NULL);
1672 s->type.ref = s; /* set push boundary */
1673 } else {
1674 for (s = define_stack; s; s = s->prev)
1675 if (s->v == v && s->type.ref == s) {
1676 s->type.ref = NULL;
1677 break;
1680 if (s)
1681 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1682 else
1683 tcc_warning("unbalanced #pragma pop_macro");
1684 pp_debug_tok = t, pp_debug_symv = v;
1686 } else if (tok == TOK_once) {
1687 search_cached_include(s1, file->filename, 1)->once = pp_once;
1689 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1690 /* tcc -E: keep pragmas below unchanged */
1691 unget_tok(' ');
1692 unget_tok(TOK_PRAGMA);
1693 unget_tok('#');
1694 unget_tok(TOK_LINEFEED);
1696 } else if (tok == TOK_pack) {
1697 /* This may be:
1698 #pragma pack(1) // set
1699 #pragma pack() // reset to default
1700 #pragma pack(push,1) // push & set
1701 #pragma pack(pop) // restore previous */
1702 next();
1703 skip('(');
1704 if (tok == TOK_ASM_pop) {
1705 next();
1706 if (s1->pack_stack_ptr <= s1->pack_stack) {
1707 stk_error:
1708 tcc_error("out of pack stack");
1710 s1->pack_stack_ptr--;
1711 } else {
1712 int val = 0;
1713 if (tok != ')') {
1714 if (tok == TOK_ASM_push) {
1715 next();
1716 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1717 goto stk_error;
1718 s1->pack_stack_ptr++;
1719 skip(',');
1721 if (tok != TOK_CINT)
1722 goto pragma_err;
1723 val = tokc.i;
1724 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1725 goto pragma_err;
1726 next();
1728 *s1->pack_stack_ptr = val;
1730 if (tok != ')')
1731 goto pragma_err;
1733 } else if (tok == TOK_comment) {
1734 char *p; int t;
1735 next();
1736 skip('(');
1737 t = tok;
1738 next();
1739 skip(',');
1740 if (tok != TOK_STR)
1741 goto pragma_err;
1742 p = tcc_strdup((char *)tokc.str.data);
1743 next();
1744 if (tok != ')')
1745 goto pragma_err;
1746 if (t == TOK_lib) {
1747 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1748 } else {
1749 if (t == TOK_option)
1750 tcc_set_options(s1, p);
1751 tcc_free(p);
1754 } else if (s1->warn_unsupported) {
1755 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1757 return;
1759 pragma_err:
1760 tcc_error("malformed #pragma directive");
1761 return;
1764 /* is_bof is true if first non space token at beginning of file */
1765 ST_FUNC void preprocess(int is_bof)
1767 TCCState *s1 = tcc_state;
1768 int i, c, n, saved_parse_flags;
1769 char buf[1024], *q;
1770 Sym *s;
1772 saved_parse_flags = parse_flags;
1773 parse_flags = PARSE_FLAG_PREPROCESS
1774 | PARSE_FLAG_TOK_NUM
1775 | PARSE_FLAG_TOK_STR
1776 | PARSE_FLAG_LINEFEED
1777 | (parse_flags & PARSE_FLAG_ASM_FILE)
1780 next_nomacro();
1781 redo:
1782 switch(tok) {
1783 case TOK_DEFINE:
1784 pp_debug_tok = tok;
1785 next_nomacro();
1786 pp_debug_symv = tok;
1787 parse_define();
1788 break;
1789 case TOK_UNDEF:
1790 pp_debug_tok = tok;
1791 next_nomacro();
1792 pp_debug_symv = tok;
1793 s = define_find(tok);
1794 /* undefine symbol by putting an invalid name */
1795 if (s)
1796 define_undef(s);
1797 break;
1798 case TOK_INCLUDE:
1799 case TOK_INCLUDE_NEXT:
1800 ch = file->buf_ptr[0];
1801 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1802 skip_spaces();
1803 if (ch == '<') {
1804 c = '>';
1805 goto read_name;
1806 } else if (ch == '\"') {
1807 c = ch;
1808 read_name:
1809 inp();
1810 q = buf;
1811 while (ch != c && ch != '\n' && ch != CH_EOF) {
1812 if ((q - buf) < sizeof(buf) - 1)
1813 *q++ = ch;
1814 if (ch == '\\') {
1815 if (handle_stray_noerror() == 0)
1816 --q;
1817 } else
1818 inp();
1820 *q = '\0';
1821 minp();
1822 #if 0
1823 /* eat all spaces and comments after include */
1824 /* XXX: slightly incorrect */
1825 while (ch1 != '\n' && ch1 != CH_EOF)
1826 inp();
1827 #endif
1828 } else {
1829 int len;
1830 /* computed #include : concatenate everything up to linefeed,
1831 the result must be one of the two accepted forms.
1832 Don't convert pp-tokens to tokens here. */
1833 parse_flags = (PARSE_FLAG_PREPROCESS
1834 | PARSE_FLAG_LINEFEED
1835 | (parse_flags & PARSE_FLAG_ASM_FILE));
1836 next();
1837 buf[0] = '\0';
1838 while (tok != TOK_LINEFEED) {
1839 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1840 next();
1842 len = strlen(buf);
1843 /* check syntax and remove '<>|""' */
1844 if ((len < 2 || ((buf[0] != '"' || buf[len-1] != '"') &&
1845 (buf[0] != '<' || buf[len-1] != '>'))))
1846 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1847 c = buf[len-1];
1848 memmove(buf, buf + 1, len - 2);
1849 buf[len - 2] = '\0';
1852 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1853 tcc_error("#include recursion too deep");
1854 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index + 1 : 0;
1855 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1856 for (; i < n; ++i) {
1857 char buf1[sizeof file->filename];
1858 CachedInclude *e;
1859 const char *path;
1861 if (i == 0) {
1862 /* check absolute include path */
1863 if (!IS_ABSPATH(buf))
1864 continue;
1865 buf1[0] = 0;
1867 } else if (i == 1) {
1868 /* search in file's dir if "header.h" */
1869 if (c != '\"')
1870 continue;
1871 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1872 path = file->true_filename;
1873 pstrncpy(buf1, path, tcc_basename(path) - path);
1875 } else {
1876 /* search in all the include paths */
1877 int j = i - 2, k = j - s1->nb_include_paths;
1878 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1879 pstrcpy(buf1, sizeof(buf1), path);
1880 pstrcat(buf1, sizeof(buf1), "/");
1883 pstrcat(buf1, sizeof(buf1), buf);
1884 e = search_cached_include(s1, buf1, 0);
1885 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1886 /* no need to parse the include because the 'ifndef macro'
1887 is defined (or had #pragma once) */
1888 #ifdef INC_DEBUG
1889 printf("%s: skipping cached %s\n", file->filename, buf1);
1890 #endif
1891 goto include_done;
1894 if (tcc_open(s1, buf1) < 0)
1895 continue;
1896 /* push previous file on stack */
1897 *s1->include_stack_ptr++ = file->prev;
1898 file->include_next_index = i;
1899 #ifdef INC_DEBUG
1900 printf("%s: including %s\n", file->prev->filename, file->filename);
1901 #endif
1902 /* update target deps */
1903 if (s1->gen_deps) {
1904 BufferedFile *bf = file;
1905 while (i == 1 && (bf = bf->prev))
1906 i = bf->include_next_index;
1907 /* skip system include files */
1908 if (n - i > s1->nb_sysinclude_paths)
1909 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1910 tcc_strdup(buf1));
1912 /* add include file debug info */
1913 tcc_debug_bincl(tcc_state);
1914 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1915 ch = file->buf_ptr[0];
1916 goto the_end;
1918 tcc_error("include file '%s' not found", buf);
1919 include_done:
1920 break;
1921 case TOK_IFNDEF:
1922 c = 1;
1923 goto do_ifdef;
1924 case TOK_IF:
1925 c = expr_preprocess();
1926 goto do_if;
1927 case TOK_IFDEF:
1928 c = 0;
1929 do_ifdef:
1930 next_nomacro();
1931 if (tok < TOK_IDENT)
1932 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1933 if (is_bof) {
1934 if (c) {
1935 #ifdef INC_DEBUG
1936 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1937 #endif
1938 file->ifndef_macro = tok;
1941 c = (define_find(tok) != 0) ^ c;
1942 do_if:
1943 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1944 tcc_error("memory full (ifdef)");
1945 *s1->ifdef_stack_ptr++ = c;
1946 goto test_skip;
1947 case TOK_ELSE:
1948 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1949 tcc_error("#else without matching #if");
1950 if (s1->ifdef_stack_ptr[-1] & 2)
1951 tcc_error("#else after #else");
1952 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1953 goto test_else;
1954 case TOK_ELIF:
1955 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1956 tcc_error("#elif without matching #if");
1957 c = s1->ifdef_stack_ptr[-1];
1958 if (c > 1)
1959 tcc_error("#elif after #else");
1960 /* last #if/#elif expression was true: we skip */
1961 if (c == 1) {
1962 c = 0;
1963 } else {
1964 c = expr_preprocess();
1965 s1->ifdef_stack_ptr[-1] = c;
1967 test_else:
1968 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1969 file->ifndef_macro = 0;
1970 test_skip:
1971 if (!(c & 1)) {
1972 preprocess_skip();
1973 is_bof = 0;
1974 goto redo;
1976 break;
1977 case TOK_ENDIF:
1978 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1979 tcc_error("#endif without matching #if");
1980 s1->ifdef_stack_ptr--;
1981 /* '#ifndef macro' was at the start of file. Now we check if
1982 an '#endif' is exactly at the end of file */
1983 if (file->ifndef_macro &&
1984 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1985 file->ifndef_macro_saved = file->ifndef_macro;
1986 /* need to set to zero to avoid false matches if another
1987 #ifndef at middle of file */
1988 file->ifndef_macro = 0;
1989 while (tok != TOK_LINEFEED)
1990 next_nomacro();
1991 tok_flags |= TOK_FLAG_ENDIF;
1992 goto the_end;
1994 break;
1995 case TOK_PPNUM:
1996 n = strtoul((char*)tokc.str.data, &q, 10);
1997 goto _line_num;
1998 case TOK_LINE:
1999 next();
2000 if (tok != TOK_CINT)
2001 _line_err:
2002 tcc_error("wrong #line format");
2003 n = tokc.i;
2004 _line_num:
2005 next();
2006 if (tok != TOK_LINEFEED) {
2007 if (tok == TOK_STR) {
2008 if (file->true_filename == file->filename)
2009 file->true_filename = tcc_strdup(file->filename);
2010 /* prepend directory from real file */
2011 pstrcpy(buf, sizeof buf, file->true_filename);
2012 *tcc_basename(buf) = 0;
2013 pstrcat(buf, sizeof buf, (char *)tokc.str.data);
2014 tcc_debug_putfile(s1, buf);
2015 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
2016 break;
2017 else
2018 goto _line_err;
2019 --n;
2021 if (file->fd > 0)
2022 total_lines += file->line_num - n;
2023 file->line_num = n;
2024 break;
2025 case TOK_ERROR:
2026 case TOK_WARNING:
2027 c = tok;
2028 ch = file->buf_ptr[0];
2029 skip_spaces();
2030 q = buf;
2031 while (ch != '\n' && ch != CH_EOF) {
2032 if ((q - buf) < sizeof(buf) - 1)
2033 *q++ = ch;
2034 if (ch == '\\') {
2035 if (handle_stray_noerror() == 0)
2036 --q;
2037 } else
2038 inp();
2040 *q = '\0';
2041 if (c == TOK_ERROR)
2042 tcc_error("#error %s", buf);
2043 else
2044 tcc_warning("#warning %s", buf);
2045 break;
2046 case TOK_PRAGMA:
2047 pragma_parse(s1);
2048 break;
2049 case TOK_LINEFEED:
2050 goto the_end;
2051 default:
2052 /* ignore gas line comment in an 'S' file. */
2053 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
2054 goto ignore;
2055 if (tok == '!' && is_bof)
2056 /* '!' is ignored at beginning to allow C scripts. */
2057 goto ignore;
2058 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
2059 ignore:
2060 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
2061 goto the_end;
2063 /* ignore other preprocess commands or #! for C scripts */
2064 while (tok != TOK_LINEFEED)
2065 next_nomacro();
2066 the_end:
2067 parse_flags = saved_parse_flags;
2070 /* evaluate escape codes in a string. */
2071 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
2073 int c, n;
2074 const uint8_t *p;
2076 p = buf;
2077 for(;;) {
2078 c = *p;
2079 if (c == '\0')
2080 break;
2081 if (c == '\\') {
2082 p++;
2083 /* escape */
2084 c = *p;
2085 switch(c) {
2086 case '0': case '1': case '2': case '3':
2087 case '4': case '5': case '6': case '7':
2088 /* at most three octal digits */
2089 n = c - '0';
2090 p++;
2091 c = *p;
2092 if (isoct(c)) {
2093 n = n * 8 + c - '0';
2094 p++;
2095 c = *p;
2096 if (isoct(c)) {
2097 n = n * 8 + c - '0';
2098 p++;
2101 c = n;
2102 goto add_char_nonext;
2103 case 'x':
2104 case 'u':
2105 case 'U':
2106 p++;
2107 n = 0;
2108 for(;;) {
2109 c = *p;
2110 if (c >= 'a' && c <= 'f')
2111 c = c - 'a' + 10;
2112 else if (c >= 'A' && c <= 'F')
2113 c = c - 'A' + 10;
2114 else if (isnum(c))
2115 c = c - '0';
2116 else
2117 break;
2118 n = n * 16 + c;
2119 p++;
2121 c = n;
2122 goto add_char_nonext;
2123 case 'a':
2124 c = '\a';
2125 break;
2126 case 'b':
2127 c = '\b';
2128 break;
2129 case 'f':
2130 c = '\f';
2131 break;
2132 case 'n':
2133 c = '\n';
2134 break;
2135 case 'r':
2136 c = '\r';
2137 break;
2138 case 't':
2139 c = '\t';
2140 break;
2141 case 'v':
2142 c = '\v';
2143 break;
2144 case 'e':
2145 if (!gnu_ext)
2146 goto invalid_escape;
2147 c = 27;
2148 break;
2149 case '\'':
2150 case '\"':
2151 case '\\':
2152 case '?':
2153 break;
2154 default:
2155 invalid_escape:
2156 if (c >= '!' && c <= '~')
2157 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2158 else
2159 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2160 break;
2162 } else if (is_long && c >= 0x80) {
2163 /* assume we are processing UTF-8 sequence */
2164 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2166 int cont; /* count of continuation bytes */
2167 int skip; /* how many bytes should skip when error occurred */
2168 int i;
2170 /* decode leading byte */
2171 if (c < 0xC2) {
2172 skip = 1; goto invalid_utf8_sequence;
2173 } else if (c <= 0xDF) {
2174 cont = 1; n = c & 0x1f;
2175 } else if (c <= 0xEF) {
2176 cont = 2; n = c & 0xf;
2177 } else if (c <= 0xF4) {
2178 cont = 3; n = c & 0x7;
2179 } else {
2180 skip = 1; goto invalid_utf8_sequence;
2183 /* decode continuation bytes */
2184 for (i = 1; i <= cont; i++) {
2185 int l = 0x80, h = 0xBF;
2187 /* adjust limit for second byte */
2188 if (i == 1) {
2189 switch (c) {
2190 case 0xE0: l = 0xA0; break;
2191 case 0xED: h = 0x9F; break;
2192 case 0xF0: l = 0x90; break;
2193 case 0xF4: h = 0x8F; break;
2197 if (p[i] < l || p[i] > h) {
2198 skip = i; goto invalid_utf8_sequence;
2201 n = (n << 6) | (p[i] & 0x3f);
2204 /* advance pointer */
2205 p += 1 + cont;
2206 c = n;
2207 goto add_char_nonext;
2209 /* error handling */
2210 invalid_utf8_sequence:
2211 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2212 c = 0xFFFD;
2213 p += skip;
2214 goto add_char_nonext;
2217 p++;
2218 add_char_nonext:
2219 if (!is_long)
2220 cstr_ccat(outstr, c);
2221 else {
2222 #ifdef TCC_TARGET_PE
2223 /* store as UTF-16 */
2224 if (c < 0x10000) {
2225 cstr_wccat(outstr, c);
2226 } else {
2227 c -= 0x10000;
2228 cstr_wccat(outstr, (c >> 10) + 0xD800);
2229 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2231 #else
2232 cstr_wccat(outstr, c);
2233 #endif
2236 /* add a trailing '\0' */
2237 if (!is_long)
2238 cstr_ccat(outstr, '\0');
2239 else
2240 cstr_wccat(outstr, '\0');
2243 static void parse_string(const char *s, int len)
2245 uint8_t buf[1000], *p = buf;
2246 int is_long, sep;
2248 if ((is_long = *s == 'L'))
2249 ++s, --len;
2250 sep = *s++;
2251 len -= 2;
2252 if (len >= sizeof buf)
2253 p = tcc_malloc(len + 1);
2254 memcpy(p, s, len);
2255 p[len] = 0;
2257 cstr_reset(&tokcstr);
2258 parse_escape_string(&tokcstr, p, is_long);
2259 if (p != buf)
2260 tcc_free(p);
2262 if (sep == '\'') {
2263 int char_size, i, n, c;
2264 /* XXX: make it portable */
2265 if (!is_long)
2266 tok = TOK_CCHAR, char_size = 1;
2267 else
2268 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2269 n = tokcstr.size / char_size - 1;
2270 if (n < 1)
2271 tcc_error("empty character constant");
2272 if (n > 1)
2273 tcc_warning("multi-character character constant");
2274 for (c = i = 0; i < n; ++i) {
2275 if (is_long)
2276 c = ((nwchar_t *)tokcstr.data)[i];
2277 else
2278 c = (c << 8) | ((char *)tokcstr.data)[i];
2280 tokc.i = c;
2281 } else {
2282 tokc.str.size = tokcstr.size;
2283 tokc.str.data = tokcstr.data;
2284 if (!is_long)
2285 tok = TOK_STR;
2286 else
2287 tok = TOK_LSTR;
2291 /* we use 64 bit numbers */
2292 #define BN_SIZE 2
2294 /* bn = (bn << shift) | or_val */
2295 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2297 int i;
2298 unsigned int v;
2299 for(i=0;i<BN_SIZE;i++) {
2300 v = bn[i];
2301 bn[i] = (v << shift) | or_val;
2302 or_val = v >> (32 - shift);
2306 static void bn_zero(unsigned int *bn)
2308 int i;
2309 for(i=0;i<BN_SIZE;i++) {
2310 bn[i] = 0;
2314 /* parse number in null terminated string 'p' and return it in the
2315 current token */
2316 static void parse_number(const char *p)
2318 int b, t, shift, frac_bits, s, exp_val, ch;
2319 char *q;
2320 unsigned int bn[BN_SIZE];
2321 double d;
2323 /* number */
2324 q = token_buf;
2325 ch = *p++;
2326 t = ch;
2327 ch = *p++;
2328 *q++ = t;
2329 b = 10;
2330 if (t == '.') {
2331 goto float_frac_parse;
2332 } else if (t == '0') {
2333 if (ch == 'x' || ch == 'X') {
2334 q--;
2335 ch = *p++;
2336 b = 16;
2337 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2338 q--;
2339 ch = *p++;
2340 b = 2;
2343 /* parse all digits. cannot check octal numbers at this stage
2344 because of floating point constants */
2345 while (1) {
2346 if (ch >= 'a' && ch <= 'f')
2347 t = ch - 'a' + 10;
2348 else if (ch >= 'A' && ch <= 'F')
2349 t = ch - 'A' + 10;
2350 else if (isnum(ch))
2351 t = ch - '0';
2352 else
2353 break;
2354 if (t >= b)
2355 break;
2356 if (q >= token_buf + STRING_MAX_SIZE) {
2357 num_too_long:
2358 tcc_error("number too long");
2360 *q++ = ch;
2361 ch = *p++;
2363 if (ch == '.' ||
2364 ((ch == 'e' || ch == 'E') && b == 10) ||
2365 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2366 if (b != 10) {
2367 /* NOTE: strtox should support that for hexa numbers, but
2368 non ISOC99 libcs do not support it, so we prefer to do
2369 it by hand */
2370 /* hexadecimal or binary floats */
2371 /* XXX: handle overflows */
2372 *q = '\0';
2373 if (b == 16)
2374 shift = 4;
2375 else
2376 shift = 1;
2377 bn_zero(bn);
2378 q = token_buf;
2379 while (1) {
2380 t = *q++;
2381 if (t == '\0') {
2382 break;
2383 } else if (t >= 'a') {
2384 t = t - 'a' + 10;
2385 } else if (t >= 'A') {
2386 t = t - 'A' + 10;
2387 } else {
2388 t = t - '0';
2390 bn_lshift(bn, shift, t);
2392 frac_bits = 0;
2393 if (ch == '.') {
2394 ch = *p++;
2395 while (1) {
2396 t = ch;
2397 if (t >= 'a' && t <= 'f') {
2398 t = t - 'a' + 10;
2399 } else if (t >= 'A' && t <= 'F') {
2400 t = t - 'A' + 10;
2401 } else if (t >= '0' && t <= '9') {
2402 t = t - '0';
2403 } else {
2404 break;
2406 if (t >= b)
2407 tcc_error("invalid digit");
2408 bn_lshift(bn, shift, t);
2409 frac_bits += shift;
2410 ch = *p++;
2413 if (ch != 'p' && ch != 'P')
2414 expect("exponent");
2415 ch = *p++;
2416 s = 1;
2417 exp_val = 0;
2418 if (ch == '+') {
2419 ch = *p++;
2420 } else if (ch == '-') {
2421 s = -1;
2422 ch = *p++;
2424 if (ch < '0' || ch > '9')
2425 expect("exponent digits");
2426 while (ch >= '0' && ch <= '9') {
2427 exp_val = exp_val * 10 + ch - '0';
2428 ch = *p++;
2430 exp_val = exp_val * s;
2432 /* now we can generate the number */
2433 /* XXX: should patch directly float number */
2434 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2435 d = ldexp(d, exp_val - frac_bits);
2436 t = toup(ch);
2437 if (t == 'F') {
2438 ch = *p++;
2439 tok = TOK_CFLOAT;
2440 /* float : should handle overflow */
2441 tokc.f = (float)d;
2442 } else if (t == 'L') {
2443 ch = *p++;
2444 #ifdef TCC_TARGET_PE
2445 tok = TOK_CDOUBLE;
2446 tokc.d = d;
2447 #else
2448 tok = TOK_CLDOUBLE;
2449 /* XXX: not large enough */
2450 tokc.ld = (long double)d;
2451 #endif
2452 } else {
2453 tok = TOK_CDOUBLE;
2454 tokc.d = d;
2456 } else {
2457 /* decimal floats */
2458 if (ch == '.') {
2459 if (q >= token_buf + STRING_MAX_SIZE)
2460 goto num_too_long;
2461 *q++ = ch;
2462 ch = *p++;
2463 float_frac_parse:
2464 while (ch >= '0' && ch <= '9') {
2465 if (q >= token_buf + STRING_MAX_SIZE)
2466 goto num_too_long;
2467 *q++ = ch;
2468 ch = *p++;
2471 if (ch == 'e' || ch == 'E') {
2472 if (q >= token_buf + STRING_MAX_SIZE)
2473 goto num_too_long;
2474 *q++ = ch;
2475 ch = *p++;
2476 if (ch == '-' || ch == '+') {
2477 if (q >= token_buf + STRING_MAX_SIZE)
2478 goto num_too_long;
2479 *q++ = ch;
2480 ch = *p++;
2482 if (ch < '0' || ch > '9')
2483 expect("exponent digits");
2484 while (ch >= '0' && ch <= '9') {
2485 if (q >= token_buf + STRING_MAX_SIZE)
2486 goto num_too_long;
2487 *q++ = ch;
2488 ch = *p++;
2491 *q = '\0';
2492 t = toup(ch);
2493 errno = 0;
2494 if (t == 'F') {
2495 ch = *p++;
2496 tok = TOK_CFLOAT;
2497 tokc.f = strtof(token_buf, NULL);
2498 } else if (t == 'L') {
2499 ch = *p++;
2500 #ifdef TCC_TARGET_PE
2501 tok = TOK_CDOUBLE;
2502 tokc.d = strtod(token_buf, NULL);
2503 #else
2504 tok = TOK_CLDOUBLE;
2505 tokc.ld = strtold(token_buf, NULL);
2506 #endif
2507 } else {
2508 tok = TOK_CDOUBLE;
2509 tokc.d = strtod(token_buf, NULL);
2512 } else {
2513 unsigned long long n, n1;
2514 int lcount, ucount, ov = 0;
2515 const char *p1;
2517 /* integer number */
2518 *q = '\0';
2519 q = token_buf;
2520 if (b == 10 && *q == '0') {
2521 b = 8;
2522 q++;
2524 n = 0;
2525 while(1) {
2526 t = *q++;
2527 /* no need for checks except for base 10 / 8 errors */
2528 if (t == '\0')
2529 break;
2530 else if (t >= 'a')
2531 t = t - 'a' + 10;
2532 else if (t >= 'A')
2533 t = t - 'A' + 10;
2534 else
2535 t = t - '0';
2536 if (t >= b)
2537 tcc_error("invalid digit");
2538 n1 = n;
2539 n = n * b + t;
2540 /* detect overflow */
2541 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2542 ov = 1;
2545 /* Determine the characteristics (unsigned and/or 64bit) the type of
2546 the constant must have according to the constant suffix(es) */
2547 lcount = ucount = 0;
2548 p1 = p;
2549 for(;;) {
2550 t = toup(ch);
2551 if (t == 'L') {
2552 if (lcount >= 2)
2553 tcc_error("three 'l's in integer constant");
2554 if (lcount && *(p - 1) != ch)
2555 tcc_error("incorrect integer suffix: %s", p1);
2556 lcount++;
2557 ch = *p++;
2558 } else if (t == 'U') {
2559 if (ucount >= 1)
2560 tcc_error("two 'u's in integer constant");
2561 ucount++;
2562 ch = *p++;
2563 } else {
2564 break;
2568 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2569 if (ucount == 0 && b == 10) {
2570 if (lcount <= (LONG_SIZE == 4)) {
2571 if (n >= 0x80000000U)
2572 lcount = (LONG_SIZE == 4) + 1;
2574 if (n >= 0x8000000000000000ULL)
2575 ov = 1, ucount = 1;
2576 } else {
2577 if (lcount <= (LONG_SIZE == 4)) {
2578 if (n >= 0x100000000ULL)
2579 lcount = (LONG_SIZE == 4) + 1;
2580 else if (n >= 0x80000000U)
2581 ucount = 1;
2583 if (n >= 0x8000000000000000ULL)
2584 ucount = 1;
2587 if (ov)
2588 tcc_warning("integer constant overflow");
2590 tok = TOK_CINT;
2591 if (lcount) {
2592 tok = TOK_CLONG;
2593 if (lcount == 2)
2594 tok = TOK_CLLONG;
2596 if (ucount)
2597 ++tok; /* TOK_CU... */
2598 tokc.i = n;
2600 if (ch)
2601 tcc_error("invalid number");
2605 #define PARSE2(c1, tok1, c2, tok2) \
2606 case c1: \
2607 PEEKC(c, p); \
2608 if (c == c2) { \
2609 p++; \
2610 tok = tok2; \
2611 } else { \
2612 tok = tok1; \
2614 break;
2616 /* return next token without macro substitution */
2617 static inline void next_nomacro1(void)
2619 int t, c, is_long, len;
2620 TokenSym *ts;
2621 uint8_t *p, *p1;
2622 unsigned int h;
2624 p = file->buf_ptr;
2625 redo_no_start:
2626 c = *p;
2627 switch(c) {
2628 case ' ':
2629 case '\t':
2630 tok = c;
2631 p++;
2632 maybe_space:
2633 if (parse_flags & PARSE_FLAG_SPACES)
2634 goto keep_tok_flags;
2635 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2636 ++p;
2637 goto redo_no_start;
2638 case '\f':
2639 case '\v':
2640 case '\r':
2641 p++;
2642 goto redo_no_start;
2643 case '\\':
2644 /* first look if it is in fact an end of buffer */
2645 c = handle_stray1(p);
2646 p = file->buf_ptr;
2647 if (c == '\\')
2648 goto parse_simple;
2649 if (c != CH_EOF)
2650 goto redo_no_start;
2652 TCCState *s1 = tcc_state;
2653 if ((parse_flags & PARSE_FLAG_LINEFEED)
2654 && !(tok_flags & TOK_FLAG_EOF)) {
2655 tok_flags |= TOK_FLAG_EOF;
2656 tok = TOK_LINEFEED;
2657 goto keep_tok_flags;
2658 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2659 tok = TOK_EOF;
2660 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2661 tcc_error("missing #endif");
2662 } else if (s1->include_stack_ptr == s1->include_stack) {
2663 /* no include left : end of file. */
2664 tok = TOK_EOF;
2665 } else {
2666 tok_flags &= ~TOK_FLAG_EOF;
2667 /* pop include file */
2669 /* test if previous '#endif' was after a #ifdef at
2670 start of file */
2671 if (tok_flags & TOK_FLAG_ENDIF) {
2672 #ifdef INC_DEBUG
2673 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2674 #endif
2675 search_cached_include(s1, file->filename, 1)
2676 ->ifndef_macro = file->ifndef_macro_saved;
2677 tok_flags &= ~TOK_FLAG_ENDIF;
2680 /* add end of include file debug info */
2681 tcc_debug_eincl(tcc_state);
2682 /* pop include stack */
2683 tcc_close();
2684 s1->include_stack_ptr--;
2685 p = file->buf_ptr;
2686 if (p == file->buffer)
2687 tok_flags = TOK_FLAG_BOF|TOK_FLAG_BOL;
2688 goto redo_no_start;
2691 break;
2693 case '\n':
2694 file->line_num++;
2695 tok_flags |= TOK_FLAG_BOL;
2696 p++;
2697 maybe_newline:
2698 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2699 goto redo_no_start;
2700 tok = TOK_LINEFEED;
2701 goto keep_tok_flags;
2703 case '#':
2704 /* XXX: simplify */
2705 PEEKC(c, p);
2706 if ((tok_flags & TOK_FLAG_BOL) &&
2707 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2708 file->buf_ptr = p;
2709 preprocess(tok_flags & TOK_FLAG_BOF);
2710 p = file->buf_ptr;
2711 goto maybe_newline;
2712 } else {
2713 if (c == '#') {
2714 p++;
2715 tok = TOK_TWOSHARPS;
2716 } else {
2717 #if !defined(TCC_TARGET_ARM)
2718 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2719 p = parse_line_comment(p - 1);
2720 goto redo_no_start;
2721 } else
2722 #endif
2724 tok = '#';
2728 break;
2730 /* dollar is allowed to start identifiers when not parsing asm */
2731 case '$':
2732 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2733 || (parse_flags & PARSE_FLAG_ASM_FILE))
2734 goto parse_simple;
2736 case 'a': case 'b': case 'c': case 'd':
2737 case 'e': case 'f': case 'g': case 'h':
2738 case 'i': case 'j': case 'k': case 'l':
2739 case 'm': case 'n': case 'o': case 'p':
2740 case 'q': case 'r': case 's': case 't':
2741 case 'u': case 'v': case 'w': case 'x':
2742 case 'y': case 'z':
2743 case 'A': case 'B': case 'C': case 'D':
2744 case 'E': case 'F': case 'G': case 'H':
2745 case 'I': case 'J': case 'K':
2746 case 'M': case 'N': case 'O': case 'P':
2747 case 'Q': case 'R': case 'S': case 'T':
2748 case 'U': case 'V': case 'W': case 'X':
2749 case 'Y': case 'Z':
2750 case '_':
2751 parse_ident_fast:
2752 p1 = p;
2753 h = TOK_HASH_INIT;
2754 h = TOK_HASH_FUNC(h, c);
2755 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2756 h = TOK_HASH_FUNC(h, c);
2757 len = p - p1;
2758 if (c != '\\') {
2759 TokenSym **pts;
2761 /* fast case : no stray found, so we have the full token
2762 and we have already hashed it */
2763 h &= (TOK_HASH_SIZE - 1);
2764 pts = &hash_ident[h];
2765 for(;;) {
2766 ts = *pts;
2767 if (!ts)
2768 break;
2769 if (ts->len == len && !memcmp(ts->str, p1, len))
2770 goto token_found;
2771 pts = &(ts->hash_next);
2773 ts = tok_alloc_new(pts, (char *) p1, len);
2774 token_found: ;
2775 } else {
2776 /* slower case */
2777 cstr_reset(&tokcstr);
2778 cstr_cat(&tokcstr, (char *) p1, len);
2779 p--;
2780 PEEKC(c, p);
2781 parse_ident_slow:
2782 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2784 cstr_ccat(&tokcstr, c);
2785 PEEKC(c, p);
2787 ts = tok_alloc(tokcstr.data, tokcstr.size);
2789 tok = ts->tok;
2790 break;
2791 case 'L':
2792 t = p[1];
2793 if (t != '\\' && t != '\'' && t != '\"') {
2794 /* fast case */
2795 goto parse_ident_fast;
2796 } else {
2797 PEEKC(c, p);
2798 if (c == '\'' || c == '\"') {
2799 is_long = 1;
2800 goto str_const;
2801 } else {
2802 cstr_reset(&tokcstr);
2803 cstr_ccat(&tokcstr, 'L');
2804 goto parse_ident_slow;
2807 break;
2809 case '0': case '1': case '2': case '3':
2810 case '4': case '5': case '6': case '7':
2811 case '8': case '9':
2812 t = c;
2813 PEEKC(c, p);
2814 /* after the first digit, accept digits, alpha, '.' or sign if
2815 prefixed by 'eEpP' */
2816 parse_num:
2817 cstr_reset(&tokcstr);
2818 for(;;) {
2819 cstr_ccat(&tokcstr, t);
2820 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2821 || c == '.'
2822 || ((c == '+' || c == '-')
2823 && (((t == 'e' || t == 'E')
2824 && !(parse_flags & PARSE_FLAG_ASM_FILE
2825 /* 0xe+1 is 3 tokens in asm */
2826 && ((char*)tokcstr.data)[0] == '0'
2827 && toup(((char*)tokcstr.data)[1]) == 'X'))
2828 || t == 'p' || t == 'P'))))
2829 break;
2830 t = c;
2831 PEEKC(c, p);
2833 /* We add a trailing '\0' to ease parsing */
2834 cstr_ccat(&tokcstr, '\0');
2835 tokc.str.size = tokcstr.size;
2836 tokc.str.data = tokcstr.data;
2837 tok = TOK_PPNUM;
2838 break;
2840 case '.':
2841 /* special dot handling because it can also start a number */
2842 PEEKC(c, p);
2843 if (isnum(c)) {
2844 t = '.';
2845 goto parse_num;
2846 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2847 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2848 *--p = c = '.';
2849 goto parse_ident_fast;
2850 } else if (c == '.') {
2851 PEEKC(c, p);
2852 if (c == '.') {
2853 p++;
2854 tok = TOK_DOTS;
2855 } else {
2856 *--p = '.'; /* may underflow into file->unget[] */
2857 tok = '.';
2859 } else {
2860 tok = '.';
2862 break;
2863 case '\'':
2864 case '\"':
2865 is_long = 0;
2866 str_const:
2867 cstr_reset(&tokcstr);
2868 if (is_long)
2869 cstr_ccat(&tokcstr, 'L');
2870 cstr_ccat(&tokcstr, c);
2871 p = parse_pp_string(p, c, &tokcstr);
2872 cstr_ccat(&tokcstr, c);
2873 cstr_ccat(&tokcstr, '\0');
2874 tokc.str.size = tokcstr.size;
2875 tokc.str.data = tokcstr.data;
2876 tok = TOK_PPSTR;
2877 break;
2879 case '<':
2880 PEEKC(c, p);
2881 if (c == '=') {
2882 p++;
2883 tok = TOK_LE;
2884 } else if (c == '<') {
2885 PEEKC(c, p);
2886 if (c == '=') {
2887 p++;
2888 tok = TOK_A_SHL;
2889 } else {
2890 tok = TOK_SHL;
2892 } else {
2893 tok = TOK_LT;
2895 break;
2896 case '>':
2897 PEEKC(c, p);
2898 if (c == '=') {
2899 p++;
2900 tok = TOK_GE;
2901 } else if (c == '>') {
2902 PEEKC(c, p);
2903 if (c == '=') {
2904 p++;
2905 tok = TOK_A_SAR;
2906 } else {
2907 tok = TOK_SAR;
2909 } else {
2910 tok = TOK_GT;
2912 break;
2914 case '&':
2915 PEEKC(c, p);
2916 if (c == '&') {
2917 p++;
2918 tok = TOK_LAND;
2919 } else if (c == '=') {
2920 p++;
2921 tok = TOK_A_AND;
2922 } else {
2923 tok = '&';
2925 break;
2927 case '|':
2928 PEEKC(c, p);
2929 if (c == '|') {
2930 p++;
2931 tok = TOK_LOR;
2932 } else if (c == '=') {
2933 p++;
2934 tok = TOK_A_OR;
2935 } else {
2936 tok = '|';
2938 break;
2940 case '+':
2941 PEEKC(c, p);
2942 if (c == '+') {
2943 p++;
2944 tok = TOK_INC;
2945 } else if (c == '=') {
2946 p++;
2947 tok = TOK_A_ADD;
2948 } else {
2949 tok = '+';
2951 break;
2953 case '-':
2954 PEEKC(c, p);
2955 if (c == '-') {
2956 p++;
2957 tok = TOK_DEC;
2958 } else if (c == '=') {
2959 p++;
2960 tok = TOK_A_SUB;
2961 } else if (c == '>') {
2962 p++;
2963 tok = TOK_ARROW;
2964 } else {
2965 tok = '-';
2967 break;
2969 PARSE2('!', '!', '=', TOK_NE)
2970 PARSE2('=', '=', '=', TOK_EQ)
2971 PARSE2('*', '*', '=', TOK_A_MUL)
2972 PARSE2('%', '%', '=', TOK_A_MOD)
2973 PARSE2('^', '^', '=', TOK_A_XOR)
2975 /* comments or operator */
2976 case '/':
2977 PEEKC(c, p);
2978 if (c == '*') {
2979 p = parse_comment(p);
2980 /* comments replaced by a blank */
2981 tok = ' ';
2982 goto maybe_space;
2983 } else if (c == '/') {
2984 p = parse_line_comment(p);
2985 tok = ' ';
2986 goto maybe_space;
2987 } else if (c == '=') {
2988 p++;
2989 tok = TOK_A_DIV;
2990 } else {
2991 tok = '/';
2993 break;
2995 /* simple tokens */
2996 case '(':
2997 case ')':
2998 case '[':
2999 case ']':
3000 case '{':
3001 case '}':
3002 case ',':
3003 case ';':
3004 case ':':
3005 case '?':
3006 case '~':
3007 case '@': /* only used in assembler */
3008 parse_simple:
3009 tok = c;
3010 p++;
3011 break;
3012 default:
3013 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
3014 goto parse_ident_fast;
3015 if (parse_flags & PARSE_FLAG_ASM_FILE)
3016 goto parse_simple;
3017 tcc_error("unrecognized character \\x%02x", c);
3018 break;
3020 tok_flags = 0;
3021 keep_tok_flags:
3022 file->buf_ptr = p;
3023 #if defined(PARSE_DEBUG)
3024 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
3025 #endif
3028 static void macro_subst(
3029 TokenString *tok_str,
3030 Sym **nested_list,
3031 const int *macro_str
3034 /* substitute arguments in replacement lists in macro_str by the values in
3035 args (field d) and return allocated string */
3036 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
3038 int t, t0, t1, spc;
3039 const int *st;
3040 Sym *s;
3041 CValue cval;
3042 TokenString str;
3043 CString cstr;
3045 tok_str_new(&str);
3046 t0 = t1 = 0;
3047 while(1) {
3048 TOK_GET(&t, &macro_str, &cval);
3049 if (!t)
3050 break;
3051 if (t == '#') {
3052 /* stringize */
3053 TOK_GET(&t, &macro_str, &cval);
3054 if (!t)
3055 goto bad_stringy;
3056 s = sym_find2(args, t);
3057 if (s) {
3058 cstr_new(&cstr);
3059 cstr_ccat(&cstr, '\"');
3060 st = s->d;
3061 spc = 0;
3062 while (*st >= 0) {
3063 TOK_GET(&t, &st, &cval);
3064 if (t != TOK_PLCHLDR
3065 && t != TOK_NOSUBST
3066 && 0 == check_space(t, &spc)) {
3067 const char *s = get_tok_str(t, &cval);
3068 while (*s) {
3069 if (t == TOK_PPSTR && *s != '\'')
3070 add_char(&cstr, *s);
3071 else
3072 cstr_ccat(&cstr, *s);
3073 ++s;
3077 cstr.size -= spc;
3078 cstr_ccat(&cstr, '\"');
3079 cstr_ccat(&cstr, '\0');
3080 #ifdef PP_DEBUG
3081 printf("\nstringize: <%s>\n", (char *)cstr.data);
3082 #endif
3083 /* add string */
3084 cval.str.size = cstr.size;
3085 cval.str.data = cstr.data;
3086 tok_str_add2(&str, TOK_PPSTR, &cval);
3087 cstr_free(&cstr);
3088 } else {
3089 bad_stringy:
3090 expect("macro parameter after '#'");
3092 } else if (t >= TOK_IDENT) {
3093 s = sym_find2(args, t);
3094 if (s) {
3095 int l0 = str.len;
3096 st = s->d;
3097 /* if '##' is present before or after, no arg substitution */
3098 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
3099 /* special case for var arg macros : ## eats the ','
3100 if empty VA_ARGS variable. */
3101 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
3102 if (*st <= 0) {
3103 /* suppress ',' '##' */
3104 str.len -= 2;
3105 } else {
3106 /* suppress '##' and add variable */
3107 str.len--;
3108 goto add_var;
3111 } else {
3112 add_var:
3113 if (!s->next) {
3114 /* Expand arguments tokens and store them. In most
3115 cases we could also re-expand each argument if
3116 used multiple times, but not if the argument
3117 contains the __COUNTER__ macro. */
3118 TokenString str2;
3119 sym_push2(&s->next, s->v, s->type.t, 0);
3120 tok_str_new(&str2);
3121 macro_subst(&str2, nested_list, st);
3122 tok_str_add(&str2, 0);
3123 s->next->d = str2.str;
3125 st = s->next->d;
3127 for(;;) {
3128 int t2;
3129 TOK_GET(&t2, &st, &cval);
3130 if (t2 <= 0)
3131 break;
3132 tok_str_add2(&str, t2, &cval);
3134 if (str.len == l0) /* expanded to empty string */
3135 tok_str_add(&str, TOK_PLCHLDR);
3136 } else {
3137 tok_str_add(&str, t);
3139 } else {
3140 tok_str_add2(&str, t, &cval);
3142 t0 = t1, t1 = t;
3144 tok_str_add(&str, 0);
3145 return str.str;
3148 static char const ab_month_name[12][4] =
3150 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3151 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3154 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3156 CString cstr;
3157 int n, ret = 1;
3159 cstr_new(&cstr);
3160 if (t1 != TOK_PLCHLDR)
3161 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3162 n = cstr.size;
3163 if (t2 != TOK_PLCHLDR)
3164 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3165 cstr_ccat(&cstr, '\0');
3167 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3168 memcpy(file->buffer, cstr.data, cstr.size);
3169 tok_flags = 0;
3170 for (;;) {
3171 next_nomacro1();
3172 if (0 == *file->buf_ptr)
3173 break;
3174 if (is_space(tok))
3175 continue;
3176 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3177 " preprocessing token", n, (char *)cstr.data, (char*)cstr.data + n);
3178 ret = 0;
3179 break;
3181 tcc_close();
3182 //printf("paste <%s>\n", (char*)cstr.data);
3183 cstr_free(&cstr);
3184 return ret;
3187 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3188 return the resulting string (which must be freed). */
3189 static inline int *macro_twosharps(const int *ptr0)
3191 int t;
3192 CValue cval;
3193 TokenString macro_str1;
3194 int start_of_nosubsts = -1;
3195 const int *ptr;
3197 /* we search the first '##' */
3198 for (ptr = ptr0;;) {
3199 TOK_GET(&t, &ptr, &cval);
3200 if (t == TOK_PPJOIN)
3201 break;
3202 if (t == 0)
3203 return NULL;
3206 tok_str_new(&macro_str1);
3208 //tok_print(" $$$", ptr0);
3209 for (ptr = ptr0;;) {
3210 TOK_GET(&t, &ptr, &cval);
3211 if (t == 0)
3212 break;
3213 if (t == TOK_PPJOIN)
3214 continue;
3215 while (*ptr == TOK_PPJOIN) {
3216 int t1; CValue cv1;
3217 /* given 'a##b', remove nosubsts preceding 'a' */
3218 if (start_of_nosubsts >= 0)
3219 macro_str1.len = start_of_nosubsts;
3220 /* given 'a##b', remove nosubsts preceding 'b' */
3221 while ((t1 = *++ptr) == TOK_NOSUBST)
3223 if (t1 && t1 != TOK_PPJOIN) {
3224 TOK_GET(&t1, &ptr, &cv1);
3225 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3226 if (paste_tokens(t, &cval, t1, &cv1)) {
3227 t = tok, cval = tokc;
3228 } else {
3229 tok_str_add2(&macro_str1, t, &cval);
3230 t = t1, cval = cv1;
3235 if (t == TOK_NOSUBST) {
3236 if (start_of_nosubsts < 0)
3237 start_of_nosubsts = macro_str1.len;
3238 } else {
3239 start_of_nosubsts = -1;
3241 tok_str_add2(&macro_str1, t, &cval);
3243 tok_str_add(&macro_str1, 0);
3244 //tok_print(" ###", macro_str1.str);
3245 return macro_str1.str;
3248 /* peek or read [ws_str == NULL] next token from function macro call,
3249 walking up macro levels up to the file if necessary */
3250 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3252 int t;
3253 const int *p;
3254 Sym *sa;
3256 for (;;) {
3257 if (macro_ptr) {
3258 p = macro_ptr, t = *p;
3259 if (ws_str) {
3260 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3261 tok_str_add(ws_str, t), t = *++p;
3263 if (t == 0) {
3264 end_macro();
3265 /* also, end of scope for nested defined symbol */
3266 sa = *nested_list;
3267 while (sa && sa->v == 0)
3268 sa = sa->prev;
3269 if (sa)
3270 sa->v = 0;
3271 continue;
3273 } else {
3274 ch = handle_eob();
3275 if (ws_str) {
3276 while (is_space(ch) || ch == '\n' || ch == '/') {
3277 if (ch == '/') {
3278 int c;
3279 uint8_t *p = file->buf_ptr;
3280 PEEKC(c, p);
3281 if (c == '*') {
3282 p = parse_comment(p);
3283 file->buf_ptr = p - 1;
3284 } else if (c == '/') {
3285 p = parse_line_comment(p);
3286 file->buf_ptr = p - 1;
3287 } else
3288 break;
3289 ch = ' ';
3291 if (ch == '\n')
3292 file->line_num++;
3293 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3294 tok_str_add(ws_str, ch);
3295 cinp();
3298 t = ch;
3301 if (ws_str)
3302 return t;
3303 next_nomacro();
3304 return tok;
3308 /* do macro substitution of current token with macro 's' and add
3309 result to (tok_str,tok_len). 'nested_list' is the list of all
3310 macros we got inside to avoid recursing. Return non zero if no
3311 substitution needs to be done */
3312 static int macro_subst_tok(
3313 TokenString *tok_str,
3314 Sym **nested_list,
3315 Sym *s)
3317 Sym *args, *sa, *sa1;
3318 int parlevel, t, t1, spc;
3319 TokenString str;
3320 char *cstrval;
3321 CValue cval;
3322 CString cstr;
3323 char buf[32];
3325 /* if symbol is a macro, prepare substitution */
3326 /* special macros */
3327 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3328 t = tok == TOK___LINE__ ? file->line_num : pp_counter++;
3329 snprintf(buf, sizeof(buf), "%d", t);
3330 cstrval = buf;
3331 t1 = TOK_PPNUM;
3332 goto add_cstr1;
3333 } else if (tok == TOK___FILE__) {
3334 cstrval = file->filename;
3335 goto add_cstr;
3336 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3337 time_t ti;
3338 struct tm *tm;
3340 time(&ti);
3341 tm = localtime(&ti);
3342 if (tok == TOK___DATE__) {
3343 snprintf(buf, sizeof(buf), "%s %2d %d",
3344 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3345 } else {
3346 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3347 tm->tm_hour, tm->tm_min, tm->tm_sec);
3349 cstrval = buf;
3350 add_cstr:
3351 t1 = TOK_STR;
3352 add_cstr1:
3353 cstr_new(&cstr);
3354 cstr_cat(&cstr, cstrval, 0);
3355 cval.str.size = cstr.size;
3356 cval.str.data = cstr.data;
3357 tok_str_add2(tok_str, t1, &cval);
3358 cstr_free(&cstr);
3359 } else if (s->d) {
3360 int saved_parse_flags = parse_flags;
3361 int *joined_str = NULL;
3362 int *mstr = s->d;
3364 if (s->type.t == MACRO_FUNC) {
3365 /* whitespace between macro name and argument list */
3366 TokenString ws_str;
3367 tok_str_new(&ws_str);
3369 spc = 0;
3370 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3371 | PARSE_FLAG_ACCEPT_STRAYS;
3373 /* get next token from argument stream */
3374 t = next_argstream(nested_list, &ws_str);
3375 if (t != '(') {
3376 /* not a macro substitution after all, restore the
3377 * macro token plus all whitespace we've read.
3378 * whitespace is intentionally not merged to preserve
3379 * newlines. */
3380 parse_flags = saved_parse_flags;
3381 tok_str_add(tok_str, tok);
3382 if (parse_flags & PARSE_FLAG_SPACES) {
3383 int i;
3384 for (i = 0; i < ws_str.len; i++)
3385 tok_str_add(tok_str, ws_str.str[i]);
3387 tok_str_free_str(ws_str.str);
3388 return 0;
3389 } else {
3390 tok_str_free_str(ws_str.str);
3392 do {
3393 next_nomacro(); /* eat '(' */
3394 } while (tok == TOK_PLCHLDR || is_space(tok));
3396 /* argument macro */
3397 args = NULL;
3398 sa = s->next;
3399 /* NOTE: empty args are allowed, except if no args */
3400 for(;;) {
3401 do {
3402 next_argstream(nested_list, NULL);
3403 } while (is_space(tok) || TOK_LINEFEED == tok);
3404 empty_arg:
3405 /* handle '()' case */
3406 if (!args && !sa && tok == ')')
3407 break;
3408 if (!sa)
3409 tcc_error("macro '%s' used with too many args",
3410 get_tok_str(s->v, 0));
3411 tok_str_new(&str);
3412 parlevel = spc = 0;
3413 /* NOTE: non zero sa->t indicates VA_ARGS */
3414 while ((parlevel > 0 ||
3415 (tok != ')' &&
3416 (tok != ',' || sa->type.t)))) {
3417 if (tok == TOK_EOF || tok == 0)
3418 break;
3419 if (tok == '(')
3420 parlevel++;
3421 else if (tok == ')')
3422 parlevel--;
3423 if (tok == TOK_LINEFEED)
3424 tok = ' ';
3425 if (!check_space(tok, &spc))
3426 tok_str_add2(&str, tok, &tokc);
3427 next_argstream(nested_list, NULL);
3429 if (parlevel)
3430 expect(")");
3431 str.len -= spc;
3432 tok_str_add(&str, -1);
3433 tok_str_add(&str, 0);
3434 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3435 sa1->d = str.str;
3436 sa = sa->next;
3437 if (tok == ')') {
3438 /* special case for gcc var args: add an empty
3439 var arg argument if it is omitted */
3440 if (sa && sa->type.t && gnu_ext)
3441 goto empty_arg;
3442 break;
3444 if (tok != ',')
3445 expect(",");
3447 if (sa) {
3448 tcc_error("macro '%s' used with too few args",
3449 get_tok_str(s->v, 0));
3452 /* now subst each arg */
3453 mstr = macro_arg_subst(nested_list, mstr, args);
3454 /* free memory */
3455 sa = args;
3456 while (sa) {
3457 sa1 = sa->prev;
3458 tok_str_free_str(sa->d);
3459 if (sa->next) {
3460 tok_str_free_str(sa->next->d);
3461 sym_free(sa->next);
3463 sym_free(sa);
3464 sa = sa1;
3466 parse_flags = saved_parse_flags;
3469 sym_push2(nested_list, s->v, 0, 0);
3470 parse_flags = saved_parse_flags;
3471 joined_str = macro_twosharps(mstr);
3472 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3474 /* pop nested defined symbol */
3475 sa1 = *nested_list;
3476 *nested_list = sa1->prev;
3477 sym_free(sa1);
3478 if (joined_str)
3479 tok_str_free_str(joined_str);
3480 if (mstr != s->d)
3481 tok_str_free_str(mstr);
3483 return 0;
3486 /* do macro substitution of macro_str and add result to
3487 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3488 inside to avoid recursing. */
3489 static void macro_subst(
3490 TokenString *tok_str,
3491 Sym **nested_list,
3492 const int *macro_str
3495 Sym *s;
3496 int t, spc, nosubst;
3497 CValue cval;
3499 spc = nosubst = 0;
3501 while (1) {
3502 TOK_GET(&t, &macro_str, &cval);
3503 if (t <= 0)
3504 break;
3506 if (t >= TOK_IDENT && 0 == nosubst) {
3507 s = define_find(t);
3508 if (s == NULL)
3509 goto no_subst;
3511 /* if nested substitution, do nothing */
3512 if (sym_find2(*nested_list, t)) {
3513 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3514 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3515 goto no_subst;
3519 TokenString *str = tok_str_alloc();
3520 str->str = (int*)macro_str;
3521 begin_macro(str, 2);
3523 tok = t;
3524 macro_subst_tok(tok_str, nested_list, s);
3526 if (macro_stack != str) {
3527 /* already finished by reading function macro arguments */
3528 break;
3531 macro_str = macro_ptr;
3532 end_macro ();
3534 if (tok_str->len)
3535 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3536 } else {
3537 no_subst:
3538 if (!check_space(t, &spc))
3539 tok_str_add2(tok_str, t, &cval);
3541 if (nosubst) {
3542 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3543 continue;
3544 nosubst = 0;
3546 if (t == TOK_NOSUBST)
3547 nosubst = 1;
3549 /* GCC supports 'defined' as result of a macro substitution */
3550 if (t == TOK_DEFINED && pp_expr)
3551 nosubst = 2;
3555 /* return next token without macro substitution. Can read input from
3556 macro_ptr buffer */
3557 static void next_nomacro(void)
3559 int t;
3560 if (macro_ptr) {
3561 redo:
3562 t = *macro_ptr;
3563 if (TOK_HAS_VALUE(t)) {
3564 tok_get(&tok, &macro_ptr, &tokc);
3565 if (t == TOK_LINENUM) {
3566 file->line_num = tokc.i;
3567 goto redo;
3569 } else {
3570 macro_ptr++;
3571 if (t < TOK_IDENT) {
3572 if (!(parse_flags & PARSE_FLAG_SPACES)
3573 && (isidnum_table[t - CH_EOF] & IS_SPC))
3574 goto redo;
3576 tok = t;
3578 } else {
3579 next_nomacro1();
3583 /* return next token with macro substitution */
3584 ST_FUNC void next(void)
3586 int t;
3587 redo:
3588 next_nomacro();
3589 t = tok;
3590 if (macro_ptr) {
3591 if (!TOK_HAS_VALUE(t)) {
3592 if (t == TOK_NOSUBST || t == TOK_PLCHLDR) {
3593 /* discard preprocessor markers */
3594 goto redo;
3595 } else if (t == 0) {
3596 /* end of macro or unget token string */
3597 end_macro();
3598 goto redo;
3599 } else if (t == '\\') {
3600 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3601 tcc_error("stray '\\' in program");
3603 return;
3605 } else if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3606 /* if reading from file, try to substitute macros */
3607 Sym *s = define_find(t);
3608 if (s) {
3609 Sym *nested_list = NULL;
3610 tokstr_buf.len = 0;
3611 macro_subst_tok(&tokstr_buf, &nested_list, s);
3612 tok_str_add(&tokstr_buf, 0);
3613 begin_macro(&tokstr_buf, 0);
3614 goto redo;
3616 return;
3618 /* convert preprocessor tokens into C tokens */
3619 if (t == TOK_PPNUM) {
3620 if (parse_flags & PARSE_FLAG_TOK_NUM)
3621 parse_number((char *)tokc.str.data);
3622 } else if (t == TOK_PPSTR) {
3623 if (parse_flags & PARSE_FLAG_TOK_STR)
3624 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3628 /* push back current token and set current token to 'last_tok'. Only
3629 identifier case handled for labels. */
3630 ST_INLN void unget_tok(int last_tok)
3633 TokenString *str = tok_str_alloc();
3634 tok_str_add2(str, tok, &tokc);
3635 tok_str_add(str, 0);
3636 begin_macro(str, 1);
3637 tok = last_tok;
3640 /* ------------------------------------------------------------------------- */
3641 /* init preprocessor */
3643 static const char *target_os_defs =
3644 #ifdef TCC_TARGET_PE
3645 "_WIN32\0"
3646 # if PTR_SIZE == 8
3647 "_WIN64\0"
3648 # endif
3649 #else
3650 # if defined TCC_TARGET_MACHO
3651 "__APPLE__\0"
3652 # elif TARGETOS_FreeBSD
3653 "__FreeBSD__ 12\0"
3654 # elif TARGETOS_FreeBSD_kernel
3655 "__FreeBSD_kernel__\0"
3656 # elif TARGETOS_NetBSD
3657 "__NetBSD__\0"
3658 # elif TARGETOS_OpenBSD
3659 "__OpenBSD__\0"
3660 # else
3661 "__linux__\0"
3662 "__linux\0"
3663 # endif
3664 "__unix__\0"
3665 "__unix\0"
3666 #endif
3669 static void putdef(CString *cs, const char *p)
3671 cstr_printf(cs, "#define %s%s\n", p, &" 1"[!!strchr(p, ' ')*2]);
3674 static void tcc_predefs(TCCState *s1, CString *cs, int is_asm)
3676 int a, b, c;
3677 const char *defs[] = { target_machine_defs, target_os_defs, NULL };
3678 const char *p;
3680 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
3681 cstr_printf(cs, "#define __TINYC__ %d\n", a*10000 + b*100 + c);
3682 for (a = 0; defs[a]; ++a)
3683 for (p = defs[a]; *p; p = strchr(p, 0) + 1)
3684 putdef(cs, p);
3685 #ifdef TCC_TARGET_ARM
3686 if (s1->float_abi == ARM_HARD_FLOAT)
3687 putdef(cs, "__ARM_PCS_VFP");
3688 #endif
3689 if (is_asm)
3690 putdef(cs, "__ASSEMBLER__");
3691 if (s1->output_type == TCC_OUTPUT_PREPROCESS)
3692 putdef(cs, "__TCC_PP__");
3693 if (s1->output_type == TCC_OUTPUT_MEMORY)
3694 putdef(cs, "__TCC_RUN__");
3695 if (s1->char_is_unsigned)
3696 putdef(cs, "__CHAR_UNSIGNED__");
3697 if (s1->optimize > 0)
3698 putdef(cs, "__OPTIMIZE__");
3699 if (s1->option_pthread)
3700 putdef(cs, "_REENTRANT");
3701 if (s1->leading_underscore)
3702 putdef(cs, "__leading_underscore");
3703 #ifdef CONFIG_TCC_BCHECK
3704 if (s1->do_bounds_check)
3705 putdef(cs, "__BOUNDS_CHECKING_ON");
3706 #endif
3707 cstr_printf(cs, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE);
3708 cstr_printf(cs, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE);
3709 if (!is_asm) {
3710 putdef(cs, "__STDC__");
3711 cstr_printf(cs, "#define __STDC_VERSION__ %dL\n", s1->cversion);
3712 cstr_cat(cs,
3713 /* load more predefs and __builtins */
3714 #if CONFIG_TCC_PREDEFS
3715 #include "tccdefs_.h" /* include as strings */
3716 #else
3717 "#include <tccdefs.h>\n" /* load at runtime */
3718 #endif
3719 , -1);
3721 cstr_printf(cs, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3724 ST_FUNC void preprocess_start(TCCState *s1, int filetype)
3726 int is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
3727 CString cstr;
3729 tccpp_new(s1);
3731 s1->include_stack_ptr = s1->include_stack;
3732 s1->ifdef_stack_ptr = s1->ifdef_stack;
3733 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3734 pp_expr = 0;
3735 pp_counter = 0;
3736 pp_debug_tok = pp_debug_symv = 0;
3737 pp_once++;
3738 s1->pack_stack[0] = 0;
3739 s1->pack_stack_ptr = s1->pack_stack;
3741 set_idnum('$', !is_asm && s1->dollars_in_identifiers ? IS_ID : 0);
3742 set_idnum('.', is_asm ? IS_ID : 0);
3744 if (!(filetype & AFF_TYPE_ASM)) {
3745 cstr_new(&cstr);
3746 tcc_predefs(s1, &cstr, is_asm);
3747 if (s1->cmdline_defs.size)
3748 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3749 if (s1->cmdline_incl.size)
3750 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3751 //printf("%s\n", (char*)cstr.data);
3752 *s1->include_stack_ptr++ = file;
3753 tcc_open_bf(s1, "<command line>", cstr.size);
3754 memcpy(file->buffer, cstr.data, cstr.size);
3755 cstr_free(&cstr);
3758 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3759 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3762 /* cleanup from error/setjmp */
3763 ST_FUNC void preprocess_end(TCCState *s1)
3765 while (macro_stack)
3766 end_macro();
3767 macro_ptr = NULL;
3768 while (file)
3769 tcc_close();
3770 tccpp_delete(s1);
3773 ST_FUNC void tccpp_new(TCCState *s)
3775 int i, c;
3776 const char *p, *r;
3778 /* init isid table */
3779 for(i = CH_EOF; i<128; i++)
3780 set_idnum(i,
3781 is_space(i) ? IS_SPC
3782 : isid(i) ? IS_ID
3783 : isnum(i) ? IS_NUM
3784 : 0);
3786 for(i = 128; i<256; i++)
3787 set_idnum(i, IS_ID);
3789 /* init allocators */
3790 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3791 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3793 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3794 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3796 cstr_new(&cstr_buf);
3797 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3798 tok_str_new(&tokstr_buf);
3799 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3801 tok_ident = TOK_IDENT;
3802 p = tcc_keywords;
3803 while (*p) {
3804 r = p;
3805 for(;;) {
3806 c = *r++;
3807 if (c == '\0')
3808 break;
3810 tok_alloc(p, r - p - 1);
3811 p = r;
3814 /* we add dummy defines for some special macros to speed up tests
3815 and to have working defined() */
3816 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3817 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3818 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3819 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3820 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3823 ST_FUNC void tccpp_delete(TCCState *s)
3825 int i, n;
3827 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3829 /* free tokens */
3830 n = tok_ident - TOK_IDENT;
3831 if (n > total_idents)
3832 total_idents = n;
3833 for(i = 0; i < n; i++)
3834 tal_free(toksym_alloc, table_ident[i]);
3835 tcc_free(table_ident);
3836 table_ident = NULL;
3838 /* free static buffers */
3839 cstr_free(&tokcstr);
3840 cstr_free(&cstr_buf);
3841 cstr_free(&macro_equal_buf);
3842 tok_str_free_str(tokstr_buf.str);
3844 /* free allocators */
3845 tal_delete(toksym_alloc);
3846 toksym_alloc = NULL;
3847 tal_delete(tokstr_alloc);
3848 tokstr_alloc = NULL;
3851 /* ------------------------------------------------------------------------- */
3852 /* tcc -E [-P[1]] [-dD} support */
3854 static void tok_print(const char *msg, const int *str)
3856 FILE *fp;
3857 int t, s = 0;
3858 CValue cval;
3860 fp = tcc_state->ppfp;
3861 fprintf(fp, "%s", msg);
3862 while (str) {
3863 TOK_GET(&t, &str, &cval);
3864 if (!t)
3865 break;
3866 fprintf(fp, &" %s"[s], get_tok_str(t, &cval)), s = 1;
3868 fprintf(fp, "\n");
3871 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3873 int d = f->line_num - f->line_ref;
3875 if (s1->dflag & 4)
3876 return;
3878 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3880 } else if (level == 0 && f->line_ref && d < 8) {
3881 while (d > 0)
3882 fputs("\n", s1->ppfp), --d;
3883 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3884 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3885 } else {
3886 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3887 level > 0 ? " 1" : level < 0 ? " 2" : "");
3889 f->line_ref = f->line_num;
3892 static void define_print(TCCState *s1, int v)
3894 FILE *fp;
3895 Sym *s;
3897 s = define_find(v);
3898 if (NULL == s || NULL == s->d)
3899 return;
3901 fp = s1->ppfp;
3902 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3903 if (s->type.t == MACRO_FUNC) {
3904 Sym *a = s->next;
3905 fprintf(fp,"(");
3906 if (a)
3907 for (;;) {
3908 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3909 if (!(a = a->next))
3910 break;
3911 fprintf(fp,",");
3913 fprintf(fp,")");
3915 tok_print("", s->d);
3918 static void pp_debug_defines(TCCState *s1)
3920 int v, t;
3921 const char *vs;
3922 FILE *fp;
3924 t = pp_debug_tok;
3925 if (t == 0)
3926 return;
3928 file->line_num--;
3929 pp_line(s1, file, 0);
3930 file->line_ref = ++file->line_num;
3932 fp = s1->ppfp;
3933 v = pp_debug_symv;
3934 vs = get_tok_str(v, NULL);
3935 if (t == TOK_DEFINE) {
3936 define_print(s1, v);
3937 } else if (t == TOK_UNDEF) {
3938 fprintf(fp, "#undef %s\n", vs);
3939 } else if (t == TOK_push_macro) {
3940 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3941 } else if (t == TOK_pop_macro) {
3942 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3944 pp_debug_tok = 0;
3947 static void pp_debug_builtins(TCCState *s1)
3949 int v;
3950 for (v = TOK_IDENT; v < tok_ident; ++v)
3951 define_print(s1, v);
3954 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3955 static int pp_need_space(int a, int b)
3957 return 'E' == a ? '+' == b || '-' == b
3958 : '+' == a ? TOK_INC == b || '+' == b
3959 : '-' == a ? TOK_DEC == b || '-' == b
3960 : a >= TOK_IDENT ? b >= TOK_IDENT
3961 : a == TOK_PPNUM ? b >= TOK_IDENT
3962 : 0;
3965 /* maybe hex like 0x1e */
3966 static int pp_check_he0xE(int t, const char *p)
3968 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3969 return 'E';
3970 return t;
3973 /* Preprocess the current file */
3974 ST_FUNC int tcc_preprocess(TCCState *s1)
3976 BufferedFile **iptr;
3977 int token_seen, spcs, level;
3978 const char *p;
3979 char white[400];
3981 parse_flags = PARSE_FLAG_PREPROCESS
3982 | (parse_flags & PARSE_FLAG_ASM_FILE)
3983 | PARSE_FLAG_LINEFEED
3984 | PARSE_FLAG_SPACES
3985 | PARSE_FLAG_ACCEPT_STRAYS
3987 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3988 capability to compile and run itself, provided all numbers are
3989 given as decimals. tcc -E -P10 will do. */
3990 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3991 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3993 if (s1->do_bench) {
3994 /* for PP benchmarks */
3995 do next(); while (tok != TOK_EOF);
3996 return 0;
3999 if (s1->dflag & 1) {
4000 pp_debug_builtins(s1);
4001 s1->dflag &= ~1;
4004 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
4005 if (file->prev)
4006 pp_line(s1, file->prev, level++);
4007 pp_line(s1, file, level);
4008 for (;;) {
4009 iptr = s1->include_stack_ptr;
4010 next();
4011 if (tok == TOK_EOF)
4012 break;
4014 level = s1->include_stack_ptr - iptr;
4015 if (level) {
4016 if (level > 0)
4017 pp_line(s1, *iptr, 0);
4018 pp_line(s1, file, level);
4020 if (s1->dflag & 7) {
4021 pp_debug_defines(s1);
4022 if (s1->dflag & 4)
4023 continue;
4026 if (is_space(tok)) {
4027 if (spcs < sizeof white - 1)
4028 white[spcs++] = tok;
4029 continue;
4030 } else if (tok == TOK_LINEFEED) {
4031 spcs = 0;
4032 if (token_seen == TOK_LINEFEED)
4033 continue;
4034 ++file->line_ref;
4035 } else if (token_seen == TOK_LINEFEED) {
4036 pp_line(s1, file, 0);
4037 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
4038 white[spcs++] = ' ';
4041 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
4042 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
4043 token_seen = pp_check_he0xE(tok, p);
4045 return 0;
4048 /* ------------------------------------------------------------------------- */