move some global variables into TCCState
[tinycc.git] / tccpp.c
blobb327a6452d944806eb2b76accfc341a87329351d
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
22 static const char tcc_keywords[] =
23 #define DEF(id, str) str "\0"
24 #include "tcctok.h"
25 #undef DEF
28 /* WARNING: the content of this string encodes token numbers */
29 static char tok_two_chars[] = "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
31 /* true if isid(c) || isnum(c) */
32 static unsigned char isidnum_table[256-CH_EOF];
35 /* allocate a new token */
36 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
38 TokenSym *ts, **ptable;
39 int i;
41 if (tok_ident >= SYM_FIRST_ANOM)
42 error("memory full");
44 /* expand token table if needed */
45 i = tok_ident - TOK_IDENT;
46 if ((i % TOK_ALLOC_INCR) == 0) {
47 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
48 if (!ptable)
49 error("memory full");
50 table_ident = ptable;
53 ts = tcc_malloc(sizeof(TokenSym) + len);
54 table_ident[i] = ts;
55 ts->tok = tok_ident++;
56 ts->sym_define = NULL;
57 ts->sym_label = NULL;
58 ts->sym_struct = NULL;
59 ts->sym_identifier = NULL;
60 ts->len = len;
61 ts->hash_next = NULL;
62 memcpy(ts->str, str, len);
63 ts->str[len] = '\0';
64 *pts = ts;
65 return ts;
68 #define TOK_HASH_INIT 1
69 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
71 /* find a token and add it if not found */
72 static TokenSym *tok_alloc(const char *str, int len)
74 TokenSym *ts, **pts;
75 int i;
76 unsigned int h;
78 h = TOK_HASH_INIT;
79 for(i=0;i<len;i++)
80 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
81 h &= (TOK_HASH_SIZE - 1);
83 pts = &hash_ident[h];
84 for(;;) {
85 ts = *pts;
86 if (!ts)
87 break;
88 if (ts->len == len && !memcmp(ts->str, str, len))
89 return ts;
90 pts = &(ts->hash_next);
92 return tok_alloc_new(pts, str, len);
95 /* XXX: buffer overflow */
96 /* XXX: float tokens */
97 char *get_tok_str(int v, CValue *cv)
99 static char buf[STRING_MAX_SIZE + 1];
100 static CString cstr_buf;
101 CString *cstr;
102 unsigned char *q;
103 char *p;
104 int i, len;
106 /* NOTE: to go faster, we give a fixed buffer for small strings */
107 cstr_reset(&cstr_buf);
108 cstr_buf.data = buf;
109 cstr_buf.size_allocated = sizeof(buf);
110 p = buf;
112 switch(v) {
113 case TOK_CINT:
114 case TOK_CUINT:
115 /* XXX: not quite exact, but only useful for testing */
116 sprintf(p, "%u", cv->ui);
117 break;
118 case TOK_CLLONG:
119 case TOK_CULLONG:
120 /* XXX: not quite exact, but only useful for testing */
121 sprintf(p, "%Lu", cv->ull);
122 break;
123 case TOK_LCHAR:
124 cstr_ccat(&cstr_buf, 'L');
125 case TOK_CCHAR:
126 cstr_ccat(&cstr_buf, '\'');
127 add_char(&cstr_buf, cv->i);
128 cstr_ccat(&cstr_buf, '\'');
129 cstr_ccat(&cstr_buf, '\0');
130 break;
131 case TOK_PPNUM:
132 cstr = cv->cstr;
133 len = cstr->size - 1;
134 for(i=0;i<len;i++)
135 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
136 cstr_ccat(&cstr_buf, '\0');
137 break;
138 case TOK_LSTR:
139 cstr_ccat(&cstr_buf, 'L');
140 case TOK_STR:
141 cstr = cv->cstr;
142 cstr_ccat(&cstr_buf, '\"');
143 if (v == TOK_STR) {
144 len = cstr->size - 1;
145 for(i=0;i<len;i++)
146 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
147 } else {
148 len = (cstr->size / sizeof(nwchar_t)) - 1;
149 for(i=0;i<len;i++)
150 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
152 cstr_ccat(&cstr_buf, '\"');
153 cstr_ccat(&cstr_buf, '\0');
154 break;
155 case TOK_LT:
156 v = '<';
157 goto addv;
158 case TOK_GT:
159 v = '>';
160 goto addv;
161 case TOK_DOTS:
162 return strcpy(p, "...");
163 case TOK_A_SHL:
164 return strcpy(p, "<<=");
165 case TOK_A_SAR:
166 return strcpy(p, ">>=");
167 default:
168 if (v < TOK_IDENT) {
169 /* search in two bytes table */
170 q = tok_two_chars;
171 while (*q) {
172 if (q[2] == v) {
173 *p++ = q[0];
174 *p++ = q[1];
175 *p = '\0';
176 return buf;
178 q += 3;
180 addv:
181 *p++ = v;
182 *p = '\0';
183 } else if (v < tok_ident) {
184 return table_ident[v - TOK_IDENT]->str;
185 } else if (v >= SYM_FIRST_ANOM) {
186 /* special name for anonymous symbol */
187 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
188 } else {
189 /* should never happen */
190 return NULL;
192 break;
194 return cstr_buf.data;
197 /* fill input buffer and peek next char */
198 static int tcc_peekc_slow(BufferedFile *bf)
200 int len;
201 /* only tries to read if really end of buffer */
202 if (bf->buf_ptr >= bf->buf_end) {
203 if (bf->fd != -1) {
204 #if defined(PARSE_DEBUG)
205 len = 8;
206 #else
207 len = IO_BUF_SIZE;
208 #endif
209 len = read(bf->fd, bf->buffer, len);
210 if (len < 0)
211 len = 0;
212 } else {
213 len = 0;
215 total_bytes += len;
216 bf->buf_ptr = bf->buffer;
217 bf->buf_end = bf->buffer + len;
218 *bf->buf_end = CH_EOB;
220 if (bf->buf_ptr < bf->buf_end) {
221 return bf->buf_ptr[0];
222 } else {
223 bf->buf_ptr = bf->buf_end;
224 return CH_EOF;
228 /* return the current character, handling end of block if necessary
229 (but not stray) */
230 static int handle_eob(void)
232 return tcc_peekc_slow(file);
235 /* read next char from current input file and handle end of input buffer */
236 static inline void inp(void)
238 ch = *(++(file->buf_ptr));
239 /* end of buffer/file handling */
240 if (ch == CH_EOB)
241 ch = handle_eob();
244 /* handle '\[\r]\n' */
245 static int handle_stray_noerror(void)
247 while (ch == '\\') {
248 inp();
249 if (ch == '\n') {
250 file->line_num++;
251 inp();
252 } else if (ch == '\r') {
253 inp();
254 if (ch != '\n')
255 goto fail;
256 file->line_num++;
257 inp();
258 } else {
259 fail:
260 return 1;
263 return 0;
266 static void handle_stray(void)
268 if (handle_stray_noerror())
269 error("stray '\\' in program");
272 /* skip the stray and handle the \\n case. Output an error if
273 incorrect char after the stray */
274 static int handle_stray1(uint8_t *p)
276 int c;
278 if (p >= file->buf_end) {
279 file->buf_ptr = p;
280 c = handle_eob();
281 p = file->buf_ptr;
282 if (c == '\\')
283 goto parse_stray;
284 } else {
285 parse_stray:
286 file->buf_ptr = p;
287 ch = *p;
288 handle_stray();
289 p = file->buf_ptr;
290 c = *p;
292 return c;
295 /* handle just the EOB case, but not stray */
296 #define PEEKC_EOB(c, p)\
298 p++;\
299 c = *p;\
300 if (c == '\\') {\
301 file->buf_ptr = p;\
302 c = handle_eob();\
303 p = file->buf_ptr;\
307 /* handle the complicated stray case */
308 #define PEEKC(c, p)\
310 p++;\
311 c = *p;\
312 if (c == '\\') {\
313 c = handle_stray1(p);\
314 p = file->buf_ptr;\
318 /* input with '\[\r]\n' handling. Note that this function cannot
319 handle other characters after '\', so you cannot call it inside
320 strings or comments */
321 static void minp(void)
323 inp();
324 if (ch == '\\')
325 handle_stray();
329 /* single line C++ comments */
330 static uint8_t *parse_line_comment(uint8_t *p)
332 int c;
334 p++;
335 for(;;) {
336 c = *p;
337 redo:
338 if (c == '\n' || c == CH_EOF) {
339 break;
340 } else if (c == '\\') {
341 file->buf_ptr = p;
342 c = handle_eob();
343 p = file->buf_ptr;
344 if (c == '\\') {
345 PEEKC_EOB(c, p);
346 if (c == '\n') {
347 file->line_num++;
348 PEEKC_EOB(c, p);
349 } else if (c == '\r') {
350 PEEKC_EOB(c, p);
351 if (c == '\n') {
352 file->line_num++;
353 PEEKC_EOB(c, p);
356 } else {
357 goto redo;
359 } else {
360 p++;
363 return p;
366 /* C comments */
367 static uint8_t *parse_comment(uint8_t *p)
369 int c;
371 p++;
372 for(;;) {
373 /* fast skip loop */
374 for(;;) {
375 c = *p;
376 if (c == '\n' || c == '*' || c == '\\')
377 break;
378 p++;
379 c = *p;
380 if (c == '\n' || c == '*' || c == '\\')
381 break;
382 p++;
384 /* now we can handle all the cases */
385 if (c == '\n') {
386 file->line_num++;
387 p++;
388 } else if (c == '*') {
389 p++;
390 for(;;) {
391 c = *p;
392 if (c == '*') {
393 p++;
394 } else if (c == '/') {
395 goto end_of_comment;
396 } else if (c == '\\') {
397 file->buf_ptr = p;
398 c = handle_eob();
399 p = file->buf_ptr;
400 if (c == '\\') {
401 /* skip '\[\r]\n', otherwise just skip the stray */
402 while (c == '\\') {
403 PEEKC_EOB(c, p);
404 if (c == '\n') {
405 file->line_num++;
406 PEEKC_EOB(c, p);
407 } else if (c == '\r') {
408 PEEKC_EOB(c, p);
409 if (c == '\n') {
410 file->line_num++;
411 PEEKC_EOB(c, p);
413 } else {
414 goto after_star;
418 } else {
419 break;
422 after_star: ;
423 } else {
424 /* stray, eob or eof */
425 file->buf_ptr = p;
426 c = handle_eob();
427 p = file->buf_ptr;
428 if (c == CH_EOF) {
429 error("unexpected end of file in comment");
430 } else if (c == '\\') {
431 p++;
435 end_of_comment:
436 p++;
437 return p;
440 #define cinp minp
442 /* space exlcuding newline */
443 LIBTCCAPI static inline int is_space(int ch)
445 return ch == ' ' || ch == '\t' || ch == '\v' || ch == '\f' || ch == '\r';
448 static inline void skip_spaces(void)
450 while (is_space(ch))
451 cinp();
454 static inline int check_space(int t, int *spc)
456 if (is_space(t)) {
457 if (*spc)
458 return 1;
459 *spc = 1;
460 } else
461 *spc = 0;
462 return 0;
465 /* parse a string without interpreting escapes */
466 static uint8_t *parse_pp_string(uint8_t *p,
467 int sep, CString *str)
469 int c;
470 p++;
471 for(;;) {
472 c = *p;
473 if (c == sep) {
474 break;
475 } else if (c == '\\') {
476 file->buf_ptr = p;
477 c = handle_eob();
478 p = file->buf_ptr;
479 if (c == CH_EOF) {
480 unterminated_string:
481 /* XXX: indicate line number of start of string */
482 error("missing terminating %c character", sep);
483 } else if (c == '\\') {
484 /* escape : just skip \[\r]\n */
485 PEEKC_EOB(c, p);
486 if (c == '\n') {
487 file->line_num++;
488 p++;
489 } else if (c == '\r') {
490 PEEKC_EOB(c, p);
491 if (c != '\n')
492 expect("'\n' after '\r'");
493 file->line_num++;
494 p++;
495 } else if (c == CH_EOF) {
496 goto unterminated_string;
497 } else {
498 if (str) {
499 cstr_ccat(str, '\\');
500 cstr_ccat(str, c);
502 p++;
505 } else if (c == '\n') {
506 file->line_num++;
507 goto add_char;
508 } else if (c == '\r') {
509 PEEKC_EOB(c, p);
510 if (c != '\n') {
511 if (str)
512 cstr_ccat(str, '\r');
513 } else {
514 file->line_num++;
515 goto add_char;
517 } else {
518 add_char:
519 if (str)
520 cstr_ccat(str, c);
521 p++;
524 p++;
525 return p;
528 /* skip block of text until #else, #elif or #endif. skip also pairs of
529 #if/#endif */
530 void preprocess_skip(void)
532 int a, start_of_line, c, in_warn_or_error;
533 uint8_t *p;
535 p = file->buf_ptr;
536 a = 0;
537 redo_start:
538 start_of_line = 1;
539 in_warn_or_error = 0;
540 for(;;) {
541 redo_no_start:
542 c = *p;
543 switch(c) {
544 case ' ':
545 case '\t':
546 case '\f':
547 case '\v':
548 case '\r':
549 p++;
550 goto redo_no_start;
551 case '\n':
552 file->line_num++;
553 p++;
554 goto redo_start;
555 case '\\':
556 file->buf_ptr = p;
557 c = handle_eob();
558 if (c == CH_EOF) {
559 expect("#endif");
560 } else if (c == '\\') {
561 ch = file->buf_ptr[0];
562 handle_stray_noerror();
564 p = file->buf_ptr;
565 goto redo_no_start;
566 /* skip strings */
567 case '\"':
568 case '\'':
569 if (in_warn_or_error)
570 goto _default;
571 p = parse_pp_string(p, c, NULL);
572 break;
573 /* skip comments */
574 case '/':
575 if (in_warn_or_error)
576 goto _default;
577 file->buf_ptr = p;
578 ch = *p;
579 minp();
580 p = file->buf_ptr;
581 if (ch == '*') {
582 p = parse_comment(p);
583 } else if (ch == '/') {
584 p = parse_line_comment(p);
586 break;
587 case '#':
588 p++;
589 if (start_of_line) {
590 file->buf_ptr = p;
591 next_nomacro();
592 p = file->buf_ptr;
593 if (a == 0 &&
594 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
595 goto the_end;
596 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
597 a++;
598 else if (tok == TOK_ENDIF)
599 a--;
600 else if( tok == TOK_ERROR || tok == TOK_WARNING)
601 in_warn_or_error = 1;
603 break;
604 _default:
605 default:
606 p++;
607 break;
609 start_of_line = 0;
611 the_end: ;
612 file->buf_ptr = p;
615 /* ParseState handling */
617 /* XXX: currently, no include file info is stored. Thus, we cannot display
618 accurate messages if the function or data definition spans multiple
619 files */
621 /* save current parse state in 's' */
622 void save_parse_state(ParseState *s)
624 s->line_num = file->line_num;
625 s->macro_ptr = macro_ptr;
626 s->tok = tok;
627 s->tokc = tokc;
630 /* restore parse state from 's' */
631 void restore_parse_state(ParseState *s)
633 file->line_num = s->line_num;
634 macro_ptr = s->macro_ptr;
635 tok = s->tok;
636 tokc = s->tokc;
639 /* return the number of additional 'ints' necessary to store the
640 token */
641 static inline int tok_ext_size(int t)
643 switch(t) {
644 /* 4 bytes */
645 case TOK_CINT:
646 case TOK_CUINT:
647 case TOK_CCHAR:
648 case TOK_LCHAR:
649 case TOK_CFLOAT:
650 case TOK_LINENUM:
651 return 1;
652 case TOK_STR:
653 case TOK_LSTR:
654 case TOK_PPNUM:
655 error("unsupported token");
656 return 1;
657 case TOK_CDOUBLE:
658 case TOK_CLLONG:
659 case TOK_CULLONG:
660 return 2;
661 case TOK_CLDOUBLE:
662 return LDOUBLE_SIZE / 4;
663 default:
664 return 0;
668 /* token string handling */
670 static inline void tok_str_new(TokenString *s)
672 s->str = NULL;
673 s->len = 0;
674 s->allocated_len = 0;
675 s->last_line_num = -1;
678 static void tok_str_free(int *str)
680 tcc_free(str);
683 static int *tok_str_realloc(TokenString *s)
685 int *str, len;
687 if (s->allocated_len == 0) {
688 len = 8;
689 } else {
690 len = s->allocated_len * 2;
692 str = tcc_realloc(s->str, len * sizeof(int));
693 if (!str)
694 error("memory full");
695 s->allocated_len = len;
696 s->str = str;
697 return str;
700 static void tok_str_add(TokenString *s, int t)
702 int len, *str;
704 len = s->len;
705 str = s->str;
706 if (len >= s->allocated_len)
707 str = tok_str_realloc(s);
708 str[len++] = t;
709 s->len = len;
712 static void tok_str_add2(TokenString *s, int t, CValue *cv)
714 int len, *str;
716 len = s->len;
717 str = s->str;
719 /* allocate space for worst case */
720 if (len + TOK_MAX_SIZE > s->allocated_len)
721 str = tok_str_realloc(s);
722 str[len++] = t;
723 switch(t) {
724 case TOK_CINT:
725 case TOK_CUINT:
726 case TOK_CCHAR:
727 case TOK_LCHAR:
728 case TOK_CFLOAT:
729 case TOK_LINENUM:
730 str[len++] = cv->tab[0];
731 break;
732 case TOK_PPNUM:
733 case TOK_STR:
734 case TOK_LSTR:
736 int nb_words;
737 CString *cstr;
739 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
740 while ((len + nb_words) > s->allocated_len)
741 str = tok_str_realloc(s);
742 cstr = (CString *)(str + len);
743 cstr->data = NULL;
744 cstr->size = cv->cstr->size;
745 cstr->data_allocated = NULL;
746 cstr->size_allocated = cstr->size;
747 memcpy((char *)cstr + sizeof(CString),
748 cv->cstr->data, cstr->size);
749 len += nb_words;
751 break;
752 case TOK_CDOUBLE:
753 case TOK_CLLONG:
754 case TOK_CULLONG:
755 #if LDOUBLE_SIZE == 8
756 case TOK_CLDOUBLE:
757 #endif
758 str[len++] = cv->tab[0];
759 str[len++] = cv->tab[1];
760 break;
761 #if LDOUBLE_SIZE == 12
762 case TOK_CLDOUBLE:
763 str[len++] = cv->tab[0];
764 str[len++] = cv->tab[1];
765 str[len++] = cv->tab[2];
766 #elif LDOUBLE_SIZE == 16
767 case TOK_CLDOUBLE:
768 str[len++] = cv->tab[0];
769 str[len++] = cv->tab[1];
770 str[len++] = cv->tab[2];
771 str[len++] = cv->tab[3];
772 #elif LDOUBLE_SIZE != 8
773 #error add long double size support
774 #endif
775 break;
776 default:
777 break;
779 s->len = len;
782 /* add the current parse token in token string 's' */
783 static void tok_str_add_tok(TokenString *s)
785 CValue cval;
787 /* save line number info */
788 if (file->line_num != s->last_line_num) {
789 s->last_line_num = file->line_num;
790 cval.i = s->last_line_num;
791 tok_str_add2(s, TOK_LINENUM, &cval);
793 tok_str_add2(s, tok, &tokc);
796 #if LDOUBLE_SIZE == 16
797 #define LDOUBLE_GET(p, cv) \
798 cv.tab[0] = p[0]; \
799 cv.tab[1] = p[1]; \
800 cv.tab[2] = p[2]; \
801 cv.tab[3] = p[3];
802 #elif LDOUBLE_SIZE == 12
803 #define LDOUBLE_GET(p, cv) \
804 cv.tab[0] = p[0]; \
805 cv.tab[1] = p[1]; \
806 cv.tab[2] = p[2];
807 #elif LDOUBLE_SIZE == 8
808 #define LDOUBLE_GET(p, cv) \
809 cv.tab[0] = p[0]; \
810 cv.tab[1] = p[1];
811 #else
812 #error add long double size support
813 #endif
816 /* get a token from an integer array and increment pointer
817 accordingly. we code it as a macro to avoid pointer aliasing. */
818 #define TOK_GET(t, p, cv) \
820 t = *p++; \
821 switch(t) { \
822 case TOK_CINT: \
823 case TOK_CUINT: \
824 case TOK_CCHAR: \
825 case TOK_LCHAR: \
826 case TOK_CFLOAT: \
827 case TOK_LINENUM: \
828 cv.tab[0] = *p++; \
829 break; \
830 case TOK_STR: \
831 case TOK_LSTR: \
832 case TOK_PPNUM: \
833 cv.cstr = (CString *)p; \
834 cv.cstr->data = (char *)p + sizeof(CString);\
835 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
836 break; \
837 case TOK_CDOUBLE: \
838 case TOK_CLLONG: \
839 case TOK_CULLONG: \
840 cv.tab[0] = p[0]; \
841 cv.tab[1] = p[1]; \
842 p += 2; \
843 break; \
844 case TOK_CLDOUBLE: \
845 LDOUBLE_GET(p, cv); \
846 p += LDOUBLE_SIZE / 4; \
847 break; \
848 default: \
849 break; \
853 /* defines handling */
854 static inline void define_push(int v, int macro_type, int *str, Sym *first_arg)
856 Sym *s;
858 s = sym_push2(&define_stack, v, macro_type, (long)str);
859 s->next = first_arg;
860 table_ident[v - TOK_IDENT]->sym_define = s;
863 /* undefined a define symbol. Its name is just set to zero */
864 static void define_undef(Sym *s)
866 int v;
867 v = s->v;
868 if (v >= TOK_IDENT && v < tok_ident)
869 table_ident[v - TOK_IDENT]->sym_define = NULL;
870 s->v = 0;
873 static inline Sym *define_find(int v)
875 v -= TOK_IDENT;
876 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
877 return NULL;
878 return table_ident[v]->sym_define;
881 /* free define stack until top reaches 'b' */
882 static void free_defines(Sym *b)
884 Sym *top, *top1;
885 int v;
887 top = define_stack;
888 while (top != b) {
889 top1 = top->prev;
890 /* do not free args or predefined defines */
891 if (top->c)
892 tok_str_free((int *)top->c);
893 v = top->v;
894 if (v >= TOK_IDENT && v < tok_ident)
895 table_ident[v - TOK_IDENT]->sym_define = NULL;
896 sym_free(top);
897 top = top1;
899 define_stack = b;
902 /* label lookup */
903 static Sym *label_find(int v)
905 v -= TOK_IDENT;
906 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
907 return NULL;
908 return table_ident[v]->sym_label;
911 static Sym *label_push(Sym **ptop, int v, int flags)
913 Sym *s, **ps;
914 s = sym_push2(ptop, v, 0, 0);
915 s->r = flags;
916 ps = &table_ident[v - TOK_IDENT]->sym_label;
917 if (ptop == &global_label_stack) {
918 /* modify the top most local identifier, so that
919 sym_identifier will point to 's' when popped */
920 while (*ps != NULL)
921 ps = &(*ps)->prev_tok;
923 s->prev_tok = *ps;
924 *ps = s;
925 return s;
928 /* pop labels until element last is reached. Look if any labels are
929 undefined. Define symbols if '&&label' was used. */
930 static void label_pop(Sym **ptop, Sym *slast)
932 Sym *s, *s1;
933 for(s = *ptop; s != slast; s = s1) {
934 s1 = s->prev;
935 if (s->r == LABEL_DECLARED) {
936 warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
937 } else if (s->r == LABEL_FORWARD) {
938 error("label '%s' used but not defined",
939 get_tok_str(s->v, NULL));
940 } else {
941 if (s->c) {
942 /* define corresponding symbol. A size of
943 1 is put. */
944 put_extern_sym(s, cur_text_section, (long)s->next, 1);
947 /* remove label */
948 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
949 sym_free(s);
951 *ptop = slast;
954 /* eval an expression for #if/#elif */
955 static int expr_preprocess(void)
957 int c, t;
958 TokenString str;
960 tok_str_new(&str);
961 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
962 next(); /* do macro subst */
963 if (tok == TOK_DEFINED) {
964 next_nomacro();
965 t = tok;
966 if (t == '(')
967 next_nomacro();
968 c = define_find(tok) != 0;
969 if (t == '(')
970 next_nomacro();
971 tok = TOK_CINT;
972 tokc.i = c;
973 } else if (tok >= TOK_IDENT) {
974 /* if undefined macro */
975 tok = TOK_CINT;
976 tokc.i = 0;
978 tok_str_add_tok(&str);
980 tok_str_add(&str, -1); /* simulate end of file */
981 tok_str_add(&str, 0);
982 /* now evaluate C constant expression */
983 macro_ptr = str.str;
984 next();
985 c = expr_const();
986 macro_ptr = NULL;
987 tok_str_free(str.str);
988 return c != 0;
991 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
992 static void tok_print(int *str)
994 int t;
995 CValue cval;
997 printf("<");
998 while (1) {
999 TOK_GET(t, str, cval);
1000 if (!t)
1001 break;
1002 printf("%s", get_tok_str(t, &cval));
1004 printf(">\n");
1006 #endif
1008 /* parse after #define */
1009 static void parse_define(void)
1011 Sym *s, *first, **ps;
1012 int v, t, varg, is_vaargs, spc;
1013 TokenString str;
1015 v = tok;
1016 if (v < TOK_IDENT)
1017 error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1018 /* XXX: should check if same macro (ANSI) */
1019 first = NULL;
1020 t = MACRO_OBJ;
1021 /* '(' must be just after macro definition for MACRO_FUNC */
1022 next_nomacro_spc();
1023 if (tok == '(') {
1024 next_nomacro();
1025 ps = &first;
1026 while (tok != ')') {
1027 varg = tok;
1028 next_nomacro();
1029 is_vaargs = 0;
1030 if (varg == TOK_DOTS) {
1031 varg = TOK___VA_ARGS__;
1032 is_vaargs = 1;
1033 } else if (tok == TOK_DOTS && gnu_ext) {
1034 is_vaargs = 1;
1035 next_nomacro();
1037 if (varg < TOK_IDENT)
1038 error("badly punctuated parameter list");
1039 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1040 *ps = s;
1041 ps = &s->next;
1042 if (tok != ',')
1043 break;
1044 next_nomacro();
1046 if (tok == ')')
1047 next_nomacro_spc();
1048 t = MACRO_FUNC;
1050 tok_str_new(&str);
1051 spc = 2;
1052 /* EOF testing necessary for '-D' handling */
1053 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1054 /* remove spaces around ## and after '#' */
1055 if (TOK_TWOSHARPS == tok) {
1056 if (1 == spc)
1057 --str.len;
1058 spc = 2;
1059 } else if ('#' == tok) {
1060 spc = 2;
1061 } else if (check_space(tok, &spc)) {
1062 goto skip;
1064 tok_str_add2(&str, tok, &tokc);
1065 skip:
1066 next_nomacro_spc();
1068 if (spc == 1)
1069 --str.len; /* remove trailing space */
1070 tok_str_add(&str, 0);
1071 #ifdef PP_DEBUG
1072 printf("define %s %d: ", get_tok_str(v, NULL), t);
1073 tok_print(str.str);
1074 #endif
1075 define_push(v, t, str.str, first);
1078 static inline int hash_cached_include(int type, const char *filename)
1080 const unsigned char *s;
1081 unsigned int h;
1083 h = TOK_HASH_INIT;
1084 h = TOK_HASH_FUNC(h, type);
1085 s = filename;
1086 while (*s) {
1087 h = TOK_HASH_FUNC(h, *s);
1088 s++;
1090 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1091 return h;
1094 /* XXX: use a token or a hash table to accelerate matching ? */
1095 static CachedInclude *search_cached_include(TCCState *s1,
1096 int type, const char *filename)
1098 CachedInclude *e;
1099 int i, h;
1100 h = hash_cached_include(type, filename);
1101 i = s1->cached_includes_hash[h];
1102 for(;;) {
1103 if (i == 0)
1104 break;
1105 e = s1->cached_includes[i - 1];
1106 if (e->type == type && !PATHCMP(e->filename, filename))
1107 return e;
1108 i = e->hash_next;
1110 return NULL;
1113 static inline void add_cached_include(TCCState *s1, int type,
1114 const char *filename, int ifndef_macro)
1116 CachedInclude *e;
1117 int h;
1119 if (search_cached_include(s1, type, filename))
1120 return;
1121 #ifdef INC_DEBUG
1122 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
1123 #endif
1124 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1125 if (!e)
1126 return;
1127 e->type = type;
1128 strcpy(e->filename, filename);
1129 e->ifndef_macro = ifndef_macro;
1130 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1131 /* add in hash table */
1132 h = hash_cached_include(type, filename);
1133 e->hash_next = s1->cached_includes_hash[h];
1134 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1137 static void pragma_parse(TCCState *s1)
1139 int val;
1141 next();
1142 if (tok == TOK_pack) {
1144 This may be:
1145 #pragma pack(1) // set
1146 #pragma pack() // reset to default
1147 #pragma pack(push,1) // push & set
1148 #pragma pack(pop) // restore previous
1150 next();
1151 skip('(');
1152 if (tok == TOK_ASM_pop) {
1153 next();
1154 if (s1->pack_stack_ptr <= s1->pack_stack) {
1155 stk_error:
1156 error("out of pack stack");
1158 s1->pack_stack_ptr--;
1159 } else {
1160 val = 0;
1161 if (tok != ')') {
1162 if (tok == TOK_ASM_push) {
1163 next();
1164 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1165 goto stk_error;
1166 s1->pack_stack_ptr++;
1167 skip(',');
1169 if (tok != TOK_CINT) {
1170 pack_error:
1171 error("invalid pack pragma");
1173 val = tokc.i;
1174 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1175 goto pack_error;
1176 next();
1178 *s1->pack_stack_ptr = val;
1179 skip(')');
1184 /* is_bof is true if first non space token at beginning of file */
1185 static void preprocess(int is_bof)
1187 TCCState *s1 = tcc_state;
1188 int size, i, c, n, saved_parse_flags;
1189 char buf[1024], *q;
1190 char buf1[1024];
1191 BufferedFile *f;
1192 Sym *s;
1193 CachedInclude *e;
1195 saved_parse_flags = parse_flags;
1196 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
1197 PARSE_FLAG_LINEFEED;
1198 next_nomacro();
1199 redo:
1200 switch(tok) {
1201 case TOK_DEFINE:
1202 next_nomacro();
1203 parse_define();
1204 break;
1205 case TOK_UNDEF:
1206 next_nomacro();
1207 s = define_find(tok);
1208 /* undefine symbol by putting an invalid name */
1209 if (s)
1210 define_undef(s);
1211 break;
1212 case TOK_INCLUDE:
1213 case TOK_INCLUDE_NEXT:
1214 ch = file->buf_ptr[0];
1215 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1216 skip_spaces();
1217 if (ch == '<') {
1218 c = '>';
1219 goto read_name;
1220 } else if (ch == '\"') {
1221 c = ch;
1222 read_name:
1223 inp();
1224 q = buf;
1225 while (ch != c && ch != '\n' && ch != CH_EOF) {
1226 if ((q - buf) < sizeof(buf) - 1)
1227 *q++ = ch;
1228 if (ch == '\\') {
1229 if (handle_stray_noerror() == 0)
1230 --q;
1231 } else
1232 inp();
1234 *q = '\0';
1235 minp();
1236 #if 0
1237 /* eat all spaces and comments after include */
1238 /* XXX: slightly incorrect */
1239 while (ch1 != '\n' && ch1 != CH_EOF)
1240 inp();
1241 #endif
1242 } else {
1243 /* computed #include : either we have only strings or
1244 we have anything enclosed in '<>' */
1245 next();
1246 buf[0] = '\0';
1247 if (tok == TOK_STR) {
1248 while (tok != TOK_LINEFEED) {
1249 if (tok != TOK_STR) {
1250 include_syntax:
1251 error("'#include' expects \"FILENAME\" or <FILENAME>");
1253 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
1254 next();
1256 c = '\"';
1257 } else {
1258 int len;
1259 while (tok != TOK_LINEFEED) {
1260 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1261 next();
1263 len = strlen(buf);
1264 /* check syntax and remove '<>' */
1265 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1266 goto include_syntax;
1267 memmove(buf, buf + 1, len - 2);
1268 buf[len - 2] = '\0';
1269 c = '>';
1273 e = search_cached_include(s1, c, buf);
1274 if (e && define_find(e->ifndef_macro)) {
1275 /* no need to parse the include because the 'ifndef macro'
1276 is defined */
1277 #ifdef INC_DEBUG
1278 printf("%s: skipping %s\n", file->filename, buf);
1279 #endif
1280 } else {
1281 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1282 error("#include recursion too deep");
1283 /* push current file in stack */
1284 /* XXX: fix current line init */
1285 *s1->include_stack_ptr++ = file;
1287 /* check absolute include path */
1288 if (IS_ABSPATH(buf)) {
1289 f = tcc_open(s1, buf);
1290 if (f)
1291 goto found;
1293 if (c == '\"') {
1294 /* first search in current dir if "header.h" */
1295 size = tcc_basename(file->filename) - file->filename;
1296 if (size > sizeof(buf1) - 1)
1297 size = sizeof(buf1) - 1;
1298 memcpy(buf1, file->filename, size);
1299 buf1[size] = '\0';
1300 pstrcat(buf1, sizeof(buf1), buf);
1301 f = tcc_open(s1, buf1);
1302 if (f) {
1303 if (tok == TOK_INCLUDE_NEXT)
1304 tok = TOK_INCLUDE;
1305 else
1306 goto found;
1309 /* now search in all the include paths */
1310 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
1311 for(i = 0; i < n; i++) {
1312 const char *path;
1313 if (i < s1->nb_include_paths)
1314 path = s1->include_paths[i];
1315 else
1316 path = s1->sysinclude_paths[i - s1->nb_include_paths];
1317 pstrcpy(buf1, sizeof(buf1), path);
1318 pstrcat(buf1, sizeof(buf1), "/");
1319 pstrcat(buf1, sizeof(buf1), buf);
1320 f = tcc_open(s1, buf1);
1321 if (f) {
1322 if (tok == TOK_INCLUDE_NEXT)
1323 tok = TOK_INCLUDE;
1324 else
1325 goto found;
1328 --s1->include_stack_ptr;
1329 error("include file '%s' not found", buf);
1330 break;
1331 found:
1332 #ifdef INC_DEBUG
1333 printf("%s: including %s\n", file->filename, buf1);
1334 #endif
1335 f->inc_type = c;
1336 pstrcpy(f->inc_filename, sizeof(f->inc_filename), buf);
1337 file = f;
1338 /* add include file debug info */
1339 if (tcc_state->do_debug) {
1340 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1342 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1343 ch = file->buf_ptr[0];
1344 goto the_end;
1346 break;
1347 case TOK_IFNDEF:
1348 c = 1;
1349 goto do_ifdef;
1350 case TOK_IF:
1351 c = expr_preprocess();
1352 goto do_if;
1353 case TOK_IFDEF:
1354 c = 0;
1355 do_ifdef:
1356 next_nomacro();
1357 if (tok < TOK_IDENT)
1358 error("invalid argument for '#if%sdef'", c ? "n" : "");
1359 if (is_bof) {
1360 if (c) {
1361 #ifdef INC_DEBUG
1362 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1363 #endif
1364 file->ifndef_macro = tok;
1367 c = (define_find(tok) != 0) ^ c;
1368 do_if:
1369 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1370 error("memory full");
1371 *s1->ifdef_stack_ptr++ = c;
1372 goto test_skip;
1373 case TOK_ELSE:
1374 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1375 error("#else without matching #if");
1376 if (s1->ifdef_stack_ptr[-1] & 2)
1377 error("#else after #else");
1378 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1379 goto test_skip;
1380 case TOK_ELIF:
1381 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1382 error("#elif without matching #if");
1383 c = s1->ifdef_stack_ptr[-1];
1384 if (c > 1)
1385 error("#elif after #else");
1386 /* last #if/#elif expression was true: we skip */
1387 if (c == 1)
1388 goto skip;
1389 c = expr_preprocess();
1390 s1->ifdef_stack_ptr[-1] = c;
1391 test_skip:
1392 if (!(c & 1)) {
1393 skip:
1394 preprocess_skip();
1395 is_bof = 0;
1396 goto redo;
1398 break;
1399 case TOK_ENDIF:
1400 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1401 error("#endif without matching #if");
1402 s1->ifdef_stack_ptr--;
1403 /* '#ifndef macro' was at the start of file. Now we check if
1404 an '#endif' is exactly at the end of file */
1405 if (file->ifndef_macro &&
1406 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1407 file->ifndef_macro_saved = file->ifndef_macro;
1408 /* need to set to zero to avoid false matches if another
1409 #ifndef at middle of file */
1410 file->ifndef_macro = 0;
1411 while (tok != TOK_LINEFEED)
1412 next_nomacro();
1413 tok_flags |= TOK_FLAG_ENDIF;
1414 goto the_end;
1416 break;
1417 case TOK_LINE:
1418 next();
1419 if (tok != TOK_CINT)
1420 error("#line");
1421 file->line_num = tokc.i - 1; /* the line number will be incremented after */
1422 next();
1423 if (tok != TOK_LINEFEED) {
1424 if (tok != TOK_STR)
1425 error("#line");
1426 pstrcpy(file->filename, sizeof(file->filename),
1427 (char *)tokc.cstr->data);
1429 break;
1430 case TOK_ERROR:
1431 case TOK_WARNING:
1432 c = tok;
1433 ch = file->buf_ptr[0];
1434 skip_spaces();
1435 q = buf;
1436 while (ch != '\n' && ch != CH_EOF) {
1437 if ((q - buf) < sizeof(buf) - 1)
1438 *q++ = ch;
1439 if (ch == '\\') {
1440 if (handle_stray_noerror() == 0)
1441 --q;
1442 } else
1443 inp();
1445 *q = '\0';
1446 if (c == TOK_ERROR)
1447 error("#error %s", buf);
1448 else
1449 warning("#warning %s", buf);
1450 break;
1451 case TOK_PRAGMA:
1452 pragma_parse(s1);
1453 break;
1454 default:
1455 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_CINT) {
1456 /* '!' is ignored to allow C scripts. numbers are ignored
1457 to emulate cpp behaviour */
1458 } else {
1459 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
1460 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1462 break;
1464 /* ignore other preprocess commands or #! for C scripts */
1465 while (tok != TOK_LINEFEED)
1466 next_nomacro();
1467 the_end:
1468 parse_flags = saved_parse_flags;
1471 /* evaluate escape codes in a string. */
1472 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1474 int c, n;
1475 const uint8_t *p;
1477 p = buf;
1478 for(;;) {
1479 c = *p;
1480 if (c == '\0')
1481 break;
1482 if (c == '\\') {
1483 p++;
1484 /* escape */
1485 c = *p;
1486 switch(c) {
1487 case '0': case '1': case '2': case '3':
1488 case '4': case '5': case '6': case '7':
1489 /* at most three octal digits */
1490 n = c - '0';
1491 p++;
1492 c = *p;
1493 if (isoct(c)) {
1494 n = n * 8 + c - '0';
1495 p++;
1496 c = *p;
1497 if (isoct(c)) {
1498 n = n * 8 + c - '0';
1499 p++;
1502 c = n;
1503 goto add_char_nonext;
1504 case 'x':
1505 case 'u':
1506 case 'U':
1507 p++;
1508 n = 0;
1509 for(;;) {
1510 c = *p;
1511 if (c >= 'a' && c <= 'f')
1512 c = c - 'a' + 10;
1513 else if (c >= 'A' && c <= 'F')
1514 c = c - 'A' + 10;
1515 else if (isnum(c))
1516 c = c - '0';
1517 else
1518 break;
1519 n = n * 16 + c;
1520 p++;
1522 c = n;
1523 goto add_char_nonext;
1524 case 'a':
1525 c = '\a';
1526 break;
1527 case 'b':
1528 c = '\b';
1529 break;
1530 case 'f':
1531 c = '\f';
1532 break;
1533 case 'n':
1534 c = '\n';
1535 break;
1536 case 'r':
1537 c = '\r';
1538 break;
1539 case 't':
1540 c = '\t';
1541 break;
1542 case 'v':
1543 c = '\v';
1544 break;
1545 case 'e':
1546 if (!gnu_ext)
1547 goto invalid_escape;
1548 c = 27;
1549 break;
1550 case '\'':
1551 case '\"':
1552 case '\\':
1553 case '?':
1554 break;
1555 default:
1556 invalid_escape:
1557 if (c >= '!' && c <= '~')
1558 warning("unknown escape sequence: \'\\%c\'", c);
1559 else
1560 warning("unknown escape sequence: \'\\x%x\'", c);
1561 break;
1564 p++;
1565 add_char_nonext:
1566 if (!is_long)
1567 cstr_ccat(outstr, c);
1568 else
1569 cstr_wccat(outstr, c);
1571 /* add a trailing '\0' */
1572 if (!is_long)
1573 cstr_ccat(outstr, '\0');
1574 else
1575 cstr_wccat(outstr, '\0');
1578 /* we use 64 bit numbers */
1579 #define BN_SIZE 2
1581 /* bn = (bn << shift) | or_val */
1582 void bn_lshift(unsigned int *bn, int shift, int or_val)
1584 int i;
1585 unsigned int v;
1586 for(i=0;i<BN_SIZE;i++) {
1587 v = bn[i];
1588 bn[i] = (v << shift) | or_val;
1589 or_val = v >> (32 - shift);
1593 void bn_zero(unsigned int *bn)
1595 int i;
1596 for(i=0;i<BN_SIZE;i++) {
1597 bn[i] = 0;
1601 /* parse number in null terminated string 'p' and return it in the
1602 current token */
1603 void parse_number(const char *p)
1605 int b, t, shift, frac_bits, s, exp_val, ch;
1606 char *q;
1607 unsigned int bn[BN_SIZE];
1608 double d;
1610 /* number */
1611 q = token_buf;
1612 ch = *p++;
1613 t = ch;
1614 ch = *p++;
1615 *q++ = t;
1616 b = 10;
1617 if (t == '.') {
1618 goto float_frac_parse;
1619 } else if (t == '0') {
1620 if (ch == 'x' || ch == 'X') {
1621 q--;
1622 ch = *p++;
1623 b = 16;
1624 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
1625 q--;
1626 ch = *p++;
1627 b = 2;
1630 /* parse all digits. cannot check octal numbers at this stage
1631 because of floating point constants */
1632 while (1) {
1633 if (ch >= 'a' && ch <= 'f')
1634 t = ch - 'a' + 10;
1635 else if (ch >= 'A' && ch <= 'F')
1636 t = ch - 'A' + 10;
1637 else if (isnum(ch))
1638 t = ch - '0';
1639 else
1640 break;
1641 if (t >= b)
1642 break;
1643 if (q >= token_buf + STRING_MAX_SIZE) {
1644 num_too_long:
1645 error("number too long");
1647 *q++ = ch;
1648 ch = *p++;
1650 if (ch == '.' ||
1651 ((ch == 'e' || ch == 'E') && b == 10) ||
1652 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
1653 if (b != 10) {
1654 /* NOTE: strtox should support that for hexa numbers, but
1655 non ISOC99 libcs do not support it, so we prefer to do
1656 it by hand */
1657 /* hexadecimal or binary floats */
1658 /* XXX: handle overflows */
1659 *q = '\0';
1660 if (b == 16)
1661 shift = 4;
1662 else
1663 shift = 2;
1664 bn_zero(bn);
1665 q = token_buf;
1666 while (1) {
1667 t = *q++;
1668 if (t == '\0') {
1669 break;
1670 } else if (t >= 'a') {
1671 t = t - 'a' + 10;
1672 } else if (t >= 'A') {
1673 t = t - 'A' + 10;
1674 } else {
1675 t = t - '0';
1677 bn_lshift(bn, shift, t);
1679 frac_bits = 0;
1680 if (ch == '.') {
1681 ch = *p++;
1682 while (1) {
1683 t = ch;
1684 if (t >= 'a' && t <= 'f') {
1685 t = t - 'a' + 10;
1686 } else if (t >= 'A' && t <= 'F') {
1687 t = t - 'A' + 10;
1688 } else if (t >= '0' && t <= '9') {
1689 t = t - '0';
1690 } else {
1691 break;
1693 if (t >= b)
1694 error("invalid digit");
1695 bn_lshift(bn, shift, t);
1696 frac_bits += shift;
1697 ch = *p++;
1700 if (ch != 'p' && ch != 'P')
1701 expect("exponent");
1702 ch = *p++;
1703 s = 1;
1704 exp_val = 0;
1705 if (ch == '+') {
1706 ch = *p++;
1707 } else if (ch == '-') {
1708 s = -1;
1709 ch = *p++;
1711 if (ch < '0' || ch > '9')
1712 expect("exponent digits");
1713 while (ch >= '0' && ch <= '9') {
1714 exp_val = exp_val * 10 + ch - '0';
1715 ch = *p++;
1717 exp_val = exp_val * s;
1719 /* now we can generate the number */
1720 /* XXX: should patch directly float number */
1721 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
1722 d = ldexp(d, exp_val - frac_bits);
1723 t = toup(ch);
1724 if (t == 'F') {
1725 ch = *p++;
1726 tok = TOK_CFLOAT;
1727 /* float : should handle overflow */
1728 tokc.f = (float)d;
1729 } else if (t == 'L') {
1730 ch = *p++;
1731 tok = TOK_CLDOUBLE;
1732 /* XXX: not large enough */
1733 tokc.ld = (long double)d;
1734 } else {
1735 tok = TOK_CDOUBLE;
1736 tokc.d = d;
1738 } else {
1739 /* decimal floats */
1740 if (ch == '.') {
1741 if (q >= token_buf + STRING_MAX_SIZE)
1742 goto num_too_long;
1743 *q++ = ch;
1744 ch = *p++;
1745 float_frac_parse:
1746 while (ch >= '0' && ch <= '9') {
1747 if (q >= token_buf + STRING_MAX_SIZE)
1748 goto num_too_long;
1749 *q++ = ch;
1750 ch = *p++;
1753 if (ch == 'e' || ch == 'E') {
1754 if (q >= token_buf + STRING_MAX_SIZE)
1755 goto num_too_long;
1756 *q++ = ch;
1757 ch = *p++;
1758 if (ch == '-' || ch == '+') {
1759 if (q >= token_buf + STRING_MAX_SIZE)
1760 goto num_too_long;
1761 *q++ = ch;
1762 ch = *p++;
1764 if (ch < '0' || ch > '9')
1765 expect("exponent digits");
1766 while (ch >= '0' && ch <= '9') {
1767 if (q >= token_buf + STRING_MAX_SIZE)
1768 goto num_too_long;
1769 *q++ = ch;
1770 ch = *p++;
1773 *q = '\0';
1774 t = toup(ch);
1775 errno = 0;
1776 if (t == 'F') {
1777 ch = *p++;
1778 tok = TOK_CFLOAT;
1779 tokc.f = strtof(token_buf, NULL);
1780 } else if (t == 'L') {
1781 ch = *p++;
1782 tok = TOK_CLDOUBLE;
1783 tokc.ld = strtold(token_buf, NULL);
1784 } else {
1785 tok = TOK_CDOUBLE;
1786 tokc.d = strtod(token_buf, NULL);
1789 } else {
1790 unsigned long long n, n1;
1791 int lcount, ucount;
1793 /* integer number */
1794 *q = '\0';
1795 q = token_buf;
1796 if (b == 10 && *q == '0') {
1797 b = 8;
1798 q++;
1800 n = 0;
1801 while(1) {
1802 t = *q++;
1803 /* no need for checks except for base 10 / 8 errors */
1804 if (t == '\0') {
1805 break;
1806 } else if (t >= 'a') {
1807 t = t - 'a' + 10;
1808 } else if (t >= 'A') {
1809 t = t - 'A' + 10;
1810 } else {
1811 t = t - '0';
1812 if (t >= b)
1813 error("invalid digit");
1815 n1 = n;
1816 n = n * b + t;
1817 /* detect overflow */
1818 /* XXX: this test is not reliable */
1819 if (n < n1)
1820 error("integer constant overflow");
1823 /* XXX: not exactly ANSI compliant */
1824 if ((n & 0xffffffff00000000LL) != 0) {
1825 if ((n >> 63) != 0)
1826 tok = TOK_CULLONG;
1827 else
1828 tok = TOK_CLLONG;
1829 } else if (n > 0x7fffffff) {
1830 tok = TOK_CUINT;
1831 } else {
1832 tok = TOK_CINT;
1834 lcount = 0;
1835 ucount = 0;
1836 for(;;) {
1837 t = toup(ch);
1838 if (t == 'L') {
1839 if (lcount >= 2)
1840 error("three 'l's in integer constant");
1841 lcount++;
1842 if (lcount == 2) {
1843 if (tok == TOK_CINT)
1844 tok = TOK_CLLONG;
1845 else if (tok == TOK_CUINT)
1846 tok = TOK_CULLONG;
1848 ch = *p++;
1849 } else if (t == 'U') {
1850 if (ucount >= 1)
1851 error("two 'u's in integer constant");
1852 ucount++;
1853 if (tok == TOK_CINT)
1854 tok = TOK_CUINT;
1855 else if (tok == TOK_CLLONG)
1856 tok = TOK_CULLONG;
1857 ch = *p++;
1858 } else {
1859 break;
1862 if (tok == TOK_CINT || tok == TOK_CUINT)
1863 tokc.ui = n;
1864 else
1865 tokc.ull = n;
1867 if (ch)
1868 error("invalid number\n");
1872 #define PARSE2(c1, tok1, c2, tok2) \
1873 case c1: \
1874 PEEKC(c, p); \
1875 if (c == c2) { \
1876 p++; \
1877 tok = tok2; \
1878 } else { \
1879 tok = tok1; \
1881 break;
1883 /* return next token without macro substitution */
1884 static inline void next_nomacro1(void)
1886 int t, c, is_long;
1887 TokenSym *ts;
1888 uint8_t *p, *p1;
1889 unsigned int h;
1891 p = file->buf_ptr;
1892 redo_no_start:
1893 c = *p;
1894 switch(c) {
1895 case ' ':
1896 case '\t':
1897 tok = c;
1898 p++;
1899 goto keep_tok_flags;
1900 case '\f':
1901 case '\v':
1902 case '\r':
1903 p++;
1904 goto redo_no_start;
1905 case '\\':
1906 /* first look if it is in fact an end of buffer */
1907 if (p >= file->buf_end) {
1908 file->buf_ptr = p;
1909 handle_eob();
1910 p = file->buf_ptr;
1911 if (p >= file->buf_end)
1912 goto parse_eof;
1913 else
1914 goto redo_no_start;
1915 } else {
1916 file->buf_ptr = p;
1917 ch = *p;
1918 handle_stray();
1919 p = file->buf_ptr;
1920 goto redo_no_start;
1922 parse_eof:
1924 TCCState *s1 = tcc_state;
1925 if ((parse_flags & PARSE_FLAG_LINEFEED)
1926 && !(tok_flags & TOK_FLAG_EOF)) {
1927 tok_flags |= TOK_FLAG_EOF;
1928 tok = TOK_LINEFEED;
1929 goto keep_tok_flags;
1930 } else if (s1->include_stack_ptr == s1->include_stack ||
1931 !(parse_flags & PARSE_FLAG_PREPROCESS)) {
1932 /* no include left : end of file. */
1933 tok = TOK_EOF;
1934 } else {
1935 tok_flags &= ~TOK_FLAG_EOF;
1936 /* pop include file */
1938 /* test if previous '#endif' was after a #ifdef at
1939 start of file */
1940 if (tok_flags & TOK_FLAG_ENDIF) {
1941 #ifdef INC_DEBUG
1942 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
1943 #endif
1944 add_cached_include(s1, file->inc_type, file->inc_filename,
1945 file->ifndef_macro_saved);
1948 /* add end of include file debug info */
1949 if (tcc_state->do_debug) {
1950 put_stabd(N_EINCL, 0, 0);
1952 /* pop include stack */
1953 tcc_close(file);
1954 s1->include_stack_ptr--;
1955 file = *s1->include_stack_ptr;
1956 p = file->buf_ptr;
1957 goto redo_no_start;
1960 break;
1962 case '\n':
1963 file->line_num++;
1964 tok_flags |= TOK_FLAG_BOL;
1965 p++;
1966 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
1967 goto redo_no_start;
1968 tok = TOK_LINEFEED;
1969 goto keep_tok_flags;
1971 case '#':
1972 /* XXX: simplify */
1973 PEEKC(c, p);
1974 if ((tok_flags & TOK_FLAG_BOL) &&
1975 (parse_flags & PARSE_FLAG_PREPROCESS)) {
1976 file->buf_ptr = p;
1977 preprocess(tok_flags & TOK_FLAG_BOF);
1978 p = file->buf_ptr;
1979 goto redo_no_start;
1980 } else {
1981 if (c == '#') {
1982 p++;
1983 tok = TOK_TWOSHARPS;
1984 } else {
1985 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
1986 p = parse_line_comment(p - 1);
1987 goto redo_no_start;
1988 } else {
1989 tok = '#';
1993 break;
1995 case 'a': case 'b': case 'c': case 'd':
1996 case 'e': case 'f': case 'g': case 'h':
1997 case 'i': case 'j': case 'k': case 'l':
1998 case 'm': case 'n': case 'o': case 'p':
1999 case 'q': case 'r': case 's': case 't':
2000 case 'u': case 'v': case 'w': case 'x':
2001 case 'y': case 'z':
2002 case 'A': case 'B': case 'C': case 'D':
2003 case 'E': case 'F': case 'G': case 'H':
2004 case 'I': case 'J': case 'K':
2005 case 'M': case 'N': case 'O': case 'P':
2006 case 'Q': case 'R': case 'S': case 'T':
2007 case 'U': case 'V': case 'W': case 'X':
2008 case 'Y': case 'Z':
2009 case '_':
2010 parse_ident_fast:
2011 p1 = p;
2012 h = TOK_HASH_INIT;
2013 h = TOK_HASH_FUNC(h, c);
2014 p++;
2015 for(;;) {
2016 c = *p;
2017 if (!isidnum_table[c-CH_EOF])
2018 break;
2019 h = TOK_HASH_FUNC(h, c);
2020 p++;
2022 if (c != '\\') {
2023 TokenSym **pts;
2024 int len;
2026 /* fast case : no stray found, so we have the full token
2027 and we have already hashed it */
2028 len = p - p1;
2029 h &= (TOK_HASH_SIZE - 1);
2030 pts = &hash_ident[h];
2031 for(;;) {
2032 ts = *pts;
2033 if (!ts)
2034 break;
2035 if (ts->len == len && !memcmp(ts->str, p1, len))
2036 goto token_found;
2037 pts = &(ts->hash_next);
2039 ts = tok_alloc_new(pts, p1, len);
2040 token_found: ;
2041 } else {
2042 /* slower case */
2043 cstr_reset(&tokcstr);
2045 while (p1 < p) {
2046 cstr_ccat(&tokcstr, *p1);
2047 p1++;
2049 p--;
2050 PEEKC(c, p);
2051 parse_ident_slow:
2052 while (isidnum_table[c-CH_EOF]) {
2053 cstr_ccat(&tokcstr, c);
2054 PEEKC(c, p);
2056 ts = tok_alloc(tokcstr.data, tokcstr.size);
2058 tok = ts->tok;
2059 break;
2060 case 'L':
2061 t = p[1];
2062 if (t != '\\' && t != '\'' && t != '\"') {
2063 /* fast case */
2064 goto parse_ident_fast;
2065 } else {
2066 PEEKC(c, p);
2067 if (c == '\'' || c == '\"') {
2068 is_long = 1;
2069 goto str_const;
2070 } else {
2071 cstr_reset(&tokcstr);
2072 cstr_ccat(&tokcstr, 'L');
2073 goto parse_ident_slow;
2076 break;
2077 case '0': case '1': case '2': case '3':
2078 case '4': case '5': case '6': case '7':
2079 case '8': case '9':
2081 cstr_reset(&tokcstr);
2082 /* after the first digit, accept digits, alpha, '.' or sign if
2083 prefixed by 'eEpP' */
2084 parse_num:
2085 for(;;) {
2086 t = c;
2087 cstr_ccat(&tokcstr, c);
2088 PEEKC(c, p);
2089 if (!(isnum(c) || isid(c) || c == '.' ||
2090 ((c == '+' || c == '-') &&
2091 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
2092 break;
2094 /* We add a trailing '\0' to ease parsing */
2095 cstr_ccat(&tokcstr, '\0');
2096 tokc.cstr = &tokcstr;
2097 tok = TOK_PPNUM;
2098 break;
2099 case '.':
2100 /* special dot handling because it can also start a number */
2101 PEEKC(c, p);
2102 if (isnum(c)) {
2103 cstr_reset(&tokcstr);
2104 cstr_ccat(&tokcstr, '.');
2105 goto parse_num;
2106 } else if (c == '.') {
2107 PEEKC(c, p);
2108 if (c != '.')
2109 expect("'.'");
2110 PEEKC(c, p);
2111 tok = TOK_DOTS;
2112 } else {
2113 tok = '.';
2115 break;
2116 case '\'':
2117 case '\"':
2118 is_long = 0;
2119 str_const:
2121 CString str;
2122 int sep;
2124 sep = c;
2126 /* parse the string */
2127 cstr_new(&str);
2128 p = parse_pp_string(p, sep, &str);
2129 cstr_ccat(&str, '\0');
2131 /* eval the escape (should be done as TOK_PPNUM) */
2132 cstr_reset(&tokcstr);
2133 parse_escape_string(&tokcstr, str.data, is_long);
2134 cstr_free(&str);
2136 if (sep == '\'') {
2137 int char_size;
2138 /* XXX: make it portable */
2139 if (!is_long)
2140 char_size = 1;
2141 else
2142 char_size = sizeof(nwchar_t);
2143 if (tokcstr.size <= char_size)
2144 error("empty character constant");
2145 if (tokcstr.size > 2 * char_size)
2146 warning("multi-character character constant");
2147 if (!is_long) {
2148 tokc.i = *(int8_t *)tokcstr.data;
2149 tok = TOK_CCHAR;
2150 } else {
2151 tokc.i = *(nwchar_t *)tokcstr.data;
2152 tok = TOK_LCHAR;
2154 } else {
2155 tokc.cstr = &tokcstr;
2156 if (!is_long)
2157 tok = TOK_STR;
2158 else
2159 tok = TOK_LSTR;
2162 break;
2164 case '<':
2165 PEEKC(c, p);
2166 if (c == '=') {
2167 p++;
2168 tok = TOK_LE;
2169 } else if (c == '<') {
2170 PEEKC(c, p);
2171 if (c == '=') {
2172 p++;
2173 tok = TOK_A_SHL;
2174 } else {
2175 tok = TOK_SHL;
2177 } else {
2178 tok = TOK_LT;
2180 break;
2182 case '>':
2183 PEEKC(c, p);
2184 if (c == '=') {
2185 p++;
2186 tok = TOK_GE;
2187 } else if (c == '>') {
2188 PEEKC(c, p);
2189 if (c == '=') {
2190 p++;
2191 tok = TOK_A_SAR;
2192 } else {
2193 tok = TOK_SAR;
2195 } else {
2196 tok = TOK_GT;
2198 break;
2200 case '&':
2201 PEEKC(c, p);
2202 if (c == '&') {
2203 p++;
2204 tok = TOK_LAND;
2205 } else if (c == '=') {
2206 p++;
2207 tok = TOK_A_AND;
2208 } else {
2209 tok = '&';
2211 break;
2213 case '|':
2214 PEEKC(c, p);
2215 if (c == '|') {
2216 p++;
2217 tok = TOK_LOR;
2218 } else if (c == '=') {
2219 p++;
2220 tok = TOK_A_OR;
2221 } else {
2222 tok = '|';
2224 break;
2226 case '+':
2227 PEEKC(c, p);
2228 if (c == '+') {
2229 p++;
2230 tok = TOK_INC;
2231 } else if (c == '=') {
2232 p++;
2233 tok = TOK_A_ADD;
2234 } else {
2235 tok = '+';
2237 break;
2239 case '-':
2240 PEEKC(c, p);
2241 if (c == '-') {
2242 p++;
2243 tok = TOK_DEC;
2244 } else if (c == '=') {
2245 p++;
2246 tok = TOK_A_SUB;
2247 } else if (c == '>') {
2248 p++;
2249 tok = TOK_ARROW;
2250 } else {
2251 tok = '-';
2253 break;
2255 PARSE2('!', '!', '=', TOK_NE)
2256 PARSE2('=', '=', '=', TOK_EQ)
2257 PARSE2('*', '*', '=', TOK_A_MUL)
2258 PARSE2('%', '%', '=', TOK_A_MOD)
2259 PARSE2('^', '^', '=', TOK_A_XOR)
2261 /* comments or operator */
2262 case '/':
2263 PEEKC(c, p);
2264 if (c == '*') {
2265 p = parse_comment(p);
2266 goto redo_no_start;
2267 } else if (c == '/') {
2268 p = parse_line_comment(p);
2269 goto redo_no_start;
2270 } else if (c == '=') {
2271 p++;
2272 tok = TOK_A_DIV;
2273 } else {
2274 tok = '/';
2276 break;
2278 /* simple tokens */
2279 case '(':
2280 case ')':
2281 case '[':
2282 case ']':
2283 case '{':
2284 case '}':
2285 case ',':
2286 case ';':
2287 case ':':
2288 case '?':
2289 case '~':
2290 case '$': /* only used in assembler */
2291 case '@': /* dito */
2292 tok = c;
2293 p++;
2294 break;
2295 default:
2296 error("unrecognized character \\x%02x", c);
2297 break;
2299 tok_flags = 0;
2300 keep_tok_flags:
2301 file->buf_ptr = p;
2302 #if defined(PARSE_DEBUG)
2303 printf("token = %s\n", get_tok_str(tok, &tokc));
2304 #endif
2307 /* return next token without macro substitution. Can read input from
2308 macro_ptr buffer */
2309 static void next_nomacro_spc(void)
2311 if (macro_ptr) {
2312 redo:
2313 tok = *macro_ptr;
2314 if (tok) {
2315 TOK_GET(tok, macro_ptr, tokc);
2316 if (tok == TOK_LINENUM) {
2317 file->line_num = tokc.i;
2318 goto redo;
2321 } else {
2322 next_nomacro1();
2326 static void next_nomacro(void)
2328 do {
2329 next_nomacro_spc();
2330 } while (is_space(tok));
2333 /* substitute args in macro_str and return allocated string */
2334 static int *macro_arg_subst(Sym **nested_list, int *macro_str, Sym *args)
2336 int *st, last_tok, t, spc;
2337 Sym *s;
2338 CValue cval;
2339 TokenString str;
2340 CString cstr;
2342 tok_str_new(&str);
2343 last_tok = 0;
2344 while(1) {
2345 TOK_GET(t, macro_str, cval);
2346 if (!t)
2347 break;
2348 if (t == '#') {
2349 /* stringize */
2350 TOK_GET(t, macro_str, cval);
2351 if (!t)
2352 break;
2353 s = sym_find2(args, t);
2354 if (s) {
2355 cstr_new(&cstr);
2356 st = (int *)s->c;
2357 spc = 0;
2358 while (*st) {
2359 TOK_GET(t, st, cval);
2360 if (!check_space(t, &spc))
2361 cstr_cat(&cstr, get_tok_str(t, &cval));
2363 cstr.size -= spc;
2364 cstr_ccat(&cstr, '\0');
2365 #ifdef PP_DEBUG
2366 printf("stringize: %s\n", (char *)cstr.data);
2367 #endif
2368 /* add string */
2369 cval.cstr = &cstr;
2370 tok_str_add2(&str, TOK_STR, &cval);
2371 cstr_free(&cstr);
2372 } else {
2373 tok_str_add2(&str, t, &cval);
2375 } else if (t >= TOK_IDENT) {
2376 s = sym_find2(args, t);
2377 if (s) {
2378 st = (int *)s->c;
2379 /* if '##' is present before or after, no arg substitution */
2380 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
2381 /* special case for var arg macros : ## eats the
2382 ',' if empty VA_ARGS variable. */
2383 /* XXX: test of the ',' is not 100%
2384 reliable. should fix it to avoid security
2385 problems */
2386 if (gnu_ext && s->type.t &&
2387 last_tok == TOK_TWOSHARPS &&
2388 str.len >= 2 && str.str[str.len - 2] == ',') {
2389 if (*st == 0) {
2390 /* suppress ',' '##' */
2391 str.len -= 2;
2392 } else {
2393 /* suppress '##' and add variable */
2394 str.len--;
2395 goto add_var;
2397 } else {
2398 int t1;
2399 add_var:
2400 for(;;) {
2401 TOK_GET(t1, st, cval);
2402 if (!t1)
2403 break;
2404 tok_str_add2(&str, t1, &cval);
2407 } else {
2408 /* NOTE: the stream cannot be read when macro
2409 substituing an argument */
2410 macro_subst(&str, nested_list, st, NULL);
2412 } else {
2413 tok_str_add(&str, t);
2415 } else {
2416 tok_str_add2(&str, t, &cval);
2418 last_tok = t;
2420 tok_str_add(&str, 0);
2421 return str.str;
2424 static char const ab_month_name[12][4] =
2426 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2427 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2430 /* do macro substitution of current token with macro 's' and add
2431 result to (tok_str,tok_len). 'nested_list' is the list of all
2432 macros we got inside to avoid recursing. Return non zero if no
2433 substitution needs to be done */
2434 static int macro_subst_tok(TokenString *tok_str,
2435 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
2437 Sym *args, *sa, *sa1;
2438 int mstr_allocated, parlevel, *mstr, t, t1, *p, spc;
2439 TokenString str;
2440 char *cstrval;
2441 CValue cval;
2442 CString cstr;
2443 char buf[32];
2445 /* if symbol is a macro, prepare substitution */
2446 /* special macros */
2447 if (tok == TOK___LINE__) {
2448 snprintf(buf, sizeof(buf), "%d", file->line_num);
2449 cstrval = buf;
2450 t1 = TOK_PPNUM;
2451 goto add_cstr1;
2452 } else if (tok == TOK___FILE__) {
2453 cstrval = file->filename;
2454 goto add_cstr;
2455 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
2456 time_t ti;
2457 struct tm *tm;
2459 time(&ti);
2460 tm = localtime(&ti);
2461 if (tok == TOK___DATE__) {
2462 snprintf(buf, sizeof(buf), "%s %2d %d",
2463 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
2464 } else {
2465 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
2466 tm->tm_hour, tm->tm_min, tm->tm_sec);
2468 cstrval = buf;
2469 add_cstr:
2470 t1 = TOK_STR;
2471 add_cstr1:
2472 cstr_new(&cstr);
2473 cstr_cat(&cstr, cstrval);
2474 cstr_ccat(&cstr, '\0');
2475 cval.cstr = &cstr;
2476 tok_str_add2(tok_str, t1, &cval);
2477 cstr_free(&cstr);
2478 } else {
2479 mstr = (int *)s->c;
2480 mstr_allocated = 0;
2481 if (s->type.t == MACRO_FUNC) {
2482 /* NOTE: we do not use next_nomacro to avoid eating the
2483 next token. XXX: find better solution */
2484 redo:
2485 if (macro_ptr) {
2486 p = macro_ptr;
2487 while (is_space(t = *p) || TOK_LINEFEED == t)
2488 ++p;
2489 if (t == 0 && can_read_stream) {
2490 /* end of macro stream: we must look at the token
2491 after in the file */
2492 struct macro_level *ml = *can_read_stream;
2493 macro_ptr = NULL;
2494 if (ml)
2496 macro_ptr = ml->p;
2497 ml->p = NULL;
2498 *can_read_stream = ml -> prev;
2500 goto redo;
2502 } else {
2503 /* XXX: incorrect with comments */
2504 ch = file->buf_ptr[0];
2505 while (is_space(ch) || ch == '\n')
2506 cinp();
2507 t = ch;
2509 if (t != '(') /* no macro subst */
2510 return -1;
2512 /* argument macro */
2513 next_nomacro();
2514 next_nomacro();
2515 args = NULL;
2516 sa = s->next;
2517 /* NOTE: empty args are allowed, except if no args */
2518 for(;;) {
2519 /* handle '()' case */
2520 if (!args && !sa && tok == ')')
2521 break;
2522 if (!sa)
2523 error("macro '%s' used with too many args",
2524 get_tok_str(s->v, 0));
2525 tok_str_new(&str);
2526 parlevel = spc = 0;
2527 /* NOTE: non zero sa->t indicates VA_ARGS */
2528 while ((parlevel > 0 ||
2529 (tok != ')' &&
2530 (tok != ',' || sa->type.t))) &&
2531 tok != -1) {
2532 if (tok == '(')
2533 parlevel++;
2534 else if (tok == ')')
2535 parlevel--;
2536 if (tok == TOK_LINEFEED)
2537 tok = ' ';
2538 if (!check_space(tok, &spc))
2539 tok_str_add2(&str, tok, &tokc);
2540 next_nomacro_spc();
2542 str.len -= spc;
2543 tok_str_add(&str, 0);
2544 sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, (long)str.str);
2545 sa = sa->next;
2546 if (tok == ')') {
2547 /* special case for gcc var args: add an empty
2548 var arg argument if it is omitted */
2549 if (sa && sa->type.t && gnu_ext)
2550 continue;
2551 else
2552 break;
2554 if (tok != ',')
2555 expect(",");
2556 next_nomacro();
2558 if (sa) {
2559 error("macro '%s' used with too few args",
2560 get_tok_str(s->v, 0));
2563 /* now subst each arg */
2564 mstr = macro_arg_subst(nested_list, mstr, args);
2565 /* free memory */
2566 sa = args;
2567 while (sa) {
2568 sa1 = sa->prev;
2569 tok_str_free((int *)sa->c);
2570 sym_free(sa);
2571 sa = sa1;
2573 mstr_allocated = 1;
2575 sym_push2(nested_list, s->v, 0, 0);
2576 macro_subst(tok_str, nested_list, mstr, can_read_stream);
2577 /* pop nested defined symbol */
2578 sa1 = *nested_list;
2579 *nested_list = sa1->prev;
2580 sym_free(sa1);
2581 if (mstr_allocated)
2582 tok_str_free(mstr);
2584 return 0;
2587 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2588 return the resulting string (which must be freed). */
2589 static inline int *macro_twosharps(const int *macro_str)
2591 TokenSym *ts;
2592 const int *ptr, *saved_macro_ptr;
2593 int t;
2594 const char *p1, *p2;
2595 CValue cval;
2596 TokenString macro_str1;
2597 CString cstr;
2599 /* we search the first '##' */
2600 for(ptr = macro_str;;) {
2601 TOK_GET(t, ptr, cval);
2602 if (t == TOK_TWOSHARPS)
2603 break;
2604 /* nothing more to do if end of string */
2605 if (t == 0)
2606 return NULL;
2609 /* we saw '##', so we need more processing to handle it */
2610 cstr_new(&cstr);
2611 tok_str_new(&macro_str1);
2612 saved_macro_ptr = macro_ptr;
2613 /* XXX: get rid of the use of macro_ptr here */
2614 macro_ptr = (int *)macro_str;
2615 for(;;) {
2616 next_nomacro_spc();
2617 if (tok == 0)
2618 break;
2619 if (tok == TOK_TWOSHARPS)
2620 continue;
2621 while (*macro_ptr == TOK_TWOSHARPS) {
2622 t = *++macro_ptr;
2623 if (t && t != TOK_TWOSHARPS) {
2624 TOK_GET(t, macro_ptr, cval);
2625 /* We concatenate the two tokens if we have an
2626 identifier or a preprocessing number */
2627 cstr_reset(&cstr);
2628 p1 = get_tok_str(tok, &tokc);
2629 cstr_cat(&cstr, p1);
2630 p2 = get_tok_str(t, &cval);
2631 cstr_cat(&cstr, p2);
2632 cstr_ccat(&cstr, '\0');
2634 if ((tok >= TOK_IDENT || tok == TOK_PPNUM) &&
2635 (t >= TOK_IDENT || t == TOK_PPNUM)) {
2636 if (tok == TOK_PPNUM) {
2637 /* if number, then create a number token */
2638 /* NOTE: no need to allocate because
2639 tok_str_add2() does it */
2640 cstr_reset(&tokcstr);
2641 tokcstr = cstr;
2642 cstr_new(&cstr);
2643 tokc.cstr = &tokcstr;
2644 } else {
2645 /* if identifier, we must do a test to
2646 validate we have a correct identifier */
2647 if (t == TOK_PPNUM) {
2648 const char *p;
2649 int c;
2651 p = p2;
2652 for(;;) {
2653 c = *p;
2654 if (c == '\0')
2655 break;
2656 p++;
2657 if (!isnum(c) && !isid(c))
2658 goto error_pasting;
2661 ts = tok_alloc(cstr.data, strlen(cstr.data));
2662 tok = ts->tok; /* modify current token */
2664 } else {
2665 const char *str = cstr.data;
2666 const unsigned char *q;
2668 /* we look for a valid token */
2669 /* XXX: do more extensive checks */
2670 if (!strcmp(str, ">>=")) {
2671 tok = TOK_A_SAR;
2672 } else if (!strcmp(str, "<<=")) {
2673 tok = TOK_A_SHL;
2674 } else if (strlen(str) == 2) {
2675 /* search in two bytes table */
2676 q = tok_two_chars;
2677 for(;;) {
2678 if (!*q)
2679 goto error_pasting;
2680 if (q[0] == str[0] && q[1] == str[1])
2681 break;
2682 q += 3;
2684 tok = q[2];
2685 } else {
2686 error_pasting:
2687 /* NOTE: because get_tok_str use a static buffer,
2688 we must save it */
2689 cstr_reset(&cstr);
2690 p1 = get_tok_str(tok, &tokc);
2691 cstr_cat(&cstr, p1);
2692 cstr_ccat(&cstr, '\0');
2693 p2 = get_tok_str(t, &cval);
2694 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr.data, p2);
2695 /* cannot merge tokens: just add them separately */
2696 tok_str_add2(&macro_str1, tok, &tokc);
2697 /* XXX: free associated memory ? */
2698 tok = t;
2699 tokc = cval;
2704 tok_str_add2(&macro_str1, tok, &tokc);
2706 macro_ptr = (int *)saved_macro_ptr;
2707 cstr_free(&cstr);
2708 tok_str_add(&macro_str1, 0);
2709 return macro_str1.str;
2713 /* do macro substitution of macro_str and add result to
2714 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2715 inside to avoid recursing. */
2716 static void macro_subst(TokenString *tok_str, Sym **nested_list,
2717 const int *macro_str, struct macro_level ** can_read_stream)
2719 Sym *s;
2720 int *macro_str1;
2721 const int *ptr;
2722 int t, ret, spc;
2723 CValue cval;
2724 struct macro_level ml;
2726 /* first scan for '##' operator handling */
2727 ptr = macro_str;
2728 macro_str1 = macro_twosharps(ptr);
2729 if (macro_str1)
2730 ptr = macro_str1;
2731 spc = 0;
2732 while (1) {
2733 /* NOTE: ptr == NULL can only happen if tokens are read from
2734 file stream due to a macro function call */
2735 if (ptr == NULL)
2736 break;
2737 TOK_GET(t, ptr, cval);
2738 if (t == 0)
2739 break;
2740 s = define_find(t);
2741 if (s != NULL) {
2742 /* if nested substitution, do nothing */
2743 if (sym_find2(*nested_list, t))
2744 goto no_subst;
2745 ml.p = macro_ptr;
2746 if (can_read_stream)
2747 ml.prev = *can_read_stream, *can_read_stream = &ml;
2748 macro_ptr = (int *)ptr;
2749 tok = t;
2750 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
2751 ptr = (int *)macro_ptr;
2752 macro_ptr = ml.p;
2753 if (can_read_stream && *can_read_stream == &ml)
2754 *can_read_stream = ml.prev;
2755 if (ret != 0)
2756 goto no_subst;
2757 } else {
2758 no_subst:
2759 if (!check_space(t, &spc))
2760 tok_str_add2(tok_str, t, &cval);
2763 if (macro_str1)
2764 tok_str_free(macro_str1);
2767 /* return next token with macro substitution */
2768 static void next(void)
2770 Sym *nested_list, *s;
2771 TokenString str;
2772 struct macro_level *ml;
2774 redo:
2775 if (parse_flags & PARSE_FLAG_SPACES)
2776 next_nomacro_spc();
2777 else
2778 next_nomacro();
2779 if (!macro_ptr) {
2780 /* if not reading from macro substituted string, then try
2781 to substitute macros */
2782 if (tok >= TOK_IDENT &&
2783 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2784 s = define_find(tok);
2785 if (s) {
2786 /* we have a macro: we try to substitute */
2787 tok_str_new(&str);
2788 nested_list = NULL;
2789 ml = NULL;
2790 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
2791 /* substitution done, NOTE: maybe empty */
2792 tok_str_add(&str, 0);
2793 macro_ptr = str.str;
2794 macro_ptr_allocated = str.str;
2795 goto redo;
2799 } else {
2800 if (tok == 0) {
2801 /* end of macro or end of unget buffer */
2802 if (unget_buffer_enabled) {
2803 macro_ptr = unget_saved_macro_ptr;
2804 unget_buffer_enabled = 0;
2805 } else {
2806 /* end of macro string: free it */
2807 tok_str_free(macro_ptr_allocated);
2808 macro_ptr = NULL;
2810 goto redo;
2814 /* convert preprocessor tokens into C tokens */
2815 if (tok == TOK_PPNUM &&
2816 (parse_flags & PARSE_FLAG_TOK_NUM)) {
2817 parse_number((char *)tokc.cstr->data);
2821 /* push back current token and set current token to 'last_tok'. Only
2822 identifier case handled for labels. */
2823 static inline void unget_tok(int last_tok)
2825 int i, n;
2826 int *q;
2827 unget_saved_macro_ptr = macro_ptr;
2828 unget_buffer_enabled = 1;
2829 q = unget_saved_buffer;
2830 macro_ptr = q;
2831 *q++ = tok;
2832 n = tok_ext_size(tok) - 1;
2833 for(i=0;i<n;i++)
2834 *q++ = tokc.tab[i];
2835 *q = 0; /* end of token string */
2836 tok = last_tok;
2840 /* better than nothing, but needs extension to handle '-E' option
2841 correctly too */
2842 static void preprocess_init(TCCState *s1)
2844 s1->include_stack_ptr = s1->include_stack;
2845 /* XXX: move that before to avoid having to initialize
2846 file->ifdef_stack_ptr ? */
2847 s1->ifdef_stack_ptr = s1->ifdef_stack;
2848 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
2850 /* XXX: not ANSI compliant: bound checking says error */
2851 vtop = vstack - 1;
2852 s1->pack_stack[0] = 0;
2853 s1->pack_stack_ptr = s1->pack_stack;
2856 void preprocess_new()
2858 int i, c;
2859 const char *p, *r;
2860 TokenSym *ts;
2862 /* init isid table */
2863 for(i=CH_EOF;i<256;i++)
2864 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
2866 /* add all tokens */
2867 table_ident = NULL;
2868 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
2870 tok_ident = TOK_IDENT;
2871 p = tcc_keywords;
2872 while (*p) {
2873 r = p;
2874 for(;;) {
2875 c = *r++;
2876 if (c == '\0')
2877 break;
2879 ts = tok_alloc(p, r - p - 1);
2880 p = r;
2884 /* Preprocess the current file */
2885 static int tcc_preprocess(TCCState *s1)
2887 Sym *define_start;
2888 BufferedFile *file_ref;
2889 int token_seen, line_ref;
2891 preprocess_init(s1);
2892 define_start = define_stack;
2893 ch = file->buf_ptr[0];
2894 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
2895 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
2896 PARSE_FLAG_LINEFEED | PARSE_FLAG_SPACES;
2897 token_seen = 0;
2898 line_ref = 0;
2899 file_ref = NULL;
2901 for (;;) {
2902 next();
2903 if (tok == TOK_EOF) {
2904 break;
2905 } else if (tok == TOK_LINEFEED) {
2906 if (!token_seen)
2907 continue;
2908 ++line_ref;
2909 token_seen = 0;
2910 } else if (!token_seen) {
2911 int d = file->line_num - line_ref;
2912 if (file != file_ref || d < 0 || d >= 8)
2913 fprintf(s1->outfile, "# %d \"%s\"\n", file->line_num, file->filename);
2914 else
2915 while (d)
2916 fputs("\n", s1->outfile), --d;
2917 line_ref = (file_ref = file)->line_num;
2918 token_seen = 1;
2920 fputs(get_tok_str(tok, &tokc), s1->outfile);
2922 free_defines(define_start);
2923 return 0;