arm-gen.c: Invalid operator test always false
[tinycc.git] / tccpp.c
blobaff5a535d2bab30b48adadd07399c4bded2bc2aa
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 ST_DATA int tok_flags;
27 /* additional informations about token */
28 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
29 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
30 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
31 #define TOK_FLAG_EOF 0x0008 /* end of file */
33 ST_DATA int parse_flags;
34 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
35 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
36 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
37 token. line feed is also
38 returned at eof */
39 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
40 #define PARSE_FLAG_SPACES 0x0010 /* next() returns space tokens (for -E) */
42 ST_DATA struct BufferedFile *file;
43 ST_DATA int ch, tok;
44 ST_DATA CValue tokc;
45 ST_DATA const int *macro_ptr;
46 ST_DATA CString tokcstr; /* current parsed string, if any */
48 /* display benchmark infos */
49 ST_DATA int total_lines;
50 ST_DATA int total_bytes;
51 ST_DATA int tok_ident;
52 ST_DATA TokenSym **table_ident;
54 /* ------------------------------------------------------------------------- */
56 static int *macro_ptr_allocated;
57 static const int *unget_saved_macro_ptr;
58 static int unget_saved_buffer[TOK_MAX_SIZE + 1];
59 static int unget_buffer_enabled;
60 static TokenSym *hash_ident[TOK_HASH_SIZE];
61 static char token_buf[STRING_MAX_SIZE + 1];
62 /* true if isid(c) || isnum(c) */
63 static unsigned char isidnum_table[256-CH_EOF];
65 static const char tcc_keywords[] =
66 #define DEF(id, str) str "\0"
67 #include "tcctok.h"
68 #undef DEF
71 /* WARNING: the content of this string encodes token numbers */
72 static const unsigned char tok_two_chars[] =
73 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
74 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
76 struct macro_level {
77 struct macro_level *prev;
78 const int *p;
81 ST_FUNC void next_nomacro(void);
82 static void next_nomacro_spc(void);
83 static void macro_subst(
84 TokenString *tok_str,
85 Sym **nested_list,
86 const int *macro_str,
87 struct macro_level **can_read_stream
90 ST_FUNC void skip(int c)
92 if (tok != c)
93 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
94 next();
97 ST_FUNC void expect(const char *msg)
99 tcc_error("%s expected", msg);
102 /* ------------------------------------------------------------------------- */
103 /* CString handling */
104 static void cstr_realloc(CString *cstr, int new_size)
106 int size;
107 void *data;
109 size = cstr->size_allocated;
110 if (size == 0)
111 size = 8; /* no need to allocate a too small first string */
112 while (size < new_size)
113 size = size * 2;
114 data = tcc_realloc(cstr->data_allocated, size);
115 cstr->data_allocated = data;
116 cstr->size_allocated = size;
117 cstr->data = data;
120 /* add a byte */
121 PUB_FUNC void cstr_ccat(CString *cstr, int ch)
123 int size;
124 size = cstr->size + 1;
125 if (size > cstr->size_allocated)
126 cstr_realloc(cstr, size);
127 ((unsigned char *)cstr->data)[size - 1] = ch;
128 cstr->size = size;
131 PUB_FUNC void cstr_cat(CString *cstr, const char *str)
133 int c;
134 for(;;) {
135 c = *str;
136 if (c == '\0')
137 break;
138 cstr_ccat(cstr, c);
139 str++;
143 /* add a wide char */
144 PUB_FUNC void cstr_wccat(CString *cstr, int ch)
146 int size;
147 size = cstr->size + sizeof(nwchar_t);
148 if (size > cstr->size_allocated)
149 cstr_realloc(cstr, size);
150 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
151 cstr->size = size;
154 PUB_FUNC void cstr_new(CString *cstr)
156 memset(cstr, 0, sizeof(CString));
159 /* free string and reset it to NULL */
160 PUB_FUNC void cstr_free(CString *cstr)
162 tcc_free(cstr->data_allocated);
163 cstr_new(cstr);
166 /* XXX: unicode ? */
167 static void add_char(CString *cstr, int c)
169 if (c == '\'' || c == '\"' || c == '\\') {
170 /* XXX: could be more precise if char or string */
171 cstr_ccat(cstr, '\\');
173 if (c >= 32 && c <= 126) {
174 cstr_ccat(cstr, c);
175 } else {
176 cstr_ccat(cstr, '\\');
177 if (c == '\n') {
178 cstr_ccat(cstr, 'n');
179 } else {
180 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
181 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
182 cstr_ccat(cstr, '0' + (c & 7));
187 /* ------------------------------------------------------------------------- */
188 /* allocate a new token */
189 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
191 TokenSym *ts, **ptable;
192 int i;
194 if (tok_ident >= SYM_FIRST_ANOM)
195 tcc_error("memory full");
197 /* expand token table if needed */
198 i = tok_ident - TOK_IDENT;
199 if ((i % TOK_ALLOC_INCR) == 0) {
200 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
201 table_ident = ptable;
204 ts = tcc_malloc(sizeof(TokenSym) + len);
205 table_ident[i] = ts;
206 ts->tok = tok_ident++;
207 ts->sym_define = NULL;
208 ts->sym_label = NULL;
209 ts->sym_struct = NULL;
210 ts->sym_identifier = NULL;
211 ts->len = len;
212 ts->hash_next = NULL;
213 memcpy(ts->str, str, len);
214 ts->str[len] = '\0';
215 *pts = ts;
216 return ts;
219 #define TOK_HASH_INIT 1
220 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
222 /* find a token and add it if not found */
223 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
225 TokenSym *ts, **pts;
226 int i;
227 unsigned int h;
229 h = TOK_HASH_INIT;
230 for(i=0;i<len;i++)
231 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
232 h &= (TOK_HASH_SIZE - 1);
234 pts = &hash_ident[h];
235 for(;;) {
236 ts = *pts;
237 if (!ts)
238 break;
239 if (ts->len == len && !memcmp(ts->str, str, len))
240 return ts;
241 pts = &(ts->hash_next);
243 return tok_alloc_new(pts, str, len);
246 /* XXX: buffer overflow */
247 /* XXX: float tokens */
248 ST_FUNC char *get_tok_str(int v, CValue *cv)
250 static char buf[STRING_MAX_SIZE + 1];
251 static CString cstr_buf;
252 CString *cstr;
253 char *p;
254 int i, len;
256 /* NOTE: to go faster, we give a fixed buffer for small strings */
257 cstr_reset(&cstr_buf);
258 cstr_buf.data = buf;
259 cstr_buf.size_allocated = sizeof(buf);
260 p = buf;
262 switch(v) {
263 case TOK_CINT:
264 case TOK_CUINT:
265 /* XXX: not quite exact, but only useful for testing */
266 sprintf(p, "%u", cv->ui);
267 break;
268 case TOK_CLLONG:
269 case TOK_CULLONG:
270 /* XXX: not quite exact, but only useful for testing */
271 #ifdef _WIN32
272 sprintf(p, "%u", (unsigned)cv->ull);
273 #else
274 sprintf(p, "%Lu", cv->ull);
275 #endif
276 break;
277 case TOK_LCHAR:
278 cstr_ccat(&cstr_buf, 'L');
279 case TOK_CCHAR:
280 cstr_ccat(&cstr_buf, '\'');
281 add_char(&cstr_buf, cv->i);
282 cstr_ccat(&cstr_buf, '\'');
283 cstr_ccat(&cstr_buf, '\0');
284 break;
285 case TOK_PPNUM:
286 cstr = cv->cstr;
287 len = cstr->size - 1;
288 for(i=0;i<len;i++)
289 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
290 cstr_ccat(&cstr_buf, '\0');
291 break;
292 case TOK_LSTR:
293 cstr_ccat(&cstr_buf, 'L');
294 case TOK_STR:
295 cstr = cv->cstr;
296 cstr_ccat(&cstr_buf, '\"');
297 if (v == TOK_STR) {
298 len = cstr->size - 1;
299 for(i=0;i<len;i++)
300 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
301 } else {
302 len = (cstr->size / sizeof(nwchar_t)) - 1;
303 for(i=0;i<len;i++)
304 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
306 cstr_ccat(&cstr_buf, '\"');
307 cstr_ccat(&cstr_buf, '\0');
308 break;
309 case TOK_LT:
310 v = '<';
311 goto addv;
312 case TOK_GT:
313 v = '>';
314 goto addv;
315 case TOK_DOTS:
316 return strcpy(p, "...");
317 case TOK_A_SHL:
318 return strcpy(p, "<<=");
319 case TOK_A_SAR:
320 return strcpy(p, ">>=");
321 default:
322 if (v < TOK_IDENT) {
323 /* search in two bytes table */
324 const unsigned char *q = tok_two_chars;
325 while (*q) {
326 if (q[2] == v) {
327 *p++ = q[0];
328 *p++ = q[1];
329 *p = '\0';
330 return buf;
332 q += 3;
334 addv:
335 *p++ = v;
336 *p = '\0';
337 } else if (v < tok_ident) {
338 return table_ident[v - TOK_IDENT]->str;
339 } else if (v >= SYM_FIRST_ANOM) {
340 /* special name for anonymous symbol */
341 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
342 } else {
343 /* should never happen */
344 return NULL;
346 break;
348 return cstr_buf.data;
351 /* fill input buffer and peek next char */
352 static int tcc_peekc_slow(BufferedFile *bf)
354 int len;
355 /* only tries to read if really end of buffer */
356 if (bf->buf_ptr >= bf->buf_end) {
357 if (bf->fd != -1) {
358 #if defined(PARSE_DEBUG)
359 len = 8;
360 #else
361 len = IO_BUF_SIZE;
362 #endif
363 len = read(bf->fd, bf->buffer, len);
364 if (len < 0)
365 len = 0;
366 } else {
367 len = 0;
369 total_bytes += len;
370 bf->buf_ptr = bf->buffer;
371 bf->buf_end = bf->buffer + len;
372 *bf->buf_end = CH_EOB;
374 if (bf->buf_ptr < bf->buf_end) {
375 return bf->buf_ptr[0];
376 } else {
377 bf->buf_ptr = bf->buf_end;
378 return CH_EOF;
382 /* return the current character, handling end of block if necessary
383 (but not stray) */
384 ST_FUNC int handle_eob(void)
386 return tcc_peekc_slow(file);
389 /* read next char from current input file and handle end of input buffer */
390 ST_INLN void inp(void)
392 ch = *(++(file->buf_ptr));
393 /* end of buffer/file handling */
394 if (ch == CH_EOB)
395 ch = handle_eob();
398 /* handle '\[\r]\n' */
399 static int handle_stray_noerror(void)
401 while (ch == '\\') {
402 inp();
403 if (ch == '\n') {
404 file->line_num++;
405 inp();
406 } else if (ch == '\r') {
407 inp();
408 if (ch != '\n')
409 goto fail;
410 file->line_num++;
411 inp();
412 } else {
413 fail:
414 return 1;
417 return 0;
420 static void handle_stray(void)
422 if (handle_stray_noerror())
423 tcc_error("stray '\\' in program");
426 /* skip the stray and handle the \\n case. Output an error if
427 incorrect char after the stray */
428 static int handle_stray1(uint8_t *p)
430 int c;
432 if (p >= file->buf_end) {
433 file->buf_ptr = p;
434 c = handle_eob();
435 p = file->buf_ptr;
436 if (c == '\\')
437 goto parse_stray;
438 } else {
439 parse_stray:
440 file->buf_ptr = p;
441 ch = *p;
442 handle_stray();
443 p = file->buf_ptr;
444 c = *p;
446 return c;
449 /* handle just the EOB case, but not stray */
450 #define PEEKC_EOB(c, p)\
452 p++;\
453 c = *p;\
454 if (c == '\\') {\
455 file->buf_ptr = p;\
456 c = handle_eob();\
457 p = file->buf_ptr;\
461 /* handle the complicated stray case */
462 #define PEEKC(c, p)\
464 p++;\
465 c = *p;\
466 if (c == '\\') {\
467 c = handle_stray1(p);\
468 p = file->buf_ptr;\
472 /* input with '\[\r]\n' handling. Note that this function cannot
473 handle other characters after '\', so you cannot call it inside
474 strings or comments */
475 ST_FUNC void minp(void)
477 inp();
478 if (ch == '\\')
479 handle_stray();
483 /* single line C++ comments */
484 static uint8_t *parse_line_comment(uint8_t *p)
486 int c;
488 p++;
489 for(;;) {
490 c = *p;
491 redo:
492 if (c == '\n' || c == CH_EOF) {
493 break;
494 } else if (c == '\\') {
495 file->buf_ptr = p;
496 c = handle_eob();
497 p = file->buf_ptr;
498 if (c == '\\') {
499 PEEKC_EOB(c, p);
500 if (c == '\n') {
501 file->line_num++;
502 PEEKC_EOB(c, p);
503 } else if (c == '\r') {
504 PEEKC_EOB(c, p);
505 if (c == '\n') {
506 file->line_num++;
507 PEEKC_EOB(c, p);
510 } else {
511 goto redo;
513 } else {
514 p++;
517 return p;
520 /* C comments */
521 ST_FUNC uint8_t *parse_comment(uint8_t *p)
523 int c;
525 p++;
526 for(;;) {
527 /* fast skip loop */
528 for(;;) {
529 c = *p;
530 if (c == '\n' || c == '*' || c == '\\')
531 break;
532 p++;
533 c = *p;
534 if (c == '\n' || c == '*' || c == '\\')
535 break;
536 p++;
538 /* now we can handle all the cases */
539 if (c == '\n') {
540 file->line_num++;
541 p++;
542 } else if (c == '*') {
543 p++;
544 for(;;) {
545 c = *p;
546 if (c == '*') {
547 p++;
548 } else if (c == '/') {
549 goto end_of_comment;
550 } else if (c == '\\') {
551 file->buf_ptr = p;
552 c = handle_eob();
553 p = file->buf_ptr;
554 if (c == '\\') {
555 /* skip '\[\r]\n', otherwise just skip the stray */
556 while (c == '\\') {
557 PEEKC_EOB(c, p);
558 if (c == '\n') {
559 file->line_num++;
560 PEEKC_EOB(c, p);
561 } else if (c == '\r') {
562 PEEKC_EOB(c, p);
563 if (c == '\n') {
564 file->line_num++;
565 PEEKC_EOB(c, p);
567 } else {
568 goto after_star;
572 } else {
573 break;
576 after_star: ;
577 } else {
578 /* stray, eob or eof */
579 file->buf_ptr = p;
580 c = handle_eob();
581 p = file->buf_ptr;
582 if (c == CH_EOF) {
583 tcc_error("unexpected end of file in comment");
584 } else if (c == '\\') {
585 p++;
589 end_of_comment:
590 p++;
591 return p;
594 #define cinp minp
596 static inline void skip_spaces(void)
598 while (is_space(ch))
599 cinp();
602 static inline int check_space(int t, int *spc)
604 if (is_space(t)) {
605 if (*spc)
606 return 1;
607 *spc = 1;
608 } else
609 *spc = 0;
610 return 0;
613 /* parse a string without interpreting escapes */
614 static uint8_t *parse_pp_string(uint8_t *p,
615 int sep, CString *str)
617 int c;
618 p++;
619 for(;;) {
620 c = *p;
621 if (c == sep) {
622 break;
623 } else if (c == '\\') {
624 file->buf_ptr = p;
625 c = handle_eob();
626 p = file->buf_ptr;
627 if (c == CH_EOF) {
628 unterminated_string:
629 /* XXX: indicate line number of start of string */
630 tcc_error("missing terminating %c character", sep);
631 } else if (c == '\\') {
632 /* escape : just skip \[\r]\n */
633 PEEKC_EOB(c, p);
634 if (c == '\n') {
635 file->line_num++;
636 p++;
637 } else if (c == '\r') {
638 PEEKC_EOB(c, p);
639 if (c != '\n')
640 expect("'\n' after '\r'");
641 file->line_num++;
642 p++;
643 } else if (c == CH_EOF) {
644 goto unterminated_string;
645 } else {
646 if (str) {
647 cstr_ccat(str, '\\');
648 cstr_ccat(str, c);
650 p++;
653 } else if (c == '\n') {
654 file->line_num++;
655 goto add_char;
656 } else if (c == '\r') {
657 PEEKC_EOB(c, p);
658 if (c != '\n') {
659 if (str)
660 cstr_ccat(str, '\r');
661 } else {
662 file->line_num++;
663 goto add_char;
665 } else {
666 add_char:
667 if (str)
668 cstr_ccat(str, c);
669 p++;
672 p++;
673 return p;
676 /* skip block of text until #else, #elif or #endif. skip also pairs of
677 #if/#endif */
678 static void preprocess_skip(void)
680 int a, start_of_line, c, in_warn_or_error;
681 uint8_t *p;
683 p = file->buf_ptr;
684 a = 0;
685 redo_start:
686 start_of_line = 1;
687 in_warn_or_error = 0;
688 for(;;) {
689 redo_no_start:
690 c = *p;
691 switch(c) {
692 case ' ':
693 case '\t':
694 case '\f':
695 case '\v':
696 case '\r':
697 p++;
698 goto redo_no_start;
699 case '\n':
700 file->line_num++;
701 p++;
702 goto redo_start;
703 case '\\':
704 file->buf_ptr = p;
705 c = handle_eob();
706 if (c == CH_EOF) {
707 expect("#endif");
708 } else if (c == '\\') {
709 ch = file->buf_ptr[0];
710 handle_stray_noerror();
712 p = file->buf_ptr;
713 goto redo_no_start;
714 /* skip strings */
715 case '\"':
716 case '\'':
717 if (in_warn_or_error)
718 goto _default;
719 p = parse_pp_string(p, c, NULL);
720 break;
721 /* skip comments */
722 case '/':
723 if (in_warn_or_error)
724 goto _default;
725 file->buf_ptr = p;
726 ch = *p;
727 minp();
728 p = file->buf_ptr;
729 if (ch == '*') {
730 p = parse_comment(p);
731 } else if (ch == '/') {
732 p = parse_line_comment(p);
734 break;
735 case '#':
736 p++;
737 if (start_of_line) {
738 file->buf_ptr = p;
739 next_nomacro();
740 p = file->buf_ptr;
741 if (a == 0 &&
742 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
743 goto the_end;
744 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
745 a++;
746 else if (tok == TOK_ENDIF)
747 a--;
748 else if( tok == TOK_ERROR || tok == TOK_WARNING)
749 in_warn_or_error = 1;
750 else if (tok == TOK_LINEFEED)
751 goto redo_start;
753 break;
754 _default:
755 default:
756 p++;
757 break;
759 start_of_line = 0;
761 the_end: ;
762 file->buf_ptr = p;
765 /* ParseState handling */
767 /* XXX: currently, no include file info is stored. Thus, we cannot display
768 accurate messages if the function or data definition spans multiple
769 files */
771 /* save current parse state in 's' */
772 ST_FUNC void save_parse_state(ParseState *s)
774 s->line_num = file->line_num;
775 s->macro_ptr = macro_ptr;
776 s->tok = tok;
777 s->tokc = tokc;
780 /* restore parse state from 's' */
781 ST_FUNC void restore_parse_state(ParseState *s)
783 file->line_num = s->line_num;
784 macro_ptr = s->macro_ptr;
785 tok = s->tok;
786 tokc = s->tokc;
789 /* return the number of additional 'ints' necessary to store the
790 token */
791 static inline int tok_ext_size(int t)
793 switch(t) {
794 /* 4 bytes */
795 case TOK_CINT:
796 case TOK_CUINT:
797 case TOK_CCHAR:
798 case TOK_LCHAR:
799 case TOK_CFLOAT:
800 case TOK_LINENUM:
801 return 1;
802 case TOK_STR:
803 case TOK_LSTR:
804 case TOK_PPNUM:
805 tcc_error("unsupported token");
806 return 1;
807 case TOK_CDOUBLE:
808 case TOK_CLLONG:
809 case TOK_CULLONG:
810 return 2;
811 case TOK_CLDOUBLE:
812 return LDOUBLE_SIZE / 4;
813 default:
814 return 0;
818 /* token string handling */
820 ST_INLN void tok_str_new(TokenString *s)
822 s->str = NULL;
823 s->len = 0;
824 s->allocated_len = 0;
825 s->last_line_num = -1;
828 ST_FUNC void tok_str_free(int *str)
830 tcc_free(str);
833 static int *tok_str_realloc(TokenString *s)
835 int *str, len;
837 if (s->allocated_len == 0) {
838 len = 8;
839 } else {
840 len = s->allocated_len * 2;
842 str = tcc_realloc(s->str, len * sizeof(int));
843 s->allocated_len = len;
844 s->str = str;
845 return str;
848 ST_FUNC void tok_str_add(TokenString *s, int t)
850 int len, *str;
852 len = s->len;
853 str = s->str;
854 if (len >= s->allocated_len)
855 str = tok_str_realloc(s);
856 str[len++] = t;
857 s->len = len;
860 static void tok_str_add2(TokenString *s, int t, CValue *cv)
862 int len, *str;
864 len = s->len;
865 str = s->str;
867 /* allocate space for worst case */
868 if (len + TOK_MAX_SIZE > s->allocated_len)
869 str = tok_str_realloc(s);
870 str[len++] = t;
871 switch(t) {
872 case TOK_CINT:
873 case TOK_CUINT:
874 case TOK_CCHAR:
875 case TOK_LCHAR:
876 case TOK_CFLOAT:
877 case TOK_LINENUM:
878 str[len++] = cv->tab[0];
879 break;
880 case TOK_PPNUM:
881 case TOK_STR:
882 case TOK_LSTR:
884 int nb_words;
885 CString *cstr;
887 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
888 while ((len + nb_words) > s->allocated_len)
889 str = tok_str_realloc(s);
890 cstr = (CString *)(str + len);
891 cstr->data = NULL;
892 cstr->size = cv->cstr->size;
893 cstr->data_allocated = NULL;
894 cstr->size_allocated = cstr->size;
895 memcpy((char *)cstr + sizeof(CString),
896 cv->cstr->data, cstr->size);
897 len += nb_words;
899 break;
900 case TOK_CDOUBLE:
901 case TOK_CLLONG:
902 case TOK_CULLONG:
903 #if LDOUBLE_SIZE == 8
904 case TOK_CLDOUBLE:
905 #endif
906 str[len++] = cv->tab[0];
907 str[len++] = cv->tab[1];
908 break;
909 #if LDOUBLE_SIZE == 12
910 case TOK_CLDOUBLE:
911 str[len++] = cv->tab[0];
912 str[len++] = cv->tab[1];
913 str[len++] = cv->tab[2];
914 #elif LDOUBLE_SIZE == 16
915 case TOK_CLDOUBLE:
916 str[len++] = cv->tab[0];
917 str[len++] = cv->tab[1];
918 str[len++] = cv->tab[2];
919 str[len++] = cv->tab[3];
920 #elif LDOUBLE_SIZE != 8
921 #error add long double size support
922 #endif
923 break;
924 default:
925 break;
927 s->len = len;
930 /* add the current parse token in token string 's' */
931 ST_FUNC void tok_str_add_tok(TokenString *s)
933 CValue cval;
935 /* save line number info */
936 if (file->line_num != s->last_line_num) {
937 s->last_line_num = file->line_num;
938 cval.i = s->last_line_num;
939 tok_str_add2(s, TOK_LINENUM, &cval);
941 tok_str_add2(s, tok, &tokc);
944 /* get a token from an integer array and increment pointer
945 accordingly. we code it as a macro to avoid pointer aliasing. */
946 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
948 const int *p = *pp;
949 int n, *tab;
951 tab = cv->tab;
952 switch(*t = *p++) {
953 case TOK_CINT:
954 case TOK_CUINT:
955 case TOK_CCHAR:
956 case TOK_LCHAR:
957 case TOK_CFLOAT:
958 case TOK_LINENUM:
959 tab[0] = *p++;
960 break;
961 case TOK_STR:
962 case TOK_LSTR:
963 case TOK_PPNUM:
964 cv->cstr = (CString *)p;
965 cv->cstr->data = (char *)p + sizeof(CString);
966 p += (sizeof(CString) + cv->cstr->size + 3) >> 2;
967 break;
968 case TOK_CDOUBLE:
969 case TOK_CLLONG:
970 case TOK_CULLONG:
971 n = 2;
972 goto copy;
973 case TOK_CLDOUBLE:
974 #if LDOUBLE_SIZE == 16
975 n = 4;
976 #elif LDOUBLE_SIZE == 12
977 n = 3;
978 #elif LDOUBLE_SIZE == 8
979 n = 2;
980 #else
981 # error add long double size support
982 #endif
983 copy:
985 *tab++ = *p++;
986 while (--n);
987 break;
988 default:
989 break;
991 *pp = p;
994 static int macro_is_equal(const int *a, const int *b)
996 char buf[STRING_MAX_SIZE + 1];
997 CValue cv;
998 int t;
999 while (*a && *b) {
1000 TOK_GET(&t, &a, &cv);
1001 pstrcpy(buf, sizeof buf, get_tok_str(t, &cv));
1002 TOK_GET(&t, &b, &cv);
1003 if (strcmp(buf, get_tok_str(t, &cv)))
1004 return 0;
1006 return !(*a || *b);
1009 /* defines handling */
1010 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1012 Sym *s;
1014 s = define_find(v);
1015 if (s && !macro_is_equal(s->d, str))
1016 tcc_warning("%s redefined", get_tok_str(v, NULL));
1018 s = sym_push2(&define_stack, v, macro_type, 0);
1019 s->d = str;
1020 s->next = first_arg;
1021 table_ident[v - TOK_IDENT]->sym_define = s;
1024 /* undefined a define symbol. Its name is just set to zero */
1025 ST_FUNC void define_undef(Sym *s)
1027 int v;
1028 v = s->v;
1029 if (v >= TOK_IDENT && v < tok_ident)
1030 table_ident[v - TOK_IDENT]->sym_define = NULL;
1031 s->v = 0;
1034 ST_INLN Sym *define_find(int v)
1036 v -= TOK_IDENT;
1037 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1038 return NULL;
1039 return table_ident[v]->sym_define;
1042 /* free define stack until top reaches 'b' */
1043 ST_FUNC void free_defines(Sym *b)
1045 Sym *top, *top1;
1046 int v;
1048 top = define_stack;
1049 while (top != b) {
1050 top1 = top->prev;
1051 /* do not free args or predefined defines */
1052 if (top->d)
1053 tok_str_free(top->d);
1054 v = top->v;
1055 if (v >= TOK_IDENT && v < tok_ident)
1056 table_ident[v - TOK_IDENT]->sym_define = NULL;
1057 sym_free(top);
1058 top = top1;
1060 define_stack = b;
1063 /* label lookup */
1064 ST_FUNC Sym *label_find(int v)
1066 v -= TOK_IDENT;
1067 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1068 return NULL;
1069 return table_ident[v]->sym_label;
1072 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1074 Sym *s, **ps;
1075 s = sym_push2(ptop, v, 0, 0);
1076 s->r = flags;
1077 ps = &table_ident[v - TOK_IDENT]->sym_label;
1078 if (ptop == &global_label_stack) {
1079 /* modify the top most local identifier, so that
1080 sym_identifier will point to 's' when popped */
1081 while (*ps != NULL)
1082 ps = &(*ps)->prev_tok;
1084 s->prev_tok = *ps;
1085 *ps = s;
1086 return s;
1089 /* pop labels until element last is reached. Look if any labels are
1090 undefined. Define symbols if '&&label' was used. */
1091 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1093 Sym *s, *s1;
1094 for(s = *ptop; s != slast; s = s1) {
1095 s1 = s->prev;
1096 if (s->r == LABEL_DECLARED) {
1097 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1098 } else if (s->r == LABEL_FORWARD) {
1099 tcc_error("label '%s' used but not defined",
1100 get_tok_str(s->v, NULL));
1101 } else {
1102 if (s->c) {
1103 /* define corresponding symbol. A size of
1104 1 is put. */
1105 put_extern_sym(s, cur_text_section, s->jnext, 1);
1108 /* remove label */
1109 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1110 sym_free(s);
1112 *ptop = slast;
1115 /* eval an expression for #if/#elif */
1116 static int expr_preprocess(void)
1118 int c, t;
1119 TokenString str;
1121 tok_str_new(&str);
1122 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1123 next(); /* do macro subst */
1124 if (tok == TOK_DEFINED) {
1125 next_nomacro();
1126 t = tok;
1127 if (t == '(')
1128 next_nomacro();
1129 c = define_find(tok) != 0;
1130 if (t == '(')
1131 next_nomacro();
1132 tok = TOK_CINT;
1133 tokc.i = c;
1134 } else if (tok >= TOK_IDENT) {
1135 /* if undefined macro */
1136 tok = TOK_CINT;
1137 tokc.i = 0;
1139 tok_str_add_tok(&str);
1141 tok_str_add(&str, -1); /* simulate end of file */
1142 tok_str_add(&str, 0);
1143 /* now evaluate C constant expression */
1144 macro_ptr = str.str;
1145 next();
1146 c = expr_const();
1147 macro_ptr = NULL;
1148 tok_str_free(str.str);
1149 return c != 0;
1152 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1153 static void tok_print(int *str)
1155 int t;
1156 CValue cval;
1158 printf("<");
1159 while (1) {
1160 TOK_GET(&t, &str, &cval);
1161 if (!t)
1162 break;
1163 printf("%s", get_tok_str(t, &cval));
1165 printf(">\n");
1167 #endif
1169 /* parse after #define */
1170 ST_FUNC void parse_define(void)
1172 Sym *s, *first, **ps;
1173 int v, t, varg, is_vaargs, spc;
1174 TokenString str;
1176 v = tok;
1177 if (v < TOK_IDENT)
1178 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1179 /* XXX: should check if same macro (ANSI) */
1180 first = NULL;
1181 t = MACRO_OBJ;
1182 /* '(' must be just after macro definition for MACRO_FUNC */
1183 next_nomacro_spc();
1184 if (tok == '(') {
1185 next_nomacro();
1186 ps = &first;
1187 while (tok != ')') {
1188 varg = tok;
1189 next_nomacro();
1190 is_vaargs = 0;
1191 if (varg == TOK_DOTS) {
1192 varg = TOK___VA_ARGS__;
1193 is_vaargs = 1;
1194 } else if (tok == TOK_DOTS && gnu_ext) {
1195 is_vaargs = 1;
1196 next_nomacro();
1198 if (varg < TOK_IDENT)
1199 tcc_error("badly punctuated parameter list");
1200 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1201 *ps = s;
1202 ps = &s->next;
1203 if (tok != ',')
1204 break;
1205 next_nomacro();
1207 if (tok == ')')
1208 next_nomacro_spc();
1209 t = MACRO_FUNC;
1211 tok_str_new(&str);
1212 spc = 2;
1213 /* EOF testing necessary for '-D' handling */
1214 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1215 /* remove spaces around ## and after '#' */
1216 if (TOK_TWOSHARPS == tok) {
1217 if (1 == spc)
1218 --str.len;
1219 spc = 2;
1220 } else if ('#' == tok) {
1221 spc = 2;
1222 } else if (check_space(tok, &spc)) {
1223 goto skip;
1225 tok_str_add2(&str, tok, &tokc);
1226 skip:
1227 next_nomacro_spc();
1229 if (spc == 1)
1230 --str.len; /* remove trailing space */
1231 tok_str_add(&str, 0);
1232 #ifdef PP_DEBUG
1233 printf("define %s %d: ", get_tok_str(v, NULL), t);
1234 tok_print(str.str);
1235 #endif
1236 define_push(v, t, str.str, first);
1239 static inline int hash_cached_include(int type, const char *filename)
1241 const unsigned char *s;
1242 unsigned int h;
1244 h = TOK_HASH_INIT;
1245 h = TOK_HASH_FUNC(h, type);
1246 s = filename;
1247 while (*s) {
1248 h = TOK_HASH_FUNC(h, *s);
1249 s++;
1251 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1252 return h;
1255 /* XXX: use a token or a hash table to accelerate matching ? */
1256 static CachedInclude *search_cached_include(TCCState *s1,
1257 int type, const char *filename)
1259 CachedInclude *e;
1260 int i, h;
1261 h = hash_cached_include(type, filename);
1262 i = s1->cached_includes_hash[h];
1263 for(;;) {
1264 if (i == 0)
1265 break;
1266 e = s1->cached_includes[i - 1];
1267 if (e->type == type && !PATHCMP(e->filename, filename))
1268 return e;
1269 i = e->hash_next;
1271 return NULL;
1274 static inline void add_cached_include(TCCState *s1, int type,
1275 const char *filename, int ifndef_macro)
1277 CachedInclude *e;
1278 int h;
1280 if (search_cached_include(s1, type, filename))
1281 return;
1282 #ifdef INC_DEBUG
1283 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
1284 #endif
1285 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1286 if (!e)
1287 return;
1288 e->type = type;
1289 strcpy(e->filename, filename);
1290 e->ifndef_macro = ifndef_macro;
1291 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1292 /* add in hash table */
1293 h = hash_cached_include(type, filename);
1294 e->hash_next = s1->cached_includes_hash[h];
1295 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1298 static void pragma_parse(TCCState *s1)
1300 int val;
1302 next();
1303 if (tok == TOK_pack) {
1305 This may be:
1306 #pragma pack(1) // set
1307 #pragma pack() // reset to default
1308 #pragma pack(push,1) // push & set
1309 #pragma pack(pop) // restore previous
1311 next();
1312 skip('(');
1313 if (tok == TOK_ASM_pop) {
1314 next();
1315 if (s1->pack_stack_ptr <= s1->pack_stack) {
1316 stk_error:
1317 tcc_error("out of pack stack");
1319 s1->pack_stack_ptr--;
1320 } else {
1321 val = 0;
1322 if (tok != ')') {
1323 if (tok == TOK_ASM_push) {
1324 next();
1325 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1326 goto stk_error;
1327 s1->pack_stack_ptr++;
1328 skip(',');
1330 if (tok != TOK_CINT) {
1331 pack_error:
1332 tcc_error("invalid pack pragma");
1334 val = tokc.i;
1335 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1336 goto pack_error;
1337 next();
1339 *s1->pack_stack_ptr = val;
1340 skip(')');
1345 /* is_bof is true if first non space token at beginning of file */
1346 ST_FUNC void preprocess(int is_bof)
1348 TCCState *s1 = tcc_state;
1349 int i, c, n, saved_parse_flags;
1350 char buf[1024], *q;
1351 Sym *s;
1353 saved_parse_flags = parse_flags;
1354 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
1355 PARSE_FLAG_LINEFEED;
1356 next_nomacro();
1357 redo:
1358 switch(tok) {
1359 case TOK_DEFINE:
1360 next_nomacro();
1361 parse_define();
1362 break;
1363 case TOK_UNDEF:
1364 next_nomacro();
1365 s = define_find(tok);
1366 /* undefine symbol by putting an invalid name */
1367 if (s)
1368 define_undef(s);
1369 break;
1370 case TOK_INCLUDE:
1371 case TOK_INCLUDE_NEXT:
1372 ch = file->buf_ptr[0];
1373 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1374 skip_spaces();
1375 if (ch == '<') {
1376 c = '>';
1377 goto read_name;
1378 } else if (ch == '\"') {
1379 c = ch;
1380 read_name:
1381 inp();
1382 q = buf;
1383 while (ch != c && ch != '\n' && ch != CH_EOF) {
1384 if ((q - buf) < sizeof(buf) - 1)
1385 *q++ = ch;
1386 if (ch == '\\') {
1387 if (handle_stray_noerror() == 0)
1388 --q;
1389 } else
1390 inp();
1392 *q = '\0';
1393 minp();
1394 #if 0
1395 /* eat all spaces and comments after include */
1396 /* XXX: slightly incorrect */
1397 while (ch1 != '\n' && ch1 != CH_EOF)
1398 inp();
1399 #endif
1400 } else {
1401 /* computed #include : either we have only strings or
1402 we have anything enclosed in '<>' */
1403 next();
1404 buf[0] = '\0';
1405 if (tok == TOK_STR) {
1406 while (tok != TOK_LINEFEED) {
1407 if (tok != TOK_STR) {
1408 include_syntax:
1409 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1411 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
1412 next();
1414 c = '\"';
1415 } else {
1416 int len;
1417 while (tok != TOK_LINEFEED) {
1418 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1419 next();
1421 len = strlen(buf);
1422 /* check syntax and remove '<>' */
1423 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1424 goto include_syntax;
1425 memmove(buf, buf + 1, len - 2);
1426 buf[len - 2] = '\0';
1427 c = '>';
1431 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1432 tcc_error("#include recursion too deep");
1434 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
1435 for (i = -2; i < n; ++i) {
1436 char buf1[sizeof file->filename];
1437 CachedInclude *e;
1438 const char *path;
1439 int size, fd;
1441 if (i == -2) {
1442 /* check absolute include path */
1443 if (!IS_ABSPATH(buf))
1444 continue;
1445 buf1[0] = 0;
1447 } else if (i == -1) {
1448 /* search in current dir if "header.h" */
1449 if (c != '\"')
1450 continue;
1451 size = tcc_basename(file->filename) - file->filename;
1452 memcpy(buf1, file->filename, size);
1453 buf1[size] = '\0';
1455 } else {
1456 /* search in all the include paths */
1457 if (i < s1->nb_include_paths)
1458 path = s1->include_paths[i];
1459 else
1460 path = s1->sysinclude_paths[i - s1->nb_include_paths];
1461 pstrcpy(buf1, sizeof(buf1), path);
1462 pstrcat(buf1, sizeof(buf1), "/");
1465 pstrcat(buf1, sizeof(buf1), buf);
1467 e = search_cached_include(s1, c, buf1);
1468 if (e && define_find(e->ifndef_macro)) {
1469 /* no need to parse the include because the 'ifndef macro'
1470 is defined */
1471 #ifdef INC_DEBUG
1472 printf("%s: skipping %s\n", file->filename, buf);
1473 #endif
1474 fd = 0;
1475 } else {
1476 fd = tcc_open(s1, buf1);
1477 if (fd < 0)
1478 continue;
1481 if (tok == TOK_INCLUDE_NEXT) {
1482 tok = TOK_INCLUDE;
1483 if (fd)
1484 tcc_close();
1485 continue;
1488 if (0 == fd)
1489 goto include_done;
1491 #ifdef INC_DEBUG
1492 printf("%s: including %s\n", file->filename, buf1);
1493 #endif
1494 /* update target deps */
1495 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1496 tcc_strdup(buf1));
1497 /* XXX: fix current line init */
1498 /* push current file in stack */
1499 *s1->include_stack_ptr++ = file->prev;
1500 file->inc_type = c;
1501 pstrcpy(file->inc_filename, sizeof(file->inc_filename), buf1);
1502 /* add include file debug info */
1503 if (s1->do_debug)
1504 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1505 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1506 ch = file->buf_ptr[0];
1507 goto the_end;
1509 tcc_error("include file '%s' not found", buf);
1510 include_done:
1511 break;
1512 case TOK_IFNDEF:
1513 c = 1;
1514 goto do_ifdef;
1515 case TOK_IF:
1516 c = expr_preprocess();
1517 goto do_if;
1518 case TOK_IFDEF:
1519 c = 0;
1520 do_ifdef:
1521 next_nomacro();
1522 if (tok < TOK_IDENT)
1523 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1524 if (is_bof) {
1525 if (c) {
1526 #ifdef INC_DEBUG
1527 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1528 #endif
1529 file->ifndef_macro = tok;
1532 c = (define_find(tok) != 0) ^ c;
1533 do_if:
1534 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1535 tcc_error("memory full");
1536 *s1->ifdef_stack_ptr++ = c;
1537 goto test_skip;
1538 case TOK_ELSE:
1539 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1540 tcc_error("#else without matching #if");
1541 if (s1->ifdef_stack_ptr[-1] & 2)
1542 tcc_error("#else after #else");
1543 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1544 goto test_else;
1545 case TOK_ELIF:
1546 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1547 tcc_error("#elif without matching #if");
1548 c = s1->ifdef_stack_ptr[-1];
1549 if (c > 1)
1550 tcc_error("#elif after #else");
1551 /* last #if/#elif expression was true: we skip */
1552 if (c == 1)
1553 goto skip;
1554 c = expr_preprocess();
1555 s1->ifdef_stack_ptr[-1] = c;
1556 test_else:
1557 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1558 file->ifndef_macro = 0;
1559 test_skip:
1560 if (!(c & 1)) {
1561 skip:
1562 preprocess_skip();
1563 is_bof = 0;
1564 goto redo;
1566 break;
1567 case TOK_ENDIF:
1568 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1569 tcc_error("#endif without matching #if");
1570 s1->ifdef_stack_ptr--;
1571 /* '#ifndef macro' was at the start of file. Now we check if
1572 an '#endif' is exactly at the end of file */
1573 if (file->ifndef_macro &&
1574 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1575 file->ifndef_macro_saved = file->ifndef_macro;
1576 /* need to set to zero to avoid false matches if another
1577 #ifndef at middle of file */
1578 file->ifndef_macro = 0;
1579 while (tok != TOK_LINEFEED)
1580 next_nomacro();
1581 tok_flags |= TOK_FLAG_ENDIF;
1582 goto the_end;
1584 break;
1585 case TOK_LINE:
1586 next();
1587 if (tok != TOK_CINT)
1588 tcc_error("#line");
1589 file->line_num = tokc.i - 1; /* the line number will be incremented after */
1590 next();
1591 if (tok != TOK_LINEFEED) {
1592 if (tok != TOK_STR)
1593 tcc_error("#line");
1594 pstrcpy(file->filename, sizeof(file->filename),
1595 (char *)tokc.cstr->data);
1597 break;
1598 case TOK_ERROR:
1599 case TOK_WARNING:
1600 c = tok;
1601 ch = file->buf_ptr[0];
1602 skip_spaces();
1603 q = buf;
1604 while (ch != '\n' && ch != CH_EOF) {
1605 if ((q - buf) < sizeof(buf) - 1)
1606 *q++ = ch;
1607 if (ch == '\\') {
1608 if (handle_stray_noerror() == 0)
1609 --q;
1610 } else
1611 inp();
1613 *q = '\0';
1614 if (c == TOK_ERROR)
1615 tcc_error("#error %s", buf);
1616 else
1617 tcc_warning("#warning %s", buf);
1618 break;
1619 case TOK_PRAGMA:
1620 pragma_parse(s1);
1621 break;
1622 default:
1623 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_PPNUM) {
1624 /* '!' is ignored to allow C scripts. numbers are ignored
1625 to emulate cpp behaviour */
1626 } else {
1627 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
1628 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1629 else {
1630 /* this is a gas line comment in an 'S' file. */
1631 file->buf_ptr = parse_line_comment(file->buf_ptr);
1632 goto the_end;
1635 break;
1637 /* ignore other preprocess commands or #! for C scripts */
1638 while (tok != TOK_LINEFEED)
1639 next_nomacro();
1640 the_end:
1641 parse_flags = saved_parse_flags;
1644 /* evaluate escape codes in a string. */
1645 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1647 int c, n;
1648 const uint8_t *p;
1650 p = buf;
1651 for(;;) {
1652 c = *p;
1653 if (c == '\0')
1654 break;
1655 if (c == '\\') {
1656 p++;
1657 /* escape */
1658 c = *p;
1659 switch(c) {
1660 case '0': case '1': case '2': case '3':
1661 case '4': case '5': case '6': case '7':
1662 /* at most three octal digits */
1663 n = c - '0';
1664 p++;
1665 c = *p;
1666 if (isoct(c)) {
1667 n = n * 8 + c - '0';
1668 p++;
1669 c = *p;
1670 if (isoct(c)) {
1671 n = n * 8 + c - '0';
1672 p++;
1675 c = n;
1676 goto add_char_nonext;
1677 case 'x':
1678 case 'u':
1679 case 'U':
1680 p++;
1681 n = 0;
1682 for(;;) {
1683 c = *p;
1684 if (c >= 'a' && c <= 'f')
1685 c = c - 'a' + 10;
1686 else if (c >= 'A' && c <= 'F')
1687 c = c - 'A' + 10;
1688 else if (isnum(c))
1689 c = c - '0';
1690 else
1691 break;
1692 n = n * 16 + c;
1693 p++;
1695 c = n;
1696 goto add_char_nonext;
1697 case 'a':
1698 c = '\a';
1699 break;
1700 case 'b':
1701 c = '\b';
1702 break;
1703 case 'f':
1704 c = '\f';
1705 break;
1706 case 'n':
1707 c = '\n';
1708 break;
1709 case 'r':
1710 c = '\r';
1711 break;
1712 case 't':
1713 c = '\t';
1714 break;
1715 case 'v':
1716 c = '\v';
1717 break;
1718 case 'e':
1719 if (!gnu_ext)
1720 goto invalid_escape;
1721 c = 27;
1722 break;
1723 case '\'':
1724 case '\"':
1725 case '\\':
1726 case '?':
1727 break;
1728 default:
1729 invalid_escape:
1730 if (c >= '!' && c <= '~')
1731 tcc_warning("unknown escape sequence: \'\\%c\'", c);
1732 else
1733 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
1734 break;
1737 p++;
1738 add_char_nonext:
1739 if (!is_long)
1740 cstr_ccat(outstr, c);
1741 else
1742 cstr_wccat(outstr, c);
1744 /* add a trailing '\0' */
1745 if (!is_long)
1746 cstr_ccat(outstr, '\0');
1747 else
1748 cstr_wccat(outstr, '\0');
1751 /* we use 64 bit numbers */
1752 #define BN_SIZE 2
1754 /* bn = (bn << shift) | or_val */
1755 static void bn_lshift(unsigned int *bn, int shift, int or_val)
1757 int i;
1758 unsigned int v;
1759 for(i=0;i<BN_SIZE;i++) {
1760 v = bn[i];
1761 bn[i] = (v << shift) | or_val;
1762 or_val = v >> (32 - shift);
1766 static void bn_zero(unsigned int *bn)
1768 int i;
1769 for(i=0;i<BN_SIZE;i++) {
1770 bn[i] = 0;
1774 /* parse number in null terminated string 'p' and return it in the
1775 current token */
1776 static void parse_number(const char *p)
1778 int b, t, shift, frac_bits, s, exp_val, ch;
1779 char *q;
1780 unsigned int bn[BN_SIZE];
1781 double d;
1783 /* number */
1784 q = token_buf;
1785 ch = *p++;
1786 t = ch;
1787 ch = *p++;
1788 *q++ = t;
1789 b = 10;
1790 if (t == '.') {
1791 goto float_frac_parse;
1792 } else if (t == '0') {
1793 if (ch == 'x' || ch == 'X') {
1794 q--;
1795 ch = *p++;
1796 b = 16;
1797 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
1798 q--;
1799 ch = *p++;
1800 b = 2;
1803 /* parse all digits. cannot check octal numbers at this stage
1804 because of floating point constants */
1805 while (1) {
1806 if (ch >= 'a' && ch <= 'f')
1807 t = ch - 'a' + 10;
1808 else if (ch >= 'A' && ch <= 'F')
1809 t = ch - 'A' + 10;
1810 else if (isnum(ch))
1811 t = ch - '0';
1812 else
1813 break;
1814 if (t >= b)
1815 break;
1816 if (q >= token_buf + STRING_MAX_SIZE) {
1817 num_too_long:
1818 tcc_error("number too long");
1820 *q++ = ch;
1821 ch = *p++;
1823 if (ch == '.' ||
1824 ((ch == 'e' || ch == 'E') && b == 10) ||
1825 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
1826 if (b != 10) {
1827 /* NOTE: strtox should support that for hexa numbers, but
1828 non ISOC99 libcs do not support it, so we prefer to do
1829 it by hand */
1830 /* hexadecimal or binary floats */
1831 /* XXX: handle overflows */
1832 *q = '\0';
1833 if (b == 16)
1834 shift = 4;
1835 else
1836 shift = 2;
1837 bn_zero(bn);
1838 q = token_buf;
1839 while (1) {
1840 t = *q++;
1841 if (t == '\0') {
1842 break;
1843 } else if (t >= 'a') {
1844 t = t - 'a' + 10;
1845 } else if (t >= 'A') {
1846 t = t - 'A' + 10;
1847 } else {
1848 t = t - '0';
1850 bn_lshift(bn, shift, t);
1852 frac_bits = 0;
1853 if (ch == '.') {
1854 ch = *p++;
1855 while (1) {
1856 t = ch;
1857 if (t >= 'a' && t <= 'f') {
1858 t = t - 'a' + 10;
1859 } else if (t >= 'A' && t <= 'F') {
1860 t = t - 'A' + 10;
1861 } else if (t >= '0' && t <= '9') {
1862 t = t - '0';
1863 } else {
1864 break;
1866 if (t >= b)
1867 tcc_error("invalid digit");
1868 bn_lshift(bn, shift, t);
1869 frac_bits += shift;
1870 ch = *p++;
1873 if (ch != 'p' && ch != 'P')
1874 expect("exponent");
1875 ch = *p++;
1876 s = 1;
1877 exp_val = 0;
1878 if (ch == '+') {
1879 ch = *p++;
1880 } else if (ch == '-') {
1881 s = -1;
1882 ch = *p++;
1884 if (ch < '0' || ch > '9')
1885 expect("exponent digits");
1886 while (ch >= '0' && ch <= '9') {
1887 exp_val = exp_val * 10 + ch - '0';
1888 ch = *p++;
1890 exp_val = exp_val * s;
1892 /* now we can generate the number */
1893 /* XXX: should patch directly float number */
1894 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
1895 d = ldexp(d, exp_val - frac_bits);
1896 t = toup(ch);
1897 if (t == 'F') {
1898 ch = *p++;
1899 tok = TOK_CFLOAT;
1900 /* float : should handle overflow */
1901 tokc.f = (float)d;
1902 } else if (t == 'L') {
1903 ch = *p++;
1904 #ifdef TCC_TARGET_PE
1905 tok = TOK_CDOUBLE;
1906 tokc.d = d;
1907 #else
1908 tok = TOK_CLDOUBLE;
1909 /* XXX: not large enough */
1910 tokc.ld = (long double)d;
1911 #endif
1912 } else {
1913 tok = TOK_CDOUBLE;
1914 tokc.d = d;
1916 } else {
1917 /* decimal floats */
1918 if (ch == '.') {
1919 if (q >= token_buf + STRING_MAX_SIZE)
1920 goto num_too_long;
1921 *q++ = ch;
1922 ch = *p++;
1923 float_frac_parse:
1924 while (ch >= '0' && ch <= '9') {
1925 if (q >= token_buf + STRING_MAX_SIZE)
1926 goto num_too_long;
1927 *q++ = ch;
1928 ch = *p++;
1931 if (ch == 'e' || ch == 'E') {
1932 if (q >= token_buf + STRING_MAX_SIZE)
1933 goto num_too_long;
1934 *q++ = ch;
1935 ch = *p++;
1936 if (ch == '-' || ch == '+') {
1937 if (q >= token_buf + STRING_MAX_SIZE)
1938 goto num_too_long;
1939 *q++ = ch;
1940 ch = *p++;
1942 if (ch < '0' || ch > '9')
1943 expect("exponent digits");
1944 while (ch >= '0' && ch <= '9') {
1945 if (q >= token_buf + STRING_MAX_SIZE)
1946 goto num_too_long;
1947 *q++ = ch;
1948 ch = *p++;
1951 *q = '\0';
1952 t = toup(ch);
1953 errno = 0;
1954 if (t == 'F') {
1955 ch = *p++;
1956 tok = TOK_CFLOAT;
1957 tokc.f = strtof(token_buf, NULL);
1958 } else if (t == 'L') {
1959 ch = *p++;
1960 #ifdef TCC_TARGET_PE
1961 tok = TOK_CDOUBLE;
1962 tokc.d = strtod(token_buf, NULL);
1963 #else
1964 tok = TOK_CLDOUBLE;
1965 tokc.ld = strtold(token_buf, NULL);
1966 #endif
1967 } else {
1968 tok = TOK_CDOUBLE;
1969 tokc.d = strtod(token_buf, NULL);
1972 } else {
1973 unsigned long long n, n1;
1974 int lcount, ucount;
1976 /* integer number */
1977 *q = '\0';
1978 q = token_buf;
1979 if (b == 10 && *q == '0') {
1980 b = 8;
1981 q++;
1983 n = 0;
1984 while(1) {
1985 t = *q++;
1986 /* no need for checks except for base 10 / 8 errors */
1987 if (t == '\0') {
1988 break;
1989 } else if (t >= 'a') {
1990 t = t - 'a' + 10;
1991 } else if (t >= 'A') {
1992 t = t - 'A' + 10;
1993 } else {
1994 t = t - '0';
1995 if (t >= b)
1996 tcc_error("invalid digit");
1998 n1 = n;
1999 n = n * b + t;
2000 /* detect overflow */
2001 /* XXX: this test is not reliable */
2002 if (n < n1)
2003 tcc_error("integer constant overflow");
2006 /* XXX: not exactly ANSI compliant */
2007 if ((n & 0xffffffff00000000LL) != 0) {
2008 if ((n >> 63) != 0)
2009 tok = TOK_CULLONG;
2010 else
2011 tok = TOK_CLLONG;
2012 } else if (n > 0x7fffffff) {
2013 tok = TOK_CUINT;
2014 } else {
2015 tok = TOK_CINT;
2017 lcount = 0;
2018 ucount = 0;
2019 for(;;) {
2020 t = toup(ch);
2021 if (t == 'L') {
2022 if (lcount >= 2)
2023 tcc_error("three 'l's in integer constant");
2024 lcount++;
2025 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2026 if (lcount == 2) {
2027 #endif
2028 if (tok == TOK_CINT)
2029 tok = TOK_CLLONG;
2030 else if (tok == TOK_CUINT)
2031 tok = TOK_CULLONG;
2032 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2034 #endif
2035 ch = *p++;
2036 } else if (t == 'U') {
2037 if (ucount >= 1)
2038 tcc_error("two 'u's in integer constant");
2039 ucount++;
2040 if (tok == TOK_CINT)
2041 tok = TOK_CUINT;
2042 else if (tok == TOK_CLLONG)
2043 tok = TOK_CULLONG;
2044 ch = *p++;
2045 } else {
2046 break;
2049 if (tok == TOK_CINT || tok == TOK_CUINT)
2050 tokc.ui = n;
2051 else
2052 tokc.ull = n;
2054 if (ch)
2055 tcc_error("invalid number\n");
2059 #define PARSE2(c1, tok1, c2, tok2) \
2060 case c1: \
2061 PEEKC(c, p); \
2062 if (c == c2) { \
2063 p++; \
2064 tok = tok2; \
2065 } else { \
2066 tok = tok1; \
2068 break;
2070 /* return next token without macro substitution */
2071 static inline void next_nomacro1(void)
2073 int t, c, is_long;
2074 TokenSym *ts;
2075 uint8_t *p, *p1;
2076 unsigned int h;
2078 p = file->buf_ptr;
2079 redo_no_start:
2080 c = *p;
2081 switch(c) {
2082 case ' ':
2083 case '\t':
2084 tok = c;
2085 p++;
2086 goto keep_tok_flags;
2087 case '\f':
2088 case '\v':
2089 case '\r':
2090 p++;
2091 goto redo_no_start;
2092 case '\\':
2093 /* first look if it is in fact an end of buffer */
2094 if (p >= file->buf_end) {
2095 file->buf_ptr = p;
2096 handle_eob();
2097 p = file->buf_ptr;
2098 if (p >= file->buf_end)
2099 goto parse_eof;
2100 else
2101 goto redo_no_start;
2102 } else {
2103 file->buf_ptr = p;
2104 ch = *p;
2105 handle_stray();
2106 p = file->buf_ptr;
2107 goto redo_no_start;
2109 parse_eof:
2111 TCCState *s1 = tcc_state;
2112 if ((parse_flags & PARSE_FLAG_LINEFEED)
2113 && !(tok_flags & TOK_FLAG_EOF)) {
2114 tok_flags |= TOK_FLAG_EOF;
2115 tok = TOK_LINEFEED;
2116 goto keep_tok_flags;
2117 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2118 tok = TOK_EOF;
2119 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2120 tcc_error("missing #endif");
2121 } else if (s1->include_stack_ptr == s1->include_stack) {
2122 /* no include left : end of file. */
2123 tok = TOK_EOF;
2124 } else {
2125 tok_flags &= ~TOK_FLAG_EOF;
2126 /* pop include file */
2128 /* test if previous '#endif' was after a #ifdef at
2129 start of file */
2130 if (tok_flags & TOK_FLAG_ENDIF) {
2131 #ifdef INC_DEBUG
2132 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2133 #endif
2134 add_cached_include(s1, file->inc_type, file->inc_filename,
2135 file->ifndef_macro_saved);
2138 /* add end of include file debug info */
2139 if (tcc_state->do_debug) {
2140 put_stabd(N_EINCL, 0, 0);
2142 /* pop include stack */
2143 tcc_close();
2144 s1->include_stack_ptr--;
2145 p = file->buf_ptr;
2146 goto redo_no_start;
2149 break;
2151 case '\n':
2152 file->line_num++;
2153 tok_flags |= TOK_FLAG_BOL;
2154 p++;
2155 maybe_newline:
2156 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2157 goto redo_no_start;
2158 tok = TOK_LINEFEED;
2159 goto keep_tok_flags;
2161 case '#':
2162 /* XXX: simplify */
2163 PEEKC(c, p);
2164 if ((tok_flags & TOK_FLAG_BOL) &&
2165 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2166 file->buf_ptr = p;
2167 preprocess(tok_flags & TOK_FLAG_BOF);
2168 p = file->buf_ptr;
2169 goto maybe_newline;
2170 } else {
2171 if (c == '#') {
2172 p++;
2173 tok = TOK_TWOSHARPS;
2174 } else {
2175 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
2176 p = parse_line_comment(p - 1);
2177 goto redo_no_start;
2178 } else {
2179 tok = '#';
2183 break;
2185 case 'a': case 'b': case 'c': case 'd':
2186 case 'e': case 'f': case 'g': case 'h':
2187 case 'i': case 'j': case 'k': case 'l':
2188 case 'm': case 'n': case 'o': case 'p':
2189 case 'q': case 'r': case 's': case 't':
2190 case 'u': case 'v': case 'w': case 'x':
2191 case 'y': case 'z':
2192 case 'A': case 'B': case 'C': case 'D':
2193 case 'E': case 'F': case 'G': case 'H':
2194 case 'I': case 'J': case 'K':
2195 case 'M': case 'N': case 'O': case 'P':
2196 case 'Q': case 'R': case 'S': case 'T':
2197 case 'U': case 'V': case 'W': case 'X':
2198 case 'Y': case 'Z':
2199 case '_':
2200 parse_ident_fast:
2201 p1 = p;
2202 h = TOK_HASH_INIT;
2203 h = TOK_HASH_FUNC(h, c);
2204 p++;
2205 for(;;) {
2206 c = *p;
2207 if (!isidnum_table[c-CH_EOF])
2208 break;
2209 h = TOK_HASH_FUNC(h, c);
2210 p++;
2212 if (c != '\\') {
2213 TokenSym **pts;
2214 int len;
2216 /* fast case : no stray found, so we have the full token
2217 and we have already hashed it */
2218 len = p - p1;
2219 h &= (TOK_HASH_SIZE - 1);
2220 pts = &hash_ident[h];
2221 for(;;) {
2222 ts = *pts;
2223 if (!ts)
2224 break;
2225 if (ts->len == len && !memcmp(ts->str, p1, len))
2226 goto token_found;
2227 pts = &(ts->hash_next);
2229 ts = tok_alloc_new(pts, p1, len);
2230 token_found: ;
2231 } else {
2232 /* slower case */
2233 cstr_reset(&tokcstr);
2235 while (p1 < p) {
2236 cstr_ccat(&tokcstr, *p1);
2237 p1++;
2239 p--;
2240 PEEKC(c, p);
2241 parse_ident_slow:
2242 while (isidnum_table[c-CH_EOF]) {
2243 cstr_ccat(&tokcstr, c);
2244 PEEKC(c, p);
2246 ts = tok_alloc(tokcstr.data, tokcstr.size);
2248 tok = ts->tok;
2249 break;
2250 case 'L':
2251 t = p[1];
2252 if (t != '\\' && t != '\'' && t != '\"') {
2253 /* fast case */
2254 goto parse_ident_fast;
2255 } else {
2256 PEEKC(c, p);
2257 if (c == '\'' || c == '\"') {
2258 is_long = 1;
2259 goto str_const;
2260 } else {
2261 cstr_reset(&tokcstr);
2262 cstr_ccat(&tokcstr, 'L');
2263 goto parse_ident_slow;
2266 break;
2267 case '0': case '1': case '2': case '3':
2268 case '4': case '5': case '6': case '7':
2269 case '8': case '9':
2271 cstr_reset(&tokcstr);
2272 /* after the first digit, accept digits, alpha, '.' or sign if
2273 prefixed by 'eEpP' */
2274 parse_num:
2275 for(;;) {
2276 t = c;
2277 cstr_ccat(&tokcstr, c);
2278 PEEKC(c, p);
2279 if (!(isnum(c) || isid(c) || c == '.' ||
2280 ((c == '+' || c == '-') &&
2281 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
2282 break;
2284 /* We add a trailing '\0' to ease parsing */
2285 cstr_ccat(&tokcstr, '\0');
2286 tokc.cstr = &tokcstr;
2287 tok = TOK_PPNUM;
2288 break;
2289 case '.':
2290 /* special dot handling because it can also start a number */
2291 PEEKC(c, p);
2292 if (isnum(c)) {
2293 cstr_reset(&tokcstr);
2294 cstr_ccat(&tokcstr, '.');
2295 goto parse_num;
2296 } else if (c == '.') {
2297 PEEKC(c, p);
2298 if (c != '.')
2299 expect("'.'");
2300 PEEKC(c, p);
2301 tok = TOK_DOTS;
2302 } else {
2303 tok = '.';
2305 break;
2306 case '\'':
2307 case '\"':
2308 is_long = 0;
2309 str_const:
2311 CString str;
2312 int sep;
2314 sep = c;
2316 /* parse the string */
2317 cstr_new(&str);
2318 p = parse_pp_string(p, sep, &str);
2319 cstr_ccat(&str, '\0');
2321 /* eval the escape (should be done as TOK_PPNUM) */
2322 cstr_reset(&tokcstr);
2323 parse_escape_string(&tokcstr, str.data, is_long);
2324 cstr_free(&str);
2326 if (sep == '\'') {
2327 int char_size;
2328 /* XXX: make it portable */
2329 if (!is_long)
2330 char_size = 1;
2331 else
2332 char_size = sizeof(nwchar_t);
2333 if (tokcstr.size <= char_size)
2334 tcc_error("empty character constant");
2335 if (tokcstr.size > 2 * char_size)
2336 tcc_warning("multi-character character constant");
2337 if (!is_long) {
2338 tokc.i = *(int8_t *)tokcstr.data;
2339 tok = TOK_CCHAR;
2340 } else {
2341 tokc.i = *(nwchar_t *)tokcstr.data;
2342 tok = TOK_LCHAR;
2344 } else {
2345 tokc.cstr = &tokcstr;
2346 if (!is_long)
2347 tok = TOK_STR;
2348 else
2349 tok = TOK_LSTR;
2352 break;
2354 case '<':
2355 PEEKC(c, p);
2356 if (c == '=') {
2357 p++;
2358 tok = TOK_LE;
2359 } else if (c == '<') {
2360 PEEKC(c, p);
2361 if (c == '=') {
2362 p++;
2363 tok = TOK_A_SHL;
2364 } else {
2365 tok = TOK_SHL;
2367 } else {
2368 tok = TOK_LT;
2370 break;
2372 case '>':
2373 PEEKC(c, p);
2374 if (c == '=') {
2375 p++;
2376 tok = TOK_GE;
2377 } else if (c == '>') {
2378 PEEKC(c, p);
2379 if (c == '=') {
2380 p++;
2381 tok = TOK_A_SAR;
2382 } else {
2383 tok = TOK_SAR;
2385 } else {
2386 tok = TOK_GT;
2388 break;
2390 case '&':
2391 PEEKC(c, p);
2392 if (c == '&') {
2393 p++;
2394 tok = TOK_LAND;
2395 } else if (c == '=') {
2396 p++;
2397 tok = TOK_A_AND;
2398 } else {
2399 tok = '&';
2401 break;
2403 case '|':
2404 PEEKC(c, p);
2405 if (c == '|') {
2406 p++;
2407 tok = TOK_LOR;
2408 } else if (c == '=') {
2409 p++;
2410 tok = TOK_A_OR;
2411 } else {
2412 tok = '|';
2414 break;
2416 case '+':
2417 PEEKC(c, p);
2418 if (c == '+') {
2419 p++;
2420 tok = TOK_INC;
2421 } else if (c == '=') {
2422 p++;
2423 tok = TOK_A_ADD;
2424 } else {
2425 tok = '+';
2427 break;
2429 case '-':
2430 PEEKC(c, p);
2431 if (c == '-') {
2432 p++;
2433 tok = TOK_DEC;
2434 } else if (c == '=') {
2435 p++;
2436 tok = TOK_A_SUB;
2437 } else if (c == '>') {
2438 p++;
2439 tok = TOK_ARROW;
2440 } else {
2441 tok = '-';
2443 break;
2445 PARSE2('!', '!', '=', TOK_NE)
2446 PARSE2('=', '=', '=', TOK_EQ)
2447 PARSE2('*', '*', '=', TOK_A_MUL)
2448 PARSE2('%', '%', '=', TOK_A_MOD)
2449 PARSE2('^', '^', '=', TOK_A_XOR)
2451 /* comments or operator */
2452 case '/':
2453 PEEKC(c, p);
2454 if (c == '*') {
2455 p = parse_comment(p);
2456 /* comments replaced by a blank */
2457 tok = ' ';
2458 goto keep_tok_flags;
2459 } else if (c == '/') {
2460 p = parse_line_comment(p);
2461 tok = ' ';
2462 goto keep_tok_flags;
2463 } else if (c == '=') {
2464 p++;
2465 tok = TOK_A_DIV;
2466 } else {
2467 tok = '/';
2469 break;
2471 /* simple tokens */
2472 case '(':
2473 case ')':
2474 case '[':
2475 case ']':
2476 case '{':
2477 case '}':
2478 case ',':
2479 case ';':
2480 case ':':
2481 case '?':
2482 case '~':
2483 case '$': /* only used in assembler */
2484 case '@': /* dito */
2485 tok = c;
2486 p++;
2487 break;
2488 default:
2489 tcc_error("unrecognized character \\x%02x", c);
2490 break;
2492 tok_flags = 0;
2493 keep_tok_flags:
2494 file->buf_ptr = p;
2495 #if defined(PARSE_DEBUG)
2496 printf("token = %s\n", get_tok_str(tok, &tokc));
2497 #endif
2500 /* return next token without macro substitution. Can read input from
2501 macro_ptr buffer */
2502 static void next_nomacro_spc(void)
2504 if (macro_ptr) {
2505 redo:
2506 tok = *macro_ptr;
2507 if (tok) {
2508 TOK_GET(&tok, &macro_ptr, &tokc);
2509 if (tok == TOK_LINENUM) {
2510 file->line_num = tokc.i;
2511 goto redo;
2514 } else {
2515 next_nomacro1();
2519 ST_FUNC void next_nomacro(void)
2521 do {
2522 next_nomacro_spc();
2523 } while (is_space(tok));
2526 /* substitute args in macro_str and return allocated string */
2527 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2529 int last_tok, t, spc;
2530 const int *st;
2531 Sym *s;
2532 CValue cval;
2533 TokenString str;
2534 CString cstr;
2536 tok_str_new(&str);
2537 last_tok = 0;
2538 while(1) {
2539 TOK_GET(&t, &macro_str, &cval);
2540 if (!t)
2541 break;
2542 if (t == '#') {
2543 /* stringize */
2544 TOK_GET(&t, &macro_str, &cval);
2545 if (!t)
2546 break;
2547 s = sym_find2(args, t);
2548 if (s) {
2549 cstr_new(&cstr);
2550 st = s->d;
2551 spc = 0;
2552 while (*st) {
2553 TOK_GET(&t, &st, &cval);
2554 if (!check_space(t, &spc))
2555 cstr_cat(&cstr, get_tok_str(t, &cval));
2557 cstr.size -= spc;
2558 cstr_ccat(&cstr, '\0');
2559 #ifdef PP_DEBUG
2560 printf("stringize: %s\n", (char *)cstr.data);
2561 #endif
2562 /* add string */
2563 cval.cstr = &cstr;
2564 tok_str_add2(&str, TOK_STR, &cval);
2565 cstr_free(&cstr);
2566 } else {
2567 tok_str_add2(&str, t, &cval);
2569 } else if (t >= TOK_IDENT) {
2570 s = sym_find2(args, t);
2571 if (s) {
2572 st = s->d;
2573 /* if '##' is present before or after, no arg substitution */
2574 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
2575 /* special case for var arg macros : ## eats the
2576 ',' if empty VA_ARGS variable. */
2577 /* XXX: test of the ',' is not 100%
2578 reliable. should fix it to avoid security
2579 problems */
2580 if (gnu_ext && s->type.t &&
2581 last_tok == TOK_TWOSHARPS &&
2582 str.len >= 2 && str.str[str.len - 2] == ',') {
2583 if (*st == 0) {
2584 /* suppress ',' '##' */
2585 str.len -= 2;
2586 } else {
2587 /* suppress '##' and add variable */
2588 str.len--;
2589 goto add_var;
2591 } else {
2592 int t1;
2593 add_var:
2594 for(;;) {
2595 TOK_GET(&t1, &st, &cval);
2596 if (!t1)
2597 break;
2598 tok_str_add2(&str, t1, &cval);
2601 } else {
2602 /* NOTE: the stream cannot be read when macro
2603 substituing an argument */
2604 macro_subst(&str, nested_list, st, NULL);
2606 } else {
2607 tok_str_add(&str, t);
2609 } else {
2610 tok_str_add2(&str, t, &cval);
2612 last_tok = t;
2614 tok_str_add(&str, 0);
2615 return str.str;
2618 static char const ab_month_name[12][4] =
2620 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2621 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2624 /* do macro substitution of current token with macro 's' and add
2625 result to (tok_str,tok_len). 'nested_list' is the list of all
2626 macros we got inside to avoid recursing. Return non zero if no
2627 substitution needs to be done */
2628 static int macro_subst_tok(TokenString *tok_str,
2629 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
2631 Sym *args, *sa, *sa1;
2632 int mstr_allocated, parlevel, *mstr, t, t1, spc;
2633 const int *p;
2634 TokenString str;
2635 char *cstrval;
2636 CValue cval;
2637 CString cstr;
2638 char buf[32];
2640 /* if symbol is a macro, prepare substitution */
2641 /* special macros */
2642 if (tok == TOK___LINE__) {
2643 snprintf(buf, sizeof(buf), "%d", file->line_num);
2644 cstrval = buf;
2645 t1 = TOK_PPNUM;
2646 goto add_cstr1;
2647 } else if (tok == TOK___FILE__) {
2648 cstrval = file->filename;
2649 goto add_cstr;
2650 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
2651 time_t ti;
2652 struct tm *tm;
2654 time(&ti);
2655 tm = localtime(&ti);
2656 if (tok == TOK___DATE__) {
2657 snprintf(buf, sizeof(buf), "%s %2d %d",
2658 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
2659 } else {
2660 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
2661 tm->tm_hour, tm->tm_min, tm->tm_sec);
2663 cstrval = buf;
2664 add_cstr:
2665 t1 = TOK_STR;
2666 add_cstr1:
2667 cstr_new(&cstr);
2668 cstr_cat(&cstr, cstrval);
2669 cstr_ccat(&cstr, '\0');
2670 cval.cstr = &cstr;
2671 tok_str_add2(tok_str, t1, &cval);
2672 cstr_free(&cstr);
2673 } else {
2674 mstr = s->d;
2675 mstr_allocated = 0;
2676 if (s->type.t == MACRO_FUNC) {
2677 /* NOTE: we do not use next_nomacro to avoid eating the
2678 next token. XXX: find better solution */
2679 redo:
2680 if (macro_ptr) {
2681 p = macro_ptr;
2682 while (is_space(t = *p) || TOK_LINEFEED == t)
2683 ++p;
2684 if (t == 0 && can_read_stream) {
2685 /* end of macro stream: we must look at the token
2686 after in the file */
2687 struct macro_level *ml = *can_read_stream;
2688 macro_ptr = NULL;
2689 if (ml)
2691 macro_ptr = ml->p;
2692 ml->p = NULL;
2693 *can_read_stream = ml -> prev;
2695 /* also, end of scope for nested defined symbol */
2696 (*nested_list)->v = -1;
2697 goto redo;
2699 } else {
2700 ch = file->buf_ptr[0];
2701 while (is_space(ch) || ch == '\n' || ch == '/')
2703 if (ch == '/')
2705 int c;
2706 uint8_t *p = file->buf_ptr;
2707 PEEKC(c, p);
2708 if (c == '*') {
2709 p = parse_comment(p);
2710 file->buf_ptr = p - 1;
2711 } else if (c == '/') {
2712 p = parse_line_comment(p);
2713 file->buf_ptr = p - 1;
2714 } else
2715 break;
2717 cinp();
2719 t = ch;
2721 if (t != '(') /* no macro subst */
2722 return -1;
2724 /* argument macro */
2725 next_nomacro();
2726 next_nomacro();
2727 args = NULL;
2728 sa = s->next;
2729 /* NOTE: empty args are allowed, except if no args */
2730 for(;;) {
2731 /* handle '()' case */
2732 if (!args && !sa && tok == ')')
2733 break;
2734 if (!sa)
2735 tcc_error("macro '%s' used with too many args",
2736 get_tok_str(s->v, 0));
2737 tok_str_new(&str);
2738 parlevel = spc = 0;
2739 /* NOTE: non zero sa->t indicates VA_ARGS */
2740 while ((parlevel > 0 ||
2741 (tok != ')' &&
2742 (tok != ',' || sa->type.t))) &&
2743 tok != -1) {
2744 if (tok == '(')
2745 parlevel++;
2746 else if (tok == ')')
2747 parlevel--;
2748 if (tok == TOK_LINEFEED)
2749 tok = ' ';
2750 if (!check_space(tok, &spc))
2751 tok_str_add2(&str, tok, &tokc);
2752 next_nomacro_spc();
2754 str.len -= spc;
2755 tok_str_add(&str, 0);
2756 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
2757 sa1->d = str.str;
2758 sa = sa->next;
2759 if (tok == ')') {
2760 /* special case for gcc var args: add an empty
2761 var arg argument if it is omitted */
2762 if (sa && sa->type.t && gnu_ext)
2763 continue;
2764 else
2765 break;
2767 if (tok != ',')
2768 expect(",");
2769 next_nomacro();
2771 if (sa) {
2772 tcc_error("macro '%s' used with too few args",
2773 get_tok_str(s->v, 0));
2776 /* now subst each arg */
2777 mstr = macro_arg_subst(nested_list, mstr, args);
2778 /* free memory */
2779 sa = args;
2780 while (sa) {
2781 sa1 = sa->prev;
2782 tok_str_free(sa->d);
2783 sym_free(sa);
2784 sa = sa1;
2786 mstr_allocated = 1;
2788 sym_push2(nested_list, s->v, 0, 0);
2789 macro_subst(tok_str, nested_list, mstr, can_read_stream);
2790 /* pop nested defined symbol */
2791 sa1 = *nested_list;
2792 *nested_list = sa1->prev;
2793 sym_free(sa1);
2794 if (mstr_allocated)
2795 tok_str_free(mstr);
2797 return 0;
2800 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2801 return the resulting string (which must be freed). */
2802 static inline int *macro_twosharps(const int *macro_str)
2804 const int *ptr;
2805 int t;
2806 CValue cval;
2807 TokenString macro_str1;
2808 CString cstr;
2809 int n, start_of_nosubsts;
2811 /* we search the first '##' */
2812 for(ptr = macro_str;;) {
2813 TOK_GET(&t, &ptr, &cval);
2814 if (t == TOK_TWOSHARPS)
2815 break;
2816 /* nothing more to do if end of string */
2817 if (t == 0)
2818 return NULL;
2821 /* we saw '##', so we need more processing to handle it */
2822 start_of_nosubsts = -1;
2823 tok_str_new(&macro_str1);
2824 for(ptr = macro_str;;) {
2825 TOK_GET(&tok, &ptr, &tokc);
2826 if (tok == 0)
2827 break;
2828 if (tok == TOK_TWOSHARPS)
2829 continue;
2830 if (tok == TOK_NOSUBST && start_of_nosubsts < 0)
2831 start_of_nosubsts = macro_str1.len;
2832 while (*ptr == TOK_TWOSHARPS) {
2833 /* given 'a##b', remove nosubsts preceding 'a' */
2834 if (start_of_nosubsts >= 0)
2835 macro_str1.len = start_of_nosubsts;
2836 /* given 'a##b', skip '##' */
2837 t = *++ptr;
2838 /* given 'a##b', remove nosubsts preceding 'b' */
2839 while (t == TOK_NOSUBST)
2840 t = *++ptr;
2842 if (t && t != TOK_TWOSHARPS) {
2843 TOK_GET(&t, &ptr, &cval);
2845 /* We concatenate the two tokens */
2846 cstr_new(&cstr);
2847 cstr_cat(&cstr, get_tok_str(tok, &tokc));
2848 n = cstr.size;
2849 cstr_cat(&cstr, get_tok_str(t, &cval));
2850 cstr_ccat(&cstr, '\0');
2852 tcc_open_bf(tcc_state, "<paste>", cstr.size);
2853 memcpy(file->buffer, cstr.data, cstr.size);
2854 for (;;) {
2855 next_nomacro1();
2856 if (0 == *file->buf_ptr)
2857 break;
2858 tok_str_add2(&macro_str1, tok, &tokc);
2859 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2860 n, cstr.data, (char*)cstr.data + n);
2862 tcc_close();
2863 cstr_reset(&cstr);
2866 if (tok != TOK_NOSUBST)
2867 start_of_nosubsts = -1;
2868 tok_str_add2(&macro_str1, tok, &tokc);
2870 tok_str_add(&macro_str1, 0);
2871 return macro_str1.str;
2875 /* do macro substitution of macro_str and add result to
2876 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2877 inside to avoid recursing. */
2878 static void macro_subst(TokenString *tok_str, Sym **nested_list,
2879 const int *macro_str, struct macro_level ** can_read_stream)
2881 Sym *s;
2882 int *macro_str1;
2883 const int *ptr;
2884 int t, ret, spc;
2885 CValue cval;
2886 struct macro_level ml;
2887 int force_blank;
2889 /* first scan for '##' operator handling */
2890 ptr = macro_str;
2891 macro_str1 = macro_twosharps(ptr);
2893 if (macro_str1)
2894 ptr = macro_str1;
2895 spc = 0;
2896 force_blank = 0;
2898 while (1) {
2899 /* NOTE: ptr == NULL can only happen if tokens are read from
2900 file stream due to a macro function call */
2901 if (ptr == NULL)
2902 break;
2903 TOK_GET(&t, &ptr, &cval);
2904 if (t == 0)
2905 break;
2906 if (t == TOK_NOSUBST) {
2907 /* following token has already been subst'd. just copy it on */
2908 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
2909 TOK_GET(&t, &ptr, &cval);
2910 goto no_subst;
2912 s = define_find(t);
2913 if (s != NULL) {
2914 /* if nested substitution, do nothing */
2915 if (sym_find2(*nested_list, t)) {
2916 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
2917 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
2918 goto no_subst;
2920 ml.p = macro_ptr;
2921 if (can_read_stream)
2922 ml.prev = *can_read_stream, *can_read_stream = &ml;
2923 macro_ptr = (int *)ptr;
2924 tok = t;
2925 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
2926 ptr = (int *)macro_ptr;
2927 macro_ptr = ml.p;
2928 if (can_read_stream && *can_read_stream == &ml)
2929 *can_read_stream = ml.prev;
2930 if (ret != 0)
2931 goto no_subst;
2932 if (parse_flags & PARSE_FLAG_SPACES)
2933 force_blank = 1;
2934 } else {
2935 no_subst:
2936 if (force_blank) {
2937 tok_str_add(tok_str, ' ');
2938 spc = 1;
2939 force_blank = 0;
2941 if (!check_space(t, &spc))
2942 tok_str_add2(tok_str, t, &cval);
2945 if (macro_str1)
2946 tok_str_free(macro_str1);
2949 /* return next token with macro substitution */
2950 ST_FUNC void next(void)
2952 Sym *nested_list, *s;
2953 TokenString str;
2954 struct macro_level *ml;
2956 redo:
2957 if (parse_flags & PARSE_FLAG_SPACES)
2958 next_nomacro_spc();
2959 else
2960 next_nomacro();
2961 if (!macro_ptr) {
2962 /* if not reading from macro substituted string, then try
2963 to substitute macros */
2964 if (tok >= TOK_IDENT &&
2965 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2966 s = define_find(tok);
2967 if (s) {
2968 /* we have a macro: we try to substitute */
2969 tok_str_new(&str);
2970 nested_list = NULL;
2971 ml = NULL;
2972 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
2973 /* substitution done, NOTE: maybe empty */
2974 tok_str_add(&str, 0);
2975 macro_ptr = str.str;
2976 macro_ptr_allocated = str.str;
2977 goto redo;
2981 } else {
2982 if (tok == 0) {
2983 /* end of macro or end of unget buffer */
2984 if (unget_buffer_enabled) {
2985 macro_ptr = unget_saved_macro_ptr;
2986 unget_buffer_enabled = 0;
2987 } else {
2988 /* end of macro string: free it */
2989 tok_str_free(macro_ptr_allocated);
2990 macro_ptr_allocated = NULL;
2991 macro_ptr = NULL;
2993 goto redo;
2994 } else if (tok == TOK_NOSUBST) {
2995 /* discard preprocessor's nosubst markers */
2996 goto redo;
3000 /* convert preprocessor tokens into C tokens */
3001 if (tok == TOK_PPNUM &&
3002 (parse_flags & PARSE_FLAG_TOK_NUM)) {
3003 parse_number((char *)tokc.cstr->data);
3007 /* push back current token and set current token to 'last_tok'. Only
3008 identifier case handled for labels. */
3009 ST_INLN void unget_tok(int last_tok)
3011 int i, n;
3012 int *q;
3013 if (unget_buffer_enabled)
3015 /* assert(macro_ptr == unget_saved_buffer + 1);
3016 assert(*macro_ptr == 0); */
3018 else
3020 unget_saved_macro_ptr = macro_ptr;
3021 unget_buffer_enabled = 1;
3023 q = unget_saved_buffer;
3024 macro_ptr = q;
3025 *q++ = tok;
3026 n = tok_ext_size(tok) - 1;
3027 for(i=0;i<n;i++)
3028 *q++ = tokc.tab[i];
3029 *q = 0; /* end of token string */
3030 tok = last_tok;
3034 /* better than nothing, but needs extension to handle '-E' option
3035 correctly too */
3036 ST_FUNC void preprocess_init(TCCState *s1)
3038 s1->include_stack_ptr = s1->include_stack;
3039 /* XXX: move that before to avoid having to initialize
3040 file->ifdef_stack_ptr ? */
3041 s1->ifdef_stack_ptr = s1->ifdef_stack;
3042 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3044 /* XXX: not ANSI compliant: bound checking says error */
3045 vtop = vstack - 1;
3046 s1->pack_stack[0] = 0;
3047 s1->pack_stack_ptr = s1->pack_stack;
3050 ST_FUNC void preprocess_new()
3052 int i, c;
3053 const char *p, *r;
3055 /* init isid table */
3056 for(i=CH_EOF;i<256;i++)
3057 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
3059 /* add all tokens */
3060 table_ident = NULL;
3061 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3063 tok_ident = TOK_IDENT;
3064 p = tcc_keywords;
3065 while (*p) {
3066 r = p;
3067 for(;;) {
3068 c = *r++;
3069 if (c == '\0')
3070 break;
3072 tok_alloc(p, r - p - 1);
3073 p = r;
3077 /* Preprocess the current file */
3078 ST_FUNC int tcc_preprocess(TCCState *s1)
3080 Sym *define_start;
3082 BufferedFile *file_ref, **iptr, **iptr_new;
3083 int token_seen, line_ref, d;
3084 const char *s;
3086 preprocess_init(s1);
3087 define_start = define_stack;
3088 ch = file->buf_ptr[0];
3089 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3090 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
3091 PARSE_FLAG_LINEFEED | PARSE_FLAG_SPACES;
3092 token_seen = 0;
3093 line_ref = 0;
3094 file_ref = NULL;
3095 iptr = s1->include_stack_ptr;
3097 for (;;) {
3098 next();
3099 if (tok == TOK_EOF) {
3100 break;
3101 } else if (file != file_ref) {
3102 goto print_line;
3103 } else if (tok == TOK_LINEFEED) {
3104 if (!token_seen)
3105 continue;
3106 ++line_ref;
3107 token_seen = 0;
3108 } else if (!token_seen) {
3109 d = file->line_num - line_ref;
3110 if (file != file_ref || d < 0 || d >= 8) {
3111 print_line:
3112 iptr_new = s1->include_stack_ptr;
3113 s = iptr_new > iptr ? " 1"
3114 : iptr_new < iptr ? " 2"
3115 : iptr_new > s1->include_stack ? " 3"
3116 : ""
3118 iptr = iptr_new;
3119 fprintf(s1->outfile, "# %d \"%s\"%s\n", file->line_num, file->filename, s);
3120 } else {
3121 while (d)
3122 fputs("\n", s1->outfile), --d;
3124 line_ref = (file_ref = file)->line_num;
3125 token_seen = tok != TOK_LINEFEED;
3126 if (!token_seen)
3127 continue;
3129 fputs(get_tok_str(tok, &tokc), s1->outfile);
3131 free_defines(define_start);
3132 return 0;