cross-compilers: allow individual configuration
[tinycc.git] / tccpp.c
blobbdf2815cd8858fabb4afa07e82113f36c5466dbd
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 /* return the number of additional 'ints' necessary to store the
1025 token */
1026 static inline int tok_size(const int *p)
1028 switch(*p) {
1029 /* 4 bytes */
1030 case TOK_CINT:
1031 case TOK_CUINT:
1032 case TOK_CCHAR:
1033 case TOK_LCHAR:
1034 case TOK_CFLOAT:
1035 case TOK_LINENUM:
1036 return 1 + 1;
1037 case TOK_STR:
1038 case TOK_LSTR:
1039 case TOK_PPNUM:
1040 case TOK_PPSTR:
1041 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1042 case TOK_CDOUBLE:
1043 case TOK_CLLONG:
1044 case TOK_CULLONG:
1045 return 1 + 2;
1046 case TOK_CLDOUBLE:
1047 return 1 + LDOUBLE_SIZE / 4;
1048 default:
1049 return 1 + 0;
1053 /* token string handling */
1055 ST_INLN void tok_str_new(TokenString *s)
1057 s->str = NULL;
1058 s->len = 0;
1059 s->allocated_len = 0;
1060 s->last_line_num = -1;
1063 ST_FUNC TokenString *tok_str_alloc(void)
1065 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1066 tok_str_new(str);
1067 return str;
1070 ST_FUNC int *tok_str_dup(TokenString *s)
1072 int *str;
1074 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1075 memcpy(str, s->str, s->len * sizeof(int));
1076 return str;
1079 ST_FUNC void tok_str_free_str(int *str)
1081 tal_free(tokstr_alloc, str);
1084 ST_FUNC void tok_str_free(TokenString *str)
1086 tok_str_free_str(str->str);
1087 tal_free(tokstr_alloc, str);
1090 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1092 int *str, size;
1094 size = s->allocated_len;
1095 if (size < 16)
1096 size = 16;
1097 while (size < new_size)
1098 size = size * 2;
1099 if (size > s->allocated_len) {
1100 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1101 s->allocated_len = size;
1102 s->str = str;
1104 return s->str;
1107 ST_FUNC void tok_str_add(TokenString *s, int t)
1109 int len, *str;
1111 len = s->len;
1112 str = s->str;
1113 if (len >= s->allocated_len)
1114 str = tok_str_realloc(s, len + 1);
1115 str[len++] = t;
1116 s->len = len;
1119 ST_FUNC void begin_macro(TokenString *str, int alloc)
1121 str->alloc = alloc;
1122 str->prev = macro_stack;
1123 str->prev_ptr = macro_ptr;
1124 macro_ptr = str->str;
1125 macro_stack = str;
1128 ST_FUNC void end_macro(void)
1130 TokenString *str = macro_stack;
1131 macro_stack = str->prev;
1132 macro_ptr = str->prev_ptr;
1133 if (str->alloc == 2) {
1134 str->alloc = 3; /* just mark as finished */
1135 } else {
1136 tok_str_free(str);
1140 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1142 int len, *str;
1144 len = s->len;
1145 str = s->str;
1147 /* allocate space for worst case */
1148 if (len + TOK_MAX_SIZE >= s->allocated_len)
1149 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1150 str[len++] = t;
1151 switch(t) {
1152 case TOK_CINT:
1153 case TOK_CUINT:
1154 case TOK_CCHAR:
1155 case TOK_LCHAR:
1156 case TOK_CFLOAT:
1157 case TOK_LINENUM:
1158 str[len++] = cv->tab[0];
1159 break;
1160 case TOK_PPNUM:
1161 case TOK_PPSTR:
1162 case TOK_STR:
1163 case TOK_LSTR:
1165 /* Insert the string into the int array. */
1166 size_t nb_words =
1167 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1168 if (len + nb_words >= s->allocated_len)
1169 str = tok_str_realloc(s, len + nb_words + 1);
1170 str[len] = cv->str.size;
1171 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1172 len += nb_words;
1174 break;
1175 case TOK_CDOUBLE:
1176 case TOK_CLLONG:
1177 case TOK_CULLONG:
1178 #if LDOUBLE_SIZE == 8
1179 case TOK_CLDOUBLE:
1180 #endif
1181 str[len++] = cv->tab[0];
1182 str[len++] = cv->tab[1];
1183 break;
1184 #if LDOUBLE_SIZE == 12
1185 case TOK_CLDOUBLE:
1186 str[len++] = cv->tab[0];
1187 str[len++] = cv->tab[1];
1188 str[len++] = cv->tab[2];
1189 #elif LDOUBLE_SIZE == 16
1190 case TOK_CLDOUBLE:
1191 str[len++] = cv->tab[0];
1192 str[len++] = cv->tab[1];
1193 str[len++] = cv->tab[2];
1194 str[len++] = cv->tab[3];
1195 #elif LDOUBLE_SIZE != 8
1196 #error add long double size support
1197 #endif
1198 break;
1199 default:
1200 break;
1202 s->len = len;
1205 /* add the current parse token in token string 's' */
1206 ST_FUNC void tok_str_add_tok(TokenString *s)
1208 CValue cval;
1210 /* save line number info */
1211 if (file->line_num != s->last_line_num) {
1212 s->last_line_num = file->line_num;
1213 cval.i = s->last_line_num;
1214 tok_str_add2(s, TOK_LINENUM, &cval);
1216 tok_str_add2(s, tok, &tokc);
1219 /* get a token from an integer array and increment pointer
1220 accordingly. we code it as a macro to avoid pointer aliasing. */
1221 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
1223 const int *p = *pp;
1224 int n, *tab;
1226 tab = cv->tab;
1227 switch(*t = *p++) {
1228 case TOK_CINT:
1229 case TOK_CUINT:
1230 case TOK_CCHAR:
1231 case TOK_LCHAR:
1232 case TOK_CFLOAT:
1233 case TOK_LINENUM:
1234 tab[0] = *p++;
1235 break;
1236 case TOK_STR:
1237 case TOK_LSTR:
1238 case TOK_PPNUM:
1239 case TOK_PPSTR:
1240 cv->str.size = *p++;
1241 cv->str.data = p;
1242 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1243 break;
1244 case TOK_CDOUBLE:
1245 case TOK_CLLONG:
1246 case TOK_CULLONG:
1247 n = 2;
1248 goto copy;
1249 case TOK_CLDOUBLE:
1250 #if LDOUBLE_SIZE == 16
1251 n = 4;
1252 #elif LDOUBLE_SIZE == 12
1253 n = 3;
1254 #elif LDOUBLE_SIZE == 8
1255 n = 2;
1256 #else
1257 # error add long double size support
1258 #endif
1259 copy:
1261 *tab++ = *p++;
1262 while (--n);
1263 break;
1264 default:
1265 break;
1267 *pp = p;
1270 /* Calling this function is expensive, but it is not possible
1271 to read a token string backwards. */
1272 static int tok_last(const int *str0, const int *str1)
1274 const int *str = str0;
1275 int tok = 0;
1276 CValue cval;
1278 while (str < str1)
1279 TOK_GET(&tok, &str, &cval);
1280 return tok;
1283 static int macro_is_equal(const int *a, const int *b)
1285 CValue cv;
1286 int t;
1288 if (!a || !b)
1289 return 1;
1291 while (*a && *b) {
1292 /* first time preallocate macro_equal_buf, next time only reset position to start */
1293 cstr_reset(&macro_equal_buf);
1294 TOK_GET(&t, &a, &cv);
1295 cstr_cat(&macro_equal_buf, get_tok_str(t, &cv), 0);
1296 TOK_GET(&t, &b, &cv);
1297 if (strcmp(macro_equal_buf.data, get_tok_str(t, &cv)))
1298 return 0;
1300 return !(*a || *b);
1303 /* defines handling */
1304 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1306 Sym *s, *o;
1308 o = define_find(v);
1309 s = sym_push2(&define_stack, v, macro_type, 0);
1310 s->d = str;
1311 s->next = first_arg;
1312 table_ident[v - TOK_IDENT]->sym_define = s;
1314 if (o && !macro_is_equal(o->d, s->d))
1315 tcc_warning("%s redefined", get_tok_str(v, NULL));
1318 /* undefined a define symbol. Its name is just set to zero */
1319 ST_FUNC void define_undef(Sym *s)
1321 int v = s->v;
1322 if (v >= TOK_IDENT && v < tok_ident)
1323 table_ident[v - TOK_IDENT]->sym_define = NULL;
1326 ST_INLN Sym *define_find(int v)
1328 v -= TOK_IDENT;
1329 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1330 return NULL;
1331 return table_ident[v]->sym_define;
1334 /* free define stack until top reaches 'b' */
1335 ST_FUNC void free_defines(Sym *b)
1337 while (define_stack != b) {
1338 Sym *top = define_stack;
1339 define_stack = top->prev;
1340 tok_str_free_str(top->d);
1341 define_undef(top);
1342 sym_free(top);
1345 /* restore remaining (-D or predefined) symbols if they were
1346 #undef'd in the file */
1347 while (b) {
1348 int v = b->v;
1349 if (v >= TOK_IDENT && v < tok_ident) {
1350 Sym **d = &table_ident[v - TOK_IDENT]->sym_define;
1351 if (!*d)
1352 *d = b;
1354 b = b->prev;
1358 /* label lookup */
1359 ST_FUNC Sym *label_find(int v)
1361 v -= TOK_IDENT;
1362 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1363 return NULL;
1364 return table_ident[v]->sym_label;
1367 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1369 Sym *s, **ps;
1370 s = sym_push2(ptop, v, 0, 0);
1371 s->r = flags;
1372 ps = &table_ident[v - TOK_IDENT]->sym_label;
1373 if (ptop == &global_label_stack) {
1374 /* modify the top most local identifier, so that
1375 sym_identifier will point to 's' when popped */
1376 while (*ps != NULL)
1377 ps = &(*ps)->prev_tok;
1379 s->prev_tok = *ps;
1380 *ps = s;
1381 return s;
1384 /* pop labels until element last is reached. Look if any labels are
1385 undefined. Define symbols if '&&label' was used. */
1386 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1388 Sym *s, *s1;
1389 for(s = *ptop; s != slast; s = s1) {
1390 s1 = s->prev;
1391 if (s->r == LABEL_DECLARED) {
1392 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1393 } else if (s->r == LABEL_FORWARD) {
1394 tcc_error("label '%s' used but not defined",
1395 get_tok_str(s->v, NULL));
1396 } else {
1397 if (s->c) {
1398 /* define corresponding symbol. A size of
1399 1 is put. */
1400 put_extern_sym(s, cur_text_section, s->jnext, 1);
1403 /* remove label */
1404 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1405 sym_free(s);
1407 *ptop = slast;
1410 /* eval an expression for #if/#elif */
1411 static int expr_preprocess(void)
1413 int c, t;
1414 TokenString *str;
1416 str = tok_str_alloc();
1417 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1418 next(); /* do macro subst */
1419 if (tok == TOK_DEFINED) {
1420 next_nomacro();
1421 t = tok;
1422 if (t == '(')
1423 next_nomacro();
1424 c = define_find(tok) != 0;
1425 if (t == '(')
1426 next_nomacro();
1427 tok = TOK_CINT;
1428 tokc.i = c;
1429 } else if (tok >= TOK_IDENT) {
1430 /* if undefined macro */
1431 tok = TOK_CINT;
1432 tokc.i = 0;
1434 tok_str_add_tok(str);
1436 tok_str_add(str, -1); /* simulate end of file */
1437 tok_str_add(str, 0);
1438 /* now evaluate C constant expression */
1439 begin_macro(str, 1);
1440 next();
1441 c = expr_const();
1442 end_macro();
1443 return c != 0;
1447 /* parse after #define */
1448 ST_FUNC void parse_define(void)
1450 Sym *s, *first, **ps;
1451 int v, t, varg, is_vaargs, spc;
1452 int saved_parse_flags = parse_flags;
1454 v = tok;
1455 if (v < TOK_IDENT)
1456 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1457 /* XXX: should check if same macro (ANSI) */
1458 first = NULL;
1459 t = MACRO_OBJ;
1460 /* We have to parse the whole define as if not in asm mode, in particular
1461 no line comment with '#' must be ignored. Also for function
1462 macros the argument list must be parsed without '.' being an ID
1463 character. */
1464 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1465 /* '(' must be just after macro definition for MACRO_FUNC */
1466 next_nomacro_spc();
1467 if (tok == '(') {
1468 set_idnum('.', 0);
1469 next_nomacro();
1470 ps = &first;
1471 if (tok != ')') for (;;) {
1472 varg = tok;
1473 next_nomacro();
1474 is_vaargs = 0;
1475 if (varg == TOK_DOTS) {
1476 varg = TOK___VA_ARGS__;
1477 is_vaargs = 1;
1478 } else if (tok == TOK_DOTS && gnu_ext) {
1479 is_vaargs = 1;
1480 next_nomacro();
1482 if (varg < TOK_IDENT)
1483 bad_list:
1484 tcc_error("bad macro parameter list");
1485 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1486 *ps = s;
1487 ps = &s->next;
1488 if (tok == ')')
1489 break;
1490 if (tok != ',' || is_vaargs)
1491 goto bad_list;
1492 next_nomacro();
1494 next_nomacro_spc();
1495 t = MACRO_FUNC;
1498 tokstr_buf.len = 0;
1499 spc = 2;
1500 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1501 /* The body of a macro definition should be parsed such that identifiers
1502 are parsed like the file mode determines (i.e. with '.' being an
1503 ID character in asm mode). But '#' should be retained instead of
1504 regarded as line comment leader, so still don't set ASM_FILE
1505 in parse_flags. */
1506 set_idnum('.', (saved_parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0);
1507 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1508 /* remove spaces around ## and after '#' */
1509 if (TOK_TWOSHARPS == tok) {
1510 if (2 == spc)
1511 goto bad_twosharp;
1512 if (1 == spc)
1513 --tokstr_buf.len;
1514 spc = 3;
1515 tok = TOK_PPJOIN;
1516 } else if ('#' == tok) {
1517 spc = 4;
1518 } else if (check_space(tok, &spc)) {
1519 goto skip;
1521 tok_str_add2(&tokstr_buf, tok, &tokc);
1522 skip:
1523 next_nomacro_spc();
1526 parse_flags = saved_parse_flags;
1527 if (spc == 1)
1528 --tokstr_buf.len; /* remove trailing space */
1529 tok_str_add(&tokstr_buf, 0);
1530 if (3 == spc)
1531 bad_twosharp:
1532 tcc_error("'##' cannot appear at either end of macro");
1533 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1536 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1538 const unsigned char *s;
1539 unsigned int h;
1540 CachedInclude *e;
1541 int i;
1543 h = TOK_HASH_INIT;
1544 s = (unsigned char *) filename;
1545 while (*s) {
1546 #ifdef _WIN32
1547 h = TOK_HASH_FUNC(h, toup(*s));
1548 #else
1549 h = TOK_HASH_FUNC(h, *s);
1550 #endif
1551 s++;
1553 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1555 i = s1->cached_includes_hash[h];
1556 for(;;) {
1557 if (i == 0)
1558 break;
1559 e = s1->cached_includes[i - 1];
1560 if (0 == PATHCMP(e->filename, filename))
1561 return e;
1562 i = e->hash_next;
1564 if (!add)
1565 return NULL;
1567 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1568 strcpy(e->filename, filename);
1569 e->ifndef_macro = e->once = 0;
1570 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1571 /* add in hash table */
1572 e->hash_next = s1->cached_includes_hash[h];
1573 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1574 #ifdef INC_DEBUG
1575 printf("adding cached '%s'\n", filename);
1576 #endif
1577 return e;
1580 static void pragma_parse(TCCState *s1)
1582 next_nomacro();
1583 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1584 int t = tok, v;
1585 Sym *s;
1587 if (next(), tok != '(')
1588 goto pragma_err;
1589 if (next(), tok != TOK_STR)
1590 goto pragma_err;
1591 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1592 if (next(), tok != ')')
1593 goto pragma_err;
1594 if (t == TOK_push_macro) {
1595 while (NULL == (s = define_find(v)))
1596 define_push(v, 0, NULL, NULL);
1597 s->type.ref = s; /* set push boundary */
1598 } else {
1599 for (s = define_stack; s; s = s->prev)
1600 if (s->v == v && s->type.ref == s) {
1601 s->type.ref = NULL;
1602 break;
1605 if (s)
1606 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1607 else
1608 tcc_warning("unbalanced #pragma pop_macro");
1609 pp_debug_tok = t, pp_debug_symv = v;
1611 } else if (tok == TOK_once) {
1612 search_cached_include(s1, file->filename, 1)->once = pp_once;
1614 } else if (s1->ppfp) {
1615 /* tcc -E: keep pragmas below unchanged */
1616 unget_tok(' ');
1617 unget_tok(TOK_PRAGMA);
1618 unget_tok('#');
1619 unget_tok(TOK_LINEFEED);
1621 } else if (tok == TOK_pack) {
1622 /* This may be:
1623 #pragma pack(1) // set
1624 #pragma pack() // reset to default
1625 #pragma pack(push,1) // push & set
1626 #pragma pack(pop) // restore previous */
1627 next();
1628 skip('(');
1629 if (tok == TOK_ASM_pop) {
1630 next();
1631 if (s1->pack_stack_ptr <= s1->pack_stack) {
1632 stk_error:
1633 tcc_error("out of pack stack");
1635 s1->pack_stack_ptr--;
1636 } else {
1637 int val = 0;
1638 if (tok != ')') {
1639 if (tok == TOK_ASM_push) {
1640 next();
1641 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1642 goto stk_error;
1643 s1->pack_stack_ptr++;
1644 skip(',');
1646 if (tok != TOK_CINT)
1647 goto pragma_err;
1648 val = tokc.i;
1649 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1650 goto pragma_err;
1651 next();
1653 *s1->pack_stack_ptr = val;
1655 if (tok != ')')
1656 goto pragma_err;
1658 } else if (tok == TOK_comment) {
1659 char *file;
1660 next();
1661 skip('(');
1662 if (tok != TOK_lib)
1663 goto pragma_warn;
1664 next();
1665 skip(',');
1666 if (tok != TOK_STR)
1667 goto pragma_err;
1668 file = tcc_strdup((char *)tokc.str.data);
1669 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, file);
1670 next();
1671 if (tok != ')')
1672 goto pragma_err;
1673 } else {
1674 pragma_warn:
1675 if (s1->warn_unsupported)
1676 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1678 return;
1680 pragma_err:
1681 tcc_error("malformed #pragma directive");
1682 return;
1685 /* is_bof is true if first non space token at beginning of file */
1686 ST_FUNC void preprocess(int is_bof)
1688 TCCState *s1 = tcc_state;
1689 int i, c, n, saved_parse_flags;
1690 char buf[1024], *q;
1691 Sym *s;
1693 saved_parse_flags = parse_flags;
1694 parse_flags = PARSE_FLAG_PREPROCESS
1695 | PARSE_FLAG_TOK_NUM
1696 | PARSE_FLAG_TOK_STR
1697 | PARSE_FLAG_LINEFEED
1698 | (parse_flags & PARSE_FLAG_ASM_FILE)
1701 next_nomacro();
1702 redo:
1703 switch(tok) {
1704 case TOK_DEFINE:
1705 pp_debug_tok = tok;
1706 next_nomacro();
1707 pp_debug_symv = tok;
1708 parse_define();
1709 break;
1710 case TOK_UNDEF:
1711 pp_debug_tok = tok;
1712 next_nomacro();
1713 pp_debug_symv = tok;
1714 s = define_find(tok);
1715 /* undefine symbol by putting an invalid name */
1716 if (s)
1717 define_undef(s);
1718 break;
1719 case TOK_INCLUDE:
1720 case TOK_INCLUDE_NEXT:
1721 ch = file->buf_ptr[0];
1722 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1723 skip_spaces();
1724 if (ch == '<') {
1725 c = '>';
1726 goto read_name;
1727 } else if (ch == '\"') {
1728 c = ch;
1729 read_name:
1730 inp();
1731 q = buf;
1732 while (ch != c && ch != '\n' && ch != CH_EOF) {
1733 if ((q - buf) < sizeof(buf) - 1)
1734 *q++ = ch;
1735 if (ch == '\\') {
1736 if (handle_stray_noerror() == 0)
1737 --q;
1738 } else
1739 inp();
1741 *q = '\0';
1742 minp();
1743 #if 0
1744 /* eat all spaces and comments after include */
1745 /* XXX: slightly incorrect */
1746 while (ch1 != '\n' && ch1 != CH_EOF)
1747 inp();
1748 #endif
1749 } else {
1750 int len;
1751 /* computed #include : concatenate everything up to linefeed,
1752 the result must be one of the two accepted forms.
1753 Don't convert pp-tokens to tokens here. */
1754 parse_flags = (PARSE_FLAG_PREPROCESS
1755 | PARSE_FLAG_LINEFEED
1756 | (parse_flags & PARSE_FLAG_ASM_FILE));
1757 next();
1758 buf[0] = '\0';
1759 while (tok != TOK_LINEFEED) {
1760 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1761 next();
1763 len = strlen(buf);
1764 /* check syntax and remove '<>|""' */
1765 if ((len < 2 || ((buf[0] != '"' || buf[len-1] != '"') &&
1766 (buf[0] != '<' || buf[len-1] != '>'))))
1767 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1768 c = buf[len-1];
1769 memmove(buf, buf + 1, len - 2);
1770 buf[len - 2] = '\0';
1773 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1774 tcc_error("#include recursion too deep");
1775 /* store current file in stack, but increment stack later below */
1776 *s1->include_stack_ptr = file;
1777 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index : 0;
1778 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1779 for (; i < n; ++i) {
1780 char buf1[sizeof file->filename];
1781 CachedInclude *e;
1782 const char *path;
1784 if (i == 0) {
1785 /* check absolute include path */
1786 if (!IS_ABSPATH(buf))
1787 continue;
1788 buf1[0] = 0;
1790 } else if (i == 1) {
1791 /* search in file's dir if "header.h" */
1792 if (c != '\"')
1793 continue;
1794 path = file->filename;
1795 pstrncpy(buf1, path, tcc_basename(path) - path);
1797 } else {
1798 /* search in all the include paths */
1799 int j = i - 2, k = j - s1->nb_include_paths;
1800 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1801 pstrcpy(buf1, sizeof(buf1), path);
1802 pstrcat(buf1, sizeof(buf1), "/");
1805 pstrcat(buf1, sizeof(buf1), buf);
1806 e = search_cached_include(s1, buf1, 0);
1807 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1808 /* no need to parse the include because the 'ifndef macro'
1809 is defined (or had #pragma once) */
1810 #ifdef INC_DEBUG
1811 printf("%s: skipping cached %s\n", file->filename, buf1);
1812 #endif
1813 goto include_done;
1816 if (tcc_open(s1, buf1) < 0)
1817 continue;
1819 file->include_next_index = i + 1;
1820 #ifdef INC_DEBUG
1821 printf("%s: including %s\n", file->prev->filename, file->filename);
1822 #endif
1823 /* update target deps */
1824 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1825 tcc_strdup(buf1));
1826 /* push current file in stack */
1827 ++s1->include_stack_ptr;
1828 /* add include file debug info */
1829 if (s1->do_debug)
1830 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1831 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1832 ch = file->buf_ptr[0];
1833 goto the_end;
1835 tcc_error("include file '%s' not found", buf);
1836 include_done:
1837 break;
1838 case TOK_IFNDEF:
1839 c = 1;
1840 goto do_ifdef;
1841 case TOK_IF:
1842 c = expr_preprocess();
1843 goto do_if;
1844 case TOK_IFDEF:
1845 c = 0;
1846 do_ifdef:
1847 next_nomacro();
1848 if (tok < TOK_IDENT)
1849 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1850 if (is_bof) {
1851 if (c) {
1852 #ifdef INC_DEBUG
1853 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1854 #endif
1855 file->ifndef_macro = tok;
1858 c = (define_find(tok) != 0) ^ c;
1859 do_if:
1860 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1861 tcc_error("memory full (ifdef)");
1862 *s1->ifdef_stack_ptr++ = c;
1863 goto test_skip;
1864 case TOK_ELSE:
1865 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1866 tcc_error("#else without matching #if");
1867 if (s1->ifdef_stack_ptr[-1] & 2)
1868 tcc_error("#else after #else");
1869 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1870 goto test_else;
1871 case TOK_ELIF:
1872 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1873 tcc_error("#elif without matching #if");
1874 c = s1->ifdef_stack_ptr[-1];
1875 if (c > 1)
1876 tcc_error("#elif after #else");
1877 /* last #if/#elif expression was true: we skip */
1878 if (c == 1) {
1879 c = 0;
1880 } else {
1881 c = expr_preprocess();
1882 s1->ifdef_stack_ptr[-1] = c;
1884 test_else:
1885 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1886 file->ifndef_macro = 0;
1887 test_skip:
1888 if (!(c & 1)) {
1889 preprocess_skip();
1890 is_bof = 0;
1891 goto redo;
1893 break;
1894 case TOK_ENDIF:
1895 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1896 tcc_error("#endif without matching #if");
1897 s1->ifdef_stack_ptr--;
1898 /* '#ifndef macro' was at the start of file. Now we check if
1899 an '#endif' is exactly at the end of file */
1900 if (file->ifndef_macro &&
1901 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1902 file->ifndef_macro_saved = file->ifndef_macro;
1903 /* need to set to zero to avoid false matches if another
1904 #ifndef at middle of file */
1905 file->ifndef_macro = 0;
1906 while (tok != TOK_LINEFEED)
1907 next_nomacro();
1908 tok_flags |= TOK_FLAG_ENDIF;
1909 goto the_end;
1911 break;
1912 case TOK_PPNUM:
1913 n = strtoul((char*)tokc.str.data, &q, 10);
1914 goto _line_num;
1915 case TOK_LINE:
1916 next();
1917 if (tok != TOK_CINT)
1918 _line_err:
1919 tcc_error("wrong #line format");
1920 n = tokc.i;
1921 _line_num:
1922 next();
1923 if (tok != TOK_LINEFEED) {
1924 if (tok == TOK_STR)
1925 pstrcpy(file->filename, sizeof(file->filename), (char *)tokc.str.data);
1926 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1927 break;
1928 else
1929 goto _line_err;
1930 --n;
1932 if (file->fd > 0)
1933 total_lines += file->line_num - n;
1934 file->line_num = n;
1935 if (s1->do_debug)
1936 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1937 break;
1938 case TOK_ERROR:
1939 case TOK_WARNING:
1940 c = tok;
1941 ch = file->buf_ptr[0];
1942 skip_spaces();
1943 q = buf;
1944 while (ch != '\n' && ch != CH_EOF) {
1945 if ((q - buf) < sizeof(buf) - 1)
1946 *q++ = ch;
1947 if (ch == '\\') {
1948 if (handle_stray_noerror() == 0)
1949 --q;
1950 } else
1951 inp();
1953 *q = '\0';
1954 if (c == TOK_ERROR)
1955 tcc_error("#error %s", buf);
1956 else
1957 tcc_warning("#warning %s", buf);
1958 break;
1959 case TOK_PRAGMA:
1960 pragma_parse(s1);
1961 break;
1962 case TOK_LINEFEED:
1963 goto the_end;
1964 default:
1965 /* ignore gas line comment in an 'S' file. */
1966 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1967 goto ignore;
1968 if (tok == '!' && is_bof)
1969 /* '!' is ignored at beginning to allow C scripts. */
1970 goto ignore;
1971 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1972 ignore:
1973 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
1974 goto the_end;
1976 /* ignore other preprocess commands or #! for C scripts */
1977 while (tok != TOK_LINEFEED)
1978 next_nomacro();
1979 the_end:
1980 parse_flags = saved_parse_flags;
1983 /* evaluate escape codes in a string. */
1984 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1986 int c, n;
1987 const uint8_t *p;
1989 p = buf;
1990 for(;;) {
1991 c = *p;
1992 if (c == '\0')
1993 break;
1994 if (c == '\\') {
1995 p++;
1996 /* escape */
1997 c = *p;
1998 switch(c) {
1999 case '0': case '1': case '2': case '3':
2000 case '4': case '5': case '6': case '7':
2001 /* at most three octal digits */
2002 n = c - '0';
2003 p++;
2004 c = *p;
2005 if (isoct(c)) {
2006 n = n * 8 + c - '0';
2007 p++;
2008 c = *p;
2009 if (isoct(c)) {
2010 n = n * 8 + c - '0';
2011 p++;
2014 c = n;
2015 goto add_char_nonext;
2016 case 'x':
2017 case 'u':
2018 case 'U':
2019 p++;
2020 n = 0;
2021 for(;;) {
2022 c = *p;
2023 if (c >= 'a' && c <= 'f')
2024 c = c - 'a' + 10;
2025 else if (c >= 'A' && c <= 'F')
2026 c = c - 'A' + 10;
2027 else if (isnum(c))
2028 c = c - '0';
2029 else
2030 break;
2031 n = n * 16 + c;
2032 p++;
2034 c = n;
2035 goto add_char_nonext;
2036 case 'a':
2037 c = '\a';
2038 break;
2039 case 'b':
2040 c = '\b';
2041 break;
2042 case 'f':
2043 c = '\f';
2044 break;
2045 case 'n':
2046 c = '\n';
2047 break;
2048 case 'r':
2049 c = '\r';
2050 break;
2051 case 't':
2052 c = '\t';
2053 break;
2054 case 'v':
2055 c = '\v';
2056 break;
2057 case 'e':
2058 if (!gnu_ext)
2059 goto invalid_escape;
2060 c = 27;
2061 break;
2062 case '\'':
2063 case '\"':
2064 case '\\':
2065 case '?':
2066 break;
2067 default:
2068 invalid_escape:
2069 if (c >= '!' && c <= '~')
2070 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2071 else
2072 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2073 break;
2076 p++;
2077 add_char_nonext:
2078 if (!is_long)
2079 cstr_ccat(outstr, c);
2080 else
2081 cstr_wccat(outstr, c);
2083 /* add a trailing '\0' */
2084 if (!is_long)
2085 cstr_ccat(outstr, '\0');
2086 else
2087 cstr_wccat(outstr, '\0');
2090 static void parse_string(const char *s, int len)
2092 uint8_t buf[1000], *p = buf;
2093 int is_long, sep;
2095 if ((is_long = *s == 'L'))
2096 ++s, --len;
2097 sep = *s++;
2098 len -= 2;
2099 if (len >= sizeof buf)
2100 p = tcc_malloc(len + 1);
2101 memcpy(p, s, len);
2102 p[len] = 0;
2104 cstr_reset(&tokcstr);
2105 parse_escape_string(&tokcstr, p, is_long);
2106 if (p != buf)
2107 tcc_free(p);
2109 if (sep == '\'') {
2110 int char_size;
2111 /* XXX: make it portable */
2112 if (!is_long)
2113 char_size = 1;
2114 else
2115 char_size = sizeof(nwchar_t);
2116 if (tokcstr.size <= char_size)
2117 tcc_error("empty character constant");
2118 if (tokcstr.size > 2 * char_size)
2119 tcc_warning("multi-character character constant");
2120 if (!is_long) {
2121 tokc.i = *(int8_t *)tokcstr.data;
2122 tok = TOK_CCHAR;
2123 } else {
2124 tokc.i = *(nwchar_t *)tokcstr.data;
2125 tok = TOK_LCHAR;
2127 } else {
2128 tokc.str.size = tokcstr.size;
2129 tokc.str.data = tokcstr.data;
2130 if (!is_long)
2131 tok = TOK_STR;
2132 else
2133 tok = TOK_LSTR;
2137 /* we use 64 bit numbers */
2138 #define BN_SIZE 2
2140 /* bn = (bn << shift) | or_val */
2141 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2143 int i;
2144 unsigned int v;
2145 for(i=0;i<BN_SIZE;i++) {
2146 v = bn[i];
2147 bn[i] = (v << shift) | or_val;
2148 or_val = v >> (32 - shift);
2152 static void bn_zero(unsigned int *bn)
2154 int i;
2155 for(i=0;i<BN_SIZE;i++) {
2156 bn[i] = 0;
2160 /* parse number in null terminated string 'p' and return it in the
2161 current token */
2162 static void parse_number(const char *p)
2164 int b, t, shift, frac_bits, s, exp_val, ch;
2165 char *q;
2166 unsigned int bn[BN_SIZE];
2167 double d;
2169 /* number */
2170 q = token_buf;
2171 ch = *p++;
2172 t = ch;
2173 ch = *p++;
2174 *q++ = t;
2175 b = 10;
2176 if (t == '.') {
2177 goto float_frac_parse;
2178 } else if (t == '0') {
2179 if (ch == 'x' || ch == 'X') {
2180 q--;
2181 ch = *p++;
2182 b = 16;
2183 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
2184 q--;
2185 ch = *p++;
2186 b = 2;
2189 /* parse all digits. cannot check octal numbers at this stage
2190 because of floating point constants */
2191 while (1) {
2192 if (ch >= 'a' && ch <= 'f')
2193 t = ch - 'a' + 10;
2194 else if (ch >= 'A' && ch <= 'F')
2195 t = ch - 'A' + 10;
2196 else if (isnum(ch))
2197 t = ch - '0';
2198 else
2199 break;
2200 if (t >= b)
2201 break;
2202 if (q >= token_buf + STRING_MAX_SIZE) {
2203 num_too_long:
2204 tcc_error("number too long");
2206 *q++ = ch;
2207 ch = *p++;
2209 if (ch == '.' ||
2210 ((ch == 'e' || ch == 'E') && b == 10) ||
2211 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2212 if (b != 10) {
2213 /* NOTE: strtox should support that for hexa numbers, but
2214 non ISOC99 libcs do not support it, so we prefer to do
2215 it by hand */
2216 /* hexadecimal or binary floats */
2217 /* XXX: handle overflows */
2218 *q = '\0';
2219 if (b == 16)
2220 shift = 4;
2221 else
2222 shift = 1;
2223 bn_zero(bn);
2224 q = token_buf;
2225 while (1) {
2226 t = *q++;
2227 if (t == '\0') {
2228 break;
2229 } else if (t >= 'a') {
2230 t = t - 'a' + 10;
2231 } else if (t >= 'A') {
2232 t = t - 'A' + 10;
2233 } else {
2234 t = t - '0';
2236 bn_lshift(bn, shift, t);
2238 frac_bits = 0;
2239 if (ch == '.') {
2240 ch = *p++;
2241 while (1) {
2242 t = ch;
2243 if (t >= 'a' && t <= 'f') {
2244 t = t - 'a' + 10;
2245 } else if (t >= 'A' && t <= 'F') {
2246 t = t - 'A' + 10;
2247 } else if (t >= '0' && t <= '9') {
2248 t = t - '0';
2249 } else {
2250 break;
2252 if (t >= b)
2253 tcc_error("invalid digit");
2254 bn_lshift(bn, shift, t);
2255 frac_bits += shift;
2256 ch = *p++;
2259 if (ch != 'p' && ch != 'P')
2260 expect("exponent");
2261 ch = *p++;
2262 s = 1;
2263 exp_val = 0;
2264 if (ch == '+') {
2265 ch = *p++;
2266 } else if (ch == '-') {
2267 s = -1;
2268 ch = *p++;
2270 if (ch < '0' || ch > '9')
2271 expect("exponent digits");
2272 while (ch >= '0' && ch <= '9') {
2273 exp_val = exp_val * 10 + ch - '0';
2274 ch = *p++;
2276 exp_val = exp_val * s;
2278 /* now we can generate the number */
2279 /* XXX: should patch directly float number */
2280 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2281 d = ldexp(d, exp_val - frac_bits);
2282 t = toup(ch);
2283 if (t == 'F') {
2284 ch = *p++;
2285 tok = TOK_CFLOAT;
2286 /* float : should handle overflow */
2287 tokc.f = (float)d;
2288 } else if (t == 'L') {
2289 ch = *p++;
2290 #ifdef TCC_TARGET_PE
2291 tok = TOK_CDOUBLE;
2292 tokc.d = d;
2293 #else
2294 tok = TOK_CLDOUBLE;
2295 /* XXX: not large enough */
2296 tokc.ld = (long double)d;
2297 #endif
2298 } else {
2299 tok = TOK_CDOUBLE;
2300 tokc.d = d;
2302 } else {
2303 /* decimal floats */
2304 if (ch == '.') {
2305 if (q >= token_buf + STRING_MAX_SIZE)
2306 goto num_too_long;
2307 *q++ = ch;
2308 ch = *p++;
2309 float_frac_parse:
2310 while (ch >= '0' && ch <= '9') {
2311 if (q >= token_buf + STRING_MAX_SIZE)
2312 goto num_too_long;
2313 *q++ = ch;
2314 ch = *p++;
2317 if (ch == 'e' || ch == 'E') {
2318 if (q >= token_buf + STRING_MAX_SIZE)
2319 goto num_too_long;
2320 *q++ = ch;
2321 ch = *p++;
2322 if (ch == '-' || ch == '+') {
2323 if (q >= token_buf + STRING_MAX_SIZE)
2324 goto num_too_long;
2325 *q++ = ch;
2326 ch = *p++;
2328 if (ch < '0' || ch > '9')
2329 expect("exponent digits");
2330 while (ch >= '0' && ch <= '9') {
2331 if (q >= token_buf + STRING_MAX_SIZE)
2332 goto num_too_long;
2333 *q++ = ch;
2334 ch = *p++;
2337 *q = '\0';
2338 t = toup(ch);
2339 errno = 0;
2340 if (t == 'F') {
2341 ch = *p++;
2342 tok = TOK_CFLOAT;
2343 tokc.f = strtof(token_buf, NULL);
2344 } else if (t == 'L') {
2345 ch = *p++;
2346 #ifdef TCC_TARGET_PE
2347 tok = TOK_CDOUBLE;
2348 tokc.d = strtod(token_buf, NULL);
2349 #else
2350 tok = TOK_CLDOUBLE;
2351 tokc.ld = strtold(token_buf, NULL);
2352 #endif
2353 } else {
2354 tok = TOK_CDOUBLE;
2355 tokc.d = strtod(token_buf, NULL);
2358 } else {
2359 unsigned long long n, n1;
2360 int lcount, ucount, must_64bit;
2361 const char *p1;
2363 /* integer number */
2364 *q = '\0';
2365 q = token_buf;
2366 if (b == 10 && *q == '0') {
2367 b = 8;
2368 q++;
2370 n = 0;
2371 while(1) {
2372 t = *q++;
2373 /* no need for checks except for base 10 / 8 errors */
2374 if (t == '\0')
2375 break;
2376 else if (t >= 'a')
2377 t = t - 'a' + 10;
2378 else if (t >= 'A')
2379 t = t - 'A' + 10;
2380 else
2381 t = t - '0';
2382 if (t >= b)
2383 tcc_error("invalid digit");
2384 n1 = n;
2385 n = n * b + t;
2386 /* detect overflow */
2387 /* XXX: this test is not reliable */
2388 if (n < n1)
2389 tcc_error("integer constant overflow");
2392 /* Determine the characteristics (unsigned and/or 64bit) the type of
2393 the constant must have according to the constant suffix(es) */
2394 lcount = ucount = must_64bit = 0;
2395 p1 = p;
2396 for(;;) {
2397 t = toup(ch);
2398 if (t == 'L') {
2399 if (lcount >= 2)
2400 tcc_error("three 'l's in integer constant");
2401 if (lcount && *(p - 1) != ch)
2402 tcc_error("incorrect integer suffix: %s", p1);
2403 lcount++;
2404 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2405 if (lcount == 2)
2406 #endif
2407 must_64bit = 1;
2408 ch = *p++;
2409 } else if (t == 'U') {
2410 if (ucount >= 1)
2411 tcc_error("two 'u's in integer constant");
2412 ucount++;
2413 ch = *p++;
2414 } else {
2415 break;
2419 /* Whether 64 bits are needed to hold the constant's value */
2420 if (n & 0xffffffff00000000LL || must_64bit) {
2421 tok = TOK_CLLONG;
2422 n1 = n >> 32;
2423 } else {
2424 tok = TOK_CINT;
2425 n1 = n;
2428 /* Whether type must be unsigned to hold the constant's value */
2429 if (ucount || ((n1 >> 31) && (b != 10))) {
2430 if (tok == TOK_CLLONG)
2431 tok = TOK_CULLONG;
2432 else
2433 tok = TOK_CUINT;
2434 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2435 } else if (n1 >> 31) {
2436 if (tok == TOK_CINT)
2437 tok = TOK_CLLONG;
2438 else
2439 tcc_error("integer constant overflow");
2442 tokc.i = n;
2444 if (ch)
2445 tcc_error("invalid number\n");
2449 #define PARSE2(c1, tok1, c2, tok2) \
2450 case c1: \
2451 PEEKC(c, p); \
2452 if (c == c2) { \
2453 p++; \
2454 tok = tok2; \
2455 } else { \
2456 tok = tok1; \
2458 break;
2460 /* return next token without macro substitution */
2461 static inline void next_nomacro1(void)
2463 int t, c, is_long, len;
2464 TokenSym *ts;
2465 uint8_t *p, *p1;
2466 unsigned int h;
2468 p = file->buf_ptr;
2469 redo_no_start:
2470 c = *p;
2471 switch(c) {
2472 case ' ':
2473 case '\t':
2474 tok = c;
2475 p++;
2476 if (parse_flags & PARSE_FLAG_SPACES)
2477 goto keep_tok_flags;
2478 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2479 ++p;
2480 goto redo_no_start;
2481 case '\f':
2482 case '\v':
2483 case '\r':
2484 p++;
2485 goto redo_no_start;
2486 case '\\':
2487 /* first look if it is in fact an end of buffer */
2488 c = handle_stray1(p);
2489 p = file->buf_ptr;
2490 if (c == '\\')
2491 goto parse_simple;
2492 if (c != CH_EOF)
2493 goto redo_no_start;
2495 TCCState *s1 = tcc_state;
2496 if ((parse_flags & PARSE_FLAG_LINEFEED)
2497 && !(tok_flags & TOK_FLAG_EOF)) {
2498 tok_flags |= TOK_FLAG_EOF;
2499 tok = TOK_LINEFEED;
2500 goto keep_tok_flags;
2501 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2502 tok = TOK_EOF;
2503 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2504 tcc_error("missing #endif");
2505 } else if (s1->include_stack_ptr == s1->include_stack) {
2506 /* no include left : end of file. */
2507 tok = TOK_EOF;
2508 } else {
2509 tok_flags &= ~TOK_FLAG_EOF;
2510 /* pop include file */
2512 /* test if previous '#endif' was after a #ifdef at
2513 start of file */
2514 if (tok_flags & TOK_FLAG_ENDIF) {
2515 #ifdef INC_DEBUG
2516 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2517 #endif
2518 search_cached_include(s1, file->filename, 1)
2519 ->ifndef_macro = file->ifndef_macro_saved;
2520 tok_flags &= ~TOK_FLAG_ENDIF;
2523 /* add end of include file debug info */
2524 if (tcc_state->do_debug) {
2525 put_stabd(N_EINCL, 0, 0);
2527 /* pop include stack */
2528 tcc_close();
2529 s1->include_stack_ptr--;
2530 p = file->buf_ptr;
2531 goto redo_no_start;
2534 break;
2536 case '\n':
2537 file->line_num++;
2538 tok_flags |= TOK_FLAG_BOL;
2539 p++;
2540 maybe_newline:
2541 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2542 goto redo_no_start;
2543 tok = TOK_LINEFEED;
2544 goto keep_tok_flags;
2546 case '#':
2547 /* XXX: simplify */
2548 PEEKC(c, p);
2549 if ((tok_flags & TOK_FLAG_BOL) &&
2550 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2551 file->buf_ptr = p;
2552 preprocess(tok_flags & TOK_FLAG_BOF);
2553 p = file->buf_ptr;
2554 goto maybe_newline;
2555 } else {
2556 if (c == '#') {
2557 p++;
2558 tok = TOK_TWOSHARPS;
2559 } else {
2560 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2561 p = parse_line_comment(p - 1);
2562 goto redo_no_start;
2563 } else {
2564 tok = '#';
2568 break;
2570 /* dollar is allowed to start identifiers when not parsing asm */
2571 case '$':
2572 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2573 || (parse_flags & PARSE_FLAG_ASM_FILE))
2574 goto parse_simple;
2576 case 'a': case 'b': case 'c': case 'd':
2577 case 'e': case 'f': case 'g': case 'h':
2578 case 'i': case 'j': case 'k': case 'l':
2579 case 'm': case 'n': case 'o': case 'p':
2580 case 'q': case 'r': case 's': case 't':
2581 case 'u': case 'v': case 'w': case 'x':
2582 case 'y': case 'z':
2583 case 'A': case 'B': case 'C': case 'D':
2584 case 'E': case 'F': case 'G': case 'H':
2585 case 'I': case 'J': case 'K':
2586 case 'M': case 'N': case 'O': case 'P':
2587 case 'Q': case 'R': case 'S': case 'T':
2588 case 'U': case 'V': case 'W': case 'X':
2589 case 'Y': case 'Z':
2590 case '_':
2591 parse_ident_fast:
2592 p1 = p;
2593 h = TOK_HASH_INIT;
2594 h = TOK_HASH_FUNC(h, c);
2595 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2596 h = TOK_HASH_FUNC(h, c);
2597 len = p - p1;
2598 if (c != '\\') {
2599 TokenSym **pts;
2601 /* fast case : no stray found, so we have the full token
2602 and we have already hashed it */
2603 h &= (TOK_HASH_SIZE - 1);
2604 pts = &hash_ident[h];
2605 for(;;) {
2606 ts = *pts;
2607 if (!ts)
2608 break;
2609 if (ts->len == len && !memcmp(ts->str, p1, len))
2610 goto token_found;
2611 pts = &(ts->hash_next);
2613 ts = tok_alloc_new(pts, (char *) p1, len);
2614 token_found: ;
2615 } else {
2616 /* slower case */
2617 cstr_reset(&tokcstr);
2618 cstr_cat(&tokcstr, p1, len);
2619 p--;
2620 PEEKC(c, p);
2621 parse_ident_slow:
2622 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2624 cstr_ccat(&tokcstr, c);
2625 PEEKC(c, p);
2627 ts = tok_alloc(tokcstr.data, tokcstr.size);
2629 tok = ts->tok;
2630 break;
2631 case 'L':
2632 t = p[1];
2633 if (t != '\\' && t != '\'' && t != '\"') {
2634 /* fast case */
2635 goto parse_ident_fast;
2636 } else {
2637 PEEKC(c, p);
2638 if (c == '\'' || c == '\"') {
2639 is_long = 1;
2640 goto str_const;
2641 } else {
2642 cstr_reset(&tokcstr);
2643 cstr_ccat(&tokcstr, 'L');
2644 goto parse_ident_slow;
2647 break;
2649 case '0': case '1': case '2': case '3':
2650 case '4': case '5': case '6': case '7':
2651 case '8': case '9':
2652 t = c;
2653 PEEKC(c, p);
2654 /* after the first digit, accept digits, alpha, '.' or sign if
2655 prefixed by 'eEpP' */
2656 parse_num:
2657 cstr_reset(&tokcstr);
2658 for(;;) {
2659 cstr_ccat(&tokcstr, t);
2660 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2661 || c == '.'
2662 || ((c == '+' || c == '-')
2663 && (((t == 'e' || t == 'E')
2664 && !(parse_flags & PARSE_FLAG_ASM_FILE
2665 /* 0xe+1 is 3 tokens in asm */
2666 && ((char*)tokcstr.data)[0] == '0'
2667 && toup(((char*)tokcstr.data)[1]) == 'X'))
2668 || t == 'p' || t == 'P'))))
2669 break;
2670 t = c;
2671 PEEKC(c, p);
2673 /* We add a trailing '\0' to ease parsing */
2674 cstr_ccat(&tokcstr, '\0');
2675 tokc.str.size = tokcstr.size;
2676 tokc.str.data = tokcstr.data;
2677 tok = TOK_PPNUM;
2678 break;
2680 case '.':
2681 /* special dot handling because it can also start a number */
2682 PEEKC(c, p);
2683 if (isnum(c)) {
2684 t = '.';
2685 goto parse_num;
2686 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2687 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2688 *--p = c = '.';
2689 goto parse_ident_fast;
2690 } else if (c == '.') {
2691 PEEKC(c, p);
2692 if (c == '.') {
2693 p++;
2694 tok = TOK_DOTS;
2695 } else {
2696 *--p = '.'; /* may underflow into file->unget[] */
2697 tok = '.';
2699 } else {
2700 tok = '.';
2702 break;
2703 case '\'':
2704 case '\"':
2705 is_long = 0;
2706 str_const:
2707 cstr_reset(&tokcstr);
2708 if (is_long)
2709 cstr_ccat(&tokcstr, 'L');
2710 cstr_ccat(&tokcstr, c);
2711 p = parse_pp_string(p, c, &tokcstr);
2712 cstr_ccat(&tokcstr, c);
2713 cstr_ccat(&tokcstr, '\0');
2714 tokc.str.size = tokcstr.size;
2715 tokc.str.data = tokcstr.data;
2716 tok = TOK_PPSTR;
2717 break;
2719 case '<':
2720 PEEKC(c, p);
2721 if (c == '=') {
2722 p++;
2723 tok = TOK_LE;
2724 } else if (c == '<') {
2725 PEEKC(c, p);
2726 if (c == '=') {
2727 p++;
2728 tok = TOK_A_SHL;
2729 } else {
2730 tok = TOK_SHL;
2732 } else {
2733 tok = TOK_LT;
2735 break;
2736 case '>':
2737 PEEKC(c, p);
2738 if (c == '=') {
2739 p++;
2740 tok = TOK_GE;
2741 } else if (c == '>') {
2742 PEEKC(c, p);
2743 if (c == '=') {
2744 p++;
2745 tok = TOK_A_SAR;
2746 } else {
2747 tok = TOK_SAR;
2749 } else {
2750 tok = TOK_GT;
2752 break;
2754 case '&':
2755 PEEKC(c, p);
2756 if (c == '&') {
2757 p++;
2758 tok = TOK_LAND;
2759 } else if (c == '=') {
2760 p++;
2761 tok = TOK_A_AND;
2762 } else {
2763 tok = '&';
2765 break;
2767 case '|':
2768 PEEKC(c, p);
2769 if (c == '|') {
2770 p++;
2771 tok = TOK_LOR;
2772 } else if (c == '=') {
2773 p++;
2774 tok = TOK_A_OR;
2775 } else {
2776 tok = '|';
2778 break;
2780 case '+':
2781 PEEKC(c, p);
2782 if (c == '+') {
2783 p++;
2784 tok = TOK_INC;
2785 } else if (c == '=') {
2786 p++;
2787 tok = TOK_A_ADD;
2788 } else {
2789 tok = '+';
2791 break;
2793 case '-':
2794 PEEKC(c, p);
2795 if (c == '-') {
2796 p++;
2797 tok = TOK_DEC;
2798 } else if (c == '=') {
2799 p++;
2800 tok = TOK_A_SUB;
2801 } else if (c == '>') {
2802 p++;
2803 tok = TOK_ARROW;
2804 } else {
2805 tok = '-';
2807 break;
2809 PARSE2('!', '!', '=', TOK_NE)
2810 PARSE2('=', '=', '=', TOK_EQ)
2811 PARSE2('*', '*', '=', TOK_A_MUL)
2812 PARSE2('%', '%', '=', TOK_A_MOD)
2813 PARSE2('^', '^', '=', TOK_A_XOR)
2815 /* comments or operator */
2816 case '/':
2817 PEEKC(c, p);
2818 if (c == '*') {
2819 p = parse_comment(p);
2820 /* comments replaced by a blank */
2821 tok = ' ';
2822 goto keep_tok_flags;
2823 } else if (c == '/') {
2824 p = parse_line_comment(p);
2825 tok = ' ';
2826 goto keep_tok_flags;
2827 } else if (c == '=') {
2828 p++;
2829 tok = TOK_A_DIV;
2830 } else {
2831 tok = '/';
2833 break;
2835 /* simple tokens */
2836 case '(':
2837 case ')':
2838 case '[':
2839 case ']':
2840 case '{':
2841 case '}':
2842 case ',':
2843 case ';':
2844 case ':':
2845 case '?':
2846 case '~':
2847 case '@': /* only used in assembler */
2848 parse_simple:
2849 tok = c;
2850 p++;
2851 break;
2852 default:
2853 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2854 goto parse_ident_fast;
2855 if (parse_flags & PARSE_FLAG_ASM_FILE)
2856 goto parse_simple;
2857 tcc_error("unrecognized character \\x%02x", c);
2858 break;
2860 tok_flags = 0;
2861 keep_tok_flags:
2862 file->buf_ptr = p;
2863 #if defined(PARSE_DEBUG)
2864 printf("token = %s\n", get_tok_str(tok, &tokc));
2865 #endif
2868 /* return next token without macro substitution. Can read input from
2869 macro_ptr buffer */
2870 static void next_nomacro_spc(void)
2872 if (macro_ptr) {
2873 redo:
2874 tok = *macro_ptr;
2875 if (tok) {
2876 TOK_GET(&tok, &macro_ptr, &tokc);
2877 if (tok == TOK_LINENUM) {
2878 file->line_num = tokc.i;
2879 goto redo;
2882 } else {
2883 next_nomacro1();
2887 ST_FUNC void next_nomacro(void)
2889 do {
2890 next_nomacro_spc();
2891 } while (tok < 256 && (isidnum_table[tok - CH_EOF] & IS_SPC));
2895 static void macro_subst(
2896 TokenString *tok_str,
2897 Sym **nested_list,
2898 const int *macro_str,
2899 int can_read_stream
2902 /* substitute arguments in replacement lists in macro_str by the values in
2903 args (field d) and return allocated string */
2904 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2906 int t, t0, t1, spc;
2907 const int *st;
2908 Sym *s;
2909 CValue cval;
2910 TokenString str;
2911 CString cstr;
2913 tok_str_new(&str);
2914 t0 = t1 = 0;
2915 while(1) {
2916 TOK_GET(&t, &macro_str, &cval);
2917 if (!t)
2918 break;
2919 if (t == '#') {
2920 /* stringize */
2921 TOK_GET(&t, &macro_str, &cval);
2922 if (!t)
2923 goto bad_stringy;
2924 s = sym_find2(args, t);
2925 if (s) {
2926 cstr_new(&cstr);
2927 cstr_ccat(&cstr, '\"');
2928 st = s->d;
2929 spc = 0;
2930 while (*st) {
2931 TOK_GET(&t, &st, &cval);
2932 if (t != TOK_PLCHLDR
2933 && t != TOK_NOSUBST
2934 && 0 == check_space(t, &spc)) {
2935 const char *s = get_tok_str(t, &cval);
2936 while (*s) {
2937 if (t == TOK_PPSTR && *s != '\'')
2938 add_char(&cstr, *s);
2939 else
2940 cstr_ccat(&cstr, *s);
2941 ++s;
2945 cstr.size -= spc;
2946 cstr_ccat(&cstr, '\"');
2947 cstr_ccat(&cstr, '\0');
2948 #ifdef PP_DEBUG
2949 printf("\nstringize: <%s>\n", (char *)cstr.data);
2950 #endif
2951 /* add string */
2952 cval.str.size = cstr.size;
2953 cval.str.data = cstr.data;
2954 tok_str_add2(&str, TOK_PPSTR, &cval);
2955 cstr_free(&cstr);
2956 } else {
2957 bad_stringy:
2958 expect("macro parameter after '#'");
2960 } else if (t >= TOK_IDENT) {
2961 s = sym_find2(args, t);
2962 if (s) {
2963 int l0 = str.len;
2964 st = s->d;
2965 /* if '##' is present before or after, no arg substitution */
2966 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
2967 /* special case for var arg macros : ## eats the ','
2968 if empty VA_ARGS variable. */
2969 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
2970 if (*st == 0) {
2971 /* suppress ',' '##' */
2972 str.len -= 2;
2973 } else {
2974 /* suppress '##' and add variable */
2975 str.len--;
2976 goto add_var;
2978 } else {
2979 for(;;) {
2980 int t1;
2981 TOK_GET(&t1, &st, &cval);
2982 if (!t1)
2983 break;
2984 tok_str_add2(&str, t1, &cval);
2988 } else {
2989 add_var:
2990 /* NOTE: the stream cannot be read when macro
2991 substituing an argument */
2992 macro_subst(&str, nested_list, st, 0);
2994 if (str.len == l0) /* exanded to empty string */
2995 tok_str_add(&str, TOK_PLCHLDR);
2996 } else {
2997 tok_str_add(&str, t);
2999 } else {
3000 tok_str_add2(&str, t, &cval);
3002 t0 = t1, t1 = t;
3004 tok_str_add(&str, 0);
3005 return str.str;
3008 static char const ab_month_name[12][4] =
3010 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3011 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3014 /* peek or read [ws_str == NULL] next token from function macro call,
3015 walking up macro levels up to the file if necessary */
3016 static int next_argstream(Sym **nested_list, int can_read_stream, TokenString *ws_str)
3018 int t;
3019 const int *p;
3020 Sym *sa;
3022 for (;;) {
3023 if (macro_ptr) {
3024 p = macro_ptr, t = *p;
3025 if (ws_str) {
3026 while (is_space(t) || TOK_LINEFEED == t)
3027 tok_str_add(ws_str, t), t = *++p;
3029 if (t == 0 && can_read_stream) {
3030 end_macro();
3031 /* also, end of scope for nested defined symbol */
3032 sa = *nested_list;
3033 while (sa && sa->v == 0)
3034 sa = sa->prev;
3035 if (sa)
3036 sa->v = 0;
3037 continue;
3039 } else {
3040 ch = handle_eob();
3041 if (ws_str) {
3042 while (is_space(ch) || ch == '\n' || ch == '/') {
3043 if (ch == '/') {
3044 int c;
3045 uint8_t *p = file->buf_ptr;
3046 PEEKC(c, p);
3047 if (c == '*') {
3048 p = parse_comment(p);
3049 file->buf_ptr = p - 1;
3050 } else if (c == '/') {
3051 p = parse_line_comment(p);
3052 file->buf_ptr = p - 1;
3053 } else
3054 break;
3055 ch = ' ';
3057 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3058 tok_str_add(ws_str, ch);
3059 cinp();
3062 t = ch;
3065 if (ws_str)
3066 return t;
3067 next_nomacro_spc();
3068 return tok;
3072 /* do macro substitution of current token with macro 's' and add
3073 result to (tok_str,tok_len). 'nested_list' is the list of all
3074 macros we got inside to avoid recursing. Return non zero if no
3075 substitution needs to be done */
3076 static int macro_subst_tok(
3077 TokenString *tok_str,
3078 Sym **nested_list,
3079 Sym *s,
3080 int can_read_stream)
3082 Sym *args, *sa, *sa1;
3083 int parlevel, *mstr, t, t1, spc;
3084 TokenString str;
3085 char *cstrval;
3086 CValue cval;
3087 CString cstr;
3088 char buf[32];
3090 /* if symbol is a macro, prepare substitution */
3091 /* special macros */
3092 if (tok == TOK___LINE__) {
3093 snprintf(buf, sizeof(buf), "%d", file->line_num);
3094 cstrval = buf;
3095 t1 = TOK_PPNUM;
3096 goto add_cstr1;
3097 } else if (tok == TOK___FILE__) {
3098 cstrval = file->filename;
3099 goto add_cstr;
3100 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3101 time_t ti;
3102 struct tm *tm;
3104 time(&ti);
3105 tm = localtime(&ti);
3106 if (tok == TOK___DATE__) {
3107 snprintf(buf, sizeof(buf), "%s %2d %d",
3108 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3109 } else {
3110 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3111 tm->tm_hour, tm->tm_min, tm->tm_sec);
3113 cstrval = buf;
3114 add_cstr:
3115 t1 = TOK_STR;
3116 add_cstr1:
3117 cstr_new(&cstr);
3118 cstr_cat(&cstr, cstrval, 0);
3119 cval.str.size = cstr.size;
3120 cval.str.data = cstr.data;
3121 tok_str_add2(tok_str, t1, &cval);
3122 cstr_free(&cstr);
3123 } else {
3124 int saved_parse_flags = parse_flags;
3126 mstr = s->d;
3127 if (s->type.t == MACRO_FUNC) {
3128 /* whitespace between macro name and argument list */
3129 TokenString ws_str;
3130 tok_str_new(&ws_str);
3132 spc = 0;
3133 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3134 | PARSE_FLAG_ACCEPT_STRAYS;
3136 /* get next token from argument stream */
3137 t = next_argstream(nested_list, can_read_stream, &ws_str);
3138 if (t != '(') {
3139 /* not a macro substitution after all, restore the
3140 * macro token plus all whitespace we've read.
3141 * whitespace is intentionally not merged to preserve
3142 * newlines. */
3143 parse_flags = saved_parse_flags;
3144 tok_str_add(tok_str, tok);
3145 if (parse_flags & PARSE_FLAG_SPACES) {
3146 int i;
3147 for (i = 0; i < ws_str.len; i++)
3148 tok_str_add(tok_str, ws_str.str[i]);
3150 tok_str_free_str(ws_str.str);
3151 return 0;
3152 } else {
3153 tok_str_free_str(ws_str.str);
3155 next_nomacro(); /* eat '(' */
3157 /* argument macro */
3158 args = NULL;
3159 sa = s->next;
3160 /* NOTE: empty args are allowed, except if no args */
3161 for(;;) {
3162 do {
3163 next_argstream(nested_list, can_read_stream, NULL);
3164 } while (is_space(tok) || TOK_LINEFEED == tok);
3165 empty_arg:
3166 /* handle '()' case */
3167 if (!args && !sa && tok == ')')
3168 break;
3169 if (!sa)
3170 tcc_error("macro '%s' used with too many args",
3171 get_tok_str(s->v, 0));
3172 tok_str_new(&str);
3173 parlevel = spc = 0;
3174 /* NOTE: non zero sa->t indicates VA_ARGS */
3175 while ((parlevel > 0 ||
3176 (tok != ')' &&
3177 (tok != ',' || sa->type.t)))) {
3178 if (tok == TOK_EOF || tok == 0)
3179 break;
3180 if (tok == '(')
3181 parlevel++;
3182 else if (tok == ')')
3183 parlevel--;
3184 if (tok == TOK_LINEFEED)
3185 tok = ' ';
3186 if (!check_space(tok, &spc))
3187 tok_str_add2(&str, tok, &tokc);
3188 next_argstream(nested_list, can_read_stream, NULL);
3190 if (parlevel)
3191 expect(")");
3192 str.len -= spc;
3193 tok_str_add(&str, 0);
3194 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3195 sa1->d = str.str;
3196 sa = sa->next;
3197 if (tok == ')') {
3198 /* special case for gcc var args: add an empty
3199 var arg argument if it is omitted */
3200 if (sa && sa->type.t && gnu_ext)
3201 goto empty_arg;
3202 break;
3204 if (tok != ',')
3205 expect(",");
3207 if (sa) {
3208 tcc_error("macro '%s' used with too few args",
3209 get_tok_str(s->v, 0));
3212 parse_flags = saved_parse_flags;
3214 /* now subst each arg */
3215 mstr = macro_arg_subst(nested_list, mstr, args);
3216 /* free memory */
3217 sa = args;
3218 while (sa) {
3219 sa1 = sa->prev;
3220 tok_str_free_str(sa->d);
3221 sym_free(sa);
3222 sa = sa1;
3226 sym_push2(nested_list, s->v, 0, 0);
3227 parse_flags = saved_parse_flags;
3228 macro_subst(tok_str, nested_list, mstr, can_read_stream | 2);
3230 /* pop nested defined symbol */
3231 sa1 = *nested_list;
3232 *nested_list = sa1->prev;
3233 sym_free(sa1);
3234 if (mstr != s->d)
3235 tok_str_free_str(mstr);
3237 return 0;
3240 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3242 CString cstr;
3243 int n, ret = 1;
3245 cstr_new(&cstr);
3246 if (t1 != TOK_PLCHLDR)
3247 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3248 n = cstr.size;
3249 if (t2 != TOK_PLCHLDR)
3250 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3251 cstr_ccat(&cstr, '\0');
3253 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3254 memcpy(file->buffer, cstr.data, cstr.size);
3255 for (;;) {
3256 next_nomacro1();
3257 if (0 == *file->buf_ptr)
3258 break;
3259 if (is_space(tok))
3260 continue;
3261 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3262 " preprocessing token", n, cstr.data, (char*)cstr.data + n);
3263 ret = 0;
3264 break;
3266 tcc_close();
3267 //printf("paste <%s>\n", (char*)cstr.data);
3268 cstr_free(&cstr);
3269 return ret;
3272 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3273 return the resulting string (which must be freed). */
3274 static inline int *macro_twosharps(const int *ptr0)
3276 int t;
3277 CValue cval;
3278 TokenString macro_str1;
3279 int start_of_nosubsts = -1;
3280 const int *ptr;
3282 /* we search the first '##' */
3283 for (ptr = ptr0;;) {
3284 TOK_GET(&t, &ptr, &cval);
3285 if (t == TOK_PPJOIN)
3286 break;
3287 if (t == 0)
3288 return NULL;
3291 tok_str_new(&macro_str1);
3293 //tok_print(" $$$", ptr0);
3294 for (ptr = ptr0;;) {
3295 TOK_GET(&t, &ptr, &cval);
3296 if (t == 0)
3297 break;
3298 if (t == TOK_PPJOIN)
3299 continue;
3300 while (*ptr == TOK_PPJOIN) {
3301 int t1; CValue cv1;
3302 /* given 'a##b', remove nosubsts preceding 'a' */
3303 if (start_of_nosubsts >= 0)
3304 macro_str1.len = start_of_nosubsts;
3305 /* given 'a##b', remove nosubsts preceding 'b' */
3306 while ((t1 = *++ptr) == TOK_NOSUBST)
3308 if (t1 && t1 != TOK_PPJOIN) {
3309 TOK_GET(&t1, &ptr, &cv1);
3310 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3311 if (paste_tokens(t, &cval, t1, &cv1)) {
3312 t = tok, cval = tokc;
3313 } else {
3314 tok_str_add2(&macro_str1, t, &cval);
3315 t = t1, cval = cv1;
3320 if (t == TOK_NOSUBST) {
3321 if (start_of_nosubsts < 0)
3322 start_of_nosubsts = macro_str1.len;
3323 } else {
3324 start_of_nosubsts = -1;
3326 tok_str_add2(&macro_str1, t, &cval);
3328 tok_str_add(&macro_str1, 0);
3329 //tok_print(" ###", macro_str1.str);
3330 return macro_str1.str;
3333 /* do macro substitution of macro_str and add result to
3334 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3335 inside to avoid recursing. */
3336 static void macro_subst(
3337 TokenString *tok_str,
3338 Sym **nested_list,
3339 const int *macro_str,
3340 int can_read_stream
3343 Sym *s;
3344 const int *ptr;
3345 int t, spc, nosubst;
3346 CValue cval;
3347 int *macro_str1 = NULL;
3349 /* first scan for '##' operator handling */
3350 ptr = macro_str;
3351 spc = nosubst = 0;
3353 /* first scan for '##' operator handling */
3354 if (can_read_stream) {
3355 macro_str1 = macro_twosharps(ptr);
3356 if (macro_str1)
3357 ptr = macro_str1;
3360 while (1) {
3361 TOK_GET(&t, &ptr, &cval);
3362 if (t == 0)
3363 break;
3365 if (t >= TOK_IDENT && 0 == nosubst) {
3366 s = define_find(t);
3367 if (s == NULL)
3368 goto no_subst;
3370 /* if nested substitution, do nothing */
3371 if (sym_find2(*nested_list, t)) {
3372 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3373 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3374 goto no_subst;
3378 TokenString str;
3379 str.str = (int*)ptr;
3380 begin_macro(&str, 2);
3382 tok = t;
3383 macro_subst_tok(tok_str, nested_list, s, can_read_stream);
3385 if (str.alloc == 3) {
3386 /* already finished by reading function macro arguments */
3387 break;
3390 ptr = macro_ptr;
3391 end_macro ();
3394 spc = (tok_str->len &&
3395 is_space(tok_last(tok_str->str,
3396 tok_str->str + tok_str->len)));
3398 } else {
3400 if (t == '\\' && !(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3401 tcc_error("stray '\\' in program");
3403 no_subst:
3404 if (!check_space(t, &spc))
3405 tok_str_add2(tok_str, t, &cval);
3406 nosubst = 0;
3407 if (t == TOK_NOSUBST)
3408 nosubst = 1;
3411 if (macro_str1)
3412 tok_str_free_str(macro_str1);
3416 /* return next token with macro substitution */
3417 ST_FUNC void next(void)
3419 redo:
3420 if (parse_flags & PARSE_FLAG_SPACES)
3421 next_nomacro_spc();
3422 else
3423 next_nomacro();
3425 if (macro_ptr) {
3426 if (tok == TOK_NOSUBST || tok == TOK_PLCHLDR) {
3427 /* discard preprocessor markers */
3428 goto redo;
3429 } else if (tok == 0) {
3430 /* end of macro or unget token string */
3431 end_macro();
3432 goto redo;
3434 } else if (tok >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3435 Sym *s;
3436 /* if reading from file, try to substitute macros */
3437 s = define_find(tok);
3438 if (s) {
3439 Sym *nested_list = NULL;
3440 tokstr_buf.len = 0;
3441 macro_subst_tok(&tokstr_buf, &nested_list, s, 1);
3442 tok_str_add(&tokstr_buf, 0);
3443 begin_macro(&tokstr_buf, 2);
3444 goto redo;
3447 /* convert preprocessor tokens into C tokens */
3448 if (tok == TOK_PPNUM) {
3449 if (parse_flags & PARSE_FLAG_TOK_NUM)
3450 parse_number((char *)tokc.str.data);
3451 } else if (tok == TOK_PPSTR) {
3452 if (parse_flags & PARSE_FLAG_TOK_STR)
3453 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3457 /* push back current token and set current token to 'last_tok'. Only
3458 identifier case handled for labels. */
3459 ST_INLN void unget_tok(int last_tok)
3462 TokenString *str = tok_str_alloc();
3463 tok_str_add2(str, tok, &tokc);
3464 tok_str_add(str, 0);
3465 begin_macro(str, 1);
3466 tok = last_tok;
3469 ST_FUNC void preprocess_start(TCCState *s1)
3471 char *buf;
3473 s1->include_stack_ptr = s1->include_stack;
3474 s1->ifdef_stack_ptr = s1->ifdef_stack;
3475 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3476 pp_once++;
3477 pvtop = vtop = vstack - 1;
3478 s1->pack_stack[0] = 0;
3479 s1->pack_stack_ptr = s1->pack_stack;
3481 set_idnum('$', s1->dollars_in_identifiers ? IS_ID : 0);
3482 set_idnum('.', (parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0);
3484 buf = tcc_malloc(3 + strlen(file->filename));
3485 sprintf(buf, "\"%s\"", file->filename);
3486 tcc_define_symbol(s1, "__BASE_FILE__", buf);
3487 tcc_free(buf);
3489 if (s1->nb_cmd_include_files) {
3490 CString cstr;
3491 int i;
3492 cstr_new(&cstr);
3493 for (i = 0; i < s1->nb_cmd_include_files; i++) {
3494 cstr_cat(&cstr, "#include \"", -1);
3495 cstr_cat(&cstr, s1->cmd_include_files[i], -1);
3496 cstr_cat(&cstr, "\"\n", -1);
3498 *s1->include_stack_ptr++ = file;
3499 tcc_open_bf(s1, "<command line>", cstr.size);
3500 memcpy(file->buffer, cstr.data, cstr.size);
3501 cstr_free(&cstr);
3505 ST_FUNC void tccpp_new(TCCState *s)
3507 int i, c;
3508 const char *p, *r;
3510 /* might be used in error() before preprocess_start() */
3511 s->include_stack_ptr = s->include_stack;
3513 /* init isid table */
3514 for(i = CH_EOF; i<128; i++)
3515 set_idnum(i,
3516 is_space(i) ? IS_SPC
3517 : isid(i) ? IS_ID
3518 : isnum(i) ? IS_NUM
3519 : 0);
3521 for(i = 128; i<256; i++)
3522 set_idnum(i, IS_ID);
3524 /* init allocators */
3525 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3526 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3527 tal_new(&cstr_alloc, CSTR_TAL_LIMIT, CSTR_TAL_SIZE);
3529 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3530 cstr_new(&cstr_buf);
3531 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3532 tok_str_new(&tokstr_buf);
3533 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3535 tok_ident = TOK_IDENT;
3536 p = tcc_keywords;
3537 while (*p) {
3538 r = p;
3539 for(;;) {
3540 c = *r++;
3541 if (c == '\0')
3542 break;
3544 tok_alloc(p, r - p - 1);
3545 p = r;
3549 ST_FUNC void tccpp_delete(TCCState *s)
3551 int i, n;
3553 /* free -D and compiler defines */
3554 free_defines(NULL);
3556 /* cleanup from error/setjmp */
3557 while (macro_stack)
3558 end_macro();
3559 macro_ptr = NULL;
3561 while (file)
3562 tcc_close();
3564 /* free tokens */
3565 n = tok_ident - TOK_IDENT;
3566 for(i = 0; i < n; i++)
3567 tal_free(toksym_alloc, table_ident[i]);
3568 tcc_free(table_ident);
3569 table_ident = NULL;
3571 /* free static buffers */
3572 cstr_free(&tokcstr);
3573 cstr_free(&cstr_buf);
3574 cstr_free(&macro_equal_buf);
3575 tok_str_free_str(tokstr_buf.str);
3577 /* free allocators */
3578 tal_delete(toksym_alloc);
3579 toksym_alloc = NULL;
3580 tal_delete(tokstr_alloc);
3581 tokstr_alloc = NULL;
3582 tal_delete(cstr_alloc);
3583 cstr_alloc = NULL;
3586 /* ------------------------------------------------------------------------- */
3587 /* tcc -E [-P[1]] [-dD} support */
3589 static void tok_print(const char *msg, const int *str)
3591 FILE *fp;
3592 int t;
3593 CValue cval;
3595 fp = tcc_state->ppfp;
3596 if (!fp || !tcc_state->dflag)
3597 fp = stdout;
3599 fprintf(fp, "%s ", msg);
3600 while (str) {
3601 TOK_GET(&t, &str, &cval);
3602 if (!t)
3603 break;
3604 fprintf(fp,"%s", get_tok_str(t, &cval));
3606 fprintf(fp, "\n");
3609 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3611 int d = f->line_num - f->line_ref;
3613 if (s1->dflag & 4)
3614 return;
3616 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3618 } else if (level == 0 && f->line_ref && d < 8) {
3619 while (d > 0)
3620 fputs("\n", s1->ppfp), --d;
3621 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3622 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3623 } else {
3624 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3625 level > 0 ? " 1" : level < 0 ? " 2" : "");
3627 f->line_ref = f->line_num;
3630 static void define_print(TCCState *s1, int v)
3632 FILE *fp;
3633 Sym *s;
3635 s = define_find(v);
3636 if (NULL == s || NULL == s->d)
3637 return;
3639 fp = s1->ppfp;
3640 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3641 if (s->type.t == MACRO_FUNC) {
3642 Sym *a = s->next;
3643 fprintf(fp,"(");
3644 if (a)
3645 for (;;) {
3646 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3647 if (!(a = a->next))
3648 break;
3649 fprintf(fp,",");
3651 fprintf(fp,")");
3653 tok_print("", s->d);
3656 static void pp_debug_defines(TCCState *s1)
3658 int v, t;
3659 const char *vs;
3660 FILE *fp;
3662 t = pp_debug_tok;
3663 if (t == 0)
3664 return;
3666 file->line_num--;
3667 pp_line(s1, file, 0);
3668 file->line_ref = ++file->line_num;
3670 fp = s1->ppfp;
3671 v = pp_debug_symv;
3672 vs = get_tok_str(v, NULL);
3673 if (t == TOK_DEFINE) {
3674 define_print(s1, v);
3675 } else if (t == TOK_UNDEF) {
3676 fprintf(fp, "#undef %s\n", vs);
3677 } else if (t == TOK_push_macro) {
3678 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3679 } else if (t == TOK_pop_macro) {
3680 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3682 pp_debug_tok = 0;
3685 static void pp_debug_builtins(TCCState *s1)
3687 int v;
3688 for (v = TOK_IDENT; v < tok_ident; ++v)
3689 define_print(s1, v);
3692 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3693 static int pp_need_space(int a, int b)
3695 return 'E' == a ? '+' == b || '-' == b
3696 : '+' == a ? TOK_INC == b || '+' == b
3697 : '-' == a ? TOK_DEC == b || '-' == b
3698 : a >= TOK_IDENT ? b >= TOK_IDENT
3699 : 0;
3702 /* maybe hex like 0x1e */
3703 static int pp_check_he0xE(int t, const char *p)
3705 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3706 return 'E';
3707 return t;
3710 /* Preprocess the current file */
3711 ST_FUNC int tcc_preprocess(TCCState *s1)
3713 BufferedFile **iptr;
3714 int token_seen, spcs, level;
3715 const char *p;
3716 Sym *define_start;
3718 define_start = define_stack;
3719 preprocess_start(s1);
3721 ch = file->buf_ptr[0];
3722 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3723 parse_flags = PARSE_FLAG_PREPROCESS
3724 | (parse_flags & PARSE_FLAG_ASM_FILE)
3725 | PARSE_FLAG_LINEFEED
3726 | PARSE_FLAG_SPACES
3727 | PARSE_FLAG_ACCEPT_STRAYS
3730 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3731 capability to compile and run itself, provided all numbers are
3732 given as decimals. tcc -E -P10 will do. */
3733 if (s1->Pflag == 1 + 10)
3734 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3736 #ifdef PP_BENCH
3737 /* for PP benchmarks */
3738 do next(); while (tok != TOK_EOF);
3739 free_defines(define_start);
3740 return 0;
3741 #endif
3743 if (s1->dflag & 1) {
3744 pp_debug_builtins(s1);
3745 s1->dflag &= ~1;
3748 token_seen = TOK_LINEFEED, spcs = 0;
3749 pp_line(s1, file, 0);
3751 for (;;) {
3752 iptr = s1->include_stack_ptr;
3753 next();
3754 if (tok == TOK_EOF)
3755 break;
3756 level = s1->include_stack_ptr - iptr;
3757 if (level) {
3758 if (level > 0)
3759 pp_line(s1, *iptr, 0);
3760 pp_line(s1, file, level);
3763 if (s1->dflag) {
3764 pp_debug_defines(s1);
3765 if (s1->dflag & 4)
3766 continue;
3769 if (token_seen == TOK_LINEFEED) {
3770 if (tok == ' ') {
3771 ++spcs;
3772 continue;
3774 if (tok == TOK_LINEFEED) {
3775 spcs = 0;
3776 continue;
3778 pp_line(s1, file, 0);
3779 } else if (tok == TOK_LINEFEED) {
3780 ++file->line_ref;
3781 } else {
3782 spcs = pp_need_space(token_seen, tok);
3785 while (spcs)
3786 fputs(" ", s1->ppfp), --spcs;
3787 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
3788 token_seen = pp_check_he0xE(tok, p);;
3790 /* reset define stack, but keep -D and built-ins */
3791 free_defines(define_start);
3792 return 0;
3795 /* ------------------------------------------------------------------------- */