Fix initializing members multiple times
[tinycc.git] / tccpp.c
blob04d57222bea33c4742c456d85ad32abf5f4c994f
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 static TokenString *macro_stack;
58 static const char tcc_keywords[] =
59 #define DEF(id, str) str "\0"
60 #include "tcctok.h"
61 #undef DEF
64 /* WARNING: the content of this string encodes token numbers */
65 static const unsigned char tok_two_chars[] =
66 /* outdated -- gr
67 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
68 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
69 */{
70 '<','=', TOK_LE,
71 '>','=', TOK_GE,
72 '!','=', TOK_NE,
73 '&','&', TOK_LAND,
74 '|','|', TOK_LOR,
75 '+','+', TOK_INC,
76 '-','-', TOK_DEC,
77 '=','=', TOK_EQ,
78 '<','<', TOK_SHL,
79 '>','>', TOK_SAR,
80 '+','=', TOK_A_ADD,
81 '-','=', TOK_A_SUB,
82 '*','=', TOK_A_MUL,
83 '/','=', TOK_A_DIV,
84 '%','=', TOK_A_MOD,
85 '&','=', TOK_A_AND,
86 '^','=', TOK_A_XOR,
87 '|','=', TOK_A_OR,
88 '-','>', TOK_ARROW,
89 '.','.', 0xa8, // C++ token ?
90 '#','#', TOK_TWOSHARPS,
94 static void next_nomacro_spc(void);
96 ST_FUNC void skip(int c)
98 if (tok != c)
99 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
100 next();
103 ST_FUNC void expect(const char *msg)
105 tcc_error("%s expected", msg);
108 /* ------------------------------------------------------------------------- */
109 /* Custom allocator for tiny objects */
111 #define USE_TAL
113 #ifndef USE_TAL
114 #define tal_free(al, p) tcc_free(p)
115 #define tal_realloc(al, p, size) tcc_realloc(p, size)
116 #define tal_new(a,b,c)
117 #define tal_delete(a)
118 #else
119 #if !defined(MEM_DEBUG)
120 #define tal_free(al, p) tal_free_impl(al, p)
121 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
122 #define TAL_DEBUG_PARAMS
123 #else
124 #define TAL_DEBUG 1
125 //#define TAL_INFO 1 /* collect and dump allocators stats */
126 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
127 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
128 #define TAL_DEBUG_PARAMS , const char *file, int line
129 #define TAL_DEBUG_FILE_LEN 15
130 #endif
132 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
133 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
134 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
135 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
136 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
137 #define CSTR_TAL_LIMIT 1024
139 typedef struct TinyAlloc {
140 size_t limit;
141 size_t size;
142 uint8_t *buffer;
143 uint8_t *p;
144 size_t nb_allocs;
145 struct TinyAlloc *next, *top;
146 #ifdef TAL_INFO
147 size_t nb_peak;
148 size_t nb_total;
149 size_t nb_missed;
150 uint8_t *peak_p;
151 #endif
152 } TinyAlloc;
154 typedef struct tal_header_t {
155 size_t size;
156 #ifdef TAL_DEBUG
157 int line_num; /* negative line_num used for double free check */
158 char file_name[TAL_DEBUG_FILE_LEN + 1];
159 #endif
160 } tal_header_t;
162 /* ------------------------------------------------------------------------- */
164 ST_FUNC TinyAlloc *tal_new(TinyAlloc **pal, size_t limit, size_t size)
166 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
167 al->p = al->buffer = tcc_malloc(size);
168 al->limit = limit;
169 al->size = size;
170 if (pal) *pal = al;
171 return al;
174 ST_FUNC void tal_delete(TinyAlloc *al)
176 TinyAlloc *next;
178 tail_call:
179 if (!al)
180 return;
181 #ifdef TAL_INFO
182 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
183 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
184 (al->peak_p - al->buffer) * 100.0 / al->size);
185 #endif
186 #ifdef TAL_DEBUG
187 if (al->nb_allocs > 0) {
188 uint8_t *p;
189 fprintf(stderr, "TAL_DEBUG: mem leak %d chunks (limit= %d)\n",
190 al->nb_allocs, al->limit);
191 p = al->buffer;
192 while (p < al->p) {
193 tal_header_t *header = (tal_header_t *)p;
194 if (header->line_num > 0) {
195 fprintf(stderr, " file %s, line %u: %u bytes\n",
196 header->file_name, header->line_num, header->size);
198 p += header->size + sizeof(tal_header_t);
201 #endif
202 next = al->next;
203 tcc_free(al->buffer);
204 tcc_free(al);
205 al = next;
206 goto tail_call;
209 ST_FUNC void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
211 if (!p)
212 return;
213 tail_call:
214 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
215 #ifdef TAL_DEBUG
216 tal_header_t *header = (((tal_header_t *)p) - 1);
217 if (header->line_num < 0) {
218 fprintf(stderr, "TAL_DEBUG: file %s, line %u double frees chunk from\n",
219 file, line);
220 fprintf(stderr, " file %s, line %u: %u bytes\n",
221 header->file_name, -header->line_num, header->size);
222 } else
223 header->line_num = -header->line_num;
224 #endif
225 al->nb_allocs--;
226 if (!al->nb_allocs)
227 al->p = al->buffer;
228 } else if (al->next) {
229 al = al->next;
230 goto tail_call;
232 else
233 tcc_free(p);
236 ST_FUNC void *tal_realloc_impl(TinyAlloc **pal, void *p, size_t size TAL_DEBUG_PARAMS)
238 tal_header_t *header;
239 void *ret;
240 int is_own;
241 size_t adj_size = (size + 3) & -4;
242 TinyAlloc *al = *pal;
244 tail_call:
245 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
246 if ((!p || is_own) && size <= al->limit) {
247 if (al->p + adj_size + sizeof(tal_header_t) < al->buffer + al->size) {
248 header = (tal_header_t *)al->p;
249 header->size = adj_size;
250 #ifdef TAL_DEBUG
251 { int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
252 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
253 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
254 header->line_num = line; }
255 #endif
256 ret = al->p + sizeof(tal_header_t);
257 al->p += adj_size + sizeof(tal_header_t);
258 if (is_own) {
259 header = (((tal_header_t *)p) - 1);
260 memcpy(ret, p, header->size);
261 #ifdef TAL_DEBUG
262 header->line_num = -header->line_num;
263 #endif
264 } else {
265 al->nb_allocs++;
267 #ifdef TAL_INFO
268 if (al->nb_peak < al->nb_allocs)
269 al->nb_peak = al->nb_allocs;
270 if (al->peak_p < al->p)
271 al->peak_p = al->p;
272 al->nb_total++;
273 #endif
274 return ret;
275 } else if (is_own) {
276 al->nb_allocs--;
277 ret = tal_realloc(*pal, 0, size);
278 header = (((tal_header_t *)p) - 1);
279 memcpy(ret, p, header->size);
280 #ifdef TAL_DEBUG
281 header->line_num = -header->line_num;
282 #endif
283 return ret;
285 if (al->next) {
286 al = al->next;
287 } else {
288 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
290 al = tal_new(pal, next->limit, next->size * 2);
291 al->next = next;
292 bottom->top = al;
294 goto tail_call;
296 if (is_own) {
297 al->nb_allocs--;
298 ret = tcc_malloc(size);
299 header = (((tal_header_t *)p) - 1);
300 memcpy(ret, p, header->size);
301 #ifdef TAL_DEBUG
302 header->line_num = -header->line_num;
303 #endif
304 } else if (al->next) {
305 al = al->next;
306 goto tail_call;
307 } else
308 ret = tcc_realloc(p, size);
309 #ifdef TAL_INFO
310 al->nb_missed++;
311 #endif
312 return ret;
315 #endif /* USE_TAL */
317 /* ------------------------------------------------------------------------- */
318 /* CString handling */
319 static void cstr_realloc(CString *cstr, int new_size)
321 int size;
323 size = cstr->size_allocated;
324 if (size < 8)
325 size = 8; /* no need to allocate a too small first string */
326 while (size < new_size)
327 size = size * 2;
328 cstr->data = tal_realloc(cstr_alloc, cstr->data, size);
329 cstr->size_allocated = size;
332 /* add a byte */
333 ST_INLN void cstr_ccat(CString *cstr, int ch)
335 int size;
336 size = cstr->size + 1;
337 if (size > cstr->size_allocated)
338 cstr_realloc(cstr, size);
339 ((unsigned char *)cstr->data)[size - 1] = ch;
340 cstr->size = size;
343 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
345 int size;
346 if (len <= 0)
347 len = strlen(str) + 1 + len;
348 size = cstr->size + len;
349 if (size > cstr->size_allocated)
350 cstr_realloc(cstr, size);
351 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
352 cstr->size = size;
355 /* add a wide char */
356 ST_FUNC void cstr_wccat(CString *cstr, int ch)
358 int size;
359 size = cstr->size + sizeof(nwchar_t);
360 if (size > cstr->size_allocated)
361 cstr_realloc(cstr, size);
362 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
363 cstr->size = size;
366 ST_FUNC void cstr_new(CString *cstr)
368 memset(cstr, 0, sizeof(CString));
371 /* free string and reset it to NULL */
372 ST_FUNC void cstr_free(CString *cstr)
374 tal_free(cstr_alloc, cstr->data);
375 cstr_new(cstr);
378 /* reset string to empty */
379 ST_FUNC void cstr_reset(CString *cstr)
381 cstr->size = 0;
384 /* XXX: unicode ? */
385 static void add_char(CString *cstr, int c)
387 if (c == '\'' || c == '\"' || c == '\\') {
388 /* XXX: could be more precise if char or string */
389 cstr_ccat(cstr, '\\');
391 if (c >= 32 && c <= 126) {
392 cstr_ccat(cstr, c);
393 } else {
394 cstr_ccat(cstr, '\\');
395 if (c == '\n') {
396 cstr_ccat(cstr, 'n');
397 } else {
398 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
399 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
400 cstr_ccat(cstr, '0' + (c & 7));
405 /* ------------------------------------------------------------------------- */
406 /* allocate a new token */
407 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
409 TokenSym *ts, **ptable;
410 int i;
412 if (tok_ident >= SYM_FIRST_ANOM)
413 tcc_error("memory full (symbols)");
415 /* expand token table if needed */
416 i = tok_ident - TOK_IDENT;
417 if ((i % TOK_ALLOC_INCR) == 0) {
418 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
419 table_ident = ptable;
422 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
423 table_ident[i] = ts;
424 ts->tok = tok_ident++;
425 ts->sym_define = NULL;
426 ts->sym_label = NULL;
427 ts->sym_struct = NULL;
428 ts->sym_identifier = NULL;
429 ts->len = len;
430 ts->hash_next = NULL;
431 memcpy(ts->str, str, len);
432 ts->str[len] = '\0';
433 *pts = ts;
434 return ts;
437 #define TOK_HASH_INIT 1
438 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
441 /* find a token and add it if not found */
442 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
444 TokenSym *ts, **pts;
445 int i;
446 unsigned int h;
448 h = TOK_HASH_INIT;
449 for(i=0;i<len;i++)
450 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
451 h &= (TOK_HASH_SIZE - 1);
453 pts = &hash_ident[h];
454 for(;;) {
455 ts = *pts;
456 if (!ts)
457 break;
458 if (ts->len == len && !memcmp(ts->str, str, len))
459 return ts;
460 pts = &(ts->hash_next);
462 return tok_alloc_new(pts, str, len);
465 /* XXX: buffer overflow */
466 /* XXX: float tokens */
467 ST_FUNC const char *get_tok_str(int v, CValue *cv)
469 char *p;
470 int i, len;
472 cstr_reset(&cstr_buf);
473 p = cstr_buf.data;
475 switch(v) {
476 case TOK_CINT:
477 case TOK_CUINT:
478 case TOK_CLLONG:
479 case TOK_CULLONG:
480 /* XXX: not quite exact, but only useful for testing */
481 #ifdef _WIN32
482 sprintf(p, "%u", (unsigned)cv->i);
483 #else
484 sprintf(p, "%llu", (unsigned long long)cv->i);
485 #endif
486 break;
487 case TOK_LCHAR:
488 cstr_ccat(&cstr_buf, 'L');
489 case TOK_CCHAR:
490 cstr_ccat(&cstr_buf, '\'');
491 add_char(&cstr_buf, cv->i);
492 cstr_ccat(&cstr_buf, '\'');
493 cstr_ccat(&cstr_buf, '\0');
494 break;
495 case TOK_PPNUM:
496 case TOK_PPSTR:
497 return (char*)cv->str.data;
498 case TOK_LSTR:
499 cstr_ccat(&cstr_buf, 'L');
500 case TOK_STR:
501 cstr_ccat(&cstr_buf, '\"');
502 if (v == TOK_STR) {
503 len = cv->str.size - 1;
504 for(i=0;i<len;i++)
505 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
506 } else {
507 len = (cv->str.size / sizeof(nwchar_t)) - 1;
508 for(i=0;i<len;i++)
509 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
511 cstr_ccat(&cstr_buf, '\"');
512 cstr_ccat(&cstr_buf, '\0');
513 break;
515 case TOK_CFLOAT:
516 cstr_cat(&cstr_buf, "<float>", 0);
517 break;
518 case TOK_CDOUBLE:
519 cstr_cat(&cstr_buf, "<double>", 0);
520 break;
521 case TOK_CLDOUBLE:
522 cstr_cat(&cstr_buf, "<long double>", 0);
523 break;
524 case TOK_LINENUM:
525 cstr_cat(&cstr_buf, "<linenumber>", 0);
526 break;
528 /* above tokens have value, the ones below don't */
530 case TOK_LT:
531 v = '<';
532 goto addv;
533 case TOK_GT:
534 v = '>';
535 goto addv;
536 case TOK_DOTS:
537 return strcpy(p, "...");
538 case TOK_A_SHL:
539 return strcpy(p, "<<=");
540 case TOK_A_SAR:
541 return strcpy(p, ">>=");
542 default:
543 if (v < TOK_IDENT) {
544 /* search in two bytes table */
545 const unsigned char *q = tok_two_chars;
546 while (*q) {
547 if (q[2] == v) {
548 *p++ = q[0];
549 *p++ = q[1];
550 *p = '\0';
551 return cstr_buf.data;
553 q += 3;
555 if (v >= 127) {
556 sprintf(cstr_buf.data, "<%02x>", v);
557 return cstr_buf.data;
559 addv:
560 *p++ = v;
561 *p = '\0';
562 } else if (v < tok_ident) {
563 return table_ident[v - TOK_IDENT]->str;
564 } else if (v >= SYM_FIRST_ANOM) {
565 /* special name for anonymous symbol */
566 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
567 } else {
568 /* should never happen */
569 return NULL;
571 break;
573 return cstr_buf.data;
576 /* return the current character, handling end of block if necessary
577 (but not stray) */
578 ST_FUNC int handle_eob(void)
580 BufferedFile *bf = file;
581 int len;
583 /* only tries to read if really end of buffer */
584 if (bf->buf_ptr >= bf->buf_end) {
585 if (bf->fd != -1) {
586 #if defined(PARSE_DEBUG)
587 len = 1;
588 #else
589 len = IO_BUF_SIZE;
590 #endif
591 len = read(bf->fd, bf->buffer, len);
592 if (len < 0)
593 len = 0;
594 } else {
595 len = 0;
597 total_bytes += len;
598 bf->buf_ptr = bf->buffer;
599 bf->buf_end = bf->buffer + len;
600 *bf->buf_end = CH_EOB;
602 if (bf->buf_ptr < bf->buf_end) {
603 return bf->buf_ptr[0];
604 } else {
605 bf->buf_ptr = bf->buf_end;
606 return CH_EOF;
610 /* read next char from current input file and handle end of input buffer */
611 ST_INLN void inp(void)
613 ch = *(++(file->buf_ptr));
614 /* end of buffer/file handling */
615 if (ch == CH_EOB)
616 ch = handle_eob();
619 /* handle '\[\r]\n' */
620 static int handle_stray_noerror(void)
622 while (ch == '\\') {
623 inp();
624 if (ch == '\n') {
625 file->line_num++;
626 inp();
627 } else if (ch == '\r') {
628 inp();
629 if (ch != '\n')
630 goto fail;
631 file->line_num++;
632 inp();
633 } else {
634 fail:
635 return 1;
638 return 0;
641 static void handle_stray(void)
643 if (handle_stray_noerror())
644 tcc_error("stray '\\' in program");
647 /* skip the stray and handle the \\n case. Output an error if
648 incorrect char after the stray */
649 static int handle_stray1(uint8_t *p)
651 int c;
653 file->buf_ptr = p;
654 if (p >= file->buf_end) {
655 c = handle_eob();
656 if (c != '\\')
657 return c;
658 p = file->buf_ptr;
660 ch = *p;
661 if (handle_stray_noerror()) {
662 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
663 tcc_error("stray '\\' in program");
664 *--file->buf_ptr = '\\';
666 p = file->buf_ptr;
667 c = *p;
668 return c;
671 /* handle just the EOB case, but not stray */
672 #define PEEKC_EOB(c, p)\
674 p++;\
675 c = *p;\
676 if (c == '\\') {\
677 file->buf_ptr = p;\
678 c = handle_eob();\
679 p = file->buf_ptr;\
683 /* handle the complicated stray case */
684 #define PEEKC(c, p)\
686 p++;\
687 c = *p;\
688 if (c == '\\') {\
689 c = handle_stray1(p);\
690 p = file->buf_ptr;\
694 /* input with '\[\r]\n' handling. Note that this function cannot
695 handle other characters after '\', so you cannot call it inside
696 strings or comments */
697 ST_FUNC void minp(void)
699 inp();
700 if (ch == '\\')
701 handle_stray();
704 /* single line C++ comments */
705 static uint8_t *parse_line_comment(uint8_t *p)
707 int c;
709 p++;
710 for(;;) {
711 c = *p;
712 redo:
713 if (c == '\n' || c == CH_EOF) {
714 break;
715 } else if (c == '\\') {
716 file->buf_ptr = p;
717 c = handle_eob();
718 p = file->buf_ptr;
719 if (c == '\\') {
720 PEEKC_EOB(c, p);
721 if (c == '\n') {
722 file->line_num++;
723 PEEKC_EOB(c, p);
724 } else if (c == '\r') {
725 PEEKC_EOB(c, p);
726 if (c == '\n') {
727 file->line_num++;
728 PEEKC_EOB(c, p);
731 } else {
732 goto redo;
734 } else {
735 p++;
738 return p;
741 /* C comments */
742 ST_FUNC uint8_t *parse_comment(uint8_t *p)
744 int c;
746 p++;
747 for(;;) {
748 /* fast skip loop */
749 for(;;) {
750 c = *p;
751 if (c == '\n' || c == '*' || c == '\\')
752 break;
753 p++;
754 c = *p;
755 if (c == '\n' || c == '*' || c == '\\')
756 break;
757 p++;
759 /* now we can handle all the cases */
760 if (c == '\n') {
761 file->line_num++;
762 p++;
763 } else if (c == '*') {
764 p++;
765 for(;;) {
766 c = *p;
767 if (c == '*') {
768 p++;
769 } else if (c == '/') {
770 goto end_of_comment;
771 } else if (c == '\\') {
772 file->buf_ptr = p;
773 c = handle_eob();
774 p = file->buf_ptr;
775 if (c == CH_EOF)
776 tcc_error("unexpected end of file in comment");
777 if (c == '\\') {
778 /* skip '\[\r]\n', otherwise just skip the stray */
779 while (c == '\\') {
780 PEEKC_EOB(c, p);
781 if (c == '\n') {
782 file->line_num++;
783 PEEKC_EOB(c, p);
784 } else if (c == '\r') {
785 PEEKC_EOB(c, p);
786 if (c == '\n') {
787 file->line_num++;
788 PEEKC_EOB(c, p);
790 } else {
791 goto after_star;
795 } else {
796 break;
799 after_star: ;
800 } else {
801 /* stray, eob or eof */
802 file->buf_ptr = p;
803 c = handle_eob();
804 p = file->buf_ptr;
805 if (c == CH_EOF) {
806 tcc_error("unexpected end of file in comment");
807 } else if (c == '\\') {
808 p++;
812 end_of_comment:
813 p++;
814 return p;
817 ST_FUNC void set_idnum(int c, int val)
819 isidnum_table[c - CH_EOF] = val;
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 /* We have to parse the whole define as if not in asm mode, in particular
1457 no line comment with '#' must be ignored. Also for function
1458 macros the argument list must be parsed without '.' being an ID
1459 character. */
1460 parse_flags = ((parse_flags & ~PARSE_FLAG_ASM_FILE) | PARSE_FLAG_SPACES);
1461 /* '(' must be just after macro definition for MACRO_FUNC */
1462 next_nomacro_spc();
1463 if (tok == '(') {
1464 set_idnum('.', 0);
1465 next_nomacro();
1466 ps = &first;
1467 if (tok != ')') for (;;) {
1468 varg = tok;
1469 next_nomacro();
1470 is_vaargs = 0;
1471 if (varg == TOK_DOTS) {
1472 varg = TOK___VA_ARGS__;
1473 is_vaargs = 1;
1474 } else if (tok == TOK_DOTS && gnu_ext) {
1475 is_vaargs = 1;
1476 next_nomacro();
1478 if (varg < TOK_IDENT)
1479 bad_list:
1480 tcc_error("bad macro parameter list");
1481 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1482 *ps = s;
1483 ps = &s->next;
1484 if (tok == ')')
1485 break;
1486 if (tok != ',' || is_vaargs)
1487 goto bad_list;
1488 next_nomacro();
1490 next_nomacro_spc();
1491 t = MACRO_FUNC;
1494 tokstr_buf.len = 0;
1495 spc = 2;
1496 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1497 /* The body of a macro definition should be parsed such that identifiers
1498 are parsed like the file mode determines (i.e. with '.' being an
1499 ID character in asm mode). But '#' should be retained instead of
1500 regarded as line comment leader, so still don't set ASM_FILE
1501 in parse_flags. */
1502 set_idnum('.', (saved_parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0);
1503 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1504 /* remove spaces around ## and after '#' */
1505 if (TOK_TWOSHARPS == tok) {
1506 if (2 == spc)
1507 goto bad_twosharp;
1508 if (1 == spc)
1509 --tokstr_buf.len;
1510 spc = 3;
1511 } else if ('#' == tok) {
1512 spc = 4;
1513 } else if (check_space(tok, &spc)) {
1514 goto skip;
1516 tok_str_add2(&tokstr_buf, tok, &tokc);
1517 skip:
1518 next_nomacro_spc();
1521 parse_flags = saved_parse_flags;
1522 if (spc == 1)
1523 --tokstr_buf.len; /* remove trailing space */
1524 tok_str_add(&tokstr_buf, 0);
1525 if (3 == spc)
1526 bad_twosharp:
1527 tcc_error("'##' cannot appear at either end of macro");
1528 define_push(v, t, tok_str_dup(&tokstr_buf), first);
1531 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1533 const unsigned char *s;
1534 unsigned int h;
1535 CachedInclude *e;
1536 int i;
1538 h = TOK_HASH_INIT;
1539 s = (unsigned char *) filename;
1540 while (*s) {
1541 #ifdef _WIN32
1542 h = TOK_HASH_FUNC(h, toup(*s));
1543 #else
1544 h = TOK_HASH_FUNC(h, *s);
1545 #endif
1546 s++;
1548 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1550 i = s1->cached_includes_hash[h];
1551 for(;;) {
1552 if (i == 0)
1553 break;
1554 e = s1->cached_includes[i - 1];
1555 if (0 == PATHCMP(e->filename, filename))
1556 return e;
1557 i = e->hash_next;
1559 if (!add)
1560 return NULL;
1562 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1563 strcpy(e->filename, filename);
1564 e->ifndef_macro = e->once = 0;
1565 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1566 /* add in hash table */
1567 e->hash_next = s1->cached_includes_hash[h];
1568 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1569 #ifdef INC_DEBUG
1570 printf("adding cached '%s'\n", filename);
1571 #endif
1572 return e;
1575 static void pragma_parse(TCCState *s1)
1577 next_nomacro();
1578 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1579 int t = tok, v;
1580 Sym *s;
1582 if (next(), tok != '(')
1583 goto pragma_err;
1584 if (next(), tok != TOK_STR)
1585 goto pragma_err;
1586 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1587 if (next(), tok != ')')
1588 goto pragma_err;
1589 if (t == TOK_push_macro) {
1590 while (NULL == (s = define_find(v)))
1591 define_push(v, 0, NULL, NULL);
1592 s->type.ref = s; /* set push boundary */
1593 } else {
1594 for (s = define_stack; s; s = s->prev)
1595 if (s->v == v && s->type.ref == s) {
1596 s->type.ref = NULL;
1597 break;
1600 if (s)
1601 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1602 else
1603 tcc_warning("unbalanced #pragma pop_macro");
1604 pp_debug_tok = t, pp_debug_symv = v;
1606 } else if (tok == TOK_once) {
1607 search_cached_include(s1, file->filename, 1)->once = pp_once;
1609 } else if (s1->ppfp) {
1610 /* tcc -E: keep pragmas below unchanged */
1611 unget_tok(' ');
1612 unget_tok(TOK_PRAGMA);
1613 unget_tok('#');
1614 unget_tok(TOK_LINEFEED);
1616 } else if (tok == TOK_pack) {
1617 /* This may be:
1618 #pragma pack(1) // set
1619 #pragma pack() // reset to default
1620 #pragma pack(push,1) // push & set
1621 #pragma pack(pop) // restore previous */
1622 next();
1623 skip('(');
1624 if (tok == TOK_ASM_pop) {
1625 next();
1626 if (s1->pack_stack_ptr <= s1->pack_stack) {
1627 stk_error:
1628 tcc_error("out of pack stack");
1630 s1->pack_stack_ptr--;
1631 } else {
1632 int val = 0;
1633 if (tok != ')') {
1634 if (tok == TOK_ASM_push) {
1635 next();
1636 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1637 goto stk_error;
1638 s1->pack_stack_ptr++;
1639 skip(',');
1641 if (tok != TOK_CINT)
1642 goto pragma_err;
1643 val = tokc.i;
1644 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1645 goto pragma_err;
1646 next();
1648 *s1->pack_stack_ptr = val;
1650 if (tok != ')')
1651 goto pragma_err;
1653 } else if (tok == TOK_comment) {
1654 char *file;
1655 next();
1656 skip('(');
1657 if (tok != TOK_lib)
1658 goto pragma_warn;
1659 next();
1660 skip(',');
1661 if (tok != TOK_STR)
1662 goto pragma_err;
1663 file = tcc_strdup((char *)tokc.str.data);
1664 dynarray_add((void ***)&s1->pragma_libs, &s1->nb_pragma_libs, file);
1665 next();
1666 if (tok != ')')
1667 goto pragma_err;
1668 } else {
1669 pragma_warn:
1670 if (s1->warn_unsupported)
1671 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1673 return;
1675 pragma_err:
1676 tcc_error("malformed #pragma directive");
1677 return;
1680 /* is_bof is true if first non space token at beginning of file */
1681 ST_FUNC void preprocess(int is_bof)
1683 TCCState *s1 = tcc_state;
1684 int i, c, n, saved_parse_flags;
1685 char buf[1024], *q;
1686 Sym *s;
1688 saved_parse_flags = parse_flags;
1689 parse_flags = PARSE_FLAG_PREPROCESS
1690 | PARSE_FLAG_TOK_NUM
1691 | PARSE_FLAG_TOK_STR
1692 | PARSE_FLAG_LINEFEED
1693 | (parse_flags & PARSE_FLAG_ASM_FILE)
1696 next_nomacro();
1697 redo:
1698 switch(tok) {
1699 case TOK_DEFINE:
1700 pp_debug_tok = tok;
1701 next_nomacro();
1702 pp_debug_symv = tok;
1703 parse_define();
1704 break;
1705 case TOK_UNDEF:
1706 pp_debug_tok = tok;
1707 next_nomacro();
1708 pp_debug_symv = tok;
1709 s = define_find(tok);
1710 /* undefine symbol by putting an invalid name */
1711 if (s)
1712 define_undef(s);
1713 break;
1714 case TOK_INCLUDE:
1715 case TOK_INCLUDE_NEXT:
1716 ch = file->buf_ptr[0];
1717 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1718 skip_spaces();
1719 if (ch == '<') {
1720 c = '>';
1721 goto read_name;
1722 } else if (ch == '\"') {
1723 c = ch;
1724 read_name:
1725 inp();
1726 q = buf;
1727 while (ch != c && ch != '\n' && ch != CH_EOF) {
1728 if ((q - buf) < sizeof(buf) - 1)
1729 *q++ = ch;
1730 if (ch == '\\') {
1731 if (handle_stray_noerror() == 0)
1732 --q;
1733 } else
1734 inp();
1736 *q = '\0';
1737 minp();
1738 #if 0
1739 /* eat all spaces and comments after include */
1740 /* XXX: slightly incorrect */
1741 while (ch1 != '\n' && ch1 != CH_EOF)
1742 inp();
1743 #endif
1744 } else {
1745 int len;
1746 /* computed #include : concatenate everything up to linefeed,
1747 the result must be one of the two accepted forms.
1748 Don't convert pp-tokens to tokens here. */
1749 parse_flags = (PARSE_FLAG_PREPROCESS
1750 | PARSE_FLAG_LINEFEED
1751 | (parse_flags & PARSE_FLAG_ASM_FILE));
1752 next();
1753 buf[0] = '\0';
1754 while (tok != TOK_LINEFEED) {
1755 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1756 next();
1758 len = strlen(buf);
1759 /* check syntax and remove '<>|""' */
1760 if ((len < 2 || ((buf[0] != '"' || buf[len-1] != '"') &&
1761 (buf[0] != '<' || buf[len-1] != '>'))))
1762 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1763 c = buf[len-1];
1764 memmove(buf, buf + 1, len - 2);
1765 buf[len - 2] = '\0';
1768 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1769 tcc_error("#include recursion too deep");
1770 /* store current file in stack, but increment stack later below */
1771 *s1->include_stack_ptr = file;
1772 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index : 0;
1773 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1774 for (; i < n; ++i) {
1775 char buf1[sizeof file->filename];
1776 CachedInclude *e;
1777 const char *path;
1779 if (i == 0) {
1780 /* check absolute include path */
1781 if (!IS_ABSPATH(buf))
1782 continue;
1783 buf1[0] = 0;
1785 } else if (i == 1) {
1786 /* search in file's dir if "header.h" */
1787 if (c != '\"')
1788 continue;
1789 path = file->filename;
1790 pstrncpy(buf1, path, tcc_basename(path) - path);
1792 } else {
1793 /* search in all the include paths */
1794 int j = i - 2, k = j - s1->nb_include_paths;
1795 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1796 pstrcpy(buf1, sizeof(buf1), path);
1797 pstrcat(buf1, sizeof(buf1), "/");
1800 pstrcat(buf1, sizeof(buf1), buf);
1801 e = search_cached_include(s1, buf1, 0);
1802 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1803 /* no need to parse the include because the 'ifndef macro'
1804 is defined (or had #pragma once) */
1805 #ifdef INC_DEBUG
1806 printf("%s: skipping cached %s\n", file->filename, buf1);
1807 #endif
1808 goto include_done;
1811 if (tcc_open(s1, buf1) < 0)
1812 continue;
1814 file->include_next_index = i + 1;
1815 #ifdef INC_DEBUG
1816 printf("%s: including %s\n", file->prev->filename, file->filename);
1817 #endif
1818 /* update target deps */
1819 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1820 tcc_strdup(buf1));
1821 /* push current file in stack */
1822 ++s1->include_stack_ptr;
1823 /* add include file debug info */
1824 if (s1->do_debug)
1825 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1826 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1827 ch = file->buf_ptr[0];
1828 goto the_end;
1830 tcc_error("include file '%s' not found", buf);
1831 include_done:
1832 break;
1833 case TOK_IFNDEF:
1834 c = 1;
1835 goto do_ifdef;
1836 case TOK_IF:
1837 c = expr_preprocess();
1838 goto do_if;
1839 case TOK_IFDEF:
1840 c = 0;
1841 do_ifdef:
1842 next_nomacro();
1843 if (tok < TOK_IDENT)
1844 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1845 if (is_bof) {
1846 if (c) {
1847 #ifdef INC_DEBUG
1848 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1849 #endif
1850 file->ifndef_macro = tok;
1853 c = (define_find(tok) != 0) ^ c;
1854 do_if:
1855 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1856 tcc_error("memory full (ifdef)");
1857 *s1->ifdef_stack_ptr++ = c;
1858 goto test_skip;
1859 case TOK_ELSE:
1860 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1861 tcc_error("#else without matching #if");
1862 if (s1->ifdef_stack_ptr[-1] & 2)
1863 tcc_error("#else after #else");
1864 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1865 goto test_else;
1866 case TOK_ELIF:
1867 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1868 tcc_error("#elif without matching #if");
1869 c = s1->ifdef_stack_ptr[-1];
1870 if (c > 1)
1871 tcc_error("#elif after #else");
1872 /* last #if/#elif expression was true: we skip */
1873 if (c == 1) {
1874 c = 0;
1875 } else {
1876 c = expr_preprocess();
1877 s1->ifdef_stack_ptr[-1] = c;
1879 test_else:
1880 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1881 file->ifndef_macro = 0;
1882 test_skip:
1883 if (!(c & 1)) {
1884 preprocess_skip();
1885 is_bof = 0;
1886 goto redo;
1888 break;
1889 case TOK_ENDIF:
1890 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1891 tcc_error("#endif without matching #if");
1892 s1->ifdef_stack_ptr--;
1893 /* '#ifndef macro' was at the start of file. Now we check if
1894 an '#endif' is exactly at the end of file */
1895 if (file->ifndef_macro &&
1896 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1897 file->ifndef_macro_saved = file->ifndef_macro;
1898 /* need to set to zero to avoid false matches if another
1899 #ifndef at middle of file */
1900 file->ifndef_macro = 0;
1901 while (tok != TOK_LINEFEED)
1902 next_nomacro();
1903 tok_flags |= TOK_FLAG_ENDIF;
1904 goto the_end;
1906 break;
1907 case TOK_PPNUM:
1908 n = strtoul((char*)tokc.str.data, &q, 10);
1909 goto _line_num;
1910 case TOK_LINE:
1911 next();
1912 if (tok != TOK_CINT)
1913 _line_err:
1914 tcc_error("wrong #line format");
1915 n = tokc.i;
1916 _line_num:
1917 next();
1918 if (tok != TOK_LINEFEED) {
1919 if (tok == TOK_STR)
1920 pstrcpy(file->filename, sizeof(file->filename), (char *)tokc.str.data);
1921 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1922 break;
1923 else
1924 goto _line_err;
1925 --n;
1927 if (file->fd > 0)
1928 total_lines += file->line_num - n;
1929 file->line_num = n;
1930 if (s1->do_debug)
1931 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1932 break;
1933 case TOK_ERROR:
1934 case TOK_WARNING:
1935 c = tok;
1936 ch = file->buf_ptr[0];
1937 skip_spaces();
1938 q = buf;
1939 while (ch != '\n' && ch != CH_EOF) {
1940 if ((q - buf) < sizeof(buf) - 1)
1941 *q++ = ch;
1942 if (ch == '\\') {
1943 if (handle_stray_noerror() == 0)
1944 --q;
1945 } else
1946 inp();
1948 *q = '\0';
1949 if (c == TOK_ERROR)
1950 tcc_error("#error %s", buf);
1951 else
1952 tcc_warning("#warning %s", buf);
1953 break;
1954 case TOK_PRAGMA:
1955 pragma_parse(s1);
1956 break;
1957 case TOK_LINEFEED:
1958 goto the_end;
1959 default:
1960 /* ignore gas line comment in an 'S' file. */
1961 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1962 goto ignore;
1963 if (tok == '!' && is_bof)
1964 /* '!' is ignored at beginning to allow C scripts. */
1965 goto ignore;
1966 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1967 ignore:
1968 file->buf_ptr = parse_line_comment(file->buf_ptr - 1);
1969 goto the_end;
1971 /* ignore other preprocess commands or #! for C scripts */
1972 while (tok != TOK_LINEFEED)
1973 next_nomacro();
1974 the_end:
1975 parse_flags = saved_parse_flags;
1978 /* evaluate escape codes in a string. */
1979 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1981 int c, n;
1982 const uint8_t *p;
1984 p = buf;
1985 for(;;) {
1986 c = *p;
1987 if (c == '\0')
1988 break;
1989 if (c == '\\') {
1990 p++;
1991 /* escape */
1992 c = *p;
1993 switch(c) {
1994 case '0': case '1': case '2': case '3':
1995 case '4': case '5': case '6': case '7':
1996 /* at most three octal digits */
1997 n = c - '0';
1998 p++;
1999 c = *p;
2000 if (isoct(c)) {
2001 n = n * 8 + c - '0';
2002 p++;
2003 c = *p;
2004 if (isoct(c)) {
2005 n = n * 8 + c - '0';
2006 p++;
2009 c = n;
2010 goto add_char_nonext;
2011 case 'x':
2012 case 'u':
2013 case 'U':
2014 p++;
2015 n = 0;
2016 for(;;) {
2017 c = *p;
2018 if (c >= 'a' && c <= 'f')
2019 c = c - 'a' + 10;
2020 else if (c >= 'A' && c <= 'F')
2021 c = c - 'A' + 10;
2022 else if (isnum(c))
2023 c = c - '0';
2024 else
2025 break;
2026 n = n * 16 + c;
2027 p++;
2029 c = n;
2030 goto add_char_nonext;
2031 case 'a':
2032 c = '\a';
2033 break;
2034 case 'b':
2035 c = '\b';
2036 break;
2037 case 'f':
2038 c = '\f';
2039 break;
2040 case 'n':
2041 c = '\n';
2042 break;
2043 case 'r':
2044 c = '\r';
2045 break;
2046 case 't':
2047 c = '\t';
2048 break;
2049 case 'v':
2050 c = '\v';
2051 break;
2052 case 'e':
2053 if (!gnu_ext)
2054 goto invalid_escape;
2055 c = 27;
2056 break;
2057 case '\'':
2058 case '\"':
2059 case '\\':
2060 case '?':
2061 break;
2062 default:
2063 invalid_escape:
2064 if (c >= '!' && c <= '~')
2065 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2066 else
2067 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2068 break;
2071 p++;
2072 add_char_nonext:
2073 if (!is_long)
2074 cstr_ccat(outstr, c);
2075 else
2076 cstr_wccat(outstr, c);
2078 /* add a trailing '\0' */
2079 if (!is_long)
2080 cstr_ccat(outstr, '\0');
2081 else
2082 cstr_wccat(outstr, '\0');
2085 static void parse_string(const char *s, int len)
2087 uint8_t buf[1000], *p = buf;
2088 int is_long, sep;
2090 if ((is_long = *s == 'L'))
2091 ++s, --len;
2092 sep = *s++;
2093 len -= 2;
2094 if (len >= sizeof buf)
2095 p = tcc_malloc(len + 1);
2096 memcpy(p, s, len);
2097 p[len] = 0;
2099 cstr_reset(&tokcstr);
2100 parse_escape_string(&tokcstr, p, is_long);
2101 if (p != buf)
2102 tcc_free(p);
2104 if (sep == '\'') {
2105 int char_size;
2106 /* XXX: make it portable */
2107 if (!is_long)
2108 char_size = 1;
2109 else
2110 char_size = sizeof(nwchar_t);
2111 if (tokcstr.size <= char_size)
2112 tcc_error("empty character constant");
2113 if (tokcstr.size > 2 * char_size)
2114 tcc_warning("multi-character character constant");
2115 if (!is_long) {
2116 tokc.i = *(int8_t *)tokcstr.data;
2117 tok = TOK_CCHAR;
2118 } else {
2119 tokc.i = *(nwchar_t *)tokcstr.data;
2120 tok = TOK_LCHAR;
2122 } else {
2123 tokc.str.size = tokcstr.size;
2124 tokc.str.data = tokcstr.data;
2125 if (!is_long)
2126 tok = TOK_STR;
2127 else
2128 tok = TOK_LSTR;
2132 /* we use 64 bit numbers */
2133 #define BN_SIZE 2
2135 /* bn = (bn << shift) | or_val */
2136 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2138 int i;
2139 unsigned int v;
2140 for(i=0;i<BN_SIZE;i++) {
2141 v = bn[i];
2142 bn[i] = (v << shift) | or_val;
2143 or_val = v >> (32 - shift);
2147 static void bn_zero(unsigned int *bn)
2149 int i;
2150 for(i=0;i<BN_SIZE;i++) {
2151 bn[i] = 0;
2155 /* parse number in null terminated string 'p' and return it in the
2156 current token */
2157 static void parse_number(const char *p)
2159 int b, t, shift, frac_bits, s, exp_val, ch;
2160 char *q;
2161 unsigned int bn[BN_SIZE];
2162 double d;
2164 /* number */
2165 q = token_buf;
2166 ch = *p++;
2167 t = ch;
2168 ch = *p++;
2169 *q++ = t;
2170 b = 10;
2171 if (t == '.') {
2172 goto float_frac_parse;
2173 } else if (t == '0') {
2174 if (ch == 'x' || ch == 'X') {
2175 q--;
2176 ch = *p++;
2177 b = 16;
2178 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
2179 q--;
2180 ch = *p++;
2181 b = 2;
2184 /* parse all digits. cannot check octal numbers at this stage
2185 because of floating point constants */
2186 while (1) {
2187 if (ch >= 'a' && ch <= 'f')
2188 t = ch - 'a' + 10;
2189 else if (ch >= 'A' && ch <= 'F')
2190 t = ch - 'A' + 10;
2191 else if (isnum(ch))
2192 t = ch - '0';
2193 else
2194 break;
2195 if (t >= b)
2196 break;
2197 if (q >= token_buf + STRING_MAX_SIZE) {
2198 num_too_long:
2199 tcc_error("number too long");
2201 *q++ = ch;
2202 ch = *p++;
2204 if (ch == '.' ||
2205 ((ch == 'e' || ch == 'E') && b == 10) ||
2206 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2207 if (b != 10) {
2208 /* NOTE: strtox should support that for hexa numbers, but
2209 non ISOC99 libcs do not support it, so we prefer to do
2210 it by hand */
2211 /* hexadecimal or binary floats */
2212 /* XXX: handle overflows */
2213 *q = '\0';
2214 if (b == 16)
2215 shift = 4;
2216 else
2217 shift = 1;
2218 bn_zero(bn);
2219 q = token_buf;
2220 while (1) {
2221 t = *q++;
2222 if (t == '\0') {
2223 break;
2224 } else if (t >= 'a') {
2225 t = t - 'a' + 10;
2226 } else if (t >= 'A') {
2227 t = t - 'A' + 10;
2228 } else {
2229 t = t - '0';
2231 bn_lshift(bn, shift, t);
2233 frac_bits = 0;
2234 if (ch == '.') {
2235 ch = *p++;
2236 while (1) {
2237 t = ch;
2238 if (t >= 'a' && t <= 'f') {
2239 t = t - 'a' + 10;
2240 } else if (t >= 'A' && t <= 'F') {
2241 t = t - 'A' + 10;
2242 } else if (t >= '0' && t <= '9') {
2243 t = t - '0';
2244 } else {
2245 break;
2247 if (t >= b)
2248 tcc_error("invalid digit");
2249 bn_lshift(bn, shift, t);
2250 frac_bits += shift;
2251 ch = *p++;
2254 if (ch != 'p' && ch != 'P')
2255 expect("exponent");
2256 ch = *p++;
2257 s = 1;
2258 exp_val = 0;
2259 if (ch == '+') {
2260 ch = *p++;
2261 } else if (ch == '-') {
2262 s = -1;
2263 ch = *p++;
2265 if (ch < '0' || ch > '9')
2266 expect("exponent digits");
2267 while (ch >= '0' && ch <= '9') {
2268 exp_val = exp_val * 10 + ch - '0';
2269 ch = *p++;
2271 exp_val = exp_val * s;
2273 /* now we can generate the number */
2274 /* XXX: should patch directly float number */
2275 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2276 d = ldexp(d, exp_val - frac_bits);
2277 t = toup(ch);
2278 if (t == 'F') {
2279 ch = *p++;
2280 tok = TOK_CFLOAT;
2281 /* float : should handle overflow */
2282 tokc.f = (float)d;
2283 } else if (t == 'L') {
2284 ch = *p++;
2285 #ifdef TCC_TARGET_PE
2286 tok = TOK_CDOUBLE;
2287 tokc.d = d;
2288 #else
2289 tok = TOK_CLDOUBLE;
2290 /* XXX: not large enough */
2291 tokc.ld = (long double)d;
2292 #endif
2293 } else {
2294 tok = TOK_CDOUBLE;
2295 tokc.d = d;
2297 } else {
2298 /* decimal floats */
2299 if (ch == '.') {
2300 if (q >= token_buf + STRING_MAX_SIZE)
2301 goto num_too_long;
2302 *q++ = ch;
2303 ch = *p++;
2304 float_frac_parse:
2305 while (ch >= '0' && ch <= '9') {
2306 if (q >= token_buf + STRING_MAX_SIZE)
2307 goto num_too_long;
2308 *q++ = ch;
2309 ch = *p++;
2312 if (ch == 'e' || ch == 'E') {
2313 if (q >= token_buf + STRING_MAX_SIZE)
2314 goto num_too_long;
2315 *q++ = ch;
2316 ch = *p++;
2317 if (ch == '-' || ch == '+') {
2318 if (q >= token_buf + STRING_MAX_SIZE)
2319 goto num_too_long;
2320 *q++ = ch;
2321 ch = *p++;
2323 if (ch < '0' || ch > '9')
2324 expect("exponent digits");
2325 while (ch >= '0' && ch <= '9') {
2326 if (q >= token_buf + STRING_MAX_SIZE)
2327 goto num_too_long;
2328 *q++ = ch;
2329 ch = *p++;
2332 *q = '\0';
2333 t = toup(ch);
2334 errno = 0;
2335 if (t == 'F') {
2336 ch = *p++;
2337 tok = TOK_CFLOAT;
2338 tokc.f = strtof(token_buf, NULL);
2339 } else if (t == 'L') {
2340 ch = *p++;
2341 #ifdef TCC_TARGET_PE
2342 tok = TOK_CDOUBLE;
2343 tokc.d = strtod(token_buf, NULL);
2344 #else
2345 tok = TOK_CLDOUBLE;
2346 tokc.ld = strtold(token_buf, NULL);
2347 #endif
2348 } else {
2349 tok = TOK_CDOUBLE;
2350 tokc.d = strtod(token_buf, NULL);
2353 } else {
2354 unsigned long long n, n1;
2355 int lcount, ucount, must_64bit;
2356 const char *p1;
2358 /* integer number */
2359 *q = '\0';
2360 q = token_buf;
2361 if (b == 10 && *q == '0') {
2362 b = 8;
2363 q++;
2365 n = 0;
2366 while(1) {
2367 t = *q++;
2368 /* no need for checks except for base 10 / 8 errors */
2369 if (t == '\0')
2370 break;
2371 else if (t >= 'a')
2372 t = t - 'a' + 10;
2373 else if (t >= 'A')
2374 t = t - 'A' + 10;
2375 else
2376 t = t - '0';
2377 if (t >= b)
2378 tcc_error("invalid digit");
2379 n1 = n;
2380 n = n * b + t;
2381 /* detect overflow */
2382 /* XXX: this test is not reliable */
2383 if (n < n1)
2384 tcc_error("integer constant overflow");
2387 /* Determine the characteristics (unsigned and/or 64bit) the type of
2388 the constant must have according to the constant suffix(es) */
2389 lcount = ucount = must_64bit = 0;
2390 p1 = p;
2391 for(;;) {
2392 t = toup(ch);
2393 if (t == 'L') {
2394 if (lcount >= 2)
2395 tcc_error("three 'l's in integer constant");
2396 if (lcount && *(p - 1) != ch)
2397 tcc_error("incorrect integer suffix: %s", p1);
2398 lcount++;
2399 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2400 if (lcount == 2)
2401 #endif
2402 must_64bit = 1;
2403 ch = *p++;
2404 } else if (t == 'U') {
2405 if (ucount >= 1)
2406 tcc_error("two 'u's in integer constant");
2407 ucount++;
2408 ch = *p++;
2409 } else {
2410 break;
2414 /* Whether 64 bits are needed to hold the constant's value */
2415 if (n & 0xffffffff00000000LL || must_64bit) {
2416 tok = TOK_CLLONG;
2417 n1 = n >> 32;
2418 } else {
2419 tok = TOK_CINT;
2420 n1 = n;
2423 /* Whether type must be unsigned to hold the constant's value */
2424 if (ucount || ((n1 >> 31) && (b != 10))) {
2425 if (tok == TOK_CLLONG)
2426 tok = TOK_CULLONG;
2427 else
2428 tok = TOK_CUINT;
2429 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2430 } else if (n1 >> 31) {
2431 if (tok == TOK_CINT)
2432 tok = TOK_CLLONG;
2433 else
2434 tcc_error("integer constant overflow");
2437 tokc.i = n;
2439 if (ch)
2440 tcc_error("invalid number\n");
2444 #define PARSE2(c1, tok1, c2, tok2) \
2445 case c1: \
2446 PEEKC(c, p); \
2447 if (c == c2) { \
2448 p++; \
2449 tok = tok2; \
2450 } else { \
2451 tok = tok1; \
2453 break;
2455 /* return next token without macro substitution */
2456 static inline void next_nomacro1(void)
2458 int t, c, is_long, len;
2459 TokenSym *ts;
2460 uint8_t *p, *p1;
2461 unsigned int h;
2463 p = file->buf_ptr;
2464 redo_no_start:
2465 c = *p;
2466 switch(c) {
2467 case ' ':
2468 case '\t':
2469 tok = c;
2470 p++;
2471 if (parse_flags & PARSE_FLAG_SPACES)
2472 goto keep_tok_flags;
2473 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2474 ++p;
2475 goto redo_no_start;
2476 case '\f':
2477 case '\v':
2478 case '\r':
2479 p++;
2480 goto redo_no_start;
2481 case '\\':
2482 /* first look if it is in fact an end of buffer */
2483 c = handle_stray1(p);
2484 p = file->buf_ptr;
2485 if (c == '\\')
2486 goto parse_simple;
2487 if (c != CH_EOF)
2488 goto redo_no_start;
2490 TCCState *s1 = tcc_state;
2491 if ((parse_flags & PARSE_FLAG_LINEFEED)
2492 && !(tok_flags & TOK_FLAG_EOF)) {
2493 tok_flags |= TOK_FLAG_EOF;
2494 tok = TOK_LINEFEED;
2495 goto keep_tok_flags;
2496 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2497 tok = TOK_EOF;
2498 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2499 tcc_error("missing #endif");
2500 } else if (s1->include_stack_ptr == s1->include_stack) {
2501 /* no include left : end of file. */
2502 tok = TOK_EOF;
2503 } else {
2504 tok_flags &= ~TOK_FLAG_EOF;
2505 /* pop include file */
2507 /* test if previous '#endif' was after a #ifdef at
2508 start of file */
2509 if (tok_flags & TOK_FLAG_ENDIF) {
2510 #ifdef INC_DEBUG
2511 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2512 #endif
2513 search_cached_include(s1, file->filename, 1)
2514 ->ifndef_macro = file->ifndef_macro_saved;
2515 tok_flags &= ~TOK_FLAG_ENDIF;
2518 /* add end of include file debug info */
2519 if (tcc_state->do_debug) {
2520 put_stabd(N_EINCL, 0, 0);
2522 /* pop include stack */
2523 tcc_close();
2524 s1->include_stack_ptr--;
2525 p = file->buf_ptr;
2526 goto redo_no_start;
2529 break;
2531 case '\n':
2532 file->line_num++;
2533 tok_flags |= TOK_FLAG_BOL;
2534 p++;
2535 maybe_newline:
2536 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2537 goto redo_no_start;
2538 tok = TOK_LINEFEED;
2539 goto keep_tok_flags;
2541 case '#':
2542 /* XXX: simplify */
2543 PEEKC(c, p);
2544 if ((tok_flags & TOK_FLAG_BOL) &&
2545 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2546 file->buf_ptr = p;
2547 preprocess(tok_flags & TOK_FLAG_BOF);
2548 p = file->buf_ptr;
2549 goto maybe_newline;
2550 } else {
2551 if (c == '#') {
2552 p++;
2553 tok = TOK_TWOSHARPS;
2554 } else {
2555 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2556 p = parse_line_comment(p - 1);
2557 goto redo_no_start;
2558 } else {
2559 tok = '#';
2563 break;
2565 /* dollar is allowed to start identifiers when not parsing asm */
2566 case '$':
2567 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2568 || (parse_flags & PARSE_FLAG_ASM_FILE))
2569 goto parse_simple;
2571 case 'a': case 'b': case 'c': case 'd':
2572 case 'e': case 'f': case 'g': case 'h':
2573 case 'i': case 'j': case 'k': case 'l':
2574 case 'm': case 'n': case 'o': case 'p':
2575 case 'q': case 'r': case 's': case 't':
2576 case 'u': case 'v': case 'w': case 'x':
2577 case 'y': case 'z':
2578 case 'A': case 'B': case 'C': case 'D':
2579 case 'E': case 'F': case 'G': case 'H':
2580 case 'I': case 'J': case 'K':
2581 case 'M': case 'N': case 'O': case 'P':
2582 case 'Q': case 'R': case 'S': case 'T':
2583 case 'U': case 'V': case 'W': case 'X':
2584 case 'Y': case 'Z':
2585 case '_':
2586 parse_ident_fast:
2587 p1 = p;
2588 h = TOK_HASH_INIT;
2589 h = TOK_HASH_FUNC(h, c);
2590 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2591 h = TOK_HASH_FUNC(h, c);
2592 len = p - p1;
2593 if (c != '\\') {
2594 TokenSym **pts;
2596 /* fast case : no stray found, so we have the full token
2597 and we have already hashed it */
2598 h &= (TOK_HASH_SIZE - 1);
2599 pts = &hash_ident[h];
2600 for(;;) {
2601 ts = *pts;
2602 if (!ts)
2603 break;
2604 if (ts->len == len && !memcmp(ts->str, p1, len))
2605 goto token_found;
2606 pts = &(ts->hash_next);
2608 ts = tok_alloc_new(pts, (char *) p1, len);
2609 token_found: ;
2610 } else {
2611 /* slower case */
2612 cstr_reset(&tokcstr);
2613 cstr_cat(&tokcstr, p1, len);
2614 p--;
2615 PEEKC(c, p);
2616 parse_ident_slow:
2617 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2619 cstr_ccat(&tokcstr, c);
2620 PEEKC(c, p);
2622 ts = tok_alloc(tokcstr.data, tokcstr.size);
2624 tok = ts->tok;
2625 break;
2626 case 'L':
2627 t = p[1];
2628 if (t != '\\' && t != '\'' && t != '\"') {
2629 /* fast case */
2630 goto parse_ident_fast;
2631 } else {
2632 PEEKC(c, p);
2633 if (c == '\'' || c == '\"') {
2634 is_long = 1;
2635 goto str_const;
2636 } else {
2637 cstr_reset(&tokcstr);
2638 cstr_ccat(&tokcstr, 'L');
2639 goto parse_ident_slow;
2642 break;
2644 case '0': case '1': case '2': case '3':
2645 case '4': case '5': case '6': case '7':
2646 case '8': case '9':
2647 t = c;
2648 PEEKC(c, p);
2649 /* after the first digit, accept digits, alpha, '.' or sign if
2650 prefixed by 'eEpP' */
2651 parse_num:
2652 cstr_reset(&tokcstr);
2653 for(;;) {
2654 cstr_ccat(&tokcstr, t);
2655 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2656 || c == '.'
2657 || ((c == '+' || c == '-')
2658 && (((t == 'e' || t == 'E')
2659 && !(parse_flags & PARSE_FLAG_ASM_FILE
2660 /* 0xe+1 is 3 tokens in asm */
2661 && ((char*)tokcstr.data)[0] == '0'
2662 && toup(((char*)tokcstr.data)[1]) == 'X'))
2663 || t == 'p' || t == 'P'))))
2664 break;
2665 t = c;
2666 PEEKC(c, p);
2668 /* We add a trailing '\0' to ease parsing */
2669 cstr_ccat(&tokcstr, '\0');
2670 tokc.str.size = tokcstr.size;
2671 tokc.str.data = tokcstr.data;
2672 tok = TOK_PPNUM;
2673 break;
2675 case '.':
2676 /* special dot handling because it can also start a number */
2677 PEEKC(c, p);
2678 if (isnum(c)) {
2679 t = '.';
2680 goto parse_num;
2681 } else if ((isidnum_table['.' - CH_EOF] & IS_ID)
2682 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2683 *--p = c = '.';
2684 goto parse_ident_fast;
2685 } else if (c == '.') {
2686 PEEKC(c, p);
2687 if (c == '.') {
2688 p++;
2689 tok = TOK_DOTS;
2690 } else {
2691 *--p = '.'; /* may underflow into file->unget[] */
2692 tok = '.';
2694 } else {
2695 tok = '.';
2697 break;
2698 case '\'':
2699 case '\"':
2700 is_long = 0;
2701 str_const:
2702 cstr_reset(&tokcstr);
2703 if (is_long)
2704 cstr_ccat(&tokcstr, 'L');
2705 cstr_ccat(&tokcstr, c);
2706 p = parse_pp_string(p, c, &tokcstr);
2707 cstr_ccat(&tokcstr, c);
2708 cstr_ccat(&tokcstr, '\0');
2709 tokc.str.size = tokcstr.size;
2710 tokc.str.data = tokcstr.data;
2711 tok = TOK_PPSTR;
2712 break;
2714 case '<':
2715 PEEKC(c, p);
2716 if (c == '=') {
2717 p++;
2718 tok = TOK_LE;
2719 } else if (c == '<') {
2720 PEEKC(c, p);
2721 if (c == '=') {
2722 p++;
2723 tok = TOK_A_SHL;
2724 } else {
2725 tok = TOK_SHL;
2727 } else {
2728 tok = TOK_LT;
2730 break;
2731 case '>':
2732 PEEKC(c, p);
2733 if (c == '=') {
2734 p++;
2735 tok = TOK_GE;
2736 } else if (c == '>') {
2737 PEEKC(c, p);
2738 if (c == '=') {
2739 p++;
2740 tok = TOK_A_SAR;
2741 } else {
2742 tok = TOK_SAR;
2744 } else {
2745 tok = TOK_GT;
2747 break;
2749 case '&':
2750 PEEKC(c, p);
2751 if (c == '&') {
2752 p++;
2753 tok = TOK_LAND;
2754 } else if (c == '=') {
2755 p++;
2756 tok = TOK_A_AND;
2757 } else {
2758 tok = '&';
2760 break;
2762 case '|':
2763 PEEKC(c, p);
2764 if (c == '|') {
2765 p++;
2766 tok = TOK_LOR;
2767 } else if (c == '=') {
2768 p++;
2769 tok = TOK_A_OR;
2770 } else {
2771 tok = '|';
2773 break;
2775 case '+':
2776 PEEKC(c, p);
2777 if (c == '+') {
2778 p++;
2779 tok = TOK_INC;
2780 } else if (c == '=') {
2781 p++;
2782 tok = TOK_A_ADD;
2783 } else {
2784 tok = '+';
2786 break;
2788 case '-':
2789 PEEKC(c, p);
2790 if (c == '-') {
2791 p++;
2792 tok = TOK_DEC;
2793 } else if (c == '=') {
2794 p++;
2795 tok = TOK_A_SUB;
2796 } else if (c == '>') {
2797 p++;
2798 tok = TOK_ARROW;
2799 } else {
2800 tok = '-';
2802 break;
2804 PARSE2('!', '!', '=', TOK_NE)
2805 PARSE2('=', '=', '=', TOK_EQ)
2806 PARSE2('*', '*', '=', TOK_A_MUL)
2807 PARSE2('%', '%', '=', TOK_A_MOD)
2808 PARSE2('^', '^', '=', TOK_A_XOR)
2810 /* comments or operator */
2811 case '/':
2812 PEEKC(c, p);
2813 if (c == '*') {
2814 p = parse_comment(p);
2815 /* comments replaced by a blank */
2816 tok = ' ';
2817 goto keep_tok_flags;
2818 } else if (c == '/') {
2819 p = parse_line_comment(p);
2820 tok = ' ';
2821 goto keep_tok_flags;
2822 } else if (c == '=') {
2823 p++;
2824 tok = TOK_A_DIV;
2825 } else {
2826 tok = '/';
2828 break;
2830 /* simple tokens */
2831 case '(':
2832 case ')':
2833 case '[':
2834 case ']':
2835 case '{':
2836 case '}':
2837 case ',':
2838 case ';':
2839 case ':':
2840 case '?':
2841 case '~':
2842 case '@': /* only used in assembler */
2843 parse_simple:
2844 tok = c;
2845 p++;
2846 break;
2847 default:
2848 if (c >= 0x80 && c <= 0xFF) /* utf8 identifiers */
2849 goto parse_ident_fast;
2850 if (parse_flags & PARSE_FLAG_ASM_FILE)
2851 goto parse_simple;
2852 tcc_error("unrecognized character \\x%02x", c);
2853 break;
2855 tok_flags = 0;
2856 keep_tok_flags:
2857 file->buf_ptr = p;
2858 #if defined(PARSE_DEBUG)
2859 printf("token = %s\n", get_tok_str(tok, &tokc));
2860 #endif
2863 /* return next token without macro substitution. Can read input from
2864 macro_ptr buffer */
2865 static void next_nomacro_spc(void)
2867 if (macro_ptr) {
2868 redo:
2869 tok = *macro_ptr;
2870 if (tok) {
2871 TOK_GET(&tok, &macro_ptr, &tokc);
2872 if (tok == TOK_LINENUM) {
2873 file->line_num = tokc.i;
2874 goto redo;
2877 } else {
2878 next_nomacro1();
2882 ST_FUNC void next_nomacro(void)
2884 do {
2885 next_nomacro_spc();
2886 } while (tok < 256 && (isidnum_table[tok - CH_EOF] & IS_SPC));
2890 static void macro_subst(
2891 TokenString *tok_str,
2892 Sym **nested_list,
2893 const int *macro_str,
2894 int can_read_stream
2897 /* substitute arguments in replacement lists in macro_str by the values in
2898 args (field d) and return allocated string */
2899 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2901 int t, t0, t1, spc;
2902 const int *st;
2903 Sym *s;
2904 CValue cval;
2905 TokenString str;
2906 CString cstr;
2908 tok_str_new(&str);
2909 t0 = t1 = 0;
2910 while(1) {
2911 TOK_GET(&t, &macro_str, &cval);
2912 if (!t)
2913 break;
2914 if (t == '#') {
2915 /* stringize */
2916 TOK_GET(&t, &macro_str, &cval);
2917 if (!t)
2918 goto bad_stringy;
2919 s = sym_find2(args, t);
2920 if (s) {
2921 cstr_new(&cstr);
2922 cstr_ccat(&cstr, '\"');
2923 st = s->d;
2924 spc = 0;
2925 while (*st) {
2926 TOK_GET(&t, &st, &cval);
2927 if (t != TOK_PLCHLDR
2928 && t != TOK_NOSUBST
2929 && 0 == check_space(t, &spc)) {
2930 const char *s = get_tok_str(t, &cval);
2931 while (*s) {
2932 if (t == TOK_PPSTR && *s != '\'')
2933 add_char(&cstr, *s);
2934 else
2935 cstr_ccat(&cstr, *s);
2936 ++s;
2940 cstr.size -= spc;
2941 cstr_ccat(&cstr, '\"');
2942 cstr_ccat(&cstr, '\0');
2943 #ifdef PP_DEBUG
2944 printf("\nstringize: <%s>\n", (char *)cstr.data);
2945 #endif
2946 /* add string */
2947 cval.str.size = cstr.size;
2948 cval.str.data = cstr.data;
2949 tok_str_add2(&str, TOK_PPSTR, &cval);
2950 cstr_free(&cstr);
2951 } else {
2952 bad_stringy:
2953 expect("macro parameter after '#'");
2955 } else if (t >= TOK_IDENT) {
2956 s = sym_find2(args, t);
2957 if (s) {
2958 int l0 = str.len;
2959 st = s->d;
2960 /* if '##' is present before or after, no arg substitution */
2961 if (*macro_str == TOK_TWOSHARPS || t1 == TOK_TWOSHARPS) {
2962 /* special case for var arg macros : ## eats the ','
2963 if empty VA_ARGS variable. */
2964 if (t1 == TOK_TWOSHARPS && t0 == ',' && gnu_ext && s->type.t) {
2965 if (*st == 0) {
2966 /* suppress ',' '##' */
2967 str.len -= 2;
2968 } else {
2969 /* suppress '##' and add variable */
2970 str.len--;
2971 goto add_var;
2973 } else {
2974 for(;;) {
2975 int t1;
2976 TOK_GET(&t1, &st, &cval);
2977 if (!t1)
2978 break;
2979 tok_str_add2(&str, t1, &cval);
2983 } else {
2984 add_var:
2985 /* NOTE: the stream cannot be read when macro
2986 substituing an argument */
2987 macro_subst(&str, nested_list, st, 0);
2989 if (str.len == l0) /* exanded to empty string */
2990 tok_str_add(&str, TOK_PLCHLDR);
2991 } else {
2992 tok_str_add(&str, t);
2994 } else {
2995 tok_str_add2(&str, t, &cval);
2997 t0 = t1, t1 = t;
2999 tok_str_add(&str, 0);
3000 return str.str;
3003 static char const ab_month_name[12][4] =
3005 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3006 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3009 /* peek or read [ws_str == NULL] next token from function macro call,
3010 walking up macro levels up to the file if necessary */
3011 static int next_argstream(Sym **nested_list, int can_read_stream, TokenString *ws_str)
3013 int t;
3014 const int *p;
3015 Sym *sa;
3017 for (;;) {
3018 if (macro_ptr) {
3019 p = macro_ptr, t = *p;
3020 if (ws_str) {
3021 while (is_space(t) || TOK_LINEFEED == t)
3022 tok_str_add(ws_str, t), t = *++p;
3024 if (t == 0 && can_read_stream) {
3025 end_macro();
3026 /* also, end of scope for nested defined symbol */
3027 sa = *nested_list;
3028 while (sa && sa->v == 0)
3029 sa = sa->prev;
3030 if (sa)
3031 sa->v = 0;
3032 continue;
3034 } else {
3035 ch = handle_eob();
3036 if (ws_str) {
3037 while (is_space(ch) || ch == '\n' || ch == '/') {
3038 if (ch == '/') {
3039 int c;
3040 uint8_t *p = file->buf_ptr;
3041 PEEKC(c, p);
3042 if (c == '*') {
3043 p = parse_comment(p);
3044 file->buf_ptr = p - 1;
3045 } else if (c == '/') {
3046 p = parse_line_comment(p);
3047 file->buf_ptr = p - 1;
3048 } else
3049 break;
3050 ch = ' ';
3052 if (!(ch == '\f' || ch == '\v' || ch == '\r'))
3053 tok_str_add(ws_str, ch);
3054 cinp();
3057 t = ch;
3060 if (ws_str)
3061 return t;
3062 next_nomacro_spc();
3063 return tok;
3067 /* do macro substitution of current token with macro 's' and add
3068 result to (tok_str,tok_len). 'nested_list' is the list of all
3069 macros we got inside to avoid recursing. Return non zero if no
3070 substitution needs to be done */
3071 static int macro_subst_tok(
3072 TokenString *tok_str,
3073 Sym **nested_list,
3074 Sym *s,
3075 int can_read_stream)
3077 Sym *args, *sa, *sa1;
3078 int parlevel, *mstr, t, t1, spc;
3079 TokenString str;
3080 char *cstrval;
3081 CValue cval;
3082 CString cstr;
3083 char buf[32];
3085 /* if symbol is a macro, prepare substitution */
3086 /* special macros */
3087 if (tok == TOK___LINE__) {
3088 snprintf(buf, sizeof(buf), "%d", file->line_num);
3089 cstrval = buf;
3090 t1 = TOK_PPNUM;
3091 goto add_cstr1;
3092 } else if (tok == TOK___FILE__) {
3093 cstrval = file->filename;
3094 goto add_cstr;
3095 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3096 time_t ti;
3097 struct tm *tm;
3099 time(&ti);
3100 tm = localtime(&ti);
3101 if (tok == TOK___DATE__) {
3102 snprintf(buf, sizeof(buf), "%s %2d %d",
3103 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3104 } else {
3105 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3106 tm->tm_hour, tm->tm_min, tm->tm_sec);
3108 cstrval = buf;
3109 add_cstr:
3110 t1 = TOK_STR;
3111 add_cstr1:
3112 cstr_new(&cstr);
3113 cstr_cat(&cstr, cstrval, 0);
3114 cval.str.size = cstr.size;
3115 cval.str.data = cstr.data;
3116 tok_str_add2(tok_str, t1, &cval);
3117 cstr_free(&cstr);
3118 } else {
3119 int saved_parse_flags = parse_flags;
3121 mstr = s->d;
3122 if (s->type.t == MACRO_FUNC) {
3123 /* whitespace between macro name and argument list */
3124 TokenString ws_str;
3125 tok_str_new(&ws_str);
3127 spc = 0;
3128 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3129 | PARSE_FLAG_ACCEPT_STRAYS;
3131 /* get next token from argument stream */
3132 t = next_argstream(nested_list, can_read_stream, &ws_str);
3133 if (t != '(') {
3134 /* not a macro substitution after all, restore the
3135 * macro token plus all whitespace we've read.
3136 * whitespace is intentionally not merged to preserve
3137 * newlines. */
3138 parse_flags = saved_parse_flags;
3139 tok_str_add(tok_str, tok);
3140 if (parse_flags & PARSE_FLAG_SPACES) {
3141 int i;
3142 for (i = 0; i < ws_str.len; i++)
3143 tok_str_add(tok_str, ws_str.str[i]);
3145 tok_str_free_str(ws_str.str);
3146 return 0;
3147 } else {
3148 tok_str_free_str(ws_str.str);
3150 next_nomacro(); /* eat '(' */
3152 /* argument macro */
3153 args = NULL;
3154 sa = s->next;
3155 /* NOTE: empty args are allowed, except if no args */
3156 for(;;) {
3157 do {
3158 next_argstream(nested_list, can_read_stream, NULL);
3159 } while (is_space(tok) || TOK_LINEFEED == tok);
3160 empty_arg:
3161 /* handle '()' case */
3162 if (!args && !sa && tok == ')')
3163 break;
3164 if (!sa)
3165 tcc_error("macro '%s' used with too many args",
3166 get_tok_str(s->v, 0));
3167 tok_str_new(&str);
3168 parlevel = spc = 0;
3169 /* NOTE: non zero sa->t indicates VA_ARGS */
3170 while ((parlevel > 0 ||
3171 (tok != ')' &&
3172 (tok != ',' || sa->type.t)))) {
3173 if (tok == TOK_EOF || tok == 0)
3174 break;
3175 if (tok == '(')
3176 parlevel++;
3177 else if (tok == ')')
3178 parlevel--;
3179 if (tok == TOK_LINEFEED)
3180 tok = ' ';
3181 if (!check_space(tok, &spc))
3182 tok_str_add2(&str, tok, &tokc);
3183 next_argstream(nested_list, can_read_stream, NULL);
3185 if (parlevel)
3186 expect(")");
3187 str.len -= spc;
3188 tok_str_add(&str, 0);
3189 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3190 sa1->d = str.str;
3191 sa = sa->next;
3192 if (tok == ')') {
3193 /* special case for gcc var args: add an empty
3194 var arg argument if it is omitted */
3195 if (sa && sa->type.t && gnu_ext)
3196 goto empty_arg;
3197 break;
3199 if (tok != ',')
3200 expect(",");
3202 if (sa) {
3203 tcc_error("macro '%s' used with too few args",
3204 get_tok_str(s->v, 0));
3207 parse_flags = saved_parse_flags;
3209 /* now subst each arg */
3210 mstr = macro_arg_subst(nested_list, mstr, args);
3211 /* free memory */
3212 sa = args;
3213 while (sa) {
3214 sa1 = sa->prev;
3215 tok_str_free_str(sa->d);
3216 sym_free(sa);
3217 sa = sa1;
3221 sym_push2(nested_list, s->v, 0, 0);
3222 parse_flags = saved_parse_flags;
3223 macro_subst(tok_str, nested_list, mstr, can_read_stream | 2);
3225 /* pop nested defined symbol */
3226 sa1 = *nested_list;
3227 *nested_list = sa1->prev;
3228 sym_free(sa1);
3229 if (mstr != s->d)
3230 tok_str_free_str(mstr);
3232 return 0;
3235 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3237 CString cstr;
3238 int n, ret = 1;
3240 cstr_new(&cstr);
3241 if (t1 != TOK_PLCHLDR)
3242 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3243 n = cstr.size;
3244 if (t2 != TOK_PLCHLDR)
3245 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3246 cstr_ccat(&cstr, '\0');
3248 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3249 memcpy(file->buffer, cstr.data, cstr.size);
3250 for (;;) {
3251 next_nomacro1();
3252 if (0 == *file->buf_ptr)
3253 break;
3254 if (is_space(tok))
3255 continue;
3256 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3257 " preprocessing token", n, cstr.data, (char*)cstr.data + n);
3258 ret = 0;
3259 break;
3261 tcc_close();
3262 //printf("paste <%s>\n", (char*)cstr.data);
3263 cstr_free(&cstr);
3264 return ret;
3267 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3268 return the resulting string (which must be freed). */
3269 static inline int *macro_twosharps(const int *ptr0)
3271 int t;
3272 CValue cval;
3273 TokenString macro_str1;
3274 int start_of_nosubsts = -1;
3275 const int *ptr;
3277 /* we search the first '##' */
3278 for (ptr = ptr0;;) {
3279 TOK_GET(&t, &ptr, &cval);
3280 if (t == TOK_TWOSHARPS)
3281 break;
3282 if (t == 0)
3283 return NULL;
3286 tok_str_new(&macro_str1);
3288 //tok_print(" $$$", ptr0);
3289 for (ptr = ptr0;;) {
3290 TOK_GET(&t, &ptr, &cval);
3291 if (t == 0)
3292 break;
3293 if (t == TOK_TWOSHARPS)
3294 continue;
3295 while (*ptr == TOK_TWOSHARPS) {
3296 int t1; CValue cv1;
3297 /* given 'a##b', remove nosubsts preceding 'a' */
3298 if (start_of_nosubsts >= 0)
3299 macro_str1.len = start_of_nosubsts;
3300 /* given 'a##b', remove nosubsts preceding 'b' */
3301 while ((t1 = *++ptr) == TOK_NOSUBST)
3303 if (t1 && t1 != TOK_TWOSHARPS) {
3304 TOK_GET(&t1, &ptr, &cv1);
3305 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3306 if (paste_tokens(t, &cval, t1, &cv1)) {
3307 t = tok, cval = tokc;
3308 } else {
3309 tok_str_add2(&macro_str1, t, &cval);
3310 t = t1, cval = cv1;
3315 if (t == TOK_NOSUBST) {
3316 if (start_of_nosubsts < 0)
3317 start_of_nosubsts = macro_str1.len;
3318 } else {
3319 start_of_nosubsts = -1;
3321 tok_str_add2(&macro_str1, t, &cval);
3323 tok_str_add(&macro_str1, 0);
3324 //tok_print(" ###", macro_str1.str);
3325 return macro_str1.str;
3328 /* do macro substitution of macro_str and add result to
3329 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3330 inside to avoid recursing. */
3331 static void macro_subst(
3332 TokenString *tok_str,
3333 Sym **nested_list,
3334 const int *macro_str,
3335 int can_read_stream
3338 Sym *s;
3339 const int *ptr;
3340 int t, spc, nosubst;
3341 CValue cval;
3342 int *macro_str1 = NULL;
3344 /* first scan for '##' operator handling */
3345 ptr = macro_str;
3346 spc = nosubst = 0;
3348 /* first scan for '##' operator handling */
3349 if (can_read_stream & 1) {
3350 macro_str1 = macro_twosharps(ptr);
3351 if (macro_str1)
3352 ptr = macro_str1;
3355 while (1) {
3356 TOK_GET(&t, &ptr, &cval);
3357 if (t == 0)
3358 break;
3360 if (t >= TOK_IDENT && 0 == nosubst) {
3361 s = define_find(t);
3362 if (s == NULL)
3363 goto no_subst;
3365 /* if nested substitution, do nothing */
3366 if (sym_find2(*nested_list, t)) {
3367 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3368 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3369 goto no_subst;
3373 TokenString str;
3374 str.str = (int*)ptr;
3375 begin_macro(&str, 2);
3377 tok = t;
3378 macro_subst_tok(tok_str, nested_list, s, can_read_stream);
3380 if (str.alloc == 3) {
3381 /* already finished by reading function macro arguments */
3382 break;
3385 ptr = macro_ptr;
3386 end_macro ();
3389 spc = (tok_str->len &&
3390 is_space(tok_last(tok_str->str,
3391 tok_str->str + tok_str->len)));
3393 } else {
3395 if (t == '\\' && !(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3396 tcc_error("stray '\\' in program");
3398 no_subst:
3399 if (!check_space(t, &spc))
3400 tok_str_add2(tok_str, t, &cval);
3401 nosubst = 0;
3402 if (t == TOK_NOSUBST)
3403 nosubst = 1;
3406 if (macro_str1)
3407 tok_str_free_str(macro_str1);
3411 /* return next token with macro substitution */
3412 ST_FUNC void next(void)
3414 redo:
3415 if (parse_flags & PARSE_FLAG_SPACES)
3416 next_nomacro_spc();
3417 else
3418 next_nomacro();
3420 if (macro_ptr) {
3421 if (tok == TOK_NOSUBST || tok == TOK_PLCHLDR) {
3422 /* discard preprocessor markers */
3423 goto redo;
3424 } else if (tok == 0) {
3425 /* end of macro or unget token string */
3426 end_macro();
3427 goto redo;
3429 } else if (tok >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3430 Sym *s;
3431 /* if reading from file, try to substitute macros */
3432 s = define_find(tok);
3433 if (s) {
3434 Sym *nested_list = NULL;
3435 tokstr_buf.len = 0;
3436 macro_subst_tok(&tokstr_buf, &nested_list, s, 1);
3437 tok_str_add(&tokstr_buf, 0);
3438 begin_macro(&tokstr_buf, 2);
3439 goto redo;
3442 /* convert preprocessor tokens into C tokens */
3443 if (tok == TOK_PPNUM) {
3444 if (parse_flags & PARSE_FLAG_TOK_NUM)
3445 parse_number((char *)tokc.str.data);
3446 } else if (tok == TOK_PPSTR) {
3447 if (parse_flags & PARSE_FLAG_TOK_STR)
3448 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3452 /* push back current token and set current token to 'last_tok'. Only
3453 identifier case handled for labels. */
3454 ST_INLN void unget_tok(int last_tok)
3457 TokenString *str = tok_str_alloc();
3458 tok_str_add2(str, tok, &tokc);
3459 tok_str_add(str, 0);
3460 begin_macro(str, 1);
3461 tok = last_tok;
3464 ST_FUNC void preprocess_start(TCCState *s1)
3466 char *buf;
3467 s1->include_stack_ptr = s1->include_stack;
3468 /* XXX: move that before to avoid having to initialize
3469 file->ifdef_stack_ptr ? */
3470 s1->ifdef_stack_ptr = s1->ifdef_stack;
3471 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3472 pp_once++;
3474 pvtop = vtop = vstack - 1;
3475 s1->pack_stack[0] = 0;
3476 s1->pack_stack_ptr = s1->pack_stack;
3478 set_idnum('$', s1->dollars_in_identifiers ? IS_ID : 0);
3479 set_idnum('.', (parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0);
3480 buf = tcc_malloc(3 + strlen(file->filename));
3481 sprintf(buf, "\"%s\"", file->filename);
3482 tcc_undefine_symbol(s1, "__BASE_FILE__");
3483 tcc_define_symbol(s1, "__BASE_FILE__", buf);
3484 tcc_free(buf);
3485 if (s1->nb_cmd_include_files) {
3486 CString cstr;
3487 int i;
3488 cstr_new(&cstr);
3489 for (i = 0; i < s1->nb_cmd_include_files; i++) {
3490 cstr_cat(&cstr, "#include \"", -1);
3491 cstr_cat(&cstr, s1->cmd_include_files[i], -1);
3492 cstr_cat(&cstr, "\"\n", -1);
3494 *s1->include_stack_ptr++ = file;
3495 tcc_open_bf(s1, "<command line>", cstr.size);
3496 memcpy(file->buffer, cstr.data, cstr.size);
3497 cstr_free(&cstr);
3501 ST_FUNC void tccpp_new(TCCState *s)
3503 int i, c;
3504 const char *p, *r;
3506 /* might be used in error() before preprocess_start() */
3507 s->include_stack_ptr = s->include_stack;
3509 /* init isid table */
3510 for(i = CH_EOF; i<128; i++)
3511 set_idnum(i,
3512 is_space(i) ? IS_SPC
3513 : isid(i) ? IS_ID
3514 : isnum(i) ? IS_NUM
3515 : 0);
3517 for(i = 128; i<256; i++)
3518 set_idnum(i, IS_ID);
3520 /* init allocators */
3521 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3522 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3523 tal_new(&cstr_alloc, CSTR_TAL_LIMIT, CSTR_TAL_SIZE);
3525 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3526 cstr_new(&cstr_buf);
3527 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3528 tok_str_new(&tokstr_buf);
3529 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3531 tok_ident = TOK_IDENT;
3532 p = tcc_keywords;
3533 while (*p) {
3534 r = p;
3535 for(;;) {
3536 c = *r++;
3537 if (c == '\0')
3538 break;
3540 tok_alloc(p, r - p - 1);
3541 p = r;
3545 ST_FUNC void tccpp_delete(TCCState *s)
3547 int i, n;
3549 /* free -D and compiler defines */
3550 free_defines(NULL);
3552 /* cleanup from error/setjmp */
3553 while (macro_stack)
3554 end_macro();
3555 macro_ptr = NULL;
3557 /* free tokens */
3558 n = tok_ident - TOK_IDENT;
3559 for(i = 0; i < n; i++)
3560 tal_free(toksym_alloc, table_ident[i]);
3561 tcc_free(table_ident);
3562 table_ident = NULL;
3564 /* free static buffers */
3565 cstr_free(&tokcstr);
3566 cstr_free(&cstr_buf);
3567 tok_str_free_str(tokstr_buf.str);
3569 /* free allocators */
3570 tal_delete(toksym_alloc);
3571 toksym_alloc = NULL;
3572 tal_delete(tokstr_alloc);
3573 tokstr_alloc = NULL;
3574 tal_delete(cstr_alloc);
3575 cstr_alloc = NULL;
3578 /* ------------------------------------------------------------------------- */
3579 /* tcc -E [-P[1]] [-dD} support */
3581 static void tok_print(const char *msg, const int *str)
3583 FILE *fp;
3584 int t;
3585 CValue cval;
3587 fp = tcc_state->ppfp;
3588 if (!fp || !tcc_state->dflag)
3589 fp = stdout;
3591 fprintf(fp, "%s ", msg);
3592 while (str) {
3593 TOK_GET(&t, &str, &cval);
3594 if (!t)
3595 break;
3596 fprintf(fp,"%s", get_tok_str(t, &cval));
3598 fprintf(fp, "\n");
3601 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3603 int d = f->line_num - f->line_ref;
3605 if (s1->dflag & 4)
3606 return;
3608 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3610 } else if (level == 0 && f->line_ref && d < 8) {
3611 while (d > 0)
3612 fputs("\n", s1->ppfp), --d;
3613 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3614 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3615 } else {
3616 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3617 level > 0 ? " 1" : level < 0 ? " 2" : "");
3619 f->line_ref = f->line_num;
3622 static void define_print(TCCState *s1, int v)
3624 FILE *fp;
3625 Sym *s;
3627 s = define_find(v);
3628 if (NULL == s || NULL == s->d)
3629 return;
3631 fp = s1->ppfp;
3632 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3633 if (s->type.t == MACRO_FUNC) {
3634 Sym *a = s->next;
3635 fprintf(fp,"(");
3636 if (a)
3637 for (;;) {
3638 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3639 if (!(a = a->next))
3640 break;
3641 fprintf(fp,",");
3643 fprintf(fp,")");
3645 tok_print("", s->d);
3648 static void pp_debug_defines(TCCState *s1)
3650 int v, t;
3651 const char *vs;
3652 FILE *fp;
3654 t = pp_debug_tok;
3655 if (t == 0)
3656 return;
3658 file->line_num--;
3659 pp_line(s1, file, 0);
3660 file->line_ref = ++file->line_num;
3662 fp = s1->ppfp;
3663 v = pp_debug_symv;
3664 vs = get_tok_str(v, NULL);
3665 if (t == TOK_DEFINE) {
3666 define_print(s1, v);
3667 } else if (t == TOK_UNDEF) {
3668 fprintf(fp, "#undef %s\n", vs);
3669 } else if (t == TOK_push_macro) {
3670 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3671 } else if (t == TOK_pop_macro) {
3672 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3674 pp_debug_tok = 0;
3677 static void pp_debug_builtins(TCCState *s1)
3679 int v;
3680 for (v = TOK_IDENT; v < tok_ident; ++v)
3681 define_print(s1, v);
3684 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3685 static int pp_need_space(int a, int b)
3687 return 'E' == a ? '+' == b || '-' == b
3688 : '+' == a ? TOK_INC == b || '+' == b
3689 : '-' == a ? TOK_DEC == b || '-' == b
3690 : a >= TOK_IDENT ? b >= TOK_IDENT
3691 : 0;
3694 /* maybe hex like 0x1e */
3695 static int pp_check_he0xE(int t, const char *p)
3697 if (t == TOK_PPNUM && toup(strchr(p, 0)[-1]) == 'E')
3698 return 'E';
3699 return t;
3702 /* Preprocess the current file */
3703 ST_FUNC int tcc_preprocess(TCCState *s1)
3705 BufferedFile **iptr;
3706 int token_seen, spcs, level;
3707 const char *p;
3708 Sym *define_start;
3710 preprocess_start(s1);
3711 ch = file->buf_ptr[0];
3712 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3713 parse_flags = PARSE_FLAG_PREPROCESS
3714 | (parse_flags & PARSE_FLAG_ASM_FILE)
3715 | PARSE_FLAG_LINEFEED
3716 | PARSE_FLAG_SPACES
3717 | PARSE_FLAG_ACCEPT_STRAYS
3719 define_start = define_stack;
3721 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3722 capability to compile and run itself, provided all numbers are
3723 given as decimals. tcc -E -P10 will do. */
3724 if (s1->Pflag == 1 + 10)
3725 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3727 #ifdef PP_BENCH
3728 /* for PP benchmarks */
3729 do next(); while (tok != TOK_EOF);
3730 free_defines(define_start);
3731 return 0;
3732 #endif
3734 if (s1->dflag & 1) {
3735 pp_debug_builtins(s1);
3736 s1->dflag &= ~1;
3739 token_seen = TOK_LINEFEED, spcs = 0;
3740 pp_line(s1, file, 0);
3742 for (;;) {
3743 iptr = s1->include_stack_ptr;
3744 next();
3745 if (tok == TOK_EOF)
3746 break;
3747 level = s1->include_stack_ptr - iptr;
3748 if (level) {
3749 if (level > 0)
3750 pp_line(s1, *iptr, 0);
3751 pp_line(s1, file, level);
3754 if (s1->dflag) {
3755 pp_debug_defines(s1);
3756 if (s1->dflag & 4)
3757 continue;
3760 if (token_seen == TOK_LINEFEED) {
3761 if (tok == ' ') {
3762 ++spcs;
3763 continue;
3765 if (tok == TOK_LINEFEED) {
3766 spcs = 0;
3767 continue;
3769 pp_line(s1, file, 0);
3770 } else if (tok == TOK_LINEFEED) {
3771 ++file->line_ref;
3772 } else {
3773 spcs = pp_need_space(token_seen, tok);
3776 while (spcs)
3777 fputs(" ", s1->ppfp), --spcs;
3778 fputs(p = get_tok_str(tok, &tokc), s1->ppfp);
3779 token_seen = pp_check_he0xE(tok, p);;
3781 /* reset define stack, but keep -D and built-ins */
3782 free_defines(define_start);
3783 return 0;
3786 /* ------------------------------------------------------------------------- */