stuff & etc..
[tinycc.git] / tccpp.c
bloba76654e3fed5d62e69938c9b6882a7da36a8d994
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_once;
52 static int pp_expr;
53 static int pp_counter;
54 static void tok_print(const char *msg, const int *str);
56 static struct TinyAlloc *toksym_alloc;
57 static struct TinyAlloc *tokstr_alloc;
59 static TokenString *macro_stack;
61 static const char tcc_keywords[] =
62 #define DEF(id, str) str "\0"
63 #include "tcctok.h"
64 #undef DEF
67 /* WARNING: the content of this string encodes token numbers */
68 static const unsigned char tok_two_chars[] =
69 /* outdated -- gr
70 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
71 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
72 */{
73 '<','=', TOK_LE,
74 '>','=', TOK_GE,
75 '!','=', TOK_NE,
76 '&','&', TOK_LAND,
77 '|','|', TOK_LOR,
78 '+','+', TOK_INC,
79 '-','-', TOK_DEC,
80 '=','=', TOK_EQ,
81 '<','<', TOK_SHL,
82 '>','>', TOK_SAR,
83 '+','=', TOK_A_ADD,
84 '-','=', TOK_A_SUB,
85 '*','=', TOK_A_MUL,
86 '/','=', TOK_A_DIV,
87 '%','=', TOK_A_MOD,
88 '&','=', TOK_A_AND,
89 '^','=', TOK_A_XOR,
90 '|','=', TOK_A_OR,
91 '-','>', TOK_ARROW,
92 '.','.', TOK_TWODOTS,
93 '#','#', TOK_TWOSHARPS,
94 '#','#', TOK_PPJOIN,
98 static void next_nomacro(void);
100 ST_FUNC void skip(int c)
102 if (tok != c)
103 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
104 next();
107 ST_FUNC void expect(const char *msg)
109 tcc_error("%s expected", msg);
112 /* ------------------------------------------------------------------------- */
113 /* Custom allocator for tiny objects */
115 #define USE_TAL
117 #ifndef USE_TAL
118 #define tal_free(al, p) tcc_free(p)
119 #define tal_realloc(al, p, size) tcc_realloc(p, size)
120 #define tal_new(a,b,c)
121 #define tal_delete(a)
122 #else
123 #if !defined(MEM_DEBUG)
124 #define tal_free(al, p) tal_free_impl(al, p)
125 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
126 #define TAL_DEBUG_PARAMS
127 #else
128 #define TAL_DEBUG 1
129 //#define TAL_INFO 1 /* collect and dump allocators stats */
130 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
131 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
132 #define TAL_DEBUG_PARAMS , const char *file, int line
133 #define TAL_DEBUG_FILE_LEN 40
134 #endif
136 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
137 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
138 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
139 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
140 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
141 #define CSTR_TAL_LIMIT 1024
143 typedef struct TinyAlloc {
144 unsigned limit;
145 unsigned size;
146 uint8_t *buffer;
147 uint8_t *p;
148 unsigned nb_allocs;
149 struct TinyAlloc *next, *top;
150 #ifdef TAL_INFO
151 unsigned nb_peak;
152 unsigned nb_total;
153 unsigned nb_missed;
154 uint8_t *peak_p;
155 #endif
156 } TinyAlloc;
158 typedef struct tal_header_t {
159 unsigned size;
160 #ifdef TAL_DEBUG
161 int line_num; /* negative line_num used for double free check */
162 char file_name[TAL_DEBUG_FILE_LEN + 1];
163 #endif
164 } tal_header_t;
166 /* ------------------------------------------------------------------------- */
168 static TinyAlloc *tal_new(TinyAlloc **pal, unsigned limit, unsigned size)
170 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
171 al->p = al->buffer = tcc_malloc(size);
172 al->limit = limit;
173 al->size = size;
174 if (pal) *pal = al;
175 return al;
178 static void tal_delete(TinyAlloc *al)
180 TinyAlloc *next;
182 tail_call:
183 if (!al)
184 return;
185 #ifdef TAL_INFO
186 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
187 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
188 (al->peak_p - al->buffer) * 100.0 / al->size);
189 #endif
190 #ifdef TAL_DEBUG
191 if (al->nb_allocs > 0) {
192 uint8_t *p;
193 fprintf(stderr, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
194 al->nb_allocs, al->limit);
195 p = al->buffer;
196 while (p < al->p) {
197 tal_header_t *header = (tal_header_t *)p;
198 if (header->line_num > 0) {
199 fprintf(stderr, "%s:%d: chunk of %d bytes leaked\n",
200 header->file_name, header->line_num, header->size);
202 p += header->size + sizeof(tal_header_t);
204 #if MEM_DEBUG-0 == 2
205 exit(2);
206 #endif
208 #endif
209 next = al->next;
210 tcc_free(al->buffer);
211 tcc_free(al);
212 al = next;
213 goto tail_call;
216 static void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
218 if (!p)
219 return;
220 tail_call:
221 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
222 #ifdef TAL_DEBUG
223 tal_header_t *header = (((tal_header_t *)p) - 1);
224 if (header->line_num < 0) {
225 fprintf(stderr, "%s:%d: TAL_DEBUG: double frees chunk from\n",
226 file, line);
227 fprintf(stderr, "%s:%d: %d bytes\n",
228 header->file_name, (int)-header->line_num, (int)header->size);
229 } else
230 header->line_num = -header->line_num;
231 #endif
232 al->nb_allocs--;
233 if (!al->nb_allocs)
234 al->p = al->buffer;
235 } else if (al->next) {
236 al = al->next;
237 goto tail_call;
239 else
240 tcc_free(p);
243 static void *tal_realloc_impl(TinyAlloc **pal, void *p, unsigned size TAL_DEBUG_PARAMS)
245 tal_header_t *header;
246 void *ret;
247 int is_own;
248 unsigned adj_size = (size + 3) & -4;
249 TinyAlloc *al = *pal;
251 tail_call:
252 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
253 if ((!p || is_own) && size <= al->limit) {
254 if (al->p - al->buffer + adj_size + sizeof(tal_header_t) < al->size) {
255 header = (tal_header_t *)al->p;
256 header->size = adj_size;
257 #ifdef TAL_DEBUG
258 { int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
259 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
260 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
261 header->line_num = line; }
262 #endif
263 ret = al->p + sizeof(tal_header_t);
264 al->p += adj_size + sizeof(tal_header_t);
265 if (is_own) {
266 header = (((tal_header_t *)p) - 1);
267 if (p) memcpy(ret, p, header->size);
268 #ifdef TAL_DEBUG
269 header->line_num = -header->line_num;
270 #endif
271 } else {
272 al->nb_allocs++;
274 #ifdef TAL_INFO
275 if (al->nb_peak < al->nb_allocs)
276 al->nb_peak = al->nb_allocs;
277 if (al->peak_p < al->p)
278 al->peak_p = al->p;
279 al->nb_total++;
280 #endif
281 return ret;
282 } else if (is_own) {
283 al->nb_allocs--;
284 ret = tal_realloc(*pal, 0, size);
285 header = (((tal_header_t *)p) - 1);
286 if (p) memcpy(ret, p, header->size);
287 #ifdef TAL_DEBUG
288 header->line_num = -header->line_num;
289 #endif
290 return ret;
292 if (al->next) {
293 al = al->next;
294 } else {
295 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
297 al = tal_new(pal, next->limit, next->size * 2);
298 al->next = next;
299 bottom->top = al;
301 goto tail_call;
303 if (is_own) {
304 al->nb_allocs--;
305 ret = tcc_malloc(size);
306 header = (((tal_header_t *)p) - 1);
307 if (p) memcpy(ret, p, header->size);
308 #ifdef TAL_DEBUG
309 header->line_num = -header->line_num;
310 #endif
311 } else if (al->next) {
312 al = al->next;
313 goto tail_call;
314 } else
315 ret = tcc_realloc(p, size);
316 #ifdef TAL_INFO
317 al->nb_missed++;
318 #endif
319 return ret;
322 #endif /* USE_TAL */
324 /* ------------------------------------------------------------------------- */
325 /* CString handling */
326 static void cstr_realloc(CString *cstr, int new_size)
328 int size;
330 size = cstr->size_allocated;
331 if (size < 8)
332 size = 8; /* no need to allocate a too small first string */
333 while (size < new_size)
334 size = size * 2;
335 cstr->data = tcc_realloc(cstr->data, size);
336 cstr->size_allocated = size;
339 /* add a byte */
340 ST_INLN void cstr_ccat(CString *cstr, int ch)
342 int size;
343 size = cstr->size + 1;
344 if (size > cstr->size_allocated)
345 cstr_realloc(cstr, size);
346 ((unsigned char *)cstr->data)[size - 1] = ch;
347 cstr->size = size;
350 ST_INLN char *unicode_to_utf8 (char *b, uint32_t Uc)
352 if (Uc<0x80) *b++=Uc;
353 else if (Uc<0x800) *b++=192+Uc/64, *b++=128+Uc%64;
354 else if (Uc-0xd800u<0x800) goto error;
355 else if (Uc<0x10000) *b++=224+Uc/4096, *b++=128+Uc/64%64, *b++=128+Uc%64;
356 else if (Uc<0x110000) *b++=240+Uc/262144, *b++=128+Uc/4096%64, *b++=128+Uc/64%64, *b++=128+Uc%64;
357 else error: tcc_error("0x%x is not a valid universal character", Uc);
358 return b;
361 /* add a unicode character expanded into utf8 */
362 ST_INLN void cstr_u8cat(CString *cstr, int ch)
364 char buf[4], *e;
365 e = unicode_to_utf8(buf, (uint32_t)ch);
366 cstr_cat(cstr, buf, e - buf);
369 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
371 int size;
372 if (len <= 0)
373 len = strlen(str) + 1 + len;
374 size = cstr->size + len;
375 if (size > cstr->size_allocated)
376 cstr_realloc(cstr, size);
377 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
378 cstr->size = size;
381 /* add a wide char */
382 ST_FUNC void cstr_wccat(CString *cstr, int ch)
384 int size;
385 size = cstr->size + sizeof(nwchar_t);
386 if (size > cstr->size_allocated)
387 cstr_realloc(cstr, size);
388 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
389 cstr->size = size;
392 ST_FUNC void cstr_new(CString *cstr)
394 memset(cstr, 0, sizeof(CString));
397 /* free string and reset it to NULL */
398 ST_FUNC void cstr_free(CString *cstr)
400 tcc_free(cstr->data);
403 /* reset string to empty */
404 ST_FUNC void cstr_reset(CString *cstr)
406 cstr->size = 0;
409 ST_FUNC int cstr_vprintf(CString *cstr, const char *fmt, va_list ap)
411 va_list v;
412 int len, size = 80;
413 for (;;) {
414 size += cstr->size;
415 if (size > cstr->size_allocated)
416 cstr_realloc(cstr, size);
417 size = cstr->size_allocated - cstr->size;
418 va_copy(v, ap);
419 len = vsnprintf((char*)cstr->data + cstr->size, size, fmt, v);
420 va_end(v);
421 if (len >= 0 && len < size)
422 break;
423 size *= 2;
425 cstr->size += len;
426 return len;
429 ST_FUNC int cstr_printf(CString *cstr, const char *fmt, ...)
431 va_list ap; int len;
432 va_start(ap, fmt);
433 len = cstr_vprintf(cstr, fmt, ap);
434 va_end(ap);
435 return len;
438 /* XXX: unicode ? */
439 static void add_char(CString *cstr, int c)
441 if (c == '\'' || c == '\"' || c == '\\') {
442 /* XXX: could be more precise if char or string */
443 cstr_ccat(cstr, '\\');
445 if (c >= 32 && c <= 126) {
446 cstr_ccat(cstr, c);
447 } else {
448 cstr_ccat(cstr, '\\');
449 if (c == '\n') {
450 cstr_ccat(cstr, 'n');
451 } else {
452 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
453 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
454 cstr_ccat(cstr, '0' + (c & 7));
459 /* ------------------------------------------------------------------------- */
460 /* allocate a new token */
461 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
463 TokenSym *ts, **ptable;
464 int i;
466 if (tok_ident >= SYM_FIRST_ANOM)
467 tcc_error("memory full (symbols)");
469 /* expand token table if needed */
470 i = tok_ident - TOK_IDENT;
471 if ((i % TOK_ALLOC_INCR) == 0) {
472 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
473 table_ident = ptable;
476 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
477 table_ident[i] = ts;
478 ts->tok = tok_ident++;
479 ts->sym_define = NULL;
480 ts->sym_label = NULL;
481 ts->sym_struct = NULL;
482 ts->sym_identifier = NULL;
483 ts->len = len;
484 ts->hash_next = NULL;
485 memcpy(ts->str, str, len);
486 ts->str[len] = '\0';
487 *pts = ts;
488 return ts;
491 #define TOK_HASH_INIT 1
492 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
495 /* find a token and add it if not found */
496 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
498 TokenSym *ts, **pts;
499 int i;
500 unsigned int h;
502 h = TOK_HASH_INIT;
503 for(i=0;i<len;i++)
504 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
505 h &= (TOK_HASH_SIZE - 1);
507 pts = &hash_ident[h];
508 for(;;) {
509 ts = *pts;
510 if (!ts)
511 break;
512 if (ts->len == len && !memcmp(ts->str, str, len))
513 return ts;
514 pts = &(ts->hash_next);
516 return tok_alloc_new(pts, str, len);
519 ST_FUNC int tok_alloc_const(const char *str)
521 return tok_alloc(str, strlen(str))->tok;
525 /* XXX: buffer overflow */
526 /* XXX: float tokens */
527 ST_FUNC const char *get_tok_str(int v, CValue *cv)
529 char *p;
530 int i, len;
532 cstr_reset(&cstr_buf);
533 p = cstr_buf.data;
535 switch(v) {
536 case TOK_CINT:
537 case TOK_CUINT:
538 case TOK_CLONG:
539 case TOK_CULONG:
540 case TOK_CLLONG:
541 case TOK_CULLONG:
542 /* XXX: not quite exact, but only useful for testing */
543 #ifdef _WIN32
544 sprintf(p, "%u", (unsigned)cv->i);
545 #else
546 sprintf(p, "%llu", (unsigned long long)cv->i);
547 #endif
548 break;
549 case TOK_LCHAR:
550 cstr_ccat(&cstr_buf, 'L');
551 case TOK_CCHAR:
552 cstr_ccat(&cstr_buf, '\'');
553 add_char(&cstr_buf, cv->i);
554 cstr_ccat(&cstr_buf, '\'');
555 cstr_ccat(&cstr_buf, '\0');
556 break;
557 case TOK_PPNUM:
558 case TOK_PPSTR:
559 return (char*)cv->str.data;
560 case TOK_LSTR:
561 cstr_ccat(&cstr_buf, 'L');
562 case TOK_STR:
563 cstr_ccat(&cstr_buf, '\"');
564 if (v == TOK_STR) {
565 len = cv->str.size - 1;
566 for(i=0;i<len;i++)
567 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
568 } else {
569 len = (cv->str.size / sizeof(nwchar_t)) - 1;
570 for(i=0;i<len;i++)
571 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
573 cstr_ccat(&cstr_buf, '\"');
574 cstr_ccat(&cstr_buf, '\0');
575 break;
577 case TOK_CFLOAT:
578 return strcpy(p, "<float>");
579 case TOK_CDOUBLE:
580 return strcpy(p, "<double>");
581 case TOK_CLDOUBLE:
582 return strcpy(p, "<long double>");
583 case TOK_LINENUM:
584 return strcpy(p, "<linenumber");
586 /* above tokens have value, the ones below don't */
587 case TOK_LT:
588 v = '<';
589 goto addv;
590 case TOK_GT:
591 v = '>';
592 goto addv;
593 case TOK_DOTS:
594 return strcpy(p, "...");
595 case TOK_A_SHL:
596 return strcpy(p, "<<=");
597 case TOK_A_SAR:
598 return strcpy(p, ">>=");
599 case TOK_EOF:
600 return strcpy(p, "<eof>");
601 case 0: /* anonymous nameless symbols */
602 return strcpy(p, "<no name>");
603 default:
604 if (v < TOK_IDENT) {
605 /* search in two bytes table */
606 const unsigned char *q = tok_two_chars;
607 while (*q) {
608 if (q[2] == v) {
609 *p++ = q[0];
610 *p++ = q[1];
611 *p = '\0';
612 return cstr_buf.data;
614 q += 3;
616 if (v >= 127 || (v < 32 && !is_space(v) && v != '\n')) {
617 sprintf(p, "<\\x%02x>", v);
618 break;
620 addv:
621 *p++ = v;
622 *p = '\0';
623 } else if (v < tok_ident) {
624 return table_ident[v - TOK_IDENT]->str;
625 } else if (v >= SYM_FIRST_ANOM) {
626 /* special name for anonymous symbol */
627 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
628 } else {
629 /* should never happen */
630 return NULL;
632 break;
634 return cstr_buf.data;
637 static inline int check_space(int t, int *spc)
639 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
640 if (*spc)
641 return 1;
642 *spc = 1;
643 } else
644 *spc = 0;
645 return 0;
648 /* return the current character, handling end of block if necessary
649 (but not stray) */
650 static int handle_eob(void)
652 BufferedFile *bf = file;
653 int len;
655 /* only tries to read if really end of buffer */
656 if (bf->buf_ptr >= bf->buf_end) {
657 if (bf->fd >= 0) {
658 #if defined(PARSE_DEBUG)
659 len = 1;
660 #else
661 len = IO_BUF_SIZE;
662 #endif
663 len = read(bf->fd, bf->buffer, len);
664 if (len < 0)
665 len = 0;
666 } else {
667 len = 0;
669 total_bytes += len;
670 bf->buf_ptr = bf->buffer;
671 bf->buf_end = bf->buffer + len;
672 *bf->buf_end = CH_EOB;
674 if (bf->buf_ptr < bf->buf_end) {
675 return bf->buf_ptr[0];
676 } else {
677 bf->buf_ptr = bf->buf_end;
678 return CH_EOF;
682 /* read next char from current input file and handle end of input buffer */
683 static int next_c(void)
685 int ch = *++file->buf_ptr;
686 /* end of buffer/file handling */
687 if (ch == CH_EOB && file->buf_ptr >= file->buf_end)
688 ch = handle_eob();
689 return ch;
692 /* input with '\[\r]\n' handling. */
693 static int handle_stray_noerror(int err)
695 int ch;
696 while ((ch = next_c()) == '\\') {
697 ch = next_c();
698 if (ch == '\n') {
699 newl:
700 file->line_num++;
701 } else {
702 if (ch == '\r') {
703 ch = next_c();
704 if (ch == '\n')
705 goto newl;
706 *--file->buf_ptr = '\r';
708 if (err)
709 tcc_error("stray '\\' in program");
710 /* may take advantage of 'BufferedFile.unget[4}' */
711 return *--file->buf_ptr = '\\';
714 return ch;
717 #define ninp() handle_stray_noerror(0)
719 /* handle '\\' in strings, comments and skipped regions */
720 static int handle_bs(uint8_t **p)
722 int c;
723 file->buf_ptr = *p - 1;
724 c = ninp();
725 *p = file->buf_ptr;
726 return c;
729 /* skip the stray and handle the \\n case. Output an error if
730 incorrect char after the stray */
731 static int handle_stray(uint8_t **p)
733 int c;
734 file->buf_ptr = *p - 1;
735 c = handle_stray_noerror(!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS));
736 *p = file->buf_ptr;
737 return c;
740 /* handle the complicated stray case */
741 #define PEEKC(c, p)\
743 c = *++p;\
744 if (c == '\\')\
745 c = handle_stray(&p); \
748 static int skip_spaces(void)
750 int ch;
751 --file->buf_ptr;
752 do {
753 ch = ninp();
754 } while (isidnum_table[ch - CH_EOF] & IS_SPC);
755 return ch;
758 /* single line C++ comments */
759 static uint8_t *parse_line_comment(uint8_t *p)
761 int c;
762 for(;;) {
763 for (;;) {
764 c = *++p;
765 redo:
766 if (c == '\n' || c == '\\')
767 break;
768 c = *++p;
769 if (c == '\n' || c == '\\')
770 break;
772 if (c == '\n')
773 break;
774 c = handle_bs(&p);
775 if (c == CH_EOF)
776 break;
777 if (c != '\\')
778 goto redo;
780 return p;
783 /* C comments */
784 static uint8_t *parse_comment(uint8_t *p)
786 int c;
787 for(;;) {
788 /* fast skip loop */
789 for(;;) {
790 c = *++p;
791 redo:
792 if (c == '\n' || c == '*' || c == '\\')
793 break;
794 c = *++p;
795 if (c == '\n' || c == '*' || c == '\\')
796 break;
798 /* now we can handle all the cases */
799 if (c == '\n') {
800 file->line_num++;
801 } else if (c == '*') {
802 do {
803 c = *++p;
804 } while (c == '*');
805 if (c == '\\')
806 c = handle_bs(&p);
807 if (c == '/')
808 break;
809 goto check_eof;
810 } else {
811 c = handle_bs(&p);
812 check_eof:
813 if (c == CH_EOF)
814 tcc_error("unexpected end of file in comment");
815 if (c != '\\')
816 goto redo;
819 return p + 1;
822 /* parse a string without interpreting escapes */
823 static uint8_t *parse_pp_string(uint8_t *p, int sep, CString *str)
825 int c;
826 for(;;) {
827 c = *++p;
828 redo:
829 if (c == sep) {
830 break;
831 } else if (c == '\\') {
832 c = handle_bs(&p);
833 if (c == CH_EOF) {
834 unterminated_string:
835 /* XXX: indicate line number of start of string */
836 tok_flags &= ~TOK_FLAG_BOL;
837 tcc_error("missing terminating %c character", sep);
838 } else if (c == '\\') {
839 if (str)
840 cstr_ccat(str, c);
841 c = *++p;
842 /* add char after '\\' unconditionally */
843 if (c == '\\') {
844 c = handle_bs(&p);
845 if (c == CH_EOF)
846 goto unterminated_string;
848 goto add_char;
849 } else {
850 goto redo;
852 } else if (c == '\n') {
853 add_lf:
854 if (ACCEPT_LF_IN_STRINGS) {
855 file->line_num++;
856 goto add_char;
857 } else if (str) { /* not skipping */
858 goto unterminated_string;
859 } else {
860 //tcc_warning("missing terminating %c character", sep);
861 return p;
863 } else if (c == '\r') {
864 c = *++p;
865 if (c == '\\')
866 c = handle_bs(&p);
867 if (c == '\n')
868 goto add_lf;
869 if (c == CH_EOF)
870 goto unterminated_string;
871 if (str)
872 cstr_ccat(str, '\r');
873 goto redo;
874 } else {
875 add_char:
876 if (str)
877 cstr_ccat(str, c);
880 p++;
881 return p;
884 /* skip block of text until #else, #elif or #endif. skip also pairs of
885 #if/#endif */
886 static void preprocess_skip(void)
888 int a, start_of_line, c, in_warn_or_error;
889 uint8_t *p;
891 p = file->buf_ptr;
892 a = 0;
893 redo_start:
894 start_of_line = 1;
895 in_warn_or_error = 0;
896 for(;;) {
897 redo_no_start:
898 c = *p;
899 switch(c) {
900 case ' ':
901 case '\t':
902 case '\f':
903 case '\v':
904 case '\r':
905 p++;
906 goto redo_no_start;
907 case '\n':
908 file->line_num++;
909 p++;
910 goto redo_start;
911 case '\\':
912 c = handle_bs(&p);
913 if (c == CH_EOF)
914 expect("#endif");
915 if (c == '\\')
916 ++p;
917 goto redo_no_start;
918 /* skip strings */
919 case '\"':
920 case '\'':
921 if (in_warn_or_error)
922 goto _default;
923 tok_flags &= ~TOK_FLAG_BOL;
924 p = parse_pp_string(p, c, NULL);
925 break;
926 /* skip comments */
927 case '/':
928 if (in_warn_or_error)
929 goto _default;
930 ++p;
931 c = handle_bs(&p);
932 if (c == '*') {
933 p = parse_comment(p);
934 } else if (c == '/') {
935 p = parse_line_comment(p);
937 break;
938 case '#':
939 p++;
940 if (start_of_line) {
941 file->buf_ptr = p;
942 next_nomacro();
943 p = file->buf_ptr;
944 if (a == 0 &&
945 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
946 goto the_end;
947 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
948 a++;
949 else if (tok == TOK_ENDIF)
950 a--;
951 else if( tok == TOK_ERROR || tok == TOK_WARNING)
952 in_warn_or_error = 1;
953 else if (tok == TOK_LINEFEED)
954 goto redo_start;
955 else if (parse_flags & PARSE_FLAG_ASM_FILE)
956 p = parse_line_comment(p - 1);
958 #if !defined(TCC_TARGET_ARM)
959 else if (parse_flags & PARSE_FLAG_ASM_FILE)
960 p = parse_line_comment(p - 1);
961 #else
962 /* ARM assembly uses '#' for constants */
963 #endif
964 break;
965 _default:
966 default:
967 p++;
968 break;
970 start_of_line = 0;
972 the_end: ;
973 file->buf_ptr = p;
976 #if 0
977 /* return the number of additional 'ints' necessary to store the
978 token */
979 static inline int tok_size(const int *p)
981 switch(*p) {
982 /* 4 bytes */
983 case TOK_CINT:
984 case TOK_CUINT:
985 case TOK_CCHAR:
986 case TOK_LCHAR:
987 case TOK_CFLOAT:
988 case TOK_LINENUM:
989 return 1 + 1;
990 case TOK_STR:
991 case TOK_LSTR:
992 case TOK_PPNUM:
993 case TOK_PPSTR:
994 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
995 case TOK_CLONG:
996 case TOK_CULONG:
997 return 1 + LONG_SIZE / 4;
998 case TOK_CDOUBLE:
999 case TOK_CLLONG:
1000 case TOK_CULLONG:
1001 return 1 + 2;
1002 case TOK_CLDOUBLE:
1003 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
1004 return 1 + 8 / 4;
1005 #else
1006 return 1 + LDOUBLE_SIZE / 4;
1007 #endif
1008 default:
1009 return 1 + 0;
1012 #endif
1014 /* token string handling */
1015 ST_INLN void tok_str_new(TokenString *s)
1017 s->str = NULL;
1018 s->len = s->lastlen = 0;
1019 s->allocated_len = 0;
1020 s->last_line_num = -1;
1023 ST_FUNC TokenString *tok_str_alloc(void)
1025 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1026 tok_str_new(str);
1027 return str;
1030 ST_FUNC int *tok_str_dup(TokenString *s)
1032 int *str;
1034 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1035 memcpy(str, s->str, s->len * sizeof(int));
1036 return str;
1039 ST_FUNC void tok_str_free_str(int *str)
1041 tal_free(tokstr_alloc, str);
1044 ST_FUNC void tok_str_free(TokenString *str)
1046 tok_str_free_str(str->str);
1047 tal_free(tokstr_alloc, str);
1050 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1052 int *str, size;
1054 size = s->allocated_len;
1055 if (size < 16)
1056 size = 16;
1057 while (size < new_size)
1058 size = size * 2;
1059 if (size > s->allocated_len) {
1060 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1061 s->allocated_len = size;
1062 s->str = str;
1064 return s->str;
1067 ST_FUNC void tok_str_add(TokenString *s, int t)
1069 int len, *str;
1071 len = s->len;
1072 str = s->str;
1073 if (len >= s->allocated_len)
1074 str = tok_str_realloc(s, len + 1);
1075 str[len++] = t;
1076 s->len = len;
1079 ST_FUNC void begin_macro(TokenString *str, int alloc)
1081 str->alloc = alloc;
1082 str->prev = macro_stack;
1083 str->prev_ptr = macro_ptr;
1084 str->save_line_num = file->line_num;
1085 macro_ptr = str->str;
1086 macro_stack = str;
1089 ST_FUNC void end_macro(void)
1091 TokenString *str = macro_stack;
1092 macro_stack = str->prev;
1093 macro_ptr = str->prev_ptr;
1094 file->line_num = str->save_line_num;
1095 str->len = 0; /* matters if str not alloced, may be tokstr_buf */
1096 if (str->alloc != 0) {
1097 if (str->alloc == 2)
1098 str->str = NULL; /* don't free */
1099 tok_str_free(str);
1103 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1105 int len, *str;
1107 len = s->lastlen = s->len;
1108 str = s->str;
1110 /* allocate space for worst case */
1111 if (len + TOK_MAX_SIZE >= s->allocated_len)
1112 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1113 str[len++] = t;
1114 switch(t) {
1115 case TOK_CINT:
1116 case TOK_CUINT:
1117 case TOK_CCHAR:
1118 case TOK_LCHAR:
1119 case TOK_CFLOAT:
1120 case TOK_LINENUM:
1121 #if LONG_SIZE == 4
1122 case TOK_CLONG:
1123 case TOK_CULONG:
1124 #endif
1125 str[len++] = cv->tab[0];
1126 break;
1127 case TOK_PPNUM:
1128 case TOK_PPSTR:
1129 case TOK_STR:
1130 case TOK_LSTR:
1132 /* Insert the string into the int array. */
1133 size_t nb_words =
1134 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1135 if (len + nb_words >= s->allocated_len)
1136 str = tok_str_realloc(s, len + nb_words + 1);
1137 str[len] = cv->str.size;
1138 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1139 len += nb_words;
1141 break;
1142 case TOK_CDOUBLE:
1143 case TOK_CLLONG:
1144 case TOK_CULLONG:
1145 #if LONG_SIZE == 8
1146 case TOK_CLONG:
1147 case TOK_CULONG:
1148 #endif
1149 str[len++] = cv->tab[0];
1150 str[len++] = cv->tab[1];
1151 break;
1152 case TOK_CLDOUBLE:
1153 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1154 str[len++] = cv->tab[0];
1155 str[len++] = cv->tab[1];
1156 #elif LDOUBLE_SIZE == 12
1157 str[len++] = cv->tab[0];
1158 str[len++] = cv->tab[1];
1159 str[len++] = cv->tab[2];
1160 #elif LDOUBLE_SIZE == 16
1161 str[len++] = cv->tab[0];
1162 str[len++] = cv->tab[1];
1163 str[len++] = cv->tab[2];
1164 str[len++] = cv->tab[3];
1165 #else
1166 #error add long double size support
1167 #endif
1168 break;
1169 default:
1170 break;
1172 s->len = len;
1175 /* add the current parse token in token string 's' */
1176 ST_FUNC void tok_str_add_tok(TokenString *s)
1178 CValue cval;
1180 /* save line number info */
1181 if (file->line_num != s->last_line_num) {
1182 s->last_line_num = file->line_num;
1183 cval.i = s->last_line_num;
1184 tok_str_add2(s, TOK_LINENUM, &cval);
1186 tok_str_add2(s, tok, &tokc);
1189 /* get a token from an integer array and increment pointer. */
1190 static inline void tok_get(int *t, const int **pp, CValue *cv)
1192 const int *p = *pp;
1193 int n, *tab;
1195 tab = cv->tab;
1196 switch(*t = *p++) {
1197 #if LONG_SIZE == 4
1198 case TOK_CLONG:
1199 #endif
1200 case TOK_CINT:
1201 case TOK_CCHAR:
1202 case TOK_LCHAR:
1203 case TOK_LINENUM:
1204 cv->i = *p++;
1205 break;
1206 #if LONG_SIZE == 4
1207 case TOK_CULONG:
1208 #endif
1209 case TOK_CUINT:
1210 cv->i = (unsigned)*p++;
1211 break;
1212 case TOK_CFLOAT:
1213 tab[0] = *p++;
1214 break;
1215 case TOK_STR:
1216 case TOK_LSTR:
1217 case TOK_PPNUM:
1218 case TOK_PPSTR:
1219 cv->str.size = *p++;
1220 cv->str.data = p;
1221 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1222 break;
1223 case TOK_CDOUBLE:
1224 case TOK_CLLONG:
1225 case TOK_CULLONG:
1226 #if LONG_SIZE == 8
1227 case TOK_CLONG:
1228 case TOK_CULONG:
1229 #endif
1230 n = 2;
1231 goto copy;
1232 case TOK_CLDOUBLE:
1233 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1234 n = 2;
1235 #elif LDOUBLE_SIZE == 12
1236 n = 3;
1237 #elif LDOUBLE_SIZE == 16
1238 n = 4;
1239 #else
1240 # error add long double size support
1241 #endif
1242 copy:
1244 *tab++ = *p++;
1245 while (--n);
1246 break;
1247 default:
1248 break;
1250 *pp = p;
1253 #if 0
1254 # define TOK_GET(t,p,c) tok_get(t,p,c)
1255 #else
1256 # define TOK_GET(t,p,c) do { \
1257 int _t = **(p); \
1258 if (TOK_HAS_VALUE(_t)) \
1259 tok_get(t, p, c); \
1260 else \
1261 *(t) = _t, ++*(p); \
1262 } while (0)
1263 #endif
1265 static int macro_is_equal(const int *a, const int *b)
1267 CValue cv;
1268 int t;
1270 if (!a || !b)
1271 return 1;
1273 while (*a && *b) {
1274 cstr_reset(&tokcstr);
1275 TOK_GET(&t, &a, &cv);
1276 cstr_cat(&tokcstr, get_tok_str(t, &cv), 0);
1277 TOK_GET(&t, &b, &cv);
1278 if (strcmp(tokcstr.data, get_tok_str(t, &cv)))
1279 return 0;
1281 return !(*a || *b);
1284 /* defines handling */
1285 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1287 Sym *s, *o;
1289 o = define_find(v);
1290 s = sym_push2(&define_stack, v, macro_type, 0);
1291 s->d = str;
1292 s->next = first_arg;
1293 table_ident[v - TOK_IDENT]->sym_define = s;
1295 if (o && !macro_is_equal(o->d, s->d))
1296 tcc_warning("%s redefined", get_tok_str(v, NULL));
1299 /* undefined a define symbol. Its name is just set to zero */
1300 ST_FUNC void define_undef(Sym *s)
1302 int v = s->v;
1303 if (v >= TOK_IDENT && v < tok_ident)
1304 table_ident[v - TOK_IDENT]->sym_define = NULL;
1307 ST_INLN Sym *define_find(int v)
1309 v -= TOK_IDENT;
1310 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1311 return NULL;
1312 return table_ident[v]->sym_define;
1315 /* free define stack until top reaches 'b' */
1316 ST_FUNC void free_defines(Sym *b)
1318 while (define_stack != b) {
1319 Sym *top = define_stack;
1320 define_stack = top->prev;
1321 tok_str_free_str(top->d);
1322 define_undef(top);
1323 sym_free(top);
1327 /* fake the nth "#if defined test_..." for tcc -dt -run */
1328 static void maybe_run_test(TCCState *s)
1330 const char *p;
1331 if (s->include_stack_ptr != s->include_stack)
1332 return;
1333 p = get_tok_str(tok, NULL);
1334 if (0 != memcmp(p, "test_", 5))
1335 return;
1336 if (0 != --s->run_test)
1337 return;
1338 fprintf(s->ppfp, &"\n[%s]\n"[!(s->dflag & 32)], p), fflush(s->ppfp);
1339 define_push(tok, MACRO_OBJ, NULL, NULL);
1342 static CachedInclude *
1343 search_cached_include(TCCState *s1, const char *filename, int add);
1345 static int parse_include(TCCState *s1, int do_next, int test)
1347 int c, i;
1348 char name[1024], buf[1024], *p;
1349 CachedInclude *e;
1351 c = skip_spaces();
1352 if (c == '<' || c == '\"') {
1353 cstr_reset(&tokcstr);
1354 file->buf_ptr = parse_pp_string(file->buf_ptr, c == '<' ? '>' : c, &tokcstr);
1355 i = tokcstr.size;
1356 pstrncpy(name, tokcstr.data, i >= sizeof name ? sizeof name - 1 : i);
1357 next_nomacro();
1358 } else {
1359 /* computed #include : concatenate tokens until result is one of
1360 the two accepted forms. Don't convert pp-tokens to tokens here. */
1361 parse_flags = PARSE_FLAG_PREPROCESS
1362 | PARSE_FLAG_LINEFEED
1363 | (parse_flags & PARSE_FLAG_ASM_FILE);
1364 name[0] = 0;
1365 for (;;) {
1366 next();
1367 p = name, i = strlen(p) - 1;
1368 if (i > 0
1369 && ((p[0] == '"' && p[i] == '"')
1370 || (p[0] == '<' && p[i] == '>')))
1371 break;
1372 if (tok == TOK_LINEFEED)
1373 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1374 pstrcat(name, sizeof name, get_tok_str(tok, &tokc));
1376 c = p[0];
1377 /* remove '<>|""' */
1378 memmove(p, p + 1, i - 1), p[i - 1] = 0;
1381 i = do_next ? file->include_next_index : -1;
1382 for (;;) {
1383 ++i;
1384 if (i == 0) {
1385 /* check absolute include path */
1386 if (!IS_ABSPATH(name))
1387 continue;
1388 buf[0] = '\0';
1389 } else if (i == 1) {
1390 /* search in file's dir if "header.h" */
1391 if (c != '\"')
1392 continue;
1393 p = file->true_filename;
1394 pstrncpy(buf, p, tcc_basename(p) - p);
1395 } else {
1396 int j = i - 2, k = j - s1->nb_include_paths;
1397 if (k < 0)
1398 p = s1->include_paths[j];
1399 else if (k < s1->nb_sysinclude_paths)
1400 p = s1->sysinclude_paths[k];
1401 else if (test)
1402 return 0;
1403 else
1404 tcc_error("include file '%s' not found", name);
1405 pstrcpy(buf, sizeof buf, p);
1406 pstrcat(buf, sizeof buf, "/");
1408 pstrcat(buf, sizeof buf, name);
1409 e = search_cached_include(s1, buf, 0);
1410 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1411 /* no need to parse the include because the 'ifndef macro'
1412 is defined (or had #pragma once) */
1413 #ifdef INC_DEBUG
1414 printf("%s: skipping cached %s\n", file->filename, buf);
1415 #endif
1416 return 1;
1418 if (tcc_open(s1, buf) >= 0)
1419 break;
1422 if (test) {
1423 tcc_close();
1424 } else {
1425 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1426 tcc_error("#include recursion too deep");
1427 /* push previous file on stack */
1428 *s1->include_stack_ptr++ = file->prev;
1429 file->include_next_index = i;
1430 #ifdef INC_DEBUG
1431 printf("%s: including %s\n", file->prev->filename, file->filename);
1432 #endif
1433 /* update target deps */
1434 if (s1->gen_deps) {
1435 BufferedFile *bf = file;
1436 while (i == 1 && (bf = bf->prev))
1437 i = bf->include_next_index;
1438 /* skip system include files */
1439 if (s1->include_sys_deps || i - 2 < s1->nb_include_paths)
1440 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1441 tcc_strdup(buf));
1443 /* add include file debug info */
1444 tcc_debug_bincl(s1);
1445 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1447 return 1;
1450 /* eval an expression for #if/#elif */
1451 static int expr_preprocess(TCCState *s1)
1453 int c, t;
1454 TokenString *str;
1456 str = tok_str_alloc();
1457 pp_expr = 1;
1458 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1459 next(); /* do macro subst */
1460 redo:
1461 if (tok == TOK_DEFINED) {
1462 next_nomacro();
1463 t = tok;
1464 if (t == '(')
1465 next_nomacro();
1466 if (tok < TOK_IDENT)
1467 expect("identifier");
1468 if (s1->run_test)
1469 maybe_run_test(s1);
1470 c = 0;
1471 if (define_find(tok)
1472 || tok == TOK___HAS_INCLUDE
1473 || tok == TOK___HAS_INCLUDE_NEXT)
1474 c = 1;
1475 if (t == '(') {
1476 next_nomacro();
1477 if (tok != ')')
1478 expect("')'");
1480 tok = TOK_CINT;
1481 tokc.i = c;
1482 } else if (tok == TOK___HAS_INCLUDE ||
1483 tok == TOK___HAS_INCLUDE_NEXT) {
1484 t = tok;
1485 next_nomacro();
1486 if (tok != '(')
1487 expect("(");
1488 c = parse_include(s1, t - TOK___HAS_INCLUDE, 1);
1489 if (tok != ')')
1490 expect("')'");
1491 tok = TOK_CINT;
1492 tokc.i = c;
1493 } else if (tok >= TOK_IDENT) {
1494 /* if undefined macro, replace with zero, check for func-like */
1495 t = tok;
1496 tok = TOK_CINT;
1497 tokc.i = 0;
1498 tok_str_add_tok(str);
1499 next();
1500 if (tok == '(')
1501 tcc_error("function-like macro '%s' is not defined",
1502 get_tok_str(t, NULL));
1503 goto redo;
1505 tok_str_add_tok(str);
1507 pp_expr = 0;
1508 tok_str_add(str, -1); /* simulate end of file */
1509 tok_str_add(str, 0);
1510 /* now evaluate C constant expression */
1511 begin_macro(str, 1);
1512 next();
1513 c = expr_const();
1514 end_macro();
1515 return c != 0;
1519 /* parse after #define */
1520 ST_FUNC void parse_define(void)
1522 Sym *s, *first, **ps;
1523 int v, t, varg, is_vaargs, spc;
1524 int saved_parse_flags = parse_flags;
1526 v = tok;
1527 if (v < TOK_IDENT || v == TOK_DEFINED)
1528 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1529 /* XXX: should check if same macro (ANSI) */
1530 first = NULL;
1531 t = MACRO_OBJ;
1532 /* We have to parse the whole define as if not in asm mode, in particular
1533 no line comment with '#' must be ignored. Also for function
1534 macros the argument list must be parsed without '.' being an ID
1535 character. */
1536 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1537 /* '(' must be just after macro definition for MACRO_FUNC */
1538 next_nomacro();
1539 parse_flags &= ~PARSE_FLAG_SPACES;
1540 if (tok == '(') {
1541 int dotid = set_idnum('.', 0);
1542 next_nomacro();
1543 ps = &first;
1544 if (tok != ')') for (;;) {
1545 varg = tok;
1546 next_nomacro();
1547 is_vaargs = 0;
1548 if (varg == TOK_DOTS) {
1549 varg = TOK___VA_ARGS__;
1550 is_vaargs = 1;
1551 } else if (tok == TOK_DOTS && gnu_ext) {
1552 is_vaargs = 1;
1553 next_nomacro();
1555 if (varg < TOK_IDENT)
1556 bad_list:
1557 tcc_error("bad macro parameter list");
1558 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1559 *ps = s;
1560 ps = &s->next;
1561 if (tok == ')')
1562 break;
1563 if (tok != ',' || is_vaargs)
1564 goto bad_list;
1565 next_nomacro();
1567 parse_flags |= PARSE_FLAG_SPACES;
1568 next_nomacro();
1569 t = MACRO_FUNC;
1570 set_idnum('.', dotid);
1573 tokstr_buf.len = 0;
1574 spc = 2;
1575 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1576 /* The body of a macro definition should be parsed such that identifiers
1577 are parsed like the file mode determines (i.e. with '.' being an
1578 ID character in asm mode). But '#' should be retained instead of
1579 regarded as line comment leader, so still don't set ASM_FILE
1580 in parse_flags. */
1581 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1582 /* remove spaces around ## and after '#' */
1583 if (TOK_TWOSHARPS == tok) {
1584 if (2 == spc)
1585 goto bad_twosharp;
1586 if (1 == spc)
1587 --tokstr_buf.len;
1588 spc = 3;
1589 tok = TOK_PPJOIN;
1590 } else if ('#' == tok) {
1591 spc = 4;
1592 } else if (check_space(tok, &spc)) {
1593 goto skip;
1595 tok_str_add2(&tokstr_buf, tok, &tokc);
1596 skip:
1597 next_nomacro();
1600 parse_flags = saved_parse_flags;
1601 if (spc == 1)
1602 --tokstr_buf.len; /* remove trailing space */
1603 tok_str_add(&tokstr_buf, 0);
1604 if (3 == spc)
1605 bad_twosharp:
1606 tcc_error("'##' cannot appear at either end of macro");
1607 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1610 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1612 const unsigned char *s;
1613 unsigned int h;
1614 CachedInclude *e;
1615 int i;
1617 h = TOK_HASH_INIT;
1618 s = (unsigned char *) filename;
1619 while (*s) {
1620 #ifdef _WIN32
1621 h = TOK_HASH_FUNC(h, toup(*s));
1622 #else
1623 h = TOK_HASH_FUNC(h, *s);
1624 #endif
1625 s++;
1627 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1629 i = s1->cached_includes_hash[h];
1630 for(;;) {
1631 if (i == 0)
1632 break;
1633 e = s1->cached_includes[i - 1];
1634 if (0 == PATHCMP(e->filename, filename))
1635 return e;
1636 i = e->hash_next;
1638 if (!add)
1639 return NULL;
1641 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1642 strcpy(e->filename, filename);
1643 e->ifndef_macro = e->once = 0;
1644 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1645 /* add in hash table */
1646 e->hash_next = s1->cached_includes_hash[h];
1647 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1648 #ifdef INC_DEBUG
1649 printf("adding cached '%s'\n", filename);
1650 #endif
1651 return e;
1654 static void pragma_parse(TCCState *s1)
1656 next_nomacro();
1657 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1658 int t = tok, v;
1659 Sym *s;
1661 if (next(), tok != '(')
1662 goto pragma_err;
1663 if (next(), tok != TOK_STR)
1664 goto pragma_err;
1665 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1666 if (next(), tok != ')')
1667 goto pragma_err;
1668 if (t == TOK_push_macro) {
1669 while (NULL == (s = define_find(v)))
1670 define_push(v, 0, NULL, NULL);
1671 s->type.ref = s; /* set push boundary */
1672 } else {
1673 for (s = define_stack; s; s = s->prev)
1674 if (s->v == v && s->type.ref == s) {
1675 s->type.ref = NULL;
1676 break;
1679 if (s)
1680 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1681 else
1682 tcc_warning("unbalanced #pragma pop_macro");
1683 pp_debug_tok = t, pp_debug_symv = v;
1685 } else if (tok == TOK_once) {
1686 search_cached_include(s1, file->filename, 1)->once = pp_once;
1688 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1689 /* tcc -E: keep pragmas below unchanged */
1690 unget_tok(' ');
1691 unget_tok(TOK_PRAGMA);
1692 unget_tok('#');
1693 unget_tok(TOK_LINEFEED);
1695 } else if (tok == TOK_pack) {
1696 /* This may be:
1697 #pragma pack(1) // set
1698 #pragma pack() // reset to default
1699 #pragma pack(push) // push current
1700 #pragma pack(push,1) // push & set
1701 #pragma pack(pop) // restore previous */
1702 next();
1703 skip('(');
1704 if (tok == TOK_ASM_pop) {
1705 next();
1706 if (s1->pack_stack_ptr <= s1->pack_stack) {
1707 stk_error:
1708 tcc_error("out of pack stack");
1710 s1->pack_stack_ptr--;
1711 } else {
1712 int val = 0;
1713 if (tok != ')') {
1714 if (tok == TOK_ASM_push) {
1715 next();
1716 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1717 goto stk_error;
1718 val = *s1->pack_stack_ptr++;
1719 if (tok != ',')
1720 goto pack_set;
1721 next();
1723 if (tok != TOK_CINT)
1724 goto pragma_err;
1725 val = tokc.i;
1726 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1727 goto pragma_err;
1728 next();
1730 pack_set:
1731 *s1->pack_stack_ptr = val;
1733 if (tok != ')')
1734 goto pragma_err;
1736 } else if (tok == TOK_comment) {
1737 char *p; int t;
1738 next();
1739 skip('(');
1740 t = tok;
1741 next();
1742 skip(',');
1743 if (tok != TOK_STR)
1744 goto pragma_err;
1745 p = tcc_strdup((char *)tokc.str.data);
1746 next();
1747 if (tok != ')')
1748 goto pragma_err;
1749 if (t == TOK_lib) {
1750 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1751 } else {
1752 if (t == TOK_option)
1753 tcc_set_options(s1, p);
1754 tcc_free(p);
1757 } else
1758 tcc_warning_c(warn_unsupported)("#pragma %s ignored", get_tok_str(tok, &tokc));
1759 return;
1761 pragma_err:
1762 tcc_error("malformed #pragma directive");
1763 return;
1766 /* is_bof is true if first non space token at beginning of file */
1767 ST_FUNC void preprocess(int is_bof)
1769 TCCState *s1 = tcc_state;
1770 int c, n, saved_parse_flags;
1771 char buf[1024], *q;
1772 Sym *s;
1774 saved_parse_flags = parse_flags;
1775 parse_flags = PARSE_FLAG_PREPROCESS
1776 | PARSE_FLAG_TOK_NUM
1777 | PARSE_FLAG_TOK_STR
1778 | PARSE_FLAG_LINEFEED
1779 | (parse_flags & PARSE_FLAG_ASM_FILE)
1782 next_nomacro();
1783 redo:
1784 switch(tok) {
1785 case TOK_DEFINE:
1786 pp_debug_tok = tok;
1787 next_nomacro();
1788 pp_debug_symv = tok;
1789 parse_define();
1790 break;
1791 case TOK_UNDEF:
1792 pp_debug_tok = tok;
1793 next_nomacro();
1794 pp_debug_symv = tok;
1795 s = define_find(tok);
1796 /* undefine symbol by putting an invalid name */
1797 if (s)
1798 define_undef(s);
1799 break;
1800 case TOK_INCLUDE:
1801 case TOK_INCLUDE_NEXT:
1802 parse_include(s1, tok - TOK_INCLUDE, 0);
1803 break;
1804 case TOK_IFNDEF:
1805 c = 1;
1806 goto do_ifdef;
1807 case TOK_IF:
1808 c = expr_preprocess(s1);
1809 goto do_if;
1810 case TOK_IFDEF:
1811 c = 0;
1812 do_ifdef:
1813 next_nomacro();
1814 if (tok < TOK_IDENT)
1815 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1816 if (is_bof) {
1817 if (c) {
1818 #ifdef INC_DEBUG
1819 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1820 #endif
1821 file->ifndef_macro = tok;
1824 if (define_find(tok)
1825 || tok == TOK___HAS_INCLUDE
1826 || tok == TOK___HAS_INCLUDE_NEXT)
1827 c ^= 1;
1828 do_if:
1829 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1830 tcc_error("memory full (ifdef)");
1831 *s1->ifdef_stack_ptr++ = c;
1832 goto test_skip;
1833 case TOK_ELSE:
1834 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1835 tcc_error("#else without matching #if");
1836 if (s1->ifdef_stack_ptr[-1] & 2)
1837 tcc_error("#else after #else");
1838 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1839 goto test_else;
1840 case TOK_ELIF:
1841 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1842 tcc_error("#elif without matching #if");
1843 c = s1->ifdef_stack_ptr[-1];
1844 if (c > 1)
1845 tcc_error("#elif after #else");
1846 /* last #if/#elif expression was true: we skip */
1847 if (c == 1) {
1848 c = 0;
1849 } else {
1850 c = expr_preprocess(s1);
1851 s1->ifdef_stack_ptr[-1] = c;
1853 test_else:
1854 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1855 file->ifndef_macro = 0;
1856 test_skip:
1857 if (!(c & 1)) {
1858 preprocess_skip();
1859 is_bof = 0;
1860 goto redo;
1862 break;
1863 case TOK_ENDIF:
1864 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1865 tcc_error("#endif without matching #if");
1866 s1->ifdef_stack_ptr--;
1867 /* '#ifndef macro' was at the start of file. Now we check if
1868 an '#endif' is exactly at the end of file */
1869 if (file->ifndef_macro &&
1870 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1871 file->ifndef_macro_saved = file->ifndef_macro;
1872 /* need to set to zero to avoid false matches if another
1873 #ifndef at middle of file */
1874 file->ifndef_macro = 0;
1875 while (tok != TOK_LINEFEED)
1876 next_nomacro();
1877 tok_flags |= TOK_FLAG_ENDIF;
1878 goto the_end;
1880 break;
1881 case TOK_PPNUM:
1882 n = strtoul((char*)tokc.str.data, &q, 10);
1883 goto _line_num;
1884 case TOK_LINE:
1885 next();
1886 if (tok != TOK_CINT)
1887 _line_err:
1888 tcc_error("wrong #line format");
1889 n = tokc.i;
1890 _line_num:
1891 next();
1892 if (tok != TOK_LINEFEED) {
1893 if (tok == TOK_STR) {
1894 if (file->true_filename == file->filename)
1895 file->true_filename = tcc_strdup(file->filename);
1896 q = (char *)tokc.str.data;
1897 buf[0] = 0;
1898 if (!IS_ABSPATH(q)) {
1899 /* prepend directory from real file */
1900 pstrcpy(buf, sizeof buf, file->true_filename);
1901 *tcc_basename(buf) = 0;
1903 pstrcat(buf, sizeof buf, q);
1904 tcc_debug_putfile(s1, buf);
1905 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
1906 break;
1907 else
1908 goto _line_err;
1909 --n;
1911 if (file->fd > 0)
1912 total_lines += file->line_num - n;
1913 file->line_num = n;
1914 break;
1915 case TOK_ERROR:
1916 case TOK_WARNING:
1917 q = buf;
1918 c = skip_spaces();
1919 while (c != '\n' && c != CH_EOF) {
1920 if ((q - buf) < sizeof(buf) - 1)
1921 *q++ = c;
1922 c = ninp();
1924 *q = '\0';
1925 if (tok == TOK_ERROR)
1926 tcc_error("#error %s", buf);
1927 else
1928 tcc_warning("#warning %s", buf);
1929 break;
1930 case TOK_PRAGMA:
1931 pragma_parse(s1);
1932 break;
1933 case TOK_LINEFEED:
1934 goto the_end;
1935 default:
1936 /* ignore gas line comment in an 'S' file. */
1937 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1938 goto ignore;
1939 if (tok == '!' && is_bof)
1940 /* '!' is ignored at beginning to allow C scripts. */
1941 goto ignore;
1942 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1943 ignore:
1944 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
1945 goto the_end;
1947 /* ignore other preprocess commands or #! for C scripts */
1948 while (tok != TOK_LINEFEED)
1949 next_nomacro();
1950 the_end:
1951 parse_flags = saved_parse_flags;
1954 /* evaluate escape codes in a string. */
1955 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1957 int c, n, i;
1958 const uint8_t *p;
1960 p = buf;
1961 for(;;) {
1962 c = *p;
1963 if (c == '\0')
1964 break;
1965 if (c == '\\') {
1966 p++;
1967 /* escape */
1968 c = *p;
1969 switch(c) {
1970 case '0': case '1': case '2': case '3':
1971 case '4': case '5': case '6': case '7':
1972 /* at most three octal digits */
1973 n = c - '0';
1974 p++;
1975 c = *p;
1976 if (isoct(c)) {
1977 n = n * 8 + c - '0';
1978 p++;
1979 c = *p;
1980 if (isoct(c)) {
1981 n = n * 8 + c - '0';
1982 p++;
1985 c = n;
1986 goto add_char_nonext;
1987 case 'x': i = 0; goto parse_hex_or_ucn;
1988 case 'u': i = 4; goto parse_hex_or_ucn;
1989 case 'U': i = 8; goto parse_hex_or_ucn;
1990 parse_hex_or_ucn:
1991 p++;
1992 n = 0;
1993 do {
1994 c = *p;
1995 if (c >= 'a' && c <= 'f')
1996 c = c - 'a' + 10;
1997 else if (c >= 'A' && c <= 'F')
1998 c = c - 'A' + 10;
1999 else if (isnum(c))
2000 c = c - '0';
2001 else if (i > 0)
2002 expect("more hex digits in universal-character-name");
2003 else
2004 goto add_hex_or_ucn;
2005 n = n * 16 + c;
2006 p++;
2007 } while (--i);
2008 if (is_long) {
2009 add_hex_or_ucn:
2010 c = n;
2011 goto add_char_nonext;
2013 cstr_u8cat(outstr, n);
2014 continue;
2015 case 'a':
2016 c = '\a';
2017 break;
2018 case 'b':
2019 c = '\b';
2020 break;
2021 case 'f':
2022 c = '\f';
2023 break;
2024 case 'n':
2025 c = '\n';
2026 break;
2027 case 'r':
2028 c = '\r';
2029 break;
2030 case 't':
2031 c = '\t';
2032 break;
2033 case 'v':
2034 c = '\v';
2035 break;
2036 case 'e':
2037 if (!gnu_ext)
2038 goto invalid_escape;
2039 c = 27;
2040 break;
2041 case '\'':
2042 case '\"':
2043 case '\\':
2044 case '?':
2045 break;
2046 default:
2047 invalid_escape:
2048 if (c >= '!' && c <= '~')
2049 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2050 else
2051 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2052 break;
2054 } else if (is_long && c >= 0x80) {
2055 /* assume we are processing UTF-8 sequence */
2056 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2058 int cont; /* count of continuation bytes */
2059 int skip; /* how many bytes should skip when error occurred */
2060 int i;
2062 /* decode leading byte */
2063 if (c < 0xC2) {
2064 skip = 1; goto invalid_utf8_sequence;
2065 } else if (c <= 0xDF) {
2066 cont = 1; n = c & 0x1f;
2067 } else if (c <= 0xEF) {
2068 cont = 2; n = c & 0xf;
2069 } else if (c <= 0xF4) {
2070 cont = 3; n = c & 0x7;
2071 } else {
2072 skip = 1; goto invalid_utf8_sequence;
2075 /* decode continuation bytes */
2076 for (i = 1; i <= cont; i++) {
2077 int l = 0x80, h = 0xBF;
2079 /* adjust limit for second byte */
2080 if (i == 1) {
2081 switch (c) {
2082 case 0xE0: l = 0xA0; break;
2083 case 0xED: h = 0x9F; break;
2084 case 0xF0: l = 0x90; break;
2085 case 0xF4: h = 0x8F; break;
2089 if (p[i] < l || p[i] > h) {
2090 skip = i; goto invalid_utf8_sequence;
2093 n = (n << 6) | (p[i] & 0x3f);
2096 /* advance pointer */
2097 p += 1 + cont;
2098 c = n;
2099 goto add_char_nonext;
2101 /* error handling */
2102 invalid_utf8_sequence:
2103 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2104 c = 0xFFFD;
2105 p += skip;
2106 goto add_char_nonext;
2109 p++;
2110 add_char_nonext:
2111 if (!is_long)
2112 cstr_ccat(outstr, c);
2113 else {
2114 #ifdef TCC_TARGET_PE
2115 /* store as UTF-16 */
2116 if (c < 0x10000) {
2117 cstr_wccat(outstr, c);
2118 } else {
2119 c -= 0x10000;
2120 cstr_wccat(outstr, (c >> 10) + 0xD800);
2121 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2123 #else
2124 cstr_wccat(outstr, c);
2125 #endif
2128 /* add a trailing '\0' */
2129 if (!is_long)
2130 cstr_ccat(outstr, '\0');
2131 else
2132 cstr_wccat(outstr, '\0');
2135 static void parse_string(const char *s, int len)
2137 uint8_t buf[1000], *p = buf;
2138 int is_long, sep;
2140 if ((is_long = *s == 'L'))
2141 ++s, --len;
2142 sep = *s++;
2143 len -= 2;
2144 if (len >= sizeof buf)
2145 p = tcc_malloc(len + 1);
2146 memcpy(p, s, len);
2147 p[len] = 0;
2149 cstr_reset(&tokcstr);
2150 parse_escape_string(&tokcstr, p, is_long);
2151 if (p != buf)
2152 tcc_free(p);
2154 if (sep == '\'') {
2155 int char_size, i, n, c;
2156 /* XXX: make it portable */
2157 if (!is_long)
2158 tok = TOK_CCHAR, char_size = 1;
2159 else
2160 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2161 n = tokcstr.size / char_size - 1;
2162 if (n < 1)
2163 tcc_error("empty character constant");
2164 if (n > 1)
2165 tcc_warning_c(warn_all)("multi-character character constant");
2166 for (c = i = 0; i < n; ++i) {
2167 if (is_long)
2168 c = ((nwchar_t *)tokcstr.data)[i];
2169 else
2170 c = (c << 8) | ((char *)tokcstr.data)[i];
2172 tokc.i = c;
2173 } else {
2174 tokc.str.size = tokcstr.size;
2175 tokc.str.data = tokcstr.data;
2176 if (!is_long)
2177 tok = TOK_STR;
2178 else
2179 tok = TOK_LSTR;
2183 /* we use 64 bit numbers */
2184 #define BN_SIZE 2
2186 /* bn = (bn << shift) | or_val */
2187 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2189 int i;
2190 unsigned int v;
2191 for(i=0;i<BN_SIZE;i++) {
2192 v = bn[i];
2193 bn[i] = (v << shift) | or_val;
2194 or_val = v >> (32 - shift);
2198 static void bn_zero(unsigned int *bn)
2200 int i;
2201 for(i=0;i<BN_SIZE;i++) {
2202 bn[i] = 0;
2206 /* parse number in null terminated string 'p' and return it in the
2207 current token */
2208 static void parse_number(const char *p)
2210 int b, t, shift, frac_bits, s, exp_val, ch;
2211 char *q;
2212 unsigned int bn[BN_SIZE];
2213 double d;
2215 /* number */
2216 q = token_buf;
2217 ch = *p++;
2218 t = ch;
2219 ch = *p++;
2220 *q++ = t;
2221 b = 10;
2222 if (t == '.') {
2223 goto float_frac_parse;
2224 } else if (t == '0') {
2225 if (ch == 'x' || ch == 'X') {
2226 q--;
2227 ch = *p++;
2228 b = 16;
2229 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2230 q--;
2231 ch = *p++;
2232 b = 2;
2235 /* parse all digits. cannot check octal numbers at this stage
2236 because of floating point constants */
2237 while (1) {
2238 if (ch >= 'a' && ch <= 'f')
2239 t = ch - 'a' + 10;
2240 else if (ch >= 'A' && ch <= 'F')
2241 t = ch - 'A' + 10;
2242 else if (isnum(ch))
2243 t = ch - '0';
2244 else
2245 break;
2246 if (t >= b)
2247 break;
2248 if (q >= token_buf + STRING_MAX_SIZE) {
2249 num_too_long:
2250 tcc_error("number too long");
2252 *q++ = ch;
2253 ch = *p++;
2255 if (ch == '.' ||
2256 ((ch == 'e' || ch == 'E') && b == 10) ||
2257 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2258 if (b != 10) {
2259 /* NOTE: strtox should support that for hexa numbers, but
2260 non ISOC99 libcs do not support it, so we prefer to do
2261 it by hand */
2262 /* hexadecimal or binary floats */
2263 /* XXX: handle overflows */
2264 *q = '\0';
2265 if (b == 16)
2266 shift = 4;
2267 else
2268 shift = 1;
2269 bn_zero(bn);
2270 q = token_buf;
2271 while (1) {
2272 t = *q++;
2273 if (t == '\0') {
2274 break;
2275 } else if (t >= 'a') {
2276 t = t - 'a' + 10;
2277 } else if (t >= 'A') {
2278 t = t - 'A' + 10;
2279 } else {
2280 t = t - '0';
2282 bn_lshift(bn, shift, t);
2284 frac_bits = 0;
2285 if (ch == '.') {
2286 ch = *p++;
2287 while (1) {
2288 t = ch;
2289 if (t >= 'a' && t <= 'f') {
2290 t = t - 'a' + 10;
2291 } else if (t >= 'A' && t <= 'F') {
2292 t = t - 'A' + 10;
2293 } else if (t >= '0' && t <= '9') {
2294 t = t - '0';
2295 } else {
2296 break;
2298 if (t >= b)
2299 tcc_error("invalid digit");
2300 bn_lshift(bn, shift, t);
2301 frac_bits += shift;
2302 ch = *p++;
2305 if (ch != 'p' && ch != 'P')
2306 expect("exponent");
2307 ch = *p++;
2308 s = 1;
2309 exp_val = 0;
2310 if (ch == '+') {
2311 ch = *p++;
2312 } else if (ch == '-') {
2313 s = -1;
2314 ch = *p++;
2316 if (ch < '0' || ch > '9')
2317 expect("exponent digits");
2318 while (ch >= '0' && ch <= '9') {
2319 exp_val = exp_val * 10 + ch - '0';
2320 ch = *p++;
2322 exp_val = exp_val * s;
2324 /* now we can generate the number */
2325 /* XXX: should patch directly float number */
2326 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2327 d = ldexp(d, exp_val - frac_bits);
2328 t = toup(ch);
2329 if (t == 'F') {
2330 ch = *p++;
2331 tok = TOK_CFLOAT;
2332 /* float : should handle overflow */
2333 tokc.f = (float)d;
2334 } else if (t == 'L') {
2335 ch = *p++;
2336 tok = TOK_CLDOUBLE;
2337 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2338 tokc.d = d;
2339 #else
2340 /* XXX: not large enough */
2341 tokc.ld = (long double)d;
2342 #endif
2343 } else {
2344 tok = TOK_CDOUBLE;
2345 tokc.d = d;
2347 } else {
2348 /* decimal floats */
2349 if (ch == '.') {
2350 if (q >= token_buf + STRING_MAX_SIZE)
2351 goto num_too_long;
2352 *q++ = ch;
2353 ch = *p++;
2354 float_frac_parse:
2355 while (ch >= '0' && ch <= '9') {
2356 if (q >= token_buf + STRING_MAX_SIZE)
2357 goto num_too_long;
2358 *q++ = ch;
2359 ch = *p++;
2362 if (ch == 'e' || ch == 'E') {
2363 if (q >= token_buf + STRING_MAX_SIZE)
2364 goto num_too_long;
2365 *q++ = ch;
2366 ch = *p++;
2367 if (ch == '-' || ch == '+') {
2368 if (q >= token_buf + STRING_MAX_SIZE)
2369 goto num_too_long;
2370 *q++ = ch;
2371 ch = *p++;
2373 if (ch < '0' || ch > '9')
2374 expect("exponent digits");
2375 while (ch >= '0' && ch <= '9') {
2376 if (q >= token_buf + STRING_MAX_SIZE)
2377 goto num_too_long;
2378 *q++ = ch;
2379 ch = *p++;
2382 *q = '\0';
2383 t = toup(ch);
2384 errno = 0;
2385 if (t == 'F') {
2386 ch = *p++;
2387 tok = TOK_CFLOAT;
2388 tokc.f = strtof(token_buf, NULL);
2389 } else if (t == 'L') {
2390 ch = *p++;
2391 tok = TOK_CLDOUBLE;
2392 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2393 tokc.d = strtod(token_buf, NULL);
2394 #else
2395 tokc.ld = strtold(token_buf, NULL);
2396 #endif
2397 } else {
2398 tok = TOK_CDOUBLE;
2399 tokc.d = strtod(token_buf, NULL);
2402 } else {
2403 unsigned long long n, n1;
2404 int lcount, ucount, ov = 0;
2405 const char *p1;
2407 /* integer number */
2408 *q = '\0';
2409 q = token_buf;
2410 if (b == 10 && *q == '0') {
2411 b = 8;
2412 q++;
2414 n = 0;
2415 while(1) {
2416 t = *q++;
2417 /* no need for checks except for base 10 / 8 errors */
2418 if (t == '\0')
2419 break;
2420 else if (t >= 'a')
2421 t = t - 'a' + 10;
2422 else if (t >= 'A')
2423 t = t - 'A' + 10;
2424 else
2425 t = t - '0';
2426 if (t >= b)
2427 tcc_error("invalid digit");
2428 n1 = n;
2429 n = n * b + t;
2430 /* detect overflow */
2431 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2432 ov = 1;
2435 /* Determine the characteristics (unsigned and/or 64bit) the type of
2436 the constant must have according to the constant suffix(es) */
2437 lcount = ucount = 0;
2438 p1 = p;
2439 for(;;) {
2440 t = toup(ch);
2441 if (t == 'L') {
2442 if (lcount >= 2)
2443 tcc_error("three 'l's in integer constant");
2444 if (lcount && *(p - 1) != ch)
2445 tcc_error("incorrect integer suffix: %s", p1);
2446 lcount++;
2447 ch = *p++;
2448 } else if (t == 'U') {
2449 if (ucount >= 1)
2450 tcc_error("two 'u's in integer constant");
2451 ucount++;
2452 ch = *p++;
2453 } else {
2454 break;
2458 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2459 if (ucount == 0 && b == 10) {
2460 if (lcount <= (LONG_SIZE == 4)) {
2461 if (n >= 0x80000000U)
2462 lcount = (LONG_SIZE == 4) + 1;
2464 if (n >= 0x8000000000000000ULL)
2465 ov = 1, ucount = 1;
2466 } else {
2467 if (lcount <= (LONG_SIZE == 4)) {
2468 if (n >= 0x100000000ULL)
2469 lcount = (LONG_SIZE == 4) + 1;
2470 else if (n >= 0x80000000U)
2471 ucount = 1;
2473 if (n >= 0x8000000000000000ULL)
2474 ucount = 1;
2477 if (ov)
2478 tcc_warning("integer constant overflow");
2480 tok = TOK_CINT;
2481 if (lcount) {
2482 tok = TOK_CLONG;
2483 if (lcount == 2)
2484 tok = TOK_CLLONG;
2486 if (ucount)
2487 ++tok; /* TOK_CU... */
2488 tokc.i = n;
2490 if (ch)
2491 tcc_error("invalid number");
2495 #define PARSE2(c1, tok1, c2, tok2) \
2496 case c1: \
2497 PEEKC(c, p); \
2498 if (c == c2) { \
2499 p++; \
2500 tok = tok2; \
2501 } else { \
2502 tok = tok1; \
2504 break;
2506 /* return next token without macro substitution */
2507 static inline void next_nomacro1(void)
2509 int t, c, is_long, len;
2510 TokenSym *ts;
2511 uint8_t *p, *p1;
2512 unsigned int h;
2514 p = file->buf_ptr;
2515 redo_no_start:
2516 c = *p;
2517 switch(c) {
2518 case ' ':
2519 case '\t':
2520 tok = c;
2521 p++;
2522 maybe_space:
2523 if (parse_flags & PARSE_FLAG_SPACES)
2524 goto keep_tok_flags;
2525 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2526 ++p;
2527 goto redo_no_start;
2528 case '\f':
2529 case '\v':
2530 case '\r':
2531 p++;
2532 goto redo_no_start;
2533 case '\\':
2534 /* first look if it is in fact an end of buffer */
2535 c = handle_stray(&p);
2536 if (c == '\\')
2537 goto parse_simple;
2538 if (c == CH_EOF) {
2539 TCCState *s1 = tcc_state;
2540 if ((parse_flags & PARSE_FLAG_LINEFEED)
2541 && !(tok_flags & TOK_FLAG_EOF)) {
2542 tok_flags |= TOK_FLAG_EOF;
2543 tok = TOK_LINEFEED;
2544 goto keep_tok_flags;
2545 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2546 tok = TOK_EOF;
2547 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2548 tcc_error("missing #endif");
2549 } else if (s1->include_stack_ptr == s1->include_stack) {
2550 /* no include left : end of file. */
2551 tok = TOK_EOF;
2552 } else {
2553 tok_flags &= ~TOK_FLAG_EOF;
2554 /* pop include file */
2556 /* test if previous '#endif' was after a #ifdef at
2557 start of file */
2558 if (tok_flags & TOK_FLAG_ENDIF) {
2559 #ifdef INC_DEBUG
2560 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2561 #endif
2562 search_cached_include(s1, file->filename, 1)
2563 ->ifndef_macro = file->ifndef_macro_saved;
2564 tok_flags &= ~TOK_FLAG_ENDIF;
2567 /* add end of include file debug info */
2568 tcc_debug_eincl(tcc_state);
2569 /* pop include stack */
2570 tcc_close();
2571 s1->include_stack_ptr--;
2572 p = file->buf_ptr;
2573 if (p == file->buffer)
2574 tok_flags = TOK_FLAG_BOF;
2575 tok_flags |= TOK_FLAG_BOL;
2576 goto redo_no_start;
2578 } else {
2579 goto redo_no_start;
2581 break;
2583 case '\n':
2584 file->line_num++;
2585 tok_flags |= TOK_FLAG_BOL;
2586 p++;
2587 maybe_newline:
2588 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2589 goto redo_no_start;
2590 tok = TOK_LINEFEED;
2591 goto keep_tok_flags;
2593 case '#':
2594 /* XXX: simplify */
2595 PEEKC(c, p);
2596 if ((tok_flags & TOK_FLAG_BOL) &&
2597 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2598 file->buf_ptr = p;
2599 preprocess(tok_flags & TOK_FLAG_BOF);
2600 p = file->buf_ptr;
2601 goto maybe_newline;
2602 } else {
2603 if (c == '#') {
2604 p++;
2605 tok = TOK_TWOSHARPS;
2606 } else {
2607 #if !defined(TCC_TARGET_ARM)
2608 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2609 p = parse_line_comment(p - 1);
2610 goto redo_no_start;
2611 } else
2612 #endif
2614 tok = '#';
2618 break;
2620 /* dollar is allowed to start identifiers when not parsing asm */
2621 case '$':
2622 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2623 || (parse_flags & PARSE_FLAG_ASM_FILE))
2624 goto parse_simple;
2626 case 'a': case 'b': case 'c': case 'd':
2627 case 'e': case 'f': case 'g': case 'h':
2628 case 'i': case 'j': case 'k': case 'l':
2629 case 'm': case 'n': case 'o': case 'p':
2630 case 'q': case 'r': case 's': case 't':
2631 case 'u': case 'v': case 'w': case 'x':
2632 case 'y': case 'z':
2633 case 'A': case 'B': case 'C': case 'D':
2634 case 'E': case 'F': case 'G': case 'H':
2635 case 'I': case 'J': case 'K':
2636 case 'M': case 'N': case 'O': case 'P':
2637 case 'Q': case 'R': case 'S': case 'T':
2638 case 'U': case 'V': case 'W': case 'X':
2639 case 'Y': case 'Z':
2640 case '_':
2641 parse_ident_fast:
2642 p1 = p;
2643 h = TOK_HASH_INIT;
2644 h = TOK_HASH_FUNC(h, c);
2645 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2646 h = TOK_HASH_FUNC(h, c);
2647 len = p - p1;
2648 if (c != '\\') {
2649 TokenSym **pts;
2651 /* fast case : no stray found, so we have the full token
2652 and we have already hashed it */
2653 h &= (TOK_HASH_SIZE - 1);
2654 pts = &hash_ident[h];
2655 for(;;) {
2656 ts = *pts;
2657 if (!ts)
2658 break;
2659 if (ts->len == len && !memcmp(ts->str, p1, len))
2660 goto token_found;
2661 pts = &(ts->hash_next);
2663 ts = tok_alloc_new(pts, (char *) p1, len);
2664 token_found: ;
2665 } else {
2666 /* slower case */
2667 cstr_reset(&tokcstr);
2668 cstr_cat(&tokcstr, (char *) p1, len);
2669 p--;
2670 PEEKC(c, p);
2671 parse_ident_slow:
2672 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2674 cstr_ccat(&tokcstr, c);
2675 PEEKC(c, p);
2677 ts = tok_alloc(tokcstr.data, tokcstr.size);
2679 tok = ts->tok;
2680 break;
2681 case 'L':
2682 t = p[1];
2683 if (t != '\\' && t != '\'' && t != '\"') {
2684 /* fast case */
2685 goto parse_ident_fast;
2686 } else {
2687 PEEKC(c, p);
2688 if (c == '\'' || c == '\"') {
2689 is_long = 1;
2690 goto str_const;
2691 } else {
2692 cstr_reset(&tokcstr);
2693 cstr_ccat(&tokcstr, 'L');
2694 goto parse_ident_slow;
2697 break;
2699 case '0': case '1': case '2': case '3':
2700 case '4': case '5': case '6': case '7':
2701 case '8': case '9':
2702 t = c;
2703 PEEKC(c, p);
2704 /* after the first digit, accept digits, alpha, '.' or sign if
2705 prefixed by 'eEpP' */
2706 parse_num:
2707 cstr_reset(&tokcstr);
2708 for(;;) {
2709 cstr_ccat(&tokcstr, t);
2710 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2711 || c == '.'
2712 || ((c == '+' || c == '-')
2713 && (((t == 'e' || t == 'E')
2714 && !(parse_flags & PARSE_FLAG_ASM_FILE
2715 /* 0xe+1 is 3 tokens in asm */
2716 && ((char*)tokcstr.data)[0] == '0'
2717 && toup(((char*)tokcstr.data)[1]) == 'X'))
2718 || t == 'p' || t == 'P'))))
2719 break;
2720 t = c;
2721 PEEKC(c, p);
2723 /* We add a trailing '\0' to ease parsing */
2724 cstr_ccat(&tokcstr, '\0');
2725 tokc.str.size = tokcstr.size;
2726 tokc.str.data = tokcstr.data;
2727 tok = TOK_PPNUM;
2728 break;
2730 case '.':
2731 /* special dot handling because it can also start a number */
2732 PEEKC(c, p);
2733 if (isnum(c)) {
2734 t = '.';
2735 goto parse_num;
2736 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2737 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2738 *--p = c = '.';
2739 goto parse_ident_fast;
2740 } else if (c == '.') {
2741 PEEKC(c, p);
2742 if (c == '.') {
2743 p++;
2744 tok = TOK_DOTS;
2745 } else {
2746 *--p = '.'; /* may underflow into file->unget[] */
2747 tok = '.';
2749 } else {
2750 tok = '.';
2752 break;
2753 case '\'':
2754 case '\"':
2755 is_long = 0;
2756 str_const:
2757 cstr_reset(&tokcstr);
2758 if (is_long)
2759 cstr_ccat(&tokcstr, 'L');
2760 cstr_ccat(&tokcstr, c);
2761 p = parse_pp_string(p, c, &tokcstr);
2762 cstr_ccat(&tokcstr, c);
2763 cstr_ccat(&tokcstr, '\0');
2764 tokc.str.size = tokcstr.size;
2765 tokc.str.data = tokcstr.data;
2766 tok = TOK_PPSTR;
2767 break;
2769 case '<':
2770 PEEKC(c, p);
2771 if (c == '=') {
2772 p++;
2773 tok = TOK_LE;
2774 } else if (c == '<') {
2775 PEEKC(c, p);
2776 if (c == '=') {
2777 p++;
2778 tok = TOK_A_SHL;
2779 } else {
2780 tok = TOK_SHL;
2782 } else {
2783 tok = TOK_LT;
2785 break;
2786 case '>':
2787 PEEKC(c, p);
2788 if (c == '=') {
2789 p++;
2790 tok = TOK_GE;
2791 } else if (c == '>') {
2792 PEEKC(c, p);
2793 if (c == '=') {
2794 p++;
2795 tok = TOK_A_SAR;
2796 } else {
2797 tok = TOK_SAR;
2799 } else {
2800 tok = TOK_GT;
2802 break;
2804 case '&':
2805 PEEKC(c, p);
2806 if (c == '&') {
2807 p++;
2808 tok = TOK_LAND;
2809 } else if (c == '=') {
2810 p++;
2811 tok = TOK_A_AND;
2812 } else {
2813 tok = '&';
2815 break;
2817 case '|':
2818 PEEKC(c, p);
2819 if (c == '|') {
2820 p++;
2821 tok = TOK_LOR;
2822 } else if (c == '=') {
2823 p++;
2824 tok = TOK_A_OR;
2825 } else {
2826 tok = '|';
2828 break;
2830 case '+':
2831 PEEKC(c, p);
2832 if (c == '+') {
2833 p++;
2834 tok = TOK_INC;
2835 } else if (c == '=') {
2836 p++;
2837 tok = TOK_A_ADD;
2838 } else {
2839 tok = '+';
2841 break;
2843 case '-':
2844 PEEKC(c, p);
2845 if (c == '-') {
2846 p++;
2847 tok = TOK_DEC;
2848 } else if (c == '=') {
2849 p++;
2850 tok = TOK_A_SUB;
2851 } else if (c == '>') {
2852 p++;
2853 tok = TOK_ARROW;
2854 } else {
2855 tok = '-';
2857 break;
2859 PARSE2('!', '!', '=', TOK_NE)
2860 PARSE2('=', '=', '=', TOK_EQ)
2861 PARSE2('*', '*', '=', TOK_A_MUL)
2862 PARSE2('%', '%', '=', TOK_A_MOD)
2863 PARSE2('^', '^', '=', TOK_A_XOR)
2865 /* comments or operator */
2866 case '/':
2867 PEEKC(c, p);
2868 if (c == '*') {
2869 p = parse_comment(p);
2870 /* comments replaced by a blank */
2871 tok = ' ';
2872 goto maybe_space;
2873 } else if (c == '/') {
2874 p = parse_line_comment(p);
2875 tok = ' ';
2876 goto maybe_space;
2877 } else if (c == '=') {
2878 p++;
2879 tok = TOK_A_DIV;
2880 } else {
2881 tok = '/';
2883 break;
2885 /* simple tokens */
2886 case '(':
2887 case ')':
2888 case '[':
2889 case ']':
2890 case '{':
2891 case '}':
2892 case ',':
2893 case ';':
2894 case ':':
2895 case '?':
2896 case '~':
2897 case '@': /* only used in assembler */
2898 parse_simple:
2899 tok = c;
2900 p++;
2901 break;
2902 default:
2903 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2904 goto parse_ident_fast;
2905 if (parse_flags & PARSE_FLAG_ASM_FILE)
2906 goto parse_simple;
2907 tcc_error("unrecognized character \\x%02x", c);
2908 break;
2910 tok_flags = 0;
2911 keep_tok_flags:
2912 file->buf_ptr = p;
2913 #if defined(PARSE_DEBUG)
2914 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
2915 #endif
2918 static void macro_subst(
2919 TokenString *tok_str,
2920 Sym **nested_list,
2921 const int *macro_str
2924 /* substitute arguments in replacement lists in macro_str by the values in
2925 args (field d) and return allocated string */
2926 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2928 int t, t0, t1, spc;
2929 const int *st;
2930 Sym *s;
2931 CValue cval;
2932 TokenString str;
2934 tok_str_new(&str);
2935 t0 = t1 = 0;
2936 while(1) {
2937 TOK_GET(&t, &macro_str, &cval);
2938 if (!t)
2939 break;
2940 if (t == '#') {
2941 /* stringize */
2942 TOK_GET(&t, &macro_str, &cval);
2943 if (!t)
2944 goto bad_stringy;
2945 s = sym_find2(args, t);
2946 if (s) {
2947 cstr_reset(&tokcstr);
2948 cstr_ccat(&tokcstr, '\"');
2949 st = s->d;
2950 spc = 0;
2951 while (*st >= 0) {
2952 TOK_GET(&t, &st, &cval);
2953 if (t != TOK_PLCHLDR
2954 && t != TOK_NOSUBST
2955 && 0 == check_space(t, &spc)) {
2956 const char *s = get_tok_str(t, &cval);
2957 while (*s) {
2958 if (t == TOK_PPSTR && *s != '\'')
2959 add_char(&tokcstr, *s);
2960 else
2961 cstr_ccat(&tokcstr, *s);
2962 ++s;
2966 tokcstr.size -= spc;
2967 cstr_ccat(&tokcstr, '\"');
2968 cstr_ccat(&tokcstr, '\0');
2969 #ifdef PP_DEBUG
2970 printf("\nstringize: <%s>\n", (char *)tokcstr.data);
2971 #endif
2972 /* add string */
2973 cval.str.size = tokcstr.size;
2974 cval.str.data = tokcstr.data;
2975 tok_str_add2(&str, TOK_PPSTR, &cval);
2976 } else {
2977 bad_stringy:
2978 expect("macro parameter after '#'");
2980 } else if (t >= TOK_IDENT) {
2981 s = sym_find2(args, t);
2982 if (s) {
2983 st = s->d;
2984 /* if '##' is present before or after, no arg substitution */
2985 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
2986 /* special case for var arg macros : ## eats the ','
2987 if empty VA_ARGS variable. */
2988 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
2989 if (*st <= 0) {
2990 /* suppress ',' '##' */
2991 str.len -= 2;
2992 } else {
2993 /* suppress '##' and add variable */
2994 str.len--;
2995 goto add_var;
2998 } else {
2999 add_var:
3000 if (!s->next) {
3001 /* Expand arguments tokens and store them. In most
3002 cases we could also re-expand each argument if
3003 used multiple times, but not if the argument
3004 contains the __COUNTER__ macro. */
3005 TokenString str2;
3006 sym_push2(&s->next, s->v, s->type.t, 0);
3007 tok_str_new(&str2);
3008 macro_subst(&str2, nested_list, st);
3009 tok_str_add(&str2, 0);
3010 s->next->d = str2.str;
3012 st = s->next->d;
3014 if (*st <= 0) {
3015 /* expanded to empty string */
3016 tok_str_add(&str, TOK_PLCHLDR);
3017 } else for (;;) {
3018 int t2;
3019 TOK_GET(&t2, &st, &cval);
3020 if (t2 <= 0)
3021 break;
3022 tok_str_add2(&str, t2, &cval);
3024 } else {
3025 tok_str_add(&str, t);
3027 } else {
3028 tok_str_add2(&str, t, &cval);
3030 t0 = t1, t1 = t;
3032 tok_str_add(&str, 0);
3033 return str.str;
3036 static char const ab_month_name[12][4] =
3038 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3039 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3042 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3044 int n, ret = 1;
3046 cstr_reset(&tokcstr);
3047 if (t1 != TOK_PLCHLDR)
3048 cstr_cat(&tokcstr, get_tok_str(t1, v1), -1);
3049 n = tokcstr.size;
3050 if (t2 != TOK_PLCHLDR)
3051 cstr_cat(&tokcstr, get_tok_str(t2, v2), -1);
3052 cstr_ccat(&tokcstr, '\0');
3053 //printf("paste <%s>\n", (char*)tokcstr.data);
3055 tcc_open_bf(tcc_state, ":paste:", tokcstr.size);
3056 memcpy(file->buffer, tokcstr.data, tokcstr.size);
3057 tok_flags = 0;
3058 for (;;) {
3059 next_nomacro1();
3060 if (0 == *file->buf_ptr)
3061 break;
3062 if (is_space(tok))
3063 continue;
3064 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3065 " preprocessing token", n, file->buffer, file->buffer + n);
3066 ret = 0;
3067 break;
3069 tcc_close();
3070 return ret;
3073 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3074 return the resulting string (which must be freed). */
3075 static inline int *macro_twosharps(const int *ptr0)
3077 int t;
3078 CValue cval;
3079 TokenString macro_str1;
3080 int start_of_nosubsts = -1;
3081 const int *ptr;
3083 /* we search the first '##' */
3084 for (ptr = ptr0;;) {
3085 TOK_GET(&t, &ptr, &cval);
3086 if (t == TOK_PPJOIN)
3087 break;
3088 if (t == 0)
3089 return NULL;
3092 tok_str_new(&macro_str1);
3094 //tok_print(" $$$", ptr0);
3095 for (ptr = ptr0;;) {
3096 TOK_GET(&t, &ptr, &cval);
3097 if (t == 0)
3098 break;
3099 if (t == TOK_PPJOIN)
3100 continue;
3101 while (*ptr == TOK_PPJOIN) {
3102 int t1; CValue cv1;
3103 /* given 'a##b', remove nosubsts preceding 'a' */
3104 if (start_of_nosubsts >= 0)
3105 macro_str1.len = start_of_nosubsts;
3106 /* given 'a##b', remove nosubsts preceding 'b' */
3107 while ((t1 = *++ptr) == TOK_NOSUBST)
3109 if (t1 && t1 != TOK_PPJOIN) {
3110 TOK_GET(&t1, &ptr, &cv1);
3111 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3112 if (paste_tokens(t, &cval, t1, &cv1)) {
3113 t = tok, cval = tokc;
3114 } else {
3115 tok_str_add2(&macro_str1, t, &cval);
3116 t = t1, cval = cv1;
3121 if (t == TOK_NOSUBST) {
3122 if (start_of_nosubsts < 0)
3123 start_of_nosubsts = macro_str1.len;
3124 } else {
3125 start_of_nosubsts = -1;
3127 tok_str_add2(&macro_str1, t, &cval);
3129 tok_str_add(&macro_str1, 0);
3130 //tok_print(" ###", macro_str1.str);
3131 return macro_str1.str;
3134 /* peek or read [ws_str == NULL] next token from function macro call,
3135 walking up macro levels up to the file if necessary */
3136 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3138 int t;
3139 const int *p;
3140 Sym *sa;
3142 for (;;) {
3143 if (macro_ptr) {
3144 p = macro_ptr, t = *p;
3145 if (ws_str) {
3146 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3147 tok_str_add(ws_str, t), t = *++p;
3149 if (t == 0) {
3150 end_macro();
3151 /* also, end of scope for nested defined symbol */
3152 sa = *nested_list;
3153 while (sa && sa->v == 0)
3154 sa = sa->prev;
3155 if (sa)
3156 sa->v = 0;
3157 continue;
3159 } else {
3160 uint8_t *p = file->buf_ptr;
3161 int ch = handle_bs(&p);
3162 if (ws_str) {
3163 while (is_space(ch) || ch == '\n' || ch == '/') {
3164 if (ch == '/') {
3165 int c;
3166 PEEKC(c, p);
3167 if (c == '*') {
3168 p = parse_comment(p) - 1;
3169 } else if (c == '/') {
3170 p = parse_line_comment(p) - 1;
3171 } else {
3172 *--p = ch;
3173 break;
3175 ch = ' ';
3177 if (ch == '\n')
3178 file->line_num++;
3179 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3180 tok_str_add(ws_str, ch);
3181 PEEKC(ch, p);
3184 file->buf_ptr = p;
3185 t = ch;
3188 if (ws_str)
3189 return t;
3190 next_nomacro();
3191 return tok;
3195 /* do macro substitution of current token with macro 's' and add
3196 result to (tok_str,tok_len). 'nested_list' is the list of all
3197 macros we got inside to avoid recursing. Return non zero if no
3198 substitution needs to be done */
3199 static int macro_subst_tok(
3200 TokenString *tok_str,
3201 Sym **nested_list,
3202 Sym *s)
3204 Sym *args, *sa, *sa1;
3205 int parlevel, t, t1, spc;
3206 TokenString str;
3207 char *cstrval;
3208 CValue cval;
3209 char buf[32];
3211 /* if symbol is a macro, prepare substitution */
3212 /* special macros */
3213 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3214 t = tok == TOK___LINE__ ? file->line_num : pp_counter++;
3215 snprintf(buf, sizeof(buf), "%d", t);
3216 cstrval = buf;
3217 t1 = TOK_PPNUM;
3218 goto add_cstr1;
3219 } else if (tok == TOK___FILE__) {
3220 cstrval = file->filename;
3221 goto add_cstr;
3222 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3223 time_t ti;
3224 struct tm *tm;
3226 time(&ti);
3227 tm = localtime(&ti);
3228 if (tok == TOK___DATE__) {
3229 snprintf(buf, sizeof(buf), "%s %2d %d",
3230 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3231 } else {
3232 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3233 tm->tm_hour, tm->tm_min, tm->tm_sec);
3235 cstrval = buf;
3236 add_cstr:
3237 t1 = TOK_STR;
3238 add_cstr1:
3239 cstr_reset(&tokcstr);
3240 cstr_cat(&tokcstr, cstrval, 0);
3241 cval.str.size = tokcstr.size;
3242 cval.str.data = tokcstr.data;
3243 tok_str_add2(tok_str, t1, &cval);
3244 } else if (s->d) {
3245 int saved_parse_flags = parse_flags;
3246 int *joined_str = NULL;
3247 int *mstr = s->d;
3249 if (s->type.t == MACRO_FUNC) {
3250 /* whitespace between macro name and argument list */
3251 TokenString ws_str;
3252 tok_str_new(&ws_str);
3254 spc = 0;
3255 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3256 | PARSE_FLAG_ACCEPT_STRAYS;
3258 /* get next token from argument stream */
3259 t = next_argstream(nested_list, &ws_str);
3260 if (t != '(') {
3261 /* not a macro substitution after all, restore the
3262 * macro token plus all whitespace we've read.
3263 * whitespace is intentionally not merged to preserve
3264 * newlines. */
3265 parse_flags = saved_parse_flags;
3266 tok_str_add(tok_str, tok);
3267 if (parse_flags & PARSE_FLAG_SPACES) {
3268 int i;
3269 for (i = 0; i < ws_str.len; i++)
3270 tok_str_add(tok_str, ws_str.str[i]);
3272 if (ws_str.len && ws_str.str[ws_str.len - 1] == '\n')
3273 tok_flags |= TOK_FLAG_BOL;
3274 tok_str_free_str(ws_str.str);
3275 return 0;
3276 } else {
3277 tok_str_free_str(ws_str.str);
3279 do {
3280 next_nomacro(); /* eat '(' */
3281 } while (tok == TOK_PLCHLDR || is_space(tok));
3283 /* argument macro */
3284 args = NULL;
3285 sa = s->next;
3286 /* NOTE: empty args are allowed, except if no args */
3287 for(;;) {
3288 do {
3289 next_argstream(nested_list, NULL);
3290 } while (tok == TOK_PLCHLDR || is_space(tok) ||
3291 TOK_LINEFEED == tok);
3292 empty_arg:
3293 /* handle '()' case */
3294 if (!args && !sa && tok == ')')
3295 break;
3296 if (!sa)
3297 tcc_error("macro '%s' used with too many args",
3298 get_tok_str(s->v, 0));
3299 tok_str_new(&str);
3300 parlevel = spc = 0;
3301 /* NOTE: non zero sa->t indicates VA_ARGS */
3302 while ((parlevel > 0 ||
3303 (tok != ')' &&
3304 (tok != ',' || sa->type.t)))) {
3305 if (tok == TOK_EOF || tok == 0)
3306 break;
3307 if (tok == '(')
3308 parlevel++;
3309 else if (tok == ')')
3310 parlevel--;
3311 if (tok == TOK_LINEFEED)
3312 tok = ' ';
3313 if (!check_space(tok, &spc))
3314 tok_str_add2(&str, tok, &tokc);
3315 next_argstream(nested_list, NULL);
3317 if (parlevel)
3318 expect(")");
3319 str.len -= spc;
3320 tok_str_add(&str, -1);
3321 tok_str_add(&str, 0);
3322 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3323 sa1->d = str.str;
3324 sa = sa->next;
3325 if (tok == ')') {
3326 /* special case for gcc var args: add an empty
3327 var arg argument if it is omitted */
3328 if (sa && sa->type.t && gnu_ext)
3329 goto empty_arg;
3330 break;
3332 if (tok != ',')
3333 expect(",");
3335 if (sa) {
3336 tcc_error("macro '%s' used with too few args",
3337 get_tok_str(s->v, 0));
3340 /* now subst each arg */
3341 mstr = macro_arg_subst(nested_list, mstr, args);
3342 /* free memory */
3343 sa = args;
3344 while (sa) {
3345 sa1 = sa->prev;
3346 tok_str_free_str(sa->d);
3347 if (sa->next) {
3348 tok_str_free_str(sa->next->d);
3349 sym_free(sa->next);
3351 sym_free(sa);
3352 sa = sa1;
3354 parse_flags = saved_parse_flags;
3357 sym_push2(nested_list, s->v, 0, 0);
3358 parse_flags = saved_parse_flags;
3359 joined_str = macro_twosharps(mstr);
3360 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3362 /* pop nested defined symbol */
3363 sa1 = *nested_list;
3364 *nested_list = sa1->prev;
3365 sym_free(sa1);
3366 if (joined_str)
3367 tok_str_free_str(joined_str);
3368 if (mstr != s->d)
3369 tok_str_free_str(mstr);
3371 return 0;
3374 /* do macro substitution of macro_str and add result to
3375 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3376 inside to avoid recursing. */
3377 static void macro_subst(
3378 TokenString *tok_str,
3379 Sym **nested_list,
3380 const int *macro_str
3383 Sym *s;
3384 int t, spc, nosubst;
3385 CValue cval;
3387 spc = nosubst = 0;
3389 while (1) {
3390 TOK_GET(&t, &macro_str, &cval);
3391 if (t <= 0)
3392 break;
3394 if (t >= TOK_IDENT && 0 == nosubst) {
3395 s = define_find(t);
3396 if (s == NULL)
3397 goto no_subst;
3399 /* if nested substitution, do nothing */
3400 if (sym_find2(*nested_list, t)) {
3401 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3402 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3403 goto no_subst;
3407 TokenString *str = tok_str_alloc();
3408 str->str = (int*)macro_str;
3409 begin_macro(str, 2);
3411 tok = t;
3412 macro_subst_tok(tok_str, nested_list, s);
3414 if (macro_stack != str) {
3415 /* already finished by reading function macro arguments */
3416 break;
3419 macro_str = macro_ptr;
3420 end_macro ();
3422 if (tok_str->len)
3423 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3424 } else {
3425 no_subst:
3426 if (!check_space(t, &spc))
3427 tok_str_add2(tok_str, t, &cval);
3429 if (nosubst) {
3430 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3431 continue;
3432 nosubst = 0;
3434 if (t == TOK_NOSUBST)
3435 nosubst = 1;
3437 /* GCC supports 'defined' as result of a macro substitution */
3438 if (t == TOK_DEFINED && pp_expr)
3439 nosubst = 2;
3443 /* return next token without macro substitution. Can read input from
3444 macro_ptr buffer */
3445 static void next_nomacro(void)
3447 int t;
3448 if (macro_ptr) {
3449 redo:
3450 t = *macro_ptr;
3451 if (TOK_HAS_VALUE(t)) {
3452 tok_get(&tok, &macro_ptr, &tokc);
3453 if (t == TOK_LINENUM) {
3454 file->line_num = tokc.i;
3455 goto redo;
3457 } else {
3458 macro_ptr++;
3459 if (t < TOK_IDENT) {
3460 if (!(parse_flags & PARSE_FLAG_SPACES)
3461 && (isidnum_table[t - CH_EOF] & IS_SPC))
3462 goto redo;
3464 tok = t;
3466 } else {
3467 next_nomacro1();
3471 /* return next token with macro substitution */
3472 ST_FUNC void next(void)
3474 int t;
3475 redo:
3476 next_nomacro();
3477 t = tok;
3478 if (macro_ptr) {
3479 if (!TOK_HAS_VALUE(t)) {
3480 if (t == TOK_NOSUBST || t == TOK_PLCHLDR) {
3481 /* discard preprocessor markers */
3482 goto redo;
3483 } else if (t == 0) {
3484 /* end of macro or unget token string */
3485 end_macro();
3486 goto redo;
3487 } else if (t == '\\') {
3488 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3489 tcc_error("stray '\\' in program");
3491 return;
3493 } else if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3494 /* if reading from file, try to substitute macros */
3495 Sym *s = define_find(t);
3496 if (s) {
3497 Sym *nested_list = NULL;
3498 tokstr_buf.len = 0;
3499 macro_subst_tok(&tokstr_buf, &nested_list, s);
3500 tok_str_add(&tokstr_buf, 0);
3501 begin_macro(&tokstr_buf, 0);
3502 goto redo;
3504 return;
3506 /* convert preprocessor tokens into C tokens */
3507 if (t == TOK_PPNUM) {
3508 if (parse_flags & PARSE_FLAG_TOK_NUM)
3509 parse_number((char *)tokc.str.data);
3510 } else if (t == TOK_PPSTR) {
3511 if (parse_flags & PARSE_FLAG_TOK_STR)
3512 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3516 /* push back current token and set current token to 'last_tok'. Only
3517 identifier case handled for labels. */
3518 ST_INLN void unget_tok(int last_tok)
3521 TokenString *str = tok_str_alloc();
3522 tok_str_add2(str, tok, &tokc);
3523 tok_str_add(str, 0);
3524 begin_macro(str, 1);
3525 tok = last_tok;
3528 /* ------------------------------------------------------------------------- */
3529 /* init preprocessor */
3531 static const char * const target_os_defs =
3532 #ifdef TCC_TARGET_PE
3533 "_WIN32\0"
3534 # if PTR_SIZE == 8
3535 "_WIN64\0"
3536 # endif
3537 #else
3538 # if defined TCC_TARGET_MACHO
3539 "__APPLE__\0"
3540 # elif TARGETOS_FreeBSD
3541 "__FreeBSD__ 12\0"
3542 # elif TARGETOS_FreeBSD_kernel
3543 "__FreeBSD_kernel__\0"
3544 # elif TARGETOS_NetBSD
3545 "__NetBSD__\0"
3546 # elif TARGETOS_OpenBSD
3547 "__OpenBSD__\0"
3548 # else
3549 "__linux__\0"
3550 "__linux\0"
3551 # if TARGETOS_ANDROID
3552 "__ANDROID__\0"
3553 # endif
3554 # endif
3555 "__unix__\0"
3556 "__unix\0"
3557 #endif
3560 static void putdef(CString *cs, const char *p)
3562 cstr_printf(cs, "#define %s%s\n", p, &" 1"[!!strchr(p, ' ')*2]);
3565 static void putdefs(CString *cs, const char *p)
3567 while (*p)
3568 putdef(cs, p), p = strchr(p, 0) + 1;
3571 static void tcc_predefs(TCCState *s1, CString *cs, int is_asm)
3573 int a, b, c;
3575 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
3576 cstr_printf(cs, "#define __TINYC__ %d\n", a*10000 + b*100 + c);
3578 putdefs(cs, target_machine_defs);
3579 putdefs(cs, target_os_defs);
3581 #ifdef TCC_TARGET_ARM
3582 if (s1->float_abi == ARM_HARD_FLOAT)
3583 putdef(cs, "__ARM_PCS_VFP");
3584 #endif
3585 if (is_asm)
3586 putdef(cs, "__ASSEMBLER__");
3587 if (s1->output_type == TCC_OUTPUT_PREPROCESS)
3588 putdef(cs, "__TCC_PP__");
3589 if (s1->output_type == TCC_OUTPUT_MEMORY)
3590 putdef(cs, "__TCC_RUN__");
3591 #ifdef CONFIG_TCC_BACKTRACE
3592 if (s1->do_backtrace)
3593 putdef(cs, "__TCC_BACKTRACE__");
3594 #endif
3595 #ifdef CONFIG_TCC_BCHECK
3596 if (s1->do_bounds_check)
3597 putdef(cs, "__TCC_BCHECK__");
3598 #endif
3599 if (s1->char_is_unsigned)
3600 putdef(cs, "__CHAR_UNSIGNED__");
3601 if (s1->optimize > 0)
3602 putdef(cs, "__OPTIMIZE__");
3603 if (s1->option_pthread)
3604 putdef(cs, "_REENTRANT");
3605 if (s1->leading_underscore)
3606 putdef(cs, "__leading_underscore");
3607 cstr_printf(cs, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE);
3608 cstr_printf(cs, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE);
3609 if (!is_asm) {
3610 putdef(cs, "__STDC__");
3611 cstr_printf(cs, "#define __STDC_VERSION__ %dL\n", s1->cversion);
3612 cstr_cat(cs,
3613 /* load more predefs and __builtins */
3614 #if CONFIG_TCC_PREDEFS
3615 #include "tccdefs_.h" /* include as strings */
3616 #else
3617 "#include <tccdefs.h>\n" /* load at runtime */
3618 #endif
3619 , -1);
3621 cstr_printf(cs, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3624 ST_FUNC void preprocess_start(TCCState *s1, int filetype)
3626 int is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
3628 tccpp_new(s1);
3630 s1->include_stack_ptr = s1->include_stack;
3631 s1->ifdef_stack_ptr = s1->ifdef_stack;
3632 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3633 pp_expr = 0;
3634 pp_counter = 0;
3635 pp_debug_tok = pp_debug_symv = 0;
3636 pp_once++;
3637 s1->pack_stack[0] = 0;
3638 s1->pack_stack_ptr = s1->pack_stack;
3640 set_idnum('$', !is_asm && s1->dollars_in_identifiers ? IS_ID : 0);
3641 set_idnum('.', is_asm ? IS_ID : 0);
3643 if (!(filetype & AFF_TYPE_ASM)) {
3644 CString cstr;
3645 cstr_new(&cstr);
3646 tcc_predefs(s1, &cstr, is_asm);
3647 if (s1->cmdline_defs.size)
3648 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3649 if (s1->cmdline_incl.size)
3650 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3651 //printf("%s\n", (char*)cstr.data);
3652 *s1->include_stack_ptr++ = file;
3653 tcc_open_bf(s1, "<command line>", cstr.size);
3654 memcpy(file->buffer, cstr.data, cstr.size);
3655 cstr_free(&cstr);
3658 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3659 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3662 /* cleanup from error/setjmp */
3663 ST_FUNC void preprocess_end(TCCState *s1)
3665 while (macro_stack)
3666 end_macro();
3667 macro_ptr = NULL;
3668 while (file)
3669 tcc_close();
3670 tccpp_delete(s1);
3673 ST_FUNC int set_idnum(int c, int val)
3675 int prev = isidnum_table[c - CH_EOF];
3676 isidnum_table[c - CH_EOF] = val;
3677 return prev;
3680 ST_FUNC void tccpp_new(TCCState *s)
3682 int i, c;
3683 const char *p, *r;
3685 /* init isid table */
3686 for(i = CH_EOF; i<128; i++)
3687 set_idnum(i,
3688 is_space(i) ? IS_SPC
3689 : isid(i) ? IS_ID
3690 : isnum(i) ? IS_NUM
3691 : 0);
3693 for(i = 128; i<256; i++)
3694 set_idnum(i, IS_ID);
3696 /* init allocators */
3697 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3698 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3700 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3701 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3703 cstr_new(&tokcstr);
3704 cstr_new(&cstr_buf);
3705 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3706 tok_str_new(&tokstr_buf);
3707 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3709 tok_ident = TOK_IDENT;
3710 p = tcc_keywords;
3711 while (*p) {
3712 r = p;
3713 for(;;) {
3714 c = *r++;
3715 if (c == '\0')
3716 break;
3718 tok_alloc(p, r - p - 1);
3719 p = r;
3722 /* we add dummy defines for some special macros to speed up tests
3723 and to have working defined() */
3724 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3725 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3726 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3727 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3728 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3731 ST_FUNC void tccpp_delete(TCCState *s)
3733 int i, n;
3735 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3737 /* free tokens */
3738 n = tok_ident - TOK_IDENT;
3739 if (n > total_idents)
3740 total_idents = n;
3741 for(i = 0; i < n; i++)
3742 tal_free(toksym_alloc, table_ident[i]);
3743 tcc_free(table_ident);
3744 table_ident = NULL;
3746 /* free static buffers */
3747 cstr_free(&tokcstr);
3748 cstr_free(&cstr_buf);
3749 tok_str_free_str(tokstr_buf.str);
3751 /* free allocators */
3752 tal_delete(toksym_alloc);
3753 toksym_alloc = NULL;
3754 tal_delete(tokstr_alloc);
3755 tokstr_alloc = NULL;
3758 /* ------------------------------------------------------------------------- */
3759 /* tcc -E [-P[1]] [-dD} support */
3761 static void tok_print(const char *msg, const int *str)
3763 FILE *fp;
3764 int t, s = 0;
3765 CValue cval;
3767 fp = tcc_state->ppfp;
3768 fprintf(fp, "%s", msg);
3769 while (str) {
3770 TOK_GET(&t, &str, &cval);
3771 if (!t)
3772 break;
3773 fprintf(fp, &" %s"[s], get_tok_str(t, &cval)), s = 1;
3775 fprintf(fp, "\n");
3778 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3780 int d = f->line_num - f->line_ref;
3782 if (s1->dflag & 4)
3783 return;
3785 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3787 } else if (level == 0 && f->line_ref && d < 8) {
3788 while (d > 0)
3789 fputs("\n", s1->ppfp), --d;
3790 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3791 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3792 } else {
3793 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3794 level > 0 ? " 1" : level < 0 ? " 2" : "");
3796 f->line_ref = f->line_num;
3799 static void define_print(TCCState *s1, int v)
3801 FILE *fp;
3802 Sym *s;
3804 s = define_find(v);
3805 if (NULL == s || NULL == s->d)
3806 return;
3808 fp = s1->ppfp;
3809 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3810 if (s->type.t == MACRO_FUNC) {
3811 Sym *a = s->next;
3812 fprintf(fp,"(");
3813 if (a)
3814 for (;;) {
3815 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3816 if (!(a = a->next))
3817 break;
3818 fprintf(fp,",");
3820 fprintf(fp,")");
3822 tok_print("", s->d);
3825 static void pp_debug_defines(TCCState *s1)
3827 int v, t;
3828 const char *vs;
3829 FILE *fp;
3831 t = pp_debug_tok;
3832 if (t == 0)
3833 return;
3835 file->line_num--;
3836 pp_line(s1, file, 0);
3837 file->line_ref = ++file->line_num;
3839 fp = s1->ppfp;
3840 v = pp_debug_symv;
3841 vs = get_tok_str(v, NULL);
3842 if (t == TOK_DEFINE) {
3843 define_print(s1, v);
3844 } else if (t == TOK_UNDEF) {
3845 fprintf(fp, "#undef %s\n", vs);
3846 } else if (t == TOK_push_macro) {
3847 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3848 } else if (t == TOK_pop_macro) {
3849 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3851 pp_debug_tok = 0;
3854 static void pp_debug_builtins(TCCState *s1)
3856 int v;
3857 for (v = TOK_IDENT; v < tok_ident; ++v)
3858 define_print(s1, v);
3861 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3862 static int pp_need_space(int a, int b)
3864 return 'E' == a ? '+' == b || '-' == b
3865 : '+' == a ? TOK_INC == b || '+' == b
3866 : '-' == a ? TOK_DEC == b || '-' == b
3867 : a >= TOK_IDENT ? b >= TOK_IDENT
3868 : a == TOK_PPNUM ? b >= TOK_IDENT
3869 : 0;
3872 /* maybe hex like 0x1e */
3873 static int pp_check_he0xE(int t, const char *p)
3875 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3876 return 'E';
3877 return t;
3880 /* Preprocess the current file */
3881 ST_FUNC int tcc_preprocess(TCCState *s1)
3883 BufferedFile **iptr;
3884 int token_seen, spcs, level;
3885 const char *p;
3886 char white[400];
3888 parse_flags = PARSE_FLAG_PREPROCESS
3889 | (parse_flags & PARSE_FLAG_ASM_FILE)
3890 | PARSE_FLAG_LINEFEED
3891 | PARSE_FLAG_SPACES
3892 | PARSE_FLAG_ACCEPT_STRAYS
3894 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3895 capability to compile and run itself, provided all numbers are
3896 given as decimals. tcc -E -P10 will do. */
3897 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3898 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3900 if (s1->do_bench) {
3901 /* for PP benchmarks */
3902 do next(); while (tok != TOK_EOF);
3903 return 0;
3906 if (s1->dflag & 1) {
3907 pp_debug_builtins(s1);
3908 s1->dflag &= ~1;
3911 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
3912 if (file->prev)
3913 pp_line(s1, file->prev, level++);
3914 pp_line(s1, file, level);
3915 for (;;) {
3916 iptr = s1->include_stack_ptr;
3917 next();
3918 if (tok == TOK_EOF)
3919 break;
3921 level = s1->include_stack_ptr - iptr;
3922 if (level) {
3923 if (level > 0)
3924 pp_line(s1, *iptr, 0);
3925 pp_line(s1, file, level);
3927 if (s1->dflag & 7) {
3928 pp_debug_defines(s1);
3929 if (s1->dflag & 4)
3930 continue;
3933 if (is_space(tok)) {
3934 if (spcs < sizeof white - 1)
3935 white[spcs++] = tok;
3936 continue;
3937 } else if (tok == TOK_LINEFEED) {
3938 spcs = 0;
3939 if (token_seen == TOK_LINEFEED)
3940 continue;
3941 ++file->line_ref;
3942 } else if (token_seen == TOK_LINEFEED) {
3943 pp_line(s1, file, 0);
3944 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
3945 white[spcs++] = ' ';
3948 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
3949 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
3950 token_seen = pp_check_he0xE(tok, p);
3952 return 0;
3955 /* ------------------------------------------------------------------------- */