the R_X86_64_GOTOFF64 relocation was missing
[tinycc.git] / tccpp.c
blobd70ddd60509db87c872b47fc184f6fdd5d33e44c
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 void tok_print(const char *msg, const int *str);
53 static struct TinyAlloc *toksym_alloc;
54 static struct TinyAlloc *tokstr_alloc;
55 static struct TinyAlloc *cstr_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 '.','.', 0xa8, // C++ token ?
91 '#','#', TOK_TWOSHARPS,
95 static void next_nomacro_spc(void);
97 ST_FUNC void skip(int c)
99 if (tok != c)
100 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
101 next();
104 ST_FUNC void expect(const char *msg)
106 tcc_error("%s expected", msg);
109 /* ------------------------------------------------------------------------- */
110 /* Custom allocator for tiny objects */
112 #define USE_TAL
114 #ifndef USE_TAL
115 #define tal_free(al, p) tcc_free(p)
116 #define tal_realloc(al, p, size) tcc_realloc(p, size)
117 #define tal_new(a,b,c)
118 #define tal_delete(a)
119 #else
120 #if !defined(MEM_DEBUG)
121 #define tal_free(al, p) tal_free_impl(al, p)
122 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
123 #define TAL_DEBUG_PARAMS
124 #else
125 #define TAL_DEBUG 1
126 //#define TAL_INFO 1 /* collect and dump allocators stats */
127 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
128 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
129 #define TAL_DEBUG_PARAMS , const char *file, int line
130 #define TAL_DEBUG_FILE_LEN 15
131 #endif
133 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
134 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
135 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
136 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
137 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
138 #define CSTR_TAL_LIMIT 1024
140 typedef struct TinyAlloc {
141 unsigned limit;
142 unsigned size;
143 uint8_t *buffer;
144 uint8_t *p;
145 unsigned nb_allocs;
146 struct TinyAlloc *next, *top;
147 #ifdef TAL_INFO
148 unsigned nb_peak;
149 unsigned nb_total;
150 unsigned nb_missed;
151 uint8_t *peak_p;
152 #endif
153 } TinyAlloc;
155 typedef struct tal_header_t {
156 unsigned size;
157 #ifdef TAL_DEBUG
158 int line_num; /* negative line_num used for double free check */
159 char file_name[TAL_DEBUG_FILE_LEN + 1];
160 #endif
161 } tal_header_t;
163 /* ------------------------------------------------------------------------- */
165 static TinyAlloc *tal_new(TinyAlloc **pal, unsigned limit, unsigned size)
167 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
168 al->p = al->buffer = tcc_malloc(size);
169 al->limit = limit;
170 al->size = size;
171 if (pal) *pal = al;
172 return al;
175 static void tal_delete(TinyAlloc *al)
177 TinyAlloc *next;
179 tail_call:
180 if (!al)
181 return;
182 #ifdef TAL_INFO
183 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
184 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
185 (al->peak_p - al->buffer) * 100.0 / al->size);
186 #endif
187 #ifdef TAL_DEBUG
188 if (al->nb_allocs > 0) {
189 uint8_t *p;
190 fprintf(stderr, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
191 al->nb_allocs, al->limit);
192 p = al->buffer;
193 while (p < al->p) {
194 tal_header_t *header = (tal_header_t *)p;
195 if (header->line_num > 0) {
196 fprintf(stderr, "%s:%d: chunk of %d bytes leaked\n",
197 header->file_name, header->line_num, header->size);
199 p += header->size + sizeof(tal_header_t);
201 #if MEM_DEBUG-0 == 2
202 exit(2);
203 #endif
205 #endif
206 next = al->next;
207 tcc_free(al->buffer);
208 tcc_free(al);
209 al = next;
210 goto tail_call;
213 static void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
215 if (!p)
216 return;
217 tail_call:
218 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
219 #ifdef TAL_DEBUG
220 tal_header_t *header = (((tal_header_t *)p) - 1);
221 if (header->line_num < 0) {
222 fprintf(stderr, "%s:%d: TAL_DEBUG: double frees chunk from\n",
223 file, line);
224 fprintf(stderr, "%s:%d: %d bytes\n",
225 header->file_name, (int)-header->line_num, (int)header->size);
226 } else
227 header->line_num = -header->line_num;
228 #endif
229 al->nb_allocs--;
230 if (!al->nb_allocs)
231 al->p = al->buffer;
232 } else if (al->next) {
233 al = al->next;
234 goto tail_call;
236 else
237 tcc_free(p);
240 static void *tal_realloc_impl(TinyAlloc **pal, void *p, unsigned size TAL_DEBUG_PARAMS)
242 tal_header_t *header;
243 void *ret;
244 int is_own;
245 unsigned adj_size = (size + 3) & -4;
246 TinyAlloc *al = *pal;
248 tail_call:
249 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
250 if ((!p || is_own) && size <= al->limit) {
251 if (al->p + adj_size + sizeof(tal_header_t) < al->buffer + al->size) {
252 header = (tal_header_t *)al->p;
253 header->size = adj_size;
254 #ifdef TAL_DEBUG
255 { int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
256 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
257 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
258 header->line_num = line; }
259 #endif
260 ret = al->p + sizeof(tal_header_t);
261 al->p += adj_size + sizeof(tal_header_t);
262 if (is_own) {
263 header = (((tal_header_t *)p) - 1);
264 memcpy(ret, p, header->size);
265 #ifdef TAL_DEBUG
266 header->line_num = -header->line_num;
267 #endif
268 } else {
269 al->nb_allocs++;
271 #ifdef TAL_INFO
272 if (al->nb_peak < al->nb_allocs)
273 al->nb_peak = al->nb_allocs;
274 if (al->peak_p < al->p)
275 al->peak_p = al->p;
276 al->nb_total++;
277 #endif
278 return ret;
279 } else if (is_own) {
280 al->nb_allocs--;
281 ret = tal_realloc(*pal, 0, size);
282 header = (((tal_header_t *)p) - 1);
283 memcpy(ret, p, header->size);
284 #ifdef TAL_DEBUG
285 header->line_num = -header->line_num;
286 #endif
287 return ret;
289 if (al->next) {
290 al = al->next;
291 } else {
292 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
294 al = tal_new(pal, next->limit, next->size * 2);
295 al->next = next;
296 bottom->top = al;
298 goto tail_call;
300 if (is_own) {
301 al->nb_allocs--;
302 ret = tcc_malloc(size);
303 header = (((tal_header_t *)p) - 1);
304 memcpy(ret, p, header->size);
305 #ifdef TAL_DEBUG
306 header->line_num = -header->line_num;
307 #endif
308 } else if (al->next) {
309 al = al->next;
310 goto tail_call;
311 } else
312 ret = tcc_realloc(p, size);
313 #ifdef TAL_INFO
314 al->nb_missed++;
315 #endif
316 return ret;
319 #endif /* USE_TAL */
321 /* ------------------------------------------------------------------------- */
322 /* CString handling */
323 static void cstr_realloc(CString *cstr, int new_size)
325 int size;
327 size = cstr->size_allocated;
328 if (size < 8)
329 size = 8; /* no need to allocate a too small first string */
330 while (size < new_size)
331 size = size * 2;
332 cstr->data = tal_realloc(cstr_alloc, cstr->data, size);
333 cstr->size_allocated = size;
336 /* add a byte */
337 ST_INLN void cstr_ccat(CString *cstr, int ch)
339 int size;
340 size = cstr->size + 1;
341 if (size > cstr->size_allocated)
342 cstr_realloc(cstr, size);
343 ((unsigned char *)cstr->data)[size - 1] = ch;
344 cstr->size = size;
347 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
349 int size;
350 if (len <= 0)
351 len = strlen(str) + 1 + len;
352 size = cstr->size + len;
353 if (size > cstr->size_allocated)
354 cstr_realloc(cstr, size);
355 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
356 cstr->size = size;
359 /* add a wide char */
360 ST_FUNC void cstr_wccat(CString *cstr, int ch)
362 int size;
363 size = cstr->size + sizeof(nwchar_t);
364 if (size > cstr->size_allocated)
365 cstr_realloc(cstr, size);
366 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
367 cstr->size = size;
370 ST_FUNC void cstr_new(CString *cstr)
372 memset(cstr, 0, sizeof(CString));
375 /* free string and reset it to NULL */
376 ST_FUNC void cstr_free(CString *cstr)
378 tal_free(cstr_alloc, cstr->data);
379 cstr_new(cstr);
382 /* reset string to empty */
383 ST_FUNC void cstr_reset(CString *cstr)
385 cstr->size = 0;
388 /* XXX: unicode ? */
389 static void add_char(CString *cstr, int c)
391 if (c == '\'' || c == '\"' || c == '\\') {
392 /* XXX: could be more precise if char or string */
393 cstr_ccat(cstr, '\\');
395 if (c >= 32 && c <= 126) {
396 cstr_ccat(cstr, c);
397 } else {
398 cstr_ccat(cstr, '\\');
399 if (c == '\n') {
400 cstr_ccat(cstr, 'n');
401 } else {
402 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
403 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
404 cstr_ccat(cstr, '0' + (c & 7));
409 /* ------------------------------------------------------------------------- */
410 /* allocate a new token */
411 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
413 TokenSym *ts, **ptable;
414 int i;
416 if (tok_ident >= SYM_FIRST_ANOM)
417 tcc_error("memory full (symbols)");
419 /* expand token table if needed */
420 i = tok_ident - TOK_IDENT;
421 if ((i % TOK_ALLOC_INCR) == 0) {
422 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
423 table_ident = ptable;
426 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
427 table_ident[i] = ts;
428 ts->tok = tok_ident++;
429 ts->sym_define = NULL;
430 ts->sym_label = NULL;
431 ts->sym_struct = NULL;
432 ts->sym_identifier = NULL;
433 ts->len = len;
434 ts->hash_next = NULL;
435 memcpy(ts->str, str, len);
436 ts->str[len] = '\0';
437 *pts = ts;
438 return ts;
441 #define TOK_HASH_INIT 1
442 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
445 /* find a token and add it if not found */
446 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
448 TokenSym *ts, **pts;
449 int i;
450 unsigned int h;
452 h = TOK_HASH_INIT;
453 for(i=0;i<len;i++)
454 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
455 h &= (TOK_HASH_SIZE - 1);
457 pts = &hash_ident[h];
458 for(;;) {
459 ts = *pts;
460 if (!ts)
461 break;
462 if (ts->len == len && !memcmp(ts->str, str, len))
463 return ts;
464 pts = &(ts->hash_next);
466 return tok_alloc_new(pts, str, len);
469 /* XXX: buffer overflow */
470 /* XXX: float tokens */
471 ST_FUNC const char *get_tok_str(int v, CValue *cv)
473 char *p;
474 int i, len;
476 cstr_reset(&cstr_buf);
477 p = cstr_buf.data;
479 switch(v) {
480 case TOK_CINT:
481 case TOK_CUINT:
482 case TOK_CLLONG:
483 case TOK_CULLONG:
484 /* XXX: not quite exact, but only useful for testing */
485 #ifdef _WIN32
486 sprintf(p, "%u", (unsigned)cv->i);
487 #else
488 sprintf(p, "%llu", (unsigned long long)cv->i);
489 #endif
490 break;
491 case TOK_LCHAR:
492 cstr_ccat(&cstr_buf, 'L');
493 case TOK_CCHAR:
494 cstr_ccat(&cstr_buf, '\'');
495 add_char(&cstr_buf, cv->i);
496 cstr_ccat(&cstr_buf, '\'');
497 cstr_ccat(&cstr_buf, '\0');
498 break;
499 case TOK_PPNUM:
500 case TOK_PPSTR:
501 return (char*)cv->str.data;
502 case TOK_LSTR:
503 cstr_ccat(&cstr_buf, 'L');
504 case TOK_STR:
505 cstr_ccat(&cstr_buf, '\"');
506 if (v == TOK_STR) {
507 len = cv->str.size - 1;
508 for(i=0;i<len;i++)
509 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
510 } else {
511 len = (cv->str.size / sizeof(nwchar_t)) - 1;
512 for(i=0;i<len;i++)
513 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
515 cstr_ccat(&cstr_buf, '\"');
516 cstr_ccat(&cstr_buf, '\0');
517 break;
519 case TOK_CFLOAT:
520 cstr_cat(&cstr_buf, "<float>", 0);
521 break;
522 case TOK_CDOUBLE:
523 cstr_cat(&cstr_buf, "<double>", 0);
524 break;
525 case TOK_CLDOUBLE:
526 cstr_cat(&cstr_buf, "<long double>", 0);
527 break;
528 case TOK_LINENUM:
529 cstr_cat(&cstr_buf, "<linenumber>", 0);
530 break;
532 /* 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 default:
547 if (v < TOK_IDENT) {
548 /* search in two bytes table */
549 const unsigned char *q = tok_two_chars;
550 while (*q) {
551 if (q[2] == v) {
552 *p++ = q[0];
553 *p++ = q[1];
554 *p = '\0';
555 return cstr_buf.data;
557 q += 3;
559 if (v >= 127) {
560 sprintf(cstr_buf.data, "<%02x>", v);
561 return cstr_buf.data;
563 addv:
564 *p++ = v;
565 *p = '\0';
566 } else if (v < tok_ident) {
567 return table_ident[v - TOK_IDENT]->str;
568 } else if (v >= SYM_FIRST_ANOM) {
569 /* special name for anonymous symbol */
570 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
571 } else {
572 /* should never happen */
573 return NULL;
575 break;
577 return cstr_buf.data;
580 /* return the current character, handling end of block if necessary
581 (but not stray) */
582 ST_FUNC int handle_eob(void)
584 BufferedFile *bf = file;
585 int len;
587 /* only tries to read if really end of buffer */
588 if (bf->buf_ptr >= bf->buf_end) {
589 if (bf->fd != -1) {
590 #if defined(PARSE_DEBUG)
591 len = 1;
592 #else
593 len = IO_BUF_SIZE;
594 #endif
595 len = read(bf->fd, bf->buffer, len);
596 if (len < 0)
597 len = 0;
598 } else {
599 len = 0;
601 total_bytes += len;
602 bf->buf_ptr = bf->buffer;
603 bf->buf_end = bf->buffer + len;
604 *bf->buf_end = CH_EOB;
606 if (bf->buf_ptr < bf->buf_end) {
607 return bf->buf_ptr[0];
608 } else {
609 bf->buf_ptr = bf->buf_end;
610 return CH_EOF;
614 /* read next char from current input file and handle end of input buffer */
615 ST_INLN void inp(void)
617 ch = *(++(file->buf_ptr));
618 /* end of buffer/file handling */
619 if (ch == CH_EOB)
620 ch = handle_eob();
623 /* handle '\[\r]\n' */
624 static int handle_stray_noerror(void)
626 while (ch == '\\') {
627 inp();
628 if (ch == '\n') {
629 file->line_num++;
630 inp();
631 } else if (ch == '\r') {
632 inp();
633 if (ch != '\n')
634 goto fail;
635 file->line_num++;
636 inp();
637 } else {
638 fail:
639 return 1;
642 return 0;
645 static void handle_stray(void)
647 if (handle_stray_noerror())
648 tcc_error("stray '\\' in program");
651 /* skip the stray and handle the \\n case. Output an error if
652 incorrect char after the stray */
653 static int handle_stray1(uint8_t *p)
655 int c;
657 file->buf_ptr = p;
658 if (p >= file->buf_end) {
659 c = handle_eob();
660 if (c != '\\')
661 return c;
662 p = file->buf_ptr;
664 ch = *p;
665 if (handle_stray_noerror()) {
666 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
667 tcc_error("stray '\\' in program");
668 *--file->buf_ptr = '\\';
670 p = file->buf_ptr;
671 c = *p;
672 return c;
675 /* handle just the EOB case, but not stray */
676 #define PEEKC_EOB(c, p)\
678 p++;\
679 c = *p;\
680 if (c == '\\') {\
681 file->buf_ptr = p;\
682 c = handle_eob();\
683 p = file->buf_ptr;\
687 /* handle the complicated stray case */
688 #define PEEKC(c, p)\
690 p++;\
691 c = *p;\
692 if (c == '\\') {\
693 c = handle_stray1(p);\
694 p = file->buf_ptr;\
698 /* input with '\[\r]\n' handling. Note that this function cannot
699 handle other characters after '\', so you cannot call it inside
700 strings or comments */
701 ST_FUNC void minp(void)
703 inp();
704 if (ch == '\\')
705 handle_stray();
708 /* single line C++ comments */
709 static uint8_t *parse_line_comment(uint8_t *p)
711 int c;
713 p++;
714 for(;;) {
715 c = *p;
716 redo:
717 if (c == '\n' || c == CH_EOF) {
718 break;
719 } else if (c == '\\') {
720 file->buf_ptr = p;
721 c = handle_eob();
722 p = file->buf_ptr;
723 if (c == '\\') {
724 PEEKC_EOB(c, p);
725 if (c == '\n') {
726 file->line_num++;
727 PEEKC_EOB(c, p);
728 } else if (c == '\r') {
729 PEEKC_EOB(c, p);
730 if (c == '\n') {
731 file->line_num++;
732 PEEKC_EOB(c, p);
735 } else {
736 goto redo;
738 } else {
739 p++;
742 return p;
745 /* C comments */
746 ST_FUNC uint8_t *parse_comment(uint8_t *p)
748 int c;
750 p++;
751 for(;;) {
752 /* fast skip loop */
753 for(;;) {
754 c = *p;
755 if (c == '\n' || c == '*' || c == '\\')
756 break;
757 p++;
758 c = *p;
759 if (c == '\n' || c == '*' || c == '\\')
760 break;
761 p++;
763 /* now we can handle all the cases */
764 if (c == '\n') {
765 file->line_num++;
766 p++;
767 } else if (c == '*') {
768 p++;
769 for(;;) {
770 c = *p;
771 if (c == '*') {
772 p++;
773 } else if (c == '/') {
774 goto end_of_comment;
775 } else if (c == '\\') {
776 file->buf_ptr = p;
777 c = handle_eob();
778 p = file->buf_ptr;
779 if (c == CH_EOF)
780 tcc_error("unexpected end of file in comment");
781 if (c == '\\') {
782 /* skip '\[\r]\n', otherwise just skip the stray */
783 while (c == '\\') {
784 PEEKC_EOB(c, p);
785 if (c == '\n') {
786 file->line_num++;
787 PEEKC_EOB(c, p);
788 } else if (c == '\r') {
789 PEEKC_EOB(c, p);
790 if (c == '\n') {
791 file->line_num++;
792 PEEKC_EOB(c, p);
794 } else {
795 goto after_star;
799 } else {
800 break;
803 after_star: ;
804 } else {
805 /* stray, eob or eof */
806 file->buf_ptr = p;
807 c = handle_eob();
808 p = file->buf_ptr;
809 if (c == CH_EOF) {
810 tcc_error("unexpected end of file in comment");
811 } else if (c == '\\') {
812 p++;
816 end_of_comment:
817 p++;
818 return p;
821 ST_FUNC void set_idnum(int c, int val)
823 isidnum_table[c - CH_EOF] = val;
826 #define cinp minp
828 static inline void skip_spaces(void)
830 while (isidnum_table[ch - CH_EOF] & IS_SPC)
831 cinp();
834 static inline int check_space(int t, int *spc)
836 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
837 if (*spc)
838 return 1;
839 *spc = 1;
840 } else
841 *spc = 0;
842 return 0;
845 /* parse a string without interpreting escapes */
846 static uint8_t *parse_pp_string(uint8_t *p,
847 int sep, CString *str)
849 int c;
850 p++;
851 for(;;) {
852 c = *p;
853 if (c == sep) {
854 break;
855 } else if (c == '\\') {
856 file->buf_ptr = p;
857 c = handle_eob();
858 p = file->buf_ptr;
859 if (c == CH_EOF) {
860 unterminated_string:
861 /* XXX: indicate line number of start of string */
862 tcc_error("missing terminating %c character", sep);
863 } else if (c == '\\') {
864 /* escape : just skip \[\r]\n */
865 PEEKC_EOB(c, p);
866 if (c == '\n') {
867 file->line_num++;
868 p++;
869 } else if (c == '\r') {
870 PEEKC_EOB(c, p);
871 if (c != '\n')
872 expect("'\n' after '\r'");
873 file->line_num++;
874 p++;
875 } else if (c == CH_EOF) {
876 goto unterminated_string;
877 } else {
878 if (str) {
879 cstr_ccat(str, '\\');
880 cstr_ccat(str, c);
882 p++;
885 } else if (c == '\n') {
886 file->line_num++;
887 goto add_char;
888 } else if (c == '\r') {
889 PEEKC_EOB(c, p);
890 if (c != '\n') {
891 if (str)
892 cstr_ccat(str, '\r');
893 } else {
894 file->line_num++;
895 goto add_char;
897 } else {
898 add_char:
899 if (str)
900 cstr_ccat(str, c);
901 p++;
904 p++;
905 return p;
908 /* skip block of text until #else, #elif or #endif. skip also pairs of
909 #if/#endif */
910 static void preprocess_skip(void)
912 int a, start_of_line, c, in_warn_or_error;
913 uint8_t *p;
915 p = file->buf_ptr;
916 a = 0;
917 redo_start:
918 start_of_line = 1;
919 in_warn_or_error = 0;
920 for(;;) {
921 redo_no_start:
922 c = *p;
923 switch(c) {
924 case ' ':
925 case '\t':
926 case '\f':
927 case '\v':
928 case '\r':
929 p++;
930 goto redo_no_start;
931 case '\n':
932 file->line_num++;
933 p++;
934 goto redo_start;
935 case '\\':
936 file->buf_ptr = p;
937 c = handle_eob();
938 if (c == CH_EOF) {
939 expect("#endif");
940 } else if (c == '\\') {
941 ch = file->buf_ptr[0];
942 handle_stray_noerror();
944 p = file->buf_ptr;
945 goto redo_no_start;
946 /* skip strings */
947 case '\"':
948 case '\'':
949 if (in_warn_or_error)
950 goto _default;
951 p = parse_pp_string(p, c, NULL);
952 break;
953 /* skip comments */
954 case '/':
955 if (in_warn_or_error)
956 goto _default;
957 file->buf_ptr = p;
958 ch = *p;
959 minp();
960 p = file->buf_ptr;
961 if (ch == '*') {
962 p = parse_comment(p);
963 } else if (ch == '/') {
964 p = parse_line_comment(p);
966 break;
967 case '#':
968 p++;
969 if (start_of_line) {
970 file->buf_ptr = p;
971 next_nomacro();
972 p = file->buf_ptr;
973 if (a == 0 &&
974 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
975 goto the_end;
976 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
977 a++;
978 else if (tok == TOK_ENDIF)
979 a--;
980 else if( tok == TOK_ERROR || tok == TOK_WARNING)
981 in_warn_or_error = 1;
982 else if (tok == TOK_LINEFEED)
983 goto redo_start;
984 else if (parse_flags & PARSE_FLAG_ASM_FILE)
985 p = parse_line_comment(p - 1);
986 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
987 p = parse_line_comment(p - 1);
988 break;
989 _default:
990 default:
991 p++;
992 break;
994 start_of_line = 0;
996 the_end: ;
997 file->buf_ptr = p;
1000 /* ParseState handling */
1002 /* XXX: currently, no include file info is stored. Thus, we cannot display
1003 accurate messages if the function or data definition spans multiple
1004 files */
1006 /* save current parse state in 's' */
1007 ST_FUNC void save_parse_state(ParseState *s)
1009 s->line_num = file->line_num;
1010 s->macro_ptr = macro_ptr;
1011 s->tok = tok;
1012 s->tokc = tokc;
1015 /* restore parse state from 's' */
1016 ST_FUNC void restore_parse_state(ParseState *s)
1018 file->line_num = s->line_num;
1019 macro_ptr = s->macro_ptr;
1020 tok = s->tok;
1021 tokc = s->tokc;
1024 #if 0
1025 /* return the number of additional 'ints' necessary to store the
1026 token */
1027 static inline int tok_size(const int *p)
1029 switch(*p) {
1030 /* 4 bytes */
1031 case TOK_CINT:
1032 case TOK_CUINT:
1033 case TOK_CCHAR:
1034 case TOK_LCHAR:
1035 case TOK_CFLOAT:
1036 case TOK_LINENUM:
1037 return 1 + 1;
1038 case TOK_STR:
1039 case TOK_LSTR:
1040 case TOK_PPNUM:
1041 case TOK_PPSTR:
1042 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1043 case TOK_CDOUBLE:
1044 case TOK_CLLONG:
1045 case TOK_CULLONG:
1046 return 1 + 2;
1047 case TOK_CLDOUBLE:
1048 return 1 + LDOUBLE_SIZE / 4;
1049 default:
1050 return 1 + 0;
1053 #endif
1055 /* token string handling */
1056 ST_INLN void tok_str_new(TokenString *s)
1058 s->str = NULL;
1059 s->len = 0;
1060 s->allocated_len = 0;
1061 s->last_line_num = -1;
1064 ST_FUNC TokenString *tok_str_alloc(void)
1066 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1067 tok_str_new(str);
1068 return str;
1071 ST_FUNC int *tok_str_dup(TokenString *s)
1073 int *str;
1075 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1076 memcpy(str, s->str, s->len * sizeof(int));
1077 return str;
1080 ST_FUNC void tok_str_free_str(int *str)
1082 tal_free(tokstr_alloc, str);
1085 ST_FUNC void tok_str_free(TokenString *str)
1087 tok_str_free_str(str->str);
1088 tal_free(tokstr_alloc, str);
1091 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1093 int *str, size;
1095 size = s->allocated_len;
1096 if (size < 16)
1097 size = 16;
1098 while (size < new_size)
1099 size = size * 2;
1100 if (size > s->allocated_len) {
1101 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1102 s->allocated_len = size;
1103 s->str = str;
1105 return s->str;
1108 ST_FUNC void tok_str_add(TokenString *s, int t)
1110 int len, *str;
1112 len = s->len;
1113 str = s->str;
1114 if (len >= s->allocated_len)
1115 str = tok_str_realloc(s, len + 1);
1116 str[len++] = t;
1117 s->len = len;
1120 ST_FUNC void begin_macro(TokenString *str, int alloc)
1122 str->alloc = alloc;
1123 str->prev = macro_stack;
1124 str->prev_ptr = macro_ptr;
1125 macro_ptr = str->str;
1126 macro_stack = str;
1129 ST_FUNC void end_macro(void)
1131 TokenString *str = macro_stack;
1132 macro_stack = str->prev;
1133 macro_ptr = str->prev_ptr;
1134 if (str->alloc == 2) {
1135 str->alloc = 3; /* just mark as finished */
1136 } else {
1137 tok_str_free(str);
1141 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1143 int len, *str;
1145 len = s->len;
1146 str = s->str;
1148 /* allocate space for worst case */
1149 if (len + TOK_MAX_SIZE >= s->allocated_len)
1150 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1151 str[len++] = t;
1152 switch(t) {
1153 case TOK_CINT:
1154 case TOK_CUINT:
1155 case TOK_CCHAR:
1156 case TOK_LCHAR:
1157 case TOK_CFLOAT:
1158 case TOK_LINENUM:
1159 str[len++] = cv->tab[0];
1160 break;
1161 case TOK_PPNUM:
1162 case TOK_PPSTR:
1163 case TOK_STR:
1164 case TOK_LSTR:
1166 /* Insert the string into the int array. */
1167 size_t nb_words =
1168 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1169 if (len + nb_words >= s->allocated_len)
1170 str = tok_str_realloc(s, len + nb_words + 1);
1171 str[len] = cv->str.size;
1172 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1173 len += nb_words;
1175 break;
1176 case TOK_CDOUBLE:
1177 case TOK_CLLONG:
1178 case TOK_CULLONG:
1179 #if LDOUBLE_SIZE == 8
1180 case TOK_CLDOUBLE:
1181 #endif
1182 str[len++] = cv->tab[0];
1183 str[len++] = cv->tab[1];
1184 break;
1185 #if LDOUBLE_SIZE == 12
1186 case TOK_CLDOUBLE:
1187 str[len++] = cv->tab[0];
1188 str[len++] = cv->tab[1];
1189 str[len++] = cv->tab[2];
1190 #elif LDOUBLE_SIZE == 16
1191 case TOK_CLDOUBLE:
1192 str[len++] = cv->tab[0];
1193 str[len++] = cv->tab[1];
1194 str[len++] = cv->tab[2];
1195 str[len++] = cv->tab[3];
1196 #elif LDOUBLE_SIZE != 8
1197 #error add long double size support
1198 #endif
1199 break;
1200 default:
1201 break;
1203 s->len = len;
1206 /* add the current parse token in token string 's' */
1207 ST_FUNC void tok_str_add_tok(TokenString *s)
1209 CValue cval;
1211 /* save line number info */
1212 if (file->line_num != s->last_line_num) {
1213 s->last_line_num = file->line_num;
1214 cval.i = s->last_line_num;
1215 tok_str_add2(s, TOK_LINENUM, &cval);
1217 tok_str_add2(s, tok, &tokc);
1220 /* get a token from an integer array and increment pointer
1221 accordingly. we code it as a macro to avoid pointer aliasing. */
1222 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
1224 const int *p = *pp;
1225 int n, *tab;
1227 tab = cv->tab;
1228 switch(*t = *p++) {
1229 case TOK_CINT:
1230 case TOK_CUINT:
1231 case TOK_CCHAR:
1232 case TOK_LCHAR:
1233 case TOK_LINENUM:
1234 tab[0] = *p++;
1235 cv->i = (*t == TOK_CUINT) ? (unsigned)cv->i : (int)cv->i;
1236 break;
1237 case TOK_CFLOAT:
1238 tab[0] = *p++;
1239 break;
1240 case TOK_STR:
1241 case TOK_LSTR:
1242 case TOK_PPNUM:
1243 case TOK_PPSTR:
1244 cv->str.size = *p++;
1245 cv->str.data = p;
1246 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1247 break;
1248 case TOK_CDOUBLE:
1249 case TOK_CLLONG:
1250 case TOK_CULLONG:
1251 n = 2;
1252 goto copy;
1253 case TOK_CLDOUBLE:
1254 #if LDOUBLE_SIZE == 16
1255 n = 4;
1256 #elif LDOUBLE_SIZE == 12
1257 n = 3;
1258 #elif LDOUBLE_SIZE == 8
1259 n = 2;
1260 #else
1261 # error add long double size support
1262 #endif
1263 copy:
1265 *tab++ = *p++;
1266 while (--n);
1267 break;
1268 default:
1269 break;
1271 *pp = p;
1274 /* Calling this function is expensive, but it is not possible
1275 to read a token string backwards. */
1276 static int tok_last(const int *str0, const int *str1)
1278 const int *str = str0;
1279 int tok = 0;
1280 CValue cval;
1282 while (str < str1)
1283 TOK_GET(&tok, &str, &cval);
1284 return tok;
1287 static int macro_is_equal(const int *a, const int *b)
1289 CValue cv;
1290 int t;
1292 if (!a || !b)
1293 return 1;
1295 while (*a && *b) {
1296 /* first time preallocate macro_equal_buf, next time only reset position to start */
1297 cstr_reset(&macro_equal_buf);
1298 TOK_GET(&t, &a, &cv);
1299 cstr_cat(&macro_equal_buf, get_tok_str(t, &cv), 0);
1300 TOK_GET(&t, &b, &cv);
1301 if (strcmp(macro_equal_buf.data, get_tok_str(t, &cv)))
1302 return 0;
1304 return !(*a || *b);
1307 /* defines handling */
1308 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1310 Sym *s, *o;
1312 o = define_find(v);
1313 s = sym_push2(&define_stack, v, macro_type, 0);
1314 s->d = str;
1315 s->next = first_arg;
1316 table_ident[v - TOK_IDENT]->sym_define = s;
1318 if (o && !macro_is_equal(o->d, s->d))
1319 tcc_warning("%s redefined", get_tok_str(v, NULL));
1322 /* undefined a define symbol. Its name is just set to zero */
1323 ST_FUNC void define_undef(Sym *s)
1325 int v = s->v;
1326 if (v >= TOK_IDENT && v < tok_ident)
1327 table_ident[v - TOK_IDENT]->sym_define = NULL;
1330 ST_INLN Sym *define_find(int v)
1332 v -= TOK_IDENT;
1333 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1334 return NULL;
1335 return table_ident[v]->sym_define;
1338 /* free define stack until top reaches 'b' */
1339 ST_FUNC void free_defines(Sym *b)
1341 while (define_stack != b) {
1342 Sym *top = define_stack;
1343 define_stack = top->prev;
1344 tok_str_free_str(top->d);
1345 define_undef(top);
1346 sym_free(top);
1349 /* restore remaining (-D or predefined) symbols if they were
1350 #undef'd in the file */
1351 while (b) {
1352 int v = b->v;
1353 if (v >= TOK_IDENT && v < tok_ident) {
1354 Sym **d = &table_ident[v - TOK_IDENT]->sym_define;
1355 if (!*d)
1356 *d = b;
1358 b = b->prev;
1362 /* label lookup */
1363 ST_FUNC Sym *label_find(int v)
1365 v -= TOK_IDENT;
1366 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1367 return NULL;
1368 return table_ident[v]->sym_label;
1371 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1373 Sym *s, **ps;
1374 s = sym_push2(ptop, v, 0, 0);
1375 s->r = flags;
1376 ps = &table_ident[v - TOK_IDENT]->sym_label;
1377 if (ptop == &global_label_stack) {
1378 /* modify the top most local identifier, so that
1379 sym_identifier will point to 's' when popped */
1380 while (*ps != NULL)
1381 ps = &(*ps)->prev_tok;
1383 s->prev_tok = *ps;
1384 *ps = s;
1385 return s;
1388 /* pop labels until element last is reached. Look if any labels are
1389 undefined. Define symbols if '&&label' was used. */
1390 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1392 Sym *s, *s1;
1393 for(s = *ptop; s != slast; s = s1) {
1394 s1 = s->prev;
1395 if (s->r == LABEL_DECLARED) {
1396 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1397 } else if (s->r == LABEL_FORWARD) {
1398 tcc_error("label '%s' used but not defined",
1399 get_tok_str(s->v, NULL));
1400 } else {
1401 if (s->c) {
1402 /* define corresponding symbol. A size of
1403 1 is put. */
1404 put_extern_sym(s, cur_text_section, s->jnext, 1);
1407 /* remove label */
1408 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1409 sym_free(s);
1411 *ptop = slast;
1414 /* eval an expression for #if/#elif */
1415 static int expr_preprocess(void)
1417 int c, t;
1418 TokenString *str;
1420 str = tok_str_alloc();
1421 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1422 next(); /* do macro subst */
1423 if (tok == TOK_DEFINED) {
1424 next_nomacro();
1425 t = tok;
1426 if (t == '(')
1427 next_nomacro();
1428 c = define_find(tok) != 0;
1429 if (t == '(')
1430 next_nomacro();
1431 tok = TOK_CINT;
1432 tokc.i = c;
1433 } else if (tok >= TOK_IDENT) {
1434 /* if undefined macro */
1435 tok = TOK_CINT;
1436 tokc.i = 0;
1438 tok_str_add_tok(str);
1440 tok_str_add(str, -1); /* simulate end of file */
1441 tok_str_add(str, 0);
1442 /* now evaluate C constant expression */
1443 begin_macro(str, 1);
1444 next();
1445 c = expr_const();
1446 end_macro();
1447 return c != 0;
1451 /* parse after #define */
1452 ST_FUNC void parse_define(void)
1454 Sym *s, *first, **ps;
1455 int v, t, varg, is_vaargs, spc;
1456 int saved_parse_flags = parse_flags;
1458 v = tok;
1459 if (v < TOK_IDENT)
1460 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1461 /* XXX: should check if same macro (ANSI) */
1462 first = NULL;
1463 t = MACRO_OBJ;
1464 /* We have to parse the whole define as if not in asm mode, in particular
1465 no line comment with '#' must be ignored. Also for function
1466 macros the argument list must be parsed without '.' being an ID
1467 character. */
1468 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1469 /* '(' must be just after macro definition for MACRO_FUNC */
1470 next_nomacro_spc();
1471 if (tok == '(') {
1472 set_idnum('.', 0);
1473 next_nomacro();
1474 ps = &first;
1475 if (tok != ')') for (;;) {
1476 varg = tok;
1477 next_nomacro();
1478 is_vaargs = 0;
1479 if (varg == TOK_DOTS) {
1480 varg = TOK___VA_ARGS__;
1481 is_vaargs = 1;
1482 } else if (tok == TOK_DOTS && gnu_ext) {
1483 is_vaargs = 1;
1484 next_nomacro();
1486 if (varg < TOK_IDENT)
1487 bad_list:
1488 tcc_error("bad macro parameter list");
1489 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1490 *ps = s;
1491 ps = &s->next;
1492 if (tok == ')')
1493 break;
1494 if (tok != ',' || is_vaargs)
1495 goto bad_list;
1496 next_nomacro();
1498 next_nomacro_spc();
1499 t = MACRO_FUNC;
1502 tokstr_buf.len = 0;
1503 spc = 2;
1504 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1505 /* The body of a macro definition should be parsed such that identifiers
1506 are parsed like the file mode determines (i.e. with '.' being an
1507 ID character in asm mode). But '#' should be retained instead of
1508 regarded as line comment leader, so still don't set ASM_FILE
1509 in parse_flags. */
1510 set_idnum('.', (saved_parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0);
1511 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1512 /* remove spaces around ## and after '#' */
1513 if (TOK_TWOSHARPS == tok) {
1514 if (2 == spc)
1515 goto bad_twosharp;
1516 if (1 == spc)
1517 --tokstr_buf.len;
1518 spc = 3;
1519 tok = TOK_PPJOIN;
1520 } else if ('#' == tok) {
1521 spc = 4;
1522 } else if (check_space(tok, &spc)) {
1523 goto skip;
1525 tok_str_add2(&tokstr_buf, tok, &tokc);
1526 skip:
1527 next_nomacro_spc();
1530 parse_flags = saved_parse_flags;
1531 if (spc == 1)
1532 --tokstr_buf.len; /* remove trailing space */
1533 tok_str_add(&tokstr_buf, 0);
1534 if (3 == spc)
1535 bad_twosharp:
1536 tcc_error("'##' cannot appear at either end of macro");
1537 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1540 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1542 const unsigned char *s;
1543 unsigned int h;
1544 CachedInclude *e;
1545 int i;
1547 h = TOK_HASH_INIT;
1548 s = (unsigned char *) filename;
1549 while (*s) {
1550 #ifdef _WIN32
1551 h = TOK_HASH_FUNC(h, toup(*s));
1552 #else
1553 h = TOK_HASH_FUNC(h, *s);
1554 #endif
1555 s++;
1557 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1559 i = s1->cached_includes_hash[h];
1560 for(;;) {
1561 if (i == 0)
1562 break;
1563 e = s1->cached_includes[i - 1];
1564 if (0 == PATHCMP(e->filename, filename))
1565 return e;
1566 i = e->hash_next;
1568 if (!add)
1569 return NULL;
1571 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1572 strcpy(e->filename, filename);
1573 e->ifndef_macro = e->once = 0;
1574 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1575 /* add in hash table */
1576 e->hash_next = s1->cached_includes_hash[h];
1577 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1578 #ifdef INC_DEBUG
1579 printf("adding cached '%s'\n", filename);
1580 #endif
1581 return e;
1584 static void pragma_parse(TCCState *s1)
1586 next_nomacro();
1587 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1588 int t = tok, v;
1589 Sym *s;
1591 if (next(), tok != '(')
1592 goto pragma_err;
1593 if (next(), tok != TOK_STR)
1594 goto pragma_err;
1595 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1596 if (next(), tok != ')')
1597 goto pragma_err;
1598 if (t == TOK_push_macro) {
1599 while (NULL == (s = define_find(v)))
1600 define_push(v, 0, NULL, NULL);
1601 s->type.ref = s; /* set push boundary */
1602 } else {
1603 for (s = define_stack; s; s = s->prev)
1604 if (s->v == v && s->type.ref == s) {
1605 s->type.ref = NULL;
1606 break;
1609 if (s)
1610 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1611 else
1612 tcc_warning("unbalanced #pragma pop_macro");
1613 pp_debug_tok = t, pp_debug_symv = v;
1615 } else if (tok == TOK_once) {
1616 search_cached_include(s1, file->filename, 1)->once = pp_once;
1618 } else if (s1->ppfp) {
1619 /* tcc -E: keep pragmas below unchanged */
1620 unget_tok(' ');
1621 unget_tok(TOK_PRAGMA);
1622 unget_tok('#');
1623 unget_tok(TOK_LINEFEED);
1625 } else if (tok == TOK_pack) {
1626 /* This may be:
1627 #pragma pack(1) // set
1628 #pragma pack() // reset to default
1629 #pragma pack(push,1) // push & set
1630 #pragma pack(pop) // restore previous */
1631 next();
1632 skip('(');
1633 if (tok == TOK_ASM_pop) {
1634 next();
1635 if (s1->pack_stack_ptr <= s1->pack_stack) {
1636 stk_error:
1637 tcc_error("out of pack stack");
1639 s1->pack_stack_ptr--;
1640 } else {
1641 int val = 0;
1642 if (tok != ')') {
1643 if (tok == TOK_ASM_push) {
1644 next();
1645 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1646 goto stk_error;
1647 s1->pack_stack_ptr++;
1648 skip(',');
1650 if (tok != TOK_CINT)
1651 goto pragma_err;
1652 val = tokc.i;
1653 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1654 goto pragma_err;
1655 next();
1657 *s1->pack_stack_ptr = val;
1659 if (tok != ')')
1660 goto pragma_err;
1662 } else if (tok == TOK_comment) {
1663 char *file;
1664 next();
1665 skip('(');
1666 if (tok != TOK_lib)
1667 goto pragma_warn;
1668 next();
1669 skip(',');
1670 if (tok != TOK_STR)
1671 goto pragma_err;
1672 file = tcc_strdup((char *)tokc.str.data);
1673 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, file);
1674 next();
1675 if (tok != ')')
1676 goto pragma_err;
1677 } else {
1678 pragma_warn:
1679 if (s1->warn_unsupported)
1680 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1682 return;
1684 pragma_err:
1685 tcc_error("malformed #pragma directive");
1686 return;
1689 /* is_bof is true if first non space token at beginning of file */
1690 ST_FUNC void preprocess(int is_bof)
1692 TCCState *s1 = tcc_state;
1693 int i, c, n, saved_parse_flags;
1694 char buf[1024], *q;
1695 Sym *s;
1697 saved_parse_flags = parse_flags;
1698 parse_flags = PARSE_FLAG_PREPROCESS
1699 | PARSE_FLAG_TOK_NUM
1700 | PARSE_FLAG_TOK_STR
1701 | PARSE_FLAG_LINEFEED
1702 | (parse_flags & PARSE_FLAG_ASM_FILE)
1705 next_nomacro();
1706 redo:
1707 switch(tok) {
1708 case TOK_DEFINE:
1709 pp_debug_tok = tok;
1710 next_nomacro();
1711 pp_debug_symv = tok;
1712 parse_define();
1713 break;
1714 case TOK_UNDEF:
1715 pp_debug_tok = tok;
1716 next_nomacro();
1717 pp_debug_symv = tok;
1718 s = define_find(tok);
1719 /* undefine symbol by putting an invalid name */
1720 if (s)
1721 define_undef(s);
1722 break;
1723 case TOK_INCLUDE:
1724 case TOK_INCLUDE_NEXT:
1725 ch = file->buf_ptr[0];
1726 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1727 skip_spaces();
1728 if (ch == '<') {
1729 c = '>';
1730 goto read_name;
1731 } else if (ch == '\"') {
1732 c = ch;
1733 read_name:
1734 inp();
1735 q = buf;
1736 while (ch != c && ch != '\n' && ch != CH_EOF) {
1737 if ((q - buf) < sizeof(buf) - 1)
1738 *q++ = ch;
1739 if (ch == '\\') {
1740 if (handle_stray_noerror() == 0)
1741 --q;
1742 } else
1743 inp();
1745 *q = '\0';
1746 minp();
1747 #if 0
1748 /* eat all spaces and comments after include */
1749 /* XXX: slightly incorrect */
1750 while (ch1 != '\n' && ch1 != CH_EOF)
1751 inp();
1752 #endif
1753 } else {
1754 int len;
1755 /* computed #include : concatenate everything up to linefeed,
1756 the result must be one of the two accepted forms.
1757 Don't convert pp-tokens to tokens here. */
1758 parse_flags = (PARSE_FLAG_PREPROCESS
1759 | PARSE_FLAG_LINEFEED
1760 | (parse_flags & PARSE_FLAG_ASM_FILE));
1761 next();
1762 buf[0] = '\0';
1763 while (tok != TOK_LINEFEED) {
1764 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1765 next();
1767 len = strlen(buf);
1768 /* check syntax and remove '<>|""' */
1769 if ((len < 2 || ((buf[0] != '"' || buf[len-1] != '"') &&
1770 (buf[0] != '<' || buf[len-1] != '>'))))
1771 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1772 c = buf[len-1];
1773 memmove(buf, buf + 1, len - 2);
1774 buf[len - 2] = '\0';
1777 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1778 tcc_error("#include recursion too deep");
1779 /* store current file in stack, but increment stack later below */
1780 *s1->include_stack_ptr = file;
1781 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index : 0;
1782 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1783 for (; i < n; ++i) {
1784 char buf1[sizeof file->filename];
1785 CachedInclude *e;
1786 const char *path;
1788 if (i == 0) {
1789 /* check absolute include path */
1790 if (!IS_ABSPATH(buf))
1791 continue;
1792 buf1[0] = 0;
1794 } else if (i == 1) {
1795 /* search in file's dir if "header.h" */
1796 if (c != '\"')
1797 continue;
1798 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1799 path = file->filename2;
1800 pstrncpy(buf1, path, tcc_basename(path) - path);
1802 } else {
1803 /* search in all the include paths */
1804 int j = i - 2, k = j - s1->nb_include_paths;
1805 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1806 pstrcpy(buf1, sizeof(buf1), path);
1807 pstrcat(buf1, sizeof(buf1), "/");
1810 pstrcat(buf1, sizeof(buf1), buf);
1811 e = search_cached_include(s1, buf1, 0);
1812 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1813 /* no need to parse the include because the 'ifndef macro'
1814 is defined (or had #pragma once) */
1815 #ifdef INC_DEBUG
1816 printf("%s: skipping cached %s\n", file->filename, buf1);
1817 #endif
1818 goto include_done;
1821 if (tcc_open(s1, buf1) < 0)
1822 continue;
1824 file->include_next_index = i + 1;
1825 #ifdef INC_DEBUG
1826 printf("%s: including %s\n", file->prev->filename, file->filename);
1827 #endif
1828 /* update target deps */
1829 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1830 tcc_strdup(buf1));
1831 /* push current file in stack */
1832 ++s1->include_stack_ptr;
1833 /* add include file debug info */
1834 if (s1->do_debug)
1835 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1836 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1837 ch = file->buf_ptr[0];
1838 goto the_end;
1840 tcc_error("include file '%s' not found", buf);
1841 include_done:
1842 break;
1843 case TOK_IFNDEF:
1844 c = 1;
1845 goto do_ifdef;
1846 case TOK_IF:
1847 c = expr_preprocess();
1848 goto do_if;
1849 case TOK_IFDEF:
1850 c = 0;
1851 do_ifdef:
1852 next_nomacro();
1853 if (tok < TOK_IDENT)
1854 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1855 if (is_bof) {
1856 if (c) {
1857 #ifdef INC_DEBUG
1858 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1859 #endif
1860 file->ifndef_macro = tok;
1863 c = (define_find(tok) != 0) ^ c;
1864 do_if:
1865 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1866 tcc_error("memory full (ifdef)");
1867 *s1->ifdef_stack_ptr++ = c;
1868 goto test_skip;
1869 case TOK_ELSE:
1870 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1871 tcc_error("#else without matching #if");
1872 if (s1->ifdef_stack_ptr[-1] & 2)
1873 tcc_error("#else after #else");
1874 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1875 goto test_else;
1876 case TOK_ELIF:
1877 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1878 tcc_error("#elif without matching #if");
1879 c = s1->ifdef_stack_ptr[-1];
1880 if (c > 1)
1881 tcc_error("#elif after #else");
1882 /* last #if/#elif expression was true: we skip */
1883 if (c == 1) {
1884 c = 0;
1885 } else {
1886 c = expr_preprocess();
1887 s1->ifdef_stack_ptr[-1] = c;
1889 test_else:
1890 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1891 file->ifndef_macro = 0;
1892 test_skip:
1893 if (!(c & 1)) {
1894 preprocess_skip();
1895 is_bof = 0;
1896 goto redo;
1898 break;
1899 case TOK_ENDIF:
1900 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1901 tcc_error("#endif without matching #if");
1902 s1->ifdef_stack_ptr--;
1903 /* '#ifndef macro' was at the start of file. Now we check if
1904 an '#endif' is exactly at the end of file */
1905 if (file->ifndef_macro &&
1906 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1907 file->ifndef_macro_saved = file->ifndef_macro;
1908 /* need to set to zero to avoid false matches if another
1909 #ifndef at middle of file */
1910 file->ifndef_macro = 0;
1911 while (tok != TOK_LINEFEED)
1912 next_nomacro();
1913 tok_flags |= TOK_FLAG_ENDIF;
1914 goto the_end;
1916 break;
1917 case TOK_PPNUM:
1918 n = strtoul((char*)tokc.str.data, &q, 10);
1919 goto _line_num;
1920 case TOK_LINE:
1921 next();
1922 if (tok != TOK_CINT)
1923 _line_err:
1924 tcc_error("wrong #line format");
1925 n = tokc.i;
1926 _line_num:
1927 next();
1928 if (tok != TOK_LINEFEED) {
1929 if (tok == TOK_STR)
1930 pstrcpy(file->filename, sizeof(file->filename), (char *)tokc.str.data);
1931 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1932 break;
1933 else
1934 goto _line_err;
1935 --n;
1937 if (file->fd > 0)
1938 total_lines += file->line_num - n;
1939 file->line_num = n;
1940 if (s1->do_debug)
1941 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1942 break;
1943 case TOK_ERROR:
1944 case TOK_WARNING:
1945 c = tok;
1946 ch = file->buf_ptr[0];
1947 skip_spaces();
1948 q = buf;
1949 while (ch != '\n' && ch != CH_EOF) {
1950 if ((q - buf) < sizeof(buf) - 1)
1951 *q++ = ch;
1952 if (ch == '\\') {
1953 if (handle_stray_noerror() == 0)
1954 --q;
1955 } else
1956 inp();
1958 *q = '\0';
1959 if (c == TOK_ERROR)
1960 tcc_error("#error %s", buf);
1961 else
1962 tcc_warning("#warning %s", buf);
1963 break;
1964 case TOK_PRAGMA:
1965 pragma_parse(s1);
1966 break;
1967 case TOK_LINEFEED:
1968 goto the_end;
1969 default:
1970 /* ignore gas line comment in an 'S' file. */
1971 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1972 goto ignore;
1973 if (tok == '!' && is_bof)
1974 /* '!' is ignored at beginning to allow C scripts. */
1975 goto ignore;
1976 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1977 ignore:
1978 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
1979 goto the_end;
1981 /* ignore other preprocess commands or #! for C scripts */
1982 while (tok != TOK_LINEFEED)
1983 next_nomacro();
1984 the_end:
1985 parse_flags = saved_parse_flags;
1988 /* evaluate escape codes in a string. */
1989 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1991 int c, n;
1992 const uint8_t *p;
1994 p = buf;
1995 for(;;) {
1996 c = *p;
1997 if (c == '\0')
1998 break;
1999 if (c == '\\') {
2000 p++;
2001 /* escape */
2002 c = *p;
2003 switch(c) {
2004 case '0': case '1': case '2': case '3':
2005 case '4': case '5': case '6': case '7':
2006 /* at most three octal digits */
2007 n = c - '0';
2008 p++;
2009 c = *p;
2010 if (isoct(c)) {
2011 n = n * 8 + c - '0';
2012 p++;
2013 c = *p;
2014 if (isoct(c)) {
2015 n = n * 8 + c - '0';
2016 p++;
2019 c = n;
2020 goto add_char_nonext;
2021 case 'x':
2022 case 'u':
2023 case 'U':
2024 p++;
2025 n = 0;
2026 for(;;) {
2027 c = *p;
2028 if (c >= 'a' && c <= 'f')
2029 c = c - 'a' + 10;
2030 else if (c >= 'A' && c <= 'F')
2031 c = c - 'A' + 10;
2032 else if (isnum(c))
2033 c = c - '0';
2034 else
2035 break;
2036 n = n * 16 + c;
2037 p++;
2039 c = n;
2040 goto add_char_nonext;
2041 case 'a':
2042 c = '\a';
2043 break;
2044 case 'b':
2045 c = '\b';
2046 break;
2047 case 'f':
2048 c = '\f';
2049 break;
2050 case 'n':
2051 c = '\n';
2052 break;
2053 case 'r':
2054 c = '\r';
2055 break;
2056 case 't':
2057 c = '\t';
2058 break;
2059 case 'v':
2060 c = '\v';
2061 break;
2062 case 'e':
2063 if (!gnu_ext)
2064 goto invalid_escape;
2065 c = 27;
2066 break;
2067 case '\'':
2068 case '\"':
2069 case '\\':
2070 case '?':
2071 break;
2072 default:
2073 invalid_escape:
2074 if (c >= '!' && c <= '~')
2075 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2076 else
2077 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2078 break;
2081 p++;
2082 add_char_nonext:
2083 if (!is_long)
2084 cstr_ccat(outstr, c);
2085 else
2086 cstr_wccat(outstr, c);
2088 /* add a trailing '\0' */
2089 if (!is_long)
2090 cstr_ccat(outstr, '\0');
2091 else
2092 cstr_wccat(outstr, '\0');
2095 static void parse_string(const char *s, int len)
2097 uint8_t buf[1000], *p = buf;
2098 int is_long, sep;
2100 if ((is_long = *s == 'L'))
2101 ++s, --len;
2102 sep = *s++;
2103 len -= 2;
2104 if (len >= sizeof buf)
2105 p = tcc_malloc(len + 1);
2106 memcpy(p, s, len);
2107 p[len] = 0;
2109 cstr_reset(&tokcstr);
2110 parse_escape_string(&tokcstr, p, is_long);
2111 if (p != buf)
2112 tcc_free(p);
2114 if (sep == '\'') {
2115 int char_size;
2116 /* XXX: make it portable */
2117 if (!is_long)
2118 char_size = 1;
2119 else
2120 char_size = sizeof(nwchar_t);
2121 if (tokcstr.size <= char_size)
2122 tcc_error("empty character constant");
2123 if (tokcstr.size > 2 * char_size)
2124 tcc_warning("multi-character character constant");
2125 if (!is_long) {
2126 tokc.i = *(int8_t *)tokcstr.data;
2127 tok = TOK_CCHAR;
2128 } else {
2129 tokc.i = *(nwchar_t *)tokcstr.data;
2130 tok = TOK_LCHAR;
2132 } else {
2133 tokc.str.size = tokcstr.size;
2134 tokc.str.data = tokcstr.data;
2135 if (!is_long)
2136 tok = TOK_STR;
2137 else
2138 tok = TOK_LSTR;
2142 /* we use 64 bit numbers */
2143 #define BN_SIZE 2
2145 /* bn = (bn << shift) | or_val */
2146 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2148 int i;
2149 unsigned int v;
2150 for(i=0;i<BN_SIZE;i++) {
2151 v = bn[i];
2152 bn[i] = (v << shift) | or_val;
2153 or_val = v >> (32 - shift);
2157 static void bn_zero(unsigned int *bn)
2159 int i;
2160 for(i=0;i<BN_SIZE;i++) {
2161 bn[i] = 0;
2165 /* parse number in null terminated string 'p' and return it in the
2166 current token */
2167 static void parse_number(const char *p)
2169 int b, t, shift, frac_bits, s, exp_val, ch;
2170 char *q;
2171 unsigned int bn[BN_SIZE];
2172 double d;
2174 /* number */
2175 q = token_buf;
2176 ch = *p++;
2177 t = ch;
2178 ch = *p++;
2179 *q++ = t;
2180 b = 10;
2181 if (t == '.') {
2182 goto float_frac_parse;
2183 } else if (t == '0') {
2184 if (ch == 'x' || ch == 'X') {
2185 q--;
2186 ch = *p++;
2187 b = 16;
2188 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
2189 q--;
2190 ch = *p++;
2191 b = 2;
2194 /* parse all digits. cannot check octal numbers at this stage
2195 because of floating point constants */
2196 while (1) {
2197 if (ch >= 'a' && ch <= 'f')
2198 t = ch - 'a' + 10;
2199 else if (ch >= 'A' && ch <= 'F')
2200 t = ch - 'A' + 10;
2201 else if (isnum(ch))
2202 t = ch - '0';
2203 else
2204 break;
2205 if (t >= b)
2206 break;
2207 if (q >= token_buf + STRING_MAX_SIZE) {
2208 num_too_long:
2209 tcc_error("number too long");
2211 *q++ = ch;
2212 ch = *p++;
2214 if (ch == '.' ||
2215 ((ch == 'e' || ch == 'E') && b == 10) ||
2216 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2217 if (b != 10) {
2218 /* NOTE: strtox should support that for hexa numbers, but
2219 non ISOC99 libcs do not support it, so we prefer to do
2220 it by hand */
2221 /* hexadecimal or binary floats */
2222 /* XXX: handle overflows */
2223 *q = '\0';
2224 if (b == 16)
2225 shift = 4;
2226 else
2227 shift = 1;
2228 bn_zero(bn);
2229 q = token_buf;
2230 while (1) {
2231 t = *q++;
2232 if (t == '\0') {
2233 break;
2234 } else if (t >= 'a') {
2235 t = t - 'a' + 10;
2236 } else if (t >= 'A') {
2237 t = t - 'A' + 10;
2238 } else {
2239 t = t - '0';
2241 bn_lshift(bn, shift, t);
2243 frac_bits = 0;
2244 if (ch == '.') {
2245 ch = *p++;
2246 while (1) {
2247 t = ch;
2248 if (t >= 'a' && t <= 'f') {
2249 t = t - 'a' + 10;
2250 } else if (t >= 'A' && t <= 'F') {
2251 t = t - 'A' + 10;
2252 } else if (t >= '0' && t <= '9') {
2253 t = t - '0';
2254 } else {
2255 break;
2257 if (t >= b)
2258 tcc_error("invalid digit");
2259 bn_lshift(bn, shift, t);
2260 frac_bits += shift;
2261 ch = *p++;
2264 if (ch != 'p' && ch != 'P')
2265 expect("exponent");
2266 ch = *p++;
2267 s = 1;
2268 exp_val = 0;
2269 if (ch == '+') {
2270 ch = *p++;
2271 } else if (ch == '-') {
2272 s = -1;
2273 ch = *p++;
2275 if (ch < '0' || ch > '9')
2276 expect("exponent digits");
2277 while (ch >= '0' && ch <= '9') {
2278 exp_val = exp_val * 10 + ch - '0';
2279 ch = *p++;
2281 exp_val = exp_val * s;
2283 /* now we can generate the number */
2284 /* XXX: should patch directly float number */
2285 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2286 d = ldexp(d, exp_val - frac_bits);
2287 t = toup(ch);
2288 if (t == 'F') {
2289 ch = *p++;
2290 tok = TOK_CFLOAT;
2291 /* float : should handle overflow */
2292 tokc.f = (float)d;
2293 } else if (t == 'L') {
2294 ch = *p++;
2295 #ifdef TCC_TARGET_PE
2296 tok = TOK_CDOUBLE;
2297 tokc.d = d;
2298 #else
2299 tok = TOK_CLDOUBLE;
2300 /* XXX: not large enough */
2301 tokc.ld = (long double)d;
2302 #endif
2303 } else {
2304 tok = TOK_CDOUBLE;
2305 tokc.d = d;
2307 } else {
2308 /* decimal floats */
2309 if (ch == '.') {
2310 if (q >= token_buf + STRING_MAX_SIZE)
2311 goto num_too_long;
2312 *q++ = ch;
2313 ch = *p++;
2314 float_frac_parse:
2315 while (ch >= '0' && ch <= '9') {
2316 if (q >= token_buf + STRING_MAX_SIZE)
2317 goto num_too_long;
2318 *q++ = ch;
2319 ch = *p++;
2322 if (ch == 'e' || ch == 'E') {
2323 if (q >= token_buf + STRING_MAX_SIZE)
2324 goto num_too_long;
2325 *q++ = ch;
2326 ch = *p++;
2327 if (ch == '-' || ch == '+') {
2328 if (q >= token_buf + STRING_MAX_SIZE)
2329 goto num_too_long;
2330 *q++ = ch;
2331 ch = *p++;
2333 if (ch < '0' || ch > '9')
2334 expect("exponent digits");
2335 while (ch >= '0' && ch <= '9') {
2336 if (q >= token_buf + STRING_MAX_SIZE)
2337 goto num_too_long;
2338 *q++ = ch;
2339 ch = *p++;
2342 *q = '\0';
2343 t = toup(ch);
2344 errno = 0;
2345 if (t == 'F') {
2346 ch = *p++;
2347 tok = TOK_CFLOAT;
2348 tokc.f = strtof(token_buf, NULL);
2349 } else if (t == 'L') {
2350 ch = *p++;
2351 #ifdef TCC_TARGET_PE
2352 tok = TOK_CDOUBLE;
2353 tokc.d = strtod(token_buf, NULL);
2354 #else
2355 tok = TOK_CLDOUBLE;
2356 tokc.ld = strtold(token_buf, NULL);
2357 #endif
2358 } else {
2359 tok = TOK_CDOUBLE;
2360 tokc.d = strtod(token_buf, NULL);
2363 } else {
2364 unsigned long long n, n1;
2365 int lcount, ucount, must_64bit;
2366 const char *p1;
2368 /* integer number */
2369 *q = '\0';
2370 q = token_buf;
2371 if (b == 10 && *q == '0') {
2372 b = 8;
2373 q++;
2375 n = 0;
2376 while(1) {
2377 t = *q++;
2378 /* no need for checks except for base 10 / 8 errors */
2379 if (t == '\0')
2380 break;
2381 else if (t >= 'a')
2382 t = t - 'a' + 10;
2383 else if (t >= 'A')
2384 t = t - 'A' + 10;
2385 else
2386 t = t - '0';
2387 if (t >= b)
2388 tcc_error("invalid digit");
2389 n1 = n;
2390 n = n * b + t;
2391 /* detect overflow */
2392 /* XXX: this test is not reliable */
2393 if (n < n1)
2394 tcc_error("integer constant overflow");
2397 /* Determine the characteristics (unsigned and/or 64bit) the type of
2398 the constant must have according to the constant suffix(es) */
2399 lcount = ucount = must_64bit = 0;
2400 p1 = p;
2401 for(;;) {
2402 t = toup(ch);
2403 if (t == 'L') {
2404 if (lcount >= 2)
2405 tcc_error("three 'l's in integer constant");
2406 if (lcount && *(p - 1) != ch)
2407 tcc_error("incorrect integer suffix: %s", p1);
2408 lcount++;
2409 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2410 if (lcount == 2)
2411 #endif
2412 must_64bit = 1;
2413 ch = *p++;
2414 } else if (t == 'U') {
2415 if (ucount >= 1)
2416 tcc_error("two 'u's in integer constant");
2417 ucount++;
2418 ch = *p++;
2419 } else {
2420 break;
2424 /* Whether 64 bits are needed to hold the constant's value */
2425 if (n & 0xffffffff00000000LL || must_64bit) {
2426 tok = TOK_CLLONG;
2427 n1 = n >> 32;
2428 } else {
2429 tok = TOK_CINT;
2430 n1 = n;
2433 /* Whether type must be unsigned to hold the constant's value */
2434 if (ucount || ((n1 >> 31) && (b != 10))) {
2435 if (tok == TOK_CLLONG)
2436 tok = TOK_CULLONG;
2437 else
2438 tok = TOK_CUINT;
2439 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2440 } else if (n1 >> 31) {
2441 if (tok == TOK_CINT)
2442 tok = TOK_CLLONG;
2443 else
2444 tcc_error("integer constant overflow");
2447 tokc.i = n;
2449 if (ch)
2450 tcc_error("invalid number\n");
2454 #define PARSE2(c1, tok1, c2, tok2) \
2455 case c1: \
2456 PEEKC(c, p); \
2457 if (c == c2) { \
2458 p++; \
2459 tok = tok2; \
2460 } else { \
2461 tok = tok1; \
2463 break;
2465 /* return next token without macro substitution */
2466 static inline void next_nomacro1(void)
2468 int t, c, is_long, len;
2469 TokenSym *ts;
2470 uint8_t *p, *p1;
2471 unsigned int h;
2473 p = file->buf_ptr;
2474 redo_no_start:
2475 c = *p;
2476 switch(c) {
2477 case ' ':
2478 case '\t':
2479 tok = c;
2480 p++;
2481 if (parse_flags & PARSE_FLAG_SPACES)
2482 goto keep_tok_flags;
2483 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2484 ++p;
2485 goto redo_no_start;
2486 case '\f':
2487 case '\v':
2488 case '\r':
2489 p++;
2490 goto redo_no_start;
2491 case '\\':
2492 /* first look if it is in fact an end of buffer */
2493 c = handle_stray1(p);
2494 p = file->buf_ptr;
2495 if (c == '\\')
2496 goto parse_simple;
2497 if (c != CH_EOF)
2498 goto redo_no_start;
2500 TCCState *s1 = tcc_state;
2501 if ((parse_flags & PARSE_FLAG_LINEFEED)
2502 && !(tok_flags & TOK_FLAG_EOF)) {
2503 tok_flags |= TOK_FLAG_EOF;
2504 tok = TOK_LINEFEED;
2505 goto keep_tok_flags;
2506 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2507 tok = TOK_EOF;
2508 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2509 tcc_error("missing #endif");
2510 } else if (s1->include_stack_ptr == s1->include_stack) {
2511 /* no include left : end of file. */
2512 tok = TOK_EOF;
2513 } else {
2514 tok_flags &= ~TOK_FLAG_EOF;
2515 /* pop include file */
2517 /* test if previous '#endif' was after a #ifdef at
2518 start of file */
2519 if (tok_flags & TOK_FLAG_ENDIF) {
2520 #ifdef INC_DEBUG
2521 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2522 #endif
2523 search_cached_include(s1, file->filename, 1)
2524 ->ifndef_macro = file->ifndef_macro_saved;
2525 tok_flags &= ~TOK_FLAG_ENDIF;
2528 /* add end of include file debug info */
2529 if (tcc_state->do_debug) {
2530 put_stabd(N_EINCL, 0, 0);
2532 /* pop include stack */
2533 tcc_close();
2534 s1->include_stack_ptr--;
2535 p = file->buf_ptr;
2536 goto redo_no_start;
2539 break;
2541 case '\n':
2542 file->line_num++;
2543 tok_flags |= TOK_FLAG_BOL;
2544 p++;
2545 maybe_newline:
2546 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2547 goto redo_no_start;
2548 tok = TOK_LINEFEED;
2549 goto keep_tok_flags;
2551 case '#':
2552 /* XXX: simplify */
2553 PEEKC(c, p);
2554 if ((tok_flags & TOK_FLAG_BOL) &&
2555 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2556 file->buf_ptr = p;
2557 preprocess(tok_flags & TOK_FLAG_BOF);
2558 p = file->buf_ptr;
2559 goto maybe_newline;
2560 } else {
2561 if (c == '#') {
2562 p++;
2563 tok = TOK_TWOSHARPS;
2564 } else {
2565 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2566 p = parse_line_comment(p - 1);
2567 goto redo_no_start;
2568 } else {
2569 tok = '#';
2573 break;
2575 /* dollar is allowed to start identifiers when not parsing asm */
2576 case '$':
2577 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2578 || (parse_flags & PARSE_FLAG_ASM_FILE))
2579 goto parse_simple;
2581 case 'a': case 'b': case 'c': case 'd':
2582 case 'e': case 'f': case 'g': case 'h':
2583 case 'i': case 'j': case 'k': case 'l':
2584 case 'm': case 'n': case 'o': case 'p':
2585 case 'q': case 'r': case 's': case 't':
2586 case 'u': case 'v': case 'w': case 'x':
2587 case 'y': case 'z':
2588 case 'A': case 'B': case 'C': case 'D':
2589 case 'E': case 'F': case 'G': case 'H':
2590 case 'I': case 'J': case 'K':
2591 case 'M': case 'N': case 'O': case 'P':
2592 case 'Q': case 'R': case 'S': case 'T':
2593 case 'U': case 'V': case 'W': case 'X':
2594 case 'Y': case 'Z':
2595 case '_':
2596 parse_ident_fast:
2597 p1 = p;
2598 h = TOK_HASH_INIT;
2599 h = TOK_HASH_FUNC(h, c);
2600 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2601 h = TOK_HASH_FUNC(h, c);
2602 len = p - p1;
2603 if (c != '\\') {
2604 TokenSym **pts;
2606 /* fast case : no stray found, so we have the full token
2607 and we have already hashed it */
2608 h &= (TOK_HASH_SIZE - 1);
2609 pts = &hash_ident[h];
2610 for(;;) {
2611 ts = *pts;
2612 if (!ts)
2613 break;
2614 if (ts->len == len && !memcmp(ts->str, p1, len))
2615 goto token_found;
2616 pts = &(ts->hash_next);
2618 ts = tok_alloc_new(pts, (char *) p1, len);
2619 token_found: ;
2620 } else {
2621 /* slower case */
2622 cstr_reset(&tokcstr);
2623 cstr_cat(&tokcstr, (char *) p1, len);
2624 p--;
2625 PEEKC(c, p);
2626 parse_ident_slow:
2627 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2629 cstr_ccat(&tokcstr, c);
2630 PEEKC(c, p);
2632 ts = tok_alloc(tokcstr.data, tokcstr.size);
2634 tok = ts->tok;
2635 break;
2636 case 'L':
2637 t = p[1];
2638 if (t != '\\' && t != '\'' && t != '\"') {
2639 /* fast case */
2640 goto parse_ident_fast;
2641 } else {
2642 PEEKC(c, p);
2643 if (c == '\'' || c == '\"') {
2644 is_long = 1;
2645 goto str_const;
2646 } else {
2647 cstr_reset(&tokcstr);
2648 cstr_ccat(&tokcstr, 'L');
2649 goto parse_ident_slow;
2652 break;
2654 case '0': case '1': case '2': case '3':
2655 case '4': case '5': case '6': case '7':
2656 case '8': case '9':
2657 t = c;
2658 PEEKC(c, p);
2659 /* after the first digit, accept digits, alpha, '.' or sign if
2660 prefixed by 'eEpP' */
2661 parse_num:
2662 cstr_reset(&tokcstr);
2663 for(;;) {
2664 cstr_ccat(&tokcstr, t);
2665 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2666 || c == '.'
2667 || ((c == '+' || c == '-')
2668 && (((t == 'e' || t == 'E')
2669 && !(parse_flags & PARSE_FLAG_ASM_FILE
2670 /* 0xe+1 is 3 tokens in asm */
2671 && ((char*)tokcstr.data)[0] == '0'
2672 && toup(((char*)tokcstr.data)[1]) == 'X'))
2673 || t == 'p' || t == 'P'))))
2674 break;
2675 t = c;
2676 PEEKC(c, p);
2678 /* We add a trailing '\0' to ease parsing */
2679 cstr_ccat(&tokcstr, '\0');
2680 tokc.str.size = tokcstr.size;
2681 tokc.str.data = tokcstr.data;
2682 tok = TOK_PPNUM;
2683 break;
2685 case '.':
2686 /* special dot handling because it can also start a number */
2687 PEEKC(c, p);
2688 if (isnum(c)) {
2689 t = '.';
2690 goto parse_num;
2691 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2692 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2693 *--p = c = '.';
2694 goto parse_ident_fast;
2695 } else if (c == '.') {
2696 PEEKC(c, p);
2697 if (c == '.') {
2698 p++;
2699 tok = TOK_DOTS;
2700 } else {
2701 *--p = '.'; /* may underflow into file->unget[] */
2702 tok = '.';
2704 } else {
2705 tok = '.';
2707 break;
2708 case '\'':
2709 case '\"':
2710 is_long = 0;
2711 str_const:
2712 cstr_reset(&tokcstr);
2713 if (is_long)
2714 cstr_ccat(&tokcstr, 'L');
2715 cstr_ccat(&tokcstr, c);
2716 p = parse_pp_string(p, c, &tokcstr);
2717 cstr_ccat(&tokcstr, c);
2718 cstr_ccat(&tokcstr, '\0');
2719 tokc.str.size = tokcstr.size;
2720 tokc.str.data = tokcstr.data;
2721 tok = TOK_PPSTR;
2722 break;
2724 case '<':
2725 PEEKC(c, p);
2726 if (c == '=') {
2727 p++;
2728 tok = TOK_LE;
2729 } else if (c == '<') {
2730 PEEKC(c, p);
2731 if (c == '=') {
2732 p++;
2733 tok = TOK_A_SHL;
2734 } else {
2735 tok = TOK_SHL;
2737 } else {
2738 tok = TOK_LT;
2740 break;
2741 case '>':
2742 PEEKC(c, p);
2743 if (c == '=') {
2744 p++;
2745 tok = TOK_GE;
2746 } else if (c == '>') {
2747 PEEKC(c, p);
2748 if (c == '=') {
2749 p++;
2750 tok = TOK_A_SAR;
2751 } else {
2752 tok = TOK_SAR;
2754 } else {
2755 tok = TOK_GT;
2757 break;
2759 case '&':
2760 PEEKC(c, p);
2761 if (c == '&') {
2762 p++;
2763 tok = TOK_LAND;
2764 } else if (c == '=') {
2765 p++;
2766 tok = TOK_A_AND;
2767 } else {
2768 tok = '&';
2770 break;
2772 case '|':
2773 PEEKC(c, p);
2774 if (c == '|') {
2775 p++;
2776 tok = TOK_LOR;
2777 } else if (c == '=') {
2778 p++;
2779 tok = TOK_A_OR;
2780 } else {
2781 tok = '|';
2783 break;
2785 case '+':
2786 PEEKC(c, p);
2787 if (c == '+') {
2788 p++;
2789 tok = TOK_INC;
2790 } else if (c == '=') {
2791 p++;
2792 tok = TOK_A_ADD;
2793 } else {
2794 tok = '+';
2796 break;
2798 case '-':
2799 PEEKC(c, p);
2800 if (c == '-') {
2801 p++;
2802 tok = TOK_DEC;
2803 } else if (c == '=') {
2804 p++;
2805 tok = TOK_A_SUB;
2806 } else if (c == '>') {
2807 p++;
2808 tok = TOK_ARROW;
2809 } else {
2810 tok = '-';
2812 break;
2814 PARSE2('!', '!', '=', TOK_NE)
2815 PARSE2('=', '=', '=', TOK_EQ)
2816 PARSE2('*', '*', '=', TOK_A_MUL)
2817 PARSE2('%', '%', '=', TOK_A_MOD)
2818 PARSE2('^', '^', '=', TOK_A_XOR)
2820 /* comments or operator */
2821 case '/':
2822 PEEKC(c, p);
2823 if (c == '*') {
2824 p = parse_comment(p);
2825 /* comments replaced by a blank */
2826 tok = ' ';
2827 goto keep_tok_flags;
2828 } else if (c == '/') {
2829 p = parse_line_comment(p);
2830 tok = ' ';
2831 goto keep_tok_flags;
2832 } else if (c == '=') {
2833 p++;
2834 tok = TOK_A_DIV;
2835 } else {
2836 tok = '/';
2838 break;
2840 /* simple tokens */
2841 case '(':
2842 case ')':
2843 case '[':
2844 case ']':
2845 case '{':
2846 case '}':
2847 case ',':
2848 case ';':
2849 case ':':
2850 case '?':
2851 case '~':
2852 case '@': /* only used in assembler */
2853 parse_simple:
2854 tok = c;
2855 p++;
2856 break;
2857 default:
2858 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2859 goto parse_ident_fast;
2860 if (parse_flags & PARSE_FLAG_ASM_FILE)
2861 goto parse_simple;
2862 tcc_error("unrecognized character \\x%02x", c);
2863 break;
2865 tok_flags = 0;
2866 keep_tok_flags:
2867 file->buf_ptr = p;
2868 #if defined(PARSE_DEBUG)
2869 printf("token = %s\n", get_tok_str(tok, &tokc));
2870 #endif
2873 /* return next token without macro substitution. Can read input from
2874 macro_ptr buffer */
2875 static void next_nomacro_spc(void)
2877 if (macro_ptr) {
2878 redo:
2879 tok = *macro_ptr;
2880 if (tok) {
2881 TOK_GET(&tok, &macro_ptr, &tokc);
2882 if (tok == TOK_LINENUM) {
2883 file->line_num = tokc.i;
2884 goto redo;
2887 } else {
2888 next_nomacro1();
2892 ST_FUNC void next_nomacro(void)
2894 do {
2895 next_nomacro_spc();
2896 } while (tok < 256 && (isidnum_table[tok - CH_EOF] & IS_SPC));
2900 static void macro_subst(
2901 TokenString *tok_str,
2902 Sym **nested_list,
2903 const int *macro_str,
2904 int can_read_stream
2907 /* substitute arguments in replacement lists in macro_str by the values in
2908 args (field d) and return allocated string */
2909 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2911 int t, t0, t1, spc;
2912 const int *st;
2913 Sym *s;
2914 CValue cval;
2915 TokenString str;
2916 CString cstr;
2918 tok_str_new(&str);
2919 t0 = t1 = 0;
2920 while(1) {
2921 TOK_GET(&t, &macro_str, &cval);
2922 if (!t)
2923 break;
2924 if (t == '#') {
2925 /* stringize */
2926 TOK_GET(&t, &macro_str, &cval);
2927 if (!t)
2928 goto bad_stringy;
2929 s = sym_find2(args, t);
2930 if (s) {
2931 cstr_new(&cstr);
2932 cstr_ccat(&cstr, '\"');
2933 st = s->d;
2934 spc = 0;
2935 while (*st) {
2936 TOK_GET(&t, &st, &cval);
2937 if (t != TOK_PLCHLDR
2938 && t != TOK_NOSUBST
2939 && 0 == check_space(t, &spc)) {
2940 const char *s = get_tok_str(t, &cval);
2941 while (*s) {
2942 if (t == TOK_PPSTR && *s != '\'')
2943 add_char(&cstr, *s);
2944 else
2945 cstr_ccat(&cstr, *s);
2946 ++s;
2950 cstr.size -= spc;
2951 cstr_ccat(&cstr, '\"');
2952 cstr_ccat(&cstr, '\0');
2953 #ifdef PP_DEBUG
2954 printf("\nstringize: <%s>\n", (char *)cstr.data);
2955 #endif
2956 /* add string */
2957 cval.str.size = cstr.size;
2958 cval.str.data = cstr.data;
2959 tok_str_add2(&str, TOK_PPSTR, &cval);
2960 cstr_free(&cstr);
2961 } else {
2962 bad_stringy:
2963 expect("macro parameter after '#'");
2965 } else if (t >= TOK_IDENT) {
2966 s = sym_find2(args, t);
2967 if (s) {
2968 int l0 = str.len;
2969 st = s->d;
2970 /* if '##' is present before or after, no arg substitution */
2971 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
2972 /* special case for var arg macros : ## eats the ','
2973 if empty VA_ARGS variable. */
2974 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
2975 if (*st == 0) {
2976 /* suppress ',' '##' */
2977 str.len -= 2;
2978 } else {
2979 /* suppress '##' and add variable */
2980 str.len--;
2981 goto add_var;
2983 } else {
2984 for(;;) {
2985 int t1;
2986 TOK_GET(&t1, &st, &cval);
2987 if (!t1)
2988 break;
2989 tok_str_add2(&str, t1, &cval);
2993 } else {
2994 add_var:
2995 /* NOTE: the stream cannot be read when macro
2996 substituting an argument */
2997 macro_subst(&str, nested_list, st, 0);
2999 if (str.len == l0) /* expanded to empty string */
3000 tok_str_add(&str, TOK_PLCHLDR);
3001 } else {
3002 tok_str_add(&str, t);
3004 } else {
3005 tok_str_add2(&str, t, &cval);
3007 t0 = t1, t1 = t;
3009 tok_str_add(&str, 0);
3010 return str.str;
3013 static char const ab_month_name[12][4] =
3015 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3016 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3019 /* peek or read [ws_str == NULL] next token from function macro call,
3020 walking up macro levels up to the file if necessary */
3021 static int next_argstream(Sym **nested_list, int can_read_stream, TokenString *ws_str)
3023 int t;
3024 const int *p;
3025 Sym *sa;
3027 for (;;) {
3028 if (macro_ptr) {
3029 p = macro_ptr, t = *p;
3030 if (ws_str) {
3031 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3032 tok_str_add(ws_str, t), t = *++p;
3034 if (t == 0 && can_read_stream) {
3035 end_macro();
3036 /* also, end of scope for nested defined symbol */
3037 sa = *nested_list;
3038 while (sa && sa->v == 0)
3039 sa = sa->prev;
3040 if (sa)
3041 sa->v = 0;
3042 continue;
3044 } else {
3045 ch = handle_eob();
3046 if (ws_str) {
3047 while (is_space(ch) || ch == '\n' || ch == '/') {
3048 if (ch == '/') {
3049 int c;
3050 uint8_t *p = file->buf_ptr;
3051 PEEKC(c, p);
3052 if (c == '*') {
3053 p = parse_comment(p);
3054 file->buf_ptr = p - 1;
3055 } else if (c == '/') {
3056 p = parse_line_comment(p);
3057 file->buf_ptr = p - 1;
3058 } else
3059 break;
3060 ch = ' ';
3062 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3063 tok_str_add(ws_str, ch);
3064 cinp();
3067 t = ch;
3070 if (ws_str)
3071 return t;
3072 next_nomacro_spc();
3073 return tok;
3077 /* do macro substitution of current token with macro 's' and add
3078 result to (tok_str,tok_len). 'nested_list' is the list of all
3079 macros we got inside to avoid recursing. Return non zero if no
3080 substitution needs to be done */
3081 static int macro_subst_tok(
3082 TokenString *tok_str,
3083 Sym **nested_list,
3084 Sym *s,
3085 int can_read_stream)
3087 Sym *args, *sa, *sa1;
3088 int parlevel, *mstr, t, t1, spc;
3089 TokenString str;
3090 char *cstrval;
3091 CValue cval;
3092 CString cstr;
3093 char buf[32];
3095 /* if symbol is a macro, prepare substitution */
3096 /* special macros */
3097 if (tok == TOK___LINE__) {
3098 snprintf(buf, sizeof(buf), "%d", file->line_num);
3099 cstrval = buf;
3100 t1 = TOK_PPNUM;
3101 goto add_cstr1;
3102 } else if (tok == TOK___FILE__) {
3103 cstrval = file->filename;
3104 goto add_cstr;
3105 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3106 time_t ti;
3107 struct tm *tm;
3109 time(&ti);
3110 tm = localtime(&ti);
3111 if (tok == TOK___DATE__) {
3112 snprintf(buf, sizeof(buf), "%s %2d %d",
3113 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3114 } else {
3115 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3116 tm->tm_hour, tm->tm_min, tm->tm_sec);
3118 cstrval = buf;
3119 add_cstr:
3120 t1 = TOK_STR;
3121 add_cstr1:
3122 cstr_new(&cstr);
3123 cstr_cat(&cstr, cstrval, 0);
3124 cval.str.size = cstr.size;
3125 cval.str.data = cstr.data;
3126 tok_str_add2(tok_str, t1, &cval);
3127 cstr_free(&cstr);
3128 } else {
3129 int saved_parse_flags = parse_flags;
3131 mstr = s->d;
3132 if (s->type.t == MACRO_FUNC) {
3133 /* whitespace between macro name and argument list */
3134 TokenString ws_str;
3135 tok_str_new(&ws_str);
3137 spc = 0;
3138 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3139 | PARSE_FLAG_ACCEPT_STRAYS;
3141 /* get next token from argument stream */
3142 t = next_argstream(nested_list, can_read_stream, &ws_str);
3143 if (t != '(') {
3144 /* not a macro substitution after all, restore the
3145 * macro token plus all whitespace we've read.
3146 * whitespace is intentionally not merged to preserve
3147 * newlines. */
3148 parse_flags = saved_parse_flags;
3149 tok_str_add(tok_str, tok);
3150 if (parse_flags & PARSE_FLAG_SPACES) {
3151 int i;
3152 for (i = 0; i < ws_str.len; i++)
3153 tok_str_add(tok_str, ws_str.str[i]);
3155 tok_str_free_str(ws_str.str);
3156 return 0;
3157 } else {
3158 tok_str_free_str(ws_str.str);
3160 do {
3161 next_nomacro(); /* eat '(' */
3162 } while (tok == TOK_PLCHLDR);
3164 /* argument macro */
3165 args = NULL;
3166 sa = s->next;
3167 /* NOTE: empty args are allowed, except if no args */
3168 for(;;) {
3169 do {
3170 next_argstream(nested_list, can_read_stream, NULL);
3171 } while (is_space(tok) || TOK_LINEFEED == tok);
3172 empty_arg:
3173 /* handle '()' case */
3174 if (!args && !sa && tok == ')')
3175 break;
3176 if (!sa)
3177 tcc_error("macro '%s' used with too many args",
3178 get_tok_str(s->v, 0));
3179 tok_str_new(&str);
3180 parlevel = spc = 0;
3181 /* NOTE: non zero sa->t indicates VA_ARGS */
3182 while ((parlevel > 0 ||
3183 (tok != ')' &&
3184 (tok != ',' || sa->type.t)))) {
3185 if (tok == TOK_EOF || tok == 0)
3186 break;
3187 if (tok == '(')
3188 parlevel++;
3189 else if (tok == ')')
3190 parlevel--;
3191 if (tok == TOK_LINEFEED)
3192 tok = ' ';
3193 if (!check_space(tok, &spc))
3194 tok_str_add2(&str, tok, &tokc);
3195 next_argstream(nested_list, can_read_stream, NULL);
3197 if (parlevel)
3198 expect(")");
3199 str.len -= spc;
3200 tok_str_add(&str, 0);
3201 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3202 sa1->d = str.str;
3203 sa = sa->next;
3204 if (tok == ')') {
3205 /* special case for gcc var args: add an empty
3206 var arg argument if it is omitted */
3207 if (sa && sa->type.t && gnu_ext)
3208 goto empty_arg;
3209 break;
3211 if (tok != ',')
3212 expect(",");
3214 if (sa) {
3215 tcc_error("macro '%s' used with too few args",
3216 get_tok_str(s->v, 0));
3219 parse_flags = saved_parse_flags;
3221 /* now subst each arg */
3222 mstr = macro_arg_subst(nested_list, mstr, args);
3223 /* free memory */
3224 sa = args;
3225 while (sa) {
3226 sa1 = sa->prev;
3227 tok_str_free_str(sa->d);
3228 sym_free(sa);
3229 sa = sa1;
3233 sym_push2(nested_list, s->v, 0, 0);
3234 parse_flags = saved_parse_flags;
3235 macro_subst(tok_str, nested_list, mstr, can_read_stream | 2);
3237 /* pop nested defined symbol */
3238 sa1 = *nested_list;
3239 *nested_list = sa1->prev;
3240 sym_free(sa1);
3241 if (mstr != s->d)
3242 tok_str_free_str(mstr);
3244 return 0;
3247 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3249 CString cstr;
3250 int n, ret = 1;
3252 cstr_new(&cstr);
3253 if (t1 != TOK_PLCHLDR)
3254 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3255 n = cstr.size;
3256 if (t2 != TOK_PLCHLDR)
3257 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3258 cstr_ccat(&cstr, '\0');
3260 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3261 memcpy(file->buffer, cstr.data, cstr.size);
3262 for (;;) {
3263 next_nomacro1();
3264 if (0 == *file->buf_ptr)
3265 break;
3266 if (is_space(tok))
3267 continue;
3268 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3269 " preprocessing token", n, cstr.data, (char*)cstr.data + n);
3270 ret = 0;
3271 break;
3273 tcc_close();
3274 //printf("paste <%s>\n", (char*)cstr.data);
3275 cstr_free(&cstr);
3276 return ret;
3279 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3280 return the resulting string (which must be freed). */
3281 static inline int *macro_twosharps(const int *ptr0)
3283 int t;
3284 CValue cval;
3285 TokenString macro_str1;
3286 int start_of_nosubsts = -1;
3287 const int *ptr;
3289 /* we search the first '##' */
3290 for (ptr = ptr0;;) {
3291 TOK_GET(&t, &ptr, &cval);
3292 if (t == TOK_PPJOIN)
3293 break;
3294 if (t == 0)
3295 return NULL;
3298 tok_str_new(&macro_str1);
3300 //tok_print(" $$$", ptr0);
3301 for (ptr = ptr0;;) {
3302 TOK_GET(&t, &ptr, &cval);
3303 if (t == 0)
3304 break;
3305 if (t == TOK_PPJOIN)
3306 continue;
3307 while (*ptr == TOK_PPJOIN) {
3308 int t1; CValue cv1;
3309 /* given 'a##b', remove nosubsts preceding 'a' */
3310 if (start_of_nosubsts >= 0)
3311 macro_str1.len = start_of_nosubsts;
3312 /* given 'a##b', remove nosubsts preceding 'b' */
3313 while ((t1 = *++ptr) == TOK_NOSUBST)
3315 if (t1 && t1 != TOK_PPJOIN) {
3316 TOK_GET(&t1, &ptr, &cv1);
3317 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3318 if (paste_tokens(t, &cval, t1, &cv1)) {
3319 t = tok, cval = tokc;
3320 } else {
3321 tok_str_add2(&macro_str1, t, &cval);
3322 t = t1, cval = cv1;
3327 if (t == TOK_NOSUBST) {
3328 if (start_of_nosubsts < 0)
3329 start_of_nosubsts = macro_str1.len;
3330 } else {
3331 start_of_nosubsts = -1;
3333 tok_str_add2(&macro_str1, t, &cval);
3335 tok_str_add(&macro_str1, 0);
3336 //tok_print(" ###", macro_str1.str);
3337 return macro_str1.str;
3340 /* do macro substitution of macro_str and add result to
3341 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3342 inside to avoid recursing. */
3343 static void macro_subst(
3344 TokenString *tok_str,
3345 Sym **nested_list,
3346 const int *macro_str,
3347 int can_read_stream
3350 Sym *s;
3351 const int *ptr;
3352 int t, spc, nosubst;
3353 CValue cval;
3354 int *macro_str1 = NULL;
3356 /* first scan for '##' operator handling */
3357 ptr = macro_str;
3358 spc = nosubst = 0;
3360 /* first scan for '##' operator handling */
3361 if (can_read_stream) {
3362 macro_str1 = macro_twosharps(ptr);
3363 if (macro_str1)
3364 ptr = macro_str1;
3367 while (1) {
3368 TOK_GET(&t, &ptr, &cval);
3369 if (t == 0)
3370 break;
3372 if (t >= TOK_IDENT && 0 == nosubst) {
3373 s = define_find(t);
3374 if (s == NULL)
3375 goto no_subst;
3377 /* if nested substitution, do nothing */
3378 if (sym_find2(*nested_list, t)) {
3379 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3380 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3381 goto no_subst;
3385 TokenString str;
3386 str.str = (int*)ptr;
3387 begin_macro(&str, 2);
3389 tok = t;
3390 macro_subst_tok(tok_str, nested_list, s, can_read_stream);
3392 if (str.alloc == 3) {
3393 /* already finished by reading function macro arguments */
3394 break;
3397 ptr = macro_ptr;
3398 end_macro ();
3401 spc = (tok_str->len &&
3402 is_space(tok_last(tok_str->str,
3403 tok_str->str + tok_str->len)));
3405 } else {
3407 if (t == '\\' && !(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3408 tcc_error("stray '\\' in program");
3410 no_subst:
3411 if (!check_space(t, &spc))
3412 tok_str_add2(tok_str, t, &cval);
3413 nosubst = 0;
3414 if (t == TOK_NOSUBST)
3415 nosubst = 1;
3418 if (macro_str1)
3419 tok_str_free_str(macro_str1);
3423 /* return next token with macro substitution */
3424 ST_FUNC void next(void)
3426 redo:
3427 if (parse_flags & PARSE_FLAG_SPACES)
3428 next_nomacro_spc();
3429 else
3430 next_nomacro();
3432 if (macro_ptr) {
3433 if (tok == TOK_NOSUBST || tok == TOK_PLCHLDR) {
3434 /* discard preprocessor markers */
3435 goto redo;
3436 } else if (tok == 0) {
3437 /* end of macro or unget token string */
3438 end_macro();
3439 goto redo;
3441 } else if (tok >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3442 Sym *s;
3443 /* if reading from file, try to substitute macros */
3444 s = define_find(tok);
3445 if (s) {
3446 Sym *nested_list = NULL;
3447 tokstr_buf.len = 0;
3448 macro_subst_tok(&tokstr_buf, &nested_list, s, 1);
3449 tok_str_add(&tokstr_buf, 0);
3450 begin_macro(&tokstr_buf, 2);
3451 goto redo;
3454 /* convert preprocessor tokens into C tokens */
3455 if (tok == TOK_PPNUM) {
3456 if (parse_flags & PARSE_FLAG_TOK_NUM)
3457 parse_number((char *)tokc.str.data);
3458 } else if (tok == TOK_PPSTR) {
3459 if (parse_flags & PARSE_FLAG_TOK_STR)
3460 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3464 /* push back current token and set current token to 'last_tok'. Only
3465 identifier case handled for labels. */
3466 ST_INLN void unget_tok(int last_tok)
3469 TokenString *str = tok_str_alloc();
3470 tok_str_add2(str, tok, &tokc);
3471 tok_str_add(str, 0);
3472 begin_macro(str, 1);
3473 tok = last_tok;
3476 ST_FUNC void preprocess_start(TCCState *s1)
3478 char *buf;
3480 s1->include_stack_ptr = s1->include_stack;
3481 s1->ifdef_stack_ptr = s1->ifdef_stack;
3482 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3483 pp_once++;
3484 pvtop = vtop = vstack - 1;
3485 s1->pack_stack[0] = 0;
3486 s1->pack_stack_ptr = s1->pack_stack;
3488 set_idnum('$', s1->dollars_in_identifiers ? IS_ID : 0);
3489 set_idnum('.', (parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0);
3491 buf = tcc_malloc(3 + strlen(file->filename));
3492 sprintf(buf, "\"%s\"", file->filename);
3493 tcc_define_symbol(s1, "__BASE_FILE__", buf);
3494 tcc_free(buf);
3496 if (s1->nb_cmd_include_files) {
3497 CString cstr;
3498 int i;
3499 cstr_new(&cstr);
3500 for (i = 0; i < s1->nb_cmd_include_files; i++) {
3501 cstr_cat(&cstr, "#include \"", -1);
3502 cstr_cat(&cstr, s1->cmd_include_files[i], -1);
3503 cstr_cat(&cstr, "\"\n", -1);
3505 *s1->include_stack_ptr++ = file;
3506 tcc_open_bf(s1, "<command line>", cstr.size);
3507 memcpy(file->buffer, cstr.data, cstr.size);
3508 cstr_free(&cstr);
3512 ST_FUNC void tccpp_new(TCCState *s)
3514 int i, c;
3515 const char *p, *r;
3517 /* might be used in error() before preprocess_start() */
3518 s->include_stack_ptr = s->include_stack;
3520 /* init isid table */
3521 for(i = CH_EOF; i<128; i++)
3522 set_idnum(i,
3523 is_space(i) ? IS_SPC
3524 : isid(i) ? IS_ID
3525 : isnum(i) ? IS_NUM
3526 : 0);
3528 for(i = 128; i<256; i++)
3529 set_idnum(i, IS_ID);
3531 /* init allocators */
3532 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3533 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3534 tal_new(&cstr_alloc, CSTR_TAL_LIMIT, CSTR_TAL_SIZE);
3536 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3537 cstr_new(&cstr_buf);
3538 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3539 tok_str_new(&tokstr_buf);
3540 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3542 tok_ident = TOK_IDENT;
3543 p = tcc_keywords;
3544 while (*p) {
3545 r = p;
3546 for(;;) {
3547 c = *r++;
3548 if (c == '\0')
3549 break;
3551 tok_alloc(p, r - p - 1);
3552 p = r;
3556 ST_FUNC void tccpp_delete(TCCState *s)
3558 int i, n;
3560 /* free -D and compiler defines */
3561 free_defines(NULL);
3563 /* cleanup from error/setjmp */
3564 while (macro_stack)
3565 end_macro();
3566 macro_ptr = NULL;
3568 while (file)
3569 tcc_close();
3571 /* free tokens */
3572 n = tok_ident - TOK_IDENT;
3573 for(i = 0; i < n; i++)
3574 tal_free(toksym_alloc, table_ident[i]);
3575 tcc_free(table_ident);
3576 table_ident = NULL;
3578 /* free static buffers */
3579 cstr_free(&tokcstr);
3580 cstr_free(&cstr_buf);
3581 cstr_free(&macro_equal_buf);
3582 tok_str_free_str(tokstr_buf.str);
3584 /* free allocators */
3585 tal_delete(toksym_alloc);
3586 toksym_alloc = NULL;
3587 tal_delete(tokstr_alloc);
3588 tokstr_alloc = NULL;
3589 tal_delete(cstr_alloc);
3590 cstr_alloc = NULL;
3593 /* ------------------------------------------------------------------------- */
3594 /* tcc -E [-P[1]] [-dD} support */
3596 static void tok_print(const char *msg, const int *str)
3598 FILE *fp;
3599 int t;
3600 CValue cval;
3602 fp = tcc_state->ppfp;
3603 if (!fp || !tcc_state->dflag)
3604 fp = stdout;
3606 fprintf(fp, "%s ", msg);
3607 while (str) {
3608 TOK_GET(&t, &str, &cval);
3609 if (!t)
3610 break;
3611 fprintf(fp,"%s", get_tok_str(t, &cval));
3613 fprintf(fp, "\n");
3616 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3618 int d = f->line_num - f->line_ref;
3620 if (s1->dflag & 4)
3621 return;
3623 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3625 } else if (level == 0 && f->line_ref && d < 8) {
3626 while (d > 0)
3627 fputs("\n", s1->ppfp), --d;
3628 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3629 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3630 } else {
3631 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3632 level > 0 ? " 1" : level < 0 ? " 2" : "");
3634 f->line_ref = f->line_num;
3637 static void define_print(TCCState *s1, int v)
3639 FILE *fp;
3640 Sym *s;
3642 s = define_find(v);
3643 if (NULL == s || NULL == s->d)
3644 return;
3646 fp = s1->ppfp;
3647 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3648 if (s->type.t == MACRO_FUNC) {
3649 Sym *a = s->next;
3650 fprintf(fp,"(");
3651 if (a)
3652 for (;;) {
3653 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3654 if (!(a = a->next))
3655 break;
3656 fprintf(fp,",");
3658 fprintf(fp,")");
3660 tok_print("", s->d);
3663 static void pp_debug_defines(TCCState *s1)
3665 int v, t;
3666 const char *vs;
3667 FILE *fp;
3669 t = pp_debug_tok;
3670 if (t == 0)
3671 return;
3673 file->line_num--;
3674 pp_line(s1, file, 0);
3675 file->line_ref = ++file->line_num;
3677 fp = s1->ppfp;
3678 v = pp_debug_symv;
3679 vs = get_tok_str(v, NULL);
3680 if (t == TOK_DEFINE) {
3681 define_print(s1, v);
3682 } else if (t == TOK_UNDEF) {
3683 fprintf(fp, "#undef %s\n", vs);
3684 } else if (t == TOK_push_macro) {
3685 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3686 } else if (t == TOK_pop_macro) {
3687 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3689 pp_debug_tok = 0;
3692 static void pp_debug_builtins(TCCState *s1)
3694 int v;
3695 for (v = TOK_IDENT; v < tok_ident; ++v)
3696 define_print(s1, v);
3699 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3700 static int pp_need_space(int a, int b)
3702 return 'E' == a ? '+' == b || '-' == b
3703 : '+' == a ? TOK_INC == b || '+' == b
3704 : '-' == a ? TOK_DEC == b || '-' == b
3705 : a >= TOK_IDENT ? b >= TOK_IDENT
3706 : 0;
3709 /* maybe hex like 0x1e */
3710 static int pp_check_he0xE(int t, const char *p)
3712 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3713 return 'E';
3714 return t;
3717 /* Preprocess the current file */
3718 ST_FUNC int tcc_preprocess(TCCState *s1)
3720 BufferedFile **iptr;
3721 int token_seen, spcs, level;
3722 const char *p;
3723 Sym *define_start;
3725 define_start = define_stack;
3726 preprocess_start(s1);
3728 ch = file->buf_ptr[0];
3729 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3730 parse_flags = PARSE_FLAG_PREPROCESS
3731 | (parse_flags & PARSE_FLAG_ASM_FILE)
3732 | PARSE_FLAG_LINEFEED
3733 | PARSE_FLAG_SPACES
3734 | PARSE_FLAG_ACCEPT_STRAYS
3737 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3738 capability to compile and run itself, provided all numbers are
3739 given as decimals. tcc -E -P10 will do. */
3740 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3741 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3743 #ifdef PP_BENCH
3744 /* for PP benchmarks */
3745 do next(); while (tok != TOK_EOF);
3746 free_defines(define_start);
3747 return 0;
3748 #endif
3750 if (s1->dflag & 1) {
3751 pp_debug_builtins(s1);
3752 s1->dflag &= ~1;
3755 token_seen = TOK_LINEFEED, spcs = 0;
3756 pp_line(s1, file, 0);
3758 for (;;) {
3759 iptr = s1->include_stack_ptr;
3760 next();
3761 if (tok == TOK_EOF)
3762 break;
3763 level = s1->include_stack_ptr - iptr;
3764 if (level) {
3765 if (level > 0)
3766 pp_line(s1, *iptr, 0);
3767 pp_line(s1, file, level);
3770 if (s1->dflag) {
3771 pp_debug_defines(s1);
3772 if (s1->dflag & 4)
3773 continue;
3776 if (token_seen == TOK_LINEFEED) {
3777 if (tok == ' ') {
3778 ++spcs;
3779 continue;
3781 if (tok == TOK_LINEFEED) {
3782 spcs = 0;
3783 continue;
3785 pp_line(s1, file, 0);
3786 } else if (tok == TOK_LINEFEED) {
3787 ++file->line_ref;
3788 } else {
3789 spcs = pp_need_space(token_seen, tok);
3792 while (spcs)
3793 fputs(" ", s1->ppfp), --spcs;
3794 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
3795 token_seen = pp_check_he0xE(tok, p);;
3797 /* reset define stack, but keep -D and built-ins */
3798 free_defines(define_start);
3799 return 0;
3802 /* ------------------------------------------------------------------------- */