Fix Makefile as suggested by Urs Janßen
[tinycc.git] / tccpp.c
bloba72f29e58312fa85fe92b0212a110f110ec43617
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #define USING_GLOBALS
22 #include "tcc.h"
24 /********************************************************/
25 /* global variables */
27 ST_DATA int tok_flags;
28 ST_DATA int parse_flags;
30 ST_DATA struct BufferedFile *file;
31 ST_DATA int ch, tok;
32 ST_DATA CValue tokc;
33 ST_DATA const int *macro_ptr;
34 ST_DATA CString tokcstr; /* current parsed string, if any */
36 /* display benchmark infos */
37 ST_DATA int tok_ident;
38 ST_DATA TokenSym **table_ident;
40 /* ------------------------------------------------------------------------- */
42 static TokenSym *hash_ident[TOK_HASH_SIZE];
43 static char token_buf[STRING_MAX_SIZE + 1];
44 static CString cstr_buf;
45 static CString macro_equal_buf;
46 static TokenString tokstr_buf;
47 static unsigned char isidnum_table[256 - CH_EOF];
48 static int pp_debug_tok, pp_debug_symv;
49 static int pp_once;
50 static int pp_expr;
51 static int pp_counter;
52 static void tok_print(const char *msg, const int *str);
54 static struct TinyAlloc *toksym_alloc;
55 static struct TinyAlloc *tokstr_alloc;
57 static TokenString *macro_stack;
59 static const char tcc_keywords[] =
60 #define DEF(id, str) str "\0"
61 #include "tcctok.h"
62 #undef DEF
65 /* WARNING: the content of this string encodes token numbers */
66 static const unsigned char tok_two_chars[] =
67 /* outdated -- gr
68 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
69 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
70 */{
71 '<','=', TOK_LE,
72 '>','=', TOK_GE,
73 '!','=', TOK_NE,
74 '&','&', TOK_LAND,
75 '|','|', TOK_LOR,
76 '+','+', TOK_INC,
77 '-','-', TOK_DEC,
78 '=','=', TOK_EQ,
79 '<','<', TOK_SHL,
80 '>','>', TOK_SAR,
81 '+','=', TOK_A_ADD,
82 '-','=', TOK_A_SUB,
83 '*','=', TOK_A_MUL,
84 '/','=', TOK_A_DIV,
85 '%','=', TOK_A_MOD,
86 '&','=', TOK_A_AND,
87 '^','=', TOK_A_XOR,
88 '|','=', TOK_A_OR,
89 '-','>', TOK_ARROW,
90 '.','.', TOK_TWODOTS,
91 '#','#', TOK_TWOSHARPS,
92 '#','#', TOK_PPJOIN,
96 static void next_nomacro(void);
98 ST_FUNC void skip(int c)
100 if (tok != c)
101 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
102 next();
105 ST_FUNC void expect(const char *msg)
107 tcc_error("%s expected", msg);
110 /* ------------------------------------------------------------------------- */
111 /* Custom allocator for tiny objects */
113 #define USE_TAL
115 #ifndef USE_TAL
116 #define tal_free(al, p) tcc_free(p)
117 #define tal_realloc(al, p, size) tcc_realloc(p, size)
118 #define tal_new(a,b,c)
119 #define tal_delete(a)
120 #else
121 #if !defined(MEM_DEBUG)
122 #define tal_free(al, p) tal_free_impl(al, p)
123 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
124 #define TAL_DEBUG_PARAMS
125 #else
126 #define TAL_DEBUG 1
127 //#define TAL_INFO 1 /* collect and dump allocators stats */
128 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
129 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
130 #define TAL_DEBUG_PARAMS , const char *file, int line
131 #define TAL_DEBUG_FILE_LEN 40
132 #endif
134 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
135 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
136 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
137 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
138 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
139 #define CSTR_TAL_LIMIT 1024
141 typedef struct TinyAlloc {
142 unsigned limit;
143 unsigned size;
144 uint8_t *buffer;
145 uint8_t *p;
146 unsigned nb_allocs;
147 struct TinyAlloc *next, *top;
148 #ifdef TAL_INFO
149 unsigned nb_peak;
150 unsigned nb_total;
151 unsigned nb_missed;
152 uint8_t *peak_p;
153 #endif
154 } TinyAlloc;
156 typedef struct tal_header_t {
157 unsigned size;
158 #ifdef TAL_DEBUG
159 int line_num; /* negative line_num used for double free check */
160 char file_name[TAL_DEBUG_FILE_LEN + 1];
161 #endif
162 } tal_header_t;
164 /* ------------------------------------------------------------------------- */
166 static TinyAlloc *tal_new(TinyAlloc **pal, unsigned limit, unsigned size)
168 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
169 al->p = al->buffer = tcc_malloc(size);
170 al->limit = limit;
171 al->size = size;
172 if (pal) *pal = al;
173 return al;
176 static void tal_delete(TinyAlloc *al)
178 TinyAlloc *next;
180 tail_call:
181 if (!al)
182 return;
183 #ifdef TAL_INFO
184 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
185 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
186 (al->peak_p - al->buffer) * 100.0 / al->size);
187 #endif
188 #ifdef TAL_DEBUG
189 if (al->nb_allocs > 0) {
190 uint8_t *p;
191 fprintf(stderr, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
192 al->nb_allocs, al->limit);
193 p = al->buffer;
194 while (p < al->p) {
195 tal_header_t *header = (tal_header_t *)p;
196 if (header->line_num > 0) {
197 fprintf(stderr, "%s:%d: chunk of %d bytes leaked\n",
198 header->file_name, header->line_num, header->size);
200 p += header->size + sizeof(tal_header_t);
202 #if MEM_DEBUG-0 == 2
203 exit(2);
204 #endif
206 #endif
207 next = al->next;
208 tcc_free(al->buffer);
209 tcc_free(al);
210 al = next;
211 goto tail_call;
214 static void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
216 if (!p)
217 return;
218 tail_call:
219 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
220 #ifdef TAL_DEBUG
221 tal_header_t *header = (((tal_header_t *)p) - 1);
222 if (header->line_num < 0) {
223 fprintf(stderr, "%s:%d: TAL_DEBUG: double frees chunk from\n",
224 file, line);
225 fprintf(stderr, "%s:%d: %d bytes\n",
226 header->file_name, (int)-header->line_num, (int)header->size);
227 } else
228 header->line_num = -header->line_num;
229 #endif
230 al->nb_allocs--;
231 if (!al->nb_allocs)
232 al->p = al->buffer;
233 } else if (al->next) {
234 al = al->next;
235 goto tail_call;
237 else
238 tcc_free(p);
241 static void *tal_realloc_impl(TinyAlloc **pal, void *p, unsigned size TAL_DEBUG_PARAMS)
243 tal_header_t *header;
244 void *ret;
245 int is_own;
246 unsigned adj_size = (size + 3) & -4;
247 TinyAlloc *al = *pal;
249 tail_call:
250 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
251 if ((!p || is_own) && size <= al->limit) {
252 if (al->p - al->buffer + adj_size + sizeof(tal_header_t) < al->size) {
253 header = (tal_header_t *)al->p;
254 header->size = adj_size;
255 #ifdef TAL_DEBUG
256 { int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
257 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
258 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
259 header->line_num = line; }
260 #endif
261 ret = al->p + sizeof(tal_header_t);
262 al->p += adj_size + sizeof(tal_header_t);
263 if (is_own) {
264 header = (((tal_header_t *)p) - 1);
265 if (p) memcpy(ret, p, header->size);
266 #ifdef TAL_DEBUG
267 header->line_num = -header->line_num;
268 #endif
269 } else {
270 al->nb_allocs++;
272 #ifdef TAL_INFO
273 if (al->nb_peak < al->nb_allocs)
274 al->nb_peak = al->nb_allocs;
275 if (al->peak_p < al->p)
276 al->peak_p = al->p;
277 al->nb_total++;
278 #endif
279 return ret;
280 } else if (is_own) {
281 al->nb_allocs--;
282 ret = tal_realloc(*pal, 0, size);
283 header = (((tal_header_t *)p) - 1);
284 if (p) memcpy(ret, p, header->size);
285 #ifdef TAL_DEBUG
286 header->line_num = -header->line_num;
287 #endif
288 return ret;
290 if (al->next) {
291 al = al->next;
292 } else {
293 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
295 al = tal_new(pal, next->limit, next->size * 2);
296 al->next = next;
297 bottom->top = al;
299 goto tail_call;
301 if (is_own) {
302 al->nb_allocs--;
303 ret = tcc_malloc(size);
304 header = (((tal_header_t *)p) - 1);
305 if (p) memcpy(ret, p, header->size);
306 #ifdef TAL_DEBUG
307 header->line_num = -header->line_num;
308 #endif
309 } else if (al->next) {
310 al = al->next;
311 goto tail_call;
312 } else
313 ret = tcc_realloc(p, size);
314 #ifdef TAL_INFO
315 al->nb_missed++;
316 #endif
317 return ret;
320 #endif /* USE_TAL */
322 /* ------------------------------------------------------------------------- */
323 /* CString handling */
324 static void cstr_realloc(CString *cstr, int new_size)
326 int size;
328 size = cstr->size_allocated;
329 if (size < 8)
330 size = 8; /* no need to allocate a too small first string */
331 while (size < new_size)
332 size = size * 2;
333 cstr->data = tcc_realloc(cstr->data, size);
334 cstr->size_allocated = size;
337 /* add a byte */
338 ST_INLN void cstr_ccat(CString *cstr, int ch)
340 int size;
341 size = cstr->size + 1;
342 if (size > cstr->size_allocated)
343 cstr_realloc(cstr, size);
344 ((unsigned char *)cstr->data)[size - 1] = ch;
345 cstr->size = size;
348 ST_INLN char *unicode_to_utf8 (char *b, uint32_t Uc)
350 if (Uc<0x80) *b++=Uc;
351 else if (Uc<0x800) *b++=192+Uc/64, *b++=128+Uc%64;
352 else if (Uc-0xd800u<0x800) return b;
353 else if (Uc<0x10000) *b++=224+Uc/4096, *b++=128+Uc/64%64, *b++=128+Uc%64;
354 else if (Uc<0x110000) *b++=240+Uc/262144, *b++=128+Uc/4096%64, *b++=128+Uc/64%64, *b++=128+Uc%64;
355 return b;
358 /* add a unicode character expanded into utf8 */
359 ST_INLN void cstr_u8cat(CString *cstr, int ch)
361 char buf[4], *e;
362 e = unicode_to_utf8(buf, (uint32_t)ch);
363 cstr_cat(cstr, buf, e - buf);
366 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
368 int size;
369 if (len <= 0)
370 len = strlen(str) + 1 + len;
371 size = cstr->size + len;
372 if (size > cstr->size_allocated)
373 cstr_realloc(cstr, size);
374 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
375 cstr->size = size;
378 /* add a wide char */
379 ST_FUNC void cstr_wccat(CString *cstr, int ch)
381 int size;
382 size = cstr->size + sizeof(nwchar_t);
383 if (size > cstr->size_allocated)
384 cstr_realloc(cstr, size);
385 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
386 cstr->size = size;
389 ST_FUNC void cstr_new(CString *cstr)
391 memset(cstr, 0, sizeof(CString));
394 /* free string and reset it to NULL */
395 ST_FUNC void cstr_free(CString *cstr)
397 tcc_free(cstr->data);
398 cstr_new(cstr);
401 /* reset string to empty */
402 ST_FUNC void cstr_reset(CString *cstr)
404 cstr->size = 0;
407 ST_FUNC int cstr_printf(CString *cstr, const char *fmt, ...)
409 va_list v;
410 int len, size = 80;
411 for (;;) {
412 size += cstr->size;
413 if (size > cstr->size_allocated)
414 cstr_realloc(cstr, size);
415 size = cstr->size_allocated - cstr->size;
416 va_start(v, fmt);
417 len = vsnprintf((char*)cstr->data + cstr->size, size, fmt, v);
418 va_end(v);
419 if (len > 0 && len < size)
420 break;
421 size *= 2;
423 cstr->size += len;
424 return len;
427 /* XXX: unicode ? */
428 static void add_char(CString *cstr, int c)
430 if (c == '\'' || c == '\"' || c == '\\') {
431 /* XXX: could be more precise if char or string */
432 cstr_ccat(cstr, '\\');
434 if (c >= 32 && c <= 126) {
435 cstr_ccat(cstr, c);
436 } else {
437 cstr_ccat(cstr, '\\');
438 if (c == '\n') {
439 cstr_ccat(cstr, 'n');
440 } else {
441 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
442 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
443 cstr_ccat(cstr, '0' + (c & 7));
448 /* ------------------------------------------------------------------------- */
449 /* allocate a new token */
450 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
452 TokenSym *ts, **ptable;
453 int i;
455 if (tok_ident >= SYM_FIRST_ANOM)
456 tcc_error("memory full (symbols)");
458 /* expand token table if needed */
459 i = tok_ident - TOK_IDENT;
460 if ((i % TOK_ALLOC_INCR) == 0) {
461 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
462 table_ident = ptable;
465 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
466 table_ident[i] = ts;
467 ts->tok = tok_ident++;
468 ts->sym_define = NULL;
469 ts->sym_label = NULL;
470 ts->sym_struct = NULL;
471 ts->sym_identifier = NULL;
472 ts->len = len;
473 ts->hash_next = NULL;
474 memcpy(ts->str, str, len);
475 ts->str[len] = '\0';
476 *pts = ts;
477 return ts;
480 #define TOK_HASH_INIT 1
481 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
484 /* find a token and add it if not found */
485 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
487 TokenSym *ts, **pts;
488 int i;
489 unsigned int h;
491 h = TOK_HASH_INIT;
492 for(i=0;i<len;i++)
493 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
494 h &= (TOK_HASH_SIZE - 1);
496 pts = &hash_ident[h];
497 for(;;) {
498 ts = *pts;
499 if (!ts)
500 break;
501 if (ts->len == len && !memcmp(ts->str, str, len))
502 return ts;
503 pts = &(ts->hash_next);
505 return tok_alloc_new(pts, str, len);
508 ST_FUNC int tok_alloc_const(const char *str)
510 return tok_alloc(str, strlen(str))->tok;
514 /* XXX: buffer overflow */
515 /* XXX: float tokens */
516 ST_FUNC const char *get_tok_str(int v, CValue *cv)
518 char *p;
519 int i, len;
521 cstr_reset(&cstr_buf);
522 p = cstr_buf.data;
524 switch(v) {
525 case TOK_CINT:
526 case TOK_CUINT:
527 case TOK_CLONG:
528 case TOK_CULONG:
529 case TOK_CLLONG:
530 case TOK_CULLONG:
531 /* XXX: not quite exact, but only useful for testing */
532 #ifdef _WIN32
533 sprintf(p, "%u", (unsigned)cv->i);
534 #else
535 sprintf(p, "%llu", (unsigned long long)cv->i);
536 #endif
537 break;
538 case TOK_LCHAR:
539 cstr_ccat(&cstr_buf, 'L');
540 case TOK_CCHAR:
541 cstr_ccat(&cstr_buf, '\'');
542 add_char(&cstr_buf, cv->i);
543 cstr_ccat(&cstr_buf, '\'');
544 cstr_ccat(&cstr_buf, '\0');
545 break;
546 case TOK_PPNUM:
547 case TOK_PPSTR:
548 return (char*)cv->str.data;
549 case TOK_LSTR:
550 cstr_ccat(&cstr_buf, 'L');
551 case TOK_STR:
552 cstr_ccat(&cstr_buf, '\"');
553 if (v == TOK_STR) {
554 len = cv->str.size - 1;
555 for(i=0;i<len;i++)
556 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
557 } else {
558 len = (cv->str.size / sizeof(nwchar_t)) - 1;
559 for(i=0;i<len;i++)
560 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
562 cstr_ccat(&cstr_buf, '\"');
563 cstr_ccat(&cstr_buf, '\0');
564 break;
566 case TOK_CFLOAT:
567 cstr_cat(&cstr_buf, "<float>", 0);
568 break;
569 case TOK_CDOUBLE:
570 cstr_cat(&cstr_buf, "<double>", 0);
571 break;
572 case TOK_CLDOUBLE:
573 cstr_cat(&cstr_buf, "<long double>", 0);
574 break;
575 case TOK_LINENUM:
576 cstr_cat(&cstr_buf, "<linenumber>", 0);
577 break;
579 /* above tokens have value, the ones below don't */
580 case TOK_LT:
581 v = '<';
582 goto addv;
583 case TOK_GT:
584 v = '>';
585 goto addv;
586 case TOK_DOTS:
587 return strcpy(p, "...");
588 case TOK_A_SHL:
589 return strcpy(p, "<<=");
590 case TOK_A_SAR:
591 return strcpy(p, ">>=");
592 case TOK_EOF:
593 return strcpy(p, "<eof>");
594 default:
595 if (v < TOK_IDENT) {
596 /* search in two bytes table */
597 const unsigned char *q = tok_two_chars;
598 while (*q) {
599 if (q[2] == v) {
600 *p++ = q[0];
601 *p++ = q[1];
602 *p = '\0';
603 return cstr_buf.data;
605 q += 3;
607 if (v >= 127) {
608 sprintf(cstr_buf.data, "<%02x>", v);
609 return cstr_buf.data;
611 addv:
612 *p++ = v;
613 case 0: /* nameless anonymous symbol */
614 *p = '\0';
615 } else if (v < tok_ident) {
616 return table_ident[v - TOK_IDENT]->str;
617 } else if (v >= SYM_FIRST_ANOM) {
618 /* special name for anonymous symbol */
619 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
620 } else {
621 /* should never happen */
622 return NULL;
624 break;
626 return cstr_buf.data;
629 /* return the current character, handling end of block if necessary
630 (but not stray) */
631 static int handle_eob(void)
633 BufferedFile *bf = file;
634 int len;
636 /* only tries to read if really end of buffer */
637 if (bf->buf_ptr >= bf->buf_end) {
638 if (bf->fd >= 0) {
639 #if defined(PARSE_DEBUG)
640 len = 1;
641 #else
642 len = IO_BUF_SIZE;
643 #endif
644 len = read(bf->fd, bf->buffer, len);
645 if (len < 0)
646 len = 0;
647 } else {
648 len = 0;
650 total_bytes += len;
651 bf->buf_ptr = bf->buffer;
652 bf->buf_end = bf->buffer + len;
653 *bf->buf_end = CH_EOB;
655 if (bf->buf_ptr < bf->buf_end) {
656 return bf->buf_ptr[0];
657 } else {
658 bf->buf_ptr = bf->buf_end;
659 return CH_EOF;
663 /* read next char from current input file and handle end of input buffer */
664 static inline void inp(void)
666 ch = *(++(file->buf_ptr));
667 /* end of buffer/file handling */
668 if (ch == CH_EOB)
669 ch = handle_eob();
672 /* handle '\[\r]\n' */
673 static int handle_stray_noerror(void)
675 while (ch == '\\') {
676 inp();
677 if (ch == '\n') {
678 file->line_num++;
679 inp();
680 } else if (ch == '\r') {
681 inp();
682 if (ch != '\n')
683 goto fail;
684 file->line_num++;
685 inp();
686 } else {
687 fail:
688 return 1;
691 return 0;
694 static void handle_stray(void)
696 if (handle_stray_noerror())
697 tcc_error("stray '\\' in program");
700 /* skip the stray and handle the \\n case. Output an error if
701 incorrect char after the stray */
702 static int handle_stray1(uint8_t *p)
704 int c;
706 file->buf_ptr = p;
707 if (p >= file->buf_end) {
708 c = handle_eob();
709 if (c != '\\')
710 return c;
711 p = file->buf_ptr;
713 ch = *p;
714 if (handle_stray_noerror()) {
715 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
716 tcc_error("stray '\\' in program");
717 *--file->buf_ptr = '\\';
719 p = file->buf_ptr;
720 c = *p;
721 return c;
724 /* handle just the EOB case, but not stray */
725 #define PEEKC_EOB(c, p)\
727 p++;\
728 c = *p;\
729 if (c == '\\') {\
730 file->buf_ptr = p;\
731 c = handle_eob();\
732 p = file->buf_ptr;\
736 /* handle the complicated stray case */
737 #define PEEKC(c, p)\
739 p++;\
740 c = *p;\
741 if (c == '\\') {\
742 c = handle_stray1(p);\
743 p = file->buf_ptr;\
747 /* input with '\[\r]\n' handling. Note that this function cannot
748 handle other characters after '\', so you cannot call it inside
749 strings or comments */
750 static void minp(void)
752 inp();
753 if (ch == '\\')
754 handle_stray();
757 /* single line C++ comments */
758 static uint8_t *parse_line_comment(uint8_t *p)
760 int c;
762 p++;
763 for(;;) {
764 c = *p;
765 redo:
766 if (c == '\n' || c == CH_EOF) {
767 break;
768 } else if (c == '\\') {
769 file->buf_ptr = p;
770 c = handle_eob();
771 p = file->buf_ptr;
772 if (c == '\\') {
773 PEEKC_EOB(c, p);
774 if (c == '\n') {
775 file->line_num++;
776 PEEKC_EOB(c, p);
777 } else if (c == '\r') {
778 PEEKC_EOB(c, p);
779 if (c == '\n') {
780 file->line_num++;
781 PEEKC_EOB(c, p);
784 } else {
785 goto redo;
787 } else {
788 p++;
791 return p;
794 /* C comments */
795 static uint8_t *parse_comment(uint8_t *p)
797 int c;
799 p++;
800 for(;;) {
801 /* fast skip loop */
802 for(;;) {
803 c = *p;
804 if (c == '\n' || c == '*' || c == '\\')
805 break;
806 p++;
807 c = *p;
808 if (c == '\n' || c == '*' || c == '\\')
809 break;
810 p++;
812 /* now we can handle all the cases */
813 if (c == '\n') {
814 file->line_num++;
815 p++;
816 } else if (c == '*') {
817 p++;
818 for(;;) {
819 c = *p;
820 if (c == '*') {
821 p++;
822 } else if (c == '/') {
823 goto end_of_comment;
824 } else if (c == '\\') {
825 file->buf_ptr = p;
826 c = handle_eob();
827 p = file->buf_ptr;
828 if (c == CH_EOF)
829 tcc_error("unexpected end of file in comment");
830 if (c == '\\') {
831 /* skip '\[\r]\n', otherwise just skip the stray */
832 while (c == '\\') {
833 PEEKC_EOB(c, p);
834 if (c == '\n') {
835 file->line_num++;
836 PEEKC_EOB(c, p);
837 } else if (c == '\r') {
838 PEEKC_EOB(c, p);
839 if (c == '\n') {
840 file->line_num++;
841 PEEKC_EOB(c, p);
843 } else {
844 goto after_star;
848 } else {
849 break;
852 after_star: ;
853 } else {
854 /* stray, eob or eof */
855 file->buf_ptr = p;
856 c = handle_eob();
857 p = file->buf_ptr;
858 if (c == CH_EOF) {
859 tcc_error("unexpected end of file in comment");
860 } else if (c == '\\') {
861 p++;
865 end_of_comment:
866 p++;
867 return p;
870 ST_FUNC int set_idnum(int c, int val)
872 int prev = isidnum_table[c - CH_EOF];
873 isidnum_table[c - CH_EOF] = val;
874 return prev;
877 #define cinp minp
879 static inline void skip_spaces(void)
881 while (isidnum_table[ch - CH_EOF] & IS_SPC)
882 cinp();
885 static inline int check_space(int t, int *spc)
887 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
888 if (*spc)
889 return 1;
890 *spc = 1;
891 } else
892 *spc = 0;
893 return 0;
896 /* parse a string without interpreting escapes */
897 static uint8_t *parse_pp_string(uint8_t *p,
898 int sep, CString *str)
900 int c;
901 p++;
902 for(;;) {
903 c = *p;
904 if (c == sep) {
905 break;
906 } else if (c == '\\') {
907 file->buf_ptr = p;
908 c = handle_eob();
909 p = file->buf_ptr;
910 if (c == CH_EOF) {
911 unterminated_string:
912 /* XXX: indicate line number of start of string */
913 tcc_error("missing terminating %c character", sep);
914 } else if (c == '\\') {
915 /* escape : just skip \[\r]\n */
916 PEEKC_EOB(c, p);
917 if (c == '\n') {
918 file->line_num++;
919 p++;
920 } else if (c == '\r') {
921 PEEKC_EOB(c, p);
922 if (c != '\n')
923 expect("'\n' after '\r'");
924 file->line_num++;
925 p++;
926 } else if (c == CH_EOF) {
927 goto unterminated_string;
928 } else {
929 if (str) {
930 cstr_ccat(str, '\\');
931 cstr_ccat(str, c);
933 p++;
936 } else if (c == '\n') {
937 file->line_num++;
938 goto add_char;
939 } else if (c == '\r') {
940 PEEKC_EOB(c, p);
941 if (c != '\n') {
942 if (str)
943 cstr_ccat(str, '\r');
944 } else {
945 file->line_num++;
946 goto add_char;
948 } else {
949 add_char:
950 if (str)
951 cstr_ccat(str, c);
952 p++;
955 p++;
956 return p;
959 /* skip block of text until #else, #elif or #endif. skip also pairs of
960 #if/#endif */
961 static void preprocess_skip(void)
963 int a, start_of_line, c, in_warn_or_error;
964 uint8_t *p;
966 p = file->buf_ptr;
967 a = 0;
968 redo_start:
969 start_of_line = 1;
970 in_warn_or_error = 0;
971 for(;;) {
972 redo_no_start:
973 c = *p;
974 switch(c) {
975 case ' ':
976 case '\t':
977 case '\f':
978 case '\v':
979 case '\r':
980 p++;
981 goto redo_no_start;
982 case '\n':
983 file->line_num++;
984 p++;
985 goto redo_start;
986 case '\\':
987 file->buf_ptr = p;
988 c = handle_eob();
989 if (c == CH_EOF) {
990 expect("#endif");
991 } else if (c == '\\') {
992 ch = file->buf_ptr[0];
993 handle_stray_noerror();
995 p = file->buf_ptr;
996 goto redo_no_start;
997 /* skip strings */
998 case '\"':
999 case '\'':
1000 if (in_warn_or_error)
1001 goto _default;
1002 p = parse_pp_string(p, c, NULL);
1003 break;
1004 /* skip comments */
1005 case '/':
1006 if (in_warn_or_error)
1007 goto _default;
1008 file->buf_ptr = p;
1009 ch = *p;
1010 minp();
1011 p = file->buf_ptr;
1012 if (ch == '*') {
1013 p = parse_comment(p);
1014 } else if (ch == '/') {
1015 p = parse_line_comment(p);
1017 break;
1018 case '#':
1019 p++;
1020 if (start_of_line) {
1021 file->buf_ptr = p;
1022 next_nomacro();
1023 p = file->buf_ptr;
1024 if (a == 0 &&
1025 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
1026 goto the_end;
1027 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
1028 a++;
1029 else if (tok == TOK_ENDIF)
1030 a--;
1031 else if( tok == TOK_ERROR || tok == TOK_WARNING)
1032 in_warn_or_error = 1;
1033 else if (tok == TOK_LINEFEED)
1034 goto redo_start;
1035 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1036 p = parse_line_comment(p - 1);
1038 #if !defined(TCC_TARGET_ARM)
1039 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1040 p = parse_line_comment(p - 1);
1041 #else
1042 /* ARM assembly uses '#' for constants */
1043 #endif
1044 break;
1045 _default:
1046 default:
1047 p++;
1048 break;
1050 start_of_line = 0;
1052 the_end: ;
1053 file->buf_ptr = p;
1056 #if 0
1057 /* return the number of additional 'ints' necessary to store the
1058 token */
1059 static inline int tok_size(const int *p)
1061 switch(*p) {
1062 /* 4 bytes */
1063 case TOK_CINT:
1064 case TOK_CUINT:
1065 case TOK_CCHAR:
1066 case TOK_LCHAR:
1067 case TOK_CFLOAT:
1068 case TOK_LINENUM:
1069 return 1 + 1;
1070 case TOK_STR:
1071 case TOK_LSTR:
1072 case TOK_PPNUM:
1073 case TOK_PPSTR:
1074 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1075 case TOK_CLONG:
1076 case TOK_CULONG:
1077 return 1 + LONG_SIZE / 4;
1078 case TOK_CDOUBLE:
1079 case TOK_CLLONG:
1080 case TOK_CULLONG:
1081 return 1 + 2;
1082 case TOK_CLDOUBLE:
1083 return 1 + LDOUBLE_SIZE / 4;
1084 default:
1085 return 1 + 0;
1088 #endif
1090 /* token string handling */
1091 ST_INLN void tok_str_new(TokenString *s)
1093 s->str = NULL;
1094 s->len = s->lastlen = 0;
1095 s->allocated_len = 0;
1096 s->last_line_num = -1;
1099 ST_FUNC TokenString *tok_str_alloc(void)
1101 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1102 tok_str_new(str);
1103 return str;
1106 ST_FUNC int *tok_str_dup(TokenString *s)
1108 int *str;
1110 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1111 memcpy(str, s->str, s->len * sizeof(int));
1112 return str;
1115 ST_FUNC void tok_str_free_str(int *str)
1117 tal_free(tokstr_alloc, str);
1120 ST_FUNC void tok_str_free(TokenString *str)
1122 tok_str_free_str(str->str);
1123 tal_free(tokstr_alloc, str);
1126 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1128 int *str, size;
1130 size = s->allocated_len;
1131 if (size < 16)
1132 size = 16;
1133 while (size < new_size)
1134 size = size * 2;
1135 if (size > s->allocated_len) {
1136 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1137 s->allocated_len = size;
1138 s->str = str;
1140 return s->str;
1143 ST_FUNC void tok_str_add(TokenString *s, int t)
1145 int len, *str;
1147 len = s->len;
1148 str = s->str;
1149 if (len >= s->allocated_len)
1150 str = tok_str_realloc(s, len + 1);
1151 str[len++] = t;
1152 s->len = len;
1155 ST_FUNC void begin_macro(TokenString *str, int alloc)
1157 str->alloc = alloc;
1158 str->prev = macro_stack;
1159 str->prev_ptr = macro_ptr;
1160 str->save_line_num = file->line_num;
1161 macro_ptr = str->str;
1162 macro_stack = str;
1165 ST_FUNC void end_macro(void)
1167 TokenString *str = macro_stack;
1168 macro_stack = str->prev;
1169 macro_ptr = str->prev_ptr;
1170 file->line_num = str->save_line_num;
1171 if (str->alloc != 0) {
1172 if (str->alloc == 2)
1173 str->str = NULL; /* don't free */
1174 tok_str_free(str);
1178 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1180 int len, *str;
1182 len = s->lastlen = s->len;
1183 str = s->str;
1185 /* allocate space for worst case */
1186 if (len + TOK_MAX_SIZE >= s->allocated_len)
1187 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1188 str[len++] = t;
1189 switch(t) {
1190 case TOK_CINT:
1191 case TOK_CUINT:
1192 case TOK_CCHAR:
1193 case TOK_LCHAR:
1194 case TOK_CFLOAT:
1195 case TOK_LINENUM:
1196 #if LONG_SIZE == 4
1197 case TOK_CLONG:
1198 case TOK_CULONG:
1199 #endif
1200 str[len++] = cv->tab[0];
1201 break;
1202 case TOK_PPNUM:
1203 case TOK_PPSTR:
1204 case TOK_STR:
1205 case TOK_LSTR:
1207 /* Insert the string into the int array. */
1208 size_t nb_words =
1209 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1210 if (len + nb_words >= s->allocated_len)
1211 str = tok_str_realloc(s, len + nb_words + 1);
1212 str[len] = cv->str.size;
1213 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1214 len += nb_words;
1216 break;
1217 case TOK_CDOUBLE:
1218 case TOK_CLLONG:
1219 case TOK_CULLONG:
1220 #if LONG_SIZE == 8
1221 case TOK_CLONG:
1222 case TOK_CULONG:
1223 #endif
1224 #if LDOUBLE_SIZE == 8
1225 case TOK_CLDOUBLE:
1226 #endif
1227 str[len++] = cv->tab[0];
1228 str[len++] = cv->tab[1];
1229 break;
1230 #if LDOUBLE_SIZE == 12
1231 case TOK_CLDOUBLE:
1232 str[len++] = cv->tab[0];
1233 str[len++] = cv->tab[1];
1234 str[len++] = cv->tab[2];
1235 #elif LDOUBLE_SIZE == 16
1236 case TOK_CLDOUBLE:
1237 str[len++] = cv->tab[0];
1238 str[len++] = cv->tab[1];
1239 str[len++] = cv->tab[2];
1240 str[len++] = cv->tab[3];
1241 #elif LDOUBLE_SIZE != 8
1242 #error add long double size support
1243 #endif
1244 break;
1245 default:
1246 break;
1248 s->len = len;
1251 /* add the current parse token in token string 's' */
1252 ST_FUNC void tok_str_add_tok(TokenString *s)
1254 CValue cval;
1256 /* save line number info */
1257 if (file->line_num != s->last_line_num) {
1258 s->last_line_num = file->line_num;
1259 cval.i = s->last_line_num;
1260 tok_str_add2(s, TOK_LINENUM, &cval);
1262 tok_str_add2(s, tok, &tokc);
1265 /* get a token from an integer array and increment pointer. */
1266 static inline void tok_get(int *t, const int **pp, CValue *cv)
1268 const int *p = *pp;
1269 int n, *tab;
1271 tab = cv->tab;
1272 switch(*t = *p++) {
1273 #if LONG_SIZE == 4
1274 case TOK_CLONG:
1275 #endif
1276 case TOK_CINT:
1277 case TOK_CCHAR:
1278 case TOK_LCHAR:
1279 case TOK_LINENUM:
1280 cv->i = *p++;
1281 break;
1282 #if LONG_SIZE == 4
1283 case TOK_CULONG:
1284 #endif
1285 case TOK_CUINT:
1286 cv->i = (unsigned)*p++;
1287 break;
1288 case TOK_CFLOAT:
1289 tab[0] = *p++;
1290 break;
1291 case TOK_STR:
1292 case TOK_LSTR:
1293 case TOK_PPNUM:
1294 case TOK_PPSTR:
1295 cv->str.size = *p++;
1296 cv->str.data = p;
1297 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1298 break;
1299 case TOK_CDOUBLE:
1300 case TOK_CLLONG:
1301 case TOK_CULLONG:
1302 #if LONG_SIZE == 8
1303 case TOK_CLONG:
1304 case TOK_CULONG:
1305 #endif
1306 n = 2;
1307 goto copy;
1308 case TOK_CLDOUBLE:
1309 #if LDOUBLE_SIZE == 16
1310 n = 4;
1311 #elif LDOUBLE_SIZE == 12
1312 n = 3;
1313 #elif LDOUBLE_SIZE == 8
1314 n = 2;
1315 #else
1316 # error add long double size support
1317 #endif
1318 copy:
1320 *tab++ = *p++;
1321 while (--n);
1322 break;
1323 default:
1324 break;
1326 *pp = p;
1329 #if 0
1330 # define TOK_GET(t,p,c) tok_get(t,p,c)
1331 #else
1332 # define TOK_GET(t,p,c) do { \
1333 int _t = **(p); \
1334 if (TOK_HAS_VALUE(_t)) \
1335 tok_get(t, p, c); \
1336 else \
1337 *(t) = _t, ++*(p); \
1338 } while (0)
1339 #endif
1341 static int macro_is_equal(const int *a, const int *b)
1343 CValue cv;
1344 int t;
1346 if (!a || !b)
1347 return 1;
1349 while (*a && *b) {
1350 /* first time preallocate macro_equal_buf, next time only reset position to start */
1351 cstr_reset(&macro_equal_buf);
1352 TOK_GET(&t, &a, &cv);
1353 cstr_cat(&macro_equal_buf, get_tok_str(t, &cv), 0);
1354 TOK_GET(&t, &b, &cv);
1355 if (strcmp(macro_equal_buf.data, get_tok_str(t, &cv)))
1356 return 0;
1358 return !(*a || *b);
1361 /* defines handling */
1362 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1364 Sym *s, *o;
1366 o = define_find(v);
1367 s = sym_push2(&define_stack, v, macro_type, 0);
1368 s->d = str;
1369 s->next = first_arg;
1370 table_ident[v - TOK_IDENT]->sym_define = s;
1372 if (o && !macro_is_equal(o->d, s->d))
1373 tcc_warning("%s redefined", get_tok_str(v, NULL));
1376 /* undefined a define symbol. Its name is just set to zero */
1377 ST_FUNC void define_undef(Sym *s)
1379 int v = s->v;
1380 if (v >= TOK_IDENT && v < tok_ident)
1381 table_ident[v - TOK_IDENT]->sym_define = NULL;
1384 ST_INLN Sym *define_find(int v)
1386 v -= TOK_IDENT;
1387 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1388 return NULL;
1389 return table_ident[v]->sym_define;
1392 /* free define stack until top reaches 'b' */
1393 ST_FUNC void free_defines(Sym *b)
1395 while (define_stack != b) {
1396 Sym *top = define_stack;
1397 define_stack = top->prev;
1398 tok_str_free_str(top->d);
1399 define_undef(top);
1400 sym_free(top);
1404 /* label lookup */
1405 ST_FUNC Sym *label_find(int v)
1407 v -= TOK_IDENT;
1408 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1409 return NULL;
1410 return table_ident[v]->sym_label;
1413 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1415 Sym *s, **ps;
1416 s = sym_push2(ptop, v, 0, 0);
1417 s->r = flags;
1418 ps = &table_ident[v - TOK_IDENT]->sym_label;
1419 if (ptop == &global_label_stack) {
1420 /* modify the top most local identifier, so that
1421 sym_identifier will point to 's' when popped */
1422 while (*ps != NULL)
1423 ps = &(*ps)->prev_tok;
1425 s->prev_tok = *ps;
1426 *ps = s;
1427 return s;
1430 /* pop labels until element last is reached. Look if any labels are
1431 undefined. Define symbols if '&&label' was used. */
1432 ST_FUNC void label_pop(Sym **ptop, Sym *slast, int keep)
1434 Sym *s, *s1;
1435 for(s = *ptop; s != slast; s = s1) {
1436 s1 = s->prev;
1437 if (s->r == LABEL_DECLARED) {
1438 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1439 } else if (s->r == LABEL_FORWARD) {
1440 tcc_error("label '%s' used but not defined",
1441 get_tok_str(s->v, NULL));
1442 } else {
1443 if (s->c) {
1444 /* define corresponding symbol. A size of
1445 1 is put. */
1446 put_extern_sym(s, cur_text_section, s->jnext, 1);
1449 /* remove label */
1450 if (s->r != LABEL_GONE)
1451 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1452 if (!keep)
1453 sym_free(s);
1454 else
1455 s->r = LABEL_GONE;
1457 if (!keep)
1458 *ptop = slast;
1461 /* fake the nth "#if defined test_..." for tcc -dt -run */
1462 static void maybe_run_test(TCCState *s)
1464 const char *p;
1465 if (s->include_stack_ptr != s->include_stack)
1466 return;
1467 p = get_tok_str(tok, NULL);
1468 if (0 != memcmp(p, "test_", 5))
1469 return;
1470 if (0 != --s->run_test)
1471 return;
1472 fprintf(s->ppfp, &"\n[%s]\n"[!(s->dflag & 32)], p), fflush(s->ppfp);
1473 define_push(tok, MACRO_OBJ, NULL, NULL);
1476 /* eval an expression for #if/#elif */
1477 static int expr_preprocess(void)
1479 int c, t;
1480 TokenString *str;
1482 str = tok_str_alloc();
1483 pp_expr = 1;
1484 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1485 next(); /* do macro subst */
1486 redo:
1487 if (tok == TOK_DEFINED) {
1488 next_nomacro();
1489 t = tok;
1490 if (t == '(')
1491 next_nomacro();
1492 if (tok < TOK_IDENT)
1493 expect("identifier");
1494 if (tcc_state->run_test)
1495 maybe_run_test(tcc_state);
1496 c = define_find(tok) != 0;
1497 if (t == '(') {
1498 next_nomacro();
1499 if (tok != ')')
1500 expect("')'");
1502 tok = TOK_CINT;
1503 tokc.i = c;
1504 } else if (1 && tok == TOK___HAS_INCLUDE) {
1505 next(); /* XXX check if correct to use expansion */
1506 skip('(');
1507 while (tok != ')' && tok != TOK_EOF)
1508 next();
1509 if (tok != ')')
1510 expect("')'");
1511 tok = TOK_CINT;
1512 tokc.i = 0;
1513 } else if (tok >= TOK_IDENT) {
1514 /* if undefined macro, replace with zero, check for func-like */
1515 t = tok;
1516 tok = TOK_CINT;
1517 tokc.i = 0;
1518 tok_str_add_tok(str);
1519 next();
1520 if (tok == '(')
1521 tcc_error("function-like macro '%s' is not defined",
1522 get_tok_str(t, NULL));
1523 goto redo;
1525 tok_str_add_tok(str);
1527 pp_expr = 0;
1528 tok_str_add(str, -1); /* simulate end of file */
1529 tok_str_add(str, 0);
1530 /* now evaluate C constant expression */
1531 begin_macro(str, 1);
1532 next();
1533 c = expr_const();
1534 end_macro();
1535 return c != 0;
1539 /* parse after #define */
1540 ST_FUNC void parse_define(void)
1542 Sym *s, *first, **ps;
1543 int v, t, varg, is_vaargs, spc;
1544 int saved_parse_flags = parse_flags;
1546 v = tok;
1547 if (v < TOK_IDENT || v == TOK_DEFINED)
1548 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1549 /* XXX: should check if same macro (ANSI) */
1550 first = NULL;
1551 t = MACRO_OBJ;
1552 /* We have to parse the whole define as if not in asm mode, in particular
1553 no line comment with '#' must be ignored. Also for function
1554 macros the argument list must be parsed without '.' being an ID
1555 character. */
1556 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1557 /* '(' must be just after macro definition for MACRO_FUNC */
1558 next_nomacro();
1559 parse_flags &= ~PARSE_FLAG_SPACES;
1560 if (tok == '(') {
1561 int dotid = set_idnum('.', 0);
1562 next_nomacro();
1563 ps = &first;
1564 if (tok != ')') for (;;) {
1565 varg = tok;
1566 next_nomacro();
1567 is_vaargs = 0;
1568 if (varg == TOK_DOTS) {
1569 varg = TOK___VA_ARGS__;
1570 is_vaargs = 1;
1571 } else if (tok == TOK_DOTS && gnu_ext) {
1572 is_vaargs = 1;
1573 next_nomacro();
1575 if (varg < TOK_IDENT)
1576 bad_list:
1577 tcc_error("bad macro parameter list");
1578 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1579 *ps = s;
1580 ps = &s->next;
1581 if (tok == ')')
1582 break;
1583 if (tok != ',' || is_vaargs)
1584 goto bad_list;
1585 next_nomacro();
1587 parse_flags |= PARSE_FLAG_SPACES;
1588 next_nomacro();
1589 t = MACRO_FUNC;
1590 set_idnum('.', dotid);
1593 tokstr_buf.len = 0;
1594 spc = 2;
1595 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1596 /* The body of a macro definition should be parsed such that identifiers
1597 are parsed like the file mode determines (i.e. with '.' being an
1598 ID character in asm mode). But '#' should be retained instead of
1599 regarded as line comment leader, so still don't set ASM_FILE
1600 in parse_flags. */
1601 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1602 /* remove spaces around ## and after '#' */
1603 if (TOK_TWOSHARPS == tok) {
1604 if (2 == spc)
1605 goto bad_twosharp;
1606 if (1 == spc)
1607 --tokstr_buf.len;
1608 spc = 3;
1609 tok = TOK_PPJOIN;
1610 } else if ('#' == tok) {
1611 spc = 4;
1612 } else if (check_space(tok, &spc)) {
1613 goto skip;
1615 tok_str_add2(&tokstr_buf, tok, &tokc);
1616 skip:
1617 next_nomacro();
1620 parse_flags = saved_parse_flags;
1621 if (spc == 1)
1622 --tokstr_buf.len; /* remove trailing space */
1623 tok_str_add(&tokstr_buf, 0);
1624 if (3 == spc)
1625 bad_twosharp:
1626 tcc_error("'##' cannot appear at either end of macro");
1627 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1630 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1632 const unsigned char *s;
1633 unsigned int h;
1634 CachedInclude *e;
1635 int i;
1637 h = TOK_HASH_INIT;
1638 s = (unsigned char *) filename;
1639 while (*s) {
1640 #ifdef _WIN32
1641 h = TOK_HASH_FUNC(h, toup(*s));
1642 #else
1643 h = TOK_HASH_FUNC(h, *s);
1644 #endif
1645 s++;
1647 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1649 i = s1->cached_includes_hash[h];
1650 for(;;) {
1651 if (i == 0)
1652 break;
1653 e = s1->cached_includes[i - 1];
1654 if (0 == PATHCMP(e->filename, filename))
1655 return e;
1656 i = e->hash_next;
1658 if (!add)
1659 return NULL;
1661 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1662 strcpy(e->filename, filename);
1663 e->ifndef_macro = e->once = 0;
1664 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1665 /* add in hash table */
1666 e->hash_next = s1->cached_includes_hash[h];
1667 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1668 #ifdef INC_DEBUG
1669 printf("adding cached '%s'\n", filename);
1670 #endif
1671 return e;
1674 static void pragma_parse(TCCState *s1)
1676 next_nomacro();
1677 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1678 int t = tok, v;
1679 Sym *s;
1681 if (next(), tok != '(')
1682 goto pragma_err;
1683 if (next(), tok != TOK_STR)
1684 goto pragma_err;
1685 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1686 if (next(), tok != ')')
1687 goto pragma_err;
1688 if (t == TOK_push_macro) {
1689 while (NULL == (s = define_find(v)))
1690 define_push(v, 0, NULL, NULL);
1691 s->type.ref = s; /* set push boundary */
1692 } else {
1693 for (s = define_stack; s; s = s->prev)
1694 if (s->v == v && s->type.ref == s) {
1695 s->type.ref = NULL;
1696 break;
1699 if (s)
1700 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1701 else
1702 tcc_warning("unbalanced #pragma pop_macro");
1703 pp_debug_tok = t, pp_debug_symv = v;
1705 } else if (tok == TOK_once) {
1706 search_cached_include(s1, file->filename, 1)->once = pp_once;
1708 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1709 /* tcc -E: keep pragmas below unchanged */
1710 unget_tok(' ');
1711 unget_tok(TOK_PRAGMA);
1712 unget_tok('#');
1713 unget_tok(TOK_LINEFEED);
1715 } else if (tok == TOK_pack) {
1716 /* This may be:
1717 #pragma pack(1) // set
1718 #pragma pack() // reset to default
1719 #pragma pack(push,1) // push & set
1720 #pragma pack(pop) // restore previous */
1721 next();
1722 skip('(');
1723 if (tok == TOK_ASM_pop) {
1724 next();
1725 if (s1->pack_stack_ptr <= s1->pack_stack) {
1726 stk_error:
1727 tcc_error("out of pack stack");
1729 s1->pack_stack_ptr--;
1730 } else {
1731 int val = 0;
1732 if (tok != ')') {
1733 if (tok == TOK_ASM_push) {
1734 next();
1735 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1736 goto stk_error;
1737 s1->pack_stack_ptr++;
1738 skip(',');
1740 if (tok != TOK_CINT)
1741 goto pragma_err;
1742 val = tokc.i;
1743 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1744 goto pragma_err;
1745 next();
1747 *s1->pack_stack_ptr = val;
1749 if (tok != ')')
1750 goto pragma_err;
1752 } else if (tok == TOK_comment) {
1753 char *p; int t;
1754 next();
1755 skip('(');
1756 t = tok;
1757 next();
1758 skip(',');
1759 if (tok != TOK_STR)
1760 goto pragma_err;
1761 p = tcc_strdup((char *)tokc.str.data);
1762 next();
1763 if (tok != ')')
1764 goto pragma_err;
1765 if (t == TOK_lib) {
1766 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1767 } else {
1768 if (t == TOK_option)
1769 tcc_set_options(s1, p);
1770 tcc_free(p);
1773 } else if (s1->warn_unsupported) {
1774 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1776 return;
1778 pragma_err:
1779 tcc_error("malformed #pragma directive");
1780 return;
1783 /* is_bof is true if first non space token at beginning of file */
1784 ST_FUNC void preprocess(int is_bof)
1786 TCCState *s1 = tcc_state;
1787 int i, c, n, saved_parse_flags;
1788 char buf[1024], *q;
1789 Sym *s;
1791 saved_parse_flags = parse_flags;
1792 parse_flags = PARSE_FLAG_PREPROCESS
1793 | PARSE_FLAG_TOK_NUM
1794 | PARSE_FLAG_TOK_STR
1795 | PARSE_FLAG_LINEFEED
1796 | (parse_flags & PARSE_FLAG_ASM_FILE)
1799 next_nomacro();
1800 redo:
1801 switch(tok) {
1802 case TOK_DEFINE:
1803 pp_debug_tok = tok;
1804 next_nomacro();
1805 pp_debug_symv = tok;
1806 parse_define();
1807 break;
1808 case TOK_UNDEF:
1809 pp_debug_tok = tok;
1810 next_nomacro();
1811 pp_debug_symv = tok;
1812 s = define_find(tok);
1813 /* undefine symbol by putting an invalid name */
1814 if (s)
1815 define_undef(s);
1816 break;
1817 case TOK_INCLUDE:
1818 case TOK_INCLUDE_NEXT:
1819 ch = file->buf_ptr[0];
1820 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1821 skip_spaces();
1822 if (ch == '<') {
1823 c = '>';
1824 goto read_name;
1825 } else if (ch == '\"') {
1826 c = ch;
1827 read_name:
1828 inp();
1829 q = buf;
1830 while (ch != c && ch != '\n' && ch != CH_EOF) {
1831 if ((q - buf) < sizeof(buf) - 1)
1832 *q++ = ch;
1833 if (ch == '\\') {
1834 if (handle_stray_noerror() == 0)
1835 --q;
1836 } else
1837 inp();
1839 *q = '\0';
1840 minp();
1841 #if 0
1842 /* eat all spaces and comments after include */
1843 /* XXX: slightly incorrect */
1844 while (ch1 != '\n' && ch1 != CH_EOF)
1845 inp();
1846 #endif
1847 } else {
1848 int len;
1849 /* computed #include : concatenate everything up to linefeed,
1850 the result must be one of the two accepted forms.
1851 Don't convert pp-tokens to tokens here. */
1852 parse_flags = (PARSE_FLAG_PREPROCESS
1853 | PARSE_FLAG_LINEFEED
1854 | (parse_flags & PARSE_FLAG_ASM_FILE));
1855 next();
1856 buf[0] = '\0';
1857 while (tok != TOK_LINEFEED) {
1858 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1859 next();
1861 len = strlen(buf);
1862 /* check syntax and remove '<>|""' */
1863 if ((len < 2 || ((buf[0] != '"' || buf[len-1] != '"') &&
1864 (buf[0] != '<' || buf[len-1] != '>'))))
1865 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1866 c = buf[len-1];
1867 memmove(buf, buf + 1, len - 2);
1868 buf[len - 2] = '\0';
1871 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1872 tcc_error("#include recursion too deep");
1873 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index + 1 : 0;
1874 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1875 for (; i < n; ++i) {
1876 char buf1[sizeof file->filename];
1877 CachedInclude *e;
1878 const char *path;
1880 if (i == 0) {
1881 /* check absolute include path */
1882 if (!IS_ABSPATH(buf))
1883 continue;
1884 buf1[0] = 0;
1886 } else if (i == 1) {
1887 /* search in file's dir if "header.h" */
1888 if (c != '\"')
1889 continue;
1890 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1891 path = file->true_filename;
1892 pstrncpy(buf1, path, tcc_basename(path) - path);
1894 } else {
1895 /* search in all the include paths */
1896 int j = i - 2, k = j - s1->nb_include_paths;
1897 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1898 pstrcpy(buf1, sizeof(buf1), path);
1899 pstrcat(buf1, sizeof(buf1), "/");
1902 pstrcat(buf1, sizeof(buf1), buf);
1903 e = search_cached_include(s1, buf1, 0);
1904 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1905 /* no need to parse the include because the 'ifndef macro'
1906 is defined (or had #pragma once) */
1907 #ifdef INC_DEBUG
1908 printf("%s: skipping cached %s\n", file->filename, buf1);
1909 #endif
1910 goto include_done;
1913 if (tcc_open(s1, buf1) < 0)
1914 continue;
1915 /* push previous file on stack */
1916 *s1->include_stack_ptr++ = file->prev;
1917 file->include_next_index = i;
1918 #ifdef INC_DEBUG
1919 printf("%s: including %s\n", file->prev->filename, file->filename);
1920 #endif
1921 /* update target deps */
1922 if (s1->gen_deps) {
1923 BufferedFile *bf = file;
1924 while (i == 1 && (bf = bf->prev))
1925 i = bf->include_next_index;
1926 /* skip system include files */
1927 if (n - i > s1->nb_sysinclude_paths)
1928 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1929 tcc_strdup(buf1));
1931 /* add include file debug info */
1932 tcc_debug_bincl(tcc_state);
1933 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1934 ch = file->buf_ptr[0];
1935 goto the_end;
1937 tcc_error("include file '%s' not found", buf);
1938 include_done:
1939 break;
1940 case TOK_IFNDEF:
1941 c = 1;
1942 goto do_ifdef;
1943 case TOK_IF:
1944 c = expr_preprocess();
1945 goto do_if;
1946 case TOK_IFDEF:
1947 c = 0;
1948 do_ifdef:
1949 next_nomacro();
1950 if (tok < TOK_IDENT)
1951 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1952 if (is_bof) {
1953 if (c) {
1954 #ifdef INC_DEBUG
1955 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1956 #endif
1957 file->ifndef_macro = tok;
1960 c = (define_find(tok) != 0) ^ c;
1961 do_if:
1962 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1963 tcc_error("memory full (ifdef)");
1964 *s1->ifdef_stack_ptr++ = c;
1965 goto test_skip;
1966 case TOK_ELSE:
1967 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1968 tcc_error("#else without matching #if");
1969 if (s1->ifdef_stack_ptr[-1] & 2)
1970 tcc_error("#else after #else");
1971 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1972 goto test_else;
1973 case TOK_ELIF:
1974 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1975 tcc_error("#elif without matching #if");
1976 c = s1->ifdef_stack_ptr[-1];
1977 if (c > 1)
1978 tcc_error("#elif after #else");
1979 /* last #if/#elif expression was true: we skip */
1980 if (c == 1) {
1981 c = 0;
1982 } else {
1983 c = expr_preprocess();
1984 s1->ifdef_stack_ptr[-1] = c;
1986 test_else:
1987 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1988 file->ifndef_macro = 0;
1989 test_skip:
1990 if (!(c & 1)) {
1991 preprocess_skip();
1992 is_bof = 0;
1993 goto redo;
1995 break;
1996 case TOK_ENDIF:
1997 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1998 tcc_error("#endif without matching #if");
1999 s1->ifdef_stack_ptr--;
2000 /* '#ifndef macro' was at the start of file. Now we check if
2001 an '#endif' is exactly at the end of file */
2002 if (file->ifndef_macro &&
2003 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
2004 file->ifndef_macro_saved = file->ifndef_macro;
2005 /* need to set to zero to avoid false matches if another
2006 #ifndef at middle of file */
2007 file->ifndef_macro = 0;
2008 while (tok != TOK_LINEFEED)
2009 next_nomacro();
2010 tok_flags |= TOK_FLAG_ENDIF;
2011 goto the_end;
2013 break;
2014 case TOK_PPNUM:
2015 n = strtoul((char*)tokc.str.data, &q, 10);
2016 goto _line_num;
2017 case TOK_LINE:
2018 next();
2019 if (tok != TOK_CINT)
2020 _line_err:
2021 tcc_error("wrong #line format");
2022 n = tokc.i;
2023 _line_num:
2024 next();
2025 if (tok != TOK_LINEFEED) {
2026 if (tok == TOK_STR) {
2027 if (file->true_filename == file->filename)
2028 file->true_filename = tcc_strdup(file->filename);
2029 /* prepend directory from real file */
2030 pstrcpy(buf, sizeof buf, file->true_filename);
2031 *tcc_basename(buf) = 0;
2032 pstrcat(buf, sizeof buf, (char *)tokc.str.data);
2033 tcc_debug_putfile(s1, buf);
2034 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
2035 break;
2036 else
2037 goto _line_err;
2038 --n;
2040 if (file->fd > 0)
2041 total_lines += file->line_num - n;
2042 file->line_num = n;
2043 break;
2044 case TOK_ERROR:
2045 case TOK_WARNING:
2046 c = tok;
2047 ch = file->buf_ptr[0];
2048 skip_spaces();
2049 q = buf;
2050 while (ch != '\n' && ch != CH_EOF) {
2051 if ((q - buf) < sizeof(buf) - 1)
2052 *q++ = ch;
2053 if (ch == '\\') {
2054 if (handle_stray_noerror() == 0)
2055 --q;
2056 } else
2057 inp();
2059 *q = '\0';
2060 if (c == TOK_ERROR)
2061 tcc_error("#error %s", buf);
2062 else
2063 tcc_warning("#warning %s", buf);
2064 break;
2065 case TOK_PRAGMA:
2066 pragma_parse(s1);
2067 break;
2068 case TOK_LINEFEED:
2069 goto the_end;
2070 default:
2071 /* ignore gas line comment in an 'S' file. */
2072 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
2073 goto ignore;
2074 if (tok == '!' && is_bof)
2075 /* '!' is ignored at beginning to allow C scripts. */
2076 goto ignore;
2077 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
2078 ignore:
2079 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
2080 goto the_end;
2082 /* ignore other preprocess commands or #! for C scripts */
2083 while (tok != TOK_LINEFEED)
2084 next_nomacro();
2085 the_end:
2086 parse_flags = saved_parse_flags;
2089 /* evaluate escape codes in a string. */
2090 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
2092 int c, n, i;
2093 const uint8_t *p;
2095 p = buf;
2096 for(;;) {
2097 c = *p;
2098 if (c == '\0')
2099 break;
2100 if (c == '\\') {
2101 p++;
2102 /* escape */
2103 c = *p;
2104 switch(c) {
2105 case '0': case '1': case '2': case '3':
2106 case '4': case '5': case '6': case '7':
2107 /* at most three octal digits */
2108 n = c - '0';
2109 p++;
2110 c = *p;
2111 if (isoct(c)) {
2112 n = n * 8 + c - '0';
2113 p++;
2114 c = *p;
2115 if (isoct(c)) {
2116 n = n * 8 + c - '0';
2117 p++;
2120 c = n;
2121 goto add_char_nonext;
2122 case 'x': i = 0; goto parse_hex_or_ucn;
2123 case 'u': i = 4; goto parse_hex_or_ucn;
2124 case 'U': i = 8; goto parse_hex_or_ucn;
2125 parse_hex_or_ucn:
2126 p++;
2127 n = 0;
2128 do {
2129 c = *p;
2130 if (c >= 'a' && c <= 'f')
2131 c = c - 'a' + 10;
2132 else if (c >= 'A' && c <= 'F')
2133 c = c - 'A' + 10;
2134 else if (isnum(c))
2135 c = c - '0';
2136 else if (i > 0)
2137 expect("more hex digits in universal-character-name");
2138 else {
2139 c = n;
2140 goto add_char_nonext;
2142 n = n * 16 + c;
2143 p++;
2144 } while (--i);
2145 cstr_u8cat(outstr, n);
2146 continue;
2147 case 'a':
2148 c = '\a';
2149 break;
2150 case 'b':
2151 c = '\b';
2152 break;
2153 case 'f':
2154 c = '\f';
2155 break;
2156 case 'n':
2157 c = '\n';
2158 break;
2159 case 'r':
2160 c = '\r';
2161 break;
2162 case 't':
2163 c = '\t';
2164 break;
2165 case 'v':
2166 c = '\v';
2167 break;
2168 case 'e':
2169 if (!gnu_ext)
2170 goto invalid_escape;
2171 c = 27;
2172 break;
2173 case '\'':
2174 case '\"':
2175 case '\\':
2176 case '?':
2177 break;
2178 default:
2179 invalid_escape:
2180 if (c >= '!' && c <= '~')
2181 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2182 else
2183 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2184 break;
2186 } else if (is_long && c >= 0x80) {
2187 /* assume we are processing UTF-8 sequence */
2188 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2190 int cont; /* count of continuation bytes */
2191 int skip; /* how many bytes should skip when error occurred */
2192 int i;
2194 /* decode leading byte */
2195 if (c < 0xC2) {
2196 skip = 1; goto invalid_utf8_sequence;
2197 } else if (c <= 0xDF) {
2198 cont = 1; n = c & 0x1f;
2199 } else if (c <= 0xEF) {
2200 cont = 2; n = c & 0xf;
2201 } else if (c <= 0xF4) {
2202 cont = 3; n = c & 0x7;
2203 } else {
2204 skip = 1; goto invalid_utf8_sequence;
2207 /* decode continuation bytes */
2208 for (i = 1; i <= cont; i++) {
2209 int l = 0x80, h = 0xBF;
2211 /* adjust limit for second byte */
2212 if (i == 1) {
2213 switch (c) {
2214 case 0xE0: l = 0xA0; break;
2215 case 0xED: h = 0x9F; break;
2216 case 0xF0: l = 0x90; break;
2217 case 0xF4: h = 0x8F; break;
2221 if (p[i] < l || p[i] > h) {
2222 skip = i; goto invalid_utf8_sequence;
2225 n = (n << 6) | (p[i] & 0x3f);
2228 /* advance pointer */
2229 p += 1 + cont;
2230 c = n;
2231 goto add_char_nonext;
2233 /* error handling */
2234 invalid_utf8_sequence:
2235 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2236 c = 0xFFFD;
2237 p += skip;
2238 goto add_char_nonext;
2241 p++;
2242 add_char_nonext:
2243 if (!is_long)
2244 cstr_ccat(outstr, c);
2245 else {
2246 #ifdef TCC_TARGET_PE
2247 /* store as UTF-16 */
2248 if (c < 0x10000) {
2249 cstr_wccat(outstr, c);
2250 } else {
2251 c -= 0x10000;
2252 cstr_wccat(outstr, (c >> 10) + 0xD800);
2253 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2255 #else
2256 cstr_wccat(outstr, c);
2257 #endif
2260 /* add a trailing '\0' */
2261 if (!is_long)
2262 cstr_ccat(outstr, '\0');
2263 else
2264 cstr_wccat(outstr, '\0');
2267 static void parse_string(const char *s, int len)
2269 uint8_t buf[1000], *p = buf;
2270 int is_long, sep;
2272 if ((is_long = *s == 'L'))
2273 ++s, --len;
2274 sep = *s++;
2275 len -= 2;
2276 if (len >= sizeof buf)
2277 p = tcc_malloc(len + 1);
2278 memcpy(p, s, len);
2279 p[len] = 0;
2281 cstr_reset(&tokcstr);
2282 parse_escape_string(&tokcstr, p, is_long);
2283 if (p != buf)
2284 tcc_free(p);
2286 if (sep == '\'') {
2287 int char_size, i, n, c;
2288 /* XXX: make it portable */
2289 if (!is_long)
2290 tok = TOK_CCHAR, char_size = 1;
2291 else
2292 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2293 n = tokcstr.size / char_size - 1;
2294 if (n < 1)
2295 tcc_error("empty character constant");
2296 if (n > 1)
2297 tcc_warning("multi-character character constant");
2298 for (c = i = 0; i < n; ++i) {
2299 if (is_long)
2300 c = ((nwchar_t *)tokcstr.data)[i];
2301 else
2302 c = (c << 8) | ((char *)tokcstr.data)[i];
2304 tokc.i = c;
2305 } else {
2306 tokc.str.size = tokcstr.size;
2307 tokc.str.data = tokcstr.data;
2308 if (!is_long)
2309 tok = TOK_STR;
2310 else
2311 tok = TOK_LSTR;
2315 /* we use 64 bit numbers */
2316 #define BN_SIZE 2
2318 /* bn = (bn << shift) | or_val */
2319 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2321 int i;
2322 unsigned int v;
2323 for(i=0;i<BN_SIZE;i++) {
2324 v = bn[i];
2325 bn[i] = (v << shift) | or_val;
2326 or_val = v >> (32 - shift);
2330 static void bn_zero(unsigned int *bn)
2332 int i;
2333 for(i=0;i<BN_SIZE;i++) {
2334 bn[i] = 0;
2338 /* parse number in null terminated string 'p' and return it in the
2339 current token */
2340 static void parse_number(const char *p)
2342 int b, t, shift, frac_bits, s, exp_val, ch;
2343 char *q;
2344 unsigned int bn[BN_SIZE];
2345 double d;
2347 /* number */
2348 q = token_buf;
2349 ch = *p++;
2350 t = ch;
2351 ch = *p++;
2352 *q++ = t;
2353 b = 10;
2354 if (t == '.') {
2355 goto float_frac_parse;
2356 } else if (t == '0') {
2357 if (ch == 'x' || ch == 'X') {
2358 q--;
2359 ch = *p++;
2360 b = 16;
2361 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2362 q--;
2363 ch = *p++;
2364 b = 2;
2367 /* parse all digits. cannot check octal numbers at this stage
2368 because of floating point constants */
2369 while (1) {
2370 if (ch >= 'a' && ch <= 'f')
2371 t = ch - 'a' + 10;
2372 else if (ch >= 'A' && ch <= 'F')
2373 t = ch - 'A' + 10;
2374 else if (isnum(ch))
2375 t = ch - '0';
2376 else
2377 break;
2378 if (t >= b)
2379 break;
2380 if (q >= token_buf + STRING_MAX_SIZE) {
2381 num_too_long:
2382 tcc_error("number too long");
2384 *q++ = ch;
2385 ch = *p++;
2387 if (ch == '.' ||
2388 ((ch == 'e' || ch == 'E') && b == 10) ||
2389 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2390 if (b != 10) {
2391 /* NOTE: strtox should support that for hexa numbers, but
2392 non ISOC99 libcs do not support it, so we prefer to do
2393 it by hand */
2394 /* hexadecimal or binary floats */
2395 /* XXX: handle overflows */
2396 *q = '\0';
2397 if (b == 16)
2398 shift = 4;
2399 else
2400 shift = 1;
2401 bn_zero(bn);
2402 q = token_buf;
2403 while (1) {
2404 t = *q++;
2405 if (t == '\0') {
2406 break;
2407 } else if (t >= 'a') {
2408 t = t - 'a' + 10;
2409 } else if (t >= 'A') {
2410 t = t - 'A' + 10;
2411 } else {
2412 t = t - '0';
2414 bn_lshift(bn, shift, t);
2416 frac_bits = 0;
2417 if (ch == '.') {
2418 ch = *p++;
2419 while (1) {
2420 t = ch;
2421 if (t >= 'a' && t <= 'f') {
2422 t = t - 'a' + 10;
2423 } else if (t >= 'A' && t <= 'F') {
2424 t = t - 'A' + 10;
2425 } else if (t >= '0' && t <= '9') {
2426 t = t - '0';
2427 } else {
2428 break;
2430 if (t >= b)
2431 tcc_error("invalid digit");
2432 bn_lshift(bn, shift, t);
2433 frac_bits += shift;
2434 ch = *p++;
2437 if (ch != 'p' && ch != 'P')
2438 expect("exponent");
2439 ch = *p++;
2440 s = 1;
2441 exp_val = 0;
2442 if (ch == '+') {
2443 ch = *p++;
2444 } else if (ch == '-') {
2445 s = -1;
2446 ch = *p++;
2448 if (ch < '0' || ch > '9')
2449 expect("exponent digits");
2450 while (ch >= '0' && ch <= '9') {
2451 exp_val = exp_val * 10 + ch - '0';
2452 ch = *p++;
2454 exp_val = exp_val * s;
2456 /* now we can generate the number */
2457 /* XXX: should patch directly float number */
2458 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2459 d = ldexp(d, exp_val - frac_bits);
2460 t = toup(ch);
2461 if (t == 'F') {
2462 ch = *p++;
2463 tok = TOK_CFLOAT;
2464 /* float : should handle overflow */
2465 tokc.f = (float)d;
2466 } else if (t == 'L') {
2467 ch = *p++;
2468 #ifdef TCC_TARGET_PE
2469 tok = TOK_CDOUBLE;
2470 tokc.d = d;
2471 #else
2472 tok = TOK_CLDOUBLE;
2473 /* XXX: not large enough */
2474 tokc.ld = (long double)d;
2475 #endif
2476 } else {
2477 tok = TOK_CDOUBLE;
2478 tokc.d = d;
2480 } else {
2481 /* decimal floats */
2482 if (ch == '.') {
2483 if (q >= token_buf + STRING_MAX_SIZE)
2484 goto num_too_long;
2485 *q++ = ch;
2486 ch = *p++;
2487 float_frac_parse:
2488 while (ch >= '0' && ch <= '9') {
2489 if (q >= token_buf + STRING_MAX_SIZE)
2490 goto num_too_long;
2491 *q++ = ch;
2492 ch = *p++;
2495 if (ch == 'e' || ch == 'E') {
2496 if (q >= token_buf + STRING_MAX_SIZE)
2497 goto num_too_long;
2498 *q++ = ch;
2499 ch = *p++;
2500 if (ch == '-' || ch == '+') {
2501 if (q >= token_buf + STRING_MAX_SIZE)
2502 goto num_too_long;
2503 *q++ = ch;
2504 ch = *p++;
2506 if (ch < '0' || ch > '9')
2507 expect("exponent digits");
2508 while (ch >= '0' && ch <= '9') {
2509 if (q >= token_buf + STRING_MAX_SIZE)
2510 goto num_too_long;
2511 *q++ = ch;
2512 ch = *p++;
2515 *q = '\0';
2516 t = toup(ch);
2517 errno = 0;
2518 if (t == 'F') {
2519 ch = *p++;
2520 tok = TOK_CFLOAT;
2521 tokc.f = strtof(token_buf, NULL);
2522 } else if (t == 'L') {
2523 ch = *p++;
2524 #ifdef TCC_TARGET_PE
2525 tok = TOK_CDOUBLE;
2526 tokc.d = strtod(token_buf, NULL);
2527 #else
2528 tok = TOK_CLDOUBLE;
2529 tokc.ld = strtold(token_buf, NULL);
2530 #endif
2531 } else {
2532 tok = TOK_CDOUBLE;
2533 tokc.d = strtod(token_buf, NULL);
2536 } else {
2537 unsigned long long n, n1;
2538 int lcount, ucount, ov = 0;
2539 const char *p1;
2541 /* integer number */
2542 *q = '\0';
2543 q = token_buf;
2544 if (b == 10 && *q == '0') {
2545 b = 8;
2546 q++;
2548 n = 0;
2549 while(1) {
2550 t = *q++;
2551 /* no need for checks except for base 10 / 8 errors */
2552 if (t == '\0')
2553 break;
2554 else if (t >= 'a')
2555 t = t - 'a' + 10;
2556 else if (t >= 'A')
2557 t = t - 'A' + 10;
2558 else
2559 t = t - '0';
2560 if (t >= b)
2561 tcc_error("invalid digit");
2562 n1 = n;
2563 n = n * b + t;
2564 /* detect overflow */
2565 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2566 ov = 1;
2569 /* Determine the characteristics (unsigned and/or 64bit) the type of
2570 the constant must have according to the constant suffix(es) */
2571 lcount = ucount = 0;
2572 p1 = p;
2573 for(;;) {
2574 t = toup(ch);
2575 if (t == 'L') {
2576 if (lcount >= 2)
2577 tcc_error("three 'l's in integer constant");
2578 if (lcount && *(p - 1) != ch)
2579 tcc_error("incorrect integer suffix: %s", p1);
2580 lcount++;
2581 ch = *p++;
2582 } else if (t == 'U') {
2583 if (ucount >= 1)
2584 tcc_error("two 'u's in integer constant");
2585 ucount++;
2586 ch = *p++;
2587 } else {
2588 break;
2592 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2593 if (ucount == 0 && b == 10) {
2594 if (lcount <= (LONG_SIZE == 4)) {
2595 if (n >= 0x80000000U)
2596 lcount = (LONG_SIZE == 4) + 1;
2598 if (n >= 0x8000000000000000ULL)
2599 ov = 1, ucount = 1;
2600 } else {
2601 if (lcount <= (LONG_SIZE == 4)) {
2602 if (n >= 0x100000000ULL)
2603 lcount = (LONG_SIZE == 4) + 1;
2604 else if (n >= 0x80000000U)
2605 ucount = 1;
2607 if (n >= 0x8000000000000000ULL)
2608 ucount = 1;
2611 if (ov)
2612 tcc_warning("integer constant overflow");
2614 tok = TOK_CINT;
2615 if (lcount) {
2616 tok = TOK_CLONG;
2617 if (lcount == 2)
2618 tok = TOK_CLLONG;
2620 if (ucount)
2621 ++tok; /* TOK_CU... */
2622 tokc.i = n;
2624 if (ch)
2625 tcc_error("invalid number");
2629 #define PARSE2(c1, tok1, c2, tok2) \
2630 case c1: \
2631 PEEKC(c, p); \
2632 if (c == c2) { \
2633 p++; \
2634 tok = tok2; \
2635 } else { \
2636 tok = tok1; \
2638 break;
2640 /* return next token without macro substitution */
2641 static inline void next_nomacro1(void)
2643 int t, c, is_long, len;
2644 TokenSym *ts;
2645 uint8_t *p, *p1;
2646 unsigned int h;
2648 p = file->buf_ptr;
2649 redo_no_start:
2650 c = *p;
2651 switch(c) {
2652 case ' ':
2653 case '\t':
2654 tok = c;
2655 p++;
2656 maybe_space:
2657 if (parse_flags & PARSE_FLAG_SPACES)
2658 goto keep_tok_flags;
2659 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2660 ++p;
2661 goto redo_no_start;
2662 case '\f':
2663 case '\v':
2664 case '\r':
2665 p++;
2666 goto redo_no_start;
2667 case '\\':
2668 /* first look if it is in fact an end of buffer */
2669 c = handle_stray1(p);
2670 p = file->buf_ptr;
2671 if (c == '\\')
2672 goto parse_simple;
2673 if (c != CH_EOF)
2674 goto redo_no_start;
2676 TCCState *s1 = tcc_state;
2677 if ((parse_flags & PARSE_FLAG_LINEFEED)
2678 && !(tok_flags & TOK_FLAG_EOF)) {
2679 tok_flags |= TOK_FLAG_EOF;
2680 tok = TOK_LINEFEED;
2681 goto keep_tok_flags;
2682 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2683 tok = TOK_EOF;
2684 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2685 tcc_error("missing #endif");
2686 } else if (s1->include_stack_ptr == s1->include_stack) {
2687 /* no include left : end of file. */
2688 tok = TOK_EOF;
2689 } else {
2690 tok_flags &= ~TOK_FLAG_EOF;
2691 /* pop include file */
2693 /* test if previous '#endif' was after a #ifdef at
2694 start of file */
2695 if (tok_flags & TOK_FLAG_ENDIF) {
2696 #ifdef INC_DEBUG
2697 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2698 #endif
2699 search_cached_include(s1, file->filename, 1)
2700 ->ifndef_macro = file->ifndef_macro_saved;
2701 tok_flags &= ~TOK_FLAG_ENDIF;
2704 /* add end of include file debug info */
2705 tcc_debug_eincl(tcc_state);
2706 /* pop include stack */
2707 tcc_close();
2708 s1->include_stack_ptr--;
2709 p = file->buf_ptr;
2710 if (p == file->buffer)
2711 tok_flags = TOK_FLAG_BOF|TOK_FLAG_BOL;
2712 goto redo_no_start;
2715 break;
2717 case '\n':
2718 file->line_num++;
2719 tok_flags |= TOK_FLAG_BOL;
2720 p++;
2721 maybe_newline:
2722 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2723 goto redo_no_start;
2724 tok = TOK_LINEFEED;
2725 goto keep_tok_flags;
2727 case '#':
2728 /* XXX: simplify */
2729 PEEKC(c, p);
2730 if ((tok_flags & TOK_FLAG_BOL) &&
2731 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2732 file->buf_ptr = p;
2733 preprocess(tok_flags & TOK_FLAG_BOF);
2734 p = file->buf_ptr;
2735 goto maybe_newline;
2736 } else {
2737 if (c == '#') {
2738 p++;
2739 tok = TOK_TWOSHARPS;
2740 } else {
2741 #if !defined(TCC_TARGET_ARM)
2742 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2743 p = parse_line_comment(p - 1);
2744 goto redo_no_start;
2745 } else
2746 #endif
2748 tok = '#';
2752 break;
2754 /* dollar is allowed to start identifiers when not parsing asm */
2755 case '$':
2756 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2757 || (parse_flags & PARSE_FLAG_ASM_FILE))
2758 goto parse_simple;
2760 case 'a': case 'b': case 'c': case 'd':
2761 case 'e': case 'f': case 'g': case 'h':
2762 case 'i': case 'j': case 'k': case 'l':
2763 case 'm': case 'n': case 'o': case 'p':
2764 case 'q': case 'r': case 's': case 't':
2765 case 'u': case 'v': case 'w': case 'x':
2766 case 'y': case 'z':
2767 case 'A': case 'B': case 'C': case 'D':
2768 case 'E': case 'F': case 'G': case 'H':
2769 case 'I': case 'J': case 'K':
2770 case 'M': case 'N': case 'O': case 'P':
2771 case 'Q': case 'R': case 'S': case 'T':
2772 case 'U': case 'V': case 'W': case 'X':
2773 case 'Y': case 'Z':
2774 case '_':
2775 parse_ident_fast:
2776 p1 = p;
2777 h = TOK_HASH_INIT;
2778 h = TOK_HASH_FUNC(h, c);
2779 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2780 h = TOK_HASH_FUNC(h, c);
2781 len = p - p1;
2782 if (c != '\\') {
2783 TokenSym **pts;
2785 /* fast case : no stray found, so we have the full token
2786 and we have already hashed it */
2787 h &= (TOK_HASH_SIZE - 1);
2788 pts = &hash_ident[h];
2789 for(;;) {
2790 ts = *pts;
2791 if (!ts)
2792 break;
2793 if (ts->len == len && !memcmp(ts->str, p1, len))
2794 goto token_found;
2795 pts = &(ts->hash_next);
2797 ts = tok_alloc_new(pts, (char *) p1, len);
2798 token_found: ;
2799 } else {
2800 /* slower case */
2801 cstr_reset(&tokcstr);
2802 cstr_cat(&tokcstr, (char *) p1, len);
2803 p--;
2804 PEEKC(c, p);
2805 parse_ident_slow:
2806 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2808 cstr_ccat(&tokcstr, c);
2809 PEEKC(c, p);
2811 ts = tok_alloc(tokcstr.data, tokcstr.size);
2813 tok = ts->tok;
2814 break;
2815 case 'L':
2816 t = p[1];
2817 if (t != '\\' && t != '\'' && t != '\"') {
2818 /* fast case */
2819 goto parse_ident_fast;
2820 } else {
2821 PEEKC(c, p);
2822 if (c == '\'' || c == '\"') {
2823 is_long = 1;
2824 goto str_const;
2825 } else {
2826 cstr_reset(&tokcstr);
2827 cstr_ccat(&tokcstr, 'L');
2828 goto parse_ident_slow;
2831 break;
2833 case '0': case '1': case '2': case '3':
2834 case '4': case '5': case '6': case '7':
2835 case '8': case '9':
2836 t = c;
2837 PEEKC(c, p);
2838 /* after the first digit, accept digits, alpha, '.' or sign if
2839 prefixed by 'eEpP' */
2840 parse_num:
2841 cstr_reset(&tokcstr);
2842 for(;;) {
2843 cstr_ccat(&tokcstr, t);
2844 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2845 || c == '.'
2846 || ((c == '+' || c == '-')
2847 && (((t == 'e' || t == 'E')
2848 && !(parse_flags & PARSE_FLAG_ASM_FILE
2849 /* 0xe+1 is 3 tokens in asm */
2850 && ((char*)tokcstr.data)[0] == '0'
2851 && toup(((char*)tokcstr.data)[1]) == 'X'))
2852 || t == 'p' || t == 'P'))))
2853 break;
2854 t = c;
2855 PEEKC(c, p);
2857 /* We add a trailing '\0' to ease parsing */
2858 cstr_ccat(&tokcstr, '\0');
2859 tokc.str.size = tokcstr.size;
2860 tokc.str.data = tokcstr.data;
2861 tok = TOK_PPNUM;
2862 break;
2864 case '.':
2865 /* special dot handling because it can also start a number */
2866 PEEKC(c, p);
2867 if (isnum(c)) {
2868 t = '.';
2869 goto parse_num;
2870 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2871 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2872 *--p = c = '.';
2873 goto parse_ident_fast;
2874 } else if (c == '.') {
2875 PEEKC(c, p);
2876 if (c == '.') {
2877 p++;
2878 tok = TOK_DOTS;
2879 } else {
2880 *--p = '.'; /* may underflow into file->unget[] */
2881 tok = '.';
2883 } else {
2884 tok = '.';
2886 break;
2887 case '\'':
2888 case '\"':
2889 is_long = 0;
2890 str_const:
2891 cstr_reset(&tokcstr);
2892 if (is_long)
2893 cstr_ccat(&tokcstr, 'L');
2894 cstr_ccat(&tokcstr, c);
2895 p = parse_pp_string(p, c, &tokcstr);
2896 cstr_ccat(&tokcstr, c);
2897 cstr_ccat(&tokcstr, '\0');
2898 tokc.str.size = tokcstr.size;
2899 tokc.str.data = tokcstr.data;
2900 tok = TOK_PPSTR;
2901 break;
2903 case '<':
2904 PEEKC(c, p);
2905 if (c == '=') {
2906 p++;
2907 tok = TOK_LE;
2908 } else if (c == '<') {
2909 PEEKC(c, p);
2910 if (c == '=') {
2911 p++;
2912 tok = TOK_A_SHL;
2913 } else {
2914 tok = TOK_SHL;
2916 } else {
2917 tok = TOK_LT;
2919 break;
2920 case '>':
2921 PEEKC(c, p);
2922 if (c == '=') {
2923 p++;
2924 tok = TOK_GE;
2925 } else if (c == '>') {
2926 PEEKC(c, p);
2927 if (c == '=') {
2928 p++;
2929 tok = TOK_A_SAR;
2930 } else {
2931 tok = TOK_SAR;
2933 } else {
2934 tok = TOK_GT;
2936 break;
2938 case '&':
2939 PEEKC(c, p);
2940 if (c == '&') {
2941 p++;
2942 tok = TOK_LAND;
2943 } else if (c == '=') {
2944 p++;
2945 tok = TOK_A_AND;
2946 } else {
2947 tok = '&';
2949 break;
2951 case '|':
2952 PEEKC(c, p);
2953 if (c == '|') {
2954 p++;
2955 tok = TOK_LOR;
2956 } else if (c == '=') {
2957 p++;
2958 tok = TOK_A_OR;
2959 } else {
2960 tok = '|';
2962 break;
2964 case '+':
2965 PEEKC(c, p);
2966 if (c == '+') {
2967 p++;
2968 tok = TOK_INC;
2969 } else if (c == '=') {
2970 p++;
2971 tok = TOK_A_ADD;
2972 } else {
2973 tok = '+';
2975 break;
2977 case '-':
2978 PEEKC(c, p);
2979 if (c == '-') {
2980 p++;
2981 tok = TOK_DEC;
2982 } else if (c == '=') {
2983 p++;
2984 tok = TOK_A_SUB;
2985 } else if (c == '>') {
2986 p++;
2987 tok = TOK_ARROW;
2988 } else {
2989 tok = '-';
2991 break;
2993 PARSE2('!', '!', '=', TOK_NE)
2994 PARSE2('=', '=', '=', TOK_EQ)
2995 PARSE2('*', '*', '=', TOK_A_MUL)
2996 PARSE2('%', '%', '=', TOK_A_MOD)
2997 PARSE2('^', '^', '=', TOK_A_XOR)
2999 /* comments or operator */
3000 case '/':
3001 PEEKC(c, p);
3002 if (c == '*') {
3003 p = parse_comment(p);
3004 /* comments replaced by a blank */
3005 tok = ' ';
3006 goto maybe_space;
3007 } else if (c == '/') {
3008 p = parse_line_comment(p);
3009 tok = ' ';
3010 goto maybe_space;
3011 } else if (c == '=') {
3012 p++;
3013 tok = TOK_A_DIV;
3014 } else {
3015 tok = '/';
3017 break;
3019 /* simple tokens */
3020 case '(':
3021 case ')':
3022 case '[':
3023 case ']':
3024 case '{':
3025 case '}':
3026 case ',':
3027 case ';':
3028 case ':':
3029 case '?':
3030 case '~':
3031 case '@': /* only used in assembler */
3032 parse_simple:
3033 tok = c;
3034 p++;
3035 break;
3036 default:
3037 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
3038 goto parse_ident_fast;
3039 if (parse_flags & PARSE_FLAG_ASM_FILE)
3040 goto parse_simple;
3041 tcc_error("unrecognized character \\x%02x", c);
3042 break;
3044 tok_flags = 0;
3045 keep_tok_flags:
3046 file->buf_ptr = p;
3047 #if defined(PARSE_DEBUG)
3048 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
3049 #endif
3052 static void macro_subst(
3053 TokenString *tok_str,
3054 Sym **nested_list,
3055 const int *macro_str
3058 /* substitute arguments in replacement lists in macro_str by the values in
3059 args (field d) and return allocated string */
3060 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
3062 int t, t0, t1, spc;
3063 const int *st;
3064 Sym *s;
3065 CValue cval;
3066 TokenString str;
3067 CString cstr;
3069 tok_str_new(&str);
3070 t0 = t1 = 0;
3071 while(1) {
3072 TOK_GET(&t, &macro_str, &cval);
3073 if (!t)
3074 break;
3075 if (t == '#') {
3076 /* stringize */
3077 TOK_GET(&t, &macro_str, &cval);
3078 if (!t)
3079 goto bad_stringy;
3080 s = sym_find2(args, t);
3081 if (s) {
3082 cstr_new(&cstr);
3083 cstr_ccat(&cstr, '\"');
3084 st = s->d;
3085 spc = 0;
3086 while (*st >= 0) {
3087 TOK_GET(&t, &st, &cval);
3088 if (t != TOK_PLCHLDR
3089 && t != TOK_NOSUBST
3090 && 0 == check_space(t, &spc)) {
3091 const char *s = get_tok_str(t, &cval);
3092 while (*s) {
3093 if (t == TOK_PPSTR && *s != '\'')
3094 add_char(&cstr, *s);
3095 else
3096 cstr_ccat(&cstr, *s);
3097 ++s;
3101 cstr.size -= spc;
3102 cstr_ccat(&cstr, '\"');
3103 cstr_ccat(&cstr, '\0');
3104 #ifdef PP_DEBUG
3105 printf("\nstringize: <%s>\n", (char *)cstr.data);
3106 #endif
3107 /* add string */
3108 cval.str.size = cstr.size;
3109 cval.str.data = cstr.data;
3110 tok_str_add2(&str, TOK_PPSTR, &cval);
3111 cstr_free(&cstr);
3112 } else {
3113 bad_stringy:
3114 expect("macro parameter after '#'");
3116 } else if (t >= TOK_IDENT) {
3117 s = sym_find2(args, t);
3118 if (s) {
3119 int l0 = str.len;
3120 st = s->d;
3121 /* if '##' is present before or after, no arg substitution */
3122 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
3123 /* special case for var arg macros : ## eats the ','
3124 if empty VA_ARGS variable. */
3125 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
3126 if (*st <= 0) {
3127 /* suppress ',' '##' */
3128 str.len -= 2;
3129 } else {
3130 /* suppress '##' and add variable */
3131 str.len--;
3132 goto add_var;
3135 } else {
3136 add_var:
3137 if (!s->next) {
3138 /* Expand arguments tokens and store them. In most
3139 cases we could also re-expand each argument if
3140 used multiple times, but not if the argument
3141 contains the __COUNTER__ macro. */
3142 TokenString str2;
3143 sym_push2(&s->next, s->v, s->type.t, 0);
3144 tok_str_new(&str2);
3145 macro_subst(&str2, nested_list, st);
3146 tok_str_add(&str2, 0);
3147 s->next->d = str2.str;
3149 st = s->next->d;
3151 for(;;) {
3152 int t2;
3153 TOK_GET(&t2, &st, &cval);
3154 if (t2 <= 0)
3155 break;
3156 tok_str_add2(&str, t2, &cval);
3158 if (str.len == l0) /* expanded to empty string */
3159 tok_str_add(&str, TOK_PLCHLDR);
3160 } else {
3161 tok_str_add(&str, t);
3163 } else {
3164 tok_str_add2(&str, t, &cval);
3166 t0 = t1, t1 = t;
3168 tok_str_add(&str, 0);
3169 return str.str;
3172 static char const ab_month_name[12][4] =
3174 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3175 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3178 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3180 CString cstr;
3181 int n, ret = 1;
3183 cstr_new(&cstr);
3184 if (t1 != TOK_PLCHLDR)
3185 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3186 n = cstr.size;
3187 if (t2 != TOK_PLCHLDR)
3188 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3189 cstr_ccat(&cstr, '\0');
3191 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3192 memcpy(file->buffer, cstr.data, cstr.size);
3193 tok_flags = 0;
3194 for (;;) {
3195 next_nomacro1();
3196 if (0 == *file->buf_ptr)
3197 break;
3198 if (is_space(tok))
3199 continue;
3200 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3201 " preprocessing token", n, (char *)cstr.data, (char*)cstr.data + n);
3202 ret = 0;
3203 break;
3205 tcc_close();
3206 //printf("paste <%s>\n", (char*)cstr.data);
3207 cstr_free(&cstr);
3208 return ret;
3211 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3212 return the resulting string (which must be freed). */
3213 static inline int *macro_twosharps(const int *ptr0)
3215 int t;
3216 CValue cval;
3217 TokenString macro_str1;
3218 int start_of_nosubsts = -1;
3219 const int *ptr;
3221 /* we search the first '##' */
3222 for (ptr = ptr0;;) {
3223 TOK_GET(&t, &ptr, &cval);
3224 if (t == TOK_PPJOIN)
3225 break;
3226 if (t == 0)
3227 return NULL;
3230 tok_str_new(&macro_str1);
3232 //tok_print(" $$$", ptr0);
3233 for (ptr = ptr0;;) {
3234 TOK_GET(&t, &ptr, &cval);
3235 if (t == 0)
3236 break;
3237 if (t == TOK_PPJOIN)
3238 continue;
3239 while (*ptr == TOK_PPJOIN) {
3240 int t1; CValue cv1;
3241 /* given 'a##b', remove nosubsts preceding 'a' */
3242 if (start_of_nosubsts >= 0)
3243 macro_str1.len = start_of_nosubsts;
3244 /* given 'a##b', remove nosubsts preceding 'b' */
3245 while ((t1 = *++ptr) == TOK_NOSUBST)
3247 if (t1 && t1 != TOK_PPJOIN) {
3248 TOK_GET(&t1, &ptr, &cv1);
3249 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3250 if (paste_tokens(t, &cval, t1, &cv1)) {
3251 t = tok, cval = tokc;
3252 } else {
3253 tok_str_add2(&macro_str1, t, &cval);
3254 t = t1, cval = cv1;
3259 if (t == TOK_NOSUBST) {
3260 if (start_of_nosubsts < 0)
3261 start_of_nosubsts = macro_str1.len;
3262 } else {
3263 start_of_nosubsts = -1;
3265 tok_str_add2(&macro_str1, t, &cval);
3267 tok_str_add(&macro_str1, 0);
3268 //tok_print(" ###", macro_str1.str);
3269 return macro_str1.str;
3272 /* peek or read [ws_str == NULL] next token from function macro call,
3273 walking up macro levels up to the file if necessary */
3274 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3276 int t;
3277 const int *p;
3278 Sym *sa;
3280 for (;;) {
3281 if (macro_ptr) {
3282 p = macro_ptr, t = *p;
3283 if (ws_str) {
3284 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3285 tok_str_add(ws_str, t), t = *++p;
3287 if (t == 0) {
3288 end_macro();
3289 /* also, end of scope for nested defined symbol */
3290 sa = *nested_list;
3291 while (sa && sa->v == 0)
3292 sa = sa->prev;
3293 if (sa)
3294 sa->v = 0;
3295 continue;
3297 } else {
3298 ch = handle_eob();
3299 if (ws_str) {
3300 while (is_space(ch) || ch == '\n' || ch == '/') {
3301 if (ch == '/') {
3302 int c;
3303 uint8_t *p = file->buf_ptr;
3304 PEEKC(c, p);
3305 if (c == '*') {
3306 p = parse_comment(p);
3307 file->buf_ptr = p - 1;
3308 } else if (c == '/') {
3309 p = parse_line_comment(p);
3310 file->buf_ptr = p - 1;
3311 } else
3312 break;
3313 ch = ' ';
3315 if (ch == '\n')
3316 file->line_num++;
3317 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3318 tok_str_add(ws_str, ch);
3319 cinp();
3322 t = ch;
3325 if (ws_str)
3326 return t;
3327 next_nomacro();
3328 return tok;
3332 /* do macro substitution of current token with macro 's' and add
3333 result to (tok_str,tok_len). 'nested_list' is the list of all
3334 macros we got inside to avoid recursing. Return non zero if no
3335 substitution needs to be done */
3336 static int macro_subst_tok(
3337 TokenString *tok_str,
3338 Sym **nested_list,
3339 Sym *s)
3341 Sym *args, *sa, *sa1;
3342 int parlevel, t, t1, spc;
3343 TokenString str;
3344 char *cstrval;
3345 CValue cval;
3346 CString cstr;
3347 char buf[32];
3349 /* if symbol is a macro, prepare substitution */
3350 /* special macros */
3351 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3352 t = tok == TOK___LINE__ ? file->line_num : pp_counter++;
3353 snprintf(buf, sizeof(buf), "%d", t);
3354 cstrval = buf;
3355 t1 = TOK_PPNUM;
3356 goto add_cstr1;
3357 } else if (tok == TOK___FILE__) {
3358 cstrval = file->filename;
3359 goto add_cstr;
3360 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3361 time_t ti;
3362 struct tm *tm;
3364 time(&ti);
3365 tm = localtime(&ti);
3366 if (tok == TOK___DATE__) {
3367 snprintf(buf, sizeof(buf), "%s %2d %d",
3368 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3369 } else {
3370 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3371 tm->tm_hour, tm->tm_min, tm->tm_sec);
3373 cstrval = buf;
3374 add_cstr:
3375 t1 = TOK_STR;
3376 add_cstr1:
3377 cstr_new(&cstr);
3378 cstr_cat(&cstr, cstrval, 0);
3379 cval.str.size = cstr.size;
3380 cval.str.data = cstr.data;
3381 tok_str_add2(tok_str, t1, &cval);
3382 cstr_free(&cstr);
3383 } else if (s->d) {
3384 int saved_parse_flags = parse_flags;
3385 int *joined_str = NULL;
3386 int *mstr = s->d;
3388 if (s->type.t == MACRO_FUNC) {
3389 /* whitespace between macro name and argument list */
3390 TokenString ws_str;
3391 tok_str_new(&ws_str);
3393 spc = 0;
3394 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3395 | PARSE_FLAG_ACCEPT_STRAYS;
3397 /* get next token from argument stream */
3398 t = next_argstream(nested_list, &ws_str);
3399 if (t != '(') {
3400 /* not a macro substitution after all, restore the
3401 * macro token plus all whitespace we've read.
3402 * whitespace is intentionally not merged to preserve
3403 * newlines. */
3404 parse_flags = saved_parse_flags;
3405 tok_str_add(tok_str, tok);
3406 if (parse_flags & PARSE_FLAG_SPACES) {
3407 int i;
3408 for (i = 0; i < ws_str.len; i++)
3409 tok_str_add(tok_str, ws_str.str[i]);
3411 tok_str_free_str(ws_str.str);
3412 return 0;
3413 } else {
3414 tok_str_free_str(ws_str.str);
3416 do {
3417 next_nomacro(); /* eat '(' */
3418 } while (tok == TOK_PLCHLDR || is_space(tok));
3420 /* argument macro */
3421 args = NULL;
3422 sa = s->next;
3423 /* NOTE: empty args are allowed, except if no args */
3424 for(;;) {
3425 do {
3426 next_argstream(nested_list, NULL);
3427 } while (is_space(tok) || TOK_LINEFEED == tok);
3428 empty_arg:
3429 /* handle '()' case */
3430 if (!args && !sa && tok == ')')
3431 break;
3432 if (!sa)
3433 tcc_error("macro '%s' used with too many args",
3434 get_tok_str(s->v, 0));
3435 tok_str_new(&str);
3436 parlevel = spc = 0;
3437 /* NOTE: non zero sa->t indicates VA_ARGS */
3438 while ((parlevel > 0 ||
3439 (tok != ')' &&
3440 (tok != ',' || sa->type.t)))) {
3441 if (tok == TOK_EOF || tok == 0)
3442 break;
3443 if (tok == '(')
3444 parlevel++;
3445 else if (tok == ')')
3446 parlevel--;
3447 if (tok == TOK_LINEFEED)
3448 tok = ' ';
3449 if (!check_space(tok, &spc))
3450 tok_str_add2(&str, tok, &tokc);
3451 next_argstream(nested_list, NULL);
3453 if (parlevel)
3454 expect(")");
3455 str.len -= spc;
3456 tok_str_add(&str, -1);
3457 tok_str_add(&str, 0);
3458 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3459 sa1->d = str.str;
3460 sa = sa->next;
3461 if (tok == ')') {
3462 /* special case for gcc var args: add an empty
3463 var arg argument if it is omitted */
3464 if (sa && sa->type.t && gnu_ext)
3465 goto empty_arg;
3466 break;
3468 if (tok != ',')
3469 expect(",");
3471 if (sa) {
3472 tcc_error("macro '%s' used with too few args",
3473 get_tok_str(s->v, 0));
3476 /* now subst each arg */
3477 mstr = macro_arg_subst(nested_list, mstr, args);
3478 /* free memory */
3479 sa = args;
3480 while (sa) {
3481 sa1 = sa->prev;
3482 tok_str_free_str(sa->d);
3483 if (sa->next) {
3484 tok_str_free_str(sa->next->d);
3485 sym_free(sa->next);
3487 sym_free(sa);
3488 sa = sa1;
3490 parse_flags = saved_parse_flags;
3493 sym_push2(nested_list, s->v, 0, 0);
3494 parse_flags = saved_parse_flags;
3495 joined_str = macro_twosharps(mstr);
3496 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3498 /* pop nested defined symbol */
3499 sa1 = *nested_list;
3500 *nested_list = sa1->prev;
3501 sym_free(sa1);
3502 if (joined_str)
3503 tok_str_free_str(joined_str);
3504 if (mstr != s->d)
3505 tok_str_free_str(mstr);
3507 return 0;
3510 /* do macro substitution of macro_str and add result to
3511 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3512 inside to avoid recursing. */
3513 static void macro_subst(
3514 TokenString *tok_str,
3515 Sym **nested_list,
3516 const int *macro_str
3519 Sym *s;
3520 int t, spc, nosubst;
3521 CValue cval;
3523 spc = nosubst = 0;
3525 while (1) {
3526 TOK_GET(&t, &macro_str, &cval);
3527 if (t <= 0)
3528 break;
3530 if (t >= TOK_IDENT && 0 == nosubst) {
3531 s = define_find(t);
3532 if (s == NULL)
3533 goto no_subst;
3535 /* if nested substitution, do nothing */
3536 if (sym_find2(*nested_list, t)) {
3537 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3538 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3539 goto no_subst;
3543 TokenString *str = tok_str_alloc();
3544 str->str = (int*)macro_str;
3545 begin_macro(str, 2);
3547 tok = t;
3548 macro_subst_tok(tok_str, nested_list, s);
3550 if (macro_stack != str) {
3551 /* already finished by reading function macro arguments */
3552 break;
3555 macro_str = macro_ptr;
3556 end_macro ();
3558 if (tok_str->len)
3559 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3560 } else {
3561 no_subst:
3562 if (!check_space(t, &spc))
3563 tok_str_add2(tok_str, t, &cval);
3565 if (nosubst) {
3566 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3567 continue;
3568 nosubst = 0;
3570 if (t == TOK_NOSUBST)
3571 nosubst = 1;
3573 /* GCC supports 'defined' as result of a macro substitution */
3574 if (t == TOK_DEFINED && pp_expr)
3575 nosubst = 2;
3579 /* return next token without macro substitution. Can read input from
3580 macro_ptr buffer */
3581 static void next_nomacro(void)
3583 int t;
3584 if (macro_ptr) {
3585 redo:
3586 t = *macro_ptr;
3587 if (TOK_HAS_VALUE(t)) {
3588 tok_get(&tok, &macro_ptr, &tokc);
3589 if (t == TOK_LINENUM) {
3590 file->line_num = tokc.i;
3591 goto redo;
3593 } else {
3594 macro_ptr++;
3595 if (t < TOK_IDENT) {
3596 if (!(parse_flags & PARSE_FLAG_SPACES)
3597 && (isidnum_table[t - CH_EOF] & IS_SPC))
3598 goto redo;
3600 tok = t;
3602 } else {
3603 next_nomacro1();
3607 /* return next token with macro substitution */
3608 ST_FUNC void next(void)
3610 int t;
3611 redo:
3612 next_nomacro();
3613 t = tok;
3614 if (macro_ptr) {
3615 if (!TOK_HAS_VALUE(t)) {
3616 if (t == TOK_NOSUBST || t == TOK_PLCHLDR) {
3617 /* discard preprocessor markers */
3618 goto redo;
3619 } else if (t == 0) {
3620 /* end of macro or unget token string */
3621 end_macro();
3622 goto redo;
3623 } else if (t == '\\') {
3624 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3625 tcc_error("stray '\\' in program");
3627 return;
3629 } else if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3630 /* if reading from file, try to substitute macros */
3631 Sym *s = define_find(t);
3632 if (s) {
3633 Sym *nested_list = NULL;
3634 tokstr_buf.len = 0;
3635 macro_subst_tok(&tokstr_buf, &nested_list, s);
3636 tok_str_add(&tokstr_buf, 0);
3637 begin_macro(&tokstr_buf, 0);
3638 goto redo;
3640 return;
3642 /* convert preprocessor tokens into C tokens */
3643 if (t == TOK_PPNUM) {
3644 if (parse_flags & PARSE_FLAG_TOK_NUM)
3645 parse_number((char *)tokc.str.data);
3646 } else if (t == TOK_PPSTR) {
3647 if (parse_flags & PARSE_FLAG_TOK_STR)
3648 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3652 /* push back current token and set current token to 'last_tok'. Only
3653 identifier case handled for labels. */
3654 ST_INLN void unget_tok(int last_tok)
3657 TokenString *str = tok_str_alloc();
3658 tok_str_add2(str, tok, &tokc);
3659 tok_str_add(str, 0);
3660 begin_macro(str, 1);
3661 tok = last_tok;
3664 /* ------------------------------------------------------------------------- */
3665 /* init preprocessor */
3667 static const char * const target_os_defs =
3668 #ifdef TCC_TARGET_PE
3669 "_WIN32\0"
3670 # if PTR_SIZE == 8
3671 "_WIN64\0"
3672 # endif
3673 #else
3674 # if defined TCC_TARGET_MACHO
3675 "__APPLE__\0"
3676 # elif TARGETOS_FreeBSD
3677 "__FreeBSD__ 12\0"
3678 # elif TARGETOS_FreeBSD_kernel
3679 "__FreeBSD_kernel__\0"
3680 # elif TARGETOS_NetBSD
3681 "__NetBSD__\0"
3682 # elif TARGETOS_OpenBSD
3683 "__OpenBSD__\0"
3684 # else
3685 "__linux__\0"
3686 "__linux\0"
3687 # endif
3688 "__unix__\0"
3689 "__unix\0"
3690 #endif
3693 static void putdef(CString *cs, const char *p)
3695 cstr_printf(cs, "#define %s%s\n", p, &" 1"[!!strchr(p, ' ')*2]);
3698 static void tcc_predefs(TCCState *s1, CString *cs, int is_asm)
3700 int a, b, c;
3701 const char *defs[] = { target_machine_defs, target_os_defs, NULL };
3702 const char *p;
3704 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
3705 cstr_printf(cs, "#define __TINYC__ %d\n", a*10000 + b*100 + c);
3706 for (a = 0; defs[a]; ++a)
3707 for (p = defs[a]; *p; p = strchr(p, 0) + 1)
3708 putdef(cs, p);
3709 #ifdef TCC_TARGET_ARM
3710 if (s1->float_abi == ARM_HARD_FLOAT)
3711 putdef(cs, "__ARM_PCS_VFP");
3712 #endif
3713 if (is_asm)
3714 putdef(cs, "__ASSEMBLER__");
3715 if (s1->output_type == TCC_OUTPUT_PREPROCESS)
3716 putdef(cs, "__TCC_PP__");
3717 if (s1->output_type == TCC_OUTPUT_MEMORY)
3718 putdef(cs, "__TCC_RUN__");
3719 if (s1->char_is_unsigned)
3720 putdef(cs, "__CHAR_UNSIGNED__");
3721 if (s1->optimize > 0)
3722 putdef(cs, "__OPTIMIZE__");
3723 if (s1->option_pthread)
3724 putdef(cs, "_REENTRANT");
3725 if (s1->leading_underscore)
3726 putdef(cs, "__leading_underscore");
3727 #ifdef CONFIG_TCC_BCHECK
3728 if (s1->do_bounds_check)
3729 putdef(cs, "__BOUNDS_CHECKING_ON");
3730 #endif
3731 cstr_printf(cs, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE);
3732 cstr_printf(cs, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE);
3733 if (!is_asm) {
3734 putdef(cs, "__STDC__");
3735 cstr_printf(cs, "#define __STDC_VERSION__ %dL\n", s1->cversion);
3736 cstr_cat(cs,
3737 /* load more predefs and __builtins */
3738 #if CONFIG_TCC_PREDEFS
3739 #include "tccdefs_.h" /* include as strings */
3740 #else
3741 "#include <tccdefs.h>\n" /* load at runtime */
3742 #endif
3743 , -1);
3745 cstr_printf(cs, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3748 ST_FUNC void preprocess_start(TCCState *s1, int filetype)
3750 int is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
3751 CString cstr;
3753 tccpp_new(s1);
3755 s1->include_stack_ptr = s1->include_stack;
3756 s1->ifdef_stack_ptr = s1->ifdef_stack;
3757 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3758 pp_expr = 0;
3759 pp_counter = 0;
3760 pp_debug_tok = pp_debug_symv = 0;
3761 pp_once++;
3762 s1->pack_stack[0] = 0;
3763 s1->pack_stack_ptr = s1->pack_stack;
3765 set_idnum('$', !is_asm && s1->dollars_in_identifiers ? IS_ID : 0);
3766 set_idnum('.', is_asm ? IS_ID : 0);
3768 if (!(filetype & AFF_TYPE_ASM)) {
3769 cstr_new(&cstr);
3770 tcc_predefs(s1, &cstr, is_asm);
3771 if (s1->cmdline_defs.size)
3772 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3773 if (s1->cmdline_incl.size)
3774 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3775 //printf("%s\n", (char*)cstr.data);
3776 *s1->include_stack_ptr++ = file;
3777 tcc_open_bf(s1, "<command line>", cstr.size);
3778 memcpy(file->buffer, cstr.data, cstr.size);
3779 cstr_free(&cstr);
3782 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3783 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3786 /* cleanup from error/setjmp */
3787 ST_FUNC void preprocess_end(TCCState *s1)
3789 while (macro_stack)
3790 end_macro();
3791 macro_ptr = NULL;
3792 while (file)
3793 tcc_close();
3794 tccpp_delete(s1);
3797 ST_FUNC void tccpp_new(TCCState *s)
3799 int i, c;
3800 const char *p, *r;
3802 /* init isid table */
3803 for(i = CH_EOF; i<128; i++)
3804 set_idnum(i,
3805 is_space(i) ? IS_SPC
3806 : isid(i) ? IS_ID
3807 : isnum(i) ? IS_NUM
3808 : 0);
3810 for(i = 128; i<256; i++)
3811 set_idnum(i, IS_ID);
3813 /* init allocators */
3814 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3815 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3817 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3818 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3820 cstr_new(&cstr_buf);
3821 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3822 tok_str_new(&tokstr_buf);
3823 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3825 tok_ident = TOK_IDENT;
3826 p = tcc_keywords;
3827 while (*p) {
3828 r = p;
3829 for(;;) {
3830 c = *r++;
3831 if (c == '\0')
3832 break;
3834 tok_alloc(p, r - p - 1);
3835 p = r;
3838 /* we add dummy defines for some special macros to speed up tests
3839 and to have working defined() */
3840 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3841 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3842 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3843 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3844 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3847 ST_FUNC void tccpp_delete(TCCState *s)
3849 int i, n;
3851 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3853 /* free tokens */
3854 n = tok_ident - TOK_IDENT;
3855 if (n > total_idents)
3856 total_idents = n;
3857 for(i = 0; i < n; i++)
3858 tal_free(toksym_alloc, table_ident[i]);
3859 tcc_free(table_ident);
3860 table_ident = NULL;
3862 /* free static buffers */
3863 cstr_free(&tokcstr);
3864 cstr_free(&cstr_buf);
3865 cstr_free(&macro_equal_buf);
3866 tok_str_free_str(tokstr_buf.str);
3868 /* free allocators */
3869 tal_delete(toksym_alloc);
3870 toksym_alloc = NULL;
3871 tal_delete(tokstr_alloc);
3872 tokstr_alloc = NULL;
3875 /* ------------------------------------------------------------------------- */
3876 /* tcc -E [-P[1]] [-dD} support */
3878 static void tok_print(const char *msg, const int *str)
3880 FILE *fp;
3881 int t, s = 0;
3882 CValue cval;
3884 fp = tcc_state->ppfp;
3885 fprintf(fp, "%s", msg);
3886 while (str) {
3887 TOK_GET(&t, &str, &cval);
3888 if (!t)
3889 break;
3890 fprintf(fp, &" %s"[s], get_tok_str(t, &cval)), s = 1;
3892 fprintf(fp, "\n");
3895 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3897 int d = f->line_num - f->line_ref;
3899 if (s1->dflag & 4)
3900 return;
3902 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3904 } else if (level == 0 && f->line_ref && d < 8) {
3905 while (d > 0)
3906 fputs("\n", s1->ppfp), --d;
3907 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3908 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3909 } else {
3910 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3911 level > 0 ? " 1" : level < 0 ? " 2" : "");
3913 f->line_ref = f->line_num;
3916 static void define_print(TCCState *s1, int v)
3918 FILE *fp;
3919 Sym *s;
3921 s = define_find(v);
3922 if (NULL == s || NULL == s->d)
3923 return;
3925 fp = s1->ppfp;
3926 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3927 if (s->type.t == MACRO_FUNC) {
3928 Sym *a = s->next;
3929 fprintf(fp,"(");
3930 if (a)
3931 for (;;) {
3932 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3933 if (!(a = a->next))
3934 break;
3935 fprintf(fp,",");
3937 fprintf(fp,")");
3939 tok_print("", s->d);
3942 static void pp_debug_defines(TCCState *s1)
3944 int v, t;
3945 const char *vs;
3946 FILE *fp;
3948 t = pp_debug_tok;
3949 if (t == 0)
3950 return;
3952 file->line_num--;
3953 pp_line(s1, file, 0);
3954 file->line_ref = ++file->line_num;
3956 fp = s1->ppfp;
3957 v = pp_debug_symv;
3958 vs = get_tok_str(v, NULL);
3959 if (t == TOK_DEFINE) {
3960 define_print(s1, v);
3961 } else if (t == TOK_UNDEF) {
3962 fprintf(fp, "#undef %s\n", vs);
3963 } else if (t == TOK_push_macro) {
3964 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3965 } else if (t == TOK_pop_macro) {
3966 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3968 pp_debug_tok = 0;
3971 static void pp_debug_builtins(TCCState *s1)
3973 int v;
3974 for (v = TOK_IDENT; v < tok_ident; ++v)
3975 define_print(s1, v);
3978 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3979 static int pp_need_space(int a, int b)
3981 return 'E' == a ? '+' == b || '-' == b
3982 : '+' == a ? TOK_INC == b || '+' == b
3983 : '-' == a ? TOK_DEC == b || '-' == b
3984 : a >= TOK_IDENT ? b >= TOK_IDENT
3985 : a == TOK_PPNUM ? b >= TOK_IDENT
3986 : 0;
3989 /* maybe hex like 0x1e */
3990 static int pp_check_he0xE(int t, const char *p)
3992 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3993 return 'E';
3994 return t;
3997 /* Preprocess the current file */
3998 ST_FUNC int tcc_preprocess(TCCState *s1)
4000 BufferedFile **iptr;
4001 int token_seen, spcs, level;
4002 const char *p;
4003 char white[400];
4005 parse_flags = PARSE_FLAG_PREPROCESS
4006 | (parse_flags & PARSE_FLAG_ASM_FILE)
4007 | PARSE_FLAG_LINEFEED
4008 | PARSE_FLAG_SPACES
4009 | PARSE_FLAG_ACCEPT_STRAYS
4011 /* Credits to Fabrice Bellard's initial revision to demonstrate its
4012 capability to compile and run itself, provided all numbers are
4013 given as decimals. tcc -E -P10 will do. */
4014 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
4015 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
4017 if (s1->do_bench) {
4018 /* for PP benchmarks */
4019 do next(); while (tok != TOK_EOF);
4020 return 0;
4023 if (s1->dflag & 1) {
4024 pp_debug_builtins(s1);
4025 s1->dflag &= ~1;
4028 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
4029 if (file->prev)
4030 pp_line(s1, file->prev, level++);
4031 pp_line(s1, file, level);
4032 for (;;) {
4033 iptr = s1->include_stack_ptr;
4034 next();
4035 if (tok == TOK_EOF)
4036 break;
4038 level = s1->include_stack_ptr - iptr;
4039 if (level) {
4040 if (level > 0)
4041 pp_line(s1, *iptr, 0);
4042 pp_line(s1, file, level);
4044 if (s1->dflag & 7) {
4045 pp_debug_defines(s1);
4046 if (s1->dflag & 4)
4047 continue;
4050 if (is_space(tok)) {
4051 if (spcs < sizeof white - 1)
4052 white[spcs++] = tok;
4053 continue;
4054 } else if (tok == TOK_LINEFEED) {
4055 spcs = 0;
4056 if (token_seen == TOK_LINEFEED)
4057 continue;
4058 ++file->line_ref;
4059 } else if (token_seen == TOK_LINEFEED) {
4060 pp_line(s1, file, 0);
4061 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
4062 white[spcs++] = ' ';
4065 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
4066 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
4067 token_seen = pp_check_he0xE(tok, p);
4069 return 0;
4072 /* ------------------------------------------------------------------------- */