fix warnings with tcc_add/get_symbol
[tinycc/k1w1.git] / tccpp.c
blobd00897c94ba7bf4838ad7ac2c063cb402e0c93bf
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, (long)str);
864 s->next = first_arg;
865 table_ident[v - TOK_IDENT]->sym_define = s;
868 /* undefined a define symbol. Its name is just set to zero */
869 static void define_undef(Sym *s)
871 int v;
872 v = s->v;
873 if (v >= TOK_IDENT && v < tok_ident)
874 table_ident[v - TOK_IDENT]->sym_define = NULL;
875 s->v = 0;
878 static inline Sym *define_find(int v)
880 v -= TOK_IDENT;
881 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
882 return NULL;
883 return table_ident[v]->sym_define;
886 /* free define stack until top reaches 'b' */
887 static void free_defines(Sym *b)
889 Sym *top, *top1;
890 int v;
892 top = define_stack;
893 while (top != b) {
894 top1 = top->prev;
895 /* do not free args or predefined defines */
896 if (top->c)
897 tok_str_free((int *)top->c);
898 v = top->v;
899 if (v >= TOK_IDENT && v < tok_ident)
900 table_ident[v - TOK_IDENT]->sym_define = NULL;
901 sym_free(top);
902 top = top1;
904 define_stack = b;
907 /* label lookup */
908 static Sym *label_find(int v)
910 v -= TOK_IDENT;
911 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
912 return NULL;
913 return table_ident[v]->sym_label;
916 static Sym *label_push(Sym **ptop, int v, int flags)
918 Sym *s, **ps;
919 s = sym_push2(ptop, v, 0, 0);
920 s->r = flags;
921 ps = &table_ident[v - TOK_IDENT]->sym_label;
922 if (ptop == &global_label_stack) {
923 /* modify the top most local identifier, so that
924 sym_identifier will point to 's' when popped */
925 while (*ps != NULL)
926 ps = &(*ps)->prev_tok;
928 s->prev_tok = *ps;
929 *ps = s;
930 return s;
933 /* pop labels until element last is reached. Look if any labels are
934 undefined. Define symbols if '&&label' was used. */
935 static void label_pop(Sym **ptop, Sym *slast)
937 Sym *s, *s1;
938 for(s = *ptop; s != slast; s = s1) {
939 s1 = s->prev;
940 if (s->r == LABEL_DECLARED) {
941 warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
942 } else if (s->r == LABEL_FORWARD) {
943 error("label '%s' used but not defined",
944 get_tok_str(s->v, NULL));
945 } else {
946 if (s->c) {
947 /* define corresponding symbol. A size of
948 1 is put. */
949 put_extern_sym(s, cur_text_section, (long)s->next, 1);
952 /* remove label */
953 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
954 sym_free(s);
956 *ptop = slast;
959 /* eval an expression for #if/#elif */
960 static int expr_preprocess(void)
962 int c, t;
963 TokenString str;
965 tok_str_new(&str);
966 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
967 next(); /* do macro subst */
968 if (tok == TOK_DEFINED) {
969 next_nomacro();
970 t = tok;
971 if (t == '(')
972 next_nomacro();
973 c = define_find(tok) != 0;
974 if (t == '(')
975 next_nomacro();
976 tok = TOK_CINT;
977 tokc.i = c;
978 } else if (tok >= TOK_IDENT) {
979 /* if undefined macro */
980 tok = TOK_CINT;
981 tokc.i = 0;
983 tok_str_add_tok(&str);
985 tok_str_add(&str, -1); /* simulate end of file */
986 tok_str_add(&str, 0);
987 /* now evaluate C constant expression */
988 macro_ptr = str.str;
989 next();
990 c = expr_const();
991 macro_ptr = NULL;
992 tok_str_free(str.str);
993 return c != 0;
996 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
997 static void tok_print(int *str)
999 int t;
1000 CValue cval;
1002 printf("<");
1003 while (1) {
1004 TOK_GET(t, str, cval);
1005 if (!t)
1006 break;
1007 printf("%s", get_tok_str(t, &cval));
1009 printf(">\n");
1011 #endif
1013 /* parse after #define */
1014 static void parse_define(void)
1016 Sym *s, *first, **ps;
1017 int v, t, varg, is_vaargs, spc;
1018 TokenString str;
1020 v = tok;
1021 if (v < TOK_IDENT)
1022 error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1023 /* XXX: should check if same macro (ANSI) */
1024 first = NULL;
1025 t = MACRO_OBJ;
1026 /* '(' must be just after macro definition for MACRO_FUNC */
1027 next_nomacro_spc();
1028 if (tok == '(') {
1029 next_nomacro();
1030 ps = &first;
1031 while (tok != ')') {
1032 varg = tok;
1033 next_nomacro();
1034 is_vaargs = 0;
1035 if (varg == TOK_DOTS) {
1036 varg = TOK___VA_ARGS__;
1037 is_vaargs = 1;
1038 } else if (tok == TOK_DOTS && gnu_ext) {
1039 is_vaargs = 1;
1040 next_nomacro();
1042 if (varg < TOK_IDENT)
1043 error("badly punctuated parameter list");
1044 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1045 *ps = s;
1046 ps = &s->next;
1047 if (tok != ',')
1048 break;
1049 next_nomacro();
1051 if (tok == ')')
1052 next_nomacro_spc();
1053 t = MACRO_FUNC;
1055 tok_str_new(&str);
1056 spc = 2;
1057 /* EOF testing necessary for '-D' handling */
1058 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1059 /* remove spaces around ## and after '#' */
1060 if (TOK_TWOSHARPS == tok) {
1061 if (1 == spc)
1062 --str.len;
1063 spc = 2;
1064 } else if ('#' == tok) {
1065 spc = 2;
1066 } else if (check_space(tok, &spc)) {
1067 goto skip;
1069 tok_str_add2(&str, tok, &tokc);
1070 skip:
1071 next_nomacro_spc();
1073 if (spc == 1)
1074 --str.len; /* remove trailing space */
1075 tok_str_add(&str, 0);
1076 #ifdef PP_DEBUG
1077 printf("define %s %d: ", get_tok_str(v, NULL), t);
1078 tok_print(str.str);
1079 #endif
1080 define_push(v, t, str.str, first);
1083 static inline int hash_cached_include(int type, const char *filename)
1085 const unsigned char *s;
1086 unsigned int h;
1088 h = TOK_HASH_INIT;
1089 h = TOK_HASH_FUNC(h, type);
1090 s = filename;
1091 while (*s) {
1092 h = TOK_HASH_FUNC(h, *s);
1093 s++;
1095 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1096 return h;
1099 /* XXX: use a token or a hash table to accelerate matching ? */
1100 static CachedInclude *search_cached_include(TCCState *s1,
1101 int type, const char *filename)
1103 CachedInclude *e;
1104 int i, h;
1105 h = hash_cached_include(type, filename);
1106 i = s1->cached_includes_hash[h];
1107 for(;;) {
1108 if (i == 0)
1109 break;
1110 e = s1->cached_includes[i - 1];
1111 if (e->type == type && !PATHCMP(e->filename, filename))
1112 return e;
1113 i = e->hash_next;
1115 return NULL;
1118 static inline void add_cached_include(TCCState *s1, int type,
1119 const char *filename, int ifndef_macro)
1121 CachedInclude *e;
1122 int h;
1124 if (search_cached_include(s1, type, filename))
1125 return;
1126 #ifdef INC_DEBUG
1127 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
1128 #endif
1129 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1130 if (!e)
1131 return;
1132 e->type = type;
1133 strcpy(e->filename, filename);
1134 e->ifndef_macro = ifndef_macro;
1135 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1136 /* add in hash table */
1137 h = hash_cached_include(type, filename);
1138 e->hash_next = s1->cached_includes_hash[h];
1139 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1142 static void pragma_parse(TCCState *s1)
1144 int val;
1146 next();
1147 if (tok == TOK_pack) {
1149 This may be:
1150 #pragma pack(1) // set
1151 #pragma pack() // reset to default
1152 #pragma pack(push,1) // push & set
1153 #pragma pack(pop) // restore previous
1155 next();
1156 skip('(');
1157 if (tok == TOK_ASM_pop) {
1158 next();
1159 if (s1->pack_stack_ptr <= s1->pack_stack) {
1160 stk_error:
1161 error("out of pack stack");
1163 s1->pack_stack_ptr--;
1164 } else {
1165 val = 0;
1166 if (tok != ')') {
1167 if (tok == TOK_ASM_push) {
1168 next();
1169 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1170 goto stk_error;
1171 s1->pack_stack_ptr++;
1172 skip(',');
1174 if (tok != TOK_CINT) {
1175 pack_error:
1176 error("invalid pack pragma");
1178 val = tokc.i;
1179 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1180 goto pack_error;
1181 next();
1183 *s1->pack_stack_ptr = val;
1184 skip(')');
1189 /* is_bof is true if first non space token at beginning of file */
1190 static void preprocess(int is_bof)
1192 TCCState *s1 = tcc_state;
1193 int size, i, c, n, saved_parse_flags;
1194 char buf[1024], *q;
1195 char buf1[1024];
1196 BufferedFile *f;
1197 Sym *s;
1198 CachedInclude *e;
1200 saved_parse_flags = parse_flags;
1201 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
1202 PARSE_FLAG_LINEFEED;
1203 next_nomacro();
1204 redo:
1205 switch(tok) {
1206 case TOK_DEFINE:
1207 next_nomacro();
1208 parse_define();
1209 break;
1210 case TOK_UNDEF:
1211 next_nomacro();
1212 s = define_find(tok);
1213 /* undefine symbol by putting an invalid name */
1214 if (s)
1215 define_undef(s);
1216 break;
1217 case TOK_INCLUDE:
1218 case TOK_INCLUDE_NEXT:
1219 ch = file->buf_ptr[0];
1220 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1221 skip_spaces();
1222 if (ch == '<') {
1223 c = '>';
1224 goto read_name;
1225 } else if (ch == '\"') {
1226 c = ch;
1227 read_name:
1228 inp();
1229 q = buf;
1230 while (ch != c && ch != '\n' && ch != CH_EOF) {
1231 if ((q - buf) < sizeof(buf) - 1)
1232 *q++ = ch;
1233 if (ch == '\\') {
1234 if (handle_stray_noerror() == 0)
1235 --q;
1236 } else
1237 inp();
1239 *q = '\0';
1240 minp();
1241 #if 0
1242 /* eat all spaces and comments after include */
1243 /* XXX: slightly incorrect */
1244 while (ch1 != '\n' && ch1 != CH_EOF)
1245 inp();
1246 #endif
1247 } else {
1248 /* computed #include : either we have only strings or
1249 we have anything enclosed in '<>' */
1250 next();
1251 buf[0] = '\0';
1252 if (tok == TOK_STR) {
1253 while (tok != TOK_LINEFEED) {
1254 if (tok != TOK_STR) {
1255 include_syntax:
1256 error("'#include' expects \"FILENAME\" or <FILENAME>");
1258 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
1259 next();
1261 c = '\"';
1262 } else {
1263 int len;
1264 while (tok != TOK_LINEFEED) {
1265 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1266 next();
1268 len = strlen(buf);
1269 /* check syntax and remove '<>' */
1270 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1271 goto include_syntax;
1272 memmove(buf, buf + 1, len - 2);
1273 buf[len - 2] = '\0';
1274 c = '>';
1278 e = search_cached_include(s1, c, buf);
1279 if (e && define_find(e->ifndef_macro)) {
1280 /* no need to parse the include because the 'ifndef macro'
1281 is defined */
1282 #ifdef INC_DEBUG
1283 printf("%s: skipping %s\n", file->filename, buf);
1284 #endif
1285 } else {
1286 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1287 error("#include recursion too deep");
1288 /* push current file in stack */
1289 /* XXX: fix current line init */
1290 *s1->include_stack_ptr++ = file;
1292 /* check absolute include path */
1293 if (IS_ABSPATH(buf)) {
1294 f = tcc_open(s1, buf);
1295 if (f)
1296 goto found;
1298 if (c == '\"') {
1299 /* first search in current dir if "header.h" */
1300 size = tcc_basename(file->filename) - file->filename;
1301 if (size > sizeof(buf1) - 1)
1302 size = sizeof(buf1) - 1;
1303 memcpy(buf1, file->filename, size);
1304 buf1[size] = '\0';
1305 pstrcat(buf1, sizeof(buf1), buf);
1306 f = tcc_open(s1, buf1);
1307 if (f) {
1308 if (tok == TOK_INCLUDE_NEXT)
1309 tok = TOK_INCLUDE;
1310 else
1311 goto found;
1314 /* now search in all the include paths */
1315 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
1316 for(i = 0; i < n; i++) {
1317 const char *path;
1318 if (i < s1->nb_include_paths)
1319 path = s1->include_paths[i];
1320 else
1321 path = s1->sysinclude_paths[i - s1->nb_include_paths];
1322 pstrcpy(buf1, sizeof(buf1), path);
1323 pstrcat(buf1, sizeof(buf1), "/");
1324 pstrcat(buf1, sizeof(buf1), buf);
1325 f = tcc_open(s1, buf1);
1326 if (f) {
1327 if (tok == TOK_INCLUDE_NEXT)
1328 tok = TOK_INCLUDE;
1329 else
1330 goto found;
1333 --s1->include_stack_ptr;
1334 error("include file '%s' not found", buf);
1335 break;
1336 found:
1337 #ifdef INC_DEBUG
1338 printf("%s: including %s\n", file->filename, buf1);
1339 #endif
1340 f->inc_type = c;
1341 pstrcpy(f->inc_filename, sizeof(f->inc_filename), buf);
1342 file = f;
1343 /* add include file debug info */
1344 if (tcc_state->do_debug) {
1345 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1347 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1348 ch = file->buf_ptr[0];
1349 goto the_end;
1351 break;
1352 case TOK_IFNDEF:
1353 c = 1;
1354 goto do_ifdef;
1355 case TOK_IF:
1356 c = expr_preprocess();
1357 goto do_if;
1358 case TOK_IFDEF:
1359 c = 0;
1360 do_ifdef:
1361 next_nomacro();
1362 if (tok < TOK_IDENT)
1363 error("invalid argument for '#if%sdef'", c ? "n" : "");
1364 if (is_bof) {
1365 if (c) {
1366 #ifdef INC_DEBUG
1367 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1368 #endif
1369 file->ifndef_macro = tok;
1372 c = (define_find(tok) != 0) ^ c;
1373 do_if:
1374 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1375 error("memory full");
1376 *s1->ifdef_stack_ptr++ = c;
1377 goto test_skip;
1378 case TOK_ELSE:
1379 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1380 error("#else without matching #if");
1381 if (s1->ifdef_stack_ptr[-1] & 2)
1382 error("#else after #else");
1383 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1384 goto test_skip;
1385 case TOK_ELIF:
1386 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1387 error("#elif without matching #if");
1388 c = s1->ifdef_stack_ptr[-1];
1389 if (c > 1)
1390 error("#elif after #else");
1391 /* last #if/#elif expression was true: we skip */
1392 if (c == 1)
1393 goto skip;
1394 c = expr_preprocess();
1395 s1->ifdef_stack_ptr[-1] = c;
1396 test_skip:
1397 if (!(c & 1)) {
1398 skip:
1399 preprocess_skip();
1400 is_bof = 0;
1401 goto redo;
1403 break;
1404 case TOK_ENDIF:
1405 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1406 error("#endif without matching #if");
1407 s1->ifdef_stack_ptr--;
1408 /* '#ifndef macro' was at the start of file. Now we check if
1409 an '#endif' is exactly at the end of file */
1410 if (file->ifndef_macro &&
1411 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1412 file->ifndef_macro_saved = file->ifndef_macro;
1413 /* need to set to zero to avoid false matches if another
1414 #ifndef at middle of file */
1415 file->ifndef_macro = 0;
1416 while (tok != TOK_LINEFEED)
1417 next_nomacro();
1418 tok_flags |= TOK_FLAG_ENDIF;
1419 goto the_end;
1421 break;
1422 case TOK_LINE:
1423 next();
1424 if (tok != TOK_CINT)
1425 error("#line");
1426 file->line_num = tokc.i - 1; /* the line number will be incremented after */
1427 next();
1428 if (tok != TOK_LINEFEED) {
1429 if (tok != TOK_STR)
1430 error("#line");
1431 pstrcpy(file->filename, sizeof(file->filename),
1432 (char *)tokc.cstr->data);
1434 break;
1435 case TOK_ERROR:
1436 case TOK_WARNING:
1437 c = tok;
1438 ch = file->buf_ptr[0];
1439 skip_spaces();
1440 q = buf;
1441 while (ch != '\n' && ch != CH_EOF) {
1442 if ((q - buf) < sizeof(buf) - 1)
1443 *q++ = ch;
1444 if (ch == '\\') {
1445 if (handle_stray_noerror() == 0)
1446 --q;
1447 } else
1448 inp();
1450 *q = '\0';
1451 if (c == TOK_ERROR)
1452 error("#error %s", buf);
1453 else
1454 warning("#warning %s", buf);
1455 break;
1456 case TOK_PRAGMA:
1457 pragma_parse(s1);
1458 break;
1459 default:
1460 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_CINT) {
1461 /* '!' is ignored to allow C scripts. numbers are ignored
1462 to emulate cpp behaviour */
1463 } else {
1464 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
1465 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1467 break;
1469 /* ignore other preprocess commands or #! for C scripts */
1470 while (tok != TOK_LINEFEED)
1471 next_nomacro();
1472 the_end:
1473 parse_flags = saved_parse_flags;
1476 /* evaluate escape codes in a string. */
1477 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1479 int c, n;
1480 const uint8_t *p;
1482 p = buf;
1483 for(;;) {
1484 c = *p;
1485 if (c == '\0')
1486 break;
1487 if (c == '\\') {
1488 p++;
1489 /* escape */
1490 c = *p;
1491 switch(c) {
1492 case '0': case '1': case '2': case '3':
1493 case '4': case '5': case '6': case '7':
1494 /* at most three octal digits */
1495 n = c - '0';
1496 p++;
1497 c = *p;
1498 if (isoct(c)) {
1499 n = n * 8 + c - '0';
1500 p++;
1501 c = *p;
1502 if (isoct(c)) {
1503 n = n * 8 + c - '0';
1504 p++;
1507 c = n;
1508 goto add_char_nonext;
1509 case 'x':
1510 case 'u':
1511 case 'U':
1512 p++;
1513 n = 0;
1514 for(;;) {
1515 c = *p;
1516 if (c >= 'a' && c <= 'f')
1517 c = c - 'a' + 10;
1518 else if (c >= 'A' && c <= 'F')
1519 c = c - 'A' + 10;
1520 else if (isnum(c))
1521 c = c - '0';
1522 else
1523 break;
1524 n = n * 16 + c;
1525 p++;
1527 c = n;
1528 goto add_char_nonext;
1529 case 'a':
1530 c = '\a';
1531 break;
1532 case 'b':
1533 c = '\b';
1534 break;
1535 case 'f':
1536 c = '\f';
1537 break;
1538 case 'n':
1539 c = '\n';
1540 break;
1541 case 'r':
1542 c = '\r';
1543 break;
1544 case 't':
1545 c = '\t';
1546 break;
1547 case 'v':
1548 c = '\v';
1549 break;
1550 case 'e':
1551 if (!gnu_ext)
1552 goto invalid_escape;
1553 c = 27;
1554 break;
1555 case '\'':
1556 case '\"':
1557 case '\\':
1558 case '?':
1559 break;
1560 default:
1561 invalid_escape:
1562 if (c >= '!' && c <= '~')
1563 warning("unknown escape sequence: \'\\%c\'", c);
1564 else
1565 warning("unknown escape sequence: \'\\x%x\'", c);
1566 break;
1569 p++;
1570 add_char_nonext:
1571 if (!is_long)
1572 cstr_ccat(outstr, c);
1573 else
1574 cstr_wccat(outstr, c);
1576 /* add a trailing '\0' */
1577 if (!is_long)
1578 cstr_ccat(outstr, '\0');
1579 else
1580 cstr_wccat(outstr, '\0');
1583 /* we use 64 bit numbers */
1584 #define BN_SIZE 2
1586 /* bn = (bn << shift) | or_val */
1587 void bn_lshift(unsigned int *bn, int shift, int or_val)
1589 int i;
1590 unsigned int v;
1591 for(i=0;i<BN_SIZE;i++) {
1592 v = bn[i];
1593 bn[i] = (v << shift) | or_val;
1594 or_val = v >> (32 - shift);
1598 void bn_zero(unsigned int *bn)
1600 int i;
1601 for(i=0;i<BN_SIZE;i++) {
1602 bn[i] = 0;
1606 /* parse number in null terminated string 'p' and return it in the
1607 current token */
1608 void parse_number(const char *p)
1610 int b, t, shift, frac_bits, s, exp_val, ch;
1611 char *q;
1612 unsigned int bn[BN_SIZE];
1613 double d;
1615 /* number */
1616 q = token_buf;
1617 ch = *p++;
1618 t = ch;
1619 ch = *p++;
1620 *q++ = t;
1621 b = 10;
1622 if (t == '.') {
1623 goto float_frac_parse;
1624 } else if (t == '0') {
1625 if (ch == 'x' || ch == 'X') {
1626 q--;
1627 ch = *p++;
1628 b = 16;
1629 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
1630 q--;
1631 ch = *p++;
1632 b = 2;
1635 /* parse all digits. cannot check octal numbers at this stage
1636 because of floating point constants */
1637 while (1) {
1638 if (ch >= 'a' && ch <= 'f')
1639 t = ch - 'a' + 10;
1640 else if (ch >= 'A' && ch <= 'F')
1641 t = ch - 'A' + 10;
1642 else if (isnum(ch))
1643 t = ch - '0';
1644 else
1645 break;
1646 if (t >= b)
1647 break;
1648 if (q >= token_buf + STRING_MAX_SIZE) {
1649 num_too_long:
1650 error("number too long");
1652 *q++ = ch;
1653 ch = *p++;
1655 if (ch == '.' ||
1656 ((ch == 'e' || ch == 'E') && b == 10) ||
1657 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
1658 if (b != 10) {
1659 /* NOTE: strtox should support that for hexa numbers, but
1660 non ISOC99 libcs do not support it, so we prefer to do
1661 it by hand */
1662 /* hexadecimal or binary floats */
1663 /* XXX: handle overflows */
1664 *q = '\0';
1665 if (b == 16)
1666 shift = 4;
1667 else
1668 shift = 2;
1669 bn_zero(bn);
1670 q = token_buf;
1671 while (1) {
1672 t = *q++;
1673 if (t == '\0') {
1674 break;
1675 } else if (t >= 'a') {
1676 t = t - 'a' + 10;
1677 } else if (t >= 'A') {
1678 t = t - 'A' + 10;
1679 } else {
1680 t = t - '0';
1682 bn_lshift(bn, shift, t);
1684 frac_bits = 0;
1685 if (ch == '.') {
1686 ch = *p++;
1687 while (1) {
1688 t = ch;
1689 if (t >= 'a' && t <= 'f') {
1690 t = t - 'a' + 10;
1691 } else if (t >= 'A' && t <= 'F') {
1692 t = t - 'A' + 10;
1693 } else if (t >= '0' && t <= '9') {
1694 t = t - '0';
1695 } else {
1696 break;
1698 if (t >= b)
1699 error("invalid digit");
1700 bn_lshift(bn, shift, t);
1701 frac_bits += shift;
1702 ch = *p++;
1705 if (ch != 'p' && ch != 'P')
1706 expect("exponent");
1707 ch = *p++;
1708 s = 1;
1709 exp_val = 0;
1710 if (ch == '+') {
1711 ch = *p++;
1712 } else if (ch == '-') {
1713 s = -1;
1714 ch = *p++;
1716 if (ch < '0' || ch > '9')
1717 expect("exponent digits");
1718 while (ch >= '0' && ch <= '9') {
1719 exp_val = exp_val * 10 + ch - '0';
1720 ch = *p++;
1722 exp_val = exp_val * s;
1724 /* now we can generate the number */
1725 /* XXX: should patch directly float number */
1726 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
1727 d = ldexp(d, exp_val - frac_bits);
1728 t = toup(ch);
1729 if (t == 'F') {
1730 ch = *p++;
1731 tok = TOK_CFLOAT;
1732 /* float : should handle overflow */
1733 tokc.f = (float)d;
1734 } else if (t == 'L') {
1735 ch = *p++;
1736 tok = TOK_CLDOUBLE;
1737 /* XXX: not large enough */
1738 tokc.ld = (long double)d;
1739 } else {
1740 tok = TOK_CDOUBLE;
1741 tokc.d = d;
1743 } else {
1744 /* decimal floats */
1745 if (ch == '.') {
1746 if (q >= token_buf + STRING_MAX_SIZE)
1747 goto num_too_long;
1748 *q++ = ch;
1749 ch = *p++;
1750 float_frac_parse:
1751 while (ch >= '0' && ch <= '9') {
1752 if (q >= token_buf + STRING_MAX_SIZE)
1753 goto num_too_long;
1754 *q++ = ch;
1755 ch = *p++;
1758 if (ch == 'e' || ch == 'E') {
1759 if (q >= token_buf + STRING_MAX_SIZE)
1760 goto num_too_long;
1761 *q++ = ch;
1762 ch = *p++;
1763 if (ch == '-' || ch == '+') {
1764 if (q >= token_buf + STRING_MAX_SIZE)
1765 goto num_too_long;
1766 *q++ = ch;
1767 ch = *p++;
1769 if (ch < '0' || ch > '9')
1770 expect("exponent digits");
1771 while (ch >= '0' && ch <= '9') {
1772 if (q >= token_buf + STRING_MAX_SIZE)
1773 goto num_too_long;
1774 *q++ = ch;
1775 ch = *p++;
1778 *q = '\0';
1779 t = toup(ch);
1780 errno = 0;
1781 if (t == 'F') {
1782 ch = *p++;
1783 tok = TOK_CFLOAT;
1784 tokc.f = strtof(token_buf, NULL);
1785 } else if (t == 'L') {
1786 ch = *p++;
1787 tok = TOK_CLDOUBLE;
1788 tokc.ld = strtold(token_buf, NULL);
1789 } else {
1790 tok = TOK_CDOUBLE;
1791 tokc.d = strtod(token_buf, NULL);
1794 } else {
1795 unsigned long long n, n1;
1796 int lcount, ucount;
1798 /* integer number */
1799 *q = '\0';
1800 q = token_buf;
1801 if (b == 10 && *q == '0') {
1802 b = 8;
1803 q++;
1805 n = 0;
1806 while(1) {
1807 t = *q++;
1808 /* no need for checks except for base 10 / 8 errors */
1809 if (t == '\0') {
1810 break;
1811 } else if (t >= 'a') {
1812 t = t - 'a' + 10;
1813 } else if (t >= 'A') {
1814 t = t - 'A' + 10;
1815 } else {
1816 t = t - '0';
1817 if (t >= b)
1818 error("invalid digit");
1820 n1 = n;
1821 n = n * b + t;
1822 /* detect overflow */
1823 /* XXX: this test is not reliable */
1824 if (n < n1)
1825 error("integer constant overflow");
1828 /* XXX: not exactly ANSI compliant */
1829 if ((n & 0xffffffff00000000LL) != 0) {
1830 if ((n >> 63) != 0)
1831 tok = TOK_CULLONG;
1832 else
1833 tok = TOK_CLLONG;
1834 } else if (n > 0x7fffffff) {
1835 tok = TOK_CUINT;
1836 } else {
1837 tok = TOK_CINT;
1839 lcount = 0;
1840 ucount = 0;
1841 for(;;) {
1842 t = toup(ch);
1843 if (t == 'L') {
1844 if (lcount >= 2)
1845 error("three 'l's in integer constant");
1846 lcount++;
1847 if (lcount == 2) {
1848 if (tok == TOK_CINT)
1849 tok = TOK_CLLONG;
1850 else if (tok == TOK_CUINT)
1851 tok = TOK_CULLONG;
1853 ch = *p++;
1854 } else if (t == 'U') {
1855 if (ucount >= 1)
1856 error("two 'u's in integer constant");
1857 ucount++;
1858 if (tok == TOK_CINT)
1859 tok = TOK_CUINT;
1860 else if (tok == TOK_CLLONG)
1861 tok = TOK_CULLONG;
1862 ch = *p++;
1863 } else {
1864 break;
1867 if (tok == TOK_CINT || tok == TOK_CUINT)
1868 tokc.ui = n;
1869 else
1870 tokc.ull = n;
1872 if (ch)
1873 error("invalid number\n");
1877 #define PARSE2(c1, tok1, c2, tok2) \
1878 case c1: \
1879 PEEKC(c, p); \
1880 if (c == c2) { \
1881 p++; \
1882 tok = tok2; \
1883 } else { \
1884 tok = tok1; \
1886 break;
1888 /* return next token without macro substitution */
1889 static inline void next_nomacro1(void)
1891 int t, c, is_long;
1892 TokenSym *ts;
1893 uint8_t *p, *p1;
1894 unsigned int h;
1896 p = file->buf_ptr;
1897 redo_no_start:
1898 c = *p;
1899 switch(c) {
1900 case ' ':
1901 case '\t':
1902 tok = c;
1903 p++;
1904 goto keep_tok_flags;
1905 case '\f':
1906 case '\v':
1907 case '\r':
1908 p++;
1909 goto redo_no_start;
1910 case '\\':
1911 /* first look if it is in fact an end of buffer */
1912 if (p >= file->buf_end) {
1913 file->buf_ptr = p;
1914 handle_eob();
1915 p = file->buf_ptr;
1916 if (p >= file->buf_end)
1917 goto parse_eof;
1918 else
1919 goto redo_no_start;
1920 } else {
1921 file->buf_ptr = p;
1922 ch = *p;
1923 handle_stray();
1924 p = file->buf_ptr;
1925 goto redo_no_start;
1927 parse_eof:
1929 TCCState *s1 = tcc_state;
1930 if ((parse_flags & PARSE_FLAG_LINEFEED)
1931 && !(tok_flags & TOK_FLAG_EOF)) {
1932 tok_flags |= TOK_FLAG_EOF;
1933 tok = TOK_LINEFEED;
1934 goto keep_tok_flags;
1935 } else if (s1->include_stack_ptr == s1->include_stack ||
1936 !(parse_flags & PARSE_FLAG_PREPROCESS)) {
1937 /* no include left : end of file. */
1938 tok = TOK_EOF;
1939 } else {
1940 tok_flags &= ~TOK_FLAG_EOF;
1941 /* pop include file */
1943 /* test if previous '#endif' was after a #ifdef at
1944 start of file */
1945 if (tok_flags & TOK_FLAG_ENDIF) {
1946 #ifdef INC_DEBUG
1947 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
1948 #endif
1949 add_cached_include(s1, file->inc_type, file->inc_filename,
1950 file->ifndef_macro_saved);
1953 /* add end of include file debug info */
1954 if (tcc_state->do_debug) {
1955 put_stabd(N_EINCL, 0, 0);
1957 /* pop include stack */
1958 tcc_close(file);
1959 s1->include_stack_ptr--;
1960 file = *s1->include_stack_ptr;
1961 p = file->buf_ptr;
1962 goto redo_no_start;
1965 break;
1967 case '\n':
1968 file->line_num++;
1969 tok_flags |= TOK_FLAG_BOL;
1970 p++;
1971 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
1972 goto redo_no_start;
1973 tok = TOK_LINEFEED;
1974 goto keep_tok_flags;
1976 case '#':
1977 /* XXX: simplify */
1978 PEEKC(c, p);
1979 if ((tok_flags & TOK_FLAG_BOL) &&
1980 (parse_flags & PARSE_FLAG_PREPROCESS)) {
1981 file->buf_ptr = p;
1982 preprocess(tok_flags & TOK_FLAG_BOF);
1983 p = file->buf_ptr;
1984 goto redo_no_start;
1985 } else {
1986 if (c == '#') {
1987 p++;
1988 tok = TOK_TWOSHARPS;
1989 } else {
1990 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
1991 p = parse_line_comment(p - 1);
1992 goto redo_no_start;
1993 } else {
1994 tok = '#';
1998 break;
2000 case 'a': case 'b': case 'c': case 'd':
2001 case 'e': case 'f': case 'g': case 'h':
2002 case 'i': case 'j': case 'k': case 'l':
2003 case 'm': case 'n': case 'o': case 'p':
2004 case 'q': case 'r': case 's': case 't':
2005 case 'u': case 'v': case 'w': case 'x':
2006 case 'y': case 'z':
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':
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 '_':
2015 parse_ident_fast:
2016 p1 = p;
2017 h = TOK_HASH_INIT;
2018 h = TOK_HASH_FUNC(h, c);
2019 p++;
2020 for(;;) {
2021 c = *p;
2022 if (!isidnum_table[c-CH_EOF])
2023 break;
2024 h = TOK_HASH_FUNC(h, c);
2025 p++;
2027 if (c != '\\') {
2028 TokenSym **pts;
2029 int len;
2031 /* fast case : no stray found, so we have the full token
2032 and we have already hashed it */
2033 len = p - p1;
2034 h &= (TOK_HASH_SIZE - 1);
2035 pts = &hash_ident[h];
2036 for(;;) {
2037 ts = *pts;
2038 if (!ts)
2039 break;
2040 if (ts->len == len && !memcmp(ts->str, p1, len))
2041 goto token_found;
2042 pts = &(ts->hash_next);
2044 ts = tok_alloc_new(pts, p1, len);
2045 token_found: ;
2046 } else {
2047 /* slower case */
2048 cstr_reset(&tokcstr);
2050 while (p1 < p) {
2051 cstr_ccat(&tokcstr, *p1);
2052 p1++;
2054 p--;
2055 PEEKC(c, p);
2056 parse_ident_slow:
2057 while (isidnum_table[c-CH_EOF]) {
2058 cstr_ccat(&tokcstr, c);
2059 PEEKC(c, p);
2061 ts = tok_alloc(tokcstr.data, tokcstr.size);
2063 tok = ts->tok;
2064 break;
2065 case 'L':
2066 t = p[1];
2067 if (t != '\\' && t != '\'' && t != '\"') {
2068 /* fast case */
2069 goto parse_ident_fast;
2070 } else {
2071 PEEKC(c, p);
2072 if (c == '\'' || c == '\"') {
2073 is_long = 1;
2074 goto str_const;
2075 } else {
2076 cstr_reset(&tokcstr);
2077 cstr_ccat(&tokcstr, 'L');
2078 goto parse_ident_slow;
2081 break;
2082 case '0': case '1': case '2': case '3':
2083 case '4': case '5': case '6': case '7':
2084 case '8': case '9':
2086 cstr_reset(&tokcstr);
2087 /* after the first digit, accept digits, alpha, '.' or sign if
2088 prefixed by 'eEpP' */
2089 parse_num:
2090 for(;;) {
2091 t = c;
2092 cstr_ccat(&tokcstr, c);
2093 PEEKC(c, p);
2094 if (!(isnum(c) || isid(c) || c == '.' ||
2095 ((c == '+' || c == '-') &&
2096 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
2097 break;
2099 /* We add a trailing '\0' to ease parsing */
2100 cstr_ccat(&tokcstr, '\0');
2101 tokc.cstr = &tokcstr;
2102 tok = TOK_PPNUM;
2103 break;
2104 case '.':
2105 /* special dot handling because it can also start a number */
2106 PEEKC(c, p);
2107 if (isnum(c)) {
2108 cstr_reset(&tokcstr);
2109 cstr_ccat(&tokcstr, '.');
2110 goto parse_num;
2111 } else if (c == '.') {
2112 PEEKC(c, p);
2113 if (c != '.')
2114 expect("'.'");
2115 PEEKC(c, p);
2116 tok = TOK_DOTS;
2117 } else {
2118 tok = '.';
2120 break;
2121 case '\'':
2122 case '\"':
2123 is_long = 0;
2124 str_const:
2126 CString str;
2127 int sep;
2129 sep = c;
2131 /* parse the string */
2132 cstr_new(&str);
2133 p = parse_pp_string(p, sep, &str);
2134 cstr_ccat(&str, '\0');
2136 /* eval the escape (should be done as TOK_PPNUM) */
2137 cstr_reset(&tokcstr);
2138 parse_escape_string(&tokcstr, str.data, is_long);
2139 cstr_free(&str);
2141 if (sep == '\'') {
2142 int char_size;
2143 /* XXX: make it portable */
2144 if (!is_long)
2145 char_size = 1;
2146 else
2147 char_size = sizeof(nwchar_t);
2148 if (tokcstr.size <= char_size)
2149 error("empty character constant");
2150 if (tokcstr.size > 2 * char_size)
2151 warning("multi-character character constant");
2152 if (!is_long) {
2153 tokc.i = *(int8_t *)tokcstr.data;
2154 tok = TOK_CCHAR;
2155 } else {
2156 tokc.i = *(nwchar_t *)tokcstr.data;
2157 tok = TOK_LCHAR;
2159 } else {
2160 tokc.cstr = &tokcstr;
2161 if (!is_long)
2162 tok = TOK_STR;
2163 else
2164 tok = TOK_LSTR;
2167 break;
2169 case '<':
2170 PEEKC(c, p);
2171 if (c == '=') {
2172 p++;
2173 tok = TOK_LE;
2174 } else if (c == '<') {
2175 PEEKC(c, p);
2176 if (c == '=') {
2177 p++;
2178 tok = TOK_A_SHL;
2179 } else {
2180 tok = TOK_SHL;
2182 } else {
2183 tok = TOK_LT;
2185 break;
2187 case '>':
2188 PEEKC(c, p);
2189 if (c == '=') {
2190 p++;
2191 tok = TOK_GE;
2192 } else if (c == '>') {
2193 PEEKC(c, p);
2194 if (c == '=') {
2195 p++;
2196 tok = TOK_A_SAR;
2197 } else {
2198 tok = TOK_SAR;
2200 } else {
2201 tok = TOK_GT;
2203 break;
2205 case '&':
2206 PEEKC(c, p);
2207 if (c == '&') {
2208 p++;
2209 tok = TOK_LAND;
2210 } else if (c == '=') {
2211 p++;
2212 tok = TOK_A_AND;
2213 } else {
2214 tok = '&';
2216 break;
2218 case '|':
2219 PEEKC(c, p);
2220 if (c == '|') {
2221 p++;
2222 tok = TOK_LOR;
2223 } else if (c == '=') {
2224 p++;
2225 tok = TOK_A_OR;
2226 } else {
2227 tok = '|';
2229 break;
2231 case '+':
2232 PEEKC(c, p);
2233 if (c == '+') {
2234 p++;
2235 tok = TOK_INC;
2236 } else if (c == '=') {
2237 p++;
2238 tok = TOK_A_ADD;
2239 } else {
2240 tok = '+';
2242 break;
2244 case '-':
2245 PEEKC(c, p);
2246 if (c == '-') {
2247 p++;
2248 tok = TOK_DEC;
2249 } else if (c == '=') {
2250 p++;
2251 tok = TOK_A_SUB;
2252 } else if (c == '>') {
2253 p++;
2254 tok = TOK_ARROW;
2255 } else {
2256 tok = '-';
2258 break;
2260 PARSE2('!', '!', '=', TOK_NE)
2261 PARSE2('=', '=', '=', TOK_EQ)
2262 PARSE2('*', '*', '=', TOK_A_MUL)
2263 PARSE2('%', '%', '=', TOK_A_MOD)
2264 PARSE2('^', '^', '=', TOK_A_XOR)
2266 /* comments or operator */
2267 case '/':
2268 PEEKC(c, p);
2269 if (c == '*') {
2270 p = parse_comment(p);
2271 goto redo_no_start;
2272 } else if (c == '/') {
2273 p = parse_line_comment(p);
2274 goto redo_no_start;
2275 } else if (c == '=') {
2276 p++;
2277 tok = TOK_A_DIV;
2278 } else {
2279 tok = '/';
2281 break;
2283 /* simple tokens */
2284 case '(':
2285 case ')':
2286 case '[':
2287 case ']':
2288 case '{':
2289 case '}':
2290 case ',':
2291 case ';':
2292 case ':':
2293 case '?':
2294 case '~':
2295 case '$': /* only used in assembler */
2296 case '@': /* dito */
2297 tok = c;
2298 p++;
2299 break;
2300 default:
2301 error("unrecognized character \\x%02x", c);
2302 break;
2304 tok_flags = 0;
2305 keep_tok_flags:
2306 file->buf_ptr = p;
2307 #if defined(PARSE_DEBUG)
2308 printf("token = %s\n", get_tok_str(tok, &tokc));
2309 #endif
2312 /* return next token without macro substitution. Can read input from
2313 macro_ptr buffer */
2314 static void next_nomacro_spc(void)
2316 if (macro_ptr) {
2317 redo:
2318 tok = *macro_ptr;
2319 if (tok) {
2320 TOK_GET(tok, macro_ptr, tokc);
2321 if (tok == TOK_LINENUM) {
2322 file->line_num = tokc.i;
2323 goto redo;
2326 } else {
2327 next_nomacro1();
2331 static void next_nomacro(void)
2333 do {
2334 next_nomacro_spc();
2335 } while (is_space(tok));
2338 /* substitute args in macro_str and return allocated string */
2339 static int *macro_arg_subst(Sym **nested_list, int *macro_str, Sym *args)
2341 int *st, last_tok, t, spc;
2342 Sym *s;
2343 CValue cval;
2344 TokenString str;
2345 CString cstr;
2347 tok_str_new(&str);
2348 last_tok = 0;
2349 while(1) {
2350 TOK_GET(t, macro_str, cval);
2351 if (!t)
2352 break;
2353 if (t == '#') {
2354 /* stringize */
2355 TOK_GET(t, macro_str, cval);
2356 if (!t)
2357 break;
2358 s = sym_find2(args, t);
2359 if (s) {
2360 cstr_new(&cstr);
2361 st = (int *)s->c;
2362 spc = 0;
2363 while (*st) {
2364 TOK_GET(t, st, cval);
2365 if (!check_space(t, &spc))
2366 cstr_cat(&cstr, get_tok_str(t, &cval));
2368 cstr.size -= spc;
2369 cstr_ccat(&cstr, '\0');
2370 #ifdef PP_DEBUG
2371 printf("stringize: %s\n", (char *)cstr.data);
2372 #endif
2373 /* add string */
2374 cval.cstr = &cstr;
2375 tok_str_add2(&str, TOK_STR, &cval);
2376 cstr_free(&cstr);
2377 } else {
2378 tok_str_add2(&str, t, &cval);
2380 } else if (t >= TOK_IDENT) {
2381 s = sym_find2(args, t);
2382 if (s) {
2383 st = (int *)s->c;
2384 /* if '##' is present before or after, no arg substitution */
2385 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
2386 /* special case for var arg macros : ## eats the
2387 ',' if empty VA_ARGS variable. */
2388 /* XXX: test of the ',' is not 100%
2389 reliable. should fix it to avoid security
2390 problems */
2391 if (gnu_ext && s->type.t &&
2392 last_tok == TOK_TWOSHARPS &&
2393 str.len >= 2 && str.str[str.len - 2] == ',') {
2394 if (*st == 0) {
2395 /* suppress ',' '##' */
2396 str.len -= 2;
2397 } else {
2398 /* suppress '##' and add variable */
2399 str.len--;
2400 goto add_var;
2402 } else {
2403 int t1;
2404 add_var:
2405 for(;;) {
2406 TOK_GET(t1, st, cval);
2407 if (!t1)
2408 break;
2409 tok_str_add2(&str, t1, &cval);
2412 } else {
2413 /* NOTE: the stream cannot be read when macro
2414 substituing an argument */
2415 macro_subst(&str, nested_list, st, NULL);
2417 } else {
2418 tok_str_add(&str, t);
2420 } else {
2421 tok_str_add2(&str, t, &cval);
2423 last_tok = t;
2425 tok_str_add(&str, 0);
2426 return str.str;
2429 static char const ab_month_name[12][4] =
2431 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2432 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2435 /* do macro substitution of current token with macro 's' and add
2436 result to (tok_str,tok_len). 'nested_list' is the list of all
2437 macros we got inside to avoid recursing. Return non zero if no
2438 substitution needs to be done */
2439 static int macro_subst_tok(TokenString *tok_str,
2440 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
2442 Sym *args, *sa, *sa1;
2443 int mstr_allocated, parlevel, *mstr, t, t1, *p, spc;
2444 TokenString str;
2445 char *cstrval;
2446 CValue cval;
2447 CString cstr;
2448 char buf[32];
2450 /* if symbol is a macro, prepare substitution */
2451 /* special macros */
2452 if (tok == TOK___LINE__) {
2453 snprintf(buf, sizeof(buf), "%d", file->line_num);
2454 cstrval = buf;
2455 t1 = TOK_PPNUM;
2456 goto add_cstr1;
2457 } else if (tok == TOK___FILE__) {
2458 cstrval = file->filename;
2459 goto add_cstr;
2460 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
2461 time_t ti;
2462 struct tm *tm;
2464 time(&ti);
2465 tm = localtime(&ti);
2466 if (tok == TOK___DATE__) {
2467 snprintf(buf, sizeof(buf), "%s %2d %d",
2468 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
2469 } else {
2470 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
2471 tm->tm_hour, tm->tm_min, tm->tm_sec);
2473 cstrval = buf;
2474 add_cstr:
2475 t1 = TOK_STR;
2476 add_cstr1:
2477 cstr_new(&cstr);
2478 cstr_cat(&cstr, cstrval);
2479 cstr_ccat(&cstr, '\0');
2480 cval.cstr = &cstr;
2481 tok_str_add2(tok_str, t1, &cval);
2482 cstr_free(&cstr);
2483 } else {
2484 mstr = (int *)s->c;
2485 mstr_allocated = 0;
2486 if (s->type.t == MACRO_FUNC) {
2487 /* NOTE: we do not use next_nomacro to avoid eating the
2488 next token. XXX: find better solution */
2489 redo:
2490 if (macro_ptr) {
2491 p = macro_ptr;
2492 while (is_space(t = *p) || TOK_LINEFEED == t)
2493 ++p;
2494 if (t == 0 && can_read_stream) {
2495 /* end of macro stream: we must look at the token
2496 after in the file */
2497 struct macro_level *ml = *can_read_stream;
2498 macro_ptr = NULL;
2499 if (ml)
2501 macro_ptr = ml->p;
2502 ml->p = NULL;
2503 *can_read_stream = ml -> prev;
2505 goto redo;
2507 } else {
2508 /* XXX: incorrect with comments */
2509 ch = file->buf_ptr[0];
2510 while (is_space(ch) || ch == '\n')
2511 cinp();
2512 t = ch;
2514 if (t != '(') /* no macro subst */
2515 return -1;
2517 /* argument macro */
2518 next_nomacro();
2519 next_nomacro();
2520 args = NULL;
2521 sa = s->next;
2522 /* NOTE: empty args are allowed, except if no args */
2523 for(;;) {
2524 /* handle '()' case */
2525 if (!args && !sa && tok == ')')
2526 break;
2527 if (!sa)
2528 error("macro '%s' used with too many args",
2529 get_tok_str(s->v, 0));
2530 tok_str_new(&str);
2531 parlevel = spc = 0;
2532 /* NOTE: non zero sa->t indicates VA_ARGS */
2533 while ((parlevel > 0 ||
2534 (tok != ')' &&
2535 (tok != ',' || sa->type.t))) &&
2536 tok != -1) {
2537 if (tok == '(')
2538 parlevel++;
2539 else if (tok == ')')
2540 parlevel--;
2541 if (tok == TOK_LINEFEED)
2542 tok = ' ';
2543 if (!check_space(tok, &spc))
2544 tok_str_add2(&str, tok, &tokc);
2545 next_nomacro_spc();
2547 str.len -= spc;
2548 tok_str_add(&str, 0);
2549 sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, (long)str.str);
2550 sa = sa->next;
2551 if (tok == ')') {
2552 /* special case for gcc var args: add an empty
2553 var arg argument if it is omitted */
2554 if (sa && sa->type.t && gnu_ext)
2555 continue;
2556 else
2557 break;
2559 if (tok != ',')
2560 expect(",");
2561 next_nomacro();
2563 if (sa) {
2564 error("macro '%s' used with too few args",
2565 get_tok_str(s->v, 0));
2568 /* now subst each arg */
2569 mstr = macro_arg_subst(nested_list, mstr, args);
2570 /* free memory */
2571 sa = args;
2572 while (sa) {
2573 sa1 = sa->prev;
2574 tok_str_free((int *)sa->c);
2575 sym_free(sa);
2576 sa = sa1;
2578 mstr_allocated = 1;
2580 sym_push2(nested_list, s->v, 0, 0);
2581 macro_subst(tok_str, nested_list, mstr, can_read_stream);
2582 /* pop nested defined symbol */
2583 sa1 = *nested_list;
2584 *nested_list = sa1->prev;
2585 sym_free(sa1);
2586 if (mstr_allocated)
2587 tok_str_free(mstr);
2589 return 0;
2592 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2593 return the resulting string (which must be freed). */
2594 static inline int *macro_twosharps(const int *macro_str)
2596 TokenSym *ts;
2597 const int *ptr, *saved_macro_ptr;
2598 int t;
2599 const char *p1, *p2;
2600 CValue cval;
2601 TokenString macro_str1;
2602 CString cstr;
2604 /* we search the first '##' */
2605 for(ptr = macro_str;;) {
2606 TOK_GET(t, ptr, cval);
2607 if (t == TOK_TWOSHARPS)
2608 break;
2609 /* nothing more to do if end of string */
2610 if (t == 0)
2611 return NULL;
2614 /* we saw '##', so we need more processing to handle it */
2615 cstr_new(&cstr);
2616 tok_str_new(&macro_str1);
2617 saved_macro_ptr = macro_ptr;
2618 /* XXX: get rid of the use of macro_ptr here */
2619 macro_ptr = (int *)macro_str;
2620 for(;;) {
2621 next_nomacro_spc();
2622 if (tok == 0)
2623 break;
2624 if (tok == TOK_TWOSHARPS)
2625 continue;
2626 while (*macro_ptr == TOK_TWOSHARPS) {
2627 t = *++macro_ptr;
2628 if (t && t != TOK_TWOSHARPS) {
2629 TOK_GET(t, macro_ptr, cval);
2630 /* We concatenate the two tokens if we have an
2631 identifier or a preprocessing number */
2632 cstr_reset(&cstr);
2633 p1 = get_tok_str(tok, &tokc);
2634 cstr_cat(&cstr, p1);
2635 p2 = get_tok_str(t, &cval);
2636 cstr_cat(&cstr, p2);
2637 cstr_ccat(&cstr, '\0');
2639 if ((tok >= TOK_IDENT || tok == TOK_PPNUM) &&
2640 (t >= TOK_IDENT || t == TOK_PPNUM)) {
2641 if (tok == TOK_PPNUM) {
2642 /* if number, then create a number token */
2643 /* NOTE: no need to allocate because
2644 tok_str_add2() does it */
2645 cstr_reset(&tokcstr);
2646 tokcstr = cstr;
2647 cstr_new(&cstr);
2648 tokc.cstr = &tokcstr;
2649 } else {
2650 /* if identifier, we must do a test to
2651 validate we have a correct identifier */
2652 if (t == TOK_PPNUM) {
2653 const char *p;
2654 int c;
2656 p = p2;
2657 for(;;) {
2658 c = *p;
2659 if (c == '\0')
2660 break;
2661 p++;
2662 if (!isnum(c) && !isid(c))
2663 goto error_pasting;
2666 ts = tok_alloc(cstr.data, strlen(cstr.data));
2667 tok = ts->tok; /* modify current token */
2669 } else {
2670 const char *str = cstr.data;
2671 const unsigned char *q;
2673 /* we look for a valid token */
2674 /* XXX: do more extensive checks */
2675 if (!strcmp(str, ">>=")) {
2676 tok = TOK_A_SAR;
2677 } else if (!strcmp(str, "<<=")) {
2678 tok = TOK_A_SHL;
2679 } else if (strlen(str) == 2) {
2680 /* search in two bytes table */
2681 q = tok_two_chars;
2682 for(;;) {
2683 if (!*q)
2684 goto error_pasting;
2685 if (q[0] == str[0] && q[1] == str[1])
2686 break;
2687 q += 3;
2689 tok = q[2];
2690 } else {
2691 error_pasting:
2692 /* NOTE: because get_tok_str use a static buffer,
2693 we must save it */
2694 cstr_reset(&cstr);
2695 p1 = get_tok_str(tok, &tokc);
2696 cstr_cat(&cstr, p1);
2697 cstr_ccat(&cstr, '\0');
2698 p2 = get_tok_str(t, &cval);
2699 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr.data, p2);
2700 /* cannot merge tokens: just add them separately */
2701 tok_str_add2(&macro_str1, tok, &tokc);
2702 /* XXX: free associated memory ? */
2703 tok = t;
2704 tokc = cval;
2709 tok_str_add2(&macro_str1, tok, &tokc);
2711 macro_ptr = (int *)saved_macro_ptr;
2712 cstr_free(&cstr);
2713 tok_str_add(&macro_str1, 0);
2714 return macro_str1.str;
2718 /* do macro substitution of macro_str and add result to
2719 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2720 inside to avoid recursing. */
2721 static void macro_subst(TokenString *tok_str, Sym **nested_list,
2722 const int *macro_str, struct macro_level ** can_read_stream)
2724 Sym *s;
2725 int *macro_str1;
2726 const int *ptr;
2727 int t, ret, spc;
2728 CValue cval;
2729 struct macro_level ml;
2731 /* first scan for '##' operator handling */
2732 ptr = macro_str;
2733 macro_str1 = macro_twosharps(ptr);
2734 if (macro_str1)
2735 ptr = macro_str1;
2736 spc = 0;
2737 while (1) {
2738 /* NOTE: ptr == NULL can only happen if tokens are read from
2739 file stream due to a macro function call */
2740 if (ptr == NULL)
2741 break;
2742 TOK_GET(t, ptr, cval);
2743 if (t == 0)
2744 break;
2745 s = define_find(t);
2746 if (s != NULL) {
2747 /* if nested substitution, do nothing */
2748 if (sym_find2(*nested_list, t))
2749 goto no_subst;
2750 ml.p = macro_ptr;
2751 if (can_read_stream)
2752 ml.prev = *can_read_stream, *can_read_stream = &ml;
2753 macro_ptr = (int *)ptr;
2754 tok = t;
2755 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
2756 ptr = (int *)macro_ptr;
2757 macro_ptr = ml.p;
2758 if (can_read_stream && *can_read_stream == &ml)
2759 *can_read_stream = ml.prev;
2760 if (ret != 0)
2761 goto no_subst;
2762 } else {
2763 no_subst:
2764 if (!check_space(t, &spc))
2765 tok_str_add2(tok_str, t, &cval);
2768 if (macro_str1)
2769 tok_str_free(macro_str1);
2772 /* return next token with macro substitution */
2773 static void next(void)
2775 Sym *nested_list, *s;
2776 TokenString str;
2777 struct macro_level *ml;
2779 redo:
2780 if (parse_flags & PARSE_FLAG_SPACES)
2781 next_nomacro_spc();
2782 else
2783 next_nomacro();
2784 if (!macro_ptr) {
2785 /* if not reading from macro substituted string, then try
2786 to substitute macros */
2787 if (tok >= TOK_IDENT &&
2788 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2789 s = define_find(tok);
2790 if (s) {
2791 /* we have a macro: we try to substitute */
2792 tok_str_new(&str);
2793 nested_list = NULL;
2794 ml = NULL;
2795 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
2796 /* substitution done, NOTE: maybe empty */
2797 tok_str_add(&str, 0);
2798 macro_ptr = str.str;
2799 macro_ptr_allocated = str.str;
2800 goto redo;
2804 } else {
2805 if (tok == 0) {
2806 /* end of macro or end of unget buffer */
2807 if (unget_buffer_enabled) {
2808 macro_ptr = unget_saved_macro_ptr;
2809 unget_buffer_enabled = 0;
2810 } else {
2811 /* end of macro string: free it */
2812 tok_str_free(macro_ptr_allocated);
2813 macro_ptr = NULL;
2815 goto redo;
2819 /* convert preprocessor tokens into C tokens */
2820 if (tok == TOK_PPNUM &&
2821 (parse_flags & PARSE_FLAG_TOK_NUM)) {
2822 parse_number((char *)tokc.cstr->data);
2826 /* push back current token and set current token to 'last_tok'. Only
2827 identifier case handled for labels. */
2828 static inline void unget_tok(int last_tok)
2830 int i, n;
2831 int *q;
2832 unget_saved_macro_ptr = macro_ptr;
2833 unget_buffer_enabled = 1;
2834 q = unget_saved_buffer;
2835 macro_ptr = q;
2836 *q++ = tok;
2837 n = tok_ext_size(tok) - 1;
2838 for(i=0;i<n;i++)
2839 *q++ = tokc.tab[i];
2840 *q = 0; /* end of token string */
2841 tok = last_tok;
2845 /* better than nothing, but needs extension to handle '-E' option
2846 correctly too */
2847 static void preprocess_init(TCCState *s1)
2849 s1->include_stack_ptr = s1->include_stack;
2850 /* XXX: move that before to avoid having to initialize
2851 file->ifdef_stack_ptr ? */
2852 s1->ifdef_stack_ptr = s1->ifdef_stack;
2853 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
2855 /* XXX: not ANSI compliant: bound checking says error */
2856 vtop = vstack - 1;
2857 s1->pack_stack[0] = 0;
2858 s1->pack_stack_ptr = s1->pack_stack;
2861 void preprocess_new()
2863 int i, c;
2864 const char *p, *r;
2865 TokenSym *ts;
2867 /* init isid table */
2868 for(i=CH_EOF;i<256;i++)
2869 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
2871 /* add all tokens */
2872 table_ident = NULL;
2873 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
2875 tok_ident = TOK_IDENT;
2876 p = tcc_keywords;
2877 while (*p) {
2878 r = p;
2879 for(;;) {
2880 c = *r++;
2881 if (c == '\0')
2882 break;
2884 ts = tok_alloc(p, r - p - 1);
2885 p = r;
2889 /* Preprocess the current file */
2890 static int tcc_preprocess(TCCState *s1)
2892 Sym *define_start;
2893 BufferedFile *file_ref;
2894 int token_seen, line_ref;
2896 preprocess_init(s1);
2897 define_start = define_stack;
2898 ch = file->buf_ptr[0];
2899 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
2900 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
2901 PARSE_FLAG_LINEFEED | PARSE_FLAG_SPACES;
2902 token_seen = 0;
2903 line_ref = 0;
2904 file_ref = NULL;
2906 for (;;) {
2907 next();
2908 if (tok == TOK_EOF) {
2909 break;
2910 } else if (tok == TOK_LINEFEED) {
2911 if (!token_seen)
2912 continue;
2913 ++line_ref;
2914 token_seen = 0;
2915 } else if (!token_seen) {
2916 int d = file->line_num - line_ref;
2917 if (file != file_ref || d < 0 || d >= 8)
2918 fprintf(s1->outfile, "# %d \"%s\"\n", file->line_num, file->filename);
2919 else
2920 while (d)
2921 fputs("\n", s1->outfile), --d;
2922 line_ref = (file_ref = file)->line_num;
2923 token_seen = 1;
2925 fputs(get_tok_str(tok, &tokc), s1->outfile);
2927 free_defines(define_start);
2928 return 0;