Simple-minded fix for bug #50847
[tinycc.git] / tccpp.c
blob1f3b083b1e931f09a537a06b08a366c23c8b405e
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_CFLOAT:
1234 case TOK_LINENUM:
1235 tab[0] = *p++;
1236 break;
1237 case TOK_STR:
1238 case TOK_LSTR:
1239 case TOK_PPNUM:
1240 case TOK_PPSTR:
1241 cv->str.size = *p++;
1242 cv->str.data = p;
1243 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1244 break;
1245 case TOK_CDOUBLE:
1246 case TOK_CLLONG:
1247 case TOK_CULLONG:
1248 n = 2;
1249 goto copy;
1250 case TOK_CLDOUBLE:
1251 #if LDOUBLE_SIZE == 16
1252 n = 4;
1253 #elif LDOUBLE_SIZE == 12
1254 n = 3;
1255 #elif LDOUBLE_SIZE == 8
1256 n = 2;
1257 #else
1258 # error add long double size support
1259 #endif
1260 copy:
1262 *tab++ = *p++;
1263 while (--n);
1264 break;
1265 default:
1266 break;
1268 *pp = p;
1271 /* Calling this function is expensive, but it is not possible
1272 to read a token string backwards. */
1273 static int tok_last(const int *str0, const int *str1)
1275 const int *str = str0;
1276 int tok = 0;
1277 CValue cval;
1279 while (str < str1)
1280 TOK_GET(&tok, &str, &cval);
1281 return tok;
1284 static int macro_is_equal(const int *a, const int *b)
1286 CValue cv;
1287 int t;
1289 if (!a || !b)
1290 return 1;
1292 while (*a && *b) {
1293 /* first time preallocate macro_equal_buf, next time only reset position to start */
1294 cstr_reset(&macro_equal_buf);
1295 TOK_GET(&t, &a, &cv);
1296 cstr_cat(&macro_equal_buf, get_tok_str(t, &cv), 0);
1297 TOK_GET(&t, &b, &cv);
1298 if (strcmp(macro_equal_buf.data, get_tok_str(t, &cv)))
1299 return 0;
1301 return !(*a || *b);
1304 /* defines handling */
1305 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1307 Sym *s, *o;
1309 o = define_find(v);
1310 s = sym_push2(&define_stack, v, macro_type, 0);
1311 s->d = str;
1312 s->next = first_arg;
1313 table_ident[v - TOK_IDENT]->sym_define = s;
1315 if (o && !macro_is_equal(o->d, s->d))
1316 tcc_warning("%s redefined", get_tok_str(v, NULL));
1319 /* undefined a define symbol. Its name is just set to zero */
1320 ST_FUNC void define_undef(Sym *s)
1322 int v = s->v;
1323 if (v >= TOK_IDENT && v < tok_ident)
1324 table_ident[v - TOK_IDENT]->sym_define = NULL;
1327 ST_INLN Sym *define_find(int v)
1329 v -= TOK_IDENT;
1330 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1331 return NULL;
1332 return table_ident[v]->sym_define;
1335 /* free define stack until top reaches 'b' */
1336 ST_FUNC void free_defines(Sym *b)
1338 while (define_stack != b) {
1339 Sym *top = define_stack;
1340 define_stack = top->prev;
1341 tok_str_free_str(top->d);
1342 define_undef(top);
1343 sym_free(top);
1346 /* restore remaining (-D or predefined) symbols if they were
1347 #undef'd in the file */
1348 while (b) {
1349 int v = b->v;
1350 if (v >= TOK_IDENT && v < tok_ident) {
1351 Sym **d = &table_ident[v - TOK_IDENT]->sym_define;
1352 if (!*d)
1353 *d = b;
1355 b = b->prev;
1359 /* label lookup */
1360 ST_FUNC Sym *label_find(int v)
1362 v -= TOK_IDENT;
1363 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1364 return NULL;
1365 return table_ident[v]->sym_label;
1368 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1370 Sym *s, **ps;
1371 s = sym_push2(ptop, v, 0, 0);
1372 s->r = flags;
1373 ps = &table_ident[v - TOK_IDENT]->sym_label;
1374 if (ptop == &global_label_stack) {
1375 /* modify the top most local identifier, so that
1376 sym_identifier will point to 's' when popped */
1377 while (*ps != NULL)
1378 ps = &(*ps)->prev_tok;
1380 s->prev_tok = *ps;
1381 *ps = s;
1382 return s;
1385 /* pop labels until element last is reached. Look if any labels are
1386 undefined. Define symbols if '&&label' was used. */
1387 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1389 Sym *s, *s1;
1390 for(s = *ptop; s != slast; s = s1) {
1391 s1 = s->prev;
1392 if (s->r == LABEL_DECLARED) {
1393 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1394 } else if (s->r == LABEL_FORWARD) {
1395 tcc_error("label '%s' used but not defined",
1396 get_tok_str(s->v, NULL));
1397 } else {
1398 if (s->c) {
1399 /* define corresponding symbol. A size of
1400 1 is put. */
1401 put_extern_sym(s, cur_text_section, s->jnext, 1);
1404 /* remove label */
1405 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1406 sym_free(s);
1408 *ptop = slast;
1411 /* eval an expression for #if/#elif */
1412 static int expr_preprocess(void)
1414 int c, t;
1415 TokenString *str;
1417 str = tok_str_alloc();
1418 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1419 next(); /* do macro subst */
1420 if (tok == TOK_DEFINED) {
1421 next_nomacro();
1422 t = tok;
1423 if (t == '(')
1424 next_nomacro();
1425 c = define_find(tok) != 0;
1426 if (t == '(')
1427 next_nomacro();
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 tok_str_add(str, -1); /* simulate end of file */
1438 tok_str_add(str, 0);
1439 /* now evaluate C constant expression */
1440 begin_macro(str, 1);
1441 next();
1442 c = expr_const();
1443 end_macro();
1444 return c != 0;
1448 /* parse after #define */
1449 ST_FUNC void parse_define(void)
1451 Sym *s, *first, **ps;
1452 int v, t, varg, is_vaargs, spc;
1453 int saved_parse_flags = parse_flags;
1455 v = tok;
1456 if (v < TOK_IDENT)
1457 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1458 /* XXX: should check if same macro (ANSI) */
1459 first = NULL;
1460 t = MACRO_OBJ;
1461 /* We have to parse the whole define as if not in asm mode, in particular
1462 no line comment with '#' must be ignored. Also for function
1463 macros the argument list must be parsed without '.' being an ID
1464 character. */
1465 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1466 /* '(' must be just after macro definition for MACRO_FUNC */
1467 next_nomacro_spc();
1468 if (tok == '(') {
1469 set_idnum('.', 0);
1470 next_nomacro();
1471 ps = &first;
1472 if (tok != ')') for (;;) {
1473 varg = tok;
1474 next_nomacro();
1475 is_vaargs = 0;
1476 if (varg == TOK_DOTS) {
1477 varg = TOK___VA_ARGS__;
1478 is_vaargs = 1;
1479 } else if (tok == TOK_DOTS && gnu_ext) {
1480 is_vaargs = 1;
1481 next_nomacro();
1483 if (varg < TOK_IDENT)
1484 bad_list:
1485 tcc_error("bad macro parameter list");
1486 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1487 *ps = s;
1488 ps = &s->next;
1489 if (tok == ')')
1490 break;
1491 if (tok != ',' || is_vaargs)
1492 goto bad_list;
1493 next_nomacro();
1495 next_nomacro_spc();
1496 t = MACRO_FUNC;
1499 tokstr_buf.len = 0;
1500 spc = 2;
1501 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1502 /* The body of a macro definition should be parsed such that identifiers
1503 are parsed like the file mode determines (i.e. with '.' being an
1504 ID character in asm mode). But '#' should be retained instead of
1505 regarded as line comment leader, so still don't set ASM_FILE
1506 in parse_flags. */
1507 set_idnum('.', (saved_parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0);
1508 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1509 /* remove spaces around ## and after '#' */
1510 if (TOK_TWOSHARPS == tok) {
1511 if (2 == spc)
1512 goto bad_twosharp;
1513 if (1 == spc)
1514 --tokstr_buf.len;
1515 spc = 3;
1516 tok = TOK_PPJOIN;
1517 } else if ('#' == tok) {
1518 spc = 4;
1519 } else if (check_space(tok, &spc)) {
1520 goto skip;
1522 tok_str_add2(&tokstr_buf, tok, &tokc);
1523 skip:
1524 next_nomacro_spc();
1527 parse_flags = saved_parse_flags;
1528 if (spc == 1)
1529 --tokstr_buf.len; /* remove trailing space */
1530 tok_str_add(&tokstr_buf, 0);
1531 if (3 == spc)
1532 bad_twosharp:
1533 tcc_error("'##' cannot appear at either end of macro");
1534 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1537 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1539 const unsigned char *s;
1540 unsigned int h;
1541 CachedInclude *e;
1542 int i;
1544 h = TOK_HASH_INIT;
1545 s = (unsigned char *) filename;
1546 while (*s) {
1547 #ifdef _WIN32
1548 h = TOK_HASH_FUNC(h, toup(*s));
1549 #else
1550 h = TOK_HASH_FUNC(h, *s);
1551 #endif
1552 s++;
1554 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1556 i = s1->cached_includes_hash[h];
1557 for(;;) {
1558 if (i == 0)
1559 break;
1560 e = s1->cached_includes[i - 1];
1561 if (0 == PATHCMP(e->filename, filename))
1562 return e;
1563 i = e->hash_next;
1565 if (!add)
1566 return NULL;
1568 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1569 strcpy(e->filename, filename);
1570 e->ifndef_macro = e->once = 0;
1571 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1572 /* add in hash table */
1573 e->hash_next = s1->cached_includes_hash[h];
1574 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1575 #ifdef INC_DEBUG
1576 printf("adding cached '%s'\n", filename);
1577 #endif
1578 return e;
1581 static void pragma_parse(TCCState *s1)
1583 next_nomacro();
1584 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1585 int t = tok, v;
1586 Sym *s;
1588 if (next(), tok != '(')
1589 goto pragma_err;
1590 if (next(), tok != TOK_STR)
1591 goto pragma_err;
1592 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1593 if (next(), tok != ')')
1594 goto pragma_err;
1595 if (t == TOK_push_macro) {
1596 while (NULL == (s = define_find(v)))
1597 define_push(v, 0, NULL, NULL);
1598 s->type.ref = s; /* set push boundary */
1599 } else {
1600 for (s = define_stack; s; s = s->prev)
1601 if (s->v == v && s->type.ref == s) {
1602 s->type.ref = NULL;
1603 break;
1606 if (s)
1607 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1608 else
1609 tcc_warning("unbalanced #pragma pop_macro");
1610 pp_debug_tok = t, pp_debug_symv = v;
1612 } else if (tok == TOK_once) {
1613 search_cached_include(s1, file->filename, 1)->once = pp_once;
1615 } else if (s1->ppfp) {
1616 /* tcc -E: keep pragmas below unchanged */
1617 unget_tok(' ');
1618 unget_tok(TOK_PRAGMA);
1619 unget_tok('#');
1620 unget_tok(TOK_LINEFEED);
1622 } else if (tok == TOK_pack) {
1623 /* This may be:
1624 #pragma pack(1) // set
1625 #pragma pack() // reset to default
1626 #pragma pack(push,1) // push & set
1627 #pragma pack(pop) // restore previous */
1628 next();
1629 skip('(');
1630 if (tok == TOK_ASM_pop) {
1631 next();
1632 if (s1->pack_stack_ptr <= s1->pack_stack) {
1633 stk_error:
1634 tcc_error("out of pack stack");
1636 s1->pack_stack_ptr--;
1637 } else {
1638 int val = 0;
1639 if (tok != ')') {
1640 if (tok == TOK_ASM_push) {
1641 next();
1642 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1643 goto stk_error;
1644 s1->pack_stack_ptr++;
1645 skip(',');
1647 if (tok != TOK_CINT)
1648 goto pragma_err;
1649 val = tokc.i;
1650 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1651 goto pragma_err;
1652 next();
1654 *s1->pack_stack_ptr = val;
1656 if (tok != ')')
1657 goto pragma_err;
1659 } else if (tok == TOK_comment) {
1660 char *file;
1661 next();
1662 skip('(');
1663 if (tok != TOK_lib)
1664 goto pragma_warn;
1665 next();
1666 skip(',');
1667 if (tok != TOK_STR)
1668 goto pragma_err;
1669 file = tcc_strdup((char *)tokc.str.data);
1670 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, file);
1671 next();
1672 if (tok != ')')
1673 goto pragma_err;
1674 } else {
1675 pragma_warn:
1676 if (s1->warn_unsupported)
1677 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1679 return;
1681 pragma_err:
1682 tcc_error("malformed #pragma directive");
1683 return;
1686 /* is_bof is true if first non space token at beginning of file */
1687 ST_FUNC void preprocess(int is_bof)
1689 TCCState *s1 = tcc_state;
1690 int i, c, n, saved_parse_flags;
1691 char buf[1024], *q;
1692 Sym *s;
1694 saved_parse_flags = parse_flags;
1695 parse_flags = PARSE_FLAG_PREPROCESS
1696 | PARSE_FLAG_TOK_NUM
1697 | PARSE_FLAG_TOK_STR
1698 | PARSE_FLAG_LINEFEED
1699 | (parse_flags & PARSE_FLAG_ASM_FILE)
1702 next_nomacro();
1703 redo:
1704 switch(tok) {
1705 case TOK_DEFINE:
1706 pp_debug_tok = tok;
1707 next_nomacro();
1708 pp_debug_symv = tok;
1709 parse_define();
1710 break;
1711 case TOK_UNDEF:
1712 pp_debug_tok = tok;
1713 next_nomacro();
1714 pp_debug_symv = tok;
1715 s = define_find(tok);
1716 /* undefine symbol by putting an invalid name */
1717 if (s)
1718 define_undef(s);
1719 break;
1720 case TOK_INCLUDE:
1721 case TOK_INCLUDE_NEXT:
1722 ch = file->buf_ptr[0];
1723 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1724 skip_spaces();
1725 if (ch == '<') {
1726 c = '>';
1727 goto read_name;
1728 } else if (ch == '\"') {
1729 c = ch;
1730 read_name:
1731 inp();
1732 q = buf;
1733 while (ch != c && ch != '\n' && ch != CH_EOF) {
1734 if ((q - buf) < sizeof(buf) - 1)
1735 *q++ = ch;
1736 if (ch == '\\') {
1737 if (handle_stray_noerror() == 0)
1738 --q;
1739 } else
1740 inp();
1742 *q = '\0';
1743 minp();
1744 #if 0
1745 /* eat all spaces and comments after include */
1746 /* XXX: slightly incorrect */
1747 while (ch1 != '\n' && ch1 != CH_EOF)
1748 inp();
1749 #endif
1750 } else {
1751 int len;
1752 /* computed #include : concatenate everything up to linefeed,
1753 the result must be one of the two accepted forms.
1754 Don't convert pp-tokens to tokens here. */
1755 parse_flags = (PARSE_FLAG_PREPROCESS
1756 | PARSE_FLAG_LINEFEED
1757 | (parse_flags & PARSE_FLAG_ASM_FILE));
1758 next();
1759 buf[0] = '\0';
1760 while (tok != TOK_LINEFEED) {
1761 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1762 next();
1764 len = strlen(buf);
1765 /* check syntax and remove '<>|""' */
1766 if ((len < 2 || ((buf[0] != '"' || buf[len-1] != '"') &&
1767 (buf[0] != '<' || buf[len-1] != '>'))))
1768 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1769 c = buf[len-1];
1770 memmove(buf, buf + 1, len - 2);
1771 buf[len - 2] = '\0';
1774 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1775 tcc_error("#include recursion too deep");
1776 /* store current file in stack, but increment stack later below */
1777 *s1->include_stack_ptr = file;
1778 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index : 0;
1779 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1780 for (; i < n; ++i) {
1781 char buf1[sizeof file->filename];
1782 CachedInclude *e;
1783 const char *path;
1785 if (i == 0) {
1786 /* check absolute include path */
1787 if (!IS_ABSPATH(buf))
1788 continue;
1789 buf1[0] = 0;
1791 } else if (i == 1) {
1792 /* search in file's dir if "header.h" */
1793 if (c != '\"')
1794 continue;
1795 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1796 path = file->filename2;
1797 pstrncpy(buf1, path, tcc_basename(path) - path);
1799 } else {
1800 /* search in all the include paths */
1801 int j = i - 2, k = j - s1->nb_include_paths;
1802 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1803 pstrcpy(buf1, sizeof(buf1), path);
1804 pstrcat(buf1, sizeof(buf1), "/");
1807 pstrcat(buf1, sizeof(buf1), buf);
1808 e = search_cached_include(s1, buf1, 0);
1809 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1810 /* no need to parse the include because the 'ifndef macro'
1811 is defined (or had #pragma once) */
1812 #ifdef INC_DEBUG
1813 printf("%s: skipping cached %s\n", file->filename, buf1);
1814 #endif
1815 goto include_done;
1818 if (tcc_open(s1, buf1) < 0)
1819 continue;
1821 file->include_next_index = i + 1;
1822 #ifdef INC_DEBUG
1823 printf("%s: including %s\n", file->prev->filename, file->filename);
1824 #endif
1825 /* update target deps */
1826 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1827 tcc_strdup(buf1));
1828 /* push current file in stack */
1829 ++s1->include_stack_ptr;
1830 /* add include file debug info */
1831 if (s1->do_debug)
1832 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1833 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1834 ch = file->buf_ptr[0];
1835 goto the_end;
1837 tcc_error("include file '%s' not found", buf);
1838 include_done:
1839 break;
1840 case TOK_IFNDEF:
1841 c = 1;
1842 goto do_ifdef;
1843 case TOK_IF:
1844 c = expr_preprocess();
1845 goto do_if;
1846 case TOK_IFDEF:
1847 c = 0;
1848 do_ifdef:
1849 next_nomacro();
1850 if (tok < TOK_IDENT)
1851 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1852 if (is_bof) {
1853 if (c) {
1854 #ifdef INC_DEBUG
1855 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1856 #endif
1857 file->ifndef_macro = tok;
1860 c = (define_find(tok) != 0) ^ c;
1861 do_if:
1862 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1863 tcc_error("memory full (ifdef)");
1864 *s1->ifdef_stack_ptr++ = c;
1865 goto test_skip;
1866 case TOK_ELSE:
1867 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1868 tcc_error("#else without matching #if");
1869 if (s1->ifdef_stack_ptr[-1] & 2)
1870 tcc_error("#else after #else");
1871 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1872 goto test_else;
1873 case TOK_ELIF:
1874 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1875 tcc_error("#elif without matching #if");
1876 c = s1->ifdef_stack_ptr[-1];
1877 if (c > 1)
1878 tcc_error("#elif after #else");
1879 /* last #if/#elif expression was true: we skip */
1880 if (c == 1) {
1881 c = 0;
1882 } else {
1883 c = expr_preprocess();
1884 s1->ifdef_stack_ptr[-1] = c;
1886 test_else:
1887 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1888 file->ifndef_macro = 0;
1889 test_skip:
1890 if (!(c & 1)) {
1891 preprocess_skip();
1892 is_bof = 0;
1893 goto redo;
1895 break;
1896 case TOK_ENDIF:
1897 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1898 tcc_error("#endif without matching #if");
1899 s1->ifdef_stack_ptr--;
1900 /* '#ifndef macro' was at the start of file. Now we check if
1901 an '#endif' is exactly at the end of file */
1902 if (file->ifndef_macro &&
1903 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1904 file->ifndef_macro_saved = file->ifndef_macro;
1905 /* need to set to zero to avoid false matches if another
1906 #ifndef at middle of file */
1907 file->ifndef_macro = 0;
1908 while (tok != TOK_LINEFEED)
1909 next_nomacro();
1910 tok_flags |= TOK_FLAG_ENDIF;
1911 goto the_end;
1913 break;
1914 case TOK_PPNUM:
1915 n = strtoul((char*)tokc.str.data, &q, 10);
1916 goto _line_num;
1917 case TOK_LINE:
1918 next();
1919 if (tok != TOK_CINT)
1920 _line_err:
1921 tcc_error("wrong #line format");
1922 n = tokc.i;
1923 _line_num:
1924 next();
1925 if (tok != TOK_LINEFEED) {
1926 if (tok == TOK_STR)
1927 pstrcpy(file->filename, sizeof(file->filename), (char *)tokc.str.data);
1928 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1929 break;
1930 else
1931 goto _line_err;
1932 --n;
1934 if (file->fd > 0)
1935 total_lines += file->line_num - n;
1936 file->line_num = n;
1937 if (s1->do_debug)
1938 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1939 break;
1940 case TOK_ERROR:
1941 case TOK_WARNING:
1942 c = tok;
1943 ch = file->buf_ptr[0];
1944 skip_spaces();
1945 q = buf;
1946 while (ch != '\n' && ch != CH_EOF) {
1947 if ((q - buf) < sizeof(buf) - 1)
1948 *q++ = ch;
1949 if (ch == '\\') {
1950 if (handle_stray_noerror() == 0)
1951 --q;
1952 } else
1953 inp();
1955 *q = '\0';
1956 if (c == TOK_ERROR)
1957 tcc_error("#error %s", buf);
1958 else
1959 tcc_warning("#warning %s", buf);
1960 break;
1961 case TOK_PRAGMA:
1962 pragma_parse(s1);
1963 break;
1964 case TOK_LINEFEED:
1965 goto the_end;
1966 default:
1967 /* ignore gas line comment in an 'S' file. */
1968 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1969 goto ignore;
1970 if (tok == '!' && is_bof)
1971 /* '!' is ignored at beginning to allow C scripts. */
1972 goto ignore;
1973 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1974 ignore:
1975 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
1976 goto the_end;
1978 /* ignore other preprocess commands or #! for C scripts */
1979 while (tok != TOK_LINEFEED)
1980 next_nomacro();
1981 the_end:
1982 parse_flags = saved_parse_flags;
1985 /* evaluate escape codes in a string. */
1986 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1988 int c, n;
1989 const uint8_t *p;
1991 p = buf;
1992 for(;;) {
1993 c = *p;
1994 if (c == '\0')
1995 break;
1996 if (c == '\\') {
1997 p++;
1998 /* escape */
1999 c = *p;
2000 switch(c) {
2001 case '0': case '1': case '2': case '3':
2002 case '4': case '5': case '6': case '7':
2003 /* at most three octal digits */
2004 n = c - '0';
2005 p++;
2006 c = *p;
2007 if (isoct(c)) {
2008 n = n * 8 + c - '0';
2009 p++;
2010 c = *p;
2011 if (isoct(c)) {
2012 n = n * 8 + c - '0';
2013 p++;
2016 c = n;
2017 goto add_char_nonext;
2018 case 'x':
2019 case 'u':
2020 case 'U':
2021 p++;
2022 n = 0;
2023 for(;;) {
2024 c = *p;
2025 if (c >= 'a' && c <= 'f')
2026 c = c - 'a' + 10;
2027 else if (c >= 'A' && c <= 'F')
2028 c = c - 'A' + 10;
2029 else if (isnum(c))
2030 c = c - '0';
2031 else
2032 break;
2033 n = n * 16 + c;
2034 p++;
2036 c = n;
2037 goto add_char_nonext;
2038 case 'a':
2039 c = '\a';
2040 break;
2041 case 'b':
2042 c = '\b';
2043 break;
2044 case 'f':
2045 c = '\f';
2046 break;
2047 case 'n':
2048 c = '\n';
2049 break;
2050 case 'r':
2051 c = '\r';
2052 break;
2053 case 't':
2054 c = '\t';
2055 break;
2056 case 'v':
2057 c = '\v';
2058 break;
2059 case 'e':
2060 if (!gnu_ext)
2061 goto invalid_escape;
2062 c = 27;
2063 break;
2064 case '\'':
2065 case '\"':
2066 case '\\':
2067 case '?':
2068 break;
2069 default:
2070 invalid_escape:
2071 if (c >= '!' && c <= '~')
2072 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2073 else
2074 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2075 break;
2078 p++;
2079 add_char_nonext:
2080 if (!is_long)
2081 cstr_ccat(outstr, c);
2082 else
2083 cstr_wccat(outstr, c);
2085 /* add a trailing '\0' */
2086 if (!is_long)
2087 cstr_ccat(outstr, '\0');
2088 else
2089 cstr_wccat(outstr, '\0');
2092 static void parse_string(const char *s, int len)
2094 uint8_t buf[1000], *p = buf;
2095 int is_long, sep;
2097 if ((is_long = *s == 'L'))
2098 ++s, --len;
2099 sep = *s++;
2100 len -= 2;
2101 if (len >= sizeof buf)
2102 p = tcc_malloc(len + 1);
2103 memcpy(p, s, len);
2104 p[len] = 0;
2106 cstr_reset(&tokcstr);
2107 parse_escape_string(&tokcstr, p, is_long);
2108 if (p != buf)
2109 tcc_free(p);
2111 if (sep == '\'') {
2112 int char_size;
2113 /* XXX: make it portable */
2114 if (!is_long)
2115 char_size = 1;
2116 else
2117 char_size = sizeof(nwchar_t);
2118 if (tokcstr.size <= char_size)
2119 tcc_error("empty character constant");
2120 if (tokcstr.size > 2 * char_size)
2121 tcc_warning("multi-character character constant");
2122 if (!is_long) {
2123 tokc.i = *(int8_t *)tokcstr.data;
2124 tok = TOK_CCHAR;
2125 } else {
2126 tokc.i = *(nwchar_t *)tokcstr.data;
2127 tok = TOK_LCHAR;
2129 } else {
2130 tokc.str.size = tokcstr.size;
2131 tokc.str.data = tokcstr.data;
2132 if (!is_long)
2133 tok = TOK_STR;
2134 else
2135 tok = TOK_LSTR;
2139 /* we use 64 bit numbers */
2140 #define BN_SIZE 2
2142 /* bn = (bn << shift) | or_val */
2143 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2145 int i;
2146 unsigned int v;
2147 for(i=0;i<BN_SIZE;i++) {
2148 v = bn[i];
2149 bn[i] = (v << shift) | or_val;
2150 or_val = v >> (32 - shift);
2154 static void bn_zero(unsigned int *bn)
2156 int i;
2157 for(i=0;i<BN_SIZE;i++) {
2158 bn[i] = 0;
2162 /* parse number in null terminated string 'p' and return it in the
2163 current token */
2164 static void parse_number(const char *p)
2166 int b, t, shift, frac_bits, s, exp_val, ch;
2167 char *q;
2168 unsigned int bn[BN_SIZE];
2169 double d;
2171 /* number */
2172 q = token_buf;
2173 ch = *p++;
2174 t = ch;
2175 ch = *p++;
2176 *q++ = t;
2177 b = 10;
2178 if (t == '.') {
2179 goto float_frac_parse;
2180 } else if (t == '0') {
2181 if (ch == 'x' || ch == 'X') {
2182 q--;
2183 ch = *p++;
2184 b = 16;
2185 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
2186 q--;
2187 ch = *p++;
2188 b = 2;
2191 /* parse all digits. cannot check octal numbers at this stage
2192 because of floating point constants */
2193 while (1) {
2194 if (ch >= 'a' && ch <= 'f')
2195 t = ch - 'a' + 10;
2196 else if (ch >= 'A' && ch <= 'F')
2197 t = ch - 'A' + 10;
2198 else if (isnum(ch))
2199 t = ch - '0';
2200 else
2201 break;
2202 if (t >= b)
2203 break;
2204 if (q >= token_buf + STRING_MAX_SIZE) {
2205 num_too_long:
2206 tcc_error("number too long");
2208 *q++ = ch;
2209 ch = *p++;
2211 if (ch == '.' ||
2212 ((ch == 'e' || ch == 'E') && b == 10) ||
2213 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2214 if (b != 10) {
2215 /* NOTE: strtox should support that for hexa numbers, but
2216 non ISOC99 libcs do not support it, so we prefer to do
2217 it by hand */
2218 /* hexadecimal or binary floats */
2219 /* XXX: handle overflows */
2220 *q = '\0';
2221 if (b == 16)
2222 shift = 4;
2223 else
2224 shift = 1;
2225 bn_zero(bn);
2226 q = token_buf;
2227 while (1) {
2228 t = *q++;
2229 if (t == '\0') {
2230 break;
2231 } else if (t >= 'a') {
2232 t = t - 'a' + 10;
2233 } else if (t >= 'A') {
2234 t = t - 'A' + 10;
2235 } else {
2236 t = t - '0';
2238 bn_lshift(bn, shift, t);
2240 frac_bits = 0;
2241 if (ch == '.') {
2242 ch = *p++;
2243 while (1) {
2244 t = ch;
2245 if (t >= 'a' && t <= 'f') {
2246 t = t - 'a' + 10;
2247 } else if (t >= 'A' && t <= 'F') {
2248 t = t - 'A' + 10;
2249 } else if (t >= '0' && t <= '9') {
2250 t = t - '0';
2251 } else {
2252 break;
2254 if (t >= b)
2255 tcc_error("invalid digit");
2256 bn_lshift(bn, shift, t);
2257 frac_bits += shift;
2258 ch = *p++;
2261 if (ch != 'p' && ch != 'P')
2262 expect("exponent");
2263 ch = *p++;
2264 s = 1;
2265 exp_val = 0;
2266 if (ch == '+') {
2267 ch = *p++;
2268 } else if (ch == '-') {
2269 s = -1;
2270 ch = *p++;
2272 if (ch < '0' || ch > '9')
2273 expect("exponent digits");
2274 while (ch >= '0' && ch <= '9') {
2275 exp_val = exp_val * 10 + ch - '0';
2276 ch = *p++;
2278 exp_val = exp_val * s;
2280 /* now we can generate the number */
2281 /* XXX: should patch directly float number */
2282 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2283 d = ldexp(d, exp_val - frac_bits);
2284 t = toup(ch);
2285 if (t == 'F') {
2286 ch = *p++;
2287 tok = TOK_CFLOAT;
2288 /* float : should handle overflow */
2289 tokc.f = (float)d;
2290 } else if (t == 'L') {
2291 ch = *p++;
2292 #ifdef TCC_TARGET_PE
2293 tok = TOK_CDOUBLE;
2294 tokc.d = d;
2295 #else
2296 tok = TOK_CLDOUBLE;
2297 /* XXX: not large enough */
2298 tokc.ld = (long double)d;
2299 #endif
2300 } else {
2301 tok = TOK_CDOUBLE;
2302 tokc.d = d;
2304 } else {
2305 /* decimal floats */
2306 if (ch == '.') {
2307 if (q >= token_buf + STRING_MAX_SIZE)
2308 goto num_too_long;
2309 *q++ = ch;
2310 ch = *p++;
2311 float_frac_parse:
2312 while (ch >= '0' && ch <= '9') {
2313 if (q >= token_buf + STRING_MAX_SIZE)
2314 goto num_too_long;
2315 *q++ = ch;
2316 ch = *p++;
2319 if (ch == 'e' || ch == 'E') {
2320 if (q >= token_buf + STRING_MAX_SIZE)
2321 goto num_too_long;
2322 *q++ = ch;
2323 ch = *p++;
2324 if (ch == '-' || ch == '+') {
2325 if (q >= token_buf + STRING_MAX_SIZE)
2326 goto num_too_long;
2327 *q++ = ch;
2328 ch = *p++;
2330 if (ch < '0' || ch > '9')
2331 expect("exponent digits");
2332 while (ch >= '0' && ch <= '9') {
2333 if (q >= token_buf + STRING_MAX_SIZE)
2334 goto num_too_long;
2335 *q++ = ch;
2336 ch = *p++;
2339 *q = '\0';
2340 t = toup(ch);
2341 errno = 0;
2342 if (t == 'F') {
2343 ch = *p++;
2344 tok = TOK_CFLOAT;
2345 tokc.f = strtof(token_buf, NULL);
2346 } else if (t == 'L') {
2347 ch = *p++;
2348 #ifdef TCC_TARGET_PE
2349 tok = TOK_CDOUBLE;
2350 tokc.d = strtod(token_buf, NULL);
2351 #else
2352 tok = TOK_CLDOUBLE;
2353 tokc.ld = strtold(token_buf, NULL);
2354 #endif
2355 } else {
2356 tok = TOK_CDOUBLE;
2357 tokc.d = strtod(token_buf, NULL);
2360 } else {
2361 unsigned long long n, n1;
2362 int lcount, ucount, must_64bit;
2363 const char *p1;
2365 /* integer number */
2366 *q = '\0';
2367 q = token_buf;
2368 if (b == 10 && *q == '0') {
2369 b = 8;
2370 q++;
2372 n = 0;
2373 while(1) {
2374 t = *q++;
2375 /* no need for checks except for base 10 / 8 errors */
2376 if (t == '\0')
2377 break;
2378 else if (t >= 'a')
2379 t = t - 'a' + 10;
2380 else if (t >= 'A')
2381 t = t - 'A' + 10;
2382 else
2383 t = t - '0';
2384 if (t >= b)
2385 tcc_error("invalid digit");
2386 n1 = n;
2387 n = n * b + t;
2388 /* detect overflow */
2389 /* XXX: this test is not reliable */
2390 if (n < n1)
2391 tcc_error("integer constant overflow");
2394 /* Determine the characteristics (unsigned and/or 64bit) the type of
2395 the constant must have according to the constant suffix(es) */
2396 lcount = ucount = must_64bit = 0;
2397 p1 = p;
2398 for(;;) {
2399 t = toup(ch);
2400 if (t == 'L') {
2401 if (lcount >= 2)
2402 tcc_error("three 'l's in integer constant");
2403 if (lcount && *(p - 1) != ch)
2404 tcc_error("incorrect integer suffix: %s", p1);
2405 lcount++;
2406 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2407 if (lcount == 2)
2408 #endif
2409 must_64bit = 1;
2410 ch = *p++;
2411 } else if (t == 'U') {
2412 if (ucount >= 1)
2413 tcc_error("two 'u's in integer constant");
2414 ucount++;
2415 ch = *p++;
2416 } else {
2417 break;
2421 /* Whether 64 bits are needed to hold the constant's value */
2422 if (n & 0xffffffff00000000LL || must_64bit) {
2423 tok = TOK_CLLONG;
2424 n1 = n >> 32;
2425 } else {
2426 tok = TOK_CINT;
2427 n1 = n;
2430 /* Whether type must be unsigned to hold the constant's value */
2431 if (ucount || ((n1 >> 31) && (b != 10))) {
2432 if (tok == TOK_CLLONG)
2433 tok = TOK_CULLONG;
2434 else
2435 tok = TOK_CUINT;
2436 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2437 } else if (n1 >> 31) {
2438 if (tok == TOK_CINT)
2439 tok = TOK_CLLONG;
2440 else
2441 tcc_error("integer constant overflow");
2444 tokc.i = n;
2446 if (ch)
2447 tcc_error("invalid number\n");
2451 #define PARSE2(c1, tok1, c2, tok2) \
2452 case c1: \
2453 PEEKC(c, p); \
2454 if (c == c2) { \
2455 p++; \
2456 tok = tok2; \
2457 } else { \
2458 tok = tok1; \
2460 break;
2462 /* return next token without macro substitution */
2463 static inline void next_nomacro1(void)
2465 int t, c, is_long, len;
2466 TokenSym *ts;
2467 uint8_t *p, *p1;
2468 unsigned int h;
2470 p = file->buf_ptr;
2471 redo_no_start:
2472 c = *p;
2473 switch(c) {
2474 case ' ':
2475 case '\t':
2476 tok = c;
2477 p++;
2478 if (parse_flags & PARSE_FLAG_SPACES)
2479 goto keep_tok_flags;
2480 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2481 ++p;
2482 goto redo_no_start;
2483 case '\f':
2484 case '\v':
2485 case '\r':
2486 p++;
2487 goto redo_no_start;
2488 case '\\':
2489 /* first look if it is in fact an end of buffer */
2490 c = handle_stray1(p);
2491 p = file->buf_ptr;
2492 if (c == '\\')
2493 goto parse_simple;
2494 if (c != CH_EOF)
2495 goto redo_no_start;
2497 TCCState *s1 = tcc_state;
2498 if ((parse_flags & PARSE_FLAG_LINEFEED)
2499 && !(tok_flags & TOK_FLAG_EOF)) {
2500 tok_flags |= TOK_FLAG_EOF;
2501 tok = TOK_LINEFEED;
2502 goto keep_tok_flags;
2503 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2504 tok = TOK_EOF;
2505 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2506 tcc_error("missing #endif");
2507 } else if (s1->include_stack_ptr == s1->include_stack) {
2508 /* no include left : end of file. */
2509 tok = TOK_EOF;
2510 } else {
2511 tok_flags &= ~TOK_FLAG_EOF;
2512 /* pop include file */
2514 /* test if previous '#endif' was after a #ifdef at
2515 start of file */
2516 if (tok_flags & TOK_FLAG_ENDIF) {
2517 #ifdef INC_DEBUG
2518 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2519 #endif
2520 search_cached_include(s1, file->filename, 1)
2521 ->ifndef_macro = file->ifndef_macro_saved;
2522 tok_flags &= ~TOK_FLAG_ENDIF;
2525 /* add end of include file debug info */
2526 if (tcc_state->do_debug) {
2527 put_stabd(N_EINCL, 0, 0);
2529 /* pop include stack */
2530 tcc_close();
2531 s1->include_stack_ptr--;
2532 p = file->buf_ptr;
2533 goto redo_no_start;
2536 break;
2538 case '\n':
2539 file->line_num++;
2540 tok_flags |= TOK_FLAG_BOL;
2541 p++;
2542 maybe_newline:
2543 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2544 goto redo_no_start;
2545 tok = TOK_LINEFEED;
2546 goto keep_tok_flags;
2548 case '#':
2549 /* XXX: simplify */
2550 PEEKC(c, p);
2551 if ((tok_flags & TOK_FLAG_BOL) &&
2552 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2553 file->buf_ptr = p;
2554 preprocess(tok_flags & TOK_FLAG_BOF);
2555 p = file->buf_ptr;
2556 goto maybe_newline;
2557 } else {
2558 if (c == '#') {
2559 p++;
2560 tok = TOK_TWOSHARPS;
2561 } else {
2562 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2563 p = parse_line_comment(p - 1);
2564 goto redo_no_start;
2565 } else {
2566 tok = '#';
2570 break;
2572 /* dollar is allowed to start identifiers when not parsing asm */
2573 case '$':
2574 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2575 || (parse_flags & PARSE_FLAG_ASM_FILE))
2576 goto parse_simple;
2578 case 'a': case 'b': case 'c': case 'd':
2579 case 'e': case 'f': case 'g': case 'h':
2580 case 'i': case 'j': case 'k': case 'l':
2581 case 'm': case 'n': case 'o': case 'p':
2582 case 'q': case 'r': case 's': case 't':
2583 case 'u': case 'v': case 'w': case 'x':
2584 case 'y': case 'z':
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':
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 '_':
2593 parse_ident_fast:
2594 p1 = p;
2595 h = TOK_HASH_INIT;
2596 h = TOK_HASH_FUNC(h, c);
2597 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2598 h = TOK_HASH_FUNC(h, c);
2599 len = p - p1;
2600 if (c != '\\') {
2601 TokenSym **pts;
2603 /* fast case : no stray found, so we have the full token
2604 and we have already hashed it */
2605 h &= (TOK_HASH_SIZE - 1);
2606 pts = &hash_ident[h];
2607 for(;;) {
2608 ts = *pts;
2609 if (!ts)
2610 break;
2611 if (ts->len == len && !memcmp(ts->str, p1, len))
2612 goto token_found;
2613 pts = &(ts->hash_next);
2615 ts = tok_alloc_new(pts, (char *) p1, len);
2616 token_found: ;
2617 } else {
2618 /* slower case */
2619 cstr_reset(&tokcstr);
2620 cstr_cat(&tokcstr, (char *) p1, len);
2621 p--;
2622 PEEKC(c, p);
2623 parse_ident_slow:
2624 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2626 cstr_ccat(&tokcstr, c);
2627 PEEKC(c, p);
2629 ts = tok_alloc(tokcstr.data, tokcstr.size);
2631 tok = ts->tok;
2632 break;
2633 case 'L':
2634 t = p[1];
2635 if (t != '\\' && t != '\'' && t != '\"') {
2636 /* fast case */
2637 goto parse_ident_fast;
2638 } else {
2639 PEEKC(c, p);
2640 if (c == '\'' || c == '\"') {
2641 is_long = 1;
2642 goto str_const;
2643 } else {
2644 cstr_reset(&tokcstr);
2645 cstr_ccat(&tokcstr, 'L');
2646 goto parse_ident_slow;
2649 break;
2651 case '0': case '1': case '2': case '3':
2652 case '4': case '5': case '6': case '7':
2653 case '8': case '9':
2654 t = c;
2655 PEEKC(c, p);
2656 /* after the first digit, accept digits, alpha, '.' or sign if
2657 prefixed by 'eEpP' */
2658 parse_num:
2659 cstr_reset(&tokcstr);
2660 for(;;) {
2661 cstr_ccat(&tokcstr, t);
2662 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2663 || c == '.'
2664 || ((c == '+' || c == '-')
2665 && (((t == 'e' || t == 'E')
2666 && !(parse_flags & PARSE_FLAG_ASM_FILE
2667 /* 0xe+1 is 3 tokens in asm */
2668 && ((char*)tokcstr.data)[0] == '0'
2669 && toup(((char*)tokcstr.data)[1]) == 'X'))
2670 || t == 'p' || t == 'P'))))
2671 break;
2672 t = c;
2673 PEEKC(c, p);
2675 /* We add a trailing '\0' to ease parsing */
2676 cstr_ccat(&tokcstr, '\0');
2677 tokc.str.size = tokcstr.size;
2678 tokc.str.data = tokcstr.data;
2679 tok = TOK_PPNUM;
2680 break;
2682 case '.':
2683 /* special dot handling because it can also start a number */
2684 PEEKC(c, p);
2685 if (isnum(c)) {
2686 t = '.';
2687 goto parse_num;
2688 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2689 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2690 *--p = c = '.';
2691 goto parse_ident_fast;
2692 } else if (c == '.') {
2693 PEEKC(c, p);
2694 if (c == '.') {
2695 p++;
2696 tok = TOK_DOTS;
2697 } else {
2698 *--p = '.'; /* may underflow into file->unget[] */
2699 tok = '.';
2701 } else {
2702 tok = '.';
2704 break;
2705 case '\'':
2706 case '\"':
2707 is_long = 0;
2708 str_const:
2709 cstr_reset(&tokcstr);
2710 if (is_long)
2711 cstr_ccat(&tokcstr, 'L');
2712 cstr_ccat(&tokcstr, c);
2713 p = parse_pp_string(p, c, &tokcstr);
2714 cstr_ccat(&tokcstr, c);
2715 cstr_ccat(&tokcstr, '\0');
2716 tokc.str.size = tokcstr.size;
2717 tokc.str.data = tokcstr.data;
2718 tok = TOK_PPSTR;
2719 break;
2721 case '<':
2722 PEEKC(c, p);
2723 if (c == '=') {
2724 p++;
2725 tok = TOK_LE;
2726 } else if (c == '<') {
2727 PEEKC(c, p);
2728 if (c == '=') {
2729 p++;
2730 tok = TOK_A_SHL;
2731 } else {
2732 tok = TOK_SHL;
2734 } else {
2735 tok = TOK_LT;
2737 break;
2738 case '>':
2739 PEEKC(c, p);
2740 if (c == '=') {
2741 p++;
2742 tok = TOK_GE;
2743 } else if (c == '>') {
2744 PEEKC(c, p);
2745 if (c == '=') {
2746 p++;
2747 tok = TOK_A_SAR;
2748 } else {
2749 tok = TOK_SAR;
2751 } else {
2752 tok = TOK_GT;
2754 break;
2756 case '&':
2757 PEEKC(c, p);
2758 if (c == '&') {
2759 p++;
2760 tok = TOK_LAND;
2761 } else if (c == '=') {
2762 p++;
2763 tok = TOK_A_AND;
2764 } else {
2765 tok = '&';
2767 break;
2769 case '|':
2770 PEEKC(c, p);
2771 if (c == '|') {
2772 p++;
2773 tok = TOK_LOR;
2774 } else if (c == '=') {
2775 p++;
2776 tok = TOK_A_OR;
2777 } else {
2778 tok = '|';
2780 break;
2782 case '+':
2783 PEEKC(c, p);
2784 if (c == '+') {
2785 p++;
2786 tok = TOK_INC;
2787 } else if (c == '=') {
2788 p++;
2789 tok = TOK_A_ADD;
2790 } else {
2791 tok = '+';
2793 break;
2795 case '-':
2796 PEEKC(c, p);
2797 if (c == '-') {
2798 p++;
2799 tok = TOK_DEC;
2800 } else if (c == '=') {
2801 p++;
2802 tok = TOK_A_SUB;
2803 } else if (c == '>') {
2804 p++;
2805 tok = TOK_ARROW;
2806 } else {
2807 tok = '-';
2809 break;
2811 PARSE2('!', '!', '=', TOK_NE)
2812 PARSE2('=', '=', '=', TOK_EQ)
2813 PARSE2('*', '*', '=', TOK_A_MUL)
2814 PARSE2('%', '%', '=', TOK_A_MOD)
2815 PARSE2('^', '^', '=', TOK_A_XOR)
2817 /* comments or operator */
2818 case '/':
2819 PEEKC(c, p);
2820 if (c == '*') {
2821 p = parse_comment(p);
2822 /* comments replaced by a blank */
2823 tok = ' ';
2824 goto keep_tok_flags;
2825 } else if (c == '/') {
2826 p = parse_line_comment(p);
2827 tok = ' ';
2828 goto keep_tok_flags;
2829 } else if (c == '=') {
2830 p++;
2831 tok = TOK_A_DIV;
2832 } else {
2833 tok = '/';
2835 break;
2837 /* simple tokens */
2838 case '(':
2839 case ')':
2840 case '[':
2841 case ']':
2842 case '{':
2843 case '}':
2844 case ',':
2845 case ';':
2846 case ':':
2847 case '?':
2848 case '~':
2849 case '@': /* only used in assembler */
2850 parse_simple:
2851 tok = c;
2852 p++;
2853 break;
2854 default:
2855 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2856 goto parse_ident_fast;
2857 if (parse_flags & PARSE_FLAG_ASM_FILE)
2858 goto parse_simple;
2859 tcc_error("unrecognized character \\x%02x", c);
2860 break;
2862 tok_flags = 0;
2863 keep_tok_flags:
2864 file->buf_ptr = p;
2865 #if defined(PARSE_DEBUG)
2866 printf("token = %s\n", get_tok_str(tok, &tokc));
2867 #endif
2870 /* return next token without macro substitution. Can read input from
2871 macro_ptr buffer */
2872 static void next_nomacro_spc(void)
2874 if (macro_ptr) {
2875 redo:
2876 tok = *macro_ptr;
2877 if (tok) {
2878 TOK_GET(&tok, &macro_ptr, &tokc);
2879 if (tok == TOK_LINENUM) {
2880 file->line_num = tokc.i;
2881 goto redo;
2884 } else {
2885 next_nomacro1();
2889 ST_FUNC void next_nomacro(void)
2891 do {
2892 next_nomacro_spc();
2893 } while (tok < 256 && (isidnum_table[tok - CH_EOF] & IS_SPC));
2897 static void macro_subst(
2898 TokenString *tok_str,
2899 Sym **nested_list,
2900 const int *macro_str,
2901 int can_read_stream
2904 /* substitute arguments in replacement lists in macro_str by the values in
2905 args (field d) and return allocated string */
2906 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2908 int t, t0, t1, spc;
2909 const int *st;
2910 Sym *s;
2911 CValue cval;
2912 TokenString str;
2913 CString cstr;
2915 tok_str_new(&str);
2916 t0 = t1 = 0;
2917 while(1) {
2918 TOK_GET(&t, &macro_str, &cval);
2919 if (!t)
2920 break;
2921 if (t == '#') {
2922 /* stringize */
2923 TOK_GET(&t, &macro_str, &cval);
2924 if (!t)
2925 goto bad_stringy;
2926 s = sym_find2(args, t);
2927 if (s) {
2928 cstr_new(&cstr);
2929 cstr_ccat(&cstr, '\"');
2930 st = s->d;
2931 spc = 0;
2932 while (*st) {
2933 TOK_GET(&t, &st, &cval);
2934 if (t != TOK_PLCHLDR
2935 && t != TOK_NOSUBST
2936 && 0 == check_space(t, &spc)) {
2937 const char *s = get_tok_str(t, &cval);
2938 while (*s) {
2939 if (t == TOK_PPSTR && *s != '\'')
2940 add_char(&cstr, *s);
2941 else
2942 cstr_ccat(&cstr, *s);
2943 ++s;
2947 cstr.size -= spc;
2948 cstr_ccat(&cstr, '\"');
2949 cstr_ccat(&cstr, '\0');
2950 #ifdef PP_DEBUG
2951 printf("\nstringize: <%s>\n", (char *)cstr.data);
2952 #endif
2953 /* add string */
2954 cval.str.size = cstr.size;
2955 cval.str.data = cstr.data;
2956 tok_str_add2(&str, TOK_PPSTR, &cval);
2957 cstr_free(&cstr);
2958 } else {
2959 bad_stringy:
2960 expect("macro parameter after '#'");
2962 } else if (t >= TOK_IDENT) {
2963 s = sym_find2(args, t);
2964 if (s) {
2965 int l0 = str.len;
2966 st = s->d;
2967 /* if '##' is present before or after, no arg substitution */
2968 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
2969 /* special case for var arg macros : ## eats the ','
2970 if empty VA_ARGS variable. */
2971 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
2972 if (*st == 0) {
2973 /* suppress ',' '##' */
2974 str.len -= 2;
2975 } else {
2976 /* suppress '##' and add variable */
2977 str.len--;
2978 goto add_var;
2980 } else {
2981 for(;;) {
2982 int t1;
2983 TOK_GET(&t1, &st, &cval);
2984 if (!t1)
2985 break;
2986 tok_str_add2(&str, t1, &cval);
2990 } else {
2991 add_var:
2992 /* NOTE: the stream cannot be read when macro
2993 substituing an argument */
2994 macro_subst(&str, nested_list, st, 0);
2996 if (str.len == l0) /* exanded to empty string */
2997 tok_str_add(&str, TOK_PLCHLDR);
2998 } else {
2999 tok_str_add(&str, t);
3001 } else {
3002 tok_str_add2(&str, t, &cval);
3004 t0 = t1, t1 = t;
3006 tok_str_add(&str, 0);
3007 return str.str;
3010 static char const ab_month_name[12][4] =
3012 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3013 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3016 /* peek or read [ws_str == NULL] next token from function macro call,
3017 walking up macro levels up to the file if necessary */
3018 static int next_argstream(Sym **nested_list, int can_read_stream, TokenString *ws_str)
3020 int t;
3021 const int *p;
3022 Sym *sa;
3024 for (;;) {
3025 if (macro_ptr) {
3026 p = macro_ptr, t = *p;
3027 if (ws_str) {
3028 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3029 tok_str_add(ws_str, t), t = *++p;
3031 if (t == 0 && can_read_stream) {
3032 end_macro();
3033 /* also, end of scope for nested defined symbol */
3034 sa = *nested_list;
3035 while (sa && sa->v == 0)
3036 sa = sa->prev;
3037 if (sa)
3038 sa->v = 0;
3039 continue;
3041 } else {
3042 ch = handle_eob();
3043 if (ws_str) {
3044 while (is_space(ch) || ch == '\n' || ch == '/') {
3045 if (ch == '/') {
3046 int c;
3047 uint8_t *p = file->buf_ptr;
3048 PEEKC(c, p);
3049 if (c == '*') {
3050 p = parse_comment(p);
3051 file->buf_ptr = p - 1;
3052 } else if (c == '/') {
3053 p = parse_line_comment(p);
3054 file->buf_ptr = p - 1;
3055 } else
3056 break;
3057 ch = ' ';
3059 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3060 tok_str_add(ws_str, ch);
3061 cinp();
3064 t = ch;
3067 if (ws_str)
3068 return t;
3069 next_nomacro_spc();
3070 return tok;
3074 /* do macro substitution of current token with macro 's' and add
3075 result to (tok_str,tok_len). 'nested_list' is the list of all
3076 macros we got inside to avoid recursing. Return non zero if no
3077 substitution needs to be done */
3078 static int macro_subst_tok(
3079 TokenString *tok_str,
3080 Sym **nested_list,
3081 Sym *s,
3082 int can_read_stream)
3084 Sym *args, *sa, *sa1;
3085 int parlevel, *mstr, t, t1, spc;
3086 TokenString str;
3087 char *cstrval;
3088 CValue cval;
3089 CString cstr;
3090 char buf[32];
3092 /* if symbol is a macro, prepare substitution */
3093 /* special macros */
3094 if (tok == TOK___LINE__) {
3095 snprintf(buf, sizeof(buf), "%d", file->line_num);
3096 cstrval = buf;
3097 t1 = TOK_PPNUM;
3098 goto add_cstr1;
3099 } else if (tok == TOK___FILE__) {
3100 cstrval = file->filename;
3101 goto add_cstr;
3102 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3103 time_t ti;
3104 struct tm *tm;
3106 time(&ti);
3107 tm = localtime(&ti);
3108 if (tok == TOK___DATE__) {
3109 snprintf(buf, sizeof(buf), "%s %2d %d",
3110 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3111 } else {
3112 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3113 tm->tm_hour, tm->tm_min, tm->tm_sec);
3115 cstrval = buf;
3116 add_cstr:
3117 t1 = TOK_STR;
3118 add_cstr1:
3119 cstr_new(&cstr);
3120 cstr_cat(&cstr, cstrval, 0);
3121 cval.str.size = cstr.size;
3122 cval.str.data = cstr.data;
3123 tok_str_add2(tok_str, t1, &cval);
3124 cstr_free(&cstr);
3125 } else {
3126 int saved_parse_flags = parse_flags;
3128 mstr = s->d;
3129 if (s->type.t == MACRO_FUNC) {
3130 /* whitespace between macro name and argument list */
3131 TokenString ws_str;
3132 tok_str_new(&ws_str);
3134 spc = 0;
3135 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3136 | PARSE_FLAG_ACCEPT_STRAYS;
3138 /* get next token from argument stream */
3139 t = next_argstream(nested_list, can_read_stream, &ws_str);
3140 if (t != '(') {
3141 /* not a macro substitution after all, restore the
3142 * macro token plus all whitespace we've read.
3143 * whitespace is intentionally not merged to preserve
3144 * newlines. */
3145 parse_flags = saved_parse_flags;
3146 tok_str_add(tok_str, tok);
3147 if (parse_flags & PARSE_FLAG_SPACES) {
3148 int i;
3149 for (i = 0; i < ws_str.len; i++)
3150 tok_str_add(tok_str, ws_str.str[i]);
3152 tok_str_free_str(ws_str.str);
3153 return 0;
3154 } else {
3155 tok_str_free_str(ws_str.str);
3157 do {
3158 next_nomacro(); /* eat '(' */
3159 } while (tok == TOK_PLCHLDR);
3161 /* argument macro */
3162 args = NULL;
3163 sa = s->next;
3164 /* NOTE: empty args are allowed, except if no args */
3165 for(;;) {
3166 do {
3167 next_argstream(nested_list, can_read_stream, NULL);
3168 } while (is_space(tok) || TOK_LINEFEED == tok);
3169 empty_arg:
3170 /* handle '()' case */
3171 if (!args && !sa && tok == ')')
3172 break;
3173 if (!sa)
3174 tcc_error("macro '%s' used with too many args",
3175 get_tok_str(s->v, 0));
3176 tok_str_new(&str);
3177 parlevel = spc = 0;
3178 /* NOTE: non zero sa->t indicates VA_ARGS */
3179 while ((parlevel > 0 ||
3180 (tok != ')' &&
3181 (tok != ',' || sa->type.t)))) {
3182 if (tok == TOK_EOF || tok == 0)
3183 break;
3184 if (tok == '(')
3185 parlevel++;
3186 else if (tok == ')')
3187 parlevel--;
3188 if (tok == TOK_LINEFEED)
3189 tok = ' ';
3190 if (!check_space(tok, &spc))
3191 tok_str_add2(&str, tok, &tokc);
3192 next_argstream(nested_list, can_read_stream, NULL);
3194 if (parlevel)
3195 expect(")");
3196 str.len -= spc;
3197 tok_str_add(&str, 0);
3198 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3199 sa1->d = str.str;
3200 sa = sa->next;
3201 if (tok == ')') {
3202 /* special case for gcc var args: add an empty
3203 var arg argument if it is omitted */
3204 if (sa && sa->type.t && gnu_ext)
3205 goto empty_arg;
3206 break;
3208 if (tok != ',')
3209 expect(",");
3211 if (sa) {
3212 tcc_error("macro '%s' used with too few args",
3213 get_tok_str(s->v, 0));
3216 parse_flags = saved_parse_flags;
3218 /* now subst each arg */
3219 mstr = macro_arg_subst(nested_list, mstr, args);
3220 /* free memory */
3221 sa = args;
3222 while (sa) {
3223 sa1 = sa->prev;
3224 tok_str_free_str(sa->d);
3225 sym_free(sa);
3226 sa = sa1;
3230 sym_push2(nested_list, s->v, 0, 0);
3231 parse_flags = saved_parse_flags;
3232 macro_subst(tok_str, nested_list, mstr, can_read_stream | 2);
3234 /* pop nested defined symbol */
3235 sa1 = *nested_list;
3236 *nested_list = sa1->prev;
3237 sym_free(sa1);
3238 if (mstr != s->d)
3239 tok_str_free_str(mstr);
3241 return 0;
3244 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3246 CString cstr;
3247 int n, ret = 1;
3249 cstr_new(&cstr);
3250 if (t1 != TOK_PLCHLDR)
3251 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3252 n = cstr.size;
3253 if (t2 != TOK_PLCHLDR)
3254 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3255 cstr_ccat(&cstr, '\0');
3257 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3258 memcpy(file->buffer, cstr.data, cstr.size);
3259 for (;;) {
3260 next_nomacro1();
3261 if (0 == *file->buf_ptr)
3262 break;
3263 if (is_space(tok))
3264 continue;
3265 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3266 " preprocessing token", n, cstr.data, (char*)cstr.data + n);
3267 ret = 0;
3268 break;
3270 tcc_close();
3271 //printf("paste <%s>\n", (char*)cstr.data);
3272 cstr_free(&cstr);
3273 return ret;
3276 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3277 return the resulting string (which must be freed). */
3278 static inline int *macro_twosharps(const int *ptr0)
3280 int t;
3281 CValue cval;
3282 TokenString macro_str1;
3283 int start_of_nosubsts = -1;
3284 const int *ptr;
3286 /* we search the first '##' */
3287 for (ptr = ptr0;;) {
3288 TOK_GET(&t, &ptr, &cval);
3289 if (t == TOK_PPJOIN)
3290 break;
3291 if (t == 0)
3292 return NULL;
3295 tok_str_new(&macro_str1);
3297 //tok_print(" $$$", ptr0);
3298 for (ptr = ptr0;;) {
3299 TOK_GET(&t, &ptr, &cval);
3300 if (t == 0)
3301 break;
3302 if (t == TOK_PPJOIN)
3303 continue;
3304 while (*ptr == TOK_PPJOIN) {
3305 int t1; CValue cv1;
3306 /* given 'a##b', remove nosubsts preceding 'a' */
3307 if (start_of_nosubsts >= 0)
3308 macro_str1.len = start_of_nosubsts;
3309 /* given 'a##b', remove nosubsts preceding 'b' */
3310 while ((t1 = *++ptr) == TOK_NOSUBST)
3312 if (t1 && t1 != TOK_PPJOIN) {
3313 TOK_GET(&t1, &ptr, &cv1);
3314 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3315 if (paste_tokens(t, &cval, t1, &cv1)) {
3316 t = tok, cval = tokc;
3317 } else {
3318 tok_str_add2(&macro_str1, t, &cval);
3319 t = t1, cval = cv1;
3324 if (t == TOK_NOSUBST) {
3325 if (start_of_nosubsts < 0)
3326 start_of_nosubsts = macro_str1.len;
3327 } else {
3328 start_of_nosubsts = -1;
3330 tok_str_add2(&macro_str1, t, &cval);
3332 tok_str_add(&macro_str1, 0);
3333 //tok_print(" ###", macro_str1.str);
3334 return macro_str1.str;
3337 /* do macro substitution of macro_str and add result to
3338 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3339 inside to avoid recursing. */
3340 static void macro_subst(
3341 TokenString *tok_str,
3342 Sym **nested_list,
3343 const int *macro_str,
3344 int can_read_stream
3347 Sym *s;
3348 const int *ptr;
3349 int t, spc, nosubst;
3350 CValue cval;
3351 int *macro_str1 = NULL;
3353 /* first scan for '##' operator handling */
3354 ptr = macro_str;
3355 spc = nosubst = 0;
3357 /* first scan for '##' operator handling */
3358 if (can_read_stream) {
3359 macro_str1 = macro_twosharps(ptr);
3360 if (macro_str1)
3361 ptr = macro_str1;
3364 while (1) {
3365 TOK_GET(&t, &ptr, &cval);
3366 if (t == 0)
3367 break;
3369 if (t >= TOK_IDENT && 0 == nosubst) {
3370 s = define_find(t);
3371 if (s == NULL)
3372 goto no_subst;
3374 /* if nested substitution, do nothing */
3375 if (sym_find2(*nested_list, t)) {
3376 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3377 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3378 goto no_subst;
3382 TokenString str;
3383 str.str = (int*)ptr;
3384 begin_macro(&str, 2);
3386 tok = t;
3387 macro_subst_tok(tok_str, nested_list, s, can_read_stream);
3389 if (str.alloc == 3) {
3390 /* already finished by reading function macro arguments */
3391 break;
3394 ptr = macro_ptr;
3395 end_macro ();
3398 spc = (tok_str->len &&
3399 is_space(tok_last(tok_str->str,
3400 tok_str->str + tok_str->len)));
3402 } else {
3404 if (t == '\\' && !(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3405 tcc_error("stray '\\' in program");
3407 no_subst:
3408 if (!check_space(t, &spc))
3409 tok_str_add2(tok_str, t, &cval);
3410 nosubst = 0;
3411 if (t == TOK_NOSUBST)
3412 nosubst = 1;
3415 if (macro_str1)
3416 tok_str_free_str(macro_str1);
3420 /* return next token with macro substitution */
3421 ST_FUNC void next(void)
3423 redo:
3424 if (parse_flags & PARSE_FLAG_SPACES)
3425 next_nomacro_spc();
3426 else
3427 next_nomacro();
3429 if (macro_ptr) {
3430 if (tok == TOK_NOSUBST || tok == TOK_PLCHLDR) {
3431 /* discard preprocessor markers */
3432 goto redo;
3433 } else if (tok == 0) {
3434 /* end of macro or unget token string */
3435 end_macro();
3436 goto redo;
3438 } else if (tok >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3439 Sym *s;
3440 /* if reading from file, try to substitute macros */
3441 s = define_find(tok);
3442 if (s) {
3443 Sym *nested_list = NULL;
3444 tokstr_buf.len = 0;
3445 macro_subst_tok(&tokstr_buf, &nested_list, s, 1);
3446 tok_str_add(&tokstr_buf, 0);
3447 begin_macro(&tokstr_buf, 2);
3448 goto redo;
3451 /* convert preprocessor tokens into C tokens */
3452 if (tok == TOK_PPNUM) {
3453 if (parse_flags & PARSE_FLAG_TOK_NUM)
3454 parse_number((char *)tokc.str.data);
3455 } else if (tok == TOK_PPSTR) {
3456 if (parse_flags & PARSE_FLAG_TOK_STR)
3457 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3461 /* push back current token and set current token to 'last_tok'. Only
3462 identifier case handled for labels. */
3463 ST_INLN void unget_tok(int last_tok)
3466 TokenString *str = tok_str_alloc();
3467 tok_str_add2(str, tok, &tokc);
3468 tok_str_add(str, 0);
3469 begin_macro(str, 1);
3470 tok = last_tok;
3473 ST_FUNC void preprocess_start(TCCState *s1)
3475 char *buf;
3477 s1->include_stack_ptr = s1->include_stack;
3478 s1->ifdef_stack_ptr = s1->ifdef_stack;
3479 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3480 pp_once++;
3481 pvtop = vtop = vstack - 1;
3482 s1->pack_stack[0] = 0;
3483 s1->pack_stack_ptr = s1->pack_stack;
3485 set_idnum('$', s1->dollars_in_identifiers ? IS_ID : 0);
3486 set_idnum('.', (parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0);
3488 buf = tcc_malloc(3 + strlen(file->filename));
3489 sprintf(buf, "\"%s\"", file->filename);
3490 tcc_define_symbol(s1, "__BASE_FILE__", buf);
3491 tcc_free(buf);
3493 if (s1->nb_cmd_include_files) {
3494 CString cstr;
3495 int i;
3496 cstr_new(&cstr);
3497 for (i = 0; i < s1->nb_cmd_include_files; i++) {
3498 cstr_cat(&cstr, "#include \"", -1);
3499 cstr_cat(&cstr, s1->cmd_include_files[i], -1);
3500 cstr_cat(&cstr, "\"\n", -1);
3502 *s1->include_stack_ptr++ = file;
3503 tcc_open_bf(s1, "<command line>", cstr.size);
3504 memcpy(file->buffer, cstr.data, cstr.size);
3505 cstr_free(&cstr);
3509 ST_FUNC void tccpp_new(TCCState *s)
3511 int i, c;
3512 const char *p, *r;
3514 /* might be used in error() before preprocess_start() */
3515 s->include_stack_ptr = s->include_stack;
3517 /* init isid table */
3518 for(i = CH_EOF; i<128; i++)
3519 set_idnum(i,
3520 is_space(i) ? IS_SPC
3521 : isid(i) ? IS_ID
3522 : isnum(i) ? IS_NUM
3523 : 0);
3525 for(i = 128; i<256; i++)
3526 set_idnum(i, IS_ID);
3528 /* init allocators */
3529 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3530 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3531 tal_new(&cstr_alloc, CSTR_TAL_LIMIT, CSTR_TAL_SIZE);
3533 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3534 cstr_new(&cstr_buf);
3535 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3536 tok_str_new(&tokstr_buf);
3537 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3539 tok_ident = TOK_IDENT;
3540 p = tcc_keywords;
3541 while (*p) {
3542 r = p;
3543 for(;;) {
3544 c = *r++;
3545 if (c == '\0')
3546 break;
3548 tok_alloc(p, r - p - 1);
3549 p = r;
3553 ST_FUNC void tccpp_delete(TCCState *s)
3555 int i, n;
3557 /* free -D and compiler defines */
3558 free_defines(NULL);
3560 /* cleanup from error/setjmp */
3561 while (macro_stack)
3562 end_macro();
3563 macro_ptr = NULL;
3565 while (file)
3566 tcc_close();
3568 /* free tokens */
3569 n = tok_ident - TOK_IDENT;
3570 for(i = 0; i < n; i++)
3571 tal_free(toksym_alloc, table_ident[i]);
3572 tcc_free(table_ident);
3573 table_ident = NULL;
3575 /* free static buffers */
3576 cstr_free(&tokcstr);
3577 cstr_free(&cstr_buf);
3578 cstr_free(&macro_equal_buf);
3579 tok_str_free_str(tokstr_buf.str);
3581 /* free allocators */
3582 tal_delete(toksym_alloc);
3583 toksym_alloc = NULL;
3584 tal_delete(tokstr_alloc);
3585 tokstr_alloc = NULL;
3586 tal_delete(cstr_alloc);
3587 cstr_alloc = NULL;
3590 /* ------------------------------------------------------------------------- */
3591 /* tcc -E [-P[1]] [-dD} support */
3593 static void tok_print(const char *msg, const int *str)
3595 FILE *fp;
3596 int t;
3597 CValue cval;
3599 fp = tcc_state->ppfp;
3600 if (!fp || !tcc_state->dflag)
3601 fp = stdout;
3603 fprintf(fp, "%s ", msg);
3604 while (str) {
3605 TOK_GET(&t, &str, &cval);
3606 if (!t)
3607 break;
3608 fprintf(fp,"%s", get_tok_str(t, &cval));
3610 fprintf(fp, "\n");
3613 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3615 int d = f->line_num - f->line_ref;
3617 if (s1->dflag & 4)
3618 return;
3620 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3622 } else if (level == 0 && f->line_ref && d < 8) {
3623 while (d > 0)
3624 fputs("\n", s1->ppfp), --d;
3625 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3626 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3627 } else {
3628 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3629 level > 0 ? " 1" : level < 0 ? " 2" : "");
3631 f->line_ref = f->line_num;
3634 static void define_print(TCCState *s1, int v)
3636 FILE *fp;
3637 Sym *s;
3639 s = define_find(v);
3640 if (NULL == s || NULL == s->d)
3641 return;
3643 fp = s1->ppfp;
3644 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3645 if (s->type.t == MACRO_FUNC) {
3646 Sym *a = s->next;
3647 fprintf(fp,"(");
3648 if (a)
3649 for (;;) {
3650 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3651 if (!(a = a->next))
3652 break;
3653 fprintf(fp,",");
3655 fprintf(fp,")");
3657 tok_print("", s->d);
3660 static void pp_debug_defines(TCCState *s1)
3662 int v, t;
3663 const char *vs;
3664 FILE *fp;
3666 t = pp_debug_tok;
3667 if (t == 0)
3668 return;
3670 file->line_num--;
3671 pp_line(s1, file, 0);
3672 file->line_ref = ++file->line_num;
3674 fp = s1->ppfp;
3675 v = pp_debug_symv;
3676 vs = get_tok_str(v, NULL);
3677 if (t == TOK_DEFINE) {
3678 define_print(s1, v);
3679 } else if (t == TOK_UNDEF) {
3680 fprintf(fp, "#undef %s\n", vs);
3681 } else if (t == TOK_push_macro) {
3682 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3683 } else if (t == TOK_pop_macro) {
3684 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3686 pp_debug_tok = 0;
3689 static void pp_debug_builtins(TCCState *s1)
3691 int v;
3692 for (v = TOK_IDENT; v < tok_ident; ++v)
3693 define_print(s1, v);
3696 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3697 static int pp_need_space(int a, int b)
3699 return 'E' == a ? '+' == b || '-' == b
3700 : '+' == a ? TOK_INC == b || '+' == b
3701 : '-' == a ? TOK_DEC == b || '-' == b
3702 : a >= TOK_IDENT ? b >= TOK_IDENT
3703 : 0;
3706 /* maybe hex like 0x1e */
3707 static int pp_check_he0xE(int t, const char *p)
3709 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3710 return 'E';
3711 return t;
3714 /* Preprocess the current file */
3715 ST_FUNC int tcc_preprocess(TCCState *s1)
3717 BufferedFile **iptr;
3718 int token_seen, spcs, level;
3719 const char *p;
3720 Sym *define_start;
3722 define_start = define_stack;
3723 preprocess_start(s1);
3725 ch = file->buf_ptr[0];
3726 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3727 parse_flags = PARSE_FLAG_PREPROCESS
3728 | (parse_flags & PARSE_FLAG_ASM_FILE)
3729 | PARSE_FLAG_LINEFEED
3730 | PARSE_FLAG_SPACES
3731 | PARSE_FLAG_ACCEPT_STRAYS
3734 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3735 capability to compile and run itself, provided all numbers are
3736 given as decimals. tcc -E -P10 will do. */
3737 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3738 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3740 #ifdef PP_BENCH
3741 /* for PP benchmarks */
3742 do next(); while (tok != TOK_EOF);
3743 free_defines(define_start);
3744 return 0;
3745 #endif
3747 if (s1->dflag & 1) {
3748 pp_debug_builtins(s1);
3749 s1->dflag &= ~1;
3752 token_seen = TOK_LINEFEED, spcs = 0;
3753 pp_line(s1, file, 0);
3755 for (;;) {
3756 iptr = s1->include_stack_ptr;
3757 next();
3758 if (tok == TOK_EOF)
3759 break;
3760 level = s1->include_stack_ptr - iptr;
3761 if (level) {
3762 if (level > 0)
3763 pp_line(s1, *iptr, 0);
3764 pp_line(s1, file, level);
3767 if (s1->dflag) {
3768 pp_debug_defines(s1);
3769 if (s1->dflag & 4)
3770 continue;
3773 if (token_seen == TOK_LINEFEED) {
3774 if (tok == ' ') {
3775 ++spcs;
3776 continue;
3778 if (tok == TOK_LINEFEED) {
3779 spcs = 0;
3780 continue;
3782 pp_line(s1, file, 0);
3783 } else if (tok == TOK_LINEFEED) {
3784 ++file->line_ref;
3785 } else {
3786 spcs = pp_need_space(token_seen, tok);
3789 while (spcs)
3790 fputs(" ", s1->ppfp), --spcs;
3791 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
3792 token_seen = pp_check_he0xE(tok, p);;
3794 /* reset define stack, but keep -D and built-ins */
3795 free_defines(define_start);
3796 return 0;
3799 /* ------------------------------------------------------------------------- */