tccpp: #pragma once: make it work
[tinycc.git] / tccpp.c
blobc40a14cb1cdfeddb8ae570c3aaf22725ad85c943
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 ST_DATA TinyAlloc *toksym_alloc;
42 ST_DATA TinyAlloc *tokstr_alloc;
43 ST_DATA TinyAlloc *cstr_alloc;
45 /* ------------------------------------------------------------------------- */
47 static TokenSym *hash_ident[TOK_HASH_SIZE];
48 static char token_buf[STRING_MAX_SIZE + 1];
49 static CString cstr_buf;
50 static TokenString tokstr_buf;
51 static unsigned char isidnum_table[256 - CH_EOF];
52 static int pp_debug_tok, pp_debug_symv;
53 static int pp_once;
54 static void tok_print(const char *msg, const int *str);
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 ST_FUNC void begin_macro(TokenString *str, int alloc)
115 str->alloc = alloc;
116 str->prev = macro_stack;
117 str->prev_ptr = macro_ptr;
118 macro_ptr = str->str;
119 macro_stack = str;
122 ST_FUNC void end_macro(void)
124 TokenString *str = macro_stack;
125 macro_stack = str->prev;
126 macro_ptr = str->prev_ptr;
127 if (str->alloc == 2) {
128 str->alloc = 3; /* just mark as finished */
129 } else {
130 tok_str_free(str->str);
131 if (str->alloc == 1)
132 tcc_free(str);
136 ST_FUNC char *trimfront(char *p)
138 while (*p && (unsigned char)*p <= ' ')
139 ++p;
140 return p;
143 ST_FUNC char *trimback(char *a, char *e)
145 while (e > a && (unsigned char)e[-1] <= ' ')
146 --e;
147 *e = 0;;
148 return a;
151 /* ------------------------------------------------------------------------- */
152 /* Custom allocator for tiny objects */
154 ST_FUNC TinyAlloc *tal_new(TinyAlloc **pal, size_t limit, size_t size)
156 TinyAlloc *al = tcc_mallocz(sizeof(TinyAlloc));
157 al->p = al->buffer = tcc_malloc(size);
158 al->limit = limit;
159 al->size = size;
160 if (pal) *pal = al;
161 return al;
164 ST_FUNC void tal_delete(TinyAlloc *al)
166 TinyAlloc *next;
168 tail_call:
169 if (!al)
170 return;
171 #ifdef TAL_INFO
172 fprintf(stderr, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
173 al->limit, al->size / 1024.0 / 1024.0, al->nb_peak, al->nb_total, al->nb_missed,
174 (al->peak_p - al->buffer) * 100.0 / al->size);
175 #endif
176 #ifdef TAL_DEBUG
177 if (al->nb_allocs > 0) {
178 fprintf(stderr, "TAL_DEBUG: mem leak %d chunks (limit= %d)\n",
179 al->nb_allocs, al->limit);
180 uint8_t *p = al->buffer;
181 while (p < al->p) {
182 tal_header_t *header = (tal_header_t *)p;
183 if (header->line_num > 0) {
184 fprintf(stderr, " file %s, line %u: %u bytes\n",
185 header->file_name, header->line_num, header->size);
187 p += header->size + sizeof(tal_header_t);
190 #endif
191 next = al->next;
192 tcc_free(al->buffer);
193 tcc_free(al);
194 al = next;
195 goto tail_call;
198 ST_FUNC void tal_free_impl(TinyAlloc *al, void *p TAL_DEBUG_PARAMS)
200 if (!p)
201 return;
202 tail_call:
203 if (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size) {
204 #ifdef TAL_DEBUG
205 tal_header_t *header = (((tal_header_t *)p) - 1);
206 if (header->line_num < 0) {
207 fprintf(stderr, "TAL_DEBUG: file %s, line %u double frees chunk from\n",
208 file, line);
209 fprintf(stderr, " file %s, line %u: %u bytes\n",
210 header->file_name, -header->line_num, header->size);
211 } else
212 header->line_num = -header->line_num;
213 #endif
214 al->nb_allocs--;
215 if (!al->nb_allocs)
216 al->p = al->buffer;
217 } else if (al->next) {
218 al = al->next;
219 goto tail_call;
221 else
222 tcc_free(p);
225 ST_FUNC void *tal_realloc_impl(TinyAlloc **pal, void *p, size_t size TAL_DEBUG_PARAMS)
227 tal_header_t *header;
228 void *ret;
229 int is_own;
230 size_t adj_size = (size + 3) & -4;
231 TinyAlloc *al = *pal;
233 tail_call:
234 is_own = (al->buffer <= (uint8_t *)p && (uint8_t *)p < al->buffer + al->size);
235 if ((!p || is_own) && size <= al->limit) {
236 if (al->p + adj_size + sizeof(tal_header_t) < al->buffer + al->size) {
237 header = (tal_header_t *)al->p;
238 header->size = adj_size;
239 #ifdef TAL_DEBUG
240 int ofs = strlen(file) - TAL_DEBUG_FILE_LEN;
241 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), TAL_DEBUG_FILE_LEN);
242 header->file_name[TAL_DEBUG_FILE_LEN] = 0;
243 header->line_num = line;
244 #endif
245 ret = al->p + sizeof(tal_header_t);
246 al->p += adj_size + sizeof(tal_header_t);
247 if (is_own) {
248 header = (((tal_header_t *)p) - 1);
249 memcpy(ret, p, header->size);
250 #ifdef TAL_DEBUG
251 header->line_num = -header->line_num;
252 #endif
253 } else {
254 al->nb_allocs++;
256 #ifdef TAL_INFO
257 if (al->nb_peak < al->nb_allocs)
258 al->nb_peak = al->nb_allocs;
259 if (al->peak_p < al->p)
260 al->peak_p = al->p;
261 al->nb_total++;
262 #endif
263 return ret;
264 } else if (is_own) {
265 al->nb_allocs--;
266 ret = tal_realloc(*pal, 0, size);
267 header = (((tal_header_t *)p) - 1);
268 memcpy(ret, p, header->size);
269 #ifdef TAL_DEBUG
270 header->line_num = -header->line_num;
271 #endif
272 return ret;
274 if (al->next) {
275 al = al->next;
276 } else {
277 TinyAlloc *bottom = al, *next = al->top ? al->top : al;
279 al = tal_new(pal, next->limit, next->size * 2);
280 al->next = next;
281 bottom->top = al;
283 goto tail_call;
285 if (is_own) {
286 al->nb_allocs--;
287 ret = tcc_malloc(size);
288 header = (((tal_header_t *)p) - 1);
289 memcpy(ret, p, header->size);
290 #ifdef TAL_DEBUG
291 header->line_num = -header->line_num;
292 #endif
293 } else if (al->next) {
294 al = al->next;
295 goto tail_call;
296 } else
297 ret = tcc_realloc(p, size);
298 #ifdef TAL_INFO
299 al->nb_missed++;
300 #endif
301 return ret;
304 /* ------------------------------------------------------------------------- */
305 /* CString handling */
306 static void cstr_realloc(CString *cstr, int new_size)
308 int size;
309 void *data;
311 size = cstr->size_allocated;
312 if (size < 8)
313 size = 8; /* no need to allocate a too small first string */
314 while (size < new_size)
315 size = size * 2;
316 data = tal_realloc(cstr_alloc, cstr->data_allocated, size);
317 cstr->data_allocated = data;
318 cstr->size_allocated = size;
319 cstr->data = data;
322 /* add a byte */
323 ST_FUNC void cstr_ccat(CString *cstr, int ch)
325 int size;
326 size = cstr->size + 1;
327 if (size > cstr->size_allocated)
328 cstr_realloc(cstr, size);
329 ((unsigned char *)cstr->data)[size - 1] = ch;
330 cstr->size = size;
333 ST_FUNC void cstr_cat(CString *cstr, const char *str, int len)
335 int size;
336 if (len <= 0)
337 len = strlen(str) + 1 + len;
338 size = cstr->size + len;
339 if (size > cstr->size_allocated)
340 cstr_realloc(cstr, size);
341 memmove(((unsigned char *)cstr->data) + cstr->size, str, len);
342 cstr->size = size;
345 /* add a wide char */
346 ST_FUNC void cstr_wccat(CString *cstr, int ch)
348 int size;
349 size = cstr->size + sizeof(nwchar_t);
350 if (size > cstr->size_allocated)
351 cstr_realloc(cstr, size);
352 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
353 cstr->size = size;
356 ST_FUNC void cstr_new(CString *cstr)
358 memset(cstr, 0, sizeof(CString));
361 /* free string and reset it to NULL */
362 ST_FUNC void cstr_free(CString *cstr)
364 tal_free(cstr_alloc, cstr->data_allocated);
365 cstr_new(cstr);
368 /* reset string to empty */
369 ST_FUNC void cstr_reset(CString *cstr)
371 cstr->size = 0;
374 /* XXX: unicode ? */
375 static void add_char(CString *cstr, int c)
377 if (c == '\'' || c == '\"' || c == '\\') {
378 /* XXX: could be more precise if char or string */
379 cstr_ccat(cstr, '\\');
381 if (c >= 32 && c <= 126) {
382 cstr_ccat(cstr, c);
383 } else {
384 cstr_ccat(cstr, '\\');
385 if (c == '\n') {
386 cstr_ccat(cstr, 'n');
387 } else {
388 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
389 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
390 cstr_ccat(cstr, '0' + (c & 7));
395 /* ------------------------------------------------------------------------- */
396 /* allocate a new token */
397 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
399 TokenSym *ts, **ptable;
400 int i;
402 if (tok_ident >= SYM_FIRST_ANOM)
403 tcc_error("memory full (symbols)");
405 /* expand token table if needed */
406 i = tok_ident - TOK_IDENT;
407 if ((i % TOK_ALLOC_INCR) == 0) {
408 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
409 table_ident = ptable;
412 ts = tal_realloc(toksym_alloc, 0, sizeof(TokenSym) + len);
413 table_ident[i] = ts;
414 ts->tok = tok_ident++;
415 ts->sym_define = NULL;
416 ts->sym_label = NULL;
417 ts->sym_struct = NULL;
418 ts->sym_identifier = NULL;
419 ts->len = len;
420 ts->hash_next = NULL;
421 memcpy(ts->str, str, len);
422 ts->str[len] = '\0';
423 *pts = ts;
424 return ts;
427 #define TOK_HASH_INIT 1
428 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
431 /* find a token and add it if not found */
432 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
434 TokenSym *ts, **pts;
435 int i;
436 unsigned int h;
438 h = TOK_HASH_INIT;
439 for(i=0;i<len;i++)
440 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
441 h &= (TOK_HASH_SIZE - 1);
443 pts = &hash_ident[h];
444 for(;;) {
445 ts = *pts;
446 if (!ts)
447 break;
448 if (ts->len == len && !memcmp(ts->str, str, len))
449 return ts;
450 pts = &(ts->hash_next);
452 return tok_alloc_new(pts, str, len);
455 /* XXX: buffer overflow */
456 /* XXX: float tokens */
457 ST_FUNC const char *get_tok_str(int v, CValue *cv)
459 char *p;
460 int i, len;
462 cstr_reset(&cstr_buf);
463 p = cstr_buf.data;
465 switch(v) {
466 case TOK_CINT:
467 case TOK_CUINT:
468 case TOK_CLLONG:
469 case TOK_CULLONG:
470 /* XXX: not quite exact, but only useful for testing */
471 #ifdef _WIN32
472 sprintf(p, "%u", (unsigned)cv->i);
473 #else
474 sprintf(p, "%llu", (unsigned long long)cv->i);
475 #endif
476 break;
477 case TOK_LCHAR:
478 cstr_ccat(&cstr_buf, 'L');
479 case TOK_CCHAR:
480 cstr_ccat(&cstr_buf, '\'');
481 add_char(&cstr_buf, cv->i);
482 cstr_ccat(&cstr_buf, '\'');
483 cstr_ccat(&cstr_buf, '\0');
484 break;
485 case TOK_PPNUM:
486 case TOK_PPSTR:
487 return (char*)cv->str.data;
488 case TOK_LSTR:
489 cstr_ccat(&cstr_buf, 'L');
490 case TOK_STR:
491 cstr_ccat(&cstr_buf, '\"');
492 if (v == TOK_STR) {
493 len = cv->str.size - 1;
494 for(i=0;i<len;i++)
495 add_char(&cstr_buf, ((unsigned char *)cv->str.data)[i]);
496 } else {
497 len = (cv->str.size / sizeof(nwchar_t)) - 1;
498 for(i=0;i<len;i++)
499 add_char(&cstr_buf, ((nwchar_t *)cv->str.data)[i]);
501 cstr_ccat(&cstr_buf, '\"');
502 cstr_ccat(&cstr_buf, '\0');
503 break;
505 case TOK_CFLOAT:
506 cstr_cat(&cstr_buf, "<float>", 0);
507 break;
508 case TOK_CDOUBLE:
509 cstr_cat(&cstr_buf, "<double>", 0);
510 break;
511 case TOK_CLDOUBLE:
512 cstr_cat(&cstr_buf, "<long double>", 0);
513 break;
514 case TOK_LINENUM:
515 cstr_cat(&cstr_buf, "<linenumber>", 0);
516 break;
518 /* above tokens have value, the ones below don't */
520 case TOK_LT:
521 v = '<';
522 goto addv;
523 case TOK_GT:
524 v = '>';
525 goto addv;
526 case TOK_DOTS:
527 return strcpy(p, "...");
528 case TOK_A_SHL:
529 return strcpy(p, "<<=");
530 case TOK_A_SAR:
531 return strcpy(p, ">>=");
532 default:
533 if (v < TOK_IDENT) {
534 /* search in two bytes table */
535 const unsigned char *q = tok_two_chars;
536 while (*q) {
537 if (q[2] == v) {
538 *p++ = q[0];
539 *p++ = q[1];
540 *p = '\0';
541 return cstr_buf.data;
543 q += 3;
545 if (v >= 127) {
546 sprintf(cstr_buf.data, "<%02x>", v);
547 return cstr_buf.data;
549 addv:
550 *p++ = v;
551 *p = '\0';
552 } else if (v < tok_ident) {
553 return table_ident[v - TOK_IDENT]->str;
554 } else if (v >= SYM_FIRST_ANOM) {
555 /* special name for anonymous symbol */
556 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
557 } else {
558 /* should never happen */
559 return NULL;
561 break;
563 return cstr_buf.data;
566 /* return the current character, handling end of block if necessary
567 (but not stray) */
568 ST_FUNC int handle_eob(void)
570 BufferedFile *bf = file;
571 int len;
573 /* only tries to read if really end of buffer */
574 if (bf->buf_ptr >= bf->buf_end) {
575 if (bf->fd != -1) {
576 #if defined(PARSE_DEBUG)
577 len = 1;
578 #else
579 len = IO_BUF_SIZE;
580 #endif
581 len = read(bf->fd, bf->buffer, len);
582 if (len < 0)
583 len = 0;
584 } else {
585 len = 0;
587 total_bytes += len;
588 bf->buf_ptr = bf->buffer;
589 bf->buf_end = bf->buffer + len;
590 *bf->buf_end = CH_EOB;
592 if (bf->buf_ptr < bf->buf_end) {
593 return bf->buf_ptr[0];
594 } else {
595 bf->buf_ptr = bf->buf_end;
596 return CH_EOF;
600 /* read next char from current input file and handle end of input buffer */
601 ST_INLN void inp(void)
603 ch = *(++(file->buf_ptr));
604 /* end of buffer/file handling */
605 if (ch == CH_EOB)
606 ch = handle_eob();
609 /* handle '\[\r]\n' */
610 static int handle_stray_noerror(void)
612 while (ch == '\\') {
613 inp();
614 if (ch == '\n') {
615 file->line_num++;
616 inp();
617 } else if (ch == '\r') {
618 inp();
619 if (ch != '\n')
620 goto fail;
621 file->line_num++;
622 inp();
623 } else {
624 fail:
625 return 1;
628 return 0;
631 static void handle_stray(void)
633 if (handle_stray_noerror())
634 tcc_error("stray '\\' in program");
637 /* skip the stray and handle the \\n case. Output an error if
638 incorrect char after the stray */
639 static int handle_stray1(uint8_t *p)
641 int c;
643 file->buf_ptr = p;
644 if (p >= file->buf_end) {
645 c = handle_eob();
646 if (c != '\\')
647 return c;
648 p = file->buf_ptr;
650 ch = *p;
651 if (handle_stray_noerror()) {
652 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
653 tcc_error("stray '\\' in program");
654 *--file->buf_ptr = '\\';
656 p = file->buf_ptr;
657 c = *p;
658 return c;
661 /* handle just the EOB case, but not stray */
662 #define PEEKC_EOB(c, p)\
664 p++;\
665 c = *p;\
666 if (c == '\\') {\
667 file->buf_ptr = p;\
668 c = handle_eob();\
669 p = file->buf_ptr;\
673 /* handle the complicated stray case */
674 #define PEEKC(c, p)\
676 p++;\
677 c = *p;\
678 if (c == '\\') {\
679 c = handle_stray1(p);\
680 p = file->buf_ptr;\
684 /* input with '\[\r]\n' handling. Note that this function cannot
685 handle other characters after '\', so you cannot call it inside
686 strings or comments */
687 ST_FUNC void minp(void)
689 inp();
690 if (ch == '\\')
691 handle_stray();
694 /* single line C++ comments */
695 static uint8_t *parse_line_comment(uint8_t *p)
697 int c;
699 p++;
700 for(;;) {
701 c = *p;
702 redo:
703 if (c == '\n' || c == CH_EOF) {
704 break;
705 } else if (c == '\\') {
706 file->buf_ptr = p;
707 c = handle_eob();
708 p = file->buf_ptr;
709 if (c == '\\') {
710 PEEKC_EOB(c, p);
711 if (c == '\n') {
712 file->line_num++;
713 PEEKC_EOB(c, p);
714 } else if (c == '\r') {
715 PEEKC_EOB(c, p);
716 if (c == '\n') {
717 file->line_num++;
718 PEEKC_EOB(c, p);
721 } else {
722 goto redo;
724 } else {
725 p++;
728 return p;
731 /* C comments */
732 ST_FUNC uint8_t *parse_comment(uint8_t *p)
734 int c;
736 p++;
737 for(;;) {
738 /* fast skip loop */
739 for(;;) {
740 c = *p;
741 if (c == '\n' || c == '*' || c == '\\')
742 break;
743 p++;
744 c = *p;
745 if (c == '\n' || c == '*' || c == '\\')
746 break;
747 p++;
749 /* now we can handle all the cases */
750 if (c == '\n') {
751 file->line_num++;
752 p++;
753 } else if (c == '*') {
754 p++;
755 for(;;) {
756 c = *p;
757 if (c == '*') {
758 p++;
759 } else if (c == '/') {
760 goto end_of_comment;
761 } else if (c == '\\') {
762 file->buf_ptr = p;
763 c = handle_eob();
764 p = file->buf_ptr;
765 if (c == CH_EOF)
766 tcc_error("unexpected end of file in comment");
767 if (c == '\\') {
768 /* skip '\[\r]\n', otherwise just skip the stray */
769 while (c == '\\') {
770 PEEKC_EOB(c, p);
771 if (c == '\n') {
772 file->line_num++;
773 PEEKC_EOB(c, p);
774 } else if (c == '\r') {
775 PEEKC_EOB(c, p);
776 if (c == '\n') {
777 file->line_num++;
778 PEEKC_EOB(c, p);
780 } else {
781 goto after_star;
785 } else {
786 break;
789 after_star: ;
790 } else {
791 /* stray, eob or eof */
792 file->buf_ptr = p;
793 c = handle_eob();
794 p = file->buf_ptr;
795 if (c == CH_EOF) {
796 tcc_error("unexpected end of file in comment");
797 } else if (c == '\\') {
798 p++;
802 end_of_comment:
803 p++;
804 return p;
807 #define cinp minp
809 static inline void skip_spaces(void)
811 while (isidnum_table[ch - CH_EOF] & IS_SPC)
812 cinp();
815 static inline int check_space(int t, int *spc)
817 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
818 if (*spc)
819 return 1;
820 *spc = 1;
821 } else
822 *spc = 0;
823 return 0;
826 /* parse a string without interpreting escapes */
827 static uint8_t *parse_pp_string(uint8_t *p,
828 int sep, CString *str)
830 int c;
831 p++;
832 for(;;) {
833 c = *p;
834 if (c == sep) {
835 break;
836 } else if (c == '\\') {
837 file->buf_ptr = p;
838 c = handle_eob();
839 p = file->buf_ptr;
840 if (c == CH_EOF) {
841 unterminated_string:
842 /* XXX: indicate line number of start of string */
843 tcc_error("missing terminating %c character", sep);
844 } else if (c == '\\') {
845 /* escape : just skip \[\r]\n */
846 PEEKC_EOB(c, p);
847 if (c == '\n') {
848 file->line_num++;
849 p++;
850 } else if (c == '\r') {
851 PEEKC_EOB(c, p);
852 if (c != '\n')
853 expect("'\n' after '\r'");
854 file->line_num++;
855 p++;
856 } else if (c == CH_EOF) {
857 goto unterminated_string;
858 } else {
859 if (str) {
860 cstr_ccat(str, '\\');
861 cstr_ccat(str, c);
863 p++;
866 } else if (c == '\n') {
867 file->line_num++;
868 goto add_char;
869 } else if (c == '\r') {
870 PEEKC_EOB(c, p);
871 if (c != '\n') {
872 if (str)
873 cstr_ccat(str, '\r');
874 } else {
875 file->line_num++;
876 goto add_char;
878 } else {
879 add_char:
880 if (str)
881 cstr_ccat(str, c);
882 p++;
885 p++;
886 return p;
889 /* skip block of text until #else, #elif or #endif. skip also pairs of
890 #if/#endif */
891 static void preprocess_skip(void)
893 int a, start_of_line, c, in_warn_or_error;
894 uint8_t *p;
896 p = file->buf_ptr;
897 a = 0;
898 redo_start:
899 start_of_line = 1;
900 in_warn_or_error = 0;
901 for(;;) {
902 redo_no_start:
903 c = *p;
904 switch(c) {
905 case ' ':
906 case '\t':
907 case '\f':
908 case '\v':
909 case '\r':
910 p++;
911 goto redo_no_start;
912 case '\n':
913 file->line_num++;
914 p++;
915 goto redo_start;
916 case '\\':
917 file->buf_ptr = p;
918 c = handle_eob();
919 if (c == CH_EOF) {
920 expect("#endif");
921 } else if (c == '\\') {
922 ch = file->buf_ptr[0];
923 handle_stray_noerror();
925 p = file->buf_ptr;
926 goto redo_no_start;
927 /* skip strings */
928 case '\"':
929 case '\'':
930 if (in_warn_or_error)
931 goto _default;
932 p = parse_pp_string(p, c, NULL);
933 break;
934 /* skip comments */
935 case '/':
936 if (in_warn_or_error)
937 goto _default;
938 file->buf_ptr = p;
939 ch = *p;
940 minp();
941 p = file->buf_ptr;
942 if (ch == '*') {
943 p = parse_comment(p);
944 } else if (ch == '/') {
945 p = parse_line_comment(p);
947 break;
948 case '#':
949 p++;
950 if (start_of_line) {
951 file->buf_ptr = p;
952 next_nomacro();
953 p = file->buf_ptr;
954 if (a == 0 &&
955 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
956 goto the_end;
957 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
958 a++;
959 else if (tok == TOK_ENDIF)
960 a--;
961 else if( tok == TOK_ERROR || tok == TOK_WARNING)
962 in_warn_or_error = 1;
963 else if (tok == TOK_LINEFEED)
964 goto redo_start;
965 else if (parse_flags & PARSE_FLAG_ASM_FILE)
966 p = parse_line_comment(p);
967 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
968 p = parse_line_comment(p);
969 break;
970 _default:
971 default:
972 p++;
973 break;
975 start_of_line = 0;
977 the_end: ;
978 file->buf_ptr = p;
981 /* ParseState handling */
983 /* XXX: currently, no include file info is stored. Thus, we cannot display
984 accurate messages if the function or data definition spans multiple
985 files */
987 /* save current parse state in 's' */
988 ST_FUNC void save_parse_state(ParseState *s)
990 s->line_num = file->line_num;
991 s->macro_ptr = macro_ptr;
992 s->tok = tok;
993 s->tokc = tokc;
996 /* restore parse state from 's' */
997 ST_FUNC void restore_parse_state(ParseState *s)
999 file->line_num = s->line_num;
1000 macro_ptr = s->macro_ptr;
1001 tok = s->tok;
1002 tokc = s->tokc;
1005 /* return the number of additional 'ints' necessary to store the
1006 token */
1007 static inline int tok_size(const int *p)
1009 switch(*p) {
1010 /* 4 bytes */
1011 case TOK_CINT:
1012 case TOK_CUINT:
1013 case TOK_CCHAR:
1014 case TOK_LCHAR:
1015 case TOK_CFLOAT:
1016 case TOK_LINENUM:
1017 return 1 + 1;
1018 case TOK_STR:
1019 case TOK_LSTR:
1020 case TOK_PPNUM:
1021 case TOK_PPSTR:
1022 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
1023 case TOK_CDOUBLE:
1024 case TOK_CLLONG:
1025 case TOK_CULLONG:
1026 return 1 + 2;
1027 case TOK_CLDOUBLE:
1028 return 1 + LDOUBLE_SIZE / 4;
1029 default:
1030 return 1 + 0;
1034 /* token string handling */
1036 ST_INLN void tok_str_new(TokenString *s)
1038 s->str = NULL;
1039 s->len = 0;
1040 s->allocated_len = 0;
1041 s->last_line_num = -1;
1044 ST_FUNC int *tok_str_dup(TokenString *s)
1046 int *str;
1048 str = tal_realloc(tokstr_alloc, 0, s->len * sizeof(int));
1049 memcpy(str, s->str, s->len * sizeof(int));
1050 return str;
1053 ST_FUNC void tok_str_free(int *str)
1055 tal_free(tokstr_alloc, str);
1058 ST_FUNC int *tok_str_realloc(TokenString *s, int new_size)
1060 int *str, size;
1062 size = s->allocated_len;
1063 if (size < 16)
1064 size = 16;
1065 while (size < new_size)
1066 size = size * 2;
1067 TCC_ASSERT((size & (size -1)) == 0);
1068 if (size > s->allocated_len) {
1069 str = tal_realloc(tokstr_alloc, s->str, size * sizeof(int));
1070 s->allocated_len = size;
1071 s->str = str;
1073 return s->str;
1076 ST_FUNC void tok_str_add(TokenString *s, int t)
1078 int len, *str;
1080 len = s->len;
1081 str = s->str;
1082 if (len >= s->allocated_len)
1083 str = tok_str_realloc(s, len + 1);
1084 str[len++] = t;
1085 s->len = len;
1088 static void tok_str_add2(TokenString *s, int t, CValue *cv)
1090 int len, *str;
1092 len = s->len;
1093 str = s->str;
1095 /* allocate space for worst case */
1096 if (len + TOK_MAX_SIZE >= s->allocated_len)
1097 str = tok_str_realloc(s, len + TOK_MAX_SIZE + 1);
1098 str[len++] = t;
1099 switch(t) {
1100 case TOK_CINT:
1101 case TOK_CUINT:
1102 case TOK_CCHAR:
1103 case TOK_LCHAR:
1104 case TOK_CFLOAT:
1105 case TOK_LINENUM:
1106 str[len++] = cv->tab[0];
1107 break;
1108 case TOK_PPNUM:
1109 case TOK_PPSTR:
1110 case TOK_STR:
1111 case TOK_LSTR:
1113 /* Insert the string into the int array. */
1114 size_t nb_words =
1115 1 + (cv->str.size + sizeof(int) - 1) / sizeof(int);
1116 if (len + nb_words >= s->allocated_len)
1117 str = tok_str_realloc(s, len + nb_words + 1);
1118 str[len] = cv->str.size;
1119 memcpy(&str[len + 1], cv->str.data, cv->str.size);
1120 len += nb_words;
1122 break;
1123 case TOK_CDOUBLE:
1124 case TOK_CLLONG:
1125 case TOK_CULLONG:
1126 #if LDOUBLE_SIZE == 8
1127 case TOK_CLDOUBLE:
1128 #endif
1129 str[len++] = cv->tab[0];
1130 str[len++] = cv->tab[1];
1131 break;
1132 #if LDOUBLE_SIZE == 12
1133 case TOK_CLDOUBLE:
1134 str[len++] = cv->tab[0];
1135 str[len++] = cv->tab[1];
1136 str[len++] = cv->tab[2];
1137 #elif LDOUBLE_SIZE == 16
1138 case TOK_CLDOUBLE:
1139 str[len++] = cv->tab[0];
1140 str[len++] = cv->tab[1];
1141 str[len++] = cv->tab[2];
1142 str[len++] = cv->tab[3];
1143 #elif LDOUBLE_SIZE != 8
1144 #error add long double size support
1145 #endif
1146 break;
1147 default:
1148 break;
1150 s->len = len;
1153 /* add the current parse token in token string 's' */
1154 ST_FUNC void tok_str_add_tok(TokenString *s)
1156 CValue cval;
1158 /* save line number info */
1159 if (file->line_num != s->last_line_num) {
1160 s->last_line_num = file->line_num;
1161 cval.i = s->last_line_num;
1162 tok_str_add2(s, TOK_LINENUM, &cval);
1164 tok_str_add2(s, tok, &tokc);
1167 /* get a token from an integer array and increment pointer
1168 accordingly. we code it as a macro to avoid pointer aliasing. */
1169 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
1171 const int *p = *pp;
1172 int n, *tab;
1174 tab = cv->tab;
1175 switch(*t = *p++) {
1176 case TOK_CINT:
1177 case TOK_CUINT:
1178 case TOK_CCHAR:
1179 case TOK_LCHAR:
1180 case TOK_CFLOAT:
1181 case TOK_LINENUM:
1182 tab[0] = *p++;
1183 break;
1184 case TOK_STR:
1185 case TOK_LSTR:
1186 case TOK_PPNUM:
1187 case TOK_PPSTR:
1188 cv->str.size = *p++;
1189 cv->str.data = p;
1190 cv->str.data_allocated = 0;
1191 p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
1192 break;
1193 case TOK_CDOUBLE:
1194 case TOK_CLLONG:
1195 case TOK_CULLONG:
1196 n = 2;
1197 goto copy;
1198 case TOK_CLDOUBLE:
1199 #if LDOUBLE_SIZE == 16
1200 n = 4;
1201 #elif LDOUBLE_SIZE == 12
1202 n = 3;
1203 #elif LDOUBLE_SIZE == 8
1204 n = 2;
1205 #else
1206 # error add long double size support
1207 #endif
1208 copy:
1210 *tab++ = *p++;
1211 while (--n);
1212 break;
1213 default:
1214 break;
1216 *pp = p;
1219 /* Calling this function is expensive, but it is not possible
1220 to read a token string backwards. */
1221 static int tok_last(const int *str0, const int *str1)
1223 const int *str = str0;
1224 int tok = 0;
1225 CValue cval;
1227 while (str < str1)
1228 TOK_GET(&tok, &str, &cval);
1229 return tok;
1232 static int macro_is_equal(const int *a, const int *b)
1234 CValue cv;
1235 int t;
1237 if (!a || !b)
1238 return 1;
1240 while (*a && *b) {
1241 /* first time preallocate static cstr_buf, next time only reset position to start */
1242 cstr_reset(&cstr_buf);
1243 TOK_GET(&t, &a, &cv);
1244 cstr_cat(&cstr_buf, get_tok_str(t, &cv), 0);
1245 TOK_GET(&t, &b, &cv);
1246 if (strcmp(cstr_buf.data, get_tok_str(t, &cv)))
1247 return 0;
1249 return !(*a || *b);
1252 /* defines handling */
1253 ST_INLN void define_push(int v, int macro_type, TokenString *str, Sym *first_arg)
1255 Sym *s, *o;
1257 o = define_find(v);
1258 s = sym_push2(&define_stack, v, macro_type, 0);
1259 s->d = str ? tok_str_dup(str) : NULL;
1260 s->next = first_arg;
1261 table_ident[v - TOK_IDENT]->sym_define = s;
1263 if (o && !macro_is_equal(o->d, s->d))
1264 tcc_warning("%s redefined", get_tok_str(v, NULL));
1267 /* undefined a define symbol. Its name is just set to zero */
1268 ST_FUNC void define_undef(Sym *s)
1270 int v = s->v;
1271 if (v >= TOK_IDENT && v < tok_ident)
1272 table_ident[v - TOK_IDENT]->sym_define = NULL;
1275 ST_INLN Sym *define_find(int v)
1277 v -= TOK_IDENT;
1278 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1279 return NULL;
1280 return table_ident[v]->sym_define;
1283 /* free define stack until top reaches 'b' */
1284 ST_FUNC void free_defines(Sym *b)
1286 while (define_stack != b) {
1287 Sym *top = define_stack;
1288 define_stack = top->prev;
1289 tok_str_free(top->d);
1290 define_undef(top);
1291 sym_free(top);
1294 /* restore remaining (-D or predefined) symbols */
1295 while (b) {
1296 int v = b->v;
1297 if (v >= TOK_IDENT && v < tok_ident) {
1298 Sym **d = &table_ident[v - TOK_IDENT]->sym_define;
1299 if (!*d)
1300 *d = b;
1302 b = b->prev;
1306 /* label lookup */
1307 ST_FUNC Sym *label_find(int v)
1309 v -= TOK_IDENT;
1310 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1311 return NULL;
1312 return table_ident[v]->sym_label;
1315 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1317 Sym *s, **ps;
1318 s = sym_push2(ptop, v, 0, 0);
1319 s->r = flags;
1320 ps = &table_ident[v - TOK_IDENT]->sym_label;
1321 if (ptop == &global_label_stack) {
1322 /* modify the top most local identifier, so that
1323 sym_identifier will point to 's' when popped */
1324 while (*ps != NULL)
1325 ps = &(*ps)->prev_tok;
1327 s->prev_tok = *ps;
1328 *ps = s;
1329 return s;
1332 /* pop labels until element last is reached. Look if any labels are
1333 undefined. Define symbols if '&&label' was used. */
1334 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1336 Sym *s, *s1;
1337 for(s = *ptop; s != slast; s = s1) {
1338 s1 = s->prev;
1339 if (s->r == LABEL_DECLARED) {
1340 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1341 } else if (s->r == LABEL_FORWARD) {
1342 tcc_error("label '%s' used but not defined",
1343 get_tok_str(s->v, NULL));
1344 } else {
1345 if (s->c) {
1346 /* define corresponding symbol. A size of
1347 1 is put. */
1348 put_extern_sym(s, cur_text_section, s->jnext, 1);
1351 /* remove label */
1352 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1353 sym_free(s);
1355 *ptop = slast;
1358 /* eval an expression for #if/#elif */
1359 static int expr_preprocess(void)
1361 int c, t;
1362 TokenString str;
1364 tok_str_new(&str);
1365 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1366 next(); /* do macro subst */
1367 if (tok == TOK_DEFINED) {
1368 next_nomacro();
1369 t = tok;
1370 if (t == '(')
1371 next_nomacro();
1372 c = define_find(tok) != 0;
1373 if (t == '(')
1374 next_nomacro();
1375 tok = TOK_CINT;
1376 tokc.i = c;
1377 } else if (tok >= TOK_IDENT) {
1378 /* if undefined macro */
1379 tok = TOK_CINT;
1380 tokc.i = 0;
1382 tok_str_add_tok(&str);
1384 tok_str_add(&str, -1); /* simulate end of file */
1385 tok_str_add(&str, 0);
1386 /* now evaluate C constant expression */
1387 begin_macro(&str, 0);
1388 next();
1389 c = expr_const();
1390 end_macro();
1391 return c != 0;
1395 /* parse after #define */
1396 ST_FUNC void parse_define(void)
1398 Sym *s, *first, **ps;
1399 int v, t, varg, is_vaargs, spc;
1400 int saved_parse_flags = parse_flags;
1402 v = tok;
1403 if (v < TOK_IDENT)
1404 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1405 /* XXX: should check if same macro (ANSI) */
1406 first = NULL;
1407 t = MACRO_OBJ;
1408 /* '(' must be just after macro definition for MACRO_FUNC */
1409 parse_flags |= PARSE_FLAG_SPACES;
1410 next_nomacro_spc();
1411 if (tok == '(') {
1412 /* must be able to parse TOK_DOTS (in asm mode '.' can be part of identifier) */
1413 parse_flags &= ~PARSE_FLAG_ASM_FILE;
1414 isidnum_table['.' - CH_EOF] = 0;
1415 next_nomacro();
1416 ps = &first;
1417 if (tok != ')') for (;;) {
1418 varg = tok;
1419 next_nomacro();
1420 is_vaargs = 0;
1421 if (varg == TOK_DOTS) {
1422 varg = TOK___VA_ARGS__;
1423 is_vaargs = 1;
1424 } else if (tok == TOK_DOTS && gnu_ext) {
1425 is_vaargs = 1;
1426 next_nomacro();
1428 if (varg < TOK_IDENT)
1429 bad_list:
1430 tcc_error("bad macro parameter list");
1431 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1432 *ps = s;
1433 ps = &s->next;
1434 if (tok == ')')
1435 break;
1436 if (tok != ',' || is_vaargs)
1437 goto bad_list;
1438 next_nomacro();
1440 next_nomacro_spc();
1441 t = MACRO_FUNC;
1442 parse_flags |= (saved_parse_flags & PARSE_FLAG_ASM_FILE);
1443 isidnum_table['.' - CH_EOF] =
1444 (parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0;
1447 tokstr_buf.len = 0;
1448 spc = 2;
1449 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1450 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1451 /* remove spaces around ## and after '#' */
1452 if (TOK_TWOSHARPS == tok) {
1453 if (2 == spc)
1454 goto bad_twosharp;
1455 if (1 == spc)
1456 --tokstr_buf.len;
1457 spc = 3;
1458 } else if ('#' == tok) {
1459 spc = 4;
1460 } else if (check_space(tok, &spc)) {
1461 goto skip;
1463 tok_str_add2(&tokstr_buf, tok, &tokc);
1464 skip:
1465 next_nomacro_spc();
1468 parse_flags = saved_parse_flags;
1469 if (spc == 1)
1470 --tokstr_buf.len; /* remove trailing space */
1471 tok_str_add(&tokstr_buf, 0);
1472 if (3 == spc)
1473 bad_twosharp:
1474 tcc_error("'##' cannot appear at either end of macro");
1475 define_push(v, t, &tokstr_buf, first);
1478 static CachedInclude *search_cached_include(TCCState *s1, const char *filename, int add)
1480 const unsigned char *s;
1481 unsigned int h;
1482 CachedInclude *e;
1483 int i;
1485 h = TOK_HASH_INIT;
1486 s = (unsigned char *) filename;
1487 while (*s) {
1488 #ifdef _WIN32
1489 h = TOK_HASH_FUNC(h, toup(*s));
1490 #else
1491 h = TOK_HASH_FUNC(h, *s);
1492 #endif
1493 s++;
1495 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1497 i = s1->cached_includes_hash[h];
1498 for(;;) {
1499 if (i == 0)
1500 break;
1501 e = s1->cached_includes[i - 1];
1502 if (0 == PATHCMP(e->filename, filename))
1503 return e;
1504 i = e->hash_next;
1506 if (!add)
1507 return NULL;
1509 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1510 strcpy(e->filename, filename);
1511 e->ifndef_macro = e->once = 0;
1512 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1513 /* add in hash table */
1514 e->hash_next = s1->cached_includes_hash[h];
1515 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1516 #ifdef INC_DEBUG
1517 printf("adding cached '%s'\n", filename);
1518 #endif
1519 return e;
1522 static void pragma_parse(TCCState *s1)
1524 next_nomacro();
1525 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1526 int t = tok, v;
1527 Sym *s;
1529 if (next(), tok != '(')
1530 goto pragma_err;
1531 if (next(), tok != TOK_STR)
1532 goto pragma_err;
1533 v = tok_alloc(tokc.str.data, tokc.str.size - 1)->tok;
1534 if (next(), tok != ')')
1535 goto pragma_err;
1536 if (t == TOK_push_macro) {
1537 while (NULL == (s = define_find(v)))
1538 define_push(v, 0, NULL, NULL);
1539 s->type.ref = s; /* set push boundary */
1540 } else {
1541 for (s = define_stack; s; s = s->prev)
1542 if (s->v == v && s->type.ref == s) {
1543 s->type.ref = NULL;
1544 break;
1547 if (s)
1548 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1549 else
1550 tcc_warning("unbalanced #pragma pop_macro");
1551 pp_debug_tok = t, pp_debug_symv = v;
1553 } else if (tok == TOK_once) {
1554 search_cached_include(s1, file->filename, 1)->once = pp_once;
1556 } else if (s1->ppfp) {
1557 /* tcc -E: keep pragmas below unchanged */
1558 unget_tok(' ');
1559 unget_tok(TOK_PRAGMA);
1560 unget_tok('#');
1561 unget_tok(TOK_LINEFEED);
1563 } else if (tok == TOK_pack) {
1564 /* This may be:
1565 #pragma pack(1) // set
1566 #pragma pack() // reset to default
1567 #pragma pack(push,1) // push & set
1568 #pragma pack(pop) // restore previous */
1569 next();
1570 skip('(');
1571 if (tok == TOK_ASM_pop) {
1572 next();
1573 if (s1->pack_stack_ptr <= s1->pack_stack) {
1574 stk_error:
1575 tcc_error("out of pack stack");
1577 s1->pack_stack_ptr--;
1578 } else {
1579 int val = 0;
1580 if (tok != ')') {
1581 if (tok == TOK_ASM_push) {
1582 next();
1583 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1584 goto stk_error;
1585 s1->pack_stack_ptr++;
1586 skip(',');
1588 if (tok != TOK_CINT)
1589 goto pragma_err;
1590 val = tokc.i;
1591 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1592 goto pragma_err;
1593 next();
1595 *s1->pack_stack_ptr = val;
1597 if (tok != ')')
1598 goto pragma_err;
1600 } else if (tok == TOK_comment) {
1601 char *file;
1602 next();
1603 skip('(');
1604 if (tok != TOK_lib)
1605 goto pragma_warn;
1606 next();
1607 skip(',');
1608 if (tok != TOK_STR)
1609 goto pragma_err;
1610 file = tcc_strdup((char *)tokc.str.data);
1611 dynarray_add((void ***)&s1->pragma_libs, &s1->nb_pragma_libs, file);
1612 next();
1613 if (tok != ')')
1614 goto pragma_err;
1615 } else {
1616 pragma_warn:
1617 if (s1->warn_unsupported)
1618 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1620 return;
1622 pragma_err:
1623 tcc_error("malformed #pragma directive");
1624 return;
1627 /* is_bof is true if first non space token at beginning of file */
1628 ST_FUNC void preprocess(int is_bof)
1630 TCCState *s1 = tcc_state;
1631 int i, c, n, saved_parse_flags;
1632 char buf[1024], *q;
1633 Sym *s;
1635 saved_parse_flags = parse_flags;
1636 parse_flags = PARSE_FLAG_PREPROCESS
1637 | PARSE_FLAG_TOK_NUM
1638 | PARSE_FLAG_TOK_STR
1639 | PARSE_FLAG_LINEFEED
1640 | (parse_flags & PARSE_FLAG_ASM_FILE)
1643 next_nomacro();
1644 redo:
1645 switch(tok) {
1646 case TOK_DEFINE:
1647 pp_debug_tok = tok;
1648 next_nomacro();
1649 pp_debug_symv = tok;
1650 parse_define();
1651 break;
1652 case TOK_UNDEF:
1653 pp_debug_tok = tok;
1654 next_nomacro();
1655 pp_debug_symv = tok;
1656 s = define_find(tok);
1657 /* undefine symbol by putting an invalid name */
1658 if (s)
1659 define_undef(s);
1660 break;
1661 case TOK_INCLUDE:
1662 case TOK_INCLUDE_NEXT:
1663 ch = file->buf_ptr[0];
1664 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1665 skip_spaces();
1666 if (ch == '<') {
1667 c = '>';
1668 goto read_name;
1669 } else if (ch == '\"') {
1670 c = ch;
1671 read_name:
1672 inp();
1673 q = buf;
1674 while (ch != c && ch != '\n' && ch != CH_EOF) {
1675 if ((q - buf) < sizeof(buf) - 1)
1676 *q++ = ch;
1677 if (ch == '\\') {
1678 if (handle_stray_noerror() == 0)
1679 --q;
1680 } else
1681 inp();
1683 *q = '\0';
1684 minp();
1685 #if 0
1686 /* eat all spaces and comments after include */
1687 /* XXX: slightly incorrect */
1688 while (ch1 != '\n' && ch1 != CH_EOF)
1689 inp();
1690 #endif
1691 } else {
1692 /* computed #include : either we have only strings or
1693 we have anything enclosed in '<>' */
1694 next();
1695 buf[0] = '\0';
1696 if (tok == TOK_STR) {
1697 while (tok != TOK_LINEFEED) {
1698 if (tok != TOK_STR) {
1699 include_syntax:
1700 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1702 pstrcat(buf, sizeof(buf), (char *)tokc.str.data);
1703 next();
1705 c = '\"';
1706 } else {
1707 int len;
1708 while (tok != TOK_LINEFEED) {
1709 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1710 next();
1712 len = strlen(buf);
1713 /* check syntax and remove '<>' */
1714 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1715 goto include_syntax;
1716 memmove(buf, buf + 1, len - 2);
1717 buf[len - 2] = '\0';
1718 c = '>';
1722 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1723 tcc_error("#include recursion too deep");
1724 /* store current file in stack, but increment stack later below */
1725 *s1->include_stack_ptr = file;
1726 i = tok == TOK_INCLUDE_NEXT ? file->include_next_index : 0;
1727 n = 2 + s1->nb_include_paths + s1->nb_sysinclude_paths;
1728 for (; i < n; ++i) {
1729 char buf1[sizeof file->filename];
1730 CachedInclude *e;
1731 const char *path;
1733 if (i == 0) {
1734 /* check absolute include path */
1735 if (!IS_ABSPATH(buf))
1736 continue;
1737 buf1[0] = 0;
1739 } else if (i == 1) {
1740 /* search in current dir if "header.h" */
1741 if (c != '\"')
1742 continue;
1743 path = file->filename;
1744 pstrncpy(buf1, path, tcc_basename(path) - path);
1746 } else {
1747 /* search in all the include paths */
1748 int j = i - 2, k = j - s1->nb_include_paths;
1749 path = k < 0 ? s1->include_paths[j] : s1->sysinclude_paths[k];
1750 if (path == 0) continue;
1751 pstrcpy(buf1, sizeof(buf1), path);
1752 pstrcat(buf1, sizeof(buf1), "/");
1755 pstrcat(buf1, sizeof(buf1), buf);
1756 e = search_cached_include(s1, buf1, 0);
1757 if (e && (define_find(e->ifndef_macro) || e->once == pp_once)) {
1758 /* no need to parse the include because the 'ifndef macro'
1759 is defined (or had #pragma once) */
1760 #ifdef INC_DEBUG
1761 printf("%s: skipping cached %s\n", file->filename, buf1);
1762 #endif
1763 goto include_done;
1766 if (tcc_open(s1, buf1) < 0)
1767 continue;
1769 file->include_next_index = i + 1;
1770 #ifdef INC_DEBUG
1771 printf("%s: including %s\n", file->prev->filename, file->filename);
1772 #endif
1773 /* update target deps */
1774 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1775 tcc_strdup(buf1));
1776 /* push current file in stack */
1777 ++s1->include_stack_ptr;
1778 /* add include file debug info */
1779 if (s1->do_debug)
1780 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1781 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1782 ch = file->buf_ptr[0];
1783 goto the_end;
1785 tcc_error("include file '%s' not found", buf);
1786 include_done:
1787 break;
1788 case TOK_IFNDEF:
1789 c = 1;
1790 goto do_ifdef;
1791 case TOK_IF:
1792 c = expr_preprocess();
1793 goto do_if;
1794 case TOK_IFDEF:
1795 c = 0;
1796 do_ifdef:
1797 next_nomacro();
1798 if (tok < TOK_IDENT)
1799 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1800 if (is_bof) {
1801 if (c) {
1802 #ifdef INC_DEBUG
1803 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1804 #endif
1805 file->ifndef_macro = tok;
1808 c = (define_find(tok) != 0) ^ c;
1809 do_if:
1810 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1811 tcc_error("memory full (ifdef)");
1812 *s1->ifdef_stack_ptr++ = c;
1813 goto test_skip;
1814 case TOK_ELSE:
1815 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1816 tcc_error("#else without matching #if");
1817 if (s1->ifdef_stack_ptr[-1] & 2)
1818 tcc_error("#else after #else");
1819 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1820 goto test_else;
1821 case TOK_ELIF:
1822 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1823 tcc_error("#elif without matching #if");
1824 c = s1->ifdef_stack_ptr[-1];
1825 if (c > 1)
1826 tcc_error("#elif after #else");
1827 /* last #if/#elif expression was true: we skip */
1828 if (c == 1)
1829 goto skip;
1830 c = expr_preprocess();
1831 s1->ifdef_stack_ptr[-1] = c;
1832 test_else:
1833 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1834 file->ifndef_macro = 0;
1835 test_skip:
1836 if (!(c & 1)) {
1837 skip:
1838 preprocess_skip();
1839 is_bof = 0;
1840 goto redo;
1842 break;
1843 case TOK_ENDIF:
1844 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1845 tcc_error("#endif without matching #if");
1846 s1->ifdef_stack_ptr--;
1847 /* '#ifndef macro' was at the start of file. Now we check if
1848 an '#endif' is exactly at the end of file */
1849 if (file->ifndef_macro &&
1850 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1851 file->ifndef_macro_saved = file->ifndef_macro;
1852 /* need to set to zero to avoid false matches if another
1853 #ifndef at middle of file */
1854 file->ifndef_macro = 0;
1855 while (tok != TOK_LINEFEED)
1856 next_nomacro();
1857 tok_flags |= TOK_FLAG_ENDIF;
1858 goto the_end;
1860 break;
1861 case TOK_PPNUM:
1862 n = strtoul((char*)tokc.str.data, &q, 10);
1863 goto _line_num;
1864 case TOK_LINE:
1865 next();
1866 if (tok != TOK_CINT)
1867 _line_err:
1868 tcc_error("wrong #line format");
1869 n = tokc.i;
1870 _line_num:
1871 next();
1872 if (tok != TOK_LINEFEED) {
1873 if (tok == TOK_STR)
1874 pstrcpy(file->filename, sizeof(file->filename), (char *)tokc.str.data);
1875 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1876 break;
1877 else
1878 goto _line_err;
1879 --n;
1881 if (file->fd > 0)
1882 total_lines += file->line_num - n;
1883 file->line_num = n;
1884 if (s1->do_debug)
1885 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1886 break;
1887 case TOK_ERROR:
1888 case TOK_WARNING:
1889 c = tok;
1890 ch = file->buf_ptr[0];
1891 skip_spaces();
1892 q = buf;
1893 while (ch != '\n' && ch != CH_EOF) {
1894 if ((q - buf) < sizeof(buf) - 1)
1895 *q++ = ch;
1896 if (ch == '\\') {
1897 if (handle_stray_noerror() == 0)
1898 --q;
1899 } else
1900 inp();
1902 *q = '\0';
1903 if (c == TOK_ERROR)
1904 tcc_error("#error %s", buf);
1905 else
1906 tcc_warning("#warning %s", buf);
1907 break;
1908 case TOK_PRAGMA:
1909 pragma_parse(s1);
1910 break;
1911 case TOK_LINEFEED:
1912 goto the_end;
1913 default:
1914 /* ignore gas line comment in an 'S' file. */
1915 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1916 goto ignore;
1917 if (tok == '!' && is_bof)
1918 /* '!' is ignored at beginning to allow C scripts. */
1919 goto ignore;
1920 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1921 ignore:
1922 file->buf_ptr = parse_line_comment(file->buf_ptr);
1923 goto the_end;
1925 /* ignore other preprocess commands or #! for C scripts */
1926 while (tok != TOK_LINEFEED)
1927 next_nomacro();
1928 the_end:
1929 parse_flags = saved_parse_flags;
1932 /* evaluate escape codes in a string. */
1933 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1935 int c, n;
1936 const uint8_t *p;
1938 p = buf;
1939 for(;;) {
1940 c = *p;
1941 if (c == '\0')
1942 break;
1943 if (c == '\\') {
1944 p++;
1945 /* escape */
1946 c = *p;
1947 switch(c) {
1948 case '0': case '1': case '2': case '3':
1949 case '4': case '5': case '6': case '7':
1950 /* at most three octal digits */
1951 n = c - '0';
1952 p++;
1953 c = *p;
1954 if (isoct(c)) {
1955 n = n * 8 + c - '0';
1956 p++;
1957 c = *p;
1958 if (isoct(c)) {
1959 n = n * 8 + c - '0';
1960 p++;
1963 c = n;
1964 goto add_char_nonext;
1965 case 'x':
1966 case 'u':
1967 case 'U':
1968 p++;
1969 n = 0;
1970 for(;;) {
1971 c = *p;
1972 if (c >= 'a' && c <= 'f')
1973 c = c - 'a' + 10;
1974 else if (c >= 'A' && c <= 'F')
1975 c = c - 'A' + 10;
1976 else if (isnum(c))
1977 c = c - '0';
1978 else
1979 break;
1980 n = n * 16 + c;
1981 p++;
1983 c = n;
1984 goto add_char_nonext;
1985 case 'a':
1986 c = '\a';
1987 break;
1988 case 'b':
1989 c = '\b';
1990 break;
1991 case 'f':
1992 c = '\f';
1993 break;
1994 case 'n':
1995 c = '\n';
1996 break;
1997 case 'r':
1998 c = '\r';
1999 break;
2000 case 't':
2001 c = '\t';
2002 break;
2003 case 'v':
2004 c = '\v';
2005 break;
2006 case 'e':
2007 if (!gnu_ext)
2008 goto invalid_escape;
2009 c = 27;
2010 break;
2011 case '\'':
2012 case '\"':
2013 case '\\':
2014 case '?':
2015 break;
2016 default:
2017 invalid_escape:
2018 if (c >= '!' && c <= '~')
2019 tcc_warning("unknown escape sequence: \'\\%c\'", c);
2020 else
2021 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
2022 break;
2025 p++;
2026 add_char_nonext:
2027 if (!is_long)
2028 cstr_ccat(outstr, c);
2029 else
2030 cstr_wccat(outstr, c);
2032 /* add a trailing '\0' */
2033 if (!is_long)
2034 cstr_ccat(outstr, '\0');
2035 else
2036 cstr_wccat(outstr, '\0');
2039 static void parse_string(const char *s, int len)
2041 uint8_t buf[1000], *p = buf;
2042 int is_long, sep;
2044 if ((is_long = *s == 'L'))
2045 ++s, --len;
2046 sep = *s++;
2047 len -= 2;
2048 if (len >= sizeof buf)
2049 p = tcc_malloc(len + 1);
2050 memcpy(p, s, len);
2051 p[len] = 0;
2053 cstr_reset(&tokcstr);
2054 parse_escape_string(&tokcstr, p, is_long);
2055 if (p != buf)
2056 tcc_free(p);
2058 if (sep == '\'') {
2059 int char_size;
2060 /* XXX: make it portable */
2061 if (!is_long)
2062 char_size = 1;
2063 else
2064 char_size = sizeof(nwchar_t);
2065 if (tokcstr.size <= char_size)
2066 tcc_error("empty character constant");
2067 if (tokcstr.size > 2 * char_size)
2068 tcc_warning("multi-character character constant");
2069 if (!is_long) {
2070 tokc.i = *(int8_t *)tokcstr.data;
2071 tok = TOK_CCHAR;
2072 } else {
2073 tokc.i = *(nwchar_t *)tokcstr.data;
2074 tok = TOK_LCHAR;
2076 } else {
2077 tokc.str.size = tokcstr.size;
2078 tokc.str.data = tokcstr.data;
2079 tokc.str.data_allocated = tokcstr.data_allocated;
2080 if (!is_long)
2081 tok = TOK_STR;
2082 else
2083 tok = TOK_LSTR;
2087 /* we use 64 bit numbers */
2088 #define BN_SIZE 2
2090 /* bn = (bn << shift) | or_val */
2091 static void bn_lshift(unsigned int *bn, int shift, int or_val)
2093 int i;
2094 unsigned int v;
2095 for(i=0;i<BN_SIZE;i++) {
2096 v = bn[i];
2097 bn[i] = (v << shift) | or_val;
2098 or_val = v >> (32 - shift);
2102 static void bn_zero(unsigned int *bn)
2104 int i;
2105 for(i=0;i<BN_SIZE;i++) {
2106 bn[i] = 0;
2110 /* parse number in null terminated string 'p' and return it in the
2111 current token */
2112 static void parse_number(const char *p)
2114 int b, t, shift, frac_bits, s, exp_val, ch;
2115 char *q;
2116 unsigned int bn[BN_SIZE];
2117 double d;
2119 /* number */
2120 q = token_buf;
2121 ch = *p++;
2122 t = ch;
2123 ch = *p++;
2124 *q++ = t;
2125 b = 10;
2126 if (t == '.') {
2127 goto float_frac_parse;
2128 } else if (t == '0') {
2129 if (ch == 'x' || ch == 'X') {
2130 q--;
2131 ch = *p++;
2132 b = 16;
2133 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
2134 q--;
2135 ch = *p++;
2136 b = 2;
2139 /* parse all digits. cannot check octal numbers at this stage
2140 because of floating point constants */
2141 while (1) {
2142 if (ch >= 'a' && ch <= 'f')
2143 t = ch - 'a' + 10;
2144 else if (ch >= 'A' && ch <= 'F')
2145 t = ch - 'A' + 10;
2146 else if (isnum(ch))
2147 t = ch - '0';
2148 else
2149 break;
2150 if (t >= b)
2151 break;
2152 if (q >= token_buf + STRING_MAX_SIZE) {
2153 num_too_long:
2154 tcc_error("number too long");
2156 *q++ = ch;
2157 ch = *p++;
2159 if (ch == '.' ||
2160 ((ch == 'e' || ch == 'E') && b == 10) ||
2161 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2162 if (b != 10) {
2163 /* NOTE: strtox should support that for hexa numbers, but
2164 non ISOC99 libcs do not support it, so we prefer to do
2165 it by hand */
2166 /* hexadecimal or binary floats */
2167 /* XXX: handle overflows */
2168 *q = '\0';
2169 if (b == 16)
2170 shift = 4;
2171 else
2172 shift = 1;
2173 bn_zero(bn);
2174 q = token_buf;
2175 while (1) {
2176 t = *q++;
2177 if (t == '\0') {
2178 break;
2179 } else if (t >= 'a') {
2180 t = t - 'a' + 10;
2181 } else if (t >= 'A') {
2182 t = t - 'A' + 10;
2183 } else {
2184 t = t - '0';
2186 bn_lshift(bn, shift, t);
2188 frac_bits = 0;
2189 if (ch == '.') {
2190 ch = *p++;
2191 while (1) {
2192 t = ch;
2193 if (t >= 'a' && t <= 'f') {
2194 t = t - 'a' + 10;
2195 } else if (t >= 'A' && t <= 'F') {
2196 t = t - 'A' + 10;
2197 } else if (t >= '0' && t <= '9') {
2198 t = t - '0';
2199 } else {
2200 break;
2202 if (t >= b)
2203 tcc_error("invalid digit");
2204 bn_lshift(bn, shift, t);
2205 frac_bits += shift;
2206 ch = *p++;
2209 if (ch != 'p' && ch != 'P')
2210 expect("exponent");
2211 ch = *p++;
2212 s = 1;
2213 exp_val = 0;
2214 if (ch == '+') {
2215 ch = *p++;
2216 } else if (ch == '-') {
2217 s = -1;
2218 ch = *p++;
2220 if (ch < '0' || ch > '9')
2221 expect("exponent digits");
2222 while (ch >= '0' && ch <= '9') {
2223 exp_val = exp_val * 10 + ch - '0';
2224 ch = *p++;
2226 exp_val = exp_val * s;
2228 /* now we can generate the number */
2229 /* XXX: should patch directly float number */
2230 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2231 d = ldexp(d, exp_val - frac_bits);
2232 t = toup(ch);
2233 if (t == 'F') {
2234 ch = *p++;
2235 tok = TOK_CFLOAT;
2236 /* float : should handle overflow */
2237 tokc.f = (float)d;
2238 } else if (t == 'L') {
2239 ch = *p++;
2240 #ifdef TCC_TARGET_PE
2241 tok = TOK_CDOUBLE;
2242 tokc.d = d;
2243 #else
2244 tok = TOK_CLDOUBLE;
2245 /* XXX: not large enough */
2246 tokc.ld = (long double)d;
2247 #endif
2248 } else {
2249 tok = TOK_CDOUBLE;
2250 tokc.d = d;
2252 } else {
2253 /* decimal floats */
2254 if (ch == '.') {
2255 if (q >= token_buf + STRING_MAX_SIZE)
2256 goto num_too_long;
2257 *q++ = ch;
2258 ch = *p++;
2259 float_frac_parse:
2260 while (ch >= '0' && ch <= '9') {
2261 if (q >= token_buf + STRING_MAX_SIZE)
2262 goto num_too_long;
2263 *q++ = ch;
2264 ch = *p++;
2267 if (ch == 'e' || ch == 'E') {
2268 if (q >= token_buf + STRING_MAX_SIZE)
2269 goto num_too_long;
2270 *q++ = ch;
2271 ch = *p++;
2272 if (ch == '-' || ch == '+') {
2273 if (q >= token_buf + STRING_MAX_SIZE)
2274 goto num_too_long;
2275 *q++ = ch;
2276 ch = *p++;
2278 if (ch < '0' || ch > '9')
2279 expect("exponent digits");
2280 while (ch >= '0' && ch <= '9') {
2281 if (q >= token_buf + STRING_MAX_SIZE)
2282 goto num_too_long;
2283 *q++ = ch;
2284 ch = *p++;
2287 *q = '\0';
2288 t = toup(ch);
2289 errno = 0;
2290 if (t == 'F') {
2291 ch = *p++;
2292 tok = TOK_CFLOAT;
2293 tokc.f = strtof(token_buf, NULL);
2294 } else if (t == 'L') {
2295 ch = *p++;
2296 #ifdef TCC_TARGET_PE
2297 tok = TOK_CDOUBLE;
2298 tokc.d = strtod(token_buf, NULL);
2299 #else
2300 tok = TOK_CLDOUBLE;
2301 tokc.ld = strtold(token_buf, NULL);
2302 #endif
2303 } else {
2304 tok = TOK_CDOUBLE;
2305 tokc.d = strtod(token_buf, NULL);
2308 } else {
2309 unsigned long long n, n1;
2310 int lcount, ucount, must_64bit;
2311 const char *p1;
2313 /* integer number */
2314 *q = '\0';
2315 q = token_buf;
2316 if (b == 10 && *q == '0') {
2317 b = 8;
2318 q++;
2320 n = 0;
2321 while(1) {
2322 t = *q++;
2323 /* no need for checks except for base 10 / 8 errors */
2324 if (t == '\0')
2325 break;
2326 else if (t >= 'a')
2327 t = t - 'a' + 10;
2328 else if (t >= 'A')
2329 t = t - 'A' + 10;
2330 else
2331 t = t - '0';
2332 if (t >= b)
2333 tcc_error("invalid digit");
2334 n1 = n;
2335 n = n * b + t;
2336 /* detect overflow */
2337 /* XXX: this test is not reliable */
2338 if (n < n1)
2339 tcc_error("integer constant overflow");
2342 /* Determine the characteristics (unsigned and/or 64bit) the type of
2343 the constant must have according to the constant suffix(es) */
2344 lcount = ucount = must_64bit = 0;
2345 p1 = p;
2346 for(;;) {
2347 t = toup(ch);
2348 if (t == 'L') {
2349 if (lcount >= 2)
2350 tcc_error("three 'l's in integer constant");
2351 if (lcount && *(p - 1) != ch)
2352 tcc_error("incorrect integer suffix: %s", p1);
2353 lcount++;
2354 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2355 if (lcount == 2)
2356 #endif
2357 must_64bit = 1;
2358 ch = *p++;
2359 } else if (t == 'U') {
2360 if (ucount >= 1)
2361 tcc_error("two 'u's in integer constant");
2362 ucount++;
2363 ch = *p++;
2364 } else {
2365 break;
2369 /* Whether 64 bits are needed to hold the constant's value */
2370 if (n & 0xffffffff00000000LL || must_64bit) {
2371 tok = TOK_CLLONG;
2372 n1 = n >> 32;
2373 } else {
2374 tok = TOK_CINT;
2375 n1 = n;
2378 /* Whether type must be unsigned to hold the constant's value */
2379 if (ucount || ((n1 >> 31) && (b != 10))) {
2380 if (tok == TOK_CLLONG)
2381 tok = TOK_CULLONG;
2382 else
2383 tok = TOK_CUINT;
2384 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2385 } else if (n1 >> 31) {
2386 if (tok == TOK_CINT)
2387 tok = TOK_CLLONG;
2388 else
2389 tcc_error("integer constant overflow");
2392 tokc.i = n;
2394 if (ch)
2395 tcc_error("invalid number\n");
2399 #define PARSE2(c1, tok1, c2, tok2) \
2400 case c1: \
2401 PEEKC(c, p); \
2402 if (c == c2) { \
2403 p++; \
2404 tok = tok2; \
2405 } else { \
2406 tok = tok1; \
2408 break;
2410 /* return next token without macro substitution */
2411 static inline void next_nomacro1(void)
2413 int t, c, is_long, len;
2414 TokenSym *ts;
2415 uint8_t *p, *p1;
2416 unsigned int h;
2418 p = file->buf_ptr;
2419 redo_no_start:
2420 c = *p;
2421 #if (__TINYC__ || __GNUC__)
2422 #else
2423 if (c & 0x80)
2424 goto parse_ident_fast;
2425 #endif
2426 switch(c) {
2427 case ' ':
2428 case '\t':
2429 tok = c;
2430 p++;
2431 if (parse_flags & PARSE_FLAG_SPACES)
2432 goto keep_tok_flags;
2433 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2434 ++p;
2435 goto redo_no_start;
2436 case '\f':
2437 case '\v':
2438 case '\r':
2439 p++;
2440 goto redo_no_start;
2441 case '\\':
2442 /* first look if it is in fact an end of buffer */
2443 c = handle_stray1(p);
2444 p = file->buf_ptr;
2445 if (c == '\\')
2446 goto parse_simple;
2447 if (c != CH_EOF)
2448 goto redo_no_start;
2450 TCCState *s1 = tcc_state;
2451 if ((parse_flags & PARSE_FLAG_LINEFEED)
2452 && !(tok_flags & TOK_FLAG_EOF)) {
2453 tok_flags |= TOK_FLAG_EOF;
2454 tok = TOK_LINEFEED;
2455 goto keep_tok_flags;
2456 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2457 tok = TOK_EOF;
2458 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2459 tcc_error("missing #endif");
2460 } else if (s1->include_stack_ptr == s1->include_stack) {
2461 /* no include left : end of file. */
2462 tok = TOK_EOF;
2463 } else {
2464 tok_flags &= ~TOK_FLAG_EOF;
2465 /* pop include file */
2467 /* test if previous '#endif' was after a #ifdef at
2468 start of file */
2469 if (tok_flags & TOK_FLAG_ENDIF) {
2470 #ifdef INC_DEBUG
2471 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2472 #endif
2473 search_cached_include(s1, file->filename, 1)
2474 ->ifndef_macro = file->ifndef_macro_saved;
2475 tok_flags &= ~TOK_FLAG_ENDIF;
2478 /* add end of include file debug info */
2479 if (tcc_state->do_debug) {
2480 put_stabd(N_EINCL, 0, 0);
2482 /* pop include stack */
2483 tcc_close();
2484 s1->include_stack_ptr--;
2485 p = file->buf_ptr;
2486 goto redo_no_start;
2489 break;
2491 case '\n':
2492 file->line_num++;
2493 tok_flags |= TOK_FLAG_BOL;
2494 p++;
2495 maybe_newline:
2496 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2497 goto redo_no_start;
2498 tok = TOK_LINEFEED;
2499 goto keep_tok_flags;
2501 case '#':
2502 /* XXX: simplify */
2503 PEEKC(c, p);
2504 if ((tok_flags & TOK_FLAG_BOL) &&
2505 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2506 file->buf_ptr = p;
2507 preprocess(tok_flags & TOK_FLAG_BOF);
2508 p = file->buf_ptr;
2509 goto maybe_newline;
2510 } else {
2511 if (c == '#') {
2512 p++;
2513 tok = TOK_TWOSHARPS;
2514 } else {
2515 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2516 p = parse_line_comment(p - 1);
2517 goto redo_no_start;
2518 } else {
2519 tok = '#';
2523 break;
2525 /* dollar is allowed to start identifiers when not parsing asm */
2526 case '$':
2527 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2528 || (parse_flags & PARSE_FLAG_ASM_FILE))
2529 goto parse_simple;
2531 #if (__TINYC__ || __GNUC__)
2532 case 'a' ... 'z':
2533 case 'A' ... 'K':
2534 case 'M' ... 'Z':
2535 case '_':
2536 case 0x80 ... 0xFF:
2537 #else
2538 case 'a': case 'b': case 'c': case 'd':
2539 case 'e': case 'f': case 'g': case 'h':
2540 case 'i': case 'j': case 'k': case 'l':
2541 case 'm': case 'n': case 'o': case 'p':
2542 case 'q': case 'r': case 's': case 't':
2543 case 'u': case 'v': case 'w': case 'x':
2544 case 'y': case 'z':
2545 case 'A': case 'B': case 'C': case 'D':
2546 case 'E': case 'F': case 'G': case 'H':
2547 case 'I': case 'J': case 'K':
2548 case 'M': case 'N': case 'O': case 'P':
2549 case 'Q': case 'R': case 'S': case 'T':
2550 case 'U': case 'V': case 'W': case 'X':
2551 case 'Y': case 'Z':
2552 case '_':
2553 #endif
2554 parse_ident_fast:
2555 p1 = p;
2556 h = TOK_HASH_INIT;
2557 h = TOK_HASH_FUNC(h, c);
2558 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2559 h = TOK_HASH_FUNC(h, c);
2560 len = p - p1;
2561 if (c != '\\') {
2562 TokenSym **pts;
2564 /* fast case : no stray found, so we have the full token
2565 and we have already hashed it */
2566 h &= (TOK_HASH_SIZE - 1);
2567 pts = &hash_ident[h];
2568 for(;;) {
2569 ts = *pts;
2570 if (!ts)
2571 break;
2572 if (ts->len == len && !memcmp(ts->str, p1, len))
2573 goto token_found;
2574 pts = &(ts->hash_next);
2576 ts = tok_alloc_new(pts, (char *) p1, len);
2577 token_found: ;
2578 } else {
2579 /* slower case */
2580 cstr_reset(&tokcstr);
2581 cstr_cat(&tokcstr, p1, len);
2582 p--;
2583 PEEKC(c, p);
2584 parse_ident_slow:
2585 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2587 cstr_ccat(&tokcstr, c);
2588 PEEKC(c, p);
2590 ts = tok_alloc(tokcstr.data, tokcstr.size);
2592 tok = ts->tok;
2593 break;
2594 case 'L':
2595 t = p[1];
2596 if (t != '\\' && t != '\'' && t != '\"') {
2597 /* fast case */
2598 goto parse_ident_fast;
2599 } else {
2600 PEEKC(c, p);
2601 if (c == '\'' || c == '\"') {
2602 is_long = 1;
2603 goto str_const;
2604 } else {
2605 cstr_reset(&tokcstr);
2606 cstr_ccat(&tokcstr, 'L');
2607 goto parse_ident_slow;
2610 break;
2612 case '0': case '1': case '2': case '3':
2613 case '4': case '5': case '6': case '7':
2614 case '8': case '9':
2615 cstr_reset(&tokcstr);
2616 /* after the first digit, accept digits, alpha, '.' or sign if
2617 prefixed by 'eEpP' */
2618 parse_num:
2619 for(;;) {
2620 t = c;
2621 cstr_ccat(&tokcstr, c);
2622 PEEKC(c, p);
2623 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2624 || c == '.'
2625 || ((c == '+' || c == '-')
2626 && (t == 'e' || t == 'E' || t == 'p' || t == 'P')
2627 && !(parse_flags & PARSE_FLAG_ASM_FILE)
2629 break;
2631 /* We add a trailing '\0' to ease parsing */
2632 cstr_ccat(&tokcstr, '\0');
2633 tokc.str.size = tokcstr.size;
2634 tokc.str.data = tokcstr.data;
2635 tokc.str.data_allocated = tokcstr.data_allocated;
2636 tok = TOK_PPNUM;
2637 break;
2639 case '.':
2640 /* special dot handling because it can also start a number */
2641 PEEKC(c, p);
2642 if (isnum(c)) {
2643 cstr_reset(&tokcstr);
2644 cstr_ccat(&tokcstr, '.');
2645 goto parse_num;
2646 } else if ((parse_flags & PARSE_FLAG_ASM_FILE)
2647 && (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))) {
2648 *--p = c = '.';
2649 goto parse_ident_fast;
2650 } else if (c == '.') {
2651 PEEKC(c, p);
2652 if (c == '.') {
2653 p++;
2654 tok = TOK_DOTS;
2655 } else {
2656 *--p = '.'; /* may underflow into file->unget[] */
2657 tok = '.';
2659 } else {
2660 tok = '.';
2662 break;
2663 case '\'':
2664 case '\"':
2665 is_long = 0;
2666 str_const:
2667 cstr_reset(&tokcstr);
2668 if (is_long)
2669 cstr_ccat(&tokcstr, 'L');
2670 cstr_ccat(&tokcstr, c);
2671 p = parse_pp_string(p, c, &tokcstr);
2672 cstr_ccat(&tokcstr, c);
2673 cstr_ccat(&tokcstr, '\0');
2674 tokc.str.size = tokcstr.size;
2675 tokc.str.data = tokcstr.data;
2676 tokc.str.data_allocated = tokcstr.data_allocated;
2677 tok = TOK_PPSTR;
2678 break;
2680 case '<':
2681 PEEKC(c, p);
2682 if (c == '=') {
2683 p++;
2684 tok = TOK_LE;
2685 } else if (c == '<') {
2686 PEEKC(c, p);
2687 if (c == '=') {
2688 p++;
2689 tok = TOK_A_SHL;
2690 } else {
2691 tok = TOK_SHL;
2693 } else {
2694 tok = TOK_LT;
2696 break;
2697 case '>':
2698 PEEKC(c, p);
2699 if (c == '=') {
2700 p++;
2701 tok = TOK_GE;
2702 } else if (c == '>') {
2703 PEEKC(c, p);
2704 if (c == '=') {
2705 p++;
2706 tok = TOK_A_SAR;
2707 } else {
2708 tok = TOK_SAR;
2710 } else {
2711 tok = TOK_GT;
2713 break;
2715 case '&':
2716 PEEKC(c, p);
2717 if (c == '&') {
2718 p++;
2719 tok = TOK_LAND;
2720 } else if (c == '=') {
2721 p++;
2722 tok = TOK_A_AND;
2723 } else {
2724 tok = '&';
2726 break;
2728 case '|':
2729 PEEKC(c, p);
2730 if (c == '|') {
2731 p++;
2732 tok = TOK_LOR;
2733 } else if (c == '=') {
2734 p++;
2735 tok = TOK_A_OR;
2736 } else {
2737 tok = '|';
2739 break;
2741 case '+':
2742 PEEKC(c, p);
2743 if (c == '+') {
2744 p++;
2745 tok = TOK_INC;
2746 } else if (c == '=') {
2747 p++;
2748 tok = TOK_A_ADD;
2749 } else {
2750 tok = '+';
2752 break;
2754 case '-':
2755 PEEKC(c, p);
2756 if (c == '-') {
2757 p++;
2758 tok = TOK_DEC;
2759 } else if (c == '=') {
2760 p++;
2761 tok = TOK_A_SUB;
2762 } else if (c == '>') {
2763 p++;
2764 tok = TOK_ARROW;
2765 } else {
2766 tok = '-';
2768 break;
2770 PARSE2('!', '!', '=', TOK_NE)
2771 PARSE2('=', '=', '=', TOK_EQ)
2772 PARSE2('*', '*', '=', TOK_A_MUL)
2773 PARSE2('%', '%', '=', TOK_A_MOD)
2774 PARSE2('^', '^', '=', TOK_A_XOR)
2776 /* comments or operator */
2777 case '/':
2778 PEEKC(c, p);
2779 if (c == '*') {
2780 p = parse_comment(p);
2781 /* comments replaced by a blank */
2782 tok = ' ';
2783 goto keep_tok_flags;
2784 } else if (c == '/') {
2785 p = parse_line_comment(p);
2786 tok = ' ';
2787 goto keep_tok_flags;
2788 } else if (c == '=') {
2789 p++;
2790 tok = TOK_A_DIV;
2791 } else {
2792 tok = '/';
2794 break;
2796 /* simple tokens */
2797 case '(':
2798 case ')':
2799 case '[':
2800 case ']':
2801 case '{':
2802 case '}':
2803 case ',':
2804 case ';':
2805 case ':':
2806 case '?':
2807 case '~':
2808 case '@': /* only used in assembler */
2809 parse_simple:
2810 tok = c;
2811 p++;
2812 break;
2813 default:
2814 if (parse_flags & PARSE_FLAG_ASM_FILE)
2815 goto parse_simple;
2816 tcc_error("unrecognized character \\x%02x", c);
2817 break;
2819 tok_flags = 0;
2820 keep_tok_flags:
2821 file->buf_ptr = p;
2822 #if defined(PARSE_DEBUG)
2823 printf("token = %s\n", get_tok_str(tok, &tokc));
2824 #endif
2827 /* return next token without macro substitution. Can read input from
2828 macro_ptr buffer */
2829 static void next_nomacro_spc(void)
2831 if (macro_ptr) {
2832 redo:
2833 tok = *macro_ptr;
2834 if (tok) {
2835 TOK_GET(&tok, &macro_ptr, &tokc);
2836 if (tok == TOK_LINENUM) {
2837 file->line_num = tokc.i;
2838 goto redo;
2841 } else {
2842 next_nomacro1();
2846 ST_FUNC void next_nomacro(void)
2848 do {
2849 next_nomacro_spc();
2850 } while (tok < 256 && (isidnum_table[tok - CH_EOF] & IS_SPC));
2854 static void macro_subst(
2855 TokenString *tok_str,
2856 Sym **nested_list,
2857 const int *macro_str,
2858 int can_read_stream
2861 /* substitute arguments in replacement lists in macro_str by the values in
2862 args (field d) and return allocated string */
2863 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2865 int t, t0, t1, spc;
2866 const int *st;
2867 Sym *s;
2868 CValue cval;
2869 TokenString str;
2870 CString cstr;
2872 tok_str_new(&str);
2873 t0 = t1 = 0;
2874 while(1) {
2875 TOK_GET(&t, &macro_str, &cval);
2876 if (!t)
2877 break;
2878 if (t == '#') {
2879 /* stringize */
2880 TOK_GET(&t, &macro_str, &cval);
2881 if (!t)
2882 goto bad_stringy;
2883 s = sym_find2(args, t);
2884 if (s) {
2885 cstr_new(&cstr);
2886 cstr_ccat(&cstr, '\"');
2887 st = s->d;
2888 spc = 0;
2889 while (*st) {
2890 TOK_GET(&t, &st, &cval);
2891 if (t != TOK_PLCHLDR
2892 && t != TOK_NOSUBST
2893 && 0 == check_space(t, &spc)) {
2894 const char *s = get_tok_str(t, &cval);
2895 while (*s) {
2896 if (t == TOK_PPSTR && *s != '\'')
2897 add_char(&cstr, *s);
2898 else
2899 cstr_ccat(&cstr, *s);
2900 ++s;
2904 cstr.size -= spc;
2905 cstr_ccat(&cstr, '\"');
2906 cstr_ccat(&cstr, '\0');
2907 #ifdef PP_DEBUG
2908 printf("\nstringize: <%s>\n", (char *)cstr.data);
2909 #endif
2910 /* add string */
2911 cval.str.size = cstr.size;
2912 cval.str.data = cstr.data;
2913 cval.str.data_allocated = cstr.data_allocated;
2914 tok_str_add2(&str, TOK_PPSTR, &cval);
2915 cstr_free(&cstr);
2916 } else {
2917 bad_stringy:
2918 expect("macro parameter after '#'");
2920 } else if (t >= TOK_IDENT) {
2921 s = sym_find2(args, t);
2922 if (s) {
2923 int l0 = str.len;
2924 st = s->d;
2925 /* if '##' is present before or after, no arg substitution */
2926 if (*macro_str == TOK_TWOSHARPS || t1 == TOK_TWOSHARPS) {
2927 /* special case for var arg macros : ## eats the ','
2928 if empty VA_ARGS variable. */
2929 if (t1 == TOK_TWOSHARPS && t0 == ',' && gnu_ext && s->type.t) {
2930 if (*st == 0) {
2931 /* suppress ',' '##' */
2932 str.len -= 2;
2933 } else {
2934 /* suppress '##' and add variable */
2935 str.len--;
2936 goto add_var;
2938 } else {
2939 for(;;) {
2940 int t1;
2941 TOK_GET(&t1, &st, &cval);
2942 if (!t1)
2943 break;
2944 tok_str_add2(&str, t1, &cval);
2948 } else {
2949 add_var:
2950 /* NOTE: the stream cannot be read when macro
2951 substituing an argument */
2952 macro_subst(&str, nested_list, st, 0);
2954 if (str.len == l0) /* exanded to empty string */
2955 tok_str_add(&str, TOK_PLCHLDR);
2956 } else {
2957 tok_str_add(&str, t);
2959 } else {
2960 tok_str_add2(&str, t, &cval);
2962 t0 = t1, t1 = t;
2964 tok_str_add(&str, 0);
2965 return str.str;
2968 static char const ab_month_name[12][4] =
2970 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2971 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2974 /* peek or read [ws_str == NULL] next token from function macro call,
2975 walking up macro levels up to the file if necessary */
2976 static int next_argstream(Sym **nested_list, int can_read_stream, TokenString *ws_str)
2978 int t;
2979 const int *p;
2980 Sym *sa;
2982 for (;;) {
2983 if (macro_ptr) {
2984 p = macro_ptr, t = *p;
2985 if (ws_str) {
2986 while (is_space(t) || TOK_LINEFEED == t)
2987 tok_str_add(ws_str, t), t = *++p;
2989 if (t == 0 && can_read_stream) {
2990 end_macro();
2991 /* also, end of scope for nested defined symbol */
2992 sa = *nested_list;
2993 while (sa && sa->v == 0)
2994 sa = sa->prev;
2995 if (sa)
2996 sa->v = 0;
2997 continue;
2999 } else {
3000 ch = handle_eob();
3001 if (ws_str) {
3002 while (is_space(ch) || ch == '\n' || ch == '/') {
3003 if (ch == '/') {
3004 int c;
3005 uint8_t *p = file->buf_ptr;
3006 PEEKC(c, p);
3007 if (c == '*') {
3008 p = parse_comment(p);
3009 file->buf_ptr = p - 1;
3010 } else if (c == '/') {
3011 p = parse_line_comment(p);
3012 file->buf_ptr = p - 1;
3013 } else
3014 break;
3015 ch = ' ';
3017 tok_str_add(ws_str, ch);
3018 cinp();
3021 t = ch;
3024 if (ws_str)
3025 return t;
3026 next_nomacro_spc();
3027 return tok;
3031 /* do macro substitution of current token with macro 's' and add
3032 result to (tok_str,tok_len). 'nested_list' is the list of all
3033 macros we got inside to avoid recursing. Return non zero if no
3034 substitution needs to be done */
3035 static int macro_subst_tok(
3036 TokenString *tok_str,
3037 Sym **nested_list,
3038 Sym *s,
3039 int can_read_stream)
3041 Sym *args, *sa, *sa1;
3042 int parlevel, *mstr, t, t1, spc;
3043 TokenString str;
3044 char *cstrval;
3045 CValue cval;
3046 CString cstr;
3047 char buf[32];
3049 /* if symbol is a macro, prepare substitution */
3050 /* special macros */
3051 if (tok == TOK___LINE__) {
3052 snprintf(buf, sizeof(buf), "%d", file->line_num);
3053 cstrval = buf;
3054 t1 = TOK_PPNUM;
3055 goto add_cstr1;
3056 } else if (tok == TOK___FILE__) {
3057 cstrval = file->filename;
3058 goto add_cstr;
3059 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
3060 time_t ti;
3061 struct tm *tm;
3063 time(&ti);
3064 tm = localtime(&ti);
3065 if (tok == TOK___DATE__) {
3066 snprintf(buf, sizeof(buf), "%s %2d %d",
3067 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
3068 } else {
3069 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
3070 tm->tm_hour, tm->tm_min, tm->tm_sec);
3072 cstrval = buf;
3073 add_cstr:
3074 t1 = TOK_STR;
3075 add_cstr1:
3076 cstr_new(&cstr);
3077 cstr_cat(&cstr, cstrval, 0);
3078 cval.str.size = cstr.size;
3079 cval.str.data = cstr.data;
3080 cval.str.data_allocated = cstr.data_allocated;
3081 tok_str_add2(tok_str, t1, &cval);
3082 cstr_free(&cstr);
3083 } else {
3084 int saved_parse_flags = parse_flags;
3086 mstr = s->d;
3087 if (s->type.t == MACRO_FUNC) {
3088 /* whitespace between macro name and argument list */
3089 TokenString ws_str;
3090 tok_str_new(&ws_str);
3092 spc = 0;
3093 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
3094 | PARSE_FLAG_ACCEPT_STRAYS;
3096 /* get next token from argument stream */
3097 t = next_argstream(nested_list, can_read_stream, &ws_str);
3098 if (t != '(') {
3099 /* not a macro substitution after all, restore the
3100 * macro token plus all whitespace we've read.
3101 * whitespace is intentionally not merged to preserve
3102 * newlines. */
3103 parse_flags = saved_parse_flags;
3104 tok_str_add(tok_str, tok);
3105 if (parse_flags & PARSE_FLAG_SPACES) {
3106 int i;
3107 for (i = 0; i < ws_str.len; i++)
3108 tok_str_add(tok_str, ws_str.str[i]);
3110 tok_str_free(ws_str.str);
3111 return 0;
3112 } else {
3113 tok_str_free(ws_str.str);
3115 next_nomacro(); /* eat '(' */
3117 /* argument macro */
3118 args = NULL;
3119 sa = s->next;
3120 /* NOTE: empty args are allowed, except if no args */
3121 for(;;) {
3122 do {
3123 next_argstream(nested_list, can_read_stream, NULL);
3124 } while (is_space(tok) || TOK_LINEFEED == tok);
3125 empty_arg:
3126 /* handle '()' case */
3127 if (!args && !sa && tok == ')')
3128 break;
3129 if (!sa)
3130 tcc_error("macro '%s' used with too many args",
3131 get_tok_str(s->v, 0));
3132 tok_str_new(&str);
3133 parlevel = spc = 0;
3134 /* NOTE: non zero sa->t indicates VA_ARGS */
3135 while ((parlevel > 0 ||
3136 (tok != ')' &&
3137 (tok != ',' || sa->type.t)))) {
3138 if (tok == TOK_EOF || tok == 0)
3139 break;
3140 if (tok == '(')
3141 parlevel++;
3142 else if (tok == ')')
3143 parlevel--;
3144 if (tok == TOK_LINEFEED)
3145 tok = ' ';
3146 if (!check_space(tok, &spc))
3147 tok_str_add2(&str, tok, &tokc);
3148 next_argstream(nested_list, can_read_stream, NULL);
3150 if (parlevel)
3151 expect(")");
3152 str.len -= spc;
3153 tok_str_add(&str, 0);
3154 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3155 sa1->d = str.str;
3156 sa = sa->next;
3157 if (tok == ')') {
3158 /* special case for gcc var args: add an empty
3159 var arg argument if it is omitted */
3160 if (sa && sa->type.t && gnu_ext)
3161 goto empty_arg;
3162 break;
3164 if (tok != ',')
3165 expect(",");
3167 if (sa) {
3168 tcc_error("macro '%s' used with too few args",
3169 get_tok_str(s->v, 0));
3172 parse_flags = saved_parse_flags;
3174 /* now subst each arg */
3175 mstr = macro_arg_subst(nested_list, mstr, args);
3176 /* free memory */
3177 sa = args;
3178 while (sa) {
3179 sa1 = sa->prev;
3180 tok_str_free(sa->d);
3181 sym_free(sa);
3182 sa = sa1;
3186 sym_push2(nested_list, s->v, 0, 0);
3187 parse_flags = saved_parse_flags;
3188 macro_subst(tok_str, nested_list, mstr, can_read_stream | 2);
3190 /* pop nested defined symbol */
3191 sa1 = *nested_list;
3192 *nested_list = sa1->prev;
3193 sym_free(sa1);
3194 if (mstr != s->d)
3195 tok_str_free(mstr);
3197 return 0;
3200 static int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3202 CString cstr;
3203 int n;
3205 cstr_new(&cstr);
3206 if (t1 != TOK_PLCHLDR)
3207 cstr_cat(&cstr, get_tok_str(t1, v1), -1);
3208 n = cstr.size;
3209 if (t2 != TOK_PLCHLDR)
3210 cstr_cat(&cstr, get_tok_str(t2, v2), -1);
3211 cstr_ccat(&cstr, '\0');
3213 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3214 memcpy(file->buffer, cstr.data, cstr.size);
3215 for (;;) {
3216 next_nomacro1();
3217 if (0 == *file->buf_ptr)
3218 break;
3219 if (is_space(tok))
3220 continue;
3221 tcc_warning("pasting <%.*s> and <%s> does not give a valid preprocessing token",
3222 n, cstr.data, (char*)cstr.data + n);
3223 break;
3225 tcc_close();
3227 //printf("paste <%s>\n", (char*)cstr.data);
3228 cstr_free(&cstr);
3229 return 0;
3232 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3233 return the resulting string (which must be freed). */
3234 static inline int *macro_twosharps(const int *ptr0)
3236 int t;
3237 CValue cval;
3238 TokenString macro_str1;
3239 int start_of_nosubsts = -1;
3240 const int *ptr;
3242 /* we search the first '##' */
3243 for (ptr = ptr0;;) {
3244 TOK_GET(&t, &ptr, &cval);
3245 if (t == TOK_TWOSHARPS)
3246 break;
3247 if (t == 0)
3248 return NULL;
3251 tok_str_new(&macro_str1);
3253 //tok_print(" $$$", ptr0);
3254 for (ptr = ptr0;;) {
3255 TOK_GET(&t, &ptr, &cval);
3256 if (t == 0)
3257 break;
3258 if (t == TOK_TWOSHARPS)
3259 continue;
3260 while (*ptr == TOK_TWOSHARPS) {
3261 int t1; CValue cv1;
3262 /* given 'a##b', remove nosubsts preceding 'a' */
3263 if (start_of_nosubsts >= 0)
3264 macro_str1.len = start_of_nosubsts;
3265 /* given 'a##b', remove nosubsts preceding 'b' */
3266 while ((t1 = *++ptr) == TOK_NOSUBST)
3268 if (t1 && t1 != TOK_TWOSHARPS
3269 && t1 != ':') /* 'a##:' don't build a new token */
3271 TOK_GET(&t1, &ptr, &cv1);
3272 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3273 paste_tokens(t, &cval, t1, &cv1);
3274 t = tok, cval = tokc;
3278 if (t == TOK_NOSUBST) {
3279 if (start_of_nosubsts < 0)
3280 start_of_nosubsts = macro_str1.len;
3281 } else {
3282 start_of_nosubsts = -1;
3284 tok_str_add2(&macro_str1, t, &cval);
3286 tok_str_add(&macro_str1, 0);
3287 //tok_print(" ###", macro_str1.str);
3288 return macro_str1.str;
3291 /* do macro substitution of macro_str and add result to
3292 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3293 inside to avoid recursing. */
3294 static void macro_subst(
3295 TokenString *tok_str,
3296 Sym **nested_list,
3297 const int *macro_str,
3298 int can_read_stream
3301 Sym *s;
3302 const int *ptr;
3303 int t, spc, nosubst;
3304 CValue cval;
3305 int *macro_str1 = NULL;
3307 /* first scan for '##' operator handling */
3308 ptr = macro_str;
3309 spc = nosubst = 0;
3311 /* first scan for '##' operator handling */
3312 if (can_read_stream & 1) {
3313 macro_str1 = macro_twosharps(ptr);
3314 if (macro_str1)
3315 ptr = macro_str1;
3318 while (1) {
3319 TOK_GET(&t, &ptr, &cval);
3320 if (t == 0)
3321 break;
3323 if (t >= TOK_IDENT && 0 == nosubst) {
3324 s = define_find(t);
3325 if (s == NULL)
3326 goto no_subst;
3328 /* if nested substitution, do nothing */
3329 if (sym_find2(*nested_list, t)) {
3330 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3331 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3332 goto no_subst;
3336 TokenString str;
3337 str.str = (int*)ptr;
3338 begin_macro(&str, 2);
3340 tok = t;
3341 macro_subst_tok(tok_str, nested_list, s, can_read_stream);
3343 if (str.alloc == 3) {
3344 /* already finished by reading function macro arguments */
3345 break;
3348 ptr = macro_ptr;
3349 end_macro ();
3352 spc = (tok_str->len &&
3353 is_space(tok_last(tok_str->str,
3354 tok_str->str + tok_str->len)));
3356 } else {
3358 if (t == '\\' && !(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3359 tcc_error("stray '\\' in program");
3361 no_subst:
3362 if (!check_space(t, &spc))
3363 tok_str_add2(tok_str, t, &cval);
3364 nosubst = 0;
3365 if (t == TOK_NOSUBST)
3366 nosubst = 1;
3369 if (macro_str1)
3370 tok_str_free(macro_str1);
3374 /* return next token with macro substitution */
3375 ST_FUNC void next(void)
3377 redo:
3378 if (parse_flags & PARSE_FLAG_SPACES)
3379 next_nomacro_spc();
3380 else
3381 next_nomacro();
3383 if (macro_ptr) {
3384 if (tok == TOK_NOSUBST || tok == TOK_PLCHLDR) {
3385 /* discard preprocessor markers */
3386 goto redo;
3387 } else if (tok == 0) {
3388 /* end of macro or unget token string */
3389 end_macro();
3390 goto redo;
3392 } else if (tok >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3393 Sym *s;
3394 /* if reading from file, try to substitute macros */
3395 s = define_find(tok);
3396 if (s) {
3397 Sym *nested_list = NULL;
3398 tokstr_buf.len = 0;
3399 nested_list = NULL;
3400 macro_subst_tok(&tokstr_buf, &nested_list, s, 1);
3401 tok_str_add(&tokstr_buf, 0);
3402 begin_macro(&tokstr_buf, 2);
3403 goto redo;
3406 /* convert preprocessor tokens into C tokens */
3407 if (tok == TOK_PPNUM) {
3408 if (parse_flags & PARSE_FLAG_TOK_NUM)
3409 parse_number((char *)tokc.str.data);
3410 } else if (tok == TOK_PPSTR) {
3411 if (parse_flags & PARSE_FLAG_TOK_STR)
3412 parse_string((char *)tokc.str.data, tokc.str.size - 1);
3416 /* push back current token and set current token to 'last_tok'. Only
3417 identifier case handled for labels. */
3418 ST_INLN void unget_tok(int last_tok)
3420 TokenString *str = tcc_malloc(sizeof *str);
3421 tok_str_new(str);
3422 tok_str_add2(str, tok, &tokc);
3423 tok_str_add(str, 0);
3424 begin_macro(str, 1);
3425 tok = last_tok;
3428 ST_FUNC void preprocess_init(TCCState *s1)
3430 s1->include_stack_ptr = s1->include_stack;
3431 /* XXX: move that before to avoid having to initialize
3432 file->ifdef_stack_ptr ? */
3433 s1->ifdef_stack_ptr = s1->ifdef_stack;
3434 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3435 pp_once++;
3437 pvtop = vtop = vstack - 1;
3438 s1->pack_stack[0] = 0;
3439 s1->pack_stack_ptr = s1->pack_stack;
3441 isidnum_table['$' - CH_EOF] =
3442 s1->dollars_in_identifiers ? IS_ID : 0;
3443 isidnum_table['.' - CH_EOF] =
3444 (parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0;
3447 ST_FUNC void preprocess_new(void)
3449 int i, c;
3450 const char *p, *r;
3452 /* init isid table */
3453 for(i = CH_EOF; i<128; i++)
3454 isidnum_table[i - CH_EOF]
3455 = is_space(i) ? IS_SPC
3456 : isid(i) ? IS_ID
3457 : isnum(i) ? IS_NUM
3458 : 0;
3460 for(i = 128; i<256; i++)
3461 isidnum_table[i - CH_EOF] = IS_ID;
3463 /* init allocators */
3464 tal_new(&toksym_alloc, TOKSYM_TAL_LIMIT, TOKSYM_TAL_SIZE);
3465 tal_new(&tokstr_alloc, TOKSTR_TAL_LIMIT, TOKSTR_TAL_SIZE);
3466 tal_new(&cstr_alloc, CSTR_TAL_LIMIT, CSTR_TAL_SIZE);
3468 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3469 cstr_new(&cstr_buf);
3470 cstr_realloc(&cstr_buf, STRING_MAX_SIZE);
3471 tok_str_new(&tokstr_buf);
3472 tok_str_realloc(&tokstr_buf, TOKSTR_MAX_SIZE);
3474 tok_ident = TOK_IDENT;
3475 p = tcc_keywords;
3476 while (*p) {
3477 r = p;
3478 for(;;) {
3479 c = *r++;
3480 if (c == '\0')
3481 break;
3483 tok_alloc(p, r - p - 1);
3484 p = r;
3488 ST_FUNC void preprocess_delete(void)
3490 int i, n;
3492 /* free -D and compiler defines */
3493 free_defines(NULL);
3495 /* cleanup from error/setjmp */
3496 while (macro_stack)
3497 end_macro();
3498 macro_ptr = NULL;
3500 /* free tokens */
3501 n = tok_ident - TOK_IDENT;
3502 for(i = 0; i < n; i++)
3503 tal_free(toksym_alloc, table_ident[i]);
3504 tcc_free(table_ident);
3505 table_ident = NULL;
3507 /* free static buffers */
3508 cstr_free(&tokcstr);
3509 cstr_free(&cstr_buf);
3510 tok_str_free(tokstr_buf.str);
3512 /* free allocators */
3513 tal_delete(toksym_alloc);
3514 toksym_alloc = NULL;
3515 tal_delete(tokstr_alloc);
3516 tokstr_alloc = NULL;
3517 tal_delete(cstr_alloc);
3518 cstr_alloc = NULL;
3521 /* ------------------------------------------------------------------------- */
3522 /* tcc -E [-P[1]] [-dD} support */
3524 static void tok_print(const char *msg, const int *str)
3526 FILE *fp;
3527 int t;
3528 CValue cval;
3530 fp = tcc_state->ppfp;
3531 if (!fp || !tcc_state->dflag)
3532 fp = stdout;
3534 fprintf(fp, "%s ", msg);
3535 while (str) {
3536 TOK_GET(&t, &str, &cval);
3537 if (!t)
3538 break;
3539 fprintf(fp,"%s", get_tok_str(t, &cval));
3541 fprintf(fp, "\n");
3544 static void pp_line(TCCState *s1, BufferedFile *f, int level)
3546 int d = f->line_num - f->line_ref;
3548 if (s1->dflag & 4)
3549 return;
3551 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE) {
3552 if (level == 0 && f->line_ref && d) {
3553 d = 1;
3554 goto simple;
3556 } else if (level == 0 && f->line_ref && d < 8) {
3557 simple:
3558 while (d > 0)
3559 fputs("\n", s1->ppfp), --d;
3560 } else if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
3561 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
3562 } else {
3563 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
3564 level > 0 ? " 1" : level < 0 ? " 2" : "");
3566 f->line_ref = f->line_num;
3569 static void define_print(TCCState *s1, int v)
3571 FILE *fp;
3572 Sym *s;
3574 s = define_find(v);
3575 if (NULL == s || NULL == s->d)
3576 return;
3578 fp = s1->ppfp;
3579 fprintf(fp, "#define %s", get_tok_str(v, NULL));
3580 if (s->type.t == MACRO_FUNC) {
3581 Sym *a = s->next;
3582 fprintf(fp,"(");
3583 if (a)
3584 for (;;) {
3585 fprintf(fp,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
3586 if (!(a = a->next))
3587 break;
3588 fprintf(fp,",");
3590 fprintf(fp,")");
3592 tok_print("", s->d);
3595 static void pp_debug_defines(TCCState *s1)
3597 int v, t;
3598 const char *vs;
3599 FILE *fp;
3601 t = pp_debug_tok;
3602 if (t == 0)
3603 return;
3605 file->line_num--;
3606 pp_line(s1, file, 0);
3607 file->line_ref = ++file->line_num;
3609 fp = s1->ppfp;
3610 v = pp_debug_symv;
3611 vs = get_tok_str(v, NULL);
3612 if (t == TOK_DEFINE) {
3613 define_print(s1, v);
3614 } else if (t == TOK_UNDEF) {
3615 fprintf(fp, "#undef %s\n", vs);
3616 } else if (t == TOK_push_macro) {
3617 fprintf(fp, "#pragma push_macro(\"%s\")\n", vs);
3618 } else if (t == TOK_pop_macro) {
3619 fprintf(fp, "#pragma pop_macro(\"%s\")\n", vs);
3621 pp_debug_tok = 0;
3624 static void pp_debug_builtins(TCCState *s1)
3626 int v;
3627 for (v = TOK_IDENT; v < tok_ident; ++v)
3628 define_print(s1, v);
3631 static int need_space(int prev_tok, int tok, const char *tokstr)
3633 const char *sp_chars = "";
3634 if ((prev_tok >= TOK_IDENT || prev_tok == TOK_PPNUM) &&
3635 (tok >= TOK_IDENT || tok == TOK_PPNUM))
3636 return 1;
3637 switch (prev_tok) {
3638 case '+':
3639 sp_chars = "+=";
3640 break;
3641 case '-':
3642 sp_chars = "-=>";
3643 break;
3644 case '*':
3645 case '/':
3646 case '%':
3647 case '^':
3648 case '=':
3649 case '!':
3650 case TOK_A_SHL:
3651 case TOK_A_SAR:
3652 sp_chars = "=";
3653 break;
3654 case '&':
3655 sp_chars = "&=";
3656 break;
3657 case '|':
3658 sp_chars = "|=";
3659 break;
3660 case '<':
3661 sp_chars = "<=";
3662 break;
3663 case '>':
3664 sp_chars = ">=";
3665 break;
3666 case '.':
3667 sp_chars = ".";
3668 break;
3669 case '#':
3670 sp_chars = "#";
3671 break;
3672 case TOK_PPNUM:
3673 sp_chars = "+-";
3674 break;
3676 return !!strchr(sp_chars, tokstr[0]);
3679 /* Preprocess the current file */
3680 ST_FUNC int tcc_preprocess(TCCState *s1)
3682 BufferedFile **iptr;
3683 int token_seen, spcs, level;
3684 Sym *define_start;
3685 const char *tokstr;
3687 preprocess_init(s1);
3688 ch = file->buf_ptr[0];
3689 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3690 parse_flags = PARSE_FLAG_PREPROCESS
3691 | (parse_flags & PARSE_FLAG_ASM_FILE)
3692 | PARSE_FLAG_LINEFEED
3693 | PARSE_FLAG_SPACES
3694 | PARSE_FLAG_ACCEPT_STRAYS
3696 define_start = define_stack;
3698 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3699 capability to compile and run itself, provided all numbers are
3700 given as decimals. tcc -E -P10 will do. */
3701 if (s1->Pflag == 1 + 10)
3702 parse_flags |= PARSE_FLAG_TOK_NUM, s1->Pflag = 1;
3704 #ifdef PP_BENCH
3705 /* for PP benchmarks */
3706 do next(); while (tok != TOK_EOF); return 0;
3707 #endif
3709 if (s1->dflag & 1) {
3710 pp_debug_builtins(s1);
3711 s1->dflag &= ~1;
3714 token_seen = TOK_LINEFEED, spcs = 0;
3715 pp_line(s1, file, 0);
3717 for (;;) {
3718 iptr = s1->include_stack_ptr;
3719 next();
3720 if (tok == TOK_EOF)
3721 break;
3722 level = s1->include_stack_ptr - iptr;
3723 if (level) {
3724 if (level > 0)
3725 pp_line(s1, *iptr, 0);
3726 pp_line(s1, file, level);
3729 if (s1->dflag) {
3730 pp_debug_defines(s1);
3731 if (s1->dflag & 4)
3732 continue;
3735 if (token_seen == TOK_LINEFEED) {
3736 if (tok == ' ') {
3737 ++spcs;
3738 continue;
3740 if (tok == TOK_LINEFEED) {
3741 spcs = 0;
3742 continue;
3744 pp_line(s1, file, 0);
3745 } else if (tok == TOK_LINEFEED) {
3746 ++file->line_ref;
3749 tokstr = get_tok_str(tok, &tokc);
3750 if (!spcs && need_space(token_seen, tok, tokstr))
3751 ++spcs;
3752 while (spcs)
3753 fputs(" ", s1->ppfp), --spcs;
3754 fputs(tokstr, s1->ppfp);
3756 token_seen = tok;
3758 /* reset define stack, but keep -D and built-ins */
3759 free_defines(define_start);
3760 return 0;
3763 /* ------------------------------------------------------------------------- */