#pragma comment(option,"-..."), bitfields test, etc...
[tinycc.git] / tccpp.c
blob0e46510dcf48d64ce024976382b69ff543a2821c
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 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 ST_DATA int tok_flags;
27 ST_DATA int parse_flags;
29 ST_DATA struct BufferedFile *file;
30 ST_DATA int ch, tok;
31 ST_DATA CValue tokc;
32 ST_DATA const int *macro_ptr;
33 ST_DATA CString tokcstr; /* current parsed string, if any */
35 /* display benchmark infos */
36 ST_DATA int total_lines;
37 ST_DATA int total_bytes;
38 ST_DATA int tok_ident;
39 ST_DATA TokenSym **table_ident;
41 /* ------------------------------------------------------------------------- */
43 static TokenSym *hash_ident[TOK_HASH_SIZE];
44 static char token_buf[STRING_MAX_SIZE + 1];
45 static CString cstr_buf;
46 static CString macro_equal_buf;
47 static TokenString tokstr_buf;
48 static unsigned char isidnum_table[256 - CH_EOF];
49 static int pp_debug_tok, pp_debug_symv;
50 static int pp_once;
51 static int pp_expr;
52 static void tok_print(const char *msg, const int *str);
54 static struct TinyAlloc *toksym_alloc;
55 static struct TinyAlloc *tokstr_alloc;
56 static struct TinyAlloc *cstr_alloc;
58 static TokenString *macro_stack;
60 static const char tcc_keywords[] =
61 #define DEF(id, str) str "\0"
62 #include "tcctok.h"
63 #undef DEF
66 /* WARNING: the content of this string encodes token numbers */
67 static const unsigned char tok_two_chars[] =
68 /* outdated -- gr
69 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
70 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
71 */{
72 '<','=', TOK_LE,
73 '>','=', TOK_GE,
74 '!','=', TOK_NE,
75 '&','&', TOK_LAND,
76 '|','|', TOK_LOR,
77 '+','+', TOK_INC,
78 '-','-', TOK_DEC,
79 '=','=', TOK_EQ,
80 '<','<', TOK_SHL,
81 '>','>', TOK_SAR,
82 '+','=', TOK_A_ADD,
83 '-','=', TOK_A_SUB,
84 '*','=', TOK_A_MUL,
85 '/','=', TOK_A_DIV,
86 '%','=', TOK_A_MOD,
87 '&','=', TOK_A_AND,
88 '^','=', TOK_A_XOR,
89 '|','=', TOK_A_OR,
90 '-','>', TOK_ARROW,
91 '.','.', 0xa8, // C++ token ?
92 '#','#', TOK_TWOSHARPS,
96 static void next_nomacro_spc(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 + adj_size + sizeof(tal_header_t) < al->buffer + 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 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 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 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 = tal_realloc(cstr_alloc, cstr->data, size);
334 cstr->size_allocated = size;
337 /* add a byte */
338 ST_INLN void cstr_ccat(CString *cstr, int ch)
340 int size;
341 size = cstr->size + 1;
342 if (size > cstr->size_allocated)
343 cstr_realloc(cstr, size);
344 ((unsigned char *)cstr->data)[size - 1] = ch;
345 cstr->size = size;
348 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
350 int size;
351 if (len <= 0)
352 len = strlen(str) + 1 + len;
353 size = cstr->size + len;
354 if (size > cstr->size_allocated)
355 cstr_realloc(cstr, size);
356 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
357 cstr->size = size;
360 /* add a wide char */
361 ST_FUNC void cstr_wccat(CString *cstr, int ch)
363 int size;
364 size = cstr->size + sizeof(nwchar_t);
365 if (size > cstr->size_allocated)
366 cstr_realloc(cstr, size);
367 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
368 cstr->size = size;
371 ST_FUNC void cstr_new(CString *cstr)
373 memset(cstr, 0, sizeof(CString));
376 /* free string and reset it to NULL */
377 ST_FUNC void cstr_free(CString *cstr)
379 tal_free(cstr_alloc, cstr->data);
380 cstr_new(cstr);
383 /* reset string to empty */
384 ST_FUNC void cstr_reset(CString *cstr)
386 cstr->size = 0;
389 /* XXX: unicode ? */
390 static void add_char(CString *cstr, int c)
392 if (c == '\'' || c == '\"' || c == '\\') {
393 /* XXX: could be more precise if char or string */
394 cstr_ccat(cstr, '\\');
396 if (c >= 32 && c <= 126) {
397 cstr_ccat(cstr, c);
398 } else {
399 cstr_ccat(cstr, '\\');
400 if (c == '\n') {
401 cstr_ccat(cstr, 'n');
402 } else {
403 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
404 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
405 cstr_ccat(cstr, '0' + (c & 7));
410 /* ------------------------------------------------------------------------- */
411 /* allocate a new token */
412 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
414 TokenSym *ts, **ptable;
415 int i;
417 if (tok_ident >= SYM_FIRST_ANOM)
418 tcc_error("memory full (symbols)");
420 /* expand token table if needed */
421 i = tok_ident - TOK_IDENT;
422 if ((i % TOK_ALLOC_INCR) == 0) {
423 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
424 table_ident = ptable;
427 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
428 table_ident[i] = ts;
429 ts->tok = tok_ident++;
430 ts->sym_define = NULL;
431 ts->sym_label = NULL;
432 ts->sym_struct = NULL;
433 ts->sym_identifier = NULL;
434 ts->len = len;
435 ts->hash_next = NULL;
436 memcpy(ts->str, str, len);
437 ts->str[len] = '\0';
438 *pts = ts;
439 return ts;
442 #define TOK_HASH_INIT 1
443 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
446 /* find a token and add it if not found */
447 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
449 TokenSym *ts, **pts;
450 int i;
451 unsigned int h;
453 h = TOK_HASH_INIT;
454 for(i=0;i<len;i++)
455 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
456 h &= (TOK_HASH_SIZE - 1);
458 pts = &hash_ident[h];
459 for(;;) {
460 ts = *pts;
461 if (!ts)
462 break;
463 if (ts->len == len && !memcmp(ts->str, str, len))
464 return ts;
465 pts = &(ts->hash_next);
467 return tok_alloc_new(pts, str, len);
470 /* XXX: buffer overflow */
471 /* XXX: float tokens */
472 ST_FUNC const char *get_tok_str(int v, CValue *cv)
474 char *p;
475 int i, len;
477 cstr_reset(&cstr_buf);
478 p = cstr_buf.data;
480 switch(v) {
481 case TOK_CINT:
482 case TOK_CUINT:
483 case TOK_CLLONG:
484 case TOK_CULLONG:
485 /* XXX: not quite exact, but only useful for testing */
486 #ifdef _WIN32
487 sprintf(p, "%u", (unsigned)cv->i);
488 #else
489 sprintf(p, "%llu", (unsigned long long)cv->i);
490 #endif
491 break;
492 case TOK_LCHAR:
493 cstr_ccat(&cstr_buf, 'L');
494 case TOK_CCHAR:
495 cstr_ccat(&cstr_buf, '\'');
496 add_char(&cstr_buf, cv->i);
497 cstr_ccat(&cstr_buf, '\'');
498 cstr_ccat(&cstr_buf, '\0');
499 break;
500 case TOK_PPNUM:
501 case TOK_PPSTR:
502 return (char*)cv->str.data;
503 case TOK_LSTR:
504 cstr_ccat(&cstr_buf, 'L');
505 case TOK_STR:
506 cstr_ccat(&cstr_buf, '\"');
507 if (v == TOK_STR) {
508 len = cv->str.size - 1;
509 for(i=0;i<len;i++)
510 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
511 } else {
512 len = (cv->str.size / sizeof(nwchar_t)) - 1;
513 for(i=0;i<len;i++)
514 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
516 cstr_ccat(&cstr_buf, '\"');
517 cstr_ccat(&cstr_buf, '\0');
518 break;
520 case TOK_CFLOAT:
521 cstr_cat(&cstr_buf, "<float>", 0);
522 break;
523 case TOK_CDOUBLE:
524 cstr_cat(&cstr_buf, "<double>", 0);
525 break;
526 case TOK_CLDOUBLE:
527 cstr_cat(&cstr_buf, "<long double>", 0);
528 break;
529 case TOK_LINENUM:
530 cstr_cat(&cstr_buf, "<linenumber>", 0);
531 break;
533 /* above tokens have value, the ones below don't */
534 case TOK_LT:
535 v = '<';
536 goto addv;
537 case TOK_GT:
538 v = '>';
539 goto addv;
540 case TOK_DOTS:
541 return strcpy(p, "...");
542 case TOK_A_SHL:
543 return strcpy(p, "<<=");
544 case TOK_A_SAR:
545 return strcpy(p, ">>=");
546 case TOK_EOF:
547 return strcpy(p, "<eof>");
548 default:
549 if (v < TOK_IDENT) {
550 /* search in two bytes table */
551 const unsigned char *q = tok_two_chars;
552 while (*q) {
553 if (q[2] == v) {
554 *p++ = q[0];
555 *p++ = q[1];
556 *p = '\0';
557 return cstr_buf.data;
559 q += 3;
561 if (v >= 127) {
562 sprintf(cstr_buf.data, "<%02x>", v);
563 return cstr_buf.data;
565 addv:
566 *p++ = v;
567 *p = '\0';
568 } else if (v < tok_ident) {
569 return table_ident[v - TOK_IDENT]->str;
570 } else if (v >= SYM_FIRST_ANOM) {
571 /* special name for anonymous symbol */
572 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
573 } else {
574 /* should never happen */
575 return NULL;
577 break;
579 return cstr_buf.data;
582 /* return the current character, handling end of block if necessary
583 (but not stray) */
584 ST_FUNC int handle_eob(void)
586 BufferedFile *bf = file;
587 int len;
589 /* only tries to read if really end of buffer */
590 if (bf->buf_ptr >= bf->buf_end) {
591 if (bf->fd != -1) {
592 #if defined(PARSE_DEBUG)
593 len = 1;
594 #else
595 len = IO_BUF_SIZE;
596 #endif
597 len = read(bf->fd, bf->buffer, len);
598 if (len < 0)
599 len = 0;
600 } else {
601 len = 0;
603 total_bytes += len;
604 bf->buf_ptr = bf->buffer;
605 bf->buf_end = bf->buffer + len;
606 *bf->buf_end = CH_EOB;
608 if (bf->buf_ptr < bf->buf_end) {
609 return bf->buf_ptr[0];
610 } else {
611 bf->buf_ptr = bf->buf_end;
612 return CH_EOF;
616 /* read next char from current input file and handle end of input buffer */
617 ST_INLN void inp(void)
619 ch = *(++(file->buf_ptr));
620 /* end of buffer/file handling */
621 if (ch == CH_EOB)
622 ch = handle_eob();
625 /* handle '\[\r]\n' */
626 static int handle_stray_noerror(void)
628 while (ch == '\\') {
629 inp();
630 if (ch == '\n') {
631 file->line_num++;
632 inp();
633 } else if (ch == '\r') {
634 inp();
635 if (ch != '\n')
636 goto fail;
637 file->line_num++;
638 inp();
639 } else {
640 fail:
641 return 1;
644 return 0;
647 static void handle_stray(void)
649 if (handle_stray_noerror())
650 tcc_error("stray '\\' in program");
653 /* skip the stray and handle the \\n case. Output an error if
654 incorrect char after the stray */
655 static int handle_stray1(uint8_t *p)
657 int c;
659 file->buf_ptr = p;
660 if (p >= file->buf_end) {
661 c = handle_eob();
662 if (c != '\\')
663 return c;
664 p = file->buf_ptr;
666 ch = *p;
667 if (handle_stray_noerror()) {
668 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
669 tcc_error("stray '\\' in program");
670 *--file->buf_ptr = '\\';
672 p = file->buf_ptr;
673 c = *p;
674 return c;
677 /* handle just the EOB case, but not stray */
678 #define PEEKC_EOB(c, p)\
680 p++;\
681 c = *p;\
682 if (c == '\\') {\
683 file->buf_ptr = p;\
684 c = handle_eob();\
685 p = file->buf_ptr;\
689 /* handle the complicated stray case */
690 #define PEEKC(c, p)\
692 p++;\
693 c = *p;\
694 if (c == '\\') {\
695 c = handle_stray1(p);\
696 p = file->buf_ptr;\
700 /* input with '\[\r]\n' handling. Note that this function cannot
701 handle other characters after '\', so you cannot call it inside
702 strings or comments */
703 ST_FUNC void minp(void)
705 inp();
706 if (ch == '\\')
707 handle_stray();
710 /* single line C++ comments */
711 static uint8_t *parse_line_comment(uint8_t *p)
713 int c;
715 p++;
716 for(;;) {
717 c = *p;
718 redo:
719 if (c == '\n' || c == CH_EOF) {
720 break;
721 } else if (c == '\\') {
722 file->buf_ptr = p;
723 c = handle_eob();
724 p = file->buf_ptr;
725 if (c == '\\') {
726 PEEKC_EOB(c, p);
727 if (c == '\n') {
728 file->line_num++;
729 PEEKC_EOB(c, p);
730 } else if (c == '\r') {
731 PEEKC_EOB(c, p);
732 if (c == '\n') {
733 file->line_num++;
734 PEEKC_EOB(c, p);
737 } else {
738 goto redo;
740 } else {
741 p++;
744 return p;
747 /* C comments */
748 ST_FUNC uint8_t *parse_comment(uint8_t *p)
750 int c;
752 p++;
753 for(;;) {
754 /* fast skip loop */
755 for(;;) {
756 c = *p;
757 if (c == '\n' || c == '*' || c == '\\')
758 break;
759 p++;
760 c = *p;
761 if (c == '\n' || c == '*' || c == '\\')
762 break;
763 p++;
765 /* now we can handle all the cases */
766 if (c == '\n') {
767 file->line_num++;
768 p++;
769 } else if (c == '*') {
770 p++;
771 for(;;) {
772 c = *p;
773 if (c == '*') {
774 p++;
775 } else if (c == '/') {
776 goto end_of_comment;
777 } else if (c == '\\') {
778 file->buf_ptr = p;
779 c = handle_eob();
780 p = file->buf_ptr;
781 if (c == CH_EOF)
782 tcc_error("unexpected end of file in comment");
783 if (c == '\\') {
784 /* skip '\[\r]\n', otherwise just skip the stray */
785 while (c == '\\') {
786 PEEKC_EOB(c, p);
787 if (c == '\n') {
788 file->line_num++;
789 PEEKC_EOB(c, p);
790 } else if (c == '\r') {
791 PEEKC_EOB(c, p);
792 if (c == '\n') {
793 file->line_num++;
794 PEEKC_EOB(c, p);
796 } else {
797 goto after_star;
801 } else {
802 break;
805 after_star: ;
806 } else {
807 /* stray, eob or eof */
808 file->buf_ptr = p;
809 c = handle_eob();
810 p = file->buf_ptr;
811 if (c == CH_EOF) {
812 tcc_error("unexpected end of file in comment");
813 } else if (c == '\\') {
814 p++;
818 end_of_comment:
819 p++;
820 return p;
823 ST_FUNC void set_idnum(int c, int val)
825 isidnum_table[c - CH_EOF] = val;
828 #define cinp minp
830 static inline void skip_spaces(void)
832 while (isidnum_table[ch - CH_EOF] & IS_SPC)
833 cinp();
836 static inline int check_space(int t, int *spc)
838 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
839 if (*spc)
840 return 1;
841 *spc = 1;
842 } else
843 *spc = 0;
844 return 0;
847 /* parse a string without interpreting escapes */
848 static uint8_t *parse_pp_string(uint8_t *p,
849 int sep, CString *str)
851 int c;
852 p++;
853 for(;;) {
854 c = *p;
855 if (c == sep) {
856 break;
857 } else if (c == '\\') {
858 file->buf_ptr = p;
859 c = handle_eob();
860 p = file->buf_ptr;
861 if (c == CH_EOF) {
862 unterminated_string:
863 /* XXX: indicate line number of start of string */
864 tcc_error("missing terminating %c character", sep);
865 } else if (c == '\\') {
866 /* escape : just skip \[\r]\n */
867 PEEKC_EOB(c, p);
868 if (c == '\n') {
869 file->line_num++;
870 p++;
871 } else if (c == '\r') {
872 PEEKC_EOB(c, p);
873 if (c != '\n')
874 expect("'\n' after '\r'");
875 file->line_num++;
876 p++;
877 } else if (c == CH_EOF) {
878 goto unterminated_string;
879 } else {
880 if (str) {
881 cstr_ccat(str, '\\');
882 cstr_ccat(str, c);
884 p++;
887 } else if (c == '\n') {
888 file->line_num++;
889 goto add_char;
890 } else if (c == '\r') {
891 PEEKC_EOB(c, p);
892 if (c != '\n') {
893 if (str)
894 cstr_ccat(str, '\r');
895 } else {
896 file->line_num++;
897 goto add_char;
899 } else {
900 add_char:
901 if (str)
902 cstr_ccat(str, c);
903 p++;
906 p++;
907 return p;
910 /* skip block of text until #else, #elif or #endif. skip also pairs of
911 #if/#endif */
912 static void preprocess_skip(void)
914 int a, start_of_line, c, in_warn_or_error;
915 uint8_t *p;
917 p = file->buf_ptr;
918 a = 0;
919 redo_start:
920 start_of_line = 1;
921 in_warn_or_error = 0;
922 for(;;) {
923 redo_no_start:
924 c = *p;
925 switch(c) {
926 case ' ':
927 case '\t':
928 case '\f':
929 case '\v':
930 case '\r':
931 p++;
932 goto redo_no_start;
933 case '\n':
934 file->line_num++;
935 p++;
936 goto redo_start;
937 case '\\':
938 file->buf_ptr = p;
939 c = handle_eob();
940 if (c == CH_EOF) {
941 expect("#endif");
942 } else if (c == '\\') {
943 ch = file->buf_ptr[0];
944 handle_stray_noerror();
946 p = file->buf_ptr;
947 goto redo_no_start;
948 /* skip strings */
949 case '\"':
950 case '\'':
951 if (in_warn_or_error)
952 goto _default;
953 p = parse_pp_string(p, c, NULL);
954 break;
955 /* skip comments */
956 case '/':
957 if (in_warn_or_error)
958 goto _default;
959 file->buf_ptr = p;
960 ch = *p;
961 minp();
962 p = file->buf_ptr;
963 if (ch == '*') {
964 p = parse_comment(p);
965 } else if (ch == '/') {
966 p = parse_line_comment(p);
968 break;
969 case '#':
970 p++;
971 if (start_of_line) {
972 file->buf_ptr = p;
973 next_nomacro();
974 p = file->buf_ptr;
975 if (a == 0 &&
976 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
977 goto the_end;
978 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
979 a++;
980 else if (tok == TOK_ENDIF)
981 a--;
982 else if( tok == TOK_ERROR || tok == TOK_WARNING)
983 in_warn_or_error = 1;
984 else if (tok == TOK_LINEFEED)
985 goto redo_start;
986 else if (parse_flags & PARSE_FLAG_ASM_FILE)
987 p = parse_line_comment(p - 1);
988 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
989 p = parse_line_comment(p - 1);
990 break;
991 _default:
992 default:
993 p++;
994 break;
996 start_of_line = 0;
998 the_end: ;
999 file->buf_ptr = p;
1002 /* ParseState handling */
1004 /* XXX: currently, no include file info is stored. Thus, we cannot display
1005 accurate messages if the function or data definition spans multiple
1006 files */
1008 /* save current parse state in 's' */
1009 ST_FUNC void save_parse_state(ParseState *s)
1011 s->line_num = file->line_num;
1012 s->macro_ptr = macro_ptr;
1013 s->tok = tok;
1014 s->tokc = tokc;
1017 /* restore parse state from 's' */
1018 ST_FUNC void restore_parse_state(ParseState *s)
1020 file->line_num = s->line_num;
1021 macro_ptr = s->macro_ptr;
1022 tok = s->tok;
1023 tokc = s->tokc;
1026 #if 0
1027 /* return the number of additional 'ints' necessary to store the
1028 token */
1029 static inline int tok_size(const int *p)
1031 switch(*p) {
1032 /* 4 bytes */
1033 case TOK_CINT:
1034 case TOK_CUINT:
1035 case TOK_CCHAR:
1036 case TOK_LCHAR:
1037 case TOK_CFLOAT:
1038 case TOK_LINENUM:
1039 return 1 + 1;
1040 case TOK_STR:
1041 case TOK_LSTR:
1042 case TOK_PPNUM:
1043 case TOK_PPSTR:
1044 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1045 case TOK_CDOUBLE:
1046 case TOK_CLLONG:
1047 case TOK_CULLONG:
1048 return 1 + 2;
1049 case TOK_CLDOUBLE:
1050 return 1 + LDOUBLE_SIZE / 4;
1051 default:
1052 return 1 + 0;
1055 #endif
1057 /* token string handling */
1058 ST_INLN void tok_str_new(TokenString *s)
1060 s->str = NULL;
1061 s->len = s->lastlen = 0;
1062 s->allocated_len = 0;
1063 s->last_line_num = -1;
1066 ST_FUNC TokenString *tok_str_alloc(void)
1068 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1069 tok_str_new(str);
1070 return str;
1073 ST_FUNC int *tok_str_dup(TokenString *s)
1075 int *str;
1077 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1078 memcpy(str, s->str, s->len * sizeof(int));
1079 return str;
1082 ST_FUNC void tok_str_free_str(int *str)
1084 tal_free(tokstr_alloc, str);
1087 ST_FUNC void tok_str_free(TokenString *str)
1089 tok_str_free_str(str->str);
1090 tal_free(tokstr_alloc, str);
1093 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1095 int *str, size;
1097 size = s->allocated_len;
1098 if (size < 16)
1099 size = 16;
1100 while (size < new_size)
1101 size = size * 2;
1102 if (size > s->allocated_len) {
1103 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1104 s->allocated_len = size;
1105 s->str = str;
1107 return s->str;
1110 ST_FUNC void tok_str_add(TokenString *s, int t)
1112 int len, *str;
1114 len = s->len;
1115 str = s->str;
1116 if (len >= s->allocated_len)
1117 str = tok_str_realloc(s, len + 1);
1118 str[len++] = t;
1119 s->len = len;
1122 ST_FUNC void begin_macro(TokenString *str, int alloc)
1124 str->alloc = alloc;
1125 str->prev = macro_stack;
1126 str->prev_ptr = macro_ptr;
1127 macro_ptr = str->str;
1128 macro_stack = str;
1131 ST_FUNC void end_macro(void)
1133 TokenString *str = macro_stack;
1134 macro_stack = str->prev;
1135 macro_ptr = str->prev_ptr;
1136 if (str->alloc == 2) {
1137 str->alloc = 3; /* just mark as finished */
1138 } else {
1139 tok_str_free(str);
1143 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1145 int len, *str;
1147 len = s->lastlen = s->len;
1148 str = s->str;
1150 /* allocate space for worst case */
1151 if (len + TOK_MAX_SIZE >= s->allocated_len)
1152 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1153 str[len++] = t;
1154 switch(t) {
1155 case TOK_CINT:
1156 case TOK_CUINT:
1157 case TOK_CCHAR:
1158 case TOK_LCHAR:
1159 case TOK_CFLOAT:
1160 case TOK_LINENUM:
1161 str[len++] = cv->tab[0];
1162 break;
1163 case TOK_PPNUM:
1164 case TOK_PPSTR:
1165 case TOK_STR:
1166 case TOK_LSTR:
1168 /* Insert the string into the int array. */
1169 size_t nb_words =
1170 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1171 if (len + nb_words >= s->allocated_len)
1172 str = tok_str_realloc(s, len + nb_words + 1);
1173 str[len] = cv->str.size;
1174 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1175 len += nb_words;
1177 break;
1178 case TOK_CDOUBLE:
1179 case TOK_CLLONG:
1180 case TOK_CULLONG:
1181 #if LDOUBLE_SIZE == 8
1182 case TOK_CLDOUBLE:
1183 #endif
1184 str[len++] = cv->tab[0];
1185 str[len++] = cv->tab[1];
1186 break;
1187 #if LDOUBLE_SIZE == 12
1188 case TOK_CLDOUBLE:
1189 str[len++] = cv->tab[0];
1190 str[len++] = cv->tab[1];
1191 str[len++] = cv->tab[2];
1192 #elif LDOUBLE_SIZE == 16
1193 case TOK_CLDOUBLE:
1194 str[len++] = cv->tab[0];
1195 str[len++] = cv->tab[1];
1196 str[len++] = cv->tab[2];
1197 str[len++] = cv->tab[3];
1198 #elif LDOUBLE_SIZE != 8
1199 #error add long double size support
1200 #endif
1201 break;
1202 default:
1203 break;
1205 s->len = len;
1208 /* add the current parse token in token string 's' */
1209 ST_FUNC void tok_str_add_tok(TokenString *s)
1211 CValue cval;
1213 /* save line number info */
1214 if (file->line_num != s->last_line_num) {
1215 s->last_line_num = file->line_num;
1216 cval.i = s->last_line_num;
1217 tok_str_add2(s, TOK_LINENUM, &cval);
1219 tok_str_add2(s, tok, &tokc);
1222 /* get a token from an integer array and increment pointer
1223 accordingly. we code it as a macro to avoid pointer aliasing. */
1224 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
1226 const int *p = *pp;
1227 int n, *tab;
1229 tab = cv->tab;
1230 switch(*t = *p++) {
1231 case TOK_CINT:
1232 case TOK_CUINT:
1233 case TOK_CCHAR:
1234 case TOK_LCHAR:
1235 case TOK_LINENUM:
1236 tab[0] = *p++;
1237 cv->i = (*t == TOK_CUINT) ? (unsigned)cv->i : (int)cv->i;
1238 break;
1239 case TOK_CFLOAT:
1240 tab[0] = *p++;
1241 break;
1242 case TOK_STR:
1243 case TOK_LSTR:
1244 case TOK_PPNUM:
1245 case TOK_PPSTR:
1246 cv->str.size = *p++;
1247 cv->str.data = p;
1248 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1249 break;
1250 case TOK_CDOUBLE:
1251 case TOK_CLLONG:
1252 case TOK_CULLONG:
1253 n = 2;
1254 goto copy;
1255 case TOK_CLDOUBLE:
1256 #if LDOUBLE_SIZE == 16
1257 n = 4;
1258 #elif LDOUBLE_SIZE == 12
1259 n = 3;
1260 #elif LDOUBLE_SIZE == 8
1261 n = 2;
1262 #else
1263 # error add long double size support
1264 #endif
1265 copy:
1267 *tab++ = *p++;
1268 while (--n);
1269 break;
1270 default:
1271 break;
1273 *pp = p;
1276 static int macro_is_equal(const int *a, const int *b)
1278 CValue cv;
1279 int t;
1281 if (!a || !b)
1282 return 1;
1284 while (*a && *b) {
1285 /* first time preallocate macro_equal_buf, next time only reset position to start */
1286 cstr_reset(&macro_equal_buf);
1287 TOK_GET(&t, &a, &cv);
1288 cstr_cat(&macro_equal_buf, get_tok_str(t, &cv), 0);
1289 TOK_GET(&t, &b, &cv);
1290 if (strcmp(macro_equal_buf.data, get_tok_str(t, &cv)))
1291 return 0;
1293 return !(*a || *b);
1296 /* defines handling */
1297 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1299 Sym *s, *o;
1301 o = define_find(v);
1302 s = sym_push2(&define_stack, v, macro_type, 0);
1303 s->d = str;
1304 s->next = first_arg;
1305 table_ident[v - TOK_IDENT]->sym_define = s;
1307 if (o && !macro_is_equal(o->d, s->d))
1308 tcc_warning("%s redefined", get_tok_str(v, NULL));
1311 /* undefined a define symbol. Its name is just set to zero */
1312 ST_FUNC void define_undef(Sym *s)
1314 int v = s->v;
1315 if (v >= TOK_IDENT && v < tok_ident)
1316 table_ident[v - TOK_IDENT]->sym_define = NULL;
1319 ST_INLN Sym *define_find(int v)
1321 v -= TOK_IDENT;
1322 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1323 return NULL;
1324 return table_ident[v]->sym_define;
1327 /* free define stack until top reaches 'b' */
1328 ST_FUNC void free_defines(Sym *b)
1330 while (define_stack != b) {
1331 Sym *top = define_stack;
1332 define_stack = top->prev;
1333 tok_str_free_str(top->d);
1334 define_undef(top);
1335 sym_free(top);
1338 /* restore remaining (-D or predefined) symbols if they were
1339 #undef'd in the file */
1340 while (b) {
1341 int v = b->v;
1342 if (v >= TOK_IDENT && v < tok_ident) {
1343 Sym **d = &table_ident[v - TOK_IDENT]->sym_define;
1344 if (!*d)
1345 *d = b;
1347 b = b->prev;
1351 /* label lookup */
1352 ST_FUNC Sym *label_find(int v)
1354 v -= TOK_IDENT;
1355 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1356 return NULL;
1357 return table_ident[v]->sym_label;
1360 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1362 Sym *s, **ps;
1363 s = sym_push2(ptop, v, 0, 0);
1364 s->r = flags;
1365 ps = &table_ident[v - TOK_IDENT]->sym_label;
1366 if (ptop == &global_label_stack) {
1367 /* modify the top most local identifier, so that
1368 sym_identifier will point to 's' when popped */
1369 while (*ps != NULL)
1370 ps = &(*ps)->prev_tok;
1372 s->prev_tok = *ps;
1373 *ps = s;
1374 return s;
1377 /* pop labels until element last is reached. Look if any labels are
1378 undefined. Define symbols if '&&label' was used. */
1379 ST_FUNC void label_pop(Sym **ptop, Sym *slast, int keep)
1381 Sym *s, *s1;
1382 for(s = *ptop; s != slast; s = s1) {
1383 s1 = s->prev;
1384 if (s->r == LABEL_DECLARED) {
1385 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1386 } else if (s->r == LABEL_FORWARD) {
1387 tcc_error("label '%s' used but not defined",
1388 get_tok_str(s->v, NULL));
1389 } else {
1390 if (s->c) {
1391 /* define corresponding symbol. A size of
1392 1 is put. */
1393 put_extern_sym(s, cur_text_section, s->jnext, 1);
1396 /* remove label */
1397 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1398 if (!keep)
1399 sym_free(s);
1401 if (!keep)
1402 *ptop = slast;
1405 /* eval an expression for #if/#elif */
1406 static int expr_preprocess(void)
1408 int c, t;
1409 TokenString *str;
1411 str = tok_str_alloc();
1412 pp_expr = 1;
1413 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1414 next(); /* do macro subst */
1415 if (tok == TOK_DEFINED) {
1416 next_nomacro();
1417 t = tok;
1418 if (t == '(')
1419 next_nomacro();
1420 if (tok < TOK_IDENT)
1421 expect("identifier");
1422 c = define_find(tok) != 0;
1423 if (t == '(') {
1424 next_nomacro();
1425 if (tok != ')')
1426 expect("')'");
1428 tok = TOK_CINT;
1429 tokc.i = c;
1430 } else if (tok >= TOK_IDENT) {
1431 /* if undefined macro */
1432 tok = TOK_CINT;
1433 tokc.i = 0;
1435 tok_str_add_tok(str);
1437 pp_expr = 0;
1438 tok_str_add(str, -1); /* simulate end of file */
1439 tok_str_add(str, 0);
1440 /* now evaluate C constant expression */
1441 begin_macro(str, 1);
1442 next();
1443 c = expr_const();
1444 end_macro();
1445 return c != 0;
1449 /* parse after #define */
1450 ST_FUNC void parse_define(void)
1452 Sym *s, *first, **ps;
1453 int v, t, varg, is_vaargs, spc;
1454 int saved_parse_flags = parse_flags;
1456 v = tok;
1457 if (v < TOK_IDENT || v == TOK_DEFINED)
1458 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1459 /* XXX: should check if same macro (ANSI) */
1460 first = NULL;
1461 t = MACRO_OBJ;
1462 /* We have to parse the whole define as if not in asm mode, in particular
1463 no line comment with '#' must be ignored. Also for function
1464 macros the argument list must be parsed without '.' being an ID
1465 character. */
1466 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1467 /* '(' must be just after macro definition for MACRO_FUNC */
1468 next_nomacro_spc();
1469 if (tok == '(') {
1470 set_idnum('.', 0);
1471 next_nomacro();
1472 ps = &first;
1473 if (tok != ')') for (;;) {
1474 varg = tok;
1475 next_nomacro();
1476 is_vaargs = 0;
1477 if (varg == TOK_DOTS) {
1478 varg = TOK___VA_ARGS__;
1479 is_vaargs = 1;
1480 } else if (tok == TOK_DOTS && gnu_ext) {
1481 is_vaargs = 1;
1482 next_nomacro();
1484 if (varg < TOK_IDENT)
1485 bad_list:
1486 tcc_error("bad macro parameter list");
1487 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1488 *ps = s;
1489 ps = &s->next;
1490 if (tok == ')')
1491 break;
1492 if (tok != ',' || is_vaargs)
1493 goto bad_list;
1494 next_nomacro();
1496 next_nomacro_spc();
1497 t = MACRO_FUNC;
1500 tokstr_buf.len = 0;
1501 spc = 2;
1502 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1503 /* The body of a macro definition should be parsed such that identifiers
1504 are parsed like the file mode determines (i.e. with '.' being an
1505 ID character in asm mode). But '#' should be retained instead of
1506 regarded as line comment leader, so still don't set ASM_FILE
1507 in parse_flags. */
1508 set_idnum('.', (saved_parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0);
1509 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1510 /* remove spaces around ## and after '#' */
1511 if (TOK_TWOSHARPS == tok) {
1512 if (2 == spc)
1513 goto bad_twosharp;
1514 if (1 == spc)
1515 --tokstr_buf.len;
1516 spc = 3;
1517 tok = TOK_PPJOIN;
1518 } else if ('#' == tok) {
1519 spc = 4;
1520 } else if (check_space(tok, &spc)) {
1521 goto skip;
1523 tok_str_add2(&tokstr_buf, tok, &tokc);
1524 skip:
1525 next_nomacro_spc();
1528 parse_flags = saved_parse_flags;
1529 if (spc == 1)
1530 --tokstr_buf.len; /* remove trailing space */
1531 tok_str_add(&tokstr_buf, 0);
1532 if (3 == spc)
1533 bad_twosharp:
1534 tcc_error("'##' cannot appear at either end of macro");
1535 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1538 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1540 const unsigned char *s;
1541 unsigned int h;
1542 CachedInclude *e;
1543 int i;
1545 h = TOK_HASH_INIT;
1546 s = (unsigned char *) filename;
1547 while (*s) {
1548 #ifdef _WIN32
1549 h = TOK_HASH_FUNC(h, toup(*s));
1550 #else
1551 h = TOK_HASH_FUNC(h, *s);
1552 #endif
1553 s++;
1555 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1557 i = s1->cached_includes_hash[h];
1558 for(;;) {
1559 if (i == 0)
1560 break;
1561 e = s1->cached_includes[i - 1];
1562 if (0 == PATHCMP(e->filename, filename))
1563 return e;
1564 i = e->hash_next;
1566 if (!add)
1567 return NULL;
1569 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1570 strcpy(e->filename, filename);
1571 e->ifndef_macro = e->once = 0;
1572 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1573 /* add in hash table */
1574 e->hash_next = s1->cached_includes_hash[h];
1575 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1576 #ifdef INC_DEBUG
1577 printf("adding cached '%s'\n", filename);
1578 #endif
1579 return e;
1582 static void pragma_parse(TCCState *s1)
1584 next_nomacro();
1585 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1586 int t = tok, v;
1587 Sym *s;
1589 if (next(), tok != '(')
1590 goto pragma_err;
1591 if (next(), tok != TOK_STR)
1592 goto pragma_err;
1593 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1594 if (next(), tok != ')')
1595 goto pragma_err;
1596 if (t == TOK_push_macro) {
1597 while (NULL == (s = define_find(v)))
1598 define_push(v, 0, NULL, NULL);
1599 s->type.ref = s; /* set push boundary */
1600 } else {
1601 for (s = define_stack; s; s = s->prev)
1602 if (s->v == v && s->type.ref == s) {
1603 s->type.ref = NULL;
1604 break;
1607 if (s)
1608 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1609 else
1610 tcc_warning("unbalanced #pragma pop_macro");
1611 pp_debug_tok = t, pp_debug_symv = v;
1613 } else if (tok == TOK_once) {
1614 search_cached_include(s1, file->filename, 1)->once = pp_once;
1616 } else if (s1->ppfp) {
1617 /* tcc -E: keep pragmas below unchanged */
1618 unget_tok(' ');
1619 unget_tok(TOK_PRAGMA);
1620 unget_tok('#');
1621 unget_tok(TOK_LINEFEED);
1623 } else if (tok == TOK_pack) {
1624 /* This may be:
1625 #pragma pack(1) // set
1626 #pragma pack() // reset to default
1627 #pragma pack(push,1) // push & set
1628 #pragma pack(pop) // restore previous */
1629 next();
1630 skip('(');
1631 if (tok == TOK_ASM_pop) {
1632 next();
1633 if (s1->pack_stack_ptr <= s1->pack_stack) {
1634 stk_error:
1635 tcc_error("out of pack stack");
1637 s1->pack_stack_ptr--;
1638 } else {
1639 int val = 0;
1640 if (tok != ')') {
1641 if (tok == TOK_ASM_push) {
1642 next();
1643 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1644 goto stk_error;
1645 s1->pack_stack_ptr++;
1646 skip(',');
1648 if (tok != TOK_CINT)
1649 goto pragma_err;
1650 val = tokc.i;
1651 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1652 goto pragma_err;
1653 next();
1655 *s1->pack_stack_ptr = val;
1657 if (tok != ')')
1658 goto pragma_err;
1660 } else if (tok == TOK_comment) {
1661 char *p; int t;
1662 next();
1663 skip('(');
1664 t = tok;
1665 next();
1666 skip(',');
1667 if (tok != TOK_STR)
1668 goto pragma_err;
1669 p = tcc_strdup((char *)tokc.str.data);
1670 next();
1671 if (tok != ')')
1672 goto pragma_err;
1673 if (t == TOK_lib) {
1674 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1675 } else {
1676 if (t == TOK_option)
1677 tcc_set_options(s1, p);
1678 tcc_free(p);
1681 } else if (s1->warn_unsupported) {
1682 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1684 return;
1686 pragma_err:
1687 tcc_error("malformed #pragma directive");
1688 return;
1691 /* is_bof is true if first non space token at beginning of file */
1692 ST_FUNC void preprocess(int is_bof)
1694 TCCState *s1 = tcc_state;
1695 int i, c, n, saved_parse_flags;
1696 char buf[1024], *q;
1697 Sym *s;
1699 saved_parse_flags = parse_flags;
1700 parse_flags = PARSE_FLAG_PREPROCESS
1701 | PARSE_FLAG_TOK_NUM
1702 | PARSE_FLAG_TOK_STR
1703 | PARSE_FLAG_LINEFEED
1704 | (parse_flags & PARSE_FLAG_ASM_FILE)
1707 next_nomacro();
1708 redo:
1709 switch(tok) {
1710 case TOK_DEFINE:
1711 pp_debug_tok = tok;
1712 next_nomacro();
1713 pp_debug_symv = tok;
1714 parse_define();
1715 break;
1716 case TOK_UNDEF:
1717 pp_debug_tok = tok;
1718 next_nomacro();
1719 pp_debug_symv = tok;
1720 s = define_find(tok);
1721 /* undefine symbol by putting an invalid name */
1722 if (s)
1723 define_undef(s);
1724 break;
1725 case TOK_INCLUDE:
1726 case TOK_INCLUDE_NEXT:
1727 ch = file->buf_ptr[0];
1728 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1729 skip_spaces();
1730 if (ch == '<') {
1731 c = '>';
1732 goto read_name;
1733 } else if (ch == '\"') {
1734 c = ch;
1735 read_name:
1736 inp();
1737 q = buf;
1738 while (ch != c && ch != '\n' && ch != CH_EOF) {
1739 if ((q - buf) < sizeof(buf) - 1)
1740 *q++ = ch;
1741 if (ch == '\\') {
1742 if (handle_stray_noerror() == 0)
1743 --q;
1744 } else
1745 inp();
1747 *q = '\0';
1748 minp();
1749 #if 0
1750 /* eat all spaces and comments after include */
1751 /* XXX: slightly incorrect */
1752 while (ch1 != '\n' && ch1 != CH_EOF)
1753 inp();
1754 #endif
1755 } else {
1756 int len;
1757 /* computed #include : concatenate everything up to linefeed,
1758 the result must be one of the two accepted forms.
1759 Don't convert pp-tokens to tokens here. */
1760 parse_flags = (PARSE_FLAG_PREPROCESS
1761 | PARSE_FLAG_LINEFEED
1762 | (parse_flags & PARSE_FLAG_ASM_FILE));
1763 next();
1764 buf[0] = '\0';
1765 while (tok != TOK_LINEFEED) {
1766 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1767 next();
1769 len = strlen(buf);
1770 /* check syntax and remove '<>|""' */
1771 if ((len < 2 || ((buf[0] != '"' || buf[len-1] != '"') &&
1772 (buf[0] != '<' || buf[len-1] != '>'))))
1773 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1774 c = buf[len-1];
1775 memmove(buf, buf + 1, len - 2);
1776 buf[len - 2] = '\0';
1779 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1780 tcc_error("#include recursion too deep");
1781 /* store current file in stack, but increment stack later below */
1782 *s1->include_stack_ptr = file;
1783 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index : 0;
1784 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1785 for (; i < n; ++i) {
1786 char buf1[sizeof file->filename];
1787 CachedInclude *e;
1788 const char *path;
1790 if (i == 0) {
1791 /* check absolute include path */
1792 if (!IS_ABSPATH(buf))
1793 continue;
1794 buf1[0] = 0;
1796 } else if (i == 1) {
1797 /* search in file's dir if "header.h" */
1798 if (c != '\"')
1799 continue;
1800 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1801 path = file->true_filename;
1802 pstrncpy(buf1, path, tcc_basename(path) - path);
1804 } else {
1805 /* search in all the include paths */
1806 int j = i - 2, k = j - s1->nb_include_paths;
1807 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1808 pstrcpy(buf1, sizeof(buf1), path);
1809 pstrcat(buf1, sizeof(buf1), "/");
1812 pstrcat(buf1, sizeof(buf1), buf);
1813 e = search_cached_include(s1, buf1, 0);
1814 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1815 /* no need to parse the include because the 'ifndef macro'
1816 is defined (or had #pragma once) */
1817 #ifdef INC_DEBUG
1818 printf("%s: skipping cached %s\n", file->filename, buf1);
1819 #endif
1820 goto include_done;
1823 if (tcc_open(s1, buf1) < 0)
1824 continue;
1826 file->include_next_index = i + 1;
1827 #ifdef INC_DEBUG
1828 printf("%s: including %s\n", file->prev->filename, file->filename);
1829 #endif
1830 /* update target deps */
1831 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1832 tcc_strdup(buf1));
1833 /* push current file in stack */
1834 ++s1->include_stack_ptr;
1835 /* add include file debug info */
1836 if (s1->do_debug)
1837 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1838 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1839 ch = file->buf_ptr[0];
1840 goto the_end;
1842 tcc_error("include file '%s' not found", buf);
1843 include_done:
1844 break;
1845 case TOK_IFNDEF:
1846 c = 1;
1847 goto do_ifdef;
1848 case TOK_IF:
1849 c = expr_preprocess();
1850 goto do_if;
1851 case TOK_IFDEF:
1852 c = 0;
1853 do_ifdef:
1854 next_nomacro();
1855 if (tok < TOK_IDENT)
1856 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1857 if (is_bof) {
1858 if (c) {
1859 #ifdef INC_DEBUG
1860 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1861 #endif
1862 file->ifndef_macro = tok;
1865 c = (define_find(tok) != 0) ^ c;
1866 do_if:
1867 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1868 tcc_error("memory full (ifdef)");
1869 *s1->ifdef_stack_ptr++ = c;
1870 goto test_skip;
1871 case TOK_ELSE:
1872 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1873 tcc_error("#else without matching #if");
1874 if (s1->ifdef_stack_ptr[-1] & 2)
1875 tcc_error("#else after #else");
1876 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1877 goto test_else;
1878 case TOK_ELIF:
1879 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1880 tcc_error("#elif without matching #if");
1881 c = s1->ifdef_stack_ptr[-1];
1882 if (c > 1)
1883 tcc_error("#elif after #else");
1884 /* last #if/#elif expression was true: we skip */
1885 if (c == 1) {
1886 c = 0;
1887 } else {
1888 c = expr_preprocess();
1889 s1->ifdef_stack_ptr[-1] = c;
1891 test_else:
1892 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1893 file->ifndef_macro = 0;
1894 test_skip:
1895 if (!(c & 1)) {
1896 preprocess_skip();
1897 is_bof = 0;
1898 goto redo;
1900 break;
1901 case TOK_ENDIF:
1902 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1903 tcc_error("#endif without matching #if");
1904 s1->ifdef_stack_ptr--;
1905 /* '#ifndef macro' was at the start of file. Now we check if
1906 an '#endif' is exactly at the end of file */
1907 if (file->ifndef_macro &&
1908 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1909 file->ifndef_macro_saved = file->ifndef_macro;
1910 /* need to set to zero to avoid false matches if another
1911 #ifndef at middle of file */
1912 file->ifndef_macro = 0;
1913 while (tok != TOK_LINEFEED)
1914 next_nomacro();
1915 tok_flags |= TOK_FLAG_ENDIF;
1916 goto the_end;
1918 break;
1919 case TOK_PPNUM:
1920 n = strtoul((char*)tokc.str.data, &q, 10);
1921 goto _line_num;
1922 case TOK_LINE:
1923 next();
1924 if (tok != TOK_CINT)
1925 _line_err:
1926 tcc_error("wrong #line format");
1927 n = tokc.i;
1928 _line_num:
1929 next();
1930 if (tok != TOK_LINEFEED) {
1931 if (tok == TOK_STR) {
1932 if (file->true_filename == file->filename)
1933 file->true_filename = tcc_strdup(file->filename);
1934 pstrcpy(file->filename, sizeof(file->filename), (char *)tokc.str.data);
1935 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
1936 break;
1937 else
1938 goto _line_err;
1939 --n;
1941 if (file->fd > 0)
1942 total_lines += file->line_num - n;
1943 file->line_num = n;
1944 if (s1->do_debug)
1945 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1946 break;
1947 case TOK_ERROR:
1948 case TOK_WARNING:
1949 c = tok;
1950 ch = file->buf_ptr[0];
1951 skip_spaces();
1952 q = buf;
1953 while (ch != '\n' && ch != CH_EOF) {
1954 if ((q - buf) < sizeof(buf) - 1)
1955 *q++ = ch;
1956 if (ch == '\\') {
1957 if (handle_stray_noerror() == 0)
1958 --q;
1959 } else
1960 inp();
1962 *q = '\0';
1963 if (c == TOK_ERROR)
1964 tcc_error("#error %s", buf);
1965 else
1966 tcc_warning("#warning %s", buf);
1967 break;
1968 case TOK_PRAGMA:
1969 pragma_parse(s1);
1970 break;
1971 case TOK_LINEFEED:
1972 goto the_end;
1973 default:
1974 /* ignore gas line comment in an 'S' file. */
1975 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1976 goto ignore;
1977 if (tok == '!' && is_bof)
1978 /* '!' is ignored at beginning to allow C scripts. */
1979 goto ignore;
1980 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1981 ignore:
1982 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
1983 goto the_end;
1985 /* ignore other preprocess commands or #! for C scripts */
1986 while (tok != TOK_LINEFEED)
1987 next_nomacro();
1988 the_end:
1989 parse_flags = saved_parse_flags;
1992 /* evaluate escape codes in a string. */
1993 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1995 int c, n;
1996 const uint8_t *p;
1998 p = buf;
1999 for(;;) {
2000 c = *p;
2001 if (c == '\0')
2002 break;
2003 if (c == '\\') {
2004 p++;
2005 /* escape */
2006 c = *p;
2007 switch(c) {
2008 case '0': case '1': case '2': case '3':
2009 case '4': case '5': case '6': case '7':
2010 /* at most three octal digits */
2011 n = c - '0';
2012 p++;
2013 c = *p;
2014 if (isoct(c)) {
2015 n = n * 8 + c - '0';
2016 p++;
2017 c = *p;
2018 if (isoct(c)) {
2019 n = n * 8 + c - '0';
2020 p++;
2023 c = n;
2024 goto add_char_nonext;
2025 case 'x':
2026 case 'u':
2027 case 'U':
2028 p++;
2029 n = 0;
2030 for(;;) {
2031 c = *p;
2032 if (c >= 'a' && c <= 'f')
2033 c = c - 'a' + 10;
2034 else if (c >= 'A' && c <= 'F')
2035 c = c - 'A' + 10;
2036 else if (isnum(c))
2037 c = c - '0';
2038 else
2039 break;
2040 n = n * 16 + c;
2041 p++;
2043 c = n;
2044 goto add_char_nonext;
2045 case 'a':
2046 c = '\a';
2047 break;
2048 case 'b':
2049 c = '\b';
2050 break;
2051 case 'f':
2052 c = '\f';
2053 break;
2054 case 'n':
2055 c = '\n';
2056 break;
2057 case 'r':
2058 c = '\r';
2059 break;
2060 case 't':
2061 c = '\t';
2062 break;
2063 case 'v':
2064 c = '\v';
2065 break;
2066 case 'e':
2067 if (!gnu_ext)
2068 goto invalid_escape;
2069 c = 27;
2070 break;
2071 case '\'':
2072 case '\"':
2073 case '\\':
2074 case '?':
2075 break;
2076 default:
2077 invalid_escape:
2078 if (c >= '!' && c <= '~')
2079 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2080 else
2081 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2082 break;
2085 p++;
2086 add_char_nonext:
2087 if (!is_long)
2088 cstr_ccat(outstr, c);
2089 else
2090 cstr_wccat(outstr, c);
2092 /* add a trailing '\0' */
2093 if (!is_long)
2094 cstr_ccat(outstr, '\0');
2095 else
2096 cstr_wccat(outstr, '\0');
2099 static void parse_string(const char *s, int len)
2101 uint8_t buf[1000], *p = buf;
2102 int is_long, sep;
2104 if ((is_long = *s == 'L'))
2105 ++s, --len;
2106 sep = *s++;
2107 len -= 2;
2108 if (len >= sizeof buf)
2109 p = tcc_malloc(len + 1);
2110 memcpy(p, s, len);
2111 p[len] = 0;
2113 cstr_reset(&tokcstr);
2114 parse_escape_string(&tokcstr, p, is_long);
2115 if (p != buf)
2116 tcc_free(p);
2118 if (sep == '\'') {
2119 int char_size;
2120 /* XXX: make it portable */
2121 if (!is_long)
2122 char_size = 1;
2123 else
2124 char_size = sizeof(nwchar_t);
2125 if (tokcstr.size <= char_size)
2126 tcc_error("empty character constant");
2127 if (tokcstr.size > 2 * char_size)
2128 tcc_warning("multi-character character constant");
2129 if (!is_long) {
2130 tokc.i = *(int8_t *)tokcstr.data;
2131 tok = TOK_CCHAR;
2132 } else {
2133 tokc.i = *(nwchar_t *)tokcstr.data;
2134 tok = TOK_LCHAR;
2136 } else {
2137 tokc.str.size = tokcstr.size;
2138 tokc.str.data = tokcstr.data;
2139 if (!is_long)
2140 tok = TOK_STR;
2141 else
2142 tok = TOK_LSTR;
2146 /* we use 64 bit numbers */
2147 #define BN_SIZE 2
2149 /* bn = (bn << shift) | or_val */
2150 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2152 int i;
2153 unsigned int v;
2154 for(i=0;i<BN_SIZE;i++) {
2155 v = bn[i];
2156 bn[i] = (v << shift) | or_val;
2157 or_val = v >> (32 - shift);
2161 static void bn_zero(unsigned int *bn)
2163 int i;
2164 for(i=0;i<BN_SIZE;i++) {
2165 bn[i] = 0;
2169 /* parse number in null terminated string 'p' and return it in the
2170 current token */
2171 static void parse_number(const char *p)
2173 int b, t, shift, frac_bits, s, exp_val, ch;
2174 char *q;
2175 unsigned int bn[BN_SIZE];
2176 double d;
2178 /* number */
2179 q = token_buf;
2180 ch = *p++;
2181 t = ch;
2182 ch = *p++;
2183 *q++ = t;
2184 b = 10;
2185 if (t == '.') {
2186 goto float_frac_parse;
2187 } else if (t == '0') {
2188 if (ch == 'x' || ch == 'X') {
2189 q--;
2190 ch = *p++;
2191 b = 16;
2192 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
2193 q--;
2194 ch = *p++;
2195 b = 2;
2198 /* parse all digits. cannot check octal numbers at this stage
2199 because of floating point constants */
2200 while (1) {
2201 if (ch >= 'a' && ch <= 'f')
2202 t = ch - 'a' + 10;
2203 else if (ch >= 'A' && ch <= 'F')
2204 t = ch - 'A' + 10;
2205 else if (isnum(ch))
2206 t = ch - '0';
2207 else
2208 break;
2209 if (t >= b)
2210 break;
2211 if (q >= token_buf + STRING_MAX_SIZE) {
2212 num_too_long:
2213 tcc_error("number too long");
2215 *q++ = ch;
2216 ch = *p++;
2218 if (ch == '.' ||
2219 ((ch == 'e' || ch == 'E') && b == 10) ||
2220 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2221 if (b != 10) {
2222 /* NOTE: strtox should support that for hexa numbers, but
2223 non ISOC99 libcs do not support it, so we prefer to do
2224 it by hand */
2225 /* hexadecimal or binary floats */
2226 /* XXX: handle overflows */
2227 *q = '\0';
2228 if (b == 16)
2229 shift = 4;
2230 else
2231 shift = 1;
2232 bn_zero(bn);
2233 q = token_buf;
2234 while (1) {
2235 t = *q++;
2236 if (t == '\0') {
2237 break;
2238 } else if (t >= 'a') {
2239 t = t - 'a' + 10;
2240 } else if (t >= 'A') {
2241 t = t - 'A' + 10;
2242 } else {
2243 t = t - '0';
2245 bn_lshift(bn, shift, t);
2247 frac_bits = 0;
2248 if (ch == '.') {
2249 ch = *p++;
2250 while (1) {
2251 t = ch;
2252 if (t >= 'a' && t <= 'f') {
2253 t = t - 'a' + 10;
2254 } else if (t >= 'A' && t <= 'F') {
2255 t = t - 'A' + 10;
2256 } else if (t >= '0' && t <= '9') {
2257 t = t - '0';
2258 } else {
2259 break;
2261 if (t >= b)
2262 tcc_error("invalid digit");
2263 bn_lshift(bn, shift, t);
2264 frac_bits += shift;
2265 ch = *p++;
2268 if (ch != 'p' && ch != 'P')
2269 expect("exponent");
2270 ch = *p++;
2271 s = 1;
2272 exp_val = 0;
2273 if (ch == '+') {
2274 ch = *p++;
2275 } else if (ch == '-') {
2276 s = -1;
2277 ch = *p++;
2279 if (ch < '0' || ch > '9')
2280 expect("exponent digits");
2281 while (ch >= '0' && ch <= '9') {
2282 exp_val = exp_val * 10 + ch - '0';
2283 ch = *p++;
2285 exp_val = exp_val * s;
2287 /* now we can generate the number */
2288 /* XXX: should patch directly float number */
2289 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2290 d = ldexp(d, exp_val - frac_bits);
2291 t = toup(ch);
2292 if (t == 'F') {
2293 ch = *p++;
2294 tok = TOK_CFLOAT;
2295 /* float : should handle overflow */
2296 tokc.f = (float)d;
2297 } else if (t == 'L') {
2298 ch = *p++;
2299 #ifdef TCC_TARGET_PE
2300 tok = TOK_CDOUBLE;
2301 tokc.d = d;
2302 #else
2303 tok = TOK_CLDOUBLE;
2304 /* XXX: not large enough */
2305 tokc.ld = (long double)d;
2306 #endif
2307 } else {
2308 tok = TOK_CDOUBLE;
2309 tokc.d = d;
2311 } else {
2312 /* decimal floats */
2313 if (ch == '.') {
2314 if (q >= token_buf + STRING_MAX_SIZE)
2315 goto num_too_long;
2316 *q++ = ch;
2317 ch = *p++;
2318 float_frac_parse:
2319 while (ch >= '0' && ch <= '9') {
2320 if (q >= token_buf + STRING_MAX_SIZE)
2321 goto num_too_long;
2322 *q++ = ch;
2323 ch = *p++;
2326 if (ch == 'e' || ch == 'E') {
2327 if (q >= token_buf + STRING_MAX_SIZE)
2328 goto num_too_long;
2329 *q++ = ch;
2330 ch = *p++;
2331 if (ch == '-' || ch == '+') {
2332 if (q >= token_buf + STRING_MAX_SIZE)
2333 goto num_too_long;
2334 *q++ = ch;
2335 ch = *p++;
2337 if (ch < '0' || ch > '9')
2338 expect("exponent digits");
2339 while (ch >= '0' && ch <= '9') {
2340 if (q >= token_buf + STRING_MAX_SIZE)
2341 goto num_too_long;
2342 *q++ = ch;
2343 ch = *p++;
2346 *q = '\0';
2347 t = toup(ch);
2348 errno = 0;
2349 if (t == 'F') {
2350 ch = *p++;
2351 tok = TOK_CFLOAT;
2352 tokc.f = strtof(token_buf, NULL);
2353 } else if (t == 'L') {
2354 ch = *p++;
2355 #ifdef TCC_TARGET_PE
2356 tok = TOK_CDOUBLE;
2357 tokc.d = strtod(token_buf, NULL);
2358 #else
2359 tok = TOK_CLDOUBLE;
2360 tokc.ld = strtold(token_buf, NULL);
2361 #endif
2362 } else {
2363 tok = TOK_CDOUBLE;
2364 tokc.d = strtod(token_buf, NULL);
2367 } else {
2368 unsigned long long n, n1;
2369 int lcount, ucount, must_64bit;
2370 const char *p1;
2372 /* integer number */
2373 *q = '\0';
2374 q = token_buf;
2375 if (b == 10 && *q == '0') {
2376 b = 8;
2377 q++;
2379 n = 0;
2380 while(1) {
2381 t = *q++;
2382 /* no need for checks except for base 10 / 8 errors */
2383 if (t == '\0')
2384 break;
2385 else if (t >= 'a')
2386 t = t - 'a' + 10;
2387 else if (t >= 'A')
2388 t = t - 'A' + 10;
2389 else
2390 t = t - '0';
2391 if (t >= b)
2392 tcc_error("invalid digit");
2393 n1 = n;
2394 n = n * b + t;
2395 /* detect overflow */
2396 /* XXX: this test is not reliable */
2397 if (n < n1)
2398 tcc_error("integer constant overflow");
2401 /* Determine the characteristics (unsigned and/or 64bit) the type of
2402 the constant must have according to the constant suffix(es) */
2403 lcount = ucount = must_64bit = 0;
2404 p1 = p;
2405 for(;;) {
2406 t = toup(ch);
2407 if (t == 'L') {
2408 if (lcount >= 2)
2409 tcc_error("three 'l's in integer constant");
2410 if (lcount && *(p - 1) != ch)
2411 tcc_error("incorrect integer suffix: %s", p1);
2412 lcount++;
2413 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2414 if (lcount == 2)
2415 #endif
2416 must_64bit = 1;
2417 ch = *p++;
2418 } else if (t == 'U') {
2419 if (ucount >= 1)
2420 tcc_error("two 'u's in integer constant");
2421 ucount++;
2422 ch = *p++;
2423 } else {
2424 break;
2428 /* Whether 64 bits are needed to hold the constant's value */
2429 if (n & 0xffffffff00000000LL || must_64bit) {
2430 tok = TOK_CLLONG;
2431 n1 = n >> 32;
2432 } else {
2433 tok = TOK_CINT;
2434 n1 = n;
2437 /* Whether type must be unsigned to hold the constant's value */
2438 if (ucount || ((n1 >> 31) && (b != 10))) {
2439 if (tok == TOK_CLLONG)
2440 tok = TOK_CULLONG;
2441 else
2442 tok = TOK_CUINT;
2443 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2444 } else if (n1 >> 31) {
2445 if (tok == TOK_CINT)
2446 tok = TOK_CLLONG;
2447 else
2448 tcc_error("integer constant overflow");
2451 tokc.i = n;
2453 if (ch)
2454 tcc_error("invalid number\n");
2458 #define PARSE2(c1, tok1, c2, tok2) \
2459 case c1: \
2460 PEEKC(c, p); \
2461 if (c == c2) { \
2462 p++; \
2463 tok = tok2; \
2464 } else { \
2465 tok = tok1; \
2467 break;
2469 /* return next token without macro substitution */
2470 static inline void next_nomacro1(void)
2472 int t, c, is_long, len;
2473 TokenSym *ts;
2474 uint8_t *p, *p1;
2475 unsigned int h;
2477 p = file->buf_ptr;
2478 redo_no_start:
2479 c = *p;
2480 switch(c) {
2481 case ' ':
2482 case '\t':
2483 tok = c;
2484 p++;
2485 if (parse_flags & PARSE_FLAG_SPACES)
2486 goto keep_tok_flags;
2487 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2488 ++p;
2489 goto redo_no_start;
2490 case '\f':
2491 case '\v':
2492 case '\r':
2493 p++;
2494 goto redo_no_start;
2495 case '\\':
2496 /* first look if it is in fact an end of buffer */
2497 c = handle_stray1(p);
2498 p = file->buf_ptr;
2499 if (c == '\\')
2500 goto parse_simple;
2501 if (c != CH_EOF)
2502 goto redo_no_start;
2504 TCCState *s1 = tcc_state;
2505 if ((parse_flags & PARSE_FLAG_LINEFEED)
2506 && !(tok_flags & TOK_FLAG_EOF)) {
2507 tok_flags |= TOK_FLAG_EOF;
2508 tok = TOK_LINEFEED;
2509 goto keep_tok_flags;
2510 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2511 tok = TOK_EOF;
2512 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2513 tcc_error("missing #endif");
2514 } else if (s1->include_stack_ptr == s1->include_stack) {
2515 /* no include left : end of file. */
2516 tok = TOK_EOF;
2517 } else {
2518 tok_flags &= ~TOK_FLAG_EOF;
2519 /* pop include file */
2521 /* test if previous '#endif' was after a #ifdef at
2522 start of file */
2523 if (tok_flags & TOK_FLAG_ENDIF) {
2524 #ifdef INC_DEBUG
2525 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2526 #endif
2527 search_cached_include(s1, file->filename, 1)
2528 ->ifndef_macro = file->ifndef_macro_saved;
2529 tok_flags &= ~TOK_FLAG_ENDIF;
2532 /* add end of include file debug info */
2533 if (tcc_state->do_debug) {
2534 put_stabd(N_EINCL, 0, 0);
2536 /* pop include stack */
2537 tcc_close();
2538 s1->include_stack_ptr--;
2539 p = file->buf_ptr;
2540 goto redo_no_start;
2543 break;
2545 case '\n':
2546 file->line_num++;
2547 tok_flags |= TOK_FLAG_BOL;
2548 p++;
2549 maybe_newline:
2550 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2551 goto redo_no_start;
2552 tok = TOK_LINEFEED;
2553 goto keep_tok_flags;
2555 case '#':
2556 /* XXX: simplify */
2557 PEEKC(c, p);
2558 if ((tok_flags & TOK_FLAG_BOL) &&
2559 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2560 file->buf_ptr = p;
2561 preprocess(tok_flags & TOK_FLAG_BOF);
2562 p = file->buf_ptr;
2563 goto maybe_newline;
2564 } else {
2565 if (c == '#') {
2566 p++;
2567 tok = TOK_TWOSHARPS;
2568 } else {
2569 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2570 p = parse_line_comment(p - 1);
2571 goto redo_no_start;
2572 } else {
2573 tok = '#';
2577 break;
2579 /* dollar is allowed to start identifiers when not parsing asm */
2580 case '$':
2581 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2582 || (parse_flags & PARSE_FLAG_ASM_FILE))
2583 goto parse_simple;
2585 case 'a': case 'b': case 'c': case 'd':
2586 case 'e': case 'f': case 'g': case 'h':
2587 case 'i': case 'j': case 'k': case 'l':
2588 case 'm': case 'n': case 'o': case 'p':
2589 case 'q': case 'r': case 's': case 't':
2590 case 'u': case 'v': case 'w': case 'x':
2591 case 'y': case 'z':
2592 case 'A': case 'B': case 'C': case 'D':
2593 case 'E': case 'F': case 'G': case 'H':
2594 case 'I': case 'J': case 'K':
2595 case 'M': case 'N': case 'O': case 'P':
2596 case 'Q': case 'R': case 'S': case 'T':
2597 case 'U': case 'V': case 'W': case 'X':
2598 case 'Y': case 'Z':
2599 case '_':
2600 parse_ident_fast:
2601 p1 = p;
2602 h = TOK_HASH_INIT;
2603 h = TOK_HASH_FUNC(h, c);
2604 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2605 h = TOK_HASH_FUNC(h, c);
2606 len = p - p1;
2607 if (c != '\\') {
2608 TokenSym **pts;
2610 /* fast case : no stray found, so we have the full token
2611 and we have already hashed it */
2612 h &= (TOK_HASH_SIZE - 1);
2613 pts = &hash_ident[h];
2614 for(;;) {
2615 ts = *pts;
2616 if (!ts)
2617 break;
2618 if (ts->len == len && !memcmp(ts->str, p1, len))
2619 goto token_found;
2620 pts = &(ts->hash_next);
2622 ts = tok_alloc_new(pts, (char *) p1, len);
2623 token_found: ;
2624 } else {
2625 /* slower case */
2626 cstr_reset(&tokcstr);
2627 cstr_cat(&tokcstr, (char *) p1, len);
2628 p--;
2629 PEEKC(c, p);
2630 parse_ident_slow:
2631 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2633 cstr_ccat(&tokcstr, c);
2634 PEEKC(c, p);
2636 ts = tok_alloc(tokcstr.data, tokcstr.size);
2638 tok = ts->tok;
2639 break;
2640 case 'L':
2641 t = p[1];
2642 if (t != '\\' && t != '\'' && t != '\"') {
2643 /* fast case */
2644 goto parse_ident_fast;
2645 } else {
2646 PEEKC(c, p);
2647 if (c == '\'' || c == '\"') {
2648 is_long = 1;
2649 goto str_const;
2650 } else {
2651 cstr_reset(&tokcstr);
2652 cstr_ccat(&tokcstr, 'L');
2653 goto parse_ident_slow;
2656 break;
2658 case '0': case '1': case '2': case '3':
2659 case '4': case '5': case '6': case '7':
2660 case '8': case '9':
2661 t = c;
2662 PEEKC(c, p);
2663 /* after the first digit, accept digits, alpha, '.' or sign if
2664 prefixed by 'eEpP' */
2665 parse_num:
2666 cstr_reset(&tokcstr);
2667 for(;;) {
2668 cstr_ccat(&tokcstr, t);
2669 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2670 || c == '.'
2671 || ((c == '+' || c == '-')
2672 && (((t == 'e' || t == 'E')
2673 && !(parse_flags & PARSE_FLAG_ASM_FILE
2674 /* 0xe+1 is 3 tokens in asm */
2675 && ((char*)tokcstr.data)[0] == '0'
2676 && toup(((char*)tokcstr.data)[1]) == 'X'))
2677 || t == 'p' || t == 'P'))))
2678 break;
2679 t = c;
2680 PEEKC(c, p);
2682 /* We add a trailing '\0' to ease parsing */
2683 cstr_ccat(&tokcstr, '\0');
2684 tokc.str.size = tokcstr.size;
2685 tokc.str.data = tokcstr.data;
2686 tok = TOK_PPNUM;
2687 break;
2689 case '.':
2690 /* special dot handling because it can also start a number */
2691 PEEKC(c, p);
2692 if (isnum(c)) {
2693 t = '.';
2694 goto parse_num;
2695 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2696 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2697 *--p = c = '.';
2698 goto parse_ident_fast;
2699 } else if (c == '.') {
2700 PEEKC(c, p);
2701 if (c == '.') {
2702 p++;
2703 tok = TOK_DOTS;
2704 } else {
2705 *--p = '.'; /* may underflow into file->unget[] */
2706 tok = '.';
2708 } else {
2709 tok = '.';
2711 break;
2712 case '\'':
2713 case '\"':
2714 is_long = 0;
2715 str_const:
2716 cstr_reset(&tokcstr);
2717 if (is_long)
2718 cstr_ccat(&tokcstr, 'L');
2719 cstr_ccat(&tokcstr, c);
2720 p = parse_pp_string(p, c, &tokcstr);
2721 cstr_ccat(&tokcstr, c);
2722 cstr_ccat(&tokcstr, '\0');
2723 tokc.str.size = tokcstr.size;
2724 tokc.str.data = tokcstr.data;
2725 tok = TOK_PPSTR;
2726 break;
2728 case '<':
2729 PEEKC(c, p);
2730 if (c == '=') {
2731 p++;
2732 tok = TOK_LE;
2733 } else if (c == '<') {
2734 PEEKC(c, p);
2735 if (c == '=') {
2736 p++;
2737 tok = TOK_A_SHL;
2738 } else {
2739 tok = TOK_SHL;
2741 } else {
2742 tok = TOK_LT;
2744 break;
2745 case '>':
2746 PEEKC(c, p);
2747 if (c == '=') {
2748 p++;
2749 tok = TOK_GE;
2750 } else if (c == '>') {
2751 PEEKC(c, p);
2752 if (c == '=') {
2753 p++;
2754 tok = TOK_A_SAR;
2755 } else {
2756 tok = TOK_SAR;
2758 } else {
2759 tok = TOK_GT;
2761 break;
2763 case '&':
2764 PEEKC(c, p);
2765 if (c == '&') {
2766 p++;
2767 tok = TOK_LAND;
2768 } else if (c == '=') {
2769 p++;
2770 tok = TOK_A_AND;
2771 } else {
2772 tok = '&';
2774 break;
2776 case '|':
2777 PEEKC(c, p);
2778 if (c == '|') {
2779 p++;
2780 tok = TOK_LOR;
2781 } else if (c == '=') {
2782 p++;
2783 tok = TOK_A_OR;
2784 } else {
2785 tok = '|';
2787 break;
2789 case '+':
2790 PEEKC(c, p);
2791 if (c == '+') {
2792 p++;
2793 tok = TOK_INC;
2794 } else if (c == '=') {
2795 p++;
2796 tok = TOK_A_ADD;
2797 } else {
2798 tok = '+';
2800 break;
2802 case '-':
2803 PEEKC(c, p);
2804 if (c == '-') {
2805 p++;
2806 tok = TOK_DEC;
2807 } else if (c == '=') {
2808 p++;
2809 tok = TOK_A_SUB;
2810 } else if (c == '>') {
2811 p++;
2812 tok = TOK_ARROW;
2813 } else {
2814 tok = '-';
2816 break;
2818 PARSE2('!', '!', '=', TOK_NE)
2819 PARSE2('=', '=', '=', TOK_EQ)
2820 PARSE2('*', '*', '=', TOK_A_MUL)
2821 PARSE2('%', '%', '=', TOK_A_MOD)
2822 PARSE2('^', '^', '=', TOK_A_XOR)
2824 /* comments or operator */
2825 case '/':
2826 PEEKC(c, p);
2827 if (c == '*') {
2828 p = parse_comment(p);
2829 /* comments replaced by a blank */
2830 tok = ' ';
2831 goto keep_tok_flags;
2832 } else if (c == '/') {
2833 p = parse_line_comment(p);
2834 tok = ' ';
2835 goto keep_tok_flags;
2836 } else if (c == '=') {
2837 p++;
2838 tok = TOK_A_DIV;
2839 } else {
2840 tok = '/';
2842 break;
2844 /* simple tokens */
2845 case '(':
2846 case ')':
2847 case '[':
2848 case ']':
2849 case '{':
2850 case '}':
2851 case ',':
2852 case ';':
2853 case ':':
2854 case '?':
2855 case '~':
2856 case '@': /* only used in assembler */
2857 parse_simple:
2858 tok = c;
2859 p++;
2860 break;
2861 default:
2862 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2863 goto parse_ident_fast;
2864 if (parse_flags & PARSE_FLAG_ASM_FILE)
2865 goto parse_simple;
2866 tcc_error("unrecognized character \\x%02x", c);
2867 break;
2869 tok_flags = 0;
2870 keep_tok_flags:
2871 file->buf_ptr = p;
2872 #if defined(PARSE_DEBUG)
2873 printf("token = %s\n", get_tok_str(tok, &tokc));
2874 #endif
2877 /* return next token without macro substitution. Can read input from
2878 macro_ptr buffer */
2879 static void next_nomacro_spc(void)
2881 if (macro_ptr) {
2882 redo:
2883 tok = *macro_ptr;
2884 if (tok) {
2885 TOK_GET(&tok, &macro_ptr, &tokc);
2886 if (tok == TOK_LINENUM) {
2887 file->line_num = tokc.i;
2888 goto redo;
2891 } else {
2892 next_nomacro1();
2894 //printf("token = %s\n", get_tok_str(tok, &tokc));
2897 ST_FUNC void next_nomacro(void)
2899 do {
2900 next_nomacro_spc();
2901 } while (tok < 256 && (isidnum_table[tok - CH_EOF] & IS_SPC));
2905 static void macro_subst(
2906 TokenString *tok_str,
2907 Sym **nested_list,
2908 const int *macro_str
2911 /* substitute arguments in replacement lists in macro_str by the values in
2912 args (field d) and return allocated string */
2913 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2915 int t, t0, t1, spc;
2916 const int *st;
2917 Sym *s;
2918 CValue cval;
2919 TokenString str;
2920 CString cstr;
2922 tok_str_new(&str);
2923 t0 = t1 = 0;
2924 while(1) {
2925 TOK_GET(&t, &macro_str, &cval);
2926 if (!t)
2927 break;
2928 if (t == '#') {
2929 /* stringize */
2930 TOK_GET(&t, &macro_str, &cval);
2931 if (!t)
2932 goto bad_stringy;
2933 s = sym_find2(args, t);
2934 if (s) {
2935 cstr_new(&cstr);
2936 cstr_ccat(&cstr, '\"');
2937 st = s->d;
2938 spc = 0;
2939 while (*st >= 0) {
2940 TOK_GET(&t, &st, &cval);
2941 if (t != TOK_PLCHLDR
2942 && t != TOK_NOSUBST
2943 && 0 == check_space(t, &spc)) {
2944 const char *s = get_tok_str(t, &cval);
2945 while (*s) {
2946 if (t == TOK_PPSTR && *s != '\'')
2947 add_char(&cstr, *s);
2948 else
2949 cstr_ccat(&cstr, *s);
2950 ++s;
2954 cstr.size -= spc;
2955 cstr_ccat(&cstr, '\"');
2956 cstr_ccat(&cstr, '\0');
2957 #ifdef PP_DEBUG
2958 printf("\nstringize: <%s>\n", (char *)cstr.data);
2959 #endif
2960 /* add string */
2961 cval.str.size = cstr.size;
2962 cval.str.data = cstr.data;
2963 tok_str_add2(&str, TOK_PPSTR, &cval);
2964 cstr_free(&cstr);
2965 } else {
2966 bad_stringy:
2967 expect("macro parameter after '#'");
2969 } else if (t >= TOK_IDENT) {
2970 s = sym_find2(args, t);
2971 if (s) {
2972 int l0 = str.len;
2973 st = s->d;
2974 /* if '##' is present before or after, no arg substitution */
2975 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
2976 /* special case for var arg macros : ## eats the ','
2977 if empty VA_ARGS variable. */
2978 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
2979 if (*st <= 0) {
2980 /* suppress ',' '##' */
2981 str.len -= 2;
2982 } else {
2983 /* suppress '##' and add variable */
2984 str.len--;
2985 goto add_var;
2988 } else {
2989 add_var:
2990 if (!s->next) {
2991 /* Expand arguments tokens and store them. In most
2992 cases we could also re-expand each argument if
2993 used multiple times, but not if the argument
2994 contains the __COUNTER__ macro. */
2995 TokenString str2;
2996 sym_push2(&s->next, s->v, s->type.t, 0);
2997 tok_str_new(&str2);
2998 macro_subst(&str2, nested_list, st);
2999 tok_str_add(&str2, 0);
3000 s->next->d = str2.str;
3002 st = s->next->d;
3004 for(;;) {
3005 int t2;
3006 TOK_GET(&t2, &st, &cval);
3007 if (t2 <= 0)
3008 break;
3009 tok_str_add2(&str, t2, &cval);
3011 if (str.len == l0) /* expanded to empty string */
3012 tok_str_add(&str, TOK_PLCHLDR);
3013 } else {
3014 tok_str_add(&str, t);
3016 } else {
3017 tok_str_add2(&str, t, &cval);
3019 t0 = t1, t1 = t;
3021 tok_str_add(&str, 0);
3022 return str.str;
3025 static char const ab_month_name[12][4] =
3027 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3028 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3031 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3033 CString cstr;
3034 int n, ret = 1;
3036 cstr_new(&cstr);
3037 if (t1 != TOK_PLCHLDR)
3038 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3039 n = cstr.size;
3040 if (t2 != TOK_PLCHLDR)
3041 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3042 cstr_ccat(&cstr, '\0');
3044 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3045 memcpy(file->buffer, cstr.data, cstr.size);
3046 for (;;) {
3047 next_nomacro1();
3048 if (0 == *file->buf_ptr)
3049 break;
3050 if (is_space(tok))
3051 continue;
3052 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3053 " preprocessing token", n, cstr.data, (char*)cstr.data + n);
3054 ret = 0;
3055 break;
3057 tcc_close();
3058 //printf("paste <%s>\n", (char*)cstr.data);
3059 cstr_free(&cstr);
3060 return ret;
3063 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3064 return the resulting string (which must be freed). */
3065 static inline int *macro_twosharps(const int *ptr0)
3067 int t;
3068 CValue cval;
3069 TokenString macro_str1;
3070 int start_of_nosubsts = -1;
3071 const int *ptr;
3073 /* we search the first '##' */
3074 for (ptr = ptr0;;) {
3075 TOK_GET(&t, &ptr, &cval);
3076 if (t == TOK_PPJOIN)
3077 break;
3078 if (t == 0)
3079 return NULL;
3082 tok_str_new(&macro_str1);
3084 //tok_print(" $$$", ptr0);
3085 for (ptr = ptr0;;) {
3086 TOK_GET(&t, &ptr, &cval);
3087 if (t == 0)
3088 break;
3089 if (t == TOK_PPJOIN)
3090 continue;
3091 while (*ptr == TOK_PPJOIN) {
3092 int t1; CValue cv1;
3093 /* given 'a##b', remove nosubsts preceding 'a' */
3094 if (start_of_nosubsts >= 0)
3095 macro_str1.len = start_of_nosubsts;
3096 /* given 'a##b', remove nosubsts preceding 'b' */
3097 while ((t1 = *++ptr) == TOK_NOSUBST)
3099 if (t1 && t1 != TOK_PPJOIN) {
3100 TOK_GET(&t1, &ptr, &cv1);
3101 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3102 if (paste_tokens(t, &cval, t1, &cv1)) {
3103 t = tok, cval = tokc;
3104 } else {
3105 tok_str_add2(&macro_str1, t, &cval);
3106 t = t1, cval = cv1;
3111 if (t == TOK_NOSUBST) {
3112 if (start_of_nosubsts < 0)
3113 start_of_nosubsts = macro_str1.len;
3114 } else {
3115 start_of_nosubsts = -1;
3117 tok_str_add2(&macro_str1, t, &cval);
3119 tok_str_add(&macro_str1, 0);
3120 //tok_print(" ###", macro_str1.str);
3121 return macro_str1.str;
3124 /* peek or read [ws_str == NULL] next token from function macro call,
3125 walking up macro levels up to the file if necessary */
3126 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3128 int t;
3129 const int *p;
3130 Sym *sa;
3132 for (;;) {
3133 if (macro_ptr) {
3134 p = macro_ptr, t = *p;
3135 if (ws_str) {
3136 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3137 tok_str_add(ws_str, t), t = *++p;
3139 if (t == 0) {
3140 end_macro();
3141 /* also, end of scope for nested defined symbol */
3142 sa = *nested_list;
3143 while (sa && sa->v == 0)
3144 sa = sa->prev;
3145 if (sa)
3146 sa->v = 0;
3147 continue;
3149 } else {
3150 ch = handle_eob();
3151 if (ws_str) {
3152 while (is_space(ch) || ch == '\n' || ch == '/') {
3153 if (ch == '/') {
3154 int c;
3155 uint8_t *p = file->buf_ptr;
3156 PEEKC(c, p);
3157 if (c == '*') {
3158 p = parse_comment(p);
3159 file->buf_ptr = p - 1;
3160 } else if (c == '/') {
3161 p = parse_line_comment(p);
3162 file->buf_ptr = p - 1;
3163 } else
3164 break;
3165 ch = ' ';
3167 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3168 tok_str_add(ws_str, ch);
3169 cinp();
3172 t = ch;
3175 if (ws_str)
3176 return t;
3177 next_nomacro_spc();
3178 return tok;
3182 /* do macro substitution of current token with macro 's' and add
3183 result to (tok_str,tok_len). 'nested_list' is the list of all
3184 macros we got inside to avoid recursing. Return non zero if no
3185 substitution needs to be done */
3186 static int macro_subst_tok(
3187 TokenString *tok_str,
3188 Sym **nested_list,
3189 Sym *s)
3191 Sym *args, *sa, *sa1;
3192 int parlevel, *mstr, t, t1, spc;
3193 TokenString str;
3194 char *cstrval;
3195 CValue cval;
3196 CString cstr;
3197 char buf[32];
3198 static int counter;
3200 /* if symbol is a macro, prepare substitution */
3201 /* special macros */
3202 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3203 t = tok == TOK___LINE__ ? file->line_num : counter++;
3204 snprintf(buf, sizeof(buf), "%d", t);
3205 cstrval = buf;
3206 t1 = TOK_PPNUM;
3207 goto add_cstr1;
3208 } else if (tok == TOK___FILE__) {
3209 cstrval = file->filename;
3210 goto add_cstr;
3211 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3212 time_t ti;
3213 struct tm *tm;
3215 time(&ti);
3216 tm = localtime(&ti);
3217 if (tok == TOK___DATE__) {
3218 snprintf(buf, sizeof(buf), "%s %2d %d",
3219 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3220 } else {
3221 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3222 tm->tm_hour, tm->tm_min, tm->tm_sec);
3224 cstrval = buf;
3225 add_cstr:
3226 t1 = TOK_STR;
3227 add_cstr1:
3228 cstr_new(&cstr);
3229 cstr_cat(&cstr, cstrval, 0);
3230 cval.str.size = cstr.size;
3231 cval.str.data = cstr.data;
3232 tok_str_add2(tok_str, t1, &cval);
3233 cstr_free(&cstr);
3234 } else {
3235 int saved_parse_flags = parse_flags;
3236 int *joined_str = NULL;
3238 mstr = s->d;
3239 if (s->type.t == MACRO_FUNC) {
3240 /* whitespace between macro name and argument list */
3241 TokenString ws_str;
3242 tok_str_new(&ws_str);
3244 spc = 0;
3245 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3246 | PARSE_FLAG_ACCEPT_STRAYS;
3248 /* get next token from argument stream */
3249 t = next_argstream(nested_list, &ws_str);
3250 if (t != '(') {
3251 /* not a macro substitution after all, restore the
3252 * macro token plus all whitespace we've read.
3253 * whitespace is intentionally not merged to preserve
3254 * newlines. */
3255 parse_flags = saved_parse_flags;
3256 tok_str_add(tok_str, tok);
3257 if (parse_flags & PARSE_FLAG_SPACES) {
3258 int i;
3259 for (i = 0; i < ws_str.len; i++)
3260 tok_str_add(tok_str, ws_str.str[i]);
3262 tok_str_free_str(ws_str.str);
3263 return 0;
3264 } else {
3265 tok_str_free_str(ws_str.str);
3267 do {
3268 next_nomacro(); /* eat '(' */
3269 } while (tok == TOK_PLCHLDR);
3271 /* argument macro */
3272 args = NULL;
3273 sa = s->next;
3274 /* NOTE: empty args are allowed, except if no args */
3275 for(;;) {
3276 do {
3277 next_argstream(nested_list, NULL);
3278 } while (is_space(tok) || TOK_LINEFEED == tok);
3279 empty_arg:
3280 /* handle '()' case */
3281 if (!args && !sa && tok == ')')
3282 break;
3283 if (!sa)
3284 tcc_error("macro '%s' used with too many args",
3285 get_tok_str(s->v, 0));
3286 tok_str_new(&str);
3287 parlevel = spc = 0;
3288 /* NOTE: non zero sa->t indicates VA_ARGS */
3289 while ((parlevel > 0 ||
3290 (tok != ')' &&
3291 (tok != ',' || sa->type.t)))) {
3292 if (tok == TOK_EOF || tok == 0)
3293 break;
3294 if (tok == '(')
3295 parlevel++;
3296 else if (tok == ')')
3297 parlevel--;
3298 if (tok == TOK_LINEFEED)
3299 tok = ' ';
3300 if (!check_space(tok, &spc))
3301 tok_str_add2(&str, tok, &tokc);
3302 next_argstream(nested_list, NULL);
3304 if (parlevel)
3305 expect(")");
3306 str.len -= spc;
3307 tok_str_add(&str, -1);
3308 tok_str_add(&str, 0);
3309 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3310 sa1->d = str.str;
3311 sa = sa->next;
3312 if (tok == ')') {
3313 /* special case for gcc var args: add an empty
3314 var arg argument if it is omitted */
3315 if (sa && sa->type.t && gnu_ext)
3316 goto empty_arg;
3317 break;
3319 if (tok != ',')
3320 expect(",");
3322 if (sa) {
3323 tcc_error("macro '%s' used with too few args",
3324 get_tok_str(s->v, 0));
3327 parse_flags = saved_parse_flags;
3329 /* now subst each arg */
3330 mstr = macro_arg_subst(nested_list, mstr, args);
3331 /* free memory */
3332 sa = args;
3333 while (sa) {
3334 sa1 = sa->prev;
3335 tok_str_free_str(sa->d);
3336 if (sa->next) {
3337 tok_str_free_str(sa->next->d);
3338 sym_free(sa->next);
3340 sym_free(sa);
3341 sa = sa1;
3345 sym_push2(nested_list, s->v, 0, 0);
3346 parse_flags = saved_parse_flags;
3347 joined_str = macro_twosharps(mstr);
3348 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3350 /* pop nested defined symbol */
3351 sa1 = *nested_list;
3352 *nested_list = sa1->prev;
3353 sym_free(sa1);
3354 if (joined_str)
3355 tok_str_free_str(joined_str);
3356 if (mstr != s->d)
3357 tok_str_free_str(mstr);
3359 return 0;
3362 /* do macro substitution of macro_str and add result to
3363 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3364 inside to avoid recursing. */
3365 static void macro_subst(
3366 TokenString *tok_str,
3367 Sym **nested_list,
3368 const int *macro_str
3371 Sym *s;
3372 int t, spc, nosubst;
3373 CValue cval;
3375 spc = nosubst = 0;
3377 while (1) {
3378 TOK_GET(&t, &macro_str, &cval);
3379 if (t <= 0)
3380 break;
3382 if (t >= TOK_IDENT && 0 == nosubst) {
3383 s = define_find(t);
3384 if (s == NULL)
3385 goto no_subst;
3387 /* if nested substitution, do nothing */
3388 if (sym_find2(*nested_list, t)) {
3389 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3390 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3391 goto no_subst;
3395 TokenString str;
3396 str.str = (int*)macro_str;
3397 begin_macro(&str, 2);
3399 tok = t;
3400 macro_subst_tok(tok_str, nested_list, s);
3402 if (str.alloc == 3) {
3403 /* already finished by reading function macro arguments */
3404 break;
3407 macro_str = macro_ptr;
3408 end_macro ();
3410 if (tok_str->len)
3411 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3412 } else {
3413 if (t == '\\' && !(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3414 tcc_error("stray '\\' in program");
3415 no_subst:
3416 if (!check_space(t, &spc))
3417 tok_str_add2(tok_str, t, &cval);
3419 if (nosubst) {
3420 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3421 continue;
3422 nosubst = 0;
3424 if (t == TOK_NOSUBST)
3425 nosubst = 1;
3427 /* GCC supports 'defined' as result of a macto substitution */
3428 if (t == TOK_DEFINED && pp_expr)
3429 nosubst = 2;
3433 /* return next token with macro substitution */
3434 ST_FUNC void next(void)
3436 redo:
3437 if (parse_flags & PARSE_FLAG_SPACES)
3438 next_nomacro_spc();
3439 else
3440 next_nomacro();
3442 if (macro_ptr) {
3443 if (tok == TOK_NOSUBST || tok == TOK_PLCHLDR) {
3444 /* discard preprocessor markers */
3445 goto redo;
3446 } else if (tok == 0) {
3447 /* end of macro or unget token string */
3448 end_macro();
3449 goto redo;
3451 } else if (tok >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3452 Sym *s;
3453 /* if reading from file, try to substitute macros */
3454 s = define_find(tok);
3455 if (s) {
3456 Sym *nested_list = NULL;
3457 tokstr_buf.len = 0;
3458 macro_subst_tok(&tokstr_buf, &nested_list, s);
3459 tok_str_add(&tokstr_buf, 0);
3460 begin_macro(&tokstr_buf, 2);
3461 goto redo;
3464 /* convert preprocessor tokens into C tokens */
3465 if (tok == TOK_PPNUM) {
3466 if (parse_flags & PARSE_FLAG_TOK_NUM)
3467 parse_number((char *)tokc.str.data);
3468 } else if (tok == TOK_PPSTR) {
3469 if (parse_flags & PARSE_FLAG_TOK_STR)
3470 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3474 /* push back current token and set current token to 'last_tok'. Only
3475 identifier case handled for labels. */
3476 ST_INLN void unget_tok(int last_tok)
3479 TokenString *str = tok_str_alloc();
3480 tok_str_add2(str, tok, &tokc);
3481 tok_str_add(str, 0);
3482 begin_macro(str, 1);
3483 tok = last_tok;
3486 ST_FUNC void preprocess_start(TCCState *s1)
3488 char *buf;
3490 s1->include_stack_ptr = s1->include_stack;
3491 s1->ifdef_stack_ptr = s1->ifdef_stack;
3492 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3493 pp_once++;
3494 pvtop = vtop = vstack - 1;
3495 s1->pack_stack[0] = 0;
3496 s1->pack_stack_ptr = s1->pack_stack;
3498 set_idnum('$', s1->dollars_in_identifiers ? IS_ID : 0);
3499 set_idnum('.', (parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0);
3501 buf = tcc_malloc(3 + strlen(file->filename));
3502 sprintf(buf, "\"%s\"", file->filename);
3503 tcc_define_symbol(s1, "__BASE_FILE__", buf);
3504 tcc_free(buf);
3506 if (s1->nb_cmd_include_files) {
3507 CString cstr;
3508 int i;
3509 cstr_new(&cstr);
3510 for (i = 0; i < s1->nb_cmd_include_files; i++) {
3511 cstr_cat(&cstr, "#include \"", -1);
3512 cstr_cat(&cstr, s1->cmd_include_files[i], -1);
3513 cstr_cat(&cstr, "\"\n", -1);
3515 *s1->include_stack_ptr++ = file;
3516 tcc_open_bf(s1, "<command line>", cstr.size);
3517 memcpy(file->buffer, cstr.data, cstr.size);
3518 cstr_free(&cstr);
3522 ST_FUNC void tccpp_new(TCCState *s)
3524 int i, c;
3525 const char *p, *r;
3527 /* might be used in error() before preprocess_start() */
3528 s->include_stack_ptr = s->include_stack;
3530 /* init isid table */
3531 for(i = CH_EOF; i<128; i++)
3532 set_idnum(i,
3533 is_space(i) ? IS_SPC
3534 : isid(i) ? IS_ID
3535 : isnum(i) ? IS_NUM
3536 : 0);
3538 for(i = 128; i<256; i++)
3539 set_idnum(i, IS_ID);
3541 /* init allocators */
3542 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3543 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3544 tal_new(&cstr_alloc, CSTR_TAL_LIMIT, CSTR_TAL_SIZE);
3546 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3547 cstr_new(&cstr_buf);
3548 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3549 tok_str_new(&tokstr_buf);
3550 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3552 tok_ident = TOK_IDENT;
3553 p = tcc_keywords;
3554 while (*p) {
3555 r = p;
3556 for(;;) {
3557 c = *r++;
3558 if (c == '\0')
3559 break;
3561 tok_alloc(p, r - p - 1);
3562 p = r;
3566 ST_FUNC void tccpp_delete(TCCState *s)
3568 int i, n;
3570 /* free -D and compiler defines */
3571 free_defines(NULL);
3573 /* cleanup from error/setjmp */
3574 while (macro_stack)
3575 end_macro();
3576 macro_ptr = NULL;
3578 while (file)
3579 tcc_close();
3581 /* free tokens */
3582 n = tok_ident - TOK_IDENT;
3583 for(i = 0; i < n; i++)
3584 tal_free(toksym_alloc, table_ident[i]);
3585 tcc_free(table_ident);
3586 table_ident = NULL;
3588 /* free static buffers */
3589 cstr_free(&tokcstr);
3590 cstr_free(&cstr_buf);
3591 cstr_free(&macro_equal_buf);
3592 tok_str_free_str(tokstr_buf.str);
3594 /* free allocators */
3595 tal_delete(toksym_alloc);
3596 toksym_alloc = NULL;
3597 tal_delete(tokstr_alloc);
3598 tokstr_alloc = NULL;
3599 tal_delete(cstr_alloc);
3600 cstr_alloc = NULL;
3603 /* ------------------------------------------------------------------------- */
3604 /* tcc -E [-P[1]] [-dD} support */
3606 static void tok_print(const char *msg, const int *str)
3608 FILE *fp;
3609 int t;
3610 CValue cval;
3612 fp = tcc_state->ppfp;
3613 if (!fp || !tcc_state->dflag)
3614 fp = stdout;
3616 fprintf(fp, "%s ", msg);
3617 while (str) {
3618 TOK_GET(&t, &str, &cval);
3619 if (!t)
3620 break;
3621 fprintf(fp,"%s", get_tok_str(t, &cval));
3623 fprintf(fp, "\n");
3626 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3628 int d = f->line_num - f->line_ref;
3630 if (s1->dflag & 4)
3631 return;
3633 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3635 } else if (level == 0 && f->line_ref && d < 8) {
3636 while (d > 0)
3637 fputs("\n", s1->ppfp), --d;
3638 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3639 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3640 } else {
3641 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3642 level > 0 ? " 1" : level < 0 ? " 2" : "");
3644 f->line_ref = f->line_num;
3647 static void define_print(TCCState *s1, int v)
3649 FILE *fp;
3650 Sym *s;
3652 s = define_find(v);
3653 if (NULL == s || NULL == s->d)
3654 return;
3656 fp = s1->ppfp;
3657 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3658 if (s->type.t == MACRO_FUNC) {
3659 Sym *a = s->next;
3660 fprintf(fp,"(");
3661 if (a)
3662 for (;;) {
3663 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3664 if (!(a = a->next))
3665 break;
3666 fprintf(fp,",");
3668 fprintf(fp,")");
3670 tok_print("", s->d);
3673 static void pp_debug_defines(TCCState *s1)
3675 int v, t;
3676 const char *vs;
3677 FILE *fp;
3679 t = pp_debug_tok;
3680 if (t == 0)
3681 return;
3683 file->line_num--;
3684 pp_line(s1, file, 0);
3685 file->line_ref = ++file->line_num;
3687 fp = s1->ppfp;
3688 v = pp_debug_symv;
3689 vs = get_tok_str(v, NULL);
3690 if (t == TOK_DEFINE) {
3691 define_print(s1, v);
3692 } else if (t == TOK_UNDEF) {
3693 fprintf(fp, "#undef %s\n", vs);
3694 } else if (t == TOK_push_macro) {
3695 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3696 } else if (t == TOK_pop_macro) {
3697 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3699 pp_debug_tok = 0;
3702 static void pp_debug_builtins(TCCState *s1)
3704 int v;
3705 for (v = TOK_IDENT; v < tok_ident; ++v)
3706 define_print(s1, v);
3709 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3710 static int pp_need_space(int a, int b)
3712 return 'E' == a ? '+' == b || '-' == b
3713 : '+' == a ? TOK_INC == b || '+' == b
3714 : '-' == a ? TOK_DEC == b || '-' == b
3715 : a >= TOK_IDENT ? b >= TOK_IDENT
3716 : a == TOK_PPNUM ? b >= TOK_IDENT
3717 : 0;
3720 /* maybe hex like 0x1e */
3721 static int pp_check_he0xE(int t, const char *p)
3723 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3724 return 'E';
3725 return t;
3728 /* Preprocess the current file */
3729 ST_FUNC int tcc_preprocess(TCCState *s1)
3731 BufferedFile **iptr;
3732 int token_seen, spcs, level;
3733 const char *p;
3734 Sym *define_start;
3736 define_start = define_stack;
3737 preprocess_start(s1);
3739 ch = file->buf_ptr[0];
3740 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3741 parse_flags = PARSE_FLAG_PREPROCESS
3742 | (parse_flags & PARSE_FLAG_ASM_FILE)
3743 | PARSE_FLAG_LINEFEED
3744 | PARSE_FLAG_SPACES
3745 | PARSE_FLAG_ACCEPT_STRAYS
3748 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3749 capability to compile and run itself, provided all numbers are
3750 given as decimals. tcc -E -P10 will do. */
3751 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3752 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3754 #ifdef PP_BENCH
3755 /* for PP benchmarks */
3756 do next(); while (tok != TOK_EOF);
3757 free_defines(define_start);
3758 return 0;
3759 #endif
3761 if (s1->dflag & 1) {
3762 pp_debug_builtins(s1);
3763 s1->dflag &= ~1;
3766 token_seen = TOK_LINEFEED, spcs = 0;
3767 pp_line(s1, file, 0);
3769 for (;;) {
3770 iptr = s1->include_stack_ptr;
3771 next();
3772 if (tok == TOK_EOF)
3773 break;
3774 level = s1->include_stack_ptr - iptr;
3775 if (level) {
3776 if (level > 0)
3777 pp_line(s1, *iptr, 0);
3778 pp_line(s1, file, level);
3781 if (s1->dflag) {
3782 pp_debug_defines(s1);
3783 if (s1->dflag & 4)
3784 continue;
3787 if (token_seen == TOK_LINEFEED) {
3788 if (tok == ' ') {
3789 ++spcs;
3790 continue;
3792 if (tok == TOK_LINEFEED) {
3793 spcs = 0;
3794 continue;
3796 pp_line(s1, file, 0);
3797 } else if (tok == TOK_LINEFEED) {
3798 ++file->line_ref;
3799 } else {
3800 spcs = pp_need_space(token_seen, tok);
3803 while (spcs)
3804 fputs(" ", s1->ppfp), --spcs;
3805 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
3806 token_seen = pp_check_he0xE(tok, p);;
3808 /* reset define stack, but keep -D and built-ins */
3809 free_defines(define_start);
3810 return 0;
3813 /* ------------------------------------------------------------------------- */