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