struct-init: Cleanup some more
[tinycc.git] / tccpp.c
blob1838a3a1d3b24e315b91d41fae6688f1b4a209c1
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 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 ST_DATA int tok_flags;
27 ST_DATA int parse_flags;
29 ST_DATA struct BufferedFile *file;
30 ST_DATA int ch, tok;
31 ST_DATA CValue tokc;
32 ST_DATA const int *macro_ptr;
33 ST_DATA CString tokcstr; /* current parsed string, if any */
35 /* display benchmark infos */
36 ST_DATA int total_lines;
37 ST_DATA int total_bytes;
38 ST_DATA int tok_ident;
39 ST_DATA TokenSym **table_ident;
41 /* ------------------------------------------------------------------------- */
43 static TokenSym *hash_ident[TOK_HASH_SIZE];
44 static char token_buf[STRING_MAX_SIZE + 1];
45 static CString cstr_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 void tok_print(const char *msg, const int *str);
52 static struct TinyAlloc *toksym_alloc;
53 static struct TinyAlloc *tokstr_alloc;
54 static struct TinyAlloc *cstr_alloc;
56 /* isidnum_table flags: */
57 #define IS_SPC 1
58 #define IS_ID 2
59 #define IS_NUM 4
61 static TokenString *macro_stack;
63 static const char tcc_keywords[] =
64 #define DEF(id, str) str "\0"
65 #include "tcctok.h"
66 #undef DEF
69 /* WARNING: the content of this string encodes token numbers */
70 static const unsigned char tok_two_chars[] =
71 /* outdated -- gr
72 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
73 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
74 */{
75 '<','=', TOK_LE,
76 '>','=', TOK_GE,
77 '!','=', TOK_NE,
78 '&','&', TOK_LAND,
79 '|','|', TOK_LOR,
80 '+','+', TOK_INC,
81 '-','-', TOK_DEC,
82 '=','=', TOK_EQ,
83 '<','<', TOK_SHL,
84 '>','>', TOK_SAR,
85 '+','=', TOK_A_ADD,
86 '-','=', TOK_A_SUB,
87 '*','=', TOK_A_MUL,
88 '/','=', TOK_A_DIV,
89 '%','=', TOK_A_MOD,
90 '&','=', TOK_A_AND,
91 '^','=', TOK_A_XOR,
92 '|','=', TOK_A_OR,
93 '-','>', TOK_ARROW,
94 '.','.', 0xa8, // C++ token ?
95 '#','#', TOK_TWOSHARPS,
99 static void next_nomacro_spc(void);
101 ST_FUNC void skip(int c)
103 if (tok != c)
104 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
105 next();
108 ST_FUNC void expect(const char *msg)
110 tcc_error("%s expected", msg);
113 /* ------------------------------------------------------------------------- */
114 /* Custom allocator for tiny objects */
116 #define USE_TAL
118 #ifndef USE_TAL
119 #define tal_free(al, p) tcc_free(p)
120 #define tal_realloc(al, p, size) tcc_realloc(p, size)
121 #define tal_new(a,b,c)
122 #define tal_delete(a)
123 #else
124 #if !defined(MEM_DEBUG)
125 #define tal_free(al, p) tal_free_impl(al, p)
126 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
127 #define TAL_DEBUG_PARAMS
128 #else
129 #define TAL_DEBUG 1
130 //#define TAL_INFO 1 /* collect and dump allocators stats */
131 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
132 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
133 #define TAL_DEBUG_PARAMS , const char *file, int line
134 #define TAL_DEBUG_FILE_LEN 15
135 #endif
137 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
138 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
139 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
140 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
141 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
142 #define CSTR_TAL_LIMIT 1024
144 typedef struct TinyAlloc {
145 size_t limit;
146 size_t size;
147 uint8_t *buffer;
148 uint8_t *p;
149 size_t nb_allocs;
150 struct TinyAlloc *next, *top;
151 #ifdef TAL_INFO
152 size_t nb_peak;
153 size_t nb_total;
154 size_t nb_missed;
155 uint8_t *peak_p;
156 #endif
157 } TinyAlloc;
159 typedef struct tal_header_t {
160 size_t size;
161 #ifdef TAL_DEBUG
162 int line_num; /* negative line_num used for double free check */
163 char file_name[TAL_DEBUG_FILE_LEN + 1];
164 #endif
165 } tal_header_t;
167 /* ------------------------------------------------------------------------- */
169 ST_FUNC TinyAlloc *tal_new(TinyAlloc **pal, size_t limit, size_t size)
171 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
172 al->p = al->buffer = tcc_malloc(size);
173 al->limit = limit;
174 al->size = size;
175 if (pal) *pal = al;
176 return al;
179 ST_FUNC void tal_delete(TinyAlloc *al)
181 TinyAlloc *next;
183 tail_call:
184 if (!al)
185 return;
186 #ifdef TAL_INFO
187 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
188 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
189 (al->peak_p - al->buffer) * 100.0 / al->size);
190 #endif
191 #ifdef TAL_DEBUG
192 if (al->nb_allocs > 0) {
193 uint8_t *p;
194 fprintf(stderr, "TAL_DEBUG: mem leak %d chunks (limit= %d)\n",
195 al->nb_allocs, al->limit);
196 p = al->buffer;
197 while (p < al->p) {
198 tal_header_t *header = (tal_header_t *)p;
199 if (header->line_num > 0) {
200 fprintf(stderr, " file %s, line %u: %u bytes\n",
201 header->file_name, header->line_num, header->size);
203 p += header->size + sizeof(tal_header_t);
206 #endif
207 next = al->next;
208 tcc_free(al->buffer);
209 tcc_free(al);
210 al = next;
211 goto tail_call;
214 ST_FUNC 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, "TAL_DEBUG: file %s, line %u double frees chunk from\n",
224 file, line);
225 fprintf(stderr, " file %s, line %u: %u bytes\n",
226 header->file_name, -header->line_num, 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 ST_FUNC void *tal_realloc_impl(TinyAlloc **pal, void *p, size_t size TAL_DEBUG_PARAMS)
243 tal_header_t *header;
244 void *ret;
245 int is_own;
246 size_t 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 + adj_size + sizeof(tal_header_t) < al->buffer + 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 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 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 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 = tal_realloc(cstr_alloc, 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_FUNC void cstr_cat(CString *cstr, const char *str, int len)
350 int size;
351 if (len <= 0)
352 len = strlen(str) + 1 + len;
353 size = cstr->size + len;
354 if (size > cstr->size_allocated)
355 cstr_realloc(cstr, size);
356 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
357 cstr->size = size;
360 /* add a wide char */
361 ST_FUNC void cstr_wccat(CString *cstr, int ch)
363 int size;
364 size = cstr->size + sizeof(nwchar_t);
365 if (size > cstr->size_allocated)
366 cstr_realloc(cstr, size);
367 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
368 cstr->size = size;
371 ST_FUNC void cstr_new(CString *cstr)
373 memset(cstr, 0, sizeof(CString));
376 /* free string and reset it to NULL */
377 ST_FUNC void cstr_free(CString *cstr)
379 tal_free(cstr_alloc, cstr->data);
380 cstr_new(cstr);
383 /* reset string to empty */
384 ST_FUNC void cstr_reset(CString *cstr)
386 cstr->size = 0;
389 /* XXX: unicode ? */
390 static void add_char(CString *cstr, int c)
392 if (c == '\'' || c == '\"' || c == '\\') {
393 /* XXX: could be more precise if char or string */
394 cstr_ccat(cstr, '\\');
396 if (c >= 32 && c <= 126) {
397 cstr_ccat(cstr, c);
398 } else {
399 cstr_ccat(cstr, '\\');
400 if (c == '\n') {
401 cstr_ccat(cstr, 'n');
402 } else {
403 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
404 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
405 cstr_ccat(cstr, '0' + (c & 7));
410 /* ------------------------------------------------------------------------- */
411 /* allocate a new token */
412 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
414 TokenSym *ts, **ptable;
415 int i;
417 if (tok_ident >= SYM_FIRST_ANOM)
418 tcc_error("memory full (symbols)");
420 /* expand token table if needed */
421 i = tok_ident - TOK_IDENT;
422 if ((i % TOK_ALLOC_INCR) == 0) {
423 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
424 table_ident = ptable;
427 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
428 table_ident[i] = ts;
429 ts->tok = tok_ident++;
430 ts->sym_define = NULL;
431 ts->sym_label = NULL;
432 ts->sym_struct = NULL;
433 ts->sym_identifier = NULL;
434 ts->len = len;
435 ts->hash_next = NULL;
436 memcpy(ts->str, str, len);
437 ts->str[len] = '\0';
438 *pts = ts;
439 return ts;
442 #define TOK_HASH_INIT 1
443 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
446 /* find a token and add it if not found */
447 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
449 TokenSym *ts, **pts;
450 int i;
451 unsigned int h;
453 h = TOK_HASH_INIT;
454 for(i=0;i<len;i++)
455 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
456 h &= (TOK_HASH_SIZE - 1);
458 pts = &hash_ident[h];
459 for(;;) {
460 ts = *pts;
461 if (!ts)
462 break;
463 if (ts->len == len && !memcmp(ts->str, str, len))
464 return ts;
465 pts = &(ts->hash_next);
467 return tok_alloc_new(pts, str, len);
470 /* XXX: buffer overflow */
471 /* XXX: float tokens */
472 ST_FUNC const char *get_tok_str(int v, CValue *cv)
474 char *p;
475 int i, len;
477 cstr_reset(&cstr_buf);
478 p = cstr_buf.data;
480 switch(v) {
481 case TOK_CINT:
482 case TOK_CUINT:
483 case TOK_CLLONG:
484 case TOK_CULLONG:
485 /* XXX: not quite exact, but only useful for testing */
486 #ifdef _WIN32
487 sprintf(p, "%u", (unsigned)cv->i);
488 #else
489 sprintf(p, "%llu", (unsigned long long)cv->i);
490 #endif
491 break;
492 case TOK_LCHAR:
493 cstr_ccat(&cstr_buf, 'L');
494 case TOK_CCHAR:
495 cstr_ccat(&cstr_buf, '\'');
496 add_char(&cstr_buf, cv->i);
497 cstr_ccat(&cstr_buf, '\'');
498 cstr_ccat(&cstr_buf, '\0');
499 break;
500 case TOK_PPNUM:
501 case TOK_PPSTR:
502 return (char*)cv->str.data;
503 case TOK_LSTR:
504 cstr_ccat(&cstr_buf, 'L');
505 case TOK_STR:
506 cstr_ccat(&cstr_buf, '\"');
507 if (v == TOK_STR) {
508 len = cv->str.size - 1;
509 for(i=0;i<len;i++)
510 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
511 } else {
512 len = (cv->str.size / sizeof(nwchar_t)) - 1;
513 for(i=0;i<len;i++)
514 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
516 cstr_ccat(&cstr_buf, '\"');
517 cstr_ccat(&cstr_buf, '\0');
518 break;
520 case TOK_CFLOAT:
521 cstr_cat(&cstr_buf, "<float>", 0);
522 break;
523 case TOK_CDOUBLE:
524 cstr_cat(&cstr_buf, "<double>", 0);
525 break;
526 case TOK_CLDOUBLE:
527 cstr_cat(&cstr_buf, "<long double>", 0);
528 break;
529 case TOK_LINENUM:
530 cstr_cat(&cstr_buf, "<linenumber>", 0);
531 break;
533 /* above tokens have value, the ones below don't */
535 case TOK_LT:
536 v = '<';
537 goto addv;
538 case TOK_GT:
539 v = '>';
540 goto addv;
541 case TOK_DOTS:
542 return strcpy(p, "...");
543 case TOK_A_SHL:
544 return strcpy(p, "<<=");
545 case TOK_A_SAR:
546 return strcpy(p, ">>=");
547 default:
548 if (v < TOK_IDENT) {
549 /* search in two bytes table */
550 const unsigned char *q = tok_two_chars;
551 while (*q) {
552 if (q[2] == v) {
553 *p++ = q[0];
554 *p++ = q[1];
555 *p = '\0';
556 return cstr_buf.data;
558 q += 3;
560 if (v >= 127) {
561 sprintf(cstr_buf.data, "<%02x>", v);
562 return cstr_buf.data;
564 addv:
565 *p++ = v;
566 *p = '\0';
567 } else if (v < tok_ident) {
568 return table_ident[v - TOK_IDENT]->str;
569 } else if (v >= SYM_FIRST_ANOM) {
570 /* special name for anonymous symbol */
571 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
572 } else {
573 /* should never happen */
574 return NULL;
576 break;
578 return cstr_buf.data;
581 /* return the current character, handling end of block if necessary
582 (but not stray) */
583 ST_FUNC int handle_eob(void)
585 BufferedFile *bf = file;
586 int len;
588 /* only tries to read if really end of buffer */
589 if (bf->buf_ptr >= bf->buf_end) {
590 if (bf->fd != -1) {
591 #if defined(PARSE_DEBUG)
592 len = 1;
593 #else
594 len = IO_BUF_SIZE;
595 #endif
596 len = read(bf->fd, bf->buffer, len);
597 if (len < 0)
598 len = 0;
599 } else {
600 len = 0;
602 total_bytes += len;
603 bf->buf_ptr = bf->buffer;
604 bf->buf_end = bf->buffer + len;
605 *bf->buf_end = CH_EOB;
607 if (bf->buf_ptr < bf->buf_end) {
608 return bf->buf_ptr[0];
609 } else {
610 bf->buf_ptr = bf->buf_end;
611 return CH_EOF;
615 /* read next char from current input file and handle end of input buffer */
616 ST_INLN void inp(void)
618 ch = *(++(file->buf_ptr));
619 /* end of buffer/file handling */
620 if (ch == CH_EOB)
621 ch = handle_eob();
624 /* handle '\[\r]\n' */
625 static int handle_stray_noerror(void)
627 while (ch == '\\') {
628 inp();
629 if (ch == '\n') {
630 file->line_num++;
631 inp();
632 } else if (ch == '\r') {
633 inp();
634 if (ch != '\n')
635 goto fail;
636 file->line_num++;
637 inp();
638 } else {
639 fail:
640 return 1;
643 return 0;
646 static void handle_stray(void)
648 if (handle_stray_noerror())
649 tcc_error("stray '\\' in program");
652 /* skip the stray and handle the \\n case. Output an error if
653 incorrect char after the stray */
654 static int handle_stray1(uint8_t *p)
656 int c;
658 file->buf_ptr = p;
659 if (p >= file->buf_end) {
660 c = handle_eob();
661 if (c != '\\')
662 return c;
663 p = file->buf_ptr;
665 ch = *p;
666 if (handle_stray_noerror()) {
667 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
668 tcc_error("stray '\\' in program");
669 *--file->buf_ptr = '\\';
671 p = file->buf_ptr;
672 c = *p;
673 return c;
676 /* handle just the EOB case, but not stray */
677 #define PEEKC_EOB(c, p)\
679 p++;\
680 c = *p;\
681 if (c == '\\') {\
682 file->buf_ptr = p;\
683 c = handle_eob();\
684 p = file->buf_ptr;\
688 /* handle the complicated stray case */
689 #define PEEKC(c, p)\
691 p++;\
692 c = *p;\
693 if (c == '\\') {\
694 c = handle_stray1(p);\
695 p = file->buf_ptr;\
699 /* input with '\[\r]\n' handling. Note that this function cannot
700 handle other characters after '\', so you cannot call it inside
701 strings or comments */
702 ST_FUNC void minp(void)
704 inp();
705 if (ch == '\\')
706 handle_stray();
709 /* single line C++ comments */
710 static uint8_t *parse_line_comment(uint8_t *p)
712 int c;
714 p++;
715 for(;;) {
716 c = *p;
717 redo:
718 if (c == '\n' || c == CH_EOF) {
719 break;
720 } else if (c == '\\') {
721 file->buf_ptr = p;
722 c = handle_eob();
723 p = file->buf_ptr;
724 if (c == '\\') {
725 PEEKC_EOB(c, p);
726 if (c == '\n') {
727 file->line_num++;
728 PEEKC_EOB(c, p);
729 } else if (c == '\r') {
730 PEEKC_EOB(c, p);
731 if (c == '\n') {
732 file->line_num++;
733 PEEKC_EOB(c, p);
736 } else {
737 goto redo;
739 } else {
740 p++;
743 return p;
746 /* C comments */
747 ST_FUNC uint8_t *parse_comment(uint8_t *p)
749 int c;
751 p++;
752 for(;;) {
753 /* fast skip loop */
754 for(;;) {
755 c = *p;
756 if (c == '\n' || c == '*' || c == '\\')
757 break;
758 p++;
759 c = *p;
760 if (c == '\n' || c == '*' || c == '\\')
761 break;
762 p++;
764 /* now we can handle all the cases */
765 if (c == '\n') {
766 file->line_num++;
767 p++;
768 } else if (c == '*') {
769 p++;
770 for(;;) {
771 c = *p;
772 if (c == '*') {
773 p++;
774 } else if (c == '/') {
775 goto end_of_comment;
776 } else if (c == '\\') {
777 file->buf_ptr = p;
778 c = handle_eob();
779 p = file->buf_ptr;
780 if (c == CH_EOF)
781 tcc_error("unexpected end of file in comment");
782 if (c == '\\') {
783 /* skip '\[\r]\n', otherwise just skip the stray */
784 while (c == '\\') {
785 PEEKC_EOB(c, p);
786 if (c == '\n') {
787 file->line_num++;
788 PEEKC_EOB(c, p);
789 } else if (c == '\r') {
790 PEEKC_EOB(c, p);
791 if (c == '\n') {
792 file->line_num++;
793 PEEKC_EOB(c, p);
795 } else {
796 goto after_star;
800 } else {
801 break;
804 after_star: ;
805 } else {
806 /* stray, eob or eof */
807 file->buf_ptr = p;
808 c = handle_eob();
809 p = file->buf_ptr;
810 if (c == CH_EOF) {
811 tcc_error("unexpected end of file in comment");
812 } else if (c == '\\') {
813 p++;
817 end_of_comment:
818 p++;
819 return p;
822 #define cinp minp
824 static inline void skip_spaces(void)
826 while (isidnum_table[ch - CH_EOF] & IS_SPC)
827 cinp();
830 static inline int check_space(int t, int *spc)
832 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
833 if (*spc)
834 return 1;
835 *spc = 1;
836 } else
837 *spc = 0;
838 return 0;
841 /* parse a string without interpreting escapes */
842 static uint8_t *parse_pp_string(uint8_t *p,
843 int sep, CString *str)
845 int c;
846 p++;
847 for(;;) {
848 c = *p;
849 if (c == sep) {
850 break;
851 } else if (c == '\\') {
852 file->buf_ptr = p;
853 c = handle_eob();
854 p = file->buf_ptr;
855 if (c == CH_EOF) {
856 unterminated_string:
857 /* XXX: indicate line number of start of string */
858 tcc_error("missing terminating %c character", sep);
859 } else if (c == '\\') {
860 /* escape : just skip \[\r]\n */
861 PEEKC_EOB(c, p);
862 if (c == '\n') {
863 file->line_num++;
864 p++;
865 } else if (c == '\r') {
866 PEEKC_EOB(c, p);
867 if (c != '\n')
868 expect("'\n' after '\r'");
869 file->line_num++;
870 p++;
871 } else if (c == CH_EOF) {
872 goto unterminated_string;
873 } else {
874 if (str) {
875 cstr_ccat(str, '\\');
876 cstr_ccat(str, c);
878 p++;
881 } else if (c == '\n') {
882 file->line_num++;
883 goto add_char;
884 } else if (c == '\r') {
885 PEEKC_EOB(c, p);
886 if (c != '\n') {
887 if (str)
888 cstr_ccat(str, '\r');
889 } else {
890 file->line_num++;
891 goto add_char;
893 } else {
894 add_char:
895 if (str)
896 cstr_ccat(str, c);
897 p++;
900 p++;
901 return p;
904 /* skip block of text until #else, #elif or #endif. skip also pairs of
905 #if/#endif */
906 static void preprocess_skip(void)
908 int a, start_of_line, c, in_warn_or_error;
909 uint8_t *p;
911 p = file->buf_ptr;
912 a = 0;
913 redo_start:
914 start_of_line = 1;
915 in_warn_or_error = 0;
916 for(;;) {
917 redo_no_start:
918 c = *p;
919 switch(c) {
920 case ' ':
921 case '\t':
922 case '\f':
923 case '\v':
924 case '\r':
925 p++;
926 goto redo_no_start;
927 case '\n':
928 file->line_num++;
929 p++;
930 goto redo_start;
931 case '\\':
932 file->buf_ptr = p;
933 c = handle_eob();
934 if (c == CH_EOF) {
935 expect("#endif");
936 } else if (c == '\\') {
937 ch = file->buf_ptr[0];
938 handle_stray_noerror();
940 p = file->buf_ptr;
941 goto redo_no_start;
942 /* skip strings */
943 case '\"':
944 case '\'':
945 if (in_warn_or_error)
946 goto _default;
947 p = parse_pp_string(p, c, NULL);
948 break;
949 /* skip comments */
950 case '/':
951 if (in_warn_or_error)
952 goto _default;
953 file->buf_ptr = p;
954 ch = *p;
955 minp();
956 p = file->buf_ptr;
957 if (ch == '*') {
958 p = parse_comment(p);
959 } else if (ch == '/') {
960 p = parse_line_comment(p);
962 break;
963 case '#':
964 p++;
965 if (start_of_line) {
966 file->buf_ptr = p;
967 next_nomacro();
968 p = file->buf_ptr;
969 if (a == 0 &&
970 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
971 goto the_end;
972 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
973 a++;
974 else if (tok == TOK_ENDIF)
975 a--;
976 else if( tok == TOK_ERROR || tok == TOK_WARNING)
977 in_warn_or_error = 1;
978 else if (tok == TOK_LINEFEED)
979 goto redo_start;
980 else if (parse_flags & PARSE_FLAG_ASM_FILE)
981 p = parse_line_comment(p - 1);
982 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
983 p = parse_line_comment(p - 1);
984 break;
985 _default:
986 default:
987 p++;
988 break;
990 start_of_line = 0;
992 the_end: ;
993 file->buf_ptr = p;
996 /* ParseState handling */
998 /* XXX: currently, no include file info is stored. Thus, we cannot display
999 accurate messages if the function or data definition spans multiple
1000 files */
1002 /* save current parse state in 's' */
1003 ST_FUNC void save_parse_state(ParseState *s)
1005 s->line_num = file->line_num;
1006 s->macro_ptr = macro_ptr;
1007 s->tok = tok;
1008 s->tokc = tokc;
1011 /* restore parse state from 's' */
1012 ST_FUNC void restore_parse_state(ParseState *s)
1014 file->line_num = s->line_num;
1015 macro_ptr = s->macro_ptr;
1016 tok = s->tok;
1017 tokc = s->tokc;
1020 /* return the number of additional 'ints' necessary to store the
1021 token */
1022 static inline int tok_size(const int *p)
1024 switch(*p) {
1025 /* 4 bytes */
1026 case TOK_CINT:
1027 case TOK_CUINT:
1028 case TOK_CCHAR:
1029 case TOK_LCHAR:
1030 case TOK_CFLOAT:
1031 case TOK_LINENUM:
1032 return 1 + 1;
1033 case TOK_STR:
1034 case TOK_LSTR:
1035 case TOK_PPNUM:
1036 case TOK_PPSTR:
1037 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1038 case TOK_CDOUBLE:
1039 case TOK_CLLONG:
1040 case TOK_CULLONG:
1041 return 1 + 2;
1042 case TOK_CLDOUBLE:
1043 return 1 + LDOUBLE_SIZE / 4;
1044 default:
1045 return 1 + 0;
1049 /* token string handling */
1051 ST_INLN void tok_str_new(TokenString *s)
1053 s->str = NULL;
1054 s->len = 0;
1055 s->allocated_len = 0;
1056 s->last_line_num = -1;
1059 ST_FUNC TokenString *tok_str_alloc(void)
1061 TokenString *str = tal_realloc(tokstr_alloc, 0, sizeof *str);
1062 tok_str_new(str);
1063 return str;
1066 ST_FUNC int *tok_str_dup(TokenString *s)
1068 int *str;
1070 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1071 memcpy(str, s->str, s->len * sizeof(int));
1072 return str;
1075 ST_FUNC void tok_str_free_str(int *str)
1077 tal_free(tokstr_alloc, str);
1080 ST_FUNC void tok_str_free(TokenString *str)
1082 tok_str_free_str(str->str);
1083 tal_free(tokstr_alloc, str);
1086 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1088 int *str, size;
1090 size = s->allocated_len;
1091 if (size < 16)
1092 size = 16;
1093 while (size < new_size)
1094 size = size * 2;
1095 if (size > s->allocated_len) {
1096 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1097 s->allocated_len = size;
1098 s->str = str;
1100 return s->str;
1103 ST_FUNC void tok_str_add(TokenString *s, int t)
1105 int len, *str;
1107 len = s->len;
1108 str = s->str;
1109 if (len >= s->allocated_len)
1110 str = tok_str_realloc(s, len + 1);
1111 str[len++] = t;
1112 s->len = len;
1115 ST_FUNC void begin_macro(TokenString *str, int alloc)
1117 str->alloc = alloc;
1118 str->prev = macro_stack;
1119 str->prev_ptr = macro_ptr;
1120 macro_ptr = str->str;
1121 macro_stack = str;
1124 ST_FUNC void end_macro(void)
1126 TokenString *str = macro_stack;
1127 macro_stack = str->prev;
1128 macro_ptr = str->prev_ptr;
1129 if (str->alloc == 2) {
1130 str->alloc = 3; /* just mark as finished */
1131 } else {
1132 tok_str_free(str);
1136 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1138 int len, *str;
1140 len = s->len;
1141 str = s->str;
1143 /* allocate space for worst case */
1144 if (len + TOK_MAX_SIZE >= s->allocated_len)
1145 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1146 str[len++] = t;
1147 switch(t) {
1148 case TOK_CINT:
1149 case TOK_CUINT:
1150 case TOK_CCHAR:
1151 case TOK_LCHAR:
1152 case TOK_CFLOAT:
1153 case TOK_LINENUM:
1154 str[len++] = cv->tab[0];
1155 break;
1156 case TOK_PPNUM:
1157 case TOK_PPSTR:
1158 case TOK_STR:
1159 case TOK_LSTR:
1161 /* Insert the string into the int array. */
1162 size_t nb_words =
1163 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1164 if (len + nb_words >= s->allocated_len)
1165 str = tok_str_realloc(s, len + nb_words + 1);
1166 str[len] = cv->str.size;
1167 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1168 len += nb_words;
1170 break;
1171 case TOK_CDOUBLE:
1172 case TOK_CLLONG:
1173 case TOK_CULLONG:
1174 #if LDOUBLE_SIZE == 8
1175 case TOK_CLDOUBLE:
1176 #endif
1177 str[len++] = cv->tab[0];
1178 str[len++] = cv->tab[1];
1179 break;
1180 #if LDOUBLE_SIZE == 12
1181 case TOK_CLDOUBLE:
1182 str[len++] = cv->tab[0];
1183 str[len++] = cv->tab[1];
1184 str[len++] = cv->tab[2];
1185 #elif LDOUBLE_SIZE == 16
1186 case TOK_CLDOUBLE:
1187 str[len++] = cv->tab[0];
1188 str[len++] = cv->tab[1];
1189 str[len++] = cv->tab[2];
1190 str[len++] = cv->tab[3];
1191 #elif LDOUBLE_SIZE != 8
1192 #error add long double size support
1193 #endif
1194 break;
1195 default:
1196 break;
1198 s->len = len;
1201 /* add the current parse token in token string 's' */
1202 ST_FUNC void tok_str_add_tok(TokenString *s)
1204 CValue cval;
1206 /* save line number info */
1207 if (file->line_num != s->last_line_num) {
1208 s->last_line_num = file->line_num;
1209 cval.i = s->last_line_num;
1210 tok_str_add2(s, TOK_LINENUM, &cval);
1212 tok_str_add2(s, tok, &tokc);
1215 /* get a token from an integer array and increment pointer
1216 accordingly. we code it as a macro to avoid pointer aliasing. */
1217 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
1219 const int *p = *pp;
1220 int n, *tab;
1222 tab = cv->tab;
1223 switch(*t = *p++) {
1224 case TOK_CINT:
1225 case TOK_CUINT:
1226 case TOK_CCHAR:
1227 case TOK_LCHAR:
1228 case TOK_CFLOAT:
1229 case TOK_LINENUM:
1230 tab[0] = *p++;
1231 break;
1232 case TOK_STR:
1233 case TOK_LSTR:
1234 case TOK_PPNUM:
1235 case TOK_PPSTR:
1236 cv->str.size = *p++;
1237 cv->str.data = p;
1238 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1239 break;
1240 case TOK_CDOUBLE:
1241 case TOK_CLLONG:
1242 case TOK_CULLONG:
1243 n = 2;
1244 goto copy;
1245 case TOK_CLDOUBLE:
1246 #if LDOUBLE_SIZE == 16
1247 n = 4;
1248 #elif LDOUBLE_SIZE == 12
1249 n = 3;
1250 #elif LDOUBLE_SIZE == 8
1251 n = 2;
1252 #else
1253 # error add long double size support
1254 #endif
1255 copy:
1257 *tab++ = *p++;
1258 while (--n);
1259 break;
1260 default:
1261 break;
1263 *pp = p;
1266 /* Calling this function is expensive, but it is not possible
1267 to read a token string backwards. */
1268 static int tok_last(const int *str0, const int *str1)
1270 const int *str = str0;
1271 int tok = 0;
1272 CValue cval;
1274 while (str < str1)
1275 TOK_GET(&tok, &str, &cval);
1276 return tok;
1279 static int macro_is_equal(const int *a, const int *b)
1281 CValue cv;
1282 int t;
1283 static CString localbuf;
1285 if (!a || !b)
1286 return 1;
1288 while (*a && *b) {
1289 /* first time preallocate static localbuf, next time only reset position to start */
1290 cstr_reset(&localbuf);
1291 TOK_GET(&t, &a, &cv);
1292 cstr_cat(&localbuf, get_tok_str(t, &cv), 0);
1293 TOK_GET(&t, &b, &cv);
1294 if (strcmp(localbuf.data, get_tok_str(t, &cv)))
1295 return 0;
1297 return !(*a || *b);
1300 /* defines handling */
1301 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1303 Sym *s, *o;
1305 o = define_find(v);
1306 s = sym_push2(&define_stack, v, macro_type, 0);
1307 s->d = str;
1308 s->next = first_arg;
1309 table_ident[v - TOK_IDENT]->sym_define = s;
1311 if (o && !macro_is_equal(o->d, s->d))
1312 tcc_warning("%s redefined", get_tok_str(v, NULL));
1315 /* undefined a define symbol. Its name is just set to zero */
1316 ST_FUNC void define_undef(Sym *s)
1318 int v = s->v;
1319 if (v >= TOK_IDENT && v < tok_ident)
1320 table_ident[v - TOK_IDENT]->sym_define = NULL;
1323 ST_INLN Sym *define_find(int v)
1325 v -= TOK_IDENT;
1326 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1327 return NULL;
1328 return table_ident[v]->sym_define;
1331 /* free define stack until top reaches 'b' */
1332 ST_FUNC void free_defines(Sym *b)
1334 while (define_stack != b) {
1335 Sym *top = define_stack;
1336 define_stack = top->prev;
1337 tok_str_free_str(top->d);
1338 define_undef(top);
1339 sym_free(top);
1342 /* restore remaining (-D or predefined) symbols */
1343 while (b) {
1344 int v = b->v;
1345 if (v >= TOK_IDENT && v < tok_ident) {
1346 Sym **d = &table_ident[v - TOK_IDENT]->sym_define;
1347 if (!*d)
1348 *d = b;
1350 b = b->prev;
1354 /* label lookup */
1355 ST_FUNC Sym *label_find(int v)
1357 v -= TOK_IDENT;
1358 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1359 return NULL;
1360 return table_ident[v]->sym_label;
1363 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1365 Sym *s, **ps;
1366 s = sym_push2(ptop, v, 0, 0);
1367 s->r = flags;
1368 ps = &table_ident[v - TOK_IDENT]->sym_label;
1369 if (ptop == &global_label_stack) {
1370 /* modify the top most local identifier, so that
1371 sym_identifier will point to 's' when popped */
1372 while (*ps != NULL)
1373 ps = &(*ps)->prev_tok;
1375 s->prev_tok = *ps;
1376 *ps = s;
1377 return s;
1380 /* pop labels until element last is reached. Look if any labels are
1381 undefined. Define symbols if '&&label' was used. */
1382 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1384 Sym *s, *s1;
1385 for(s = *ptop; s != slast; s = s1) {
1386 s1 = s->prev;
1387 if (s->r == LABEL_DECLARED) {
1388 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1389 } else if (s->r == LABEL_FORWARD) {
1390 tcc_error("label '%s' used but not defined",
1391 get_tok_str(s->v, NULL));
1392 } else {
1393 if (s->c) {
1394 /* define corresponding symbol. A size of
1395 1 is put. */
1396 put_extern_sym(s, cur_text_section, s->jnext, 1);
1399 /* remove label */
1400 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1401 sym_free(s);
1403 *ptop = slast;
1406 /* eval an expression for #if/#elif */
1407 static int expr_preprocess(void)
1409 int c, t;
1410 TokenString *str;
1412 str = tok_str_alloc();
1413 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1414 next(); /* do macro subst */
1415 if (tok == TOK_DEFINED) {
1416 next_nomacro();
1417 t = tok;
1418 if (t == '(')
1419 next_nomacro();
1420 c = define_find(tok) != 0;
1421 if (t == '(')
1422 next_nomacro();
1423 tok = TOK_CINT;
1424 tokc.i = c;
1425 } else if (tok >= TOK_IDENT) {
1426 /* if undefined macro */
1427 tok = TOK_CINT;
1428 tokc.i = 0;
1430 tok_str_add_tok(str);
1432 tok_str_add(str, -1); /* simulate end of file */
1433 tok_str_add(str, 0);
1434 /* now evaluate C constant expression */
1435 begin_macro(str, 1);
1436 next();
1437 c = expr_const();
1438 end_macro();
1439 return c != 0;
1443 /* parse after #define */
1444 ST_FUNC void parse_define(void)
1446 Sym *s, *first, **ps;
1447 int v, t, varg, is_vaargs, spc;
1448 int saved_parse_flags = parse_flags;
1450 v = tok;
1451 if (v < TOK_IDENT)
1452 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1453 /* XXX: should check if same macro (ANSI) */
1454 first = NULL;
1455 t = MACRO_OBJ;
1456 /* '(' must be just after macro definition for MACRO_FUNC */
1457 parse_flags |= PARSE_FLAG_SPACES;
1458 next_nomacro_spc();
1459 if (tok == '(') {
1460 /* must be able to parse TOK_DOTS (in asm mode '.' can be part of identifier) */
1461 parse_flags &= ~PARSE_FLAG_ASM_FILE;
1462 isidnum_table['.' - CH_EOF] = 0;
1463 next_nomacro();
1464 ps = &first;
1465 if (tok != ')') for (;;) {
1466 varg = tok;
1467 next_nomacro();
1468 is_vaargs = 0;
1469 if (varg == TOK_DOTS) {
1470 varg = TOK___VA_ARGS__;
1471 is_vaargs = 1;
1472 } else if (tok == TOK_DOTS && gnu_ext) {
1473 is_vaargs = 1;
1474 next_nomacro();
1476 if (varg < TOK_IDENT)
1477 bad_list:
1478 tcc_error("bad macro parameter list");
1479 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1480 *ps = s;
1481 ps = &s->next;
1482 if (tok == ')')
1483 break;
1484 if (tok != ',' || is_vaargs)
1485 goto bad_list;
1486 next_nomacro();
1488 next_nomacro_spc();
1489 t = MACRO_FUNC;
1490 parse_flags |= (saved_parse_flags & PARSE_FLAG_ASM_FILE);
1491 isidnum_table['.' - CH_EOF] =
1492 (parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0;
1495 tokstr_buf.len = 0;
1496 spc = 2;
1497 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1498 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1499 /* remove spaces around ## and after '#' */
1500 if (TOK_TWOSHARPS == tok) {
1501 if (2 == spc)
1502 goto bad_twosharp;
1503 if (1 == spc)
1504 --tokstr_buf.len;
1505 spc = 3;
1506 } else if ('#' == tok) {
1507 spc = 4;
1508 } else if (check_space(tok, &spc)) {
1509 goto skip;
1511 tok_str_add2(&tokstr_buf, tok, &tokc);
1512 skip:
1513 next_nomacro_spc();
1516 parse_flags = saved_parse_flags;
1517 if (spc == 1)
1518 --tokstr_buf.len; /* remove trailing space */
1519 tok_str_add(&tokstr_buf, 0);
1520 if (3 == spc)
1521 bad_twosharp:
1522 tcc_error("'##' cannot appear at either end of macro");
1523 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1526 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1528 const unsigned char *s;
1529 unsigned int h;
1530 CachedInclude *e;
1531 int i;
1533 h = TOK_HASH_INIT;
1534 s = (unsigned char *) filename;
1535 while (*s) {
1536 #ifdef _WIN32
1537 h = TOK_HASH_FUNC(h, toup(*s));
1538 #else
1539 h = TOK_HASH_FUNC(h, *s);
1540 #endif
1541 s++;
1543 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1545 i = s1->cached_includes_hash[h];
1546 for(;;) {
1547 if (i == 0)
1548 break;
1549 e = s1->cached_includes[i - 1];
1550 if (0 == PATHCMP(e->filename, filename))
1551 return e;
1552 i = e->hash_next;
1554 if (!add)
1555 return NULL;
1557 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1558 strcpy(e->filename, filename);
1559 e->ifndef_macro = e->once = 0;
1560 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1561 /* add in hash table */
1562 e->hash_next = s1->cached_includes_hash[h];
1563 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1564 #ifdef INC_DEBUG
1565 printf("adding cached '%s'\n", filename);
1566 #endif
1567 return e;
1570 static void pragma_parse(TCCState *s1)
1572 next_nomacro();
1573 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1574 int t = tok, v;
1575 Sym *s;
1577 if (next(), tok != '(')
1578 goto pragma_err;
1579 if (next(), tok != TOK_STR)
1580 goto pragma_err;
1581 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1582 if (next(), tok != ')')
1583 goto pragma_err;
1584 if (t == TOK_push_macro) {
1585 while (NULL == (s = define_find(v)))
1586 define_push(v, 0, NULL, NULL);
1587 s->type.ref = s; /* set push boundary */
1588 } else {
1589 for (s = define_stack; s; s = s->prev)
1590 if (s->v == v && s->type.ref == s) {
1591 s->type.ref = NULL;
1592 break;
1595 if (s)
1596 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1597 else
1598 tcc_warning("unbalanced #pragma pop_macro");
1599 pp_debug_tok = t, pp_debug_symv = v;
1601 } else if (tok == TOK_once) {
1602 search_cached_include(s1, file->filename, 1)->once = pp_once;
1604 } else if (s1->ppfp) {
1605 /* tcc -E: keep pragmas below unchanged */
1606 unget_tok(' ');
1607 unget_tok(TOK_PRAGMA);
1608 unget_tok('#');
1609 unget_tok(TOK_LINEFEED);
1611 } else if (tok == TOK_pack) {
1612 /* This may be:
1613 #pragma pack(1) // set
1614 #pragma pack() // reset to default
1615 #pragma pack(push,1) // push & set
1616 #pragma pack(pop) // restore previous */
1617 next();
1618 skip('(');
1619 if (tok == TOK_ASM_pop) {
1620 next();
1621 if (s1->pack_stack_ptr <= s1->pack_stack) {
1622 stk_error:
1623 tcc_error("out of pack stack");
1625 s1->pack_stack_ptr--;
1626 } else {
1627 int val = 0;
1628 if (tok != ')') {
1629 if (tok == TOK_ASM_push) {
1630 next();
1631 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1632 goto stk_error;
1633 s1->pack_stack_ptr++;
1634 skip(',');
1636 if (tok != TOK_CINT)
1637 goto pragma_err;
1638 val = tokc.i;
1639 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1640 goto pragma_err;
1641 next();
1643 *s1->pack_stack_ptr = val;
1645 if (tok != ')')
1646 goto pragma_err;
1648 } else if (tok == TOK_comment) {
1649 char *file;
1650 next();
1651 skip('(');
1652 if (tok != TOK_lib)
1653 goto pragma_warn;
1654 next();
1655 skip(',');
1656 if (tok != TOK_STR)
1657 goto pragma_err;
1658 file = tcc_strdup((char *)tokc.str.data);
1659 dynarray_add((void ***)&s1->pragma_libs, &s1->nb_pragma_libs, file);
1660 next();
1661 if (tok != ')')
1662 goto pragma_err;
1663 } else {
1664 pragma_warn:
1665 if (s1->warn_unsupported)
1666 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1668 return;
1670 pragma_err:
1671 tcc_error("malformed #pragma directive");
1672 return;
1675 /* is_bof is true if first non space token at beginning of file */
1676 ST_FUNC void preprocess(int is_bof)
1678 TCCState *s1 = tcc_state;
1679 int i, c, n, saved_parse_flags;
1680 char buf[1024], *q;
1681 Sym *s;
1683 saved_parse_flags = parse_flags;
1684 parse_flags = PARSE_FLAG_PREPROCESS
1685 | PARSE_FLAG_TOK_NUM
1686 | PARSE_FLAG_TOK_STR
1687 | PARSE_FLAG_LINEFEED
1688 | (parse_flags & PARSE_FLAG_ASM_FILE)
1691 next_nomacro();
1692 redo:
1693 switch(tok) {
1694 case TOK_DEFINE:
1695 pp_debug_tok = tok;
1696 next_nomacro();
1697 pp_debug_symv = tok;
1698 parse_define();
1699 break;
1700 case TOK_UNDEF:
1701 pp_debug_tok = tok;
1702 next_nomacro();
1703 pp_debug_symv = tok;
1704 s = define_find(tok);
1705 /* undefine symbol by putting an invalid name */
1706 if (s)
1707 define_undef(s);
1708 break;
1709 case TOK_INCLUDE:
1710 case TOK_INCLUDE_NEXT:
1711 ch = file->buf_ptr[0];
1712 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1713 skip_spaces();
1714 if (ch == '<') {
1715 c = '>';
1716 goto read_name;
1717 } else if (ch == '\"') {
1718 c = ch;
1719 read_name:
1720 inp();
1721 q = buf;
1722 while (ch != c && ch != '\n' && ch != CH_EOF) {
1723 if ((q - buf) < sizeof(buf) - 1)
1724 *q++ = ch;
1725 if (ch == '\\') {
1726 if (handle_stray_noerror() == 0)
1727 --q;
1728 } else
1729 inp();
1731 *q = '\0';
1732 minp();
1733 #if 0
1734 /* eat all spaces and comments after include */
1735 /* XXX: slightly incorrect */
1736 while (ch1 != '\n' && ch1 != CH_EOF)
1737 inp();
1738 #endif
1739 } else {
1740 /* computed #include : either we have only strings or
1741 we have anything enclosed in '<>' */
1742 next();
1743 buf[0] = '\0';
1744 if (tok == TOK_STR) {
1745 while (tok != TOK_LINEFEED) {
1746 if (tok != TOK_STR) {
1747 include_syntax:
1748 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1750 pstrcat(buf, sizeof(buf), (char *)tokc.str.data);
1751 next();
1753 c = '\"';
1754 } else {
1755 int len;
1756 while (tok != TOK_LINEFEED) {
1757 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1758 next();
1760 len = strlen(buf);
1761 /* check syntax and remove '<>' */
1762 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1763 goto include_syntax;
1764 memmove(buf, buf + 1, len - 2);
1765 buf[len - 2] = '\0';
1766 c = '>';
1770 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1771 tcc_error("#include recursion too deep");
1772 /* store current file in stack, but increment stack later below */
1773 *s1->include_stack_ptr = file;
1774 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index : 0;
1775 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1776 for (; i < n; ++i) {
1777 char buf1[sizeof file->filename];
1778 CachedInclude *e;
1779 const char *path;
1781 if (i == 0) {
1782 /* check absolute include path */
1783 if (!IS_ABSPATH(buf))
1784 continue;
1785 buf1[0] = 0;
1787 } else if (i == 1) {
1788 /* search in file's dir if "header.h" */
1789 if (c != '\"')
1790 continue;
1791 path = file->filename;
1792 pstrncpy(buf1, path, tcc_basename(path) - path);
1794 } else {
1795 /* search in all the include paths */
1796 int j = i - 2, k = j - s1->nb_include_paths;
1797 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1798 pstrcpy(buf1, sizeof(buf1), path);
1799 pstrcat(buf1, sizeof(buf1), "/");
1802 pstrcat(buf1, sizeof(buf1), buf);
1803 e = search_cached_include(s1, buf1, 0);
1804 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1805 /* no need to parse the include because the 'ifndef macro'
1806 is defined (or had #pragma once) */
1807 #ifdef INC_DEBUG
1808 printf("%s: skipping cached %s\n", file->filename, buf1);
1809 #endif
1810 goto include_done;
1813 if (tcc_open(s1, buf1) < 0)
1814 continue;
1816 file->include_next_index = i + 1;
1817 #ifdef INC_DEBUG
1818 printf("%s: including %s\n", file->prev->filename, file->filename);
1819 #endif
1820 /* update target deps */
1821 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1822 tcc_strdup(buf1));
1823 /* push current file in stack */
1824 ++s1->include_stack_ptr;
1825 /* add include file debug info */
1826 if (s1->do_debug)
1827 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1828 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1829 ch = file->buf_ptr[0];
1830 goto the_end;
1832 tcc_error("include file '%s' not found", buf);
1833 include_done:
1834 break;
1835 case TOK_IFNDEF:
1836 c = 1;
1837 goto do_ifdef;
1838 case TOK_IF:
1839 c = expr_preprocess();
1840 goto do_if;
1841 case TOK_IFDEF:
1842 c = 0;
1843 do_ifdef:
1844 next_nomacro();
1845 if (tok < TOK_IDENT)
1846 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1847 if (is_bof) {
1848 if (c) {
1849 #ifdef INC_DEBUG
1850 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1851 #endif
1852 file->ifndef_macro = tok;
1855 c = (define_find(tok) != 0) ^ c;
1856 do_if:
1857 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1858 tcc_error("memory full (ifdef)");
1859 *s1->ifdef_stack_ptr++ = c;
1860 goto test_skip;
1861 case TOK_ELSE:
1862 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1863 tcc_error("#else without matching #if");
1864 if (s1->ifdef_stack_ptr[-1] & 2)
1865 tcc_error("#else after #else");
1866 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1867 goto test_else;
1868 case TOK_ELIF:
1869 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1870 tcc_error("#elif without matching #if");
1871 c = s1->ifdef_stack_ptr[-1];
1872 if (c > 1)
1873 tcc_error("#elif after #else");
1874 /* last #if/#elif expression was true: we skip */
1875 if (c == 1) {
1876 c = 0;
1877 } else {
1878 c = expr_preprocess();
1879 s1->ifdef_stack_ptr[-1] = c;
1881 test_else:
1882 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1883 file->ifndef_macro = 0;
1884 test_skip:
1885 if (!(c & 1)) {
1886 preprocess_skip();
1887 is_bof = 0;
1888 goto redo;
1890 break;
1891 case TOK_ENDIF:
1892 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1893 tcc_error("#endif without matching #if");
1894 s1->ifdef_stack_ptr--;
1895 /* '#ifndef macro' was at the start of file. Now we check if
1896 an '#endif' is exactly at the end of file */
1897 if (file->ifndef_macro &&
1898 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1899 file->ifndef_macro_saved = file->ifndef_macro;
1900 /* need to set to zero to avoid false matches if another
1901 #ifndef at middle of file */
1902 file->ifndef_macro = 0;
1903 while (tok != TOK_LINEFEED)
1904 next_nomacro();
1905 tok_flags |= TOK_FLAG_ENDIF;
1906 goto the_end;
1908 break;
1909 case TOK_PPNUM:
1910 n = strtoul((char*)tokc.str.data, &q, 10);
1911 goto _line_num;
1912 case TOK_LINE:
1913 next();
1914 if (tok != TOK_CINT)
1915 _line_err:
1916 tcc_error("wrong #line format");
1917 n = tokc.i;
1918 _line_num:
1919 next();
1920 if (tok != TOK_LINEFEED) {
1921 if (tok == TOK_STR)
1922 pstrcpy(file->filename, sizeof(file->filename), (char *)tokc.str.data);
1923 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1924 break;
1925 else
1926 goto _line_err;
1927 --n;
1929 if (file->fd > 0)
1930 total_lines += file->line_num - n;
1931 file->line_num = n;
1932 if (s1->do_debug)
1933 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1934 break;
1935 case TOK_ERROR:
1936 case TOK_WARNING:
1937 c = tok;
1938 ch = file->buf_ptr[0];
1939 skip_spaces();
1940 q = buf;
1941 while (ch != '\n' && ch != CH_EOF) {
1942 if ((q - buf) < sizeof(buf) - 1)
1943 *q++ = ch;
1944 if (ch == '\\') {
1945 if (handle_stray_noerror() == 0)
1946 --q;
1947 } else
1948 inp();
1950 *q = '\0';
1951 if (c == TOK_ERROR)
1952 tcc_error("#error %s", buf);
1953 else
1954 tcc_warning("#warning %s", buf);
1955 break;
1956 case TOK_PRAGMA:
1957 pragma_parse(s1);
1958 break;
1959 case TOK_LINEFEED:
1960 goto the_end;
1961 default:
1962 /* ignore gas line comment in an 'S' file. */
1963 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1964 goto ignore;
1965 if (tok == '!' && is_bof)
1966 /* '!' is ignored at beginning to allow C scripts. */
1967 goto ignore;
1968 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1969 ignore:
1970 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
1971 goto the_end;
1973 /* ignore other preprocess commands or #! for C scripts */
1974 while (tok != TOK_LINEFEED)
1975 next_nomacro();
1976 the_end:
1977 parse_flags = saved_parse_flags;
1980 /* evaluate escape codes in a string. */
1981 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1983 int c, n;
1984 const uint8_t *p;
1986 p = buf;
1987 for(;;) {
1988 c = *p;
1989 if (c == '\0')
1990 break;
1991 if (c == '\\') {
1992 p++;
1993 /* escape */
1994 c = *p;
1995 switch(c) {
1996 case '0': case '1': case '2': case '3':
1997 case '4': case '5': case '6': case '7':
1998 /* at most three octal digits */
1999 n = c - '0';
2000 p++;
2001 c = *p;
2002 if (isoct(c)) {
2003 n = n * 8 + c - '0';
2004 p++;
2005 c = *p;
2006 if (isoct(c)) {
2007 n = n * 8 + c - '0';
2008 p++;
2011 c = n;
2012 goto add_char_nonext;
2013 case 'x':
2014 case 'u':
2015 case 'U':
2016 p++;
2017 n = 0;
2018 for(;;) {
2019 c = *p;
2020 if (c >= 'a' && c <= 'f')
2021 c = c - 'a' + 10;
2022 else if (c >= 'A' && c <= 'F')
2023 c = c - 'A' + 10;
2024 else if (isnum(c))
2025 c = c - '0';
2026 else
2027 break;
2028 n = n * 16 + c;
2029 p++;
2031 c = n;
2032 goto add_char_nonext;
2033 case 'a':
2034 c = '\a';
2035 break;
2036 case 'b':
2037 c = '\b';
2038 break;
2039 case 'f':
2040 c = '\f';
2041 break;
2042 case 'n':
2043 c = '\n';
2044 break;
2045 case 'r':
2046 c = '\r';
2047 break;
2048 case 't':
2049 c = '\t';
2050 break;
2051 case 'v':
2052 c = '\v';
2053 break;
2054 case 'e':
2055 if (!gnu_ext)
2056 goto invalid_escape;
2057 c = 27;
2058 break;
2059 case '\'':
2060 case '\"':
2061 case '\\':
2062 case '?':
2063 break;
2064 default:
2065 invalid_escape:
2066 if (c >= '!' && c <= '~')
2067 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2068 else
2069 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2070 break;
2073 p++;
2074 add_char_nonext:
2075 if (!is_long)
2076 cstr_ccat(outstr, c);
2077 else
2078 cstr_wccat(outstr, c);
2080 /* add a trailing '\0' */
2081 if (!is_long)
2082 cstr_ccat(outstr, '\0');
2083 else
2084 cstr_wccat(outstr, '\0');
2087 static void parse_string(const char *s, int len)
2089 uint8_t buf[1000], *p = buf;
2090 int is_long, sep;
2092 if ((is_long = *s == 'L'))
2093 ++s, --len;
2094 sep = *s++;
2095 len -= 2;
2096 if (len >= sizeof buf)
2097 p = tcc_malloc(len + 1);
2098 memcpy(p, s, len);
2099 p[len] = 0;
2101 cstr_reset(&tokcstr);
2102 parse_escape_string(&tokcstr, p, is_long);
2103 if (p != buf)
2104 tcc_free(p);
2106 if (sep == '\'') {
2107 int char_size;
2108 /* XXX: make it portable */
2109 if (!is_long)
2110 char_size = 1;
2111 else
2112 char_size = sizeof(nwchar_t);
2113 if (tokcstr.size <= char_size)
2114 tcc_error("empty character constant");
2115 if (tokcstr.size > 2 * char_size)
2116 tcc_warning("multi-character character constant");
2117 if (!is_long) {
2118 tokc.i = *(int8_t *)tokcstr.data;
2119 tok = TOK_CCHAR;
2120 } else {
2121 tokc.i = *(nwchar_t *)tokcstr.data;
2122 tok = TOK_LCHAR;
2124 } else {
2125 tokc.str.size = tokcstr.size;
2126 tokc.str.data = tokcstr.data;
2127 if (!is_long)
2128 tok = TOK_STR;
2129 else
2130 tok = TOK_LSTR;
2134 /* we use 64 bit numbers */
2135 #define BN_SIZE 2
2137 /* bn = (bn << shift) | or_val */
2138 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2140 int i;
2141 unsigned int v;
2142 for(i=0;i<BN_SIZE;i++) {
2143 v = bn[i];
2144 bn[i] = (v << shift) | or_val;
2145 or_val = v >> (32 - shift);
2149 static void bn_zero(unsigned int *bn)
2151 int i;
2152 for(i=0;i<BN_SIZE;i++) {
2153 bn[i] = 0;
2157 /* parse number in null terminated string 'p' and return it in the
2158 current token */
2159 static void parse_number(const char *p)
2161 int b, t, shift, frac_bits, s, exp_val, ch;
2162 char *q;
2163 unsigned int bn[BN_SIZE];
2164 double d;
2166 /* number */
2167 q = token_buf;
2168 ch = *p++;
2169 t = ch;
2170 ch = *p++;
2171 *q++ = t;
2172 b = 10;
2173 if (t == '.') {
2174 goto float_frac_parse;
2175 } else if (t == '0') {
2176 if (ch == 'x' || ch == 'X') {
2177 q--;
2178 ch = *p++;
2179 b = 16;
2180 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
2181 q--;
2182 ch = *p++;
2183 b = 2;
2186 /* parse all digits. cannot check octal numbers at this stage
2187 because of floating point constants */
2188 while (1) {
2189 if (ch >= 'a' && ch <= 'f')
2190 t = ch - 'a' + 10;
2191 else if (ch >= 'A' && ch <= 'F')
2192 t = ch - 'A' + 10;
2193 else if (isnum(ch))
2194 t = ch - '0';
2195 else
2196 break;
2197 if (t >= b)
2198 break;
2199 if (q >= token_buf + STRING_MAX_SIZE) {
2200 num_too_long:
2201 tcc_error("number too long");
2203 *q++ = ch;
2204 ch = *p++;
2206 if (ch == '.' ||
2207 ((ch == 'e' || ch == 'E') && b == 10) ||
2208 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2209 if (b != 10) {
2210 /* NOTE: strtox should support that for hexa numbers, but
2211 non ISOC99 libcs do not support it, so we prefer to do
2212 it by hand */
2213 /* hexadecimal or binary floats */
2214 /* XXX: handle overflows */
2215 *q = '\0';
2216 if (b == 16)
2217 shift = 4;
2218 else
2219 shift = 1;
2220 bn_zero(bn);
2221 q = token_buf;
2222 while (1) {
2223 t = *q++;
2224 if (t == '\0') {
2225 break;
2226 } else if (t >= 'a') {
2227 t = t - 'a' + 10;
2228 } else if (t >= 'A') {
2229 t = t - 'A' + 10;
2230 } else {
2231 t = t - '0';
2233 bn_lshift(bn, shift, t);
2235 frac_bits = 0;
2236 if (ch == '.') {
2237 ch = *p++;
2238 while (1) {
2239 t = ch;
2240 if (t >= 'a' && t <= 'f') {
2241 t = t - 'a' + 10;
2242 } else if (t >= 'A' && t <= 'F') {
2243 t = t - 'A' + 10;
2244 } else if (t >= '0' && t <= '9') {
2245 t = t - '0';
2246 } else {
2247 break;
2249 if (t >= b)
2250 tcc_error("invalid digit");
2251 bn_lshift(bn, shift, t);
2252 frac_bits += shift;
2253 ch = *p++;
2256 if (ch != 'p' && ch != 'P')
2257 expect("exponent");
2258 ch = *p++;
2259 s = 1;
2260 exp_val = 0;
2261 if (ch == '+') {
2262 ch = *p++;
2263 } else if (ch == '-') {
2264 s = -1;
2265 ch = *p++;
2267 if (ch < '0' || ch > '9')
2268 expect("exponent digits");
2269 while (ch >= '0' && ch <= '9') {
2270 exp_val = exp_val * 10 + ch - '0';
2271 ch = *p++;
2273 exp_val = exp_val * s;
2275 /* now we can generate the number */
2276 /* XXX: should patch directly float number */
2277 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2278 d = ldexp(d, exp_val - frac_bits);
2279 t = toup(ch);
2280 if (t == 'F') {
2281 ch = *p++;
2282 tok = TOK_CFLOAT;
2283 /* float : should handle overflow */
2284 tokc.f = (float)d;
2285 } else if (t == 'L') {
2286 ch = *p++;
2287 #ifdef TCC_TARGET_PE
2288 tok = TOK_CDOUBLE;
2289 tokc.d = d;
2290 #else
2291 tok = TOK_CLDOUBLE;
2292 /* XXX: not large enough */
2293 tokc.ld = (long double)d;
2294 #endif
2295 } else {
2296 tok = TOK_CDOUBLE;
2297 tokc.d = d;
2299 } else {
2300 /* decimal floats */
2301 if (ch == '.') {
2302 if (q >= token_buf + STRING_MAX_SIZE)
2303 goto num_too_long;
2304 *q++ = ch;
2305 ch = *p++;
2306 float_frac_parse:
2307 while (ch >= '0' && ch <= '9') {
2308 if (q >= token_buf + STRING_MAX_SIZE)
2309 goto num_too_long;
2310 *q++ = ch;
2311 ch = *p++;
2314 if (ch == 'e' || ch == 'E') {
2315 if (q >= token_buf + STRING_MAX_SIZE)
2316 goto num_too_long;
2317 *q++ = ch;
2318 ch = *p++;
2319 if (ch == '-' || ch == '+') {
2320 if (q >= token_buf + STRING_MAX_SIZE)
2321 goto num_too_long;
2322 *q++ = ch;
2323 ch = *p++;
2325 if (ch < '0' || ch > '9')
2326 expect("exponent digits");
2327 while (ch >= '0' && ch <= '9') {
2328 if (q >= token_buf + STRING_MAX_SIZE)
2329 goto num_too_long;
2330 *q++ = ch;
2331 ch = *p++;
2334 *q = '\0';
2335 t = toup(ch);
2336 errno = 0;
2337 if (t == 'F') {
2338 ch = *p++;
2339 tok = TOK_CFLOAT;
2340 tokc.f = strtof(token_buf, NULL);
2341 } else if (t == 'L') {
2342 ch = *p++;
2343 #ifdef TCC_TARGET_PE
2344 tok = TOK_CDOUBLE;
2345 tokc.d = strtod(token_buf, NULL);
2346 #else
2347 tok = TOK_CLDOUBLE;
2348 tokc.ld = strtold(token_buf, NULL);
2349 #endif
2350 } else {
2351 tok = TOK_CDOUBLE;
2352 tokc.d = strtod(token_buf, NULL);
2355 } else {
2356 unsigned long long n, n1;
2357 int lcount, ucount, must_64bit;
2358 const char *p1;
2360 /* integer number */
2361 *q = '\0';
2362 q = token_buf;
2363 if (b == 10 && *q == '0') {
2364 b = 8;
2365 q++;
2367 n = 0;
2368 while(1) {
2369 t = *q++;
2370 /* no need for checks except for base 10 / 8 errors */
2371 if (t == '\0')
2372 break;
2373 else if (t >= 'a')
2374 t = t - 'a' + 10;
2375 else if (t >= 'A')
2376 t = t - 'A' + 10;
2377 else
2378 t = t - '0';
2379 if (t >= b)
2380 tcc_error("invalid digit");
2381 n1 = n;
2382 n = n * b + t;
2383 /* detect overflow */
2384 /* XXX: this test is not reliable */
2385 if (n < n1)
2386 tcc_error("integer constant overflow");
2389 /* Determine the characteristics (unsigned and/or 64bit) the type of
2390 the constant must have according to the constant suffix(es) */
2391 lcount = ucount = must_64bit = 0;
2392 p1 = p;
2393 for(;;) {
2394 t = toup(ch);
2395 if (t == 'L') {
2396 if (lcount >= 2)
2397 tcc_error("three 'l's in integer constant");
2398 if (lcount && *(p - 1) != ch)
2399 tcc_error("incorrect integer suffix: %s", p1);
2400 lcount++;
2401 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2402 if (lcount == 2)
2403 #endif
2404 must_64bit = 1;
2405 ch = *p++;
2406 } else if (t == 'U') {
2407 if (ucount >= 1)
2408 tcc_error("two 'u's in integer constant");
2409 ucount++;
2410 ch = *p++;
2411 } else {
2412 break;
2416 /* Whether 64 bits are needed to hold the constant's value */
2417 if (n & 0xffffffff00000000LL || must_64bit) {
2418 tok = TOK_CLLONG;
2419 n1 = n >> 32;
2420 } else {
2421 tok = TOK_CINT;
2422 n1 = n;
2425 /* Whether type must be unsigned to hold the constant's value */
2426 if (ucount || ((n1 >> 31) && (b != 10))) {
2427 if (tok == TOK_CLLONG)
2428 tok = TOK_CULLONG;
2429 else
2430 tok = TOK_CUINT;
2431 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2432 } else if (n1 >> 31) {
2433 if (tok == TOK_CINT)
2434 tok = TOK_CLLONG;
2435 else
2436 tcc_error("integer constant overflow");
2439 tokc.i = n;
2441 if (ch)
2442 tcc_error("invalid number\n");
2446 #define PARSE2(c1, tok1, c2, tok2) \
2447 case c1: \
2448 PEEKC(c, p); \
2449 if (c == c2) { \
2450 p++; \
2451 tok = tok2; \
2452 } else { \
2453 tok = tok1; \
2455 break;
2457 /* return next token without macro substitution */
2458 static inline void next_nomacro1(void)
2460 int t, c, is_long, len;
2461 TokenSym *ts;
2462 uint8_t *p, *p1;
2463 unsigned int h;
2465 p = file->buf_ptr;
2466 redo_no_start:
2467 c = *p;
2468 switch(c) {
2469 case ' ':
2470 case '\t':
2471 tok = c;
2472 p++;
2473 if (parse_flags & PARSE_FLAG_SPACES)
2474 goto keep_tok_flags;
2475 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2476 ++p;
2477 goto redo_no_start;
2478 case '\f':
2479 case '\v':
2480 case '\r':
2481 p++;
2482 goto redo_no_start;
2483 case '\\':
2484 /* first look if it is in fact an end of buffer */
2485 c = handle_stray1(p);
2486 p = file->buf_ptr;
2487 if (c == '\\')
2488 goto parse_simple;
2489 if (c != CH_EOF)
2490 goto redo_no_start;
2492 TCCState *s1 = tcc_state;
2493 if ((parse_flags & PARSE_FLAG_LINEFEED)
2494 && !(tok_flags & TOK_FLAG_EOF)) {
2495 tok_flags |= TOK_FLAG_EOF;
2496 tok = TOK_LINEFEED;
2497 goto keep_tok_flags;
2498 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2499 tok = TOK_EOF;
2500 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2501 tcc_error("missing #endif");
2502 } else if (s1->include_stack_ptr == s1->include_stack) {
2503 /* no include left : end of file. */
2504 tok = TOK_EOF;
2505 } else {
2506 tok_flags &= ~TOK_FLAG_EOF;
2507 /* pop include file */
2509 /* test if previous '#endif' was after a #ifdef at
2510 start of file */
2511 if (tok_flags & TOK_FLAG_ENDIF) {
2512 #ifdef INC_DEBUG
2513 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2514 #endif
2515 search_cached_include(s1, file->filename, 1)
2516 ->ifndef_macro = file->ifndef_macro_saved;
2517 tok_flags &= ~TOK_FLAG_ENDIF;
2520 /* add end of include file debug info */
2521 if (tcc_state->do_debug) {
2522 put_stabd(N_EINCL, 0, 0);
2524 /* pop include stack */
2525 tcc_close();
2526 s1->include_stack_ptr--;
2527 p = file->buf_ptr;
2528 goto redo_no_start;
2531 break;
2533 case '\n':
2534 file->line_num++;
2535 tok_flags |= TOK_FLAG_BOL;
2536 p++;
2537 maybe_newline:
2538 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2539 goto redo_no_start;
2540 tok = TOK_LINEFEED;
2541 goto keep_tok_flags;
2543 case '#':
2544 /* XXX: simplify */
2545 PEEKC(c, p);
2546 if ((tok_flags & TOK_FLAG_BOL) &&
2547 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2548 file->buf_ptr = p;
2549 preprocess(tok_flags & TOK_FLAG_BOF);
2550 p = file->buf_ptr;
2551 goto maybe_newline;
2552 } else {
2553 if (c == '#') {
2554 p++;
2555 tok = TOK_TWOSHARPS;
2556 } else {
2557 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2558 p = parse_line_comment(p - 1);
2559 goto redo_no_start;
2560 } else {
2561 tok = '#';
2565 break;
2567 /* dollar is allowed to start identifiers when not parsing asm */
2568 case '$':
2569 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2570 || (parse_flags & PARSE_FLAG_ASM_FILE))
2571 goto parse_simple;
2573 case 'a': case 'b': case 'c': case 'd':
2574 case 'e': case 'f': case 'g': case 'h':
2575 case 'i': case 'j': case 'k': case 'l':
2576 case 'm': case 'n': case 'o': case 'p':
2577 case 'q': case 'r': case 's': case 't':
2578 case 'u': case 'v': case 'w': case 'x':
2579 case 'y': case 'z':
2580 case 'A': case 'B': case 'C': case 'D':
2581 case 'E': case 'F': case 'G': case 'H':
2582 case 'I': case 'J': case 'K':
2583 case 'M': case 'N': case 'O': case 'P':
2584 case 'Q': case 'R': case 'S': case 'T':
2585 case 'U': case 'V': case 'W': case 'X':
2586 case 'Y': case 'Z':
2587 case '_':
2588 parse_ident_fast:
2589 p1 = p;
2590 h = TOK_HASH_INIT;
2591 h = TOK_HASH_FUNC(h, c);
2592 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2593 h = TOK_HASH_FUNC(h, c);
2594 len = p - p1;
2595 if (c != '\\') {
2596 TokenSym **pts;
2598 /* fast case : no stray found, so we have the full token
2599 and we have already hashed it */
2600 h &= (TOK_HASH_SIZE - 1);
2601 pts = &hash_ident[h];
2602 for(;;) {
2603 ts = *pts;
2604 if (!ts)
2605 break;
2606 if (ts->len == len && !memcmp(ts->str, p1, len))
2607 goto token_found;
2608 pts = &(ts->hash_next);
2610 ts = tok_alloc_new(pts, (char *) p1, len);
2611 token_found: ;
2612 } else {
2613 /* slower case */
2614 cstr_reset(&tokcstr);
2615 cstr_cat(&tokcstr, p1, len);
2616 p--;
2617 PEEKC(c, p);
2618 parse_ident_slow:
2619 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2621 cstr_ccat(&tokcstr, c);
2622 PEEKC(c, p);
2624 ts = tok_alloc(tokcstr.data, tokcstr.size);
2626 tok = ts->tok;
2627 break;
2628 case 'L':
2629 t = p[1];
2630 if (t != '\\' && t != '\'' && t != '\"') {
2631 /* fast case */
2632 goto parse_ident_fast;
2633 } else {
2634 PEEKC(c, p);
2635 if (c == '\'' || c == '\"') {
2636 is_long = 1;
2637 goto str_const;
2638 } else {
2639 cstr_reset(&tokcstr);
2640 cstr_ccat(&tokcstr, 'L');
2641 goto parse_ident_slow;
2644 break;
2646 case '0': case '1': case '2': case '3':
2647 case '4': case '5': case '6': case '7':
2648 case '8': case '9':
2649 t = c;
2650 PEEKC(c, p);
2651 /* after the first digit, accept digits, alpha, '.' or sign if
2652 prefixed by 'eEpP' */
2653 parse_num:
2654 cstr_reset(&tokcstr);
2655 for(;;) {
2656 cstr_ccat(&tokcstr, t);
2657 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2658 || c == '.'
2659 || ((c == '+' || c == '-')
2660 && (((t == 'e' || t == 'E')
2661 && !(parse_flags & PARSE_FLAG_ASM_FILE
2662 /* 0xe+1 is 3 tokens in asm */
2663 && ((char*)tokcstr.data)[0] == '0'
2664 && toup(((char*)tokcstr.data)[1]) == 'X'))
2665 || t == 'p' || t == 'P'))))
2666 break;
2667 t = c;
2668 PEEKC(c, p);
2670 /* We add a trailing '\0' to ease parsing */
2671 cstr_ccat(&tokcstr, '\0');
2672 tokc.str.size = tokcstr.size;
2673 tokc.str.data = tokcstr.data;
2674 tok = TOK_PPNUM;
2675 break;
2677 case '.':
2678 /* special dot handling because it can also start a number */
2679 PEEKC(c, p);
2680 if (isnum(c)) {
2681 t = '.';
2682 goto parse_num;
2683 } else if ((parse_flags & PARSE_FLAG_ASM_FILE)
2684 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2685 *--p = c = '.';
2686 goto parse_ident_fast;
2687 } else if (c == '.') {
2688 PEEKC(c, p);
2689 if (c == '.') {
2690 p++;
2691 tok = TOK_DOTS;
2692 } else {
2693 *--p = '.'; /* may underflow into file->unget[] */
2694 tok = '.';
2696 } else {
2697 tok = '.';
2699 break;
2700 case '\'':
2701 case '\"':
2702 is_long = 0;
2703 str_const:
2704 cstr_reset(&tokcstr);
2705 if (is_long)
2706 cstr_ccat(&tokcstr, 'L');
2707 cstr_ccat(&tokcstr, c);
2708 p = parse_pp_string(p, c, &tokcstr);
2709 cstr_ccat(&tokcstr, c);
2710 cstr_ccat(&tokcstr, '\0');
2711 tokc.str.size = tokcstr.size;
2712 tokc.str.data = tokcstr.data;
2713 tok = TOK_PPSTR;
2714 break;
2716 case '<':
2717 PEEKC(c, p);
2718 if (c == '=') {
2719 p++;
2720 tok = TOK_LE;
2721 } else if (c == '<') {
2722 PEEKC(c, p);
2723 if (c == '=') {
2724 p++;
2725 tok = TOK_A_SHL;
2726 } else {
2727 tok = TOK_SHL;
2729 } else {
2730 tok = TOK_LT;
2732 break;
2733 case '>':
2734 PEEKC(c, p);
2735 if (c == '=') {
2736 p++;
2737 tok = TOK_GE;
2738 } else if (c == '>') {
2739 PEEKC(c, p);
2740 if (c == '=') {
2741 p++;
2742 tok = TOK_A_SAR;
2743 } else {
2744 tok = TOK_SAR;
2746 } else {
2747 tok = TOK_GT;
2749 break;
2751 case '&':
2752 PEEKC(c, p);
2753 if (c == '&') {
2754 p++;
2755 tok = TOK_LAND;
2756 } else if (c == '=') {
2757 p++;
2758 tok = TOK_A_AND;
2759 } else {
2760 tok = '&';
2762 break;
2764 case '|':
2765 PEEKC(c, p);
2766 if (c == '|') {
2767 p++;
2768 tok = TOK_LOR;
2769 } else if (c == '=') {
2770 p++;
2771 tok = TOK_A_OR;
2772 } else {
2773 tok = '|';
2775 break;
2777 case '+':
2778 PEEKC(c, p);
2779 if (c == '+') {
2780 p++;
2781 tok = TOK_INC;
2782 } else if (c == '=') {
2783 p++;
2784 tok = TOK_A_ADD;
2785 } else {
2786 tok = '+';
2788 break;
2790 case '-':
2791 PEEKC(c, p);
2792 if (c == '-') {
2793 p++;
2794 tok = TOK_DEC;
2795 } else if (c == '=') {
2796 p++;
2797 tok = TOK_A_SUB;
2798 } else if (c == '>') {
2799 p++;
2800 tok = TOK_ARROW;
2801 } else {
2802 tok = '-';
2804 break;
2806 PARSE2('!', '!', '=', TOK_NE)
2807 PARSE2('=', '=', '=', TOK_EQ)
2808 PARSE2('*', '*', '=', TOK_A_MUL)
2809 PARSE2('%', '%', '=', TOK_A_MOD)
2810 PARSE2('^', '^', '=', TOK_A_XOR)
2812 /* comments or operator */
2813 case '/':
2814 PEEKC(c, p);
2815 if (c == '*') {
2816 p = parse_comment(p);
2817 /* comments replaced by a blank */
2818 tok = ' ';
2819 goto keep_tok_flags;
2820 } else if (c == '/') {
2821 p = parse_line_comment(p);
2822 tok = ' ';
2823 goto keep_tok_flags;
2824 } else if (c == '=') {
2825 p++;
2826 tok = TOK_A_DIV;
2827 } else {
2828 tok = '/';
2830 break;
2832 /* simple tokens */
2833 case '(':
2834 case ')':
2835 case '[':
2836 case ']':
2837 case '{':
2838 case '}':
2839 case ',':
2840 case ';':
2841 case ':':
2842 case '?':
2843 case '~':
2844 case '@': /* only used in assembler */
2845 parse_simple:
2846 tok = c;
2847 p++;
2848 break;
2849 default:
2850 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2851 goto parse_ident_fast;
2852 if (parse_flags & PARSE_FLAG_ASM_FILE)
2853 goto parse_simple;
2854 tcc_error("unrecognized character \\x%02x", c);
2855 break;
2857 tok_flags = 0;
2858 keep_tok_flags:
2859 file->buf_ptr = p;
2860 #if defined(PARSE_DEBUG)
2861 printf("token = %s\n", get_tok_str(tok, &tokc));
2862 #endif
2865 /* return next token without macro substitution. Can read input from
2866 macro_ptr buffer */
2867 static void next_nomacro_spc(void)
2869 if (macro_ptr) {
2870 redo:
2871 tok = *macro_ptr;
2872 if (tok) {
2873 TOK_GET(&tok, &macro_ptr, &tokc);
2874 if (tok == TOK_LINENUM) {
2875 file->line_num = tokc.i;
2876 goto redo;
2879 } else {
2880 next_nomacro1();
2884 ST_FUNC void next_nomacro(void)
2886 do {
2887 next_nomacro_spc();
2888 } while (tok < 256 && (isidnum_table[tok - CH_EOF] & IS_SPC));
2892 static void macro_subst(
2893 TokenString *tok_str,
2894 Sym **nested_list,
2895 const int *macro_str,
2896 int can_read_stream
2899 /* substitute arguments in replacement lists in macro_str by the values in
2900 args (field d) and return allocated string */
2901 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2903 int t, t0, t1, spc;
2904 const int *st;
2905 Sym *s;
2906 CValue cval;
2907 TokenString str;
2908 CString cstr;
2910 tok_str_new(&str);
2911 t0 = t1 = 0;
2912 while(1) {
2913 TOK_GET(&t, &macro_str, &cval);
2914 if (!t)
2915 break;
2916 if (t == '#') {
2917 /* stringize */
2918 TOK_GET(&t, &macro_str, &cval);
2919 if (!t)
2920 goto bad_stringy;
2921 s = sym_find2(args, t);
2922 if (s) {
2923 cstr_new(&cstr);
2924 cstr_ccat(&cstr, '\"');
2925 st = s->d;
2926 spc = 0;
2927 while (*st) {
2928 TOK_GET(&t, &st, &cval);
2929 if (t != TOK_PLCHLDR
2930 && t != TOK_NOSUBST
2931 && 0 == check_space(t, &spc)) {
2932 const char *s = get_tok_str(t, &cval);
2933 while (*s) {
2934 if (t == TOK_PPSTR && *s != '\'')
2935 add_char(&cstr, *s);
2936 else
2937 cstr_ccat(&cstr, *s);
2938 ++s;
2942 cstr.size -= spc;
2943 cstr_ccat(&cstr, '\"');
2944 cstr_ccat(&cstr, '\0');
2945 #ifdef PP_DEBUG
2946 printf("\nstringize: <%s>\n", (char *)cstr.data);
2947 #endif
2948 /* add string */
2949 cval.str.size = cstr.size;
2950 cval.str.data = cstr.data;
2951 tok_str_add2(&str, TOK_PPSTR, &cval);
2952 cstr_free(&cstr);
2953 } else {
2954 bad_stringy:
2955 expect("macro parameter after '#'");
2957 } else if (t >= TOK_IDENT) {
2958 s = sym_find2(args, t);
2959 if (s) {
2960 int l0 = str.len;
2961 st = s->d;
2962 /* if '##' is present before or after, no arg substitution */
2963 if (*macro_str == TOK_TWOSHARPS || t1 == TOK_TWOSHARPS) {
2964 /* special case for var arg macros : ## eats the ','
2965 if empty VA_ARGS variable. */
2966 if (t1 == TOK_TWOSHARPS && t0 == ',' && gnu_ext && s->type.t) {
2967 if (*st == 0) {
2968 /* suppress ',' '##' */
2969 str.len -= 2;
2970 } else {
2971 /* suppress '##' and add variable */
2972 str.len--;
2973 goto add_var;
2975 } else {
2976 for(;;) {
2977 int t1;
2978 TOK_GET(&t1, &st, &cval);
2979 if (!t1)
2980 break;
2981 tok_str_add2(&str, t1, &cval);
2985 } else {
2986 add_var:
2987 /* NOTE: the stream cannot be read when macro
2988 substituing an argument */
2989 macro_subst(&str, nested_list, st, 0);
2991 if (str.len == l0) /* exanded to empty string */
2992 tok_str_add(&str, TOK_PLCHLDR);
2993 } else {
2994 tok_str_add(&str, t);
2996 } else {
2997 tok_str_add2(&str, t, &cval);
2999 t0 = t1, t1 = t;
3001 tok_str_add(&str, 0);
3002 return str.str;
3005 static char const ab_month_name[12][4] =
3007 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3008 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3011 /* peek or read [ws_str == NULL] next token from function macro call,
3012 walking up macro levels up to the file if necessary */
3013 static int next_argstream(Sym **nested_list, int can_read_stream, TokenString *ws_str)
3015 int t;
3016 const int *p;
3017 Sym *sa;
3019 for (;;) {
3020 if (macro_ptr) {
3021 p = macro_ptr, t = *p;
3022 if (ws_str) {
3023 while (is_space(t) || TOK_LINEFEED == t)
3024 tok_str_add(ws_str, t), t = *++p;
3026 if (t == 0 && can_read_stream) {
3027 end_macro();
3028 /* also, end of scope for nested defined symbol */
3029 sa = *nested_list;
3030 while (sa && sa->v == 0)
3031 sa = sa->prev;
3032 if (sa)
3033 sa->v = 0;
3034 continue;
3036 } else {
3037 ch = handle_eob();
3038 if (ws_str) {
3039 while (is_space(ch) || ch == '\n' || ch == '/') {
3040 if (ch == '/') {
3041 int c;
3042 uint8_t *p = file->buf_ptr;
3043 PEEKC(c, p);
3044 if (c == '*') {
3045 p = parse_comment(p);
3046 file->buf_ptr = p - 1;
3047 } else if (c == '/') {
3048 p = parse_line_comment(p);
3049 file->buf_ptr = p - 1;
3050 } else
3051 break;
3052 ch = ' ';
3054 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3055 tok_str_add(ws_str, ch);
3056 cinp();
3059 t = ch;
3062 if (ws_str)
3063 return t;
3064 next_nomacro_spc();
3065 return tok;
3069 /* do macro substitution of current token with macro 's' and add
3070 result to (tok_str,tok_len). 'nested_list' is the list of all
3071 macros we got inside to avoid recursing. Return non zero if no
3072 substitution needs to be done */
3073 static int macro_subst_tok(
3074 TokenString *tok_str,
3075 Sym **nested_list,
3076 Sym *s,
3077 int can_read_stream)
3079 Sym *args, *sa, *sa1;
3080 int parlevel, *mstr, t, t1, spc;
3081 TokenString str;
3082 char *cstrval;
3083 CValue cval;
3084 CString cstr;
3085 char buf[32];
3087 /* if symbol is a macro, prepare substitution */
3088 /* special macros */
3089 if (tok == TOK___LINE__) {
3090 snprintf(buf, sizeof(buf), "%d", file->line_num);
3091 cstrval = buf;
3092 t1 = TOK_PPNUM;
3093 goto add_cstr1;
3094 } else if (tok == TOK___FILE__) {
3095 cstrval = file->filename;
3096 goto add_cstr;
3097 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3098 time_t ti;
3099 struct tm *tm;
3101 time(&ti);
3102 tm = localtime(&ti);
3103 if (tok == TOK___DATE__) {
3104 snprintf(buf, sizeof(buf), "%s %2d %d",
3105 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3106 } else {
3107 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3108 tm->tm_hour, tm->tm_min, tm->tm_sec);
3110 cstrval = buf;
3111 add_cstr:
3112 t1 = TOK_STR;
3113 add_cstr1:
3114 cstr_new(&cstr);
3115 cstr_cat(&cstr, cstrval, 0);
3116 cval.str.size = cstr.size;
3117 cval.str.data = cstr.data;
3118 tok_str_add2(tok_str, t1, &cval);
3119 cstr_free(&cstr);
3120 } else {
3121 int saved_parse_flags = parse_flags;
3123 mstr = s->d;
3124 if (s->type.t == MACRO_FUNC) {
3125 /* whitespace between macro name and argument list */
3126 TokenString ws_str;
3127 tok_str_new(&ws_str);
3129 spc = 0;
3130 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3131 | PARSE_FLAG_ACCEPT_STRAYS;
3133 /* get next token from argument stream */
3134 t = next_argstream(nested_list, can_read_stream, &ws_str);
3135 if (t != '(') {
3136 /* not a macro substitution after all, restore the
3137 * macro token plus all whitespace we've read.
3138 * whitespace is intentionally not merged to preserve
3139 * newlines. */
3140 parse_flags = saved_parse_flags;
3141 tok_str_add(tok_str, tok);
3142 if (parse_flags & PARSE_FLAG_SPACES) {
3143 int i;
3144 for (i = 0; i < ws_str.len; i++)
3145 tok_str_add(tok_str, ws_str.str[i]);
3147 tok_str_free_str(ws_str.str);
3148 return 0;
3149 } else {
3150 tok_str_free_str(ws_str.str);
3152 next_nomacro(); /* eat '(' */
3154 /* argument macro */
3155 args = NULL;
3156 sa = s->next;
3157 /* NOTE: empty args are allowed, except if no args */
3158 for(;;) {
3159 do {
3160 next_argstream(nested_list, can_read_stream, NULL);
3161 } while (is_space(tok) || TOK_LINEFEED == tok);
3162 empty_arg:
3163 /* handle '()' case */
3164 if (!args && !sa && tok == ')')
3165 break;
3166 if (!sa)
3167 tcc_error("macro '%s' used with too many args",
3168 get_tok_str(s->v, 0));
3169 tok_str_new(&str);
3170 parlevel = spc = 0;
3171 /* NOTE: non zero sa->t indicates VA_ARGS */
3172 while ((parlevel > 0 ||
3173 (tok != ')' &&
3174 (tok != ',' || sa->type.t)))) {
3175 if (tok == TOK_EOF || tok == 0)
3176 break;
3177 if (tok == '(')
3178 parlevel++;
3179 else if (tok == ')')
3180 parlevel--;
3181 if (tok == TOK_LINEFEED)
3182 tok = ' ';
3183 if (!check_space(tok, &spc))
3184 tok_str_add2(&str, tok, &tokc);
3185 next_argstream(nested_list, can_read_stream, NULL);
3187 if (parlevel)
3188 expect(")");
3189 str.len -= spc;
3190 tok_str_add(&str, 0);
3191 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3192 sa1->d = str.str;
3193 sa = sa->next;
3194 if (tok == ')') {
3195 /* special case for gcc var args: add an empty
3196 var arg argument if it is omitted */
3197 if (sa && sa->type.t && gnu_ext)
3198 goto empty_arg;
3199 break;
3201 if (tok != ',')
3202 expect(",");
3204 if (sa) {
3205 tcc_error("macro '%s' used with too few args",
3206 get_tok_str(s->v, 0));
3209 parse_flags = saved_parse_flags;
3211 /* now subst each arg */
3212 mstr = macro_arg_subst(nested_list, mstr, args);
3213 /* free memory */
3214 sa = args;
3215 while (sa) {
3216 sa1 = sa->prev;
3217 tok_str_free_str(sa->d);
3218 sym_free(sa);
3219 sa = sa1;
3223 sym_push2(nested_list, s->v, 0, 0);
3224 parse_flags = saved_parse_flags;
3225 macro_subst(tok_str, nested_list, mstr, can_read_stream | 2);
3227 /* pop nested defined symbol */
3228 sa1 = *nested_list;
3229 *nested_list = sa1->prev;
3230 sym_free(sa1);
3231 if (mstr != s->d)
3232 tok_str_free_str(mstr);
3234 return 0;
3237 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3239 CString cstr;
3240 int n, ret = 1;
3242 cstr_new(&cstr);
3243 if (t1 != TOK_PLCHLDR)
3244 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3245 n = cstr.size;
3246 if (t2 != TOK_PLCHLDR)
3247 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3248 cstr_ccat(&cstr, '\0');
3250 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3251 memcpy(file->buffer, cstr.data, cstr.size);
3252 for (;;) {
3253 next_nomacro1();
3254 if (0 == *file->buf_ptr)
3255 break;
3256 if (is_space(tok))
3257 continue;
3258 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3259 " preprocessing token", n, cstr.data, (char*)cstr.data + n);
3260 ret = 0;
3261 break;
3263 tcc_close();
3264 //printf("paste <%s>\n", (char*)cstr.data);
3265 cstr_free(&cstr);
3266 return ret;
3269 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3270 return the resulting string (which must be freed). */
3271 static inline int *macro_twosharps(const int *ptr0)
3273 int t;
3274 CValue cval;
3275 TokenString macro_str1;
3276 int start_of_nosubsts = -1;
3277 const int *ptr;
3279 /* we search the first '##' */
3280 for (ptr = ptr0;;) {
3281 TOK_GET(&t, &ptr, &cval);
3282 if (t == TOK_TWOSHARPS)
3283 break;
3284 if (t == 0)
3285 return NULL;
3288 tok_str_new(&macro_str1);
3290 //tok_print(" $$$", ptr0);
3291 for (ptr = ptr0;;) {
3292 TOK_GET(&t, &ptr, &cval);
3293 if (t == 0)
3294 break;
3295 if (t == TOK_TWOSHARPS)
3296 continue;
3297 while (*ptr == TOK_TWOSHARPS) {
3298 int t1; CValue cv1;
3299 /* given 'a##b', remove nosubsts preceding 'a' */
3300 if (start_of_nosubsts >= 0)
3301 macro_str1.len = start_of_nosubsts;
3302 /* given 'a##b', remove nosubsts preceding 'b' */
3303 while ((t1 = *++ptr) == TOK_NOSUBST)
3305 if (t1 && t1 != TOK_TWOSHARPS) {
3306 TOK_GET(&t1, &ptr, &cv1);
3307 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3308 if (paste_tokens(t, &cval, t1, &cv1)) {
3309 t = tok, cval = tokc;
3310 } else {
3311 tok_str_add2(&macro_str1, t, &cval);
3312 t = t1, cval = cv1;
3317 if (t == TOK_NOSUBST) {
3318 if (start_of_nosubsts < 0)
3319 start_of_nosubsts = macro_str1.len;
3320 } else {
3321 start_of_nosubsts = -1;
3323 tok_str_add2(&macro_str1, t, &cval);
3325 tok_str_add(&macro_str1, 0);
3326 //tok_print(" ###", macro_str1.str);
3327 return macro_str1.str;
3330 /* do macro substitution of macro_str and add result to
3331 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3332 inside to avoid recursing. */
3333 static void macro_subst(
3334 TokenString *tok_str,
3335 Sym **nested_list,
3336 const int *macro_str,
3337 int can_read_stream
3340 Sym *s;
3341 const int *ptr;
3342 int t, spc, nosubst;
3343 CValue cval;
3344 int *macro_str1 = NULL;
3346 /* first scan for '##' operator handling */
3347 ptr = macro_str;
3348 spc = nosubst = 0;
3350 /* first scan for '##' operator handling */
3351 if (can_read_stream & 1) {
3352 macro_str1 = macro_twosharps(ptr);
3353 if (macro_str1)
3354 ptr = macro_str1;
3357 while (1) {
3358 TOK_GET(&t, &ptr, &cval);
3359 if (t == 0)
3360 break;
3362 if (t >= TOK_IDENT && 0 == nosubst) {
3363 s = define_find(t);
3364 if (s == NULL)
3365 goto no_subst;
3367 /* if nested substitution, do nothing */
3368 if (sym_find2(*nested_list, t)) {
3369 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3370 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3371 goto no_subst;
3375 TokenString str;
3376 str.str = (int*)ptr;
3377 begin_macro(&str, 2);
3379 tok = t;
3380 macro_subst_tok(tok_str, nested_list, s, can_read_stream);
3382 if (str.alloc == 3) {
3383 /* already finished by reading function macro arguments */
3384 break;
3387 ptr = macro_ptr;
3388 end_macro ();
3391 spc = (tok_str->len &&
3392 is_space(tok_last(tok_str->str,
3393 tok_str->str + tok_str->len)));
3395 } else {
3397 if (t == '\\' && !(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3398 tcc_error("stray '\\' in program");
3400 no_subst:
3401 if (!check_space(t, &spc))
3402 tok_str_add2(tok_str, t, &cval);
3403 nosubst = 0;
3404 if (t == TOK_NOSUBST)
3405 nosubst = 1;
3408 if (macro_str1)
3409 tok_str_free_str(macro_str1);
3413 /* return next token with macro substitution */
3414 ST_FUNC void next(void)
3416 redo:
3417 if (parse_flags & PARSE_FLAG_SPACES)
3418 next_nomacro_spc();
3419 else
3420 next_nomacro();
3422 if (macro_ptr) {
3423 if (tok == TOK_NOSUBST || tok == TOK_PLCHLDR) {
3424 /* discard preprocessor markers */
3425 goto redo;
3426 } else if (tok == 0) {
3427 /* end of macro or unget token string */
3428 end_macro();
3429 goto redo;
3431 } else if (tok >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3432 Sym *s;
3433 /* if reading from file, try to substitute macros */
3434 s = define_find(tok);
3435 if (s) {
3436 Sym *nested_list = NULL;
3437 tokstr_buf.len = 0;
3438 macro_subst_tok(&tokstr_buf, &nested_list, s, 1);
3439 tok_str_add(&tokstr_buf, 0);
3440 begin_macro(&tokstr_buf, 2);
3441 goto redo;
3444 /* convert preprocessor tokens into C tokens */
3445 if (tok == TOK_PPNUM) {
3446 if (parse_flags & PARSE_FLAG_TOK_NUM)
3447 parse_number((char *)tokc.str.data);
3448 } else if (tok == TOK_PPSTR) {
3449 if (parse_flags & PARSE_FLAG_TOK_STR)
3450 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3454 /* push back current token and set current token to 'last_tok'. Only
3455 identifier case handled for labels. */
3456 ST_INLN void unget_tok(int last_tok)
3459 TokenString *str = tok_str_alloc();
3460 tok_str_add2(str, tok, &tokc);
3461 tok_str_add(str, 0);
3462 begin_macro(str, 1);
3463 tok = last_tok;
3466 ST_FUNC void preprocess_start(TCCState *s1)
3468 char *buf;
3469 s1->include_stack_ptr = s1->include_stack;
3470 /* XXX: move that before to avoid having to initialize
3471 file->ifdef_stack_ptr ? */
3472 s1->ifdef_stack_ptr = s1->ifdef_stack;
3473 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3474 pp_once++;
3476 pvtop = vtop = vstack - 1;
3477 s1->pack_stack[0] = 0;
3478 s1->pack_stack_ptr = s1->pack_stack;
3480 isidnum_table['$' - CH_EOF] =
3481 s1->dollars_in_identifiers ? IS_ID : 0;
3482 isidnum_table['.' - CH_EOF] =
3483 (parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0;
3484 buf = tcc_malloc(3 + strlen(file->filename));
3485 sprintf(buf, "\"%s\"", file->filename);
3486 tcc_undefine_symbol(s1, "__BASE_FILE__");
3487 tcc_define_symbol(s1, "__BASE_FILE__", buf);
3488 tcc_free(buf);
3489 if (s1->nb_cmd_include_files) {
3490 CString cstr;
3491 int i;
3492 cstr_new(&cstr);
3493 for (i = 0; i < s1->nb_cmd_include_files; i++) {
3494 cstr_cat(&cstr, "#include \"", -1);
3495 cstr_cat(&cstr, s1->cmd_include_files[i], -1);
3496 cstr_cat(&cstr, "\"\n", -1);
3498 *s1->include_stack_ptr++ = file;
3499 tcc_open_bf(s1, "<command line>", cstr.size);
3500 memcpy(file->buffer, cstr.data, cstr.size);
3501 cstr_free(&cstr);
3505 ST_FUNC void tccpp_new(TCCState *s)
3507 int i, c;
3508 const char *p, *r;
3510 /* might be used in error() before preprocess_start() */
3511 s->include_stack_ptr = s->include_stack;
3513 /* init isid table */
3514 for(i = CH_EOF; i<128; i++)
3515 isidnum_table[i - CH_EOF]
3516 = is_space(i) ? IS_SPC
3517 : isid(i) ? IS_ID
3518 : isnum(i) ? IS_NUM
3519 : 0;
3521 for(i = 128; i<256; i++)
3522 isidnum_table[i - CH_EOF] = IS_ID;
3524 /* init allocators */
3525 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3526 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3527 tal_new(&cstr_alloc, CSTR_TAL_LIMIT, CSTR_TAL_SIZE);
3529 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3530 cstr_new(&cstr_buf);
3531 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3532 tok_str_new(&tokstr_buf);
3533 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3535 tok_ident = TOK_IDENT;
3536 p = tcc_keywords;
3537 while (*p) {
3538 r = p;
3539 for(;;) {
3540 c = *r++;
3541 if (c == '\0')
3542 break;
3544 tok_alloc(p, r - p - 1);
3545 p = r;
3549 ST_FUNC void tccpp_delete(TCCState *s)
3551 int i, n;
3553 /* free -D and compiler defines */
3554 free_defines(NULL);
3556 /* cleanup from error/setjmp */
3557 while (macro_stack)
3558 end_macro();
3559 macro_ptr = NULL;
3561 /* free tokens */
3562 n = tok_ident - TOK_IDENT;
3563 for(i = 0; i < n; i++)
3564 tal_free(toksym_alloc, table_ident[i]);
3565 tcc_free(table_ident);
3566 table_ident = NULL;
3568 /* free static buffers */
3569 cstr_free(&tokcstr);
3570 cstr_free(&cstr_buf);
3571 tok_str_free_str(tokstr_buf.str);
3573 /* free allocators */
3574 tal_delete(toksym_alloc);
3575 toksym_alloc = NULL;
3576 tal_delete(tokstr_alloc);
3577 tokstr_alloc = NULL;
3578 tal_delete(cstr_alloc);
3579 cstr_alloc = NULL;
3582 /* ------------------------------------------------------------------------- */
3583 /* tcc -E [-P[1]] [-dD} support */
3585 static void tok_print(const char *msg, const int *str)
3587 FILE *fp;
3588 int t;
3589 CValue cval;
3591 fp = tcc_state->ppfp;
3592 if (!fp || !tcc_state->dflag)
3593 fp = stdout;
3595 fprintf(fp, "%s ", msg);
3596 while (str) {
3597 TOK_GET(&t, &str, &cval);
3598 if (!t)
3599 break;
3600 fprintf(fp,"%s", get_tok_str(t, &cval));
3602 fprintf(fp, "\n");
3605 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3607 int d = f->line_num - f->line_ref;
3609 if (s1->dflag & 4)
3610 return;
3612 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3614 } else if (level == 0 && f->line_ref && d < 8) {
3615 while (d > 0)
3616 fputs("\n", s1->ppfp), --d;
3617 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3618 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3619 } else {
3620 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3621 level > 0 ? " 1" : level < 0 ? " 2" : "");
3623 f->line_ref = f->line_num;
3626 static void define_print(TCCState *s1, int v)
3628 FILE *fp;
3629 Sym *s;
3631 s = define_find(v);
3632 if (NULL == s || NULL == s->d)
3633 return;
3635 fp = s1->ppfp;
3636 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3637 if (s->type.t == MACRO_FUNC) {
3638 Sym *a = s->next;
3639 fprintf(fp,"(");
3640 if (a)
3641 for (;;) {
3642 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3643 if (!(a = a->next))
3644 break;
3645 fprintf(fp,",");
3647 fprintf(fp,")");
3649 tok_print("", s->d);
3652 static void pp_debug_defines(TCCState *s1)
3654 int v, t;
3655 const char *vs;
3656 FILE *fp;
3658 t = pp_debug_tok;
3659 if (t == 0)
3660 return;
3662 file->line_num--;
3663 pp_line(s1, file, 0);
3664 file->line_ref = ++file->line_num;
3666 fp = s1->ppfp;
3667 v = pp_debug_symv;
3668 vs = get_tok_str(v, NULL);
3669 if (t == TOK_DEFINE) {
3670 define_print(s1, v);
3671 } else if (t == TOK_UNDEF) {
3672 fprintf(fp, "#undef %s\n", vs);
3673 } else if (t == TOK_push_macro) {
3674 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3675 } else if (t == TOK_pop_macro) {
3676 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3678 pp_debug_tok = 0;
3681 static void pp_debug_builtins(TCCState *s1)
3683 int v;
3684 for (v = TOK_IDENT; v < tok_ident; ++v)
3685 define_print(s1, v);
3688 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3689 static int pp_need_space(int a, int b)
3691 return 'E' == a ? '+' == b || '-' == b
3692 : '+' == a ? TOK_INC == b || '+' == b
3693 : '-' == a ? TOK_DEC == b || '-' == b
3694 : a >= TOK_IDENT ? b >= TOK_IDENT
3695 : 0;
3698 /* maybe hex like 0x1e */
3699 static int pp_check_he0xE(int t, const char *p)
3701 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3702 return 'E';
3703 return t;
3706 /* Preprocess the current file */
3707 ST_FUNC int tcc_preprocess(TCCState *s1)
3709 BufferedFile **iptr;
3710 int token_seen, spcs, level;
3711 const char *p;
3712 Sym *define_start;
3714 preprocess_start(s1);
3715 ch = file->buf_ptr[0];
3716 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3717 parse_flags = PARSE_FLAG_PREPROCESS
3718 | (parse_flags & PARSE_FLAG_ASM_FILE)
3719 | PARSE_FLAG_LINEFEED
3720 | PARSE_FLAG_SPACES
3721 | PARSE_FLAG_ACCEPT_STRAYS
3723 define_start = define_stack;
3725 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3726 capability to compile and run itself, provided all numbers are
3727 given as decimals. tcc -E -P10 will do. */
3728 if (s1->Pflag == 1 + 10)
3729 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3731 #ifdef PP_BENCH
3732 /* for PP benchmarks */
3733 do next(); while (tok != TOK_EOF);
3734 free_defines(define_start);
3735 return 0;
3736 #endif
3738 if (s1->dflag & 1) {
3739 pp_debug_builtins(s1);
3740 s1->dflag &= ~1;
3743 token_seen = TOK_LINEFEED, spcs = 0;
3744 pp_line(s1, file, 0);
3746 for (;;) {
3747 iptr = s1->include_stack_ptr;
3748 next();
3749 if (tok == TOK_EOF)
3750 break;
3751 level = s1->include_stack_ptr - iptr;
3752 if (level) {
3753 if (level > 0)
3754 pp_line(s1, *iptr, 0);
3755 pp_line(s1, file, level);
3758 if (s1->dflag) {
3759 pp_debug_defines(s1);
3760 if (s1->dflag & 4)
3761 continue;
3764 if (token_seen == TOK_LINEFEED) {
3765 if (tok == ' ') {
3766 ++spcs;
3767 continue;
3769 if (tok == TOK_LINEFEED) {
3770 spcs = 0;
3771 continue;
3773 pp_line(s1, file, 0);
3774 } else if (tok == TOK_LINEFEED) {
3775 ++file->line_ref;
3776 } else {
3777 spcs = pp_need_space(token_seen, tok);
3780 while (spcs)
3781 fputs(" ", s1->ppfp), --spcs;
3782 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
3783 token_seen = pp_check_he0xE(tok, p);;
3785 /* reset define stack, but keep -D and built-ins */
3786 free_defines(define_start);
3787 return 0;
3790 /* ------------------------------------------------------------------------- */