Allow different names for pragma once
[tinycc.git] / tccpp.c
bloba2fafddfbb3c33d93dc2348abcc3cca96b1e68a1
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #define USING_GLOBALS
22 #include "tcc.h"
24 /* #define to 1 to enable (see parse_pp_string()) */
25 #define ACCEPT_LF_IN_STRINGS 0
27 /********************************************************/
28 /* global variables */
30 ST_DATA int tok_flags;
31 ST_DATA int parse_flags;
33 ST_DATA struct BufferedFile *file;
34 ST_DATA int tok;
35 ST_DATA CValue tokc;
36 ST_DATA const int *macro_ptr;
37 ST_DATA CString tokcstr; /* current parsed string, if any */
39 /* display benchmark infos */
40 ST_DATA int tok_ident;
41 ST_DATA TokenSym **table_ident;
43 /* ------------------------------------------------------------------------- */
45 static TokenSym *hash_ident[TOK_HASH_SIZE];
46 static char token_buf[STRING_MAX_SIZE + 1];
47 static CString cstr_buf;
48 static TokenString tokstr_buf;
49 static unsigned char isidnum_table[256 - CH_EOF];
50 static int pp_debug_tok, pp_debug_symv;
51 static int pp_once;
52 static int pp_expr;
53 static int pp_counter;
54 static void tok_print(const char *msg, const int *str);
56 static struct TinyAlloc *toksym_alloc;
57 static struct TinyAlloc *tokstr_alloc;
59 static TokenString *macro_stack;
61 static const char tcc_keywords[] =
62 #define DEF(id, str) str "\0"
63 #include "tcctok.h"
64 #undef DEF
67 /* WARNING: the content of this string encodes token numbers */
68 static const unsigned char tok_two_chars[] =
69 /* outdated -- gr
70 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
71 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
72 */{
73 '<','=', TOK_LE,
74 '>','=', TOK_GE,
75 '!','=', TOK_NE,
76 '&','&', TOK_LAND,
77 '|','|', TOK_LOR,
78 '+','+', TOK_INC,
79 '-','-', TOK_DEC,
80 '=','=', TOK_EQ,
81 '<','<', TOK_SHL,
82 '>','>', TOK_SAR,
83 '+','=', TOK_A_ADD,
84 '-','=', TOK_A_SUB,
85 '*','=', TOK_A_MUL,
86 '/','=', TOK_A_DIV,
87 '%','=', TOK_A_MOD,
88 '&','=', TOK_A_AND,
89 '^','=', TOK_A_XOR,
90 '|','=', TOK_A_OR,
91 '-','>', TOK_ARROW,
92 '.','.', TOK_TWODOTS,
93 '#','#', TOK_TWOSHARPS,
94 '#','#', TOK_PPJOIN,
98 static void next_nomacro(void);
100 ST_FUNC void skip(int c)
102 if (tok != c)
103 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
104 next();
107 ST_FUNC void expect(const char *msg)
109 tcc_error("%s expected", msg);
112 /* ------------------------------------------------------------------------- */
113 /* Custom allocator for tiny objects */
115 #define USE_TAL
117 #ifndef USE_TAL
118 #define tal_free(al, p) tcc_free(p)
119 #define tal_realloc(al, p, size) tcc_realloc(p, size)
120 #define tal_new(a,b,c)
121 #define tal_delete(a)
122 #else
123 #if !defined(MEM_DEBUG)
124 #define tal_free(al, p) tal_free_impl(al, p)
125 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
126 #define TAL_DEBUG_PARAMS
127 #else
128 #define TAL_DEBUG 1
129 //#define TAL_INFO 1 /* collect and dump allocators stats */
130 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
131 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
132 #define TAL_DEBUG_PARAMS , const char *file, int line
133 #define TAL_DEBUG_FILE_LEN 40
134 #endif
136 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
137 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
138 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
139 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
140 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
141 #define CSTR_TAL_LIMIT 1024
143 typedef struct TinyAlloc {
144 unsigned limit;
145 unsigned size;
146 uint8_t *buffer;
147 uint8_t *p;
148 unsigned nb_allocs;
149 struct TinyAlloc *next, *top;
150 #ifdef TAL_INFO
151 unsigned nb_peak;
152 unsigned nb_total;
153 unsigned nb_missed;
154 uint8_t *peak_p;
155 #endif
156 } TinyAlloc;
158 typedef struct tal_header_t {
159 unsigned size;
160 #ifdef TAL_DEBUG
161 int line_num; /* negative line_num used for double free check */
162 char file_name[TAL_DEBUG_FILE_LEN + 1];
163 #endif
164 } tal_header_t;
166 /* ------------------------------------------------------------------------- */
168 static TinyAlloc *tal_new(TinyAlloc **pal, unsigned limit, unsigned size)
170 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
171 al->p = al->buffer = tcc_malloc(size);
172 al->limit = limit;
173 al->size = size;
174 if (pal) *pal = al;
175 return al;
178 static void tal_delete(TinyAlloc *al)
180 TinyAlloc *next;
182 tail_call:
183 if (!al)
184 return;
185 #ifdef TAL_INFO
186 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
187 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
188 (al->peak_p - al->buffer) * 100.0 / al->size);
189 #endif
190 #ifdef TAL_DEBUG
191 if (al->nb_allocs > 0) {
192 uint8_t *p;
193 fprintf(stderr, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
194 al->nb_allocs, al->limit);
195 p = al->buffer;
196 while (p < al->p) {
197 tal_header_t *header = (tal_header_t *)p;
198 if (header->line_num > 0) {
199 fprintf(stderr, "%s:%d: chunk of %d bytes leaked\n",
200 header->file_name, header->line_num, header->size);
202 p += header->size + sizeof(tal_header_t);
204 #if MEM_DEBUG-0 == 2
205 exit(2);
206 #endif
208 #endif
209 next = al->next;
210 tcc_free(al->buffer);
211 tcc_free(al);
212 al = next;
213 goto tail_call;
216 static void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
218 if (!p)
219 return;
220 tail_call:
221 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
222 #ifdef TAL_DEBUG
223 tal_header_t *header = (((tal_header_t *)p) - 1);
224 if (header->line_num < 0) {
225 fprintf(stderr, "%s:%d: TAL_DEBUG: double frees chunk from\n",
226 file, line);
227 fprintf(stderr, "%s:%d: %d bytes\n",
228 header->file_name, (int)-header->line_num, (int)header->size);
229 } else
230 header->line_num = -header->line_num;
231 #endif
232 al->nb_allocs--;
233 if (!al->nb_allocs)
234 al->p = al->buffer;
235 } else if (al->next) {
236 al = al->next;
237 goto tail_call;
239 else
240 tcc_free(p);
243 static void *tal_realloc_impl(TinyAlloc **pal, void *p, unsigned size TAL_DEBUG_PARAMS)
245 tal_header_t *header;
246 void *ret;
247 int is_own;
248 unsigned adj_size = (size + 3) & -4;
249 TinyAlloc *al = *pal;
251 tail_call:
252 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
253 if ((!p || is_own) && size <= al->limit) {
254 if (al->p - al->buffer + adj_size + sizeof(tal_header_t) < al->size) {
255 header = (tal_header_t *)al->p;
256 header->size = adj_size;
257 #ifdef TAL_DEBUG
258 { int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
259 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
260 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
261 header->line_num = line; }
262 #endif
263 ret = al->p + sizeof(tal_header_t);
264 al->p += adj_size + sizeof(tal_header_t);
265 if (is_own) {
266 header = (((tal_header_t *)p) - 1);
267 if (p) memcpy(ret, p, header->size);
268 #ifdef TAL_DEBUG
269 header->line_num = -header->line_num;
270 #endif
271 } else {
272 al->nb_allocs++;
274 #ifdef TAL_INFO
275 if (al->nb_peak < al->nb_allocs)
276 al->nb_peak = al->nb_allocs;
277 if (al->peak_p < al->p)
278 al->peak_p = al->p;
279 al->nb_total++;
280 #endif
281 return ret;
282 } else if (is_own) {
283 al->nb_allocs--;
284 ret = tal_realloc(*pal, 0, size);
285 header = (((tal_header_t *)p) - 1);
286 if (p) memcpy(ret, p, header->size);
287 #ifdef TAL_DEBUG
288 header->line_num = -header->line_num;
289 #endif
290 return ret;
292 if (al->next) {
293 al = al->next;
294 } else {
295 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
297 al = tal_new(pal, next->limit, next->size * 2);
298 al->next = next;
299 bottom->top = al;
301 goto tail_call;
303 if (is_own) {
304 al->nb_allocs--;
305 ret = tcc_malloc(size);
306 header = (((tal_header_t *)p) - 1);
307 if (p) memcpy(ret, p, header->size);
308 #ifdef TAL_DEBUG
309 header->line_num = -header->line_num;
310 #endif
311 } else if (al->next) {
312 al = al->next;
313 goto tail_call;
314 } else
315 ret = tcc_realloc(p, size);
316 #ifdef TAL_INFO
317 al->nb_missed++;
318 #endif
319 return ret;
322 #endif /* USE_TAL */
324 /* ------------------------------------------------------------------------- */
325 /* CString handling */
326 static void cstr_realloc(CString *cstr, int new_size)
328 int size;
330 size = cstr->size_allocated;
331 if (size < 8)
332 size = 8; /* no need to allocate a too small first string */
333 while (size < new_size)
334 size = size * 2;
335 cstr->data = tcc_realloc(cstr->data, size);
336 cstr->size_allocated = size;
339 /* add a byte */
340 ST_INLN void cstr_ccat(CString *cstr, int ch)
342 int size;
343 size = cstr->size + 1;
344 if (size > cstr->size_allocated)
345 cstr_realloc(cstr, size);
346 ((unsigned char *)cstr->data)[size - 1] = ch;
347 cstr->size = size;
350 ST_INLN char *unicode_to_utf8 (char *b, uint32_t Uc)
352 if (Uc<0x80) *b++=Uc;
353 else if (Uc<0x800) *b++=192+Uc/64, *b++=128+Uc%64;
354 else if (Uc-0xd800u<0x800) goto error;
355 else if (Uc<0x10000) *b++=224+Uc/4096, *b++=128+Uc/64%64, *b++=128+Uc%64;
356 else if (Uc<0x110000) *b++=240+Uc/262144, *b++=128+Uc/4096%64, *b++=128+Uc/64%64, *b++=128+Uc%64;
357 else error: tcc_error("0x%x is not a valid universal character", Uc);
358 return b;
361 /* add a unicode character expanded into utf8 */
362 ST_INLN void cstr_u8cat(CString *cstr, int ch)
364 char buf[4], *e;
365 e = unicode_to_utf8(buf, (uint32_t)ch);
366 cstr_cat(cstr, buf, e - buf);
369 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
371 int size;
372 if (len <= 0)
373 len = strlen(str) + 1 + len;
374 size = cstr->size + len;
375 if (size > cstr->size_allocated)
376 cstr_realloc(cstr, size);
377 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
378 cstr->size = size;
381 /* add a wide char */
382 ST_FUNC void cstr_wccat(CString *cstr, int ch)
384 int size;
385 size = cstr->size + sizeof(nwchar_t);
386 if (size > cstr->size_allocated)
387 cstr_realloc(cstr, size);
388 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
389 cstr->size = size;
392 ST_FUNC void cstr_new(CString *cstr)
394 memset(cstr, 0, sizeof(CString));
397 /* free string and reset it to NULL */
398 ST_FUNC void cstr_free(CString *cstr)
400 tcc_free(cstr->data);
403 /* reset string to empty */
404 ST_FUNC void cstr_reset(CString *cstr)
406 cstr->size = 0;
409 ST_FUNC int cstr_vprintf(CString *cstr, const char *fmt, va_list ap)
411 va_list v;
412 int len, size = 80;
413 for (;;) {
414 size += cstr->size;
415 if (size > cstr->size_allocated)
416 cstr_realloc(cstr, size);
417 size = cstr->size_allocated - cstr->size;
418 va_copy(v, ap);
419 len = vsnprintf((char*)cstr->data + cstr->size, size, fmt, v);
420 va_end(v);
421 if (len >= 0 && len < size)
422 break;
423 size *= 2;
425 cstr->size += len;
426 return len;
429 ST_FUNC int cstr_printf(CString *cstr, const char *fmt, ...)
431 va_list ap; int len;
432 va_start(ap, fmt);
433 len = cstr_vprintf(cstr, fmt, ap);
434 va_end(ap);
435 return len;
438 /* XXX: unicode ? */
439 static void add_char(CString *cstr, int c)
441 if (c == '\'' || c == '\"' || c == '\\') {
442 /* XXX: could be more precise if char or string */
443 cstr_ccat(cstr, '\\');
445 if (c >= 32 && c <= 126) {
446 cstr_ccat(cstr, c);
447 } else {
448 cstr_ccat(cstr, '\\');
449 if (c == '\n') {
450 cstr_ccat(cstr, 'n');
451 } else {
452 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
453 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
454 cstr_ccat(cstr, '0' + (c & 7));
459 /* ------------------------------------------------------------------------- */
460 /* allocate a new token */
461 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
463 TokenSym *ts, **ptable;
464 int i;
466 if (tok_ident >= SYM_FIRST_ANOM)
467 tcc_error("memory full (symbols)");
469 /* expand token table if needed */
470 i = tok_ident - TOK_IDENT;
471 if ((i % TOK_ALLOC_INCR) == 0) {
472 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
473 table_ident = ptable;
476 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
477 table_ident[i] = ts;
478 ts->tok = tok_ident++;
479 ts->sym_define = NULL;
480 ts->sym_label = NULL;
481 ts->sym_struct = NULL;
482 ts->sym_identifier = NULL;
483 ts->len = len;
484 ts->hash_next = NULL;
485 memcpy(ts->str, str, len);
486 ts->str[len] = '\0';
487 *pts = ts;
488 return ts;
491 #define TOK_HASH_INIT 1
492 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
495 /* find a token and add it if not found */
496 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
498 TokenSym *ts, **pts;
499 int i;
500 unsigned int h;
502 h = TOK_HASH_INIT;
503 for(i=0;i<len;i++)
504 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
505 h &= (TOK_HASH_SIZE - 1);
507 pts = &hash_ident[h];
508 for(;;) {
509 ts = *pts;
510 if (!ts)
511 break;
512 if (ts->len == len && !memcmp(ts->str, str, len))
513 return ts;
514 pts = &(ts->hash_next);
516 return tok_alloc_new(pts, str, len);
519 ST_FUNC int tok_alloc_const(const char *str)
521 return tok_alloc(str, strlen(str))->tok;
525 /* XXX: buffer overflow */
526 /* XXX: float tokens */
527 ST_FUNC const char *get_tok_str(int v, CValue *cv)
529 char *p;
530 int i, len;
532 cstr_reset(&cstr_buf);
533 p = cstr_buf.data;
535 switch(v) {
536 case TOK_CINT:
537 case TOK_CUINT:
538 case TOK_CLONG:
539 case TOK_CULONG:
540 case TOK_CLLONG:
541 case TOK_CULLONG:
542 /* XXX: not quite exact, but only useful for testing */
543 #ifdef _WIN32
544 sprintf(p, "%u", (unsigned)cv->i);
545 #else
546 sprintf(p, "%llu", (unsigned long long)cv->i);
547 #endif
548 break;
549 case TOK_LCHAR:
550 cstr_ccat(&cstr_buf, 'L');
551 case TOK_CCHAR:
552 cstr_ccat(&cstr_buf, '\'');
553 add_char(&cstr_buf, cv->i);
554 cstr_ccat(&cstr_buf, '\'');
555 cstr_ccat(&cstr_buf, '\0');
556 break;
557 case TOK_PPNUM:
558 case TOK_PPSTR:
559 return (char*)cv->str.data;
560 case TOK_LSTR:
561 cstr_ccat(&cstr_buf, 'L');
562 case TOK_STR:
563 cstr_ccat(&cstr_buf, '\"');
564 if (v == TOK_STR) {
565 len = cv->str.size - 1;
566 for(i=0;i<len;i++)
567 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
568 } else {
569 len = (cv->str.size / sizeof(nwchar_t)) - 1;
570 for(i=0;i<len;i++)
571 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
573 cstr_ccat(&cstr_buf, '\"');
574 cstr_ccat(&cstr_buf, '\0');
575 break;
577 case TOK_CFLOAT:
578 return strcpy(p, "<float>");
579 case TOK_CDOUBLE:
580 return strcpy(p, "<double>");
581 case TOK_CLDOUBLE:
582 return strcpy(p, "<long double>");
583 case TOK_LINENUM:
584 return strcpy(p, "<linenumber");
586 /* above tokens have value, the ones below don't */
587 case TOK_LT:
588 v = '<';
589 goto addv;
590 case TOK_GT:
591 v = '>';
592 goto addv;
593 case TOK_DOTS:
594 return strcpy(p, "...");
595 case TOK_A_SHL:
596 return strcpy(p, "<<=");
597 case TOK_A_SAR:
598 return strcpy(p, ">>=");
599 case TOK_EOF:
600 return strcpy(p, "<eof>");
601 case 0: /* anonymous nameless symbols */
602 return strcpy(p, "<no name>");
603 default:
604 if (v < TOK_IDENT) {
605 /* search in two bytes table */
606 const unsigned char *q = tok_two_chars;
607 while (*q) {
608 if (q[2] == v) {
609 *p++ = q[0];
610 *p++ = q[1];
611 *p = '\0';
612 return cstr_buf.data;
614 q += 3;
616 if (v >= 127 || (v < 32 && !is_space(v) && v != '\n')) {
617 sprintf(p, "<\\x%02x>", v);
618 break;
620 addv:
621 *p++ = v;
622 *p = '\0';
623 } else if (v < tok_ident) {
624 return table_ident[v - TOK_IDENT]->str;
625 } else if (v >= SYM_FIRST_ANOM) {
626 /* special name for anonymous symbol */
627 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
628 } else {
629 /* should never happen */
630 return NULL;
632 break;
634 return cstr_buf.data;
637 static inline int check_space(int t, int *spc)
639 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
640 if (*spc)
641 return 1;
642 *spc = 1;
643 } else
644 *spc = 0;
645 return 0;
648 /* return the current character, handling end of block if necessary
649 (but not stray) */
650 static int handle_eob(void)
652 BufferedFile *bf = file;
653 int len;
655 /* only tries to read if really end of buffer */
656 if (bf->buf_ptr >= bf->buf_end) {
657 if (bf->fd >= 0) {
658 #if defined(PARSE_DEBUG)
659 len = 1;
660 #else
661 len = IO_BUF_SIZE;
662 #endif
663 len = read(bf->fd, bf->buffer, len);
664 if (len < 0)
665 len = 0;
666 } else {
667 len = 0;
669 total_bytes += len;
670 bf->buf_ptr = bf->buffer;
671 bf->buf_end = bf->buffer + len;
672 *bf->buf_end = CH_EOB;
674 if (bf->buf_ptr < bf->buf_end) {
675 return bf->buf_ptr[0];
676 } else {
677 bf->buf_ptr = bf->buf_end;
678 return CH_EOF;
682 /* read next char from current input file and handle end of input buffer */
683 static int next_c(void)
685 int ch = *++file->buf_ptr;
686 /* end of buffer/file handling */
687 if (ch == CH_EOB && file->buf_ptr >= file->buf_end)
688 ch = handle_eob();
689 return ch;
692 /* input with '\[\r]\n' handling. */
693 static int handle_stray_noerror(int err)
695 int ch;
696 while ((ch = next_c()) == '\\') {
697 ch = next_c();
698 if (ch == '\n') {
699 newl:
700 file->line_num++;
701 } else {
702 if (ch == '\r') {
703 ch = next_c();
704 if (ch == '\n')
705 goto newl;
706 *--file->buf_ptr = '\r';
708 if (err)
709 tcc_error("stray '\\' in program");
710 /* may take advantage of 'BufferedFile.unget[4}' */
711 return *--file->buf_ptr = '\\';
714 return ch;
717 #define ninp() handle_stray_noerror(0)
719 /* handle '\\' in strings, comments and skipped regions */
720 static int handle_bs(uint8_t **p)
722 int c;
723 file->buf_ptr = *p - 1;
724 c = ninp();
725 *p = file->buf_ptr;
726 return c;
729 /* skip the stray and handle the \\n case. Output an error if
730 incorrect char after the stray */
731 static int handle_stray(uint8_t **p)
733 int c;
734 file->buf_ptr = *p - 1;
735 c = handle_stray_noerror(!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS));
736 *p = file->buf_ptr;
737 return c;
740 /* handle the complicated stray case */
741 #define PEEKC(c, p)\
743 c = *++p;\
744 if (c == '\\')\
745 c = handle_stray(&p); \
748 static int skip_spaces(void)
750 int ch;
751 --file->buf_ptr;
752 do {
753 ch = ninp();
754 } while (isidnum_table[ch - CH_EOF] & IS_SPC);
755 return ch;
758 /* single line C++ comments */
759 static uint8_t *parse_line_comment(uint8_t *p)
761 int c;
762 for(;;) {
763 for (;;) {
764 c = *++p;
765 redo:
766 if (c == '\n' || c == '\\')
767 break;
768 c = *++p;
769 if (c == '\n' || c == '\\')
770 break;
772 if (c == '\n')
773 break;
774 c = handle_bs(&p);
775 if (c == CH_EOF)
776 break;
777 if (c != '\\')
778 goto redo;
780 return p;
783 /* C comments */
784 static uint8_t *parse_comment(uint8_t *p)
786 int c;
787 for(;;) {
788 /* fast skip loop */
789 for(;;) {
790 c = *++p;
791 redo:
792 if (c == '\n' || c == '*' || c == '\\')
793 break;
794 c = *++p;
795 if (c == '\n' || c == '*' || c == '\\')
796 break;
798 /* now we can handle all the cases */
799 if (c == '\n') {
800 file->line_num++;
801 } else if (c == '*') {
802 do {
803 c = *++p;
804 } while (c == '*');
805 if (c == '\\')
806 c = handle_bs(&p);
807 if (c == '/')
808 break;
809 goto check_eof;
810 } else {
811 c = handle_bs(&p);
812 check_eof:
813 if (c == CH_EOF)
814 tcc_error("unexpected end of file in comment");
815 if (c != '\\')
816 goto redo;
819 return p + 1;
822 /* parse a string without interpreting escapes */
823 static uint8_t *parse_pp_string(uint8_t *p, int sep, CString *str)
825 int c;
826 for(;;) {
827 c = *++p;
828 redo:
829 if (c == sep) {
830 break;
831 } else if (c == '\\') {
832 c = handle_bs(&p);
833 if (c == CH_EOF) {
834 unterminated_string:
835 /* XXX: indicate line number of start of string */
836 tok_flags &= ~TOK_FLAG_BOL;
837 tcc_error("missing terminating %c character", sep);
838 } else if (c == '\\') {
839 if (str)
840 cstr_ccat(str, c);
841 c = *++p;
842 /* add char after '\\' unconditionally */
843 if (c == '\\') {
844 c = handle_bs(&p);
845 if (c == CH_EOF)
846 goto unterminated_string;
848 goto add_char;
849 } else {
850 goto redo;
852 } else if (c == '\n') {
853 add_lf:
854 if (ACCEPT_LF_IN_STRINGS) {
855 file->line_num++;
856 goto add_char;
857 } else if (str) { /* not skipping */
858 goto unterminated_string;
859 } else {
860 //tcc_warning("missing terminating %c character", sep);
861 return p;
863 } else if (c == '\r') {
864 c = *++p;
865 if (c == '\\')
866 c = handle_bs(&p);
867 if (c == '\n')
868 goto add_lf;
869 if (c == CH_EOF)
870 goto unterminated_string;
871 if (str)
872 cstr_ccat(str, '\r');
873 goto redo;
874 } else {
875 add_char:
876 if (str)
877 cstr_ccat(str, c);
880 p++;
881 return p;
884 /* skip block of text until #else, #elif or #endif. skip also pairs of
885 #if/#endif */
886 static void preprocess_skip(void)
888 int a, start_of_line, c, in_warn_or_error;
889 uint8_t *p;
891 p = file->buf_ptr;
892 a = 0;
893 redo_start:
894 start_of_line = 1;
895 in_warn_or_error = 0;
896 for(;;) {
897 redo_no_start:
898 c = *p;
899 switch(c) {
900 case ' ':
901 case '\t':
902 case '\f':
903 case '\v':
904 case '\r':
905 p++;
906 goto redo_no_start;
907 case '\n':
908 file->line_num++;
909 p++;
910 goto redo_start;
911 case '\\':
912 c = handle_bs(&p);
913 if (c == CH_EOF)
914 expect("#endif");
915 if (c == '\\')
916 ++p;
917 goto redo_no_start;
918 /* skip strings */
919 case '\"':
920 case '\'':
921 if (in_warn_or_error)
922 goto _default;
923 tok_flags &= ~TOK_FLAG_BOL;
924 p = parse_pp_string(p, c, NULL);
925 break;
926 /* skip comments */
927 case '/':
928 if (in_warn_or_error)
929 goto _default;
930 ++p;
931 c = handle_bs(&p);
932 if (c == '*') {
933 p = parse_comment(p);
934 } else if (c == '/') {
935 p = parse_line_comment(p);
937 break;
938 case '#':
939 p++;
940 if (start_of_line) {
941 file->buf_ptr = p;
942 next_nomacro();
943 p = file->buf_ptr;
944 if (a == 0 &&
945 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
946 goto the_end;
947 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
948 a++;
949 else if (tok == TOK_ENDIF)
950 a--;
951 else if( tok == TOK_ERROR || tok == TOK_WARNING)
952 in_warn_or_error = 1;
953 else if (tok == TOK_LINEFEED)
954 goto redo_start;
955 else if (parse_flags & PARSE_FLAG_ASM_FILE)
956 p = parse_line_comment(p - 1);
958 #if !defined(TCC_TARGET_ARM)
959 else if (parse_flags & PARSE_FLAG_ASM_FILE)
960 p = parse_line_comment(p - 1);
961 #else
962 /* ARM assembly uses '#' for constants */
963 #endif
964 break;
965 _default:
966 default:
967 p++;
968 break;
970 start_of_line = 0;
972 the_end: ;
973 file->buf_ptr = p;
976 #if 0
977 /* return the number of additional 'ints' necessary to store the
978 token */
979 static inline int tok_size(const int *p)
981 switch(*p) {
982 /* 4 bytes */
983 case TOK_CINT:
984 case TOK_CUINT:
985 case TOK_CCHAR:
986 case TOK_LCHAR:
987 case TOK_CFLOAT:
988 case TOK_LINENUM:
989 return 1 + 1;
990 case TOK_STR:
991 case TOK_LSTR:
992 case TOK_PPNUM:
993 case TOK_PPSTR:
994 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
995 case TOK_CLONG:
996 case TOK_CULONG:
997 return 1 + LONG_SIZE / 4;
998 case TOK_CDOUBLE:
999 case TOK_CLLONG:
1000 case TOK_CULLONG:
1001 return 1 + 2;
1002 case TOK_CLDOUBLE:
1003 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
1004 return 1 + 8 / 4;
1005 #else
1006 return 1 + LDOUBLE_SIZE / 4;
1007 #endif
1008 default:
1009 return 1 + 0;
1012 #endif
1014 /* token string handling */
1015 ST_INLN void tok_str_new(TokenString *s)
1017 s->str = NULL;
1018 s->len = s->lastlen = 0;
1019 s->allocated_len = 0;
1020 s->last_line_num = -1;
1023 ST_FUNC TokenString *tok_str_alloc(void)
1025 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1026 tok_str_new(str);
1027 return str;
1030 ST_FUNC int *tok_str_dup(TokenString *s)
1032 int *str;
1034 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1035 memcpy(str, s->str, s->len * sizeof(int));
1036 return str;
1039 ST_FUNC void tok_str_free_str(int *str)
1041 tal_free(tokstr_alloc, str);
1044 ST_FUNC void tok_str_free(TokenString *str)
1046 tok_str_free_str(str->str);
1047 tal_free(tokstr_alloc, str);
1050 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1052 int *str, size;
1054 size = s->allocated_len;
1055 if (size < 16)
1056 size = 16;
1057 while (size < new_size)
1058 size = size * 2;
1059 if (size > s->allocated_len) {
1060 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1061 s->allocated_len = size;
1062 s->str = str;
1064 return s->str;
1067 ST_FUNC void tok_str_add(TokenString *s, int t)
1069 int len, *str;
1071 len = s->len;
1072 str = s->str;
1073 if (len >= s->allocated_len)
1074 str = tok_str_realloc(s, len + 1);
1075 str[len++] = t;
1076 s->len = len;
1079 ST_FUNC void begin_macro(TokenString *str, int alloc)
1081 str->alloc = alloc;
1082 str->prev = macro_stack;
1083 str->prev_ptr = macro_ptr;
1084 str->save_line_num = file->line_num;
1085 macro_ptr = str->str;
1086 macro_stack = str;
1089 ST_FUNC void end_macro(void)
1091 TokenString *str = macro_stack;
1092 macro_stack = str->prev;
1093 macro_ptr = str->prev_ptr;
1094 file->line_num = str->save_line_num;
1095 str->len = 0; /* matters if str not alloced, may be tokstr_buf */
1096 if (str->alloc != 0) {
1097 if (str->alloc == 2)
1098 str->str = NULL; /* don't free */
1099 tok_str_free(str);
1103 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1105 int len, *str;
1107 len = s->lastlen = s->len;
1108 str = s->str;
1110 /* allocate space for worst case */
1111 if (len + TOK_MAX_SIZE >= s->allocated_len)
1112 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1113 str[len++] = t;
1114 switch(t) {
1115 case TOK_CINT:
1116 case TOK_CUINT:
1117 case TOK_CCHAR:
1118 case TOK_LCHAR:
1119 case TOK_CFLOAT:
1120 case TOK_LINENUM:
1121 #if LONG_SIZE == 4
1122 case TOK_CLONG:
1123 case TOK_CULONG:
1124 #endif
1125 str[len++] = cv->tab[0];
1126 break;
1127 case TOK_PPNUM:
1128 case TOK_PPSTR:
1129 case TOK_STR:
1130 case TOK_LSTR:
1132 /* Insert the string into the int array. */
1133 size_t nb_words =
1134 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1135 if (len + nb_words >= s->allocated_len)
1136 str = tok_str_realloc(s, len + nb_words + 1);
1137 str[len] = cv->str.size;
1138 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1139 len += nb_words;
1141 break;
1142 case TOK_CDOUBLE:
1143 case TOK_CLLONG:
1144 case TOK_CULLONG:
1145 #if LONG_SIZE == 8
1146 case TOK_CLONG:
1147 case TOK_CULONG:
1148 #endif
1149 str[len++] = cv->tab[0];
1150 str[len++] = cv->tab[1];
1151 break;
1152 case TOK_CLDOUBLE:
1153 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1154 str[len++] = cv->tab[0];
1155 str[len++] = cv->tab[1];
1156 #elif LDOUBLE_SIZE == 12
1157 str[len++] = cv->tab[0];
1158 str[len++] = cv->tab[1];
1159 str[len++] = cv->tab[2];
1160 #elif LDOUBLE_SIZE == 16
1161 str[len++] = cv->tab[0];
1162 str[len++] = cv->tab[1];
1163 str[len++] = cv->tab[2];
1164 str[len++] = cv->tab[3];
1165 #else
1166 #error add long double size support
1167 #endif
1168 break;
1169 default:
1170 break;
1172 s->len = len;
1175 /* add the current parse token in token string 's' */
1176 ST_FUNC void tok_str_add_tok(TokenString *s)
1178 CValue cval;
1180 /* save line number info */
1181 if (file->line_num != s->last_line_num) {
1182 s->last_line_num = file->line_num;
1183 cval.i = s->last_line_num;
1184 tok_str_add2(s, TOK_LINENUM, &cval);
1186 tok_str_add2(s, tok, &tokc);
1189 /* get a token from an integer array and increment pointer. */
1190 static inline void tok_get(int *t, const int **pp, CValue *cv)
1192 const int *p = *pp;
1193 int n, *tab;
1195 tab = cv->tab;
1196 switch(*t = *p++) {
1197 #if LONG_SIZE == 4
1198 case TOK_CLONG:
1199 #endif
1200 case TOK_CINT:
1201 case TOK_CCHAR:
1202 case TOK_LCHAR:
1203 case TOK_LINENUM:
1204 cv->i = *p++;
1205 break;
1206 #if LONG_SIZE == 4
1207 case TOK_CULONG:
1208 #endif
1209 case TOK_CUINT:
1210 cv->i = (unsigned)*p++;
1211 break;
1212 case TOK_CFLOAT:
1213 tab[0] = *p++;
1214 break;
1215 case TOK_STR:
1216 case TOK_LSTR:
1217 case TOK_PPNUM:
1218 case TOK_PPSTR:
1219 cv->str.size = *p++;
1220 cv->str.data = p;
1221 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1222 break;
1223 case TOK_CDOUBLE:
1224 case TOK_CLLONG:
1225 case TOK_CULLONG:
1226 #if LONG_SIZE == 8
1227 case TOK_CLONG:
1228 case TOK_CULONG:
1229 #endif
1230 n = 2;
1231 goto copy;
1232 case TOK_CLDOUBLE:
1233 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1234 n = 2;
1235 #elif LDOUBLE_SIZE == 12
1236 n = 3;
1237 #elif LDOUBLE_SIZE == 16
1238 n = 4;
1239 #else
1240 # error add long double size support
1241 #endif
1242 copy:
1244 *tab++ = *p++;
1245 while (--n);
1246 break;
1247 default:
1248 break;
1250 *pp = p;
1253 #if 0
1254 # define TOK_GET(t,p,c) tok_get(t,p,c)
1255 #else
1256 # define TOK_GET(t,p,c) do { \
1257 int _t = **(p); \
1258 if (TOK_HAS_VALUE(_t)) \
1259 tok_get(t, p, c); \
1260 else \
1261 *(t) = _t, ++*(p); \
1262 } while (0)
1263 #endif
1265 static int macro_is_equal(const int *a, const int *b)
1267 CValue cv;
1268 int t;
1270 if (!a || !b)
1271 return 1;
1273 while (*a && *b) {
1274 cstr_reset(&tokcstr);
1275 TOK_GET(&t, &a, &cv);
1276 cstr_cat(&tokcstr, get_tok_str(t, &cv), 0);
1277 TOK_GET(&t, &b, &cv);
1278 if (strcmp(tokcstr.data, get_tok_str(t, &cv)))
1279 return 0;
1281 return !(*a || *b);
1284 /* defines handling */
1285 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1287 Sym *s, *o;
1289 o = define_find(v);
1290 s = sym_push2(&define_stack, v, macro_type, 0);
1291 s->d = str;
1292 s->next = first_arg;
1293 table_ident[v - TOK_IDENT]->sym_define = s;
1295 if (o && !macro_is_equal(o->d, s->d))
1296 tcc_warning("%s redefined", get_tok_str(v, NULL));
1299 /* undefined a define symbol. Its name is just set to zero */
1300 ST_FUNC void define_undef(Sym *s)
1302 int v = s->v;
1303 if (v >= TOK_IDENT && v < tok_ident)
1304 table_ident[v - TOK_IDENT]->sym_define = NULL;
1307 ST_INLN Sym *define_find(int v)
1309 v -= TOK_IDENT;
1310 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1311 return NULL;
1312 return table_ident[v]->sym_define;
1315 /* free define stack until top reaches 'b' */
1316 ST_FUNC void free_defines(Sym *b)
1318 while (define_stack != b) {
1319 Sym *top = define_stack;
1320 define_stack = top->prev;
1321 tok_str_free_str(top->d);
1322 define_undef(top);
1323 sym_free(top);
1327 /* fake the nth "#if defined test_..." for tcc -dt -run */
1328 static void maybe_run_test(TCCState *s)
1330 const char *p;
1331 if (s->include_stack_ptr != s->include_stack)
1332 return;
1333 p = get_tok_str(tok, NULL);
1334 if (0 != memcmp(p, "test_", 5))
1335 return;
1336 if (0 != --s->run_test)
1337 return;
1338 fprintf(s->ppfp, &"\n[%s]\n"[!(s->dflag & 32)], p), fflush(s->ppfp);
1339 define_push(tok, MACRO_OBJ, NULL, NULL);
1342 static CachedInclude *
1343 search_cached_include(TCCState *s1, const char *filename, int add);
1345 static int parse_include(TCCState *s1, int do_next, int test)
1347 int c, i;
1348 char name[1024], buf[1024], *p;
1349 CachedInclude *e;
1351 c = skip_spaces();
1352 if (c == '<' || c == '\"') {
1353 cstr_reset(&tokcstr);
1354 file->buf_ptr = parse_pp_string(file->buf_ptr, c == '<' ? '>' : c, &tokcstr);
1355 i = tokcstr.size;
1356 pstrncpy(name, tokcstr.data, i >= sizeof name ? sizeof name - 1 : i);
1357 next_nomacro();
1358 } else {
1359 /* computed #include : concatenate tokens until result is one of
1360 the two accepted forms. Don't convert pp-tokens to tokens here. */
1361 parse_flags = PARSE_FLAG_PREPROCESS
1362 | PARSE_FLAG_LINEFEED
1363 | (parse_flags & PARSE_FLAG_ASM_FILE);
1364 name[0] = 0;
1365 for (;;) {
1366 next();
1367 p = name, i = strlen(p) - 1;
1368 if (i > 0
1369 && ((p[0] == '"' && p[i] == '"')
1370 || (p[0] == '<' && p[i] == '>')))
1371 break;
1372 if (tok == TOK_LINEFEED)
1373 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1374 pstrcat(name, sizeof name, get_tok_str(tok, &tokc));
1376 c = p[0];
1377 /* remove '<>|""' */
1378 memmove(p, p + 1, i - 1), p[i - 1] = 0;
1381 i = do_next ? file->include_next_index : -1;
1382 for (;;) {
1383 ++i;
1384 if (i == 0) {
1385 /* check absolute include path */
1386 if (!IS_ABSPATH(name))
1387 continue;
1388 buf[0] = '\0';
1389 } else if (i == 1) {
1390 /* search in file's dir if "header.h" */
1391 if (c != '\"')
1392 continue;
1393 p = file->true_filename;
1394 pstrncpy(buf, p, tcc_basename(p) - p);
1395 } else {
1396 int j = i - 2, k = j - s1->nb_include_paths;
1397 if (k < 0)
1398 p = s1->include_paths[j];
1399 else if (k < s1->nb_sysinclude_paths)
1400 p = s1->sysinclude_paths[k];
1401 else if (test)
1402 return 0;
1403 else
1404 tcc_error("include file '%s' not found", name);
1405 pstrcpy(buf, sizeof buf, p);
1406 pstrcat(buf, sizeof buf, "/");
1408 pstrcat(buf, sizeof buf, name);
1409 e = search_cached_include(s1, buf, 0);
1410 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1411 /* no need to parse the include because the 'ifndef macro'
1412 is defined (or had #pragma once) */
1413 #ifdef INC_DEBUG
1414 printf("%s: skipping cached %s\n", file->filename, buf);
1415 #endif
1416 return 1;
1418 if (tcc_open(s1, buf) >= 0)
1419 break;
1422 if (test) {
1423 tcc_close();
1424 } else {
1425 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1426 tcc_error("#include recursion too deep");
1427 /* push previous file on stack */
1428 *s1->include_stack_ptr++ = file->prev;
1429 file->include_next_index = i;
1430 #ifdef INC_DEBUG
1431 printf("%s: including %s\n", file->prev->filename, file->filename);
1432 #endif
1433 /* update target deps */
1434 if (s1->gen_deps) {
1435 BufferedFile *bf = file;
1436 while (i == 1 && (bf = bf->prev))
1437 i = bf->include_next_index;
1438 /* skip system include files */
1439 if (s1->include_sys_deps || i - 2 < s1->nb_include_paths)
1440 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1441 tcc_strdup(buf));
1443 /* add include file debug info */
1444 tcc_debug_bincl(s1);
1445 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1447 return 1;
1450 /* eval an expression for #if/#elif */
1451 static int expr_preprocess(TCCState *s1)
1453 int c, t;
1454 TokenString *str;
1456 str = tok_str_alloc();
1457 pp_expr = 1;
1458 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1459 next(); /* do macro subst */
1460 redo:
1461 if (tok == TOK_DEFINED) {
1462 next_nomacro();
1463 t = tok;
1464 if (t == '(')
1465 next_nomacro();
1466 if (tok < TOK_IDENT)
1467 expect("identifier");
1468 if (s1->run_test)
1469 maybe_run_test(s1);
1470 c = 0;
1471 if (define_find(tok)
1472 || tok == TOK___HAS_INCLUDE
1473 || tok == TOK___HAS_INCLUDE_NEXT)
1474 c = 1;
1475 if (t == '(') {
1476 next_nomacro();
1477 if (tok != ')')
1478 expect("')'");
1480 tok = TOK_CINT;
1481 tokc.i = c;
1482 } else if (tok == TOK___HAS_INCLUDE ||
1483 tok == TOK___HAS_INCLUDE_NEXT) {
1484 t = tok;
1485 next_nomacro();
1486 if (tok != '(')
1487 expect("(");
1488 c = parse_include(s1, t - TOK___HAS_INCLUDE, 1);
1489 if (tok != ')')
1490 expect("')'");
1491 tok = TOK_CINT;
1492 tokc.i = c;
1493 } else if (tok >= TOK_IDENT) {
1494 /* if undefined macro, replace with zero, check for func-like */
1495 t = tok;
1496 tok = TOK_CINT;
1497 tokc.i = 0;
1498 tok_str_add_tok(str);
1499 next();
1500 if (tok == '(')
1501 tcc_error("function-like macro '%s' is not defined",
1502 get_tok_str(t, NULL));
1503 goto redo;
1505 tok_str_add_tok(str);
1507 pp_expr = 0;
1508 tok_str_add(str, -1); /* simulate end of file */
1509 tok_str_add(str, 0);
1510 /* now evaluate C constant expression */
1511 begin_macro(str, 1);
1512 next();
1513 c = expr_const();
1514 end_macro();
1515 return c != 0;
1519 /* parse after #define */
1520 ST_FUNC void parse_define(void)
1522 Sym *s, *first, **ps;
1523 int v, t, varg, is_vaargs, spc;
1524 int saved_parse_flags = parse_flags;
1526 v = tok;
1527 if (v < TOK_IDENT || v == TOK_DEFINED)
1528 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1529 /* XXX: should check if same macro (ANSI) */
1530 first = NULL;
1531 t = MACRO_OBJ;
1532 /* We have to parse the whole define as if not in asm mode, in particular
1533 no line comment with '#' must be ignored. Also for function
1534 macros the argument list must be parsed without '.' being an ID
1535 character. */
1536 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1537 /* '(' must be just after macro definition for MACRO_FUNC */
1538 next_nomacro();
1539 parse_flags &= ~PARSE_FLAG_SPACES;
1540 if (tok == '(') {
1541 int dotid = set_idnum('.', 0);
1542 next_nomacro();
1543 ps = &first;
1544 if (tok != ')') for (;;) {
1545 varg = tok;
1546 next_nomacro();
1547 is_vaargs = 0;
1548 if (varg == TOK_DOTS) {
1549 varg = TOK___VA_ARGS__;
1550 is_vaargs = 1;
1551 } else if (tok == TOK_DOTS && gnu_ext) {
1552 is_vaargs = 1;
1553 next_nomacro();
1555 if (varg < TOK_IDENT)
1556 bad_list:
1557 tcc_error("bad macro parameter list");
1558 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1559 *ps = s;
1560 ps = &s->next;
1561 if (tok == ')')
1562 break;
1563 if (tok != ',' || is_vaargs)
1564 goto bad_list;
1565 next_nomacro();
1567 parse_flags |= PARSE_FLAG_SPACES;
1568 next_nomacro();
1569 t = MACRO_FUNC;
1570 set_idnum('.', dotid);
1573 tokstr_buf.len = 0;
1574 spc = 2;
1575 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1576 /* The body of a macro definition should be parsed such that identifiers
1577 are parsed like the file mode determines (i.e. with '.' being an
1578 ID character in asm mode). But '#' should be retained instead of
1579 regarded as line comment leader, so still don't set ASM_FILE
1580 in parse_flags. */
1581 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1582 /* remove spaces around ## and after '#' */
1583 if (TOK_TWOSHARPS == tok) {
1584 if (2 == spc)
1585 goto bad_twosharp;
1586 if (1 == spc)
1587 --tokstr_buf.len;
1588 spc = 3;
1589 tok = TOK_PPJOIN;
1590 } else if ('#' == tok) {
1591 spc = 4;
1592 } else if (check_space(tok, &spc)) {
1593 goto skip;
1595 tok_str_add2(&tokstr_buf, tok, &tokc);
1596 skip:
1597 next_nomacro();
1600 parse_flags = saved_parse_flags;
1601 if (spc == 1)
1602 --tokstr_buf.len; /* remove trailing space */
1603 tok_str_add(&tokstr_buf, 0);
1604 if (3 == spc)
1605 bad_twosharp:
1606 tcc_error("'##' cannot appear at either end of macro");
1607 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1610 #ifdef _WIN32
1611 static unsigned long long calc_file_hash(const char *filename)
1613 unsigned long long hash = 14695981039346656037ull; // FNV_offset_basis;
1614 FILE *fp = fopen (filename, "rb");
1616 if (fp == NULL)
1617 return 0;
1618 for (;;) {
1619 unsigned char temp[IO_BUF_SIZE];
1620 int i, n = fread(temp, 1, sizeof(temp), fp);
1622 if (n <= 0)
1623 break;
1624 for (i = 0; i < n; i++)
1625 hash = hash * 1099511628211ull + temp[i]; // FNV_prime
1627 fclose(fp);
1628 if (hash == 0)
1629 hash = 1;
1630 return hash;
1632 #endif
1634 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1636 unsigned int h = 0;
1637 CachedInclude *e;
1638 int i;
1639 struct stat st;
1640 #ifdef _WIN32
1641 unsigned long long hash = 0;
1642 #endif
1644 /* This is needed for #pragmae once
1645 * We cannot use stat on windows because st_ino is not set correctly
1646 * so we calculate a hash of file contents.
1647 * This also works for hard/soft links as in gcc/clang.
1649 memset (&st, 0, sizeof(st));
1650 if (stat (filename, &st))
1651 goto skip;
1652 h = st.st_size & (CACHED_INCLUDES_HASH_SIZE - 1);
1653 #ifdef _WIN32
1654 /* Only calculate file hash if file size same. */
1655 i = s1->cached_includes_hash[h];
1656 for(;;) {
1657 if (i == 0)
1658 break;
1659 e = s1->cached_includes[i - 1];
1660 if (e->st.st_size == st.st_size) {
1661 if (e->hash == 0)
1662 e->hash = calc_file_hash(e->filename);
1663 hash = calc_file_hash(filename);
1664 break;
1666 i = e->hash_next;
1668 #endif
1670 i = s1->cached_includes_hash[h];
1671 for(;;) {
1672 if (i == 0)
1673 break;
1674 e = s1->cached_includes[i - 1];
1675 #ifdef _WIN32
1676 if (e->st.st_size == st.st_size && e->hash == hash)
1677 #else
1678 if (st.st_dev == e->st.st_dev && st.st_ino == e->st.st_ino)
1679 #endif
1680 return e;
1681 i = e->hash_next;
1683 skip:
1684 if (!add)
1685 return NULL;
1687 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1688 e->st = st;
1689 #ifdef _WIN32
1690 e->hash = hash;
1691 #endif
1692 strcpy(e->filename, filename);
1693 e->ifndef_macro = e->once = 0;
1694 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1695 /* add in hash table */
1696 e->hash_next = s1->cached_includes_hash[h];
1697 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1698 #ifdef INC_DEBUG
1699 printf("adding cached '%s'\n", filename);
1700 #endif
1701 return e;
1704 static void pragma_parse(TCCState *s1)
1706 next_nomacro();
1707 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1708 int t = tok, v;
1709 Sym *s;
1711 if (next(), tok != '(')
1712 goto pragma_err;
1713 if (next(), tok != TOK_STR)
1714 goto pragma_err;
1715 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1716 if (next(), tok != ')')
1717 goto pragma_err;
1718 if (t == TOK_push_macro) {
1719 while (NULL == (s = define_find(v)))
1720 define_push(v, 0, NULL, NULL);
1721 s->type.ref = s; /* set push boundary */
1722 } else {
1723 for (s = define_stack; s; s = s->prev)
1724 if (s->v == v && s->type.ref == s) {
1725 s->type.ref = NULL;
1726 break;
1729 if (s)
1730 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1731 else
1732 tcc_warning("unbalanced #pragma pop_macro");
1733 pp_debug_tok = t, pp_debug_symv = v;
1735 } else if (tok == TOK_once) {
1736 search_cached_include(s1, file->filename, 1)->once = pp_once;
1738 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1739 /* tcc -E: keep pragmas below unchanged */
1740 unget_tok(' ');
1741 unget_tok(TOK_PRAGMA);
1742 unget_tok('#');
1743 unget_tok(TOK_LINEFEED);
1745 } else if (tok == TOK_pack) {
1746 /* This may be:
1747 #pragma pack(1) // set
1748 #pragma pack() // reset to default
1749 #pragma pack(push) // push current
1750 #pragma pack(push,1) // push & set
1751 #pragma pack(pop) // restore previous */
1752 next();
1753 skip('(');
1754 if (tok == TOK_ASM_pop) {
1755 next();
1756 if (s1->pack_stack_ptr <= s1->pack_stack) {
1757 stk_error:
1758 tcc_error("out of pack stack");
1760 s1->pack_stack_ptr--;
1761 } else {
1762 int val = 0;
1763 if (tok != ')') {
1764 if (tok == TOK_ASM_push) {
1765 next();
1766 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1767 goto stk_error;
1768 val = *s1->pack_stack_ptr++;
1769 if (tok != ',')
1770 goto pack_set;
1771 next();
1773 if (tok != TOK_CINT)
1774 goto pragma_err;
1775 val = tokc.i;
1776 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1777 goto pragma_err;
1778 next();
1780 pack_set:
1781 *s1->pack_stack_ptr = val;
1783 if (tok != ')')
1784 goto pragma_err;
1786 } else if (tok == TOK_comment) {
1787 char *p; int t;
1788 next();
1789 skip('(');
1790 t = tok;
1791 next();
1792 skip(',');
1793 if (tok != TOK_STR)
1794 goto pragma_err;
1795 p = tcc_strdup((char *)tokc.str.data);
1796 next();
1797 if (tok != ')')
1798 goto pragma_err;
1799 if (t == TOK_lib) {
1800 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1801 } else {
1802 if (t == TOK_option)
1803 tcc_set_options(s1, p);
1804 tcc_free(p);
1807 } else
1808 tcc_warning_c(warn_unsupported)("#pragma %s ignored", get_tok_str(tok, &tokc));
1809 return;
1811 pragma_err:
1812 tcc_error("malformed #pragma directive");
1813 return;
1816 /* is_bof is true if first non space token at beginning of file */
1817 ST_FUNC void preprocess(int is_bof)
1819 TCCState *s1 = tcc_state;
1820 int c, n, saved_parse_flags;
1821 char buf[1024], *q;
1822 Sym *s;
1824 saved_parse_flags = parse_flags;
1825 parse_flags = PARSE_FLAG_PREPROCESS
1826 | PARSE_FLAG_TOK_NUM
1827 | PARSE_FLAG_TOK_STR
1828 | PARSE_FLAG_LINEFEED
1829 | (parse_flags & PARSE_FLAG_ASM_FILE)
1832 next_nomacro();
1833 redo:
1834 switch(tok) {
1835 case TOK_DEFINE:
1836 pp_debug_tok = tok;
1837 next_nomacro();
1838 pp_debug_symv = tok;
1839 parse_define();
1840 break;
1841 case TOK_UNDEF:
1842 pp_debug_tok = tok;
1843 next_nomacro();
1844 pp_debug_symv = tok;
1845 s = define_find(tok);
1846 /* undefine symbol by putting an invalid name */
1847 if (s)
1848 define_undef(s);
1849 break;
1850 case TOK_INCLUDE:
1851 case TOK_INCLUDE_NEXT:
1852 parse_include(s1, tok - TOK_INCLUDE, 0);
1853 break;
1854 case TOK_IFNDEF:
1855 c = 1;
1856 goto do_ifdef;
1857 case TOK_IF:
1858 c = expr_preprocess(s1);
1859 goto do_if;
1860 case TOK_IFDEF:
1861 c = 0;
1862 do_ifdef:
1863 next_nomacro();
1864 if (tok < TOK_IDENT)
1865 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1866 if (is_bof) {
1867 if (c) {
1868 #ifdef INC_DEBUG
1869 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1870 #endif
1871 file->ifndef_macro = tok;
1874 if (define_find(tok)
1875 || tok == TOK___HAS_INCLUDE
1876 || tok == TOK___HAS_INCLUDE_NEXT)
1877 c ^= 1;
1878 do_if:
1879 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1880 tcc_error("memory full (ifdef)");
1881 *s1->ifdef_stack_ptr++ = c;
1882 goto test_skip;
1883 case TOK_ELSE:
1884 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1885 tcc_error("#else without matching #if");
1886 if (s1->ifdef_stack_ptr[-1] & 2)
1887 tcc_error("#else after #else");
1888 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1889 goto test_else;
1890 case TOK_ELIF:
1891 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1892 tcc_error("#elif without matching #if");
1893 c = s1->ifdef_stack_ptr[-1];
1894 if (c > 1)
1895 tcc_error("#elif after #else");
1896 /* last #if/#elif expression was true: we skip */
1897 if (c == 1) {
1898 c = 0;
1899 } else {
1900 c = expr_preprocess(s1);
1901 s1->ifdef_stack_ptr[-1] = c;
1903 test_else:
1904 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1905 file->ifndef_macro = 0;
1906 test_skip:
1907 if (!(c & 1)) {
1908 preprocess_skip();
1909 is_bof = 0;
1910 goto redo;
1912 break;
1913 case TOK_ENDIF:
1914 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1915 tcc_error("#endif without matching #if");
1916 s1->ifdef_stack_ptr--;
1917 /* '#ifndef macro' was at the start of file. Now we check if
1918 an '#endif' is exactly at the end of file */
1919 if (file->ifndef_macro &&
1920 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1921 file->ifndef_macro_saved = file->ifndef_macro;
1922 /* need to set to zero to avoid false matches if another
1923 #ifndef at middle of file */
1924 file->ifndef_macro = 0;
1925 while (tok != TOK_LINEFEED)
1926 next_nomacro();
1927 tok_flags |= TOK_FLAG_ENDIF;
1928 goto the_end;
1930 break;
1931 case TOK_PPNUM:
1932 n = strtoul((char*)tokc.str.data, &q, 10);
1933 goto _line_num;
1934 case TOK_LINE:
1935 next();
1936 if (tok != TOK_CINT)
1937 _line_err:
1938 tcc_error("wrong #line format");
1939 n = tokc.i;
1940 _line_num:
1941 next();
1942 if (tok != TOK_LINEFEED) {
1943 if (tok == TOK_STR) {
1944 if (file->true_filename == file->filename)
1945 file->true_filename = tcc_strdup(file->filename);
1946 q = (char *)tokc.str.data;
1947 buf[0] = 0;
1948 if (!IS_ABSPATH(q)) {
1949 /* prepend directory from real file */
1950 pstrcpy(buf, sizeof buf, file->true_filename);
1951 *tcc_basename(buf) = 0;
1953 pstrcat(buf, sizeof buf, q);
1954 tcc_debug_putfile(s1, buf);
1955 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
1956 break;
1957 else
1958 goto _line_err;
1959 --n;
1961 if (file->fd > 0)
1962 total_lines += file->line_num - n;
1963 file->line_num = n;
1964 break;
1965 case TOK_ERROR:
1966 case TOK_WARNING:
1967 q = buf;
1968 c = skip_spaces();
1969 while (c != '\n' && c != CH_EOF) {
1970 if ((q - buf) < sizeof(buf) - 1)
1971 *q++ = c;
1972 c = ninp();
1974 *q = '\0';
1975 if (tok == TOK_ERROR)
1976 tcc_error("#error %s", buf);
1977 else
1978 tcc_warning("#warning %s", buf);
1979 break;
1980 case TOK_PRAGMA:
1981 pragma_parse(s1);
1982 break;
1983 case TOK_LINEFEED:
1984 goto the_end;
1985 default:
1986 /* ignore gas line comment in an 'S' file. */
1987 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1988 goto ignore;
1989 if (tok == '!' && is_bof)
1990 /* '!' is ignored at beginning to allow C scripts. */
1991 goto ignore;
1992 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1993 ignore:
1994 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
1995 goto the_end;
1997 /* ignore other preprocess commands or #! for C scripts */
1998 while (tok != TOK_LINEFEED)
1999 next_nomacro();
2000 the_end:
2001 parse_flags = saved_parse_flags;
2004 /* evaluate escape codes in a string. */
2005 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
2007 int c, n, i;
2008 const uint8_t *p;
2010 p = buf;
2011 for(;;) {
2012 c = *p;
2013 if (c == '\0')
2014 break;
2015 if (c == '\\') {
2016 p++;
2017 /* escape */
2018 c = *p;
2019 switch(c) {
2020 case '0': case '1': case '2': case '3':
2021 case '4': case '5': case '6': case '7':
2022 /* at most three octal digits */
2023 n = c - '0';
2024 p++;
2025 c = *p;
2026 if (isoct(c)) {
2027 n = n * 8 + c - '0';
2028 p++;
2029 c = *p;
2030 if (isoct(c)) {
2031 n = n * 8 + c - '0';
2032 p++;
2035 c = n;
2036 goto add_char_nonext;
2037 case 'x': i = 0; goto parse_hex_or_ucn;
2038 case 'u': i = 4; goto parse_hex_or_ucn;
2039 case 'U': i = 8; goto parse_hex_or_ucn;
2040 parse_hex_or_ucn:
2041 p++;
2042 n = 0;
2043 do {
2044 c = *p;
2045 if (c >= 'a' && c <= 'f')
2046 c = c - 'a' + 10;
2047 else if (c >= 'A' && c <= 'F')
2048 c = c - 'A' + 10;
2049 else if (isnum(c))
2050 c = c - '0';
2051 else if (i > 0)
2052 expect("more hex digits in universal-character-name");
2053 else
2054 goto add_hex_or_ucn;
2055 n = n * 16 + c;
2056 p++;
2057 } while (--i);
2058 if (is_long) {
2059 add_hex_or_ucn:
2060 c = n;
2061 goto add_char_nonext;
2063 cstr_u8cat(outstr, n);
2064 continue;
2065 case 'a':
2066 c = '\a';
2067 break;
2068 case 'b':
2069 c = '\b';
2070 break;
2071 case 'f':
2072 c = '\f';
2073 break;
2074 case 'n':
2075 c = '\n';
2076 break;
2077 case 'r':
2078 c = '\r';
2079 break;
2080 case 't':
2081 c = '\t';
2082 break;
2083 case 'v':
2084 c = '\v';
2085 break;
2086 case 'e':
2087 if (!gnu_ext)
2088 goto invalid_escape;
2089 c = 27;
2090 break;
2091 case '\'':
2092 case '\"':
2093 case '\\':
2094 case '?':
2095 break;
2096 default:
2097 invalid_escape:
2098 if (c >= '!' && c <= '~')
2099 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2100 else
2101 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2102 break;
2104 } else if (is_long && c >= 0x80) {
2105 /* assume we are processing UTF-8 sequence */
2106 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2108 int cont; /* count of continuation bytes */
2109 int skip; /* how many bytes should skip when error occurred */
2110 int i;
2112 /* decode leading byte */
2113 if (c < 0xC2) {
2114 skip = 1; goto invalid_utf8_sequence;
2115 } else if (c <= 0xDF) {
2116 cont = 1; n = c & 0x1f;
2117 } else if (c <= 0xEF) {
2118 cont = 2; n = c & 0xf;
2119 } else if (c <= 0xF4) {
2120 cont = 3; n = c & 0x7;
2121 } else {
2122 skip = 1; goto invalid_utf8_sequence;
2125 /* decode continuation bytes */
2126 for (i = 1; i <= cont; i++) {
2127 int l = 0x80, h = 0xBF;
2129 /* adjust limit for second byte */
2130 if (i == 1) {
2131 switch (c) {
2132 case 0xE0: l = 0xA0; break;
2133 case 0xED: h = 0x9F; break;
2134 case 0xF0: l = 0x90; break;
2135 case 0xF4: h = 0x8F; break;
2139 if (p[i] < l || p[i] > h) {
2140 skip = i; goto invalid_utf8_sequence;
2143 n = (n << 6) | (p[i] & 0x3f);
2146 /* advance pointer */
2147 p += 1 + cont;
2148 c = n;
2149 goto add_char_nonext;
2151 /* error handling */
2152 invalid_utf8_sequence:
2153 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2154 c = 0xFFFD;
2155 p += skip;
2156 goto add_char_nonext;
2159 p++;
2160 add_char_nonext:
2161 if (!is_long)
2162 cstr_ccat(outstr, c);
2163 else {
2164 #ifdef TCC_TARGET_PE
2165 /* store as UTF-16 */
2166 if (c < 0x10000) {
2167 cstr_wccat(outstr, c);
2168 } else {
2169 c -= 0x10000;
2170 cstr_wccat(outstr, (c >> 10) + 0xD800);
2171 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2173 #else
2174 cstr_wccat(outstr, c);
2175 #endif
2178 /* add a trailing '\0' */
2179 if (!is_long)
2180 cstr_ccat(outstr, '\0');
2181 else
2182 cstr_wccat(outstr, '\0');
2185 static void parse_string(const char *s, int len)
2187 uint8_t buf[1000], *p = buf;
2188 int is_long, sep;
2190 if ((is_long = *s == 'L'))
2191 ++s, --len;
2192 sep = *s++;
2193 len -= 2;
2194 if (len >= sizeof buf)
2195 p = tcc_malloc(len + 1);
2196 memcpy(p, s, len);
2197 p[len] = 0;
2199 cstr_reset(&tokcstr);
2200 parse_escape_string(&tokcstr, p, is_long);
2201 if (p != buf)
2202 tcc_free(p);
2204 if (sep == '\'') {
2205 int char_size, i, n, c;
2206 /* XXX: make it portable */
2207 if (!is_long)
2208 tok = TOK_CCHAR, char_size = 1;
2209 else
2210 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2211 n = tokcstr.size / char_size - 1;
2212 if (n < 1)
2213 tcc_error("empty character constant");
2214 if (n > 1)
2215 tcc_warning_c(warn_all)("multi-character character constant");
2216 for (c = i = 0; i < n; ++i) {
2217 if (is_long)
2218 c = ((nwchar_t *)tokcstr.data)[i];
2219 else
2220 c = (c << 8) | ((char *)tokcstr.data)[i];
2222 tokc.i = c;
2223 } else {
2224 tokc.str.size = tokcstr.size;
2225 tokc.str.data = tokcstr.data;
2226 if (!is_long)
2227 tok = TOK_STR;
2228 else
2229 tok = TOK_LSTR;
2233 /* we use 64 bit numbers */
2234 #define BN_SIZE 2
2236 /* bn = (bn << shift) | or_val */
2237 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2239 int i;
2240 unsigned int v;
2241 for(i=0;i<BN_SIZE;i++) {
2242 v = bn[i];
2243 bn[i] = (v << shift) | or_val;
2244 or_val = v >> (32 - shift);
2248 static void bn_zero(unsigned int *bn)
2250 int i;
2251 for(i=0;i<BN_SIZE;i++) {
2252 bn[i] = 0;
2256 /* parse number in null terminated string 'p' and return it in the
2257 current token */
2258 static void parse_number(const char *p)
2260 int b, t, shift, frac_bits, s, exp_val, ch;
2261 char *q;
2262 unsigned int bn[BN_SIZE];
2263 double d;
2265 /* number */
2266 q = token_buf;
2267 ch = *p++;
2268 t = ch;
2269 ch = *p++;
2270 *q++ = t;
2271 b = 10;
2272 if (t == '.') {
2273 goto float_frac_parse;
2274 } else if (t == '0') {
2275 if (ch == 'x' || ch == 'X') {
2276 q--;
2277 ch = *p++;
2278 b = 16;
2279 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2280 q--;
2281 ch = *p++;
2282 b = 2;
2285 /* parse all digits. cannot check octal numbers at this stage
2286 because of floating point constants */
2287 while (1) {
2288 if (ch >= 'a' && ch <= 'f')
2289 t = ch - 'a' + 10;
2290 else if (ch >= 'A' && ch <= 'F')
2291 t = ch - 'A' + 10;
2292 else if (isnum(ch))
2293 t = ch - '0';
2294 else
2295 break;
2296 if (t >= b)
2297 break;
2298 if (q >= token_buf + STRING_MAX_SIZE) {
2299 num_too_long:
2300 tcc_error("number too long");
2302 *q++ = ch;
2303 ch = *p++;
2305 if (ch == '.' ||
2306 ((ch == 'e' || ch == 'E') && b == 10) ||
2307 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2308 if (b != 10) {
2309 /* NOTE: strtox should support that for hexa numbers, but
2310 non ISOC99 libcs do not support it, so we prefer to do
2311 it by hand */
2312 /* hexadecimal or binary floats */
2313 /* XXX: handle overflows */
2314 *q = '\0';
2315 if (b == 16)
2316 shift = 4;
2317 else
2318 shift = 1;
2319 bn_zero(bn);
2320 q = token_buf;
2321 while (1) {
2322 t = *q++;
2323 if (t == '\0') {
2324 break;
2325 } else if (t >= 'a') {
2326 t = t - 'a' + 10;
2327 } else if (t >= 'A') {
2328 t = t - 'A' + 10;
2329 } else {
2330 t = t - '0';
2332 bn_lshift(bn, shift, t);
2334 frac_bits = 0;
2335 if (ch == '.') {
2336 ch = *p++;
2337 while (1) {
2338 t = ch;
2339 if (t >= 'a' && t <= 'f') {
2340 t = t - 'a' + 10;
2341 } else if (t >= 'A' && t <= 'F') {
2342 t = t - 'A' + 10;
2343 } else if (t >= '0' && t <= '9') {
2344 t = t - '0';
2345 } else {
2346 break;
2348 if (t >= b)
2349 tcc_error("invalid digit");
2350 bn_lshift(bn, shift, t);
2351 frac_bits += shift;
2352 ch = *p++;
2355 if (ch != 'p' && ch != 'P')
2356 expect("exponent");
2357 ch = *p++;
2358 s = 1;
2359 exp_val = 0;
2360 if (ch == '+') {
2361 ch = *p++;
2362 } else if (ch == '-') {
2363 s = -1;
2364 ch = *p++;
2366 if (ch < '0' || ch > '9')
2367 expect("exponent digits");
2368 while (ch >= '0' && ch <= '9') {
2369 exp_val = exp_val * 10 + ch - '0';
2370 ch = *p++;
2372 exp_val = exp_val * s;
2374 /* now we can generate the number */
2375 /* XXX: should patch directly float number */
2376 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2377 d = ldexp(d, exp_val - frac_bits);
2378 t = toup(ch);
2379 if (t == 'F') {
2380 ch = *p++;
2381 tok = TOK_CFLOAT;
2382 /* float : should handle overflow */
2383 tokc.f = (float)d;
2384 } else if (t == 'L') {
2385 ch = *p++;
2386 tok = TOK_CLDOUBLE;
2387 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2388 tokc.d = d;
2389 #else
2390 /* XXX: not large enough */
2391 tokc.ld = (long double)d;
2392 #endif
2393 } else {
2394 tok = TOK_CDOUBLE;
2395 tokc.d = d;
2397 } else {
2398 /* decimal floats */
2399 if (ch == '.') {
2400 if (q >= token_buf + STRING_MAX_SIZE)
2401 goto num_too_long;
2402 *q++ = ch;
2403 ch = *p++;
2404 float_frac_parse:
2405 while (ch >= '0' && ch <= '9') {
2406 if (q >= token_buf + STRING_MAX_SIZE)
2407 goto num_too_long;
2408 *q++ = ch;
2409 ch = *p++;
2412 if (ch == 'e' || ch == 'E') {
2413 if (q >= token_buf + STRING_MAX_SIZE)
2414 goto num_too_long;
2415 *q++ = ch;
2416 ch = *p++;
2417 if (ch == '-' || ch == '+') {
2418 if (q >= token_buf + STRING_MAX_SIZE)
2419 goto num_too_long;
2420 *q++ = ch;
2421 ch = *p++;
2423 if (ch < '0' || ch > '9')
2424 expect("exponent digits");
2425 while (ch >= '0' && ch <= '9') {
2426 if (q >= token_buf + STRING_MAX_SIZE)
2427 goto num_too_long;
2428 *q++ = ch;
2429 ch = *p++;
2432 *q = '\0';
2433 t = toup(ch);
2434 errno = 0;
2435 if (t == 'F') {
2436 ch = *p++;
2437 tok = TOK_CFLOAT;
2438 tokc.f = strtof(token_buf, NULL);
2439 } else if (t == 'L') {
2440 ch = *p++;
2441 tok = TOK_CLDOUBLE;
2442 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2443 tokc.d = strtod(token_buf, NULL);
2444 #else
2445 tokc.ld = strtold(token_buf, NULL);
2446 #endif
2447 } else {
2448 tok = TOK_CDOUBLE;
2449 tokc.d = strtod(token_buf, NULL);
2452 } else {
2453 unsigned long long n, n1;
2454 int lcount, ucount, ov = 0;
2455 const char *p1;
2457 /* integer number */
2458 *q = '\0';
2459 q = token_buf;
2460 if (b == 10 && *q == '0') {
2461 b = 8;
2462 q++;
2464 n = 0;
2465 while(1) {
2466 t = *q++;
2467 /* no need for checks except for base 10 / 8 errors */
2468 if (t == '\0')
2469 break;
2470 else if (t >= 'a')
2471 t = t - 'a' + 10;
2472 else if (t >= 'A')
2473 t = t - 'A' + 10;
2474 else
2475 t = t - '0';
2476 if (t >= b)
2477 tcc_error("invalid digit");
2478 n1 = n;
2479 n = n * b + t;
2480 /* detect overflow */
2481 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2482 ov = 1;
2485 /* Determine the characteristics (unsigned and/or 64bit) the type of
2486 the constant must have according to the constant suffix(es) */
2487 lcount = ucount = 0;
2488 p1 = p;
2489 for(;;) {
2490 t = toup(ch);
2491 if (t == 'L') {
2492 if (lcount >= 2)
2493 tcc_error("three 'l's in integer constant");
2494 if (lcount && *(p - 1) != ch)
2495 tcc_error("incorrect integer suffix: %s", p1);
2496 lcount++;
2497 ch = *p++;
2498 } else if (t == 'U') {
2499 if (ucount >= 1)
2500 tcc_error("two 'u's in integer constant");
2501 ucount++;
2502 ch = *p++;
2503 } else {
2504 break;
2508 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2509 if (ucount == 0 && b == 10) {
2510 if (lcount <= (LONG_SIZE == 4)) {
2511 if (n >= 0x80000000U)
2512 lcount = (LONG_SIZE == 4) + 1;
2514 if (n >= 0x8000000000000000ULL)
2515 ov = 1, ucount = 1;
2516 } else {
2517 if (lcount <= (LONG_SIZE == 4)) {
2518 if (n >= 0x100000000ULL)
2519 lcount = (LONG_SIZE == 4) + 1;
2520 else if (n >= 0x80000000U)
2521 ucount = 1;
2523 if (n >= 0x8000000000000000ULL)
2524 ucount = 1;
2527 if (ov)
2528 tcc_warning("integer constant overflow");
2530 tok = TOK_CINT;
2531 if (lcount) {
2532 tok = TOK_CLONG;
2533 if (lcount == 2)
2534 tok = TOK_CLLONG;
2536 if (ucount)
2537 ++tok; /* TOK_CU... */
2538 tokc.i = n;
2540 if (ch)
2541 tcc_error("invalid number");
2545 #define PARSE2(c1, tok1, c2, tok2) \
2546 case c1: \
2547 PEEKC(c, p); \
2548 if (c == c2) { \
2549 p++; \
2550 tok = tok2; \
2551 } else { \
2552 tok = tok1; \
2554 break;
2556 /* return next token without macro substitution */
2557 static inline void next_nomacro1(void)
2559 int t, c, is_long, len;
2560 TokenSym *ts;
2561 uint8_t *p, *p1;
2562 unsigned int h;
2564 p = file->buf_ptr;
2565 redo_no_start:
2566 c = *p;
2567 switch(c) {
2568 case ' ':
2569 case '\t':
2570 tok = c;
2571 p++;
2572 maybe_space:
2573 if (parse_flags & PARSE_FLAG_SPACES)
2574 goto keep_tok_flags;
2575 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2576 ++p;
2577 goto redo_no_start;
2578 case '\f':
2579 case '\v':
2580 case '\r':
2581 p++;
2582 goto redo_no_start;
2583 case '\\':
2584 /* first look if it is in fact an end of buffer */
2585 c = handle_stray(&p);
2586 if (c == '\\')
2587 goto parse_simple;
2588 if (c == CH_EOF) {
2589 TCCState *s1 = tcc_state;
2590 if ((parse_flags & PARSE_FLAG_LINEFEED)
2591 && !(tok_flags & TOK_FLAG_EOF)) {
2592 tok_flags |= TOK_FLAG_EOF;
2593 tok = TOK_LINEFEED;
2594 goto keep_tok_flags;
2595 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2596 tok = TOK_EOF;
2597 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2598 tcc_error("missing #endif");
2599 } else if (s1->include_stack_ptr == s1->include_stack) {
2600 /* no include left : end of file. */
2601 tok = TOK_EOF;
2602 } else {
2603 tok_flags &= ~TOK_FLAG_EOF;
2604 /* pop include file */
2606 /* test if previous '#endif' was after a #ifdef at
2607 start of file */
2608 if (tok_flags & TOK_FLAG_ENDIF) {
2609 #ifdef INC_DEBUG
2610 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2611 #endif
2612 search_cached_include(s1, file->filename, 1)
2613 ->ifndef_macro = file->ifndef_macro_saved;
2614 tok_flags &= ~TOK_FLAG_ENDIF;
2617 /* add end of include file debug info */
2618 tcc_debug_eincl(tcc_state);
2619 /* pop include stack */
2620 tcc_close();
2621 s1->include_stack_ptr--;
2622 p = file->buf_ptr;
2623 if (p == file->buffer)
2624 tok_flags = TOK_FLAG_BOF;
2625 tok_flags |= TOK_FLAG_BOL;
2626 goto redo_no_start;
2628 } else {
2629 goto redo_no_start;
2631 break;
2633 case '\n':
2634 file->line_num++;
2635 tok_flags |= TOK_FLAG_BOL;
2636 p++;
2637 maybe_newline:
2638 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2639 goto redo_no_start;
2640 tok = TOK_LINEFEED;
2641 goto keep_tok_flags;
2643 case '#':
2644 /* XXX: simplify */
2645 PEEKC(c, p);
2646 if ((tok_flags & TOK_FLAG_BOL) &&
2647 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2648 file->buf_ptr = p;
2649 preprocess(tok_flags & TOK_FLAG_BOF);
2650 p = file->buf_ptr;
2651 goto maybe_newline;
2652 } else {
2653 if (c == '#') {
2654 p++;
2655 tok = TOK_TWOSHARPS;
2656 } else {
2657 #if !defined(TCC_TARGET_ARM)
2658 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2659 p = parse_line_comment(p - 1);
2660 goto redo_no_start;
2661 } else
2662 #endif
2664 tok = '#';
2668 break;
2670 /* dollar is allowed to start identifiers when not parsing asm */
2671 case '$':
2672 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2673 || (parse_flags & PARSE_FLAG_ASM_FILE))
2674 goto parse_simple;
2676 case 'a': case 'b': case 'c': case 'd':
2677 case 'e': case 'f': case 'g': case 'h':
2678 case 'i': case 'j': case 'k': case 'l':
2679 case 'm': case 'n': case 'o': case 'p':
2680 case 'q': case 'r': case 's': case 't':
2681 case 'u': case 'v': case 'w': case 'x':
2682 case 'y': case 'z':
2683 case 'A': case 'B': case 'C': case 'D':
2684 case 'E': case 'F': case 'G': case 'H':
2685 case 'I': case 'J': case 'K':
2686 case 'M': case 'N': case 'O': case 'P':
2687 case 'Q': case 'R': case 'S': case 'T':
2688 case 'U': case 'V': case 'W': case 'X':
2689 case 'Y': case 'Z':
2690 case '_':
2691 parse_ident_fast:
2692 p1 = p;
2693 h = TOK_HASH_INIT;
2694 h = TOK_HASH_FUNC(h, c);
2695 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2696 h = TOK_HASH_FUNC(h, c);
2697 len = p - p1;
2698 if (c != '\\') {
2699 TokenSym **pts;
2701 /* fast case : no stray found, so we have the full token
2702 and we have already hashed it */
2703 h &= (TOK_HASH_SIZE - 1);
2704 pts = &hash_ident[h];
2705 for(;;) {
2706 ts = *pts;
2707 if (!ts)
2708 break;
2709 if (ts->len == len && !memcmp(ts->str, p1, len))
2710 goto token_found;
2711 pts = &(ts->hash_next);
2713 ts = tok_alloc_new(pts, (char *) p1, len);
2714 token_found: ;
2715 } else {
2716 /* slower case */
2717 cstr_reset(&tokcstr);
2718 cstr_cat(&tokcstr, (char *) p1, len);
2719 p--;
2720 PEEKC(c, p);
2721 parse_ident_slow:
2722 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2724 cstr_ccat(&tokcstr, c);
2725 PEEKC(c, p);
2727 ts = tok_alloc(tokcstr.data, tokcstr.size);
2729 tok = ts->tok;
2730 break;
2731 case 'L':
2732 t = p[1];
2733 if (t != '\\' && t != '\'' && t != '\"') {
2734 /* fast case */
2735 goto parse_ident_fast;
2736 } else {
2737 PEEKC(c, p);
2738 if (c == '\'' || c == '\"') {
2739 is_long = 1;
2740 goto str_const;
2741 } else {
2742 cstr_reset(&tokcstr);
2743 cstr_ccat(&tokcstr, 'L');
2744 goto parse_ident_slow;
2747 break;
2749 case '0': case '1': case '2': case '3':
2750 case '4': case '5': case '6': case '7':
2751 case '8': case '9':
2752 t = c;
2753 PEEKC(c, p);
2754 /* after the first digit, accept digits, alpha, '.' or sign if
2755 prefixed by 'eEpP' */
2756 parse_num:
2757 cstr_reset(&tokcstr);
2758 for(;;) {
2759 cstr_ccat(&tokcstr, t);
2760 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2761 || c == '.'
2762 || ((c == '+' || c == '-')
2763 && (((t == 'e' || t == 'E')
2764 && !(parse_flags & PARSE_FLAG_ASM_FILE
2765 /* 0xe+1 is 3 tokens in asm */
2766 && ((char*)tokcstr.data)[0] == '0'
2767 && toup(((char*)tokcstr.data)[1]) == 'X'))
2768 || t == 'p' || t == 'P'))))
2769 break;
2770 t = c;
2771 PEEKC(c, p);
2773 /* We add a trailing '\0' to ease parsing */
2774 cstr_ccat(&tokcstr, '\0');
2775 tokc.str.size = tokcstr.size;
2776 tokc.str.data = tokcstr.data;
2777 tok = TOK_PPNUM;
2778 break;
2780 case '.':
2781 /* special dot handling because it can also start a number */
2782 PEEKC(c, p);
2783 if (isnum(c)) {
2784 t = '.';
2785 goto parse_num;
2786 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2787 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2788 *--p = c = '.';
2789 goto parse_ident_fast;
2790 } else if (c == '.') {
2791 PEEKC(c, p);
2792 if (c == '.') {
2793 p++;
2794 tok = TOK_DOTS;
2795 } else {
2796 *--p = '.'; /* may underflow into file->unget[] */
2797 tok = '.';
2799 } else {
2800 tok = '.';
2802 break;
2803 case '\'':
2804 case '\"':
2805 is_long = 0;
2806 str_const:
2807 cstr_reset(&tokcstr);
2808 if (is_long)
2809 cstr_ccat(&tokcstr, 'L');
2810 cstr_ccat(&tokcstr, c);
2811 p = parse_pp_string(p, c, &tokcstr);
2812 cstr_ccat(&tokcstr, c);
2813 cstr_ccat(&tokcstr, '\0');
2814 tokc.str.size = tokcstr.size;
2815 tokc.str.data = tokcstr.data;
2816 tok = TOK_PPSTR;
2817 break;
2819 case '<':
2820 PEEKC(c, p);
2821 if (c == '=') {
2822 p++;
2823 tok = TOK_LE;
2824 } else if (c == '<') {
2825 PEEKC(c, p);
2826 if (c == '=') {
2827 p++;
2828 tok = TOK_A_SHL;
2829 } else {
2830 tok = TOK_SHL;
2832 } else {
2833 tok = TOK_LT;
2835 break;
2836 case '>':
2837 PEEKC(c, p);
2838 if (c == '=') {
2839 p++;
2840 tok = TOK_GE;
2841 } else if (c == '>') {
2842 PEEKC(c, p);
2843 if (c == '=') {
2844 p++;
2845 tok = TOK_A_SAR;
2846 } else {
2847 tok = TOK_SAR;
2849 } else {
2850 tok = TOK_GT;
2852 break;
2854 case '&':
2855 PEEKC(c, p);
2856 if (c == '&') {
2857 p++;
2858 tok = TOK_LAND;
2859 } else if (c == '=') {
2860 p++;
2861 tok = TOK_A_AND;
2862 } else {
2863 tok = '&';
2865 break;
2867 case '|':
2868 PEEKC(c, p);
2869 if (c == '|') {
2870 p++;
2871 tok = TOK_LOR;
2872 } else if (c == '=') {
2873 p++;
2874 tok = TOK_A_OR;
2875 } else {
2876 tok = '|';
2878 break;
2880 case '+':
2881 PEEKC(c, p);
2882 if (c == '+') {
2883 p++;
2884 tok = TOK_INC;
2885 } else if (c == '=') {
2886 p++;
2887 tok = TOK_A_ADD;
2888 } else {
2889 tok = '+';
2891 break;
2893 case '-':
2894 PEEKC(c, p);
2895 if (c == '-') {
2896 p++;
2897 tok = TOK_DEC;
2898 } else if (c == '=') {
2899 p++;
2900 tok = TOK_A_SUB;
2901 } else if (c == '>') {
2902 p++;
2903 tok = TOK_ARROW;
2904 } else {
2905 tok = '-';
2907 break;
2909 PARSE2('!', '!', '=', TOK_NE)
2910 PARSE2('=', '=', '=', TOK_EQ)
2911 PARSE2('*', '*', '=', TOK_A_MUL)
2912 PARSE2('%', '%', '=', TOK_A_MOD)
2913 PARSE2('^', '^', '=', TOK_A_XOR)
2915 /* comments or operator */
2916 case '/':
2917 PEEKC(c, p);
2918 if (c == '*') {
2919 p = parse_comment(p);
2920 /* comments replaced by a blank */
2921 tok = ' ';
2922 goto maybe_space;
2923 } else if (c == '/') {
2924 p = parse_line_comment(p);
2925 tok = ' ';
2926 goto maybe_space;
2927 } else if (c == '=') {
2928 p++;
2929 tok = TOK_A_DIV;
2930 } else {
2931 tok = '/';
2933 break;
2935 /* simple tokens */
2936 case '(':
2937 case ')':
2938 case '[':
2939 case ']':
2940 case '{':
2941 case '}':
2942 case ',':
2943 case ';':
2944 case ':':
2945 case '?':
2946 case '~':
2947 case '@': /* only used in assembler */
2948 parse_simple:
2949 tok = c;
2950 p++;
2951 break;
2952 default:
2953 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2954 goto parse_ident_fast;
2955 if (parse_flags & PARSE_FLAG_ASM_FILE)
2956 goto parse_simple;
2957 tcc_error("unrecognized character \\x%02x", c);
2958 break;
2960 tok_flags = 0;
2961 keep_tok_flags:
2962 file->buf_ptr = p;
2963 #if defined(PARSE_DEBUG)
2964 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
2965 #endif
2968 static void macro_subst(
2969 TokenString *tok_str,
2970 Sym **nested_list,
2971 const int *macro_str
2974 /* substitute arguments in replacement lists in macro_str by the values in
2975 args (field d) and return allocated string */
2976 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2978 int t, t0, t1, spc;
2979 const int *st;
2980 Sym *s;
2981 CValue cval;
2982 TokenString str;
2984 tok_str_new(&str);
2985 t0 = t1 = 0;
2986 while(1) {
2987 TOK_GET(&t, &macro_str, &cval);
2988 if (!t)
2989 break;
2990 if (t == '#') {
2991 /* stringize */
2992 TOK_GET(&t, &macro_str, &cval);
2993 if (!t)
2994 goto bad_stringy;
2995 s = sym_find2(args, t);
2996 if (s) {
2997 cstr_reset(&tokcstr);
2998 cstr_ccat(&tokcstr, '\"');
2999 st = s->d;
3000 spc = 0;
3001 while (*st >= 0) {
3002 TOK_GET(&t, &st, &cval);
3003 if (t != TOK_PLCHLDR
3004 && t != TOK_NOSUBST
3005 && 0 == check_space(t, &spc)) {
3006 const char *s = get_tok_str(t, &cval);
3007 while (*s) {
3008 if (t == TOK_PPSTR && *s != '\'')
3009 add_char(&tokcstr, *s);
3010 else
3011 cstr_ccat(&tokcstr, *s);
3012 ++s;
3016 tokcstr.size -= spc;
3017 cstr_ccat(&tokcstr, '\"');
3018 cstr_ccat(&tokcstr, '\0');
3019 #ifdef PP_DEBUG
3020 printf("\nstringize: <%s>\n", (char *)tokcstr.data);
3021 #endif
3022 /* add string */
3023 cval.str.size = tokcstr.size;
3024 cval.str.data = tokcstr.data;
3025 tok_str_add2(&str, TOK_PPSTR, &cval);
3026 } else {
3027 bad_stringy:
3028 expect("macro parameter after '#'");
3030 } else if (t >= TOK_IDENT) {
3031 s = sym_find2(args, t);
3032 if (s) {
3033 st = s->d;
3034 /* if '##' is present before or after, no arg substitution */
3035 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
3036 /* special case for var arg macros : ## eats the ','
3037 if empty VA_ARGS variable. */
3038 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
3039 if (*st <= 0) {
3040 /* suppress ',' '##' */
3041 str.len -= 2;
3042 } else {
3043 /* suppress '##' and add variable */
3044 str.len--;
3045 goto add_var;
3048 } else {
3049 add_var:
3050 if (!s->next) {
3051 /* Expand arguments tokens and store them. In most
3052 cases we could also re-expand each argument if
3053 used multiple times, but not if the argument
3054 contains the __COUNTER__ macro. */
3055 TokenString str2;
3056 sym_push2(&s->next, s->v, s->type.t, 0);
3057 tok_str_new(&str2);
3058 macro_subst(&str2, nested_list, st);
3059 tok_str_add(&str2, 0);
3060 s->next->d = str2.str;
3062 st = s->next->d;
3064 if (*st <= 0) {
3065 /* expanded to empty string */
3066 tok_str_add(&str, TOK_PLCHLDR);
3067 } else for (;;) {
3068 int t2;
3069 TOK_GET(&t2, &st, &cval);
3070 if (t2 <= 0)
3071 break;
3072 tok_str_add2(&str, t2, &cval);
3074 } else {
3075 tok_str_add(&str, t);
3077 } else {
3078 tok_str_add2(&str, t, &cval);
3080 t0 = t1, t1 = t;
3082 tok_str_add(&str, 0);
3083 return str.str;
3086 static char const ab_month_name[12][4] =
3088 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3089 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3092 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3094 int n, ret = 1;
3096 cstr_reset(&tokcstr);
3097 if (t1 != TOK_PLCHLDR)
3098 cstr_cat(&tokcstr, get_tok_str(t1, v1), -1);
3099 n = tokcstr.size;
3100 if (t2 != TOK_PLCHLDR)
3101 cstr_cat(&tokcstr, get_tok_str(t2, v2), -1);
3102 cstr_ccat(&tokcstr, '\0');
3103 //printf("paste <%s>\n", (char*)tokcstr.data);
3105 tcc_open_bf(tcc_state, ":paste:", tokcstr.size);
3106 memcpy(file->buffer, tokcstr.data, tokcstr.size);
3107 tok_flags = 0;
3108 for (;;) {
3109 next_nomacro1();
3110 if (0 == *file->buf_ptr)
3111 break;
3112 if (is_space(tok))
3113 continue;
3114 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3115 " preprocessing token", n, file->buffer, file->buffer + n);
3116 ret = 0;
3117 break;
3119 tcc_close();
3120 return ret;
3123 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3124 return the resulting string (which must be freed). */
3125 static inline int *macro_twosharps(const int *ptr0)
3127 int t;
3128 CValue cval;
3129 TokenString macro_str1;
3130 int start_of_nosubsts = -1;
3131 const int *ptr;
3133 /* we search the first '##' */
3134 for (ptr = ptr0;;) {
3135 TOK_GET(&t, &ptr, &cval);
3136 if (t == TOK_PPJOIN)
3137 break;
3138 if (t == 0)
3139 return NULL;
3142 tok_str_new(&macro_str1);
3144 //tok_print(" $$$", ptr0);
3145 for (ptr = ptr0;;) {
3146 TOK_GET(&t, &ptr, &cval);
3147 if (t == 0)
3148 break;
3149 if (t == TOK_PPJOIN)
3150 continue;
3151 while (*ptr == TOK_PPJOIN) {
3152 int t1; CValue cv1;
3153 /* given 'a##b', remove nosubsts preceding 'a' */
3154 if (start_of_nosubsts >= 0)
3155 macro_str1.len = start_of_nosubsts;
3156 /* given 'a##b', remove nosubsts preceding 'b' */
3157 while ((t1 = *++ptr) == TOK_NOSUBST)
3159 if (t1 && t1 != TOK_PPJOIN) {
3160 TOK_GET(&t1, &ptr, &cv1);
3161 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3162 if (paste_tokens(t, &cval, t1, &cv1)) {
3163 t = tok, cval = tokc;
3164 } else {
3165 tok_str_add2(&macro_str1, t, &cval);
3166 t = t1, cval = cv1;
3171 if (t == TOK_NOSUBST) {
3172 if (start_of_nosubsts < 0)
3173 start_of_nosubsts = macro_str1.len;
3174 } else {
3175 start_of_nosubsts = -1;
3177 tok_str_add2(&macro_str1, t, &cval);
3179 tok_str_add(&macro_str1, 0);
3180 //tok_print(" ###", macro_str1.str);
3181 return macro_str1.str;
3184 /* peek or read [ws_str == NULL] next token from function macro call,
3185 walking up macro levels up to the file if necessary */
3186 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3188 int t;
3189 const int *p;
3190 Sym *sa;
3192 for (;;) {
3193 if (macro_ptr) {
3194 p = macro_ptr, t = *p;
3195 if (ws_str) {
3196 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3197 tok_str_add(ws_str, t), t = *++p;
3199 if (t == 0) {
3200 end_macro();
3201 /* also, end of scope for nested defined symbol */
3202 sa = *nested_list;
3203 while (sa && sa->v == 0)
3204 sa = sa->prev;
3205 if (sa)
3206 sa->v = 0;
3207 continue;
3209 } else {
3210 uint8_t *p = file->buf_ptr;
3211 int ch = handle_bs(&p);
3212 if (ws_str) {
3213 while (is_space(ch) || ch == '\n' || ch == '/') {
3214 if (ch == '/') {
3215 int c;
3216 PEEKC(c, p);
3217 if (c == '*') {
3218 p = parse_comment(p) - 1;
3219 } else if (c == '/') {
3220 p = parse_line_comment(p) - 1;
3221 } else {
3222 *--p = ch;
3223 break;
3225 ch = ' ';
3227 if (ch == '\n')
3228 file->line_num++;
3229 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3230 tok_str_add(ws_str, ch);
3231 PEEKC(ch, p);
3234 file->buf_ptr = p;
3235 t = ch;
3238 if (ws_str)
3239 return t;
3240 next_nomacro();
3241 return tok;
3245 /* do macro substitution of current token with macro 's' and add
3246 result to (tok_str,tok_len). 'nested_list' is the list of all
3247 macros we got inside to avoid recursing. Return non zero if no
3248 substitution needs to be done */
3249 static int macro_subst_tok(
3250 TokenString *tok_str,
3251 Sym **nested_list,
3252 Sym *s)
3254 Sym *args, *sa, *sa1;
3255 int parlevel, t, t1, spc;
3256 TokenString str;
3257 char *cstrval;
3258 CValue cval;
3259 char buf[32];
3261 /* if symbol is a macro, prepare substitution */
3262 /* special macros */
3263 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3264 t = tok == TOK___LINE__ ? file->line_num : pp_counter++;
3265 snprintf(buf, sizeof(buf), "%d", t);
3266 cstrval = buf;
3267 t1 = TOK_PPNUM;
3268 goto add_cstr1;
3269 } else if (tok == TOK___FILE__) {
3270 cstrval = file->filename;
3271 goto add_cstr;
3272 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3273 time_t ti;
3274 struct tm *tm;
3276 time(&ti);
3277 tm = localtime(&ti);
3278 if (tok == TOK___DATE__) {
3279 snprintf(buf, sizeof(buf), "%s %2d %d",
3280 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3281 } else {
3282 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3283 tm->tm_hour, tm->tm_min, tm->tm_sec);
3285 cstrval = buf;
3286 add_cstr:
3287 t1 = TOK_STR;
3288 add_cstr1:
3289 cstr_reset(&tokcstr);
3290 cstr_cat(&tokcstr, cstrval, 0);
3291 cval.str.size = tokcstr.size;
3292 cval.str.data = tokcstr.data;
3293 tok_str_add2(tok_str, t1, &cval);
3294 } else if (s->d) {
3295 int saved_parse_flags = parse_flags;
3296 int *joined_str = NULL;
3297 int *mstr = s->d;
3299 if (s->type.t == MACRO_FUNC) {
3300 /* whitespace between macro name and argument list */
3301 TokenString ws_str;
3302 tok_str_new(&ws_str);
3304 spc = 0;
3305 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3306 | PARSE_FLAG_ACCEPT_STRAYS;
3308 /* get next token from argument stream */
3309 t = next_argstream(nested_list, &ws_str);
3310 if (t != '(') {
3311 /* not a macro substitution after all, restore the
3312 * macro token plus all whitespace we've read.
3313 * whitespace is intentionally not merged to preserve
3314 * newlines. */
3315 parse_flags = saved_parse_flags;
3316 tok_str_add(tok_str, tok);
3317 if (parse_flags & PARSE_FLAG_SPACES) {
3318 int i;
3319 for (i = 0; i < ws_str.len; i++)
3320 tok_str_add(tok_str, ws_str.str[i]);
3322 if (ws_str.len && ws_str.str[ws_str.len - 1] == '\n')
3323 tok_flags |= TOK_FLAG_BOL;
3324 tok_str_free_str(ws_str.str);
3325 return 0;
3326 } else {
3327 tok_str_free_str(ws_str.str);
3329 do {
3330 next_nomacro(); /* eat '(' */
3331 } while (tok == TOK_PLCHLDR || is_space(tok));
3333 /* argument macro */
3334 args = NULL;
3335 sa = s->next;
3336 /* NOTE: empty args are allowed, except if no args */
3337 for(;;) {
3338 do {
3339 next_argstream(nested_list, NULL);
3340 } while (tok == TOK_PLCHLDR || is_space(tok) ||
3341 TOK_LINEFEED == tok);
3342 empty_arg:
3343 /* handle '()' case */
3344 if (!args && !sa && tok == ')')
3345 break;
3346 if (!sa)
3347 tcc_error("macro '%s' used with too many args",
3348 get_tok_str(s->v, 0));
3349 tok_str_new(&str);
3350 parlevel = spc = 0;
3351 /* NOTE: non zero sa->t indicates VA_ARGS */
3352 while ((parlevel > 0 ||
3353 (tok != ')' &&
3354 (tok != ',' || sa->type.t)))) {
3355 if (tok == TOK_EOF || tok == 0)
3356 break;
3357 if (tok == '(')
3358 parlevel++;
3359 else if (tok == ')')
3360 parlevel--;
3361 if (tok == TOK_LINEFEED)
3362 tok = ' ';
3363 if (!check_space(tok, &spc))
3364 tok_str_add2(&str, tok, &tokc);
3365 next_argstream(nested_list, NULL);
3367 if (parlevel)
3368 expect(")");
3369 str.len -= spc;
3370 tok_str_add(&str, -1);
3371 tok_str_add(&str, 0);
3372 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3373 sa1->d = str.str;
3374 sa = sa->next;
3375 if (tok == ')') {
3376 /* special case for gcc var args: add an empty
3377 var arg argument if it is omitted */
3378 if (sa && sa->type.t && gnu_ext)
3379 goto empty_arg;
3380 break;
3382 if (tok != ',')
3383 expect(",");
3385 if (sa) {
3386 tcc_error("macro '%s' used with too few args",
3387 get_tok_str(s->v, 0));
3390 /* now subst each arg */
3391 mstr = macro_arg_subst(nested_list, mstr, args);
3392 /* free memory */
3393 sa = args;
3394 while (sa) {
3395 sa1 = sa->prev;
3396 tok_str_free_str(sa->d);
3397 if (sa->next) {
3398 tok_str_free_str(sa->next->d);
3399 sym_free(sa->next);
3401 sym_free(sa);
3402 sa = sa1;
3404 parse_flags = saved_parse_flags;
3407 sym_push2(nested_list, s->v, 0, 0);
3408 parse_flags = saved_parse_flags;
3409 joined_str = macro_twosharps(mstr);
3410 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3412 /* pop nested defined symbol */
3413 sa1 = *nested_list;
3414 *nested_list = sa1->prev;
3415 sym_free(sa1);
3416 if (joined_str)
3417 tok_str_free_str(joined_str);
3418 if (mstr != s->d)
3419 tok_str_free_str(mstr);
3421 return 0;
3424 /* do macro substitution of macro_str and add result to
3425 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3426 inside to avoid recursing. */
3427 static void macro_subst(
3428 TokenString *tok_str,
3429 Sym **nested_list,
3430 const int *macro_str
3433 Sym *s;
3434 int t, spc, nosubst;
3435 CValue cval;
3437 spc = nosubst = 0;
3439 while (1) {
3440 TOK_GET(&t, &macro_str, &cval);
3441 if (t <= 0)
3442 break;
3444 if (t >= TOK_IDENT && 0 == nosubst) {
3445 s = define_find(t);
3446 if (s == NULL)
3447 goto no_subst;
3449 /* if nested substitution, do nothing */
3450 if (sym_find2(*nested_list, t)) {
3451 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3452 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3453 goto no_subst;
3457 TokenString *str = tok_str_alloc();
3458 str->str = (int*)macro_str;
3459 begin_macro(str, 2);
3461 tok = t;
3462 macro_subst_tok(tok_str, nested_list, s);
3464 if (macro_stack != str) {
3465 /* already finished by reading function macro arguments */
3466 break;
3469 macro_str = macro_ptr;
3470 end_macro ();
3472 if (tok_str->len)
3473 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3474 } else {
3475 no_subst:
3476 if (!check_space(t, &spc))
3477 tok_str_add2(tok_str, t, &cval);
3479 if (nosubst) {
3480 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3481 continue;
3482 nosubst = 0;
3484 if (t == TOK_NOSUBST)
3485 nosubst = 1;
3487 /* GCC supports 'defined' as result of a macro substitution */
3488 if (t == TOK_DEFINED && pp_expr)
3489 nosubst = 2;
3493 /* return next token without macro substitution. Can read input from
3494 macro_ptr buffer */
3495 static void next_nomacro(void)
3497 int t;
3498 if (macro_ptr) {
3499 redo:
3500 t = *macro_ptr;
3501 if (TOK_HAS_VALUE(t)) {
3502 tok_get(&tok, &macro_ptr, &tokc);
3503 if (t == TOK_LINENUM) {
3504 file->line_num = tokc.i;
3505 goto redo;
3507 } else {
3508 macro_ptr++;
3509 if (t < TOK_IDENT) {
3510 if (!(parse_flags & PARSE_FLAG_SPACES)
3511 && (isidnum_table[t - CH_EOF] & IS_SPC))
3512 goto redo;
3514 tok = t;
3516 } else {
3517 next_nomacro1();
3521 /* return next token with macro substitution */
3522 ST_FUNC void next(void)
3524 int t;
3525 redo:
3526 next_nomacro();
3527 t = tok;
3528 if (macro_ptr) {
3529 if (!TOK_HAS_VALUE(t)) {
3530 if (t == TOK_NOSUBST || t == TOK_PLCHLDR) {
3531 /* discard preprocessor markers */
3532 goto redo;
3533 } else if (t == 0) {
3534 /* end of macro or unget token string */
3535 end_macro();
3536 goto redo;
3537 } else if (t == '\\') {
3538 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3539 tcc_error("stray '\\' in program");
3541 return;
3543 } else if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3544 /* if reading from file, try to substitute macros */
3545 Sym *s = define_find(t);
3546 if (s) {
3547 Sym *nested_list = NULL;
3548 tokstr_buf.len = 0;
3549 macro_subst_tok(&tokstr_buf, &nested_list, s);
3550 tok_str_add(&tokstr_buf, 0);
3551 begin_macro(&tokstr_buf, 0);
3552 goto redo;
3554 return;
3556 /* convert preprocessor tokens into C tokens */
3557 if (t == TOK_PPNUM) {
3558 if (parse_flags & PARSE_FLAG_TOK_NUM)
3559 parse_number((char *)tokc.str.data);
3560 } else if (t == TOK_PPSTR) {
3561 if (parse_flags & PARSE_FLAG_TOK_STR)
3562 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3566 /* push back current token and set current token to 'last_tok'. Only
3567 identifier case handled for labels. */
3568 ST_INLN void unget_tok(int last_tok)
3571 TokenString *str = tok_str_alloc();
3572 tok_str_add2(str, tok, &tokc);
3573 tok_str_add(str, 0);
3574 begin_macro(str, 1);
3575 tok = last_tok;
3578 /* ------------------------------------------------------------------------- */
3579 /* init preprocessor */
3581 static const char * const target_os_defs =
3582 #ifdef TCC_TARGET_PE
3583 "_WIN32\0"
3584 # if PTR_SIZE == 8
3585 "_WIN64\0"
3586 # endif
3587 #else
3588 # if defined TCC_TARGET_MACHO
3589 "__APPLE__\0"
3590 # elif TARGETOS_FreeBSD
3591 "__FreeBSD__ 12\0"
3592 # elif TARGETOS_FreeBSD_kernel
3593 "__FreeBSD_kernel__\0"
3594 # elif TARGETOS_NetBSD
3595 "__NetBSD__\0"
3596 # elif TARGETOS_OpenBSD
3597 "__OpenBSD__\0"
3598 # else
3599 "__linux__\0"
3600 "__linux\0"
3601 # if TARGETOS_ANDROID
3602 "__ANDROID__\0"
3603 # endif
3604 # endif
3605 "__unix__\0"
3606 "__unix\0"
3607 #endif
3610 static void putdef(CString *cs, const char *p)
3612 cstr_printf(cs, "#define %s%s\n", p, &" 1"[!!strchr(p, ' ')*2]);
3615 static void putdefs(CString *cs, const char *p)
3617 while (*p)
3618 putdef(cs, p), p = strchr(p, 0) + 1;
3621 static void tcc_predefs(TCCState *s1, CString *cs, int is_asm)
3623 int a, b, c;
3625 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
3626 cstr_printf(cs, "#define __TINYC__ %d\n", a*10000 + b*100 + c);
3628 putdefs(cs, target_machine_defs);
3629 putdefs(cs, target_os_defs);
3631 #ifdef TCC_TARGET_ARM
3632 if (s1->float_abi == ARM_HARD_FLOAT)
3633 putdef(cs, "__ARM_PCS_VFP");
3634 #endif
3635 if (is_asm)
3636 putdef(cs, "__ASSEMBLER__");
3637 if (s1->output_type == TCC_OUTPUT_PREPROCESS)
3638 putdef(cs, "__TCC_PP__");
3639 if (s1->output_type == TCC_OUTPUT_MEMORY)
3640 putdef(cs, "__TCC_RUN__");
3641 #ifdef CONFIG_TCC_BACKTRACE
3642 if (s1->do_backtrace)
3643 putdef(cs, "__TCC_BACKTRACE__");
3644 #endif
3645 #ifdef CONFIG_TCC_BCHECK
3646 if (s1->do_bounds_check)
3647 putdef(cs, "__TCC_BCHECK__");
3648 #endif
3649 if (s1->char_is_unsigned)
3650 putdef(cs, "__CHAR_UNSIGNED__");
3651 if (s1->optimize > 0)
3652 putdef(cs, "__OPTIMIZE__");
3653 if (s1->option_pthread)
3654 putdef(cs, "_REENTRANT");
3655 if (s1->leading_underscore)
3656 putdef(cs, "__leading_underscore");
3657 cstr_printf(cs, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE);
3658 cstr_printf(cs, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE);
3659 if (!is_asm) {
3660 putdef(cs, "__STDC__");
3661 cstr_printf(cs, "#define __STDC_VERSION__ %dL\n", s1->cversion);
3662 cstr_cat(cs,
3663 /* load more predefs and __builtins */
3664 #if CONFIG_TCC_PREDEFS
3665 #include "tccdefs_.h" /* include as strings */
3666 #else
3667 "#include <tccdefs.h>\n" /* load at runtime */
3668 #endif
3669 , -1);
3671 cstr_printf(cs, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3674 ST_FUNC void preprocess_start(TCCState *s1, int filetype)
3676 int is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
3678 tccpp_new(s1);
3680 s1->include_stack_ptr = s1->include_stack;
3681 s1->ifdef_stack_ptr = s1->ifdef_stack;
3682 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3683 pp_expr = 0;
3684 pp_counter = 0;
3685 pp_debug_tok = pp_debug_symv = 0;
3686 pp_once++;
3687 s1->pack_stack[0] = 0;
3688 s1->pack_stack_ptr = s1->pack_stack;
3690 set_idnum('$', !is_asm && s1->dollars_in_identifiers ? IS_ID : 0);
3691 set_idnum('.', is_asm ? IS_ID : 0);
3693 if (!(filetype & AFF_TYPE_ASM)) {
3694 CString cstr;
3695 cstr_new(&cstr);
3696 tcc_predefs(s1, &cstr, is_asm);
3697 if (s1->cmdline_defs.size)
3698 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3699 if (s1->cmdline_incl.size)
3700 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3701 //printf("%s\n", (char*)cstr.data);
3702 *s1->include_stack_ptr++ = file;
3703 tcc_open_bf(s1, "<command line>", cstr.size);
3704 memcpy(file->buffer, cstr.data, cstr.size);
3705 cstr_free(&cstr);
3708 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3709 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3712 /* cleanup from error/setjmp */
3713 ST_FUNC void preprocess_end(TCCState *s1)
3715 while (macro_stack)
3716 end_macro();
3717 macro_ptr = NULL;
3718 while (file)
3719 tcc_close();
3720 tccpp_delete(s1);
3723 ST_FUNC int set_idnum(int c, int val)
3725 int prev = isidnum_table[c - CH_EOF];
3726 isidnum_table[c - CH_EOF] = val;
3727 return prev;
3730 ST_FUNC void tccpp_new(TCCState *s)
3732 int i, c;
3733 const char *p, *r;
3735 /* init isid table */
3736 for(i = CH_EOF; i<128; i++)
3737 set_idnum(i,
3738 is_space(i) ? IS_SPC
3739 : isid(i) ? IS_ID
3740 : isnum(i) ? IS_NUM
3741 : 0);
3743 for(i = 128; i<256; i++)
3744 set_idnum(i, IS_ID);
3746 /* init allocators */
3747 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3748 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3750 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3751 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3753 cstr_new(&tokcstr);
3754 cstr_new(&cstr_buf);
3755 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3756 tok_str_new(&tokstr_buf);
3757 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3759 tok_ident = TOK_IDENT;
3760 p = tcc_keywords;
3761 while (*p) {
3762 r = p;
3763 for(;;) {
3764 c = *r++;
3765 if (c == '\0')
3766 break;
3768 tok_alloc(p, r - p - 1);
3769 p = r;
3772 /* we add dummy defines for some special macros to speed up tests
3773 and to have working defined() */
3774 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3775 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3776 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3777 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3778 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3781 ST_FUNC void tccpp_delete(TCCState *s)
3783 int i, n;
3785 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3787 /* free tokens */
3788 n = tok_ident - TOK_IDENT;
3789 if (n > total_idents)
3790 total_idents = n;
3791 for(i = 0; i < n; i++)
3792 tal_free(toksym_alloc, table_ident[i]);
3793 tcc_free(table_ident);
3794 table_ident = NULL;
3796 /* free static buffers */
3797 cstr_free(&tokcstr);
3798 cstr_free(&cstr_buf);
3799 tok_str_free_str(tokstr_buf.str);
3801 /* free allocators */
3802 tal_delete(toksym_alloc);
3803 toksym_alloc = NULL;
3804 tal_delete(tokstr_alloc);
3805 tokstr_alloc = NULL;
3808 /* ------------------------------------------------------------------------- */
3809 /* tcc -E [-P[1]] [-dD} support */
3811 static void tok_print(const char *msg, const int *str)
3813 FILE *fp;
3814 int t, s = 0;
3815 CValue cval;
3817 fp = tcc_state->ppfp;
3818 fprintf(fp, "%s", msg);
3819 while (str) {
3820 TOK_GET(&t, &str, &cval);
3821 if (!t)
3822 break;
3823 fprintf(fp, &" %s"[s], get_tok_str(t, &cval)), s = 1;
3825 fprintf(fp, "\n");
3828 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3830 int d = f->line_num - f->line_ref;
3832 if (s1->dflag & 4)
3833 return;
3835 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3837 } else if (level == 0 && f->line_ref && d < 8) {
3838 while (d > 0)
3839 fputs("\n", s1->ppfp), --d;
3840 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3841 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3842 } else {
3843 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3844 level > 0 ? " 1" : level < 0 ? " 2" : "");
3846 f->line_ref = f->line_num;
3849 static void define_print(TCCState *s1, int v)
3851 FILE *fp;
3852 Sym *s;
3854 s = define_find(v);
3855 if (NULL == s || NULL == s->d)
3856 return;
3858 fp = s1->ppfp;
3859 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3860 if (s->type.t == MACRO_FUNC) {
3861 Sym *a = s->next;
3862 fprintf(fp,"(");
3863 if (a)
3864 for (;;) {
3865 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3866 if (!(a = a->next))
3867 break;
3868 fprintf(fp,",");
3870 fprintf(fp,")");
3872 tok_print("", s->d);
3875 static void pp_debug_defines(TCCState *s1)
3877 int v, t;
3878 const char *vs;
3879 FILE *fp;
3881 t = pp_debug_tok;
3882 if (t == 0)
3883 return;
3885 file->line_num--;
3886 pp_line(s1, file, 0);
3887 file->line_ref = ++file->line_num;
3889 fp = s1->ppfp;
3890 v = pp_debug_symv;
3891 vs = get_tok_str(v, NULL);
3892 if (t == TOK_DEFINE) {
3893 define_print(s1, v);
3894 } else if (t == TOK_UNDEF) {
3895 fprintf(fp, "#undef %s\n", vs);
3896 } else if (t == TOK_push_macro) {
3897 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3898 } else if (t == TOK_pop_macro) {
3899 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3901 pp_debug_tok = 0;
3904 static void pp_debug_builtins(TCCState *s1)
3906 int v;
3907 for (v = TOK_IDENT; v < tok_ident; ++v)
3908 define_print(s1, v);
3911 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3912 static int pp_need_space(int a, int b)
3914 return 'E' == a ? '+' == b || '-' == b
3915 : '+' == a ? TOK_INC == b || '+' == b
3916 : '-' == a ? TOK_DEC == b || '-' == b
3917 : a >= TOK_IDENT ? b >= TOK_IDENT
3918 : a == TOK_PPNUM ? b >= TOK_IDENT
3919 : 0;
3922 /* maybe hex like 0x1e */
3923 static int pp_check_he0xE(int t, const char *p)
3925 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3926 return 'E';
3927 return t;
3930 /* Preprocess the current file */
3931 ST_FUNC int tcc_preprocess(TCCState *s1)
3933 BufferedFile **iptr;
3934 int token_seen, spcs, level;
3935 const char *p;
3936 char white[400];
3938 parse_flags = PARSE_FLAG_PREPROCESS
3939 | (parse_flags & PARSE_FLAG_ASM_FILE)
3940 | PARSE_FLAG_LINEFEED
3941 | PARSE_FLAG_SPACES
3942 | PARSE_FLAG_ACCEPT_STRAYS
3944 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3945 capability to compile and run itself, provided all numbers are
3946 given as decimals. tcc -E -P10 will do. */
3947 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3948 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3950 if (s1->do_bench) {
3951 /* for PP benchmarks */
3952 do next(); while (tok != TOK_EOF);
3953 return 0;
3956 if (s1->dflag & 1) {
3957 pp_debug_builtins(s1);
3958 s1->dflag &= ~1;
3961 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
3962 if (file->prev)
3963 pp_line(s1, file->prev, level++);
3964 pp_line(s1, file, level);
3965 for (;;) {
3966 iptr = s1->include_stack_ptr;
3967 next();
3968 if (tok == TOK_EOF)
3969 break;
3971 level = s1->include_stack_ptr - iptr;
3972 if (level) {
3973 if (level > 0)
3974 pp_line(s1, *iptr, 0);
3975 pp_line(s1, file, level);
3977 if (s1->dflag & 7) {
3978 pp_debug_defines(s1);
3979 if (s1->dflag & 4)
3980 continue;
3983 if (is_space(tok)) {
3984 if (spcs < sizeof white - 1)
3985 white[spcs++] = tok;
3986 continue;
3987 } else if (tok == TOK_LINEFEED) {
3988 spcs = 0;
3989 if (token_seen == TOK_LINEFEED)
3990 continue;
3991 ++file->line_ref;
3992 } else if (token_seen == TOK_LINEFEED) {
3993 pp_line(s1, file, 0);
3994 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
3995 white[spcs++] = ' ';
3998 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
3999 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
4000 token_seen = pp_check_he0xE(tok, p);
4002 return 0;
4005 /* ------------------------------------------------------------------------- */