fixup! riscv: Implement large addend for global address
[tinycc.git] / tccpp.c
blobd9d2bbc31d4c049e97a3ebb88e3fc91236a85616
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;
42 ST_DATA int pp_expr;
44 /* ------------------------------------------------------------------------- */
46 static TokenSym *hash_ident[TOK_HASH_SIZE];
47 static char token_buf[STRING_MAX_SIZE + 1];
48 static CString cstr_buf;
49 static TokenString tokstr_buf;
50 static TokenString unget_buf;
51 static unsigned char isidnum_table[256 - CH_EOF];
52 static int pp_debug_tok, pp_debug_symv;
53 static int pp_counter;
54 static void tok_print(const int *str, const char *msg, ...);
55 static void next_nomacro(void);
57 static struct TinyAlloc *toksym_alloc;
58 static struct TinyAlloc *tokstr_alloc;
60 static TokenString *macro_stack;
62 static const char tcc_keywords[] =
63 #define DEF(id, str) str "\0"
64 #include "tcctok.h"
65 #undef DEF
68 /* WARNING: the content of this string encodes token numbers */
69 static const unsigned char tok_two_chars[] =
70 /* outdated -- gr
71 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
72 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
73 */{
74 '<','=', TOK_LE,
75 '>','=', TOK_GE,
76 '!','=', TOK_NE,
77 '&','&', TOK_LAND,
78 '|','|', TOK_LOR,
79 '+','+', TOK_INC,
80 '-','-', TOK_DEC,
81 '=','=', TOK_EQ,
82 '<','<', TOK_SHL,
83 '>','>', TOK_SAR,
84 '+','=', TOK_A_ADD,
85 '-','=', TOK_A_SUB,
86 '*','=', TOK_A_MUL,
87 '/','=', TOK_A_DIV,
88 '%','=', TOK_A_MOD,
89 '&','=', TOK_A_AND,
90 '^','=', TOK_A_XOR,
91 '|','=', TOK_A_OR,
92 '-','>', TOK_ARROW,
93 '.','.', TOK_TWODOTS,
94 '#','#', TOK_TWOSHARPS,
95 '#','#', TOK_PPJOIN,
99 ST_FUNC void skip(int c)
101 if (tok != c) {
102 char tmp[40];
103 pstrcpy(tmp, sizeof tmp, get_tok_str(c, &tokc));
104 tcc_error("'%s' expected (got \"%s\")", tmp, get_tok_str(tok, &tokc));
106 next();
109 ST_FUNC void expect(const char *msg)
111 tcc_error("%s expected", msg);
114 /* ------------------------------------------------------------------------- */
115 /* Custom allocator for tiny objects */
117 #define USE_TAL
119 #ifndef USE_TAL
120 #define tal_free(al, p) tcc_free(p)
121 #define tal_realloc(al, p, size) tcc_realloc(p, size)
122 #define tal_new(a,b,c)
123 #define tal_delete(a)
124 #else
125 #if !defined(MEM_DEBUG)
126 #define tal_free(al, p) tal_free_impl(al, p)
127 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
128 #define TAL_DEBUG_PARAMS
129 #else
130 #define TAL_DEBUG MEM_DEBUG
131 //#define TAL_INFO 1 /* collect and dump allocators stats */
132 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
133 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
134 #define TAL_DEBUG_PARAMS , const char *file, int line
135 #define TAL_DEBUG_FILE_LEN 40
136 #endif
138 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
139 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
140 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
141 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
142 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
143 #define CSTR_TAL_LIMIT 1024
145 typedef struct TinyAlloc {
146 unsigned limit;
147 unsigned size;
148 uint8_t *buffer;
149 uint8_t *p;
150 unsigned nb_allocs;
151 struct TinyAlloc *next, *top;
152 #ifdef TAL_INFO
153 unsigned nb_peak;
154 unsigned nb_total;
155 unsigned nb_missed;
156 uint8_t *peak_p;
157 #endif
158 } TinyAlloc;
160 typedef struct tal_header_t {
161 unsigned size;
162 #ifdef TAL_DEBUG
163 int line_num; /* negative line_num used for double free check */
164 char file_name[TAL_DEBUG_FILE_LEN + 1];
165 #endif
166 } tal_header_t;
168 /* ------------------------------------------------------------------------- */
170 static TinyAlloc *tal_new(TinyAlloc **pal, unsigned limit, unsigned size)
172 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
173 al->p = al->buffer = tcc_malloc(size);
174 al->limit = limit;
175 al->size = size;
176 if (pal) *pal = al;
177 return al;
180 static void tal_delete(TinyAlloc *al)
182 TinyAlloc *next;
184 tail_call:
185 if (!al)
186 return;
187 #ifdef TAL_INFO
188 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
189 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
190 (al->peak_p - al->buffer) * 100.0 / al->size);
191 #endif
192 #if TAL_DEBUG && TAL_DEBUG != 3 /* do not check TAL leaks with -DMEM_DEBUG=3 */
193 if (al->nb_allocs > 0) {
194 uint8_t *p;
195 fprintf(stderr, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
196 al->nb_allocs, al->limit);
197 p = al->buffer;
198 while (p < al->p) {
199 tal_header_t *header = (tal_header_t *)p;
200 if (header->line_num > 0) {
201 fprintf(stderr, "%s:%d: chunk of %d bytes leaked\n",
202 header->file_name, header->line_num, header->size);
204 p += header->size + sizeof(tal_header_t);
206 #if TAL_DEBUG == 2
207 exit(2);
208 #endif
210 #endif
211 next = al->next;
212 tcc_free(al->buffer);
213 tcc_free(al);
214 al = next;
215 goto tail_call;
218 static void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
220 if (!p)
221 return;
222 tail_call:
223 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
224 #ifdef TAL_DEBUG
225 tal_header_t *header = (((tal_header_t *)p) - 1);
226 if (header->line_num < 0) {
227 fprintf(stderr, "%s:%d: TAL_DEBUG: double frees chunk from\n",
228 file, line);
229 fprintf(stderr, "%s:%d: %d bytes\n",
230 header->file_name, (int)-header->line_num, (int)header->size);
231 } else
232 header->line_num = -header->line_num;
233 #endif
234 al->nb_allocs--;
235 if (!al->nb_allocs)
236 al->p = al->buffer;
237 } else if (al->next) {
238 al = al->next;
239 goto tail_call;
241 else
242 tcc_free(p);
245 static void *tal_realloc_impl(TinyAlloc **pal, void *p, unsigned size TAL_DEBUG_PARAMS)
247 tal_header_t *header;
248 void *ret;
249 int is_own;
250 unsigned adj_size = (size + 3) & -4;
251 TinyAlloc *al = *pal;
253 tail_call:
254 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
255 if ((!p || is_own) && size <= al->limit) {
256 if (al->p - al->buffer + adj_size + sizeof(tal_header_t) < al->size) {
257 header = (tal_header_t *)al->p;
258 header->size = adj_size;
259 #ifdef TAL_DEBUG
260 { int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
261 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
262 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
263 header->line_num = line; }
264 #endif
265 ret = al->p + sizeof(tal_header_t);
266 al->p += adj_size + sizeof(tal_header_t);
267 if (is_own) {
268 header = (((tal_header_t *)p) - 1);
269 if (p) memcpy(ret, p, header->size);
270 #ifdef TAL_DEBUG
271 header->line_num = -header->line_num;
272 #endif
273 } else {
274 al->nb_allocs++;
276 #ifdef TAL_INFO
277 if (al->nb_peak < al->nb_allocs)
278 al->nb_peak = al->nb_allocs;
279 if (al->peak_p < al->p)
280 al->peak_p = al->p;
281 al->nb_total++;
282 #endif
283 return ret;
284 } else if (is_own) {
285 al->nb_allocs--;
286 ret = tal_realloc(*pal, 0, size);
287 header = (((tal_header_t *)p) - 1);
288 if (p) memcpy(ret, p, header->size);
289 #ifdef TAL_DEBUG
290 header->line_num = -header->line_num;
291 #endif
292 return ret;
294 if (al->next) {
295 al = al->next;
296 } else {
297 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
299 al = tal_new(pal, next->limit, next->size * 2);
300 al->next = next;
301 bottom->top = al;
303 goto tail_call;
305 if (is_own) {
306 al->nb_allocs--;
307 ret = tcc_malloc(size);
308 header = (((tal_header_t *)p) - 1);
309 if (p) memcpy(ret, p, header->size);
310 #ifdef TAL_DEBUG
311 header->line_num = -header->line_num;
312 #endif
313 } else if (al->next) {
314 al = al->next;
315 goto tail_call;
316 } else
317 ret = tcc_realloc(p, size);
318 #ifdef TAL_INFO
319 al->nb_missed++;
320 #endif
321 return ret;
324 #endif /* USE_TAL */
326 /* ------------------------------------------------------------------------- */
327 /* CString handling */
328 static void cstr_realloc(CString *cstr, int new_size)
330 int size;
332 size = cstr->size_allocated;
333 if (size < 8)
334 size = 8; /* no need to allocate a too small first string */
335 while (size < new_size)
336 size = size * 2;
337 cstr->data = tcc_realloc(cstr->data, size);
338 cstr->size_allocated = size;
341 /* add a byte */
342 ST_INLN void cstr_ccat(CString *cstr, int ch)
344 int size;
345 size = cstr->size + 1;
346 if (size > cstr->size_allocated)
347 cstr_realloc(cstr, size);
348 ((unsigned char *)cstr->data)[size - 1] = ch;
349 cstr->size = size;
352 ST_INLN char *unicode_to_utf8 (char *b, uint32_t Uc)
354 if (Uc<0x80) *b++=Uc;
355 else if (Uc<0x800) *b++=192+Uc/64, *b++=128+Uc%64;
356 else if (Uc-0xd800u<0x800) goto error;
357 else if (Uc<0x10000) *b++=224+Uc/4096, *b++=128+Uc/64%64, *b++=128+Uc%64;
358 else if (Uc<0x110000) *b++=240+Uc/262144, *b++=128+Uc/4096%64, *b++=128+Uc/64%64, *b++=128+Uc%64;
359 else error: tcc_error("0x%x is not a valid universal character", Uc);
360 return b;
363 /* add a unicode character expanded into utf8 */
364 ST_INLN void cstr_u8cat(CString *cstr, int ch)
366 char buf[4], *e;
367 e = unicode_to_utf8(buf, (uint32_t)ch);
368 cstr_cat(cstr, buf, e - buf);
371 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
373 int size;
374 if (len <= 0)
375 len = strlen(str) + 1 + len;
376 size = cstr->size + len;
377 if (size > cstr->size_allocated)
378 cstr_realloc(cstr, size);
379 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
380 cstr->size = size;
383 /* add a wide char */
384 ST_FUNC void cstr_wccat(CString *cstr, int ch)
386 int size;
387 size = cstr->size + sizeof(nwchar_t);
388 if (size > cstr->size_allocated)
389 cstr_realloc(cstr, size);
390 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
391 cstr->size = size;
394 ST_FUNC void cstr_new(CString *cstr)
396 memset(cstr, 0, sizeof(CString));
399 /* free string and reset it to NULL */
400 ST_FUNC void cstr_free(CString *cstr)
402 tcc_free(cstr->data);
405 /* reset string to empty */
406 ST_FUNC void cstr_reset(CString *cstr)
408 cstr->size = 0;
411 ST_FUNC int cstr_vprintf(CString *cstr, const char *fmt, va_list ap)
413 va_list v;
414 int len, size = 80;
415 for (;;) {
416 size += cstr->size;
417 if (size > cstr->size_allocated)
418 cstr_realloc(cstr, size);
419 size = cstr->size_allocated - cstr->size;
420 va_copy(v, ap);
421 len = vsnprintf((char*)cstr->data + cstr->size, size, fmt, v);
422 va_end(v);
423 if (len >= 0 && len < size)
424 break;
425 size *= 2;
427 cstr->size += len;
428 return len;
431 ST_FUNC int cstr_printf(CString *cstr, const char *fmt, ...)
433 va_list ap; int len;
434 va_start(ap, fmt);
435 len = cstr_vprintf(cstr, fmt, ap);
436 va_end(ap);
437 return len;
440 /* XXX: unicode ? */
441 static void add_char(CString *cstr, int c)
443 if (c == '\'' || c == '\"' || c == '\\') {
444 /* XXX: could be more precise if char or string */
445 cstr_ccat(cstr, '\\');
447 if (c >= 32 && c <= 126) {
448 cstr_ccat(cstr, c);
449 } else {
450 cstr_ccat(cstr, '\\');
451 if (c == '\n') {
452 cstr_ccat(cstr, 'n');
453 } else {
454 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
455 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
456 cstr_ccat(cstr, '0' + (c & 7));
461 /* ------------------------------------------------------------------------- */
462 /* allocate a new token */
463 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
465 TokenSym *ts, **ptable;
466 int i;
468 if (tok_ident >= SYM_FIRST_ANOM)
469 tcc_error("memory full (symbols)");
471 /* expand token table if needed */
472 i = tok_ident - TOK_IDENT;
473 if ((i % TOK_ALLOC_INCR) == 0) {
474 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
475 table_ident = ptable;
478 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
479 table_ident[i] = ts;
480 ts->tok = tok_ident++;
481 ts->sym_define = NULL;
482 ts->sym_label = NULL;
483 ts->sym_struct = NULL;
484 ts->sym_identifier = NULL;
485 ts->len = len;
486 ts->hash_next = NULL;
487 memcpy(ts->str, str, len);
488 ts->str[len] = '\0';
489 *pts = ts;
490 return ts;
493 #define TOK_HASH_INIT 1
494 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
497 /* find a token and add it if not found */
498 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
500 TokenSym *ts, **pts;
501 int i;
502 unsigned int h;
504 h = TOK_HASH_INIT;
505 for(i=0;i<len;i++)
506 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
507 h &= (TOK_HASH_SIZE - 1);
509 pts = &hash_ident[h];
510 for(;;) {
511 ts = *pts;
512 if (!ts)
513 break;
514 if (ts->len == len && !memcmp(ts->str, str, len))
515 return ts;
516 pts = &(ts->hash_next);
518 return tok_alloc_new(pts, str, len);
521 ST_FUNC int tok_alloc_const(const char *str)
523 return tok_alloc(str, strlen(str))->tok;
527 /* XXX: buffer overflow */
528 /* XXX: float tokens */
529 ST_FUNC const char *get_tok_str(int v, CValue *cv)
531 char *p;
532 int i, len;
534 cstr_reset(&cstr_buf);
535 p = cstr_buf.data;
537 switch(v) {
538 case TOK_CINT:
539 case TOK_CUINT:
540 case TOK_CLONG:
541 case TOK_CULONG:
542 case TOK_CLLONG:
543 case TOK_CULLONG:
544 /* XXX: not quite exact, but only useful for testing */
545 #ifdef _WIN32
546 sprintf(p, "%u", (unsigned)cv->i);
547 #else
548 sprintf(p, "%llu", (unsigned long long)cv->i);
549 #endif
550 break;
551 case TOK_LCHAR:
552 cstr_ccat(&cstr_buf, 'L');
553 case TOK_CCHAR:
554 cstr_ccat(&cstr_buf, '\'');
555 add_char(&cstr_buf, cv->i);
556 cstr_ccat(&cstr_buf, '\'');
557 cstr_ccat(&cstr_buf, '\0');
558 break;
559 case TOK_PPNUM:
560 case TOK_PPSTR:
561 return (char*)cv->str.data;
562 case TOK_LSTR:
563 cstr_ccat(&cstr_buf, 'L');
564 case TOK_STR:
565 cstr_ccat(&cstr_buf, '\"');
566 if (v == TOK_STR) {
567 len = cv->str.size - 1;
568 for(i=0;i<len;i++)
569 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
570 } else {
571 len = (cv->str.size / sizeof(nwchar_t)) - 1;
572 for(i=0;i<len;i++)
573 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
575 cstr_ccat(&cstr_buf, '\"');
576 cstr_ccat(&cstr_buf, '\0');
577 break;
579 case TOK_CFLOAT:
580 return strcpy(p, "<float>");
581 case TOK_CDOUBLE:
582 return strcpy(p, "<double>");
583 case TOK_CLDOUBLE:
584 return strcpy(p, "<long double>");
585 case TOK_LINENUM:
586 return strcpy(p, "<linenumber>");
588 /* above tokens have value, the ones below don't */
589 case TOK_LT:
590 v = '<';
591 goto addv;
592 case TOK_GT:
593 v = '>';
594 goto addv;
595 case TOK_DOTS:
596 return strcpy(p, "...");
597 case TOK_A_SHL:
598 return strcpy(p, "<<=");
599 case TOK_A_SAR:
600 return strcpy(p, ">>=");
601 case TOK_EOF:
602 return strcpy(p, "<eof>");
603 case 0: /* anonymous nameless symbols */
604 return strcpy(p, "<no name>");
605 default:
606 v &= ~(SYM_FIELD | SYM_STRUCT);
607 if (v < TOK_IDENT) {
608 /* search in two bytes table */
609 const unsigned char *q = tok_two_chars;
610 while (*q) {
611 if (q[2] == v) {
612 *p++ = q[0];
613 *p++ = q[1];
614 *p = '\0';
615 return cstr_buf.data;
617 q += 3;
619 if (v >= 127 || (v < 32 && !is_space(v) && v != '\n')) {
620 sprintf(p, "<\\x%02x>", v);
621 break;
623 addv:
624 *p++ = v;
625 *p = '\0';
626 } else if (v < tok_ident) {
627 return table_ident[v - TOK_IDENT]->str;
628 } else if (v >= SYM_FIRST_ANOM) {
629 /* special name for anonymous symbol */
630 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
631 } else {
632 /* should never happen */
633 return NULL;
635 break;
637 return cstr_buf.data;
640 /* return the current character, handling end of block if necessary
641 (but not stray) */
642 static int handle_eob(void)
644 BufferedFile *bf = file;
645 int len;
647 /* only tries to read if really end of buffer */
648 if (bf->buf_ptr >= bf->buf_end) {
649 if (bf->fd >= 0) {
650 #if defined(PARSE_DEBUG)
651 len = 1;
652 #else
653 len = IO_BUF_SIZE;
654 #endif
655 len = read(bf->fd, bf->buffer, len);
656 if (len < 0)
657 len = 0;
658 } else {
659 len = 0;
661 total_bytes += len;
662 bf->buf_ptr = bf->buffer;
663 bf->buf_end = bf->buffer + len;
664 *bf->buf_end = CH_EOB;
666 if (bf->buf_ptr < bf->buf_end) {
667 return bf->buf_ptr[0];
668 } else {
669 bf->buf_ptr = bf->buf_end;
670 return CH_EOF;
674 /* read next char from current input file and handle end of input buffer */
675 static int next_c(void)
677 int ch = *++file->buf_ptr;
678 /* end of buffer/file handling */
679 if (ch == CH_EOB && file->buf_ptr >= file->buf_end)
680 ch = handle_eob();
681 return ch;
684 /* input with '\[\r]\n' handling. */
685 static int handle_stray_noerror(int err)
687 int ch;
688 while ((ch = next_c()) == '\\') {
689 ch = next_c();
690 if (ch == '\n') {
691 newl:
692 file->line_num++;
693 } else {
694 if (ch == '\r') {
695 ch = next_c();
696 if (ch == '\n')
697 goto newl;
698 *--file->buf_ptr = '\r';
700 if (err)
701 tcc_error("stray '\\' in program");
702 /* may take advantage of 'BufferedFile.unget[4}' */
703 return *--file->buf_ptr = '\\';
706 return ch;
709 #define ninp() handle_stray_noerror(0)
711 /* handle '\\' in strings, comments and skipped regions */
712 static int handle_bs(uint8_t **p)
714 int c;
715 file->buf_ptr = *p - 1;
716 c = ninp();
717 *p = file->buf_ptr;
718 return c;
721 /* skip the stray and handle the \\n case. Output an error if
722 incorrect char after the stray */
723 static int handle_stray(uint8_t **p)
725 int c;
726 file->buf_ptr = *p - 1;
727 c = handle_stray_noerror(!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS));
728 *p = file->buf_ptr;
729 return c;
732 /* handle the complicated stray case */
733 #define PEEKC(c, p)\
735 c = *++p;\
736 if (c == '\\')\
737 c = handle_stray(&p); \
740 static int skip_spaces(void)
742 int ch;
743 --file->buf_ptr;
744 do {
745 ch = ninp();
746 } while (isidnum_table[ch - CH_EOF] & IS_SPC);
747 return ch;
750 /* single line C++ comments */
751 static uint8_t *parse_line_comment(uint8_t *p)
753 int c;
754 for(;;) {
755 for (;;) {
756 c = *++p;
757 redo:
758 if (c == '\n' || c == '\\')
759 break;
760 c = *++p;
761 if (c == '\n' || c == '\\')
762 break;
764 if (c == '\n')
765 break;
766 c = handle_bs(&p);
767 if (c == CH_EOF)
768 break;
769 if (c != '\\')
770 goto redo;
772 return p;
775 /* C comments */
776 static uint8_t *parse_comment(uint8_t *p)
778 int c;
779 for(;;) {
780 /* fast skip loop */
781 for(;;) {
782 c = *++p;
783 redo:
784 if (c == '\n' || c == '*' || c == '\\')
785 break;
786 c = *++p;
787 if (c == '\n' || c == '*' || c == '\\')
788 break;
790 /* now we can handle all the cases */
791 if (c == '\n') {
792 file->line_num++;
793 } else if (c == '*') {
794 do {
795 c = *++p;
796 } while (c == '*');
797 if (c == '\\')
798 c = handle_bs(&p);
799 if (c == '/')
800 break;
801 goto check_eof;
802 } else {
803 c = handle_bs(&p);
804 check_eof:
805 if (c == CH_EOF)
806 tcc_error("unexpected end of file in comment");
807 if (c != '\\')
808 goto redo;
811 return p + 1;
814 /* parse a string without interpreting escapes */
815 static uint8_t *parse_pp_string(uint8_t *p, int sep, CString *str)
817 int c;
818 for(;;) {
819 c = *++p;
820 redo:
821 if (c == sep) {
822 break;
823 } else if (c == '\\') {
824 c = handle_bs(&p);
825 if (c == CH_EOF) {
826 unterminated_string:
827 /* XXX: indicate line number of start of string */
828 tok_flags &= ~TOK_FLAG_BOL;
829 tcc_error("missing terminating %c character", sep);
830 } else if (c == '\\') {
831 if (str)
832 cstr_ccat(str, c);
833 c = *++p;
834 /* add char after '\\' unconditionally */
835 if (c == '\\') {
836 c = handle_bs(&p);
837 if (c == CH_EOF)
838 goto unterminated_string;
840 goto add_char;
841 } else {
842 goto redo;
844 } else if (c == '\n') {
845 add_lf:
846 if (ACCEPT_LF_IN_STRINGS) {
847 file->line_num++;
848 goto add_char;
849 } else if (str) { /* not skipping */
850 goto unterminated_string;
851 } else {
852 //tcc_warning("missing terminating %c character", sep);
853 return p;
855 } else if (c == '\r') {
856 c = *++p;
857 if (c == '\\')
858 c = handle_bs(&p);
859 if (c == '\n')
860 goto add_lf;
861 if (c == CH_EOF)
862 goto unterminated_string;
863 if (str)
864 cstr_ccat(str, '\r');
865 goto redo;
866 } else {
867 add_char:
868 if (str)
869 cstr_ccat(str, c);
872 p++;
873 return p;
876 /* skip block of text until #else, #elif or #endif. skip also pairs of
877 #if/#endif */
878 static void preprocess_skip(void)
880 int a, start_of_line, c, in_warn_or_error;
881 uint8_t *p;
883 p = file->buf_ptr;
884 a = 0;
885 redo_start:
886 start_of_line = 1;
887 in_warn_or_error = 0;
888 for(;;) {
889 redo_no_start:
890 c = *p;
891 switch(c) {
892 case ' ':
893 case '\t':
894 case '\f':
895 case '\v':
896 case '\r':
897 p++;
898 goto redo_no_start;
899 case '\n':
900 file->line_num++;
901 p++;
902 goto redo_start;
903 case '\\':
904 c = handle_bs(&p);
905 if (c == CH_EOF)
906 expect("#endif");
907 if (c == '\\')
908 ++p;
909 goto redo_no_start;
910 /* skip strings */
911 case '\"':
912 case '\'':
913 if (in_warn_or_error)
914 goto _default;
915 tok_flags &= ~TOK_FLAG_BOL;
916 p = parse_pp_string(p, c, NULL);
917 break;
918 /* skip comments */
919 case '/':
920 if (in_warn_or_error)
921 goto _default;
922 ++p;
923 c = handle_bs(&p);
924 if (c == '*') {
925 p = parse_comment(p);
926 } else if (c == '/') {
927 p = parse_line_comment(p);
929 break;
930 case '#':
931 p++;
932 if (start_of_line) {
933 file->buf_ptr = p;
934 next_nomacro();
935 p = file->buf_ptr;
936 if (a == 0 &&
937 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
938 goto the_end;
939 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
940 a++;
941 else if (tok == TOK_ENDIF)
942 a--;
943 else if( tok == TOK_ERROR || tok == TOK_WARNING)
944 in_warn_or_error = 1;
945 else if (tok == TOK_LINEFEED)
946 goto redo_start;
947 else if (parse_flags & PARSE_FLAG_ASM_FILE)
948 p = parse_line_comment(p - 1);
950 #if !defined(TCC_TARGET_ARM)
951 else if (parse_flags & PARSE_FLAG_ASM_FILE)
952 p = parse_line_comment(p - 1);
953 #else
954 /* ARM assembly uses '#' for constants */
955 #endif
956 break;
957 _default:
958 default:
959 p++;
960 break;
962 start_of_line = 0;
964 the_end: ;
965 file->buf_ptr = p;
968 #if 0
969 /* return the number of additional 'ints' necessary to store the
970 token */
971 static inline int tok_size(const int *p)
973 switch(*p) {
974 /* 4 bytes */
975 case TOK_CINT:
976 case TOK_CUINT:
977 case TOK_CCHAR:
978 case TOK_LCHAR:
979 case TOK_CFLOAT:
980 case TOK_LINENUM:
981 return 1 + 1;
982 case TOK_STR:
983 case TOK_LSTR:
984 case TOK_PPNUM:
985 case TOK_PPSTR:
986 return 1 + 1 + (p[1] + 3) / 4;
987 case TOK_CLONG:
988 case TOK_CULONG:
989 return 1 + LONG_SIZE / 4;
990 case TOK_CDOUBLE:
991 case TOK_CLLONG:
992 case TOK_CULLONG:
993 return 1 + 2;
994 case TOK_CLDOUBLE:
995 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
996 return 1 + 8 / 4;
997 #else
998 return 1 + LDOUBLE_SIZE / 4;
999 #endif
1000 default:
1001 return 1 + 0;
1004 #endif
1006 /* token string handling */
1007 ST_INLN void tok_str_new(TokenString *s)
1009 s->str = NULL;
1010 s->len = s->need_spc = 0;
1011 s->allocated_len = 0;
1012 s->last_line_num = -1;
1015 ST_FUNC TokenString *tok_str_alloc(void)
1017 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1018 tok_str_new(str);
1019 return str;
1022 ST_FUNC void tok_str_free_str(int *str)
1024 tal_free(tokstr_alloc, str);
1027 ST_FUNC void tok_str_free(TokenString *str)
1029 tok_str_free_str(str->str);
1030 tal_free(tokstr_alloc, str);
1033 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1035 int *str, size;
1037 size = s->allocated_len;
1038 if (size < 16)
1039 size = 16;
1040 while (size < new_size)
1041 size = size * 2;
1042 if (size > s->allocated_len) {
1043 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1044 s->allocated_len = size;
1045 s->str = str;
1047 return s->str;
1050 ST_FUNC void tok_str_add(TokenString *s, int t)
1052 int len, *str;
1054 len = s->len;
1055 str = s->str;
1056 if (len >= s->allocated_len)
1057 str = tok_str_realloc(s, len + 1);
1058 str[len++] = t;
1059 s->len = len;
1062 ST_FUNC void begin_macro(TokenString *str, int alloc)
1064 str->alloc = alloc;
1065 str->prev = macro_stack;
1066 str->prev_ptr = macro_ptr;
1067 str->save_line_num = file->line_num;
1068 macro_ptr = str->str;
1069 macro_stack = str;
1072 ST_FUNC void end_macro(void)
1074 TokenString *str = macro_stack;
1075 macro_stack = str->prev;
1076 macro_ptr = str->prev_ptr;
1077 file->line_num = str->save_line_num;
1078 if (str->alloc == 0) {
1079 /* matters if str not alloced, may be tokstr_buf */
1080 str->len = str->need_spc = 0;
1081 } else {
1082 if (str->alloc == 2)
1083 str->str = NULL; /* don't free */
1084 tok_str_free(str);
1088 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1090 int len, *str;
1092 len = s->len;
1093 str = s->str;
1095 /* allocate space for worst case */
1096 if (len + TOK_MAX_SIZE >= s->allocated_len)
1097 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1098 str[len++] = t;
1099 switch(t) {
1100 case TOK_CINT:
1101 case TOK_CUINT:
1102 case TOK_CCHAR:
1103 case TOK_LCHAR:
1104 case TOK_CFLOAT:
1105 case TOK_LINENUM:
1106 #if LONG_SIZE == 4
1107 case TOK_CLONG:
1108 case TOK_CULONG:
1109 #endif
1110 str[len++] = cv->tab[0];
1111 break;
1112 case TOK_PPNUM:
1113 case TOK_PPSTR:
1114 case TOK_STR:
1115 case TOK_LSTR:
1117 /* Insert the string into the int array. */
1118 size_t nb_words =
1119 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1120 if (len + nb_words >= s->allocated_len)
1121 str = tok_str_realloc(s, len + nb_words + 1);
1122 str[len] = cv->str.size;
1123 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1124 len += nb_words;
1126 break;
1127 case TOK_CDOUBLE:
1128 case TOK_CLLONG:
1129 case TOK_CULLONG:
1130 #if LONG_SIZE == 8
1131 case TOK_CLONG:
1132 case TOK_CULONG:
1133 #endif
1134 str[len++] = cv->tab[0];
1135 str[len++] = cv->tab[1];
1136 break;
1137 case TOK_CLDOUBLE:
1138 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1139 str[len++] = cv->tab[0];
1140 str[len++] = cv->tab[1];
1141 #elif LDOUBLE_SIZE == 12
1142 str[len++] = cv->tab[0];
1143 str[len++] = cv->tab[1];
1144 str[len++] = cv->tab[2];
1145 #elif LDOUBLE_SIZE == 16
1146 str[len++] = cv->tab[0];
1147 str[len++] = cv->tab[1];
1148 str[len++] = cv->tab[2];
1149 str[len++] = cv->tab[3];
1150 #else
1151 #error add long double size support
1152 #endif
1153 break;
1154 default:
1155 break;
1157 s->len = len;
1160 /* add the current parse token in token string 's' */
1161 ST_FUNC void tok_str_add_tok(TokenString *s)
1163 CValue cval;
1165 /* save line number info */
1166 if (file->line_num != s->last_line_num) {
1167 s->last_line_num = file->line_num;
1168 cval.i = s->last_line_num;
1169 tok_str_add2(s, TOK_LINENUM, &cval);
1171 tok_str_add2(s, tok, &tokc);
1174 /* like tok_str_add2(), add a space if needed */
1175 static void tok_str_add2_spc(TokenString *s, int t, CValue *cv)
1177 if (s->need_spc == 3)
1178 tok_str_add(s, ' ');
1179 s->need_spc = 2;
1180 tok_str_add2(s, t, cv);
1183 /* get a token from an integer array and increment pointer. */
1184 static inline void tok_get(int *t, const int **pp, CValue *cv)
1186 const int *p = *pp;
1187 int n, *tab;
1189 tab = cv->tab;
1190 switch(*t = *p++) {
1191 #if LONG_SIZE == 4
1192 case TOK_CLONG:
1193 #endif
1194 case TOK_CINT:
1195 case TOK_CCHAR:
1196 case TOK_LCHAR:
1197 case TOK_LINENUM:
1198 cv->i = *p++;
1199 break;
1200 #if LONG_SIZE == 4
1201 case TOK_CULONG:
1202 #endif
1203 case TOK_CUINT:
1204 cv->i = (unsigned)*p++;
1205 break;
1206 case TOK_CFLOAT:
1207 tab[0] = *p++;
1208 break;
1209 case TOK_STR:
1210 case TOK_LSTR:
1211 case TOK_PPNUM:
1212 case TOK_PPSTR:
1213 cv->str.size = *p++;
1214 cv->str.data = p;
1215 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1216 break;
1217 case TOK_CDOUBLE:
1218 case TOK_CLLONG:
1219 case TOK_CULLONG:
1220 #if LONG_SIZE == 8
1221 case TOK_CLONG:
1222 case TOK_CULONG:
1223 #endif
1224 n = 2;
1225 goto copy;
1226 case TOK_CLDOUBLE:
1227 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1228 n = 2;
1229 #elif LDOUBLE_SIZE == 12
1230 n = 3;
1231 #elif LDOUBLE_SIZE == 16
1232 n = 4;
1233 #else
1234 # error add long double size support
1235 #endif
1236 copy:
1238 *tab++ = *p++;
1239 while (--n);
1240 break;
1241 default:
1242 break;
1244 *pp = p;
1247 #if 0
1248 # define TOK_GET(t,p,c) tok_get(t,p,c)
1249 #else
1250 # define TOK_GET(t,p,c) do { \
1251 int _t = **(p); \
1252 if (TOK_HAS_VALUE(_t)) \
1253 tok_get(t, p, c); \
1254 else \
1255 *(t) = _t, ++*(p); \
1256 } while (0)
1257 #endif
1259 static int macro_is_equal(const int *a, const int *b)
1261 CValue cv;
1262 int t;
1264 if (!a || !b)
1265 return 1;
1267 while (*a && *b) {
1268 cstr_reset(&tokcstr);
1269 TOK_GET(&t, &a, &cv);
1270 cstr_cat(&tokcstr, get_tok_str(t, &cv), 0);
1271 TOK_GET(&t, &b, &cv);
1272 if (strcmp(tokcstr.data, get_tok_str(t, &cv)))
1273 return 0;
1275 return !(*a || *b);
1278 /* defines handling */
1279 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1281 Sym *s, *o;
1283 o = define_find(v);
1284 s = sym_push2(&define_stack, v, macro_type, 0);
1285 s->d = str;
1286 s->next = first_arg;
1287 table_ident[v - TOK_IDENT]->sym_define = s;
1289 if (o && !macro_is_equal(o->d, s->d))
1290 tcc_warning("%s redefined", get_tok_str(v, NULL));
1293 /* undefined a define symbol. Its name is just set to zero */
1294 ST_FUNC void define_undef(Sym *s)
1296 int v = s->v;
1297 if (v >= TOK_IDENT && v < tok_ident)
1298 table_ident[v - TOK_IDENT]->sym_define = NULL;
1301 ST_INLN Sym *define_find(int v)
1303 v -= TOK_IDENT;
1304 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1305 return NULL;
1306 return table_ident[v]->sym_define;
1309 /* free define stack until top reaches 'b' */
1310 ST_FUNC void free_defines(Sym *b)
1312 while (define_stack != b) {
1313 Sym *top = define_stack;
1314 define_stack = top->prev;
1315 tok_str_free_str(top->d);
1316 define_undef(top);
1317 sym_free(top);
1321 /* fake the nth "#if defined test_..." for tcc -dt -run */
1322 static void maybe_run_test(TCCState *s)
1324 const char *p;
1325 if (s->include_stack_ptr != s->include_stack)
1326 return;
1327 p = get_tok_str(tok, NULL);
1328 if (0 != memcmp(p, "test_", 5))
1329 return;
1330 if (0 != --s->run_test)
1331 return;
1332 fprintf(s->ppfp, &"\n[%s]\n"[!(s->dflag & 32)], p), fflush(s->ppfp);
1333 define_push(tok, MACRO_OBJ, NULL, NULL);
1336 static CachedInclude *
1337 search_cached_include(TCCState *s1, const char *filename, int add);
1339 static int parse_include(TCCState *s1, int do_next, int test)
1341 int c, i;
1342 char name[1024], buf[1024], *p;
1343 CachedInclude *e;
1345 c = skip_spaces();
1346 if (c == '<' || c == '\"') {
1347 cstr_reset(&tokcstr);
1348 file->buf_ptr = parse_pp_string(file->buf_ptr, c == '<' ? '>' : c, &tokcstr);
1349 i = tokcstr.size;
1350 pstrncpy(name, tokcstr.data, i >= sizeof name ? sizeof name - 1 : i);
1351 next_nomacro();
1352 } else {
1353 /* computed #include : concatenate tokens until result is one of
1354 the two accepted forms. Don't convert pp-tokens to tokens here. */
1355 parse_flags = PARSE_FLAG_PREPROCESS
1356 | PARSE_FLAG_LINEFEED
1357 | (parse_flags & PARSE_FLAG_ASM_FILE);
1358 name[0] = 0;
1359 for (;;) {
1360 next();
1361 p = name, i = strlen(p) - 1;
1362 if (i > 0
1363 && ((p[0] == '"' && p[i] == '"')
1364 || (p[0] == '<' && p[i] == '>')))
1365 break;
1366 if (tok == TOK_LINEFEED)
1367 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1368 pstrcat(name, sizeof name, get_tok_str(tok, &tokc));
1370 c = p[0];
1371 /* remove '<>|""' */
1372 memmove(p, p + 1, i - 1), p[i - 1] = 0;
1375 i = do_next ? file->include_next_index : -1;
1376 for (;;) {
1377 ++i;
1378 if (i == 0) {
1379 /* check absolute include path */
1380 if (!IS_ABSPATH(name))
1381 continue;
1382 buf[0] = '\0';
1383 } else if (i == 1) {
1384 /* search in file's dir if "header.h" */
1385 if (c != '\"')
1386 continue;
1387 p = file->true_filename;
1388 pstrncpy(buf, p, tcc_basename(p) - p);
1389 } else {
1390 int j = i - 2, k = j - s1->nb_include_paths;
1391 if (k < 0)
1392 p = s1->include_paths[j];
1393 else if (k < s1->nb_sysinclude_paths)
1394 p = s1->sysinclude_paths[k];
1395 else if (test)
1396 return 0;
1397 else
1398 tcc_error("include file '%s' not found", name);
1399 pstrcpy(buf, sizeof buf, p);
1400 pstrcat(buf, sizeof buf, "/");
1402 pstrcat(buf, sizeof buf, name);
1403 e = search_cached_include(s1, buf, 0);
1404 if (e && (define_find(e->ifndef_macro) || e->once)) {
1405 /* no need to parse the include because the 'ifndef macro'
1406 is defined (or had #pragma once) */
1407 #ifdef INC_DEBUG
1408 printf("%s: skipping cached %s\n", file->filename, buf);
1409 #endif
1410 return 1;
1412 if (tcc_open(s1, buf) >= 0)
1413 break;
1416 if (test) {
1417 tcc_close();
1418 } else {
1419 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1420 tcc_error("#include recursion too deep");
1421 /* push previous file on stack */
1422 *s1->include_stack_ptr++ = file->prev;
1423 file->include_next_index = i;
1424 #ifdef INC_DEBUG
1425 printf("%s: including %s\n", file->prev->filename, file->filename);
1426 #endif
1427 /* update target deps */
1428 if (s1->gen_deps) {
1429 BufferedFile *bf = file;
1430 while (i == 1 && (bf = bf->prev))
1431 i = bf->include_next_index;
1432 /* skip system include files */
1433 if (s1->include_sys_deps || i - 2 < s1->nb_include_paths)
1434 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1435 tcc_strdup(buf));
1437 /* add include file debug info */
1438 tcc_debug_bincl(s1);
1440 return 1;
1443 /* eval an expression for #if/#elif */
1444 static int expr_preprocess(TCCState *s1)
1446 int c, t;
1447 int t0 = tok;
1448 TokenString *str;
1450 str = tok_str_alloc();
1451 pp_expr = 1;
1452 while (1) {
1453 next(); /* do macro subst */
1454 t = tok;
1455 if (tok < TOK_IDENT) {
1456 if (tok == TOK_LINEFEED || tok == TOK_EOF)
1457 break;
1458 if (tok >= TOK_STR && tok <= TOK_CLDOUBLE)
1459 tcc_error("invalid constant in preprocessor expression");
1461 } else if (tok == TOK_DEFINED) {
1462 parse_flags &= ~PARSE_FLAG_PREPROCESS; /* no macro subst */
1463 next();
1464 t = tok;
1465 if (t == '(')
1466 next();
1467 parse_flags |= PARSE_FLAG_PREPROCESS;
1468 if (tok < TOK_IDENT)
1469 expect("identifier after 'defined'");
1470 if (s1->run_test)
1471 maybe_run_test(s1);
1472 c = 0;
1473 if (define_find(tok)
1474 || tok == TOK___HAS_INCLUDE
1475 || tok == TOK___HAS_INCLUDE_NEXT)
1476 c = 1;
1477 if (t == '(') {
1478 next();
1479 if (tok != ')')
1480 expect("')'");
1482 tok = TOK_CINT;
1483 tokc.i = c;
1484 } else if (tok == TOK___HAS_INCLUDE ||
1485 tok == TOK___HAS_INCLUDE_NEXT) {
1486 t = tok;
1487 next();
1488 if (tok != '(')
1489 expect("'('");
1490 c = parse_include(s1, t - TOK___HAS_INCLUDE, 1);
1491 if (tok != ')')
1492 expect("')'");
1493 tok = TOK_CINT;
1494 tokc.i = c;
1495 } else {
1496 /* if undefined macro, replace with zero */
1497 tok = TOK_CINT;
1498 tokc.i = 0;
1500 tok_str_add_tok(str);
1502 if (0 == str->len)
1503 tcc_error("#%s with no expression", get_tok_str(t0, 0));
1504 tok_str_add(str, TOK_EOF); /* simulate end of file */
1505 pp_expr = t0; /* redirect pre-processor expression error messages */
1506 t = tok;
1507 /* now evaluate C constant expression */
1508 begin_macro(str, 1);
1509 next();
1510 c = expr_const();
1511 if (tok != TOK_EOF)
1512 tcc_error("...");
1513 pp_expr = 0;
1514 end_macro();
1515 tok = t; /* restore LF or EOF */
1516 return c != 0;
1519 ST_FUNC void pp_error(CString *cs)
1521 cstr_printf(cs, "bad preprocessor expression: #%s", get_tok_str(pp_expr, 0));
1522 macro_ptr = macro_stack->str;
1523 while (next(), tok != TOK_EOF)
1524 cstr_printf(cs, " %s", get_tok_str(tok, &tokc));
1527 /* parse after #define */
1528 ST_FUNC void parse_define(void)
1530 Sym *s, *first, **ps;
1531 int v, t, varg, is_vaargs, t0;
1532 int saved_parse_flags = parse_flags;
1533 TokenString str;
1535 v = tok;
1536 if (v < TOK_IDENT || v == TOK_DEFINED)
1537 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1538 first = NULL;
1539 t = MACRO_OBJ;
1540 /* We have to parse the whole define as if not in asm mode, in particular
1541 no line comment with '#' must be ignored. Also for function
1542 macros the argument list must be parsed without '.' being an ID
1543 character. */
1544 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1545 /* '(' must be just after macro definition for MACRO_FUNC */
1546 next_nomacro();
1547 parse_flags &= ~PARSE_FLAG_SPACES;
1548 is_vaargs = 0;
1549 if (tok == '(') {
1550 int dotid = set_idnum('.', 0);
1551 next_nomacro();
1552 ps = &first;
1553 if (tok != ')') for (;;) {
1554 varg = tok;
1555 next_nomacro();
1556 is_vaargs = 0;
1557 if (varg == TOK_DOTS) {
1558 varg = TOK___VA_ARGS__;
1559 is_vaargs = 1;
1560 } else if (tok == TOK_DOTS && gnu_ext) {
1561 is_vaargs = 1;
1562 next_nomacro();
1564 if (varg < TOK_IDENT)
1565 bad_list:
1566 tcc_error("bad macro parameter list");
1567 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1568 *ps = s;
1569 ps = &s->next;
1570 if (tok == ')')
1571 break;
1572 if (tok != ',' || is_vaargs)
1573 goto bad_list;
1574 next_nomacro();
1576 parse_flags |= PARSE_FLAG_SPACES;
1577 next_nomacro();
1578 t = MACRO_FUNC;
1579 set_idnum('.', dotid);
1582 /* The body of a macro definition should be parsed such that identifiers
1583 are parsed like the file mode determines (i.e. with '.' being an
1584 ID character in asm mode). But '#' should be retained instead of
1585 regarded as line comment leader, so still don't set ASM_FILE
1586 in parse_flags. */
1587 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1588 tok_str_new(&str);
1589 t0 = 0;
1590 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1591 if (is_space(tok)) {
1592 str.need_spc |= 1;
1593 } else {
1594 if (TOK_TWOSHARPS == tok) {
1595 if (0 == t0)
1596 goto bad_twosharp;
1597 tok = TOK_PPJOIN;
1598 t |= MACRO_JOIN;
1600 tok_str_add2_spc(&str, tok, &tokc);
1601 t0 = tok;
1603 next_nomacro();
1605 parse_flags = saved_parse_flags;
1606 tok_str_add(&str, 0);
1607 if (t0 == TOK_PPJOIN)
1608 bad_twosharp:
1609 tcc_error("'##' cannot appear at either end of macro");
1610 define_push(v, t, str.str, first);
1611 //tok_print(str.str, "#define (%d) %s %d:", t | is_vaargs * 4, get_tok_str(v, 0));
1614 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1616 const char *s, *basename;
1617 unsigned int h;
1618 CachedInclude *e;
1619 int c, i, len;
1621 s = basename = tcc_basename(filename);
1622 h = TOK_HASH_INIT;
1623 while ((c = (unsigned char)*s) != 0) {
1624 #ifdef _WIN32
1625 h = TOK_HASH_FUNC(h, toup(c));
1626 #else
1627 h = TOK_HASH_FUNC(h, c);
1628 #endif
1629 s++;
1631 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1633 i = s1->cached_includes_hash[h];
1634 for(;;) {
1635 if (i == 0)
1636 break;
1637 e = s1->cached_includes[i - 1];
1638 if (0 == PATHCMP(filename, e->filename))
1639 return e;
1640 if (e->once
1641 && 0 == PATHCMP(basename, tcc_basename(e->filename))
1642 && 0 == normalized_PATHCMP(filename, e->filename)
1644 return e;
1645 i = e->hash_next;
1647 if (!add)
1648 return NULL;
1650 e = tcc_malloc(sizeof(CachedInclude) + (len = strlen(filename)));
1651 memcpy(e->filename, filename, len + 1);
1652 e->ifndef_macro = e->once = 0;
1653 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1654 /* add in hash table */
1655 e->hash_next = s1->cached_includes_hash[h];
1656 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1657 #ifdef INC_DEBUG
1658 printf("adding cached '%s'\n", filename);
1659 #endif
1660 return e;
1663 static void pragma_parse(TCCState *s1)
1665 next_nomacro();
1666 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1667 int t = tok, v;
1668 Sym *s;
1670 if (next(), tok != '(')
1671 goto pragma_err;
1672 if (next(), tok != TOK_STR)
1673 goto pragma_err;
1674 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1675 if (next(), tok != ')')
1676 goto pragma_err;
1677 if (t == TOK_push_macro) {
1678 while (NULL == (s = define_find(v)))
1679 define_push(v, 0, NULL, NULL);
1680 s->type.ref = s; /* set push boundary */
1681 } else {
1682 for (s = define_stack; s; s = s->prev)
1683 if (s->v == v && s->type.ref == s) {
1684 s->type.ref = NULL;
1685 break;
1688 if (s)
1689 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1690 else
1691 tcc_warning("unbalanced #pragma pop_macro");
1692 pp_debug_tok = t, pp_debug_symv = v;
1694 } else if (tok == TOK_once) {
1695 search_cached_include(s1, file->filename, 1)->once = 1;
1697 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1698 /* tcc -E: keep pragmas below unchanged */
1699 unget_tok(' ');
1700 unget_tok(TOK_PRAGMA);
1701 unget_tok('#');
1702 unget_tok(TOK_LINEFEED);
1704 } else if (tok == TOK_pack) {
1705 /* This may be:
1706 #pragma pack(1) // set
1707 #pragma pack() // reset to default
1708 #pragma pack(push) // push current
1709 #pragma pack(push,1) // push & set
1710 #pragma pack(pop) // restore previous */
1711 next();
1712 skip('(');
1713 if (tok == TOK_ASM_pop) {
1714 next();
1715 if (s1->pack_stack_ptr <= s1->pack_stack) {
1716 stk_error:
1717 tcc_error("out of pack stack");
1719 s1->pack_stack_ptr--;
1720 } else {
1721 int val = 0;
1722 if (tok != ')') {
1723 if (tok == TOK_ASM_push) {
1724 next();
1725 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1726 goto stk_error;
1727 val = *s1->pack_stack_ptr++;
1728 if (tok != ',')
1729 goto pack_set;
1730 next();
1732 if (tok != TOK_CINT)
1733 goto pragma_err;
1734 val = tokc.i;
1735 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1736 goto pragma_err;
1737 next();
1739 pack_set:
1740 *s1->pack_stack_ptr = val;
1742 if (tok != ')')
1743 goto pragma_err;
1745 } else if (tok == TOK_comment) {
1746 char *p; int t;
1747 next();
1748 skip('(');
1749 t = tok;
1750 next();
1751 skip(',');
1752 if (tok != TOK_STR)
1753 goto pragma_err;
1754 p = tcc_strdup((char *)tokc.str.data);
1755 next();
1756 if (tok != ')')
1757 goto pragma_err;
1758 if (t == TOK_lib) {
1759 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1760 } else {
1761 if (t == TOK_option)
1762 tcc_set_options(s1, p);
1763 tcc_free(p);
1766 } else
1767 tcc_warning_c(warn_unsupported)("#pragma %s ignored", get_tok_str(tok, &tokc));
1768 return;
1770 pragma_err:
1771 tcc_error("malformed #pragma directive");
1772 return;
1775 /* is_bof is true if first non space token at beginning of file */
1776 ST_FUNC void preprocess(int is_bof)
1778 TCCState *s1 = tcc_state;
1779 int c, n, saved_parse_flags;
1780 char buf[1024], *q;
1781 Sym *s;
1783 saved_parse_flags = parse_flags;
1784 parse_flags = PARSE_FLAG_PREPROCESS
1785 | PARSE_FLAG_TOK_NUM
1786 | PARSE_FLAG_TOK_STR
1787 | PARSE_FLAG_LINEFEED
1788 | (parse_flags & PARSE_FLAG_ASM_FILE)
1791 next_nomacro();
1792 redo:
1793 switch(tok) {
1794 case TOK_DEFINE:
1795 pp_debug_tok = tok;
1796 next_nomacro();
1797 pp_debug_symv = tok;
1798 parse_define();
1799 break;
1800 case TOK_UNDEF:
1801 pp_debug_tok = tok;
1802 next_nomacro();
1803 pp_debug_symv = tok;
1804 s = define_find(tok);
1805 /* undefine symbol by putting an invalid name */
1806 if (s)
1807 define_undef(s);
1808 break;
1809 case TOK_INCLUDE:
1810 case TOK_INCLUDE_NEXT:
1811 parse_include(s1, tok - TOK_INCLUDE, 0);
1812 goto the_end;
1813 case TOK_IFNDEF:
1814 c = 1;
1815 goto do_ifdef;
1816 case TOK_IF:
1817 c = expr_preprocess(s1);
1818 goto do_if;
1819 case TOK_IFDEF:
1820 c = 0;
1821 do_ifdef:
1822 next_nomacro();
1823 if (tok < TOK_IDENT)
1824 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1825 if (is_bof) {
1826 if (c) {
1827 #ifdef INC_DEBUG
1828 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1829 #endif
1830 file->ifndef_macro = tok;
1833 if (define_find(tok)
1834 || tok == TOK___HAS_INCLUDE
1835 || tok == TOK___HAS_INCLUDE_NEXT)
1836 c ^= 1;
1837 do_if:
1838 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1839 tcc_error("memory full (ifdef)");
1840 *s1->ifdef_stack_ptr++ = c;
1841 goto test_skip;
1842 case TOK_ELSE:
1843 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1844 tcc_error("#else without matching #if");
1845 if (s1->ifdef_stack_ptr[-1] & 2)
1846 tcc_error("#else after #else");
1847 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1848 goto test_else;
1849 case TOK_ELIF:
1850 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1851 tcc_error("#elif without matching #if");
1852 c = s1->ifdef_stack_ptr[-1];
1853 if (c > 1)
1854 tcc_error("#elif after #else");
1855 /* last #if/#elif expression was true: we skip */
1856 if (c == 1) {
1857 c = 0;
1858 } else {
1859 c = expr_preprocess(s1);
1860 s1->ifdef_stack_ptr[-1] = c;
1862 test_else:
1863 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1864 file->ifndef_macro = 0;
1865 test_skip:
1866 if (!(c & 1)) {
1867 preprocess_skip();
1868 is_bof = 0;
1869 goto redo;
1871 break;
1872 case TOK_ENDIF:
1873 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1874 tcc_error("#endif without matching #if");
1875 s1->ifdef_stack_ptr--;
1876 /* '#ifndef macro' was at the start of file. Now we check if
1877 an '#endif' is exactly at the end of file */
1878 if (file->ifndef_macro &&
1879 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1880 file->ifndef_macro_saved = file->ifndef_macro;
1881 /* need to set to zero to avoid false matches if another
1882 #ifndef at middle of file */
1883 file->ifndef_macro = 0;
1884 while (tok != TOK_LINEFEED)
1885 next_nomacro();
1886 tok_flags |= TOK_FLAG_ENDIF;
1887 goto the_end;
1889 break;
1890 case TOK_PPNUM:
1891 n = strtoul((char*)tokc.str.data, &q, 10);
1892 goto _line_num;
1893 case TOK_LINE:
1894 next();
1895 if (tok != TOK_CINT)
1896 _line_err:
1897 tcc_error("wrong #line format");
1898 n = tokc.i;
1899 _line_num:
1900 next();
1901 if (tok != TOK_LINEFEED) {
1902 if (tok == TOK_STR) {
1903 if (file->true_filename == file->filename)
1904 file->true_filename = tcc_strdup(file->filename);
1905 q = (char *)tokc.str.data;
1906 buf[0] = 0;
1907 if (!IS_ABSPATH(q)) {
1908 /* prepend directory from real file */
1909 pstrcpy(buf, sizeof buf, file->true_filename);
1910 *tcc_basename(buf) = 0;
1912 pstrcat(buf, sizeof buf, q);
1913 tcc_debug_putfile(s1, buf);
1914 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
1915 break;
1916 else
1917 goto _line_err;
1918 --n;
1920 if (file->fd > 0)
1921 total_lines += file->line_num - n;
1922 file->line_num = n;
1923 break;
1924 case TOK_ERROR:
1925 case TOK_WARNING:
1926 q = buf;
1927 c = skip_spaces();
1928 while (c != '\n' && c != CH_EOF) {
1929 if ((q - buf) < sizeof(buf) - 1)
1930 *q++ = c;
1931 c = ninp();
1933 *q = '\0';
1934 if (tok == TOK_ERROR)
1935 tcc_error("#error %s", buf);
1936 else
1937 tcc_warning("#warning %s", buf);
1938 break;
1939 case TOK_PRAGMA:
1940 pragma_parse(s1);
1941 break;
1942 case TOK_LINEFEED:
1943 goto the_end;
1944 default:
1945 /* ignore gas line comment in an 'S' file. */
1946 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1947 goto ignore;
1948 if (tok == '!' && is_bof)
1949 /* '!' is ignored at beginning to allow C scripts. */
1950 goto ignore;
1951 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1952 ignore:
1953 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
1954 break;
1956 /* ignore other preprocess commands or #! for C scripts */
1957 while (tok != TOK_LINEFEED)
1958 next_nomacro();
1959 the_end:
1960 parse_flags = saved_parse_flags;
1963 /* evaluate escape codes in a string. */
1964 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1966 int c, n, i;
1967 const uint8_t *p;
1969 p = buf;
1970 for(;;) {
1971 c = *p;
1972 if (c == '\0')
1973 break;
1974 if (c == '\\') {
1975 p++;
1976 /* escape */
1977 c = *p;
1978 switch(c) {
1979 case '0': case '1': case '2': case '3':
1980 case '4': case '5': case '6': case '7':
1981 /* at most three octal digits */
1982 n = c - '0';
1983 p++;
1984 c = *p;
1985 if (isoct(c)) {
1986 n = n * 8 + c - '0';
1987 p++;
1988 c = *p;
1989 if (isoct(c)) {
1990 n = n * 8 + c - '0';
1991 p++;
1994 c = n;
1995 goto add_char_nonext;
1996 case 'x': i = 0; goto parse_hex_or_ucn;
1997 case 'u': i = 4; goto parse_hex_or_ucn;
1998 case 'U': i = 8; goto parse_hex_or_ucn;
1999 parse_hex_or_ucn:
2000 p++;
2001 n = 0;
2002 do {
2003 c = *p;
2004 if (c >= 'a' && c <= 'f')
2005 c = c - 'a' + 10;
2006 else if (c >= 'A' && c <= 'F')
2007 c = c - 'A' + 10;
2008 else if (isnum(c))
2009 c = c - '0';
2010 else if (i > 0)
2011 expect("more hex digits in universal-character-name");
2012 else
2013 goto add_hex_or_ucn;
2014 n = n * 16 + c;
2015 p++;
2016 } while (--i);
2017 if (is_long) {
2018 add_hex_or_ucn:
2019 c = n;
2020 goto add_char_nonext;
2022 cstr_u8cat(outstr, n);
2023 continue;
2024 case 'a':
2025 c = '\a';
2026 break;
2027 case 'b':
2028 c = '\b';
2029 break;
2030 case 'f':
2031 c = '\f';
2032 break;
2033 case 'n':
2034 c = '\n';
2035 break;
2036 case 'r':
2037 c = '\r';
2038 break;
2039 case 't':
2040 c = '\t';
2041 break;
2042 case 'v':
2043 c = '\v';
2044 break;
2045 case 'e':
2046 if (!gnu_ext)
2047 goto invalid_escape;
2048 c = 27;
2049 break;
2050 case '\'':
2051 case '\"':
2052 case '\\':
2053 case '?':
2054 break;
2055 default:
2056 invalid_escape:
2057 if (c >= '!' && c <= '~')
2058 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2059 else
2060 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2061 break;
2063 } else if (is_long && c >= 0x80) {
2064 /* assume we are processing UTF-8 sequence */
2065 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2067 int cont; /* count of continuation bytes */
2068 int skip; /* how many bytes should skip when error occurred */
2069 int i;
2071 /* decode leading byte */
2072 if (c < 0xC2) {
2073 skip = 1; goto invalid_utf8_sequence;
2074 } else if (c <= 0xDF) {
2075 cont = 1; n = c & 0x1f;
2076 } else if (c <= 0xEF) {
2077 cont = 2; n = c & 0xf;
2078 } else if (c <= 0xF4) {
2079 cont = 3; n = c & 0x7;
2080 } else {
2081 skip = 1; goto invalid_utf8_sequence;
2084 /* decode continuation bytes */
2085 for (i = 1; i <= cont; i++) {
2086 int l = 0x80, h = 0xBF;
2088 /* adjust limit for second byte */
2089 if (i == 1) {
2090 switch (c) {
2091 case 0xE0: l = 0xA0; break;
2092 case 0xED: h = 0x9F; break;
2093 case 0xF0: l = 0x90; break;
2094 case 0xF4: h = 0x8F; break;
2098 if (p[i] < l || p[i] > h) {
2099 skip = i; goto invalid_utf8_sequence;
2102 n = (n << 6) | (p[i] & 0x3f);
2105 /* advance pointer */
2106 p += 1 + cont;
2107 c = n;
2108 goto add_char_nonext;
2110 /* error handling */
2111 invalid_utf8_sequence:
2112 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2113 c = 0xFFFD;
2114 p += skip;
2115 goto add_char_nonext;
2118 p++;
2119 add_char_nonext:
2120 if (!is_long)
2121 cstr_ccat(outstr, c);
2122 else {
2123 #ifdef TCC_TARGET_PE
2124 /* store as UTF-16 */
2125 if (c < 0x10000) {
2126 cstr_wccat(outstr, c);
2127 } else {
2128 c -= 0x10000;
2129 cstr_wccat(outstr, (c >> 10) + 0xD800);
2130 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2132 #else
2133 cstr_wccat(outstr, c);
2134 #endif
2137 /* add a trailing '\0' */
2138 if (!is_long)
2139 cstr_ccat(outstr, '\0');
2140 else
2141 cstr_wccat(outstr, '\0');
2144 static void parse_string(const char *s, int len)
2146 uint8_t buf[1000], *p = buf;
2147 int is_long, sep;
2149 if ((is_long = *s == 'L'))
2150 ++s, --len;
2151 sep = *s++;
2152 len -= 2;
2153 if (len >= sizeof buf)
2154 p = tcc_malloc(len + 1);
2155 memcpy(p, s, len);
2156 p[len] = 0;
2158 cstr_reset(&tokcstr);
2159 parse_escape_string(&tokcstr, p, is_long);
2160 if (p != buf)
2161 tcc_free(p);
2163 if (sep == '\'') {
2164 int char_size, i, n, c;
2165 /* XXX: make it portable */
2166 if (!is_long)
2167 tok = TOK_CCHAR, char_size = 1;
2168 else
2169 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2170 n = tokcstr.size / char_size - 1;
2171 if (n < 1)
2172 tcc_error("empty character constant");
2173 if (n > 1)
2174 tcc_warning_c(warn_all)("multi-character character constant");
2175 for (c = i = 0; i < n; ++i) {
2176 if (is_long)
2177 c = ((nwchar_t *)tokcstr.data)[i];
2178 else
2179 c = (c << 8) | ((char *)tokcstr.data)[i];
2181 tokc.i = c;
2182 } else {
2183 tokc.str.size = tokcstr.size;
2184 tokc.str.data = tokcstr.data;
2185 if (!is_long)
2186 tok = TOK_STR;
2187 else
2188 tok = TOK_LSTR;
2192 /* we use 64 bit numbers */
2193 #define BN_SIZE 2
2195 /* bn = (bn << shift) | or_val */
2196 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2198 int i;
2199 unsigned int v;
2200 for(i=0;i<BN_SIZE;i++) {
2201 v = bn[i];
2202 bn[i] = (v << shift) | or_val;
2203 or_val = v >> (32 - shift);
2207 static void bn_zero(unsigned int *bn)
2209 int i;
2210 for(i=0;i<BN_SIZE;i++) {
2211 bn[i] = 0;
2215 /* parse number in null terminated string 'p' and return it in the
2216 current token */
2217 static void parse_number(const char *p)
2219 int b, t, shift, frac_bits, s, exp_val, ch;
2220 char *q;
2221 unsigned int bn[BN_SIZE];
2222 double d;
2224 /* number */
2225 q = token_buf;
2226 ch = *p++;
2227 t = ch;
2228 ch = *p++;
2229 *q++ = t;
2230 b = 10;
2231 if (t == '.') {
2232 goto float_frac_parse;
2233 } else if (t == '0') {
2234 if (ch == 'x' || ch == 'X') {
2235 q--;
2236 ch = *p++;
2237 b = 16;
2238 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2239 q--;
2240 ch = *p++;
2241 b = 2;
2244 /* parse all digits. cannot check octal numbers at this stage
2245 because of floating point constants */
2246 while (1) {
2247 if (ch >= 'a' && ch <= 'f')
2248 t = ch - 'a' + 10;
2249 else if (ch >= 'A' && ch <= 'F')
2250 t = ch - 'A' + 10;
2251 else if (isnum(ch))
2252 t = ch - '0';
2253 else
2254 break;
2255 if (t >= b)
2256 break;
2257 if (q >= token_buf + STRING_MAX_SIZE) {
2258 num_too_long:
2259 tcc_error("number too long");
2261 *q++ = ch;
2262 ch = *p++;
2264 if (ch == '.' ||
2265 ((ch == 'e' || ch == 'E') && b == 10) ||
2266 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2267 if (b != 10) {
2268 /* NOTE: strtox should support that for hexa numbers, but
2269 non ISOC99 libcs do not support it, so we prefer to do
2270 it by hand */
2271 /* hexadecimal or binary floats */
2272 /* XXX: handle overflows */
2273 *q = '\0';
2274 if (b == 16)
2275 shift = 4;
2276 else
2277 shift = 1;
2278 bn_zero(bn);
2279 q = token_buf;
2280 while (1) {
2281 t = *q++;
2282 if (t == '\0') {
2283 break;
2284 } else if (t >= 'a') {
2285 t = t - 'a' + 10;
2286 } else if (t >= 'A') {
2287 t = t - 'A' + 10;
2288 } else {
2289 t = t - '0';
2291 bn_lshift(bn, shift, t);
2293 frac_bits = 0;
2294 if (ch == '.') {
2295 ch = *p++;
2296 while (1) {
2297 t = ch;
2298 if (t >= 'a' && t <= 'f') {
2299 t = t - 'a' + 10;
2300 } else if (t >= 'A' && t <= 'F') {
2301 t = t - 'A' + 10;
2302 } else if (t >= '0' && t <= '9') {
2303 t = t - '0';
2304 } else {
2305 break;
2307 if (t >= b)
2308 tcc_error("invalid digit");
2309 bn_lshift(bn, shift, t);
2310 frac_bits += shift;
2311 ch = *p++;
2314 if (ch != 'p' && ch != 'P')
2315 expect("exponent");
2316 ch = *p++;
2317 s = 1;
2318 exp_val = 0;
2319 if (ch == '+') {
2320 ch = *p++;
2321 } else if (ch == '-') {
2322 s = -1;
2323 ch = *p++;
2325 if (ch < '0' || ch > '9')
2326 expect("exponent digits");
2327 while (ch >= '0' && ch <= '9') {
2328 exp_val = exp_val * 10 + ch - '0';
2329 ch = *p++;
2331 exp_val = exp_val * s;
2333 /* now we can generate the number */
2334 /* XXX: should patch directly float number */
2335 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2336 d = ldexp(d, exp_val - frac_bits);
2337 t = toup(ch);
2338 if (t == 'F') {
2339 ch = *p++;
2340 tok = TOK_CFLOAT;
2341 /* float : should handle overflow */
2342 tokc.f = (float)d;
2343 } else if (t == 'L') {
2344 ch = *p++;
2345 tok = TOK_CLDOUBLE;
2346 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2347 tokc.d = d;
2348 #else
2349 /* XXX: not large enough */
2350 tokc.ld = (long double)d;
2351 #endif
2352 } else {
2353 tok = TOK_CDOUBLE;
2354 tokc.d = d;
2356 } else {
2357 /* decimal floats */
2358 if (ch == '.') {
2359 if (q >= token_buf + STRING_MAX_SIZE)
2360 goto num_too_long;
2361 *q++ = ch;
2362 ch = *p++;
2363 float_frac_parse:
2364 while (ch >= '0' && ch <= '9') {
2365 if (q >= token_buf + STRING_MAX_SIZE)
2366 goto num_too_long;
2367 *q++ = ch;
2368 ch = *p++;
2371 if (ch == 'e' || ch == 'E') {
2372 if (q >= token_buf + STRING_MAX_SIZE)
2373 goto num_too_long;
2374 *q++ = ch;
2375 ch = *p++;
2376 if (ch == '-' || ch == '+') {
2377 if (q >= token_buf + STRING_MAX_SIZE)
2378 goto num_too_long;
2379 *q++ = ch;
2380 ch = *p++;
2382 if (ch < '0' || ch > '9')
2383 expect("exponent digits");
2384 while (ch >= '0' && ch <= '9') {
2385 if (q >= token_buf + STRING_MAX_SIZE)
2386 goto num_too_long;
2387 *q++ = ch;
2388 ch = *p++;
2391 *q = '\0';
2392 t = toup(ch);
2393 errno = 0;
2394 if (t == 'F') {
2395 ch = *p++;
2396 tok = TOK_CFLOAT;
2397 tokc.f = strtof(token_buf, NULL);
2398 } else if (t == 'L') {
2399 ch = *p++;
2400 tok = TOK_CLDOUBLE;
2401 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2402 tokc.d = strtod(token_buf, NULL);
2403 #else
2404 tokc.ld = strtold(token_buf, NULL);
2405 #endif
2406 } else {
2407 tok = TOK_CDOUBLE;
2408 tokc.d = strtod(token_buf, NULL);
2411 } else {
2412 unsigned long long n, n1;
2413 int lcount, ucount, ov = 0;
2414 const char *p1;
2416 /* integer number */
2417 *q = '\0';
2418 q = token_buf;
2419 if (b == 10 && *q == '0') {
2420 b = 8;
2421 q++;
2423 n = 0;
2424 while(1) {
2425 t = *q++;
2426 /* no need for checks except for base 10 / 8 errors */
2427 if (t == '\0')
2428 break;
2429 else if (t >= 'a')
2430 t = t - 'a' + 10;
2431 else if (t >= 'A')
2432 t = t - 'A' + 10;
2433 else
2434 t = t - '0';
2435 if (t >= b)
2436 tcc_error("invalid digit");
2437 n1 = n;
2438 n = n * b + t;
2439 /* detect overflow */
2440 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2441 ov = 1;
2444 /* Determine the characteristics (unsigned and/or 64bit) the type of
2445 the constant must have according to the constant suffix(es) */
2446 lcount = ucount = 0;
2447 p1 = p;
2448 for(;;) {
2449 t = toup(ch);
2450 if (t == 'L') {
2451 if (lcount >= 2)
2452 tcc_error("three 'l's in integer constant");
2453 if (lcount && *(p - 1) != ch)
2454 tcc_error("incorrect integer suffix: %s", p1);
2455 lcount++;
2456 ch = *p++;
2457 } else if (t == 'U') {
2458 if (ucount >= 1)
2459 tcc_error("two 'u's in integer constant");
2460 ucount++;
2461 ch = *p++;
2462 } else {
2463 break;
2467 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2468 if (ucount == 0 && b == 10) {
2469 if (lcount <= (LONG_SIZE == 4)) {
2470 if (n >= 0x80000000U)
2471 lcount = (LONG_SIZE == 4) + 1;
2473 if (n >= 0x8000000000000000ULL)
2474 ov = 1, ucount = 1;
2475 } else {
2476 if (lcount <= (LONG_SIZE == 4)) {
2477 if (n >= 0x100000000ULL)
2478 lcount = (LONG_SIZE == 4) + 1;
2479 else if (n >= 0x80000000U)
2480 ucount = 1;
2482 if (n >= 0x8000000000000000ULL)
2483 ucount = 1;
2486 if (ov)
2487 tcc_warning("integer constant overflow");
2489 tok = TOK_CINT;
2490 if (lcount) {
2491 tok = TOK_CLONG;
2492 if (lcount == 2)
2493 tok = TOK_CLLONG;
2495 if (ucount)
2496 ++tok; /* TOK_CU... */
2497 tokc.i = n;
2499 if (ch)
2500 tcc_error("invalid number");
2504 #define PARSE2(c1, tok1, c2, tok2) \
2505 case c1: \
2506 PEEKC(c, p); \
2507 if (c == c2) { \
2508 p++; \
2509 tok = tok2; \
2510 } else { \
2511 tok = tok1; \
2513 break;
2515 /* return next token without macro substitution */
2516 static void next_nomacro(void)
2518 int t, c, is_long, len;
2519 TokenSym *ts;
2520 uint8_t *p, *p1;
2521 unsigned int h;
2523 p = file->buf_ptr;
2524 redo_no_start:
2525 c = *p;
2526 switch(c) {
2527 case ' ':
2528 case '\t':
2529 tok = c;
2530 p++;
2531 maybe_space:
2532 if (parse_flags & PARSE_FLAG_SPACES)
2533 goto keep_tok_flags;
2534 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2535 ++p;
2536 goto redo_no_start;
2537 case '\f':
2538 case '\v':
2539 case '\r':
2540 p++;
2541 goto redo_no_start;
2542 case '\\':
2543 /* first look if it is in fact an end of buffer */
2544 c = handle_stray(&p);
2545 if (c == '\\')
2546 goto parse_simple;
2547 if (c == CH_EOF) {
2548 TCCState *s1 = tcc_state;
2549 if (!(tok_flags & TOK_FLAG_BOL)) {
2550 /* add implicit newline */
2551 goto maybe_newline;
2552 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2553 tok = TOK_EOF;
2554 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2555 tcc_error("missing #endif");
2556 } else if (s1->include_stack_ptr == s1->include_stack) {
2557 /* no include left : end of file. */
2558 tok = TOK_EOF;
2559 } else {
2560 /* pop include file */
2562 /* test if previous '#endif' was after a #ifdef at
2563 start of file */
2564 if (tok_flags & TOK_FLAG_ENDIF) {
2565 #ifdef INC_DEBUG
2566 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2567 #endif
2568 search_cached_include(s1, file->filename, 1)
2569 ->ifndef_macro = file->ifndef_macro_saved;
2570 tok_flags &= ~TOK_FLAG_ENDIF;
2573 /* add end of include file debug info */
2574 tcc_debug_eincl(tcc_state);
2575 /* pop include stack */
2576 tcc_close();
2577 s1->include_stack_ptr--;
2578 p = file->buf_ptr;
2579 goto maybe_newline;
2581 } else {
2582 goto redo_no_start;
2584 break;
2586 case '\n':
2587 file->line_num++;
2588 p++;
2589 maybe_newline:
2590 tok_flags |= TOK_FLAG_BOL;
2591 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2592 goto redo_no_start;
2593 tok = TOK_LINEFEED;
2594 goto keep_tok_flags;
2596 case '#':
2597 /* XXX: simplify */
2598 PEEKC(c, p);
2599 if ((tok_flags & TOK_FLAG_BOL) &&
2600 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2601 tok_flags &= ~TOK_FLAG_BOL;
2602 file->buf_ptr = p;
2603 preprocess(tok_flags & TOK_FLAG_BOF);
2604 p = file->buf_ptr;
2605 goto maybe_newline;
2606 } else {
2607 if (c == '#') {
2608 p++;
2609 tok = TOK_TWOSHARPS;
2610 } else {
2611 #if !defined(TCC_TARGET_ARM)
2612 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2613 p = parse_line_comment(p - 1);
2614 goto redo_no_start;
2615 } else
2616 #endif
2618 tok = '#';
2622 break;
2624 /* dollar is allowed to start identifiers when not parsing asm */
2625 case '$':
2626 if (!(isidnum_table['$' - CH_EOF] & IS_ID)
2627 || (parse_flags & PARSE_FLAG_ASM_FILE))
2628 goto parse_simple;
2630 case 'a': case 'b': case 'c': case 'd':
2631 case 'e': case 'f': case 'g': case 'h':
2632 case 'i': case 'j': case 'k': case 'l':
2633 case 'm': case 'n': case 'o': case 'p':
2634 case 'q': case 'r': case 's': case 't':
2635 case 'u': case 'v': case 'w': case 'x':
2636 case 'y': case 'z':
2637 case 'A': case 'B': case 'C': case 'D':
2638 case 'E': case 'F': case 'G': case 'H':
2639 case 'I': case 'J': case 'K':
2640 case 'M': case 'N': case 'O': case 'P':
2641 case 'Q': case 'R': case 'S': case 'T':
2642 case 'U': case 'V': case 'W': case 'X':
2643 case 'Y': case 'Z':
2644 case '_':
2645 parse_ident_fast:
2646 p1 = p;
2647 h = TOK_HASH_INIT;
2648 h = TOK_HASH_FUNC(h, c);
2649 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2650 h = TOK_HASH_FUNC(h, c);
2651 len = p - p1;
2652 if (c != '\\') {
2653 TokenSym **pts;
2655 /* fast case : no stray found, so we have the full token
2656 and we have already hashed it */
2657 h &= (TOK_HASH_SIZE - 1);
2658 pts = &hash_ident[h];
2659 for(;;) {
2660 ts = *pts;
2661 if (!ts)
2662 break;
2663 if (ts->len == len && !memcmp(ts->str, p1, len))
2664 goto token_found;
2665 pts = &(ts->hash_next);
2667 ts = tok_alloc_new(pts, (char *) p1, len);
2668 token_found: ;
2669 } else {
2670 /* slower case */
2671 cstr_reset(&tokcstr);
2672 cstr_cat(&tokcstr, (char *) p1, len);
2673 p--;
2674 PEEKC(c, p);
2675 parse_ident_slow:
2676 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2678 cstr_ccat(&tokcstr, c);
2679 PEEKC(c, p);
2681 ts = tok_alloc(tokcstr.data, tokcstr.size);
2683 tok = ts->tok;
2684 break;
2685 case 'L':
2686 t = p[1];
2687 if (t != '\\' && t != '\'' && t != '\"') {
2688 /* fast case */
2689 goto parse_ident_fast;
2690 } else {
2691 PEEKC(c, p);
2692 if (c == '\'' || c == '\"') {
2693 is_long = 1;
2694 goto str_const;
2695 } else {
2696 cstr_reset(&tokcstr);
2697 cstr_ccat(&tokcstr, 'L');
2698 goto parse_ident_slow;
2701 break;
2703 case '0': case '1': case '2': case '3':
2704 case '4': case '5': case '6': case '7':
2705 case '8': case '9':
2706 t = c;
2707 PEEKC(c, p);
2708 /* after the first digit, accept digits, alpha, '.' or sign if
2709 prefixed by 'eEpP' */
2710 parse_num:
2711 cstr_reset(&tokcstr);
2712 for(;;) {
2713 cstr_ccat(&tokcstr, t);
2714 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2715 || c == '.'
2716 || ((c == '+' || c == '-')
2717 && (((t == 'e' || t == 'E')
2718 && !(parse_flags & PARSE_FLAG_ASM_FILE
2719 /* 0xe+1 is 3 tokens in asm */
2720 && ((char*)tokcstr.data)[0] == '0'
2721 && toup(((char*)tokcstr.data)[1]) == 'X'))
2722 || t == 'p' || t == 'P'))))
2723 break;
2724 t = c;
2725 PEEKC(c, p);
2727 /* We add a trailing '\0' to ease parsing */
2728 cstr_ccat(&tokcstr, '\0');
2729 tokc.str.size = tokcstr.size;
2730 tokc.str.data = tokcstr.data;
2731 tok = TOK_PPNUM;
2732 break;
2734 case '.':
2735 /* special dot handling because it can also start a number */
2736 PEEKC(c, p);
2737 if (isnum(c)) {
2738 t = '.';
2739 goto parse_num;
2740 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2741 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2742 *--p = c = '.';
2743 goto parse_ident_fast;
2744 } else if (c == '.') {
2745 PEEKC(c, p);
2746 if (c == '.') {
2747 p++;
2748 tok = TOK_DOTS;
2749 } else {
2750 *--p = '.'; /* may underflow into file->unget[] */
2751 tok = '.';
2753 } else {
2754 tok = '.';
2756 break;
2757 case '\'':
2758 case '\"':
2759 is_long = 0;
2760 str_const:
2761 cstr_reset(&tokcstr);
2762 if (is_long)
2763 cstr_ccat(&tokcstr, 'L');
2764 cstr_ccat(&tokcstr, c);
2765 p = parse_pp_string(p, c, &tokcstr);
2766 cstr_ccat(&tokcstr, c);
2767 cstr_ccat(&tokcstr, '\0');
2768 tokc.str.size = tokcstr.size;
2769 tokc.str.data = tokcstr.data;
2770 tok = TOK_PPSTR;
2771 break;
2773 case '<':
2774 PEEKC(c, p);
2775 if (c == '=') {
2776 p++;
2777 tok = TOK_LE;
2778 } else if (c == '<') {
2779 PEEKC(c, p);
2780 if (c == '=') {
2781 p++;
2782 tok = TOK_A_SHL;
2783 } else {
2784 tok = TOK_SHL;
2786 } else {
2787 tok = TOK_LT;
2789 break;
2790 case '>':
2791 PEEKC(c, p);
2792 if (c == '=') {
2793 p++;
2794 tok = TOK_GE;
2795 } else if (c == '>') {
2796 PEEKC(c, p);
2797 if (c == '=') {
2798 p++;
2799 tok = TOK_A_SAR;
2800 } else {
2801 tok = TOK_SAR;
2803 } else {
2804 tok = TOK_GT;
2806 break;
2808 case '&':
2809 PEEKC(c, p);
2810 if (c == '&') {
2811 p++;
2812 tok = TOK_LAND;
2813 } else if (c == '=') {
2814 p++;
2815 tok = TOK_A_AND;
2816 } else {
2817 tok = '&';
2819 break;
2821 case '|':
2822 PEEKC(c, p);
2823 if (c == '|') {
2824 p++;
2825 tok = TOK_LOR;
2826 } else if (c == '=') {
2827 p++;
2828 tok = TOK_A_OR;
2829 } else {
2830 tok = '|';
2832 break;
2834 case '+':
2835 PEEKC(c, p);
2836 if (c == '+') {
2837 p++;
2838 tok = TOK_INC;
2839 } else if (c == '=') {
2840 p++;
2841 tok = TOK_A_ADD;
2842 } else {
2843 tok = '+';
2845 break;
2847 case '-':
2848 PEEKC(c, p);
2849 if (c == '-') {
2850 p++;
2851 tok = TOK_DEC;
2852 } else if (c == '=') {
2853 p++;
2854 tok = TOK_A_SUB;
2855 } else if (c == '>') {
2856 p++;
2857 tok = TOK_ARROW;
2858 } else {
2859 tok = '-';
2861 break;
2863 PARSE2('!', '!', '=', TOK_NE)
2864 PARSE2('=', '=', '=', TOK_EQ)
2865 PARSE2('*', '*', '=', TOK_A_MUL)
2866 PARSE2('%', '%', '=', TOK_A_MOD)
2867 PARSE2('^', '^', '=', TOK_A_XOR)
2869 /* comments or operator */
2870 case '/':
2871 PEEKC(c, p);
2872 if (c == '*') {
2873 p = parse_comment(p);
2874 /* comments replaced by a blank */
2875 tok = ' ';
2876 goto maybe_space;
2877 } else if (c == '/') {
2878 p = parse_line_comment(p);
2879 tok = ' ';
2880 goto maybe_space;
2881 } else if (c == '=') {
2882 p++;
2883 tok = TOK_A_DIV;
2884 } else {
2885 tok = '/';
2887 break;
2889 /* simple tokens */
2890 case '(':
2891 case ')':
2892 case '[':
2893 case ']':
2894 case '{':
2895 case '}':
2896 case ',':
2897 case ';':
2898 case ':':
2899 case '?':
2900 case '~':
2901 case '@': /* only used in assembler */
2902 parse_simple:
2903 tok = c;
2904 p++;
2905 break;
2906 default:
2907 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2908 goto parse_ident_fast;
2909 if (parse_flags & PARSE_FLAG_ASM_FILE)
2910 goto parse_simple;
2911 tcc_error("unrecognized character \\x%02x", c);
2912 break;
2914 tok_flags = 0;
2915 keep_tok_flags:
2916 file->buf_ptr = p;
2917 #if defined(PARSE_DEBUG)
2918 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
2919 #endif
2922 #ifdef PP_DEBUG
2923 static int indent;
2924 static void define_print(TCCState *s1, int v);
2925 static void pp_print(const char *msg, int v, const int *str)
2927 FILE *fp = tcc_state->ppfp;
2929 if (msg[0] == '#' && indent == 0)
2930 fprintf(fp, "\n");
2931 else if (msg[0] == '+')
2932 ++indent, ++msg;
2933 else if (msg[0] == '-')
2934 --indent, ++msg;
2936 fprintf(fp, "%*s", indent, "");
2937 if (msg[0] == '#') {
2938 define_print(tcc_state, v);
2939 } else {
2940 tok_print(str, v ? "%s %s" : "%s", msg, get_tok_str(v, 0));
2943 #define PP_PRINT(x) pp_print x
2944 #else
2945 #define PP_PRINT(x)
2946 #endif
2948 static int macro_subst(
2949 TokenString *tok_str,
2950 Sym **nested_list,
2951 const int *macro_str
2954 /* substitute arguments in replacement lists in macro_str by the values in
2955 args (field d) and return allocated string */
2956 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2958 int t, t0, t1, t2, n;
2959 const int *st;
2960 Sym *s;
2961 CValue cval;
2962 TokenString str;
2964 #ifdef PP_DEBUG
2965 PP_PRINT(("asubst:", 0, macro_str));
2966 for (s = args, n = 0; s; s = s->prev, ++n);
2967 while (n--) {
2968 for (s = args, t = 0; t < n; s = s->prev, ++t);
2969 tok_print(s->d, "%*s - arg: %s:", indent, "", get_tok_str(s->v, 0));
2971 #endif
2973 tok_str_new(&str);
2974 t0 = t1 = 0;
2975 while(1) {
2976 TOK_GET(&t, &macro_str, &cval);
2977 if (!t)
2978 break;
2979 if (t == '#') {
2980 /* stringize */
2981 do t = *macro_str++; while (t == ' ');
2982 s = sym_find2(args, t);
2983 if (s) {
2984 cstr_reset(&tokcstr);
2985 cstr_ccat(&tokcstr, '\"');
2986 st = s->d;
2987 while (*st != TOK_EOF) {
2988 const char *s;
2989 TOK_GET(&t, &st, &cval);
2990 s = get_tok_str(t, &cval);
2991 while (*s) {
2992 if (t == TOK_PPSTR && *s != '\'')
2993 add_char(&tokcstr, *s);
2994 else
2995 cstr_ccat(&tokcstr, *s);
2996 ++s;
2999 cstr_ccat(&tokcstr, '\"');
3000 cstr_ccat(&tokcstr, '\0');
3001 //printf("\nstringize: <%s>\n", (char *)tokcstr.data);
3002 /* add string */
3003 cval.str.size = tokcstr.size;
3004 cval.str.data = tokcstr.data;
3005 tok_str_add2(&str, TOK_PPSTR, &cval);
3006 } else {
3007 expect("macro parameter after '#'");
3009 } else if (t >= TOK_IDENT) {
3010 s = sym_find2(args, t);
3011 if (s) {
3012 st = s->d;
3013 n = 0;
3014 while ((t2 = macro_str[n]) == ' ')
3015 ++n;
3016 /* if '##' is present before or after, no arg substitution */
3017 if (t2 == TOK_PPJOIN || t1 == TOK_PPJOIN) {
3018 /* special case for var arg macros : ## eats the ','
3019 if empty VA_ARGS variable. */
3020 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
3021 int c = str.str[str.len - 1];
3022 while (str.str[--str.len] != ',')
3024 if (*st == TOK_EOF) {
3025 /* suppress ',' '##' */
3026 } else {
3027 /* suppress '##' and add variable */
3028 str.len++;
3029 if (c == ' ')
3030 str.str[str.len++] = c;
3031 goto add_var;
3033 } else {
3034 if (*st == TOK_EOF)
3035 tok_str_add(&str, TOK_PLCHLDR);
3037 } else {
3038 add_var:
3039 if (!s->e) {
3040 /* Expand arguments tokens and store them. In most
3041 cases we could also re-expand each argument if
3042 used multiple times, but not if the argument
3043 contains the __COUNTER__ macro. */
3044 TokenString str2;
3045 tok_str_new(&str2);
3046 macro_subst(&str2, nested_list, st);
3047 tok_str_add(&str2, TOK_EOF);
3048 s->e = str2.str;
3050 st = s->e;
3052 while (*st != TOK_EOF) {
3053 TOK_GET(&t2, &st, &cval);
3054 tok_str_add2(&str, t2, &cval);
3056 } else {
3057 tok_str_add(&str, t);
3059 } else {
3060 tok_str_add2(&str, t, &cval);
3062 if (t != ' ')
3063 t0 = t1, t1 = t;
3065 tok_str_add(&str, 0);
3066 PP_PRINT(("areslt:", 0, str.str));
3067 return str.str;
3070 /* handle the '##' operator. return the resulting string (which must be freed). */
3071 static inline int *macro_twosharps(const int *ptr0)
3073 int t1, t2, n;
3074 CValue cv1, cv2;
3075 TokenString macro_str1;
3076 const int *ptr;
3078 tok_str_new(&macro_str1);
3079 for (ptr = ptr0;;) {
3080 TOK_GET(&t1, &ptr, &cv1);
3081 if (t1 == 0)
3082 break;
3083 for (;;) {
3084 n = 0;
3085 while ((t2 = ptr[n]) == ' ')
3086 ++n;
3087 if (t2 != TOK_PPJOIN)
3088 break;
3089 ptr += n;
3090 while ((t2 = *++ptr) == ' ' || t2 == TOK_PPJOIN)
3092 TOK_GET(&t2, &ptr, &cv2);
3093 if (t1 == TOK_PLCHLDR && t2 == TOK_PLCHLDR)
3094 continue;
3095 cstr_reset(&tokcstr);
3096 if (t1 != TOK_PLCHLDR)
3097 cstr_cat(&tokcstr, get_tok_str(t1, &cv1), -1);
3098 n = tokcstr.size;
3099 if (t2 != TOK_PLCHLDR)
3100 cstr_cat(&tokcstr, get_tok_str(t2, &cv2), -1);
3101 cstr_ccat(&tokcstr, '\0');
3102 //printf("paste <%s>\n", (char*)tokcstr.data);
3103 tcc_open_bf(tcc_state, ":paste:", tokcstr.size);
3104 memcpy(file->buffer, tokcstr.data, tokcstr.size);
3105 tok_flags = 0; /* don't interpret '#' */
3106 next_nomacro();
3107 if (*file->buf_ptr == 0) {
3108 t1 = tok, cv1 = tokc;
3109 } else {
3110 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3111 " preprocessing token", n, file->buffer, file->buffer + n);
3112 tok_str_add2(&macro_str1, t1, &cv1);
3113 t1 = t2, cv1 = cv2;
3115 tcc_close();
3117 if (t1 != TOK_PLCHLDR)
3118 tok_str_add2(&macro_str1, t1, &cv1);
3120 tok_str_add(&macro_str1, 0);
3121 PP_PRINT(("pasted:", 0, macro_str1.str));
3122 return macro_str1.str;
3125 static int peek_file (TokenString *ws_str)
3127 uint8_t *p = file->buf_ptr - 1;
3128 int c;
3129 for (;;) {
3130 PEEKC(c, p);
3131 switch (c) {
3132 case '/':
3133 PEEKC(c, p);
3134 if (c == '*')
3135 p = parse_comment(p);
3136 else if (c == '/')
3137 p = parse_line_comment(p);
3138 else {
3139 c = *--p = '/';
3140 goto leave;
3142 --p, c = ' ';
3143 break;
3144 case ' ': case '\t':
3145 break;
3146 case '\f': case '\v': case '\r':
3147 continue;
3148 case '\n':
3149 file->line_num++, tok_flags |= TOK_FLAG_BOL;
3150 break;
3151 default: leave:
3152 file->buf_ptr = p;
3153 return c;
3155 if (ws_str)
3156 tok_str_add(ws_str, c);
3160 /* peek or read [ws_str == NULL] next token from function macro call,
3161 walking up macro levels up to the file if necessary */
3162 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3164 int t;
3165 Sym *sa;
3167 while (macro_ptr) {
3168 const int *m = macro_ptr;
3169 while ((t = *m) != 0) {
3170 if (ws_str) {
3171 if (t != ' ')
3172 return t;
3173 ++m;
3174 } else {
3175 TOK_GET(&tok, &macro_ptr, &tokc);
3176 return tok;
3179 end_macro();
3180 /* also, end of scope for nested defined symbol */
3181 sa = *nested_list;
3182 if (sa)
3183 *nested_list = sa->prev, sym_free(sa);
3185 if (ws_str) {
3186 return peek_file(ws_str);
3187 } else {
3188 next_nomacro();
3189 if (tok == '\t' || tok == TOK_LINEFEED)
3190 tok = ' ';
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 int t;
3205 int v = s->v;
3207 PP_PRINT(("#", v, s->d));
3208 if (s->d) {
3209 int *mstr = s->d;
3210 int *jstr;
3211 Sym *sa;
3212 int ret;
3214 if (s->type.t & MACRO_FUNC) {
3215 int saved_parse_flags = parse_flags;
3216 TokenString str;
3217 int parlevel, i;
3218 Sym *sa1, *args;
3220 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3221 | PARSE_FLAG_ACCEPT_STRAYS;
3223 tok_str_new(&str);
3224 /* peek next token from argument stream */
3225 t = next_argstream(nested_list, &str);
3226 if (t != '(') {
3227 /* not a macro substitution after all, restore the
3228 * macro token plus all whitespace we've read.
3229 * whitespace is intentionally not merged to preserve
3230 * newlines. */
3231 parse_flags = saved_parse_flags;
3232 tok_str_add2_spc(tok_str, v, 0);
3233 if (parse_flags & PARSE_FLAG_SPACES)
3234 for (i = 0; i < str.len; i++)
3235 tok_str_add(tok_str, str.str[i]);
3236 tok_str_free_str(str.str);
3237 return 0;
3238 } else {
3239 tok_str_free_str(str.str);
3242 /* argument macro */
3243 args = NULL;
3244 sa = s->next;
3245 /* NOTE: empty args are allowed, except if no args */
3246 i = 2; /* eat '(' */
3247 for(;;) {
3248 do {
3249 t = next_argstream(nested_list, NULL);
3250 } while (t == ' ' || --i);
3252 if (!sa) {
3253 if (t == ')') /* handle '()' case */
3254 break;
3255 tcc_error("macro '%s' used with too many args",
3256 get_tok_str(v, 0));
3258 empty_arg:
3259 tok_str_new(&str);
3260 parlevel = 0;
3261 /* NOTE: non zero sa->type.t indicates VA_ARGS */
3262 while (parlevel > 0
3263 || (t != ')' && (t != ',' || sa->type.t))) {
3264 if (t == TOK_EOF)
3265 tcc_error("EOF in invocation of macro '%s'",
3266 get_tok_str(v, 0));
3267 if (t == '(')
3268 parlevel++;
3269 if (t == ')')
3270 parlevel--;
3271 if (t == ' ')
3272 str.need_spc |= 1;
3273 else
3274 tok_str_add2_spc(&str, t, &tokc);
3275 t = next_argstream(nested_list, NULL);
3277 tok_str_add(&str, TOK_EOF);
3278 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3279 sa1->d = str.str;
3280 sa = sa->next;
3281 if (t == ')') {
3282 if (!sa)
3283 break;
3284 /* special case for gcc var args: add an empty
3285 var arg argument if it is omitted */
3286 if (sa->type.t && gnu_ext)
3287 goto empty_arg;
3288 tcc_error("macro '%s' used with too few args",
3289 get_tok_str(v, 0));
3291 i = 1;
3294 /* now subst each arg */
3295 mstr = macro_arg_subst(nested_list, mstr, args);
3296 /* free memory */
3297 sa = args;
3298 while (sa) {
3299 sa1 = sa->prev;
3300 tok_str_free_str(sa->d);
3301 tok_str_free_str(sa->e);
3302 sym_free(sa);
3303 sa = sa1;
3305 parse_flags = saved_parse_flags;
3308 /* process '##'s (if present) */
3309 jstr = mstr;
3310 if (s->type.t & MACRO_JOIN)
3311 jstr = macro_twosharps(mstr);
3313 sa = sym_push2(nested_list, v, 0, 0);
3314 ret = macro_subst(tok_str, nested_list, jstr);
3315 /* pop nested defined symbol */
3316 if (sa == *nested_list)
3317 *nested_list = sa->prev, sym_free(sa);
3319 if (jstr != mstr)
3320 tok_str_free_str(jstr);
3321 if (mstr != s->d)
3322 tok_str_free_str(mstr);
3323 return ret;
3325 } else {
3326 CValue cval;
3327 char buf[32], *cstrval = buf;
3329 /* special macros */
3330 if (v == TOK___LINE__ || v == TOK___COUNTER__) {
3331 t = v == TOK___LINE__ ? file->line_num : pp_counter++;
3332 snprintf(buf, sizeof(buf), "%d", t);
3333 t = TOK_PPNUM;
3334 goto add_cstr1;
3336 } else if (v == TOK___FILE__) {
3337 cstrval = file->filename;
3338 goto add_cstr;
3340 } else if (v == TOK___DATE__ || v == TOK___TIME__) {
3341 time_t ti;
3342 struct tm *tm;
3343 time(&ti);
3344 tm = localtime(&ti);
3345 if (v == TOK___DATE__) {
3346 static char const ab_month_name[12][4] = {
3347 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3348 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3350 snprintf(buf, sizeof(buf), "%s %2d %d",
3351 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3352 } else {
3353 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3354 tm->tm_hour, tm->tm_min, tm->tm_sec);
3356 add_cstr:
3357 t = TOK_STR;
3358 add_cstr1:
3359 cval.str.size = strlen(cstrval) + 1;
3360 cval.str.data = cstrval;
3361 tok_str_add2_spc(tok_str, t, &cval);
3363 return 0;
3367 /* do macro substitution of macro_str and add result to
3368 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3369 inside to avoid recursing. */
3370 static int macro_subst(
3371 TokenString *tok_str,
3372 Sym **nested_list,
3373 const int *macro_str
3376 Sym *s;
3377 int t, nosubst = 0;
3378 CValue cval;
3379 TokenString *str;
3381 #ifdef PP_DEBUG
3382 int tlen = tok_str->len;
3383 PP_PRINT(("+expand:", 0, macro_str));
3384 #endif
3386 while (1) {
3387 TOK_GET(&t, &macro_str, &cval);
3388 if (t == 0 || t == TOK_EOF)
3389 break;
3390 if (t >= TOK_IDENT) {
3391 s = define_find(t);
3392 if (s == NULL || nosubst)
3393 goto no_subst;
3394 /* if nested substitution, do nothing */
3395 if (sym_find2(*nested_list, t)) {
3396 /* and mark so it doesn't get subst'd again */
3397 t |= SYM_FIELD;
3398 goto no_subst;
3400 str = tok_str_alloc();
3401 str->str = (int*)macro_str; /* setup stream for possible arguments */
3402 begin_macro(str, 2);
3403 nosubst = macro_subst_tok(tok_str, nested_list, s);
3404 if (macro_stack != str) {
3405 /* already finished by reading function macro arguments */
3406 break;
3408 macro_str = macro_ptr;
3409 end_macro ();
3410 } else if (t == ' ') {
3411 if (parse_flags & PARSE_FLAG_SPACES)
3412 tok_str->need_spc |= 1;
3413 } else {
3414 no_subst:
3415 tok_str_add2_spc(tok_str, t, &cval);
3416 if (nosubst && t != '(')
3417 nosubst = 0;
3418 /* GCC supports 'defined' as result of a macro substitution */
3419 if (t == TOK_DEFINED && pp_expr)
3420 nosubst = 1;
3424 #ifdef PP_DEBUG
3425 tok_str_add(tok_str, 0), --tok_str->len;
3426 PP_PRINT(("-result:", 0, tok_str->str + tlen));
3427 #endif
3428 return nosubst;
3431 /* return next token with macro substitution */
3432 ST_FUNC void next(void)
3434 int t;
3435 while (macro_ptr) {
3436 redo:
3437 t = *macro_ptr;
3438 if (TOK_HAS_VALUE(t)) {
3439 tok_get(&tok, &macro_ptr, &tokc);
3440 if (t == TOK_LINENUM) {
3441 file->line_num = tokc.i;
3442 goto redo;
3444 goto convert;
3445 } else if (t == 0) {
3446 /* end of macro or unget token string */
3447 end_macro();
3448 continue;
3449 } else if (t == TOK_EOF) {
3450 /* do nothing */
3451 } else {
3452 ++macro_ptr;
3453 if (t >= TOK_IDENT) {
3454 t &= ~SYM_FIELD; /* remove 'nosubst' marker */
3455 } else if (t == '\\') {
3456 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3457 tcc_error("stray '\\' in program");
3460 tok = t;
3461 return;
3464 next_nomacro();
3465 t = tok;
3466 if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3467 /* if reading from file, try to substitute macros */
3468 Sym *s = define_find(t);
3469 if (s) {
3470 Sym *nested_list = NULL;
3471 macro_subst_tok(&tokstr_buf, &nested_list, s);
3472 tok_str_add(&tokstr_buf, 0);
3473 begin_macro(&tokstr_buf, 0);
3474 goto redo;
3476 return;
3479 convert:
3480 /* convert preprocessor tokens into C tokens */
3481 if (t == TOK_PPNUM) {
3482 if (parse_flags & PARSE_FLAG_TOK_NUM)
3483 parse_number((char *)tokc.str.data);
3484 } else if (t == TOK_PPSTR) {
3485 if (parse_flags & PARSE_FLAG_TOK_STR)
3486 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3490 /* push back current token and set current token to 'last_tok'. Only
3491 identifier case handled for labels. */
3492 ST_INLN void unget_tok(int last_tok)
3494 TokenString *str = &unget_buf;
3495 int alloc = 0;
3496 if (str->len) /* use static buffer except if already in use */
3497 str = tok_str_alloc(), alloc = 1;
3498 if (tok != TOK_EOF)
3499 tok_str_add2(str, tok, &tokc);
3500 tok_str_add(str, 0);
3501 begin_macro(str, alloc);
3502 tok = last_tok;
3505 /* ------------------------------------------------------------------------- */
3506 /* init preprocessor */
3508 static const char * const target_os_defs =
3509 #ifdef TCC_TARGET_PE
3510 "_WIN32\0"
3511 # if PTR_SIZE == 8
3512 "_WIN64\0"
3513 # endif
3514 #else
3515 # if defined TCC_TARGET_MACHO
3516 "__APPLE__\0"
3517 # elif TARGETOS_FreeBSD
3518 "__FreeBSD__ 12\0"
3519 # elif TARGETOS_FreeBSD_kernel
3520 "__FreeBSD_kernel__\0"
3521 # elif TARGETOS_NetBSD
3522 "__NetBSD__\0"
3523 # elif TARGETOS_OpenBSD
3524 "__OpenBSD__\0"
3525 # else
3526 "__linux__\0"
3527 "__linux\0"
3528 # if TARGETOS_ANDROID
3529 "__ANDROID__\0"
3530 # endif
3531 # endif
3532 "__unix__\0"
3533 "__unix\0"
3534 #endif
3537 static void putdef(CString *cs, const char *p)
3539 cstr_printf(cs, "#define %s%s\n", p, &" 1"[!!strchr(p, ' ')*2]);
3542 static void putdefs(CString *cs, const char *p)
3544 while (*p)
3545 putdef(cs, p), p = strchr(p, 0) + 1;
3548 static void tcc_predefs(TCCState *s1, CString *cs, int is_asm)
3550 cstr_printf(cs, "#define __TINYC__ 9%.2s\n", TCC_VERSION + 4);
3551 putdefs(cs, target_machine_defs);
3552 putdefs(cs, target_os_defs);
3554 #ifdef TCC_TARGET_ARM
3555 if (s1->float_abi == ARM_HARD_FLOAT)
3556 putdef(cs, "__ARM_PCS_VFP");
3557 #endif
3558 if (is_asm)
3559 putdef(cs, "__ASSEMBLER__");
3560 if (s1->output_type == TCC_OUTPUT_PREPROCESS)
3561 putdef(cs, "__TCC_PP__");
3562 if (s1->output_type == TCC_OUTPUT_MEMORY)
3563 putdef(cs, "__TCC_RUN__");
3564 #ifdef CONFIG_TCC_BACKTRACE
3565 if (s1->do_backtrace)
3566 putdef(cs, "__TCC_BACKTRACE__");
3567 #endif
3568 #ifdef CONFIG_TCC_BCHECK
3569 if (s1->do_bounds_check)
3570 putdef(cs, "__TCC_BCHECK__");
3571 #endif
3572 if (s1->char_is_unsigned)
3573 putdef(cs, "__CHAR_UNSIGNED__");
3574 if (s1->optimize > 0)
3575 putdef(cs, "__OPTIMIZE__");
3576 if (s1->option_pthread)
3577 putdef(cs, "_REENTRANT");
3578 if (s1->leading_underscore)
3579 putdef(cs, "__leading_underscore");
3580 cstr_printf(cs, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE);
3581 cstr_printf(cs, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE);
3582 if (!is_asm) {
3583 putdef(cs, "__STDC__");
3584 cstr_printf(cs, "#define __STDC_VERSION__ %dL\n", s1->cversion);
3585 cstr_cat(cs,
3586 /* load more predefs and __builtins */
3587 #if CONFIG_TCC_PREDEFS
3588 #include "tccdefs_.h" /* include as strings */
3589 #else
3590 "#include <tccdefs.h>\n" /* load at runtime */
3591 #endif
3592 , -1);
3594 cstr_printf(cs, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3597 ST_FUNC void preprocess_start(TCCState *s1, int filetype)
3599 int is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
3601 tccpp_new(s1);
3603 s1->include_stack_ptr = s1->include_stack;
3604 s1->ifdef_stack_ptr = s1->ifdef_stack;
3605 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3606 pp_expr = 0;
3607 pp_counter = 0;
3608 pp_debug_tok = pp_debug_symv = 0;
3609 s1->pack_stack[0] = 0;
3610 s1->pack_stack_ptr = s1->pack_stack;
3612 set_idnum('$', !is_asm && s1->dollars_in_identifiers ? IS_ID : 0);
3613 set_idnum('.', is_asm ? IS_ID : 0);
3615 if (!(filetype & AFF_TYPE_ASM)) {
3616 CString cstr;
3617 cstr_new(&cstr);
3618 tcc_predefs(s1, &cstr, is_asm);
3619 if (s1->cmdline_defs.size)
3620 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3621 if (s1->cmdline_incl.size)
3622 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3623 //printf("%.*s\n", cstr.size, (char*)cstr.data);
3624 *s1->include_stack_ptr++ = file;
3625 tcc_open_bf(s1, "<command line>", cstr.size);
3626 memcpy(file->buffer, cstr.data, cstr.size);
3627 cstr_free(&cstr);
3629 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3632 /* cleanup from error/setjmp */
3633 ST_FUNC void preprocess_end(TCCState *s1)
3635 while (macro_stack)
3636 end_macro();
3637 macro_ptr = NULL;
3638 while (file)
3639 tcc_close();
3640 tccpp_delete(s1);
3643 ST_FUNC int set_idnum(int c, int val)
3645 int prev = isidnum_table[c - CH_EOF];
3646 isidnum_table[c - CH_EOF] = val;
3647 return prev;
3650 ST_FUNC void tccpp_new(TCCState *s)
3652 int i, c;
3653 const char *p, *r;
3655 /* init isid table */
3656 for(i = CH_EOF; i<128; i++)
3657 set_idnum(i,
3658 is_space(i) ? IS_SPC
3659 : isid(i) ? IS_ID
3660 : isnum(i) ? IS_NUM
3661 : 0);
3663 for(i = 128; i<256; i++)
3664 set_idnum(i, IS_ID);
3666 /* init allocators */
3667 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3668 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3670 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3671 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3673 cstr_new(&tokcstr);
3674 cstr_new(&cstr_buf);
3675 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3676 tok_str_new(&tokstr_buf);
3677 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3678 tok_str_new(&unget_buf);
3680 tok_ident = TOK_IDENT;
3681 p = tcc_keywords;
3682 while (*p) {
3683 r = p;
3684 for(;;) {
3685 c = *r++;
3686 if (c == '\0')
3687 break;
3689 tok_alloc(p, r - p - 1);
3690 p = r;
3693 /* we add dummy defines for some special macros to speed up tests
3694 and to have working defined() */
3695 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3696 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3697 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3698 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3699 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3702 ST_FUNC void tccpp_delete(TCCState *s)
3704 int i, n;
3706 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3708 /* free tokens */
3709 n = tok_ident - TOK_IDENT;
3710 if (n > total_idents)
3711 total_idents = n;
3712 for(i = 0; i < n; i++)
3713 tal_free(toksym_alloc, table_ident[i]);
3714 tcc_free(table_ident);
3715 table_ident = NULL;
3717 /* free static buffers */
3718 cstr_free(&tokcstr);
3719 cstr_free(&cstr_buf);
3720 tok_str_free_str(tokstr_buf.str);
3721 tok_str_free_str(unget_buf.str);
3723 /* free allocators */
3724 tal_delete(toksym_alloc);
3725 toksym_alloc = NULL;
3726 tal_delete(tokstr_alloc);
3727 tokstr_alloc = NULL;
3730 /* ------------------------------------------------------------------------- */
3731 /* tcc -E [-P[1]] [-dD} support */
3733 static int pp_need_space(int a, int b);
3735 static void tok_print(const int *str, const char *msg, ...)
3737 FILE *fp = tcc_state->ppfp;
3738 va_list ap;
3739 int t, t0, s;
3740 CValue cval;
3742 va_start(ap, msg);
3743 vfprintf(fp, msg, ap);
3744 va_end(ap);
3746 s = t0 = 0;
3747 while (str) {
3748 TOK_GET(&t, &str, &cval);
3749 if (t == 0 || t == TOK_EOF)
3750 break;
3751 if (pp_need_space(t0, t))
3752 s = 0;
3753 fprintf(fp, &" %s"[s], t == TOK_PLCHLDR ? "<>" : get_tok_str(t, &cval));
3754 s = 1, t0 = t;
3756 fprintf(fp, "\n");
3759 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3761 int d = f->line_num - f->line_ref;
3763 if (s1->dflag & 4)
3764 return;
3766 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3768 } else if (level == 0 && f->line_ref && d < 8) {
3769 while (d > 0)
3770 fputs("\n", s1->ppfp), --d;
3771 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3772 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3773 } else {
3774 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3775 level > 0 ? " 1" : level < 0 ? " 2" : "");
3777 f->line_ref = f->line_num;
3780 static void define_print(TCCState *s1, int v)
3782 FILE *fp;
3783 Sym *s;
3785 s = define_find(v);
3786 if (NULL == s || NULL == s->d)
3787 return;
3789 fp = s1->ppfp;
3790 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3791 if (s->type.t & MACRO_FUNC) {
3792 Sym *a = s->next;
3793 fprintf(fp,"(");
3794 if (a)
3795 for (;;) {
3796 fprintf(fp,"%s", get_tok_str(a->v, NULL));
3797 if (!(a = a->next))
3798 break;
3799 fprintf(fp,",");
3801 fprintf(fp,")");
3803 tok_print(s->d, "");
3806 static void pp_debug_defines(TCCState *s1)
3808 int v, t;
3809 const char *vs;
3810 FILE *fp;
3812 t = pp_debug_tok;
3813 if (t == 0)
3814 return;
3816 file->line_num--;
3817 pp_line(s1, file, 0);
3818 file->line_ref = ++file->line_num;
3820 fp = s1->ppfp;
3821 v = pp_debug_symv;
3822 vs = get_tok_str(v, NULL);
3823 if (t == TOK_DEFINE) {
3824 define_print(s1, v);
3825 } else if (t == TOK_UNDEF) {
3826 fprintf(fp, "#undef %s\n", vs);
3827 } else if (t == TOK_push_macro) {
3828 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3829 } else if (t == TOK_pop_macro) {
3830 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3832 pp_debug_tok = 0;
3835 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3836 static int pp_need_space(int a, int b)
3838 return 'E' == a ? '+' == b || '-' == b
3839 : '+' == a ? TOK_INC == b || '+' == b
3840 : '-' == a ? TOK_DEC == b || '-' == b
3841 : a >= TOK_IDENT || a == TOK_PPNUM ? b >= TOK_IDENT || b == TOK_PPNUM
3842 : 0;
3845 /* maybe hex like 0x1e */
3846 static int pp_check_he0xE(int t, const char *p)
3848 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3849 return 'E';
3850 return t;
3853 /* Preprocess the current file */
3854 ST_FUNC int tcc_preprocess(TCCState *s1)
3856 BufferedFile **iptr;
3857 int token_seen, spcs, level;
3858 const char *p;
3859 char white[400];
3861 parse_flags = PARSE_FLAG_PREPROCESS
3862 | (parse_flags & PARSE_FLAG_ASM_FILE)
3863 | PARSE_FLAG_LINEFEED
3864 | PARSE_FLAG_SPACES
3865 | PARSE_FLAG_ACCEPT_STRAYS
3867 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3868 capability to compile and run itself, provided all numbers are
3869 given as decimals. tcc -E -P10 will do. */
3870 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3871 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3873 if (s1->do_bench) {
3874 /* for PP benchmarks */
3875 do next(); while (tok != TOK_EOF);
3876 return 0;
3879 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
3880 if (file->prev)
3881 pp_line(s1, file->prev, level++);
3882 pp_line(s1, file, level);
3884 for (;;) {
3885 iptr = s1->include_stack_ptr;
3886 next();
3887 if (tok == TOK_EOF)
3888 break;
3890 level = s1->include_stack_ptr - iptr;
3891 if (level) {
3892 if (level > 0)
3893 pp_line(s1, *iptr, 0);
3894 pp_line(s1, file, level);
3896 if (s1->dflag & 7) {
3897 pp_debug_defines(s1);
3898 if (s1->dflag & 4)
3899 continue;
3902 if (is_space(tok)) {
3903 if (spcs < sizeof white - 1)
3904 white[spcs++] = tok;
3905 continue;
3906 } else if (tok == TOK_LINEFEED) {
3907 spcs = 0;
3908 if (token_seen == TOK_LINEFEED)
3909 continue;
3910 ++file->line_ref;
3911 } else if (token_seen == TOK_LINEFEED) {
3912 pp_line(s1, file, 0);
3913 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
3914 white[spcs++] = ' ';
3917 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
3918 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
3919 token_seen = pp_check_he0xE(tok, p);
3921 return 0;
3924 /* ------------------------------------------------------------------------- */