tcc.h: Extend search path for include, lib and crt.
[tinycc.git] / tccpp.c
blob2ff5d5e9b207ef83a5d3850589570234db2f6217
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) // push current
1729 #pragma pack(push,1) // push & set
1730 #pragma pack(pop) // restore previous */
1731 next();
1732 skip('(');
1733 if (tok == TOK_ASM_pop) {
1734 next();
1735 if (s1->pack_stack_ptr <= s1->pack_stack) {
1736 stk_error:
1737 tcc_error("out of pack stack");
1739 s1->pack_stack_ptr--;
1740 } else {
1741 int val = 0;
1742 if (tok != ')') {
1743 if (tok == TOK_ASM_push) {
1744 next();
1745 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1746 goto stk_error;
1747 val = *s1->pack_stack_ptr++;
1748 if (tok != ',')
1749 goto pack_set;
1750 next();
1752 if (tok != TOK_CINT)
1753 goto pragma_err;
1754 val = tokc.i;
1755 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1756 goto pragma_err;
1757 next();
1759 pack_set:
1760 *s1->pack_stack_ptr = val;
1762 if (tok != ')')
1763 goto pragma_err;
1765 } else if (tok == TOK_comment) {
1766 char *p; int t;
1767 next();
1768 skip('(');
1769 t = tok;
1770 next();
1771 skip(',');
1772 if (tok != TOK_STR)
1773 goto pragma_err;
1774 p = tcc_strdup((char *)tokc.str.data);
1775 next();
1776 if (tok != ')')
1777 goto pragma_err;
1778 if (t == TOK_lib) {
1779 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1780 } else {
1781 if (t == TOK_option)
1782 tcc_set_options(s1, p);
1783 tcc_free(p);
1786 } else
1787 tcc_warning_c(warn_unsupported)("#pragma %s ignored", get_tok_str(tok, &tokc));
1788 return;
1790 pragma_err:
1791 tcc_error("malformed #pragma directive");
1792 return;
1795 /* is_bof is true if first non space token at beginning of file */
1796 ST_FUNC void preprocess(int is_bof)
1798 TCCState *s1 = tcc_state;
1799 int i, c, n, saved_parse_flags;
1800 char buf[1024], *q;
1801 Sym *s;
1803 saved_parse_flags = parse_flags;
1804 parse_flags = PARSE_FLAG_PREPROCESS
1805 | PARSE_FLAG_TOK_NUM
1806 | PARSE_FLAG_TOK_STR
1807 | PARSE_FLAG_LINEFEED
1808 | (parse_flags & PARSE_FLAG_ASM_FILE)
1811 next_nomacro();
1812 redo:
1813 switch(tok) {
1814 case TOK_DEFINE:
1815 pp_debug_tok = tok;
1816 next_nomacro();
1817 pp_debug_symv = tok;
1818 parse_define();
1819 break;
1820 case TOK_UNDEF:
1821 pp_debug_tok = tok;
1822 next_nomacro();
1823 pp_debug_symv = tok;
1824 s = define_find(tok);
1825 /* undefine symbol by putting an invalid name */
1826 if (s)
1827 define_undef(s);
1828 break;
1829 case TOK_INCLUDE:
1830 case TOK_INCLUDE_NEXT:
1831 ch = file->buf_ptr[0];
1832 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1833 skip_spaces();
1834 if (ch == '<') {
1835 c = '>';
1836 goto read_name;
1837 } else if (ch == '\"') {
1838 c = ch;
1839 read_name:
1840 inp();
1841 q = buf;
1842 while (ch != c && ch != '\n' && ch != CH_EOF) {
1843 if ((q - buf) < sizeof(buf) - 1)
1844 *q++ = ch;
1845 if (ch == '\\') {
1846 if (handle_stray_noerror() == 0)
1847 --q;
1848 } else
1849 inp();
1851 *q = '\0';
1852 minp();
1853 #if 0
1854 /* eat all spaces and comments after include */
1855 /* XXX: slightly incorrect */
1856 while (ch1 != '\n' && ch1 != CH_EOF)
1857 inp();
1858 #endif
1859 } else {
1860 int len;
1861 /* computed #include : concatenate everything up to linefeed,
1862 the result must be one of the two accepted forms.
1863 Don't convert pp-tokens to tokens here. */
1864 parse_flags = (PARSE_FLAG_PREPROCESS
1865 | PARSE_FLAG_LINEFEED
1866 | (parse_flags & PARSE_FLAG_ASM_FILE));
1867 next();
1868 buf[0] = '\0';
1869 while (tok != TOK_LINEFEED) {
1870 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1871 next();
1873 len = strlen(buf);
1874 /* check syntax and remove '<>|""' */
1875 if ((len < 2 || ((buf[0] != '"' || buf[len-1] != '"') &&
1876 (buf[0] != '<' || buf[len-1] != '>'))))
1877 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1878 c = buf[len-1];
1879 memmove(buf, buf + 1, len - 2);
1880 buf[len - 2] = '\0';
1883 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1884 tcc_error("#include recursion too deep");
1885 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index + 1 : 0;
1886 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1887 for (; i < n; ++i) {
1888 char buf1[sizeof file->filename];
1889 CachedInclude *e;
1890 const char *path;
1892 if (i == 0) {
1893 /* check absolute include path */
1894 if (!IS_ABSPATH(buf))
1895 continue;
1896 buf1[0] = 0;
1898 } else if (i == 1) {
1899 /* search in file's dir if "header.h" */
1900 if (c != '\"')
1901 continue;
1902 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1903 path = file->true_filename;
1904 pstrncpy(buf1, path, tcc_basename(path) - path);
1906 } else {
1907 /* search in all the include paths */
1908 int j = i - 2, k = j - s1->nb_include_paths;
1909 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1910 pstrcpy(buf1, sizeof(buf1), path);
1911 pstrcat(buf1, sizeof(buf1), "/");
1914 pstrcat(buf1, sizeof(buf1), buf);
1915 e = search_cached_include(s1, buf1, 0);
1916 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1917 /* no need to parse the include because the 'ifndef macro'
1918 is defined (or had #pragma once) */
1919 #ifdef INC_DEBUG
1920 printf("%s: skipping cached %s\n", file->filename, buf1);
1921 #endif
1922 goto include_done;
1925 if (tcc_open(s1, buf1) < 0)
1926 continue;
1927 /* push previous file on stack */
1928 *s1->include_stack_ptr++ = file->prev;
1929 file->include_next_index = i;
1930 #ifdef INC_DEBUG
1931 printf("%s: including %s\n", file->prev->filename, file->filename);
1932 #endif
1933 /* update target deps */
1934 if (s1->gen_deps) {
1935 BufferedFile *bf = file;
1936 while (i == 1 && (bf = bf->prev))
1937 i = bf->include_next_index;
1938 /* skip system include files */
1939 if (s1->include_sys_deps || n - i > s1->nb_sysinclude_paths)
1940 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1941 tcc_strdup(buf1));
1943 /* add include file debug info */
1944 tcc_debug_bincl(tcc_state);
1945 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1946 ch = file->buf_ptr[0];
1947 goto the_end;
1949 tcc_error("include file '%s' not found", buf);
1950 include_done:
1951 break;
1952 case TOK_IFNDEF:
1953 c = 1;
1954 goto do_ifdef;
1955 case TOK_IF:
1956 c = expr_preprocess();
1957 goto do_if;
1958 case TOK_IFDEF:
1959 c = 0;
1960 do_ifdef:
1961 next_nomacro();
1962 if (tok < TOK_IDENT)
1963 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1964 if (is_bof) {
1965 if (c) {
1966 #ifdef INC_DEBUG
1967 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1968 #endif
1969 file->ifndef_macro = tok;
1972 c = (define_find(tok) != 0) ^ c;
1973 do_if:
1974 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1975 tcc_error("memory full (ifdef)");
1976 *s1->ifdef_stack_ptr++ = c;
1977 goto test_skip;
1978 case TOK_ELSE:
1979 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1980 tcc_error("#else without matching #if");
1981 if (s1->ifdef_stack_ptr[-1] & 2)
1982 tcc_error("#else after #else");
1983 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1984 goto test_else;
1985 case TOK_ELIF:
1986 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1987 tcc_error("#elif without matching #if");
1988 c = s1->ifdef_stack_ptr[-1];
1989 if (c > 1)
1990 tcc_error("#elif after #else");
1991 /* last #if/#elif expression was true: we skip */
1992 if (c == 1) {
1993 c = 0;
1994 } else {
1995 c = expr_preprocess();
1996 s1->ifdef_stack_ptr[-1] = c;
1998 test_else:
1999 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
2000 file->ifndef_macro = 0;
2001 test_skip:
2002 if (!(c & 1)) {
2003 preprocess_skip();
2004 is_bof = 0;
2005 goto redo;
2007 break;
2008 case TOK_ENDIF:
2009 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
2010 tcc_error("#endif without matching #if");
2011 s1->ifdef_stack_ptr--;
2012 /* '#ifndef macro' was at the start of file. Now we check if
2013 an '#endif' is exactly at the end of file */
2014 if (file->ifndef_macro &&
2015 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
2016 file->ifndef_macro_saved = file->ifndef_macro;
2017 /* need to set to zero to avoid false matches if another
2018 #ifndef at middle of file */
2019 file->ifndef_macro = 0;
2020 while (tok != TOK_LINEFEED)
2021 next_nomacro();
2022 tok_flags |= TOK_FLAG_ENDIF;
2023 goto the_end;
2025 break;
2026 case TOK_PPNUM:
2027 n = strtoul((char*)tokc.str.data, &q, 10);
2028 goto _line_num;
2029 case TOK_LINE:
2030 next();
2031 if (tok != TOK_CINT)
2032 _line_err:
2033 tcc_error("wrong #line format");
2034 n = tokc.i;
2035 _line_num:
2036 next();
2037 if (tok != TOK_LINEFEED) {
2038 if (tok == TOK_STR) {
2039 if (file->true_filename == file->filename)
2040 file->true_filename = tcc_strdup(file->filename);
2041 /* prepend directory from real file */
2042 pstrcpy(buf, sizeof buf, file->true_filename);
2043 *tcc_basename(buf) = 0;
2044 pstrcat(buf, sizeof buf, (char *)tokc.str.data);
2045 tcc_debug_putfile(s1, buf);
2046 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
2047 break;
2048 else
2049 goto _line_err;
2050 --n;
2052 if (file->fd > 0)
2053 total_lines += file->line_num - n;
2054 file->line_num = n;
2055 break;
2056 case TOK_ERROR:
2057 case TOK_WARNING:
2058 c = tok;
2059 ch = file->buf_ptr[0];
2060 skip_spaces();
2061 q = buf;
2062 while (ch != '\n' && ch != CH_EOF) {
2063 if ((q - buf) < sizeof(buf) - 1)
2064 *q++ = ch;
2065 if (ch == '\\') {
2066 if (handle_stray_noerror() == 0)
2067 --q;
2068 } else
2069 inp();
2071 *q = '\0';
2072 if (c == TOK_ERROR)
2073 tcc_error("#error %s", buf);
2074 else
2075 tcc_warning("#warning %s", buf);
2076 break;
2077 case TOK_PRAGMA:
2078 pragma_parse(s1);
2079 break;
2080 case TOK_LINEFEED:
2081 goto the_end;
2082 default:
2083 /* ignore gas line comment in an 'S' file. */
2084 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
2085 goto ignore;
2086 if (tok == '!' && is_bof)
2087 /* '!' is ignored at beginning to allow C scripts. */
2088 goto ignore;
2089 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
2090 ignore:
2091 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
2092 goto the_end;
2094 /* ignore other preprocess commands or #! for C scripts */
2095 while (tok != TOK_LINEFEED)
2096 next_nomacro();
2097 the_end:
2098 parse_flags = saved_parse_flags;
2101 /* evaluate escape codes in a string. */
2102 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
2104 int c, n, i;
2105 const uint8_t *p;
2107 p = buf;
2108 for(;;) {
2109 c = *p;
2110 if (c == '\0')
2111 break;
2112 if (c == '\\') {
2113 p++;
2114 /* escape */
2115 c = *p;
2116 switch(c) {
2117 case '0': case '1': case '2': case '3':
2118 case '4': case '5': case '6': case '7':
2119 /* at most three octal digits */
2120 n = c - '0';
2121 p++;
2122 c = *p;
2123 if (isoct(c)) {
2124 n = n * 8 + c - '0';
2125 p++;
2126 c = *p;
2127 if (isoct(c)) {
2128 n = n * 8 + c - '0';
2129 p++;
2132 c = n;
2133 goto add_char_nonext;
2134 case 'x': i = 0; goto parse_hex_or_ucn;
2135 case 'u': i = 4; goto parse_hex_or_ucn;
2136 case 'U': i = 8; goto parse_hex_or_ucn;
2137 parse_hex_or_ucn:
2138 p++;
2139 n = 0;
2140 do {
2141 c = *p;
2142 if (c >= 'a' && c <= 'f')
2143 c = c - 'a' + 10;
2144 else if (c >= 'A' && c <= 'F')
2145 c = c - 'A' + 10;
2146 else if (isnum(c))
2147 c = c - '0';
2148 else if (i > 0)
2149 expect("more hex digits in universal-character-name");
2150 else {
2151 c = n;
2152 goto add_char_nonext;
2154 n = n * 16 + c;
2155 p++;
2156 } while (--i);
2157 cstr_u8cat(outstr, n);
2158 continue;
2159 case 'a':
2160 c = '\a';
2161 break;
2162 case 'b':
2163 c = '\b';
2164 break;
2165 case 'f':
2166 c = '\f';
2167 break;
2168 case 'n':
2169 c = '\n';
2170 break;
2171 case 'r':
2172 c = '\r';
2173 break;
2174 case 't':
2175 c = '\t';
2176 break;
2177 case 'v':
2178 c = '\v';
2179 break;
2180 case 'e':
2181 if (!gnu_ext)
2182 goto invalid_escape;
2183 c = 27;
2184 break;
2185 case '\'':
2186 case '\"':
2187 case '\\':
2188 case '?':
2189 break;
2190 default:
2191 invalid_escape:
2192 if (c >= '!' && c <= '~')
2193 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2194 else
2195 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2196 break;
2198 } else if (is_long && c >= 0x80) {
2199 /* assume we are processing UTF-8 sequence */
2200 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2202 int cont; /* count of continuation bytes */
2203 int skip; /* how many bytes should skip when error occurred */
2204 int i;
2206 /* decode leading byte */
2207 if (c < 0xC2) {
2208 skip = 1; goto invalid_utf8_sequence;
2209 } else if (c <= 0xDF) {
2210 cont = 1; n = c & 0x1f;
2211 } else if (c <= 0xEF) {
2212 cont = 2; n = c & 0xf;
2213 } else if (c <= 0xF4) {
2214 cont = 3; n = c & 0x7;
2215 } else {
2216 skip = 1; goto invalid_utf8_sequence;
2219 /* decode continuation bytes */
2220 for (i = 1; i <= cont; i++) {
2221 int l = 0x80, h = 0xBF;
2223 /* adjust limit for second byte */
2224 if (i == 1) {
2225 switch (c) {
2226 case 0xE0: l = 0xA0; break;
2227 case 0xED: h = 0x9F; break;
2228 case 0xF0: l = 0x90; break;
2229 case 0xF4: h = 0x8F; break;
2233 if (p[i] < l || p[i] > h) {
2234 skip = i; goto invalid_utf8_sequence;
2237 n = (n << 6) | (p[i] & 0x3f);
2240 /* advance pointer */
2241 p += 1 + cont;
2242 c = n;
2243 goto add_char_nonext;
2245 /* error handling */
2246 invalid_utf8_sequence:
2247 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2248 c = 0xFFFD;
2249 p += skip;
2250 goto add_char_nonext;
2253 p++;
2254 add_char_nonext:
2255 if (!is_long)
2256 cstr_ccat(outstr, c);
2257 else {
2258 #ifdef TCC_TARGET_PE
2259 /* store as UTF-16 */
2260 if (c < 0x10000) {
2261 cstr_wccat(outstr, c);
2262 } else {
2263 c -= 0x10000;
2264 cstr_wccat(outstr, (c >> 10) + 0xD800);
2265 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2267 #else
2268 cstr_wccat(outstr, c);
2269 #endif
2272 /* add a trailing '\0' */
2273 if (!is_long)
2274 cstr_ccat(outstr, '\0');
2275 else
2276 cstr_wccat(outstr, '\0');
2279 static void parse_string(const char *s, int len)
2281 uint8_t buf[1000], *p = buf;
2282 int is_long, sep;
2284 if ((is_long = *s == 'L'))
2285 ++s, --len;
2286 sep = *s++;
2287 len -= 2;
2288 if (len >= sizeof buf)
2289 p = tcc_malloc(len + 1);
2290 memcpy(p, s, len);
2291 p[len] = 0;
2293 cstr_reset(&tokcstr);
2294 parse_escape_string(&tokcstr, p, is_long);
2295 if (p != buf)
2296 tcc_free(p);
2298 if (sep == '\'') {
2299 int char_size, i, n, c;
2300 /* XXX: make it portable */
2301 if (!is_long)
2302 tok = TOK_CCHAR, char_size = 1;
2303 else
2304 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2305 n = tokcstr.size / char_size - 1;
2306 if (n < 1)
2307 tcc_error("empty character constant");
2308 if (n > 1)
2309 tcc_warning_c(warn_all)("multi-character character constant");
2310 for (c = i = 0; i < n; ++i) {
2311 if (is_long)
2312 c = ((nwchar_t *)tokcstr.data)[i];
2313 else
2314 c = (c << 8) | ((char *)tokcstr.data)[i];
2316 tokc.i = c;
2317 } else {
2318 tokc.str.size = tokcstr.size;
2319 tokc.str.data = tokcstr.data;
2320 if (!is_long)
2321 tok = TOK_STR;
2322 else
2323 tok = TOK_LSTR;
2327 /* we use 64 bit numbers */
2328 #define BN_SIZE 2
2330 /* bn = (bn << shift) | or_val */
2331 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2333 int i;
2334 unsigned int v;
2335 for(i=0;i<BN_SIZE;i++) {
2336 v = bn[i];
2337 bn[i] = (v << shift) | or_val;
2338 or_val = v >> (32 - shift);
2342 static void bn_zero(unsigned int *bn)
2344 int i;
2345 for(i=0;i<BN_SIZE;i++) {
2346 bn[i] = 0;
2350 /* parse number in null terminated string 'p' and return it in the
2351 current token */
2352 static void parse_number(const char *p)
2354 int b, t, shift, frac_bits, s, exp_val, ch;
2355 char *q;
2356 unsigned int bn[BN_SIZE];
2357 double d;
2359 /* number */
2360 q = token_buf;
2361 ch = *p++;
2362 t = ch;
2363 ch = *p++;
2364 *q++ = t;
2365 b = 10;
2366 if (t == '.') {
2367 goto float_frac_parse;
2368 } else if (t == '0') {
2369 if (ch == 'x' || ch == 'X') {
2370 q--;
2371 ch = *p++;
2372 b = 16;
2373 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2374 q--;
2375 ch = *p++;
2376 b = 2;
2379 /* parse all digits. cannot check octal numbers at this stage
2380 because of floating point constants */
2381 while (1) {
2382 if (ch >= 'a' && ch <= 'f')
2383 t = ch - 'a' + 10;
2384 else if (ch >= 'A' && ch <= 'F')
2385 t = ch - 'A' + 10;
2386 else if (isnum(ch))
2387 t = ch - '0';
2388 else
2389 break;
2390 if (t >= b)
2391 break;
2392 if (q >= token_buf + STRING_MAX_SIZE) {
2393 num_too_long:
2394 tcc_error("number too long");
2396 *q++ = ch;
2397 ch = *p++;
2399 if (ch == '.' ||
2400 ((ch == 'e' || ch == 'E') && b == 10) ||
2401 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2402 if (b != 10) {
2403 /* NOTE: strtox should support that for hexa numbers, but
2404 non ISOC99 libcs do not support it, so we prefer to do
2405 it by hand */
2406 /* hexadecimal or binary floats */
2407 /* XXX: handle overflows */
2408 *q = '\0';
2409 if (b == 16)
2410 shift = 4;
2411 else
2412 shift = 1;
2413 bn_zero(bn);
2414 q = token_buf;
2415 while (1) {
2416 t = *q++;
2417 if (t == '\0') {
2418 break;
2419 } else if (t >= 'a') {
2420 t = t - 'a' + 10;
2421 } else if (t >= 'A') {
2422 t = t - 'A' + 10;
2423 } else {
2424 t = t - '0';
2426 bn_lshift(bn, shift, t);
2428 frac_bits = 0;
2429 if (ch == '.') {
2430 ch = *p++;
2431 while (1) {
2432 t = ch;
2433 if (t >= 'a' && t <= 'f') {
2434 t = t - 'a' + 10;
2435 } else if (t >= 'A' && t <= 'F') {
2436 t = t - 'A' + 10;
2437 } else if (t >= '0' && t <= '9') {
2438 t = t - '0';
2439 } else {
2440 break;
2442 if (t >= b)
2443 tcc_error("invalid digit");
2444 bn_lshift(bn, shift, t);
2445 frac_bits += shift;
2446 ch = *p++;
2449 if (ch != 'p' && ch != 'P')
2450 expect("exponent");
2451 ch = *p++;
2452 s = 1;
2453 exp_val = 0;
2454 if (ch == '+') {
2455 ch = *p++;
2456 } else if (ch == '-') {
2457 s = -1;
2458 ch = *p++;
2460 if (ch < '0' || ch > '9')
2461 expect("exponent digits");
2462 while (ch >= '0' && ch <= '9') {
2463 exp_val = exp_val * 10 + ch - '0';
2464 ch = *p++;
2466 exp_val = exp_val * s;
2468 /* now we can generate the number */
2469 /* XXX: should patch directly float number */
2470 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2471 d = ldexp(d, exp_val - frac_bits);
2472 t = toup(ch);
2473 if (t == 'F') {
2474 ch = *p++;
2475 tok = TOK_CFLOAT;
2476 /* float : should handle overflow */
2477 tokc.f = (float)d;
2478 } else if (t == 'L') {
2479 ch = *p++;
2480 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2481 tok = TOK_CDOUBLE;
2482 tokc.d = d;
2483 #else
2484 tok = TOK_CLDOUBLE;
2485 /* XXX: not large enough */
2486 tokc.ld = (long double)d;
2487 #endif
2488 } else {
2489 tok = TOK_CDOUBLE;
2490 tokc.d = d;
2492 } else {
2493 /* decimal floats */
2494 if (ch == '.') {
2495 if (q >= token_buf + STRING_MAX_SIZE)
2496 goto num_too_long;
2497 *q++ = ch;
2498 ch = *p++;
2499 float_frac_parse:
2500 while (ch >= '0' && ch <= '9') {
2501 if (q >= token_buf + STRING_MAX_SIZE)
2502 goto num_too_long;
2503 *q++ = ch;
2504 ch = *p++;
2507 if (ch == 'e' || ch == 'E') {
2508 if (q >= token_buf + STRING_MAX_SIZE)
2509 goto num_too_long;
2510 *q++ = ch;
2511 ch = *p++;
2512 if (ch == '-' || ch == '+') {
2513 if (q >= token_buf + STRING_MAX_SIZE)
2514 goto num_too_long;
2515 *q++ = ch;
2516 ch = *p++;
2518 if (ch < '0' || ch > '9')
2519 expect("exponent digits");
2520 while (ch >= '0' && ch <= '9') {
2521 if (q >= token_buf + STRING_MAX_SIZE)
2522 goto num_too_long;
2523 *q++ = ch;
2524 ch = *p++;
2527 *q = '\0';
2528 t = toup(ch);
2529 errno = 0;
2530 if (t == 'F') {
2531 ch = *p++;
2532 tok = TOK_CFLOAT;
2533 tokc.f = strtof(token_buf, NULL);
2534 } else if (t == 'L') {
2535 ch = *p++;
2536 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2537 tok = TOK_CDOUBLE;
2538 tokc.d = strtod(token_buf, NULL);
2539 #else
2540 tok = TOK_CLDOUBLE;
2541 tokc.ld = strtold(token_buf, NULL);
2542 #endif
2543 } else {
2544 tok = TOK_CDOUBLE;
2545 tokc.d = strtod(token_buf, NULL);
2548 } else {
2549 unsigned long long n, n1;
2550 int lcount, ucount, ov = 0;
2551 const char *p1;
2553 /* integer number */
2554 *q = '\0';
2555 q = token_buf;
2556 if (b == 10 && *q == '0') {
2557 b = 8;
2558 q++;
2560 n = 0;
2561 while(1) {
2562 t = *q++;
2563 /* no need for checks except for base 10 / 8 errors */
2564 if (t == '\0')
2565 break;
2566 else if (t >= 'a')
2567 t = t - 'a' + 10;
2568 else if (t >= 'A')
2569 t = t - 'A' + 10;
2570 else
2571 t = t - '0';
2572 if (t >= b)
2573 tcc_error("invalid digit");
2574 n1 = n;
2575 n = n * b + t;
2576 /* detect overflow */
2577 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2578 ov = 1;
2581 /* Determine the characteristics (unsigned and/or 64bit) the type of
2582 the constant must have according to the constant suffix(es) */
2583 lcount = ucount = 0;
2584 p1 = p;
2585 for(;;) {
2586 t = toup(ch);
2587 if (t == 'L') {
2588 if (lcount >= 2)
2589 tcc_error("three 'l's in integer constant");
2590 if (lcount && *(p - 1) != ch)
2591 tcc_error("incorrect integer suffix: %s", p1);
2592 lcount++;
2593 ch = *p++;
2594 } else if (t == 'U') {
2595 if (ucount >= 1)
2596 tcc_error("two 'u's in integer constant");
2597 ucount++;
2598 ch = *p++;
2599 } else {
2600 break;
2604 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2605 if (ucount == 0 && b == 10) {
2606 if (lcount <= (LONG_SIZE == 4)) {
2607 if (n >= 0x80000000U)
2608 lcount = (LONG_SIZE == 4) + 1;
2610 if (n >= 0x8000000000000000ULL)
2611 ov = 1, ucount = 1;
2612 } else {
2613 if (lcount <= (LONG_SIZE == 4)) {
2614 if (n >= 0x100000000ULL)
2615 lcount = (LONG_SIZE == 4) + 1;
2616 else if (n >= 0x80000000U)
2617 ucount = 1;
2619 if (n >= 0x8000000000000000ULL)
2620 ucount = 1;
2623 if (ov)
2624 tcc_warning("integer constant overflow");
2626 tok = TOK_CINT;
2627 if (lcount) {
2628 tok = TOK_CLONG;
2629 if (lcount == 2)
2630 tok = TOK_CLLONG;
2632 if (ucount)
2633 ++tok; /* TOK_CU... */
2634 tokc.i = n;
2636 if (ch)
2637 tcc_error("invalid number");
2641 #define PARSE2(c1, tok1, c2, tok2) \
2642 case c1: \
2643 PEEKC(c, p); \
2644 if (c == c2) { \
2645 p++; \
2646 tok = tok2; \
2647 } else { \
2648 tok = tok1; \
2650 break;
2652 /* return next token without macro substitution */
2653 static inline void next_nomacro1(void)
2655 int t, c, is_long, len;
2656 TokenSym *ts;
2657 uint8_t *p, *p1;
2658 unsigned int h;
2660 p = file->buf_ptr;
2661 redo_no_start:
2662 c = *p;
2663 switch(c) {
2664 case ' ':
2665 case '\t':
2666 tok = c;
2667 p++;
2668 maybe_space:
2669 if (parse_flags & PARSE_FLAG_SPACES)
2670 goto keep_tok_flags;
2671 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2672 ++p;
2673 goto redo_no_start;
2674 case '\f':
2675 case '\v':
2676 case '\r':
2677 p++;
2678 goto redo_no_start;
2679 case '\\':
2680 /* first look if it is in fact an end of buffer */
2681 c = handle_stray1(p);
2682 p = file->buf_ptr;
2683 if (c == '\\')
2684 goto parse_simple;
2685 if (c != CH_EOF)
2686 goto redo_no_start;
2688 TCCState *s1 = tcc_state;
2689 if ((parse_flags & PARSE_FLAG_LINEFEED)
2690 && !(tok_flags & TOK_FLAG_EOF)) {
2691 tok_flags |= TOK_FLAG_EOF;
2692 tok = TOK_LINEFEED;
2693 goto keep_tok_flags;
2694 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2695 tok = TOK_EOF;
2696 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2697 tcc_error("missing #endif");
2698 } else if (s1->include_stack_ptr == s1->include_stack) {
2699 /* no include left : end of file. */
2700 tok = TOK_EOF;
2701 } else {
2702 tok_flags &= ~TOK_FLAG_EOF;
2703 /* pop include file */
2705 /* test if previous '#endif' was after a #ifdef at
2706 start of file */
2707 if (tok_flags & TOK_FLAG_ENDIF) {
2708 #ifdef INC_DEBUG
2709 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2710 #endif
2711 search_cached_include(s1, file->filename, 1)
2712 ->ifndef_macro = file->ifndef_macro_saved;
2713 tok_flags &= ~TOK_FLAG_ENDIF;
2716 /* add end of include file debug info */
2717 tcc_debug_eincl(tcc_state);
2718 /* pop include stack */
2719 tcc_close();
2720 s1->include_stack_ptr--;
2721 p = file->buf_ptr;
2722 if (p == file->buffer)
2723 tok_flags = TOK_FLAG_BOF|TOK_FLAG_BOL;
2724 goto redo_no_start;
2727 break;
2729 case '\n':
2730 file->line_num++;
2731 tok_flags |= TOK_FLAG_BOL;
2732 p++;
2733 maybe_newline:
2734 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2735 goto redo_no_start;
2736 tok = TOK_LINEFEED;
2737 goto keep_tok_flags;
2739 case '#':
2740 /* XXX: simplify */
2741 PEEKC(c, p);
2742 if ((tok_flags & TOK_FLAG_BOL) &&
2743 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2744 file->buf_ptr = p;
2745 preprocess(tok_flags & TOK_FLAG_BOF);
2746 p = file->buf_ptr;
2747 goto maybe_newline;
2748 } else {
2749 if (c == '#') {
2750 p++;
2751 tok = TOK_TWOSHARPS;
2752 } else {
2753 #if !defined(TCC_TARGET_ARM)
2754 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2755 p = parse_line_comment(p - 1);
2756 goto redo_no_start;
2757 } else
2758 #endif
2760 tok = '#';
2764 break;
2766 /* dollar is allowed to start identifiers when not parsing asm */
2767 case '$':
2768 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2769 || (parse_flags & PARSE_FLAG_ASM_FILE))
2770 goto parse_simple;
2772 case 'a': case 'b': case 'c': case 'd':
2773 case 'e': case 'f': case 'g': case 'h':
2774 case 'i': case 'j': case 'k': case 'l':
2775 case 'm': case 'n': case 'o': case 'p':
2776 case 'q': case 'r': case 's': case 't':
2777 case 'u': case 'v': case 'w': case 'x':
2778 case 'y': case 'z':
2779 case 'A': case 'B': case 'C': case 'D':
2780 case 'E': case 'F': case 'G': case 'H':
2781 case 'I': case 'J': case 'K':
2782 case 'M': case 'N': case 'O': case 'P':
2783 case 'Q': case 'R': case 'S': case 'T':
2784 case 'U': case 'V': case 'W': case 'X':
2785 case 'Y': case 'Z':
2786 case '_':
2787 parse_ident_fast:
2788 p1 = p;
2789 h = TOK_HASH_INIT;
2790 h = TOK_HASH_FUNC(h, c);
2791 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2792 h = TOK_HASH_FUNC(h, c);
2793 len = p - p1;
2794 if (c != '\\') {
2795 TokenSym **pts;
2797 /* fast case : no stray found, so we have the full token
2798 and we have already hashed it */
2799 h &= (TOK_HASH_SIZE - 1);
2800 pts = &hash_ident[h];
2801 for(;;) {
2802 ts = *pts;
2803 if (!ts)
2804 break;
2805 if (ts->len == len && !memcmp(ts->str, p1, len))
2806 goto token_found;
2807 pts = &(ts->hash_next);
2809 ts = tok_alloc_new(pts, (char *) p1, len);
2810 token_found: ;
2811 } else {
2812 /* slower case */
2813 cstr_reset(&tokcstr);
2814 cstr_cat(&tokcstr, (char *) p1, len);
2815 p--;
2816 PEEKC(c, p);
2817 parse_ident_slow:
2818 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2820 cstr_ccat(&tokcstr, c);
2821 PEEKC(c, p);
2823 ts = tok_alloc(tokcstr.data, tokcstr.size);
2825 tok = ts->tok;
2826 break;
2827 case 'L':
2828 t = p[1];
2829 if (t != '\\' && t != '\'' && t != '\"') {
2830 /* fast case */
2831 goto parse_ident_fast;
2832 } else {
2833 PEEKC(c, p);
2834 if (c == '\'' || c == '\"') {
2835 is_long = 1;
2836 goto str_const;
2837 } else {
2838 cstr_reset(&tokcstr);
2839 cstr_ccat(&tokcstr, 'L');
2840 goto parse_ident_slow;
2843 break;
2845 case '0': case '1': case '2': case '3':
2846 case '4': case '5': case '6': case '7':
2847 case '8': case '9':
2848 t = c;
2849 PEEKC(c, p);
2850 /* after the first digit, accept digits, alpha, '.' or sign if
2851 prefixed by 'eEpP' */
2852 parse_num:
2853 cstr_reset(&tokcstr);
2854 for(;;) {
2855 cstr_ccat(&tokcstr, t);
2856 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2857 || c == '.'
2858 || ((c == '+' || c == '-')
2859 && (((t == 'e' || t == 'E')
2860 && !(parse_flags & PARSE_FLAG_ASM_FILE
2861 /* 0xe+1 is 3 tokens in asm */
2862 && ((char*)tokcstr.data)[0] == '0'
2863 && toup(((char*)tokcstr.data)[1]) == 'X'))
2864 || t == 'p' || t == 'P'))))
2865 break;
2866 t = c;
2867 PEEKC(c, p);
2869 /* We add a trailing '\0' to ease parsing */
2870 cstr_ccat(&tokcstr, '\0');
2871 tokc.str.size = tokcstr.size;
2872 tokc.str.data = tokcstr.data;
2873 tok = TOK_PPNUM;
2874 break;
2876 case '.':
2877 /* special dot handling because it can also start a number */
2878 PEEKC(c, p);
2879 if (isnum(c)) {
2880 t = '.';
2881 goto parse_num;
2882 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2883 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2884 *--p = c = '.';
2885 goto parse_ident_fast;
2886 } else if (c == '.') {
2887 PEEKC(c, p);
2888 if (c == '.') {
2889 p++;
2890 tok = TOK_DOTS;
2891 } else {
2892 *--p = '.'; /* may underflow into file->unget[] */
2893 tok = '.';
2895 } else {
2896 tok = '.';
2898 break;
2899 case '\'':
2900 case '\"':
2901 is_long = 0;
2902 str_const:
2903 cstr_reset(&tokcstr);
2904 if (is_long)
2905 cstr_ccat(&tokcstr, 'L');
2906 cstr_ccat(&tokcstr, c);
2907 p = parse_pp_string(p, c, &tokcstr);
2908 cstr_ccat(&tokcstr, c);
2909 cstr_ccat(&tokcstr, '\0');
2910 tokc.str.size = tokcstr.size;
2911 tokc.str.data = tokcstr.data;
2912 tok = TOK_PPSTR;
2913 break;
2915 case '<':
2916 PEEKC(c, p);
2917 if (c == '=') {
2918 p++;
2919 tok = TOK_LE;
2920 } else if (c == '<') {
2921 PEEKC(c, p);
2922 if (c == '=') {
2923 p++;
2924 tok = TOK_A_SHL;
2925 } else {
2926 tok = TOK_SHL;
2928 } else {
2929 tok = TOK_LT;
2931 break;
2932 case '>':
2933 PEEKC(c, p);
2934 if (c == '=') {
2935 p++;
2936 tok = TOK_GE;
2937 } else if (c == '>') {
2938 PEEKC(c, p);
2939 if (c == '=') {
2940 p++;
2941 tok = TOK_A_SAR;
2942 } else {
2943 tok = TOK_SAR;
2945 } else {
2946 tok = TOK_GT;
2948 break;
2950 case '&':
2951 PEEKC(c, p);
2952 if (c == '&') {
2953 p++;
2954 tok = TOK_LAND;
2955 } else if (c == '=') {
2956 p++;
2957 tok = TOK_A_AND;
2958 } else {
2959 tok = '&';
2961 break;
2963 case '|':
2964 PEEKC(c, p);
2965 if (c == '|') {
2966 p++;
2967 tok = TOK_LOR;
2968 } else if (c == '=') {
2969 p++;
2970 tok = TOK_A_OR;
2971 } else {
2972 tok = '|';
2974 break;
2976 case '+':
2977 PEEKC(c, p);
2978 if (c == '+') {
2979 p++;
2980 tok = TOK_INC;
2981 } else if (c == '=') {
2982 p++;
2983 tok = TOK_A_ADD;
2984 } else {
2985 tok = '+';
2987 break;
2989 case '-':
2990 PEEKC(c, p);
2991 if (c == '-') {
2992 p++;
2993 tok = TOK_DEC;
2994 } else if (c == '=') {
2995 p++;
2996 tok = TOK_A_SUB;
2997 } else if (c == '>') {
2998 p++;
2999 tok = TOK_ARROW;
3000 } else {
3001 tok = '-';
3003 break;
3005 PARSE2('!', '!', '=', TOK_NE)
3006 PARSE2('=', '=', '=', TOK_EQ)
3007 PARSE2('*', '*', '=', TOK_A_MUL)
3008 PARSE2('%', '%', '=', TOK_A_MOD)
3009 PARSE2('^', '^', '=', TOK_A_XOR)
3011 /* comments or operator */
3012 case '/':
3013 PEEKC(c, p);
3014 if (c == '*') {
3015 p = parse_comment(p);
3016 /* comments replaced by a blank */
3017 tok = ' ';
3018 goto maybe_space;
3019 } else if (c == '/') {
3020 p = parse_line_comment(p);
3021 tok = ' ';
3022 goto maybe_space;
3023 } else if (c == '=') {
3024 p++;
3025 tok = TOK_A_DIV;
3026 } else {
3027 tok = '/';
3029 break;
3031 /* simple tokens */
3032 case '(':
3033 case ')':
3034 case '[':
3035 case ']':
3036 case '{':
3037 case '}':
3038 case ',':
3039 case ';':
3040 case ':':
3041 case '?':
3042 case '~':
3043 case '@': /* only used in assembler */
3044 parse_simple:
3045 tok = c;
3046 p++;
3047 break;
3048 default:
3049 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
3050 goto parse_ident_fast;
3051 if (parse_flags & PARSE_FLAG_ASM_FILE)
3052 goto parse_simple;
3053 tcc_error("unrecognized character \\x%02x", c);
3054 break;
3056 tok_flags = 0;
3057 keep_tok_flags:
3058 file->buf_ptr = p;
3059 #if defined(PARSE_DEBUG)
3060 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
3061 #endif
3064 static void macro_subst(
3065 TokenString *tok_str,
3066 Sym **nested_list,
3067 const int *macro_str
3070 /* substitute arguments in replacement lists in macro_str by the values in
3071 args (field d) and return allocated string */
3072 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
3074 int t, t0, t1, spc;
3075 const int *st;
3076 Sym *s;
3077 CValue cval;
3078 TokenString str;
3079 CString cstr;
3081 tok_str_new(&str);
3082 t0 = t1 = 0;
3083 while(1) {
3084 TOK_GET(&t, &macro_str, &cval);
3085 if (!t)
3086 break;
3087 if (t == '#') {
3088 /* stringize */
3089 TOK_GET(&t, &macro_str, &cval);
3090 if (!t)
3091 goto bad_stringy;
3092 s = sym_find2(args, t);
3093 if (s) {
3094 cstr_new(&cstr);
3095 cstr_ccat(&cstr, '\"');
3096 st = s->d;
3097 spc = 0;
3098 while (*st >= 0) {
3099 TOK_GET(&t, &st, &cval);
3100 if (t != TOK_PLCHLDR
3101 && t != TOK_NOSUBST
3102 && 0 == check_space(t, &spc)) {
3103 const char *s = get_tok_str(t, &cval);
3104 while (*s) {
3105 if (t == TOK_PPSTR && *s != '\'')
3106 add_char(&cstr, *s);
3107 else
3108 cstr_ccat(&cstr, *s);
3109 ++s;
3113 cstr.size -= spc;
3114 cstr_ccat(&cstr, '\"');
3115 cstr_ccat(&cstr, '\0');
3116 #ifdef PP_DEBUG
3117 printf("\nstringize: <%s>\n", (char *)cstr.data);
3118 #endif
3119 /* add string */
3120 cval.str.size = cstr.size;
3121 cval.str.data = cstr.data;
3122 tok_str_add2(&str, TOK_PPSTR, &cval);
3123 cstr_free(&cstr);
3124 } else {
3125 bad_stringy:
3126 expect("macro parameter after '#'");
3128 } else if (t >= TOK_IDENT) {
3129 s = sym_find2(args, t);
3130 if (s) {
3131 int l0 = str.len;
3132 st = s->d;
3133 /* if '##' is present before or after, no arg substitution */
3134 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
3135 /* special case for var arg macros : ## eats the ','
3136 if empty VA_ARGS variable. */
3137 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
3138 if (*st <= 0) {
3139 /* suppress ',' '##' */
3140 str.len -= 2;
3141 } else {
3142 /* suppress '##' and add variable */
3143 str.len--;
3144 goto add_var;
3147 } else {
3148 add_var:
3149 if (!s->next) {
3150 /* Expand arguments tokens and store them. In most
3151 cases we could also re-expand each argument if
3152 used multiple times, but not if the argument
3153 contains the __COUNTER__ macro. */
3154 TokenString str2;
3155 sym_push2(&s->next, s->v, s->type.t, 0);
3156 tok_str_new(&str2);
3157 macro_subst(&str2, nested_list, st);
3158 tok_str_add(&str2, 0);
3159 s->next->d = str2.str;
3161 st = s->next->d;
3163 for(;;) {
3164 int t2;
3165 TOK_GET(&t2, &st, &cval);
3166 if (t2 <= 0)
3167 break;
3168 tok_str_add2(&str, t2, &cval);
3170 if (str.len == l0) /* expanded to empty string */
3171 tok_str_add(&str, TOK_PLCHLDR);
3172 } else {
3173 tok_str_add(&str, t);
3175 } else {
3176 tok_str_add2(&str, t, &cval);
3178 t0 = t1, t1 = t;
3180 tok_str_add(&str, 0);
3181 return str.str;
3184 static char const ab_month_name[12][4] =
3186 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3187 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3190 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3192 CString cstr;
3193 int n, ret = 1;
3195 cstr_new(&cstr);
3196 if (t1 != TOK_PLCHLDR)
3197 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3198 n = cstr.size;
3199 if (t2 != TOK_PLCHLDR)
3200 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3201 cstr_ccat(&cstr, '\0');
3203 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3204 memcpy(file->buffer, cstr.data, cstr.size);
3205 tok_flags = 0;
3206 for (;;) {
3207 next_nomacro1();
3208 if (0 == *file->buf_ptr)
3209 break;
3210 if (is_space(tok))
3211 continue;
3212 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3213 " preprocessing token", n, (char *)cstr.data, (char*)cstr.data + n);
3214 ret = 0;
3215 break;
3217 tcc_close();
3218 //printf("paste <%s>\n", (char*)cstr.data);
3219 cstr_free(&cstr);
3220 return ret;
3223 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3224 return the resulting string (which must be freed). */
3225 static inline int *macro_twosharps(const int *ptr0)
3227 int t;
3228 CValue cval;
3229 TokenString macro_str1;
3230 int start_of_nosubsts = -1;
3231 const int *ptr;
3233 /* we search the first '##' */
3234 for (ptr = ptr0;;) {
3235 TOK_GET(&t, &ptr, &cval);
3236 if (t == TOK_PPJOIN)
3237 break;
3238 if (t == 0)
3239 return NULL;
3242 tok_str_new(&macro_str1);
3244 //tok_print(" $$$", ptr0);
3245 for (ptr = ptr0;;) {
3246 TOK_GET(&t, &ptr, &cval);
3247 if (t == 0)
3248 break;
3249 if (t == TOK_PPJOIN)
3250 continue;
3251 while (*ptr == TOK_PPJOIN) {
3252 int t1; CValue cv1;
3253 /* given 'a##b', remove nosubsts preceding 'a' */
3254 if (start_of_nosubsts >= 0)
3255 macro_str1.len = start_of_nosubsts;
3256 /* given 'a##b', remove nosubsts preceding 'b' */
3257 while ((t1 = *++ptr) == TOK_NOSUBST)
3259 if (t1 && t1 != TOK_PPJOIN) {
3260 TOK_GET(&t1, &ptr, &cv1);
3261 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3262 if (paste_tokens(t, &cval, t1, &cv1)) {
3263 t = tok, cval = tokc;
3264 } else {
3265 tok_str_add2(&macro_str1, t, &cval);
3266 t = t1, cval = cv1;
3271 if (t == TOK_NOSUBST) {
3272 if (start_of_nosubsts < 0)
3273 start_of_nosubsts = macro_str1.len;
3274 } else {
3275 start_of_nosubsts = -1;
3277 tok_str_add2(&macro_str1, t, &cval);
3279 tok_str_add(&macro_str1, 0);
3280 //tok_print(" ###", macro_str1.str);
3281 return macro_str1.str;
3284 /* peek or read [ws_str == NULL] next token from function macro call,
3285 walking up macro levels up to the file if necessary */
3286 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3288 int t;
3289 const int *p;
3290 Sym *sa;
3292 for (;;) {
3293 if (macro_ptr) {
3294 p = macro_ptr, t = *p;
3295 if (ws_str) {
3296 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3297 tok_str_add(ws_str, t), t = *++p;
3299 if (t == 0) {
3300 end_macro();
3301 /* also, end of scope for nested defined symbol */
3302 sa = *nested_list;
3303 while (sa && sa->v == 0)
3304 sa = sa->prev;
3305 if (sa)
3306 sa->v = 0;
3307 continue;
3309 } else {
3310 ch = handle_eob();
3311 if (ws_str) {
3312 while (is_space(ch) || ch == '\n' || ch == '/') {
3313 if (ch == '/') {
3314 int c;
3315 uint8_t *p = file->buf_ptr;
3316 PEEKC(c, p);
3317 if (c == '*') {
3318 p = parse_comment(p);
3319 file->buf_ptr = p - 1;
3320 } else if (c == '/') {
3321 p = parse_line_comment(p);
3322 file->buf_ptr = p - 1;
3323 } else
3324 break;
3325 ch = ' ';
3327 if (ch == '\n')
3328 file->line_num++;
3329 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3330 tok_str_add(ws_str, ch);
3331 cinp();
3334 t = ch;
3337 if (ws_str)
3338 return t;
3339 next_nomacro();
3340 return tok;
3344 /* do macro substitution of current token with macro 's' and add
3345 result to (tok_str,tok_len). 'nested_list' is the list of all
3346 macros we got inside to avoid recursing. Return non zero if no
3347 substitution needs to be done */
3348 static int macro_subst_tok(
3349 TokenString *tok_str,
3350 Sym **nested_list,
3351 Sym *s)
3353 Sym *args, *sa, *sa1;
3354 int parlevel, t, t1, spc;
3355 TokenString str;
3356 char *cstrval;
3357 CValue cval;
3358 CString cstr;
3359 char buf[32];
3361 /* if symbol is a macro, prepare substitution */
3362 /* special macros */
3363 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3364 t = tok == TOK___LINE__ ? file->line_num : pp_counter++;
3365 snprintf(buf, sizeof(buf), "%d", t);
3366 cstrval = buf;
3367 t1 = TOK_PPNUM;
3368 goto add_cstr1;
3369 } else if (tok == TOK___FILE__) {
3370 cstrval = file->filename;
3371 goto add_cstr;
3372 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3373 time_t ti;
3374 struct tm *tm;
3376 time(&ti);
3377 tm = localtime(&ti);
3378 if (tok == TOK___DATE__) {
3379 snprintf(buf, sizeof(buf), "%s %2d %d",
3380 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3381 } else {
3382 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3383 tm->tm_hour, tm->tm_min, tm->tm_sec);
3385 cstrval = buf;
3386 add_cstr:
3387 t1 = TOK_STR;
3388 add_cstr1:
3389 cstr_new(&cstr);
3390 cstr_cat(&cstr, cstrval, 0);
3391 cval.str.size = cstr.size;
3392 cval.str.data = cstr.data;
3393 tok_str_add2(tok_str, t1, &cval);
3394 cstr_free(&cstr);
3395 } else if (s->d) {
3396 int saved_parse_flags = parse_flags;
3397 int *joined_str = NULL;
3398 int *mstr = s->d;
3400 if (s->type.t == MACRO_FUNC) {
3401 /* whitespace between macro name and argument list */
3402 TokenString ws_str;
3403 tok_str_new(&ws_str);
3405 spc = 0;
3406 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3407 | PARSE_FLAG_ACCEPT_STRAYS;
3409 /* get next token from argument stream */
3410 t = next_argstream(nested_list, &ws_str);
3411 if (t != '(') {
3412 /* not a macro substitution after all, restore the
3413 * macro token plus all whitespace we've read.
3414 * whitespace is intentionally not merged to preserve
3415 * newlines. */
3416 parse_flags = saved_parse_flags;
3417 tok_str_add(tok_str, tok);
3418 if (parse_flags & PARSE_FLAG_SPACES) {
3419 int i;
3420 for (i = 0; i < ws_str.len; i++)
3421 tok_str_add(tok_str, ws_str.str[i]);
3423 tok_str_free_str(ws_str.str);
3424 return 0;
3425 } else {
3426 tok_str_free_str(ws_str.str);
3428 do {
3429 next_nomacro(); /* eat '(' */
3430 } while (tok == TOK_PLCHLDR || is_space(tok));
3432 /* argument macro */
3433 args = NULL;
3434 sa = s->next;
3435 /* NOTE: empty args are allowed, except if no args */
3436 for(;;) {
3437 do {
3438 next_argstream(nested_list, NULL);
3439 } while (tok == TOK_PLCHLDR || is_space(tok) ||
3440 TOK_LINEFEED == tok);
3441 empty_arg:
3442 /* handle '()' case */
3443 if (!args && !sa && tok == ')')
3444 break;
3445 if (!sa)
3446 tcc_error("macro '%s' used with too many args",
3447 get_tok_str(s->v, 0));
3448 tok_str_new(&str);
3449 parlevel = spc = 0;
3450 /* NOTE: non zero sa->t indicates VA_ARGS */
3451 while ((parlevel > 0 ||
3452 (tok != ')' &&
3453 (tok != ',' || sa->type.t)))) {
3454 if (tok == TOK_EOF || tok == 0)
3455 break;
3456 if (tok == '(')
3457 parlevel++;
3458 else if (tok == ')')
3459 parlevel--;
3460 if (tok == TOK_LINEFEED)
3461 tok = ' ';
3462 if (!check_space(tok, &spc))
3463 tok_str_add2(&str, tok, &tokc);
3464 next_argstream(nested_list, NULL);
3466 if (parlevel)
3467 expect(")");
3468 str.len -= spc;
3469 tok_str_add(&str, -1);
3470 tok_str_add(&str, 0);
3471 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3472 sa1->d = str.str;
3473 sa = sa->next;
3474 if (tok == ')') {
3475 /* special case for gcc var args: add an empty
3476 var arg argument if it is omitted */
3477 if (sa && sa->type.t && gnu_ext)
3478 goto empty_arg;
3479 break;
3481 if (tok != ',')
3482 expect(",");
3484 if (sa) {
3485 tcc_error("macro '%s' used with too few args",
3486 get_tok_str(s->v, 0));
3489 /* now subst each arg */
3490 mstr = macro_arg_subst(nested_list, mstr, args);
3491 /* free memory */
3492 sa = args;
3493 while (sa) {
3494 sa1 = sa->prev;
3495 tok_str_free_str(sa->d);
3496 if (sa->next) {
3497 tok_str_free_str(sa->next->d);
3498 sym_free(sa->next);
3500 sym_free(sa);
3501 sa = sa1;
3503 parse_flags = saved_parse_flags;
3506 sym_push2(nested_list, s->v, 0, 0);
3507 parse_flags = saved_parse_flags;
3508 joined_str = macro_twosharps(mstr);
3509 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3511 /* pop nested defined symbol */
3512 sa1 = *nested_list;
3513 *nested_list = sa1->prev;
3514 sym_free(sa1);
3515 if (joined_str)
3516 tok_str_free_str(joined_str);
3517 if (mstr != s->d)
3518 tok_str_free_str(mstr);
3520 return 0;
3523 /* do macro substitution of macro_str and add result to
3524 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3525 inside to avoid recursing. */
3526 static void macro_subst(
3527 TokenString *tok_str,
3528 Sym **nested_list,
3529 const int *macro_str
3532 Sym *s;
3533 int t, spc, nosubst;
3534 CValue cval;
3536 spc = nosubst = 0;
3538 while (1) {
3539 TOK_GET(&t, &macro_str, &cval);
3540 if (t <= 0)
3541 break;
3543 if (t >= TOK_IDENT && 0 == nosubst) {
3544 s = define_find(t);
3545 if (s == NULL)
3546 goto no_subst;
3548 /* if nested substitution, do nothing */
3549 if (sym_find2(*nested_list, t)) {
3550 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3551 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3552 goto no_subst;
3556 TokenString *str = tok_str_alloc();
3557 str->str = (int*)macro_str;
3558 begin_macro(str, 2);
3560 tok = t;
3561 macro_subst_tok(tok_str, nested_list, s);
3563 if (macro_stack != str) {
3564 /* already finished by reading function macro arguments */
3565 break;
3568 macro_str = macro_ptr;
3569 end_macro ();
3571 if (tok_str->len)
3572 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3573 } else {
3574 no_subst:
3575 if (!check_space(t, &spc))
3576 tok_str_add2(tok_str, t, &cval);
3578 if (nosubst) {
3579 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3580 continue;
3581 nosubst = 0;
3583 if (t == TOK_NOSUBST)
3584 nosubst = 1;
3586 /* GCC supports 'defined' as result of a macro substitution */
3587 if (t == TOK_DEFINED && pp_expr)
3588 nosubst = 2;
3592 /* return next token without macro substitution. Can read input from
3593 macro_ptr buffer */
3594 static void next_nomacro(void)
3596 int t;
3597 if (macro_ptr) {
3598 redo:
3599 t = *macro_ptr;
3600 if (TOK_HAS_VALUE(t)) {
3601 tok_get(&tok, &macro_ptr, &tokc);
3602 if (t == TOK_LINENUM) {
3603 file->line_num = tokc.i;
3604 goto redo;
3606 } else {
3607 macro_ptr++;
3608 if (t < TOK_IDENT) {
3609 if (!(parse_flags & PARSE_FLAG_SPACES)
3610 && (isidnum_table[t - CH_EOF] & IS_SPC))
3611 goto redo;
3613 tok = t;
3615 } else {
3616 next_nomacro1();
3620 /* return next token with macro substitution */
3621 ST_FUNC void next(void)
3623 int t;
3624 redo:
3625 next_nomacro();
3626 t = tok;
3627 if (macro_ptr) {
3628 if (!TOK_HAS_VALUE(t)) {
3629 if (t == TOK_NOSUBST || t == TOK_PLCHLDR) {
3630 /* discard preprocessor markers */
3631 goto redo;
3632 } else if (t == 0) {
3633 /* end of macro or unget token string */
3634 end_macro();
3635 goto redo;
3636 } else if (t == '\\') {
3637 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3638 tcc_error("stray '\\' in program");
3640 return;
3642 } else if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3643 /* if reading from file, try to substitute macros */
3644 Sym *s = define_find(t);
3645 if (s) {
3646 Sym *nested_list = NULL;
3647 tokstr_buf.len = 0;
3648 macro_subst_tok(&tokstr_buf, &nested_list, s);
3649 tok_str_add(&tokstr_buf, 0);
3650 begin_macro(&tokstr_buf, 0);
3651 goto redo;
3653 return;
3655 /* convert preprocessor tokens into C tokens */
3656 if (t == TOK_PPNUM) {
3657 if (parse_flags & PARSE_FLAG_TOK_NUM)
3658 parse_number((char *)tokc.str.data);
3659 } else if (t == TOK_PPSTR) {
3660 if (parse_flags & PARSE_FLAG_TOK_STR)
3661 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3665 /* push back current token and set current token to 'last_tok'. Only
3666 identifier case handled for labels. */
3667 ST_INLN void unget_tok(int last_tok)
3670 TokenString *str = tok_str_alloc();
3671 tok_str_add2(str, tok, &tokc);
3672 tok_str_add(str, 0);
3673 begin_macro(str, 1);
3674 tok = last_tok;
3677 /* ------------------------------------------------------------------------- */
3678 /* init preprocessor */
3680 static const char * const target_os_defs =
3681 #ifdef TCC_TARGET_PE
3682 "_WIN32\0"
3683 # if PTR_SIZE == 8
3684 "_WIN64\0"
3685 # endif
3686 #else
3687 # if defined TCC_TARGET_MACHO
3688 "__APPLE__\0"
3689 # elif TARGETOS_FreeBSD
3690 "__FreeBSD__ 12\0"
3691 # elif TARGETOS_FreeBSD_kernel
3692 "__FreeBSD_kernel__\0"
3693 # elif TARGETOS_NetBSD
3694 "__NetBSD__\0"
3695 # elif TARGETOS_OpenBSD
3696 "__OpenBSD__\0"
3697 # else
3698 "__linux__\0"
3699 "__linux\0"
3700 # endif
3701 "__unix__\0"
3702 "__unix\0"
3703 #endif
3706 static void putdef(CString *cs, const char *p)
3708 cstr_printf(cs, "#define %s%s\n", p, &" 1"[!!strchr(p, ' ')*2]);
3711 static void tcc_predefs(TCCState *s1, CString *cs, int is_asm)
3713 int a, b, c;
3714 const char *defs[] = { target_machine_defs, target_os_defs, NULL };
3715 const char *p;
3717 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
3718 cstr_printf(cs, "#define __TINYC__ %d\n", a*10000 + b*100 + c);
3719 for (a = 0; defs[a]; ++a)
3720 for (p = defs[a]; *p; p = strchr(p, 0) + 1)
3721 putdef(cs, p);
3722 #ifdef TCC_TARGET_ARM
3723 if (s1->float_abi == ARM_HARD_FLOAT)
3724 putdef(cs, "__ARM_PCS_VFP");
3725 #endif
3726 if (is_asm)
3727 putdef(cs, "__ASSEMBLER__");
3728 if (s1->output_type == TCC_OUTPUT_PREPROCESS)
3729 putdef(cs, "__TCC_PP__");
3730 if (s1->output_type == TCC_OUTPUT_MEMORY)
3731 putdef(cs, "__TCC_RUN__");
3732 if (s1->char_is_unsigned)
3733 putdef(cs, "__CHAR_UNSIGNED__");
3734 if (s1->optimize > 0)
3735 putdef(cs, "__OPTIMIZE__");
3736 if (s1->optimize == 's')
3737 putdef(cs, "__OPTIMIZE_SIZE__");
3738 if (s1->option_pthread)
3739 putdef(cs, "_REENTRANT");
3740 if (s1->leading_underscore)
3741 putdef(cs, "__leading_underscore");
3742 #ifdef CONFIG_TCC_BCHECK
3743 if (s1->do_bounds_check)
3744 putdef(cs, "__BOUNDS_CHECKING_ON");
3745 #endif
3746 cstr_printf(cs, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE);
3747 cstr_printf(cs, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE);
3748 if (!is_asm) {
3749 putdef(cs, "__STDC__");
3750 cstr_printf(cs, "#define __STDC_VERSION__ %dL\n", s1->cversion);
3751 cstr_cat(cs,
3752 /* load more predefs and __builtins */
3753 #if CONFIG_TCC_PREDEFS
3754 #include "tccdefs_.h" /* include as strings */
3755 #else
3756 "#include <tccdefs.h>\n" /* load at runtime */
3757 #endif
3758 , -1);
3760 cstr_printf(cs, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3763 ST_FUNC void preprocess_start(TCCState *s1, int filetype)
3765 int is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
3766 CString cstr;
3768 tccpp_new(s1);
3770 s1->include_stack_ptr = s1->include_stack;
3771 s1->ifdef_stack_ptr = s1->ifdef_stack;
3772 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3773 pp_expr = 0;
3774 pp_counter = 0;
3775 pp_debug_tok = pp_debug_symv = 0;
3776 pp_once++;
3777 s1->pack_stack[0] = 0;
3778 s1->pack_stack_ptr = s1->pack_stack;
3780 set_idnum('$', !is_asm && s1->dollars_in_identifiers ? IS_ID : 0);
3781 set_idnum('.', is_asm ? IS_ID : 0);
3783 if (!(filetype & AFF_TYPE_ASM)) {
3784 cstr_new(&cstr);
3785 tcc_predefs(s1, &cstr, is_asm);
3786 if (s1->cmdline_defs.size)
3787 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3788 if (s1->cmdline_incl.size)
3789 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3790 //printf("%s\n", (char*)cstr.data);
3791 *s1->include_stack_ptr++ = file;
3792 tcc_open_bf(s1, "<command line>", cstr.size);
3793 memcpy(file->buffer, cstr.data, cstr.size);
3794 cstr_free(&cstr);
3797 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3798 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3801 /* cleanup from error/setjmp */
3802 ST_FUNC void preprocess_end(TCCState *s1)
3804 while (macro_stack)
3805 end_macro();
3806 macro_ptr = NULL;
3807 while (file)
3808 tcc_close();
3809 tccpp_delete(s1);
3812 ST_FUNC void tccpp_new(TCCState *s)
3814 int i, c;
3815 const char *p, *r;
3817 /* init isid table */
3818 for(i = CH_EOF; i<128; i++)
3819 set_idnum(i,
3820 is_space(i) ? IS_SPC
3821 : isid(i) ? IS_ID
3822 : isnum(i) ? IS_NUM
3823 : 0);
3825 for(i = 128; i<256; i++)
3826 set_idnum(i, IS_ID);
3828 /* init allocators */
3829 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3830 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3832 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3833 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3835 cstr_new(&cstr_buf);
3836 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3837 tok_str_new(&tokstr_buf);
3838 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3840 tok_ident = TOK_IDENT;
3841 p = tcc_keywords;
3842 while (*p) {
3843 r = p;
3844 for(;;) {
3845 c = *r++;
3846 if (c == '\0')
3847 break;
3849 tok_alloc(p, r - p - 1);
3850 p = r;
3853 /* we add dummy defines for some special macros to speed up tests
3854 and to have working defined() */
3855 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3856 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3857 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3858 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3859 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3862 ST_FUNC void tccpp_delete(TCCState *s)
3864 int i, n;
3866 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3868 /* free tokens */
3869 n = tok_ident - TOK_IDENT;
3870 if (n > total_idents)
3871 total_idents = n;
3872 for(i = 0; i < n; i++)
3873 tal_free(toksym_alloc, table_ident[i]);
3874 tcc_free(table_ident);
3875 table_ident = NULL;
3877 /* free static buffers */
3878 cstr_free(&tokcstr);
3879 cstr_free(&cstr_buf);
3880 cstr_free(&macro_equal_buf);
3881 tok_str_free_str(tokstr_buf.str);
3883 /* free allocators */
3884 tal_delete(toksym_alloc);
3885 toksym_alloc = NULL;
3886 tal_delete(tokstr_alloc);
3887 tokstr_alloc = NULL;
3890 /* ------------------------------------------------------------------------- */
3891 /* tcc -E [-P[1]] [-dD} support */
3893 static void tok_print(const char *msg, const int *str)
3895 FILE *fp;
3896 int t, s = 0;
3897 CValue cval;
3899 fp = tcc_state->ppfp;
3900 fprintf(fp, "%s", msg);
3901 while (str) {
3902 TOK_GET(&t, &str, &cval);
3903 if (!t)
3904 break;
3905 fprintf(fp, &" %s"[s], get_tok_str(t, &cval)), s = 1;
3907 fprintf(fp, "\n");
3910 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3912 int d = f->line_num - f->line_ref;
3914 if (s1->dflag & 4)
3915 return;
3917 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3919 } else if (level == 0 && f->line_ref && d < 8) {
3920 while (d > 0)
3921 fputs("\n", s1->ppfp), --d;
3922 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3923 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3924 } else {
3925 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3926 level > 0 ? " 1" : level < 0 ? " 2" : "");
3928 f->line_ref = f->line_num;
3931 static void define_print(TCCState *s1, int v)
3933 FILE *fp;
3934 Sym *s;
3936 s = define_find(v);
3937 if (NULL == s || NULL == s->d)
3938 return;
3940 fp = s1->ppfp;
3941 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3942 if (s->type.t == MACRO_FUNC) {
3943 Sym *a = s->next;
3944 fprintf(fp,"(");
3945 if (a)
3946 for (;;) {
3947 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3948 if (!(a = a->next))
3949 break;
3950 fprintf(fp,",");
3952 fprintf(fp,")");
3954 tok_print("", s->d);
3957 static void pp_debug_defines(TCCState *s1)
3959 int v, t;
3960 const char *vs;
3961 FILE *fp;
3963 t = pp_debug_tok;
3964 if (t == 0)
3965 return;
3967 file->line_num--;
3968 pp_line(s1, file, 0);
3969 file->line_ref = ++file->line_num;
3971 fp = s1->ppfp;
3972 v = pp_debug_symv;
3973 vs = get_tok_str(v, NULL);
3974 if (t == TOK_DEFINE) {
3975 define_print(s1, v);
3976 } else if (t == TOK_UNDEF) {
3977 fprintf(fp, "#undef %s\n", vs);
3978 } else if (t == TOK_push_macro) {
3979 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3980 } else if (t == TOK_pop_macro) {
3981 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3983 pp_debug_tok = 0;
3986 static void pp_debug_builtins(TCCState *s1)
3988 int v;
3989 for (v = TOK_IDENT; v < tok_ident; ++v)
3990 define_print(s1, v);
3993 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3994 static int pp_need_space(int a, int b)
3996 return 'E' == a ? '+' == b || '-' == b
3997 : '+' == a ? TOK_INC == b || '+' == b
3998 : '-' == a ? TOK_DEC == b || '-' == b
3999 : a >= TOK_IDENT ? b >= TOK_IDENT
4000 : a == TOK_PPNUM ? b >= TOK_IDENT
4001 : 0;
4004 /* maybe hex like 0x1e */
4005 static int pp_check_he0xE(int t, const char *p)
4007 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
4008 return 'E';
4009 return t;
4012 /* Preprocess the current file */
4013 ST_FUNC int tcc_preprocess(TCCState *s1)
4015 BufferedFile **iptr;
4016 int token_seen, spcs, level;
4017 const char *p;
4018 char white[400];
4020 parse_flags = PARSE_FLAG_PREPROCESS
4021 | (parse_flags & PARSE_FLAG_ASM_FILE)
4022 | PARSE_FLAG_LINEFEED
4023 | PARSE_FLAG_SPACES
4024 | PARSE_FLAG_ACCEPT_STRAYS
4026 /* Credits to Fabrice Bellard's initial revision to demonstrate its
4027 capability to compile and run itself, provided all numbers are
4028 given as decimals. tcc -E -P10 will do. */
4029 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
4030 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
4032 if (s1->do_bench) {
4033 /* for PP benchmarks */
4034 do next(); while (tok != TOK_EOF);
4035 return 0;
4038 if (s1->dflag & 1) {
4039 pp_debug_builtins(s1);
4040 s1->dflag &= ~1;
4043 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
4044 if (file->prev)
4045 pp_line(s1, file->prev, level++);
4046 pp_line(s1, file, level);
4047 for (;;) {
4048 iptr = s1->include_stack_ptr;
4049 next();
4050 if (tok == TOK_EOF)
4051 break;
4053 level = s1->include_stack_ptr - iptr;
4054 if (level) {
4055 if (level > 0)
4056 pp_line(s1, *iptr, 0);
4057 pp_line(s1, file, level);
4059 if (s1->dflag & 7) {
4060 pp_debug_defines(s1);
4061 if (s1->dflag & 4)
4062 continue;
4065 if (is_space(tok)) {
4066 if (spcs < sizeof white - 1)
4067 white[spcs++] = tok;
4068 continue;
4069 } else if (tok == TOK_LINEFEED) {
4070 spcs = 0;
4071 if (token_seen == TOK_LINEFEED)
4072 continue;
4073 ++file->line_ref;
4074 } else if (token_seen == TOK_LINEFEED) {
4075 pp_line(s1, file, 0);
4076 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
4077 white[spcs++] = ' ';
4080 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
4081 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
4082 token_seen = pp_check_he0xE(tok, p);
4084 return 0;
4087 /* ------------------------------------------------------------------------- */