Check for errors before codesign
[tinycc.git] / tccpp.c
blobae9ae00313f58b95821031ccb78f27ee13f8e4e4
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 #define USING_GLOBALS
22 #include "tcc.h"
24 /* #define to 1 to enable (see parse_pp_string()) */
25 #define ACCEPT_LF_IN_STRINGS 0
27 /********************************************************/
28 /* global variables */
30 ST_DATA int tok_flags;
31 ST_DATA int parse_flags;
33 ST_DATA struct BufferedFile *file;
34 ST_DATA int tok;
35 ST_DATA CValue tokc;
36 ST_DATA const int *macro_ptr;
37 ST_DATA CString tokcstr; /* current parsed string, if any */
39 /* display benchmark infos */
40 ST_DATA int tok_ident;
41 ST_DATA TokenSym **table_ident;
43 /* ------------------------------------------------------------------------- */
45 static TokenSym *hash_ident[TOK_HASH_SIZE];
46 static char token_buf[STRING_MAX_SIZE + 1];
47 static CString cstr_buf;
48 static TokenString tokstr_buf;
49 static unsigned char isidnum_table[256 - CH_EOF];
50 static int pp_debug_tok, pp_debug_symv;
51 static int pp_expr;
52 static int pp_counter;
53 static void tok_print(const char *msg, const int *str);
55 static struct TinyAlloc *toksym_alloc;
56 static struct TinyAlloc *tokstr_alloc;
58 static TokenString *macro_stack;
60 static const char tcc_keywords[] =
61 #define DEF(id, str) str "\0"
62 #include "tcctok.h"
63 #undef DEF
66 /* WARNING: the content of this string encodes token numbers */
67 static const unsigned char tok_two_chars[] =
68 /* outdated -- gr
69 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
70 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
71 */{
72 '<','=', TOK_LE,
73 '>','=', TOK_GE,
74 '!','=', TOK_NE,
75 '&','&', TOK_LAND,
76 '|','|', TOK_LOR,
77 '+','+', TOK_INC,
78 '-','-', TOK_DEC,
79 '=','=', TOK_EQ,
80 '<','<', TOK_SHL,
81 '>','>', TOK_SAR,
82 '+','=', TOK_A_ADD,
83 '-','=', TOK_A_SUB,
84 '*','=', TOK_A_MUL,
85 '/','=', TOK_A_DIV,
86 '%','=', TOK_A_MOD,
87 '&','=', TOK_A_AND,
88 '^','=', TOK_A_XOR,
89 '|','=', TOK_A_OR,
90 '-','>', TOK_ARROW,
91 '.','.', TOK_TWODOTS,
92 '#','#', TOK_TWOSHARPS,
93 '#','#', TOK_PPJOIN,
97 static void next_nomacro(void);
99 ST_FUNC void skip(int c)
101 if (tok != c) {
102 char tmp[40];
103 pstrcpy(tmp, sizeof tmp, get_tok_str(c, &tokc));
104 tcc_error("'%s' expected (got \"%s\")", tmp, get_tok_str(tok, &tokc));
106 next();
109 ST_FUNC void expect(const char *msg)
111 tcc_error("%s expected", msg);
114 /* ------------------------------------------------------------------------- */
115 /* Custom allocator for tiny objects */
117 #define USE_TAL
119 #ifndef USE_TAL
120 #define tal_free(al, p) tcc_free(p)
121 #define tal_realloc(al, p, size) tcc_realloc(p, size)
122 #define tal_new(a,b,c)
123 #define tal_delete(a)
124 #else
125 #if !defined(MEM_DEBUG)
126 #define tal_free(al, p) tal_free_impl(al, p)
127 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
128 #define TAL_DEBUG_PARAMS
129 #else
130 #define TAL_DEBUG 1
131 //#define TAL_INFO 1 /* collect and dump allocators stats */
132 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
133 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
134 #define TAL_DEBUG_PARAMS , const char *file, int line
135 #define TAL_DEBUG_FILE_LEN 40
136 #endif
138 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
139 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
140 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
141 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
142 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
143 #define CSTR_TAL_LIMIT 1024
145 typedef struct TinyAlloc {
146 unsigned limit;
147 unsigned size;
148 uint8_t *buffer;
149 uint8_t *p;
150 unsigned nb_allocs;
151 struct TinyAlloc *next, *top;
152 #ifdef TAL_INFO
153 unsigned nb_peak;
154 unsigned nb_total;
155 unsigned nb_missed;
156 uint8_t *peak_p;
157 #endif
158 } TinyAlloc;
160 typedef struct tal_header_t {
161 unsigned size;
162 #ifdef TAL_DEBUG
163 int line_num; /* negative line_num used for double free check */
164 char file_name[TAL_DEBUG_FILE_LEN + 1];
165 #endif
166 } tal_header_t;
168 /* ------------------------------------------------------------------------- */
170 static TinyAlloc *tal_new(TinyAlloc **pal, unsigned limit, unsigned size)
172 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
173 al->p = al->buffer = tcc_malloc(size);
174 al->limit = limit;
175 al->size = size;
176 if (pal) *pal = al;
177 return al;
180 static void tal_delete(TinyAlloc *al)
182 TinyAlloc *next;
184 tail_call:
185 if (!al)
186 return;
187 #ifdef TAL_INFO
188 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
189 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
190 (al->peak_p - al->buffer) * 100.0 / al->size);
191 #endif
192 #ifdef TAL_DEBUG
193 if (al->nb_allocs > 0) {
194 uint8_t *p;
195 fprintf(stderr, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
196 al->nb_allocs, al->limit);
197 p = al->buffer;
198 while (p < al->p) {
199 tal_header_t *header = (tal_header_t *)p;
200 if (header->line_num > 0) {
201 fprintf(stderr, "%s:%d: chunk of %d bytes leaked\n",
202 header->file_name, header->line_num, header->size);
204 p += header->size + sizeof(tal_header_t);
206 #if MEM_DEBUG-0 == 2
207 exit(2);
208 #endif
210 #endif
211 next = al->next;
212 tcc_free(al->buffer);
213 tcc_free(al);
214 al = next;
215 goto tail_call;
218 static void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
220 if (!p)
221 return;
222 tail_call:
223 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
224 #ifdef TAL_DEBUG
225 tal_header_t *header = (((tal_header_t *)p) - 1);
226 if (header->line_num < 0) {
227 fprintf(stderr, "%s:%d: TAL_DEBUG: double frees chunk from\n",
228 file, line);
229 fprintf(stderr, "%s:%d: %d bytes\n",
230 header->file_name, (int)-header->line_num, (int)header->size);
231 } else
232 header->line_num = -header->line_num;
233 #endif
234 al->nb_allocs--;
235 if (!al->nb_allocs)
236 al->p = al->buffer;
237 } else if (al->next) {
238 al = al->next;
239 goto tail_call;
241 else
242 tcc_free(p);
245 static void *tal_realloc_impl(TinyAlloc **pal, void *p, unsigned size TAL_DEBUG_PARAMS)
247 tal_header_t *header;
248 void *ret;
249 int is_own;
250 unsigned adj_size = (size + 3) & -4;
251 TinyAlloc *al = *pal;
253 tail_call:
254 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
255 if ((!p || is_own) && size <= al->limit) {
256 if (al->p - al->buffer + adj_size + sizeof(tal_header_t) < al->size) {
257 header = (tal_header_t *)al->p;
258 header->size = adj_size;
259 #ifdef TAL_DEBUG
260 { int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
261 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
262 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
263 header->line_num = line; }
264 #endif
265 ret = al->p + sizeof(tal_header_t);
266 al->p += adj_size + sizeof(tal_header_t);
267 if (is_own) {
268 header = (((tal_header_t *)p) - 1);
269 if (p) memcpy(ret, p, header->size);
270 #ifdef TAL_DEBUG
271 header->line_num = -header->line_num;
272 #endif
273 } else {
274 al->nb_allocs++;
276 #ifdef TAL_INFO
277 if (al->nb_peak < al->nb_allocs)
278 al->nb_peak = al->nb_allocs;
279 if (al->peak_p < al->p)
280 al->peak_p = al->p;
281 al->nb_total++;
282 #endif
283 return ret;
284 } else if (is_own) {
285 al->nb_allocs--;
286 ret = tal_realloc(*pal, 0, size);
287 header = (((tal_header_t *)p) - 1);
288 if (p) memcpy(ret, p, header->size);
289 #ifdef TAL_DEBUG
290 header->line_num = -header->line_num;
291 #endif
292 return ret;
294 if (al->next) {
295 al = al->next;
296 } else {
297 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
299 al = tal_new(pal, next->limit, next->size * 2);
300 al->next = next;
301 bottom->top = al;
303 goto tail_call;
305 if (is_own) {
306 al->nb_allocs--;
307 ret = tcc_malloc(size);
308 header = (((tal_header_t *)p) - 1);
309 if (p) memcpy(ret, p, header->size);
310 #ifdef TAL_DEBUG
311 header->line_num = -header->line_num;
312 #endif
313 } else if (al->next) {
314 al = al->next;
315 goto tail_call;
316 } else
317 ret = tcc_realloc(p, size);
318 #ifdef TAL_INFO
319 al->nb_missed++;
320 #endif
321 return ret;
324 #endif /* USE_TAL */
326 /* ------------------------------------------------------------------------- */
327 /* CString handling */
328 static void cstr_realloc(CString *cstr, int new_size)
330 int size;
332 size = cstr->size_allocated;
333 if (size < 8)
334 size = 8; /* no need to allocate a too small first string */
335 while (size < new_size)
336 size = size * 2;
337 cstr->data = tcc_realloc(cstr->data, size);
338 cstr->size_allocated = size;
341 /* add a byte */
342 ST_INLN void cstr_ccat(CString *cstr, int ch)
344 int size;
345 size = cstr->size + 1;
346 if (size > cstr->size_allocated)
347 cstr_realloc(cstr, size);
348 ((unsigned char *)cstr->data)[size - 1] = ch;
349 cstr->size = size;
352 ST_INLN char *unicode_to_utf8 (char *b, uint32_t Uc)
354 if (Uc<0x80) *b++=Uc;
355 else if (Uc<0x800) *b++=192+Uc/64, *b++=128+Uc%64;
356 else if (Uc-0xd800u<0x800) goto error;
357 else if (Uc<0x10000) *b++=224+Uc/4096, *b++=128+Uc/64%64, *b++=128+Uc%64;
358 else if (Uc<0x110000) *b++=240+Uc/262144, *b++=128+Uc/4096%64, *b++=128+Uc/64%64, *b++=128+Uc%64;
359 else error: tcc_error("0x%x is not a valid universal character", Uc);
360 return b;
363 /* add a unicode character expanded into utf8 */
364 ST_INLN void cstr_u8cat(CString *cstr, int ch)
366 char buf[4], *e;
367 e = unicode_to_utf8(buf, (uint32_t)ch);
368 cstr_cat(cstr, buf, e - buf);
371 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
373 int size;
374 if (len <= 0)
375 len = strlen(str) + 1 + len;
376 size = cstr->size + len;
377 if (size > cstr->size_allocated)
378 cstr_realloc(cstr, size);
379 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
380 cstr->size = size;
383 /* add a wide char */
384 ST_FUNC void cstr_wccat(CString *cstr, int ch)
386 int size;
387 size = cstr->size + sizeof(nwchar_t);
388 if (size > cstr->size_allocated)
389 cstr_realloc(cstr, size);
390 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
391 cstr->size = size;
394 ST_FUNC void cstr_new(CString *cstr)
396 memset(cstr, 0, sizeof(CString));
399 /* free string and reset it to NULL */
400 ST_FUNC void cstr_free(CString *cstr)
402 tcc_free(cstr->data);
405 /* reset string to empty */
406 ST_FUNC void cstr_reset(CString *cstr)
408 cstr->size = 0;
411 ST_FUNC int cstr_vprintf(CString *cstr, const char *fmt, va_list ap)
413 va_list v;
414 int len, size = 80;
415 for (;;) {
416 size += cstr->size;
417 if (size > cstr->size_allocated)
418 cstr_realloc(cstr, size);
419 size = cstr->size_allocated - cstr->size;
420 va_copy(v, ap);
421 len = vsnprintf((char*)cstr->data + cstr->size, size, fmt, v);
422 va_end(v);
423 if (len >= 0 && len < size)
424 break;
425 size *= 2;
427 cstr->size += len;
428 return len;
431 ST_FUNC int cstr_printf(CString *cstr, const char *fmt, ...)
433 va_list ap; int len;
434 va_start(ap, fmt);
435 len = cstr_vprintf(cstr, fmt, ap);
436 va_end(ap);
437 return len;
440 /* XXX: unicode ? */
441 static void add_char(CString *cstr, int c)
443 if (c == '\'' || c == '\"' || c == '\\') {
444 /* XXX: could be more precise if char or string */
445 cstr_ccat(cstr, '\\');
447 if (c >= 32 && c <= 126) {
448 cstr_ccat(cstr, c);
449 } else {
450 cstr_ccat(cstr, '\\');
451 if (c == '\n') {
452 cstr_ccat(cstr, 'n');
453 } else {
454 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
455 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
456 cstr_ccat(cstr, '0' + (c & 7));
461 /* ------------------------------------------------------------------------- */
462 /* allocate a new token */
463 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
465 TokenSym *ts, **ptable;
466 int i;
468 if (tok_ident >= SYM_FIRST_ANOM)
469 tcc_error("memory full (symbols)");
471 /* expand token table if needed */
472 i = tok_ident - TOK_IDENT;
473 if ((i % TOK_ALLOC_INCR) == 0) {
474 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
475 table_ident = ptable;
478 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
479 table_ident[i] = ts;
480 ts->tok = tok_ident++;
481 ts->sym_define = NULL;
482 ts->sym_label = NULL;
483 ts->sym_struct = NULL;
484 ts->sym_identifier = NULL;
485 ts->len = len;
486 ts->hash_next = NULL;
487 memcpy(ts->str, str, len);
488 ts->str[len] = '\0';
489 *pts = ts;
490 return ts;
493 #define TOK_HASH_INIT 1
494 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
497 /* find a token and add it if not found */
498 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
500 TokenSym *ts, **pts;
501 int i;
502 unsigned int h;
504 h = TOK_HASH_INIT;
505 for(i=0;i<len;i++)
506 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
507 h &= (TOK_HASH_SIZE - 1);
509 pts = &hash_ident[h];
510 for(;;) {
511 ts = *pts;
512 if (!ts)
513 break;
514 if (ts->len == len && !memcmp(ts->str, str, len))
515 return ts;
516 pts = &(ts->hash_next);
518 return tok_alloc_new(pts, str, len);
521 ST_FUNC int tok_alloc_const(const char *str)
523 return tok_alloc(str, strlen(str))->tok;
527 /* XXX: buffer overflow */
528 /* XXX: float tokens */
529 ST_FUNC const char *get_tok_str(int v, CValue *cv)
531 char *p;
532 int i, len;
534 cstr_reset(&cstr_buf);
535 p = cstr_buf.data;
537 switch(v) {
538 case TOK_CINT:
539 case TOK_CUINT:
540 case TOK_CLONG:
541 case TOK_CULONG:
542 case TOK_CLLONG:
543 case TOK_CULLONG:
544 /* XXX: not quite exact, but only useful for testing */
545 #ifdef _WIN32
546 sprintf(p, "%u", (unsigned)cv->i);
547 #else
548 sprintf(p, "%llu", (unsigned long long)cv->i);
549 #endif
550 break;
551 case TOK_LCHAR:
552 cstr_ccat(&cstr_buf, 'L');
553 case TOK_CCHAR:
554 cstr_ccat(&cstr_buf, '\'');
555 add_char(&cstr_buf, cv->i);
556 cstr_ccat(&cstr_buf, '\'');
557 cstr_ccat(&cstr_buf, '\0');
558 break;
559 case TOK_PPNUM:
560 case TOK_PPSTR:
561 return (char*)cv->str.data;
562 case TOK_LSTR:
563 cstr_ccat(&cstr_buf, 'L');
564 case TOK_STR:
565 cstr_ccat(&cstr_buf, '\"');
566 if (v == TOK_STR) {
567 len = cv->str.size - 1;
568 for(i=0;i<len;i++)
569 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
570 } else {
571 len = (cv->str.size / sizeof(nwchar_t)) - 1;
572 for(i=0;i<len;i++)
573 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
575 cstr_ccat(&cstr_buf, '\"');
576 cstr_ccat(&cstr_buf, '\0');
577 break;
579 case TOK_CFLOAT:
580 return strcpy(p, "<float>");
581 case TOK_CDOUBLE:
582 return strcpy(p, "<double>");
583 case TOK_CLDOUBLE:
584 return strcpy(p, "<long double>");
585 case TOK_LINENUM:
586 return strcpy(p, "<linenumber");
588 /* above tokens have value, the ones below don't */
589 case TOK_LT:
590 v = '<';
591 goto addv;
592 case TOK_GT:
593 v = '>';
594 goto addv;
595 case TOK_DOTS:
596 return strcpy(p, "...");
597 case TOK_A_SHL:
598 return strcpy(p, "<<=");
599 case TOK_A_SAR:
600 return strcpy(p, ">>=");
601 case TOK_EOF:
602 return strcpy(p, "<eof>");
603 case 0: /* anonymous nameless symbols */
604 return strcpy(p, "<no name>");
605 default:
606 if (v < TOK_IDENT) {
607 /* search in two bytes table */
608 const unsigned char *q = tok_two_chars;
609 while (*q) {
610 if (q[2] == v) {
611 *p++ = q[0];
612 *p++ = q[1];
613 *p = '\0';
614 return cstr_buf.data;
616 q += 3;
618 if (v >= 127 || (v < 32 && !is_space(v) && v != '\n')) {
619 sprintf(p, "<\\x%02x>", v);
620 break;
622 addv:
623 *p++ = v;
624 *p = '\0';
625 } else if (v < tok_ident) {
626 return table_ident[v - TOK_IDENT]->str;
627 } else if (v >= SYM_FIRST_ANOM) {
628 /* special name for anonymous symbol */
629 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
630 } else {
631 /* should never happen */
632 return NULL;
634 break;
636 return cstr_buf.data;
639 static inline int check_space(int t, int *spc)
641 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
642 if (*spc)
643 return 1;
644 *spc = 1;
645 } else
646 *spc = 0;
647 return 0;
650 /* return the current character, handling end of block if necessary
651 (but not stray) */
652 static int handle_eob(void)
654 BufferedFile *bf = file;
655 int len;
657 /* only tries to read if really end of buffer */
658 if (bf->buf_ptr >= bf->buf_end) {
659 if (bf->fd >= 0) {
660 #if defined(PARSE_DEBUG)
661 len = 1;
662 #else
663 len = IO_BUF_SIZE;
664 #endif
665 len = read(bf->fd, bf->buffer, len);
666 if (len < 0)
667 len = 0;
668 } else {
669 len = 0;
671 total_bytes += len;
672 bf->buf_ptr = bf->buffer;
673 bf->buf_end = bf->buffer + len;
674 *bf->buf_end = CH_EOB;
676 if (bf->buf_ptr < bf->buf_end) {
677 return bf->buf_ptr[0];
678 } else {
679 bf->buf_ptr = bf->buf_end;
680 return CH_EOF;
684 /* read next char from current input file and handle end of input buffer */
685 static int next_c(void)
687 int ch = *++file->buf_ptr;
688 /* end of buffer/file handling */
689 if (ch == CH_EOB && file->buf_ptr >= file->buf_end)
690 ch = handle_eob();
691 return ch;
694 /* input with '\[\r]\n' handling. */
695 static int handle_stray_noerror(int err)
697 int ch;
698 while ((ch = next_c()) == '\\') {
699 ch = next_c();
700 if (ch == '\n') {
701 newl:
702 file->line_num++;
703 } else {
704 if (ch == '\r') {
705 ch = next_c();
706 if (ch == '\n')
707 goto newl;
708 *--file->buf_ptr = '\r';
710 if (err)
711 tcc_error("stray '\\' in program");
712 /* may take advantage of 'BufferedFile.unget[4}' */
713 return *--file->buf_ptr = '\\';
716 return ch;
719 #define ninp() handle_stray_noerror(0)
721 /* handle '\\' in strings, comments and skipped regions */
722 static int handle_bs(uint8_t **p)
724 int c;
725 file->buf_ptr = *p - 1;
726 c = ninp();
727 *p = file->buf_ptr;
728 return c;
731 /* skip the stray and handle the \\n case. Output an error if
732 incorrect char after the stray */
733 static int handle_stray(uint8_t **p)
735 int c;
736 file->buf_ptr = *p - 1;
737 c = handle_stray_noerror(!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS));
738 *p = file->buf_ptr;
739 return c;
742 /* handle the complicated stray case */
743 #define PEEKC(c, p)\
745 c = *++p;\
746 if (c == '\\')\
747 c = handle_stray(&p); \
750 static int skip_spaces(void)
752 int ch;
753 --file->buf_ptr;
754 do {
755 ch = ninp();
756 } while (isidnum_table[ch - CH_EOF] & IS_SPC);
757 return ch;
760 /* single line C++ comments */
761 static uint8_t *parse_line_comment(uint8_t *p)
763 int c;
764 for(;;) {
765 for (;;) {
766 c = *++p;
767 redo:
768 if (c == '\n' || c == '\\')
769 break;
770 c = *++p;
771 if (c == '\n' || c == '\\')
772 break;
774 if (c == '\n')
775 break;
776 c = handle_bs(&p);
777 if (c == CH_EOF)
778 break;
779 if (c != '\\')
780 goto redo;
782 return p;
785 /* C comments */
786 static uint8_t *parse_comment(uint8_t *p)
788 int c;
789 for(;;) {
790 /* fast skip loop */
791 for(;;) {
792 c = *++p;
793 redo:
794 if (c == '\n' || c == '*' || c == '\\')
795 break;
796 c = *++p;
797 if (c == '\n' || c == '*' || c == '\\')
798 break;
800 /* now we can handle all the cases */
801 if (c == '\n') {
802 file->line_num++;
803 } else if (c == '*') {
804 do {
805 c = *++p;
806 } while (c == '*');
807 if (c == '\\')
808 c = handle_bs(&p);
809 if (c == '/')
810 break;
811 goto check_eof;
812 } else {
813 c = handle_bs(&p);
814 check_eof:
815 if (c == CH_EOF)
816 tcc_error("unexpected end of file in comment");
817 if (c != '\\')
818 goto redo;
821 return p + 1;
824 /* parse a string without interpreting escapes */
825 static uint8_t *parse_pp_string(uint8_t *p, int sep, CString *str)
827 int c;
828 for(;;) {
829 c = *++p;
830 redo:
831 if (c == sep) {
832 break;
833 } else if (c == '\\') {
834 c = handle_bs(&p);
835 if (c == CH_EOF) {
836 unterminated_string:
837 /* XXX: indicate line number of start of string */
838 tok_flags &= ~TOK_FLAG_BOL;
839 tcc_error("missing terminating %c character", sep);
840 } else if (c == '\\') {
841 if (str)
842 cstr_ccat(str, c);
843 c = *++p;
844 /* add char after '\\' unconditionally */
845 if (c == '\\') {
846 c = handle_bs(&p);
847 if (c == CH_EOF)
848 goto unterminated_string;
850 goto add_char;
851 } else {
852 goto redo;
854 } else if (c == '\n') {
855 add_lf:
856 if (ACCEPT_LF_IN_STRINGS) {
857 file->line_num++;
858 goto add_char;
859 } else if (str) { /* not skipping */
860 goto unterminated_string;
861 } else {
862 //tcc_warning("missing terminating %c character", sep);
863 return p;
865 } else if (c == '\r') {
866 c = *++p;
867 if (c == '\\')
868 c = handle_bs(&p);
869 if (c == '\n')
870 goto add_lf;
871 if (c == CH_EOF)
872 goto unterminated_string;
873 if (str)
874 cstr_ccat(str, '\r');
875 goto redo;
876 } else {
877 add_char:
878 if (str)
879 cstr_ccat(str, c);
882 p++;
883 return p;
886 /* skip block of text until #else, #elif or #endif. skip also pairs of
887 #if/#endif */
888 static void preprocess_skip(void)
890 int a, start_of_line, c, in_warn_or_error;
891 uint8_t *p;
893 p = file->buf_ptr;
894 a = 0;
895 redo_start:
896 start_of_line = 1;
897 in_warn_or_error = 0;
898 for(;;) {
899 redo_no_start:
900 c = *p;
901 switch(c) {
902 case ' ':
903 case '\t':
904 case '\f':
905 case '\v':
906 case '\r':
907 p++;
908 goto redo_no_start;
909 case '\n':
910 file->line_num++;
911 p++;
912 goto redo_start;
913 case '\\':
914 c = handle_bs(&p);
915 if (c == CH_EOF)
916 expect("#endif");
917 if (c == '\\')
918 ++p;
919 goto redo_no_start;
920 /* skip strings */
921 case '\"':
922 case '\'':
923 if (in_warn_or_error)
924 goto _default;
925 tok_flags &= ~TOK_FLAG_BOL;
926 p = parse_pp_string(p, c, NULL);
927 break;
928 /* skip comments */
929 case '/':
930 if (in_warn_or_error)
931 goto _default;
932 ++p;
933 c = handle_bs(&p);
934 if (c == '*') {
935 p = parse_comment(p);
936 } else if (c == '/') {
937 p = parse_line_comment(p);
939 break;
940 case '#':
941 p++;
942 if (start_of_line) {
943 file->buf_ptr = p;
944 next_nomacro();
945 p = file->buf_ptr;
946 if (a == 0 &&
947 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
948 goto the_end;
949 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
950 a++;
951 else if (tok == TOK_ENDIF)
952 a--;
953 else if( tok == TOK_ERROR || tok == TOK_WARNING)
954 in_warn_or_error = 1;
955 else if (tok == TOK_LINEFEED)
956 goto redo_start;
957 else if (parse_flags & PARSE_FLAG_ASM_FILE)
958 p = parse_line_comment(p - 1);
960 #if !defined(TCC_TARGET_ARM)
961 else if (parse_flags & PARSE_FLAG_ASM_FILE)
962 p = parse_line_comment(p - 1);
963 #else
964 /* ARM assembly uses '#' for constants */
965 #endif
966 break;
967 _default:
968 default:
969 p++;
970 break;
972 start_of_line = 0;
974 the_end: ;
975 file->buf_ptr = p;
978 #if 0
979 /* return the number of additional 'ints' necessary to store the
980 token */
981 static inline int tok_size(const int *p)
983 switch(*p) {
984 /* 4 bytes */
985 case TOK_CINT:
986 case TOK_CUINT:
987 case TOK_CCHAR:
988 case TOK_LCHAR:
989 case TOK_CFLOAT:
990 case TOK_LINENUM:
991 return 1 + 1;
992 case TOK_STR:
993 case TOK_LSTR:
994 case TOK_PPNUM:
995 case TOK_PPSTR:
996 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
997 case TOK_CLONG:
998 case TOK_CULONG:
999 return 1 + LONG_SIZE / 4;
1000 case TOK_CDOUBLE:
1001 case TOK_CLLONG:
1002 case TOK_CULLONG:
1003 return 1 + 2;
1004 case TOK_CLDOUBLE:
1005 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
1006 return 1 + 8 / 4;
1007 #else
1008 return 1 + LDOUBLE_SIZE / 4;
1009 #endif
1010 default:
1011 return 1 + 0;
1014 #endif
1016 /* token string handling */
1017 ST_INLN void tok_str_new(TokenString *s)
1019 s->str = NULL;
1020 s->len = s->lastlen = 0;
1021 s->allocated_len = 0;
1022 s->last_line_num = -1;
1025 ST_FUNC TokenString *tok_str_alloc(void)
1027 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1028 tok_str_new(str);
1029 return str;
1032 ST_FUNC int *tok_str_dup(TokenString *s)
1034 int *str;
1036 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1037 memcpy(str, s->str, s->len * sizeof(int));
1038 return str;
1041 ST_FUNC void tok_str_free_str(int *str)
1043 tal_free(tokstr_alloc, str);
1046 ST_FUNC void tok_str_free(TokenString *str)
1048 tok_str_free_str(str->str);
1049 tal_free(tokstr_alloc, str);
1052 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1054 int *str, size;
1056 size = s->allocated_len;
1057 if (size < 16)
1058 size = 16;
1059 while (size < new_size)
1060 size = size * 2;
1061 if (size > s->allocated_len) {
1062 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1063 s->allocated_len = size;
1064 s->str = str;
1066 return s->str;
1069 ST_FUNC void tok_str_add(TokenString *s, int t)
1071 int len, *str;
1073 len = s->len;
1074 str = s->str;
1075 if (len >= s->allocated_len)
1076 str = tok_str_realloc(s, len + 1);
1077 str[len++] = t;
1078 s->len = len;
1081 ST_FUNC void begin_macro(TokenString *str, int alloc)
1083 str->alloc = alloc;
1084 str->prev = macro_stack;
1085 str->prev_ptr = macro_ptr;
1086 str->save_line_num = file->line_num;
1087 macro_ptr = str->str;
1088 macro_stack = str;
1091 ST_FUNC void end_macro(void)
1093 TokenString *str = macro_stack;
1094 macro_stack = str->prev;
1095 macro_ptr = str->prev_ptr;
1096 file->line_num = str->save_line_num;
1097 str->len = 0; /* matters if str not alloced, may be tokstr_buf */
1098 if (str->alloc != 0) {
1099 if (str->alloc == 2)
1100 str->str = NULL; /* don't free */
1101 tok_str_free(str);
1105 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1107 int len, *str;
1109 len = s->lastlen = s->len;
1110 str = s->str;
1112 /* allocate space for worst case */
1113 if (len + TOK_MAX_SIZE >= s->allocated_len)
1114 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1115 str[len++] = t;
1116 switch(t) {
1117 case TOK_CINT:
1118 case TOK_CUINT:
1119 case TOK_CCHAR:
1120 case TOK_LCHAR:
1121 case TOK_CFLOAT:
1122 case TOK_LINENUM:
1123 #if LONG_SIZE == 4
1124 case TOK_CLONG:
1125 case TOK_CULONG:
1126 #endif
1127 str[len++] = cv->tab[0];
1128 break;
1129 case TOK_PPNUM:
1130 case TOK_PPSTR:
1131 case TOK_STR:
1132 case TOK_LSTR:
1134 /* Insert the string into the int array. */
1135 size_t nb_words =
1136 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1137 if (len + nb_words >= s->allocated_len)
1138 str = tok_str_realloc(s, len + nb_words + 1);
1139 str[len] = cv->str.size;
1140 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1141 len += nb_words;
1143 break;
1144 case TOK_CDOUBLE:
1145 case TOK_CLLONG:
1146 case TOK_CULLONG:
1147 #if LONG_SIZE == 8
1148 case TOK_CLONG:
1149 case TOK_CULONG:
1150 #endif
1151 str[len++] = cv->tab[0];
1152 str[len++] = cv->tab[1];
1153 break;
1154 case TOK_CLDOUBLE:
1155 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1156 str[len++] = cv->tab[0];
1157 str[len++] = cv->tab[1];
1158 #elif LDOUBLE_SIZE == 12
1159 str[len++] = cv->tab[0];
1160 str[len++] = cv->tab[1];
1161 str[len++] = cv->tab[2];
1162 #elif LDOUBLE_SIZE == 16
1163 str[len++] = cv->tab[0];
1164 str[len++] = cv->tab[1];
1165 str[len++] = cv->tab[2];
1166 str[len++] = cv->tab[3];
1167 #else
1168 #error add long double size support
1169 #endif
1170 break;
1171 default:
1172 break;
1174 s->len = len;
1177 /* add the current parse token in token string 's' */
1178 ST_FUNC void tok_str_add_tok(TokenString *s)
1180 CValue cval;
1182 /* save line number info */
1183 if (file->line_num != s->last_line_num) {
1184 s->last_line_num = file->line_num;
1185 cval.i = s->last_line_num;
1186 tok_str_add2(s, TOK_LINENUM, &cval);
1188 tok_str_add2(s, tok, &tokc);
1191 /* get a token from an integer array and increment pointer. */
1192 static inline void tok_get(int *t, const int **pp, CValue *cv)
1194 const int *p = *pp;
1195 int n, *tab;
1197 tab = cv->tab;
1198 switch(*t = *p++) {
1199 #if LONG_SIZE == 4
1200 case TOK_CLONG:
1201 #endif
1202 case TOK_CINT:
1203 case TOK_CCHAR:
1204 case TOK_LCHAR:
1205 case TOK_LINENUM:
1206 cv->i = *p++;
1207 break;
1208 #if LONG_SIZE == 4
1209 case TOK_CULONG:
1210 #endif
1211 case TOK_CUINT:
1212 cv->i = (unsigned)*p++;
1213 break;
1214 case TOK_CFLOAT:
1215 tab[0] = *p++;
1216 break;
1217 case TOK_STR:
1218 case TOK_LSTR:
1219 case TOK_PPNUM:
1220 case TOK_PPSTR:
1221 cv->str.size = *p++;
1222 cv->str.data = p;
1223 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1224 break;
1225 case TOK_CDOUBLE:
1226 case TOK_CLLONG:
1227 case TOK_CULLONG:
1228 #if LONG_SIZE == 8
1229 case TOK_CLONG:
1230 case TOK_CULONG:
1231 #endif
1232 n = 2;
1233 goto copy;
1234 case TOK_CLDOUBLE:
1235 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1236 n = 2;
1237 #elif LDOUBLE_SIZE == 12
1238 n = 3;
1239 #elif LDOUBLE_SIZE == 16
1240 n = 4;
1241 #else
1242 # error add long double size support
1243 #endif
1244 copy:
1246 *tab++ = *p++;
1247 while (--n);
1248 break;
1249 default:
1250 break;
1252 *pp = p;
1255 #if 0
1256 # define TOK_GET(t,p,c) tok_get(t,p,c)
1257 #else
1258 # define TOK_GET(t,p,c) do { \
1259 int _t = **(p); \
1260 if (TOK_HAS_VALUE(_t)) \
1261 tok_get(t, p, c); \
1262 else \
1263 *(t) = _t, ++*(p); \
1264 } while (0)
1265 #endif
1267 static int macro_is_equal(const int *a, const int *b)
1269 CValue cv;
1270 int t;
1272 if (!a || !b)
1273 return 1;
1275 while (*a && *b) {
1276 cstr_reset(&tokcstr);
1277 TOK_GET(&t, &a, &cv);
1278 cstr_cat(&tokcstr, get_tok_str(t, &cv), 0);
1279 TOK_GET(&t, &b, &cv);
1280 if (strcmp(tokcstr.data, get_tok_str(t, &cv)))
1281 return 0;
1283 return !(*a || *b);
1286 /* defines handling */
1287 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1289 Sym *s, *o;
1291 o = define_find(v);
1292 s = sym_push2(&define_stack, v, macro_type, 0);
1293 s->d = str;
1294 s->next = first_arg;
1295 table_ident[v - TOK_IDENT]->sym_define = s;
1297 if (o && !macro_is_equal(o->d, s->d))
1298 tcc_warning("%s redefined", get_tok_str(v, NULL));
1301 /* undefined a define symbol. Its name is just set to zero */
1302 ST_FUNC void define_undef(Sym *s)
1304 int v = s->v;
1305 if (v >= TOK_IDENT && v < tok_ident)
1306 table_ident[v - TOK_IDENT]->sym_define = NULL;
1309 ST_INLN Sym *define_find(int v)
1311 v -= TOK_IDENT;
1312 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1313 return NULL;
1314 return table_ident[v]->sym_define;
1317 /* free define stack until top reaches 'b' */
1318 ST_FUNC void free_defines(Sym *b)
1320 while (define_stack != b) {
1321 Sym *top = define_stack;
1322 define_stack = top->prev;
1323 tok_str_free_str(top->d);
1324 define_undef(top);
1325 sym_free(top);
1329 /* fake the nth "#if defined test_..." for tcc -dt -run */
1330 static void maybe_run_test(TCCState *s)
1332 const char *p;
1333 if (s->include_stack_ptr != s->include_stack)
1334 return;
1335 p = get_tok_str(tok, NULL);
1336 if (0 != memcmp(p, "test_", 5))
1337 return;
1338 if (0 != --s->run_test)
1339 return;
1340 fprintf(s->ppfp, &"\n[%s]\n"[!(s->dflag & 32)], p), fflush(s->ppfp);
1341 define_push(tok, MACRO_OBJ, NULL, NULL);
1344 static CachedInclude *
1345 search_cached_include(TCCState *s1, const char *filename, int add);
1347 static int parse_include(TCCState *s1, int do_next, int test)
1349 int c, i;
1350 char name[1024], buf[1024], *p;
1351 CachedInclude *e;
1353 c = skip_spaces();
1354 if (c == '<' || c == '\"') {
1355 cstr_reset(&tokcstr);
1356 file->buf_ptr = parse_pp_string(file->buf_ptr, c == '<' ? '>' : c, &tokcstr);
1357 i = tokcstr.size;
1358 pstrncpy(name, tokcstr.data, i >= sizeof name ? sizeof name - 1 : i);
1359 next_nomacro();
1360 } else {
1361 /* computed #include : concatenate tokens until result is one of
1362 the two accepted forms. Don't convert pp-tokens to tokens here. */
1363 parse_flags = PARSE_FLAG_PREPROCESS
1364 | PARSE_FLAG_LINEFEED
1365 | (parse_flags & PARSE_FLAG_ASM_FILE);
1366 name[0] = 0;
1367 for (;;) {
1368 next();
1369 p = name, i = strlen(p) - 1;
1370 if (i > 0
1371 && ((p[0] == '"' && p[i] == '"')
1372 || (p[0] == '<' && p[i] == '>')))
1373 break;
1374 if (tok == TOK_LINEFEED)
1375 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1376 pstrcat(name, sizeof name, get_tok_str(tok, &tokc));
1378 c = p[0];
1379 /* remove '<>|""' */
1380 memmove(p, p + 1, i - 1), p[i - 1] = 0;
1383 i = do_next ? file->include_next_index : -1;
1384 for (;;) {
1385 ++i;
1386 if (i == 0) {
1387 /* check absolute include path */
1388 if (!IS_ABSPATH(name))
1389 continue;
1390 buf[0] = '\0';
1391 } else if (i == 1) {
1392 /* search in file's dir if "header.h" */
1393 if (c != '\"')
1394 continue;
1395 p = file->true_filename;
1396 pstrncpy(buf, p, tcc_basename(p) - p);
1397 } else {
1398 int j = i - 2, k = j - s1->nb_include_paths;
1399 if (k < 0)
1400 p = s1->include_paths[j];
1401 else if (k < s1->nb_sysinclude_paths)
1402 p = s1->sysinclude_paths[k];
1403 else if (test)
1404 return 0;
1405 else
1406 tcc_error("include file '%s' not found", name);
1407 pstrcpy(buf, sizeof buf, p);
1408 pstrcat(buf, sizeof buf, "/");
1410 pstrcat(buf, sizeof buf, name);
1411 e = search_cached_include(s1, buf, 0);
1412 if (e && (define_find(e->ifndef_macro) || e->once)) {
1413 /* no need to parse the include because the 'ifndef macro'
1414 is defined (or had #pragma once) */
1415 #ifdef INC_DEBUG
1416 printf("%s: skipping cached %s\n", file->filename, buf);
1417 #endif
1418 return 1;
1420 if (tcc_open(s1, buf) >= 0)
1421 break;
1424 if (test) {
1425 tcc_close();
1426 } else {
1427 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1428 tcc_error("#include recursion too deep");
1429 /* push previous file on stack */
1430 *s1->include_stack_ptr++ = file->prev;
1431 file->include_next_index = i;
1432 #ifdef INC_DEBUG
1433 printf("%s: including %s\n", file->prev->filename, file->filename);
1434 #endif
1435 /* update target deps */
1436 if (s1->gen_deps) {
1437 BufferedFile *bf = file;
1438 while (i == 1 && (bf = bf->prev))
1439 i = bf->include_next_index;
1440 /* skip system include files */
1441 if (s1->include_sys_deps || i - 2 < s1->nb_include_paths)
1442 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1443 tcc_strdup(buf));
1445 /* add include file debug info */
1446 tcc_debug_bincl(s1);
1447 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1449 return 1;
1452 /* eval an expression for #if/#elif */
1453 static int expr_preprocess(TCCState *s1)
1455 int c, t;
1456 TokenString *str;
1458 str = tok_str_alloc();
1459 pp_expr = 1;
1460 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1461 next(); /* do macro subst */
1462 redo:
1463 if (tok < TOK_IDENT) {
1464 if (tok >= TOK_STR && tok <= TOK_CLDOUBLE)
1465 tcc_error("invalid constant in preprocessor expression");
1466 } else if (tok == TOK_DEFINED) {
1467 next_nomacro();
1468 t = tok;
1469 if (t == '(')
1470 next_nomacro();
1471 if (tok < TOK_IDENT)
1472 expect("identifier");
1473 if (s1->run_test)
1474 maybe_run_test(s1);
1475 c = 0;
1476 if (define_find(tok)
1477 || tok == TOK___HAS_INCLUDE
1478 || tok == TOK___HAS_INCLUDE_NEXT)
1479 c = 1;
1480 if (t == '(') {
1481 next_nomacro();
1482 if (tok != ')')
1483 expect("')'");
1485 tok = TOK_CINT;
1486 tokc.i = c;
1487 } else if (tok == TOK___HAS_INCLUDE ||
1488 tok == TOK___HAS_INCLUDE_NEXT) {
1489 t = tok;
1490 next_nomacro();
1491 if (tok != '(')
1492 expect("(");
1493 c = parse_include(s1, t - TOK___HAS_INCLUDE, 1);
1494 if (tok != ')')
1495 expect("')'");
1496 tok = TOK_CINT;
1497 tokc.i = c;
1498 } else {
1499 /* if undefined macro, replace with zero, check for func-like */
1500 t = tok;
1501 tok = TOK_CINT;
1502 tokc.i = 0;
1503 tok_str_add_tok(str);
1504 next();
1505 if (tok == '(')
1506 tcc_error("function-like macro '%s' is not defined",
1507 get_tok_str(t, NULL));
1508 goto redo;
1510 tok_str_add_tok(str);
1512 pp_expr = 0;
1513 tok_str_add(str, -1); /* simulate end of file */
1514 tok_str_add(str, 0);
1515 /* now evaluate C constant expression */
1516 begin_macro(str, 1);
1517 next();
1518 c = expr_const();
1519 end_macro();
1520 return c != 0;
1524 /* parse after #define */
1525 ST_FUNC void parse_define(void)
1527 Sym *s, *first, **ps;
1528 int v, t, varg, is_vaargs, spc;
1529 int saved_parse_flags = parse_flags;
1531 v = tok;
1532 if (v < TOK_IDENT || v == TOK_DEFINED)
1533 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1534 /* XXX: should check if same macro (ANSI) */
1535 first = NULL;
1536 t = MACRO_OBJ;
1537 /* We have to parse the whole define as if not in asm mode, in particular
1538 no line comment with '#' must be ignored. Also for function
1539 macros the argument list must be parsed without '.' being an ID
1540 character. */
1541 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1542 /* '(' must be just after macro definition for MACRO_FUNC */
1543 next_nomacro();
1544 parse_flags &= ~PARSE_FLAG_SPACES;
1545 if (tok == '(') {
1546 int dotid = set_idnum('.', 0);
1547 next_nomacro();
1548 ps = &first;
1549 if (tok != ')') for (;;) {
1550 varg = tok;
1551 next_nomacro();
1552 is_vaargs = 0;
1553 if (varg == TOK_DOTS) {
1554 varg = TOK___VA_ARGS__;
1555 is_vaargs = 1;
1556 } else if (tok == TOK_DOTS && gnu_ext) {
1557 is_vaargs = 1;
1558 next_nomacro();
1560 if (varg < TOK_IDENT)
1561 bad_list:
1562 tcc_error("bad macro parameter list");
1563 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1564 *ps = s;
1565 ps = &s->next;
1566 if (tok == ')')
1567 break;
1568 if (tok != ',' || is_vaargs)
1569 goto bad_list;
1570 next_nomacro();
1572 parse_flags |= PARSE_FLAG_SPACES;
1573 next_nomacro();
1574 t = MACRO_FUNC;
1575 set_idnum('.', dotid);
1578 tokstr_buf.len = 0;
1579 spc = 2;
1580 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1581 /* The body of a macro definition should be parsed such that identifiers
1582 are parsed like the file mode determines (i.e. with '.' being an
1583 ID character in asm mode). But '#' should be retained instead of
1584 regarded as line comment leader, so still don't set ASM_FILE
1585 in parse_flags. */
1586 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1587 /* remove spaces around ## and after '#' */
1588 if (TOK_TWOSHARPS == tok) {
1589 if (2 == spc)
1590 goto bad_twosharp;
1591 if (1 == spc)
1592 --tokstr_buf.len;
1593 spc = 3;
1594 tok = TOK_PPJOIN;
1595 } else if ('#' == tok) {
1596 spc = 4;
1597 } else if (check_space(tok, &spc)) {
1598 goto skip;
1600 tok_str_add2(&tokstr_buf, tok, &tokc);
1601 skip:
1602 next_nomacro();
1605 parse_flags = saved_parse_flags;
1606 if (spc == 1)
1607 --tokstr_buf.len; /* remove trailing space */
1608 tok_str_add(&tokstr_buf, 0);
1609 if (3 == spc)
1610 bad_twosharp:
1611 tcc_error("'##' cannot appear at either end of macro");
1612 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1615 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1617 const char *s, *basename;
1618 unsigned int h;
1619 CachedInclude *e;
1620 int c, i, len;
1622 s = basename = tcc_basename(filename);
1623 h = TOK_HASH_INIT;
1624 while ((c = (unsigned char)*s) != 0) {
1625 #ifdef _WIN32
1626 h = TOK_HASH_FUNC(h, toup(c));
1627 #else
1628 h = TOK_HASH_FUNC(h, c);
1629 #endif
1630 s++;
1632 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1634 i = s1->cached_includes_hash[h];
1635 for(;;) {
1636 if (i == 0)
1637 break;
1638 e = s1->cached_includes[i - 1];
1639 if (0 == PATHCMP(filename, e->filename))
1640 return e;
1641 if (e->once
1642 && 0 == PATHCMP(basename, tcc_basename(e->filename))
1643 && 0 == normalized_PATHCMP(filename, e->filename)
1645 return e;
1646 i = e->hash_next;
1648 if (!add)
1649 return NULL;
1651 e = tcc_malloc(sizeof(CachedInclude) + (len = strlen(filename)));
1652 memcpy(e->filename, filename, len + 1);
1653 e->ifndef_macro = e->once = 0;
1654 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1655 /* add in hash table */
1656 e->hash_next = s1->cached_includes_hash[h];
1657 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1658 #ifdef INC_DEBUG
1659 printf("adding cached '%s'\n", filename);
1660 #endif
1661 return e;
1664 static void pragma_parse(TCCState *s1)
1666 next_nomacro();
1667 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1668 int t = tok, v;
1669 Sym *s;
1671 if (next(), tok != '(')
1672 goto pragma_err;
1673 if (next(), tok != TOK_STR)
1674 goto pragma_err;
1675 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1676 if (next(), tok != ')')
1677 goto pragma_err;
1678 if (t == TOK_push_macro) {
1679 while (NULL == (s = define_find(v)))
1680 define_push(v, 0, NULL, NULL);
1681 s->type.ref = s; /* set push boundary */
1682 } else {
1683 for (s = define_stack; s; s = s->prev)
1684 if (s->v == v && s->type.ref == s) {
1685 s->type.ref = NULL;
1686 break;
1689 if (s)
1690 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1691 else
1692 tcc_warning("unbalanced #pragma pop_macro");
1693 pp_debug_tok = t, pp_debug_symv = v;
1695 } else if (tok == TOK_once) {
1696 search_cached_include(s1, file->filename, 1)->once = 1;
1698 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1699 /* tcc -E: keep pragmas below unchanged */
1700 unget_tok(' ');
1701 unget_tok(TOK_PRAGMA);
1702 unget_tok('#');
1703 unget_tok(TOK_LINEFEED);
1705 } else if (tok == TOK_pack) {
1706 /* This may be:
1707 #pragma pack(1) // set
1708 #pragma pack() // reset to default
1709 #pragma pack(push) // push current
1710 #pragma pack(push,1) // push & set
1711 #pragma pack(pop) // restore previous */
1712 next();
1713 skip('(');
1714 if (tok == TOK_ASM_pop) {
1715 next();
1716 if (s1->pack_stack_ptr <= s1->pack_stack) {
1717 stk_error:
1718 tcc_error("out of pack stack");
1720 s1->pack_stack_ptr--;
1721 } else {
1722 int val = 0;
1723 if (tok != ')') {
1724 if (tok == TOK_ASM_push) {
1725 next();
1726 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1727 goto stk_error;
1728 val = *s1->pack_stack_ptr++;
1729 if (tok != ',')
1730 goto pack_set;
1731 next();
1733 if (tok != TOK_CINT)
1734 goto pragma_err;
1735 val = tokc.i;
1736 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1737 goto pragma_err;
1738 next();
1740 pack_set:
1741 *s1->pack_stack_ptr = val;
1743 if (tok != ')')
1744 goto pragma_err;
1746 } else if (tok == TOK_comment) {
1747 char *p; int t;
1748 next();
1749 skip('(');
1750 t = tok;
1751 next();
1752 skip(',');
1753 if (tok != TOK_STR)
1754 goto pragma_err;
1755 p = tcc_strdup((char *)tokc.str.data);
1756 next();
1757 if (tok != ')')
1758 goto pragma_err;
1759 if (t == TOK_lib) {
1760 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1761 } else {
1762 if (t == TOK_option)
1763 tcc_set_options(s1, p);
1764 tcc_free(p);
1767 } else
1768 tcc_warning_c(warn_unsupported)("#pragma %s ignored", get_tok_str(tok, &tokc));
1769 return;
1771 pragma_err:
1772 tcc_error("malformed #pragma directive");
1773 return;
1776 /* is_bof is true if first non space token at beginning of file */
1777 ST_FUNC void preprocess(int is_bof)
1779 TCCState *s1 = tcc_state;
1780 int c, n, saved_parse_flags;
1781 char buf[1024], *q;
1782 Sym *s;
1784 saved_parse_flags = parse_flags;
1785 parse_flags = PARSE_FLAG_PREPROCESS
1786 | PARSE_FLAG_TOK_NUM
1787 | PARSE_FLAG_TOK_STR
1788 | PARSE_FLAG_LINEFEED
1789 | (parse_flags & PARSE_FLAG_ASM_FILE)
1792 next_nomacro();
1793 redo:
1794 switch(tok) {
1795 case TOK_DEFINE:
1796 pp_debug_tok = tok;
1797 next_nomacro();
1798 pp_debug_symv = tok;
1799 parse_define();
1800 break;
1801 case TOK_UNDEF:
1802 pp_debug_tok = tok;
1803 next_nomacro();
1804 pp_debug_symv = tok;
1805 s = define_find(tok);
1806 /* undefine symbol by putting an invalid name */
1807 if (s)
1808 define_undef(s);
1809 break;
1810 case TOK_INCLUDE:
1811 case TOK_INCLUDE_NEXT:
1812 parse_include(s1, tok - TOK_INCLUDE, 0);
1813 break;
1814 case TOK_IFNDEF:
1815 c = 1;
1816 goto do_ifdef;
1817 case TOK_IF:
1818 c = expr_preprocess(s1);
1819 goto do_if;
1820 case TOK_IFDEF:
1821 c = 0;
1822 do_ifdef:
1823 next_nomacro();
1824 if (tok < TOK_IDENT)
1825 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1826 if (is_bof) {
1827 if (c) {
1828 #ifdef INC_DEBUG
1829 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1830 #endif
1831 file->ifndef_macro = tok;
1834 if (define_find(tok)
1835 || tok == TOK___HAS_INCLUDE
1836 || tok == TOK___HAS_INCLUDE_NEXT)
1837 c ^= 1;
1838 do_if:
1839 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1840 tcc_error("memory full (ifdef)");
1841 *s1->ifdef_stack_ptr++ = c;
1842 goto test_skip;
1843 case TOK_ELSE:
1844 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1845 tcc_error("#else without matching #if");
1846 if (s1->ifdef_stack_ptr[-1] & 2)
1847 tcc_error("#else after #else");
1848 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1849 goto test_else;
1850 case TOK_ELIF:
1851 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1852 tcc_error("#elif without matching #if");
1853 c = s1->ifdef_stack_ptr[-1];
1854 if (c > 1)
1855 tcc_error("#elif after #else");
1856 /* last #if/#elif expression was true: we skip */
1857 if (c == 1) {
1858 c = 0;
1859 } else {
1860 c = expr_preprocess(s1);
1861 s1->ifdef_stack_ptr[-1] = c;
1863 test_else:
1864 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1865 file->ifndef_macro = 0;
1866 test_skip:
1867 if (!(c & 1)) {
1868 preprocess_skip();
1869 is_bof = 0;
1870 goto redo;
1872 break;
1873 case TOK_ENDIF:
1874 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1875 tcc_error("#endif without matching #if");
1876 s1->ifdef_stack_ptr--;
1877 /* '#ifndef macro' was at the start of file. Now we check if
1878 an '#endif' is exactly at the end of file */
1879 if (file->ifndef_macro &&
1880 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1881 file->ifndef_macro_saved = file->ifndef_macro;
1882 /* need to set to zero to avoid false matches if another
1883 #ifndef at middle of file */
1884 file->ifndef_macro = 0;
1885 while (tok != TOK_LINEFEED)
1886 next_nomacro();
1887 tok_flags |= TOK_FLAG_ENDIF;
1888 goto the_end;
1890 break;
1891 case TOK_PPNUM:
1892 n = strtoul((char*)tokc.str.data, &q, 10);
1893 goto _line_num;
1894 case TOK_LINE:
1895 next();
1896 if (tok != TOK_CINT)
1897 _line_err:
1898 tcc_error("wrong #line format");
1899 n = tokc.i;
1900 _line_num:
1901 next();
1902 if (tok != TOK_LINEFEED) {
1903 if (tok == TOK_STR) {
1904 if (file->true_filename == file->filename)
1905 file->true_filename = tcc_strdup(file->filename);
1906 q = (char *)tokc.str.data;
1907 buf[0] = 0;
1908 if (!IS_ABSPATH(q)) {
1909 /* prepend directory from real file */
1910 pstrcpy(buf, sizeof buf, file->true_filename);
1911 *tcc_basename(buf) = 0;
1913 pstrcat(buf, sizeof buf, q);
1914 tcc_debug_putfile(s1, buf);
1915 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
1916 break;
1917 else
1918 goto _line_err;
1919 --n;
1921 if (file->fd > 0)
1922 total_lines += file->line_num - n;
1923 file->line_num = n;
1924 break;
1925 case TOK_ERROR:
1926 case TOK_WARNING:
1927 q = buf;
1928 c = skip_spaces();
1929 while (c != '\n' && c != CH_EOF) {
1930 if ((q - buf) < sizeof(buf) - 1)
1931 *q++ = c;
1932 c = ninp();
1934 *q = '\0';
1935 if (tok == TOK_ERROR)
1936 tcc_error("#error %s", buf);
1937 else
1938 tcc_warning("#warning %s", buf);
1939 break;
1940 case TOK_PRAGMA:
1941 pragma_parse(s1);
1942 break;
1943 case TOK_LINEFEED:
1944 goto the_end;
1945 default:
1946 /* ignore gas line comment in an 'S' file. */
1947 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1948 goto ignore;
1949 if (tok == '!' && is_bof)
1950 /* '!' is ignored at beginning to allow C scripts. */
1951 goto ignore;
1952 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1953 ignore:
1954 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
1955 goto the_end;
1957 /* ignore other preprocess commands or #! for C scripts */
1958 while (tok != TOK_LINEFEED)
1959 next_nomacro();
1960 the_end:
1961 parse_flags = saved_parse_flags;
1964 /* evaluate escape codes in a string. */
1965 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1967 int c, n, i;
1968 const uint8_t *p;
1970 p = buf;
1971 for(;;) {
1972 c = *p;
1973 if (c == '\0')
1974 break;
1975 if (c == '\\') {
1976 p++;
1977 /* escape */
1978 c = *p;
1979 switch(c) {
1980 case '0': case '1': case '2': case '3':
1981 case '4': case '5': case '6': case '7':
1982 /* at most three octal digits */
1983 n = c - '0';
1984 p++;
1985 c = *p;
1986 if (isoct(c)) {
1987 n = n * 8 + c - '0';
1988 p++;
1989 c = *p;
1990 if (isoct(c)) {
1991 n = n * 8 + c - '0';
1992 p++;
1995 c = n;
1996 goto add_char_nonext;
1997 case 'x': i = 0; goto parse_hex_or_ucn;
1998 case 'u': i = 4; goto parse_hex_or_ucn;
1999 case 'U': i = 8; goto parse_hex_or_ucn;
2000 parse_hex_or_ucn:
2001 p++;
2002 n = 0;
2003 do {
2004 c = *p;
2005 if (c >= 'a' && c <= 'f')
2006 c = c - 'a' + 10;
2007 else if (c >= 'A' && c <= 'F')
2008 c = c - 'A' + 10;
2009 else if (isnum(c))
2010 c = c - '0';
2011 else if (i > 0)
2012 expect("more hex digits in universal-character-name");
2013 else
2014 goto add_hex_or_ucn;
2015 n = n * 16 + c;
2016 p++;
2017 } while (--i);
2018 if (is_long) {
2019 add_hex_or_ucn:
2020 c = n;
2021 goto add_char_nonext;
2023 cstr_u8cat(outstr, n);
2024 continue;
2025 case 'a':
2026 c = '\a';
2027 break;
2028 case 'b':
2029 c = '\b';
2030 break;
2031 case 'f':
2032 c = '\f';
2033 break;
2034 case 'n':
2035 c = '\n';
2036 break;
2037 case 'r':
2038 c = '\r';
2039 break;
2040 case 't':
2041 c = '\t';
2042 break;
2043 case 'v':
2044 c = '\v';
2045 break;
2046 case 'e':
2047 if (!gnu_ext)
2048 goto invalid_escape;
2049 c = 27;
2050 break;
2051 case '\'':
2052 case '\"':
2053 case '\\':
2054 case '?':
2055 break;
2056 default:
2057 invalid_escape:
2058 if (c >= '!' && c <= '~')
2059 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2060 else
2061 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2062 break;
2064 } else if (is_long && c >= 0x80) {
2065 /* assume we are processing UTF-8 sequence */
2066 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2068 int cont; /* count of continuation bytes */
2069 int skip; /* how many bytes should skip when error occurred */
2070 int i;
2072 /* decode leading byte */
2073 if (c < 0xC2) {
2074 skip = 1; goto invalid_utf8_sequence;
2075 } else if (c <= 0xDF) {
2076 cont = 1; n = c & 0x1f;
2077 } else if (c <= 0xEF) {
2078 cont = 2; n = c & 0xf;
2079 } else if (c <= 0xF4) {
2080 cont = 3; n = c & 0x7;
2081 } else {
2082 skip = 1; goto invalid_utf8_sequence;
2085 /* decode continuation bytes */
2086 for (i = 1; i <= cont; i++) {
2087 int l = 0x80, h = 0xBF;
2089 /* adjust limit for second byte */
2090 if (i == 1) {
2091 switch (c) {
2092 case 0xE0: l = 0xA0; break;
2093 case 0xED: h = 0x9F; break;
2094 case 0xF0: l = 0x90; break;
2095 case 0xF4: h = 0x8F; break;
2099 if (p[i] < l || p[i] > h) {
2100 skip = i; goto invalid_utf8_sequence;
2103 n = (n << 6) | (p[i] & 0x3f);
2106 /* advance pointer */
2107 p += 1 + cont;
2108 c = n;
2109 goto add_char_nonext;
2111 /* error handling */
2112 invalid_utf8_sequence:
2113 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2114 c = 0xFFFD;
2115 p += skip;
2116 goto add_char_nonext;
2119 p++;
2120 add_char_nonext:
2121 if (!is_long)
2122 cstr_ccat(outstr, c);
2123 else {
2124 #ifdef TCC_TARGET_PE
2125 /* store as UTF-16 */
2126 if (c < 0x10000) {
2127 cstr_wccat(outstr, c);
2128 } else {
2129 c -= 0x10000;
2130 cstr_wccat(outstr, (c >> 10) + 0xD800);
2131 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2133 #else
2134 cstr_wccat(outstr, c);
2135 #endif
2138 /* add a trailing '\0' */
2139 if (!is_long)
2140 cstr_ccat(outstr, '\0');
2141 else
2142 cstr_wccat(outstr, '\0');
2145 static void parse_string(const char *s, int len)
2147 uint8_t buf[1000], *p = buf;
2148 int is_long, sep;
2150 if ((is_long = *s == 'L'))
2151 ++s, --len;
2152 sep = *s++;
2153 len -= 2;
2154 if (len >= sizeof buf)
2155 p = tcc_malloc(len + 1);
2156 memcpy(p, s, len);
2157 p[len] = 0;
2159 cstr_reset(&tokcstr);
2160 parse_escape_string(&tokcstr, p, is_long);
2161 if (p != buf)
2162 tcc_free(p);
2164 if (sep == '\'') {
2165 int char_size, i, n, c;
2166 /* XXX: make it portable */
2167 if (!is_long)
2168 tok = TOK_CCHAR, char_size = 1;
2169 else
2170 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2171 n = tokcstr.size / char_size - 1;
2172 if (n < 1)
2173 tcc_error("empty character constant");
2174 if (n > 1)
2175 tcc_warning_c(warn_all)("multi-character character constant");
2176 for (c = i = 0; i < n; ++i) {
2177 if (is_long)
2178 c = ((nwchar_t *)tokcstr.data)[i];
2179 else
2180 c = (c << 8) | ((char *)tokcstr.data)[i];
2182 tokc.i = c;
2183 } else {
2184 tokc.str.size = tokcstr.size;
2185 tokc.str.data = tokcstr.data;
2186 if (!is_long)
2187 tok = TOK_STR;
2188 else
2189 tok = TOK_LSTR;
2193 /* we use 64 bit numbers */
2194 #define BN_SIZE 2
2196 /* bn = (bn << shift) | or_val */
2197 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2199 int i;
2200 unsigned int v;
2201 for(i=0;i<BN_SIZE;i++) {
2202 v = bn[i];
2203 bn[i] = (v << shift) | or_val;
2204 or_val = v >> (32 - shift);
2208 static void bn_zero(unsigned int *bn)
2210 int i;
2211 for(i=0;i<BN_SIZE;i++) {
2212 bn[i] = 0;
2216 /* parse number in null terminated string 'p' and return it in the
2217 current token */
2218 static void parse_number(const char *p)
2220 int b, t, shift, frac_bits, s, exp_val, ch;
2221 char *q;
2222 unsigned int bn[BN_SIZE];
2223 double d;
2225 /* number */
2226 q = token_buf;
2227 ch = *p++;
2228 t = ch;
2229 ch = *p++;
2230 *q++ = t;
2231 b = 10;
2232 if (t == '.') {
2233 goto float_frac_parse;
2234 } else if (t == '0') {
2235 if (ch == 'x' || ch == 'X') {
2236 q--;
2237 ch = *p++;
2238 b = 16;
2239 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2240 q--;
2241 ch = *p++;
2242 b = 2;
2245 /* parse all digits. cannot check octal numbers at this stage
2246 because of floating point constants */
2247 while (1) {
2248 if (ch >= 'a' && ch <= 'f')
2249 t = ch - 'a' + 10;
2250 else if (ch >= 'A' && ch <= 'F')
2251 t = ch - 'A' + 10;
2252 else if (isnum(ch))
2253 t = ch - '0';
2254 else
2255 break;
2256 if (t >= b)
2257 break;
2258 if (q >= token_buf + STRING_MAX_SIZE) {
2259 num_too_long:
2260 tcc_error("number too long");
2262 *q++ = ch;
2263 ch = *p++;
2265 if (ch == '.' ||
2266 ((ch == 'e' || ch == 'E') && b == 10) ||
2267 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2268 if (b != 10) {
2269 /* NOTE: strtox should support that for hexa numbers, but
2270 non ISOC99 libcs do not support it, so we prefer to do
2271 it by hand */
2272 /* hexadecimal or binary floats */
2273 /* XXX: handle overflows */
2274 *q = '\0';
2275 if (b == 16)
2276 shift = 4;
2277 else
2278 shift = 1;
2279 bn_zero(bn);
2280 q = token_buf;
2281 while (1) {
2282 t = *q++;
2283 if (t == '\0') {
2284 break;
2285 } else if (t >= 'a') {
2286 t = t - 'a' + 10;
2287 } else if (t >= 'A') {
2288 t = t - 'A' + 10;
2289 } else {
2290 t = t - '0';
2292 bn_lshift(bn, shift, t);
2294 frac_bits = 0;
2295 if (ch == '.') {
2296 ch = *p++;
2297 while (1) {
2298 t = ch;
2299 if (t >= 'a' && t <= 'f') {
2300 t = t - 'a' + 10;
2301 } else if (t >= 'A' && t <= 'F') {
2302 t = t - 'A' + 10;
2303 } else if (t >= '0' && t <= '9') {
2304 t = t - '0';
2305 } else {
2306 break;
2308 if (t >= b)
2309 tcc_error("invalid digit");
2310 bn_lshift(bn, shift, t);
2311 frac_bits += shift;
2312 ch = *p++;
2315 if (ch != 'p' && ch != 'P')
2316 expect("exponent");
2317 ch = *p++;
2318 s = 1;
2319 exp_val = 0;
2320 if (ch == '+') {
2321 ch = *p++;
2322 } else if (ch == '-') {
2323 s = -1;
2324 ch = *p++;
2326 if (ch < '0' || ch > '9')
2327 expect("exponent digits");
2328 while (ch >= '0' && ch <= '9') {
2329 exp_val = exp_val * 10 + ch - '0';
2330 ch = *p++;
2332 exp_val = exp_val * s;
2334 /* now we can generate the number */
2335 /* XXX: should patch directly float number */
2336 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2337 d = ldexp(d, exp_val - frac_bits);
2338 t = toup(ch);
2339 if (t == 'F') {
2340 ch = *p++;
2341 tok = TOK_CFLOAT;
2342 /* float : should handle overflow */
2343 tokc.f = (float)d;
2344 } else if (t == 'L') {
2345 ch = *p++;
2346 tok = TOK_CLDOUBLE;
2347 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2348 tokc.d = d;
2349 #else
2350 /* XXX: not large enough */
2351 tokc.ld = (long double)d;
2352 #endif
2353 } else {
2354 tok = TOK_CDOUBLE;
2355 tokc.d = d;
2357 } else {
2358 /* decimal floats */
2359 if (ch == '.') {
2360 if (q >= token_buf + STRING_MAX_SIZE)
2361 goto num_too_long;
2362 *q++ = ch;
2363 ch = *p++;
2364 float_frac_parse:
2365 while (ch >= '0' && ch <= '9') {
2366 if (q >= token_buf + STRING_MAX_SIZE)
2367 goto num_too_long;
2368 *q++ = ch;
2369 ch = *p++;
2372 if (ch == 'e' || ch == 'E') {
2373 if (q >= token_buf + STRING_MAX_SIZE)
2374 goto num_too_long;
2375 *q++ = ch;
2376 ch = *p++;
2377 if (ch == '-' || ch == '+') {
2378 if (q >= token_buf + STRING_MAX_SIZE)
2379 goto num_too_long;
2380 *q++ = ch;
2381 ch = *p++;
2383 if (ch < '0' || ch > '9')
2384 expect("exponent digits");
2385 while (ch >= '0' && ch <= '9') {
2386 if (q >= token_buf + STRING_MAX_SIZE)
2387 goto num_too_long;
2388 *q++ = ch;
2389 ch = *p++;
2392 *q = '\0';
2393 t = toup(ch);
2394 errno = 0;
2395 if (t == 'F') {
2396 ch = *p++;
2397 tok = TOK_CFLOAT;
2398 tokc.f = strtof(token_buf, NULL);
2399 } else if (t == 'L') {
2400 ch = *p++;
2401 tok = TOK_CLDOUBLE;
2402 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2403 tokc.d = strtod(token_buf, NULL);
2404 #else
2405 tokc.ld = strtold(token_buf, NULL);
2406 #endif
2407 } else {
2408 tok = TOK_CDOUBLE;
2409 tokc.d = strtod(token_buf, NULL);
2412 } else {
2413 unsigned long long n, n1;
2414 int lcount, ucount, ov = 0;
2415 const char *p1;
2417 /* integer number */
2418 *q = '\0';
2419 q = token_buf;
2420 if (b == 10 && *q == '0') {
2421 b = 8;
2422 q++;
2424 n = 0;
2425 while(1) {
2426 t = *q++;
2427 /* no need for checks except for base 10 / 8 errors */
2428 if (t == '\0')
2429 break;
2430 else if (t >= 'a')
2431 t = t - 'a' + 10;
2432 else if (t >= 'A')
2433 t = t - 'A' + 10;
2434 else
2435 t = t - '0';
2436 if (t >= b)
2437 tcc_error("invalid digit");
2438 n1 = n;
2439 n = n * b + t;
2440 /* detect overflow */
2441 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2442 ov = 1;
2445 /* Determine the characteristics (unsigned and/or 64bit) the type of
2446 the constant must have according to the constant suffix(es) */
2447 lcount = ucount = 0;
2448 p1 = p;
2449 for(;;) {
2450 t = toup(ch);
2451 if (t == 'L') {
2452 if (lcount >= 2)
2453 tcc_error("three 'l's in integer constant");
2454 if (lcount && *(p - 1) != ch)
2455 tcc_error("incorrect integer suffix: %s", p1);
2456 lcount++;
2457 ch = *p++;
2458 } else if (t == 'U') {
2459 if (ucount >= 1)
2460 tcc_error("two 'u's in integer constant");
2461 ucount++;
2462 ch = *p++;
2463 } else {
2464 break;
2468 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2469 if (ucount == 0 && b == 10) {
2470 if (lcount <= (LONG_SIZE == 4)) {
2471 if (n >= 0x80000000U)
2472 lcount = (LONG_SIZE == 4) + 1;
2474 if (n >= 0x8000000000000000ULL)
2475 ov = 1, ucount = 1;
2476 } else {
2477 if (lcount <= (LONG_SIZE == 4)) {
2478 if (n >= 0x100000000ULL)
2479 lcount = (LONG_SIZE == 4) + 1;
2480 else if (n >= 0x80000000U)
2481 ucount = 1;
2483 if (n >= 0x8000000000000000ULL)
2484 ucount = 1;
2487 if (ov)
2488 tcc_warning("integer constant overflow");
2490 tok = TOK_CINT;
2491 if (lcount) {
2492 tok = TOK_CLONG;
2493 if (lcount == 2)
2494 tok = TOK_CLLONG;
2496 if (ucount)
2497 ++tok; /* TOK_CU... */
2498 tokc.i = n;
2500 if (ch)
2501 tcc_error("invalid number");
2505 #define PARSE2(c1, tok1, c2, tok2) \
2506 case c1: \
2507 PEEKC(c, p); \
2508 if (c == c2) { \
2509 p++; \
2510 tok = tok2; \
2511 } else { \
2512 tok = tok1; \
2514 break;
2516 /* return next token without macro substitution */
2517 static inline void next_nomacro1(void)
2519 int t, c, is_long, len;
2520 TokenSym *ts;
2521 uint8_t *p, *p1;
2522 unsigned int h;
2524 p = file->buf_ptr;
2525 redo_no_start:
2526 c = *p;
2527 switch(c) {
2528 case ' ':
2529 case '\t':
2530 tok = c;
2531 p++;
2532 maybe_space:
2533 if (parse_flags & PARSE_FLAG_SPACES)
2534 goto keep_tok_flags;
2535 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2536 ++p;
2537 goto redo_no_start;
2538 case '\f':
2539 case '\v':
2540 case '\r':
2541 p++;
2542 goto redo_no_start;
2543 case '\\':
2544 /* first look if it is in fact an end of buffer */
2545 c = handle_stray(&p);
2546 if (c == '\\')
2547 goto parse_simple;
2548 if (c == CH_EOF) {
2549 TCCState *s1 = tcc_state;
2550 if ((parse_flags & PARSE_FLAG_LINEFEED)
2551 && !(tok_flags & TOK_FLAG_EOF)) {
2552 tok_flags |= TOK_FLAG_EOF;
2553 tok = TOK_LINEFEED;
2554 goto keep_tok_flags;
2555 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2556 tok = TOK_EOF;
2557 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2558 tcc_error("missing #endif");
2559 } else if (s1->include_stack_ptr == s1->include_stack) {
2560 /* no include left : end of file. */
2561 tok = TOK_EOF;
2562 } else {
2563 tok_flags &= ~TOK_FLAG_EOF;
2564 /* pop include file */
2566 /* test if previous '#endif' was after a #ifdef at
2567 start of file */
2568 if (tok_flags & TOK_FLAG_ENDIF) {
2569 #ifdef INC_DEBUG
2570 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2571 #endif
2572 search_cached_include(s1, file->filename, 1)
2573 ->ifndef_macro = file->ifndef_macro_saved;
2574 tok_flags &= ~TOK_FLAG_ENDIF;
2577 /* add end of include file debug info */
2578 tcc_debug_eincl(tcc_state);
2579 /* pop include stack */
2580 tcc_close();
2581 s1->include_stack_ptr--;
2582 p = file->buf_ptr;
2583 if (p == file->buffer)
2584 tok_flags = TOK_FLAG_BOF;
2585 tok_flags |= TOK_FLAG_BOL;
2586 goto redo_no_start;
2588 } else {
2589 goto redo_no_start;
2591 break;
2593 case '\n':
2594 file->line_num++;
2595 tok_flags |= TOK_FLAG_BOL;
2596 p++;
2597 maybe_newline:
2598 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2599 goto redo_no_start;
2600 tok = TOK_LINEFEED;
2601 goto keep_tok_flags;
2603 case '#':
2604 /* XXX: simplify */
2605 PEEKC(c, p);
2606 if ((tok_flags & TOK_FLAG_BOL) &&
2607 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2608 file->buf_ptr = p;
2609 preprocess(tok_flags & TOK_FLAG_BOF);
2610 p = file->buf_ptr;
2611 goto maybe_newline;
2612 } else {
2613 if (c == '#') {
2614 p++;
2615 tok = TOK_TWOSHARPS;
2616 } else {
2617 #if !defined(TCC_TARGET_ARM)
2618 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2619 p = parse_line_comment(p - 1);
2620 goto redo_no_start;
2621 } else
2622 #endif
2624 tok = '#';
2628 break;
2630 /* dollar is allowed to start identifiers when not parsing asm */
2631 case '$':
2632 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2633 || (parse_flags & PARSE_FLAG_ASM_FILE))
2634 goto parse_simple;
2636 case 'a': case 'b': case 'c': case 'd':
2637 case 'e': case 'f': case 'g': case 'h':
2638 case 'i': case 'j': case 'k': case 'l':
2639 case 'm': case 'n': case 'o': case 'p':
2640 case 'q': case 'r': case 's': case 't':
2641 case 'u': case 'v': case 'w': case 'x':
2642 case 'y': case 'z':
2643 case 'A': case 'B': case 'C': case 'D':
2644 case 'E': case 'F': case 'G': case 'H':
2645 case 'I': case 'J': case 'K':
2646 case 'M': case 'N': case 'O': case 'P':
2647 case 'Q': case 'R': case 'S': case 'T':
2648 case 'U': case 'V': case 'W': case 'X':
2649 case 'Y': case 'Z':
2650 case '_':
2651 parse_ident_fast:
2652 p1 = p;
2653 h = TOK_HASH_INIT;
2654 h = TOK_HASH_FUNC(h, c);
2655 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2656 h = TOK_HASH_FUNC(h, c);
2657 len = p - p1;
2658 if (c != '\\') {
2659 TokenSym **pts;
2661 /* fast case : no stray found, so we have the full token
2662 and we have already hashed it */
2663 h &= (TOK_HASH_SIZE - 1);
2664 pts = &hash_ident[h];
2665 for(;;) {
2666 ts = *pts;
2667 if (!ts)
2668 break;
2669 if (ts->len == len && !memcmp(ts->str, p1, len))
2670 goto token_found;
2671 pts = &(ts->hash_next);
2673 ts = tok_alloc_new(pts, (char *) p1, len);
2674 token_found: ;
2675 } else {
2676 /* slower case */
2677 cstr_reset(&tokcstr);
2678 cstr_cat(&tokcstr, (char *) p1, len);
2679 p--;
2680 PEEKC(c, p);
2681 parse_ident_slow:
2682 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2684 cstr_ccat(&tokcstr, c);
2685 PEEKC(c, p);
2687 ts = tok_alloc(tokcstr.data, tokcstr.size);
2689 tok = ts->tok;
2690 break;
2691 case 'L':
2692 t = p[1];
2693 if (t != '\\' && t != '\'' && t != '\"') {
2694 /* fast case */
2695 goto parse_ident_fast;
2696 } else {
2697 PEEKC(c, p);
2698 if (c == '\'' || c == '\"') {
2699 is_long = 1;
2700 goto str_const;
2701 } else {
2702 cstr_reset(&tokcstr);
2703 cstr_ccat(&tokcstr, 'L');
2704 goto parse_ident_slow;
2707 break;
2709 case '0': case '1': case '2': case '3':
2710 case '4': case '5': case '6': case '7':
2711 case '8': case '9':
2712 t = c;
2713 PEEKC(c, p);
2714 /* after the first digit, accept digits, alpha, '.' or sign if
2715 prefixed by 'eEpP' */
2716 parse_num:
2717 cstr_reset(&tokcstr);
2718 for(;;) {
2719 cstr_ccat(&tokcstr, t);
2720 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2721 || c == '.'
2722 || ((c == '+' || c == '-')
2723 && (((t == 'e' || t == 'E')
2724 && !(parse_flags & PARSE_FLAG_ASM_FILE
2725 /* 0xe+1 is 3 tokens in asm */
2726 && ((char*)tokcstr.data)[0] == '0'
2727 && toup(((char*)tokcstr.data)[1]) == 'X'))
2728 || t == 'p' || t == 'P'))))
2729 break;
2730 t = c;
2731 PEEKC(c, p);
2733 /* We add a trailing '\0' to ease parsing */
2734 cstr_ccat(&tokcstr, '\0');
2735 tokc.str.size = tokcstr.size;
2736 tokc.str.data = tokcstr.data;
2737 tok = TOK_PPNUM;
2738 break;
2740 case '.':
2741 /* special dot handling because it can also start a number */
2742 PEEKC(c, p);
2743 if (isnum(c)) {
2744 t = '.';
2745 goto parse_num;
2746 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2747 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2748 *--p = c = '.';
2749 goto parse_ident_fast;
2750 } else if (c == '.') {
2751 PEEKC(c, p);
2752 if (c == '.') {
2753 p++;
2754 tok = TOK_DOTS;
2755 } else {
2756 *--p = '.'; /* may underflow into file->unget[] */
2757 tok = '.';
2759 } else {
2760 tok = '.';
2762 break;
2763 case '\'':
2764 case '\"':
2765 is_long = 0;
2766 str_const:
2767 cstr_reset(&tokcstr);
2768 if (is_long)
2769 cstr_ccat(&tokcstr, 'L');
2770 cstr_ccat(&tokcstr, c);
2771 p = parse_pp_string(p, c, &tokcstr);
2772 cstr_ccat(&tokcstr, c);
2773 cstr_ccat(&tokcstr, '\0');
2774 tokc.str.size = tokcstr.size;
2775 tokc.str.data = tokcstr.data;
2776 tok = TOK_PPSTR;
2777 break;
2779 case '<':
2780 PEEKC(c, p);
2781 if (c == '=') {
2782 p++;
2783 tok = TOK_LE;
2784 } else if (c == '<') {
2785 PEEKC(c, p);
2786 if (c == '=') {
2787 p++;
2788 tok = TOK_A_SHL;
2789 } else {
2790 tok = TOK_SHL;
2792 } else {
2793 tok = TOK_LT;
2795 break;
2796 case '>':
2797 PEEKC(c, p);
2798 if (c == '=') {
2799 p++;
2800 tok = TOK_GE;
2801 } else if (c == '>') {
2802 PEEKC(c, p);
2803 if (c == '=') {
2804 p++;
2805 tok = TOK_A_SAR;
2806 } else {
2807 tok = TOK_SAR;
2809 } else {
2810 tok = TOK_GT;
2812 break;
2814 case '&':
2815 PEEKC(c, p);
2816 if (c == '&') {
2817 p++;
2818 tok = TOK_LAND;
2819 } else if (c == '=') {
2820 p++;
2821 tok = TOK_A_AND;
2822 } else {
2823 tok = '&';
2825 break;
2827 case '|':
2828 PEEKC(c, p);
2829 if (c == '|') {
2830 p++;
2831 tok = TOK_LOR;
2832 } else if (c == '=') {
2833 p++;
2834 tok = TOK_A_OR;
2835 } else {
2836 tok = '|';
2838 break;
2840 case '+':
2841 PEEKC(c, p);
2842 if (c == '+') {
2843 p++;
2844 tok = TOK_INC;
2845 } else if (c == '=') {
2846 p++;
2847 tok = TOK_A_ADD;
2848 } else {
2849 tok = '+';
2851 break;
2853 case '-':
2854 PEEKC(c, p);
2855 if (c == '-') {
2856 p++;
2857 tok = TOK_DEC;
2858 } else if (c == '=') {
2859 p++;
2860 tok = TOK_A_SUB;
2861 } else if (c == '>') {
2862 p++;
2863 tok = TOK_ARROW;
2864 } else {
2865 tok = '-';
2867 break;
2869 PARSE2('!', '!', '=', TOK_NE)
2870 PARSE2('=', '=', '=', TOK_EQ)
2871 PARSE2('*', '*', '=', TOK_A_MUL)
2872 PARSE2('%', '%', '=', TOK_A_MOD)
2873 PARSE2('^', '^', '=', TOK_A_XOR)
2875 /* comments or operator */
2876 case '/':
2877 PEEKC(c, p);
2878 if (c == '*') {
2879 p = parse_comment(p);
2880 /* comments replaced by a blank */
2881 tok = ' ';
2882 goto maybe_space;
2883 } else if (c == '/') {
2884 p = parse_line_comment(p);
2885 tok = ' ';
2886 goto maybe_space;
2887 } else if (c == '=') {
2888 p++;
2889 tok = TOK_A_DIV;
2890 } else {
2891 tok = '/';
2893 break;
2895 /* simple tokens */
2896 case '(':
2897 case ')':
2898 case '[':
2899 case ']':
2900 case '{':
2901 case '}':
2902 case ',':
2903 case ';':
2904 case ':':
2905 case '?':
2906 case '~':
2907 case '@': /* only used in assembler */
2908 parse_simple:
2909 tok = c;
2910 p++;
2911 break;
2912 default:
2913 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2914 goto parse_ident_fast;
2915 if (parse_flags & PARSE_FLAG_ASM_FILE)
2916 goto parse_simple;
2917 tcc_error("unrecognized character \\x%02x", c);
2918 break;
2920 tok_flags = 0;
2921 keep_tok_flags:
2922 file->buf_ptr = p;
2923 #if defined(PARSE_DEBUG)
2924 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
2925 #endif
2928 static void macro_subst(
2929 TokenString *tok_str,
2930 Sym **nested_list,
2931 const int *macro_str
2934 /* substitute arguments in replacement lists in macro_str by the values in
2935 args (field d) and return allocated string */
2936 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2938 int t, t0, t1, spc;
2939 const int *st;
2940 Sym *s;
2941 CValue cval;
2942 TokenString str;
2944 tok_str_new(&str);
2945 t0 = t1 = 0;
2946 while(1) {
2947 TOK_GET(&t, &macro_str, &cval);
2948 if (!t)
2949 break;
2950 if (t == '#') {
2951 /* stringize */
2952 TOK_GET(&t, &macro_str, &cval);
2953 if (!t)
2954 goto bad_stringy;
2955 s = sym_find2(args, t);
2956 if (s) {
2957 cstr_reset(&tokcstr);
2958 cstr_ccat(&tokcstr, '\"');
2959 st = s->d;
2960 spc = 0;
2961 while (*st >= 0) {
2962 TOK_GET(&t, &st, &cval);
2963 if (t != TOK_PLCHLDR
2964 && t != TOK_NOSUBST
2965 && 0 == check_space(t, &spc)) {
2966 const char *s = get_tok_str(t, &cval);
2967 while (*s) {
2968 if (t == TOK_PPSTR && *s != '\'')
2969 add_char(&tokcstr, *s);
2970 else
2971 cstr_ccat(&tokcstr, *s);
2972 ++s;
2976 tokcstr.size -= spc;
2977 cstr_ccat(&tokcstr, '\"');
2978 cstr_ccat(&tokcstr, '\0');
2979 #ifdef PP_DEBUG
2980 printf("\nstringize: <%s>\n", (char *)tokcstr.data);
2981 #endif
2982 /* add string */
2983 cval.str.size = tokcstr.size;
2984 cval.str.data = tokcstr.data;
2985 tok_str_add2(&str, TOK_PPSTR, &cval);
2986 } else {
2987 bad_stringy:
2988 expect("macro parameter after '#'");
2990 } else if (t >= TOK_IDENT) {
2991 s = sym_find2(args, t);
2992 if (s) {
2993 st = s->d;
2994 /* if '##' is present before or after, no arg substitution */
2995 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
2996 /* special case for var arg macros : ## eats the ','
2997 if empty VA_ARGS variable. */
2998 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
2999 if (*st <= 0) {
3000 /* suppress ',' '##' */
3001 str.len -= 2;
3002 } else {
3003 /* suppress '##' and add variable */
3004 str.len--;
3005 goto add_var;
3008 } else {
3009 add_var:
3010 if (!s->next) {
3011 /* Expand arguments tokens and store them. In most
3012 cases we could also re-expand each argument if
3013 used multiple times, but not if the argument
3014 contains the __COUNTER__ macro. */
3015 TokenString str2;
3016 sym_push2(&s->next, s->v, s->type.t, 0);
3017 tok_str_new(&str2);
3018 macro_subst(&str2, nested_list, st);
3019 tok_str_add(&str2, 0);
3020 s->next->d = str2.str;
3022 st = s->next->d;
3024 if (*st <= 0) {
3025 /* expanded to empty string */
3026 tok_str_add(&str, TOK_PLCHLDR);
3027 } else for (;;) {
3028 int t2;
3029 TOK_GET(&t2, &st, &cval);
3030 if (t2 <= 0)
3031 break;
3032 tok_str_add2(&str, t2, &cval);
3034 } else {
3035 tok_str_add(&str, t);
3037 } else {
3038 tok_str_add2(&str, t, &cval);
3040 t0 = t1, t1 = t;
3042 tok_str_add(&str, 0);
3043 return str.str;
3046 static char const ab_month_name[12][4] =
3048 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3049 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3052 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3054 int n, ret = 1;
3056 cstr_reset(&tokcstr);
3057 if (t1 != TOK_PLCHLDR)
3058 cstr_cat(&tokcstr, get_tok_str(t1, v1), -1);
3059 n = tokcstr.size;
3060 if (t2 != TOK_PLCHLDR)
3061 cstr_cat(&tokcstr, get_tok_str(t2, v2), -1);
3062 cstr_ccat(&tokcstr, '\0');
3063 //printf("paste <%s>\n", (char*)tokcstr.data);
3065 tcc_open_bf(tcc_state, ":paste:", tokcstr.size);
3066 memcpy(file->buffer, tokcstr.data, tokcstr.size);
3067 tok_flags = 0;
3068 for (;;) {
3069 next_nomacro1();
3070 if (0 == *file->buf_ptr)
3071 break;
3072 if (is_space(tok))
3073 continue;
3074 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3075 " preprocessing token", n, file->buffer, file->buffer + n);
3076 ret = 0;
3077 break;
3079 tcc_close();
3080 return ret;
3083 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3084 return the resulting string (which must be freed). */
3085 static inline int *macro_twosharps(const int *ptr0)
3087 int t;
3088 CValue cval;
3089 TokenString macro_str1;
3090 int start_of_nosubsts = -1;
3091 const int *ptr;
3093 /* we search the first '##' */
3094 for (ptr = ptr0;;) {
3095 TOK_GET(&t, &ptr, &cval);
3096 if (t == TOK_PPJOIN)
3097 break;
3098 if (t == 0)
3099 return NULL;
3102 tok_str_new(&macro_str1);
3104 //tok_print(" $$$", ptr0);
3105 for (ptr = ptr0;;) {
3106 TOK_GET(&t, &ptr, &cval);
3107 if (t == 0)
3108 break;
3109 if (t == TOK_PPJOIN)
3110 continue;
3111 while (*ptr == TOK_PPJOIN) {
3112 int t1; CValue cv1;
3113 /* given 'a##b', remove nosubsts preceding 'a' */
3114 if (start_of_nosubsts >= 0)
3115 macro_str1.len = start_of_nosubsts;
3116 /* given 'a##b', remove nosubsts preceding 'b' */
3117 while ((t1 = *++ptr) == TOK_NOSUBST)
3119 if (t1 && t1 != TOK_PPJOIN) {
3120 TOK_GET(&t1, &ptr, &cv1);
3121 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3122 if (paste_tokens(t, &cval, t1, &cv1)) {
3123 t = tok, cval = tokc;
3124 } else {
3125 tok_str_add2(&macro_str1, t, &cval);
3126 t = t1, cval = cv1;
3131 if (t == TOK_NOSUBST) {
3132 if (start_of_nosubsts < 0)
3133 start_of_nosubsts = macro_str1.len;
3134 } else {
3135 start_of_nosubsts = -1;
3137 tok_str_add2(&macro_str1, t, &cval);
3139 tok_str_add(&macro_str1, 0);
3140 //tok_print(" ###", macro_str1.str);
3141 return macro_str1.str;
3144 /* peek or read [ws_str == NULL] next token from function macro call,
3145 walking up macro levels up to the file if necessary */
3146 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3148 int t;
3149 const int *p;
3150 Sym *sa;
3152 for (;;) {
3153 if (macro_ptr) {
3154 p = macro_ptr, t = *p;
3155 if (ws_str) {
3156 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3157 tok_str_add(ws_str, t), t = *++p;
3159 if (t == 0) {
3160 end_macro();
3161 /* also, end of scope for nested defined symbol */
3162 sa = *nested_list;
3163 while (sa && sa->v == 0)
3164 sa = sa->prev;
3165 if (sa)
3166 sa->v = 0;
3167 continue;
3169 } else {
3170 uint8_t *p = file->buf_ptr;
3171 int ch = handle_bs(&p);
3172 if (ws_str) {
3173 while (is_space(ch) || ch == '\n' || ch == '/') {
3174 if (ch == '/') {
3175 int c;
3176 PEEKC(c, p);
3177 if (c == '*') {
3178 p = parse_comment(p) - 1;
3179 } else if (c == '/') {
3180 p = parse_line_comment(p) - 1;
3181 } else {
3182 *--p = ch;
3183 break;
3185 ch = ' ';
3187 if (ch == '\n')
3188 file->line_num++;
3189 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3190 tok_str_add(ws_str, ch);
3191 PEEKC(ch, p);
3194 file->buf_ptr = p;
3195 t = ch;
3198 if (ws_str)
3199 return t;
3200 next_nomacro();
3201 return tok;
3205 /* do macro substitution of current token with macro 's' and add
3206 result to (tok_str,tok_len). 'nested_list' is the list of all
3207 macros we got inside to avoid recursing. Return non zero if no
3208 substitution needs to be done */
3209 static int macro_subst_tok(
3210 TokenString *tok_str,
3211 Sym **nested_list,
3212 Sym *s)
3214 Sym *args, *sa, *sa1;
3215 int parlevel, t, t1, spc;
3216 TokenString str;
3217 char *cstrval;
3218 CValue cval;
3219 char buf[32];
3221 /* if symbol is a macro, prepare substitution */
3222 /* special macros */
3223 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3224 t = tok == TOK___LINE__ ? file->line_num : pp_counter++;
3225 snprintf(buf, sizeof(buf), "%d", t);
3226 cstrval = buf;
3227 t1 = TOK_PPNUM;
3228 goto add_cstr1;
3229 } else if (tok == TOK___FILE__) {
3230 cstrval = file->filename;
3231 goto add_cstr;
3232 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3233 time_t ti;
3234 struct tm *tm;
3236 time(&ti);
3237 tm = localtime(&ti);
3238 if (tok == TOK___DATE__) {
3239 snprintf(buf, sizeof(buf), "%s %2d %d",
3240 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3241 } else {
3242 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3243 tm->tm_hour, tm->tm_min, tm->tm_sec);
3245 cstrval = buf;
3246 add_cstr:
3247 t1 = TOK_STR;
3248 add_cstr1:
3249 cstr_reset(&tokcstr);
3250 cstr_cat(&tokcstr, cstrval, 0);
3251 cval.str.size = tokcstr.size;
3252 cval.str.data = tokcstr.data;
3253 tok_str_add2(tok_str, t1, &cval);
3254 } else if (s->d) {
3255 int saved_parse_flags = parse_flags;
3256 int *joined_str = NULL;
3257 int *mstr = s->d;
3259 if (s->type.t == MACRO_FUNC) {
3260 /* whitespace between macro name and argument list */
3261 TokenString ws_str;
3262 tok_str_new(&ws_str);
3264 spc = 0;
3265 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3266 | PARSE_FLAG_ACCEPT_STRAYS;
3268 /* get next token from argument stream */
3269 t = next_argstream(nested_list, &ws_str);
3270 if (t != '(') {
3271 /* not a macro substitution after all, restore the
3272 * macro token plus all whitespace we've read.
3273 * whitespace is intentionally not merged to preserve
3274 * newlines. */
3275 parse_flags = saved_parse_flags;
3276 tok_str_add(tok_str, tok);
3277 if (parse_flags & PARSE_FLAG_SPACES) {
3278 int i;
3279 for (i = 0; i < ws_str.len; i++)
3280 tok_str_add(tok_str, ws_str.str[i]);
3282 if (ws_str.len && ws_str.str[ws_str.len - 1] == '\n')
3283 tok_flags |= TOK_FLAG_BOL;
3284 tok_str_free_str(ws_str.str);
3285 return 0;
3286 } else {
3287 tok_str_free_str(ws_str.str);
3289 do {
3290 next_nomacro(); /* eat '(' */
3291 } while (tok == TOK_PLCHLDR || is_space(tok));
3293 /* argument macro */
3294 args = NULL;
3295 sa = s->next;
3296 /* NOTE: empty args are allowed, except if no args */
3297 for(;;) {
3298 do {
3299 next_argstream(nested_list, NULL);
3300 } while (tok == TOK_PLCHLDR || is_space(tok) ||
3301 TOK_LINEFEED == tok);
3302 empty_arg:
3303 /* handle '()' case */
3304 if (!args && !sa && tok == ')')
3305 break;
3306 if (!sa)
3307 tcc_error("macro '%s' used with too many args",
3308 get_tok_str(s->v, 0));
3309 tok_str_new(&str);
3310 parlevel = spc = 0;
3311 /* NOTE: non zero sa->t indicates VA_ARGS */
3312 while ((parlevel > 0 ||
3313 (tok != ')' &&
3314 (tok != ',' || sa->type.t)))) {
3315 if (tok == TOK_EOF || tok == 0)
3316 break;
3317 if (tok == '(')
3318 parlevel++;
3319 else if (tok == ')')
3320 parlevel--;
3321 if (tok == TOK_LINEFEED)
3322 tok = ' ';
3323 if (!check_space(tok, &spc))
3324 tok_str_add2(&str, tok, &tokc);
3325 next_argstream(nested_list, NULL);
3327 if (parlevel)
3328 expect(")");
3329 str.len -= spc;
3330 tok_str_add(&str, -1);
3331 tok_str_add(&str, 0);
3332 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3333 sa1->d = str.str;
3334 sa = sa->next;
3335 if (tok == ')') {
3336 /* special case for gcc var args: add an empty
3337 var arg argument if it is omitted */
3338 if (sa && sa->type.t && gnu_ext)
3339 goto empty_arg;
3340 break;
3342 if (tok != ',')
3343 expect(",");
3345 if (sa) {
3346 tcc_error("macro '%s' used with too few args",
3347 get_tok_str(s->v, 0));
3350 /* now subst each arg */
3351 mstr = macro_arg_subst(nested_list, mstr, args);
3352 /* free memory */
3353 sa = args;
3354 while (sa) {
3355 sa1 = sa->prev;
3356 tok_str_free_str(sa->d);
3357 if (sa->next) {
3358 tok_str_free_str(sa->next->d);
3359 sym_free(sa->next);
3361 sym_free(sa);
3362 sa = sa1;
3364 parse_flags = saved_parse_flags;
3367 sym_push2(nested_list, s->v, 0, 0);
3368 parse_flags = saved_parse_flags;
3369 joined_str = macro_twosharps(mstr);
3370 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3372 /* pop nested defined symbol */
3373 sa1 = *nested_list;
3374 *nested_list = sa1->prev;
3375 sym_free(sa1);
3376 if (joined_str)
3377 tok_str_free_str(joined_str);
3378 if (mstr != s->d)
3379 tok_str_free_str(mstr);
3381 return 0;
3384 /* do macro substitution of macro_str and add result to
3385 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3386 inside to avoid recursing. */
3387 static void macro_subst(
3388 TokenString *tok_str,
3389 Sym **nested_list,
3390 const int *macro_str
3393 Sym *s;
3394 int t, spc, nosubst;
3395 CValue cval;
3397 spc = nosubst = 0;
3399 while (1) {
3400 TOK_GET(&t, &macro_str, &cval);
3401 if (t <= 0)
3402 break;
3404 if (t >= TOK_IDENT && 0 == nosubst) {
3405 s = define_find(t);
3406 if (s == NULL)
3407 goto no_subst;
3409 /* if nested substitution, do nothing */
3410 if (sym_find2(*nested_list, t)) {
3411 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3412 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3413 goto no_subst;
3417 TokenString *str = tok_str_alloc();
3418 str->str = (int*)macro_str;
3419 begin_macro(str, 2);
3421 tok = t;
3422 macro_subst_tok(tok_str, nested_list, s);
3424 if (macro_stack != str) {
3425 /* already finished by reading function macro arguments */
3426 break;
3429 macro_str = macro_ptr;
3430 end_macro ();
3432 if (tok_str->len)
3433 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3434 } else {
3435 no_subst:
3436 if (!check_space(t, &spc))
3437 tok_str_add2(tok_str, t, &cval);
3439 if (nosubst) {
3440 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3441 continue;
3442 nosubst = 0;
3444 if (t == TOK_NOSUBST)
3445 nosubst = 1;
3447 /* GCC supports 'defined' as result of a macro substitution */
3448 if (t == TOK_DEFINED && pp_expr)
3449 nosubst = 2;
3453 /* return next token without macro substitution. Can read input from
3454 macro_ptr buffer */
3455 static void next_nomacro(void)
3457 int t;
3458 if (macro_ptr) {
3459 redo:
3460 t = *macro_ptr;
3461 if (TOK_HAS_VALUE(t)) {
3462 tok_get(&tok, &macro_ptr, &tokc);
3463 if (t == TOK_LINENUM) {
3464 file->line_num = tokc.i;
3465 goto redo;
3467 } else {
3468 macro_ptr++;
3469 if (t < TOK_IDENT) {
3470 if (!(parse_flags & PARSE_FLAG_SPACES)
3471 && (isidnum_table[t - CH_EOF] & IS_SPC))
3472 goto redo;
3474 tok = t;
3476 } else {
3477 next_nomacro1();
3481 /* return next token with macro substitution */
3482 ST_FUNC void next(void)
3484 int t;
3485 redo:
3486 next_nomacro();
3487 t = tok;
3488 if (macro_ptr) {
3489 if (!TOK_HAS_VALUE(t)) {
3490 if (t == TOK_NOSUBST || t == TOK_PLCHLDR) {
3491 /* discard preprocessor markers */
3492 goto redo;
3493 } else if (t == 0) {
3494 /* end of macro or unget token string */
3495 end_macro();
3496 goto redo;
3497 } else if (t == '\\') {
3498 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3499 tcc_error("stray '\\' in program");
3501 return;
3503 } else if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3504 /* if reading from file, try to substitute macros */
3505 Sym *s = define_find(t);
3506 if (s) {
3507 Sym *nested_list = NULL;
3508 tokstr_buf.len = 0;
3509 macro_subst_tok(&tokstr_buf, &nested_list, s);
3510 tok_str_add(&tokstr_buf, 0);
3511 begin_macro(&tokstr_buf, 0);
3512 goto redo;
3514 return;
3516 /* convert preprocessor tokens into C tokens */
3517 if (t == TOK_PPNUM) {
3518 if (parse_flags & PARSE_FLAG_TOK_NUM)
3519 parse_number((char *)tokc.str.data);
3520 } else if (t == TOK_PPSTR) {
3521 if (parse_flags & PARSE_FLAG_TOK_STR)
3522 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3526 /* push back current token and set current token to 'last_tok'. Only
3527 identifier case handled for labels. */
3528 ST_INLN void unget_tok(int last_tok)
3531 TokenString *str = tok_str_alloc();
3532 tok_str_add2(str, tok, &tokc);
3533 tok_str_add(str, 0);
3534 begin_macro(str, 1);
3535 tok = last_tok;
3538 /* ------------------------------------------------------------------------- */
3539 /* init preprocessor */
3541 static const char * const target_os_defs =
3542 #ifdef TCC_TARGET_PE
3543 "_WIN32\0"
3544 # if PTR_SIZE == 8
3545 "_WIN64\0"
3546 # endif
3547 #else
3548 # if defined TCC_TARGET_MACHO
3549 "__APPLE__\0"
3550 # elif TARGETOS_FreeBSD
3551 "__FreeBSD__ 12\0"
3552 # elif TARGETOS_FreeBSD_kernel
3553 "__FreeBSD_kernel__\0"
3554 # elif TARGETOS_NetBSD
3555 "__NetBSD__\0"
3556 # elif TARGETOS_OpenBSD
3557 "__OpenBSD__\0"
3558 # else
3559 "__linux__\0"
3560 "__linux\0"
3561 # if TARGETOS_ANDROID
3562 "__ANDROID__\0"
3563 # endif
3564 # endif
3565 "__unix__\0"
3566 "__unix\0"
3567 #endif
3570 static void putdef(CString *cs, const char *p)
3572 cstr_printf(cs, "#define %s%s\n", p, &" 1"[!!strchr(p, ' ')*2]);
3575 static void putdefs(CString *cs, const char *p)
3577 while (*p)
3578 putdef(cs, p), p = strchr(p, 0) + 1;
3581 static void tcc_predefs(TCCState *s1, CString *cs, int is_asm)
3583 int a, b, c;
3585 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
3586 cstr_printf(cs, "#define __TINYC__ %d\n", a*10000 + b*100 + c);
3588 putdefs(cs, target_machine_defs);
3589 putdefs(cs, target_os_defs);
3591 #ifdef TCC_TARGET_ARM
3592 if (s1->float_abi == ARM_HARD_FLOAT)
3593 putdef(cs, "__ARM_PCS_VFP");
3594 #endif
3595 if (is_asm)
3596 putdef(cs, "__ASSEMBLER__");
3597 if (s1->output_type == TCC_OUTPUT_PREPROCESS)
3598 putdef(cs, "__TCC_PP__");
3599 if (s1->output_type == TCC_OUTPUT_MEMORY)
3600 putdef(cs, "__TCC_RUN__");
3601 #ifdef CONFIG_TCC_BACKTRACE
3602 if (s1->do_backtrace)
3603 putdef(cs, "__TCC_BACKTRACE__");
3604 #endif
3605 #ifdef CONFIG_TCC_BCHECK
3606 if (s1->do_bounds_check)
3607 putdef(cs, "__TCC_BCHECK__");
3608 #endif
3609 if (s1->char_is_unsigned)
3610 putdef(cs, "__CHAR_UNSIGNED__");
3611 if (s1->optimize > 0)
3612 putdef(cs, "__OPTIMIZE__");
3613 if (s1->option_pthread)
3614 putdef(cs, "_REENTRANT");
3615 if (s1->leading_underscore)
3616 putdef(cs, "__leading_underscore");
3617 cstr_printf(cs, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE);
3618 cstr_printf(cs, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE);
3619 if (!is_asm) {
3620 putdef(cs, "__STDC__");
3621 cstr_printf(cs, "#define __STDC_VERSION__ %dL\n", s1->cversion);
3622 cstr_cat(cs,
3623 /* load more predefs and __builtins */
3624 #if CONFIG_TCC_PREDEFS
3625 #include "tccdefs_.h" /* include as strings */
3626 #else
3627 "#include <tccdefs.h>\n" /* load at runtime */
3628 #endif
3629 , -1);
3631 cstr_printf(cs, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3634 ST_FUNC void preprocess_start(TCCState *s1, int filetype)
3636 int is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
3638 tccpp_new(s1);
3640 s1->include_stack_ptr = s1->include_stack;
3641 s1->ifdef_stack_ptr = s1->ifdef_stack;
3642 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3643 pp_expr = 0;
3644 pp_counter = 0;
3645 pp_debug_tok = pp_debug_symv = 0;
3646 s1->pack_stack[0] = 0;
3647 s1->pack_stack_ptr = s1->pack_stack;
3649 set_idnum('$', !is_asm && s1->dollars_in_identifiers ? IS_ID : 0);
3650 set_idnum('.', is_asm ? IS_ID : 0);
3652 if (!(filetype & AFF_TYPE_ASM)) {
3653 CString cstr;
3654 cstr_new(&cstr);
3655 tcc_predefs(s1, &cstr, is_asm);
3656 if (s1->cmdline_defs.size)
3657 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3658 if (s1->cmdline_incl.size)
3659 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3660 //printf("%s\n", (char*)cstr.data);
3661 *s1->include_stack_ptr++ = file;
3662 tcc_open_bf(s1, "<command line>", cstr.size);
3663 memcpy(file->buffer, cstr.data, cstr.size);
3664 cstr_free(&cstr);
3667 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3668 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3671 /* cleanup from error/setjmp */
3672 ST_FUNC void preprocess_end(TCCState *s1)
3674 while (macro_stack)
3675 end_macro();
3676 macro_ptr = NULL;
3677 while (file)
3678 tcc_close();
3679 tccpp_delete(s1);
3682 ST_FUNC int set_idnum(int c, int val)
3684 int prev = isidnum_table[c - CH_EOF];
3685 isidnum_table[c - CH_EOF] = val;
3686 return prev;
3689 ST_FUNC void tccpp_new(TCCState *s)
3691 int i, c;
3692 const char *p, *r;
3694 /* init isid table */
3695 for(i = CH_EOF; i<128; i++)
3696 set_idnum(i,
3697 is_space(i) ? IS_SPC
3698 : isid(i) ? IS_ID
3699 : isnum(i) ? IS_NUM
3700 : 0);
3702 for(i = 128; i<256; i++)
3703 set_idnum(i, IS_ID);
3705 /* init allocators */
3706 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3707 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3709 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3710 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3712 cstr_new(&tokcstr);
3713 cstr_new(&cstr_buf);
3714 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3715 tok_str_new(&tokstr_buf);
3716 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3718 tok_ident = TOK_IDENT;
3719 p = tcc_keywords;
3720 while (*p) {
3721 r = p;
3722 for(;;) {
3723 c = *r++;
3724 if (c == '\0')
3725 break;
3727 tok_alloc(p, r - p - 1);
3728 p = r;
3731 /* we add dummy defines for some special macros to speed up tests
3732 and to have working defined() */
3733 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3734 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3735 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3736 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3737 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3740 ST_FUNC void tccpp_delete(TCCState *s)
3742 int i, n;
3744 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3746 /* free tokens */
3747 n = tok_ident - TOK_IDENT;
3748 if (n > total_idents)
3749 total_idents = n;
3750 for(i = 0; i < n; i++)
3751 tal_free(toksym_alloc, table_ident[i]);
3752 tcc_free(table_ident);
3753 table_ident = NULL;
3755 /* free static buffers */
3756 cstr_free(&tokcstr);
3757 cstr_free(&cstr_buf);
3758 tok_str_free_str(tokstr_buf.str);
3760 /* free allocators */
3761 tal_delete(toksym_alloc);
3762 toksym_alloc = NULL;
3763 tal_delete(tokstr_alloc);
3764 tokstr_alloc = NULL;
3767 /* ------------------------------------------------------------------------- */
3768 /* tcc -E [-P[1]] [-dD} support */
3770 static void tok_print(const char *msg, const int *str)
3772 FILE *fp;
3773 int t, s = 0;
3774 CValue cval;
3776 fp = tcc_state->ppfp;
3777 fprintf(fp, "%s", msg);
3778 while (str) {
3779 TOK_GET(&t, &str, &cval);
3780 if (!t)
3781 break;
3782 fprintf(fp, &" %s"[s], get_tok_str(t, &cval)), s = 1;
3784 fprintf(fp, "\n");
3787 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3789 int d = f->line_num - f->line_ref;
3791 if (s1->dflag & 4)
3792 return;
3794 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3796 } else if (level == 0 && f->line_ref && d < 8) {
3797 while (d > 0)
3798 fputs("\n", s1->ppfp), --d;
3799 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3800 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3801 } else {
3802 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3803 level > 0 ? " 1" : level < 0 ? " 2" : "");
3805 f->line_ref = f->line_num;
3808 static void define_print(TCCState *s1, int v)
3810 FILE *fp;
3811 Sym *s;
3813 s = define_find(v);
3814 if (NULL == s || NULL == s->d)
3815 return;
3817 fp = s1->ppfp;
3818 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3819 if (s->type.t == MACRO_FUNC) {
3820 Sym *a = s->next;
3821 fprintf(fp,"(");
3822 if (a)
3823 for (;;) {
3824 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3825 if (!(a = a->next))
3826 break;
3827 fprintf(fp,",");
3829 fprintf(fp,")");
3831 tok_print("", s->d);
3834 static void pp_debug_defines(TCCState *s1)
3836 int v, t;
3837 const char *vs;
3838 FILE *fp;
3840 t = pp_debug_tok;
3841 if (t == 0)
3842 return;
3844 file->line_num--;
3845 pp_line(s1, file, 0);
3846 file->line_ref = ++file->line_num;
3848 fp = s1->ppfp;
3849 v = pp_debug_symv;
3850 vs = get_tok_str(v, NULL);
3851 if (t == TOK_DEFINE) {
3852 define_print(s1, v);
3853 } else if (t == TOK_UNDEF) {
3854 fprintf(fp, "#undef %s\n", vs);
3855 } else if (t == TOK_push_macro) {
3856 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3857 } else if (t == TOK_pop_macro) {
3858 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3860 pp_debug_tok = 0;
3863 static void pp_debug_builtins(TCCState *s1)
3865 int v;
3866 for (v = TOK_IDENT; v < tok_ident; ++v)
3867 define_print(s1, v);
3870 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3871 static int pp_need_space(int a, int b)
3873 return 'E' == a ? '+' == b || '-' == b
3874 : '+' == a ? TOK_INC == b || '+' == b
3875 : '-' == a ? TOK_DEC == b || '-' == b
3876 : a >= TOK_IDENT ? b >= TOK_IDENT
3877 : a == TOK_PPNUM ? b >= TOK_IDENT
3878 : 0;
3881 /* maybe hex like 0x1e */
3882 static int pp_check_he0xE(int t, const char *p)
3884 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3885 return 'E';
3886 return t;
3889 /* Preprocess the current file */
3890 ST_FUNC int tcc_preprocess(TCCState *s1)
3892 BufferedFile **iptr;
3893 int token_seen, spcs, level;
3894 const char *p;
3895 char white[400];
3897 parse_flags = PARSE_FLAG_PREPROCESS
3898 | (parse_flags & PARSE_FLAG_ASM_FILE)
3899 | PARSE_FLAG_LINEFEED
3900 | PARSE_FLAG_SPACES
3901 | PARSE_FLAG_ACCEPT_STRAYS
3903 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3904 capability to compile and run itself, provided all numbers are
3905 given as decimals. tcc -E -P10 will do. */
3906 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3907 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3909 if (s1->do_bench) {
3910 /* for PP benchmarks */
3911 do next(); while (tok != TOK_EOF);
3912 return 0;
3915 if (s1->dflag & 1) {
3916 pp_debug_builtins(s1);
3917 s1->dflag &= ~1;
3920 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
3921 if (file->prev)
3922 pp_line(s1, file->prev, level++);
3923 pp_line(s1, file, level);
3924 for (;;) {
3925 iptr = s1->include_stack_ptr;
3926 next();
3927 if (tok == TOK_EOF)
3928 break;
3930 level = s1->include_stack_ptr - iptr;
3931 if (level) {
3932 if (level > 0)
3933 pp_line(s1, *iptr, 0);
3934 pp_line(s1, file, level);
3936 if (s1->dflag & 7) {
3937 pp_debug_defines(s1);
3938 if (s1->dflag & 4)
3939 continue;
3942 if (is_space(tok)) {
3943 if (spcs < sizeof white - 1)
3944 white[spcs++] = tok;
3945 continue;
3946 } else if (tok == TOK_LINEFEED) {
3947 spcs = 0;
3948 if (token_seen == TOK_LINEFEED)
3949 continue;
3950 ++file->line_ref;
3951 } else if (token_seen == TOK_LINEFEED) {
3952 pp_line(s1, file, 0);
3953 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
3954 white[spcs++] = ' ';
3957 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
3958 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
3959 token_seen = pp_check_he0xE(tok, p);
3961 return 0;
3964 /* ------------------------------------------------------------------------- */