win64: fix va_arg
[tinycc.git] / tccpp.c
blobb8453da2c6714b2d84ee08de714381b6c128586a
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 ST_DATA TinyAlloc *toksym_alloc;
42 ST_DATA TinyAlloc *tokstr_alloc;
43 ST_DATA TinyAlloc *cstr_alloc;
45 /* ------------------------------------------------------------------------- */
47 static TokenSym *hash_ident[TOK_HASH_SIZE];
48 static char token_buf[STRING_MAX_SIZE + 1];
49 static CString cstr_buf;
50 static TokenString tokstr_buf;
51 static unsigned char isidnum_table[256 - CH_EOF];
52 static int pp_debug_tok, pp_debug_symv;
53 static void tok_print(const char *msg, const int *str);
55 /* isidnum_table flags: */
56 #define IS_SPC 1
57 #define IS_ID 2
58 #define IS_NUM 4
60 static TokenString *macro_stack;
62 static const char tcc_keywords[] =
63 #define DEF(id, str) str "\0"
64 #include "tcctok.h"
65 #undef DEF
68 /* WARNING: the content of this string encodes token numbers */
69 static const unsigned char tok_two_chars[] =
70 /* outdated -- gr
71 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
72 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
73 */{
74 '<','=', TOK_LE,
75 '>','=', TOK_GE,
76 '!','=', TOK_NE,
77 '&','&', TOK_LAND,
78 '|','|', TOK_LOR,
79 '+','+', TOK_INC,
80 '-','-', TOK_DEC,
81 '=','=', TOK_EQ,
82 '<','<', TOK_SHL,
83 '>','>', TOK_SAR,
84 '+','=', TOK_A_ADD,
85 '-','=', TOK_A_SUB,
86 '*','=', TOK_A_MUL,
87 '/','=', TOK_A_DIV,
88 '%','=', TOK_A_MOD,
89 '&','=', TOK_A_AND,
90 '^','=', TOK_A_XOR,
91 '|','=', TOK_A_OR,
92 '-','>', TOK_ARROW,
93 '.','.', 0xa8, // C++ token ?
94 '#','#', TOK_TWOSHARPS,
98 static void next_nomacro_spc(void);
100 ST_FUNC void skip(int c)
102 if (tok != c)
103 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
104 next();
107 ST_FUNC void expect(const char *msg)
109 tcc_error("%s expected", msg);
112 ST_FUNC void begin_macro(TokenString *str, int alloc)
114 str->alloc = alloc;
115 str->prev = macro_stack;
116 str->prev_ptr = macro_ptr;
117 macro_ptr = str->str;
118 macro_stack = str;
121 ST_FUNC void end_macro(void)
123 TokenString *str = macro_stack;
124 macro_stack = str->prev;
125 macro_ptr = str->prev_ptr;
126 if (str->alloc == 2) {
127 str->alloc = 3; /* just mark as finished */
128 } else {
129 tok_str_free(str->str);
130 if (str->alloc == 1)
131 tcc_free(str);
135 ST_FUNC char *trimfront(char *p)
137 while (*p && (unsigned char)*p <= ' ')
138 ++p;
139 return p;
142 ST_FUNC char *trimback(char *a, char *e)
144 while (e > a && (unsigned char)e[-1] <= ' ')
145 --e;
146 *e = 0;;
147 return a;
150 /* ------------------------------------------------------------------------- */
151 /* Custom allocator for tiny objects */
153 ST_FUNC TinyAlloc *tal_new(TinyAlloc **pal, size_t limit, size_t size)
155 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
156 al->p = al->buffer = tcc_malloc(size);
157 al->limit = limit;
158 al->size = size;
159 if (pal) *pal = al;
160 return al;
163 ST_FUNC void tal_delete(TinyAlloc *al)
165 TinyAlloc *next;
167 tail_call:
168 if (!al)
169 return;
170 #ifdef TAL_INFO
171 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
172 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
173 (al->peak_p - al->buffer) * 100.0 / al->size);
174 #endif
175 #ifdef TAL_DEBUG
176 if (al->nb_allocs > 0) {
177 fprintf(stderr, "TAL_DEBUG: mem leak %d chunks (limit= %d)\n",
178 al->nb_allocs, al->limit);
179 uint8_t *p = al->buffer;
180 while (p < al->p) {
181 tal_header_t *header = (tal_header_t *)p;
182 if (header->line_num > 0) {
183 fprintf(stderr, " file %s, line %u: %u bytes\n",
184 header->file_name, header->line_num, header->size);
186 p += header->size + sizeof(tal_header_t);
189 #endif
190 next = al->next;
191 tcc_free(al->buffer);
192 tcc_free(al);
193 al = next;
194 goto tail_call;
197 ST_FUNC void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
199 if (!p)
200 return;
201 tail_call:
202 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
203 #ifdef TAL_DEBUG
204 tal_header_t *header = (((tal_header_t *)p) - 1);
205 if (header->line_num < 0) {
206 fprintf(stderr, "TAL_DEBUG: file %s, line %u double frees chunk from\n",
207 file, line);
208 fprintf(stderr, " file %s, line %u: %u bytes\n",
209 header->file_name, -header->line_num, header->size);
210 } else
211 header->line_num = -header->line_num;
212 #endif
213 al->nb_allocs--;
214 if (!al->nb_allocs)
215 al->p = al->buffer;
216 } else if (al->next) {
217 al = al->next;
218 goto tail_call;
220 else
221 tcc_free(p);
224 ST_FUNC void *tal_realloc_impl(TinyAlloc **pal, void *p, size_t size TAL_DEBUG_PARAMS)
226 tal_header_t *header;
227 void *ret;
228 int is_own;
229 size_t adj_size = (size + 3) & -4;
230 TinyAlloc *al = *pal;
232 tail_call:
233 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
234 if ((!p || is_own) && size <= al->limit) {
235 if (al->p + adj_size + sizeof(tal_header_t) < al->buffer + al->size) {
236 header = (tal_header_t *)al->p;
237 header->size = adj_size;
238 #ifdef TAL_DEBUG
239 int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
240 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
241 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
242 header->line_num = line;
243 #endif
244 ret = al->p + sizeof(tal_header_t);
245 al->p += adj_size + sizeof(tal_header_t);
246 if (is_own) {
247 header = (((tal_header_t *)p) - 1);
248 memcpy(ret, p, header->size);
249 #ifdef TAL_DEBUG
250 header->line_num = -header->line_num;
251 #endif
252 } else {
253 al->nb_allocs++;
255 #ifdef TAL_INFO
256 if (al->nb_peak < al->nb_allocs)
257 al->nb_peak = al->nb_allocs;
258 if (al->peak_p < al->p)
259 al->peak_p = al->p;
260 al->nb_total++;
261 #endif
262 return ret;
263 } else if (is_own) {
264 al->nb_allocs--;
265 ret = tal_realloc(*pal, 0, size);
266 header = (((tal_header_t *)p) - 1);
267 memcpy(ret, p, header->size);
268 #ifdef TAL_DEBUG
269 header->line_num = -header->line_num;
270 #endif
271 return ret;
273 if (al->next) {
274 al = al->next;
275 } else {
276 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
278 al = tal_new(pal, next->limit, next->size * 2);
279 al->next = next;
280 bottom->top = al;
282 goto tail_call;
284 if (is_own) {
285 al->nb_allocs--;
286 ret = tcc_malloc(size);
287 header = (((tal_header_t *)p) - 1);
288 memcpy(ret, p, header->size);
289 #ifdef TAL_DEBUG
290 header->line_num = -header->line_num;
291 #endif
292 } else if (al->next) {
293 al = al->next;
294 goto tail_call;
295 } else
296 ret = tcc_realloc(p, size);
297 #ifdef TAL_INFO
298 al->nb_missed++;
299 #endif
300 return ret;
303 /* ------------------------------------------------------------------------- */
304 /* CString handling */
305 static void cstr_realloc(CString *cstr, int new_size)
307 int size;
308 void *data;
310 size = cstr->size_allocated;
311 if (size < 8)
312 size = 8; /* no need to allocate a too small first string */
313 while (size < new_size)
314 size = size * 2;
315 data = tal_realloc(cstr_alloc, cstr->data_allocated, size);
316 cstr->data_allocated = data;
317 cstr->size_allocated = size;
318 cstr->data = data;
321 /* add a byte */
322 ST_FUNC void cstr_ccat(CString *cstr, int ch)
324 int size;
325 size = cstr->size + 1;
326 if (size > cstr->size_allocated)
327 cstr_realloc(cstr, size);
328 ((unsigned char *)cstr->data)[size - 1] = ch;
329 cstr->size = size;
332 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
334 int size;
335 if (len <= 0)
336 len = strlen(str) + 1 + len;
337 size = cstr->size + len;
338 if (size > cstr->size_allocated)
339 cstr_realloc(cstr, size);
340 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
341 cstr->size = size;
344 /* add a wide char */
345 ST_FUNC void cstr_wccat(CString *cstr, int ch)
347 int size;
348 size = cstr->size + sizeof(nwchar_t);
349 if (size > cstr->size_allocated)
350 cstr_realloc(cstr, size);
351 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
352 cstr->size = size;
355 ST_FUNC void cstr_new(CString *cstr)
357 memset(cstr, 0, sizeof(CString));
360 /* free string and reset it to NULL */
361 ST_FUNC void cstr_free(CString *cstr)
363 tal_free(cstr_alloc, cstr->data_allocated);
364 cstr_new(cstr);
367 /* reset string to empty */
368 ST_FUNC void cstr_reset(CString *cstr)
370 cstr->size = 0;
373 /* XXX: unicode ? */
374 static void add_char(CString *cstr, int c)
376 if (c == '\'' || c == '\"' || c == '\\') {
377 /* XXX: could be more precise if char or string */
378 cstr_ccat(cstr, '\\');
380 if (c >= 32 && c <= 126) {
381 cstr_ccat(cstr, c);
382 } else {
383 cstr_ccat(cstr, '\\');
384 if (c == '\n') {
385 cstr_ccat(cstr, 'n');
386 } else {
387 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
388 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
389 cstr_ccat(cstr, '0' + (c & 7));
394 /* ------------------------------------------------------------------------- */
395 /* allocate a new token */
396 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
398 TokenSym *ts, **ptable;
399 int i;
401 if (tok_ident >= SYM_FIRST_ANOM)
402 tcc_error("memory full (symbols)");
404 /* expand token table if needed */
405 i = tok_ident - TOK_IDENT;
406 if ((i % TOK_ALLOC_INCR) == 0) {
407 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
408 table_ident = ptable;
411 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
412 table_ident[i] = ts;
413 ts->tok = tok_ident++;
414 ts->sym_define = NULL;
415 ts->sym_label = NULL;
416 ts->sym_struct = NULL;
417 ts->sym_identifier = NULL;
418 ts->len = len;
419 ts->hash_next = NULL;
420 memcpy(ts->str, str, len);
421 ts->str[len] = '\0';
422 *pts = ts;
423 return ts;
426 #define TOK_HASH_INIT 1
427 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
430 /* find a token and add it if not found */
431 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
433 TokenSym *ts, **pts;
434 int i;
435 unsigned int h;
437 h = TOK_HASH_INIT;
438 for(i=0;i<len;i++)
439 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
440 h &= (TOK_HASH_SIZE - 1);
442 pts = &hash_ident[h];
443 for(;;) {
444 ts = *pts;
445 if (!ts)
446 break;
447 if (ts->len == len && !memcmp(ts->str, str, len))
448 return ts;
449 pts = &(ts->hash_next);
451 return tok_alloc_new(pts, str, len);
454 /* XXX: buffer overflow */
455 /* XXX: float tokens */
456 ST_FUNC const char *get_tok_str(int v, CValue *cv)
458 char *p;
459 int i, len;
461 cstr_reset(&cstr_buf);
462 p = cstr_buf.data;
464 switch(v) {
465 case TOK_CINT:
466 case TOK_CUINT:
467 case TOK_CLLONG:
468 case TOK_CULLONG:
469 /* XXX: not quite exact, but only useful for testing */
470 #ifdef _WIN32
471 sprintf(p, "%u", (unsigned)cv->i);
472 #else
473 sprintf(p, "%llu", (unsigned long long)cv->i);
474 #endif
475 break;
476 case TOK_LCHAR:
477 cstr_ccat(&cstr_buf, 'L');
478 case TOK_CCHAR:
479 cstr_ccat(&cstr_buf, '\'');
480 add_char(&cstr_buf, cv->i);
481 cstr_ccat(&cstr_buf, '\'');
482 cstr_ccat(&cstr_buf, '\0');
483 break;
484 case TOK_PPNUM:
485 case TOK_PPSTR:
486 return (char*)cv->str.data;
487 case TOK_LSTR:
488 cstr_ccat(&cstr_buf, 'L');
489 case TOK_STR:
490 cstr_ccat(&cstr_buf, '\"');
491 if (v == TOK_STR) {
492 len = cv->str.size - 1;
493 for(i=0;i<len;i++)
494 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
495 } else {
496 len = (cv->str.size / sizeof(nwchar_t)) - 1;
497 for(i=0;i<len;i++)
498 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
500 cstr_ccat(&cstr_buf, '\"');
501 cstr_ccat(&cstr_buf, '\0');
502 break;
504 case TOK_CFLOAT:
505 cstr_cat(&cstr_buf, "<float>", 0);
506 break;
507 case TOK_CDOUBLE:
508 cstr_cat(&cstr_buf, "<double>", 0);
509 break;
510 case TOK_CLDOUBLE:
511 cstr_cat(&cstr_buf, "<long double>", 0);
512 break;
513 case TOK_LINENUM:
514 cstr_cat(&cstr_buf, "<linenumber>", 0);
515 break;
517 /* above tokens have value, the ones below don't */
519 case TOK_LT:
520 v = '<';
521 goto addv;
522 case TOK_GT:
523 v = '>';
524 goto addv;
525 case TOK_DOTS:
526 return strcpy(p, "...");
527 case TOK_A_SHL:
528 return strcpy(p, "<<=");
529 case TOK_A_SAR:
530 return strcpy(p, ">>=");
531 default:
532 if (v < TOK_IDENT) {
533 /* search in two bytes table */
534 const unsigned char *q = tok_two_chars;
535 while (*q) {
536 if (q[2] == v) {
537 *p++ = q[0];
538 *p++ = q[1];
539 *p = '\0';
540 return cstr_buf.data;
542 q += 3;
544 if (v >= 127) {
545 sprintf(cstr_buf.data, "<%02x>", v);
546 return cstr_buf.data;
548 addv:
549 *p++ = v;
550 *p = '\0';
551 } else if (v < tok_ident) {
552 return table_ident[v - TOK_IDENT]->str;
553 } else if (v >= SYM_FIRST_ANOM) {
554 /* special name for anonymous symbol */
555 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
556 } else {
557 /* should never happen */
558 return NULL;
560 break;
562 return cstr_buf.data;
565 /* return the current character, handling end of block if necessary
566 (but not stray) */
567 ST_FUNC int handle_eob(void)
569 BufferedFile *bf = file;
570 int len;
572 /* only tries to read if really end of buffer */
573 if (bf->buf_ptr >= bf->buf_end) {
574 if (bf->fd != -1) {
575 #if defined(PARSE_DEBUG)
576 len = 1;
577 #else
578 len = IO_BUF_SIZE;
579 #endif
580 len = read(bf->fd, bf->buffer, len);
581 if (len < 0)
582 len = 0;
583 } else {
584 len = 0;
586 total_bytes += len;
587 bf->buf_ptr = bf->buffer;
588 bf->buf_end = bf->buffer + len;
589 *bf->buf_end = CH_EOB;
591 if (bf->buf_ptr < bf->buf_end) {
592 return bf->buf_ptr[0];
593 } else {
594 bf->buf_ptr = bf->buf_end;
595 return CH_EOF;
599 /* read next char from current input file and handle end of input buffer */
600 ST_INLN void inp(void)
602 ch = *(++(file->buf_ptr));
603 /* end of buffer/file handling */
604 if (ch == CH_EOB)
605 ch = handle_eob();
608 /* handle '\[\r]\n' */
609 static int handle_stray_noerror(void)
611 while (ch == '\\') {
612 inp();
613 if (ch == '\n') {
614 file->line_num++;
615 inp();
616 } else if (ch == '\r') {
617 inp();
618 if (ch != '\n')
619 goto fail;
620 file->line_num++;
621 inp();
622 } else {
623 fail:
624 return 1;
627 return 0;
630 static void handle_stray(void)
632 if (handle_stray_noerror())
633 tcc_error("stray '\\' in program");
636 /* skip the stray and handle the \\n case. Output an error if
637 incorrect char after the stray */
638 static int handle_stray1(uint8_t *p)
640 int c;
642 file->buf_ptr = p;
643 if (p >= file->buf_end) {
644 c = handle_eob();
645 if (c != '\\')
646 return c;
647 p = file->buf_ptr;
649 ch = *p;
650 if (handle_stray_noerror()) {
651 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
652 tcc_error("stray '\\' in program");
653 *--file->buf_ptr = '\\';
655 p = file->buf_ptr;
656 c = *p;
657 return c;
660 /* handle just the EOB case, but not stray */
661 #define PEEKC_EOB(c, p)\
663 p++;\
664 c = *p;\
665 if (c == '\\') {\
666 file->buf_ptr = p;\
667 c = handle_eob();\
668 p = file->buf_ptr;\
672 /* handle the complicated stray case */
673 #define PEEKC(c, p)\
675 p++;\
676 c = *p;\
677 if (c == '\\') {\
678 c = handle_stray1(p);\
679 p = file->buf_ptr;\
683 /* input with '\[\r]\n' handling. Note that this function cannot
684 handle other characters after '\', so you cannot call it inside
685 strings or comments */
686 ST_FUNC void minp(void)
688 inp();
689 if (ch == '\\')
690 handle_stray();
693 /* single line C++ comments */
694 static uint8_t *parse_line_comment(uint8_t *p)
696 int c;
698 p++;
699 for(;;) {
700 c = *p;
701 redo:
702 if (c == '\n' || c == CH_EOF) {
703 break;
704 } else if (c == '\\') {
705 file->buf_ptr = p;
706 c = handle_eob();
707 p = file->buf_ptr;
708 if (c == '\\') {
709 PEEKC_EOB(c, p);
710 if (c == '\n') {
711 file->line_num++;
712 PEEKC_EOB(c, p);
713 } else if (c == '\r') {
714 PEEKC_EOB(c, p);
715 if (c == '\n') {
716 file->line_num++;
717 PEEKC_EOB(c, p);
720 } else {
721 goto redo;
723 } else {
724 p++;
727 return p;
730 /* C comments */
731 ST_FUNC uint8_t *parse_comment(uint8_t *p)
733 int c;
735 p++;
736 for(;;) {
737 /* fast skip loop */
738 for(;;) {
739 c = *p;
740 if (c == '\n' || c == '*' || c == '\\')
741 break;
742 p++;
743 c = *p;
744 if (c == '\n' || c == '*' || c == '\\')
745 break;
746 p++;
748 /* now we can handle all the cases */
749 if (c == '\n') {
750 file->line_num++;
751 p++;
752 } else if (c == '*') {
753 p++;
754 for(;;) {
755 c = *p;
756 if (c == '*') {
757 p++;
758 } else if (c == '/') {
759 goto end_of_comment;
760 } else if (c == '\\') {
761 file->buf_ptr = p;
762 c = handle_eob();
763 p = file->buf_ptr;
764 if (c == CH_EOF)
765 tcc_error("unexpected end of file in comment");
766 if (c == '\\') {
767 /* skip '\[\r]\n', otherwise just skip the stray */
768 while (c == '\\') {
769 PEEKC_EOB(c, p);
770 if (c == '\n') {
771 file->line_num++;
772 PEEKC_EOB(c, p);
773 } else if (c == '\r') {
774 PEEKC_EOB(c, p);
775 if (c == '\n') {
776 file->line_num++;
777 PEEKC_EOB(c, p);
779 } else {
780 goto after_star;
784 } else {
785 break;
788 after_star: ;
789 } else {
790 /* stray, eob or eof */
791 file->buf_ptr = p;
792 c = handle_eob();
793 p = file->buf_ptr;
794 if (c == CH_EOF) {
795 tcc_error("unexpected end of file in comment");
796 } else if (c == '\\') {
797 p++;
801 end_of_comment:
802 p++;
803 return p;
806 #define cinp minp
808 static inline void skip_spaces(void)
810 while (isidnum_table[ch - CH_EOF] & IS_SPC)
811 cinp();
814 static inline int check_space(int t, int *spc)
816 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
817 if (*spc)
818 return 1;
819 *spc = 1;
820 } else
821 *spc = 0;
822 return 0;
825 /* parse a string without interpreting escapes */
826 static uint8_t *parse_pp_string(uint8_t *p,
827 int sep, CString *str)
829 int c;
830 p++;
831 for(;;) {
832 c = *p;
833 if (c == sep) {
834 break;
835 } else if (c == '\\') {
836 file->buf_ptr = p;
837 c = handle_eob();
838 p = file->buf_ptr;
839 if (c == CH_EOF) {
840 unterminated_string:
841 /* XXX: indicate line number of start of string */
842 tcc_error("missing terminating %c character", sep);
843 } else if (c == '\\') {
844 /* escape : just skip \[\r]\n */
845 PEEKC_EOB(c, p);
846 if (c == '\n') {
847 file->line_num++;
848 p++;
849 } else if (c == '\r') {
850 PEEKC_EOB(c, p);
851 if (c != '\n')
852 expect("'\n' after '\r'");
853 file->line_num++;
854 p++;
855 } else if (c == CH_EOF) {
856 goto unterminated_string;
857 } else {
858 if (str) {
859 cstr_ccat(str, '\\');
860 cstr_ccat(str, c);
862 p++;
865 } else if (c == '\n') {
866 file->line_num++;
867 goto add_char;
868 } else if (c == '\r') {
869 PEEKC_EOB(c, p);
870 if (c != '\n') {
871 if (str)
872 cstr_ccat(str, '\r');
873 } else {
874 file->line_num++;
875 goto add_char;
877 } else {
878 add_char:
879 if (str)
880 cstr_ccat(str, c);
881 p++;
884 p++;
885 return p;
888 /* skip block of text until #else, #elif or #endif. skip also pairs of
889 #if/#endif */
890 static void preprocess_skip(void)
892 int a, start_of_line, c, in_warn_or_error;
893 uint8_t *p;
895 p = file->buf_ptr;
896 a = 0;
897 redo_start:
898 start_of_line = 1;
899 in_warn_or_error = 0;
900 for(;;) {
901 redo_no_start:
902 c = *p;
903 switch(c) {
904 case ' ':
905 case '\t':
906 case '\f':
907 case '\v':
908 case '\r':
909 p++;
910 goto redo_no_start;
911 case '\n':
912 file->line_num++;
913 p++;
914 goto redo_start;
915 case '\\':
916 file->buf_ptr = p;
917 c = handle_eob();
918 if (c == CH_EOF) {
919 expect("#endif");
920 } else if (c == '\\') {
921 ch = file->buf_ptr[0];
922 handle_stray_noerror();
924 p = file->buf_ptr;
925 goto redo_no_start;
926 /* skip strings */
927 case '\"':
928 case '\'':
929 if (in_warn_or_error)
930 goto _default;
931 p = parse_pp_string(p, c, NULL);
932 break;
933 /* skip comments */
934 case '/':
935 if (in_warn_or_error)
936 goto _default;
937 file->buf_ptr = p;
938 ch = *p;
939 minp();
940 p = file->buf_ptr;
941 if (ch == '*') {
942 p = parse_comment(p);
943 } else if (ch == '/') {
944 p = parse_line_comment(p);
946 break;
947 case '#':
948 p++;
949 if (start_of_line) {
950 file->buf_ptr = p;
951 next_nomacro();
952 p = file->buf_ptr;
953 if (a == 0 &&
954 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
955 goto the_end;
956 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
957 a++;
958 else if (tok == TOK_ENDIF)
959 a--;
960 else if( tok == TOK_ERROR || tok == TOK_WARNING)
961 in_warn_or_error = 1;
962 else if (tok == TOK_LINEFEED)
963 goto redo_start;
964 else if (parse_flags & PARSE_FLAG_ASM_FILE)
965 p = parse_line_comment(p);
966 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
967 p = parse_line_comment(p);
968 break;
969 _default:
970 default:
971 p++;
972 break;
974 start_of_line = 0;
976 the_end: ;
977 file->buf_ptr = p;
980 /* ParseState handling */
982 /* XXX: currently, no include file info is stored. Thus, we cannot display
983 accurate messages if the function or data definition spans multiple
984 files */
986 /* save current parse state in 's' */
987 ST_FUNC void save_parse_state(ParseState *s)
989 s->line_num = file->line_num;
990 s->macro_ptr = macro_ptr;
991 s->tok = tok;
992 s->tokc = tokc;
995 /* restore parse state from 's' */
996 ST_FUNC void restore_parse_state(ParseState *s)
998 file->line_num = s->line_num;
999 macro_ptr = s->macro_ptr;
1000 tok = s->tok;
1001 tokc = s->tokc;
1004 /* return the number of additional 'ints' necessary to store the
1005 token */
1006 static inline int tok_size(const int *p)
1008 switch(*p) {
1009 /* 4 bytes */
1010 case TOK_CINT:
1011 case TOK_CUINT:
1012 case TOK_CCHAR:
1013 case TOK_LCHAR:
1014 case TOK_CFLOAT:
1015 case TOK_LINENUM:
1016 return 1 + 1;
1017 case TOK_STR:
1018 case TOK_LSTR:
1019 case TOK_PPNUM:
1020 case TOK_PPSTR:
1021 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1022 case TOK_CDOUBLE:
1023 case TOK_CLLONG:
1024 case TOK_CULLONG:
1025 return 1 + 2;
1026 case TOK_CLDOUBLE:
1027 return 1 + LDOUBLE_SIZE / 4;
1028 default:
1029 return 1 + 0;
1033 /* token string handling */
1035 ST_INLN void tok_str_new(TokenString *s)
1037 s->str = NULL;
1038 s->len = 0;
1039 s->allocated_len = 0;
1040 s->last_line_num = -1;
1043 ST_FUNC int *tok_str_dup(TokenString *s)
1045 int *str;
1047 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1048 memcpy(str, s->str, s->len * sizeof(int));
1049 return str;
1052 ST_FUNC void tok_str_free(int *str)
1054 tal_free(tokstr_alloc, str);
1057 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1059 int *str, size;
1061 size = s->allocated_len;
1062 if (size < 16)
1063 size = 16;
1064 while (size < new_size)
1065 size = size * 2;
1066 TCC_ASSERT((size & (size -1)) == 0);
1067 if (size > s->allocated_len) {
1068 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1069 s->allocated_len = size;
1070 s->str = str;
1072 return s->str;
1075 ST_FUNC void tok_str_add(TokenString *s, int t)
1077 int len, *str;
1079 len = s->len;
1080 str = s->str;
1081 if (len >= s->allocated_len)
1082 str = tok_str_realloc(s, len + 1);
1083 str[len++] = t;
1084 s->len = len;
1087 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1089 int len, *str;
1091 len = s->len;
1092 str = s->str;
1094 /* allocate space for worst case */
1095 if (len + TOK_MAX_SIZE >= s->allocated_len)
1096 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1097 str[len++] = t;
1098 switch(t) {
1099 case TOK_CINT:
1100 case TOK_CUINT:
1101 case TOK_CCHAR:
1102 case TOK_LCHAR:
1103 case TOK_CFLOAT:
1104 case TOK_LINENUM:
1105 str[len++] = cv->tab[0];
1106 break;
1107 case TOK_PPNUM:
1108 case TOK_PPSTR:
1109 case TOK_STR:
1110 case TOK_LSTR:
1112 /* Insert the string into the int array. */
1113 size_t nb_words =
1114 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1115 if (len + nb_words >= s->allocated_len)
1116 str = tok_str_realloc(s, len + nb_words + 1);
1117 str[len] = cv->str.size;
1118 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1119 len += nb_words;
1121 break;
1122 case TOK_CDOUBLE:
1123 case TOK_CLLONG:
1124 case TOK_CULLONG:
1125 #if LDOUBLE_SIZE == 8
1126 case TOK_CLDOUBLE:
1127 #endif
1128 str[len++] = cv->tab[0];
1129 str[len++] = cv->tab[1];
1130 break;
1131 #if LDOUBLE_SIZE == 12
1132 case TOK_CLDOUBLE:
1133 str[len++] = cv->tab[0];
1134 str[len++] = cv->tab[1];
1135 str[len++] = cv->tab[2];
1136 #elif LDOUBLE_SIZE == 16
1137 case TOK_CLDOUBLE:
1138 str[len++] = cv->tab[0];
1139 str[len++] = cv->tab[1];
1140 str[len++] = cv->tab[2];
1141 str[len++] = cv->tab[3];
1142 #elif LDOUBLE_SIZE != 8
1143 #error add long double size support
1144 #endif
1145 break;
1146 default:
1147 break;
1149 s->len = len;
1152 /* add the current parse token in token string 's' */
1153 ST_FUNC void tok_str_add_tok(TokenString *s)
1155 CValue cval;
1157 /* save line number info */
1158 if (file->line_num != s->last_line_num) {
1159 s->last_line_num = file->line_num;
1160 cval.i = s->last_line_num;
1161 tok_str_add2(s, TOK_LINENUM, &cval);
1163 tok_str_add2(s, tok, &tokc);
1166 /* get a token from an integer array and increment pointer
1167 accordingly. we code it as a macro to avoid pointer aliasing. */
1168 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
1170 const int *p = *pp;
1171 int n, *tab;
1173 tab = cv->tab;
1174 switch(*t = *p++) {
1175 case TOK_CINT:
1176 case TOK_CUINT:
1177 case TOK_CCHAR:
1178 case TOK_LCHAR:
1179 case TOK_CFLOAT:
1180 case TOK_LINENUM:
1181 tab[0] = *p++;
1182 break;
1183 case TOK_STR:
1184 case TOK_LSTR:
1185 case TOK_PPNUM:
1186 case TOK_PPSTR:
1187 cv->str.size = *p++;
1188 cv->str.data = p;
1189 cv->str.data_allocated = 0;
1190 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1191 break;
1192 case TOK_CDOUBLE:
1193 case TOK_CLLONG:
1194 case TOK_CULLONG:
1195 n = 2;
1196 goto copy;
1197 case TOK_CLDOUBLE:
1198 #if LDOUBLE_SIZE == 16
1199 n = 4;
1200 #elif LDOUBLE_SIZE == 12
1201 n = 3;
1202 #elif LDOUBLE_SIZE == 8
1203 n = 2;
1204 #else
1205 # error add long double size support
1206 #endif
1207 copy:
1209 *tab++ = *p++;
1210 while (--n);
1211 break;
1212 default:
1213 break;
1215 *pp = p;
1218 /* Calling this function is expensive, but it is not possible
1219 to read a token string backwards. */
1220 static int tok_last(const int *str0, const int *str1)
1222 const int *str = str0;
1223 int tok = 0;
1224 CValue cval;
1226 while (str < str1)
1227 TOK_GET(&tok, &str, &cval);
1228 return tok;
1231 static int macro_is_equal(const int *a, const int *b)
1233 CValue cv;
1234 int t;
1236 if (!a || !b)
1237 return 1;
1239 while (*a && *b) {
1240 /* first time preallocate static cstr_buf, next time only reset position to start */
1241 cstr_reset(&cstr_buf);
1242 TOK_GET(&t, &a, &cv);
1243 cstr_cat(&cstr_buf, get_tok_str(t, &cv), 0);
1244 TOK_GET(&t, &b, &cv);
1245 if (strcmp(cstr_buf.data, get_tok_str(t, &cv)))
1246 return 0;
1248 return !(*a || *b);
1251 /* defines handling */
1252 ST_INLN void define_push(int v, int macro_type, TokenString *str, Sym *first_arg)
1254 Sym *s, *o;
1256 o = define_find(v);
1257 s = sym_push2(&define_stack, v, macro_type, 0);
1258 s->d = str ? tok_str_dup(str) : NULL;
1259 s->next = first_arg;
1260 table_ident[v - TOK_IDENT]->sym_define = s;
1262 if (o && !macro_is_equal(o->d, s->d))
1263 tcc_warning("%s redefined", get_tok_str(v, NULL));
1266 /* undefined a define symbol. Its name is just set to zero */
1267 ST_FUNC void define_undef(Sym *s)
1269 int v = s->v;
1270 if (v >= TOK_IDENT && v < tok_ident)
1271 table_ident[v - TOK_IDENT]->sym_define = NULL;
1274 ST_INLN Sym *define_find(int v)
1276 v -= TOK_IDENT;
1277 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1278 return NULL;
1279 return table_ident[v]->sym_define;
1282 /* free define stack until top reaches 'b' */
1283 ST_FUNC void free_defines(Sym *b)
1285 Sym *top, *top1;
1286 int v;
1288 top = define_stack;
1289 while (top != b) {
1290 top1 = top->prev;
1291 /* do not free args or predefined defines */
1292 if (top->d)
1293 tok_str_free(top->d);
1294 v = top->v;
1295 if (v >= TOK_IDENT && v < tok_ident)
1296 table_ident[v - TOK_IDENT]->sym_define = NULL;
1297 sym_free(top);
1298 top = top1;
1300 define_stack = b;
1303 /* label lookup */
1304 ST_FUNC Sym *label_find(int v)
1306 v -= TOK_IDENT;
1307 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1308 return NULL;
1309 return table_ident[v]->sym_label;
1312 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1314 Sym *s, **ps;
1315 s = sym_push2(ptop, v, 0, 0);
1316 s->r = flags;
1317 ps = &table_ident[v - TOK_IDENT]->sym_label;
1318 if (ptop == &global_label_stack) {
1319 /* modify the top most local identifier, so that
1320 sym_identifier will point to 's' when popped */
1321 while (*ps != NULL)
1322 ps = &(*ps)->prev_tok;
1324 s->prev_tok = *ps;
1325 *ps = s;
1326 return s;
1329 /* pop labels until element last is reached. Look if any labels are
1330 undefined. Define symbols if '&&label' was used. */
1331 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1333 Sym *s, *s1;
1334 for(s = *ptop; s != slast; s = s1) {
1335 s1 = s->prev;
1336 if (s->r == LABEL_DECLARED) {
1337 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1338 } else if (s->r == LABEL_FORWARD) {
1339 tcc_error("label '%s' used but not defined",
1340 get_tok_str(s->v, NULL));
1341 } else {
1342 if (s->c) {
1343 /* define corresponding symbol. A size of
1344 1 is put. */
1345 put_extern_sym(s, cur_text_section, s->jnext, 1);
1348 /* remove label */
1349 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1350 sym_free(s);
1352 *ptop = slast;
1355 /* eval an expression for #if/#elif */
1356 static int expr_preprocess(void)
1358 int c, t;
1359 TokenString str;
1361 tok_str_new(&str);
1362 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1363 next(); /* do macro subst */
1364 if (tok == TOK_DEFINED) {
1365 next_nomacro();
1366 t = tok;
1367 if (t == '(')
1368 next_nomacro();
1369 c = define_find(tok) != 0;
1370 if (t == '(')
1371 next_nomacro();
1372 tok = TOK_CINT;
1373 tokc.i = c;
1374 } else if (tok >= TOK_IDENT) {
1375 /* if undefined macro */
1376 tok = TOK_CINT;
1377 tokc.i = 0;
1379 tok_str_add_tok(&str);
1381 tok_str_add(&str, -1); /* simulate end of file */
1382 tok_str_add(&str, 0);
1383 /* now evaluate C constant expression */
1384 begin_macro(&str, 0);
1385 next();
1386 c = expr_const();
1387 end_macro();
1388 return c != 0;
1392 /* parse after #define */
1393 ST_FUNC void parse_define(void)
1395 Sym *s, *first, **ps;
1396 int v, t, varg, is_vaargs, spc;
1397 int saved_parse_flags = parse_flags;
1399 v = tok;
1400 if (v < TOK_IDENT)
1401 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1402 /* XXX: should check if same macro (ANSI) */
1403 first = NULL;
1404 t = MACRO_OBJ;
1405 /* '(' must be just after macro definition for MACRO_FUNC */
1406 parse_flags |= PARSE_FLAG_SPACES;
1407 next_nomacro_spc();
1408 if (tok == '(') {
1409 /* must be able to parse TOK_DOTS (in asm mode '.' can be part of identifier) */
1410 parse_flags &= ~PARSE_FLAG_ASM_FILE;
1411 isidnum_table['.' - CH_EOF] = 0;
1412 next_nomacro();
1413 ps = &first;
1414 if (tok != ')') for (;;) {
1415 varg = tok;
1416 next_nomacro();
1417 is_vaargs = 0;
1418 if (varg == TOK_DOTS) {
1419 varg = TOK___VA_ARGS__;
1420 is_vaargs = 1;
1421 } else if (tok == TOK_DOTS && gnu_ext) {
1422 is_vaargs = 1;
1423 next_nomacro();
1425 if (varg < TOK_IDENT)
1426 bad_list:
1427 tcc_error("bad macro parameter list");
1428 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1429 *ps = s;
1430 ps = &s->next;
1431 if (tok == ')')
1432 break;
1433 if (tok != ',' || is_vaargs)
1434 goto bad_list;
1435 next_nomacro();
1437 next_nomacro_spc();
1438 t = MACRO_FUNC;
1439 parse_flags |= (saved_parse_flags & PARSE_FLAG_ASM_FILE);
1440 isidnum_table['.' - CH_EOF] =
1441 (parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0;
1444 tokstr_buf.len = 0;
1445 spc = 2;
1446 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1447 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1448 /* remove spaces around ## and after '#' */
1449 if (TOK_TWOSHARPS == tok) {
1450 if (2 == spc)
1451 goto bad_twosharp;
1452 if (1 == spc)
1453 --tokstr_buf.len;
1454 spc = 3;
1455 } else if ('#' == tok) {
1456 spc = 4;
1457 } else if (check_space(tok, &spc)) {
1458 goto skip;
1460 tok_str_add2(&tokstr_buf, tok, &tokc);
1461 skip:
1462 next_nomacro_spc();
1465 parse_flags = saved_parse_flags;
1466 if (spc == 1)
1467 --tokstr_buf.len; /* remove trailing space */
1468 tok_str_add(&tokstr_buf, 0);
1469 if (3 == spc)
1470 bad_twosharp:
1471 tcc_error("'##' cannot appear at either end of macro");
1472 define_push(v, t, &tokstr_buf, first);
1475 static inline int hash_cached_include(const char *filename)
1477 const unsigned char *s;
1478 unsigned int h;
1480 h = TOK_HASH_INIT;
1481 s = (unsigned char *) filename;
1482 while (*s) {
1483 h = TOK_HASH_FUNC(h, *s);
1484 s++;
1486 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1487 return h;
1490 static CachedInclude *search_cached_include(TCCState *s1, const char *filename)
1492 CachedInclude *e;
1493 int i, h;
1494 h = hash_cached_include(filename);
1495 i = s1->cached_includes_hash[h];
1496 for(;;) {
1497 if (i == 0)
1498 break;
1499 e = s1->cached_includes[i - 1];
1500 if (0 == PATHCMP(e->filename, filename))
1501 return e;
1502 i = e->hash_next;
1504 return NULL;
1507 static inline void add_cached_include(TCCState *s1, const char *filename, int ifndef_macro)
1509 CachedInclude *e;
1510 int h;
1512 if (search_cached_include(s1, filename))
1513 return;
1514 #ifdef INC_DEBUG
1515 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
1516 #endif
1517 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1518 strcpy(e->filename, filename);
1519 e->ifndef_macro = ifndef_macro;
1520 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1521 /* add in hash table */
1522 h = hash_cached_include(filename);
1523 e->hash_next = s1->cached_includes_hash[h];
1524 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1527 #define ONCE_PREFIX "#ONCE#"
1529 static void pragma_parse(TCCState *s1)
1531 next_nomacro();
1532 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1533 int t = tok, v;
1534 Sym *s;
1536 if (next(), tok != '(')
1537 goto pragma_err;
1538 if (next(), tok != TOK_STR)
1539 goto pragma_err;
1540 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1541 if (next(), tok != ')')
1542 goto pragma_err;
1543 if (t == TOK_push_macro) {
1544 while (NULL == (s = define_find(v)))
1545 define_push(v, 0, NULL, NULL);
1546 s->type.ref = s; /* set push boundary */
1547 } else {
1548 for (s = define_stack; s; s = s->prev)
1549 if (s->v == v && s->type.ref == s) {
1550 s->type.ref = NULL;
1551 break;
1554 if (s)
1555 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1556 else
1557 tcc_warning("unbalanced #pragma pop_macro");
1558 pp_debug_tok = t, pp_debug_symv = v;
1560 } else if (tok == TOK_once) {
1561 char buf1[sizeof(file->filename) + sizeof(ONCE_PREFIX)];
1562 strcpy(buf1, ONCE_PREFIX);
1563 strcat(buf1, file->filename);
1564 #ifdef PATH_NOCASE
1565 strupr(buf1);
1566 #endif
1567 add_cached_include(s1, file->filename, tok_alloc(buf1, strlen(buf1))->tok);
1568 } else if (s1->ppfp) {
1569 /* tcc -E: keep pragmas below unchanged */
1570 unget_tok(' ');
1571 unget_tok(TOK_PRAGMA);
1572 unget_tok('#');
1573 unget_tok(TOK_LINEFEED);
1575 } else if (tok == TOK_pack) {
1576 /* This may be:
1577 #pragma pack(1) // set
1578 #pragma pack() // reset to default
1579 #pragma pack(push,1) // push & set
1580 #pragma pack(pop) // restore previous */
1581 next();
1582 skip('(');
1583 if (tok == TOK_ASM_pop) {
1584 next();
1585 if (s1->pack_stack_ptr <= s1->pack_stack) {
1586 stk_error:
1587 tcc_error("out of pack stack");
1589 s1->pack_stack_ptr--;
1590 } else {
1591 int val = 0;
1592 if (tok != ')') {
1593 if (tok == TOK_ASM_push) {
1594 next();
1595 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1596 goto stk_error;
1597 s1->pack_stack_ptr++;
1598 skip(',');
1600 if (tok != TOK_CINT)
1601 goto pragma_err;
1602 val = tokc.i;
1603 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1604 goto pragma_err;
1605 next();
1607 *s1->pack_stack_ptr = val;
1609 if (tok != ')')
1610 goto pragma_err;
1612 } else if (tok == TOK_comment) {
1613 char *file;
1614 next();
1615 skip('(');
1616 if (tok != TOK_lib)
1617 goto pragma_warn;
1618 next();
1619 skip(',');
1620 if (tok != TOK_STR)
1621 goto pragma_err;
1622 file = tcc_strdup((char *)tokc.str.data);
1623 dynarray_add((void ***)&s1->pragma_libs, &s1->nb_pragma_libs, file);
1624 next();
1625 if (tok != ')')
1626 goto pragma_err;
1627 } else {
1628 pragma_warn:
1629 if (s1->warn_unsupported)
1630 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1632 return;
1634 pragma_err:
1635 tcc_error("malformed #pragma directive");
1636 return;
1639 /* is_bof is true if first non space token at beginning of file */
1640 ST_FUNC void preprocess(int is_bof)
1642 TCCState *s1 = tcc_state;
1643 int i, c, n, saved_parse_flags;
1644 char buf[1024], *q;
1645 Sym *s;
1647 saved_parse_flags = parse_flags;
1648 parse_flags = PARSE_FLAG_PREPROCESS
1649 | PARSE_FLAG_TOK_NUM
1650 | PARSE_FLAG_TOK_STR
1651 | PARSE_FLAG_LINEFEED
1652 | (parse_flags & PARSE_FLAG_ASM_FILE)
1655 next_nomacro();
1656 redo:
1657 switch(tok) {
1658 case TOK_DEFINE:
1659 pp_debug_tok = tok;
1660 next_nomacro();
1661 pp_debug_symv = tok;
1662 parse_define();
1663 break;
1664 case TOK_UNDEF:
1665 pp_debug_tok = tok;
1666 next_nomacro();
1667 pp_debug_symv = tok;
1668 s = define_find(tok);
1669 /* undefine symbol by putting an invalid name */
1670 if (s)
1671 define_undef(s);
1672 break;
1673 case TOK_INCLUDE:
1674 case TOK_INCLUDE_NEXT:
1675 ch = file->buf_ptr[0];
1676 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1677 skip_spaces();
1678 if (ch == '<') {
1679 c = '>';
1680 goto read_name;
1681 } else if (ch == '\"') {
1682 c = ch;
1683 read_name:
1684 inp();
1685 q = buf;
1686 while (ch != c && ch != '\n' && ch != CH_EOF) {
1687 if ((q - buf) < sizeof(buf) - 1)
1688 *q++ = ch;
1689 if (ch == '\\') {
1690 if (handle_stray_noerror() == 0)
1691 --q;
1692 } else
1693 inp();
1695 *q = '\0';
1696 minp();
1697 #if 0
1698 /* eat all spaces and comments after include */
1699 /* XXX: slightly incorrect */
1700 while (ch1 != '\n' && ch1 != CH_EOF)
1701 inp();
1702 #endif
1703 } else {
1704 /* computed #include : either we have only strings or
1705 we have anything enclosed in '<>' */
1706 next();
1707 buf[0] = '\0';
1708 if (tok == TOK_STR) {
1709 while (tok != TOK_LINEFEED) {
1710 if (tok != TOK_STR) {
1711 include_syntax:
1712 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1714 pstrcat(buf, sizeof(buf), (char *)tokc.str.data);
1715 next();
1717 c = '\"';
1718 } else {
1719 int len;
1720 while (tok != TOK_LINEFEED) {
1721 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1722 next();
1724 len = strlen(buf);
1725 /* check syntax and remove '<>' */
1726 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1727 goto include_syntax;
1728 memmove(buf, buf + 1, len - 2);
1729 buf[len - 2] = '\0';
1730 c = '>';
1734 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1735 tcc_error("#include recursion too deep");
1736 /* store current file in stack, but increment stack later below */
1737 *s1->include_stack_ptr = file;
1738 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index : 0;
1739 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1740 for (; i < n; ++i) {
1741 char buf1[sizeof file->filename];
1742 CachedInclude *e;
1743 const char *path;
1745 if (i == 0) {
1746 /* check absolute include path */
1747 if (!IS_ABSPATH(buf))
1748 continue;
1749 buf1[0] = 0;
1751 } else if (i == 1) {
1752 /* search in current dir if "header.h" */
1753 if (c != '\"')
1754 continue;
1755 path = file->filename;
1756 pstrncpy(buf1, path, tcc_basename(path) - path);
1758 } else {
1759 /* search in all the include paths */
1760 int j = i - 2, k = j - s1->nb_include_paths;
1761 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1762 if (path == 0) continue;
1763 pstrcpy(buf1, sizeof(buf1), path);
1764 pstrcat(buf1, sizeof(buf1), "/");
1767 pstrcat(buf1, sizeof(buf1), buf);
1768 e = search_cached_include(s1, buf1);
1769 if (e && define_find(e->ifndef_macro)) {
1770 /* no need to parse the include because the 'ifndef macro'
1771 is defined */
1772 #ifdef INC_DEBUG
1773 printf("%s: skipping cached %s\n", file->filename, buf1);
1774 #endif
1775 goto include_done;
1778 if (tcc_open(s1, buf1) < 0)
1779 continue;
1781 file->include_next_index = i + 1;
1782 #ifdef INC_DEBUG
1783 printf("%s: including %s\n", file->prev->filename, file->filename);
1784 #endif
1785 /* update target deps */
1786 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1787 tcc_strdup(buf1));
1788 /* push current file in stack */
1789 ++s1->include_stack_ptr;
1790 /* add include file debug info */
1791 if (s1->do_debug)
1792 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1793 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1794 ch = file->buf_ptr[0];
1795 goto the_end;
1797 tcc_error("include file '%s' not found", buf);
1798 include_done:
1799 break;
1800 case TOK_IFNDEF:
1801 c = 1;
1802 goto do_ifdef;
1803 case TOK_IF:
1804 c = expr_preprocess();
1805 goto do_if;
1806 case TOK_IFDEF:
1807 c = 0;
1808 do_ifdef:
1809 next_nomacro();
1810 if (tok < TOK_IDENT)
1811 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1812 if (is_bof) {
1813 if (c) {
1814 #ifdef INC_DEBUG
1815 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1816 #endif
1817 file->ifndef_macro = tok;
1820 c = (define_find(tok) != 0) ^ c;
1821 do_if:
1822 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1823 tcc_error("memory full (ifdef)");
1824 *s1->ifdef_stack_ptr++ = c;
1825 goto test_skip;
1826 case TOK_ELSE:
1827 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1828 tcc_error("#else without matching #if");
1829 if (s1->ifdef_stack_ptr[-1] & 2)
1830 tcc_error("#else after #else");
1831 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1832 goto test_else;
1833 case TOK_ELIF:
1834 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1835 tcc_error("#elif without matching #if");
1836 c = s1->ifdef_stack_ptr[-1];
1837 if (c > 1)
1838 tcc_error("#elif after #else");
1839 /* last #if/#elif expression was true: we skip */
1840 if (c == 1)
1841 goto skip;
1842 c = expr_preprocess();
1843 s1->ifdef_stack_ptr[-1] = c;
1844 test_else:
1845 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1846 file->ifndef_macro = 0;
1847 test_skip:
1848 if (!(c & 1)) {
1849 skip:
1850 preprocess_skip();
1851 is_bof = 0;
1852 goto redo;
1854 break;
1855 case TOK_ENDIF:
1856 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1857 tcc_error("#endif without matching #if");
1858 s1->ifdef_stack_ptr--;
1859 /* '#ifndef macro' was at the start of file. Now we check if
1860 an '#endif' is exactly at the end of file */
1861 if (file->ifndef_macro &&
1862 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1863 file->ifndef_macro_saved = file->ifndef_macro;
1864 /* need to set to zero to avoid false matches if another
1865 #ifndef at middle of file */
1866 file->ifndef_macro = 0;
1867 while (tok != TOK_LINEFEED)
1868 next_nomacro();
1869 tok_flags |= TOK_FLAG_ENDIF;
1870 goto the_end;
1872 break;
1873 case TOK_PPNUM:
1874 n = strtoul((char*)tokc.str.data, &q, 10);
1875 goto _line_num;
1876 case TOK_LINE:
1877 next();
1878 if (tok != TOK_CINT)
1879 _line_err:
1880 tcc_error("wrong #line format");
1881 n = tokc.i;
1882 _line_num:
1883 next();
1884 if (tok != TOK_LINEFEED) {
1885 if (tok == TOK_STR)
1886 pstrcpy(file->filename, sizeof(file->filename), (char *)tokc.str.data);
1887 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1888 break;
1889 else
1890 goto _line_err;
1891 --n;
1893 if (file->fd > 0)
1894 total_lines += file->line_num - n;
1895 file->line_num = n;
1896 if (s1->do_debug)
1897 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1898 break;
1899 case TOK_ERROR:
1900 case TOK_WARNING:
1901 c = tok;
1902 ch = file->buf_ptr[0];
1903 skip_spaces();
1904 q = buf;
1905 while (ch != '\n' && ch != CH_EOF) {
1906 if ((q - buf) < sizeof(buf) - 1)
1907 *q++ = ch;
1908 if (ch == '\\') {
1909 if (handle_stray_noerror() == 0)
1910 --q;
1911 } else
1912 inp();
1914 *q = '\0';
1915 if (c == TOK_ERROR)
1916 tcc_error("#error %s", buf);
1917 else
1918 tcc_warning("#warning %s", buf);
1919 break;
1920 case TOK_PRAGMA:
1921 pragma_parse(s1);
1922 break;
1923 case TOK_LINEFEED:
1924 goto the_end;
1925 default:
1926 /* ignore gas line comment in an 'S' file. */
1927 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1928 goto ignore;
1929 if (tok == '!' && is_bof)
1930 /* '!' is ignored at beginning to allow C scripts. */
1931 goto ignore;
1932 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1933 ignore:
1934 file->buf_ptr = parse_line_comment(file->buf_ptr);
1935 goto the_end;
1937 /* ignore other preprocess commands or #! for C scripts */
1938 while (tok != TOK_LINEFEED)
1939 next_nomacro();
1940 the_end:
1941 parse_flags = saved_parse_flags;
1944 /* evaluate escape codes in a string. */
1945 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1947 int c, n;
1948 const uint8_t *p;
1950 p = buf;
1951 for(;;) {
1952 c = *p;
1953 if (c == '\0')
1954 break;
1955 if (c == '\\') {
1956 p++;
1957 /* escape */
1958 c = *p;
1959 switch(c) {
1960 case '0': case '1': case '2': case '3':
1961 case '4': case '5': case '6': case '7':
1962 /* at most three octal digits */
1963 n = c - '0';
1964 p++;
1965 c = *p;
1966 if (isoct(c)) {
1967 n = n * 8 + c - '0';
1968 p++;
1969 c = *p;
1970 if (isoct(c)) {
1971 n = n * 8 + c - '0';
1972 p++;
1975 c = n;
1976 goto add_char_nonext;
1977 case 'x':
1978 case 'u':
1979 case 'U':
1980 p++;
1981 n = 0;
1982 for(;;) {
1983 c = *p;
1984 if (c >= 'a' && c <= 'f')
1985 c = c - 'a' + 10;
1986 else if (c >= 'A' && c <= 'F')
1987 c = c - 'A' + 10;
1988 else if (isnum(c))
1989 c = c - '0';
1990 else
1991 break;
1992 n = n * 16 + c;
1993 p++;
1995 c = n;
1996 goto add_char_nonext;
1997 case 'a':
1998 c = '\a';
1999 break;
2000 case 'b':
2001 c = '\b';
2002 break;
2003 case 'f':
2004 c = '\f';
2005 break;
2006 case 'n':
2007 c = '\n';
2008 break;
2009 case 'r':
2010 c = '\r';
2011 break;
2012 case 't':
2013 c = '\t';
2014 break;
2015 case 'v':
2016 c = '\v';
2017 break;
2018 case 'e':
2019 if (!gnu_ext)
2020 goto invalid_escape;
2021 c = 27;
2022 break;
2023 case '\'':
2024 case '\"':
2025 case '\\':
2026 case '?':
2027 break;
2028 default:
2029 invalid_escape:
2030 if (c >= '!' && c <= '~')
2031 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2032 else
2033 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2034 break;
2037 p++;
2038 add_char_nonext:
2039 if (!is_long)
2040 cstr_ccat(outstr, c);
2041 else
2042 cstr_wccat(outstr, c);
2044 /* add a trailing '\0' */
2045 if (!is_long)
2046 cstr_ccat(outstr, '\0');
2047 else
2048 cstr_wccat(outstr, '\0');
2051 void parse_string(const char *s, int len)
2053 uint8_t buf[1000], *p = buf;
2054 int is_long, sep;
2056 if ((is_long = *s == 'L'))
2057 ++s, --len;
2058 sep = *s++;
2059 len -= 2;
2060 if (len >= sizeof buf)
2061 p = tcc_malloc(len + 1);
2062 memcpy(p, s, len);
2063 p[len] = 0;
2065 cstr_reset(&tokcstr);
2066 parse_escape_string(&tokcstr, p, is_long);
2067 if (p != buf)
2068 tcc_free(p);
2070 if (sep == '\'') {
2071 int char_size;
2072 /* XXX: make it portable */
2073 if (!is_long)
2074 char_size = 1;
2075 else
2076 char_size = sizeof(nwchar_t);
2077 if (tokcstr.size <= char_size)
2078 tcc_error("empty character constant");
2079 if (tokcstr.size > 2 * char_size)
2080 tcc_warning("multi-character character constant");
2081 if (!is_long) {
2082 tokc.i = *(int8_t *)tokcstr.data;
2083 tok = TOK_CCHAR;
2084 } else {
2085 tokc.i = *(nwchar_t *)tokcstr.data;
2086 tok = TOK_LCHAR;
2088 } else {
2089 tokc.str.size = tokcstr.size;
2090 tokc.str.data = tokcstr.data;
2091 tokc.str.data_allocated = tokcstr.data_allocated;
2092 if (!is_long)
2093 tok = TOK_STR;
2094 else
2095 tok = TOK_LSTR;
2099 /* we use 64 bit numbers */
2100 #define BN_SIZE 2
2102 /* bn = (bn << shift) | or_val */
2103 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2105 int i;
2106 unsigned int v;
2107 for(i=0;i<BN_SIZE;i++) {
2108 v = bn[i];
2109 bn[i] = (v << shift) | or_val;
2110 or_val = v >> (32 - shift);
2114 static void bn_zero(unsigned int *bn)
2116 int i;
2117 for(i=0;i<BN_SIZE;i++) {
2118 bn[i] = 0;
2122 /* parse number in null terminated string 'p' and return it in the
2123 current token */
2124 static void parse_number(const char *p)
2126 int b, t, shift, frac_bits, s, exp_val, ch;
2127 char *q;
2128 unsigned int bn[BN_SIZE];
2129 double d;
2131 /* number */
2132 q = token_buf;
2133 ch = *p++;
2134 t = ch;
2135 ch = *p++;
2136 *q++ = t;
2137 b = 10;
2138 if (t == '.') {
2139 goto float_frac_parse;
2140 } else if (t == '0') {
2141 if (ch == 'x' || ch == 'X') {
2142 q--;
2143 ch = *p++;
2144 b = 16;
2145 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
2146 q--;
2147 ch = *p++;
2148 b = 2;
2151 /* parse all digits. cannot check octal numbers at this stage
2152 because of floating point constants */
2153 while (1) {
2154 if (ch >= 'a' && ch <= 'f')
2155 t = ch - 'a' + 10;
2156 else if (ch >= 'A' && ch <= 'F')
2157 t = ch - 'A' + 10;
2158 else if (isnum(ch))
2159 t = ch - '0';
2160 else
2161 break;
2162 if (t >= b)
2163 break;
2164 if (q >= token_buf + STRING_MAX_SIZE) {
2165 num_too_long:
2166 tcc_error("number too long");
2168 *q++ = ch;
2169 ch = *p++;
2171 if (ch == '.' ||
2172 ((ch == 'e' || ch == 'E') && b == 10) ||
2173 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2174 if (b != 10) {
2175 /* NOTE: strtox should support that for hexa numbers, but
2176 non ISOC99 libcs do not support it, so we prefer to do
2177 it by hand */
2178 /* hexadecimal or binary floats */
2179 /* XXX: handle overflows */
2180 *q = '\0';
2181 if (b == 16)
2182 shift = 4;
2183 else
2184 shift = 1;
2185 bn_zero(bn);
2186 q = token_buf;
2187 while (1) {
2188 t = *q++;
2189 if (t == '\0') {
2190 break;
2191 } else if (t >= 'a') {
2192 t = t - 'a' + 10;
2193 } else if (t >= 'A') {
2194 t = t - 'A' + 10;
2195 } else {
2196 t = t - '0';
2198 bn_lshift(bn, shift, t);
2200 frac_bits = 0;
2201 if (ch == '.') {
2202 ch = *p++;
2203 while (1) {
2204 t = ch;
2205 if (t >= 'a' && t <= 'f') {
2206 t = t - 'a' + 10;
2207 } else if (t >= 'A' && t <= 'F') {
2208 t = t - 'A' + 10;
2209 } else if (t >= '0' && t <= '9') {
2210 t = t - '0';
2211 } else {
2212 break;
2214 if (t >= b)
2215 tcc_error("invalid digit");
2216 bn_lshift(bn, shift, t);
2217 frac_bits += shift;
2218 ch = *p++;
2221 if (ch != 'p' && ch != 'P')
2222 expect("exponent");
2223 ch = *p++;
2224 s = 1;
2225 exp_val = 0;
2226 if (ch == '+') {
2227 ch = *p++;
2228 } else if (ch == '-') {
2229 s = -1;
2230 ch = *p++;
2232 if (ch < '0' || ch > '9')
2233 expect("exponent digits");
2234 while (ch >= '0' && ch <= '9') {
2235 exp_val = exp_val * 10 + ch - '0';
2236 ch = *p++;
2238 exp_val = exp_val * s;
2240 /* now we can generate the number */
2241 /* XXX: should patch directly float number */
2242 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2243 d = ldexp(d, exp_val - frac_bits);
2244 t = toup(ch);
2245 if (t == 'F') {
2246 ch = *p++;
2247 tok = TOK_CFLOAT;
2248 /* float : should handle overflow */
2249 tokc.f = (float)d;
2250 } else if (t == 'L') {
2251 ch = *p++;
2252 #ifdef TCC_TARGET_PE
2253 tok = TOK_CDOUBLE;
2254 tokc.d = d;
2255 #else
2256 tok = TOK_CLDOUBLE;
2257 /* XXX: not large enough */
2258 tokc.ld = (long double)d;
2259 #endif
2260 } else {
2261 tok = TOK_CDOUBLE;
2262 tokc.d = d;
2264 } else {
2265 /* decimal floats */
2266 if (ch == '.') {
2267 if (q >= token_buf + STRING_MAX_SIZE)
2268 goto num_too_long;
2269 *q++ = ch;
2270 ch = *p++;
2271 float_frac_parse:
2272 while (ch >= '0' && ch <= '9') {
2273 if (q >= token_buf + STRING_MAX_SIZE)
2274 goto num_too_long;
2275 *q++ = ch;
2276 ch = *p++;
2279 if (ch == 'e' || ch == 'E') {
2280 if (q >= token_buf + STRING_MAX_SIZE)
2281 goto num_too_long;
2282 *q++ = ch;
2283 ch = *p++;
2284 if (ch == '-' || ch == '+') {
2285 if (q >= token_buf + STRING_MAX_SIZE)
2286 goto num_too_long;
2287 *q++ = ch;
2288 ch = *p++;
2290 if (ch < '0' || ch > '9')
2291 expect("exponent digits");
2292 while (ch >= '0' && ch <= '9') {
2293 if (q >= token_buf + STRING_MAX_SIZE)
2294 goto num_too_long;
2295 *q++ = ch;
2296 ch = *p++;
2299 *q = '\0';
2300 t = toup(ch);
2301 errno = 0;
2302 if (t == 'F') {
2303 ch = *p++;
2304 tok = TOK_CFLOAT;
2305 tokc.f = strtof(token_buf, NULL);
2306 } else if (t == 'L') {
2307 ch = *p++;
2308 #ifdef TCC_TARGET_PE
2309 tok = TOK_CDOUBLE;
2310 tokc.d = strtod(token_buf, NULL);
2311 #else
2312 tok = TOK_CLDOUBLE;
2313 tokc.ld = strtold(token_buf, NULL);
2314 #endif
2315 } else {
2316 tok = TOK_CDOUBLE;
2317 tokc.d = strtod(token_buf, NULL);
2320 } else {
2321 unsigned long long n, n1;
2322 int lcount, ucount, must_64bit;
2323 const char *p1;
2325 /* integer number */
2326 *q = '\0';
2327 q = token_buf;
2328 if (b == 10 && *q == '0') {
2329 b = 8;
2330 q++;
2332 n = 0;
2333 while(1) {
2334 t = *q++;
2335 /* no need for checks except for base 10 / 8 errors */
2336 if (t == '\0')
2337 break;
2338 else if (t >= 'a')
2339 t = t - 'a' + 10;
2340 else if (t >= 'A')
2341 t = t - 'A' + 10;
2342 else
2343 t = t - '0';
2344 if (t >= b)
2345 tcc_error("invalid digit");
2346 n1 = n;
2347 n = n * b + t;
2348 /* detect overflow */
2349 /* XXX: this test is not reliable */
2350 if (n < n1)
2351 tcc_error("integer constant overflow");
2354 /* Determine the characteristics (unsigned and/or 64bit) the type of
2355 the constant must have according to the constant suffix(es) */
2356 lcount = ucount = must_64bit = 0;
2357 p1 = p;
2358 for(;;) {
2359 t = toup(ch);
2360 if (t == 'L') {
2361 if (lcount >= 2)
2362 tcc_error("three 'l's in integer constant");
2363 if (lcount && *(p - 1) != ch)
2364 tcc_error("incorrect integer suffix: %s", p1);
2365 lcount++;
2366 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2367 if (lcount == 2)
2368 #endif
2369 must_64bit = 1;
2370 ch = *p++;
2371 } else if (t == 'U') {
2372 if (ucount >= 1)
2373 tcc_error("two 'u's in integer constant");
2374 ucount++;
2375 ch = *p++;
2376 } else {
2377 break;
2381 /* Whether 64 bits are needed to hold the constant's value */
2382 if (n & 0xffffffff00000000LL || must_64bit) {
2383 tok = TOK_CLLONG;
2384 n1 = n >> 32;
2385 } else {
2386 tok = TOK_CINT;
2387 n1 = n;
2390 /* Whether type must be unsigned to hold the constant's value */
2391 if (ucount || ((n1 >> 31) && (b != 10))) {
2392 if (tok == TOK_CLLONG)
2393 tok = TOK_CULLONG;
2394 else
2395 tok = TOK_CUINT;
2396 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2397 } else if (n1 >> 31) {
2398 if (tok == TOK_CINT)
2399 tok = TOK_CLLONG;
2400 else
2401 tcc_error("integer constant overflow");
2404 if (tok == TOK_CINT || tok == TOK_CUINT)
2405 tokc.i = n;
2406 else
2407 tokc.i = n;
2409 if (ch)
2410 tcc_error("invalid number\n");
2414 #define PARSE2(c1, tok1, c2, tok2) \
2415 case c1: \
2416 PEEKC(c, p); \
2417 if (c == c2) { \
2418 p++; \
2419 tok = tok2; \
2420 } else { \
2421 tok = tok1; \
2423 break;
2425 /* return next token without macro substitution */
2426 static inline void next_nomacro1(void)
2428 int t, c, is_long, len;
2429 TokenSym *ts;
2430 uint8_t *p, *p1;
2431 unsigned int h;
2433 p = file->buf_ptr;
2434 redo_no_start:
2435 c = *p;
2436 #if (__TINYC__ || __GNUC__)
2437 #else
2438 if (c & 0x80)
2439 goto parse_ident_fast;
2440 #endif
2441 switch(c) {
2442 case ' ':
2443 case '\t':
2444 tok = c;
2445 p++;
2446 if (parse_flags & PARSE_FLAG_SPACES)
2447 goto keep_tok_flags;
2448 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2449 ++p;
2450 goto redo_no_start;
2451 case '\f':
2452 case '\v':
2453 case '\r':
2454 p++;
2455 goto redo_no_start;
2456 case '\\':
2457 /* first look if it is in fact an end of buffer */
2458 c = handle_stray1(p);
2459 p = file->buf_ptr;
2460 if (c == '\\')
2461 goto parse_simple;
2462 if (c != CH_EOF)
2463 goto redo_no_start;
2465 TCCState *s1 = tcc_state;
2466 if ((parse_flags & PARSE_FLAG_LINEFEED)
2467 && !(tok_flags & TOK_FLAG_EOF)) {
2468 tok_flags |= TOK_FLAG_EOF;
2469 tok = TOK_LINEFEED;
2470 goto keep_tok_flags;
2471 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2472 tok = TOK_EOF;
2473 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2474 tcc_error("missing #endif");
2475 } else if (s1->include_stack_ptr == s1->include_stack) {
2476 /* no include left : end of file. */
2477 tok = TOK_EOF;
2478 } else {
2479 tok_flags &= ~TOK_FLAG_EOF;
2480 /* pop include file */
2482 /* test if previous '#endif' was after a #ifdef at
2483 start of file */
2484 if (tok_flags & TOK_FLAG_ENDIF) {
2485 #ifdef INC_DEBUG
2486 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2487 #endif
2488 add_cached_include(s1, file->filename, file->ifndef_macro_saved);
2489 tok_flags &= ~TOK_FLAG_ENDIF;
2492 /* add end of include file debug info */
2493 if (tcc_state->do_debug) {
2494 put_stabd(N_EINCL, 0, 0);
2496 /* pop include stack */
2497 tcc_close();
2498 s1->include_stack_ptr--;
2499 p = file->buf_ptr;
2500 goto redo_no_start;
2503 break;
2505 case '\n':
2506 file->line_num++;
2507 tok_flags |= TOK_FLAG_BOL;
2508 p++;
2509 maybe_newline:
2510 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2511 goto redo_no_start;
2512 tok = TOK_LINEFEED;
2513 goto keep_tok_flags;
2515 case '#':
2516 /* XXX: simplify */
2517 PEEKC(c, p);
2518 if ((tok_flags & TOK_FLAG_BOL) &&
2519 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2520 file->buf_ptr = p;
2521 preprocess(tok_flags & TOK_FLAG_BOF);
2522 p = file->buf_ptr;
2523 goto maybe_newline;
2524 } else {
2525 if (c == '#') {
2526 p++;
2527 tok = TOK_TWOSHARPS;
2528 } else {
2529 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2530 p = parse_line_comment(p - 1);
2531 goto redo_no_start;
2532 } else {
2533 tok = '#';
2537 break;
2539 /* dollar is allowed to start identifiers when not parsing asm */
2540 case '$':
2541 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2542 || (parse_flags & PARSE_FLAG_ASM_FILE))
2543 goto parse_simple;
2545 #if (__TINYC__ || __GNUC__)
2546 case 'a' ... 'z':
2547 case 'A' ... 'K':
2548 case 'M' ... 'Z':
2549 case '_':
2550 case 0x80 ... 0xFF:
2551 #else
2552 case 'a': case 'b': case 'c': case 'd':
2553 case 'e': case 'f': case 'g': case 'h':
2554 case 'i': case 'j': case 'k': case 'l':
2555 case 'm': case 'n': case 'o': case 'p':
2556 case 'q': case 'r': case 's': case 't':
2557 case 'u': case 'v': case 'w': case 'x':
2558 case 'y': case 'z':
2559 case 'A': case 'B': case 'C': case 'D':
2560 case 'E': case 'F': case 'G': case 'H':
2561 case 'I': case 'J': case 'K':
2562 case 'M': case 'N': case 'O': case 'P':
2563 case 'Q': case 'R': case 'S': case 'T':
2564 case 'U': case 'V': case 'W': case 'X':
2565 case 'Y': case 'Z':
2566 case '_':
2567 #endif
2568 parse_ident_fast:
2569 p1 = p;
2570 h = TOK_HASH_INIT;
2571 h = TOK_HASH_FUNC(h, c);
2572 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2573 h = TOK_HASH_FUNC(h, c);
2574 len = p - p1;
2575 if (c != '\\') {
2576 TokenSym **pts;
2578 /* fast case : no stray found, so we have the full token
2579 and we have already hashed it */
2580 h &= (TOK_HASH_SIZE - 1);
2581 pts = &hash_ident[h];
2582 for(;;) {
2583 ts = *pts;
2584 if (!ts)
2585 break;
2586 if (ts->len == len && !memcmp(ts->str, p1, len))
2587 goto token_found;
2588 pts = &(ts->hash_next);
2590 ts = tok_alloc_new(pts, (char *) p1, len);
2591 token_found: ;
2592 } else {
2593 /* slower case */
2594 cstr_reset(&tokcstr);
2595 cstr_cat(&tokcstr, p1, len);
2596 p--;
2597 PEEKC(c, p);
2598 parse_ident_slow:
2599 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2601 cstr_ccat(&tokcstr, c);
2602 PEEKC(c, p);
2604 ts = tok_alloc(tokcstr.data, tokcstr.size);
2606 tok = ts->tok;
2607 break;
2608 case 'L':
2609 t = p[1];
2610 if (t != '\\' && t != '\'' && t != '\"') {
2611 /* fast case */
2612 goto parse_ident_fast;
2613 } else {
2614 PEEKC(c, p);
2615 if (c == '\'' || c == '\"') {
2616 is_long = 1;
2617 goto str_const;
2618 } else {
2619 cstr_reset(&tokcstr);
2620 cstr_ccat(&tokcstr, 'L');
2621 goto parse_ident_slow;
2624 break;
2626 case '0': case '1': case '2': case '3':
2627 case '4': case '5': case '6': case '7':
2628 case '8': case '9':
2629 cstr_reset(&tokcstr);
2630 /* after the first digit, accept digits, alpha, '.' or sign if
2631 prefixed by 'eEpP' */
2632 parse_num:
2633 for(;;) {
2634 t = c;
2635 cstr_ccat(&tokcstr, c);
2636 PEEKC(c, p);
2637 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2638 || c == '.'
2639 || ((c == '+' || c == '-')
2640 && (t == 'e' || t == 'E' || t == 'p' || t == 'P')
2641 && !(parse_flags & PARSE_FLAG_ASM_FILE)
2643 break;
2645 /* We add a trailing '\0' to ease parsing */
2646 cstr_ccat(&tokcstr, '\0');
2647 tokc.str.size = tokcstr.size;
2648 tokc.str.data = tokcstr.data;
2649 tokc.str.data_allocated = tokcstr.data_allocated;
2650 tok = TOK_PPNUM;
2651 break;
2653 case '.':
2654 /* special dot handling because it can also start a number */
2655 PEEKC(c, p);
2656 if (isnum(c)) {
2657 cstr_reset(&tokcstr);
2658 cstr_ccat(&tokcstr, '.');
2659 goto parse_num;
2660 } else if ((parse_flags & PARSE_FLAG_ASM_FILE)
2661 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2662 *--p = c = '.';
2663 goto parse_ident_fast;
2664 } else if (c == '.') {
2665 PEEKC(c, p);
2666 if (c == '.') {
2667 p++;
2668 tok = TOK_DOTS;
2669 } else {
2670 *--p = '.'; /* may underflow into file->unget[] */
2671 tok = '.';
2673 } else {
2674 tok = '.';
2676 break;
2677 case '\'':
2678 case '\"':
2679 is_long = 0;
2680 str_const:
2681 cstr_reset(&tokcstr);
2682 if (is_long)
2683 cstr_ccat(&tokcstr, 'L');
2684 cstr_ccat(&tokcstr, c);
2685 p = parse_pp_string(p, c, &tokcstr);
2686 cstr_ccat(&tokcstr, c);
2687 cstr_ccat(&tokcstr, '\0');
2688 tokc.str.size = tokcstr.size;
2689 tokc.str.data = tokcstr.data;
2690 tokc.str.data_allocated = tokcstr.data_allocated;
2691 tok = TOK_PPSTR;
2692 break;
2694 case '<':
2695 PEEKC(c, p);
2696 if (c == '=') {
2697 p++;
2698 tok = TOK_LE;
2699 } else if (c == '<') {
2700 PEEKC(c, p);
2701 if (c == '=') {
2702 p++;
2703 tok = TOK_A_SHL;
2704 } else {
2705 tok = TOK_SHL;
2707 } else {
2708 tok = TOK_LT;
2710 break;
2711 case '>':
2712 PEEKC(c, p);
2713 if (c == '=') {
2714 p++;
2715 tok = TOK_GE;
2716 } else if (c == '>') {
2717 PEEKC(c, p);
2718 if (c == '=') {
2719 p++;
2720 tok = TOK_A_SAR;
2721 } else {
2722 tok = TOK_SAR;
2724 } else {
2725 tok = TOK_GT;
2727 break;
2729 case '&':
2730 PEEKC(c, p);
2731 if (c == '&') {
2732 p++;
2733 tok = TOK_LAND;
2734 } else if (c == '=') {
2735 p++;
2736 tok = TOK_A_AND;
2737 } else {
2738 tok = '&';
2740 break;
2742 case '|':
2743 PEEKC(c, p);
2744 if (c == '|') {
2745 p++;
2746 tok = TOK_LOR;
2747 } else if (c == '=') {
2748 p++;
2749 tok = TOK_A_OR;
2750 } else {
2751 tok = '|';
2753 break;
2755 case '+':
2756 PEEKC(c, p);
2757 if (c == '+') {
2758 p++;
2759 tok = TOK_INC;
2760 } else if (c == '=') {
2761 p++;
2762 tok = TOK_A_ADD;
2763 } else {
2764 tok = '+';
2766 break;
2768 case '-':
2769 PEEKC(c, p);
2770 if (c == '-') {
2771 p++;
2772 tok = TOK_DEC;
2773 } else if (c == '=') {
2774 p++;
2775 tok = TOK_A_SUB;
2776 } else if (c == '>') {
2777 p++;
2778 tok = TOK_ARROW;
2779 } else {
2780 tok = '-';
2782 break;
2784 PARSE2('!', '!', '=', TOK_NE)
2785 PARSE2('=', '=', '=', TOK_EQ)
2786 PARSE2('*', '*', '=', TOK_A_MUL)
2787 PARSE2('%', '%', '=', TOK_A_MOD)
2788 PARSE2('^', '^', '=', TOK_A_XOR)
2790 /* comments or operator */
2791 case '/':
2792 PEEKC(c, p);
2793 if (c == '*') {
2794 p = parse_comment(p);
2795 /* comments replaced by a blank */
2796 tok = ' ';
2797 goto keep_tok_flags;
2798 } else if (c == '/') {
2799 p = parse_line_comment(p);
2800 tok = ' ';
2801 goto keep_tok_flags;
2802 } else if (c == '=') {
2803 p++;
2804 tok = TOK_A_DIV;
2805 } else {
2806 tok = '/';
2808 break;
2810 /* simple tokens */
2811 case '(':
2812 case ')':
2813 case '[':
2814 case ']':
2815 case '{':
2816 case '}':
2817 case ',':
2818 case ';':
2819 case ':':
2820 case '?':
2821 case '~':
2822 case '@': /* only used in assembler */
2823 parse_simple:
2824 tok = c;
2825 p++;
2826 break;
2827 default:
2828 if (parse_flags & PARSE_FLAG_ASM_FILE)
2829 goto parse_simple;
2830 tcc_error("unrecognized character \\x%02x", c);
2831 break;
2833 tok_flags = 0;
2834 keep_tok_flags:
2835 file->buf_ptr = p;
2836 #if defined(PARSE_DEBUG)
2837 printf("token = %s\n", get_tok_str(tok, &tokc));
2838 #endif
2841 /* return next token without macro substitution. Can read input from
2842 macro_ptr buffer */
2843 static void next_nomacro_spc(void)
2845 if (macro_ptr) {
2846 redo:
2847 tok = *macro_ptr;
2848 if (tok) {
2849 TOK_GET(&tok, &macro_ptr, &tokc);
2850 if (tok == TOK_LINENUM) {
2851 file->line_num = tokc.i;
2852 goto redo;
2855 } else {
2856 next_nomacro1();
2860 ST_FUNC void next_nomacro(void)
2862 do {
2863 next_nomacro_spc();
2864 } while (tok < 256 && (isidnum_table[tok - CH_EOF] & IS_SPC));
2868 static void macro_subst(
2869 TokenString *tok_str,
2870 Sym **nested_list,
2871 const int *macro_str,
2872 int can_read_stream
2875 /* substitute arguments in replacement lists in macro_str by the values in
2876 args (field d) and return allocated string */
2877 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2879 int t, t0, t1, spc;
2880 const int *st;
2881 Sym *s;
2882 CValue cval;
2883 TokenString str;
2884 CString cstr;
2886 tok_str_new(&str);
2887 t0 = t1 = 0;
2888 while(1) {
2889 TOK_GET(&t, &macro_str, &cval);
2890 if (!t)
2891 break;
2892 if (t == '#') {
2893 /* stringize */
2894 TOK_GET(&t, &macro_str, &cval);
2895 if (!t)
2896 goto bad_stringy;
2897 s = sym_find2(args, t);
2898 if (s) {
2899 cstr_new(&cstr);
2900 cstr_ccat(&cstr, '\"');
2901 st = s->d;
2902 spc = 0;
2903 while (*st) {
2904 TOK_GET(&t, &st, &cval);
2905 if (t != TOK_PLCHLDR
2906 && t != TOK_NOSUBST
2907 && 0 == check_space(t, &spc)) {
2908 const char *s = get_tok_str(t, &cval);
2909 while (*s) {
2910 if (t == TOK_PPSTR && *s != '\'')
2911 add_char(&cstr, *s);
2912 else
2913 cstr_ccat(&cstr, *s);
2914 ++s;
2918 cstr.size -= spc;
2919 cstr_ccat(&cstr, '\"');
2920 cstr_ccat(&cstr, '\0');
2921 #ifdef PP_DEBUG
2922 printf("\nstringize: <%s>\n", (char *)cstr.data);
2923 #endif
2924 /* add string */
2925 cval.str.size = cstr.size;
2926 cval.str.data = cstr.data;
2927 cval.str.data_allocated = cstr.data_allocated;
2928 tok_str_add2(&str, TOK_PPSTR, &cval);
2929 cstr_free(&cstr);
2930 } else {
2931 bad_stringy:
2932 expect("macro parameter after '#'");
2934 } else if (t >= TOK_IDENT) {
2935 s = sym_find2(args, t);
2936 if (s) {
2937 int l0 = str.len;
2938 st = s->d;
2939 /* if '##' is present before or after, no arg substitution */
2940 if (*macro_str == TOK_TWOSHARPS || t1 == TOK_TWOSHARPS) {
2941 /* special case for var arg macros : ## eats the ','
2942 if empty VA_ARGS variable. */
2943 if (t1 == TOK_TWOSHARPS && t0 == ',' && gnu_ext && s->type.t) {
2944 if (*st == 0) {
2945 /* suppress ',' '##' */
2946 str.len -= 2;
2947 } else {
2948 /* suppress '##' and add variable */
2949 str.len--;
2950 goto add_var;
2952 } else {
2953 for(;;) {
2954 int t1;
2955 TOK_GET(&t1, &st, &cval);
2956 if (!t1)
2957 break;
2958 tok_str_add2(&str, t1, &cval);
2962 } else {
2963 add_var:
2964 /* NOTE: the stream cannot be read when macro
2965 substituing an argument */
2966 macro_subst(&str, nested_list, st, 0);
2968 if (str.len == l0) /* exanded to empty string */
2969 tok_str_add(&str, TOK_PLCHLDR);
2970 } else {
2971 tok_str_add(&str, t);
2973 } else {
2974 tok_str_add2(&str, t, &cval);
2976 t0 = t1, t1 = t;
2978 tok_str_add(&str, 0);
2979 return str.str;
2982 static char const ab_month_name[12][4] =
2984 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2985 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2988 /* peek or read [ws_str == NULL] next token from function macro call,
2989 walking up macro levels up to the file if necessary */
2990 static int next_argstream(Sym **nested_list, int can_read_stream, TokenString *ws_str)
2992 int t;
2993 const int *p;
2994 Sym *sa;
2996 for (;;) {
2997 if (macro_ptr) {
2998 p = macro_ptr, t = *p;
2999 if (ws_str) {
3000 while (is_space(t) || TOK_LINEFEED == t)
3001 tok_str_add(ws_str, t), t = *++p;
3003 if (t == 0 && can_read_stream) {
3004 end_macro();
3005 /* also, end of scope for nested defined symbol */
3006 sa = *nested_list;
3007 while (sa && sa->v == 0)
3008 sa = sa->prev;
3009 if (sa)
3010 sa->v = 0;
3011 continue;
3013 } else {
3014 ch = handle_eob();
3015 if (ws_str) {
3016 while (is_space(ch) || ch == '\n' || ch == '/') {
3017 if (ch == '/') {
3018 int c;
3019 uint8_t *p = file->buf_ptr;
3020 PEEKC(c, p);
3021 if (c == '*') {
3022 p = parse_comment(p);
3023 file->buf_ptr = p - 1;
3024 } else if (c == '/') {
3025 p = parse_line_comment(p);
3026 file->buf_ptr = p - 1;
3027 } else
3028 break;
3029 ch = ' ';
3031 tok_str_add(ws_str, ch);
3032 cinp();
3035 t = ch;
3038 if (ws_str)
3039 return t;
3040 next_nomacro_spc();
3041 return tok;
3045 /* do macro substitution of current token with macro 's' and add
3046 result to (tok_str,tok_len). 'nested_list' is the list of all
3047 macros we got inside to avoid recursing. Return non zero if no
3048 substitution needs to be done */
3049 static int macro_subst_tok(
3050 TokenString *tok_str,
3051 Sym **nested_list,
3052 Sym *s,
3053 int can_read_stream)
3055 Sym *args, *sa, *sa1;
3056 int parlevel, *mstr, t, t1, spc;
3057 TokenString str;
3058 char *cstrval;
3059 CValue cval;
3060 CString cstr;
3061 char buf[32];
3063 /* if symbol is a macro, prepare substitution */
3064 /* special macros */
3065 if (tok == TOK___LINE__) {
3066 snprintf(buf, sizeof(buf), "%d", file->line_num);
3067 cstrval = buf;
3068 t1 = TOK_PPNUM;
3069 goto add_cstr1;
3070 } else if (tok == TOK___FILE__) {
3071 cstrval = file->filename;
3072 goto add_cstr;
3073 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3074 time_t ti;
3075 struct tm *tm;
3077 time(&ti);
3078 tm = localtime(&ti);
3079 if (tok == TOK___DATE__) {
3080 snprintf(buf, sizeof(buf), "%s %2d %d",
3081 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3082 } else {
3083 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3084 tm->tm_hour, tm->tm_min, tm->tm_sec);
3086 cstrval = buf;
3087 add_cstr:
3088 t1 = TOK_STR;
3089 add_cstr1:
3090 cstr_new(&cstr);
3091 cstr_cat(&cstr, cstrval, 0);
3092 cval.str.size = cstr.size;
3093 cval.str.data = cstr.data;
3094 cval.str.data_allocated = cstr.data_allocated;
3095 tok_str_add2(tok_str, t1, &cval);
3096 cstr_free(&cstr);
3097 } else {
3098 int saved_parse_flags = parse_flags;
3100 mstr = s->d;
3101 if (s->type.t == MACRO_FUNC) {
3102 /* whitespace between macro name and argument list */
3103 TokenString ws_str;
3104 tok_str_new(&ws_str);
3106 spc = 0;
3107 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3108 | PARSE_FLAG_ACCEPT_STRAYS;
3110 /* get next token from argument stream */
3111 t = next_argstream(nested_list, can_read_stream, &ws_str);
3112 if (t != '(') {
3113 /* not a macro substitution after all, restore the
3114 * macro token plus all whitespace we've read.
3115 * whitespace is intentionally not merged to preserve
3116 * newlines. */
3117 parse_flags = saved_parse_flags;
3118 tok_str_add(tok_str, tok);
3119 if (parse_flags & PARSE_FLAG_SPACES) {
3120 int i;
3121 for (i = 0; i < ws_str.len; i++)
3122 tok_str_add(tok_str, ws_str.str[i]);
3124 tok_str_free(ws_str.str);
3125 return 0;
3126 } else {
3127 tok_str_free(ws_str.str);
3129 next_nomacro(); /* eat '(' */
3131 /* argument macro */
3132 args = NULL;
3133 sa = s->next;
3134 /* NOTE: empty args are allowed, except if no args */
3135 for(;;) {
3136 do {
3137 next_argstream(nested_list, can_read_stream, NULL);
3138 } while (is_space(tok) || TOK_LINEFEED == tok);
3139 empty_arg:
3140 /* handle '()' case */
3141 if (!args && !sa && tok == ')')
3142 break;
3143 if (!sa)
3144 tcc_error("macro '%s' used with too many args",
3145 get_tok_str(s->v, 0));
3146 tok_str_new(&str);
3147 parlevel = spc = 0;
3148 /* NOTE: non zero sa->t indicates VA_ARGS */
3149 while ((parlevel > 0 ||
3150 (tok != ')' &&
3151 (tok != ',' || sa->type.t)))) {
3152 if (tok == TOK_EOF || tok == 0)
3153 break;
3154 if (tok == '(')
3155 parlevel++;
3156 else if (tok == ')')
3157 parlevel--;
3158 if (tok == TOK_LINEFEED)
3159 tok = ' ';
3160 if (!check_space(tok, &spc))
3161 tok_str_add2(&str, tok, &tokc);
3162 next_argstream(nested_list, can_read_stream, NULL);
3164 if (parlevel)
3165 expect(")");
3166 str.len -= spc;
3167 tok_str_add(&str, 0);
3168 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3169 sa1->d = str.str;
3170 sa = sa->next;
3171 if (tok == ')') {
3172 /* special case for gcc var args: add an empty
3173 var arg argument if it is omitted */
3174 if (sa && sa->type.t && gnu_ext)
3175 goto empty_arg;
3176 break;
3178 if (tok != ',')
3179 expect(",");
3181 if (sa) {
3182 tcc_error("macro '%s' used with too few args",
3183 get_tok_str(s->v, 0));
3186 parse_flags = saved_parse_flags;
3188 /* now subst each arg */
3189 mstr = macro_arg_subst(nested_list, mstr, args);
3190 /* free memory */
3191 sa = args;
3192 while (sa) {
3193 sa1 = sa->prev;
3194 tok_str_free(sa->d);
3195 sym_free(sa);
3196 sa = sa1;
3200 sym_push2(nested_list, s->v, 0, 0);
3201 parse_flags = saved_parse_flags;
3202 macro_subst(tok_str, nested_list, mstr, can_read_stream | 2);
3204 /* pop nested defined symbol */
3205 sa1 = *nested_list;
3206 *nested_list = sa1->prev;
3207 sym_free(sa1);
3208 if (mstr != s->d)
3209 tok_str_free(mstr);
3211 return 0;
3214 int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3216 CString cstr;
3217 int n;
3219 cstr_new(&cstr);
3220 if (t1 != TOK_PLCHLDR)
3221 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3222 n = cstr.size;
3223 if (t2 != TOK_PLCHLDR)
3224 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3225 cstr_ccat(&cstr, '\0');
3227 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3228 memcpy(file->buffer, cstr.data, cstr.size);
3229 for (;;) {
3230 next_nomacro1();
3231 if (0 == *file->buf_ptr)
3232 break;
3233 if (is_space(tok))
3234 continue;
3235 tcc_warning("pasting <%.*s> and <%s> does not give a valid preprocessing token",
3236 n, cstr.data, (char*)cstr.data + n);
3237 break;
3239 tcc_close();
3241 //printf("paste <%s>\n", (char*)cstr.data);
3242 cstr_free(&cstr);
3243 return 0;
3246 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3247 return the resulting string (which must be freed). */
3248 static inline int *macro_twosharps(const int *ptr0)
3250 int t;
3251 CValue cval;
3252 TokenString macro_str1;
3253 int start_of_nosubsts = -1;
3254 const int *ptr;
3256 /* we search the first '##' */
3257 for (ptr = ptr0;;) {
3258 TOK_GET(&t, &ptr, &cval);
3259 if (t == TOK_TWOSHARPS)
3260 break;
3261 if (t == 0)
3262 return NULL;
3265 tok_str_new(&macro_str1);
3267 //tok_print(" $$$", ptr0);
3268 for (ptr = ptr0;;) {
3269 TOK_GET(&t, &ptr, &cval);
3270 if (t == 0)
3271 break;
3272 if (t == TOK_TWOSHARPS)
3273 continue;
3274 while (*ptr == TOK_TWOSHARPS) {
3275 int t1; CValue cv1;
3276 /* given 'a##b', remove nosubsts preceding 'a' */
3277 if (start_of_nosubsts >= 0)
3278 macro_str1.len = start_of_nosubsts;
3279 /* given 'a##b', remove nosubsts preceding 'b' */
3280 while ((t1 = *++ptr) == TOK_NOSUBST)
3282 if (t1 && t1 != TOK_TWOSHARPS
3283 && t1 != ':') /* 'a##:' don't build a new token */
3285 TOK_GET(&t1, &ptr, &cv1);
3286 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3287 paste_tokens(t, &cval, t1, &cv1);
3288 t = tok, cval = tokc;
3292 if (t == TOK_NOSUBST) {
3293 if (start_of_nosubsts < 0)
3294 start_of_nosubsts = macro_str1.len;
3295 } else {
3296 start_of_nosubsts = -1;
3298 tok_str_add2(&macro_str1, t, &cval);
3300 tok_str_add(&macro_str1, 0);
3301 //tok_print(" ###", macro_str1.str);
3302 return macro_str1.str;
3305 /* do macro substitution of macro_str and add result to
3306 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3307 inside to avoid recursing. */
3308 static void macro_subst(
3309 TokenString *tok_str,
3310 Sym **nested_list,
3311 const int *macro_str,
3312 int can_read_stream
3315 Sym *s;
3316 const int *ptr;
3317 int t, spc, nosubst;
3318 CValue cval;
3319 int *macro_str1 = NULL;
3321 /* first scan for '##' operator handling */
3322 ptr = macro_str;
3323 spc = nosubst = 0;
3325 /* first scan for '##' operator handling */
3326 if (can_read_stream & 1) {
3327 macro_str1 = macro_twosharps(ptr);
3328 if (macro_str1)
3329 ptr = macro_str1;
3332 while (1) {
3333 TOK_GET(&t, &ptr, &cval);
3334 if (t == 0)
3335 break;
3337 if (t >= TOK_IDENT && 0 == nosubst) {
3338 s = define_find(t);
3339 if (s == NULL)
3340 goto no_subst;
3342 /* if nested substitution, do nothing */
3343 if (sym_find2(*nested_list, t)) {
3344 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3345 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3346 goto no_subst;
3350 TokenString str;
3351 str.str = (int*)ptr;
3352 begin_macro(&str, 2);
3354 tok = t;
3355 macro_subst_tok(tok_str, nested_list, s, can_read_stream);
3357 if (str.alloc == 3) {
3358 /* already finished by reading function macro arguments */
3359 break;
3362 ptr = macro_ptr;
3363 end_macro ();
3366 spc = (tok_str->len &&
3367 is_space(tok_last(tok_str->str,
3368 tok_str->str + tok_str->len)));
3370 } else {
3372 if (t == '\\' && !(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3373 tcc_error("stray '\\' in program");
3375 no_subst:
3376 if (!check_space(t, &spc))
3377 tok_str_add2(tok_str, t, &cval);
3378 nosubst = 0;
3379 if (t == TOK_NOSUBST)
3380 nosubst = 1;
3383 if (macro_str1)
3384 tok_str_free(macro_str1);
3388 /* return next token with macro substitution */
3389 ST_FUNC void next(void)
3391 redo:
3392 if (parse_flags & PARSE_FLAG_SPACES)
3393 next_nomacro_spc();
3394 else
3395 next_nomacro();
3397 if (macro_ptr) {
3398 if (tok == TOK_NOSUBST || tok == TOK_PLCHLDR) {
3399 /* discard preprocessor markers */
3400 goto redo;
3401 } else if (tok == 0) {
3402 /* end of macro or unget token string */
3403 end_macro();
3404 goto redo;
3406 } else if (tok >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3407 Sym *s;
3408 /* if reading from file, try to substitute macros */
3409 s = define_find(tok);
3410 if (s) {
3411 Sym *nested_list = NULL;
3412 tokstr_buf.len = 0;
3413 nested_list = NULL;
3414 macro_subst_tok(&tokstr_buf, &nested_list, s, 1);
3415 tok_str_add(&tokstr_buf, 0);
3416 begin_macro(&tokstr_buf, 2);
3417 goto redo;
3420 /* convert preprocessor tokens into C tokens */
3421 if (tok == TOK_PPNUM) {
3422 if (parse_flags & PARSE_FLAG_TOK_NUM)
3423 parse_number((char *)tokc.str.data);
3424 } else if (tok == TOK_PPSTR) {
3425 if (parse_flags & PARSE_FLAG_TOK_STR)
3426 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3430 /* push back current token and set current token to 'last_tok'. Only
3431 identifier case handled for labels. */
3432 ST_INLN void unget_tok(int last_tok)
3434 TokenString *str = tcc_malloc(sizeof *str);
3435 tok_str_new(str);
3436 tok_str_add2(str, tok, &tokc);
3437 tok_str_add(str, 0);
3438 begin_macro(str, 1);
3439 tok = last_tok;
3442 ST_FUNC void preprocess_init(TCCState *s1)
3444 s1->include_stack_ptr = s1->include_stack;
3445 /* XXX: move that before to avoid having to initialize
3446 file->ifdef_stack_ptr ? */
3447 s1->ifdef_stack_ptr = s1->ifdef_stack;
3448 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3450 pvtop = vtop = vstack - 1;
3451 s1->pack_stack[0] = 0;
3452 s1->pack_stack_ptr = s1->pack_stack;
3454 isidnum_table['$' - CH_EOF] =
3455 s1->dollars_in_identifiers ? IS_ID : 0;
3456 isidnum_table['.' - CH_EOF] =
3457 (parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0;
3460 ST_FUNC void preprocess_new(void)
3462 int i, c;
3463 const char *p, *r;
3465 /* init isid table */
3466 for(i = CH_EOF; i<128; i++)
3467 isidnum_table[i - CH_EOF]
3468 = is_space(i) ? IS_SPC
3469 : isid(i) ? IS_ID
3470 : isnum(i) ? IS_NUM
3471 : 0;
3473 for(i = 128; i<256; i++)
3474 isidnum_table[i - CH_EOF] = IS_ID;
3476 /* init allocators */
3477 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3478 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3479 tal_new(&cstr_alloc, CSTR_TAL_LIMIT, CSTR_TAL_SIZE);
3481 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3482 cstr_new(&cstr_buf);
3483 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3484 tok_str_new(&tokstr_buf);
3485 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3487 tok_ident = TOK_IDENT;
3488 p = tcc_keywords;
3489 while (*p) {
3490 r = p;
3491 for(;;) {
3492 c = *r++;
3493 if (c == '\0')
3494 break;
3496 tok_alloc(p, r - p - 1);
3497 p = r;
3501 ST_FUNC void preprocess_delete(void)
3503 int i, n;
3505 /* free -D and compiler defines */
3506 free_defines(NULL);
3508 /* cleanup from error/setjmp */
3509 while (macro_stack)
3510 end_macro();
3511 macro_ptr = NULL;
3513 /* free tokens */
3514 n = tok_ident - TOK_IDENT;
3515 for(i = 0; i < n; i++)
3516 tal_free(toksym_alloc, table_ident[i]);
3517 tcc_free(table_ident);
3518 table_ident = NULL;
3520 /* free static buffers */
3521 cstr_free(&tokcstr);
3522 cstr_free(&cstr_buf);
3523 tok_str_free(tokstr_buf.str);
3525 /* free allocators */
3526 tal_delete(toksym_alloc);
3527 toksym_alloc = NULL;
3528 tal_delete(tokstr_alloc);
3529 tokstr_alloc = NULL;
3530 tal_delete(cstr_alloc);
3531 cstr_alloc = NULL;
3534 /* ------------------------------------------------------------------------- */
3535 /* tcc -E [-P[1]] [-dD} support */
3537 static void tok_print(const char *msg, const int *str)
3539 FILE *fp;
3540 int t;
3541 CValue cval;
3543 fp = tcc_state->ppfp;
3544 if (!fp || !tcc_state->dflag)
3545 fp = stdout;
3547 fprintf(fp, "%s ", msg);
3548 while (str) {
3549 TOK_GET(&t, &str, &cval);
3550 if (!t)
3551 break;
3552 fprintf(fp,"%s", get_tok_str(t, &cval));
3554 fprintf(fp, "\n");
3557 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3559 int d = f->line_num - f->line_ref;
3561 if (s1->dflag & 4)
3562 return;
3564 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3565 if (level == 0 && f->line_ref && d) {
3566 d = 1;
3567 goto simple;
3569 } else if (level == 0 && f->line_ref && d < 8) {
3570 simple:
3571 while (d > 0)
3572 fputs("\n", s1->ppfp), --d;
3573 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3574 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3575 } else {
3576 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3577 level > 0 ? " 1" : level < 0 ? " 2" : "");
3579 f->line_ref = f->line_num;
3582 static void define_print(TCCState *s1, int v)
3584 FILE *fp;
3585 Sym *s;
3587 s = define_find(v);
3588 if (NULL == s || NULL == s->d)
3589 return;
3591 fp = s1->ppfp;
3592 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3593 if (s->type.t == MACRO_FUNC) {
3594 Sym *a = s->next;
3595 fprintf(fp,"(");
3596 if (a)
3597 for (;;) {
3598 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3599 if (!(a = a->next))
3600 break;
3601 fprintf(fp,",");
3603 fprintf(fp,")");
3605 tok_print("", s->d);
3608 static void pp_debug_defines(TCCState *s1)
3610 int v, t;
3611 const char *vs;
3612 FILE *fp;
3614 t = pp_debug_tok;
3615 if (t == 0)
3616 return;
3618 file->line_num--;
3619 pp_line(s1, file, 0);
3620 file->line_ref = ++file->line_num;
3622 fp = s1->ppfp;
3623 v = pp_debug_symv;
3624 vs = get_tok_str(v, NULL);
3625 if (t == TOK_DEFINE) {
3626 define_print(s1, v);
3627 } else if (t == TOK_UNDEF) {
3628 fprintf(fp, "#undef %s\n", vs);
3629 } else if (t == TOK_push_macro) {
3630 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3631 } else if (t == TOK_pop_macro) {
3632 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3634 pp_debug_tok = 0;
3637 static void pp_debug_builtins(TCCState *s1)
3639 int v;
3640 for (v = TOK_IDENT; v < tok_ident; ++v)
3641 define_print(s1, v);
3644 static int need_space(int prev_tok, int tok, const char *tokstr)
3646 const char *sp_chars = "";
3647 if ((prev_tok >= TOK_IDENT || prev_tok == TOK_PPNUM) &&
3648 (tok >= TOK_IDENT || tok == TOK_PPNUM))
3649 return 1;
3650 switch (prev_tok) {
3651 case '+':
3652 sp_chars = "+=";
3653 break;
3654 case '-':
3655 sp_chars = "-=>";
3656 break;
3657 case '*':
3658 case '/':
3659 case '%':
3660 case '^':
3661 case '=':
3662 case '!':
3663 case TOK_A_SHL:
3664 case TOK_A_SAR:
3665 sp_chars = "=";
3666 break;
3667 case '&':
3668 sp_chars = "&=";
3669 break;
3670 case '|':
3671 sp_chars = "|=";
3672 break;
3673 case '<':
3674 sp_chars = "<=";
3675 break;
3676 case '>':
3677 sp_chars = ">=";
3678 break;
3679 case '.':
3680 sp_chars = ".";
3681 break;
3682 case '#':
3683 sp_chars = "#";
3684 break;
3685 case TOK_PPNUM:
3686 sp_chars = "+-";
3687 break;
3689 return !!strchr(sp_chars, tokstr[0]);
3692 /* Preprocess the current file */
3693 ST_FUNC int tcc_preprocess(TCCState *s1)
3695 BufferedFile **iptr;
3696 int token_seen, spcs, level;
3697 Sym *define_start;
3698 const char *tokstr;
3700 preprocess_init(s1);
3701 ch = file->buf_ptr[0];
3702 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3703 parse_flags = PARSE_FLAG_PREPROCESS
3704 | (parse_flags & PARSE_FLAG_ASM_FILE)
3705 | PARSE_FLAG_LINEFEED
3706 | PARSE_FLAG_SPACES
3707 | PARSE_FLAG_ACCEPT_STRAYS
3709 define_start = define_stack;
3711 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3712 capability to compile and run itself, provided all numbers are
3713 given as decimals. tcc -E -P10 will do. */
3714 if (s1->Pflag == 1 + 10)
3715 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3717 #ifdef PP_BENCH
3718 /* for PP benchmarks */
3719 do next(); while (tok != TOK_EOF); return 0;
3720 #endif
3722 if (s1->dflag & 1) {
3723 pp_debug_builtins(s1);
3724 s1->dflag &= ~1;
3727 token_seen = TOK_LINEFEED, spcs = 0;
3728 pp_line(s1, file, 0);
3730 for (;;) {
3731 iptr = s1->include_stack_ptr;
3732 next();
3733 if (tok == TOK_EOF)
3734 break;
3735 level = s1->include_stack_ptr - iptr;
3736 if (level) {
3737 if (level > 0)
3738 pp_line(s1, *iptr, 0);
3739 pp_line(s1, file, level);
3742 if (s1->dflag) {
3743 pp_debug_defines(s1);
3744 if (s1->dflag & 4)
3745 continue;
3748 if (token_seen == TOK_LINEFEED) {
3749 if (tok == ' ') {
3750 ++spcs;
3751 continue;
3753 if (tok == TOK_LINEFEED) {
3754 spcs = 0;
3755 continue;
3757 pp_line(s1, file, 0);
3758 } else if (tok == TOK_LINEFEED) {
3759 ++file->line_ref;
3762 tokstr = get_tok_str(tok, &tokc);
3763 if (!spcs && need_space(token_seen, tok, tokstr))
3764 ++spcs;
3765 while (spcs)
3766 fputs(" ", s1->ppfp), --spcs;
3767 fputs(tokstr, s1->ppfp);
3769 token_seen = tok;
3771 /* reset define stack, but keep -D and built-ins */
3772 free_defines(define_start);
3773 return 0;
3776 /* ------------------------------------------------------------------------- */