fix UB in constant folding of double -> signed integer conversion
[tinycc.git] / tccpp.c
blob6f2bc173ba5add26cd24c299033b31779180d616
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);
56 static void parse_number(const char *p);
57 static void parse_string(const char *p, int len);
59 static struct TinyAlloc *toksym_alloc;
60 static struct TinyAlloc *tokstr_alloc;
62 static TokenString *macro_stack;
64 static const char tcc_keywords[] =
65 #define DEF(id, str) str "\0"
66 #include "tcctok.h"
67 #undef DEF
70 /* WARNING: the content of this string encodes token numbers */
71 static const unsigned char tok_two_chars[] =
72 /* outdated -- gr
73 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
74 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
75 */{
76 '<','=', TOK_LE,
77 '>','=', TOK_GE,
78 '!','=', TOK_NE,
79 '&','&', TOK_LAND,
80 '|','|', TOK_LOR,
81 '+','+', TOK_INC,
82 '-','-', TOK_DEC,
83 '=','=', TOK_EQ,
84 '<','<', TOK_SHL,
85 '>','>', TOK_SAR,
86 '+','=', TOK_A_ADD,
87 '-','=', TOK_A_SUB,
88 '*','=', TOK_A_MUL,
89 '/','=', TOK_A_DIV,
90 '%','=', TOK_A_MOD,
91 '&','=', TOK_A_AND,
92 '^','=', TOK_A_XOR,
93 '|','=', TOK_A_OR,
94 '-','>', TOK_ARROW,
95 '.','.', TOK_TWODOTS,
96 '#','#', TOK_TWOSHARPS,
100 ST_FUNC void skip(int c)
102 if (tok != c) {
103 char tmp[40];
104 pstrcpy(tmp, sizeof tmp, get_tok_str(c, &tokc));
105 tcc_error("'%s' expected (got \"%s\")", tmp, get_tok_str(tok, &tokc));
107 next();
110 ST_FUNC void expect(const char *msg)
112 tcc_error("%s expected", msg);
115 /* ------------------------------------------------------------------------- */
116 /* Custom allocator for tiny objects */
118 #define USE_TAL
120 #ifndef USE_TAL
121 #define tal_free(al, p) tcc_free(p)
122 #define tal_realloc(al, p, size) tcc_realloc(p, size)
123 #define tal_new(a,b,c)
124 #define tal_delete(a)
125 #else
126 #if !defined(MEM_DEBUG)
127 #define tal_free(al, p) tal_free_impl(al, p)
128 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
129 #define TAL_DEBUG_PARAMS
130 #else
131 #define TAL_DEBUG MEM_DEBUG
132 //#define TAL_INFO 1 /* collect and dump allocators stats */
133 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
134 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
135 #define TAL_DEBUG_PARAMS , const char *file, int line
136 #define TAL_DEBUG_FILE_LEN 40
137 #endif
139 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
140 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
141 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
142 #define TOKSTR_TAL_LIMIT 1024 /* 256 * sizeof(int) */
144 typedef struct TinyAlloc {
145 unsigned limit;
146 unsigned size;
147 uint8_t *buffer;
148 uint8_t *p;
149 unsigned nb_allocs;
150 struct TinyAlloc *next, *top;
151 #ifdef TAL_INFO
152 unsigned nb_peak;
153 unsigned nb_total;
154 unsigned nb_missed;
155 uint8_t *peak_p;
156 #endif
157 } TinyAlloc;
159 typedef struct tal_header_t {
160 unsigned size;
161 #ifdef TAL_DEBUG
162 int line_num; /* negative line_num used for double free check */
163 char file_name[TAL_DEBUG_FILE_LEN + 1];
164 #endif
165 } tal_header_t;
167 /* ------------------------------------------------------------------------- */
169 static TinyAlloc *tal_new(TinyAlloc **pal, unsigned limit, unsigned size)
171 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
172 al->p = al->buffer = tcc_malloc(size);
173 al->limit = limit;
174 al->size = size;
175 if (pal) *pal = al;
176 return al;
179 static void tal_delete(TinyAlloc *al)
181 TinyAlloc *next;
183 tail_call:
184 if (!al)
185 return;
186 #ifdef TAL_INFO
187 fprintf(stderr, "limit %4d size %7d nb_peak %5d nb_total %7d nb_missed %5d usage %5.1f%%\n",
188 al->limit, al->size, al->nb_peak, al->nb_total, al->nb_missed,
189 (al->peak_p - al->buffer) * 100.0 / al->size);
190 #endif
191 #if TAL_DEBUG && TAL_DEBUG != 3 /* do not check TAL leaks with -DMEM_DEBUG=3 */
192 if (al->nb_allocs > 0) {
193 uint8_t *p;
194 fprintf(stderr, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
195 al->nb_allocs, al->limit);
196 p = al->buffer;
197 while (p < al->p) {
198 tal_header_t *header = (tal_header_t *)p;
199 if (header->line_num > 0) {
200 fprintf(stderr, "%s:%d: chunk of %d bytes leaked\n",
201 header->file_name, header->line_num, header->size);
203 p += header->size + sizeof(tal_header_t);
205 #if TAL_DEBUG == 2
206 exit(2);
207 #endif
209 #endif
210 next = al->next;
211 tcc_free(al->buffer);
212 tcc_free(al);
213 al = next;
214 goto tail_call;
217 static void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
219 if (!p)
220 return;
221 tail_call:
222 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
223 #ifdef TAL_DEBUG
224 tal_header_t *header = (((tal_header_t *)p) - 1);
225 if (header->line_num < 0) {
226 fprintf(stderr, "%s:%d: TAL_DEBUG: double frees chunk from\n",
227 file, line);
228 fprintf(stderr, "%s:%d: %d bytes\n",
229 header->file_name, (int)-header->line_num, (int)header->size);
230 } else
231 header->line_num = -header->line_num;
232 #endif
233 al->nb_allocs--;
234 if (!al->nb_allocs)
235 al->p = al->buffer;
236 } else if (al->next) {
237 al = al->next;
238 goto tail_call;
240 else
241 tcc_free(p);
244 static void *tal_realloc_impl(TinyAlloc **pal, void *p, unsigned size TAL_DEBUG_PARAMS)
246 tal_header_t *header;
247 void *ret;
248 int is_own;
249 unsigned adj_size = (size + 3) & -4;
250 TinyAlloc *al = *pal;
252 tail_call:
253 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
254 if ((!p || is_own) && size <= al->limit) {
255 if (al->p - al->buffer + adj_size + sizeof(tal_header_t) < al->size) {
256 header = (tal_header_t *)al->p;
257 header->size = adj_size;
258 #ifdef TAL_DEBUG
259 { int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
260 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
261 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
262 header->line_num = line; }
263 #endif
264 ret = al->p + sizeof(tal_header_t);
265 al->p += adj_size + sizeof(tal_header_t);
266 if (is_own) {
267 header = (((tal_header_t *)p) - 1);
268 if (p) memcpy(ret, p, header->size);
269 #ifdef TAL_DEBUG
270 header->line_num = -header->line_num;
271 #endif
272 } else {
273 al->nb_allocs++;
275 #ifdef TAL_INFO
276 if (al->nb_peak < al->nb_allocs)
277 al->nb_peak = al->nb_allocs;
278 if (al->peak_p < al->p)
279 al->peak_p = al->p;
280 al->nb_total++;
281 #endif
282 return ret;
283 } else if (is_own) {
284 al->nb_allocs--;
285 ret = tal_realloc(*pal, 0, size);
286 header = (((tal_header_t *)p) - 1);
287 if (p) memcpy(ret, p, header->size);
288 #ifdef TAL_DEBUG
289 header->line_num = -header->line_num;
290 #endif
291 return ret;
293 if (al->next) {
294 al = al->next;
295 } else {
296 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
298 al = tal_new(pal, next->limit, next->size * 2);
299 al->next = next;
300 bottom->top = al;
302 goto tail_call;
304 if (is_own) {
305 al->nb_allocs--;
306 ret = tcc_malloc(size);
307 header = (((tal_header_t *)p) - 1);
308 if (p) memcpy(ret, p, header->size);
309 #ifdef TAL_DEBUG
310 header->line_num = -header->line_num;
311 #endif
312 } else if (al->next) {
313 al = al->next;
314 goto tail_call;
315 } else
316 ret = tcc_realloc(p, size);
317 #ifdef TAL_INFO
318 al->nb_missed++;
319 #endif
320 return ret;
323 #endif /* USE_TAL */
325 /* ------------------------------------------------------------------------- */
326 /* CString handling */
327 static void cstr_realloc(CString *cstr, int new_size)
329 int size;
331 size = cstr->size_allocated;
332 if (size < 8)
333 size = 8; /* no need to allocate a too small first string */
334 while (size < new_size)
335 size = size * 2;
336 cstr->data = tcc_realloc(cstr->data, size);
337 cstr->size_allocated = size;
340 /* add a byte */
341 ST_INLN void cstr_ccat(CString *cstr, int ch)
343 int size;
344 size = cstr->size + 1;
345 if (size > cstr->size_allocated)
346 cstr_realloc(cstr, size);
347 cstr->data[size - 1] = ch;
348 cstr->size = size;
351 ST_INLN char *unicode_to_utf8 (char *b, uint32_t Uc)
353 if (Uc<0x80) *b++=Uc;
354 else if (Uc<0x800) *b++=192+Uc/64, *b++=128+Uc%64;
355 else if (Uc-0xd800u<0x800) goto error;
356 else if (Uc<0x10000) *b++=224+Uc/4096, *b++=128+Uc/64%64, *b++=128+Uc%64;
357 else if (Uc<0x110000) *b++=240+Uc/262144, *b++=128+Uc/4096%64, *b++=128+Uc/64%64, *b++=128+Uc%64;
358 else error: tcc_error("0x%x is not a valid universal character", Uc);
359 return b;
362 /* add a unicode character expanded into utf8 */
363 ST_INLN void cstr_u8cat(CString *cstr, int ch)
365 char buf[4], *e;
366 e = unicode_to_utf8(buf, (uint32_t)ch);
367 cstr_cat(cstr, buf, e - buf);
370 /* add string of 'len', or of its len/len+1 when 'len' == -1/0 */
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(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 *)(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(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 c = *p;
890 switch(c) {
891 case ' ':
892 case '\t':
893 case '\f':
894 case '\v':
895 case '\r':
896 p++;
897 continue;
898 case '\n':
899 file->line_num++;
900 p++;
901 goto redo_start;
902 case '\\':
903 c = handle_bs(&p);
904 if (c == CH_EOF)
905 expect("#endif");
906 if (c == '\\')
907 ++p;
908 continue;
909 /* skip strings */
910 case '\"':
911 case '\'':
912 if (in_warn_or_error)
913 goto _default;
914 tok_flags &= ~TOK_FLAG_BOL;
915 p = parse_pp_string(p, c, NULL);
916 break;
917 /* skip comments */
918 case '/':
919 if (in_warn_or_error)
920 goto _default;
921 ++p;
922 c = handle_bs(&p);
923 if (c == '*') {
924 p = parse_comment(p);
925 } else if (c == '/') {
926 p = parse_line_comment(p);
928 continue;
929 case '#':
930 p++;
931 if (start_of_line) {
932 file->buf_ptr = p;
933 next_nomacro();
934 p = file->buf_ptr;
935 if (a == 0 &&
936 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
937 goto the_end;
938 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
939 a++;
940 else if (tok == TOK_ENDIF)
941 a--;
942 else if( tok == TOK_ERROR || tok == TOK_WARNING)
943 in_warn_or_error = 1;
944 else if (tok == TOK_LINEFEED)
945 goto redo_start;
946 else if (parse_flags & PARSE_FLAG_ASM_FILE)
947 p = parse_line_comment(p - 1);
949 #if !defined(TCC_TARGET_ARM)
950 else if (parse_flags & PARSE_FLAG_ASM_FILE)
951 p = parse_line_comment(p - 1);
952 #else
953 /* ARM assembly uses '#' for constants */
954 #endif
955 break;
956 _default:
957 default:
958 p++;
959 break;
961 start_of_line = 0;
963 the_end: ;
964 file->buf_ptr = p;
967 #if 0
968 /* return the number of additional 'ints' necessary to store the
969 token */
970 static inline int tok_size(const int *p)
972 switch(*p) {
973 /* 4 bytes */
974 case TOK_CINT:
975 case TOK_CUINT:
976 case TOK_CCHAR:
977 case TOK_LCHAR:
978 case TOK_CFLOAT:
979 case TOK_LINENUM:
980 return 1 + 1;
981 case TOK_STR:
982 case TOK_LSTR:
983 case TOK_PPNUM:
984 case TOK_PPSTR:
985 return 1 + 1 + (p[1] + 3) / 4;
986 case TOK_CLONG:
987 case TOK_CULONG:
988 return 1 + LONG_SIZE / 4;
989 case TOK_CDOUBLE:
990 case TOK_CLLONG:
991 case TOK_CULLONG:
992 return 1 + 2;
993 case TOK_CLDOUBLE:
994 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
995 return 1 + 8 / 4;
996 #else
997 return 1 + LDOUBLE_SIZE / 4;
998 #endif
999 default:
1000 return 1 + 0;
1003 #endif
1005 /* token string handling */
1006 ST_INLN void tok_str_new(TokenString *s)
1008 s->str = NULL;
1009 s->len = s->need_spc = 0;
1010 s->allocated_len = 0;
1011 s->last_line_num = -1;
1014 ST_FUNC TokenString *tok_str_alloc(void)
1016 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1017 tok_str_new(str);
1018 return str;
1021 ST_FUNC void tok_str_free_str(int *str)
1023 tal_free(tokstr_alloc, str);
1026 ST_FUNC void tok_str_free(TokenString *str)
1028 tok_str_free_str(str->str);
1029 tal_free(tokstr_alloc, str);
1032 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1034 int *str, size;
1036 size = s->allocated_len;
1037 if (size < 16)
1038 size = 16;
1039 while (size < new_size)
1040 size = size * 2;
1041 if (size > s->allocated_len) {
1042 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1043 s->allocated_len = size;
1044 s->str = str;
1046 return s->str;
1049 ST_FUNC void tok_str_add(TokenString *s, int t)
1051 int len, *str;
1053 len = s->len;
1054 str = s->str;
1055 if (len >= s->allocated_len)
1056 str = tok_str_realloc(s, len + 1);
1057 str[len++] = t;
1058 s->len = len;
1061 ST_FUNC void begin_macro(TokenString *str, int alloc)
1063 str->alloc = alloc;
1064 str->prev = macro_stack;
1065 str->prev_ptr = macro_ptr;
1066 str->save_line_num = file->line_num;
1067 macro_ptr = str->str;
1068 macro_stack = str;
1071 ST_FUNC void end_macro(void)
1073 TokenString *str = macro_stack;
1074 macro_stack = str->prev;
1075 macro_ptr = str->prev_ptr;
1076 file->line_num = str->save_line_num;
1077 if (str->alloc == 0) {
1078 /* matters if str not alloced, may be tokstr_buf */
1079 str->len = str->need_spc = 0;
1080 } else {
1081 if (str->alloc == 2)
1082 str->str = NULL; /* don't free */
1083 tok_str_free(str);
1087 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1089 int len, *str;
1091 len = s->len;
1092 str = s->str;
1094 /* allocate space for worst case */
1095 if (len + TOK_MAX_SIZE >= s->allocated_len)
1096 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1097 str[len++] = t;
1098 switch(t) {
1099 case TOK_CINT:
1100 case TOK_CUINT:
1101 case TOK_CCHAR:
1102 case TOK_LCHAR:
1103 case TOK_CFLOAT:
1104 case TOK_LINENUM:
1105 #if LONG_SIZE == 4
1106 case TOK_CLONG:
1107 case TOK_CULONG:
1108 #endif
1109 str[len++] = cv->tab[0];
1110 break;
1111 case TOK_PPNUM:
1112 case TOK_PPSTR:
1113 case TOK_STR:
1114 case TOK_LSTR:
1116 /* Insert the string into the int array. */
1117 size_t nb_words =
1118 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1119 if (len + nb_words >= s->allocated_len)
1120 str = tok_str_realloc(s, len + nb_words + 1);
1121 str[len] = cv->str.size;
1122 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1123 len += nb_words;
1125 break;
1126 case TOK_CDOUBLE:
1127 case TOK_CLLONG:
1128 case TOK_CULLONG:
1129 #if LONG_SIZE == 8
1130 case TOK_CLONG:
1131 case TOK_CULONG:
1132 #endif
1133 str[len++] = cv->tab[0];
1134 str[len++] = cv->tab[1];
1135 break;
1136 case TOK_CLDOUBLE:
1137 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1138 str[len++] = cv->tab[0];
1139 str[len++] = cv->tab[1];
1140 #elif LDOUBLE_SIZE == 12
1141 str[len++] = cv->tab[0];
1142 str[len++] = cv->tab[1];
1143 str[len++] = cv->tab[2];
1144 #elif LDOUBLE_SIZE == 16
1145 str[len++] = cv->tab[0];
1146 str[len++] = cv->tab[1];
1147 str[len++] = cv->tab[2];
1148 str[len++] = cv->tab[3];
1149 #else
1150 #error add long double size support
1151 #endif
1152 break;
1153 default:
1154 break;
1156 s->len = len;
1159 /* add the current parse token in token string 's' */
1160 ST_FUNC void tok_str_add_tok(TokenString *s)
1162 CValue cval;
1164 /* save line number info */
1165 if (file->line_num != s->last_line_num) {
1166 s->last_line_num = file->line_num;
1167 cval.i = s->last_line_num;
1168 tok_str_add2(s, TOK_LINENUM, &cval);
1170 tok_str_add2(s, tok, &tokc);
1173 /* like tok_str_add2(), add a space if needed */
1174 static void tok_str_add2_spc(TokenString *s, int t, CValue *cv)
1176 if (s->need_spc == 3)
1177 tok_str_add(s, ' ');
1178 s->need_spc = 2;
1179 tok_str_add2(s, t, cv);
1182 /* get a token from an integer array and increment pointer. */
1183 static inline void tok_get(int *t, const int **pp, CValue *cv)
1185 const int *p = *pp;
1186 int n, *tab;
1188 tab = cv->tab;
1189 switch(*t = *p++) {
1190 #if LONG_SIZE == 4
1191 case TOK_CLONG:
1192 #endif
1193 case TOK_CINT:
1194 case TOK_CCHAR:
1195 case TOK_LCHAR:
1196 case TOK_LINENUM:
1197 cv->i = *p++;
1198 break;
1199 #if LONG_SIZE == 4
1200 case TOK_CULONG:
1201 #endif
1202 case TOK_CUINT:
1203 cv->i = (unsigned)*p++;
1204 break;
1205 case TOK_CFLOAT:
1206 tab[0] = *p++;
1207 break;
1208 case TOK_STR:
1209 case TOK_LSTR:
1210 case TOK_PPNUM:
1211 case TOK_PPSTR:
1212 cv->str.size = *p++;
1213 cv->str.data = (char*)p;
1214 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1215 break;
1216 case TOK_CDOUBLE:
1217 case TOK_CLLONG:
1218 case TOK_CULLONG:
1219 #if LONG_SIZE == 8
1220 case TOK_CLONG:
1221 case TOK_CULONG:
1222 #endif
1223 n = 2;
1224 goto copy;
1225 case TOK_CLDOUBLE:
1226 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1227 n = 2;
1228 #elif LDOUBLE_SIZE == 12
1229 n = 3;
1230 #elif LDOUBLE_SIZE == 16
1231 n = 4;
1232 #else
1233 # error add long double size support
1234 #endif
1235 copy:
1237 *tab++ = *p++;
1238 while (--n);
1239 break;
1240 default:
1241 break;
1243 *pp = p;
1246 #if 0
1247 # define TOK_GET(t,p,c) tok_get(t,p,c)
1248 #else
1249 # define TOK_GET(t,p,c) do { \
1250 int _t = **(p); \
1251 if (TOK_HAS_VALUE(_t)) \
1252 tok_get(t, p, c); \
1253 else \
1254 *(t) = _t, ++*(p); \
1255 } while (0)
1256 #endif
1258 static int macro_is_equal(const int *a, const int *b)
1260 CValue cv;
1261 int t;
1263 if (!a || !b)
1264 return 1;
1266 while (*a && *b) {
1267 cstr_reset(&tokcstr);
1268 TOK_GET(&t, &a, &cv);
1269 cstr_cat(&tokcstr, get_tok_str(t, &cv), 0);
1270 TOK_GET(&t, &b, &cv);
1271 if (strcmp(tokcstr.data, get_tok_str(t, &cv)))
1272 return 0;
1274 return !(*a || *b);
1277 /* defines handling */
1278 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1280 Sym *s, *o;
1282 o = define_find(v);
1283 s = sym_push2(&define_stack, v, macro_type, 0);
1284 s->d = str;
1285 s->next = first_arg;
1286 table_ident[v - TOK_IDENT]->sym_define = s;
1288 if (o && !macro_is_equal(o->d, s->d))
1289 tcc_warning("%s redefined", get_tok_str(v, NULL));
1292 /* undefined a define symbol. Its name is just set to zero */
1293 ST_FUNC void define_undef(Sym *s)
1295 int v = s->v;
1296 if (v >= TOK_IDENT && v < tok_ident)
1297 table_ident[v - TOK_IDENT]->sym_define = NULL;
1300 ST_INLN Sym *define_find(int v)
1302 v -= TOK_IDENT;
1303 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1304 return NULL;
1305 return table_ident[v]->sym_define;
1308 /* free define stack until top reaches 'b' */
1309 ST_FUNC void free_defines(Sym *b)
1311 while (define_stack != b) {
1312 Sym *top = define_stack;
1313 define_stack = top->prev;
1314 tok_str_free_str(top->d);
1315 define_undef(top);
1316 sym_free(top);
1320 /* fake the nth "#if defined test_..." for tcc -dt -run */
1321 static void maybe_run_test(TCCState *s)
1323 const char *p;
1324 if (s->include_stack_ptr != s->include_stack)
1325 return;
1326 p = get_tok_str(tok, NULL);
1327 if (0 != memcmp(p, "test_", 5))
1328 return;
1329 if (0 != --s->run_test)
1330 return;
1331 fprintf(s->ppfp, &"\n[%s]\n"[!(s->dflag & 32)], p), fflush(s->ppfp);
1332 define_push(tok, MACRO_OBJ, NULL, NULL);
1335 ST_FUNC void skip_to_eol(int warn)
1337 if (tok == TOK_LINEFEED)
1338 return;
1339 if (warn)
1340 tcc_warning("extra tokens after directive");
1341 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
1342 tok = TOK_LINEFEED;
1345 static CachedInclude *
1346 search_cached_include(TCCState *s1, const char *filename, int add);
1348 static int parse_include(TCCState *s1, int do_next, int test)
1350 int c, i;
1351 char name[1024], buf[1024], *p;
1352 CachedInclude *e;
1354 c = skip_spaces();
1355 if (c == '<' || c == '\"') {
1356 cstr_reset(&tokcstr);
1357 file->buf_ptr = parse_pp_string(file->buf_ptr, c == '<' ? '>' : c, &tokcstr);
1358 i = tokcstr.size;
1359 pstrncpy(name, tokcstr.data, i >= sizeof name ? sizeof name - 1 : i);
1360 next_nomacro();
1361 } else {
1362 /* computed #include : concatenate tokens until result is one of
1363 the two accepted forms. Don't convert pp-tokens to tokens here. */
1364 parse_flags = PARSE_FLAG_PREPROCESS
1365 | PARSE_FLAG_LINEFEED
1366 | (parse_flags & PARSE_FLAG_ASM_FILE);
1367 name[0] = 0;
1368 for (;;) {
1369 next();
1370 p = name, i = strlen(p) - 1;
1371 if (i > 0
1372 && ((p[0] == '"' && p[i] == '"')
1373 || (p[0] == '<' && p[i] == '>')))
1374 break;
1375 if (tok == TOK_LINEFEED)
1376 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1377 pstrcat(name, sizeof name, get_tok_str(tok, &tokc));
1379 c = p[0];
1380 /* remove '<>|""' */
1381 memmove(p, p + 1, i - 1), p[i - 1] = 0;
1384 if (!test)
1385 skip_to_eol(1);
1387 i = do_next ? file->include_next_index : -1;
1388 for (;;) {
1389 ++i;
1390 if (i == 0) {
1391 /* check absolute include path */
1392 if (!IS_ABSPATH(name))
1393 continue;
1394 buf[0] = '\0';
1395 } else if (i == 1) {
1396 /* search in file's dir if "header.h" */
1397 if (c != '\"')
1398 continue;
1399 p = file->true_filename;
1400 pstrncpy(buf, p, tcc_basename(p) - p);
1401 } else {
1402 int j = i - 2, k = j - s1->nb_include_paths;
1403 if (k < 0)
1404 p = s1->include_paths[j];
1405 else if (k < s1->nb_sysinclude_paths)
1406 p = s1->sysinclude_paths[k];
1407 else if (test)
1408 return 0;
1409 else
1410 tcc_error("include file '%s' not found", name);
1411 pstrcpy(buf, sizeof buf, p);
1412 pstrcat(buf, sizeof buf, "/");
1414 pstrcat(buf, sizeof buf, name);
1415 e = search_cached_include(s1, buf, 0);
1416 if (e && (define_find(e->ifndef_macro) || e->once)) {
1417 /* no need to parse the include because the 'ifndef macro'
1418 is defined (or had #pragma once) */
1419 #ifdef INC_DEBUG
1420 printf("%s: skipping cached %s\n", file->filename, buf);
1421 #endif
1422 return 1;
1424 if (tcc_open(s1, buf) >= 0)
1425 break;
1428 if (test) {
1429 tcc_close();
1430 } else {
1431 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1432 tcc_error("#include recursion too deep");
1433 /* push previous file on stack */
1434 *s1->include_stack_ptr++ = file->prev;
1435 file->include_next_index = i;
1436 #ifdef INC_DEBUG
1437 printf("%s: including %s\n", file->prev->filename, file->filename);
1438 #endif
1439 /* update target deps */
1440 if (s1->gen_deps) {
1441 BufferedFile *bf = file;
1442 while (i == 1 && (bf = bf->prev))
1443 i = bf->include_next_index;
1444 /* skip system include files */
1445 if (s1->include_sys_deps || i - 2 < s1->nb_include_paths)
1446 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1447 tcc_strdup(buf));
1449 /* add include file debug info */
1450 tcc_debug_bincl(s1);
1452 return 1;
1455 /* eval an expression for #if/#elif */
1456 static int expr_preprocess(TCCState *s1)
1458 int c, t;
1459 int t0 = tok;
1460 TokenString *str;
1462 str = tok_str_alloc();
1463 pp_expr = 1;
1464 while (1) {
1465 next(); /* do macro subst */
1466 t = tok;
1467 if (tok < TOK_IDENT) {
1468 if (tok == TOK_LINEFEED || tok == TOK_EOF)
1469 break;
1470 if (tok >= TOK_STR && tok <= TOK_CLDOUBLE)
1471 tcc_error("invalid constant in preprocessor expression");
1473 } else if (tok == TOK_DEFINED) {
1474 parse_flags &= ~PARSE_FLAG_PREPROCESS; /* no macro subst */
1475 next();
1476 t = tok;
1477 if (t == '(')
1478 next();
1479 parse_flags |= PARSE_FLAG_PREPROCESS;
1480 if (tok < TOK_IDENT)
1481 expect("identifier after 'defined'");
1482 if (s1->run_test)
1483 maybe_run_test(s1);
1484 c = 0;
1485 if (define_find(tok)
1486 || tok == TOK___HAS_INCLUDE
1487 || tok == TOK___HAS_INCLUDE_NEXT)
1488 c = 1;
1489 if (t == '(') {
1490 next();
1491 if (tok != ')')
1492 expect("')'");
1494 tok = TOK_CINT;
1495 tokc.i = c;
1496 } else if (tok == TOK___HAS_INCLUDE ||
1497 tok == TOK___HAS_INCLUDE_NEXT) {
1498 t = tok;
1499 next();
1500 if (tok != '(')
1501 expect("'('");
1502 c = parse_include(s1, t - TOK___HAS_INCLUDE, 1);
1503 if (tok != ')')
1504 expect("')'");
1505 tok = TOK_CINT;
1506 tokc.i = c;
1507 } else {
1508 /* if undefined macro, replace with zero */
1509 tok = TOK_CINT;
1510 tokc.i = 0;
1512 tok_str_add_tok(str);
1514 if (0 == str->len)
1515 tcc_error("#%s with no expression", get_tok_str(t0, 0));
1516 tok_str_add(str, TOK_EOF); /* simulate end of file */
1517 pp_expr = t0; /* redirect pre-processor expression error messages */
1518 t = tok;
1519 /* now evaluate C constant expression */
1520 begin_macro(str, 1);
1521 next();
1522 c = expr_const();
1523 if (tok != TOK_EOF)
1524 tcc_error("...");
1525 pp_expr = 0;
1526 end_macro();
1527 tok = t; /* restore LF or EOF */
1528 return c != 0;
1531 ST_FUNC void pp_error(CString *cs)
1533 cstr_printf(cs, "bad preprocessor expression: #%s", get_tok_str(pp_expr, 0));
1534 macro_ptr = macro_stack->str;
1535 while (next(), tok != TOK_EOF)
1536 cstr_printf(cs, " %s", get_tok_str(tok, &tokc));
1539 /* parse after #define */
1540 ST_FUNC void parse_define(void)
1542 Sym *s, *first, **ps;
1543 int v, t, varg, is_vaargs, t0;
1544 int saved_parse_flags = parse_flags;
1545 TokenString str;
1547 v = tok;
1548 if (v < TOK_IDENT || v == TOK_DEFINED)
1549 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1550 first = NULL;
1551 t = MACRO_OBJ;
1552 /* We have to parse the whole define as if not in asm mode, in particular
1553 no line comment with '#' must be ignored. Also for function
1554 macros the argument list must be parsed without '.' being an ID
1555 character. */
1556 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1557 /* '(' must be just after macro definition for MACRO_FUNC */
1558 next_nomacro();
1559 parse_flags &= ~PARSE_FLAG_SPACES;
1560 is_vaargs = 0;
1561 if (tok == '(') {
1562 int dotid = set_idnum('.', 0);
1563 next_nomacro();
1564 ps = &first;
1565 if (tok != ')') for (;;) {
1566 varg = tok;
1567 next_nomacro();
1568 is_vaargs = 0;
1569 if (varg == TOK_DOTS) {
1570 varg = TOK___VA_ARGS__;
1571 is_vaargs = 1;
1572 } else if (tok == TOK_DOTS && gnu_ext) {
1573 is_vaargs = 1;
1574 next_nomacro();
1576 if (varg < TOK_IDENT)
1577 bad_list:
1578 tcc_error("bad macro parameter list");
1579 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1580 *ps = s;
1581 ps = &s->next;
1582 if (tok == ')')
1583 break;
1584 if (tok != ',' || is_vaargs)
1585 goto bad_list;
1586 next_nomacro();
1588 parse_flags |= PARSE_FLAG_SPACES;
1589 next_nomacro();
1590 t = MACRO_FUNC;
1591 set_idnum('.', dotid);
1594 /* The body of a macro definition should be parsed such that identifiers
1595 are parsed like the file mode determines (i.e. with '.' being an
1596 ID character in asm mode). But '#' should be retained instead of
1597 regarded as line comment leader, so still don't set ASM_FILE
1598 in parse_flags. */
1599 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1600 tok_str_new(&str);
1601 t0 = 0;
1602 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1603 if (is_space(tok)) {
1604 str.need_spc |= 1;
1605 } else {
1606 if (TOK_TWOSHARPS == tok) {
1607 if (0 == t0)
1608 goto bad_twosharp;
1609 tok = TOK_PPJOIN;
1610 t |= MACRO_JOIN;
1612 tok_str_add2_spc(&str, tok, &tokc);
1613 t0 = tok;
1615 next_nomacro();
1617 parse_flags = saved_parse_flags;
1618 tok_str_add(&str, 0);
1619 if (t0 == TOK_PPJOIN)
1620 bad_twosharp:
1621 tcc_error("'##' cannot appear at either end of macro");
1622 define_push(v, t, str.str, first);
1623 //tok_print(str.str, "#define (%d) %s %d:", t | is_vaargs * 4, get_tok_str(v, 0));
1626 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1628 const char *s, *basename;
1629 unsigned int h;
1630 CachedInclude *e;
1631 int c, i, len;
1633 s = basename = tcc_basename(filename);
1634 h = TOK_HASH_INIT;
1635 while ((c = (unsigned char)*s) != 0) {
1636 #ifdef _WIN32
1637 h = TOK_HASH_FUNC(h, toup(c));
1638 #else
1639 h = TOK_HASH_FUNC(h, c);
1640 #endif
1641 s++;
1643 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1645 i = s1->cached_includes_hash[h];
1646 for(;;) {
1647 if (i == 0)
1648 break;
1649 e = s1->cached_includes[i - 1];
1650 if (0 == PATHCMP(filename, e->filename))
1651 return e;
1652 if (e->once
1653 && 0 == PATHCMP(basename, tcc_basename(e->filename))
1654 && 0 == normalized_PATHCMP(filename, e->filename)
1656 return e;
1657 i = e->hash_next;
1659 if (!add)
1660 return NULL;
1662 e = tcc_malloc(sizeof(CachedInclude) + (len = strlen(filename)));
1663 memcpy(e->filename, filename, len + 1);
1664 e->ifndef_macro = e->once = 0;
1665 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1666 /* add in hash table */
1667 e->hash_next = s1->cached_includes_hash[h];
1668 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1669 #ifdef INC_DEBUG
1670 printf("adding cached '%s'\n", filename);
1671 #endif
1672 return e;
1675 static int pragma_parse(TCCState *s1)
1677 next_nomacro();
1678 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1679 int t = tok, v;
1680 Sym *s;
1682 if (next(), tok != '(')
1683 goto pragma_err;
1684 if (next(), tok != TOK_STR)
1685 goto pragma_err;
1686 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1687 if (next(), tok != ')')
1688 goto pragma_err;
1689 if (t == TOK_push_macro) {
1690 while (NULL == (s = define_find(v)))
1691 define_push(v, 0, NULL, NULL);
1692 s->type.ref = s; /* set push boundary */
1693 } else {
1694 for (s = define_stack; s; s = s->prev)
1695 if (s->v == v && s->type.ref == s) {
1696 s->type.ref = NULL;
1697 break;
1700 if (s)
1701 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1702 else
1703 tcc_warning("unbalanced #pragma pop_macro");
1704 pp_debug_tok = t, pp_debug_symv = v;
1706 } else if (tok == TOK_once) {
1707 search_cached_include(s1, file->true_filename, 1)->once = 1;
1709 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1710 /* tcc -E: keep pragmas below unchanged */
1711 unget_tok(' ');
1712 unget_tok(TOK_PRAGMA);
1713 unget_tok('#');
1714 unget_tok(TOK_LINEFEED);
1715 return 1;
1717 } else if (tok == TOK_pack) {
1718 /* This may be:
1719 #pragma pack(1) // set
1720 #pragma pack() // reset to default
1721 #pragma pack(push) // push current
1722 #pragma pack(push,1) // push & set
1723 #pragma pack(pop) // restore previous */
1724 next();
1725 skip('(');
1726 if (tok == TOK_ASM_pop) {
1727 next();
1728 if (s1->pack_stack_ptr <= s1->pack_stack) {
1729 stk_error:
1730 tcc_error("out of pack stack");
1732 s1->pack_stack_ptr--;
1733 } else {
1734 int val = 0;
1735 if (tok != ')') {
1736 if (tok == TOK_ASM_push) {
1737 next();
1738 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1739 goto stk_error;
1740 val = *s1->pack_stack_ptr++;
1741 if (tok != ',')
1742 goto pack_set;
1743 next();
1745 if (tok != TOK_CINT)
1746 goto pragma_err;
1747 val = tokc.i;
1748 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1749 goto pragma_err;
1750 next();
1752 pack_set:
1753 *s1->pack_stack_ptr = val;
1755 if (tok != ')')
1756 goto pragma_err;
1758 } else if (tok == TOK_comment) {
1759 char *p; int t;
1760 next();
1761 skip('(');
1762 t = tok;
1763 next();
1764 skip(',');
1765 if (tok != TOK_STR)
1766 goto pragma_err;
1767 p = tcc_strdup(tokc.str.data);
1768 next();
1769 if (tok != ')')
1770 goto pragma_err;
1771 if (t == TOK_lib) {
1772 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1773 } else {
1774 if (t == TOK_option)
1775 tcc_set_options(s1, p);
1776 tcc_free(p);
1779 } else {
1780 tcc_warning_c(warn_all)("#pragma %s ignored", get_tok_str(tok, &tokc));
1781 return 0;
1783 next();
1784 return 1;
1785 pragma_err:
1786 tcc_error("malformed #pragma directive");
1789 /* put alternative filename */
1790 ST_FUNC void tccpp_putfile(const char *filename)
1792 char buf[1024];
1793 buf[0] = 0;
1794 if (!IS_ABSPATH(filename)) {
1795 /* prepend directory from real file */
1796 pstrcpy(buf, sizeof buf, file->true_filename);
1797 *tcc_basename(buf) = 0;
1799 pstrcat(buf, sizeof buf, filename);
1800 #ifdef _WIN32
1801 normalize_slashes(buf);
1802 #endif
1803 if (0 == strcmp(file->filename, buf))
1804 return;
1805 //printf("new file '%s'\n", buf);
1806 if (file->true_filename == file->filename)
1807 file->true_filename = tcc_strdup(file->filename);
1808 pstrcpy(file->filename, sizeof file->filename, buf);
1809 tcc_debug_newfile(tcc_state);
1812 /* is_bof is true if first non space token at beginning of file */
1813 ST_FUNC void preprocess(int is_bof)
1815 TCCState *s1 = tcc_state;
1816 int c, n, saved_parse_flags;
1817 char buf[1024], *q;
1818 Sym *s;
1820 saved_parse_flags = parse_flags;
1821 parse_flags = PARSE_FLAG_PREPROCESS
1822 | PARSE_FLAG_TOK_NUM
1823 | PARSE_FLAG_TOK_STR
1824 | PARSE_FLAG_LINEFEED
1825 | (parse_flags & PARSE_FLAG_ASM_FILE)
1828 next_nomacro();
1829 redo:
1830 switch(tok) {
1831 case TOK_DEFINE:
1832 pp_debug_tok = tok;
1833 next_nomacro();
1834 pp_debug_symv = tok;
1835 parse_define();
1836 break;
1837 case TOK_UNDEF:
1838 pp_debug_tok = tok;
1839 next_nomacro();
1840 pp_debug_symv = tok;
1841 s = define_find(tok);
1842 /* undefine symbol by putting an invalid name */
1843 if (s)
1844 define_undef(s);
1845 next_nomacro();
1846 break;
1847 case TOK_INCLUDE:
1848 case TOK_INCLUDE_NEXT:
1849 parse_include(s1, tok - TOK_INCLUDE, 0);
1850 goto the_end;
1851 case TOK_IFNDEF:
1852 c = 1;
1853 goto do_ifdef;
1854 case TOK_IF:
1855 c = expr_preprocess(s1);
1856 goto do_if;
1857 case TOK_IFDEF:
1858 c = 0;
1859 do_ifdef:
1860 next_nomacro();
1861 if (tok < TOK_IDENT)
1862 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1863 if (is_bof) {
1864 if (c) {
1865 #ifdef INC_DEBUG
1866 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1867 #endif
1868 file->ifndef_macro = tok;
1871 if (define_find(tok)
1872 || tok == TOK___HAS_INCLUDE
1873 || tok == TOK___HAS_INCLUDE_NEXT)
1874 c ^= 1;
1875 next_nomacro();
1876 do_if:
1877 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1878 tcc_error("memory full (ifdef)");
1879 *s1->ifdef_stack_ptr++ = c;
1880 goto test_skip;
1881 case TOK_ELSE:
1882 next_nomacro();
1883 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1884 tcc_error("#else without matching #if");
1885 if (s1->ifdef_stack_ptr[-1] & 2)
1886 tcc_error("#else after #else");
1887 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1888 goto test_else;
1889 case TOK_ELIF:
1890 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1891 tcc_error("#elif without matching #if");
1892 c = s1->ifdef_stack_ptr[-1];
1893 if (c > 1)
1894 tcc_error("#elif after #else");
1895 /* last #if/#elif expression was true: we skip */
1896 if (c == 1) {
1897 skip_to_eol(0);
1898 c = 0;
1899 } else {
1900 c = expr_preprocess(s1);
1901 s1->ifdef_stack_ptr[-1] = c;
1903 test_else:
1904 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1905 file->ifndef_macro = 0;
1906 test_skip:
1907 if (!(c & 1)) {
1908 skip_to_eol(1);
1909 preprocess_skip();
1910 is_bof = 0;
1911 goto redo;
1913 break;
1914 case TOK_ENDIF:
1915 next_nomacro();
1916 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1917 tcc_error("#endif without matching #if");
1918 s1->ifdef_stack_ptr--;
1919 /* '#ifndef macro' was at the start of file. Now we check if
1920 an '#endif' is exactly at the end of file */
1921 if (file->ifndef_macro &&
1922 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1923 file->ifndef_macro_saved = file->ifndef_macro;
1924 /* need to set to zero to avoid false matches if another
1925 #ifndef at middle of file */
1926 file->ifndef_macro = 0;
1927 tok_flags |= TOK_FLAG_ENDIF;
1929 break;
1930 case TOK_LINE:
1931 next_nomacro();
1932 if (tok != TOK_PPNUM)
1933 _line_err:
1934 tcc_error("wrong #line format");
1935 case TOK_PPNUM:
1936 parse_number(tokc.str.data);
1937 n = tokc.i;
1938 next_nomacro();
1939 if (tok != TOK_LINEFEED) {
1940 if (tok == TOK_PPSTR && tokc.str.data[0] == '"') {
1941 tokc.str.data[tokc.str.size - 2] = 0;
1942 tccpp_putfile(tokc.str.data + 1);
1943 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
1944 goto ignore;
1945 else
1946 goto _line_err;
1947 next_nomacro();
1949 if (file->fd > 0)
1950 total_lines += file->line_num - n;
1951 file->line_num = n;
1952 goto ignore; /* skip optional level number */
1954 case TOK_ERROR:
1955 case TOK_WARNING:
1957 q = buf;
1958 c = skip_spaces();
1959 while (c != '\n' && c != CH_EOF) {
1960 if ((q - buf) < sizeof(buf) - 1)
1961 *q++ = c;
1962 c = ninp();
1964 *q = '\0';
1965 if (tok == TOK_ERROR)
1966 tcc_error("#error %s", buf);
1967 else
1968 tcc_warning("#warning %s", buf);
1969 next_nomacro();
1970 break;
1972 case TOK_PRAGMA:
1973 if (!pragma_parse(s1))
1974 goto ignore;
1975 break;
1976 case TOK_LINEFEED:
1977 goto the_end;
1978 default:
1979 /* ignore gas line comment in an 'S' file. */
1980 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1981 goto ignore;
1982 if (tok == '!' && is_bof)
1983 /* '#!' is ignored at beginning to allow C scripts. */
1984 goto ignore;
1985 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1986 ignore:
1987 skip_to_eol(0);
1988 goto the_end;
1990 skip_to_eol(1);
1991 the_end:
1992 parse_flags = saved_parse_flags;
1995 /* evaluate escape codes in a string. */
1996 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1998 int c, n, i;
1999 const uint8_t *p;
2001 p = buf;
2002 for(;;) {
2003 c = *p;
2004 if (c == '\0')
2005 break;
2006 if (c == '\\') {
2007 p++;
2008 /* escape */
2009 c = *p;
2010 switch(c) {
2011 case '0': case '1': case '2': case '3':
2012 case '4': case '5': case '6': case '7':
2013 /* at most three octal digits */
2014 n = c - '0';
2015 p++;
2016 c = *p;
2017 if (isoct(c)) {
2018 n = n * 8 + c - '0';
2019 p++;
2020 c = *p;
2021 if (isoct(c)) {
2022 n = n * 8 + c - '0';
2023 p++;
2026 c = n;
2027 goto add_char_nonext;
2028 case 'x': i = 0; goto parse_hex_or_ucn;
2029 case 'u': i = 4; goto parse_hex_or_ucn;
2030 case 'U': i = 8; goto parse_hex_or_ucn;
2031 parse_hex_or_ucn:
2032 p++;
2033 n = 0;
2034 do {
2035 c = *p;
2036 if (c >= 'a' && c <= 'f')
2037 c = c - 'a' + 10;
2038 else if (c >= 'A' && c <= 'F')
2039 c = c - 'A' + 10;
2040 else if (isnum(c))
2041 c = c - '0';
2042 else if (i >= 0)
2043 expect("more hex digits in universal-character-name");
2044 else
2045 goto add_hex_or_ucn;
2046 n = n * 16 + c;
2047 p++;
2048 } while (--i);
2049 if (is_long) {
2050 add_hex_or_ucn:
2051 c = n;
2052 goto add_char_nonext;
2054 cstr_u8cat(outstr, n);
2055 continue;
2056 case 'a':
2057 c = '\a';
2058 break;
2059 case 'b':
2060 c = '\b';
2061 break;
2062 case 'f':
2063 c = '\f';
2064 break;
2065 case 'n':
2066 c = '\n';
2067 break;
2068 case 'r':
2069 c = '\r';
2070 break;
2071 case 't':
2072 c = '\t';
2073 break;
2074 case 'v':
2075 c = '\v';
2076 break;
2077 case 'e':
2078 if (!gnu_ext)
2079 goto invalid_escape;
2080 c = 27;
2081 break;
2082 case '\'':
2083 case '\"':
2084 case '\\':
2085 case '?':
2086 break;
2087 default:
2088 invalid_escape:
2089 if (c >= '!' && c <= '~')
2090 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2091 else
2092 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2093 break;
2095 } else if (is_long && c >= 0x80) {
2096 /* assume we are processing UTF-8 sequence */
2097 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2099 int cont; /* count of continuation bytes */
2100 int skip; /* how many bytes should skip when error occurred */
2101 int i;
2103 /* decode leading byte */
2104 if (c < 0xC2) {
2105 skip = 1; goto invalid_utf8_sequence;
2106 } else if (c <= 0xDF) {
2107 cont = 1; n = c & 0x1f;
2108 } else if (c <= 0xEF) {
2109 cont = 2; n = c & 0xf;
2110 } else if (c <= 0xF4) {
2111 cont = 3; n = c & 0x7;
2112 } else {
2113 skip = 1; goto invalid_utf8_sequence;
2116 /* decode continuation bytes */
2117 for (i = 1; i <= cont; i++) {
2118 int l = 0x80, h = 0xBF;
2120 /* adjust limit for second byte */
2121 if (i == 1) {
2122 switch (c) {
2123 case 0xE0: l = 0xA0; break;
2124 case 0xED: h = 0x9F; break;
2125 case 0xF0: l = 0x90; break;
2126 case 0xF4: h = 0x8F; break;
2130 if (p[i] < l || p[i] > h) {
2131 skip = i; goto invalid_utf8_sequence;
2134 n = (n << 6) | (p[i] & 0x3f);
2137 /* advance pointer */
2138 p += 1 + cont;
2139 c = n;
2140 goto add_char_nonext;
2142 /* error handling */
2143 invalid_utf8_sequence:
2144 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2145 c = 0xFFFD;
2146 p += skip;
2147 goto add_char_nonext;
2150 p++;
2151 add_char_nonext:
2152 if (!is_long)
2153 cstr_ccat(outstr, c);
2154 else {
2155 #ifdef TCC_TARGET_PE
2156 /* store as UTF-16 */
2157 if (c < 0x10000) {
2158 cstr_wccat(outstr, c);
2159 } else {
2160 c -= 0x10000;
2161 cstr_wccat(outstr, (c >> 10) + 0xD800);
2162 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2164 #else
2165 cstr_wccat(outstr, c);
2166 #endif
2169 /* add a trailing '\0' */
2170 if (!is_long)
2171 cstr_ccat(outstr, '\0');
2172 else
2173 cstr_wccat(outstr, '\0');
2176 static void parse_string(const char *s, int len)
2178 uint8_t buf[1000], *p = buf;
2179 int is_long, sep;
2181 if ((is_long = *s == 'L'))
2182 ++s, --len;
2183 sep = *s++;
2184 len -= 2;
2185 if (len >= sizeof buf)
2186 p = tcc_malloc(len + 1);
2187 memcpy(p, s, len);
2188 p[len] = 0;
2190 cstr_reset(&tokcstr);
2191 parse_escape_string(&tokcstr, p, is_long);
2192 if (p != buf)
2193 tcc_free(p);
2195 if (sep == '\'') {
2196 int char_size, i, n, c;
2197 /* XXX: make it portable */
2198 if (!is_long)
2199 tok = TOK_CCHAR, char_size = 1;
2200 else
2201 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2202 n = tokcstr.size / char_size - 1;
2203 if (n < 1)
2204 tcc_error("empty character constant");
2205 if (n > 1)
2206 tcc_warning_c(warn_all)("multi-character character constant");
2207 for (c = i = 0; i < n; ++i) {
2208 if (is_long)
2209 c = ((nwchar_t *)tokcstr.data)[i];
2210 else
2211 c = (c << 8) | ((char *)tokcstr.data)[i];
2213 tokc.i = c;
2214 } else {
2215 tokc.str.size = tokcstr.size;
2216 tokc.str.data = tokcstr.data;
2217 if (!is_long)
2218 tok = TOK_STR;
2219 else
2220 tok = TOK_LSTR;
2224 /* we use 64 bit numbers */
2225 #define BN_SIZE 2
2227 /* bn = (bn << shift) | or_val */
2228 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2230 int i;
2231 unsigned int v;
2232 for(i=0;i<BN_SIZE;i++) {
2233 v = bn[i];
2234 bn[i] = (v << shift) | or_val;
2235 or_val = v >> (32 - shift);
2239 static void bn_zero(unsigned int *bn)
2241 int i;
2242 for(i=0;i<BN_SIZE;i++) {
2243 bn[i] = 0;
2247 /* parse number in null terminated string 'p' and return it in the
2248 current token */
2249 static void parse_number(const char *p)
2251 int b, t, shift, frac_bits, s, exp_val, ch;
2252 char *q;
2253 unsigned int bn[BN_SIZE];
2254 double d;
2256 /* number */
2257 q = token_buf;
2258 ch = *p++;
2259 t = ch;
2260 ch = *p++;
2261 *q++ = t;
2262 b = 10;
2263 if (t == '.') {
2264 goto float_frac_parse;
2265 } else if (t == '0') {
2266 if (ch == 'x' || ch == 'X') {
2267 q--;
2268 ch = *p++;
2269 b = 16;
2270 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2271 q--;
2272 ch = *p++;
2273 b = 2;
2276 /* parse all digits. cannot check octal numbers at this stage
2277 because of floating point constants */
2278 while (1) {
2279 if (ch >= 'a' && ch <= 'f')
2280 t = ch - 'a' + 10;
2281 else if (ch >= 'A' && ch <= 'F')
2282 t = ch - 'A' + 10;
2283 else if (isnum(ch))
2284 t = ch - '0';
2285 else
2286 break;
2287 if (t >= b)
2288 break;
2289 if (q >= token_buf + STRING_MAX_SIZE) {
2290 num_too_long:
2291 tcc_error("number too long");
2293 *q++ = ch;
2294 ch = *p++;
2296 if (ch == '.' ||
2297 ((ch == 'e' || ch == 'E') && b == 10) ||
2298 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2299 if (b != 10) {
2300 /* NOTE: strtox should support that for hexa numbers, but
2301 non ISOC99 libcs do not support it, so we prefer to do
2302 it by hand */
2303 /* hexadecimal or binary floats */
2304 /* XXX: handle overflows */
2305 *q = '\0';
2306 if (b == 16)
2307 shift = 4;
2308 else
2309 shift = 1;
2310 bn_zero(bn);
2311 q = token_buf;
2312 while (1) {
2313 t = *q++;
2314 if (t == '\0') {
2315 break;
2316 } else if (t >= 'a') {
2317 t = t - 'a' + 10;
2318 } else if (t >= 'A') {
2319 t = t - 'A' + 10;
2320 } else {
2321 t = t - '0';
2323 bn_lshift(bn, shift, t);
2325 frac_bits = 0;
2326 if (ch == '.') {
2327 ch = *p++;
2328 while (1) {
2329 t = ch;
2330 if (t >= 'a' && t <= 'f') {
2331 t = t - 'a' + 10;
2332 } else if (t >= 'A' && t <= 'F') {
2333 t = t - 'A' + 10;
2334 } else if (t >= '0' && t <= '9') {
2335 t = t - '0';
2336 } else {
2337 break;
2339 if (t >= b)
2340 tcc_error("invalid digit");
2341 bn_lshift(bn, shift, t);
2342 frac_bits += shift;
2343 ch = *p++;
2346 if (ch != 'p' && ch != 'P')
2347 expect("exponent");
2348 ch = *p++;
2349 s = 1;
2350 exp_val = 0;
2351 if (ch == '+') {
2352 ch = *p++;
2353 } else if (ch == '-') {
2354 s = -1;
2355 ch = *p++;
2357 if (ch < '0' || ch > '9')
2358 expect("exponent digits");
2359 while (ch >= '0' && ch <= '9') {
2360 exp_val = exp_val * 10 + ch - '0';
2361 ch = *p++;
2363 exp_val = exp_val * s;
2365 /* now we can generate the number */
2366 /* XXX: should patch directly float number */
2367 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2368 d = ldexp(d, exp_val - frac_bits);
2369 t = toup(ch);
2370 if (t == 'F') {
2371 ch = *p++;
2372 tok = TOK_CFLOAT;
2373 /* float : should handle overflow */
2374 tokc.f = (float)d;
2375 } else if (t == 'L') {
2376 ch = *p++;
2377 tok = TOK_CLDOUBLE;
2378 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2379 tokc.d = d;
2380 #else
2381 /* XXX: not large enough */
2382 tokc.ld = (long double)d;
2383 #endif
2384 } else {
2385 tok = TOK_CDOUBLE;
2386 tokc.d = d;
2388 } else {
2389 /* decimal floats */
2390 if (ch == '.') {
2391 if (q >= token_buf + STRING_MAX_SIZE)
2392 goto num_too_long;
2393 *q++ = ch;
2394 ch = *p++;
2395 float_frac_parse:
2396 while (ch >= '0' && ch <= '9') {
2397 if (q >= token_buf + STRING_MAX_SIZE)
2398 goto num_too_long;
2399 *q++ = ch;
2400 ch = *p++;
2403 if (ch == 'e' || ch == 'E') {
2404 if (q >= token_buf + STRING_MAX_SIZE)
2405 goto num_too_long;
2406 *q++ = ch;
2407 ch = *p++;
2408 if (ch == '-' || ch == '+') {
2409 if (q >= token_buf + STRING_MAX_SIZE)
2410 goto num_too_long;
2411 *q++ = ch;
2412 ch = *p++;
2414 if (ch < '0' || ch > '9')
2415 expect("exponent digits");
2416 while (ch >= '0' && ch <= '9') {
2417 if (q >= token_buf + STRING_MAX_SIZE)
2418 goto num_too_long;
2419 *q++ = ch;
2420 ch = *p++;
2423 *q = '\0';
2424 t = toup(ch);
2425 errno = 0;
2426 if (t == 'F') {
2427 ch = *p++;
2428 tok = TOK_CFLOAT;
2429 tokc.f = strtof(token_buf, NULL);
2430 } else if (t == 'L') {
2431 ch = *p++;
2432 tok = TOK_CLDOUBLE;
2433 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2434 tokc.d = strtod(token_buf, NULL);
2435 #else
2436 tokc.ld = strtold(token_buf, NULL);
2437 #endif
2438 } else {
2439 tok = TOK_CDOUBLE;
2440 tokc.d = strtod(token_buf, NULL);
2443 } else {
2444 unsigned long long n, n1;
2445 int lcount, ucount, ov = 0;
2446 const char *p1;
2448 /* integer number */
2449 *q = '\0';
2450 q = token_buf;
2451 if (b == 10 && *q == '0') {
2452 b = 8;
2453 q++;
2455 n = 0;
2456 while(1) {
2457 t = *q++;
2458 /* no need for checks except for base 10 / 8 errors */
2459 if (t == '\0')
2460 break;
2461 else if (t >= 'a')
2462 t = t - 'a' + 10;
2463 else if (t >= 'A')
2464 t = t - 'A' + 10;
2465 else
2466 t = t - '0';
2467 if (t >= b)
2468 tcc_error("invalid digit");
2469 n1 = n;
2470 n = n * b + t;
2471 /* detect overflow */
2472 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2473 ov = 1;
2476 /* Determine the characteristics (unsigned and/or 64bit) the type of
2477 the constant must have according to the constant suffix(es) */
2478 lcount = ucount = 0;
2479 p1 = p;
2480 for(;;) {
2481 t = toup(ch);
2482 if (t == 'L') {
2483 if (lcount >= 2)
2484 tcc_error("three 'l's in integer constant");
2485 if (lcount && *(p - 1) != ch)
2486 tcc_error("incorrect integer suffix: %s", p1);
2487 lcount++;
2488 ch = *p++;
2489 } else if (t == 'U') {
2490 if (ucount >= 1)
2491 tcc_error("two 'u's in integer constant");
2492 ucount++;
2493 ch = *p++;
2494 } else {
2495 break;
2499 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2500 if (ucount == 0 && b == 10) {
2501 if (lcount <= (LONG_SIZE == 4)) {
2502 if (n >= 0x80000000U)
2503 lcount = (LONG_SIZE == 4) + 1;
2505 if (n >= 0x8000000000000000ULL)
2506 ov = 1, ucount = 1;
2507 } else {
2508 if (lcount <= (LONG_SIZE == 4)) {
2509 if (n >= 0x100000000ULL)
2510 lcount = (LONG_SIZE == 4) + 1;
2511 else if (n >= 0x80000000U)
2512 ucount = 1;
2514 if (n >= 0x8000000000000000ULL)
2515 ucount = 1;
2518 if (ov)
2519 tcc_warning("integer constant overflow");
2521 tok = TOK_CINT;
2522 if (lcount) {
2523 tok = TOK_CLONG;
2524 if (lcount == 2)
2525 tok = TOK_CLLONG;
2527 if (ucount)
2528 ++tok; /* TOK_CU... */
2529 tokc.i = n;
2531 if (ch)
2532 tcc_error("invalid number");
2536 #define PARSE2(c1, tok1, c2, tok2) \
2537 case c1: \
2538 PEEKC(c, p); \
2539 if (c == c2) { \
2540 p++; \
2541 tok = tok2; \
2542 } else { \
2543 tok = tok1; \
2545 break;
2547 /* return next token without macro substitution */
2548 static void next_nomacro(void)
2550 int t, c, is_long, len;
2551 TokenSym *ts;
2552 uint8_t *p, *p1;
2553 unsigned int h;
2555 p = file->buf_ptr;
2556 redo_no_start:
2557 c = *p;
2558 switch(c) {
2559 case ' ':
2560 case '\t':
2561 tok = c;
2562 p++;
2563 maybe_space:
2564 if (parse_flags & PARSE_FLAG_SPACES)
2565 goto keep_tok_flags;
2566 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2567 ++p;
2568 goto redo_no_start;
2569 case '\f':
2570 case '\v':
2571 case '\r':
2572 p++;
2573 goto redo_no_start;
2574 case '\\':
2575 /* first look if it is in fact an end of buffer */
2576 c = handle_stray(&p);
2577 if (c == '\\')
2578 goto parse_simple;
2579 if (c == CH_EOF) {
2580 TCCState *s1 = tcc_state;
2581 if (!(tok_flags & TOK_FLAG_BOL)) {
2582 /* add implicit newline */
2583 goto maybe_newline;
2584 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2585 tok = TOK_EOF;
2586 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2587 tcc_error("missing #endif");
2588 } else if (s1->include_stack_ptr == s1->include_stack) {
2589 /* no include left : end of file. */
2590 tok = TOK_EOF;
2591 } else {
2592 /* pop include file */
2594 /* test if previous '#endif' was after a #ifdef at
2595 start of file */
2596 if (tok_flags & TOK_FLAG_ENDIF) {
2597 #ifdef INC_DEBUG
2598 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2599 #endif
2600 search_cached_include(s1, file->true_filename, 1)
2601 ->ifndef_macro = file->ifndef_macro_saved;
2602 tok_flags &= ~TOK_FLAG_ENDIF;
2605 /* add end of include file debug info */
2606 tcc_debug_eincl(tcc_state);
2607 /* pop include stack */
2608 tcc_close();
2609 s1->include_stack_ptr--;
2610 p = file->buf_ptr;
2611 goto maybe_newline;
2613 } else {
2614 goto redo_no_start;
2616 break;
2618 case '\n':
2619 file->line_num++;
2620 p++;
2621 maybe_newline:
2622 tok_flags |= TOK_FLAG_BOL;
2623 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2624 goto redo_no_start;
2625 tok = TOK_LINEFEED;
2626 goto keep_tok_flags;
2628 case '#':
2629 /* XXX: simplify */
2630 PEEKC(c, p);
2631 if ((tok_flags & TOK_FLAG_BOL) &&
2632 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2633 tok_flags &= ~TOK_FLAG_BOL;
2634 file->buf_ptr = p;
2635 preprocess(tok_flags & TOK_FLAG_BOF);
2636 p = file->buf_ptr;
2637 goto maybe_newline;
2638 } else {
2639 if (c == '#') {
2640 p++;
2641 tok = TOK_TWOSHARPS;
2642 } else {
2643 #if !defined(TCC_TARGET_ARM)
2644 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2645 p = parse_line_comment(p - 1);
2646 goto redo_no_start;
2647 } else
2648 #endif
2650 tok = '#';
2654 break;
2656 /* dollar is allowed to start identifiers when not parsing asm */
2657 case '$':
2658 if (!(isidnum_table['$' - CH_EOF] & IS_ID)
2659 || (parse_flags & PARSE_FLAG_ASM_FILE))
2660 goto parse_simple;
2662 case 'a': case 'b': case 'c': case 'd':
2663 case 'e': case 'f': case 'g': case 'h':
2664 case 'i': case 'j': case 'k': case 'l':
2665 case 'm': case 'n': case 'o': case 'p':
2666 case 'q': case 'r': case 's': case 't':
2667 case 'u': case 'v': case 'w': case 'x':
2668 case 'y': case 'z':
2669 case 'A': case 'B': case 'C': case 'D':
2670 case 'E': case 'F': case 'G': case 'H':
2671 case 'I': case 'J': case 'K':
2672 case 'M': case 'N': case 'O': case 'P':
2673 case 'Q': case 'R': case 'S': case 'T':
2674 case 'U': case 'V': case 'W': case 'X':
2675 case 'Y': case 'Z':
2676 case '_':
2677 parse_ident_fast:
2678 p1 = p;
2679 h = TOK_HASH_INIT;
2680 h = TOK_HASH_FUNC(h, c);
2681 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2682 h = TOK_HASH_FUNC(h, c);
2683 len = p - p1;
2684 if (c != '\\') {
2685 TokenSym **pts;
2687 /* fast case : no stray found, so we have the full token
2688 and we have already hashed it */
2689 h &= (TOK_HASH_SIZE - 1);
2690 pts = &hash_ident[h];
2691 for(;;) {
2692 ts = *pts;
2693 if (!ts)
2694 break;
2695 if (ts->len == len && !memcmp(ts->str, p1, len))
2696 goto token_found;
2697 pts = &(ts->hash_next);
2699 ts = tok_alloc_new(pts, (char *) p1, len);
2700 token_found: ;
2701 } else {
2702 /* slower case */
2703 cstr_reset(&tokcstr);
2704 cstr_cat(&tokcstr, (char *) p1, len);
2705 p--;
2706 PEEKC(c, p);
2707 parse_ident_slow:
2708 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2710 cstr_ccat(&tokcstr, c);
2711 PEEKC(c, p);
2713 ts = tok_alloc(tokcstr.data, tokcstr.size);
2715 tok = ts->tok;
2716 break;
2717 case 'L':
2718 t = p[1];
2719 if (t != '\\' && t != '\'' && t != '\"') {
2720 /* fast case */
2721 goto parse_ident_fast;
2722 } else {
2723 PEEKC(c, p);
2724 if (c == '\'' || c == '\"') {
2725 is_long = 1;
2726 goto str_const;
2727 } else {
2728 cstr_reset(&tokcstr);
2729 cstr_ccat(&tokcstr, 'L');
2730 goto parse_ident_slow;
2733 break;
2735 case '0': case '1': case '2': case '3':
2736 case '4': case '5': case '6': case '7':
2737 case '8': case '9':
2738 t = c;
2739 PEEKC(c, p);
2740 /* after the first digit, accept digits, alpha, '.' or sign if
2741 prefixed by 'eEpP' */
2742 parse_num:
2743 cstr_reset(&tokcstr);
2744 for(;;) {
2745 cstr_ccat(&tokcstr, t);
2746 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2747 || c == '.'
2748 || ((c == '+' || c == '-')
2749 && (((t == 'e' || t == 'E')
2750 && !(parse_flags & PARSE_FLAG_ASM_FILE
2751 /* 0xe+1 is 3 tokens in asm */
2752 && ((char*)tokcstr.data)[0] == '0'
2753 && toup(((char*)tokcstr.data)[1]) == 'X'))
2754 || t == 'p' || t == 'P'))))
2755 break;
2756 t = c;
2757 PEEKC(c, p);
2759 /* We add a trailing '\0' to ease parsing */
2760 cstr_ccat(&tokcstr, '\0');
2761 tokc.str.size = tokcstr.size;
2762 tokc.str.data = tokcstr.data;
2763 tok = TOK_PPNUM;
2764 break;
2766 case '.':
2767 /* special dot handling because it can also start a number */
2768 PEEKC(c, p);
2769 if (isnum(c)) {
2770 t = '.';
2771 goto parse_num;
2772 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2773 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2774 *--p = c = '.';
2775 goto parse_ident_fast;
2776 } else if (c == '.') {
2777 PEEKC(c, p);
2778 if (c == '.') {
2779 p++;
2780 tok = TOK_DOTS;
2781 } else {
2782 *--p = '.'; /* may underflow into file->unget[] */
2783 tok = '.';
2785 } else {
2786 tok = '.';
2788 break;
2789 case '\'':
2790 case '\"':
2791 is_long = 0;
2792 str_const:
2793 cstr_reset(&tokcstr);
2794 if (is_long)
2795 cstr_ccat(&tokcstr, 'L');
2796 cstr_ccat(&tokcstr, c);
2797 p = parse_pp_string(p, c, &tokcstr);
2798 cstr_ccat(&tokcstr, c);
2799 cstr_ccat(&tokcstr, '\0');
2800 tokc.str.size = tokcstr.size;
2801 tokc.str.data = tokcstr.data;
2802 tok = TOK_PPSTR;
2803 break;
2805 case '<':
2806 PEEKC(c, p);
2807 if (c == '=') {
2808 p++;
2809 tok = TOK_LE;
2810 } else if (c == '<') {
2811 PEEKC(c, p);
2812 if (c == '=') {
2813 p++;
2814 tok = TOK_A_SHL;
2815 } else {
2816 tok = TOK_SHL;
2818 } else {
2819 tok = TOK_LT;
2821 break;
2822 case '>':
2823 PEEKC(c, p);
2824 if (c == '=') {
2825 p++;
2826 tok = TOK_GE;
2827 } else if (c == '>') {
2828 PEEKC(c, p);
2829 if (c == '=') {
2830 p++;
2831 tok = TOK_A_SAR;
2832 } else {
2833 tok = TOK_SAR;
2835 } else {
2836 tok = TOK_GT;
2838 break;
2840 case '&':
2841 PEEKC(c, p);
2842 if (c == '&') {
2843 p++;
2844 tok = TOK_LAND;
2845 } else if (c == '=') {
2846 p++;
2847 tok = TOK_A_AND;
2848 } else {
2849 tok = '&';
2851 break;
2853 case '|':
2854 PEEKC(c, p);
2855 if (c == '|') {
2856 p++;
2857 tok = TOK_LOR;
2858 } else if (c == '=') {
2859 p++;
2860 tok = TOK_A_OR;
2861 } else {
2862 tok = '|';
2864 break;
2866 case '+':
2867 PEEKC(c, p);
2868 if (c == '+') {
2869 p++;
2870 tok = TOK_INC;
2871 } else if (c == '=') {
2872 p++;
2873 tok = TOK_A_ADD;
2874 } else {
2875 tok = '+';
2877 break;
2879 case '-':
2880 PEEKC(c, p);
2881 if (c == '-') {
2882 p++;
2883 tok = TOK_DEC;
2884 } else if (c == '=') {
2885 p++;
2886 tok = TOK_A_SUB;
2887 } else if (c == '>') {
2888 p++;
2889 tok = TOK_ARROW;
2890 } else {
2891 tok = '-';
2893 break;
2895 PARSE2('!', '!', '=', TOK_NE)
2896 PARSE2('=', '=', '=', TOK_EQ)
2897 PARSE2('*', '*', '=', TOK_A_MUL)
2898 PARSE2('%', '%', '=', TOK_A_MOD)
2899 PARSE2('^', '^', '=', TOK_A_XOR)
2901 /* comments or operator */
2902 case '/':
2903 PEEKC(c, p);
2904 if (c == '*') {
2905 p = parse_comment(p);
2906 /* comments replaced by a blank */
2907 tok = ' ';
2908 goto maybe_space;
2909 } else if (c == '/') {
2910 p = parse_line_comment(p);
2911 tok = ' ';
2912 goto maybe_space;
2913 } else if (c == '=') {
2914 p++;
2915 tok = TOK_A_DIV;
2916 } else {
2917 tok = '/';
2919 break;
2921 /* simple tokens */
2922 case '(':
2923 case ')':
2924 case '[':
2925 case ']':
2926 case '{':
2927 case '}':
2928 case ',':
2929 case ';':
2930 case ':':
2931 case '?':
2932 case '~':
2933 case '@': /* only used in assembler */
2934 parse_simple:
2935 tok = c;
2936 p++;
2937 break;
2938 default:
2939 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2940 goto parse_ident_fast;
2941 if (parse_flags & PARSE_FLAG_ASM_FILE)
2942 goto parse_simple;
2943 tcc_error("unrecognized character \\x%02x", c);
2944 break;
2946 tok_flags = 0;
2947 keep_tok_flags:
2948 file->buf_ptr = p;
2949 #if defined(PARSE_DEBUG)
2950 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
2951 #endif
2954 #ifdef PP_DEBUG
2955 static int indent;
2956 static void define_print(TCCState *s1, int v);
2957 static void pp_print(const char *msg, int v, const int *str)
2959 FILE *fp = tcc_state->ppfp;
2961 if (msg[0] == '#' && indent == 0)
2962 fprintf(fp, "\n");
2963 else if (msg[0] == '+')
2964 ++indent, ++msg;
2965 else if (msg[0] == '-')
2966 --indent, ++msg;
2968 fprintf(fp, "%*s", indent, "");
2969 if (msg[0] == '#') {
2970 define_print(tcc_state, v);
2971 } else {
2972 tok_print(str, v ? "%s %s" : "%s", msg, get_tok_str(v, 0));
2975 #define PP_PRINT(x) pp_print x
2976 #else
2977 #define PP_PRINT(x)
2978 #endif
2980 static int macro_subst(
2981 TokenString *tok_str,
2982 Sym **nested_list,
2983 const int *macro_str
2986 /* substitute arguments in replacement lists in macro_str by the values in
2987 args (field d) and return allocated string */
2988 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2990 int t, t0, t1, t2, n;
2991 const int *st;
2992 Sym *s;
2993 CValue cval;
2994 TokenString str;
2996 #ifdef PP_DEBUG
2997 PP_PRINT(("asubst:", 0, macro_str));
2998 for (s = args, n = 0; s; s = s->prev, ++n);
2999 while (n--) {
3000 for (s = args, t = 0; t < n; s = s->prev, ++t);
3001 tok_print(s->d, "%*s - arg: %s:", indent, "", get_tok_str(s->v, 0));
3003 #endif
3005 tok_str_new(&str);
3006 t0 = t1 = 0;
3007 while(1) {
3008 TOK_GET(&t, &macro_str, &cval);
3009 if (!t)
3010 break;
3011 if (t == '#') {
3012 /* stringize */
3013 do t = *macro_str++; while (t == ' ');
3014 s = sym_find2(args, t);
3015 if (s) {
3016 cstr_reset(&tokcstr);
3017 cstr_ccat(&tokcstr, '\"');
3018 st = s->d;
3019 while (*st != TOK_EOF) {
3020 const char *s;
3021 TOK_GET(&t, &st, &cval);
3022 s = get_tok_str(t, &cval);
3023 while (*s) {
3024 if (t == TOK_PPSTR && *s != '\'')
3025 add_char(&tokcstr, *s);
3026 else
3027 cstr_ccat(&tokcstr, *s);
3028 ++s;
3031 cstr_ccat(&tokcstr, '\"');
3032 cstr_ccat(&tokcstr, '\0');
3033 //printf("\nstringize: <%s>\n", (char *)tokcstr.data);
3034 /* add string */
3035 cval.str.size = tokcstr.size;
3036 cval.str.data = tokcstr.data;
3037 tok_str_add2(&str, TOK_PPSTR, &cval);
3038 } else {
3039 expect("macro parameter after '#'");
3041 } else if (t >= TOK_IDENT) {
3042 s = sym_find2(args, t);
3043 if (s) {
3044 st = s->d;
3045 n = 0;
3046 while ((t2 = macro_str[n]) == ' ')
3047 ++n;
3048 /* if '##' is present before or after, no arg substitution */
3049 if (t2 == TOK_PPJOIN || t1 == TOK_PPJOIN) {
3050 /* special case for var arg macros : ## eats the ','
3051 if empty VA_ARGS variable. */
3052 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
3053 int c = str.str[str.len - 1];
3054 while (str.str[--str.len] != ',')
3056 if (*st == TOK_EOF) {
3057 /* suppress ',' '##' */
3058 } else {
3059 /* suppress '##' and add variable */
3060 str.len++;
3061 if (c == ' ')
3062 str.str[str.len++] = c;
3063 goto add_var;
3065 } else {
3066 if (*st == TOK_EOF)
3067 tok_str_add(&str, TOK_PLCHLDR);
3069 } else {
3070 add_var:
3071 if (!s->e) {
3072 /* Expand arguments tokens and store them. In most
3073 cases we could also re-expand each argument if
3074 used multiple times, but not if the argument
3075 contains the __COUNTER__ macro. */
3076 TokenString str2;
3077 tok_str_new(&str2);
3078 macro_subst(&str2, nested_list, st);
3079 tok_str_add(&str2, TOK_EOF);
3080 s->e = str2.str;
3082 st = s->e;
3084 while (*st != TOK_EOF) {
3085 TOK_GET(&t2, &st, &cval);
3086 tok_str_add2(&str, t2, &cval);
3088 } else {
3089 tok_str_add(&str, t);
3091 } else {
3092 tok_str_add2(&str, t, &cval);
3094 if (t != ' ')
3095 t0 = t1, t1 = t;
3097 tok_str_add(&str, 0);
3098 PP_PRINT(("areslt:", 0, str.str));
3099 return str.str;
3102 /* handle the '##' operator. return the resulting string (which must be freed). */
3103 static inline int *macro_twosharps(const int *ptr0)
3105 int t1, t2, n, l;
3106 CValue cv1, cv2;
3107 TokenString macro_str1;
3108 const int *ptr;
3110 tok_str_new(&macro_str1);
3111 cstr_reset(&tokcstr);
3112 for (ptr = ptr0;;) {
3113 TOK_GET(&t1, &ptr, &cv1);
3114 if (t1 == 0)
3115 break;
3116 for (;;) {
3117 n = 0;
3118 while ((t2 = ptr[n]) == ' ')
3119 ++n;
3120 if (t2 != TOK_PPJOIN)
3121 break;
3122 ptr += n;
3123 while ((t2 = *++ptr) == ' ' || t2 == TOK_PPJOIN)
3125 TOK_GET(&t2, &ptr, &cv2);
3126 if (t2 == TOK_PLCHLDR)
3127 continue;
3128 if (t1 != TOK_PLCHLDR) {
3129 cstr_cat(&tokcstr, get_tok_str(t1, &cv1), -1);
3130 t1 = TOK_PLCHLDR;
3132 cstr_cat(&tokcstr, get_tok_str(t2, &cv2), -1);
3134 if (tokcstr.size) {
3135 cstr_ccat(&tokcstr, 0);
3136 tcc_open_bf(tcc_state, ":paste:", tokcstr.size);
3137 memcpy(file->buffer, tokcstr.data, tokcstr.size);
3138 tok_flags = 0; /* don't interpret '#' */
3139 for (n = 0;;n = l) {
3140 next_nomacro();
3141 tok_str_add2(&macro_str1, tok, &tokc);
3142 if (*file->buf_ptr == 0)
3143 break;
3144 tok_str_add(&macro_str1, ' ');
3145 l = file->buf_ptr - file->buffer;
3146 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3147 " preprocessing token", l - n, file->buffer + n, file->buf_ptr);
3149 tcc_close();
3150 cstr_reset(&tokcstr);
3152 if (t1 != TOK_PLCHLDR)
3153 tok_str_add2(&macro_str1, t1, &cv1);
3155 tok_str_add(&macro_str1, 0);
3156 PP_PRINT(("pasted:", 0, macro_str1.str));
3157 return macro_str1.str;
3160 static int peek_file (TokenString *ws_str)
3162 uint8_t *p = file->buf_ptr - 1;
3163 int c;
3164 for (;;) {
3165 PEEKC(c, p);
3166 switch (c) {
3167 case '/':
3168 PEEKC(c, p);
3169 if (c == '*')
3170 p = parse_comment(p);
3171 else if (c == '/')
3172 p = parse_line_comment(p);
3173 else {
3174 c = *--p = '/';
3175 goto leave;
3177 --p, c = ' ';
3178 break;
3179 case ' ': case '\t':
3180 break;
3181 case '\f': case '\v': case '\r':
3182 continue;
3183 case '\n':
3184 file->line_num++, tok_flags |= TOK_FLAG_BOL;
3185 break;
3186 default: leave:
3187 file->buf_ptr = p;
3188 return c;
3190 if (ws_str)
3191 tok_str_add(ws_str, c);
3195 /* peek or read [ws_str == NULL] next token from function macro call,
3196 walking up macro levels up to the file if necessary */
3197 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3199 int t;
3200 Sym *sa;
3202 while (macro_ptr) {
3203 const int *m = macro_ptr;
3204 while ((t = *m) != 0) {
3205 if (ws_str) {
3206 if (t != ' ')
3207 return t;
3208 ++m;
3209 } else {
3210 TOK_GET(&tok, &macro_ptr, &tokc);
3211 return tok;
3214 end_macro();
3215 /* also, end of scope for nested defined symbol */
3216 sa = *nested_list;
3217 if (sa)
3218 *nested_list = sa->prev, sym_free(sa);
3220 if (ws_str) {
3221 return peek_file(ws_str);
3222 } else {
3223 next_nomacro();
3224 if (tok == '\t' || tok == TOK_LINEFEED)
3225 tok = ' ';
3226 return tok;
3230 /* do macro substitution of current token with macro 's' and add
3231 result to (tok_str,tok_len). 'nested_list' is the list of all
3232 macros we got inside to avoid recursing. Return non zero if no
3233 substitution needs to be done */
3234 static int macro_subst_tok(
3235 TokenString *tok_str,
3236 Sym **nested_list,
3237 Sym *s)
3239 int t;
3240 int v = s->v;
3242 PP_PRINT(("#", v, s->d));
3243 if (s->d) {
3244 int *mstr = s->d;
3245 int *jstr;
3246 Sym *sa;
3247 int ret;
3249 if (s->type.t & MACRO_FUNC) {
3250 int saved_parse_flags = parse_flags;
3251 TokenString str;
3252 int parlevel, i;
3253 Sym *sa1, *args;
3255 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3256 | PARSE_FLAG_ACCEPT_STRAYS;
3258 tok_str_new(&str);
3259 /* peek next token from argument stream */
3260 t = next_argstream(nested_list, &str);
3261 if (t != '(') {
3262 /* not a macro substitution after all, restore the
3263 * macro token plus all whitespace we've read.
3264 * whitespace is intentionally not merged to preserve
3265 * newlines. */
3266 parse_flags = saved_parse_flags;
3267 tok_str_add2_spc(tok_str, v, 0);
3268 if (parse_flags & PARSE_FLAG_SPACES)
3269 for (i = 0; i < str.len; i++)
3270 tok_str_add(tok_str, str.str[i]);
3271 tok_str_free_str(str.str);
3272 return 0;
3273 } else {
3274 tok_str_free_str(str.str);
3277 /* argument macro */
3278 args = NULL;
3279 sa = s->next;
3280 /* NOTE: empty args are allowed, except if no args */
3281 i = 2; /* eat '(' */
3282 for(;;) {
3283 do {
3284 t = next_argstream(nested_list, NULL);
3285 } while (t == ' ' || --i);
3287 if (!sa) {
3288 if (t == ')') /* handle '()' case */
3289 break;
3290 tcc_error("macro '%s' used with too many args",
3291 get_tok_str(v, 0));
3293 empty_arg:
3294 tok_str_new(&str);
3295 parlevel = 0;
3296 /* NOTE: non zero sa->type.t indicates VA_ARGS */
3297 while (parlevel > 0
3298 || (t != ')' && (t != ',' || sa->type.t))) {
3299 if (t == TOK_EOF)
3300 tcc_error("EOF in invocation of macro '%s'",
3301 get_tok_str(v, 0));
3302 if (t == '(')
3303 parlevel++;
3304 if (t == ')')
3305 parlevel--;
3306 if (t == ' ')
3307 str.need_spc |= 1;
3308 else
3309 tok_str_add2_spc(&str, t, &tokc);
3310 t = next_argstream(nested_list, NULL);
3312 tok_str_add(&str, TOK_EOF);
3313 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3314 sa1->d = str.str;
3315 sa = sa->next;
3316 if (t == ')') {
3317 if (!sa)
3318 break;
3319 /* special case for gcc var args: add an empty
3320 var arg argument if it is omitted */
3321 if (sa->type.t && gnu_ext)
3322 goto empty_arg;
3323 tcc_error("macro '%s' used with too few args",
3324 get_tok_str(v, 0));
3326 i = 1;
3329 /* now subst each arg */
3330 mstr = macro_arg_subst(nested_list, mstr, args);
3331 /* free memory */
3332 sa = args;
3333 while (sa) {
3334 sa1 = sa->prev;
3335 tok_str_free_str(sa->d);
3336 tok_str_free_str(sa->e);
3337 sym_free(sa);
3338 sa = sa1;
3340 parse_flags = saved_parse_flags;
3343 /* process '##'s (if present) */
3344 jstr = mstr;
3345 if (s->type.t & MACRO_JOIN)
3346 jstr = macro_twosharps(mstr);
3348 sa = sym_push2(nested_list, v, 0, 0);
3349 ret = macro_subst(tok_str, nested_list, jstr);
3350 /* pop nested defined symbol */
3351 if (sa == *nested_list)
3352 *nested_list = sa->prev, sym_free(sa);
3354 if (jstr != mstr)
3355 tok_str_free_str(jstr);
3356 if (mstr != s->d)
3357 tok_str_free_str(mstr);
3358 return ret;
3360 } else {
3361 CValue cval;
3362 char buf[32], *cstrval = buf;
3364 /* special macros */
3365 if (v == TOK___LINE__ || v == TOK___COUNTER__) {
3366 t = v == TOK___LINE__ ? file->line_num : pp_counter++;
3367 snprintf(buf, sizeof(buf), "%d", t);
3368 t = TOK_PPNUM;
3369 goto add_cstr1;
3371 } else if (v == TOK___FILE__) {
3372 cstrval = file->filename;
3373 goto add_cstr;
3375 } else if (v == TOK___DATE__ || v == TOK___TIME__) {
3376 time_t ti;
3377 struct tm *tm;
3378 time(&ti);
3379 tm = localtime(&ti);
3380 if (v == TOK___DATE__) {
3381 static char const ab_month_name[12][4] = {
3382 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3383 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3385 snprintf(buf, sizeof(buf), "%s %2d %d",
3386 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3387 } else {
3388 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3389 tm->tm_hour, tm->tm_min, tm->tm_sec);
3391 add_cstr:
3392 t = TOK_STR;
3393 add_cstr1:
3394 cval.str.size = strlen(cstrval) + 1;
3395 cval.str.data = cstrval;
3396 tok_str_add2_spc(tok_str, t, &cval);
3398 return 0;
3402 /* do macro substitution of macro_str and add result to
3403 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3404 inside to avoid recursing. */
3405 static int macro_subst(
3406 TokenString *tok_str,
3407 Sym **nested_list,
3408 const int *macro_str
3411 Sym *s;
3412 int t, nosubst = 0;
3413 CValue cval;
3414 TokenString *str;
3416 #ifdef PP_DEBUG
3417 int tlen = tok_str->len;
3418 PP_PRINT(("+expand:", 0, macro_str));
3419 #endif
3421 while (1) {
3422 TOK_GET(&t, &macro_str, &cval);
3423 if (t == 0 || t == TOK_EOF)
3424 break;
3425 if (t >= TOK_IDENT) {
3426 s = define_find(t);
3427 if (s == NULL || nosubst)
3428 goto no_subst;
3429 /* if nested substitution, do nothing */
3430 if (sym_find2(*nested_list, t)) {
3431 /* and mark so it doesn't get subst'd again */
3432 t |= SYM_FIELD;
3433 goto no_subst;
3435 str = tok_str_alloc();
3436 str->str = (int*)macro_str; /* setup stream for possible arguments */
3437 begin_macro(str, 2);
3438 nosubst = macro_subst_tok(tok_str, nested_list, s);
3439 if (macro_stack != str) {
3440 /* already finished by reading function macro arguments */
3441 break;
3443 macro_str = macro_ptr;
3444 end_macro ();
3445 } else if (t == ' ') {
3446 if (parse_flags & PARSE_FLAG_SPACES)
3447 tok_str->need_spc |= 1;
3448 } else {
3449 no_subst:
3450 tok_str_add2_spc(tok_str, t, &cval);
3451 if (nosubst && t != '(')
3452 nosubst = 0;
3453 /* GCC supports 'defined' as result of a macro substitution */
3454 if (t == TOK_DEFINED && pp_expr)
3455 nosubst = 1;
3459 #ifdef PP_DEBUG
3460 tok_str_add(tok_str, 0), --tok_str->len;
3461 PP_PRINT(("-result:", 0, tok_str->str + tlen));
3462 #endif
3463 return nosubst;
3466 /* return next token with macro substitution */
3467 ST_FUNC void next(void)
3469 int t;
3470 while (macro_ptr) {
3471 redo:
3472 t = *macro_ptr;
3473 if (TOK_HAS_VALUE(t)) {
3474 tok_get(&tok, &macro_ptr, &tokc);
3475 if (t == TOK_LINENUM) {
3476 file->line_num = tokc.i;
3477 goto redo;
3479 goto convert;
3480 } else if (t == 0) {
3481 /* end of macro or unget token string */
3482 end_macro();
3483 continue;
3484 } else if (t == TOK_EOF) {
3485 /* do nothing */
3486 } else {
3487 ++macro_ptr;
3488 t &= ~SYM_FIELD; /* remove 'nosubst' marker */
3489 if (t == '\\') {
3490 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3491 tcc_error("stray '\\' in program");
3494 tok = t;
3495 return;
3498 next_nomacro();
3499 t = tok;
3500 if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3501 /* if reading from file, try to substitute macros */
3502 Sym *s = define_find(t);
3503 if (s) {
3504 Sym *nested_list = NULL;
3505 macro_subst_tok(&tokstr_buf, &nested_list, s);
3506 tok_str_add(&tokstr_buf, 0);
3507 begin_macro(&tokstr_buf, 0);
3508 goto redo;
3510 return;
3513 convert:
3514 /* convert preprocessor tokens into C tokens */
3515 if (t == TOK_PPNUM) {
3516 if (parse_flags & PARSE_FLAG_TOK_NUM)
3517 parse_number(tokc.str.data);
3518 } else if (t == TOK_PPSTR) {
3519 if (parse_flags & PARSE_FLAG_TOK_STR)
3520 parse_string(tokc.str.data, tokc.str.size - 1);
3524 /* push back current token and set current token to 'last_tok'. Only
3525 identifier case handled for labels. */
3526 ST_INLN void unget_tok(int last_tok)
3528 TokenString *str = &unget_buf;
3529 int alloc = 0;
3530 if (str->len) /* use static buffer except if already in use */
3531 str = tok_str_alloc(), alloc = 1;
3532 if (tok != TOK_EOF)
3533 tok_str_add2(str, tok, &tokc);
3534 tok_str_add(str, 0);
3535 begin_macro(str, alloc);
3536 tok = last_tok;
3539 /* ------------------------------------------------------------------------- */
3540 /* init preprocessor */
3542 static const char * const target_os_defs =
3543 #ifdef TCC_TARGET_PE
3544 "_WIN32\0"
3545 # if PTR_SIZE == 8
3546 "_WIN64\0"
3547 # endif
3548 #else
3549 # if defined TCC_TARGET_MACHO
3550 "__APPLE__\0"
3551 # elif TARGETOS_FreeBSD
3552 "__FreeBSD__ 12\0"
3553 # elif TARGETOS_FreeBSD_kernel
3554 "__FreeBSD_kernel__\0"
3555 # elif TARGETOS_NetBSD
3556 "__NetBSD__\0"
3557 # elif TARGETOS_OpenBSD
3558 "__OpenBSD__\0"
3559 # else
3560 "__linux__\0"
3561 "__linux\0"
3562 # if TARGETOS_ANDROID
3563 "__ANDROID__\0"
3564 # endif
3565 # endif
3566 "__unix__\0"
3567 "__unix\0"
3568 #endif
3571 static void putdef(CString *cs, const char *p)
3573 cstr_printf(cs, "#define %s%s\n", p, &" 1"[!!strchr(p, ' ')*2]);
3576 static void putdefs(CString *cs, const char *p)
3578 while (*p)
3579 putdef(cs, p), p = strchr(p, 0) + 1;
3582 static void tcc_predefs(TCCState *s1, CString *cs, int is_asm)
3584 cstr_printf(cs, "#define __TINYC__ 9%.2s\n", TCC_VERSION + 4);
3585 putdefs(cs, target_machine_defs);
3586 putdefs(cs, target_os_defs);
3588 #ifdef TCC_TARGET_ARM
3589 if (s1->float_abi == ARM_HARD_FLOAT)
3590 putdef(cs, "__ARM_PCS_VFP");
3591 #endif
3592 if (is_asm)
3593 putdef(cs, "__ASSEMBLER__");
3594 if (s1->output_type == TCC_OUTPUT_PREPROCESS)
3595 putdef(cs, "__TCC_PP__");
3596 if (s1->output_type == TCC_OUTPUT_MEMORY)
3597 putdef(cs, "__TCC_RUN__");
3598 #ifdef CONFIG_TCC_BACKTRACE
3599 if (s1->do_backtrace)
3600 putdef(cs, "__TCC_BACKTRACE__");
3601 #endif
3602 #ifdef CONFIG_TCC_BCHECK
3603 if (s1->do_bounds_check)
3604 putdef(cs, "__TCC_BCHECK__");
3605 #endif
3606 if (s1->char_is_unsigned)
3607 putdef(cs, "__CHAR_UNSIGNED__");
3608 if (s1->optimize > 0)
3609 putdef(cs, "__OPTIMIZE__");
3610 if (s1->option_pthread)
3611 putdef(cs, "_REENTRANT");
3612 if (s1->leading_underscore)
3613 putdef(cs, "__leading_underscore");
3614 cstr_printf(cs, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE);
3615 cstr_printf(cs, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE);
3616 if (!is_asm) {
3617 putdef(cs, "__STDC__");
3618 cstr_printf(cs, "#define __STDC_VERSION__ %dL\n", s1->cversion);
3619 cstr_cat(cs,
3620 /* load more predefs and __builtins */
3621 #if CONFIG_TCC_PREDEFS
3622 #include "tccdefs_.h" /* include as strings */
3623 #else
3624 "#include <tccdefs.h>\n" /* load at runtime */
3625 #endif
3626 , -1);
3628 cstr_printf(cs, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3631 ST_FUNC void preprocess_start(TCCState *s1, int filetype)
3633 int is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
3635 tccpp_new(s1);
3637 s1->include_stack_ptr = s1->include_stack;
3638 s1->ifdef_stack_ptr = s1->ifdef_stack;
3639 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3640 pp_expr = 0;
3641 pp_counter = 0;
3642 pp_debug_tok = pp_debug_symv = 0;
3643 s1->pack_stack[0] = 0;
3644 s1->pack_stack_ptr = s1->pack_stack;
3646 set_idnum('$', !is_asm && s1->dollars_in_identifiers ? IS_ID : 0);
3647 set_idnum('.', is_asm ? IS_ID : 0);
3649 if (!(filetype & AFF_TYPE_ASM)) {
3650 CString cstr;
3651 cstr_new(&cstr);
3652 tcc_predefs(s1, &cstr, is_asm);
3653 if (s1->cmdline_defs.size)
3654 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3655 if (s1->cmdline_incl.size)
3656 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3657 //printf("%.*s\n", cstr.size, (char*)cstr.data);
3658 *s1->include_stack_ptr++ = file;
3659 tcc_open_bf(s1, "<command line>", cstr.size);
3660 memcpy(file->buffer, cstr.data, cstr.size);
3661 cstr_free(&cstr);
3663 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3666 /* cleanup from error/setjmp */
3667 ST_FUNC void preprocess_end(TCCState *s1)
3669 while (macro_stack)
3670 end_macro();
3671 macro_ptr = NULL;
3672 while (file)
3673 tcc_close();
3674 tccpp_delete(s1);
3677 ST_FUNC int set_idnum(int c, int val)
3679 int prev = isidnum_table[c - CH_EOF];
3680 isidnum_table[c - CH_EOF] = val;
3681 return prev;
3684 ST_FUNC void tccpp_new(TCCState *s)
3686 int i, c;
3687 const char *p, *r;
3689 /* init isid table */
3690 for(i = CH_EOF; i<128; i++)
3691 set_idnum(i,
3692 is_space(i) ? IS_SPC
3693 : isid(i) ? IS_ID
3694 : isnum(i) ? IS_NUM
3695 : 0);
3697 for(i = 128; i<256; i++)
3698 set_idnum(i, IS_ID);
3700 /* init allocators */
3701 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3702 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3704 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3705 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3707 cstr_new(&tokcstr);
3708 cstr_new(&cstr_buf);
3709 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3710 tok_str_new(&tokstr_buf);
3711 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3712 tok_str_new(&unget_buf);
3714 tok_ident = TOK_IDENT;
3715 p = tcc_keywords;
3716 while (*p) {
3717 r = p;
3718 for(;;) {
3719 c = *r++;
3720 if (c == '\0')
3721 break;
3723 tok_alloc(p, r - p - 1);
3724 p = r;
3727 /* we add dummy defines for some special macros to speed up tests
3728 and to have working defined() */
3729 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3730 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3731 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3732 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3733 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3736 ST_FUNC void tccpp_delete(TCCState *s)
3738 int i, n;
3740 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3742 /* free tokens */
3743 n = tok_ident - TOK_IDENT;
3744 if (n > total_idents)
3745 total_idents = n;
3746 for(i = 0; i < n; i++)
3747 tal_free(toksym_alloc, table_ident[i]);
3748 tcc_free(table_ident);
3749 table_ident = NULL;
3751 /* free static buffers */
3752 cstr_free(&tokcstr);
3753 cstr_free(&cstr_buf);
3754 tok_str_free_str(tokstr_buf.str);
3755 tok_str_free_str(unget_buf.str);
3757 /* free allocators */
3758 tal_delete(toksym_alloc);
3759 toksym_alloc = NULL;
3760 tal_delete(tokstr_alloc);
3761 tokstr_alloc = NULL;
3764 /* ------------------------------------------------------------------------- */
3765 /* tcc -E [-P[1]] [-dD} support */
3767 static int pp_need_space(int a, int b);
3769 static void tok_print(const int *str, const char *msg, ...)
3771 FILE *fp = tcc_state->ppfp;
3772 va_list ap;
3773 int t, t0, s;
3774 CValue cval;
3776 va_start(ap, msg);
3777 vfprintf(fp, msg, ap);
3778 va_end(ap);
3780 s = t0 = 0;
3781 while (str) {
3782 TOK_GET(&t, &str, &cval);
3783 if (t == 0 || t == TOK_EOF)
3784 break;
3785 if (pp_need_space(t0, t))
3786 s = 0;
3787 fprintf(fp, &" %s"[s], t == TOK_PLCHLDR ? "<>" : get_tok_str(t, &cval));
3788 s = 1, t0 = t;
3790 fprintf(fp, "\n");
3793 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3795 int d = f->line_num - f->line_ref;
3797 if (s1->dflag & 4)
3798 return;
3800 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3802 } else if (level == 0 && f->line_ref && d < 8) {
3803 while (d > 0)
3804 fputs("\n", s1->ppfp), --d;
3805 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3806 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3807 } else {
3808 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3809 level > 0 ? " 1" : level < 0 ? " 2" : "");
3811 f->line_ref = f->line_num;
3814 static void define_print(TCCState *s1, int v)
3816 FILE *fp;
3817 Sym *s;
3819 s = define_find(v);
3820 if (NULL == s || NULL == s->d)
3821 return;
3823 fp = s1->ppfp;
3824 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3825 if (s->type.t & MACRO_FUNC) {
3826 Sym *a = s->next;
3827 fprintf(fp,"(");
3828 if (a)
3829 for (;;) {
3830 fprintf(fp,"%s", get_tok_str(a->v, NULL));
3831 if (!(a = a->next))
3832 break;
3833 fprintf(fp,",");
3835 fprintf(fp,")");
3837 tok_print(s->d, "");
3840 static void pp_debug_defines(TCCState *s1)
3842 int v, t;
3843 const char *vs;
3844 FILE *fp;
3846 t = pp_debug_tok;
3847 if (t == 0)
3848 return;
3850 file->line_num--;
3851 pp_line(s1, file, 0);
3852 file->line_ref = ++file->line_num;
3854 fp = s1->ppfp;
3855 v = pp_debug_symv;
3856 vs = get_tok_str(v, NULL);
3857 if (t == TOK_DEFINE) {
3858 define_print(s1, v);
3859 } else if (t == TOK_UNDEF) {
3860 fprintf(fp, "#undef %s\n", vs);
3861 } else if (t == TOK_push_macro) {
3862 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3863 } else if (t == TOK_pop_macro) {
3864 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3866 pp_debug_tok = 0;
3869 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3870 static int pp_need_space(int a, int b)
3872 return 'E' == a ? '+' == b || '-' == b
3873 : '+' == a ? TOK_INC == b || '+' == b
3874 : '-' == a ? TOK_DEC == b || '-' == b
3875 : a >= TOK_IDENT || a == TOK_PPNUM ? b >= TOK_IDENT || b == TOK_PPNUM
3876 : 0;
3879 /* maybe hex like 0x1e */
3880 static int pp_check_he0xE(int t, const char *p)
3882 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3883 return 'E';
3884 return t;
3887 /* Preprocess the current file */
3888 ST_FUNC int tcc_preprocess(TCCState *s1)
3890 BufferedFile **iptr;
3891 int token_seen, spcs, level;
3892 const char *p;
3893 char white[400];
3895 parse_flags = PARSE_FLAG_PREPROCESS
3896 | (parse_flags & PARSE_FLAG_ASM_FILE)
3897 | PARSE_FLAG_LINEFEED
3898 | PARSE_FLAG_SPACES
3899 | PARSE_FLAG_ACCEPT_STRAYS
3901 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3902 capability to compile and run itself, provided all numbers are
3903 given as decimals. tcc -E -P10 will do. */
3904 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
3905 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3907 if (s1->do_bench) {
3908 /* for PP benchmarks */
3909 do next(); while (tok != TOK_EOF);
3910 return 0;
3913 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
3914 if (file->prev)
3915 pp_line(s1, file->prev, level++);
3916 pp_line(s1, file, level);
3918 for (;;) {
3919 iptr = s1->include_stack_ptr;
3920 next();
3921 if (tok == TOK_EOF)
3922 break;
3924 level = s1->include_stack_ptr - iptr;
3925 if (level) {
3926 if (level > 0)
3927 pp_line(s1, *iptr, 0);
3928 pp_line(s1, file, level);
3930 if (s1->dflag & 7) {
3931 pp_debug_defines(s1);
3932 if (s1->dflag & 4)
3933 continue;
3936 if (is_space(tok)) {
3937 if (spcs < sizeof white - 1)
3938 white[spcs++] = tok;
3939 continue;
3940 } else if (tok == TOK_LINEFEED) {
3941 spcs = 0;
3942 if (token_seen == TOK_LINEFEED)
3943 continue;
3944 ++file->line_ref;
3945 } else if (token_seen == TOK_LINEFEED) {
3946 pp_line(s1, file, 0);
3947 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
3948 white[spcs++] = ' ';
3951 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
3952 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
3953 token_seen = pp_check_he0xE(tok, p);
3955 return 0;
3958 /* ------------------------------------------------------------------------- */