Fix unicode compiler warning again
[tinycc.git] / tccpp.c
blob25654b209891cb9990a42b07fc12186b3391d309
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 /********************************************************/
25 /* global variables */
27 ST_DATA int tok_flags;
28 ST_DATA int parse_flags;
30 ST_DATA struct BufferedFile *file;
31 ST_DATA int ch, tok;
32 ST_DATA CValue tokc;
33 ST_DATA const int *macro_ptr;
34 ST_DATA CString tokcstr; /* current parsed string, if any */
36 /* display benchmark infos */
37 ST_DATA int tok_ident;
38 ST_DATA TokenSym **table_ident;
40 /* ------------------------------------------------------------------------- */
42 static TokenSym *hash_ident[TOK_HASH_SIZE];
43 static char token_buf[STRING_MAX_SIZE + 1];
44 static CString cstr_buf;
45 static CString macro_equal_buf;
46 static TokenString tokstr_buf;
47 static unsigned char isidnum_table[256 - CH_EOF];
48 static int pp_debug_tok, pp_debug_symv;
49 static int pp_once;
50 static int pp_expr;
51 static int pp_counter;
52 static void tok_print(const char *msg, const int *str);
54 static struct TinyAlloc *toksym_alloc;
55 static struct TinyAlloc *tokstr_alloc;
57 static TokenString *macro_stack;
59 static const char tcc_keywords[] =
60 #define DEF(id, str) str "\0"
61 #include "tcctok.h"
62 #undef DEF
65 /* WARNING: the content of this string encodes token numbers */
66 static const unsigned char tok_two_chars[] =
67 /* outdated -- gr
68 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
69 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
70 */{
71 '<','=', TOK_LE,
72 '>','=', TOK_GE,
73 '!','=', TOK_NE,
74 '&','&', TOK_LAND,
75 '|','|', TOK_LOR,
76 '+','+', TOK_INC,
77 '-','-', TOK_DEC,
78 '=','=', TOK_EQ,
79 '<','<', TOK_SHL,
80 '>','>', TOK_SAR,
81 '+','=', TOK_A_ADD,
82 '-','=', TOK_A_SUB,
83 '*','=', TOK_A_MUL,
84 '/','=', TOK_A_DIV,
85 '%','=', TOK_A_MOD,
86 '&','=', TOK_A_AND,
87 '^','=', TOK_A_XOR,
88 '|','=', TOK_A_OR,
89 '-','>', TOK_ARROW,
90 '.','.', TOK_TWODOTS,
91 '#','#', TOK_TWOSHARPS,
92 '#','#', TOK_PPJOIN,
96 static void next_nomacro(void);
98 ST_FUNC void skip(int c)
100 if (tok != c)
101 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
102 next();
105 ST_FUNC void expect(const char *msg)
107 tcc_error("%s expected", msg);
110 /* ------------------------------------------------------------------------- */
111 /* Custom allocator for tiny objects */
113 #define USE_TAL
115 #ifndef USE_TAL
116 #define tal_free(al, p) tcc_free(p)
117 #define tal_realloc(al, p, size) tcc_realloc(p, size)
118 #define tal_new(a,b,c)
119 #define tal_delete(a)
120 #else
121 #if !defined(MEM_DEBUG)
122 #define tal_free(al, p) tal_free_impl(al, p)
123 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
124 #define TAL_DEBUG_PARAMS
125 #else
126 #define TAL_DEBUG 1
127 //#define TAL_INFO 1 /* collect and dump allocators stats */
128 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
129 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
130 #define TAL_DEBUG_PARAMS , const char *file, int line
131 #define TAL_DEBUG_FILE_LEN 40
132 #endif
134 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
135 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
136 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
137 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
138 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
139 #define CSTR_TAL_LIMIT 1024
141 typedef struct TinyAlloc {
142 unsigned limit;
143 unsigned size;
144 uint8_t *buffer;
145 uint8_t *p;
146 unsigned nb_allocs;
147 struct TinyAlloc *next, *top;
148 #ifdef TAL_INFO
149 unsigned nb_peak;
150 unsigned nb_total;
151 unsigned nb_missed;
152 uint8_t *peak_p;
153 #endif
154 } TinyAlloc;
156 typedef struct tal_header_t {
157 unsigned size;
158 #ifdef TAL_DEBUG
159 int line_num; /* negative line_num used for double free check */
160 char file_name[TAL_DEBUG_FILE_LEN + 1];
161 #endif
162 } tal_header_t;
164 /* ------------------------------------------------------------------------- */
166 static TinyAlloc *tal_new(TinyAlloc **pal, unsigned limit, unsigned size)
168 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
169 al->p = al->buffer = tcc_malloc(size);
170 al->limit = limit;
171 al->size = size;
172 if (pal) *pal = al;
173 return al;
176 static void tal_delete(TinyAlloc *al)
178 TinyAlloc *next;
180 tail_call:
181 if (!al)
182 return;
183 #ifdef TAL_INFO
184 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
185 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
186 (al->peak_p - al->buffer) * 100.0 / al->size);
187 #endif
188 #ifdef TAL_DEBUG
189 if (al->nb_allocs > 0) {
190 uint8_t *p;
191 fprintf(stderr, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
192 al->nb_allocs, al->limit);
193 p = al->buffer;
194 while (p < al->p) {
195 tal_header_t *header = (tal_header_t *)p;
196 if (header->line_num > 0) {
197 fprintf(stderr, "%s:%d: chunk of %d bytes leaked\n",
198 header->file_name, header->line_num, header->size);
200 p += header->size + sizeof(tal_header_t);
202 #if MEM_DEBUG-0 == 2
203 exit(2);
204 #endif
206 #endif
207 next = al->next;
208 tcc_free(al->buffer);
209 tcc_free(al);
210 al = next;
211 goto tail_call;
214 static void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
216 if (!p)
217 return;
218 tail_call:
219 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
220 #ifdef TAL_DEBUG
221 tal_header_t *header = (((tal_header_t *)p) - 1);
222 if (header->line_num < 0) {
223 fprintf(stderr, "%s:%d: TAL_DEBUG: double frees chunk from\n",
224 file, line);
225 fprintf(stderr, "%s:%d: %d bytes\n",
226 header->file_name, (int)-header->line_num, (int)header->size);
227 } else
228 header->line_num = -header->line_num;
229 #endif
230 al->nb_allocs--;
231 if (!al->nb_allocs)
232 al->p = al->buffer;
233 } else if (al->next) {
234 al = al->next;
235 goto tail_call;
237 else
238 tcc_free(p);
241 static void *tal_realloc_impl(TinyAlloc **pal, void *p, unsigned size TAL_DEBUG_PARAMS)
243 tal_header_t *header;
244 void *ret;
245 int is_own;
246 unsigned adj_size = (size + 3) & -4;
247 TinyAlloc *al = *pal;
249 tail_call:
250 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
251 if ((!p || is_own) && size <= al->limit) {
252 if (al->p - al->buffer + adj_size + sizeof(tal_header_t) < al->size) {
253 header = (tal_header_t *)al->p;
254 header->size = adj_size;
255 #ifdef TAL_DEBUG
256 { int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
257 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
258 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
259 header->line_num = line; }
260 #endif
261 ret = al->p + sizeof(tal_header_t);
262 al->p += adj_size + sizeof(tal_header_t);
263 if (is_own) {
264 header = (((tal_header_t *)p) - 1);
265 if (p) memcpy(ret, p, header->size);
266 #ifdef TAL_DEBUG
267 header->line_num = -header->line_num;
268 #endif
269 } else {
270 al->nb_allocs++;
272 #ifdef TAL_INFO
273 if (al->nb_peak < al->nb_allocs)
274 al->nb_peak = al->nb_allocs;
275 if (al->peak_p < al->p)
276 al->peak_p = al->p;
277 al->nb_total++;
278 #endif
279 return ret;
280 } else if (is_own) {
281 al->nb_allocs--;
282 ret = tal_realloc(*pal, 0, size);
283 header = (((tal_header_t *)p) - 1);
284 if (p) memcpy(ret, p, header->size);
285 #ifdef TAL_DEBUG
286 header->line_num = -header->line_num;
287 #endif
288 return ret;
290 if (al->next) {
291 al = al->next;
292 } else {
293 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
295 al = tal_new(pal, next->limit, next->size * 2);
296 al->next = next;
297 bottom->top = al;
299 goto tail_call;
301 if (is_own) {
302 al->nb_allocs--;
303 ret = tcc_malloc(size);
304 header = (((tal_header_t *)p) - 1);
305 if (p) memcpy(ret, p, header->size);
306 #ifdef TAL_DEBUG
307 header->line_num = -header->line_num;
308 #endif
309 } else if (al->next) {
310 al = al->next;
311 goto tail_call;
312 } else
313 ret = tcc_realloc(p, size);
314 #ifdef TAL_INFO
315 al->nb_missed++;
316 #endif
317 return ret;
320 #endif /* USE_TAL */
322 /* ------------------------------------------------------------------------- */
323 /* CString handling */
324 static void cstr_realloc(CString *cstr, int new_size)
326 int size;
328 size = cstr->size_allocated;
329 if (size < 8)
330 size = 8; /* no need to allocate a too small first string */
331 while (size < new_size)
332 size = size * 2;
333 cstr->data = tcc_realloc(cstr->data, size);
334 cstr->size_allocated = size;
337 /* add a byte */
338 ST_INLN void cstr_ccat(CString *cstr, int ch)
340 int size;
341 size = cstr->size + 1;
342 if (size > cstr->size_allocated)
343 cstr_realloc(cstr, size);
344 ((unsigned char *)cstr->data)[size - 1] = ch;
345 cstr->size = size;
348 ST_INLN char *unicode_to_utf8 (char *b, uint32_t Uc)
350 if (Uc<0x80) *b++=Uc;
351 else if (Uc<0x800) *b++=192+Uc/64, *b++=128+Uc%64;
352 else if (Uc-0xd800u<0x800) goto error;
353 else if (Uc<0x10000) *b++=224+Uc/4096, *b++=128+Uc/64%64, *b++=128+Uc%64;
354 else if (Uc<0x110000) *b++=240+Uc/262144, *b++=128+Uc/4096%64, *b++=128+Uc/64%64, *b++=128+Uc%64;
355 else error: tcc_error("0x%x is not a valid universal character", Uc);
356 return b;
359 /* add a unicode character expanded into utf8 */
360 ST_INLN void cstr_u8cat(CString *cstr, int ch)
362 char buf[4], *e;
363 e = unicode_to_utf8(buf, (uint32_t)ch);
364 cstr_cat(cstr, buf, e - buf);
367 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
369 int size;
370 if (len <= 0)
371 len = strlen(str) + 1 + len;
372 size = cstr->size + len;
373 if (size > cstr->size_allocated)
374 cstr_realloc(cstr, size);
375 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
376 cstr->size = size;
379 /* add a wide char */
380 ST_FUNC void cstr_wccat(CString *cstr, int ch)
382 int size;
383 size = cstr->size + sizeof(nwchar_t);
384 if (size > cstr->size_allocated)
385 cstr_realloc(cstr, size);
386 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
387 cstr->size = size;
390 ST_FUNC void cstr_new(CString *cstr)
392 memset(cstr, 0, sizeof(CString));
395 /* free string and reset it to NULL */
396 ST_FUNC void cstr_free(CString *cstr)
398 tcc_free(cstr->data);
399 cstr_new(cstr);
402 /* reset string to empty */
403 ST_FUNC void cstr_reset(CString *cstr)
405 cstr->size = 0;
408 ST_FUNC int cstr_vprintf(CString *cstr, const char *fmt, va_list ap)
410 va_list v;
411 int len, size = 80;
412 for (;;) {
413 size += cstr->size;
414 if (size > cstr->size_allocated)
415 cstr_realloc(cstr, size);
416 size = cstr->size_allocated - cstr->size;
417 va_copy(v, ap);
418 len = vsnprintf((char*)cstr->data + cstr->size, size, fmt, v);
419 va_end(v);
420 if (len > 0 && len < size)
421 break;
422 size *= 2;
424 cstr->size += len;
425 return len;
428 ST_FUNC int cstr_printf(CString *cstr, const char *fmt, ...)
430 va_list ap; int len;
431 va_start(ap, fmt);
432 len = cstr_vprintf(cstr, fmt, ap);
433 va_end(ap);
434 return len;
437 /* XXX: unicode ? */
438 static void add_char(CString *cstr, int c)
440 if (c == '\'' || c == '\"' || c == '\\') {
441 /* XXX: could be more precise if char or string */
442 cstr_ccat(cstr, '\\');
444 if (c >= 32 && c <= 126) {
445 cstr_ccat(cstr, c);
446 } else {
447 cstr_ccat(cstr, '\\');
448 if (c == '\n') {
449 cstr_ccat(cstr, 'n');
450 } else {
451 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
452 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
453 cstr_ccat(cstr, '0' + (c & 7));
458 /* ------------------------------------------------------------------------- */
459 /* allocate a new token */
460 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
462 TokenSym *ts, **ptable;
463 int i;
465 if (tok_ident >= SYM_FIRST_ANOM)
466 tcc_error("memory full (symbols)");
468 /* expand token table if needed */
469 i = tok_ident - TOK_IDENT;
470 if ((i % TOK_ALLOC_INCR) == 0) {
471 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
472 table_ident = ptable;
475 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
476 table_ident[i] = ts;
477 ts->tok = tok_ident++;
478 ts->sym_define = NULL;
479 ts->sym_label = NULL;
480 ts->sym_struct = NULL;
481 ts->sym_identifier = NULL;
482 ts->len = len;
483 ts->hash_next = NULL;
484 memcpy(ts->str, str, len);
485 ts->str[len] = '\0';
486 *pts = ts;
487 return ts;
490 #define TOK_HASH_INIT 1
491 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
494 /* find a token and add it if not found */
495 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
497 TokenSym *ts, **pts;
498 int i;
499 unsigned int h;
501 h = TOK_HASH_INIT;
502 for(i=0;i<len;i++)
503 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
504 h &= (TOK_HASH_SIZE - 1);
506 pts = &hash_ident[h];
507 for(;;) {
508 ts = *pts;
509 if (!ts)
510 break;
511 if (ts->len == len && !memcmp(ts->str, str, len))
512 return ts;
513 pts = &(ts->hash_next);
515 return tok_alloc_new(pts, str, len);
518 ST_FUNC int tok_alloc_const(const char *str)
520 return tok_alloc(str, strlen(str))->tok;
524 /* XXX: buffer overflow */
525 /* XXX: float tokens */
526 ST_FUNC const char *get_tok_str(int v, CValue *cv)
528 char *p;
529 int i, len;
531 cstr_reset(&cstr_buf);
532 p = cstr_buf.data;
534 switch(v) {
535 case TOK_CINT:
536 case TOK_CUINT:
537 case TOK_CLONG:
538 case TOK_CULONG:
539 case TOK_CLLONG:
540 case TOK_CULLONG:
541 /* XXX: not quite exact, but only useful for testing */
542 #ifdef _WIN32
543 sprintf(p, "%u", (unsigned)cv->i);
544 #else
545 sprintf(p, "%llu", (unsigned long long)cv->i);
546 #endif
547 break;
548 case TOK_LCHAR:
549 cstr_ccat(&cstr_buf, 'L');
550 case TOK_CCHAR:
551 cstr_ccat(&cstr_buf, '\'');
552 add_char(&cstr_buf, cv->i);
553 cstr_ccat(&cstr_buf, '\'');
554 cstr_ccat(&cstr_buf, '\0');
555 break;
556 case TOK_PPNUM:
557 case TOK_PPSTR:
558 return (char*)cv->str.data;
559 case TOK_LSTR:
560 cstr_ccat(&cstr_buf, 'L');
561 case TOK_STR:
562 cstr_ccat(&cstr_buf, '\"');
563 if (v == TOK_STR) {
564 len = cv->str.size - 1;
565 for(i=0;i<len;i++)
566 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
567 } else {
568 len = (cv->str.size / sizeof(nwchar_t)) - 1;
569 for(i=0;i<len;i++)
570 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
572 cstr_ccat(&cstr_buf, '\"');
573 cstr_ccat(&cstr_buf, '\0');
574 break;
576 case TOK_CFLOAT:
577 cstr_cat(&cstr_buf, "<float>", 0);
578 break;
579 case TOK_CDOUBLE:
580 cstr_cat(&cstr_buf, "<double>", 0);
581 break;
582 case TOK_CLDOUBLE:
583 cstr_cat(&cstr_buf, "<long double>", 0);
584 break;
585 case TOK_LINENUM:
586 cstr_cat(&cstr_buf, "<linenumber>", 0);
587 break;
589 /* above tokens have value, the ones below don't */
590 case TOK_LT:
591 v = '<';
592 goto addv;
593 case TOK_GT:
594 v = '>';
595 goto addv;
596 case TOK_DOTS:
597 return strcpy(p, "...");
598 case TOK_A_SHL:
599 return strcpy(p, "<<=");
600 case TOK_A_SAR:
601 return strcpy(p, ">>=");
602 case TOK_EOF:
603 return strcpy(p, "<eof>");
604 default:
605 if (v < TOK_IDENT) {
606 /* search in two bytes table */
607 const unsigned char *q = tok_two_chars;
608 while (*q) {
609 if (q[2] == v) {
610 *p++ = q[0];
611 *p++ = q[1];
612 *p = '\0';
613 return cstr_buf.data;
615 q += 3;
617 if (v >= 127) {
618 sprintf(cstr_buf.data, "<%02x>", v);
619 return cstr_buf.data;
621 addv:
622 *p++ = v;
623 case 0: /* nameless anonymous symbol */
624 *p = '\0';
625 } else if (v < tok_ident) {
626 return table_ident[v - TOK_IDENT]->str;
627 } else if (v >= SYM_FIRST_ANOM) {
628 /* special name for anonymous symbol */
629 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
630 } else {
631 /* should never happen */
632 return NULL;
634 break;
636 return cstr_buf.data;
639 /* return the current character, handling end of block if necessary
640 (but not stray) */
641 static int handle_eob(void)
643 BufferedFile *bf = file;
644 int len;
646 /* only tries to read if really end of buffer */
647 if (bf->buf_ptr >= bf->buf_end) {
648 if (bf->fd >= 0) {
649 #if defined(PARSE_DEBUG)
650 len = 1;
651 #else
652 len = IO_BUF_SIZE;
653 #endif
654 len = read(bf->fd, bf->buffer, len);
655 if (len < 0)
656 len = 0;
657 } else {
658 len = 0;
660 total_bytes += len;
661 bf->buf_ptr = bf->buffer;
662 bf->buf_end = bf->buffer + len;
663 *bf->buf_end = CH_EOB;
665 if (bf->buf_ptr < bf->buf_end) {
666 return bf->buf_ptr[0];
667 } else {
668 bf->buf_ptr = bf->buf_end;
669 return CH_EOF;
673 /* read next char from current input file and handle end of input buffer */
674 static inline void inp(void)
676 ch = *(++(file->buf_ptr));
677 /* end of buffer/file handling */
678 if (ch == CH_EOB)
679 ch = handle_eob();
682 /* handle '\[\r]\n' */
683 static int handle_stray_noerror(void)
685 while (ch == '\\') {
686 inp();
687 if (ch == '\n') {
688 file->line_num++;
689 inp();
690 } else if (ch == '\r') {
691 inp();
692 if (ch != '\n')
693 goto fail;
694 file->line_num++;
695 inp();
696 } else {
697 fail:
698 return 1;
701 return 0;
704 static void handle_stray(void)
706 if (handle_stray_noerror())
707 tcc_error("stray '\\' in program");
710 /* skip the stray and handle the \\n case. Output an error if
711 incorrect char after the stray */
712 static int handle_stray1(uint8_t *p)
714 int c;
716 file->buf_ptr = p;
717 if (p >= file->buf_end) {
718 c = handle_eob();
719 if (c != '\\')
720 return c;
721 p = file->buf_ptr;
723 ch = *p;
724 if (handle_stray_noerror()) {
725 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
726 tcc_error("stray '\\' in program");
727 *--file->buf_ptr = '\\';
729 p = file->buf_ptr;
730 c = *p;
731 return c;
734 /* handle just the EOB case, but not stray */
735 #define PEEKC_EOB(c, p)\
737 p++;\
738 c = *p;\
739 if (c == '\\') {\
740 file->buf_ptr = p;\
741 c = handle_eob();\
742 p = file->buf_ptr;\
746 /* handle the complicated stray case */
747 #define PEEKC(c, p)\
749 p++;\
750 c = *p;\
751 if (c == '\\') {\
752 c = handle_stray1(p);\
753 p = file->buf_ptr;\
757 /* input with '\[\r]\n' handling. Note that this function cannot
758 handle other characters after '\', so you cannot call it inside
759 strings or comments */
760 static void minp(void)
762 inp();
763 if (ch == '\\')
764 handle_stray();
767 /* single line C++ comments */
768 static uint8_t *parse_line_comment(uint8_t *p)
770 int c;
772 p++;
773 for(;;) {
774 c = *p;
775 redo:
776 if (c == '\n' || c == CH_EOF) {
777 break;
778 } else if (c == '\\') {
779 file->buf_ptr = p;
780 c = handle_eob();
781 p = file->buf_ptr;
782 if (c == '\\') {
783 PEEKC_EOB(c, p);
784 if (c == '\n') {
785 file->line_num++;
786 PEEKC_EOB(c, p);
787 } else if (c == '\r') {
788 PEEKC_EOB(c, p);
789 if (c == '\n') {
790 file->line_num++;
791 PEEKC_EOB(c, p);
794 } else {
795 goto redo;
797 } else {
798 p++;
801 return p;
804 /* C comments */
805 static uint8_t *parse_comment(uint8_t *p)
807 int c;
809 p++;
810 for(;;) {
811 /* fast skip loop */
812 for(;;) {
813 c = *p;
814 if (c == '\n' || c == '*' || c == '\\')
815 break;
816 p++;
817 c = *p;
818 if (c == '\n' || c == '*' || c == '\\')
819 break;
820 p++;
822 /* now we can handle all the cases */
823 if (c == '\n') {
824 file->line_num++;
825 p++;
826 } else if (c == '*') {
827 p++;
828 for(;;) {
829 c = *p;
830 if (c == '*') {
831 p++;
832 } else if (c == '/') {
833 goto end_of_comment;
834 } else if (c == '\\') {
835 file->buf_ptr = p;
836 c = handle_eob();
837 p = file->buf_ptr;
838 if (c == CH_EOF)
839 tcc_error("unexpected end of file in comment");
840 if (c == '\\') {
841 /* skip '\[\r]\n', otherwise just skip the stray */
842 while (c == '\\') {
843 PEEKC_EOB(c, p);
844 if (c == '\n') {
845 file->line_num++;
846 PEEKC_EOB(c, p);
847 } else if (c == '\r') {
848 PEEKC_EOB(c, p);
849 if (c == '\n') {
850 file->line_num++;
851 PEEKC_EOB(c, p);
853 } else {
854 goto after_star;
858 } else {
859 break;
862 after_star: ;
863 } else {
864 /* stray, eob or eof */
865 file->buf_ptr = p;
866 c = handle_eob();
867 p = file->buf_ptr;
868 if (c == CH_EOF) {
869 tcc_error("unexpected end of file in comment");
870 } else if (c == '\\') {
871 p++;
875 end_of_comment:
876 p++;
877 return p;
880 ST_FUNC int set_idnum(int c, int val)
882 int prev = isidnum_table[c - CH_EOF];
883 isidnum_table[c - CH_EOF] = val;
884 return prev;
887 #define cinp minp
889 static inline void skip_spaces(void)
891 while (isidnum_table[ch - CH_EOF] & IS_SPC)
892 cinp();
895 static inline int check_space(int t, int *spc)
897 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
898 if (*spc)
899 return 1;
900 *spc = 1;
901 } else
902 *spc = 0;
903 return 0;
906 /* parse a string without interpreting escapes */
907 static uint8_t *parse_pp_string(uint8_t *p,
908 int sep, CString *str)
910 int c;
911 p++;
912 for(;;) {
913 c = *p;
914 if (c == sep) {
915 break;
916 } else if (c == '\\') {
917 file->buf_ptr = p;
918 c = handle_eob();
919 p = file->buf_ptr;
920 if (c == CH_EOF) {
921 unterminated_string:
922 /* XXX: indicate line number of start of string */
923 tcc_error("missing terminating %c character", sep);
924 } else if (c == '\\') {
925 /* escape : just skip \[\r]\n */
926 PEEKC_EOB(c, p);
927 if (c == '\n') {
928 file->line_num++;
929 p++;
930 } else if (c == '\r') {
931 PEEKC_EOB(c, p);
932 if (c != '\n')
933 expect("'\n' after '\r'");
934 file->line_num++;
935 p++;
936 } else if (c == CH_EOF) {
937 goto unterminated_string;
938 } else {
939 if (str) {
940 cstr_ccat(str, '\\');
941 cstr_ccat(str, c);
943 p++;
946 } else if (c == '\n') {
947 file->line_num++;
948 goto add_char;
949 } else if (c == '\r') {
950 PEEKC_EOB(c, p);
951 if (c != '\n') {
952 if (str)
953 cstr_ccat(str, '\r');
954 } else {
955 file->line_num++;
956 goto add_char;
958 } else {
959 add_char:
960 if (str)
961 cstr_ccat(str, c);
962 p++;
965 p++;
966 return p;
969 /* skip block of text until #else, #elif or #endif. skip also pairs of
970 #if/#endif */
971 static void preprocess_skip(void)
973 int a, start_of_line, c, in_warn_or_error;
974 uint8_t *p;
976 p = file->buf_ptr;
977 a = 0;
978 redo_start:
979 start_of_line = 1;
980 in_warn_or_error = 0;
981 for(;;) {
982 redo_no_start:
983 c = *p;
984 switch(c) {
985 case ' ':
986 case '\t':
987 case '\f':
988 case '\v':
989 case '\r':
990 p++;
991 goto redo_no_start;
992 case '\n':
993 file->line_num++;
994 p++;
995 goto redo_start;
996 case '\\':
997 file->buf_ptr = p;
998 c = handle_eob();
999 if (c == CH_EOF) {
1000 expect("#endif");
1001 } else if (c == '\\') {
1002 ch = file->buf_ptr[0];
1003 handle_stray_noerror();
1005 p = file->buf_ptr;
1006 goto redo_no_start;
1007 /* skip strings */
1008 case '\"':
1009 case '\'':
1010 if (in_warn_or_error)
1011 goto _default;
1012 p = parse_pp_string(p, c, NULL);
1013 break;
1014 /* skip comments */
1015 case '/':
1016 if (in_warn_or_error)
1017 goto _default;
1018 file->buf_ptr = p;
1019 ch = *p;
1020 minp();
1021 p = file->buf_ptr;
1022 if (ch == '*') {
1023 p = parse_comment(p);
1024 } else if (ch == '/') {
1025 p = parse_line_comment(p);
1027 break;
1028 case '#':
1029 p++;
1030 if (start_of_line) {
1031 file->buf_ptr = p;
1032 next_nomacro();
1033 p = file->buf_ptr;
1034 if (a == 0 &&
1035 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
1036 goto the_end;
1037 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
1038 a++;
1039 else if (tok == TOK_ENDIF)
1040 a--;
1041 else if( tok == TOK_ERROR || tok == TOK_WARNING)
1042 in_warn_or_error = 1;
1043 else if (tok == TOK_LINEFEED)
1044 goto redo_start;
1045 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1046 p = parse_line_comment(p - 1);
1048 #if !defined(TCC_TARGET_ARM)
1049 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1050 p = parse_line_comment(p - 1);
1051 #else
1052 /* ARM assembly uses '#' for constants */
1053 #endif
1054 break;
1055 _default:
1056 default:
1057 p++;
1058 break;
1060 start_of_line = 0;
1062 the_end: ;
1063 file->buf_ptr = p;
1066 #if 0
1067 /* return the number of additional 'ints' necessary to store the
1068 token */
1069 static inline int tok_size(const int *p)
1071 switch(*p) {
1072 /* 4 bytes */
1073 case TOK_CINT:
1074 case TOK_CUINT:
1075 case TOK_CCHAR:
1076 case TOK_LCHAR:
1077 case TOK_CFLOAT:
1078 case TOK_LINENUM:
1079 return 1 + 1;
1080 case TOK_STR:
1081 case TOK_LSTR:
1082 case TOK_PPNUM:
1083 case TOK_PPSTR:
1084 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1085 case TOK_CLONG:
1086 case TOK_CULONG:
1087 return 1 + LONG_SIZE / 4;
1088 case TOK_CDOUBLE:
1089 case TOK_CLLONG:
1090 case TOK_CULLONG:
1091 return 1 + 2;
1092 case TOK_CLDOUBLE:
1093 return 1 + LDOUBLE_SIZE / 4;
1094 default:
1095 return 1 + 0;
1098 #endif
1100 /* token string handling */
1101 ST_INLN void tok_str_new(TokenString *s)
1103 s->str = NULL;
1104 s->len = s->lastlen = 0;
1105 s->allocated_len = 0;
1106 s->last_line_num = -1;
1109 ST_FUNC TokenString *tok_str_alloc(void)
1111 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1112 tok_str_new(str);
1113 return str;
1116 ST_FUNC int *tok_str_dup(TokenString *s)
1118 int *str;
1120 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1121 memcpy(str, s->str, s->len * sizeof(int));
1122 return str;
1125 ST_FUNC void tok_str_free_str(int *str)
1127 tal_free(tokstr_alloc, str);
1130 ST_FUNC void tok_str_free(TokenString *str)
1132 tok_str_free_str(str->str);
1133 tal_free(tokstr_alloc, str);
1136 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1138 int *str, size;
1140 size = s->allocated_len;
1141 if (size < 16)
1142 size = 16;
1143 while (size < new_size)
1144 size = size * 2;
1145 if (size > s->allocated_len) {
1146 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1147 s->allocated_len = size;
1148 s->str = str;
1150 return s->str;
1153 ST_FUNC void tok_str_add(TokenString *s, int t)
1155 int len, *str;
1157 len = s->len;
1158 str = s->str;
1159 if (len >= s->allocated_len)
1160 str = tok_str_realloc(s, len + 1);
1161 str[len++] = t;
1162 s->len = len;
1165 ST_FUNC void begin_macro(TokenString *str, int alloc)
1167 str->alloc = alloc;
1168 str->prev = macro_stack;
1169 str->prev_ptr = macro_ptr;
1170 str->save_line_num = file->line_num;
1171 macro_ptr = str->str;
1172 macro_stack = str;
1175 ST_FUNC void end_macro(void)
1177 TokenString *str = macro_stack;
1178 macro_stack = str->prev;
1179 macro_ptr = str->prev_ptr;
1180 file->line_num = str->save_line_num;
1181 if (str->alloc != 0) {
1182 if (str->alloc == 2)
1183 str->str = NULL; /* don't free */
1184 tok_str_free(str);
1188 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1190 int len, *str;
1192 len = s->lastlen = s->len;
1193 str = s->str;
1195 /* allocate space for worst case */
1196 if (len + TOK_MAX_SIZE >= s->allocated_len)
1197 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1198 str[len++] = t;
1199 switch(t) {
1200 case TOK_CINT:
1201 case TOK_CUINT:
1202 case TOK_CCHAR:
1203 case TOK_LCHAR:
1204 case TOK_CFLOAT:
1205 case TOK_LINENUM:
1206 #if LONG_SIZE == 4
1207 case TOK_CLONG:
1208 case TOK_CULONG:
1209 #endif
1210 str[len++] = cv->tab[0];
1211 break;
1212 case TOK_PPNUM:
1213 case TOK_PPSTR:
1214 case TOK_STR:
1215 case TOK_LSTR:
1217 /* Insert the string into the int array. */
1218 size_t nb_words =
1219 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1220 if (len + nb_words >= s->allocated_len)
1221 str = tok_str_realloc(s, len + nb_words + 1);
1222 str[len] = cv->str.size;
1223 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1224 len += nb_words;
1226 break;
1227 case TOK_CDOUBLE:
1228 case TOK_CLLONG:
1229 case TOK_CULLONG:
1230 #if LONG_SIZE == 8
1231 case TOK_CLONG:
1232 case TOK_CULONG:
1233 #endif
1234 #if LDOUBLE_SIZE == 8
1235 case TOK_CLDOUBLE:
1236 #endif
1237 str[len++] = cv->tab[0];
1238 str[len++] = cv->tab[1];
1239 break;
1240 #if LDOUBLE_SIZE == 12
1241 case TOK_CLDOUBLE:
1242 str[len++] = cv->tab[0];
1243 str[len++] = cv->tab[1];
1244 str[len++] = cv->tab[2];
1245 #elif LDOUBLE_SIZE == 16
1246 case TOK_CLDOUBLE:
1247 str[len++] = cv->tab[0];
1248 str[len++] = cv->tab[1];
1249 str[len++] = cv->tab[2];
1250 str[len++] = cv->tab[3];
1251 #elif LDOUBLE_SIZE != 8
1252 #error add long double size support
1253 #endif
1254 break;
1255 default:
1256 break;
1258 s->len = len;
1261 /* add the current parse token in token string 's' */
1262 ST_FUNC void tok_str_add_tok(TokenString *s)
1264 CValue cval;
1266 /* save line number info */
1267 if (file->line_num != s->last_line_num) {
1268 s->last_line_num = file->line_num;
1269 cval.i = s->last_line_num;
1270 tok_str_add2(s, TOK_LINENUM, &cval);
1272 tok_str_add2(s, tok, &tokc);
1275 /* get a token from an integer array and increment pointer. */
1276 static inline void tok_get(int *t, const int **pp, CValue *cv)
1278 const int *p = *pp;
1279 int n, *tab;
1281 tab = cv->tab;
1282 switch(*t = *p++) {
1283 #if LONG_SIZE == 4
1284 case TOK_CLONG:
1285 #endif
1286 case TOK_CINT:
1287 case TOK_CCHAR:
1288 case TOK_LCHAR:
1289 case TOK_LINENUM:
1290 cv->i = *p++;
1291 break;
1292 #if LONG_SIZE == 4
1293 case TOK_CULONG:
1294 #endif
1295 case TOK_CUINT:
1296 cv->i = (unsigned)*p++;
1297 break;
1298 case TOK_CFLOAT:
1299 tab[0] = *p++;
1300 break;
1301 case TOK_STR:
1302 case TOK_LSTR:
1303 case TOK_PPNUM:
1304 case TOK_PPSTR:
1305 cv->str.size = *p++;
1306 cv->str.data = p;
1307 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1308 break;
1309 case TOK_CDOUBLE:
1310 case TOK_CLLONG:
1311 case TOK_CULLONG:
1312 #if LONG_SIZE == 8
1313 case TOK_CLONG:
1314 case TOK_CULONG:
1315 #endif
1316 n = 2;
1317 goto copy;
1318 case TOK_CLDOUBLE:
1319 #if LDOUBLE_SIZE == 16
1320 n = 4;
1321 #elif LDOUBLE_SIZE == 12
1322 n = 3;
1323 #elif LDOUBLE_SIZE == 8
1324 n = 2;
1325 #else
1326 # error add long double size support
1327 #endif
1328 copy:
1330 *tab++ = *p++;
1331 while (--n);
1332 break;
1333 default:
1334 break;
1336 *pp = p;
1339 #if 0
1340 # define TOK_GET(t,p,c) tok_get(t,p,c)
1341 #else
1342 # define TOK_GET(t,p,c) do { \
1343 int _t = **(p); \
1344 if (TOK_HAS_VALUE(_t)) \
1345 tok_get(t, p, c); \
1346 else \
1347 *(t) = _t, ++*(p); \
1348 } while (0)
1349 #endif
1351 static int macro_is_equal(const int *a, const int *b)
1353 CValue cv;
1354 int t;
1356 if (!a || !b)
1357 return 1;
1359 while (*a && *b) {
1360 /* first time preallocate macro_equal_buf, next time only reset position to start */
1361 cstr_reset(&macro_equal_buf);
1362 TOK_GET(&t, &a, &cv);
1363 cstr_cat(&macro_equal_buf, get_tok_str(t, &cv), 0);
1364 TOK_GET(&t, &b, &cv);
1365 if (strcmp(macro_equal_buf.data, get_tok_str(t, &cv)))
1366 return 0;
1368 return !(*a || *b);
1371 /* defines handling */
1372 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1374 Sym *s, *o;
1376 o = define_find(v);
1377 s = sym_push2(&define_stack, v, macro_type, 0);
1378 s->d = str;
1379 s->next = first_arg;
1380 table_ident[v - TOK_IDENT]->sym_define = s;
1382 if (o && !macro_is_equal(o->d, s->d))
1383 tcc_warning("%s redefined", get_tok_str(v, NULL));
1386 /* undefined a define symbol. Its name is just set to zero */
1387 ST_FUNC void define_undef(Sym *s)
1389 int v = s->v;
1390 if (v >= TOK_IDENT && v < tok_ident)
1391 table_ident[v - TOK_IDENT]->sym_define = NULL;
1394 ST_INLN Sym *define_find(int v)
1396 v -= TOK_IDENT;
1397 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1398 return NULL;
1399 return table_ident[v]->sym_define;
1402 /* free define stack until top reaches 'b' */
1403 ST_FUNC void free_defines(Sym *b)
1405 while (define_stack != b) {
1406 Sym *top = define_stack;
1407 define_stack = top->prev;
1408 tok_str_free_str(top->d);
1409 define_undef(top);
1410 sym_free(top);
1414 /* label lookup */
1415 ST_FUNC Sym *label_find(int v)
1417 v -= TOK_IDENT;
1418 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1419 return NULL;
1420 return table_ident[v]->sym_label;
1423 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1425 Sym *s, **ps;
1426 s = sym_push2(ptop, v, 0, 0);
1427 s->r = flags;
1428 ps = &table_ident[v - TOK_IDENT]->sym_label;
1429 if (ptop == &global_label_stack) {
1430 /* modify the top most local identifier, so that
1431 sym_identifier will point to 's' when popped */
1432 while (*ps != NULL)
1433 ps = &(*ps)->prev_tok;
1435 s->prev_tok = *ps;
1436 *ps = s;
1437 return s;
1440 /* pop labels until element last is reached. Look if any labels are
1441 undefined. Define symbols if '&&label' was used. */
1442 ST_FUNC void label_pop(Sym **ptop, Sym *slast, int keep)
1444 Sym *s, *s1;
1445 for(s = *ptop; s != slast; s = s1) {
1446 s1 = s->prev;
1447 if (s->r == LABEL_DECLARED) {
1448 tcc_warning_c(warn_all)("label '%s' declared but not used", get_tok_str(s->v, NULL));
1449 } else if (s->r == LABEL_FORWARD) {
1450 tcc_error("label '%s' used but not defined",
1451 get_tok_str(s->v, NULL));
1452 } else {
1453 if (s->c) {
1454 /* define corresponding symbol. A size of
1455 1 is put. */
1456 put_extern_sym(s, cur_text_section, s->jnext, 1);
1459 /* remove label */
1460 if (s->r != LABEL_GONE)
1461 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1462 if (!keep)
1463 sym_free(s);
1464 else
1465 s->r = LABEL_GONE;
1467 if (!keep)
1468 *ptop = slast;
1471 /* fake the nth "#if defined test_..." for tcc -dt -run */
1472 static void maybe_run_test(TCCState *s)
1474 const char *p;
1475 if (s->include_stack_ptr != s->include_stack)
1476 return;
1477 p = get_tok_str(tok, NULL);
1478 if (0 != memcmp(p, "test_", 5))
1479 return;
1480 if (0 != --s->run_test)
1481 return;
1482 fprintf(s->ppfp, &"\n[%s]\n"[!(s->dflag & 32)], p), fflush(s->ppfp);
1483 define_push(tok, MACRO_OBJ, NULL, NULL);
1486 /* eval an expression for #if/#elif */
1487 static int expr_preprocess(void)
1489 int c, t;
1490 TokenString *str;
1492 str = tok_str_alloc();
1493 pp_expr = 1;
1494 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1495 next(); /* do macro subst */
1496 redo:
1497 if (tok == TOK_DEFINED) {
1498 next_nomacro();
1499 t = tok;
1500 if (t == '(')
1501 next_nomacro();
1502 if (tok < TOK_IDENT)
1503 expect("identifier");
1504 if (tcc_state->run_test)
1505 maybe_run_test(tcc_state);
1506 c = define_find(tok) != 0;
1507 if (t == '(') {
1508 next_nomacro();
1509 if (tok != ')')
1510 expect("')'");
1512 tok = TOK_CINT;
1513 tokc.i = c;
1514 } else if (1 && tok == TOK___HAS_INCLUDE) {
1515 next(); /* XXX check if correct to use expansion */
1516 skip('(');
1517 while (tok != ')' && tok != TOK_EOF)
1518 next();
1519 if (tok != ')')
1520 expect("')'");
1521 tok = TOK_CINT;
1522 tokc.i = 0;
1523 } else if (tok >= TOK_IDENT) {
1524 /* if undefined macro, replace with zero, check for func-like */
1525 t = tok;
1526 tok = TOK_CINT;
1527 tokc.i = 0;
1528 tok_str_add_tok(str);
1529 next();
1530 if (tok == '(')
1531 tcc_error("function-like macro '%s' is not defined",
1532 get_tok_str(t, NULL));
1533 goto redo;
1535 tok_str_add_tok(str);
1537 pp_expr = 0;
1538 tok_str_add(str, -1); /* simulate end of file */
1539 tok_str_add(str, 0);
1540 /* now evaluate C constant expression */
1541 begin_macro(str, 1);
1542 next();
1543 c = expr_const();
1544 end_macro();
1545 return c != 0;
1549 /* parse after #define */
1550 ST_FUNC void parse_define(void)
1552 Sym *s, *first, **ps;
1553 int v, t, varg, is_vaargs, spc;
1554 int saved_parse_flags = parse_flags;
1556 v = tok;
1557 if (v < TOK_IDENT || v == TOK_DEFINED)
1558 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1559 /* XXX: should check if same macro (ANSI) */
1560 first = NULL;
1561 t = MACRO_OBJ;
1562 /* We have to parse the whole define as if not in asm mode, in particular
1563 no line comment with '#' must be ignored. Also for function
1564 macros the argument list must be parsed without '.' being an ID
1565 character. */
1566 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1567 /* '(' must be just after macro definition for MACRO_FUNC */
1568 next_nomacro();
1569 parse_flags &= ~PARSE_FLAG_SPACES;
1570 if (tok == '(') {
1571 int dotid = set_idnum('.', 0);
1572 next_nomacro();
1573 ps = &first;
1574 if (tok != ')') for (;;) {
1575 varg = tok;
1576 next_nomacro();
1577 is_vaargs = 0;
1578 if (varg == TOK_DOTS) {
1579 varg = TOK___VA_ARGS__;
1580 is_vaargs = 1;
1581 } else if (tok == TOK_DOTS && gnu_ext) {
1582 is_vaargs = 1;
1583 next_nomacro();
1585 if (varg < TOK_IDENT)
1586 bad_list:
1587 tcc_error("bad macro parameter list");
1588 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1589 *ps = s;
1590 ps = &s->next;
1591 if (tok == ')')
1592 break;
1593 if (tok != ',' || is_vaargs)
1594 goto bad_list;
1595 next_nomacro();
1597 parse_flags |= PARSE_FLAG_SPACES;
1598 next_nomacro();
1599 t = MACRO_FUNC;
1600 set_idnum('.', dotid);
1603 tokstr_buf.len = 0;
1604 spc = 2;
1605 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1606 /* The body of a macro definition should be parsed such that identifiers
1607 are parsed like the file mode determines (i.e. with '.' being an
1608 ID character in asm mode). But '#' should be retained instead of
1609 regarded as line comment leader, so still don't set ASM_FILE
1610 in parse_flags. */
1611 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1612 /* remove spaces around ## and after '#' */
1613 if (TOK_TWOSHARPS == tok) {
1614 if (2 == spc)
1615 goto bad_twosharp;
1616 if (1 == spc)
1617 --tokstr_buf.len;
1618 spc = 3;
1619 tok = TOK_PPJOIN;
1620 } else if ('#' == tok) {
1621 spc = 4;
1622 } else if (check_space(tok, &spc)) {
1623 goto skip;
1625 tok_str_add2(&tokstr_buf, tok, &tokc);
1626 skip:
1627 next_nomacro();
1630 parse_flags = saved_parse_flags;
1631 if (spc == 1)
1632 --tokstr_buf.len; /* remove trailing space */
1633 tok_str_add(&tokstr_buf, 0);
1634 if (3 == spc)
1635 bad_twosharp:
1636 tcc_error("'##' cannot appear at either end of macro");
1637 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1640 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1642 const unsigned char *s;
1643 unsigned int h;
1644 CachedInclude *e;
1645 int i;
1647 h = TOK_HASH_INIT;
1648 s = (unsigned char *) filename;
1649 while (*s) {
1650 #ifdef _WIN32
1651 h = TOK_HASH_FUNC(h, toup(*s));
1652 #else
1653 h = TOK_HASH_FUNC(h, *s);
1654 #endif
1655 s++;
1657 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1659 i = s1->cached_includes_hash[h];
1660 for(;;) {
1661 if (i == 0)
1662 break;
1663 e = s1->cached_includes[i - 1];
1664 if (0 == PATHCMP(e->filename, filename))
1665 return e;
1666 i = e->hash_next;
1668 if (!add)
1669 return NULL;
1671 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1672 strcpy(e->filename, filename);
1673 e->ifndef_macro = e->once = 0;
1674 dynarray_add(&s1->cached_includes, &s1->nb_cached_includes, e);
1675 /* add in hash table */
1676 e->hash_next = s1->cached_includes_hash[h];
1677 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1678 #ifdef INC_DEBUG
1679 printf("adding cached '%s'\n", filename);
1680 #endif
1681 return e;
1684 static void pragma_parse(TCCState *s1)
1686 next_nomacro();
1687 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1688 int t = tok, v;
1689 Sym *s;
1691 if (next(), tok != '(')
1692 goto pragma_err;
1693 if (next(), tok != TOK_STR)
1694 goto pragma_err;
1695 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1696 if (next(), tok != ')')
1697 goto pragma_err;
1698 if (t == TOK_push_macro) {
1699 while (NULL == (s = define_find(v)))
1700 define_push(v, 0, NULL, NULL);
1701 s->type.ref = s; /* set push boundary */
1702 } else {
1703 for (s = define_stack; s; s = s->prev)
1704 if (s->v == v && s->type.ref == s) {
1705 s->type.ref = NULL;
1706 break;
1709 if (s)
1710 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1711 else
1712 tcc_warning("unbalanced #pragma pop_macro");
1713 pp_debug_tok = t, pp_debug_symv = v;
1715 } else if (tok == TOK_once) {
1716 search_cached_include(s1, file->filename, 1)->once = pp_once;
1718 } else if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
1719 /* tcc -E: keep pragmas below unchanged */
1720 unget_tok(' ');
1721 unget_tok(TOK_PRAGMA);
1722 unget_tok('#');
1723 unget_tok(TOK_LINEFEED);
1725 } else if (tok == TOK_pack) {
1726 /* This may be:
1727 #pragma pack(1) // set
1728 #pragma pack() // reset to default
1729 #pragma pack(push) // push current
1730 #pragma pack(push,1) // push & set
1731 #pragma pack(pop) // restore previous */
1732 next();
1733 skip('(');
1734 if (tok == TOK_ASM_pop) {
1735 next();
1736 if (s1->pack_stack_ptr <= s1->pack_stack) {
1737 stk_error:
1738 tcc_error("out of pack stack");
1740 s1->pack_stack_ptr--;
1741 } else {
1742 int val = 0;
1743 if (tok != ')') {
1744 if (tok == TOK_ASM_push) {
1745 next();
1746 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1747 goto stk_error;
1748 val = *s1->pack_stack_ptr++;
1749 if (tok != ',')
1750 goto pack_set;
1751 next();
1753 if (tok != TOK_CINT)
1754 goto pragma_err;
1755 val = tokc.i;
1756 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1757 goto pragma_err;
1758 next();
1760 pack_set:
1761 *s1->pack_stack_ptr = val;
1763 if (tok != ')')
1764 goto pragma_err;
1766 } else if (tok == TOK_comment) {
1767 char *p; int t;
1768 next();
1769 skip('(');
1770 t = tok;
1771 next();
1772 skip(',');
1773 if (tok != TOK_STR)
1774 goto pragma_err;
1775 p = tcc_strdup((char *)tokc.str.data);
1776 next();
1777 if (tok != ')')
1778 goto pragma_err;
1779 if (t == TOK_lib) {
1780 dynarray_add(&s1->pragma_libs, &s1->nb_pragma_libs, p);
1781 } else {
1782 if (t == TOK_option)
1783 tcc_set_options(s1, p);
1784 tcc_free(p);
1787 } else
1788 tcc_warning_c(warn_unsupported)("#pragma %s ignored", get_tok_str(tok, &tokc));
1789 return;
1791 pragma_err:
1792 tcc_error("malformed #pragma directive");
1793 return;
1796 /* is_bof is true if first non space token at beginning of file */
1797 ST_FUNC void preprocess(int is_bof)
1799 TCCState *s1 = tcc_state;
1800 int i, c, n, saved_parse_flags;
1801 char buf[1024], *q;
1802 Sym *s;
1804 saved_parse_flags = parse_flags;
1805 parse_flags = PARSE_FLAG_PREPROCESS
1806 | PARSE_FLAG_TOK_NUM
1807 | PARSE_FLAG_TOK_STR
1808 | PARSE_FLAG_LINEFEED
1809 | (parse_flags & PARSE_FLAG_ASM_FILE)
1812 next_nomacro();
1813 redo:
1814 switch(tok) {
1815 case TOK_DEFINE:
1816 pp_debug_tok = tok;
1817 next_nomacro();
1818 pp_debug_symv = tok;
1819 parse_define();
1820 break;
1821 case TOK_UNDEF:
1822 pp_debug_tok = tok;
1823 next_nomacro();
1824 pp_debug_symv = tok;
1825 s = define_find(tok);
1826 /* undefine symbol by putting an invalid name */
1827 if (s)
1828 define_undef(s);
1829 break;
1830 case TOK_INCLUDE:
1831 case TOK_INCLUDE_NEXT:
1832 ch = file->buf_ptr[0];
1833 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1834 skip_spaces();
1835 if (ch == '<') {
1836 c = '>';
1837 goto read_name;
1838 } else if (ch == '\"') {
1839 c = ch;
1840 read_name:
1841 inp();
1842 q = buf;
1843 while (ch != c && ch != '\n' && ch != CH_EOF) {
1844 if ((q - buf) < sizeof(buf) - 1)
1845 *q++ = ch;
1846 if (ch == '\\') {
1847 if (handle_stray_noerror() == 0)
1848 --q;
1849 } else
1850 inp();
1852 *q = '\0';
1853 minp();
1854 #if 0
1855 /* eat all spaces and comments after include */
1856 /* XXX: slightly incorrect */
1857 while (ch1 != '\n' && ch1 != CH_EOF)
1858 inp();
1859 #endif
1860 } else {
1861 int len;
1862 /* computed #include : concatenate everything up to linefeed,
1863 the result must be one of the two accepted forms.
1864 Don't convert pp-tokens to tokens here. */
1865 parse_flags = (PARSE_FLAG_PREPROCESS
1866 | PARSE_FLAG_LINEFEED
1867 | (parse_flags & PARSE_FLAG_ASM_FILE));
1868 next();
1869 buf[0] = '\0';
1870 while (tok != TOK_LINEFEED) {
1871 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1872 next();
1874 len = strlen(buf);
1875 /* check syntax and remove '<>|""' */
1876 if ((len < 2 || ((buf[0] != '"' || buf[len-1] != '"') &&
1877 (buf[0] != '<' || buf[len-1] != '>'))))
1878 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1879 c = buf[len-1];
1880 memmove(buf, buf + 1, len - 2);
1881 buf[len - 2] = '\0';
1884 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1885 tcc_error("#include recursion too deep");
1886 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index + 1 : 0;
1887 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1888 for (; i < n; ++i) {
1889 char buf1[sizeof file->filename];
1890 CachedInclude *e;
1891 const char *path;
1893 if (i == 0) {
1894 /* check absolute include path */
1895 if (!IS_ABSPATH(buf))
1896 continue;
1897 buf1[0] = 0;
1899 } else if (i == 1) {
1900 /* search in file's dir if "header.h" */
1901 if (c != '\"')
1902 continue;
1903 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1904 path = file->true_filename;
1905 pstrncpy(buf1, path, tcc_basename(path) - path);
1907 } else {
1908 /* search in all the include paths */
1909 int j = i - 2, k = j - s1->nb_include_paths;
1910 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1911 pstrcpy(buf1, sizeof(buf1), path);
1912 pstrcat(buf1, sizeof(buf1), "/");
1915 pstrcat(buf1, sizeof(buf1), buf);
1916 e = search_cached_include(s1, buf1, 0);
1917 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1918 /* no need to parse the include because the 'ifndef macro'
1919 is defined (or had #pragma once) */
1920 #ifdef INC_DEBUG
1921 printf("%s: skipping cached %s\n", file->filename, buf1);
1922 #endif
1923 goto include_done;
1926 if (tcc_open(s1, buf1) < 0)
1927 continue;
1928 /* push previous file on stack */
1929 *s1->include_stack_ptr++ = file->prev;
1930 file->include_next_index = i;
1931 #ifdef INC_DEBUG
1932 printf("%s: including %s\n", file->prev->filename, file->filename);
1933 #endif
1934 /* update target deps */
1935 if (s1->gen_deps) {
1936 BufferedFile *bf = file;
1937 while (i == 1 && (bf = bf->prev))
1938 i = bf->include_next_index;
1939 /* skip system include files */
1940 if (s1->include_sys_deps || n - i > s1->nb_sysinclude_paths)
1941 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1942 tcc_strdup(buf1));
1944 /* add include file debug info */
1945 tcc_debug_bincl(tcc_state);
1946 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1947 ch = file->buf_ptr[0];
1948 goto the_end;
1950 tcc_error("include file '%s' not found", buf);
1951 include_done:
1952 break;
1953 case TOK_IFNDEF:
1954 c = 1;
1955 goto do_ifdef;
1956 case TOK_IF:
1957 c = expr_preprocess();
1958 goto do_if;
1959 case TOK_IFDEF:
1960 c = 0;
1961 do_ifdef:
1962 next_nomacro();
1963 if (tok < TOK_IDENT)
1964 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1965 if (is_bof) {
1966 if (c) {
1967 #ifdef INC_DEBUG
1968 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1969 #endif
1970 file->ifndef_macro = tok;
1973 c = (define_find(tok) != 0) ^ c;
1974 do_if:
1975 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1976 tcc_error("memory full (ifdef)");
1977 *s1->ifdef_stack_ptr++ = c;
1978 goto test_skip;
1979 case TOK_ELSE:
1980 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1981 tcc_error("#else without matching #if");
1982 if (s1->ifdef_stack_ptr[-1] & 2)
1983 tcc_error("#else after #else");
1984 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1985 goto test_else;
1986 case TOK_ELIF:
1987 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1988 tcc_error("#elif without matching #if");
1989 c = s1->ifdef_stack_ptr[-1];
1990 if (c > 1)
1991 tcc_error("#elif after #else");
1992 /* last #if/#elif expression was true: we skip */
1993 if (c == 1) {
1994 c = 0;
1995 } else {
1996 c = expr_preprocess();
1997 s1->ifdef_stack_ptr[-1] = c;
1999 test_else:
2000 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
2001 file->ifndef_macro = 0;
2002 test_skip:
2003 if (!(c & 1)) {
2004 preprocess_skip();
2005 is_bof = 0;
2006 goto redo;
2008 break;
2009 case TOK_ENDIF:
2010 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
2011 tcc_error("#endif without matching #if");
2012 s1->ifdef_stack_ptr--;
2013 /* '#ifndef macro' was at the start of file. Now we check if
2014 an '#endif' is exactly at the end of file */
2015 if (file->ifndef_macro &&
2016 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
2017 file->ifndef_macro_saved = file->ifndef_macro;
2018 /* need to set to zero to avoid false matches if another
2019 #ifndef at middle of file */
2020 file->ifndef_macro = 0;
2021 while (tok != TOK_LINEFEED)
2022 next_nomacro();
2023 tok_flags |= TOK_FLAG_ENDIF;
2024 goto the_end;
2026 break;
2027 case TOK_PPNUM:
2028 n = strtoul((char*)tokc.str.data, &q, 10);
2029 goto _line_num;
2030 case TOK_LINE:
2031 next();
2032 if (tok != TOK_CINT)
2033 _line_err:
2034 tcc_error("wrong #line format");
2035 n = tokc.i;
2036 _line_num:
2037 next();
2038 if (tok != TOK_LINEFEED) {
2039 if (tok == TOK_STR) {
2040 if (file->true_filename == file->filename)
2041 file->true_filename = tcc_strdup(file->filename);
2042 q = (char *)tokc.str.data;
2043 buf[0] = 0;
2044 if (!IS_ABSPATH(q)) {
2045 /* prepend directory from real file */
2046 pstrcpy(buf, sizeof buf, file->true_filename);
2047 *tcc_basename(buf) = 0;
2049 pstrcat(buf, sizeof buf, q);
2050 tcc_debug_putfile(s1, buf);
2051 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
2052 break;
2053 else
2054 goto _line_err;
2055 --n;
2057 if (file->fd > 0)
2058 total_lines += file->line_num - n;
2059 file->line_num = n;
2060 break;
2061 case TOK_ERROR:
2062 case TOK_WARNING:
2063 c = tok;
2064 ch = file->buf_ptr[0];
2065 skip_spaces();
2066 q = buf;
2067 while (ch != '\n' && ch != CH_EOF) {
2068 if ((q - buf) < sizeof(buf) - 1)
2069 *q++ = ch;
2070 if (ch == '\\') {
2071 if (handle_stray_noerror() == 0)
2072 --q;
2073 } else
2074 inp();
2076 *q = '\0';
2077 if (c == TOK_ERROR)
2078 tcc_error("#error %s", buf);
2079 else
2080 tcc_warning("#warning %s", buf);
2081 break;
2082 case TOK_PRAGMA:
2083 pragma_parse(s1);
2084 break;
2085 case TOK_LINEFEED:
2086 goto the_end;
2087 default:
2088 /* ignore gas line comment in an 'S' file. */
2089 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
2090 goto ignore;
2091 if (tok == '!' && is_bof)
2092 /* '!' is ignored at beginning to allow C scripts. */
2093 goto ignore;
2094 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
2095 ignore:
2096 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
2097 goto the_end;
2099 /* ignore other preprocess commands or #! for C scripts */
2100 while (tok != TOK_LINEFEED)
2101 next_nomacro();
2102 the_end:
2103 parse_flags = saved_parse_flags;
2106 /* evaluate escape codes in a string. */
2107 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
2109 int c, n, i;
2110 const uint8_t *p;
2112 p = buf;
2113 for(;;) {
2114 c = *p;
2115 if (c == '\0')
2116 break;
2117 if (c == '\\') {
2118 p++;
2119 /* escape */
2120 c = *p;
2121 switch(c) {
2122 case '0': case '1': case '2': case '3':
2123 case '4': case '5': case '6': case '7':
2124 /* at most three octal digits */
2125 n = c - '0';
2126 p++;
2127 c = *p;
2128 if (isoct(c)) {
2129 n = n * 8 + c - '0';
2130 p++;
2131 c = *p;
2132 if (isoct(c)) {
2133 n = n * 8 + c - '0';
2134 p++;
2137 c = n;
2138 goto add_char_nonext;
2139 case 'x': i = 0; goto parse_hex_or_ucn;
2140 case 'u': i = 4; goto parse_hex_or_ucn;
2141 case 'U': i = 8; goto parse_hex_or_ucn;
2142 parse_hex_or_ucn:
2143 p++;
2144 n = 0;
2145 do {
2146 c = *p;
2147 if (c >= 'a' && c <= 'f')
2148 c = c - 'a' + 10;
2149 else if (c >= 'A' && c <= 'F')
2150 c = c - 'A' + 10;
2151 else if (isnum(c))
2152 c = c - '0';
2153 else if (i > 0)
2154 expect("more hex digits in universal-character-name");
2155 else {
2156 c = n;
2157 goto add_char_nonext;
2159 n = n * 16 + c;
2160 p++;
2161 } while (--i);
2162 cstr_u8cat(outstr, n);
2163 continue;
2164 case 'a':
2165 c = '\a';
2166 break;
2167 case 'b':
2168 c = '\b';
2169 break;
2170 case 'f':
2171 c = '\f';
2172 break;
2173 case 'n':
2174 c = '\n';
2175 break;
2176 case 'r':
2177 c = '\r';
2178 break;
2179 case 't':
2180 c = '\t';
2181 break;
2182 case 'v':
2183 c = '\v';
2184 break;
2185 case 'e':
2186 if (!gnu_ext)
2187 goto invalid_escape;
2188 c = 27;
2189 break;
2190 case '\'':
2191 case '\"':
2192 case '\\':
2193 case '?':
2194 break;
2195 default:
2196 invalid_escape:
2197 if (c >= '!' && c <= '~')
2198 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2199 else
2200 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2201 break;
2203 } else if (is_long && c >= 0x80) {
2204 /* assume we are processing UTF-8 sequence */
2205 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2207 int cont; /* count of continuation bytes */
2208 int skip; /* how many bytes should skip when error occurred */
2209 int i;
2211 /* decode leading byte */
2212 if (c < 0xC2) {
2213 skip = 1; goto invalid_utf8_sequence;
2214 } else if (c <= 0xDF) {
2215 cont = 1; n = c & 0x1f;
2216 } else if (c <= 0xEF) {
2217 cont = 2; n = c & 0xf;
2218 } else if (c <= 0xF4) {
2219 cont = 3; n = c & 0x7;
2220 } else {
2221 skip = 1; goto invalid_utf8_sequence;
2224 /* decode continuation bytes */
2225 for (i = 1; i <= cont; i++) {
2226 int l = 0x80, h = 0xBF;
2228 /* adjust limit for second byte */
2229 if (i == 1) {
2230 switch (c) {
2231 case 0xE0: l = 0xA0; break;
2232 case 0xED: h = 0x9F; break;
2233 case 0xF0: l = 0x90; break;
2234 case 0xF4: h = 0x8F; break;
2238 if (p[i] < l || p[i] > h) {
2239 skip = i; goto invalid_utf8_sequence;
2242 n = (n << 6) | (p[i] & 0x3f);
2245 /* advance pointer */
2246 p += 1 + cont;
2247 c = n;
2248 goto add_char_nonext;
2250 /* error handling */
2251 invalid_utf8_sequence:
2252 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c);
2253 c = 0xFFFD;
2254 p += skip;
2255 goto add_char_nonext;
2258 p++;
2259 add_char_nonext:
2260 if (!is_long)
2261 cstr_ccat(outstr, c);
2262 else {
2263 #ifdef TCC_TARGET_PE
2264 /* store as UTF-16 */
2265 if (c < 0x10000) {
2266 cstr_wccat(outstr, c);
2267 } else {
2268 c -= 0x10000;
2269 cstr_wccat(outstr, (c >> 10) + 0xD800);
2270 cstr_wccat(outstr, (c & 0x3FF) + 0xDC00);
2272 #else
2273 cstr_wccat(outstr, c);
2274 #endif
2277 /* add a trailing '\0' */
2278 if (!is_long)
2279 cstr_ccat(outstr, '\0');
2280 else
2281 cstr_wccat(outstr, '\0');
2284 static void parse_string(const char *s, int len)
2286 uint8_t buf[1000], *p = buf;
2287 int is_long, sep;
2289 if ((is_long = *s == 'L'))
2290 ++s, --len;
2291 sep = *s++;
2292 len -= 2;
2293 if (len >= sizeof buf)
2294 p = tcc_malloc(len + 1);
2295 memcpy(p, s, len);
2296 p[len] = 0;
2298 cstr_reset(&tokcstr);
2299 parse_escape_string(&tokcstr, p, is_long);
2300 if (p != buf)
2301 tcc_free(p);
2303 if (sep == '\'') {
2304 int char_size, i, n, c;
2305 /* XXX: make it portable */
2306 if (!is_long)
2307 tok = TOK_CCHAR, char_size = 1;
2308 else
2309 tok = TOK_LCHAR, char_size = sizeof(nwchar_t);
2310 n = tokcstr.size / char_size - 1;
2311 if (n < 1)
2312 tcc_error("empty character constant");
2313 if (n > 1)
2314 tcc_warning_c(warn_all)("multi-character character constant");
2315 for (c = i = 0; i < n; ++i) {
2316 if (is_long)
2317 c = ((nwchar_t *)tokcstr.data)[i];
2318 else
2319 c = (c << 8) | ((char *)tokcstr.data)[i];
2321 tokc.i = c;
2322 } else {
2323 tokc.str.size = tokcstr.size;
2324 tokc.str.data = tokcstr.data;
2325 if (!is_long)
2326 tok = TOK_STR;
2327 else
2328 tok = TOK_LSTR;
2332 /* we use 64 bit numbers */
2333 #define BN_SIZE 2
2335 /* bn = (bn << shift) | or_val */
2336 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2338 int i;
2339 unsigned int v;
2340 for(i=0;i<BN_SIZE;i++) {
2341 v = bn[i];
2342 bn[i] = (v << shift) | or_val;
2343 or_val = v >> (32 - shift);
2347 static void bn_zero(unsigned int *bn)
2349 int i;
2350 for(i=0;i<BN_SIZE;i++) {
2351 bn[i] = 0;
2355 /* parse number in null terminated string 'p' and return it in the
2356 current token */
2357 static void parse_number(const char *p)
2359 int b, t, shift, frac_bits, s, exp_val, ch;
2360 char *q;
2361 unsigned int bn[BN_SIZE];
2362 double d;
2364 /* number */
2365 q = token_buf;
2366 ch = *p++;
2367 t = ch;
2368 ch = *p++;
2369 *q++ = t;
2370 b = 10;
2371 if (t == '.') {
2372 goto float_frac_parse;
2373 } else if (t == '0') {
2374 if (ch == 'x' || ch == 'X') {
2375 q--;
2376 ch = *p++;
2377 b = 16;
2378 } else if (tcc_state->tcc_ext && (ch == 'b' || ch == 'B')) {
2379 q--;
2380 ch = *p++;
2381 b = 2;
2384 /* parse all digits. cannot check octal numbers at this stage
2385 because of floating point constants */
2386 while (1) {
2387 if (ch >= 'a' && ch <= 'f')
2388 t = ch - 'a' + 10;
2389 else if (ch >= 'A' && ch <= 'F')
2390 t = ch - 'A' + 10;
2391 else if (isnum(ch))
2392 t = ch - '0';
2393 else
2394 break;
2395 if (t >= b)
2396 break;
2397 if (q >= token_buf + STRING_MAX_SIZE) {
2398 num_too_long:
2399 tcc_error("number too long");
2401 *q++ = ch;
2402 ch = *p++;
2404 if (ch == '.' ||
2405 ((ch == 'e' || ch == 'E') && b == 10) ||
2406 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2407 if (b != 10) {
2408 /* NOTE: strtox should support that for hexa numbers, but
2409 non ISOC99 libcs do not support it, so we prefer to do
2410 it by hand */
2411 /* hexadecimal or binary floats */
2412 /* XXX: handle overflows */
2413 *q = '\0';
2414 if (b == 16)
2415 shift = 4;
2416 else
2417 shift = 1;
2418 bn_zero(bn);
2419 q = token_buf;
2420 while (1) {
2421 t = *q++;
2422 if (t == '\0') {
2423 break;
2424 } else if (t >= 'a') {
2425 t = t - 'a' + 10;
2426 } else if (t >= 'A') {
2427 t = t - 'A' + 10;
2428 } else {
2429 t = t - '0';
2431 bn_lshift(bn, shift, t);
2433 frac_bits = 0;
2434 if (ch == '.') {
2435 ch = *p++;
2436 while (1) {
2437 t = ch;
2438 if (t >= 'a' && t <= 'f') {
2439 t = t - 'a' + 10;
2440 } else if (t >= 'A' && t <= 'F') {
2441 t = t - 'A' + 10;
2442 } else if (t >= '0' && t <= '9') {
2443 t = t - '0';
2444 } else {
2445 break;
2447 if (t >= b)
2448 tcc_error("invalid digit");
2449 bn_lshift(bn, shift, t);
2450 frac_bits += shift;
2451 ch = *p++;
2454 if (ch != 'p' && ch != 'P')
2455 expect("exponent");
2456 ch = *p++;
2457 s = 1;
2458 exp_val = 0;
2459 if (ch == '+') {
2460 ch = *p++;
2461 } else if (ch == '-') {
2462 s = -1;
2463 ch = *p++;
2465 if (ch < '0' || ch > '9')
2466 expect("exponent digits");
2467 while (ch >= '0' && ch <= '9') {
2468 exp_val = exp_val * 10 + ch - '0';
2469 ch = *p++;
2471 exp_val = exp_val * s;
2473 /* now we can generate the number */
2474 /* XXX: should patch directly float number */
2475 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2476 d = ldexp(d, exp_val - frac_bits);
2477 t = toup(ch);
2478 if (t == 'F') {
2479 ch = *p++;
2480 tok = TOK_CFLOAT;
2481 /* float : should handle overflow */
2482 tokc.f = (float)d;
2483 } else if (t == 'L') {
2484 ch = *p++;
2485 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2486 tok = TOK_CDOUBLE;
2487 tokc.d = d;
2488 #else
2489 tok = TOK_CLDOUBLE;
2490 /* XXX: not large enough */
2491 tokc.ld = (long double)d;
2492 #endif
2493 } else {
2494 tok = TOK_CDOUBLE;
2495 tokc.d = d;
2497 } else {
2498 /* decimal floats */
2499 if (ch == '.') {
2500 if (q >= token_buf + STRING_MAX_SIZE)
2501 goto num_too_long;
2502 *q++ = ch;
2503 ch = *p++;
2504 float_frac_parse:
2505 while (ch >= '0' && ch <= '9') {
2506 if (q >= token_buf + STRING_MAX_SIZE)
2507 goto num_too_long;
2508 *q++ = ch;
2509 ch = *p++;
2512 if (ch == 'e' || ch == 'E') {
2513 if (q >= token_buf + STRING_MAX_SIZE)
2514 goto num_too_long;
2515 *q++ = ch;
2516 ch = *p++;
2517 if (ch == '-' || ch == '+') {
2518 if (q >= token_buf + STRING_MAX_SIZE)
2519 goto num_too_long;
2520 *q++ = ch;
2521 ch = *p++;
2523 if (ch < '0' || ch > '9')
2524 expect("exponent digits");
2525 while (ch >= '0' && ch <= '9') {
2526 if (q >= token_buf + STRING_MAX_SIZE)
2527 goto num_too_long;
2528 *q++ = ch;
2529 ch = *p++;
2532 *q = '\0';
2533 t = toup(ch);
2534 errno = 0;
2535 if (t == 'F') {
2536 ch = *p++;
2537 tok = TOK_CFLOAT;
2538 tokc.f = strtof(token_buf, NULL);
2539 } else if (t == 'L') {
2540 ch = *p++;
2541 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2542 tok = TOK_CDOUBLE;
2543 tokc.d = strtod(token_buf, NULL);
2544 #else
2545 tok = TOK_CLDOUBLE;
2546 tokc.ld = strtold(token_buf, NULL);
2547 #endif
2548 } else {
2549 tok = TOK_CDOUBLE;
2550 tokc.d = strtod(token_buf, NULL);
2553 } else {
2554 unsigned long long n, n1;
2555 int lcount, ucount, ov = 0;
2556 const char *p1;
2558 /* integer number */
2559 *q = '\0';
2560 q = token_buf;
2561 if (b == 10 && *q == '0') {
2562 b = 8;
2563 q++;
2565 n = 0;
2566 while(1) {
2567 t = *q++;
2568 /* no need for checks except for base 10 / 8 errors */
2569 if (t == '\0')
2570 break;
2571 else if (t >= 'a')
2572 t = t - 'a' + 10;
2573 else if (t >= 'A')
2574 t = t - 'A' + 10;
2575 else
2576 t = t - '0';
2577 if (t >= b)
2578 tcc_error("invalid digit");
2579 n1 = n;
2580 n = n * b + t;
2581 /* detect overflow */
2582 if (n1 >= 0x1000000000000000ULL && n / b != n1)
2583 ov = 1;
2586 /* Determine the characteristics (unsigned and/or 64bit) the type of
2587 the constant must have according to the constant suffix(es) */
2588 lcount = ucount = 0;
2589 p1 = p;
2590 for(;;) {
2591 t = toup(ch);
2592 if (t == 'L') {
2593 if (lcount >= 2)
2594 tcc_error("three 'l's in integer constant");
2595 if (lcount && *(p - 1) != ch)
2596 tcc_error("incorrect integer suffix: %s", p1);
2597 lcount++;
2598 ch = *p++;
2599 } else if (t == 'U') {
2600 if (ucount >= 1)
2601 tcc_error("two 'u's in integer constant");
2602 ucount++;
2603 ch = *p++;
2604 } else {
2605 break;
2609 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2610 if (ucount == 0 && b == 10) {
2611 if (lcount <= (LONG_SIZE == 4)) {
2612 if (n >= 0x80000000U)
2613 lcount = (LONG_SIZE == 4) + 1;
2615 if (n >= 0x8000000000000000ULL)
2616 ov = 1, ucount = 1;
2617 } else {
2618 if (lcount <= (LONG_SIZE == 4)) {
2619 if (n >= 0x100000000ULL)
2620 lcount = (LONG_SIZE == 4) + 1;
2621 else if (n >= 0x80000000U)
2622 ucount = 1;
2624 if (n >= 0x8000000000000000ULL)
2625 ucount = 1;
2628 if (ov)
2629 tcc_warning("integer constant overflow");
2631 tok = TOK_CINT;
2632 if (lcount) {
2633 tok = TOK_CLONG;
2634 if (lcount == 2)
2635 tok = TOK_CLLONG;
2637 if (ucount)
2638 ++tok; /* TOK_CU... */
2639 tokc.i = n;
2641 if (ch)
2642 tcc_error("invalid number");
2646 #define PARSE2(c1, tok1, c2, tok2) \
2647 case c1: \
2648 PEEKC(c, p); \
2649 if (c == c2) { \
2650 p++; \
2651 tok = tok2; \
2652 } else { \
2653 tok = tok1; \
2655 break;
2657 /* return next token without macro substitution */
2658 static inline void next_nomacro1(void)
2660 int t, c, is_long, len;
2661 TokenSym *ts;
2662 uint8_t *p, *p1;
2663 unsigned int h;
2665 p = file->buf_ptr;
2666 redo_no_start:
2667 c = *p;
2668 switch(c) {
2669 case ' ':
2670 case '\t':
2671 tok = c;
2672 p++;
2673 maybe_space:
2674 if (parse_flags & PARSE_FLAG_SPACES)
2675 goto keep_tok_flags;
2676 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2677 ++p;
2678 goto redo_no_start;
2679 case '\f':
2680 case '\v':
2681 case '\r':
2682 p++;
2683 goto redo_no_start;
2684 case '\\':
2685 /* first look if it is in fact an end of buffer */
2686 c = handle_stray1(p);
2687 p = file->buf_ptr;
2688 if (c == '\\')
2689 goto parse_simple;
2690 if (c != CH_EOF)
2691 goto redo_no_start;
2693 TCCState *s1 = tcc_state;
2694 if ((parse_flags & PARSE_FLAG_LINEFEED)
2695 && !(tok_flags & TOK_FLAG_EOF)) {
2696 tok_flags |= TOK_FLAG_EOF;
2697 tok = TOK_LINEFEED;
2698 goto keep_tok_flags;
2699 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2700 tok = TOK_EOF;
2701 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2702 tcc_error("missing #endif");
2703 } else if (s1->include_stack_ptr == s1->include_stack) {
2704 /* no include left : end of file. */
2705 tok = TOK_EOF;
2706 } else {
2707 tok_flags &= ~TOK_FLAG_EOF;
2708 /* pop include file */
2710 /* test if previous '#endif' was after a #ifdef at
2711 start of file */
2712 if (tok_flags & TOK_FLAG_ENDIF) {
2713 #ifdef INC_DEBUG
2714 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2715 #endif
2716 search_cached_include(s1, file->filename, 1)
2717 ->ifndef_macro = file->ifndef_macro_saved;
2718 tok_flags &= ~TOK_FLAG_ENDIF;
2721 /* add end of include file debug info */
2722 tcc_debug_eincl(tcc_state);
2723 /* pop include stack */
2724 tcc_close();
2725 s1->include_stack_ptr--;
2726 p = file->buf_ptr;
2727 if (p == file->buffer)
2728 tok_flags = TOK_FLAG_BOF|TOK_FLAG_BOL;
2729 goto redo_no_start;
2732 break;
2734 case '\n':
2735 file->line_num++;
2736 tok_flags |= TOK_FLAG_BOL;
2737 p++;
2738 maybe_newline:
2739 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2740 goto redo_no_start;
2741 tok = TOK_LINEFEED;
2742 goto keep_tok_flags;
2744 case '#':
2745 /* XXX: simplify */
2746 PEEKC(c, p);
2747 if ((tok_flags & TOK_FLAG_BOL) &&
2748 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2749 file->buf_ptr = p;
2750 preprocess(tok_flags & TOK_FLAG_BOF);
2751 p = file->buf_ptr;
2752 goto maybe_newline;
2753 } else {
2754 if (c == '#') {
2755 p++;
2756 tok = TOK_TWOSHARPS;
2757 } else {
2758 #if !defined(TCC_TARGET_ARM)
2759 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2760 p = parse_line_comment(p - 1);
2761 goto redo_no_start;
2762 } else
2763 #endif
2765 tok = '#';
2769 break;
2771 /* dollar is allowed to start identifiers when not parsing asm */
2772 case '$':
2773 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2774 || (parse_flags & PARSE_FLAG_ASM_FILE))
2775 goto parse_simple;
2777 case 'a': case 'b': case 'c': case 'd':
2778 case 'e': case 'f': case 'g': case 'h':
2779 case 'i': case 'j': case 'k': case 'l':
2780 case 'm': case 'n': case 'o': case 'p':
2781 case 'q': case 'r': case 's': case 't':
2782 case 'u': case 'v': case 'w': case 'x':
2783 case 'y': case 'z':
2784 case 'A': case 'B': case 'C': case 'D':
2785 case 'E': case 'F': case 'G': case 'H':
2786 case 'I': case 'J': case 'K':
2787 case 'M': case 'N': case 'O': case 'P':
2788 case 'Q': case 'R': case 'S': case 'T':
2789 case 'U': case 'V': case 'W': case 'X':
2790 case 'Y': case 'Z':
2791 case '_':
2792 parse_ident_fast:
2793 p1 = p;
2794 h = TOK_HASH_INIT;
2795 h = TOK_HASH_FUNC(h, c);
2796 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2797 h = TOK_HASH_FUNC(h, c);
2798 len = p - p1;
2799 if (c != '\\') {
2800 TokenSym **pts;
2802 /* fast case : no stray found, so we have the full token
2803 and we have already hashed it */
2804 h &= (TOK_HASH_SIZE - 1);
2805 pts = &hash_ident[h];
2806 for(;;) {
2807 ts = *pts;
2808 if (!ts)
2809 break;
2810 if (ts->len == len && !memcmp(ts->str, p1, len))
2811 goto token_found;
2812 pts = &(ts->hash_next);
2814 ts = tok_alloc_new(pts, (char *) p1, len);
2815 token_found: ;
2816 } else {
2817 /* slower case */
2818 cstr_reset(&tokcstr);
2819 cstr_cat(&tokcstr, (char *) p1, len);
2820 p--;
2821 PEEKC(c, p);
2822 parse_ident_slow:
2823 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2825 cstr_ccat(&tokcstr, c);
2826 PEEKC(c, p);
2828 ts = tok_alloc(tokcstr.data, tokcstr.size);
2830 tok = ts->tok;
2831 break;
2832 case 'L':
2833 t = p[1];
2834 if (t != '\\' && t != '\'' && t != '\"') {
2835 /* fast case */
2836 goto parse_ident_fast;
2837 } else {
2838 PEEKC(c, p);
2839 if (c == '\'' || c == '\"') {
2840 is_long = 1;
2841 goto str_const;
2842 } else {
2843 cstr_reset(&tokcstr);
2844 cstr_ccat(&tokcstr, 'L');
2845 goto parse_ident_slow;
2848 break;
2850 case '0': case '1': case '2': case '3':
2851 case '4': case '5': case '6': case '7':
2852 case '8': case '9':
2853 t = c;
2854 PEEKC(c, p);
2855 /* after the first digit, accept digits, alpha, '.' or sign if
2856 prefixed by 'eEpP' */
2857 parse_num:
2858 cstr_reset(&tokcstr);
2859 for(;;) {
2860 cstr_ccat(&tokcstr, t);
2861 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2862 || c == '.'
2863 || ((c == '+' || c == '-')
2864 && (((t == 'e' || t == 'E')
2865 && !(parse_flags & PARSE_FLAG_ASM_FILE
2866 /* 0xe+1 is 3 tokens in asm */
2867 && ((char*)tokcstr.data)[0] == '0'
2868 && toup(((char*)tokcstr.data)[1]) == 'X'))
2869 || t == 'p' || t == 'P'))))
2870 break;
2871 t = c;
2872 PEEKC(c, p);
2874 /* We add a trailing '\0' to ease parsing */
2875 cstr_ccat(&tokcstr, '\0');
2876 tokc.str.size = tokcstr.size;
2877 tokc.str.data = tokcstr.data;
2878 tok = TOK_PPNUM;
2879 break;
2881 case '.':
2882 /* special dot handling because it can also start a number */
2883 PEEKC(c, p);
2884 if (isnum(c)) {
2885 t = '.';
2886 goto parse_num;
2887 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2888 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2889 *--p = c = '.';
2890 goto parse_ident_fast;
2891 } else if (c == '.') {
2892 PEEKC(c, p);
2893 if (c == '.') {
2894 p++;
2895 tok = TOK_DOTS;
2896 } else {
2897 *--p = '.'; /* may underflow into file->unget[] */
2898 tok = '.';
2900 } else {
2901 tok = '.';
2903 break;
2904 case '\'':
2905 case '\"':
2906 is_long = 0;
2907 str_const:
2908 cstr_reset(&tokcstr);
2909 if (is_long)
2910 cstr_ccat(&tokcstr, 'L');
2911 cstr_ccat(&tokcstr, c);
2912 p = parse_pp_string(p, c, &tokcstr);
2913 cstr_ccat(&tokcstr, c);
2914 cstr_ccat(&tokcstr, '\0');
2915 tokc.str.size = tokcstr.size;
2916 tokc.str.data = tokcstr.data;
2917 tok = TOK_PPSTR;
2918 break;
2920 case '<':
2921 PEEKC(c, p);
2922 if (c == '=') {
2923 p++;
2924 tok = TOK_LE;
2925 } else if (c == '<') {
2926 PEEKC(c, p);
2927 if (c == '=') {
2928 p++;
2929 tok = TOK_A_SHL;
2930 } else {
2931 tok = TOK_SHL;
2933 } else {
2934 tok = TOK_LT;
2936 break;
2937 case '>':
2938 PEEKC(c, p);
2939 if (c == '=') {
2940 p++;
2941 tok = TOK_GE;
2942 } else if (c == '>') {
2943 PEEKC(c, p);
2944 if (c == '=') {
2945 p++;
2946 tok = TOK_A_SAR;
2947 } else {
2948 tok = TOK_SAR;
2950 } else {
2951 tok = TOK_GT;
2953 break;
2955 case '&':
2956 PEEKC(c, p);
2957 if (c == '&') {
2958 p++;
2959 tok = TOK_LAND;
2960 } else if (c == '=') {
2961 p++;
2962 tok = TOK_A_AND;
2963 } else {
2964 tok = '&';
2966 break;
2968 case '|':
2969 PEEKC(c, p);
2970 if (c == '|') {
2971 p++;
2972 tok = TOK_LOR;
2973 } else if (c == '=') {
2974 p++;
2975 tok = TOK_A_OR;
2976 } else {
2977 tok = '|';
2979 break;
2981 case '+':
2982 PEEKC(c, p);
2983 if (c == '+') {
2984 p++;
2985 tok = TOK_INC;
2986 } else if (c == '=') {
2987 p++;
2988 tok = TOK_A_ADD;
2989 } else {
2990 tok = '+';
2992 break;
2994 case '-':
2995 PEEKC(c, p);
2996 if (c == '-') {
2997 p++;
2998 tok = TOK_DEC;
2999 } else if (c == '=') {
3000 p++;
3001 tok = TOK_A_SUB;
3002 } else if (c == '>') {
3003 p++;
3004 tok = TOK_ARROW;
3005 } else {
3006 tok = '-';
3008 break;
3010 PARSE2('!', '!', '=', TOK_NE)
3011 PARSE2('=', '=', '=', TOK_EQ)
3012 PARSE2('*', '*', '=', TOK_A_MUL)
3013 PARSE2('%', '%', '=', TOK_A_MOD)
3014 PARSE2('^', '^', '=', TOK_A_XOR)
3016 /* comments or operator */
3017 case '/':
3018 PEEKC(c, p);
3019 if (c == '*') {
3020 p = parse_comment(p);
3021 /* comments replaced by a blank */
3022 tok = ' ';
3023 goto maybe_space;
3024 } else if (c == '/') {
3025 p = parse_line_comment(p);
3026 tok = ' ';
3027 goto maybe_space;
3028 } else if (c == '=') {
3029 p++;
3030 tok = TOK_A_DIV;
3031 } else {
3032 tok = '/';
3034 break;
3036 /* simple tokens */
3037 case '(':
3038 case ')':
3039 case '[':
3040 case ']':
3041 case '{':
3042 case '}':
3043 case ',':
3044 case ';':
3045 case ':':
3046 case '?':
3047 case '~':
3048 case '@': /* only used in assembler */
3049 parse_simple:
3050 tok = c;
3051 p++;
3052 break;
3053 default:
3054 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
3055 goto parse_ident_fast;
3056 if (parse_flags & PARSE_FLAG_ASM_FILE)
3057 goto parse_simple;
3058 tcc_error("unrecognized character \\x%02x", c);
3059 break;
3061 tok_flags = 0;
3062 keep_tok_flags:
3063 file->buf_ptr = p;
3064 #if defined(PARSE_DEBUG)
3065 printf("token = %d %s\n", tok, get_tok_str(tok, &tokc));
3066 #endif
3069 static void macro_subst(
3070 TokenString *tok_str,
3071 Sym **nested_list,
3072 const int *macro_str
3075 /* substitute arguments in replacement lists in macro_str by the values in
3076 args (field d) and return allocated string */
3077 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
3079 int t, t0, t1, spc;
3080 const int *st;
3081 Sym *s;
3082 CValue cval;
3083 TokenString str;
3084 CString cstr;
3086 tok_str_new(&str);
3087 t0 = t1 = 0;
3088 while(1) {
3089 TOK_GET(&t, &macro_str, &cval);
3090 if (!t)
3091 break;
3092 if (t == '#') {
3093 /* stringize */
3094 TOK_GET(&t, &macro_str, &cval);
3095 if (!t)
3096 goto bad_stringy;
3097 s = sym_find2(args, t);
3098 if (s) {
3099 cstr_new(&cstr);
3100 cstr_ccat(&cstr, '\"');
3101 st = s->d;
3102 spc = 0;
3103 while (*st >= 0) {
3104 TOK_GET(&t, &st, &cval);
3105 if (t != TOK_PLCHLDR
3106 && t != TOK_NOSUBST
3107 && 0 == check_space(t, &spc)) {
3108 const char *s = get_tok_str(t, &cval);
3109 while (*s) {
3110 if (t == TOK_PPSTR && *s != '\'')
3111 add_char(&cstr, *s);
3112 else
3113 cstr_ccat(&cstr, *s);
3114 ++s;
3118 cstr.size -= spc;
3119 cstr_ccat(&cstr, '\"');
3120 cstr_ccat(&cstr, '\0');
3121 #ifdef PP_DEBUG
3122 printf("\nstringize: <%s>\n", (char *)cstr.data);
3123 #endif
3124 /* add string */
3125 cval.str.size = cstr.size;
3126 cval.str.data = cstr.data;
3127 tok_str_add2(&str, TOK_PPSTR, &cval);
3128 cstr_free(&cstr);
3129 } else {
3130 bad_stringy:
3131 expect("macro parameter after '#'");
3133 } else if (t >= TOK_IDENT) {
3134 s = sym_find2(args, t);
3135 if (s) {
3136 int l0 = str.len;
3137 st = s->d;
3138 /* if '##' is present before or after, no arg substitution */
3139 if (*macro_str == TOK_PPJOIN || t1 == TOK_PPJOIN) {
3140 /* special case for var arg macros : ## eats the ','
3141 if empty VA_ARGS variable. */
3142 if (t1 == TOK_PPJOIN && t0 == ',' && gnu_ext && s->type.t) {
3143 if (*st <= 0) {
3144 /* suppress ',' '##' */
3145 str.len -= 2;
3146 } else {
3147 /* suppress '##' and add variable */
3148 str.len--;
3149 goto add_var;
3152 } else {
3153 add_var:
3154 if (!s->next) {
3155 /* Expand arguments tokens and store them. In most
3156 cases we could also re-expand each argument if
3157 used multiple times, but not if the argument
3158 contains the __COUNTER__ macro. */
3159 TokenString str2;
3160 sym_push2(&s->next, s->v, s->type.t, 0);
3161 tok_str_new(&str2);
3162 macro_subst(&str2, nested_list, st);
3163 tok_str_add(&str2, 0);
3164 s->next->d = str2.str;
3166 st = s->next->d;
3168 for(;;) {
3169 int t2;
3170 TOK_GET(&t2, &st, &cval);
3171 if (t2 <= 0)
3172 break;
3173 tok_str_add2(&str, t2, &cval);
3175 if (str.len == l0) /* expanded to empty string */
3176 tok_str_add(&str, TOK_PLCHLDR);
3177 } else {
3178 tok_str_add(&str, t);
3180 } else {
3181 tok_str_add2(&str, t, &cval);
3183 t0 = t1, t1 = t;
3185 tok_str_add(&str, 0);
3186 return str.str;
3189 static char const ab_month_name[12][4] =
3191 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3192 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3195 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3197 CString cstr;
3198 int n, ret = 1;
3200 cstr_new(&cstr);
3201 if (t1 != TOK_PLCHLDR)
3202 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3203 n = cstr.size;
3204 if (t2 != TOK_PLCHLDR)
3205 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3206 cstr_ccat(&cstr, '\0');
3208 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3209 memcpy(file->buffer, cstr.data, cstr.size);
3210 tok_flags = 0;
3211 for (;;) {
3212 next_nomacro1();
3213 if (0 == *file->buf_ptr)
3214 break;
3215 if (is_space(tok))
3216 continue;
3217 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3218 " preprocessing token", n, (char *)cstr.data, (char*)cstr.data + n);
3219 ret = 0;
3220 break;
3222 tcc_close();
3223 //printf("paste <%s>\n", (char*)cstr.data);
3224 cstr_free(&cstr);
3225 return ret;
3228 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3229 return the resulting string (which must be freed). */
3230 static inline int *macro_twosharps(const int *ptr0)
3232 int t;
3233 CValue cval;
3234 TokenString macro_str1;
3235 int start_of_nosubsts = -1;
3236 const int *ptr;
3238 /* we search the first '##' */
3239 for (ptr = ptr0;;) {
3240 TOK_GET(&t, &ptr, &cval);
3241 if (t == TOK_PPJOIN)
3242 break;
3243 if (t == 0)
3244 return NULL;
3247 tok_str_new(&macro_str1);
3249 //tok_print(" $$$", ptr0);
3250 for (ptr = ptr0;;) {
3251 TOK_GET(&t, &ptr, &cval);
3252 if (t == 0)
3253 break;
3254 if (t == TOK_PPJOIN)
3255 continue;
3256 while (*ptr == TOK_PPJOIN) {
3257 int t1; CValue cv1;
3258 /* given 'a##b', remove nosubsts preceding 'a' */
3259 if (start_of_nosubsts >= 0)
3260 macro_str1.len = start_of_nosubsts;
3261 /* given 'a##b', remove nosubsts preceding 'b' */
3262 while ((t1 = *++ptr) == TOK_NOSUBST)
3264 if (t1 && t1 != TOK_PPJOIN) {
3265 TOK_GET(&t1, &ptr, &cv1);
3266 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3267 if (paste_tokens(t, &cval, t1, &cv1)) {
3268 t = tok, cval = tokc;
3269 } else {
3270 tok_str_add2(&macro_str1, t, &cval);
3271 t = t1, cval = cv1;
3276 if (t == TOK_NOSUBST) {
3277 if (start_of_nosubsts < 0)
3278 start_of_nosubsts = macro_str1.len;
3279 } else {
3280 start_of_nosubsts = -1;
3282 tok_str_add2(&macro_str1, t, &cval);
3284 tok_str_add(&macro_str1, 0);
3285 //tok_print(" ###", macro_str1.str);
3286 return macro_str1.str;
3289 /* peek or read [ws_str == NULL] next token from function macro call,
3290 walking up macro levels up to the file if necessary */
3291 static int next_argstream(Sym **nested_list, TokenString *ws_str)
3293 int t;
3294 const int *p;
3295 Sym *sa;
3297 for (;;) {
3298 if (macro_ptr) {
3299 p = macro_ptr, t = *p;
3300 if (ws_str) {
3301 while (is_space(t) || TOK_LINEFEED == t || TOK_PLCHLDR == t)
3302 tok_str_add(ws_str, t), t = *++p;
3304 if (t == 0) {
3305 end_macro();
3306 /* also, end of scope for nested defined symbol */
3307 sa = *nested_list;
3308 while (sa && sa->v == 0)
3309 sa = sa->prev;
3310 if (sa)
3311 sa->v = 0;
3312 continue;
3314 } else {
3315 ch = handle_eob();
3316 if (ws_str) {
3317 while (is_space(ch) || ch == '\n' || ch == '/') {
3318 if (ch == '/') {
3319 int c;
3320 uint8_t *p = file->buf_ptr;
3321 PEEKC(c, p);
3322 if (c == '*') {
3323 p = parse_comment(p);
3324 file->buf_ptr = p - 1;
3325 } else if (c == '/') {
3326 p = parse_line_comment(p);
3327 file->buf_ptr = p - 1;
3328 } else
3329 break;
3330 ch = ' ';
3332 if (ch == '\n')
3333 file->line_num++;
3334 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3335 tok_str_add(ws_str, ch);
3336 cinp();
3339 t = ch;
3342 if (ws_str)
3343 return t;
3344 next_nomacro();
3345 return tok;
3349 /* do macro substitution of current token with macro 's' and add
3350 result to (tok_str,tok_len). 'nested_list' is the list of all
3351 macros we got inside to avoid recursing. Return non zero if no
3352 substitution needs to be done */
3353 static int macro_subst_tok(
3354 TokenString *tok_str,
3355 Sym **nested_list,
3356 Sym *s)
3358 Sym *args, *sa, *sa1;
3359 int parlevel, t, t1, spc;
3360 TokenString str;
3361 char *cstrval;
3362 CValue cval;
3363 CString cstr;
3364 char buf[32];
3366 /* if symbol is a macro, prepare substitution */
3367 /* special macros */
3368 if (tok == TOK___LINE__ || tok == TOK___COUNTER__) {
3369 t = tok == TOK___LINE__ ? file->line_num : pp_counter++;
3370 snprintf(buf, sizeof(buf), "%d", t);
3371 cstrval = buf;
3372 t1 = TOK_PPNUM;
3373 goto add_cstr1;
3374 } else if (tok == TOK___FILE__) {
3375 cstrval = file->filename;
3376 goto add_cstr;
3377 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3378 time_t ti;
3379 struct tm *tm;
3381 time(&ti);
3382 tm = localtime(&ti);
3383 if (tok == TOK___DATE__) {
3384 snprintf(buf, sizeof(buf), "%s %2d %d",
3385 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3386 } else {
3387 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3388 tm->tm_hour, tm->tm_min, tm->tm_sec);
3390 cstrval = buf;
3391 add_cstr:
3392 t1 = TOK_STR;
3393 add_cstr1:
3394 cstr_new(&cstr);
3395 cstr_cat(&cstr, cstrval, 0);
3396 cval.str.size = cstr.size;
3397 cval.str.data = cstr.data;
3398 tok_str_add2(tok_str, t1, &cval);
3399 cstr_free(&cstr);
3400 } else if (s->d) {
3401 int saved_parse_flags = parse_flags;
3402 int *joined_str = NULL;
3403 int *mstr = s->d;
3405 if (s->type.t == MACRO_FUNC) {
3406 /* whitespace between macro name and argument list */
3407 TokenString ws_str;
3408 tok_str_new(&ws_str);
3410 spc = 0;
3411 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3412 | PARSE_FLAG_ACCEPT_STRAYS;
3414 /* get next token from argument stream */
3415 t = next_argstream(nested_list, &ws_str);
3416 if (t != '(') {
3417 /* not a macro substitution after all, restore the
3418 * macro token plus all whitespace we've read.
3419 * whitespace is intentionally not merged to preserve
3420 * newlines. */
3421 parse_flags = saved_parse_flags;
3422 tok_str_add(tok_str, tok);
3423 if (parse_flags & PARSE_FLAG_SPACES) {
3424 int i;
3425 for (i = 0; i < ws_str.len; i++)
3426 tok_str_add(tok_str, ws_str.str[i]);
3428 tok_str_free_str(ws_str.str);
3429 return 0;
3430 } else {
3431 tok_str_free_str(ws_str.str);
3433 do {
3434 next_nomacro(); /* eat '(' */
3435 } while (tok == TOK_PLCHLDR || is_space(tok));
3437 /* argument macro */
3438 args = NULL;
3439 sa = s->next;
3440 /* NOTE: empty args are allowed, except if no args */
3441 for(;;) {
3442 do {
3443 next_argstream(nested_list, NULL);
3444 } while (tok == TOK_PLCHLDR || is_space(tok) ||
3445 TOK_LINEFEED == tok);
3446 empty_arg:
3447 /* handle '()' case */
3448 if (!args && !sa && tok == ')')
3449 break;
3450 if (!sa)
3451 tcc_error("macro '%s' used with too many args",
3452 get_tok_str(s->v, 0));
3453 tok_str_new(&str);
3454 parlevel = spc = 0;
3455 /* NOTE: non zero sa->t indicates VA_ARGS */
3456 while ((parlevel > 0 ||
3457 (tok != ')' &&
3458 (tok != ',' || sa->type.t)))) {
3459 if (tok == TOK_EOF || tok == 0)
3460 break;
3461 if (tok == '(')
3462 parlevel++;
3463 else if (tok == ')')
3464 parlevel--;
3465 if (tok == TOK_LINEFEED)
3466 tok = ' ';
3467 if (!check_space(tok, &spc))
3468 tok_str_add2(&str, tok, &tokc);
3469 next_argstream(nested_list, NULL);
3471 if (parlevel)
3472 expect(")");
3473 str.len -= spc;
3474 tok_str_add(&str, -1);
3475 tok_str_add(&str, 0);
3476 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3477 sa1->d = str.str;
3478 sa = sa->next;
3479 if (tok == ')') {
3480 /* special case for gcc var args: add an empty
3481 var arg argument if it is omitted */
3482 if (sa && sa->type.t && gnu_ext)
3483 goto empty_arg;
3484 break;
3486 if (tok != ',')
3487 expect(",");
3489 if (sa) {
3490 tcc_error("macro '%s' used with too few args",
3491 get_tok_str(s->v, 0));
3494 /* now subst each arg */
3495 mstr = macro_arg_subst(nested_list, mstr, args);
3496 /* free memory */
3497 sa = args;
3498 while (sa) {
3499 sa1 = sa->prev;
3500 tok_str_free_str(sa->d);
3501 if (sa->next) {
3502 tok_str_free_str(sa->next->d);
3503 sym_free(sa->next);
3505 sym_free(sa);
3506 sa = sa1;
3508 parse_flags = saved_parse_flags;
3511 sym_push2(nested_list, s->v, 0, 0);
3512 parse_flags = saved_parse_flags;
3513 joined_str = macro_twosharps(mstr);
3514 macro_subst(tok_str, nested_list, joined_str ? joined_str : mstr);
3516 /* pop nested defined symbol */
3517 sa1 = *nested_list;
3518 *nested_list = sa1->prev;
3519 sym_free(sa1);
3520 if (joined_str)
3521 tok_str_free_str(joined_str);
3522 if (mstr != s->d)
3523 tok_str_free_str(mstr);
3525 return 0;
3528 /* do macro substitution of macro_str and add result to
3529 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3530 inside to avoid recursing. */
3531 static void macro_subst(
3532 TokenString *tok_str,
3533 Sym **nested_list,
3534 const int *macro_str
3537 Sym *s;
3538 int t, spc, nosubst;
3539 CValue cval;
3541 spc = nosubst = 0;
3543 while (1) {
3544 TOK_GET(&t, &macro_str, &cval);
3545 if (t <= 0)
3546 break;
3548 if (t >= TOK_IDENT && 0 == nosubst) {
3549 s = define_find(t);
3550 if (s == NULL)
3551 goto no_subst;
3553 /* if nested substitution, do nothing */
3554 if (sym_find2(*nested_list, t)) {
3555 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3556 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3557 goto no_subst;
3561 TokenString *str = tok_str_alloc();
3562 str->str = (int*)macro_str;
3563 begin_macro(str, 2);
3565 tok = t;
3566 macro_subst_tok(tok_str, nested_list, s);
3568 if (macro_stack != str) {
3569 /* already finished by reading function macro arguments */
3570 break;
3573 macro_str = macro_ptr;
3574 end_macro ();
3576 if (tok_str->len)
3577 spc = is_space(t = tok_str->str[tok_str->lastlen]);
3578 } else {
3579 no_subst:
3580 if (!check_space(t, &spc))
3581 tok_str_add2(tok_str, t, &cval);
3583 if (nosubst) {
3584 if (nosubst > 1 && (spc || (++nosubst == 3 && t == '(')))
3585 continue;
3586 nosubst = 0;
3588 if (t == TOK_NOSUBST)
3589 nosubst = 1;
3591 /* GCC supports 'defined' as result of a macro substitution */
3592 if (t == TOK_DEFINED && pp_expr)
3593 nosubst = 2;
3597 /* return next token without macro substitution. Can read input from
3598 macro_ptr buffer */
3599 static void next_nomacro(void)
3601 int t;
3602 if (macro_ptr) {
3603 redo:
3604 t = *macro_ptr;
3605 if (TOK_HAS_VALUE(t)) {
3606 tok_get(&tok, &macro_ptr, &tokc);
3607 if (t == TOK_LINENUM) {
3608 file->line_num = tokc.i;
3609 goto redo;
3611 } else {
3612 macro_ptr++;
3613 if (t < TOK_IDENT) {
3614 if (!(parse_flags & PARSE_FLAG_SPACES)
3615 && (isidnum_table[t - CH_EOF] & IS_SPC))
3616 goto redo;
3618 tok = t;
3620 } else {
3621 next_nomacro1();
3625 /* return next token with macro substitution */
3626 ST_FUNC void next(void)
3628 int t;
3629 redo:
3630 next_nomacro();
3631 t = tok;
3632 if (macro_ptr) {
3633 if (!TOK_HAS_VALUE(t)) {
3634 if (t == TOK_NOSUBST || t == TOK_PLCHLDR) {
3635 /* discard preprocessor markers */
3636 goto redo;
3637 } else if (t == 0) {
3638 /* end of macro or unget token string */
3639 end_macro();
3640 goto redo;
3641 } else if (t == '\\') {
3642 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3643 tcc_error("stray '\\' in program");
3645 return;
3647 } else if (t >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3648 /* if reading from file, try to substitute macros */
3649 Sym *s = define_find(t);
3650 if (s) {
3651 Sym *nested_list = NULL;
3652 tokstr_buf.len = 0;
3653 macro_subst_tok(&tokstr_buf, &nested_list, s);
3654 tok_str_add(&tokstr_buf, 0);
3655 begin_macro(&tokstr_buf, 0);
3656 goto redo;
3658 return;
3660 /* convert preprocessor tokens into C tokens */
3661 if (t == TOK_PPNUM) {
3662 if (parse_flags & PARSE_FLAG_TOK_NUM)
3663 parse_number((char *)tokc.str.data);
3664 } else if (t == TOK_PPSTR) {
3665 if (parse_flags & PARSE_FLAG_TOK_STR)
3666 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3670 /* push back current token and set current token to 'last_tok'. Only
3671 identifier case handled for labels. */
3672 ST_INLN void unget_tok(int last_tok)
3675 TokenString *str = tok_str_alloc();
3676 tok_str_add2(str, tok, &tokc);
3677 tok_str_add(str, 0);
3678 begin_macro(str, 1);
3679 tok = last_tok;
3682 /* ------------------------------------------------------------------------- */
3683 /* init preprocessor */
3685 static const char * const target_os_defs =
3686 #ifdef TCC_TARGET_PE
3687 "_WIN32\0"
3688 # if PTR_SIZE == 8
3689 "_WIN64\0"
3690 # endif
3691 #else
3692 # if defined TCC_TARGET_MACHO
3693 "__APPLE__\0"
3694 # elif TARGETOS_FreeBSD
3695 "__FreeBSD__ 12\0"
3696 # elif TARGETOS_FreeBSD_kernel
3697 "__FreeBSD_kernel__\0"
3698 # elif TARGETOS_NetBSD
3699 "__NetBSD__\0"
3700 # elif TARGETOS_OpenBSD
3701 "__OpenBSD__\0"
3702 # else
3703 "__linux__\0"
3704 "__linux\0"
3705 # endif
3706 "__unix__\0"
3707 "__unix\0"
3708 #endif
3711 static void putdef(CString *cs, const char *p)
3713 cstr_printf(cs, "#define %s%s\n", p, &" 1"[!!strchr(p, ' ')*2]);
3716 static void tcc_predefs(TCCState *s1, CString *cs, int is_asm)
3718 int a, b, c;
3719 const char *defs[] = { target_machine_defs, target_os_defs, NULL };
3720 const char *p;
3722 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
3723 cstr_printf(cs, "#define __TINYC__ %d\n", a*10000 + b*100 + c);
3724 for (a = 0; defs[a]; ++a)
3725 for (p = defs[a]; *p; p = strchr(p, 0) + 1)
3726 putdef(cs, p);
3727 #ifdef TCC_TARGET_ARM
3728 if (s1->float_abi == ARM_HARD_FLOAT)
3729 putdef(cs, "__ARM_PCS_VFP");
3730 #endif
3731 if (is_asm)
3732 putdef(cs, "__ASSEMBLER__");
3733 if (s1->output_type == TCC_OUTPUT_PREPROCESS)
3734 putdef(cs, "__TCC_PP__");
3735 if (s1->output_type == TCC_OUTPUT_MEMORY)
3736 putdef(cs, "__TCC_RUN__");
3737 if (s1->char_is_unsigned)
3738 putdef(cs, "__CHAR_UNSIGNED__");
3739 if (s1->optimize > 0)
3740 putdef(cs, "__OPTIMIZE__");
3741 if (s1->option_pthread)
3742 putdef(cs, "_REENTRANT");
3743 if (s1->leading_underscore)
3744 putdef(cs, "__leading_underscore");
3745 #ifdef CONFIG_TCC_BCHECK
3746 if (s1->do_bounds_check)
3747 putdef(cs, "__BOUNDS_CHECKING_ON");
3748 #endif
3749 cstr_printf(cs, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE);
3750 cstr_printf(cs, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE);
3751 if (!is_asm) {
3752 putdef(cs, "__STDC__");
3753 cstr_printf(cs, "#define __STDC_VERSION__ %dL\n", s1->cversion);
3754 cstr_cat(cs,
3755 /* load more predefs and __builtins */
3756 #if CONFIG_TCC_PREDEFS
3757 #include "tccdefs_.h" /* include as strings */
3758 #else
3759 "#include <tccdefs.h>\n" /* load at runtime */
3760 #endif
3761 , -1);
3763 cstr_printf(cs, "#define __BASE_FILE__ \"%s\"\n", file->filename);
3766 ST_FUNC void preprocess_start(TCCState *s1, int filetype)
3768 int is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
3769 CString cstr;
3771 tccpp_new(s1);
3773 s1->include_stack_ptr = s1->include_stack;
3774 s1->ifdef_stack_ptr = s1->ifdef_stack;
3775 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3776 pp_expr = 0;
3777 pp_counter = 0;
3778 pp_debug_tok = pp_debug_symv = 0;
3779 pp_once++;
3780 s1->pack_stack[0] = 0;
3781 s1->pack_stack_ptr = s1->pack_stack;
3783 set_idnum('$', !is_asm && s1->dollars_in_identifiers ? IS_ID : 0);
3784 set_idnum('.', is_asm ? IS_ID : 0);
3786 if (!(filetype & AFF_TYPE_ASM)) {
3787 cstr_new(&cstr);
3788 tcc_predefs(s1, &cstr, is_asm);
3789 if (s1->cmdline_defs.size)
3790 cstr_cat(&cstr, s1->cmdline_defs.data, s1->cmdline_defs.size);
3791 if (s1->cmdline_incl.size)
3792 cstr_cat(&cstr, s1->cmdline_incl.data, s1->cmdline_incl.size);
3793 //printf("%s\n", (char*)cstr.data);
3794 *s1->include_stack_ptr++ = file;
3795 tcc_open_bf(s1, "<command line>", cstr.size);
3796 memcpy(file->buffer, cstr.data, cstr.size);
3797 cstr_free(&cstr);
3800 parse_flags = is_asm ? PARSE_FLAG_ASM_FILE : 0;
3801 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3804 /* cleanup from error/setjmp */
3805 ST_FUNC void preprocess_end(TCCState *s1)
3807 while (macro_stack)
3808 end_macro();
3809 macro_ptr = NULL;
3810 while (file)
3811 tcc_close();
3812 tccpp_delete(s1);
3815 ST_FUNC void tccpp_new(TCCState *s)
3817 int i, c;
3818 const char *p, *r;
3820 /* init isid table */
3821 for(i = CH_EOF; i<128; i++)
3822 set_idnum(i,
3823 is_space(i) ? IS_SPC
3824 : isid(i) ? IS_ID
3825 : isnum(i) ? IS_NUM
3826 : 0);
3828 for(i = 128; i<256; i++)
3829 set_idnum(i, IS_ID);
3831 /* init allocators */
3832 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3833 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3835 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3836 memset(s->cached_includes_hash, 0, sizeof s->cached_includes_hash);
3838 cstr_new(&cstr_buf);
3839 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3840 tok_str_new(&tokstr_buf);
3841 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3843 tok_ident = TOK_IDENT;
3844 p = tcc_keywords;
3845 while (*p) {
3846 r = p;
3847 for(;;) {
3848 c = *r++;
3849 if (c == '\0')
3850 break;
3852 tok_alloc(p, r - p - 1);
3853 p = r;
3856 /* we add dummy defines for some special macros to speed up tests
3857 and to have working defined() */
3858 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
3859 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
3860 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
3861 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
3862 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
3865 ST_FUNC void tccpp_delete(TCCState *s)
3867 int i, n;
3869 dynarray_reset(&s->cached_includes, &s->nb_cached_includes);
3871 /* free tokens */
3872 n = tok_ident - TOK_IDENT;
3873 if (n > total_idents)
3874 total_idents = n;
3875 for(i = 0; i < n; i++)
3876 tal_free(toksym_alloc, table_ident[i]);
3877 tcc_free(table_ident);
3878 table_ident = NULL;
3880 /* free static buffers */
3881 cstr_free(&tokcstr);
3882 cstr_free(&cstr_buf);
3883 cstr_free(&macro_equal_buf);
3884 tok_str_free_str(tokstr_buf.str);
3886 /* free allocators */
3887 tal_delete(toksym_alloc);
3888 toksym_alloc = NULL;
3889 tal_delete(tokstr_alloc);
3890 tokstr_alloc = NULL;
3893 /* ------------------------------------------------------------------------- */
3894 /* tcc -E [-P[1]] [-dD} support */
3896 static void tok_print(const char *msg, const int *str)
3898 FILE *fp;
3899 int t, s = 0;
3900 CValue cval;
3902 fp = tcc_state->ppfp;
3903 fprintf(fp, "%s", msg);
3904 while (str) {
3905 TOK_GET(&t, &str, &cval);
3906 if (!t)
3907 break;
3908 fprintf(fp, &" %s"[s], get_tok_str(t, &cval)), s = 1;
3910 fprintf(fp, "\n");
3913 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3915 int d = f->line_num - f->line_ref;
3917 if (s1->dflag & 4)
3918 return;
3920 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3922 } else if (level == 0 && f->line_ref && d < 8) {
3923 while (d > 0)
3924 fputs("\n", s1->ppfp), --d;
3925 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3926 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3927 } else {
3928 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3929 level > 0 ? " 1" : level < 0 ? " 2" : "");
3931 f->line_ref = f->line_num;
3934 static void define_print(TCCState *s1, int v)
3936 FILE *fp;
3937 Sym *s;
3939 s = define_find(v);
3940 if (NULL == s || NULL == s->d)
3941 return;
3943 fp = s1->ppfp;
3944 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3945 if (s->type.t == MACRO_FUNC) {
3946 Sym *a = s->next;
3947 fprintf(fp,"(");
3948 if (a)
3949 for (;;) {
3950 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3951 if (!(a = a->next))
3952 break;
3953 fprintf(fp,",");
3955 fprintf(fp,")");
3957 tok_print("", s->d);
3960 static void pp_debug_defines(TCCState *s1)
3962 int v, t;
3963 const char *vs;
3964 FILE *fp;
3966 t = pp_debug_tok;
3967 if (t == 0)
3968 return;
3970 file->line_num--;
3971 pp_line(s1, file, 0);
3972 file->line_ref = ++file->line_num;
3974 fp = s1->ppfp;
3975 v = pp_debug_symv;
3976 vs = get_tok_str(v, NULL);
3977 if (t == TOK_DEFINE) {
3978 define_print(s1, v);
3979 } else if (t == TOK_UNDEF) {
3980 fprintf(fp, "#undef %s\n", vs);
3981 } else if (t == TOK_push_macro) {
3982 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3983 } else if (t == TOK_pop_macro) {
3984 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3986 pp_debug_tok = 0;
3989 static void pp_debug_builtins(TCCState *s1)
3991 int v;
3992 for (v = TOK_IDENT; v < tok_ident; ++v)
3993 define_print(s1, v);
3996 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3997 static int pp_need_space(int a, int b)
3999 return 'E' == a ? '+' == b || '-' == b
4000 : '+' == a ? TOK_INC == b || '+' == b
4001 : '-' == a ? TOK_DEC == b || '-' == b
4002 : a >= TOK_IDENT ? b >= TOK_IDENT
4003 : a == TOK_PPNUM ? b >= TOK_IDENT
4004 : 0;
4007 /* maybe hex like 0x1e */
4008 static int pp_check_he0xE(int t, const char *p)
4010 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
4011 return 'E';
4012 return t;
4015 /* Preprocess the current file */
4016 ST_FUNC int tcc_preprocess(TCCState *s1)
4018 BufferedFile **iptr;
4019 int token_seen, spcs, level;
4020 const char *p;
4021 char white[400];
4023 parse_flags = PARSE_FLAG_PREPROCESS
4024 | (parse_flags & PARSE_FLAG_ASM_FILE)
4025 | PARSE_FLAG_LINEFEED
4026 | PARSE_FLAG_SPACES
4027 | PARSE_FLAG_ACCEPT_STRAYS
4029 /* Credits to Fabrice Bellard's initial revision to demonstrate its
4030 capability to compile and run itself, provided all numbers are
4031 given as decimals. tcc -E -P10 will do. */
4032 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_P10)
4033 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
4035 if (s1->do_bench) {
4036 /* for PP benchmarks */
4037 do next(); while (tok != TOK_EOF);
4038 return 0;
4041 if (s1->dflag & 1) {
4042 pp_debug_builtins(s1);
4043 s1->dflag &= ~1;
4046 token_seen = TOK_LINEFEED, spcs = 0, level = 0;
4047 if (file->prev)
4048 pp_line(s1, file->prev, level++);
4049 pp_line(s1, file, level);
4050 for (;;) {
4051 iptr = s1->include_stack_ptr;
4052 next();
4053 if (tok == TOK_EOF)
4054 break;
4056 level = s1->include_stack_ptr - iptr;
4057 if (level) {
4058 if (level > 0)
4059 pp_line(s1, *iptr, 0);
4060 pp_line(s1, file, level);
4062 if (s1->dflag & 7) {
4063 pp_debug_defines(s1);
4064 if (s1->dflag & 4)
4065 continue;
4068 if (is_space(tok)) {
4069 if (spcs < sizeof white - 1)
4070 white[spcs++] = tok;
4071 continue;
4072 } else if (tok == TOK_LINEFEED) {
4073 spcs = 0;
4074 if (token_seen == TOK_LINEFEED)
4075 continue;
4076 ++file->line_ref;
4077 } else if (token_seen == TOK_LINEFEED) {
4078 pp_line(s1, file, 0);
4079 } else if (spcs == 0 && pp_need_space(token_seen, tok)) {
4080 white[spcs++] = ' ';
4083 white[spcs] = 0, fputs(white, s1->ppfp), spcs = 0;
4084 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
4085 token_seen = pp_check_he0xE(tok, p);
4087 return 0;
4090 /* ------------------------------------------------------------------------- */