WAIT/POST_SEM(): generalize interface (and more)
[tinycc.git] / tccpp.c
blob897ef15126d63500df20b139599f76e6e481398c
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_vprintf(CString *cstr, const char *fmt, va_list ap)
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_copy(v, ap);
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 ST_FUNC int cstr_printf(CString *cstr, const char *fmt, ...)
429 va_list ap; int len;
430 va_start(ap, fmt);
431 len = cstr_vprintf(cstr, fmt, ap);
432 va_end(ap);
433 return len;
436 /* XXX: unicode ? */
437 static void add_char(CString *cstr, int c)
439 if (c == '\'' || c == '\"' || c == '\\') {
440 /* XXX: could be more precise if char or string */
441 cstr_ccat(cstr, '\\');
443 if (c >= 32 && c <= 126) {
444 cstr_ccat(cstr, c);
445 } else {
446 cstr_ccat(cstr, '\\');
447 if (c == '\n') {
448 cstr_ccat(cstr, 'n');
449 } else {
450 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
451 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
452 cstr_ccat(cstr, '0' + (c & 7));
457 /* ------------------------------------------------------------------------- */
458 /* allocate a new token */
459 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
461 TokenSym *ts, **ptable;
462 int i;
464 if (tok_ident >= SYM_FIRST_ANOM)
465 tcc_error("memory full (symbols)");
467 /* expand token table if needed */
468 i = tok_ident - TOK_IDENT;
469 if ((i % TOK_ALLOC_INCR) == 0) {
470 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
471 table_ident = ptable;
474 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
475 table_ident[i] = ts;
476 ts->tok = tok_ident++;
477 ts->sym_define = NULL;
478 ts->sym_label = NULL;
479 ts->sym_struct = NULL;
480 ts->sym_identifier = NULL;
481 ts->len = len;
482 ts->hash_next = NULL;
483 memcpy(ts->str, str, len);
484 ts->str[len] = '\0';
485 *pts = ts;
486 return ts;
489 #define TOK_HASH_INIT 1
490 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
493 /* find a token and add it if not found */
494 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
496 TokenSym *ts, **pts;
497 int i;
498 unsigned int h;
500 h = TOK_HASH_INIT;
501 for(i=0;i<len;i++)
502 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
503 h &= (TOK_HASH_SIZE - 1);
505 pts = &hash_ident[h];
506 for(;;) {
507 ts = *pts;
508 if (!ts)
509 break;
510 if (ts->len == len && !memcmp(ts->str, str, len))
511 return ts;
512 pts = &(ts->hash_next);
514 return tok_alloc_new(pts, str, len);
517 ST_FUNC int tok_alloc_const(const char *str)
519 return tok_alloc(str, strlen(str))->tok;
523 /* XXX: buffer overflow */
524 /* XXX: float tokens */
525 ST_FUNC const char *get_tok_str(int v, CValue *cv)
527 char *p;
528 int i, len;
530 cstr_reset(&cstr_buf);
531 p = cstr_buf.data;
533 switch(v) {
534 case TOK_CINT:
535 case TOK_CUINT:
536 case TOK_CLONG:
537 case TOK_CULONG:
538 case TOK_CLLONG:
539 case TOK_CULLONG:
540 /* XXX: not quite exact, but only useful for testing */
541 #ifdef _WIN32
542 sprintf(p, "%u", (unsigned)cv->i);
543 #else
544 sprintf(p, "%llu", (unsigned long long)cv->i);
545 #endif
546 break;
547 case TOK_LCHAR:
548 cstr_ccat(&cstr_buf, 'L');
549 case TOK_CCHAR:
550 cstr_ccat(&cstr_buf, '\'');
551 add_char(&cstr_buf, cv->i);
552 cstr_ccat(&cstr_buf, '\'');
553 cstr_ccat(&cstr_buf, '\0');
554 break;
555 case TOK_PPNUM:
556 case TOK_PPSTR:
557 return (char*)cv->str.data;
558 case TOK_LSTR:
559 cstr_ccat(&cstr_buf, 'L');
560 case TOK_STR:
561 cstr_ccat(&cstr_buf, '\"');
562 if (v == TOK_STR) {
563 len = cv->str.size - 1;
564 for(i=0;i<len;i++)
565 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
566 } else {
567 len = (cv->str.size / sizeof(nwchar_t)) - 1;
568 for(i=0;i<len;i++)
569 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
571 cstr_ccat(&cstr_buf, '\"');
572 cstr_ccat(&cstr_buf, '\0');
573 break;
575 case TOK_CFLOAT:
576 cstr_cat(&cstr_buf, "<float>", 0);
577 break;
578 case TOK_CDOUBLE:
579 cstr_cat(&cstr_buf, "<double>", 0);
580 break;
581 case TOK_CLDOUBLE:
582 cstr_cat(&cstr_buf, "<long double>", 0);
583 break;
584 case TOK_LINENUM:
585 cstr_cat(&cstr_buf, "<linenumber>", 0);
586 break;
588 /* above tokens have value, the ones below don't */
589 case TOK_LT:
590 v = '<';
591 goto addv;
592 case TOK_GT:
593 v = '>';
594 goto addv;
595 case TOK_DOTS:
596 return strcpy(p, "...");
597 case TOK_A_SHL:
598 return strcpy(p, "<<=");
599 case TOK_A_SAR:
600 return strcpy(p, ">>=");
601 case TOK_EOF:
602 return strcpy(p, "<eof>");
603 default:
604 if (v < TOK_IDENT) {
605 /* search in two bytes table */
606 const unsigned char *q = tok_two_chars;
607 while (*q) {
608 if (q[2] == v) {
609 *p++ = q[0];
610 *p++ = q[1];
611 *p = '\0';
612 return cstr_buf.data;
614 q += 3;
616 if (v >= 127) {
617 sprintf(cstr_buf.data, "<%02x>", v);
618 return cstr_buf.data;
620 addv:
621 *p++ = v;
622 case 0: /* nameless anonymous symbol */
623 *p = '\0';
624 } else if (v < tok_ident) {
625 return table_ident[v - TOK_IDENT]->str;
626 } else if (v >= SYM_FIRST_ANOM) {
627 /* special name for anonymous symbol */
628 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
629 } else {
630 /* should never happen */
631 return NULL;
633 break;
635 return cstr_buf.data;
638 /* return the current character, handling end of block if necessary
639 (but not stray) */
640 static int handle_eob(void)
642 BufferedFile *bf = file;
643 int len;
645 /* only tries to read if really end of buffer */
646 if (bf->buf_ptr >= bf->buf_end) {
647 if (bf->fd >= 0) {
648 #if defined(PARSE_DEBUG)
649 len = 1;
650 #else
651 len = IO_BUF_SIZE;
652 #endif
653 len = read(bf->fd, bf->buffer, len);
654 if (len < 0)
655 len = 0;
656 } else {
657 len = 0;
659 total_bytes += len;
660 bf->buf_ptr = bf->buffer;
661 bf->buf_end = bf->buffer + len;
662 *bf->buf_end = CH_EOB;
664 if (bf->buf_ptr < bf->buf_end) {
665 return bf->buf_ptr[0];
666 } else {
667 bf->buf_ptr = bf->buf_end;
668 return CH_EOF;
672 /* read next char from current input file and handle end of input buffer */
673 static inline void inp(void)
675 ch = *(++(file->buf_ptr));
676 /* end of buffer/file handling */
677 if (ch == CH_EOB)
678 ch = handle_eob();
681 /* handle '\[\r]\n' */
682 static int handle_stray_noerror(void)
684 while (ch == '\\') {
685 inp();
686 if (ch == '\n') {
687 file->line_num++;
688 inp();
689 } else if (ch == '\r') {
690 inp();
691 if (ch != '\n')
692 goto fail;
693 file->line_num++;
694 inp();
695 } else {
696 fail:
697 return 1;
700 return 0;
703 static void handle_stray(void)
705 if (handle_stray_noerror())
706 tcc_error("stray '\\' in program");
709 /* skip the stray and handle the \\n case. Output an error if
710 incorrect char after the stray */
711 static int handle_stray1(uint8_t *p)
713 int c;
715 file->buf_ptr = p;
716 if (p >= file->buf_end) {
717 c = handle_eob();
718 if (c != '\\')
719 return c;
720 p = file->buf_ptr;
722 ch = *p;
723 if (handle_stray_noerror()) {
724 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
725 tcc_error("stray '\\' in program");
726 *--file->buf_ptr = '\\';
728 p = file->buf_ptr;
729 c = *p;
730 return c;
733 /* handle just the EOB case, but not stray */
734 #define PEEKC_EOB(c, p)\
736 p++;\
737 c = *p;\
738 if (c == '\\') {\
739 file->buf_ptr = p;\
740 c = handle_eob();\
741 p = file->buf_ptr;\
745 /* handle the complicated stray case */
746 #define PEEKC(c, p)\
748 p++;\
749 c = *p;\
750 if (c == '\\') {\
751 c = handle_stray1(p);\
752 p = file->buf_ptr;\
756 /* input with '\[\r]\n' handling. Note that this function cannot
757 handle other characters after '\', so you cannot call it inside
758 strings or comments */
759 static void minp(void)
761 inp();
762 if (ch == '\\')
763 handle_stray();
766 /* single line C++ comments */
767 static uint8_t *parse_line_comment(uint8_t *p)
769 int c;
771 p++;
772 for(;;) {
773 c = *p;
774 redo:
775 if (c == '\n' || c == CH_EOF) {
776 break;
777 } else if (c == '\\') {
778 file->buf_ptr = p;
779 c = handle_eob();
780 p = file->buf_ptr;
781 if (c == '\\') {
782 PEEKC_EOB(c, p);
783 if (c == '\n') {
784 file->line_num++;
785 PEEKC_EOB(c, p);
786 } else if (c == '\r') {
787 PEEKC_EOB(c, p);
788 if (c == '\n') {
789 file->line_num++;
790 PEEKC_EOB(c, p);
793 } else {
794 goto redo;
796 } else {
797 p++;
800 return p;
803 /* C comments */
804 static uint8_t *parse_comment(uint8_t *p)
806 int c;
808 p++;
809 for(;;) {
810 /* fast skip loop */
811 for(;;) {
812 c = *p;
813 if (c == '\n' || c == '*' || c == '\\')
814 break;
815 p++;
816 c = *p;
817 if (c == '\n' || c == '*' || c == '\\')
818 break;
819 p++;
821 /* now we can handle all the cases */
822 if (c == '\n') {
823 file->line_num++;
824 p++;
825 } else if (c == '*') {
826 p++;
827 for(;;) {
828 c = *p;
829 if (c == '*') {
830 p++;
831 } else if (c == '/') {
832 goto end_of_comment;
833 } else if (c == '\\') {
834 file->buf_ptr = p;
835 c = handle_eob();
836 p = file->buf_ptr;
837 if (c == CH_EOF)
838 tcc_error("unexpected end of file in comment");
839 if (c == '\\') {
840 /* skip '\[\r]\n', otherwise just skip the stray */
841 while (c == '\\') {
842 PEEKC_EOB(c, p);
843 if (c == '\n') {
844 file->line_num++;
845 PEEKC_EOB(c, p);
846 } else if (c == '\r') {
847 PEEKC_EOB(c, p);
848 if (c == '\n') {
849 file->line_num++;
850 PEEKC_EOB(c, p);
852 } else {
853 goto after_star;
857 } else {
858 break;
861 after_star: ;
862 } else {
863 /* stray, eob or eof */
864 file->buf_ptr = p;
865 c = handle_eob();
866 p = file->buf_ptr;
867 if (c == CH_EOF) {
868 tcc_error("unexpected end of file in comment");
869 } else if (c == '\\') {
870 p++;
874 end_of_comment:
875 p++;
876 return p;
879 ST_FUNC int set_idnum(int c, int val)
881 int prev = isidnum_table[c - CH_EOF];
882 isidnum_table[c - CH_EOF] = val;
883 return prev;
886 #define cinp minp
888 static inline void skip_spaces(void)
890 while (isidnum_table[ch - CH_EOF] & IS_SPC)
891 cinp();
894 static inline int check_space(int t, int *spc)
896 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
897 if (*spc)
898 return 1;
899 *spc = 1;
900 } else
901 *spc = 0;
902 return 0;
905 /* parse a string without interpreting escapes */
906 static uint8_t *parse_pp_string(uint8_t *p,
907 int sep, CString *str)
909 int c;
910 p++;
911 for(;;) {
912 c = *p;
913 if (c == sep) {
914 break;
915 } else if (c == '\\') {
916 file->buf_ptr = p;
917 c = handle_eob();
918 p = file->buf_ptr;
919 if (c == CH_EOF) {
920 unterminated_string:
921 /* XXX: indicate line number of start of string */
922 tcc_error("missing terminating %c character", sep);
923 } else if (c == '\\') {
924 /* escape : just skip \[\r]\n */
925 PEEKC_EOB(c, p);
926 if (c == '\n') {
927 file->line_num++;
928 p++;
929 } else if (c == '\r') {
930 PEEKC_EOB(c, p);
931 if (c != '\n')
932 expect("'\n' after '\r'");
933 file->line_num++;
934 p++;
935 } else if (c == CH_EOF) {
936 goto unterminated_string;
937 } else {
938 if (str) {
939 cstr_ccat(str, '\\');
940 cstr_ccat(str, c);
942 p++;
945 } else if (c == '\n') {
946 file->line_num++;
947 goto add_char;
948 } else if (c == '\r') {
949 PEEKC_EOB(c, p);
950 if (c != '\n') {
951 if (str)
952 cstr_ccat(str, '\r');
953 } else {
954 file->line_num++;
955 goto add_char;
957 } else {
958 add_char:
959 if (str)
960 cstr_ccat(str, c);
961 p++;
964 p++;
965 return p;
968 /* skip block of text until #else, #elif or #endif. skip also pairs of
969 #if/#endif */
970 static void preprocess_skip(void)
972 int a, start_of_line, c, in_warn_or_error;
973 uint8_t *p;
975 p = file->buf_ptr;
976 a = 0;
977 redo_start:
978 start_of_line = 1;
979 in_warn_or_error = 0;
980 for(;;) {
981 redo_no_start:
982 c = *p;
983 switch(c) {
984 case ' ':
985 case '\t':
986 case '\f':
987 case '\v':
988 case '\r':
989 p++;
990 goto redo_no_start;
991 case '\n':
992 file->line_num++;
993 p++;
994 goto redo_start;
995 case '\\':
996 file->buf_ptr = p;
997 c = handle_eob();
998 if (c == CH_EOF) {
999 expect("#endif");
1000 } else if (c == '\\') {
1001 ch = file->buf_ptr[0];
1002 handle_stray_noerror();
1004 p = file->buf_ptr;
1005 goto redo_no_start;
1006 /* skip strings */
1007 case '\"':
1008 case '\'':
1009 if (in_warn_or_error)
1010 goto _default;
1011 p = parse_pp_string(p, c, NULL);
1012 break;
1013 /* skip comments */
1014 case '/':
1015 if (in_warn_or_error)
1016 goto _default;
1017 file->buf_ptr = p;
1018 ch = *p;
1019 minp();
1020 p = file->buf_ptr;
1021 if (ch == '*') {
1022 p = parse_comment(p);
1023 } else if (ch == '/') {
1024 p = parse_line_comment(p);
1026 break;
1027 case '#':
1028 p++;
1029 if (start_of_line) {
1030 file->buf_ptr = p;
1031 next_nomacro();
1032 p = file->buf_ptr;
1033 if (a == 0 &&
1034 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
1035 goto the_end;
1036 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
1037 a++;
1038 else if (tok == TOK_ENDIF)
1039 a--;
1040 else if( tok == TOK_ERROR || tok == TOK_WARNING)
1041 in_warn_or_error = 1;
1042 else if (tok == TOK_LINEFEED)
1043 goto redo_start;
1044 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1045 p = parse_line_comment(p - 1);
1047 #if !defined(TCC_TARGET_ARM)
1048 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1049 p = parse_line_comment(p - 1);
1050 #else
1051 /* ARM assembly uses '#' for constants */
1052 #endif
1053 break;
1054 _default:
1055 default:
1056 p++;
1057 break;
1059 start_of_line = 0;
1061 the_end: ;
1062 file->buf_ptr = p;
1065 #if 0
1066 /* return the number of additional 'ints' necessary to store the
1067 token */
1068 static inline int tok_size(const int *p)
1070 switch(*p) {
1071 /* 4 bytes */
1072 case TOK_CINT:
1073 case TOK_CUINT:
1074 case TOK_CCHAR:
1075 case TOK_LCHAR:
1076 case TOK_CFLOAT:
1077 case TOK_LINENUM:
1078 return 1 + 1;
1079 case TOK_STR:
1080 case TOK_LSTR:
1081 case TOK_PPNUM:
1082 case TOK_PPSTR:
1083 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1084 case TOK_CLONG:
1085 case TOK_CULONG:
1086 return 1 + LONG_SIZE / 4;
1087 case TOK_CDOUBLE:
1088 case TOK_CLLONG:
1089 case TOK_CULLONG:
1090 return 1 + 2;
1091 case TOK_CLDOUBLE:
1092 return 1 + LDOUBLE_SIZE / 4;
1093 default:
1094 return 1 + 0;
1097 #endif
1099 /* token string handling */
1100 ST_INLN void tok_str_new(TokenString *s)
1102 s->str = NULL;
1103 s->len = s->lastlen = 0;
1104 s->allocated_len = 0;
1105 s->last_line_num = -1;
1108 ST_FUNC TokenString *tok_str_alloc(void)
1110 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1111 tok_str_new(str);
1112 return str;
1115 ST_FUNC int *tok_str_dup(TokenString *s)
1117 int *str;
1119 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1120 memcpy(str, s->str, s->len * sizeof(int));
1121 return str;
1124 ST_FUNC void tok_str_free_str(int *str)
1126 tal_free(tokstr_alloc, str);
1129 ST_FUNC void tok_str_free(TokenString *str)
1131 tok_str_free_str(str->str);
1132 tal_free(tokstr_alloc, str);
1135 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1137 int *str, size;
1139 size = s->allocated_len;
1140 if (size < 16)
1141 size = 16;
1142 while (size < new_size)
1143 size = size * 2;
1144 if (size > s->allocated_len) {
1145 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1146 s->allocated_len = size;
1147 s->str = str;
1149 return s->str;
1152 ST_FUNC void tok_str_add(TokenString *s, int t)
1154 int len, *str;
1156 len = s->len;
1157 str = s->str;
1158 if (len >= s->allocated_len)
1159 str = tok_str_realloc(s, len + 1);
1160 str[len++] = t;
1161 s->len = len;
1164 ST_FUNC void begin_macro(TokenString *str, int alloc)
1166 str->alloc = alloc;
1167 str->prev = macro_stack;
1168 str->prev_ptr = macro_ptr;
1169 str->save_line_num = file->line_num;
1170 macro_ptr = str->str;
1171 macro_stack = str;
1174 ST_FUNC void end_macro(void)
1176 TokenString *str = macro_stack;
1177 macro_stack = str->prev;
1178 macro_ptr = str->prev_ptr;
1179 file->line_num = str->save_line_num;
1180 if (str->alloc != 0) {
1181 if (str->alloc == 2)
1182 str->str = NULL; /* don't free */
1183 tok_str_free(str);
1187 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1189 int len, *str;
1191 len = s->lastlen = s->len;
1192 str = s->str;
1194 /* allocate space for worst case */
1195 if (len + TOK_MAX_SIZE >= s->allocated_len)
1196 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1197 str[len++] = t;
1198 switch(t) {
1199 case TOK_CINT:
1200 case TOK_CUINT:
1201 case TOK_CCHAR:
1202 case TOK_LCHAR:
1203 case TOK_CFLOAT:
1204 case TOK_LINENUM:
1205 #if LONG_SIZE == 4
1206 case TOK_CLONG:
1207 case TOK_CULONG:
1208 #endif
1209 str[len++] = cv->tab[0];
1210 break;
1211 case TOK_PPNUM:
1212 case TOK_PPSTR:
1213 case TOK_STR:
1214 case TOK_LSTR:
1216 /* Insert the string into the int array. */
1217 size_t nb_words =
1218 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1219 if (len + nb_words >= s->allocated_len)
1220 str = tok_str_realloc(s, len + nb_words + 1);
1221 str[len] = cv->str.size;
1222 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1223 len += nb_words;
1225 break;
1226 case TOK_CDOUBLE:
1227 case TOK_CLLONG:
1228 case TOK_CULLONG:
1229 #if LONG_SIZE == 8
1230 case TOK_CLONG:
1231 case TOK_CULONG:
1232 #endif
1233 #if LDOUBLE_SIZE == 8
1234 case TOK_CLDOUBLE:
1235 #endif
1236 str[len++] = cv->tab[0];
1237 str[len++] = cv->tab[1];
1238 break;
1239 #if LDOUBLE_SIZE == 12
1240 case TOK_CLDOUBLE:
1241 str[len++] = cv->tab[0];
1242 str[len++] = cv->tab[1];
1243 str[len++] = cv->tab[2];
1244 #elif LDOUBLE_SIZE == 16
1245 case TOK_CLDOUBLE:
1246 str[len++] = cv->tab[0];
1247 str[len++] = cv->tab[1];
1248 str[len++] = cv->tab[2];
1249 str[len++] = cv->tab[3];
1250 #elif LDOUBLE_SIZE != 8
1251 #error add long double size support
1252 #endif
1253 break;
1254 default:
1255 break;
1257 s->len = len;
1260 /* add the current parse token in token string 's' */
1261 ST_FUNC void tok_str_add_tok(TokenString *s)
1263 CValue cval;
1265 /* save line number info */
1266 if (file->line_num != s->last_line_num) {
1267 s->last_line_num = file->line_num;
1268 cval.i = s->last_line_num;
1269 tok_str_add2(s, TOK_LINENUM, &cval);
1271 tok_str_add2(s, tok, &tokc);
1274 /* get a token from an integer array and increment pointer. */
1275 static inline void tok_get(int *t, const int **pp, CValue *cv)
1277 const int *p = *pp;
1278 int n, *tab;
1280 tab = cv->tab;
1281 switch(*t = *p++) {
1282 #if LONG_SIZE == 4
1283 case TOK_CLONG:
1284 #endif
1285 case TOK_CINT:
1286 case TOK_CCHAR:
1287 case TOK_LCHAR:
1288 case TOK_LINENUM:
1289 cv->i = *p++;
1290 break;
1291 #if LONG_SIZE == 4
1292 case TOK_CULONG:
1293 #endif
1294 case TOK_CUINT:
1295 cv->i = (unsigned)*p++;
1296 break;
1297 case TOK_CFLOAT:
1298 tab[0] = *p++;
1299 break;
1300 case TOK_STR:
1301 case TOK_LSTR:
1302 case TOK_PPNUM:
1303 case TOK_PPSTR:
1304 cv->str.size = *p++;
1305 cv->str.data = p;
1306 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1307 break;
1308 case TOK_CDOUBLE:
1309 case TOK_CLLONG:
1310 case TOK_CULLONG:
1311 #if LONG_SIZE == 8
1312 case TOK_CLONG:
1313 case TOK_CULONG:
1314 #endif
1315 n = 2;
1316 goto copy;
1317 case TOK_CLDOUBLE:
1318 #if LDOUBLE_SIZE == 16
1319 n = 4;
1320 #elif LDOUBLE_SIZE == 12
1321 n = 3;
1322 #elif LDOUBLE_SIZE == 8
1323 n = 2;
1324 #else
1325 # error add long double size support
1326 #endif
1327 copy:
1329 *tab++ = *p++;
1330 while (--n);
1331 break;
1332 default:
1333 break;
1335 *pp = p;
1338 #if 0
1339 # define TOK_GET(t,p,c) tok_get(t,p,c)
1340 #else
1341 # define TOK_GET(t,p,c) do { \
1342 int _t = **(p); \
1343 if (TOK_HAS_VALUE(_t)) \
1344 tok_get(t, p, c); \
1345 else \
1346 *(t) = _t, ++*(p); \
1347 } while (0)
1348 #endif
1350 static int macro_is_equal(const int *a, const int *b)
1352 CValue cv;
1353 int t;
1355 if (!a || !b)
1356 return 1;
1358 while (*a && *b) {
1359 /* first time preallocate macro_equal_buf, next time only reset position to start */
1360 cstr_reset(&macro_equal_buf);
1361 TOK_GET(&t, &a, &cv);
1362 cstr_cat(&macro_equal_buf, get_tok_str(t, &cv), 0);
1363 TOK_GET(&t, &b, &cv);
1364 if (strcmp(macro_equal_buf.data, get_tok_str(t, &cv)))
1365 return 0;
1367 return !(*a || *b);
1370 /* defines handling */
1371 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1373 Sym *s, *o;
1375 o = define_find(v);
1376 s = sym_push2(&define_stack, v, macro_type, 0);
1377 s->d = str;
1378 s->next = first_arg;
1379 table_ident[v - TOK_IDENT]->sym_define = s;
1381 if (o && !macro_is_equal(o->d, s->d))
1382 tcc_warning("%s redefined", get_tok_str(v, NULL));
1385 /* undefined a define symbol. Its name is just set to zero */
1386 ST_FUNC void define_undef(Sym *s)
1388 int v = s->v;
1389 if (v >= TOK_IDENT && v < tok_ident)
1390 table_ident[v - TOK_IDENT]->sym_define = NULL;
1393 ST_INLN Sym *define_find(int v)
1395 v -= TOK_IDENT;
1396 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1397 return NULL;
1398 return table_ident[v]->sym_define;
1401 /* free define stack until top reaches 'b' */
1402 ST_FUNC void free_defines(Sym *b)
1404 while (define_stack != b) {
1405 Sym *top = define_stack;
1406 define_stack = top->prev;
1407 tok_str_free_str(top->d);
1408 define_undef(top);
1409 sym_free(top);
1413 /* label lookup */
1414 ST_FUNC Sym *label_find(int v)
1416 v -= TOK_IDENT;
1417 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1418 return NULL;
1419 return table_ident[v]->sym_label;
1422 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1424 Sym *s, **ps;
1425 s = sym_push2(ptop, v, 0, 0);
1426 s->r = flags;
1427 ps = &table_ident[v - TOK_IDENT]->sym_label;
1428 if (ptop == &global_label_stack) {
1429 /* modify the top most local identifier, so that
1430 sym_identifier will point to 's' when popped */
1431 while (*ps != NULL)
1432 ps = &(*ps)->prev_tok;
1434 s->prev_tok = *ps;
1435 *ps = s;
1436 return s;
1439 /* pop labels until element last is reached. Look if any labels are
1440 undefined. Define symbols if '&&label' was used. */
1441 ST_FUNC void label_pop(Sym **ptop, Sym *slast, int keep)
1443 Sym *s, *s1;
1444 for(s = *ptop; s != slast; s = s1) {
1445 s1 = s->prev;
1446 if (s->r == LABEL_DECLARED) {
1447 tcc_warning_c(warn_all)("label '%s' declared but not used", get_tok_str(s->v, NULL));
1448 } else if (s->r == LABEL_FORWARD) {
1449 tcc_error("label '%s' used but not defined",
1450 get_tok_str(s->v, NULL));
1451 } else {
1452 if (s->c) {
1453 /* define corresponding symbol. A size of
1454 1 is put. */
1455 put_extern_sym(s, cur_text_section, s->jnext, 1);
1458 /* remove label */
1459 if (s->r != LABEL_GONE)
1460 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1461 if (!keep)
1462 sym_free(s);
1463 else
1464 s->r = LABEL_GONE;
1466 if (!keep)
1467 *ptop = slast;
1470 /* fake the nth "#if defined test_..." for tcc -dt -run */
1471 static void maybe_run_test(TCCState *s)
1473 const char *p;
1474 if (s->include_stack_ptr != s->include_stack)
1475 return;
1476 p = get_tok_str(tok, NULL);
1477 if (0 != memcmp(p, "test_", 5))
1478 return;
1479 if (0 != --s->run_test)
1480 return;
1481 fprintf(s->ppfp, &"\n[%s]\n"[!(s->dflag & 32)], p), fflush(s->ppfp);
1482 define_push(tok, MACRO_OBJ, NULL, NULL);
1485 /* eval an expression for #if/#elif */
1486 static int expr_preprocess(void)
1488 int c, t;
1489 TokenString *str;
1491 str = tok_str_alloc();
1492 pp_expr = 1;
1493 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1494 next(); /* do macro subst */
1495 redo:
1496 if (tok == TOK_DEFINED) {
1497 next_nomacro();
1498 t = tok;
1499 if (t == '(')
1500 next_nomacro();
1501 if (tok < TOK_IDENT)
1502 expect("identifier");
1503 if (tcc_state->run_test)
1504 maybe_run_test(tcc_state);
1505 c = define_find(tok) != 0;
1506 if (t == '(') {
1507 next_nomacro();
1508 if (tok != ')')
1509 expect("')'");
1511 tok = TOK_CINT;
1512 tokc.i = c;
1513 } else if (1 && tok == TOK___HAS_INCLUDE) {
1514 next(); /* XXX check if correct to use expansion */
1515 skip('(');
1516 while (tok != ')' && tok != TOK_EOF)
1517 next();
1518 if (tok != ')')
1519 expect("')'");
1520 tok = TOK_CINT;
1521 tokc.i = 0;
1522 } else if (tok >= TOK_IDENT) {
1523 /* if undefined macro, replace with zero, check for func-like */
1524 t = tok;
1525 tok = TOK_CINT;
1526 tokc.i = 0;
1527 tok_str_add_tok(str);
1528 next();
1529 if (tok == '(')
1530 tcc_error("function-like macro '%s' is not defined",
1531 get_tok_str(t, NULL));
1532 goto redo;
1534 tok_str_add_tok(str);
1536 pp_expr = 0;
1537 tok_str_add(str, -1); /* simulate end of file */
1538 tok_str_add(str, 0);
1539 /* now evaluate C constant expression */
1540 begin_macro(str, 1);
1541 next();
1542 c = expr_const();
1543 end_macro();
1544 return c != 0;
1548 /* parse after #define */
1549 ST_FUNC void parse_define(void)
1551 Sym *s, *first, **ps;
1552 int v, t, varg, is_vaargs, spc;
1553 int saved_parse_flags = parse_flags;
1555 v = tok;
1556 if (v < TOK_IDENT || v == TOK_DEFINED)
1557 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1558 /* XXX: should check if same macro (ANSI) */
1559 first = NULL;
1560 t = MACRO_OBJ;
1561 /* We have to parse the whole define as if not in asm mode, in particular
1562 no line comment with '#' must be ignored. Also for function
1563 macros the argument list must be parsed without '.' being an ID
1564 character. */
1565 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1566 /* '(' must be just after macro definition for MACRO_FUNC */
1567 next_nomacro();
1568 parse_flags &= ~PARSE_FLAG_SPACES;
1569 if (tok == '(') {
1570 int dotid = set_idnum('.', 0);
1571 next_nomacro();
1572 ps = &first;
1573 if (tok != ')') for (;;) {
1574 varg = tok;
1575 next_nomacro();
1576 is_vaargs = 0;
1577 if (varg == TOK_DOTS) {
1578 varg = TOK___VA_ARGS__;
1579 is_vaargs = 1;
1580 } else if (tok == TOK_DOTS && gnu_ext) {
1581 is_vaargs = 1;
1582 next_nomacro();
1584 if (varg < TOK_IDENT)
1585 bad_list:
1586 tcc_error("bad macro parameter list");
1587 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1588 *ps = s;
1589 ps = &s->next;
1590 if (tok == ')')
1591 break;
1592 if (tok != ',' || is_vaargs)
1593 goto bad_list;
1594 next_nomacro();
1596 parse_flags |= PARSE_FLAG_SPACES;
1597 next_nomacro();
1598 t = MACRO_FUNC;
1599 set_idnum('.', dotid);
1602 tokstr_buf.len = 0;
1603 spc = 2;
1604 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1605 /* The body of a macro definition should be parsed such that identifiers
1606 are parsed like the file mode determines (i.e. with '.' being an
1607 ID character in asm mode). But '#' should be retained instead of
1608 regarded as line comment leader, so still don't set ASM_FILE
1609 in parse_flags. */
1610 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1611 /* remove spaces around ## and after '#' */
1612 if (TOK_TWOSHARPS == tok) {
1613 if (2 == spc)
1614 goto bad_twosharp;
1615 if (1 == spc)
1616 --tokstr_buf.len;
1617 spc = 3;
1618 tok = TOK_PPJOIN;
1619 } else if ('#' == tok) {
1620 spc = 4;
1621 } else if (check_space(tok, &spc)) {
1622 goto skip;
1624 tok_str_add2(&tokstr_buf, tok, &tokc);
1625 skip:
1626 next_nomacro();
1629 parse_flags = saved_parse_flags;
1630 if (spc == 1)
1631 --tokstr_buf.len; /* remove trailing space */
1632 tok_str_add(&tokstr_buf, 0);
1633 if (3 == spc)
1634 bad_twosharp:
1635 tcc_error("'##' cannot appear at either end of macro");
1636 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1639 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1641 const unsigned char *s;
1642 unsigned int h;
1643 CachedInclude *e;
1644 int i;
1646 h = TOK_HASH_INIT;
1647 s = (unsigned char *) filename;
1648 while (*s) {
1649 #ifdef _WIN32
1650 h = TOK_HASH_FUNC(h, toup(*s));
1651 #else
1652 h = TOK_HASH_FUNC(h, *s);
1653 #endif
1654 s++;
1656 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1658 i = s1->cached_includes_hash[h];
1659 for(;;) {
1660 if (i == 0)
1661 break;
1662 e = s1->cached_includes[i - 1];
1663 if (0 == PATHCMP(e->filename, filename))
1664 return e;
1665 i = e->hash_next;
1667 if (!add)
1668 return NULL;
1670 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1671 strcpy(e->filename, filename);
1672 e->ifndef_macro = e->once = 0;
1673 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1674 /* add in hash table */
1675 e->hash_next = s1->cached_includes_hash[h];
1676 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1677 #ifdef INC_DEBUG
1678 printf("adding cached '%s'\n", filename);
1679 #endif
1680 return e;
1683 static void pragma_parse(TCCState *s1)
1685 next_nomacro();
1686 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1687 int t = tok, v;
1688 Sym *s;
1690 if (next(), tok != '(')
1691 goto pragma_err;
1692 if (next(), tok != TOK_STR)
1693 goto pragma_err;
1694 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1695 if (next(), tok != ')')
1696 goto pragma_err;
1697 if (t == TOK_push_macro) {
1698 while (NULL == (s = define_find(v)))
1699 define_push(v, 0, NULL, NULL);
1700 s->type.ref = s; /* set push boundary */
1701 } else {
1702 for (s = define_stack; s; s = s->prev)
1703 if (s->v == v && s->type.ref == s) {
1704 s->type.ref = NULL;
1705 break;
1708 if (s)
1709 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1710 else
1711 tcc_warning("unbalanced #pragma pop_macro");
1712 pp_debug_tok = t, pp_debug_symv = v;
1714 } else if (tok == TOK_once) {
1715 search_cached_include(s1, file->filename, 1)->once = pp_once;
1717 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1718 /* tcc -E: keep pragmas below unchanged */
1719 unget_tok(' ');
1720 unget_tok(TOK_PRAGMA);
1721 unget_tok('#');
1722 unget_tok(TOK_LINEFEED);
1724 } else if (tok == TOK_pack) {
1725 /* This may be:
1726 #pragma pack(1) // set
1727 #pragma pack() // reset to default
1728 #pragma pack(push,1) // push & set
1729 #pragma pack(pop) // restore previous */
1730 next();
1731 skip('(');
1732 if (tok == TOK_ASM_pop) {
1733 next();
1734 if (s1->pack_stack_ptr <= s1->pack_stack) {
1735 stk_error:
1736 tcc_error("out of pack stack");
1738 s1->pack_stack_ptr--;
1739 } else {
1740 int val = 0;
1741 if (tok != ')') {
1742 if (tok == TOK_ASM_push) {
1743 next();
1744 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1745 goto stk_error;
1746 s1->pack_stack_ptr++;
1747 skip(',');
1749 if (tok != TOK_CINT)
1750 goto pragma_err;
1751 val = tokc.i;
1752 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1753 goto pragma_err;
1754 next();
1756 *s1->pack_stack_ptr = val;
1758 if (tok != ')')
1759 goto pragma_err;
1761 } else if (tok == TOK_comment) {
1762 char *p; int t;
1763 next();
1764 skip('(');
1765 t = tok;
1766 next();
1767 skip(',');
1768 if (tok != TOK_STR)
1769 goto pragma_err;
1770 p = tcc_strdup((char *)tokc.str.data);
1771 next();
1772 if (tok != ')')
1773 goto pragma_err;
1774 if (t == TOK_lib) {
1775 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1776 } else {
1777 if (t == TOK_option)
1778 tcc_set_options(s1, p);
1779 tcc_free(p);
1782 } else
1783 tcc_warning_c(warn_unsupported)("#pragma %s ignored", get_tok_str(tok, &tokc));
1784 return;
1786 pragma_err:
1787 tcc_error("malformed #pragma directive");
1788 return;
1791 /* is_bof is true if first non space token at beginning of file */
1792 ST_FUNC void preprocess(int is_bof)
1794 TCCState *s1 = tcc_state;
1795 int i, c, n, saved_parse_flags;
1796 char buf[1024], *q;
1797 Sym *s;
1799 saved_parse_flags = parse_flags;
1800 parse_flags = PARSE_FLAG_PREPROCESS
1801 | PARSE_FLAG_TOK_NUM
1802 | PARSE_FLAG_TOK_STR
1803 | PARSE_FLAG_LINEFEED
1804 | (parse_flags & PARSE_FLAG_ASM_FILE)
1807 next_nomacro();
1808 redo:
1809 switch(tok) {
1810 case TOK_DEFINE:
1811 pp_debug_tok = tok;
1812 next_nomacro();
1813 pp_debug_symv = tok;
1814 parse_define();
1815 break;
1816 case TOK_UNDEF:
1817 pp_debug_tok = tok;
1818 next_nomacro();
1819 pp_debug_symv = tok;
1820 s = define_find(tok);
1821 /* undefine symbol by putting an invalid name */
1822 if (s)
1823 define_undef(s);
1824 break;
1825 case TOK_INCLUDE:
1826 case TOK_INCLUDE_NEXT:
1827 ch = file->buf_ptr[0];
1828 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1829 skip_spaces();
1830 if (ch == '<') {
1831 c = '>';
1832 goto read_name;
1833 } else if (ch == '\"') {
1834 c = ch;
1835 read_name:
1836 inp();
1837 q = buf;
1838 while (ch != c && ch != '\n' && ch != CH_EOF) {
1839 if ((q - buf) < sizeof(buf) - 1)
1840 *q++ = ch;
1841 if (ch == '\\') {
1842 if (handle_stray_noerror() == 0)
1843 --q;
1844 } else
1845 inp();
1847 *q = '\0';
1848 minp();
1849 #if 0
1850 /* eat all spaces and comments after include */
1851 /* XXX: slightly incorrect */
1852 while (ch1 != '\n' && ch1 != CH_EOF)
1853 inp();
1854 #endif
1855 } else {
1856 int len;
1857 /* computed #include : concatenate everything up to linefeed,
1858 the result must be one of the two accepted forms.
1859 Don't convert pp-tokens to tokens here. */
1860 parse_flags = (PARSE_FLAG_PREPROCESS
1861 | PARSE_FLAG_LINEFEED
1862 | (parse_flags & PARSE_FLAG_ASM_FILE));
1863 next();
1864 buf[0] = '\0';
1865 while (tok != TOK_LINEFEED) {
1866 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1867 next();
1869 len = strlen(buf);
1870 /* check syntax and remove '<>|""' */
1871 if ((len < 2 || ((buf[0] != '"' || buf[len-1] != '"') &&
1872 (buf[0] != '<' || buf[len-1] != '>'))))
1873 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1874 c = buf[len-1];
1875 memmove(buf, buf + 1, len - 2);
1876 buf[len - 2] = '\0';
1879 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1880 tcc_error("#include recursion too deep");
1881 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index + 1 : 0;
1882 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1883 for (; i < n; ++i) {
1884 char buf1[sizeof file->filename];
1885 CachedInclude *e;
1886 const char *path;
1888 if (i == 0) {
1889 /* check absolute include path */
1890 if (!IS_ABSPATH(buf))
1891 continue;
1892 buf1[0] = 0;
1894 } else if (i == 1) {
1895 /* search in file's dir if "header.h" */
1896 if (c != '\"')
1897 continue;
1898 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1899 path = file->true_filename;
1900 pstrncpy(buf1, path, tcc_basename(path) - path);
1902 } else {
1903 /* search in all the include paths */
1904 int j = i - 2, k = j - s1->nb_include_paths;
1905 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1906 pstrcpy(buf1, sizeof(buf1), path);
1907 pstrcat(buf1, sizeof(buf1), "/");
1910 pstrcat(buf1, sizeof(buf1), buf);
1911 e = search_cached_include(s1, buf1, 0);
1912 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1913 /* no need to parse the include because the 'ifndef macro'
1914 is defined (or had #pragma once) */
1915 #ifdef INC_DEBUG
1916 printf("%s: skipping cached %s\n", file->filename, buf1);
1917 #endif
1918 goto include_done;
1921 if (tcc_open(s1, buf1) < 0)
1922 continue;
1923 /* push previous file on stack */
1924 *s1->include_stack_ptr++ = file->prev;
1925 file->include_next_index = i;
1926 #ifdef INC_DEBUG
1927 printf("%s: including %s\n", file->prev->filename, file->filename);
1928 #endif
1929 /* update target deps */
1930 if (s1->gen_deps) {
1931 BufferedFile *bf = file;
1932 while (i == 1 && (bf = bf->prev))
1933 i = bf->include_next_index;
1934 /* skip system include files */
1935 if (s1->include_sys_deps || n - i > s1->nb_sysinclude_paths)
1936 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1937 tcc_strdup(buf1));
1939 /* add include file debug info */
1940 tcc_debug_bincl(tcc_state);
1941 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1942 ch = file->buf_ptr[0];
1943 goto the_end;
1945 tcc_error("include file '%s' not found", buf);
1946 include_done:
1947 break;
1948 case TOK_IFNDEF:
1949 c = 1;
1950 goto do_ifdef;
1951 case TOK_IF:
1952 c = expr_preprocess();
1953 goto do_if;
1954 case TOK_IFDEF:
1955 c = 0;
1956 do_ifdef:
1957 next_nomacro();
1958 if (tok < TOK_IDENT)
1959 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1960 if (is_bof) {
1961 if (c) {
1962 #ifdef INC_DEBUG
1963 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1964 #endif
1965 file->ifndef_macro = tok;
1968 c = (define_find(tok) != 0) ^ c;
1969 do_if:
1970 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1971 tcc_error("memory full (ifdef)");
1972 *s1->ifdef_stack_ptr++ = c;
1973 goto test_skip;
1974 case TOK_ELSE:
1975 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1976 tcc_error("#else without matching #if");
1977 if (s1->ifdef_stack_ptr[-1] & 2)
1978 tcc_error("#else after #else");
1979 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1980 goto test_else;
1981 case TOK_ELIF:
1982 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1983 tcc_error("#elif without matching #if");
1984 c = s1->ifdef_stack_ptr[-1];
1985 if (c > 1)
1986 tcc_error("#elif after #else");
1987 /* last #if/#elif expression was true: we skip */
1988 if (c == 1) {
1989 c = 0;
1990 } else {
1991 c = expr_preprocess();
1992 s1->ifdef_stack_ptr[-1] = c;
1994 test_else:
1995 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1996 file->ifndef_macro = 0;
1997 test_skip:
1998 if (!(c & 1)) {
1999 preprocess_skip();
2000 is_bof = 0;
2001 goto redo;
2003 break;
2004 case TOK_ENDIF:
2005 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
2006 tcc_error("#endif without matching #if");
2007 s1->ifdef_stack_ptr--;
2008 /* '#ifndef macro' was at the start of file. Now we check if
2009 an '#endif' is exactly at the end of file */
2010 if (file->ifndef_macro &&
2011 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
2012 file->ifndef_macro_saved = file->ifndef_macro;
2013 /* need to set to zero to avoid false matches if another
2014 #ifndef at middle of file */
2015 file->ifndef_macro = 0;
2016 while (tok != TOK_LINEFEED)
2017 next_nomacro();
2018 tok_flags |= TOK_FLAG_ENDIF;
2019 goto the_end;
2021 break;
2022 case TOK_PPNUM:
2023 n = strtoul((char*)tokc.str.data, &q, 10);
2024 goto _line_num;
2025 case TOK_LINE:
2026 next();
2027 if (tok != TOK_CINT)
2028 _line_err:
2029 tcc_error("wrong #line format");
2030 n = tokc.i;
2031 _line_num:
2032 next();
2033 if (tok != TOK_LINEFEED) {
2034 if (tok == TOK_STR) {
2035 if (file->true_filename == file->filename)
2036 file->true_filename = tcc_strdup(file->filename);
2037 /* prepend directory from real file */
2038 pstrcpy(buf, sizeof buf, file->true_filename);
2039 *tcc_basename(buf) = 0;
2040 pstrcat(buf, sizeof buf, (char *)tokc.str.data);
2041 tcc_debug_putfile(s1, buf);
2042 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
2043 break;
2044 else
2045 goto _line_err;
2046 --n;
2048 if (file->fd > 0)
2049 total_lines += file->line_num - n;
2050 file->line_num = n;
2051 break;
2052 case TOK_ERROR:
2053 case TOK_WARNING:
2054 c = tok;
2055 ch = file->buf_ptr[0];
2056 skip_spaces();
2057 q = buf;
2058 while (ch != '\n' && ch != CH_EOF) {
2059 if ((q - buf) < sizeof(buf) - 1)
2060 *q++ = ch;
2061 if (ch == '\\') {
2062 if (handle_stray_noerror() == 0)
2063 --q;
2064 } else
2065 inp();
2067 *q = '\0';
2068 if (c == TOK_ERROR)
2069 tcc_error("#error %s", buf);
2070 else
2071 tcc_warning("#warning %s", buf);
2072 break;
2073 case TOK_PRAGMA:
2074 pragma_parse(s1);
2075 break;
2076 case TOK_LINEFEED:
2077 goto the_end;
2078 default:
2079 /* ignore gas line comment in an 'S' file. */
2080 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
2081 goto ignore;
2082 if (tok == '!' && is_bof)
2083 /* '!' is ignored at beginning to allow C scripts. */
2084 goto ignore;
2085 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
2086 ignore:
2087 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
2088 goto the_end;
2090 /* ignore other preprocess commands or #! for C scripts */
2091 while (tok != TOK_LINEFEED)
2092 next_nomacro();
2093 the_end:
2094 parse_flags = saved_parse_flags;
2097 /* evaluate escape codes in a string. */
2098 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
2100 int c, n, i;
2101 const uint8_t *p;
2103 p = buf;
2104 for(;;) {
2105 c = *p;
2106 if (c == '\0')
2107 break;
2108 if (c == '\\') {
2109 p++;
2110 /* escape */
2111 c = *p;
2112 switch(c) {
2113 case '0': case '1': case '2': case '3':
2114 case '4': case '5': case '6': case '7':
2115 /* at most three octal digits */
2116 n = c - '0';
2117 p++;
2118 c = *p;
2119 if (isoct(c)) {
2120 n = n * 8 + c - '0';
2121 p++;
2122 c = *p;
2123 if (isoct(c)) {
2124 n = n * 8 + c - '0';
2125 p++;
2128 c = n;
2129 goto add_char_nonext;
2130 case 'x': i = 0; goto parse_hex_or_ucn;
2131 case 'u': i = 4; goto parse_hex_or_ucn;
2132 case 'U': i = 8; goto parse_hex_or_ucn;
2133 parse_hex_or_ucn:
2134 p++;
2135 n = 0;
2136 do {
2137 c = *p;
2138 if (c >= 'a' && c <= 'f')
2139 c = c - 'a' + 10;
2140 else if (c >= 'A' && c <= 'F')
2141 c = c - 'A' + 10;
2142 else if (isnum(c))
2143 c = c - '0';
2144 else if (i > 0)
2145 expect("more hex digits in universal-character-name");
2146 else {
2147 c = n;
2148 goto add_char_nonext;
2150 n = n * 16 + c;
2151 p++;
2152 } while (--i);
2153 cstr_u8cat(outstr, n);
2154 continue;
2155 case 'a':
2156 c = '\a';
2157 break;
2158 case 'b':
2159 c = '\b';
2160 break;
2161 case 'f':
2162 c = '\f';
2163 break;
2164 case 'n':
2165 c = '\n';
2166 break;
2167 case 'r':
2168 c = '\r';
2169 break;
2170 case 't':
2171 c = '\t';
2172 break;
2173 case 'v':
2174 c = '\v';
2175 break;
2176 case 'e':
2177 if (!gnu_ext)
2178 goto invalid_escape;
2179 c = 27;
2180 break;
2181 case '\'':
2182 case '\"':
2183 case '\\':
2184 case '?':
2185 break;
2186 default:
2187 invalid_escape:
2188 if (c >= '!' && c <= '~')
2189 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2190 else
2191 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2192 break;
2194 } else if (is_long && c >= 0x80) {
2195 /* assume we are processing UTF-8 sequence */
2196 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2198 int cont; /* count of continuation bytes */
2199 int skip; /* how many bytes should skip when error occurred */
2200 int i;
2202 /* decode leading byte */
2203 if (c < 0xC2) {
2204 skip = 1; goto invalid_utf8_sequence;
2205 } else if (c <= 0xDF) {
2206 cont = 1; n = c & 0x1f;
2207 } else if (c <= 0xEF) {
2208 cont = 2; n = c & 0xf;
2209 } else if (c <= 0xF4) {
2210 cont = 3; n = c & 0x7;
2211 } else {
2212 skip = 1; goto invalid_utf8_sequence;
2215 /* decode continuation bytes */
2216 for (i = 1; i <= cont; i++) {
2217 int l = 0x80, h = 0xBF;
2219 /* adjust limit for second byte */
2220 if (i == 1) {
2221 switch (c) {
2222 case 0xE0: l = 0xA0; break;
2223 case 0xED: h = 0x9F; break;
2224 case 0xF0: l = 0x90; break;
2225 case 0xF4: h = 0x8F; break;
2229 if (p[i] < l || p[i] > h) {
2230 skip = i; goto invalid_utf8_sequence;
2233 n = (n << 6) | (p[i] & 0x3f);
2236 /* advance pointer */
2237 p += 1 + cont;
2238 c = n;
2239 goto add_char_nonext;
2241 /* error handling */
2242 invalid_utf8_sequence:
2243 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2244 c = 0xFFFD;
2245 p += skip;
2246 goto add_char_nonext;
2249 p++;
2250 add_char_nonext:
2251 if (!is_long)
2252 cstr_ccat(outstr, c);
2253 else {
2254 #ifdef TCC_TARGET_PE
2255 /* store as UTF-16 */
2256 if (c < 0x10000) {
2257 cstr_wccat(outstr, c);
2258 } else {
2259 c -= 0x10000;
2260 cstr_wccat(outstr, (c >> 10) + 0xD800);
2261 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2263 #else
2264 cstr_wccat(outstr, c);
2265 #endif
2268 /* add a trailing '\0' */
2269 if (!is_long)
2270 cstr_ccat(outstr, '\0');
2271 else
2272 cstr_wccat(outstr, '\0');
2275 static void parse_string(const char *s, int len)
2277 uint8_t buf[1000], *p = buf;
2278 int is_long, sep;
2280 if ((is_long = *s == 'L'))
2281 ++s, --len;
2282 sep = *s++;
2283 len -= 2;
2284 if (len >= sizeof buf)
2285 p = tcc_malloc(len + 1);
2286 memcpy(p, s, len);
2287 p[len] = 0;
2289 cstr_reset(&tokcstr);
2290 parse_escape_string(&tokcstr, p, is_long);
2291 if (p != buf)
2292 tcc_free(p);
2294 if (sep == '\'') {
2295 int char_size, i, n, c;
2296 /* XXX: make it portable */
2297 if (!is_long)
2298 tok = TOK_CCHAR, char_size = 1;
2299 else
2300 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2301 n = tokcstr.size / char_size - 1;
2302 if (n < 1)
2303 tcc_error("empty character constant");
2304 if (n > 1)
2305 tcc_warning_c(warn_all)("multi-character character constant");
2306 for (c = i = 0; i < n; ++i) {
2307 if (is_long)
2308 c = ((nwchar_t *)tokcstr.data)[i];
2309 else
2310 c = (c << 8) | ((char *)tokcstr.data)[i];
2312 tokc.i = c;
2313 } else {
2314 tokc.str.size = tokcstr.size;
2315 tokc.str.data = tokcstr.data;
2316 if (!is_long)
2317 tok = TOK_STR;
2318 else
2319 tok = TOK_LSTR;
2323 /* we use 64 bit numbers */
2324 #define BN_SIZE 2
2326 /* bn = (bn << shift) | or_val */
2327 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2329 int i;
2330 unsigned int v;
2331 for(i=0;i<BN_SIZE;i++) {
2332 v = bn[i];
2333 bn[i] = (v << shift) | or_val;
2334 or_val = v >> (32 - shift);
2338 static void bn_zero(unsigned int *bn)
2340 int i;
2341 for(i=0;i<BN_SIZE;i++) {
2342 bn[i] = 0;
2346 /* parse number in null terminated string 'p' and return it in the
2347 current token */
2348 static void parse_number(const char *p)
2350 int b, t, shift, frac_bits, s, exp_val, ch;
2351 char *q;
2352 unsigned int bn[BN_SIZE];
2353 double d;
2355 /* number */
2356 q = token_buf;
2357 ch = *p++;
2358 t = ch;
2359 ch = *p++;
2360 *q++ = t;
2361 b = 10;
2362 if (t == '.') {
2363 goto float_frac_parse;
2364 } else if (t == '0') {
2365 if (ch == 'x' || ch == 'X') {
2366 q--;
2367 ch = *p++;
2368 b = 16;
2369 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2370 q--;
2371 ch = *p++;
2372 b = 2;
2375 /* parse all digits. cannot check octal numbers at this stage
2376 because of floating point constants */
2377 while (1) {
2378 if (ch >= 'a' && ch <= 'f')
2379 t = ch - 'a' + 10;
2380 else if (ch >= 'A' && ch <= 'F')
2381 t = ch - 'A' + 10;
2382 else if (isnum(ch))
2383 t = ch - '0';
2384 else
2385 break;
2386 if (t >= b)
2387 break;
2388 if (q >= token_buf + STRING_MAX_SIZE) {
2389 num_too_long:
2390 tcc_error("number too long");
2392 *q++ = ch;
2393 ch = *p++;
2395 if (ch == '.' ||
2396 ((ch == 'e' || ch == 'E') && b == 10) ||
2397 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2398 if (b != 10) {
2399 /* NOTE: strtox should support that for hexa numbers, but
2400 non ISOC99 libcs do not support it, so we prefer to do
2401 it by hand */
2402 /* hexadecimal or binary floats */
2403 /* XXX: handle overflows */
2404 *q = '\0';
2405 if (b == 16)
2406 shift = 4;
2407 else
2408 shift = 1;
2409 bn_zero(bn);
2410 q = token_buf;
2411 while (1) {
2412 t = *q++;
2413 if (t == '\0') {
2414 break;
2415 } else if (t >= 'a') {
2416 t = t - 'a' + 10;
2417 } else if (t >= 'A') {
2418 t = t - 'A' + 10;
2419 } else {
2420 t = t - '0';
2422 bn_lshift(bn, shift, t);
2424 frac_bits = 0;
2425 if (ch == '.') {
2426 ch = *p++;
2427 while (1) {
2428 t = ch;
2429 if (t >= 'a' && t <= 'f') {
2430 t = t - 'a' + 10;
2431 } else if (t >= 'A' && t <= 'F') {
2432 t = t - 'A' + 10;
2433 } else if (t >= '0' && t <= '9') {
2434 t = t - '0';
2435 } else {
2436 break;
2438 if (t >= b)
2439 tcc_error("invalid digit");
2440 bn_lshift(bn, shift, t);
2441 frac_bits += shift;
2442 ch = *p++;
2445 if (ch != 'p' && ch != 'P')
2446 expect("exponent");
2447 ch = *p++;
2448 s = 1;
2449 exp_val = 0;
2450 if (ch == '+') {
2451 ch = *p++;
2452 } else if (ch == '-') {
2453 s = -1;
2454 ch = *p++;
2456 if (ch < '0' || ch > '9')
2457 expect("exponent digits");
2458 while (ch >= '0' && ch <= '9') {
2459 exp_val = exp_val * 10 + ch - '0';
2460 ch = *p++;
2462 exp_val = exp_val * s;
2464 /* now we can generate the number */
2465 /* XXX: should patch directly float number */
2466 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2467 d = ldexp(d, exp_val - frac_bits);
2468 t = toup(ch);
2469 if (t == 'F') {
2470 ch = *p++;
2471 tok = TOK_CFLOAT;
2472 /* float : should handle overflow */
2473 tokc.f = (float)d;
2474 } else if (t == 'L') {
2475 ch = *p++;
2476 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2477 tok = TOK_CDOUBLE;
2478 tokc.d = d;
2479 #else
2480 tok = TOK_CLDOUBLE;
2481 /* XXX: not large enough */
2482 tokc.ld = (long double)d;
2483 #endif
2484 } else {
2485 tok = TOK_CDOUBLE;
2486 tokc.d = d;
2488 } else {
2489 /* decimal floats */
2490 if (ch == '.') {
2491 if (q >= token_buf + STRING_MAX_SIZE)
2492 goto num_too_long;
2493 *q++ = ch;
2494 ch = *p++;
2495 float_frac_parse:
2496 while (ch >= '0' && ch <= '9') {
2497 if (q >= token_buf + STRING_MAX_SIZE)
2498 goto num_too_long;
2499 *q++ = ch;
2500 ch = *p++;
2503 if (ch == 'e' || ch == 'E') {
2504 if (q >= token_buf + STRING_MAX_SIZE)
2505 goto num_too_long;
2506 *q++ = ch;
2507 ch = *p++;
2508 if (ch == '-' || ch == '+') {
2509 if (q >= token_buf + STRING_MAX_SIZE)
2510 goto num_too_long;
2511 *q++ = ch;
2512 ch = *p++;
2514 if (ch < '0' || ch > '9')
2515 expect("exponent digits");
2516 while (ch >= '0' && ch <= '9') {
2517 if (q >= token_buf + STRING_MAX_SIZE)
2518 goto num_too_long;
2519 *q++ = ch;
2520 ch = *p++;
2523 *q = '\0';
2524 t = toup(ch);
2525 errno = 0;
2526 if (t == 'F') {
2527 ch = *p++;
2528 tok = TOK_CFLOAT;
2529 tokc.f = strtof(token_buf, NULL);
2530 } else if (t == 'L') {
2531 ch = *p++;
2532 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2533 tok = TOK_CDOUBLE;
2534 tokc.d = strtod(token_buf, NULL);
2535 #else
2536 tok = TOK_CLDOUBLE;
2537 tokc.ld = strtold(token_buf, NULL);
2538 #endif
2539 } else {
2540 tok = TOK_CDOUBLE;
2541 tokc.d = strtod(token_buf, NULL);
2544 } else {
2545 unsigned long long n, n1;
2546 int lcount, ucount, ov = 0;
2547 const char *p1;
2549 /* integer number */
2550 *q = '\0';
2551 q = token_buf;
2552 if (b == 10 && *q == '0') {
2553 b = 8;
2554 q++;
2556 n = 0;
2557 while(1) {
2558 t = *q++;
2559 /* no need for checks except for base 10 / 8 errors */
2560 if (t == '\0')
2561 break;
2562 else if (t >= 'a')
2563 t = t - 'a' + 10;
2564 else if (t >= 'A')
2565 t = t - 'A' + 10;
2566 else
2567 t = t - '0';
2568 if (t >= b)
2569 tcc_error("invalid digit");
2570 n1 = n;
2571 n = n * b + t;
2572 /* detect overflow */
2573 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2574 ov = 1;
2577 /* Determine the characteristics (unsigned and/or 64bit) the type of
2578 the constant must have according to the constant suffix(es) */
2579 lcount = ucount = 0;
2580 p1 = p;
2581 for(;;) {
2582 t = toup(ch);
2583 if (t == 'L') {
2584 if (lcount >= 2)
2585 tcc_error("three 'l's in integer constant");
2586 if (lcount && *(p - 1) != ch)
2587 tcc_error("incorrect integer suffix: %s", p1);
2588 lcount++;
2589 ch = *p++;
2590 } else if (t == 'U') {
2591 if (ucount >= 1)
2592 tcc_error("two 'u's in integer constant");
2593 ucount++;
2594 ch = *p++;
2595 } else {
2596 break;
2600 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2601 if (ucount == 0 && b == 10) {
2602 if (lcount <= (LONG_SIZE == 4)) {
2603 if (n >= 0x80000000U)
2604 lcount = (LONG_SIZE == 4) + 1;
2606 if (n >= 0x8000000000000000ULL)
2607 ov = 1, ucount = 1;
2608 } else {
2609 if (lcount <= (LONG_SIZE == 4)) {
2610 if (n >= 0x100000000ULL)
2611 lcount = (LONG_SIZE == 4) + 1;
2612 else if (n >= 0x80000000U)
2613 ucount = 1;
2615 if (n >= 0x8000000000000000ULL)
2616 ucount = 1;
2619 if (ov)
2620 tcc_warning("integer constant overflow");
2622 tok = TOK_CINT;
2623 if (lcount) {
2624 tok = TOK_CLONG;
2625 if (lcount == 2)
2626 tok = TOK_CLLONG;
2628 if (ucount)
2629 ++tok; /* TOK_CU... */
2630 tokc.i = n;
2632 if (ch)
2633 tcc_error("invalid number");
2637 #define PARSE2(c1, tok1, c2, tok2) \
2638 case c1: \
2639 PEEKC(c, p); \
2640 if (c == c2) { \
2641 p++; \
2642 tok = tok2; \
2643 } else { \
2644 tok = tok1; \
2646 break;
2648 /* return next token without macro substitution */
2649 static inline void next_nomacro1(void)
2651 int t, c, is_long, len;
2652 TokenSym *ts;
2653 uint8_t *p, *p1;
2654 unsigned int h;
2656 p = file->buf_ptr;
2657 redo_no_start:
2658 c = *p;
2659 switch(c) {
2660 case ' ':
2661 case '\t':
2662 tok = c;
2663 p++;
2664 maybe_space:
2665 if (parse_flags & PARSE_FLAG_SPACES)
2666 goto keep_tok_flags;
2667 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2668 ++p;
2669 goto redo_no_start;
2670 case '\f':
2671 case '\v':
2672 case '\r':
2673 p++;
2674 goto redo_no_start;
2675 case '\\':
2676 /* first look if it is in fact an end of buffer */
2677 c = handle_stray1(p);
2678 p = file->buf_ptr;
2679 if (c == '\\')
2680 goto parse_simple;
2681 if (c != CH_EOF)
2682 goto redo_no_start;
2684 TCCState *s1 = tcc_state;
2685 if ((parse_flags & PARSE_FLAG_LINEFEED)
2686 && !(tok_flags & TOK_FLAG_EOF)) {
2687 tok_flags |= TOK_FLAG_EOF;
2688 tok = TOK_LINEFEED;
2689 goto keep_tok_flags;
2690 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2691 tok = TOK_EOF;
2692 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2693 tcc_error("missing #endif");
2694 } else if (s1->include_stack_ptr == s1->include_stack) {
2695 /* no include left : end of file. */
2696 tok = TOK_EOF;
2697 } else {
2698 tok_flags &= ~TOK_FLAG_EOF;
2699 /* pop include file */
2701 /* test if previous '#endif' was after a #ifdef at
2702 start of file */
2703 if (tok_flags & TOK_FLAG_ENDIF) {
2704 #ifdef INC_DEBUG
2705 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2706 #endif
2707 search_cached_include(s1, file->filename, 1)
2708 ->ifndef_macro = file->ifndef_macro_saved;
2709 tok_flags &= ~TOK_FLAG_ENDIF;
2712 /* add end of include file debug info */
2713 tcc_debug_eincl(tcc_state);
2714 /* pop include stack */
2715 tcc_close();
2716 s1->include_stack_ptr--;
2717 p = file->buf_ptr;
2718 if (p == file->buffer)
2719 tok_flags = TOK_FLAG_BOF|TOK_FLAG_BOL;
2720 goto redo_no_start;
2723 break;
2725 case '\n':
2726 file->line_num++;
2727 tok_flags |= TOK_FLAG_BOL;
2728 p++;
2729 maybe_newline:
2730 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2731 goto redo_no_start;
2732 tok = TOK_LINEFEED;
2733 goto keep_tok_flags;
2735 case '#':
2736 /* XXX: simplify */
2737 PEEKC(c, p);
2738 if ((tok_flags & TOK_FLAG_BOL) &&
2739 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2740 file->buf_ptr = p;
2741 preprocess(tok_flags & TOK_FLAG_BOF);
2742 p = file->buf_ptr;
2743 goto maybe_newline;
2744 } else {
2745 if (c == '#') {
2746 p++;
2747 tok = TOK_TWOSHARPS;
2748 } else {
2749 #if !defined(TCC_TARGET_ARM)
2750 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2751 p = parse_line_comment(p - 1);
2752 goto redo_no_start;
2753 } else
2754 #endif
2756 tok = '#';
2760 break;
2762 /* dollar is allowed to start identifiers when not parsing asm */
2763 case '$':
2764 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2765 || (parse_flags & PARSE_FLAG_ASM_FILE))
2766 goto parse_simple;
2768 case 'a': case 'b': case 'c': case 'd':
2769 case 'e': case 'f': case 'g': case 'h':
2770 case 'i': case 'j': case 'k': case 'l':
2771 case 'm': case 'n': case 'o': case 'p':
2772 case 'q': case 'r': case 's': case 't':
2773 case 'u': case 'v': case 'w': case 'x':
2774 case 'y': case 'z':
2775 case 'A': case 'B': case 'C': case 'D':
2776 case 'E': case 'F': case 'G': case 'H':
2777 case 'I': case 'J': case 'K':
2778 case 'M': case 'N': case 'O': case 'P':
2779 case 'Q': case 'R': case 'S': case 'T':
2780 case 'U': case 'V': case 'W': case 'X':
2781 case 'Y': case 'Z':
2782 case '_':
2783 parse_ident_fast:
2784 p1 = p;
2785 h = TOK_HASH_INIT;
2786 h = TOK_HASH_FUNC(h, c);
2787 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2788 h = TOK_HASH_FUNC(h, c);
2789 len = p - p1;
2790 if (c != '\\') {
2791 TokenSym **pts;
2793 /* fast case : no stray found, so we have the full token
2794 and we have already hashed it */
2795 h &= (TOK_HASH_SIZE - 1);
2796 pts = &hash_ident[h];
2797 for(;;) {
2798 ts = *pts;
2799 if (!ts)
2800 break;
2801 if (ts->len == len && !memcmp(ts->str, p1, len))
2802 goto token_found;
2803 pts = &(ts->hash_next);
2805 ts = tok_alloc_new(pts, (char *) p1, len);
2806 token_found: ;
2807 } else {
2808 /* slower case */
2809 cstr_reset(&tokcstr);
2810 cstr_cat(&tokcstr, (char *) p1, len);
2811 p--;
2812 PEEKC(c, p);
2813 parse_ident_slow:
2814 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2816 cstr_ccat(&tokcstr, c);
2817 PEEKC(c, p);
2819 ts = tok_alloc(tokcstr.data, tokcstr.size);
2821 tok = ts->tok;
2822 break;
2823 case 'L':
2824 t = p[1];
2825 if (t != '\\' && t != '\'' && t != '\"') {
2826 /* fast case */
2827 goto parse_ident_fast;
2828 } else {
2829 PEEKC(c, p);
2830 if (c == '\'' || c == '\"') {
2831 is_long = 1;
2832 goto str_const;
2833 } else {
2834 cstr_reset(&tokcstr);
2835 cstr_ccat(&tokcstr, 'L');
2836 goto parse_ident_slow;
2839 break;
2841 case '0': case '1': case '2': case '3':
2842 case '4': case '5': case '6': case '7':
2843 case '8': case '9':
2844 t = c;
2845 PEEKC(c, p);
2846 /* after the first digit, accept digits, alpha, '.' or sign if
2847 prefixed by 'eEpP' */
2848 parse_num:
2849 cstr_reset(&tokcstr);
2850 for(;;) {
2851 cstr_ccat(&tokcstr, t);
2852 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2853 || c == '.'
2854 || ((c == '+' || c == '-')
2855 && (((t == 'e' || t == 'E')
2856 && !(parse_flags & PARSE_FLAG_ASM_FILE
2857 /* 0xe+1 is 3 tokens in asm */
2858 && ((char*)tokcstr.data)[0] == '0'
2859 && toup(((char*)tokcstr.data)[1]) == 'X'))
2860 || t == 'p' || t == 'P'))))
2861 break;
2862 t = c;
2863 PEEKC(c, p);
2865 /* We add a trailing '\0' to ease parsing */
2866 cstr_ccat(&tokcstr, '\0');
2867 tokc.str.size = tokcstr.size;
2868 tokc.str.data = tokcstr.data;
2869 tok = TOK_PPNUM;
2870 break;
2872 case '.':
2873 /* special dot handling because it can also start a number */
2874 PEEKC(c, p);
2875 if (isnum(c)) {
2876 t = '.';
2877 goto parse_num;
2878 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2879 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2880 *--p = c = '.';
2881 goto parse_ident_fast;
2882 } else if (c == '.') {
2883 PEEKC(c, p);
2884 if (c == '.') {
2885 p++;
2886 tok = TOK_DOTS;
2887 } else {
2888 *--p = '.'; /* may underflow into file->unget[] */
2889 tok = '.';
2891 } else {
2892 tok = '.';
2894 break;
2895 case '\'':
2896 case '\"':
2897 is_long = 0;
2898 str_const:
2899 cstr_reset(&tokcstr);
2900 if (is_long)
2901 cstr_ccat(&tokcstr, 'L');
2902 cstr_ccat(&tokcstr, c);
2903 p = parse_pp_string(p, c, &tokcstr);
2904 cstr_ccat(&tokcstr, c);
2905 cstr_ccat(&tokcstr, '\0');
2906 tokc.str.size = tokcstr.size;
2907 tokc.str.data = tokcstr.data;
2908 tok = TOK_PPSTR;
2909 break;
2911 case '<':
2912 PEEKC(c, p);
2913 if (c == '=') {
2914 p++;
2915 tok = TOK_LE;
2916 } else if (c == '<') {
2917 PEEKC(c, p);
2918 if (c == '=') {
2919 p++;
2920 tok = TOK_A_SHL;
2921 } else {
2922 tok = TOK_SHL;
2924 } else {
2925 tok = TOK_LT;
2927 break;
2928 case '>':
2929 PEEKC(c, p);
2930 if (c == '=') {
2931 p++;
2932 tok = TOK_GE;
2933 } else if (c == '>') {
2934 PEEKC(c, p);
2935 if (c == '=') {
2936 p++;
2937 tok = TOK_A_SAR;
2938 } else {
2939 tok = TOK_SAR;
2941 } else {
2942 tok = TOK_GT;
2944 break;
2946 case '&':
2947 PEEKC(c, p);
2948 if (c == '&') {
2949 p++;
2950 tok = TOK_LAND;
2951 } else if (c == '=') {
2952 p++;
2953 tok = TOK_A_AND;
2954 } else {
2955 tok = '&';
2957 break;
2959 case '|':
2960 PEEKC(c, p);
2961 if (c == '|') {
2962 p++;
2963 tok = TOK_LOR;
2964 } else if (c == '=') {
2965 p++;
2966 tok = TOK_A_OR;
2967 } else {
2968 tok = '|';
2970 break;
2972 case '+':
2973 PEEKC(c, p);
2974 if (c == '+') {
2975 p++;
2976 tok = TOK_INC;
2977 } else if (c == '=') {
2978 p++;
2979 tok = TOK_A_ADD;
2980 } else {
2981 tok = '+';
2983 break;
2985 case '-':
2986 PEEKC(c, p);
2987 if (c == '-') {
2988 p++;
2989 tok = TOK_DEC;
2990 } else if (c == '=') {
2991 p++;
2992 tok = TOK_A_SUB;
2993 } else if (c == '>') {
2994 p++;
2995 tok = TOK_ARROW;
2996 } else {
2997 tok = '-';
2999 break;
3001 PARSE2('!', '!', '=', TOK_NE)
3002 PARSE2('=', '=', '=', TOK_EQ)
3003 PARSE2('*', '*', '=', TOK_A_MUL)
3004 PARSE2('%', '%', '=', TOK_A_MOD)
3005 PARSE2('^', '^', '=', TOK_A_XOR)
3007 /* comments or operator */
3008 case '/':
3009 PEEKC(c, p);
3010 if (c == '*') {
3011 p = parse_comment(p);
3012 /* comments replaced by a blank */
3013 tok = ' ';
3014 goto maybe_space;
3015 } else if (c == '/') {
3016 p = parse_line_comment(p);
3017 tok = ' ';
3018 goto maybe_space;
3019 } else if (c == '=') {
3020 p++;
3021 tok = TOK_A_DIV;
3022 } else {
3023 tok = '/';
3025 break;
3027 /* simple tokens */
3028 case '(':
3029 case ')':
3030 case '[':
3031 case ']':
3032 case '{':
3033 case '}':
3034 case ',':
3035 case ';':
3036 case ':':
3037 case '?':
3038 case '~':
3039 case '@': /* only used in assembler */
3040 parse_simple:
3041 tok = c;
3042 p++;
3043 break;
3044 default:
3045 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
3046 goto parse_ident_fast;
3047 if (parse_flags & PARSE_FLAG_ASM_FILE)
3048 goto parse_simple;
3049 tcc_error("unrecognized character \\x%02x", c);
3050 break;
3052 tok_flags = 0;
3053 keep_tok_flags:
3054 file->buf_ptr = p;
3055 #if defined(PARSE_DEBUG)
3056 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
3057 #endif
3060 static void macro_subst(
3061 TokenString *tok_str,
3062 Sym **nested_list,
3063 const int *macro_str
3066 /* substitute arguments in replacement lists in macro_str by the values in
3067 args (field d) and return allocated string */
3068 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
3070 int t, t0, t1, spc;
3071 const int *st;
3072 Sym *s;
3073 CValue cval;
3074 TokenString str;
3075 CString cstr;
3077 tok_str_new(&str);
3078 t0 = t1 = 0;
3079 while(1) {
3080 TOK_GET(&t, &macro_str, &cval);
3081 if (!t)
3082 break;
3083 if (t == '#') {
3084 /* stringize */
3085 TOK_GET(&t, &macro_str, &cval);
3086 if (!t)
3087 goto bad_stringy;
3088 s = sym_find2(args, t);
3089 if (s) {
3090 cstr_new(&cstr);
3091 cstr_ccat(&cstr, '\"');
3092 st = s->d;
3093 spc = 0;
3094 while (*st >= 0) {
3095 TOK_GET(&t, &st, &cval);
3096 if (t != TOK_PLCHLDR
3097 && t != TOK_NOSUBST
3098 && 0 == check_space(t, &spc)) {
3099 const char *s = get_tok_str(t, &cval);
3100 while (*s) {
3101 if (t == TOK_PPSTR && *s != '\'')
3102 add_char(&cstr, *s);
3103 else
3104 cstr_ccat(&cstr, *s);
3105 ++s;
3109 cstr.size -= spc;
3110 cstr_ccat(&cstr, '\"');
3111 cstr_ccat(&cstr, '\0');
3112 #ifdef PP_DEBUG
3113 printf("\nstringize: <%s>\n", (char *)cstr.data);
3114 #endif
3115 /* add string */
3116 cval.str.size = cstr.size;
3117 cval.str.data = cstr.data;
3118 tok_str_add2(&str, TOK_PPSTR, &cval);
3119 cstr_free(&cstr);
3120 } else {
3121 bad_stringy:
3122 expect("macro parameter after '#'");
3124 } else if (t >= TOK_IDENT) {
3125 s = sym_find2(args, t);
3126 if (s) {
3127 int l0 = str.len;
3128 st = s->d;
3129 /* if '##' is present before or after, no arg substitution */
3130 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
3131 /* special case for var arg macros : ## eats the ','
3132 if empty VA_ARGS variable. */
3133 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
3134 if (*st <= 0) {
3135 /* suppress ',' '##' */
3136 str.len -= 2;
3137 } else {
3138 /* suppress '##' and add variable */
3139 str.len--;
3140 goto add_var;
3143 } else {
3144 add_var:
3145 if (!s->next) {
3146 /* Expand arguments tokens and store them. In most
3147 cases we could also re-expand each argument if
3148 used multiple times, but not if the argument
3149 contains the __COUNTER__ macro. */
3150 TokenString str2;
3151 sym_push2(&s->next, s->v, s->type.t, 0);
3152 tok_str_new(&str2);
3153 macro_subst(&str2, nested_list, st);
3154 tok_str_add(&str2, 0);
3155 s->next->d = str2.str;
3157 st = s->next->d;
3159 for(;;) {
3160 int t2;
3161 TOK_GET(&t2, &st, &cval);
3162 if (t2 <= 0)
3163 break;
3164 tok_str_add2(&str, t2, &cval);
3166 if (str.len == l0) /* expanded to empty string */
3167 tok_str_add(&str, TOK_PLCHLDR);
3168 } else {
3169 tok_str_add(&str, t);
3171 } else {
3172 tok_str_add2(&str, t, &cval);
3174 t0 = t1, t1 = t;
3176 tok_str_add(&str, 0);
3177 return str.str;
3180 static char const ab_month_name[12][4] =
3182 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3183 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3186 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3188 CString cstr;
3189 int n, ret = 1;
3191 cstr_new(&cstr);
3192 if (t1 != TOK_PLCHLDR)
3193 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3194 n = cstr.size;
3195 if (t2 != TOK_PLCHLDR)
3196 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3197 cstr_ccat(&cstr, '\0');
3199 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3200 memcpy(file->buffer, cstr.data, cstr.size);
3201 tok_flags = 0;
3202 for (;;) {
3203 next_nomacro1();
3204 if (0 == *file->buf_ptr)
3205 break;
3206 if (is_space(tok))
3207 continue;
3208 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3209 " preprocessing token", n, (char *)cstr.data, (char*)cstr.data + n);
3210 ret = 0;
3211 break;
3213 tcc_close();
3214 //printf("paste <%s>\n", (char*)cstr.data);
3215 cstr_free(&cstr);
3216 return ret;
3219 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3220 return the resulting string (which must be freed). */
3221 static inline int *macro_twosharps(const int *ptr0)
3223 int t;
3224 CValue cval;
3225 TokenString macro_str1;
3226 int start_of_nosubsts = -1;
3227 const int *ptr;
3229 /* we search the first '##' */
3230 for (ptr = ptr0;;) {
3231 TOK_GET(&t, &ptr, &cval);
3232 if (t == TOK_PPJOIN)
3233 break;
3234 if (t == 0)
3235 return NULL;
3238 tok_str_new(&macro_str1);
3240 //tok_print(" $$$", ptr0);
3241 for (ptr = ptr0;;) {
3242 TOK_GET(&t, &ptr, &cval);
3243 if (t == 0)
3244 break;
3245 if (t == TOK_PPJOIN)
3246 continue;
3247 while (*ptr == TOK_PPJOIN) {
3248 int t1; CValue cv1;
3249 /* given 'a##b', remove nosubsts preceding 'a' */
3250 if (start_of_nosubsts >= 0)
3251 macro_str1.len = start_of_nosubsts;
3252 /* given 'a##b', remove nosubsts preceding 'b' */
3253 while ((t1 = *++ptr) == TOK_NOSUBST)
3255 if (t1 && t1 != TOK_PPJOIN) {
3256 TOK_GET(&t1, &ptr, &cv1);
3257 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3258 if (paste_tokens(t, &cval, t1, &cv1)) {
3259 t = tok, cval = tokc;
3260 } else {
3261 tok_str_add2(&macro_str1, t, &cval);
3262 t = t1, cval = cv1;
3267 if (t == TOK_NOSUBST) {
3268 if (start_of_nosubsts < 0)
3269 start_of_nosubsts = macro_str1.len;
3270 } else {
3271 start_of_nosubsts = -1;
3273 tok_str_add2(&macro_str1, t, &cval);
3275 tok_str_add(&macro_str1, 0);
3276 //tok_print(" ###", macro_str1.str);
3277 return macro_str1.str;
3280 /* peek or read [ws_str == NULL] next token from function macro call,
3281 walking up macro levels up to the file if necessary */
3282 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3284 int t;
3285 const int *p;
3286 Sym *sa;
3288 for (;;) {
3289 if (macro_ptr) {
3290 p = macro_ptr, t = *p;
3291 if (ws_str) {
3292 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3293 tok_str_add(ws_str, t), t = *++p;
3295 if (t == 0) {
3296 end_macro();
3297 /* also, end of scope for nested defined symbol */
3298 sa = *nested_list;
3299 while (sa && sa->v == 0)
3300 sa = sa->prev;
3301 if (sa)
3302 sa->v = 0;
3303 continue;
3305 } else {
3306 ch = handle_eob();
3307 if (ws_str) {
3308 while (is_space(ch) || ch == '\n' || ch == '/') {
3309 if (ch == '/') {
3310 int c;
3311 uint8_t *p = file->buf_ptr;
3312 PEEKC(c, p);
3313 if (c == '*') {
3314 p = parse_comment(p);
3315 file->buf_ptr = p - 1;
3316 } else if (c == '/') {
3317 p = parse_line_comment(p);
3318 file->buf_ptr = p - 1;
3319 } else
3320 break;
3321 ch = ' ';
3323 if (ch == '\n')
3324 file->line_num++;
3325 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3326 tok_str_add(ws_str, ch);
3327 cinp();
3330 t = ch;
3333 if (ws_str)
3334 return t;
3335 next_nomacro();
3336 return tok;
3340 /* do macro substitution of current token with macro 's' and add
3341 result to (tok_str,tok_len). 'nested_list' is the list of all
3342 macros we got inside to avoid recursing. Return non zero if no
3343 substitution needs to be done */
3344 static int macro_subst_tok(
3345 TokenString *tok_str,
3346 Sym **nested_list,
3347 Sym *s)
3349 Sym *args, *sa, *sa1;
3350 int parlevel, t, t1, spc;
3351 TokenString str;
3352 char *cstrval;
3353 CValue cval;
3354 CString cstr;
3355 char buf[32];
3357 /* if symbol is a macro, prepare substitution */
3358 /* special macros */
3359 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3360 t = tok == TOK___LINE__ ? file->line_num : pp_counter++;
3361 snprintf(buf, sizeof(buf), "%d", t);
3362 cstrval = buf;
3363 t1 = TOK_PPNUM;
3364 goto add_cstr1;
3365 } else if (tok == TOK___FILE__) {
3366 cstrval = file->filename;
3367 goto add_cstr;
3368 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3369 time_t ti;
3370 struct tm *tm;
3372 time(&ti);
3373 tm = localtime(&ti);
3374 if (tok == TOK___DATE__) {
3375 snprintf(buf, sizeof(buf), "%s %2d %d",
3376 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3377 } else {
3378 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3379 tm->tm_hour, tm->tm_min, tm->tm_sec);
3381 cstrval = buf;
3382 add_cstr:
3383 t1 = TOK_STR;
3384 add_cstr1:
3385 cstr_new(&cstr);
3386 cstr_cat(&cstr, cstrval, 0);
3387 cval.str.size = cstr.size;
3388 cval.str.data = cstr.data;
3389 tok_str_add2(tok_str, t1, &cval);
3390 cstr_free(&cstr);
3391 } else if (s->d) {
3392 int saved_parse_flags = parse_flags;
3393 int *joined_str = NULL;
3394 int *mstr = s->d;
3396 if (s->type.t == MACRO_FUNC) {
3397 /* whitespace between macro name and argument list */
3398 TokenString ws_str;
3399 tok_str_new(&ws_str);
3401 spc = 0;
3402 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3403 | PARSE_FLAG_ACCEPT_STRAYS;
3405 /* get next token from argument stream */
3406 t = next_argstream(nested_list, &ws_str);
3407 if (t != '(') {
3408 /* not a macro substitution after all, restore the
3409 * macro token plus all whitespace we've read.
3410 * whitespace is intentionally not merged to preserve
3411 * newlines. */
3412 parse_flags = saved_parse_flags;
3413 tok_str_add(tok_str, tok);
3414 if (parse_flags & PARSE_FLAG_SPACES) {
3415 int i;
3416 for (i = 0; i < ws_str.len; i++)
3417 tok_str_add(tok_str, ws_str.str[i]);
3419 tok_str_free_str(ws_str.str);
3420 return 0;
3421 } else {
3422 tok_str_free_str(ws_str.str);
3424 do {
3425 next_nomacro(); /* eat '(' */
3426 } while (tok == TOK_PLCHLDR || is_space(tok));
3428 /* argument macro */
3429 args = NULL;
3430 sa = s->next;
3431 /* NOTE: empty args are allowed, except if no args */
3432 for(;;) {
3433 do {
3434 next_argstream(nested_list, NULL);
3435 } while (tok == TOK_PLCHLDR || is_space(tok) ||
3436 TOK_LINEFEED == tok);
3437 empty_arg:
3438 /* handle '()' case */
3439 if (!args && !sa && tok == ')')
3440 break;
3441 if (!sa)
3442 tcc_error("macro '%s' used with too many args",
3443 get_tok_str(s->v, 0));
3444 tok_str_new(&str);
3445 parlevel = spc = 0;
3446 /* NOTE: non zero sa->t indicates VA_ARGS */
3447 while ((parlevel > 0 ||
3448 (tok != ')' &&
3449 (tok != ',' || sa->type.t)))) {
3450 if (tok == TOK_EOF || tok == 0)
3451 break;
3452 if (tok == '(')
3453 parlevel++;
3454 else if (tok == ')')
3455 parlevel--;
3456 if (tok == TOK_LINEFEED)
3457 tok = ' ';
3458 if (!check_space(tok, &spc))
3459 tok_str_add2(&str, tok, &tokc);
3460 next_argstream(nested_list, NULL);
3462 if (parlevel)
3463 expect(")");
3464 str.len -= spc;
3465 tok_str_add(&str, -1);
3466 tok_str_add(&str, 0);
3467 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3468 sa1->d = str.str;
3469 sa = sa->next;
3470 if (tok == ')') {
3471 /* special case for gcc var args: add an empty
3472 var arg argument if it is omitted */
3473 if (sa && sa->type.t && gnu_ext)
3474 goto empty_arg;
3475 break;
3477 if (tok != ',')
3478 expect(",");
3480 if (sa) {
3481 tcc_error("macro '%s' used with too few args",
3482 get_tok_str(s->v, 0));
3485 /* now subst each arg */
3486 mstr = macro_arg_subst(nested_list, mstr, args);
3487 /* free memory */
3488 sa = args;
3489 while (sa) {
3490 sa1 = sa->prev;
3491 tok_str_free_str(sa->d);
3492 if (sa->next) {
3493 tok_str_free_str(sa->next->d);
3494 sym_free(sa->next);
3496 sym_free(sa);
3497 sa = sa1;
3499 parse_flags = saved_parse_flags;
3502 sym_push2(nested_list, s->v, 0, 0);
3503 parse_flags = saved_parse_flags;
3504 joined_str = macro_twosharps(mstr);
3505 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3507 /* pop nested defined symbol */
3508 sa1 = *nested_list;
3509 *nested_list = sa1->prev;
3510 sym_free(sa1);
3511 if (joined_str)
3512 tok_str_free_str(joined_str);
3513 if (mstr != s->d)
3514 tok_str_free_str(mstr);
3516 return 0;
3519 /* do macro substitution of macro_str and add result to
3520 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3521 inside to avoid recursing. */
3522 static void macro_subst(
3523 TokenString *tok_str,
3524 Sym **nested_list,
3525 const int *macro_str
3528 Sym *s;
3529 int t, spc, nosubst;
3530 CValue cval;
3532 spc = nosubst = 0;
3534 while (1) {
3535 TOK_GET(&t, &macro_str, &cval);
3536 if (t <= 0)
3537 break;
3539 if (t >= TOK_IDENT && 0 == nosubst) {
3540 s = define_find(t);
3541 if (s == NULL)
3542 goto no_subst;
3544 /* if nested substitution, do nothing */
3545 if (sym_find2(*nested_list, t)) {
3546 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3547 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3548 goto no_subst;
3552 TokenString *str = tok_str_alloc();
3553 str->str = (int*)macro_str;
3554 begin_macro(str, 2);
3556 tok = t;
3557 macro_subst_tok(tok_str, nested_list, s);
3559 if (macro_stack != str) {
3560 /* already finished by reading function macro arguments */
3561 break;
3564 macro_str = macro_ptr;
3565 end_macro ();
3567 if (tok_str->len)
3568 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3569 } else {
3570 no_subst:
3571 if (!check_space(t, &spc))
3572 tok_str_add2(tok_str, t, &cval);
3574 if (nosubst) {
3575 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3576 continue;
3577 nosubst = 0;
3579 if (t == TOK_NOSUBST)
3580 nosubst = 1;
3582 /* GCC supports 'defined' as result of a macro substitution */
3583 if (t == TOK_DEFINED && pp_expr)
3584 nosubst = 2;
3588 /* return next token without macro substitution. Can read input from
3589 macro_ptr buffer */
3590 static void next_nomacro(void)
3592 int t;
3593 if (macro_ptr) {
3594 redo:
3595 t = *macro_ptr;
3596 if (TOK_HAS_VALUE(t)) {
3597 tok_get(&tok, &macro_ptr, &tokc);
3598 if (t == TOK_LINENUM) {
3599 file->line_num = tokc.i;
3600 goto redo;
3602 } else {
3603 macro_ptr++;
3604 if (t < TOK_IDENT) {
3605 if (!(parse_flags & PARSE_FLAG_SPACES)
3606 && (isidnum_table[t - CH_EOF] & IS_SPC))
3607 goto redo;
3609 tok = t;
3611 } else {
3612 next_nomacro1();
3616 /* return next token with macro substitution */
3617 ST_FUNC void next(void)
3619 int t;
3620 redo:
3621 next_nomacro();
3622 t = tok;
3623 if (macro_ptr) {
3624 if (!TOK_HAS_VALUE(t)) {
3625 if (t == TOK_NOSUBST || t == TOK_PLCHLDR) {
3626 /* discard preprocessor markers */
3627 goto redo;
3628 } else if (t == 0) {
3629 /* end of macro or unget token string */
3630 end_macro();
3631 goto redo;
3632 } else if (t == '\\') {
3633 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3634 tcc_error("stray '\\' in program");
3636 return;
3638 } else if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3639 /* if reading from file, try to substitute macros */
3640 Sym *s = define_find(t);
3641 if (s) {
3642 Sym *nested_list = NULL;
3643 tokstr_buf.len = 0;
3644 macro_subst_tok(&tokstr_buf, &nested_list, s);
3645 tok_str_add(&tokstr_buf, 0);
3646 begin_macro(&tokstr_buf, 0);
3647 goto redo;
3649 return;
3651 /* convert preprocessor tokens into C tokens */
3652 if (t == TOK_PPNUM) {
3653 if (parse_flags & PARSE_FLAG_TOK_NUM)
3654 parse_number((char *)tokc.str.data);
3655 } else if (t == TOK_PPSTR) {
3656 if (parse_flags & PARSE_FLAG_TOK_STR)
3657 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3661 /* push back current token and set current token to 'last_tok'. Only
3662 identifier case handled for labels. */
3663 ST_INLN void unget_tok(int last_tok)
3666 TokenString *str = tok_str_alloc();
3667 tok_str_add2(str, tok, &tokc);
3668 tok_str_add(str, 0);
3669 begin_macro(str, 1);
3670 tok = last_tok;
3673 /* ------------------------------------------------------------------------- */
3674 /* init preprocessor */
3676 static const char * const target_os_defs =
3677 #ifdef TCC_TARGET_PE
3678 "_WIN32\0"
3679 # if PTR_SIZE == 8
3680 "_WIN64\0"
3681 # endif
3682 #else
3683 # if defined TCC_TARGET_MACHO
3684 "__APPLE__\0"
3685 # elif TARGETOS_FreeBSD
3686 "__FreeBSD__ 12\0"
3687 # elif TARGETOS_FreeBSD_kernel
3688 "__FreeBSD_kernel__\0"
3689 # elif TARGETOS_NetBSD
3690 "__NetBSD__\0"
3691 # elif TARGETOS_OpenBSD
3692 "__OpenBSD__\0"
3693 # else
3694 "__linux__\0"
3695 "__linux\0"
3696 # endif
3697 "__unix__\0"
3698 "__unix\0"
3699 #endif
3702 static void putdef(CString *cs, const char *p)
3704 cstr_printf(cs, "#define %s%s\n", p, &" 1"[!!strchr(p, ' ')*2]);
3707 static void tcc_predefs(TCCState *s1, CString *cs, int is_asm)
3709 int a, b, c;
3710 const char *defs[] = { target_machine_defs, target_os_defs, NULL };
3711 const char *p;
3713 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
3714 cstr_printf(cs, "#define __TINYC__ %d\n", a*10000 + b*100 + c);
3715 for (a = 0; defs[a]; ++a)
3716 for (p = defs[a]; *p; p = strchr(p, 0) + 1)
3717 putdef(cs, p);
3718 #ifdef TCC_TARGET_ARM
3719 if (s1->float_abi == ARM_HARD_FLOAT)
3720 putdef(cs, "__ARM_PCS_VFP");
3721 #endif
3722 if (is_asm)
3723 putdef(cs, "__ASSEMBLER__");
3724 if (s1->output_type == TCC_OUTPUT_PREPROCESS)
3725 putdef(cs, "__TCC_PP__");
3726 if (s1->output_type == TCC_OUTPUT_MEMORY)
3727 putdef(cs, "__TCC_RUN__");
3728 if (s1->char_is_unsigned)
3729 putdef(cs, "__CHAR_UNSIGNED__");
3730 if (s1->optimize > 0)
3731 putdef(cs, "__OPTIMIZE__");
3732 if (s1->option_pthread)
3733 putdef(cs, "_REENTRANT");
3734 if (s1->leading_underscore)
3735 putdef(cs, "__leading_underscore");
3736 #ifdef CONFIG_TCC_BCHECK
3737 if (s1->do_bounds_check)
3738 putdef(cs, "__BOUNDS_CHECKING_ON");
3739 #endif
3740 cstr_printf(cs, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE);
3741 cstr_printf(cs, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE);
3742 if (!is_asm) {
3743 putdef(cs, "__STDC__");
3744 cstr_printf(cs, "#define __STDC_VERSION__ %dL\n", s1->cversion);
3745 cstr_cat(cs,
3746 /* load more predefs and __builtins */
3747 #if CONFIG_TCC_PREDEFS
3748 #include "tccdefs_.h" /* include as strings */
3749 #else
3750 "#include <tccdefs.h>\n" /* load at runtime */
3751 #endif
3752 , -1);
3754 cstr_printf(cs, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3757 ST_FUNC void preprocess_start(TCCState *s1, int filetype)
3759 int is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
3760 CString cstr;
3762 tccpp_new(s1);
3764 s1->include_stack_ptr = s1->include_stack;
3765 s1->ifdef_stack_ptr = s1->ifdef_stack;
3766 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3767 pp_expr = 0;
3768 pp_counter = 0;
3769 pp_debug_tok = pp_debug_symv = 0;
3770 pp_once++;
3771 s1->pack_stack[0] = 0;
3772 s1->pack_stack_ptr = s1->pack_stack;
3774 set_idnum('$', !is_asm && s1->dollars_in_identifiers ? IS_ID : 0);
3775 set_idnum('.', is_asm ? IS_ID : 0);
3777 if (!(filetype & AFF_TYPE_ASM)) {
3778 cstr_new(&cstr);
3779 tcc_predefs(s1, &cstr, is_asm);
3780 if (s1->cmdline_defs.size)
3781 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3782 if (s1->cmdline_incl.size)
3783 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3784 //printf("%s\n", (char*)cstr.data);
3785 *s1->include_stack_ptr++ = file;
3786 tcc_open_bf(s1, "<command line>", cstr.size);
3787 memcpy(file->buffer, cstr.data, cstr.size);
3788 cstr_free(&cstr);
3791 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3792 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3795 /* cleanup from error/setjmp */
3796 ST_FUNC void preprocess_end(TCCState *s1)
3798 while (macro_stack)
3799 end_macro();
3800 macro_ptr = NULL;
3801 while (file)
3802 tcc_close();
3803 tccpp_delete(s1);
3806 ST_FUNC void tccpp_new(TCCState *s)
3808 int i, c;
3809 const char *p, *r;
3811 /* init isid table */
3812 for(i = CH_EOF; i<128; i++)
3813 set_idnum(i,
3814 is_space(i) ? IS_SPC
3815 : isid(i) ? IS_ID
3816 : isnum(i) ? IS_NUM
3817 : 0);
3819 for(i = 128; i<256; i++)
3820 set_idnum(i, IS_ID);
3822 /* init allocators */
3823 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3824 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3826 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3827 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3829 cstr_new(&cstr_buf);
3830 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3831 tok_str_new(&tokstr_buf);
3832 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3834 tok_ident = TOK_IDENT;
3835 p = tcc_keywords;
3836 while (*p) {
3837 r = p;
3838 for(;;) {
3839 c = *r++;
3840 if (c == '\0')
3841 break;
3843 tok_alloc(p, r - p - 1);
3844 p = r;
3847 /* we add dummy defines for some special macros to speed up tests
3848 and to have working defined() */
3849 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3850 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3851 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3852 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3853 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3856 ST_FUNC void tccpp_delete(TCCState *s)
3858 int i, n;
3860 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3862 /* free tokens */
3863 n = tok_ident - TOK_IDENT;
3864 if (n > total_idents)
3865 total_idents = n;
3866 for(i = 0; i < n; i++)
3867 tal_free(toksym_alloc, table_ident[i]);
3868 tcc_free(table_ident);
3869 table_ident = NULL;
3871 /* free static buffers */
3872 cstr_free(&tokcstr);
3873 cstr_free(&cstr_buf);
3874 cstr_free(&macro_equal_buf);
3875 tok_str_free_str(tokstr_buf.str);
3877 /* free allocators */
3878 tal_delete(toksym_alloc);
3879 toksym_alloc = NULL;
3880 tal_delete(tokstr_alloc);
3881 tokstr_alloc = NULL;
3884 /* ------------------------------------------------------------------------- */
3885 /* tcc -E [-P[1]] [-dD} support */
3887 static void tok_print(const char *msg, const int *str)
3889 FILE *fp;
3890 int t, s = 0;
3891 CValue cval;
3893 fp = tcc_state->ppfp;
3894 fprintf(fp, "%s", msg);
3895 while (str) {
3896 TOK_GET(&t, &str, &cval);
3897 if (!t)
3898 break;
3899 fprintf(fp, &" %s"[s], get_tok_str(t, &cval)), s = 1;
3901 fprintf(fp, "\n");
3904 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3906 int d = f->line_num - f->line_ref;
3908 if (s1->dflag & 4)
3909 return;
3911 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3913 } else if (level == 0 && f->line_ref && d < 8) {
3914 while (d > 0)
3915 fputs("\n", s1->ppfp), --d;
3916 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3917 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3918 } else {
3919 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3920 level > 0 ? " 1" : level < 0 ? " 2" : "");
3922 f->line_ref = f->line_num;
3925 static void define_print(TCCState *s1, int v)
3927 FILE *fp;
3928 Sym *s;
3930 s = define_find(v);
3931 if (NULL == s || NULL == s->d)
3932 return;
3934 fp = s1->ppfp;
3935 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3936 if (s->type.t == MACRO_FUNC) {
3937 Sym *a = s->next;
3938 fprintf(fp,"(");
3939 if (a)
3940 for (;;) {
3941 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3942 if (!(a = a->next))
3943 break;
3944 fprintf(fp,",");
3946 fprintf(fp,")");
3948 tok_print("", s->d);
3951 static void pp_debug_defines(TCCState *s1)
3953 int v, t;
3954 const char *vs;
3955 FILE *fp;
3957 t = pp_debug_tok;
3958 if (t == 0)
3959 return;
3961 file->line_num--;
3962 pp_line(s1, file, 0);
3963 file->line_ref = ++file->line_num;
3965 fp = s1->ppfp;
3966 v = pp_debug_symv;
3967 vs = get_tok_str(v, NULL);
3968 if (t == TOK_DEFINE) {
3969 define_print(s1, v);
3970 } else if (t == TOK_UNDEF) {
3971 fprintf(fp, "#undef %s\n", vs);
3972 } else if (t == TOK_push_macro) {
3973 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3974 } else if (t == TOK_pop_macro) {
3975 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3977 pp_debug_tok = 0;
3980 static void pp_debug_builtins(TCCState *s1)
3982 int v;
3983 for (v = TOK_IDENT; v < tok_ident; ++v)
3984 define_print(s1, v);
3987 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3988 static int pp_need_space(int a, int b)
3990 return 'E' == a ? '+' == b || '-' == b
3991 : '+' == a ? TOK_INC == b || '+' == b
3992 : '-' == a ? TOK_DEC == b || '-' == b
3993 : a >= TOK_IDENT ? b >= TOK_IDENT
3994 : a == TOK_PPNUM ? b >= TOK_IDENT
3995 : 0;
3998 /* maybe hex like 0x1e */
3999 static int pp_check_he0xE(int t, const char *p)
4001 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
4002 return 'E';
4003 return t;
4006 /* Preprocess the current file */
4007 ST_FUNC int tcc_preprocess(TCCState *s1)
4009 BufferedFile **iptr;
4010 int token_seen, spcs, level;
4011 const char *p;
4012 char white[400];
4014 parse_flags = PARSE_FLAG_PREPROCESS
4015 | (parse_flags & PARSE_FLAG_ASM_FILE)
4016 | PARSE_FLAG_LINEFEED
4017 | PARSE_FLAG_SPACES
4018 | PARSE_FLAG_ACCEPT_STRAYS
4020 /* Credits to Fabrice Bellard's initial revision to demonstrate its
4021 capability to compile and run itself, provided all numbers are
4022 given as decimals. tcc -E -P10 will do. */
4023 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
4024 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
4026 if (s1->do_bench) {
4027 /* for PP benchmarks */
4028 do next(); while (tok != TOK_EOF);
4029 return 0;
4032 if (s1->dflag & 1) {
4033 pp_debug_builtins(s1);
4034 s1->dflag &= ~1;
4037 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
4038 if (file->prev)
4039 pp_line(s1, file->prev, level++);
4040 pp_line(s1, file, level);
4041 for (;;) {
4042 iptr = s1->include_stack_ptr;
4043 next();
4044 if (tok == TOK_EOF)
4045 break;
4047 level = s1->include_stack_ptr - iptr;
4048 if (level) {
4049 if (level > 0)
4050 pp_line(s1, *iptr, 0);
4051 pp_line(s1, file, level);
4053 if (s1->dflag & 7) {
4054 pp_debug_defines(s1);
4055 if (s1->dflag & 4)
4056 continue;
4059 if (is_space(tok)) {
4060 if (spcs < sizeof white - 1)
4061 white[spcs++] = tok;
4062 continue;
4063 } else if (tok == TOK_LINEFEED) {
4064 spcs = 0;
4065 if (token_seen == TOK_LINEFEED)
4066 continue;
4067 ++file->line_ref;
4068 } else if (token_seen == TOK_LINEFEED) {
4069 pp_line(s1, file, 0);
4070 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
4071 white[spcs++] = ' ';
4074 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
4075 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
4076 token_seen = pp_check_he0xE(tok, p);
4078 return 0;
4081 /* ------------------------------------------------------------------------- */