tccpe: use more official structs
[tinycc/kirr.git] / tccpp.c
blob1a9242b5e7731553e2386897b4d425ead8944d50
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 struct macro_level {
36 struct macro_level *prev;
37 int *p;
40 static void next_nomacro(void);
41 static void next_nomacro_spc(void);
42 static void macro_subst(TokenString *tok_str, Sym **nested_list,
43 const int *macro_str, struct macro_level **can_read_stream);
46 /* allocate a new token */
47 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
49 TokenSym *ts, **ptable;
50 int i;
52 if (tok_ident >= SYM_FIRST_ANOM)
53 error("memory full");
55 /* expand token table if needed */
56 i = tok_ident - TOK_IDENT;
57 if ((i % TOK_ALLOC_INCR) == 0) {
58 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
59 if (!ptable)
60 error("memory full");
61 table_ident = ptable;
64 ts = tcc_malloc(sizeof(TokenSym) + len);
65 table_ident[i] = ts;
66 ts->tok = tok_ident++;
67 ts->sym_define = NULL;
68 ts->sym_label = NULL;
69 ts->sym_struct = NULL;
70 ts->sym_identifier = NULL;
71 ts->len = len;
72 ts->hash_next = NULL;
73 memcpy(ts->str, str, len);
74 ts->str[len] = '\0';
75 *pts = ts;
76 return ts;
79 #define TOK_HASH_INIT 1
80 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
82 /* find a token and add it if not found */
83 static TokenSym *tok_alloc(const char *str, int len)
85 TokenSym *ts, **pts;
86 int i;
87 unsigned int h;
89 h = TOK_HASH_INIT;
90 for(i=0;i<len;i++)
91 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
92 h &= (TOK_HASH_SIZE - 1);
94 pts = &hash_ident[h];
95 for(;;) {
96 ts = *pts;
97 if (!ts)
98 break;
99 if (ts->len == len && !memcmp(ts->str, str, len))
100 return ts;
101 pts = &(ts->hash_next);
103 return tok_alloc_new(pts, str, len);
106 /* XXX: buffer overflow */
107 /* XXX: float tokens */
108 char *get_tok_str(int v, CValue *cv)
110 static char buf[STRING_MAX_SIZE + 1];
111 static CString cstr_buf;
112 CString *cstr;
113 unsigned char *q;
114 char *p;
115 int i, len;
117 /* NOTE: to go faster, we give a fixed buffer for small strings */
118 cstr_reset(&cstr_buf);
119 cstr_buf.data = buf;
120 cstr_buf.size_allocated = sizeof(buf);
121 p = buf;
123 switch(v) {
124 case TOK_CINT:
125 case TOK_CUINT:
126 /* XXX: not quite exact, but only useful for testing */
127 sprintf(p, "%u", cv->ui);
128 break;
129 case TOK_CLLONG:
130 case TOK_CULLONG:
131 /* XXX: not quite exact, but only useful for testing */
132 sprintf(p, "%Lu", cv->ull);
133 break;
134 case TOK_LCHAR:
135 cstr_ccat(&cstr_buf, 'L');
136 case TOK_CCHAR:
137 cstr_ccat(&cstr_buf, '\'');
138 add_char(&cstr_buf, cv->i);
139 cstr_ccat(&cstr_buf, '\'');
140 cstr_ccat(&cstr_buf, '\0');
141 break;
142 case TOK_PPNUM:
143 cstr = cv->cstr;
144 len = cstr->size - 1;
145 for(i=0;i<len;i++)
146 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
147 cstr_ccat(&cstr_buf, '\0');
148 break;
149 case TOK_LSTR:
150 cstr_ccat(&cstr_buf, 'L');
151 case TOK_STR:
152 cstr = cv->cstr;
153 cstr_ccat(&cstr_buf, '\"');
154 if (v == TOK_STR) {
155 len = cstr->size - 1;
156 for(i=0;i<len;i++)
157 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
158 } else {
159 len = (cstr->size / sizeof(nwchar_t)) - 1;
160 for(i=0;i<len;i++)
161 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
163 cstr_ccat(&cstr_buf, '\"');
164 cstr_ccat(&cstr_buf, '\0');
165 break;
166 case TOK_LT:
167 v = '<';
168 goto addv;
169 case TOK_GT:
170 v = '>';
171 goto addv;
172 case TOK_DOTS:
173 return strcpy(p, "...");
174 case TOK_A_SHL:
175 return strcpy(p, "<<=");
176 case TOK_A_SAR:
177 return strcpy(p, ">>=");
178 default:
179 if (v < TOK_IDENT) {
180 /* search in two bytes table */
181 q = tok_two_chars;
182 while (*q) {
183 if (q[2] == v) {
184 *p++ = q[0];
185 *p++ = q[1];
186 *p = '\0';
187 return buf;
189 q += 3;
191 addv:
192 *p++ = v;
193 *p = '\0';
194 } else if (v < tok_ident) {
195 return table_ident[v - TOK_IDENT]->str;
196 } else if (v >= SYM_FIRST_ANOM) {
197 /* special name for anonymous symbol */
198 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
199 } else {
200 /* should never happen */
201 return NULL;
203 break;
205 return cstr_buf.data;
208 /* fill input buffer and peek next char */
209 static int tcc_peekc_slow(BufferedFile *bf)
211 int len;
212 /* only tries to read if really end of buffer */
213 if (bf->buf_ptr >= bf->buf_end) {
214 if (bf->fd != -1) {
215 #if defined(PARSE_DEBUG)
216 len = 8;
217 #else
218 len = IO_BUF_SIZE;
219 #endif
220 len = read(bf->fd, bf->buffer, len);
221 if (len < 0)
222 len = 0;
223 } else {
224 len = 0;
226 total_bytes += len;
227 bf->buf_ptr = bf->buffer;
228 bf->buf_end = bf->buffer + len;
229 *bf->buf_end = CH_EOB;
231 if (bf->buf_ptr < bf->buf_end) {
232 return bf->buf_ptr[0];
233 } else {
234 bf->buf_ptr = bf->buf_end;
235 return CH_EOF;
239 /* return the current character, handling end of block if necessary
240 (but not stray) */
241 static int handle_eob(void)
243 return tcc_peekc_slow(file);
246 /* read next char from current input file and handle end of input buffer */
247 static inline void inp(void)
249 ch = *(++(file->buf_ptr));
250 /* end of buffer/file handling */
251 if (ch == CH_EOB)
252 ch = handle_eob();
255 /* handle '\[\r]\n' */
256 static int handle_stray_noerror(void)
258 while (ch == '\\') {
259 inp();
260 if (ch == '\n') {
261 file->line_num++;
262 inp();
263 } else if (ch == '\r') {
264 inp();
265 if (ch != '\n')
266 goto fail;
267 file->line_num++;
268 inp();
269 } else {
270 fail:
271 return 1;
274 return 0;
277 static void handle_stray(void)
279 if (handle_stray_noerror())
280 error("stray '\\' in program");
283 /* skip the stray and handle the \\n case. Output an error if
284 incorrect char after the stray */
285 static int handle_stray1(uint8_t *p)
287 int c;
289 if (p >= file->buf_end) {
290 file->buf_ptr = p;
291 c = handle_eob();
292 p = file->buf_ptr;
293 if (c == '\\')
294 goto parse_stray;
295 } else {
296 parse_stray:
297 file->buf_ptr = p;
298 ch = *p;
299 handle_stray();
300 p = file->buf_ptr;
301 c = *p;
303 return c;
306 /* handle just the EOB case, but not stray */
307 #define PEEKC_EOB(c, p)\
309 p++;\
310 c = *p;\
311 if (c == '\\') {\
312 file->buf_ptr = p;\
313 c = handle_eob();\
314 p = file->buf_ptr;\
318 /* handle the complicated stray case */
319 #define PEEKC(c, p)\
321 p++;\
322 c = *p;\
323 if (c == '\\') {\
324 c = handle_stray1(p);\
325 p = file->buf_ptr;\
329 /* input with '\[\r]\n' handling. Note that this function cannot
330 handle other characters after '\', so you cannot call it inside
331 strings or comments */
332 static void minp(void)
334 inp();
335 if (ch == '\\')
336 handle_stray();
340 /* single line C++ comments */
341 static uint8_t *parse_line_comment(uint8_t *p)
343 int c;
345 p++;
346 for(;;) {
347 c = *p;
348 redo:
349 if (c == '\n' || c == CH_EOF) {
350 break;
351 } else if (c == '\\') {
352 file->buf_ptr = p;
353 c = handle_eob();
354 p = file->buf_ptr;
355 if (c == '\\') {
356 PEEKC_EOB(c, p);
357 if (c == '\n') {
358 file->line_num++;
359 PEEKC_EOB(c, p);
360 } else if (c == '\r') {
361 PEEKC_EOB(c, p);
362 if (c == '\n') {
363 file->line_num++;
364 PEEKC_EOB(c, p);
367 } else {
368 goto redo;
370 } else {
371 p++;
374 return p;
377 /* C comments */
378 static uint8_t *parse_comment(uint8_t *p)
380 int c;
382 p++;
383 for(;;) {
384 /* fast skip loop */
385 for(;;) {
386 c = *p;
387 if (c == '\n' || c == '*' || c == '\\')
388 break;
389 p++;
390 c = *p;
391 if (c == '\n' || c == '*' || c == '\\')
392 break;
393 p++;
395 /* now we can handle all the cases */
396 if (c == '\n') {
397 file->line_num++;
398 p++;
399 } else if (c == '*') {
400 p++;
401 for(;;) {
402 c = *p;
403 if (c == '*') {
404 p++;
405 } else if (c == '/') {
406 goto end_of_comment;
407 } else if (c == '\\') {
408 file->buf_ptr = p;
409 c = handle_eob();
410 p = file->buf_ptr;
411 if (c == '\\') {
412 /* skip '\[\r]\n', otherwise just skip the stray */
413 while (c == '\\') {
414 PEEKC_EOB(c, p);
415 if (c == '\n') {
416 file->line_num++;
417 PEEKC_EOB(c, p);
418 } else if (c == '\r') {
419 PEEKC_EOB(c, p);
420 if (c == '\n') {
421 file->line_num++;
422 PEEKC_EOB(c, p);
424 } else {
425 goto after_star;
429 } else {
430 break;
433 after_star: ;
434 } else {
435 /* stray, eob or eof */
436 file->buf_ptr = p;
437 c = handle_eob();
438 p = file->buf_ptr;
439 if (c == CH_EOF) {
440 error("unexpected end of file in comment");
441 } else if (c == '\\') {
442 p++;
446 end_of_comment:
447 p++;
448 return p;
451 #define cinp minp
453 static inline void skip_spaces(void)
455 while (is_space(ch))
456 cinp();
459 static inline int check_space(int t, int *spc)
461 if (is_space(t)) {
462 if (*spc)
463 return 1;
464 *spc = 1;
465 } else
466 *spc = 0;
467 return 0;
470 /* parse a string without interpreting escapes */
471 static uint8_t *parse_pp_string(uint8_t *p,
472 int sep, CString *str)
474 int c;
475 p++;
476 for(;;) {
477 c = *p;
478 if (c == sep) {
479 break;
480 } else if (c == '\\') {
481 file->buf_ptr = p;
482 c = handle_eob();
483 p = file->buf_ptr;
484 if (c == CH_EOF) {
485 unterminated_string:
486 /* XXX: indicate line number of start of string */
487 error("missing terminating %c character", sep);
488 } else if (c == '\\') {
489 /* escape : just skip \[\r]\n */
490 PEEKC_EOB(c, p);
491 if (c == '\n') {
492 file->line_num++;
493 p++;
494 } else if (c == '\r') {
495 PEEKC_EOB(c, p);
496 if (c != '\n')
497 expect("'\n' after '\r'");
498 file->line_num++;
499 p++;
500 } else if (c == CH_EOF) {
501 goto unterminated_string;
502 } else {
503 if (str) {
504 cstr_ccat(str, '\\');
505 cstr_ccat(str, c);
507 p++;
510 } else if (c == '\n') {
511 file->line_num++;
512 goto add_char;
513 } else if (c == '\r') {
514 PEEKC_EOB(c, p);
515 if (c != '\n') {
516 if (str)
517 cstr_ccat(str, '\r');
518 } else {
519 file->line_num++;
520 goto add_char;
522 } else {
523 add_char:
524 if (str)
525 cstr_ccat(str, c);
526 p++;
529 p++;
530 return p;
533 /* skip block of text until #else, #elif or #endif. skip also pairs of
534 #if/#endif */
535 void preprocess_skip(void)
537 int a, start_of_line, c, in_warn_or_error;
538 uint8_t *p;
540 p = file->buf_ptr;
541 a = 0;
542 redo_start:
543 start_of_line = 1;
544 in_warn_or_error = 0;
545 for(;;) {
546 redo_no_start:
547 c = *p;
548 switch(c) {
549 case ' ':
550 case '\t':
551 case '\f':
552 case '\v':
553 case '\r':
554 p++;
555 goto redo_no_start;
556 case '\n':
557 file->line_num++;
558 p++;
559 goto redo_start;
560 case '\\':
561 file->buf_ptr = p;
562 c = handle_eob();
563 if (c == CH_EOF) {
564 expect("#endif");
565 } else if (c == '\\') {
566 ch = file->buf_ptr[0];
567 handle_stray_noerror();
569 p = file->buf_ptr;
570 goto redo_no_start;
571 /* skip strings */
572 case '\"':
573 case '\'':
574 if (in_warn_or_error)
575 goto _default;
576 p = parse_pp_string(p, c, NULL);
577 break;
578 /* skip comments */
579 case '/':
580 if (in_warn_or_error)
581 goto _default;
582 file->buf_ptr = p;
583 ch = *p;
584 minp();
585 p = file->buf_ptr;
586 if (ch == '*') {
587 p = parse_comment(p);
588 } else if (ch == '/') {
589 p = parse_line_comment(p);
591 break;
592 case '#':
593 p++;
594 if (start_of_line) {
595 file->buf_ptr = p;
596 next_nomacro();
597 p = file->buf_ptr;
598 if (a == 0 &&
599 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
600 goto the_end;
601 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
602 a++;
603 else if (tok == TOK_ENDIF)
604 a--;
605 else if( tok == TOK_ERROR || tok == TOK_WARNING)
606 in_warn_or_error = 1;
608 break;
609 _default:
610 default:
611 p++;
612 break;
614 start_of_line = 0;
616 the_end: ;
617 file->buf_ptr = p;
620 /* ParseState handling */
622 /* XXX: currently, no include file info is stored. Thus, we cannot display
623 accurate messages if the function or data definition spans multiple
624 files */
626 /* save current parse state in 's' */
627 void save_parse_state(ParseState *s)
629 s->line_num = file->line_num;
630 s->macro_ptr = macro_ptr;
631 s->tok = tok;
632 s->tokc = tokc;
635 /* restore parse state from 's' */
636 void restore_parse_state(ParseState *s)
638 file->line_num = s->line_num;
639 macro_ptr = s->macro_ptr;
640 tok = s->tok;
641 tokc = s->tokc;
644 /* return the number of additional 'ints' necessary to store the
645 token */
646 static inline int tok_ext_size(int t)
648 switch(t) {
649 /* 4 bytes */
650 case TOK_CINT:
651 case TOK_CUINT:
652 case TOK_CCHAR:
653 case TOK_LCHAR:
654 case TOK_CFLOAT:
655 case TOK_LINENUM:
656 return 1;
657 case TOK_STR:
658 case TOK_LSTR:
659 case TOK_PPNUM:
660 error("unsupported token");
661 return 1;
662 case TOK_CDOUBLE:
663 case TOK_CLLONG:
664 case TOK_CULLONG:
665 return 2;
666 case TOK_CLDOUBLE:
667 return LDOUBLE_SIZE / 4;
668 default:
669 return 0;
673 /* token string handling */
675 static inline void tok_str_new(TokenString *s)
677 s->str = NULL;
678 s->len = 0;
679 s->allocated_len = 0;
680 s->last_line_num = -1;
683 static void tok_str_free(int *str)
685 tcc_free(str);
688 static int *tok_str_realloc(TokenString *s)
690 int *str, len;
692 if (s->allocated_len == 0) {
693 len = 8;
694 } else {
695 len = s->allocated_len * 2;
697 str = tcc_realloc(s->str, len * sizeof(int));
698 if (!str)
699 error("memory full");
700 s->allocated_len = len;
701 s->str = str;
702 return str;
705 static void tok_str_add(TokenString *s, int t)
707 int len, *str;
709 len = s->len;
710 str = s->str;
711 if (len >= s->allocated_len)
712 str = tok_str_realloc(s);
713 str[len++] = t;
714 s->len = len;
717 static void tok_str_add2(TokenString *s, int t, CValue *cv)
719 int len, *str;
721 len = s->len;
722 str = s->str;
724 /* allocate space for worst case */
725 if (len + TOK_MAX_SIZE > s->allocated_len)
726 str = tok_str_realloc(s);
727 str[len++] = t;
728 switch(t) {
729 case TOK_CINT:
730 case TOK_CUINT:
731 case TOK_CCHAR:
732 case TOK_LCHAR:
733 case TOK_CFLOAT:
734 case TOK_LINENUM:
735 str[len++] = cv->tab[0];
736 break;
737 case TOK_PPNUM:
738 case TOK_STR:
739 case TOK_LSTR:
741 int nb_words;
742 CString *cstr;
744 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
745 while ((len + nb_words) > s->allocated_len)
746 str = tok_str_realloc(s);
747 cstr = (CString *)(str + len);
748 cstr->data = NULL;
749 cstr->size = cv->cstr->size;
750 cstr->data_allocated = NULL;
751 cstr->size_allocated = cstr->size;
752 memcpy((char *)cstr + sizeof(CString),
753 cv->cstr->data, cstr->size);
754 len += nb_words;
756 break;
757 case TOK_CDOUBLE:
758 case TOK_CLLONG:
759 case TOK_CULLONG:
760 #if LDOUBLE_SIZE == 8
761 case TOK_CLDOUBLE:
762 #endif
763 str[len++] = cv->tab[0];
764 str[len++] = cv->tab[1];
765 break;
766 #if LDOUBLE_SIZE == 12
767 case TOK_CLDOUBLE:
768 str[len++] = cv->tab[0];
769 str[len++] = cv->tab[1];
770 str[len++] = cv->tab[2];
771 #elif LDOUBLE_SIZE == 16
772 case TOK_CLDOUBLE:
773 str[len++] = cv->tab[0];
774 str[len++] = cv->tab[1];
775 str[len++] = cv->tab[2];
776 str[len++] = cv->tab[3];
777 #elif LDOUBLE_SIZE != 8
778 #error add long double size support
779 #endif
780 break;
781 default:
782 break;
784 s->len = len;
787 /* add the current parse token in token string 's' */
788 static void tok_str_add_tok(TokenString *s)
790 CValue cval;
792 /* save line number info */
793 if (file->line_num != s->last_line_num) {
794 s->last_line_num = file->line_num;
795 cval.i = s->last_line_num;
796 tok_str_add2(s, TOK_LINENUM, &cval);
798 tok_str_add2(s, tok, &tokc);
801 #if LDOUBLE_SIZE == 16
802 #define LDOUBLE_GET(p, cv) \
803 cv.tab[0] = p[0]; \
804 cv.tab[1] = p[1]; \
805 cv.tab[2] = p[2]; \
806 cv.tab[3] = p[3];
807 #elif LDOUBLE_SIZE == 12
808 #define LDOUBLE_GET(p, cv) \
809 cv.tab[0] = p[0]; \
810 cv.tab[1] = p[1]; \
811 cv.tab[2] = p[2];
812 #elif LDOUBLE_SIZE == 8
813 #define LDOUBLE_GET(p, cv) \
814 cv.tab[0] = p[0]; \
815 cv.tab[1] = p[1];
816 #else
817 #error add long double size support
818 #endif
821 /* get a token from an integer array and increment pointer
822 accordingly. we code it as a macro to avoid pointer aliasing. */
823 #define TOK_GET(t, p, cv) \
825 t = *p++; \
826 switch(t) { \
827 case TOK_CINT: \
828 case TOK_CUINT: \
829 case TOK_CCHAR: \
830 case TOK_LCHAR: \
831 case TOK_CFLOAT: \
832 case TOK_LINENUM: \
833 cv.tab[0] = *p++; \
834 break; \
835 case TOK_STR: \
836 case TOK_LSTR: \
837 case TOK_PPNUM: \
838 cv.cstr = (CString *)p; \
839 cv.cstr->data = (char *)p + sizeof(CString);\
840 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
841 break; \
842 case TOK_CDOUBLE: \
843 case TOK_CLLONG: \
844 case TOK_CULLONG: \
845 cv.tab[0] = p[0]; \
846 cv.tab[1] = p[1]; \
847 p += 2; \
848 break; \
849 case TOK_CLDOUBLE: \
850 LDOUBLE_GET(p, cv); \
851 p += LDOUBLE_SIZE / 4; \
852 break; \
853 default: \
854 break; \
858 /* defines handling */
859 static inline void define_push(int v, int macro_type, int *str, Sym *first_arg)
861 Sym *s;
863 s = sym_push2(&define_stack, v, macro_type, 0);
864 s->d = str;
865 s->next = first_arg;
866 table_ident[v - TOK_IDENT]->sym_define = s;
869 /* undefined a define symbol. Its name is just set to zero */
870 static void define_undef(Sym *s)
872 int v;
873 v = s->v;
874 if (v >= TOK_IDENT && v < tok_ident)
875 table_ident[v - TOK_IDENT]->sym_define = NULL;
876 s->v = 0;
879 static inline Sym *define_find(int v)
881 v -= TOK_IDENT;
882 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
883 return NULL;
884 return table_ident[v]->sym_define;
887 /* free define stack until top reaches 'b' */
888 static void free_defines(Sym *b)
890 Sym *top, *top1;
891 int v;
893 top = define_stack;
894 while (top != b) {
895 top1 = top->prev;
896 /* do not free args or predefined defines */
897 if (top->d)
898 tok_str_free(top->d);
899 v = top->v;
900 if (v >= TOK_IDENT && v < tok_ident)
901 table_ident[v - TOK_IDENT]->sym_define = NULL;
902 sym_free(top);
903 top = top1;
905 define_stack = b;
908 /* label lookup */
909 static Sym *label_find(int v)
911 v -= TOK_IDENT;
912 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
913 return NULL;
914 return table_ident[v]->sym_label;
917 static Sym *label_push(Sym **ptop, int v, int flags)
919 Sym *s, **ps;
920 s = sym_push2(ptop, v, 0, 0);
921 s->r = flags;
922 ps = &table_ident[v - TOK_IDENT]->sym_label;
923 if (ptop == &global_label_stack) {
924 /* modify the top most local identifier, so that
925 sym_identifier will point to 's' when popped */
926 while (*ps != NULL)
927 ps = &(*ps)->prev_tok;
929 s->prev_tok = *ps;
930 *ps = s;
931 return s;
934 /* pop labels until element last is reached. Look if any labels are
935 undefined. Define symbols if '&&label' was used. */
936 static void label_pop(Sym **ptop, Sym *slast)
938 Sym *s, *s1;
939 for(s = *ptop; s != slast; s = s1) {
940 s1 = s->prev;
941 if (s->r == LABEL_DECLARED) {
942 warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
943 } else if (s->r == LABEL_FORWARD) {
944 error("label '%s' used but not defined",
945 get_tok_str(s->v, NULL));
946 } else {
947 if (s->c) {
948 /* define corresponding symbol. A size of
949 1 is put. */
950 put_extern_sym(s, cur_text_section, (long)s->next, 1);
953 /* remove label */
954 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
955 sym_free(s);
957 *ptop = slast;
960 /* eval an expression for #if/#elif */
961 static int expr_preprocess(void)
963 int c, t;
964 TokenString str;
966 tok_str_new(&str);
967 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
968 next(); /* do macro subst */
969 if (tok == TOK_DEFINED) {
970 next_nomacro();
971 t = tok;
972 if (t == '(')
973 next_nomacro();
974 c = define_find(tok) != 0;
975 if (t == '(')
976 next_nomacro();
977 tok = TOK_CINT;
978 tokc.i = c;
979 } else if (tok >= TOK_IDENT) {
980 /* if undefined macro */
981 tok = TOK_CINT;
982 tokc.i = 0;
984 tok_str_add_tok(&str);
986 tok_str_add(&str, -1); /* simulate end of file */
987 tok_str_add(&str, 0);
988 /* now evaluate C constant expression */
989 macro_ptr = str.str;
990 next();
991 c = expr_const();
992 macro_ptr = NULL;
993 tok_str_free(str.str);
994 return c != 0;
997 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
998 static void tok_print(int *str)
1000 int t;
1001 CValue cval;
1003 printf("<");
1004 while (1) {
1005 TOK_GET(t, str, cval);
1006 if (!t)
1007 break;
1008 printf("%s", get_tok_str(t, &cval));
1010 printf(">\n");
1012 #endif
1014 /* parse after #define */
1015 static void parse_define(void)
1017 Sym *s, *first, **ps;
1018 int v, t, varg, is_vaargs, spc;
1019 TokenString str;
1021 v = tok;
1022 if (v < TOK_IDENT)
1023 error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1024 /* XXX: should check if same macro (ANSI) */
1025 first = NULL;
1026 t = MACRO_OBJ;
1027 /* '(' must be just after macro definition for MACRO_FUNC */
1028 next_nomacro_spc();
1029 if (tok == '(') {
1030 next_nomacro();
1031 ps = &first;
1032 while (tok != ')') {
1033 varg = tok;
1034 next_nomacro();
1035 is_vaargs = 0;
1036 if (varg == TOK_DOTS) {
1037 varg = TOK___VA_ARGS__;
1038 is_vaargs = 1;
1039 } else if (tok == TOK_DOTS && gnu_ext) {
1040 is_vaargs = 1;
1041 next_nomacro();
1043 if (varg < TOK_IDENT)
1044 error("badly punctuated parameter list");
1045 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1046 *ps = s;
1047 ps = &s->next;
1048 if (tok != ',')
1049 break;
1050 next_nomacro();
1052 if (tok == ')')
1053 next_nomacro_spc();
1054 t = MACRO_FUNC;
1056 tok_str_new(&str);
1057 spc = 2;
1058 /* EOF testing necessary for '-D' handling */
1059 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1060 /* remove spaces around ## and after '#' */
1061 if (TOK_TWOSHARPS == tok) {
1062 if (1 == spc)
1063 --str.len;
1064 spc = 2;
1065 } else if ('#' == tok) {
1066 spc = 2;
1067 } else if (check_space(tok, &spc)) {
1068 goto skip;
1070 tok_str_add2(&str, tok, &tokc);
1071 skip:
1072 next_nomacro_spc();
1074 if (spc == 1)
1075 --str.len; /* remove trailing space */
1076 tok_str_add(&str, 0);
1077 #ifdef PP_DEBUG
1078 printf("define %s %d: ", get_tok_str(v, NULL), t);
1079 tok_print(str.str);
1080 #endif
1081 define_push(v, t, str.str, first);
1084 static inline int hash_cached_include(int type, const char *filename)
1086 const unsigned char *s;
1087 unsigned int h;
1089 h = TOK_HASH_INIT;
1090 h = TOK_HASH_FUNC(h, type);
1091 s = filename;
1092 while (*s) {
1093 h = TOK_HASH_FUNC(h, *s);
1094 s++;
1096 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1097 return h;
1100 /* XXX: use a token or a hash table to accelerate matching ? */
1101 static CachedInclude *search_cached_include(TCCState *s1,
1102 int type, const char *filename)
1104 CachedInclude *e;
1105 int i, h;
1106 h = hash_cached_include(type, filename);
1107 i = s1->cached_includes_hash[h];
1108 for(;;) {
1109 if (i == 0)
1110 break;
1111 e = s1->cached_includes[i - 1];
1112 if (e->type == type && !PATHCMP(e->filename, filename))
1113 return e;
1114 i = e->hash_next;
1116 return NULL;
1119 static inline void add_cached_include(TCCState *s1, int type,
1120 const char *filename, int ifndef_macro)
1122 CachedInclude *e;
1123 int h;
1125 if (search_cached_include(s1, type, filename))
1126 return;
1127 #ifdef INC_DEBUG
1128 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
1129 #endif
1130 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1131 if (!e)
1132 return;
1133 e->type = type;
1134 strcpy(e->filename, filename);
1135 e->ifndef_macro = ifndef_macro;
1136 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1137 /* add in hash table */
1138 h = hash_cached_include(type, filename);
1139 e->hash_next = s1->cached_includes_hash[h];
1140 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1143 static void pragma_parse(TCCState *s1)
1145 int val;
1147 next();
1148 if (tok == TOK_pack) {
1150 This may be:
1151 #pragma pack(1) // set
1152 #pragma pack() // reset to default
1153 #pragma pack(push,1) // push & set
1154 #pragma pack(pop) // restore previous
1156 next();
1157 skip('(');
1158 if (tok == TOK_ASM_pop) {
1159 next();
1160 if (s1->pack_stack_ptr <= s1->pack_stack) {
1161 stk_error:
1162 error("out of pack stack");
1164 s1->pack_stack_ptr--;
1165 } else {
1166 val = 0;
1167 if (tok != ')') {
1168 if (tok == TOK_ASM_push) {
1169 next();
1170 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1171 goto stk_error;
1172 s1->pack_stack_ptr++;
1173 skip(',');
1175 if (tok != TOK_CINT) {
1176 pack_error:
1177 error("invalid pack pragma");
1179 val = tokc.i;
1180 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1181 goto pack_error;
1182 next();
1184 *s1->pack_stack_ptr = val;
1185 skip(')');
1190 /* is_bof is true if first non space token at beginning of file */
1191 static void preprocess(int is_bof)
1193 TCCState *s1 = tcc_state;
1194 int i, c, n, saved_parse_flags;
1195 char buf[1024], *q;
1196 Sym *s;
1198 saved_parse_flags = parse_flags;
1199 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
1200 PARSE_FLAG_LINEFEED;
1201 next_nomacro();
1202 redo:
1203 switch(tok) {
1204 case TOK_DEFINE:
1205 next_nomacro();
1206 parse_define();
1207 break;
1208 case TOK_UNDEF:
1209 next_nomacro();
1210 s = define_find(tok);
1211 /* undefine symbol by putting an invalid name */
1212 if (s)
1213 define_undef(s);
1214 break;
1215 case TOK_INCLUDE:
1216 case TOK_INCLUDE_NEXT:
1217 ch = file->buf_ptr[0];
1218 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1219 skip_spaces();
1220 if (ch == '<') {
1221 c = '>';
1222 goto read_name;
1223 } else if (ch == '\"') {
1224 c = ch;
1225 read_name:
1226 inp();
1227 q = buf;
1228 while (ch != c && ch != '\n' && ch != CH_EOF) {
1229 if ((q - buf) < sizeof(buf) - 1)
1230 *q++ = ch;
1231 if (ch == '\\') {
1232 if (handle_stray_noerror() == 0)
1233 --q;
1234 } else
1235 inp();
1237 *q = '\0';
1238 minp();
1239 #if 0
1240 /* eat all spaces and comments after include */
1241 /* XXX: slightly incorrect */
1242 while (ch1 != '\n' && ch1 != CH_EOF)
1243 inp();
1244 #endif
1245 } else {
1246 /* computed #include : either we have only strings or
1247 we have anything enclosed in '<>' */
1248 next();
1249 buf[0] = '\0';
1250 if (tok == TOK_STR) {
1251 while (tok != TOK_LINEFEED) {
1252 if (tok != TOK_STR) {
1253 include_syntax:
1254 error("'#include' expects \"FILENAME\" or <FILENAME>");
1256 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
1257 next();
1259 c = '\"';
1260 } else {
1261 int len;
1262 while (tok != TOK_LINEFEED) {
1263 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1264 next();
1266 len = strlen(buf);
1267 /* check syntax and remove '<>' */
1268 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1269 goto include_syntax;
1270 memmove(buf, buf + 1, len - 2);
1271 buf[len - 2] = '\0';
1272 c = '>';
1276 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1277 error("#include recursion too deep");
1279 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
1280 for (i = -2; i < n; ++i) {
1281 char buf1[sizeof file->filename];
1282 BufferedFile *f;
1283 CachedInclude *e;
1284 const char *path;
1285 int size;
1287 if (i == -2) {
1288 /* check absolute include path */
1289 if (!IS_ABSPATH(buf))
1290 continue;
1291 buf1[0] = 0;
1293 } else if (i == -1) {
1294 /* search in current dir if "header.h" */
1295 if (c != '\"')
1296 continue;
1297 size = tcc_basename(file->filename) - file->filename;
1298 memcpy(buf1, file->filename, size);
1299 buf1[size] = '\0';
1301 } else {
1302 /* search in all the include paths */
1303 if (i < s1->nb_include_paths)
1304 path = s1->include_paths[i];
1305 else
1306 path = s1->sysinclude_paths[i - s1->nb_include_paths];
1307 pstrcpy(buf1, sizeof(buf1), path);
1308 pstrcat(buf1, sizeof(buf1), "/");
1311 pstrcat(buf1, sizeof(buf1), buf);
1313 e = search_cached_include(s1, c, buf1);
1314 if (e && define_find(e->ifndef_macro)) {
1315 /* no need to parse the include because the 'ifndef macro'
1316 is defined */
1317 #ifdef INC_DEBUG
1318 printf("%s: skipping %s\n", file->filename, buf);
1319 #endif
1320 f = NULL;
1321 } else {
1322 f = tcc_open(s1, buf1);
1323 if (!f)
1324 continue;
1327 if (tok == TOK_INCLUDE_NEXT) {
1328 tok = TOK_INCLUDE;
1329 if (f)
1330 tcc_close(f);
1331 continue;
1334 if (!f)
1335 goto include_done;
1337 #ifdef INC_DEBUG
1338 printf("%s: including %s\n", file->filename, buf1);
1339 #endif
1341 /* XXX: fix current line init */
1342 /* push current file in stack */
1343 *s1->include_stack_ptr++ = file;
1344 f->inc_type = c;
1345 pstrcpy(f->inc_filename, sizeof(f->inc_filename), buf1);
1346 file = f;
1347 /* add include file debug info */
1348 if (tcc_state->do_debug) {
1349 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1351 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1352 ch = file->buf_ptr[0];
1353 goto the_end;
1355 error("include file '%s' not found", buf);
1356 include_done:
1357 break;
1358 case TOK_IFNDEF:
1359 c = 1;
1360 goto do_ifdef;
1361 case TOK_IF:
1362 c = expr_preprocess();
1363 goto do_if;
1364 case TOK_IFDEF:
1365 c = 0;
1366 do_ifdef:
1367 next_nomacro();
1368 if (tok < TOK_IDENT)
1369 error("invalid argument for '#if%sdef'", c ? "n" : "");
1370 if (is_bof) {
1371 if (c) {
1372 #ifdef INC_DEBUG
1373 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1374 #endif
1375 file->ifndef_macro = tok;
1378 c = (define_find(tok) != 0) ^ c;
1379 do_if:
1380 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1381 error("memory full");
1382 *s1->ifdef_stack_ptr++ = c;
1383 goto test_skip;
1384 case TOK_ELSE:
1385 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1386 error("#else without matching #if");
1387 if (s1->ifdef_stack_ptr[-1] & 2)
1388 error("#else after #else");
1389 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1390 goto test_skip;
1391 case TOK_ELIF:
1392 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1393 error("#elif without matching #if");
1394 c = s1->ifdef_stack_ptr[-1];
1395 if (c > 1)
1396 error("#elif after #else");
1397 /* last #if/#elif expression was true: we skip */
1398 if (c == 1)
1399 goto skip;
1400 c = expr_preprocess();
1401 s1->ifdef_stack_ptr[-1] = c;
1402 test_skip:
1403 if (!(c & 1)) {
1404 skip:
1405 preprocess_skip();
1406 is_bof = 0;
1407 goto redo;
1409 break;
1410 case TOK_ENDIF:
1411 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1412 error("#endif without matching #if");
1413 s1->ifdef_stack_ptr--;
1414 /* '#ifndef macro' was at the start of file. Now we check if
1415 an '#endif' is exactly at the end of file */
1416 if (file->ifndef_macro &&
1417 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1418 file->ifndef_macro_saved = file->ifndef_macro;
1419 /* need to set to zero to avoid false matches if another
1420 #ifndef at middle of file */
1421 file->ifndef_macro = 0;
1422 while (tok != TOK_LINEFEED)
1423 next_nomacro();
1424 tok_flags |= TOK_FLAG_ENDIF;
1425 goto the_end;
1427 break;
1428 case TOK_LINE:
1429 next();
1430 if (tok != TOK_CINT)
1431 error("#line");
1432 file->line_num = tokc.i - 1; /* the line number will be incremented after */
1433 next();
1434 if (tok != TOK_LINEFEED) {
1435 if (tok != TOK_STR)
1436 error("#line");
1437 pstrcpy(file->filename, sizeof(file->filename),
1438 (char *)tokc.cstr->data);
1440 break;
1441 case TOK_ERROR:
1442 case TOK_WARNING:
1443 c = tok;
1444 ch = file->buf_ptr[0];
1445 skip_spaces();
1446 q = buf;
1447 while (ch != '\n' && ch != CH_EOF) {
1448 if ((q - buf) < sizeof(buf) - 1)
1449 *q++ = ch;
1450 if (ch == '\\') {
1451 if (handle_stray_noerror() == 0)
1452 --q;
1453 } else
1454 inp();
1456 *q = '\0';
1457 if (c == TOK_ERROR)
1458 error("#error %s", buf);
1459 else
1460 warning("#warning %s", buf);
1461 break;
1462 case TOK_PRAGMA:
1463 pragma_parse(s1);
1464 break;
1465 default:
1466 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_CINT) {
1467 /* '!' is ignored to allow C scripts. numbers are ignored
1468 to emulate cpp behaviour */
1469 } else {
1470 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
1471 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1473 break;
1475 /* ignore other preprocess commands or #! for C scripts */
1476 while (tok != TOK_LINEFEED)
1477 next_nomacro();
1478 the_end:
1479 parse_flags = saved_parse_flags;
1482 /* evaluate escape codes in a string. */
1483 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1485 int c, n;
1486 const uint8_t *p;
1488 p = buf;
1489 for(;;) {
1490 c = *p;
1491 if (c == '\0')
1492 break;
1493 if (c == '\\') {
1494 p++;
1495 /* escape */
1496 c = *p;
1497 switch(c) {
1498 case '0': case '1': case '2': case '3':
1499 case '4': case '5': case '6': case '7':
1500 /* at most three octal digits */
1501 n = c - '0';
1502 p++;
1503 c = *p;
1504 if (isoct(c)) {
1505 n = n * 8 + c - '0';
1506 p++;
1507 c = *p;
1508 if (isoct(c)) {
1509 n = n * 8 + c - '0';
1510 p++;
1513 c = n;
1514 goto add_char_nonext;
1515 case 'x':
1516 case 'u':
1517 case 'U':
1518 p++;
1519 n = 0;
1520 for(;;) {
1521 c = *p;
1522 if (c >= 'a' && c <= 'f')
1523 c = c - 'a' + 10;
1524 else if (c >= 'A' && c <= 'F')
1525 c = c - 'A' + 10;
1526 else if (isnum(c))
1527 c = c - '0';
1528 else
1529 break;
1530 n = n * 16 + c;
1531 p++;
1533 c = n;
1534 goto add_char_nonext;
1535 case 'a':
1536 c = '\a';
1537 break;
1538 case 'b':
1539 c = '\b';
1540 break;
1541 case 'f':
1542 c = '\f';
1543 break;
1544 case 'n':
1545 c = '\n';
1546 break;
1547 case 'r':
1548 c = '\r';
1549 break;
1550 case 't':
1551 c = '\t';
1552 break;
1553 case 'v':
1554 c = '\v';
1555 break;
1556 case 'e':
1557 if (!gnu_ext)
1558 goto invalid_escape;
1559 c = 27;
1560 break;
1561 case '\'':
1562 case '\"':
1563 case '\\':
1564 case '?':
1565 break;
1566 default:
1567 invalid_escape:
1568 if (c >= '!' && c <= '~')
1569 warning("unknown escape sequence: \'\\%c\'", c);
1570 else
1571 warning("unknown escape sequence: \'\\x%x\'", c);
1572 break;
1575 p++;
1576 add_char_nonext:
1577 if (!is_long)
1578 cstr_ccat(outstr, c);
1579 else
1580 cstr_wccat(outstr, c);
1582 /* add a trailing '\0' */
1583 if (!is_long)
1584 cstr_ccat(outstr, '\0');
1585 else
1586 cstr_wccat(outstr, '\0');
1589 /* we use 64 bit numbers */
1590 #define BN_SIZE 2
1592 /* bn = (bn << shift) | or_val */
1593 void bn_lshift(unsigned int *bn, int shift, int or_val)
1595 int i;
1596 unsigned int v;
1597 for(i=0;i<BN_SIZE;i++) {
1598 v = bn[i];
1599 bn[i] = (v << shift) | or_val;
1600 or_val = v >> (32 - shift);
1604 void bn_zero(unsigned int *bn)
1606 int i;
1607 for(i=0;i<BN_SIZE;i++) {
1608 bn[i] = 0;
1612 /* parse number in null terminated string 'p' and return it in the
1613 current token */
1614 void parse_number(const char *p)
1616 int b, t, shift, frac_bits, s, exp_val, ch;
1617 char *q;
1618 unsigned int bn[BN_SIZE];
1619 double d;
1621 /* number */
1622 q = token_buf;
1623 ch = *p++;
1624 t = ch;
1625 ch = *p++;
1626 *q++ = t;
1627 b = 10;
1628 if (t == '.') {
1629 goto float_frac_parse;
1630 } else if (t == '0') {
1631 if (ch == 'x' || ch == 'X') {
1632 q--;
1633 ch = *p++;
1634 b = 16;
1635 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
1636 q--;
1637 ch = *p++;
1638 b = 2;
1641 /* parse all digits. cannot check octal numbers at this stage
1642 because of floating point constants */
1643 while (1) {
1644 if (ch >= 'a' && ch <= 'f')
1645 t = ch - 'a' + 10;
1646 else if (ch >= 'A' && ch <= 'F')
1647 t = ch - 'A' + 10;
1648 else if (isnum(ch))
1649 t = ch - '0';
1650 else
1651 break;
1652 if (t >= b)
1653 break;
1654 if (q >= token_buf + STRING_MAX_SIZE) {
1655 num_too_long:
1656 error("number too long");
1658 *q++ = ch;
1659 ch = *p++;
1661 if (ch == '.' ||
1662 ((ch == 'e' || ch == 'E') && b == 10) ||
1663 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
1664 if (b != 10) {
1665 /* NOTE: strtox should support that for hexa numbers, but
1666 non ISOC99 libcs do not support it, so we prefer to do
1667 it by hand */
1668 /* hexadecimal or binary floats */
1669 /* XXX: handle overflows */
1670 *q = '\0';
1671 if (b == 16)
1672 shift = 4;
1673 else
1674 shift = 2;
1675 bn_zero(bn);
1676 q = token_buf;
1677 while (1) {
1678 t = *q++;
1679 if (t == '\0') {
1680 break;
1681 } else if (t >= 'a') {
1682 t = t - 'a' + 10;
1683 } else if (t >= 'A') {
1684 t = t - 'A' + 10;
1685 } else {
1686 t = t - '0';
1688 bn_lshift(bn, shift, t);
1690 frac_bits = 0;
1691 if (ch == '.') {
1692 ch = *p++;
1693 while (1) {
1694 t = ch;
1695 if (t >= 'a' && t <= 'f') {
1696 t = t - 'a' + 10;
1697 } else if (t >= 'A' && t <= 'F') {
1698 t = t - 'A' + 10;
1699 } else if (t >= '0' && t <= '9') {
1700 t = t - '0';
1701 } else {
1702 break;
1704 if (t >= b)
1705 error("invalid digit");
1706 bn_lshift(bn, shift, t);
1707 frac_bits += shift;
1708 ch = *p++;
1711 if (ch != 'p' && ch != 'P')
1712 expect("exponent");
1713 ch = *p++;
1714 s = 1;
1715 exp_val = 0;
1716 if (ch == '+') {
1717 ch = *p++;
1718 } else if (ch == '-') {
1719 s = -1;
1720 ch = *p++;
1722 if (ch < '0' || ch > '9')
1723 expect("exponent digits");
1724 while (ch >= '0' && ch <= '9') {
1725 exp_val = exp_val * 10 + ch - '0';
1726 ch = *p++;
1728 exp_val = exp_val * s;
1730 /* now we can generate the number */
1731 /* XXX: should patch directly float number */
1732 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
1733 d = ldexp(d, exp_val - frac_bits);
1734 t = toup(ch);
1735 if (t == 'F') {
1736 ch = *p++;
1737 tok = TOK_CFLOAT;
1738 /* float : should handle overflow */
1739 tokc.f = (float)d;
1740 } else if (t == 'L') {
1741 ch = *p++;
1742 tok = TOK_CLDOUBLE;
1743 /* XXX: not large enough */
1744 tokc.ld = (long double)d;
1745 } else {
1746 tok = TOK_CDOUBLE;
1747 tokc.d = d;
1749 } else {
1750 /* decimal floats */
1751 if (ch == '.') {
1752 if (q >= token_buf + STRING_MAX_SIZE)
1753 goto num_too_long;
1754 *q++ = ch;
1755 ch = *p++;
1756 float_frac_parse:
1757 while (ch >= '0' && ch <= '9') {
1758 if (q >= token_buf + STRING_MAX_SIZE)
1759 goto num_too_long;
1760 *q++ = ch;
1761 ch = *p++;
1764 if (ch == 'e' || ch == 'E') {
1765 if (q >= token_buf + STRING_MAX_SIZE)
1766 goto num_too_long;
1767 *q++ = ch;
1768 ch = *p++;
1769 if (ch == '-' || ch == '+') {
1770 if (q >= token_buf + STRING_MAX_SIZE)
1771 goto num_too_long;
1772 *q++ = ch;
1773 ch = *p++;
1775 if (ch < '0' || ch > '9')
1776 expect("exponent digits");
1777 while (ch >= '0' && ch <= '9') {
1778 if (q >= token_buf + STRING_MAX_SIZE)
1779 goto num_too_long;
1780 *q++ = ch;
1781 ch = *p++;
1784 *q = '\0';
1785 t = toup(ch);
1786 errno = 0;
1787 if (t == 'F') {
1788 ch = *p++;
1789 tok = TOK_CFLOAT;
1790 tokc.f = strtof(token_buf, NULL);
1791 } else if (t == 'L') {
1792 ch = *p++;
1793 tok = TOK_CLDOUBLE;
1794 tokc.ld = strtold(token_buf, NULL);
1795 } else {
1796 tok = TOK_CDOUBLE;
1797 tokc.d = strtod(token_buf, NULL);
1800 } else {
1801 unsigned long long n, n1;
1802 int lcount, ucount;
1804 /* integer number */
1805 *q = '\0';
1806 q = token_buf;
1807 if (b == 10 && *q == '0') {
1808 b = 8;
1809 q++;
1811 n = 0;
1812 while(1) {
1813 t = *q++;
1814 /* no need for checks except for base 10 / 8 errors */
1815 if (t == '\0') {
1816 break;
1817 } else if (t >= 'a') {
1818 t = t - 'a' + 10;
1819 } else if (t >= 'A') {
1820 t = t - 'A' + 10;
1821 } else {
1822 t = t - '0';
1823 if (t >= b)
1824 error("invalid digit");
1826 n1 = n;
1827 n = n * b + t;
1828 /* detect overflow */
1829 /* XXX: this test is not reliable */
1830 if (n < n1)
1831 error("integer constant overflow");
1834 /* XXX: not exactly ANSI compliant */
1835 if ((n & 0xffffffff00000000LL) != 0) {
1836 if ((n >> 63) != 0)
1837 tok = TOK_CULLONG;
1838 else
1839 tok = TOK_CLLONG;
1840 } else if (n > 0x7fffffff) {
1841 tok = TOK_CUINT;
1842 } else {
1843 tok = TOK_CINT;
1845 lcount = 0;
1846 ucount = 0;
1847 for(;;) {
1848 t = toup(ch);
1849 if (t == 'L') {
1850 if (lcount >= 2)
1851 error("three 'l's in integer constant");
1852 lcount++;
1853 if (lcount == 2) {
1854 if (tok == TOK_CINT)
1855 tok = TOK_CLLONG;
1856 else if (tok == TOK_CUINT)
1857 tok = TOK_CULLONG;
1859 ch = *p++;
1860 } else if (t == 'U') {
1861 if (ucount >= 1)
1862 error("two 'u's in integer constant");
1863 ucount++;
1864 if (tok == TOK_CINT)
1865 tok = TOK_CUINT;
1866 else if (tok == TOK_CLLONG)
1867 tok = TOK_CULLONG;
1868 ch = *p++;
1869 } else {
1870 break;
1873 if (tok == TOK_CINT || tok == TOK_CUINT)
1874 tokc.ui = n;
1875 else
1876 tokc.ull = n;
1878 if (ch)
1879 error("invalid number\n");
1883 #define PARSE2(c1, tok1, c2, tok2) \
1884 case c1: \
1885 PEEKC(c, p); \
1886 if (c == c2) { \
1887 p++; \
1888 tok = tok2; \
1889 } else { \
1890 tok = tok1; \
1892 break;
1894 /* return next token without macro substitution */
1895 static inline void next_nomacro1(void)
1897 int t, c, is_long;
1898 TokenSym *ts;
1899 uint8_t *p, *p1;
1900 unsigned int h;
1902 p = file->buf_ptr;
1903 redo_no_start:
1904 c = *p;
1905 switch(c) {
1906 case ' ':
1907 case '\t':
1908 tok = c;
1909 p++;
1910 goto keep_tok_flags;
1911 case '\f':
1912 case '\v':
1913 case '\r':
1914 p++;
1915 goto redo_no_start;
1916 case '\\':
1917 /* first look if it is in fact an end of buffer */
1918 if (p >= file->buf_end) {
1919 file->buf_ptr = p;
1920 handle_eob();
1921 p = file->buf_ptr;
1922 if (p >= file->buf_end)
1923 goto parse_eof;
1924 else
1925 goto redo_no_start;
1926 } else {
1927 file->buf_ptr = p;
1928 ch = *p;
1929 handle_stray();
1930 p = file->buf_ptr;
1931 goto redo_no_start;
1933 parse_eof:
1935 TCCState *s1 = tcc_state;
1936 if ((parse_flags & PARSE_FLAG_LINEFEED)
1937 && !(tok_flags & TOK_FLAG_EOF)) {
1938 tok_flags |= TOK_FLAG_EOF;
1939 tok = TOK_LINEFEED;
1940 goto keep_tok_flags;
1941 } else if (s1->include_stack_ptr == s1->include_stack ||
1942 !(parse_flags & PARSE_FLAG_PREPROCESS)) {
1943 /* no include left : end of file. */
1944 tok = TOK_EOF;
1945 } else {
1946 tok_flags &= ~TOK_FLAG_EOF;
1947 /* pop include file */
1949 /* test if previous '#endif' was after a #ifdef at
1950 start of file */
1951 if (tok_flags & TOK_FLAG_ENDIF) {
1952 #ifdef INC_DEBUG
1953 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
1954 #endif
1955 add_cached_include(s1, file->inc_type, file->inc_filename,
1956 file->ifndef_macro_saved);
1959 /* add end of include file debug info */
1960 if (tcc_state->do_debug) {
1961 put_stabd(N_EINCL, 0, 0);
1963 /* pop include stack */
1964 tcc_close(file);
1965 s1->include_stack_ptr--;
1966 file = *s1->include_stack_ptr;
1967 p = file->buf_ptr;
1968 goto redo_no_start;
1971 break;
1973 case '\n':
1974 file->line_num++;
1975 tok_flags |= TOK_FLAG_BOL;
1976 p++;
1977 maybe_newline:
1978 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
1979 goto redo_no_start;
1980 tok = TOK_LINEFEED;
1981 goto keep_tok_flags;
1983 case '#':
1984 /* XXX: simplify */
1985 PEEKC(c, p);
1986 if ((tok_flags & TOK_FLAG_BOL) &&
1987 (parse_flags & PARSE_FLAG_PREPROCESS)) {
1988 file->buf_ptr = p;
1989 preprocess(tok_flags & TOK_FLAG_BOF);
1990 p = file->buf_ptr;
1991 goto maybe_newline;
1992 } else {
1993 if (c == '#') {
1994 p++;
1995 tok = TOK_TWOSHARPS;
1996 } else {
1997 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
1998 p = parse_line_comment(p - 1);
1999 goto redo_no_start;
2000 } else {
2001 tok = '#';
2005 break;
2007 case 'a': case 'b': case 'c': case 'd':
2008 case 'e': case 'f': case 'g': case 'h':
2009 case 'i': case 'j': case 'k': case 'l':
2010 case 'm': case 'n': case 'o': case 'p':
2011 case 'q': case 'r': case 's': case 't':
2012 case 'u': case 'v': case 'w': case 'x':
2013 case 'y': case 'z':
2014 case 'A': case 'B': case 'C': case 'D':
2015 case 'E': case 'F': case 'G': case 'H':
2016 case 'I': case 'J': case 'K':
2017 case 'M': case 'N': case 'O': case 'P':
2018 case 'Q': case 'R': case 'S': case 'T':
2019 case 'U': case 'V': case 'W': case 'X':
2020 case 'Y': case 'Z':
2021 case '_':
2022 parse_ident_fast:
2023 p1 = p;
2024 h = TOK_HASH_INIT;
2025 h = TOK_HASH_FUNC(h, c);
2026 p++;
2027 for(;;) {
2028 c = *p;
2029 if (!isidnum_table[c-CH_EOF])
2030 break;
2031 h = TOK_HASH_FUNC(h, c);
2032 p++;
2034 if (c != '\\') {
2035 TokenSym **pts;
2036 int len;
2038 /* fast case : no stray found, so we have the full token
2039 and we have already hashed it */
2040 len = p - p1;
2041 h &= (TOK_HASH_SIZE - 1);
2042 pts = &hash_ident[h];
2043 for(;;) {
2044 ts = *pts;
2045 if (!ts)
2046 break;
2047 if (ts->len == len && !memcmp(ts->str, p1, len))
2048 goto token_found;
2049 pts = &(ts->hash_next);
2051 ts = tok_alloc_new(pts, p1, len);
2052 token_found: ;
2053 } else {
2054 /* slower case */
2055 cstr_reset(&tokcstr);
2057 while (p1 < p) {
2058 cstr_ccat(&tokcstr, *p1);
2059 p1++;
2061 p--;
2062 PEEKC(c, p);
2063 parse_ident_slow:
2064 while (isidnum_table[c-CH_EOF]) {
2065 cstr_ccat(&tokcstr, c);
2066 PEEKC(c, p);
2068 ts = tok_alloc(tokcstr.data, tokcstr.size);
2070 tok = ts->tok;
2071 break;
2072 case 'L':
2073 t = p[1];
2074 if (t != '\\' && t != '\'' && t != '\"') {
2075 /* fast case */
2076 goto parse_ident_fast;
2077 } else {
2078 PEEKC(c, p);
2079 if (c == '\'' || c == '\"') {
2080 is_long = 1;
2081 goto str_const;
2082 } else {
2083 cstr_reset(&tokcstr);
2084 cstr_ccat(&tokcstr, 'L');
2085 goto parse_ident_slow;
2088 break;
2089 case '0': case '1': case '2': case '3':
2090 case '4': case '5': case '6': case '7':
2091 case '8': case '9':
2093 cstr_reset(&tokcstr);
2094 /* after the first digit, accept digits, alpha, '.' or sign if
2095 prefixed by 'eEpP' */
2096 parse_num:
2097 for(;;) {
2098 t = c;
2099 cstr_ccat(&tokcstr, c);
2100 PEEKC(c, p);
2101 if (!(isnum(c) || isid(c) || c == '.' ||
2102 ((c == '+' || c == '-') &&
2103 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
2104 break;
2106 /* We add a trailing '\0' to ease parsing */
2107 cstr_ccat(&tokcstr, '\0');
2108 tokc.cstr = &tokcstr;
2109 tok = TOK_PPNUM;
2110 break;
2111 case '.':
2112 /* special dot handling because it can also start a number */
2113 PEEKC(c, p);
2114 if (isnum(c)) {
2115 cstr_reset(&tokcstr);
2116 cstr_ccat(&tokcstr, '.');
2117 goto parse_num;
2118 } else if (c == '.') {
2119 PEEKC(c, p);
2120 if (c != '.')
2121 expect("'.'");
2122 PEEKC(c, p);
2123 tok = TOK_DOTS;
2124 } else {
2125 tok = '.';
2127 break;
2128 case '\'':
2129 case '\"':
2130 is_long = 0;
2131 str_const:
2133 CString str;
2134 int sep;
2136 sep = c;
2138 /* parse the string */
2139 cstr_new(&str);
2140 p = parse_pp_string(p, sep, &str);
2141 cstr_ccat(&str, '\0');
2143 /* eval the escape (should be done as TOK_PPNUM) */
2144 cstr_reset(&tokcstr);
2145 parse_escape_string(&tokcstr, str.data, is_long);
2146 cstr_free(&str);
2148 if (sep == '\'') {
2149 int char_size;
2150 /* XXX: make it portable */
2151 if (!is_long)
2152 char_size = 1;
2153 else
2154 char_size = sizeof(nwchar_t);
2155 if (tokcstr.size <= char_size)
2156 error("empty character constant");
2157 if (tokcstr.size > 2 * char_size)
2158 warning("multi-character character constant");
2159 if (!is_long) {
2160 tokc.i = *(int8_t *)tokcstr.data;
2161 tok = TOK_CCHAR;
2162 } else {
2163 tokc.i = *(nwchar_t *)tokcstr.data;
2164 tok = TOK_LCHAR;
2166 } else {
2167 tokc.cstr = &tokcstr;
2168 if (!is_long)
2169 tok = TOK_STR;
2170 else
2171 tok = TOK_LSTR;
2174 break;
2176 case '<':
2177 PEEKC(c, p);
2178 if (c == '=') {
2179 p++;
2180 tok = TOK_LE;
2181 } else if (c == '<') {
2182 PEEKC(c, p);
2183 if (c == '=') {
2184 p++;
2185 tok = TOK_A_SHL;
2186 } else {
2187 tok = TOK_SHL;
2189 } else {
2190 tok = TOK_LT;
2192 break;
2194 case '>':
2195 PEEKC(c, p);
2196 if (c == '=') {
2197 p++;
2198 tok = TOK_GE;
2199 } else if (c == '>') {
2200 PEEKC(c, p);
2201 if (c == '=') {
2202 p++;
2203 tok = TOK_A_SAR;
2204 } else {
2205 tok = TOK_SAR;
2207 } else {
2208 tok = TOK_GT;
2210 break;
2212 case '&':
2213 PEEKC(c, p);
2214 if (c == '&') {
2215 p++;
2216 tok = TOK_LAND;
2217 } else if (c == '=') {
2218 p++;
2219 tok = TOK_A_AND;
2220 } else {
2221 tok = '&';
2223 break;
2225 case '|':
2226 PEEKC(c, p);
2227 if (c == '|') {
2228 p++;
2229 tok = TOK_LOR;
2230 } else if (c == '=') {
2231 p++;
2232 tok = TOK_A_OR;
2233 } else {
2234 tok = '|';
2236 break;
2238 case '+':
2239 PEEKC(c, p);
2240 if (c == '+') {
2241 p++;
2242 tok = TOK_INC;
2243 } else if (c == '=') {
2244 p++;
2245 tok = TOK_A_ADD;
2246 } else {
2247 tok = '+';
2249 break;
2251 case '-':
2252 PEEKC(c, p);
2253 if (c == '-') {
2254 p++;
2255 tok = TOK_DEC;
2256 } else if (c == '=') {
2257 p++;
2258 tok = TOK_A_SUB;
2259 } else if (c == '>') {
2260 p++;
2261 tok = TOK_ARROW;
2262 } else {
2263 tok = '-';
2265 break;
2267 PARSE2('!', '!', '=', TOK_NE)
2268 PARSE2('=', '=', '=', TOK_EQ)
2269 PARSE2('*', '*', '=', TOK_A_MUL)
2270 PARSE2('%', '%', '=', TOK_A_MOD)
2271 PARSE2('^', '^', '=', TOK_A_XOR)
2273 /* comments or operator */
2274 case '/':
2275 PEEKC(c, p);
2276 if (c == '*') {
2277 p = parse_comment(p);
2278 goto redo_no_start;
2279 } else if (c == '/') {
2280 p = parse_line_comment(p);
2281 goto redo_no_start;
2282 } else if (c == '=') {
2283 p++;
2284 tok = TOK_A_DIV;
2285 } else {
2286 tok = '/';
2288 break;
2290 /* simple tokens */
2291 case '(':
2292 case ')':
2293 case '[':
2294 case ']':
2295 case '{':
2296 case '}':
2297 case ',':
2298 case ';':
2299 case ':':
2300 case '?':
2301 case '~':
2302 case '$': /* only used in assembler */
2303 case '@': /* dito */
2304 tok = c;
2305 p++;
2306 break;
2307 default:
2308 error("unrecognized character \\x%02x", c);
2309 break;
2311 tok_flags = 0;
2312 keep_tok_flags:
2313 file->buf_ptr = p;
2314 #if defined(PARSE_DEBUG)
2315 printf("token = %s\n", get_tok_str(tok, &tokc));
2316 #endif
2319 /* return next token without macro substitution. Can read input from
2320 macro_ptr buffer */
2321 static void next_nomacro_spc(void)
2323 if (macro_ptr) {
2324 redo:
2325 tok = *macro_ptr;
2326 if (tok) {
2327 TOK_GET(tok, macro_ptr, tokc);
2328 if (tok == TOK_LINENUM) {
2329 file->line_num = tokc.i;
2330 goto redo;
2333 } else {
2334 next_nomacro1();
2338 static void next_nomacro(void)
2340 do {
2341 next_nomacro_spc();
2342 } while (is_space(tok));
2345 /* substitute args in macro_str and return allocated string */
2346 static int *macro_arg_subst(Sym **nested_list, int *macro_str, Sym *args)
2348 int *st, last_tok, t, spc;
2349 Sym *s;
2350 CValue cval;
2351 TokenString str;
2352 CString cstr;
2354 tok_str_new(&str);
2355 last_tok = 0;
2356 while(1) {
2357 TOK_GET(t, macro_str, cval);
2358 if (!t)
2359 break;
2360 if (t == '#') {
2361 /* stringize */
2362 TOK_GET(t, macro_str, cval);
2363 if (!t)
2364 break;
2365 s = sym_find2(args, t);
2366 if (s) {
2367 cstr_new(&cstr);
2368 st = s->d;
2369 spc = 0;
2370 while (*st) {
2371 TOK_GET(t, st, cval);
2372 if (!check_space(t, &spc))
2373 cstr_cat(&cstr, get_tok_str(t, &cval));
2375 cstr.size -= spc;
2376 cstr_ccat(&cstr, '\0');
2377 #ifdef PP_DEBUG
2378 printf("stringize: %s\n", (char *)cstr.data);
2379 #endif
2380 /* add string */
2381 cval.cstr = &cstr;
2382 tok_str_add2(&str, TOK_STR, &cval);
2383 cstr_free(&cstr);
2384 } else {
2385 tok_str_add2(&str, t, &cval);
2387 } else if (t >= TOK_IDENT) {
2388 s = sym_find2(args, t);
2389 if (s) {
2390 st = s->d;
2391 /* if '##' is present before or after, no arg substitution */
2392 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
2393 /* special case for var arg macros : ## eats the
2394 ',' if empty VA_ARGS variable. */
2395 /* XXX: test of the ',' is not 100%
2396 reliable. should fix it to avoid security
2397 problems */
2398 if (gnu_ext && s->type.t &&
2399 last_tok == TOK_TWOSHARPS &&
2400 str.len >= 2 && str.str[str.len - 2] == ',') {
2401 if (*st == 0) {
2402 /* suppress ',' '##' */
2403 str.len -= 2;
2404 } else {
2405 /* suppress '##' and add variable */
2406 str.len--;
2407 goto add_var;
2409 } else {
2410 int t1;
2411 add_var:
2412 for(;;) {
2413 TOK_GET(t1, st, cval);
2414 if (!t1)
2415 break;
2416 tok_str_add2(&str, t1, &cval);
2419 } else {
2420 /* NOTE: the stream cannot be read when macro
2421 substituing an argument */
2422 macro_subst(&str, nested_list, st, NULL);
2424 } else {
2425 tok_str_add(&str, t);
2427 } else {
2428 tok_str_add2(&str, t, &cval);
2430 last_tok = t;
2432 tok_str_add(&str, 0);
2433 return str.str;
2436 static char const ab_month_name[12][4] =
2438 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2439 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2442 /* do macro substitution of current token with macro 's' and add
2443 result to (tok_str,tok_len). 'nested_list' is the list of all
2444 macros we got inside to avoid recursing. Return non zero if no
2445 substitution needs to be done */
2446 static int macro_subst_tok(TokenString *tok_str,
2447 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
2449 Sym *args, *sa, *sa1;
2450 int mstr_allocated, parlevel, *mstr, t, t1, *p, spc;
2451 TokenString str;
2452 char *cstrval;
2453 CValue cval;
2454 CString cstr;
2455 char buf[32];
2457 /* if symbol is a macro, prepare substitution */
2458 /* special macros */
2459 if (tok == TOK___LINE__) {
2460 snprintf(buf, sizeof(buf), "%d", file->line_num);
2461 cstrval = buf;
2462 t1 = TOK_PPNUM;
2463 goto add_cstr1;
2464 } else if (tok == TOK___FILE__) {
2465 cstrval = file->filename;
2466 goto add_cstr;
2467 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
2468 time_t ti;
2469 struct tm *tm;
2471 time(&ti);
2472 tm = localtime(&ti);
2473 if (tok == TOK___DATE__) {
2474 snprintf(buf, sizeof(buf), "%s %2d %d",
2475 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
2476 } else {
2477 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
2478 tm->tm_hour, tm->tm_min, tm->tm_sec);
2480 cstrval = buf;
2481 add_cstr:
2482 t1 = TOK_STR;
2483 add_cstr1:
2484 cstr_new(&cstr);
2485 cstr_cat(&cstr, cstrval);
2486 cstr_ccat(&cstr, '\0');
2487 cval.cstr = &cstr;
2488 tok_str_add2(tok_str, t1, &cval);
2489 cstr_free(&cstr);
2490 } else {
2491 mstr = s->d;
2492 mstr_allocated = 0;
2493 if (s->type.t == MACRO_FUNC) {
2494 /* NOTE: we do not use next_nomacro to avoid eating the
2495 next token. XXX: find better solution */
2496 redo:
2497 if (macro_ptr) {
2498 p = macro_ptr;
2499 while (is_space(t = *p) || TOK_LINEFEED == t)
2500 ++p;
2501 if (t == 0 && can_read_stream) {
2502 /* end of macro stream: we must look at the token
2503 after in the file */
2504 struct macro_level *ml = *can_read_stream;
2505 macro_ptr = NULL;
2506 if (ml)
2508 macro_ptr = ml->p;
2509 ml->p = NULL;
2510 *can_read_stream = ml -> prev;
2512 goto redo;
2514 } else {
2515 /* XXX: incorrect with comments */
2516 ch = file->buf_ptr[0];
2517 while (is_space(ch) || ch == '\n')
2518 cinp();
2519 t = ch;
2521 if (t != '(') /* no macro subst */
2522 return -1;
2524 /* argument macro */
2525 next_nomacro();
2526 next_nomacro();
2527 args = NULL;
2528 sa = s->next;
2529 /* NOTE: empty args are allowed, except if no args */
2530 for(;;) {
2531 /* handle '()' case */
2532 if (!args && !sa && tok == ')')
2533 break;
2534 if (!sa)
2535 error("macro '%s' used with too many args",
2536 get_tok_str(s->v, 0));
2537 tok_str_new(&str);
2538 parlevel = spc = 0;
2539 /* NOTE: non zero sa->t indicates VA_ARGS */
2540 while ((parlevel > 0 ||
2541 (tok != ')' &&
2542 (tok != ',' || sa->type.t))) &&
2543 tok != -1) {
2544 if (tok == '(')
2545 parlevel++;
2546 else if (tok == ')')
2547 parlevel--;
2548 if (tok == TOK_LINEFEED)
2549 tok = ' ';
2550 if (!check_space(tok, &spc))
2551 tok_str_add2(&str, tok, &tokc);
2552 next_nomacro_spc();
2554 str.len -= spc;
2555 tok_str_add(&str, 0);
2556 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
2557 sa1->d = str.str;
2558 sa = sa->next;
2559 if (tok == ')') {
2560 /* special case for gcc var args: add an empty
2561 var arg argument if it is omitted */
2562 if (sa && sa->type.t && gnu_ext)
2563 continue;
2564 else
2565 break;
2567 if (tok != ',')
2568 expect(",");
2569 next_nomacro();
2571 if (sa) {
2572 error("macro '%s' used with too few args",
2573 get_tok_str(s->v, 0));
2576 /* now subst each arg */
2577 mstr = macro_arg_subst(nested_list, mstr, args);
2578 /* free memory */
2579 sa = args;
2580 while (sa) {
2581 sa1 = sa->prev;
2582 tok_str_free(sa->d);
2583 sym_free(sa);
2584 sa = sa1;
2586 mstr_allocated = 1;
2588 sym_push2(nested_list, s->v, 0, 0);
2589 macro_subst(tok_str, nested_list, mstr, can_read_stream);
2590 /* pop nested defined symbol */
2591 sa1 = *nested_list;
2592 *nested_list = sa1->prev;
2593 sym_free(sa1);
2594 if (mstr_allocated)
2595 tok_str_free(mstr);
2597 return 0;
2600 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2601 return the resulting string (which must be freed). */
2602 static inline int *macro_twosharps(const int *macro_str)
2604 const int *ptr;
2605 int t;
2606 CValue cval;
2607 TokenString macro_str1;
2608 CString cstr;
2609 char *p;
2610 int n;
2612 /* we search the first '##' */
2613 for(ptr = macro_str;;) {
2614 TOK_GET(t, ptr, cval);
2615 if (t == TOK_TWOSHARPS)
2616 break;
2617 /* nothing more to do if end of string */
2618 if (t == 0)
2619 return NULL;
2622 /* we saw '##', so we need more processing to handle it */
2623 tok_str_new(&macro_str1);
2624 for(ptr = macro_str;;) {
2625 TOK_GET(tok, ptr, tokc);
2626 if (tok == 0)
2627 break;
2628 if (tok == TOK_TWOSHARPS)
2629 continue;
2630 while (*ptr == TOK_TWOSHARPS) {
2631 t = *++ptr;
2632 if (t && t != TOK_TWOSHARPS) {
2633 TOK_GET(t, ptr, cval);
2635 /* We concatenate the two tokens */
2636 cstr_new(&cstr);
2637 cstr_cat(&cstr, get_tok_str(tok, &tokc));
2638 n = cstr.size;
2639 cstr_cat(&cstr, get_tok_str(t, &cval));
2640 cstr_ccat(&cstr, '\0');
2642 p = file->buf_ptr;
2643 file->buf_ptr = cstr.data;
2644 for (;;) {
2645 next_nomacro1();
2646 if (0 == *file->buf_ptr)
2647 break;
2648 tok_str_add2(&macro_str1, tok, &tokc);
2650 warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2651 n, cstr.data, (char*)cstr.data + n);
2653 file->buf_ptr = p;
2654 cstr_reset(&cstr);
2657 tok_str_add2(&macro_str1, tok, &tokc);
2659 tok_str_add(&macro_str1, 0);
2660 return macro_str1.str;
2664 /* do macro substitution of macro_str and add result to
2665 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2666 inside to avoid recursing. */
2667 static void macro_subst(TokenString *tok_str, Sym **nested_list,
2668 const int *macro_str, struct macro_level ** can_read_stream)
2670 Sym *s;
2671 int *macro_str1;
2672 const int *ptr;
2673 int t, ret, spc;
2674 CValue cval;
2675 struct macro_level ml;
2677 /* first scan for '##' operator handling */
2678 ptr = macro_str;
2679 macro_str1 = macro_twosharps(ptr);
2680 if (macro_str1)
2681 ptr = macro_str1;
2682 spc = 0;
2683 while (1) {
2684 /* NOTE: ptr == NULL can only happen if tokens are read from
2685 file stream due to a macro function call */
2686 if (ptr == NULL)
2687 break;
2688 TOK_GET(t, ptr, cval);
2689 if (t == 0)
2690 break;
2691 s = define_find(t);
2692 if (s != NULL) {
2693 /* if nested substitution, do nothing */
2694 if (sym_find2(*nested_list, t))
2695 goto no_subst;
2696 ml.p = macro_ptr;
2697 if (can_read_stream)
2698 ml.prev = *can_read_stream, *can_read_stream = &ml;
2699 macro_ptr = (int *)ptr;
2700 tok = t;
2701 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
2702 ptr = (int *)macro_ptr;
2703 macro_ptr = ml.p;
2704 if (can_read_stream && *can_read_stream == &ml)
2705 *can_read_stream = ml.prev;
2706 if (ret != 0)
2707 goto no_subst;
2708 } else {
2709 no_subst:
2710 if (!check_space(t, &spc))
2711 tok_str_add2(tok_str, t, &cval);
2714 if (macro_str1)
2715 tok_str_free(macro_str1);
2718 /* return next token with macro substitution */
2719 static void next(void)
2721 Sym *nested_list, *s;
2722 TokenString str;
2723 struct macro_level *ml;
2725 redo:
2726 if (parse_flags & PARSE_FLAG_SPACES)
2727 next_nomacro_spc();
2728 else
2729 next_nomacro();
2730 if (!macro_ptr) {
2731 /* if not reading from macro substituted string, then try
2732 to substitute macros */
2733 if (tok >= TOK_IDENT &&
2734 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2735 s = define_find(tok);
2736 if (s) {
2737 /* we have a macro: we try to substitute */
2738 tok_str_new(&str);
2739 nested_list = NULL;
2740 ml = NULL;
2741 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
2742 /* substitution done, NOTE: maybe empty */
2743 tok_str_add(&str, 0);
2744 macro_ptr = str.str;
2745 macro_ptr_allocated = str.str;
2746 goto redo;
2750 } else {
2751 if (tok == 0) {
2752 /* end of macro or end of unget buffer */
2753 if (unget_buffer_enabled) {
2754 macro_ptr = unget_saved_macro_ptr;
2755 unget_buffer_enabled = 0;
2756 } else {
2757 /* end of macro string: free it */
2758 tok_str_free(macro_ptr_allocated);
2759 macro_ptr = NULL;
2761 goto redo;
2765 /* convert preprocessor tokens into C tokens */
2766 if (tok == TOK_PPNUM &&
2767 (parse_flags & PARSE_FLAG_TOK_NUM)) {
2768 parse_number((char *)tokc.cstr->data);
2772 /* push back current token and set current token to 'last_tok'. Only
2773 identifier case handled for labels. */
2774 static inline void unget_tok(int last_tok)
2776 int i, n;
2777 int *q;
2778 unget_saved_macro_ptr = macro_ptr;
2779 unget_buffer_enabled = 1;
2780 q = unget_saved_buffer;
2781 macro_ptr = q;
2782 *q++ = tok;
2783 n = tok_ext_size(tok) - 1;
2784 for(i=0;i<n;i++)
2785 *q++ = tokc.tab[i];
2786 *q = 0; /* end of token string */
2787 tok = last_tok;
2791 /* better than nothing, but needs extension to handle '-E' option
2792 correctly too */
2793 static void preprocess_init(TCCState *s1)
2795 s1->include_stack_ptr = s1->include_stack;
2796 /* XXX: move that before to avoid having to initialize
2797 file->ifdef_stack_ptr ? */
2798 s1->ifdef_stack_ptr = s1->ifdef_stack;
2799 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
2801 /* XXX: not ANSI compliant: bound checking says error */
2802 vtop = vstack - 1;
2803 s1->pack_stack[0] = 0;
2804 s1->pack_stack_ptr = s1->pack_stack;
2807 void preprocess_new()
2809 int i, c;
2810 const char *p, *r;
2811 TokenSym *ts;
2813 /* init isid table */
2814 for(i=CH_EOF;i<256;i++)
2815 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
2817 /* add all tokens */
2818 table_ident = NULL;
2819 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
2821 tok_ident = TOK_IDENT;
2822 p = tcc_keywords;
2823 while (*p) {
2824 r = p;
2825 for(;;) {
2826 c = *r++;
2827 if (c == '\0')
2828 break;
2830 ts = tok_alloc(p, r - p - 1);
2831 p = r;
2835 /* Preprocess the current file */
2836 static int tcc_preprocess(TCCState *s1)
2838 Sym *define_start;
2839 BufferedFile *file_ref, **iptr, **iptr_new;
2840 int token_seen, line_ref, d;
2841 const char *s;
2843 preprocess_init(s1);
2844 define_start = define_stack;
2845 ch = file->buf_ptr[0];
2846 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
2847 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
2848 PARSE_FLAG_LINEFEED | PARSE_FLAG_SPACES;
2849 token_seen = 0;
2850 line_ref = 0;
2851 file_ref = NULL;
2853 iptr = s1->include_stack_ptr;
2854 for (;;) {
2855 next();
2856 if (tok == TOK_EOF) {
2857 break;
2858 } else if (file != file_ref) {
2859 goto print_line;
2860 } else if (tok == TOK_LINEFEED) {
2861 if (!token_seen)
2862 continue;
2863 ++line_ref;
2864 token_seen = 0;
2865 } else if (!token_seen) {
2866 d = file->line_num - line_ref;
2867 if (file != file_ref || d < 0 || d >= 8) {
2868 print_line:
2869 iptr_new = s1->include_stack_ptr;
2870 s = iptr_new > iptr ? " 1"
2871 : iptr_new < iptr ? " 2"
2872 : iptr_new > s1->include_stack ? " 3"
2873 : ""
2875 iptr = iptr_new;
2876 fprintf(s1->outfile, "# %d \"%s\"%s\n", file->line_num, file->filename, s);
2877 } else {
2878 while (d)
2879 fputs("\n", s1->outfile), --d;
2881 line_ref = (file_ref = file)->line_num;
2882 token_seen = tok != TOK_LINEFEED;
2883 if (!token_seen)
2884 continue;
2886 fputs(get_tok_str(tok, &tokc), s1->outfile);
2888 free_defines(define_start);
2889 return 0;