Replace comment by a blank
[tinycc.git] / tccpp.c
blob3afee3ff90623db74dda71361f3be6c5622fb80d
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 error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
94 next();
97 /* ------------------------------------------------------------------------- */
98 /* CString handling */
99 static void cstr_realloc(CString *cstr, int new_size)
101 int size;
102 void *data;
104 size = cstr->size_allocated;
105 if (size == 0)
106 size = 8; /* no need to allocate a too small first string */
107 while (size < new_size)
108 size = size * 2;
109 data = tcc_realloc(cstr->data_allocated, size);
110 if (!data)
111 error("memory full");
112 cstr->data_allocated = data;
113 cstr->size_allocated = size;
114 cstr->data = data;
117 /* add a byte */
118 ST_INLN void cstr_ccat(CString *cstr, int ch)
120 int size;
121 size = cstr->size + 1;
122 if (size > cstr->size_allocated)
123 cstr_realloc(cstr, size);
124 ((unsigned char *)cstr->data)[size - 1] = ch;
125 cstr->size = size;
128 ST_FUNC void cstr_cat(CString *cstr, const char *str)
130 int c;
131 for(;;) {
132 c = *str;
133 if (c == '\0')
134 break;
135 cstr_ccat(cstr, c);
136 str++;
140 /* add a wide char */
141 ST_FUNC void cstr_wccat(CString *cstr, int ch)
143 int size;
144 size = cstr->size + sizeof(nwchar_t);
145 if (size > cstr->size_allocated)
146 cstr_realloc(cstr, size);
147 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
148 cstr->size = size;
151 ST_FUNC void cstr_new(CString *cstr)
153 memset(cstr, 0, sizeof(CString));
156 /* free string and reset it to NULL */
157 ST_FUNC void cstr_free(CString *cstr)
159 tcc_free(cstr->data_allocated);
160 cstr_new(cstr);
163 /* XXX: unicode ? */
164 ST_FUNC void add_char(CString *cstr, int c)
166 if (c == '\'' || c == '\"' || c == '\\') {
167 /* XXX: could be more precise if char or string */
168 cstr_ccat(cstr, '\\');
170 if (c >= 32 && c <= 126) {
171 cstr_ccat(cstr, c);
172 } else {
173 cstr_ccat(cstr, '\\');
174 if (c == '\n') {
175 cstr_ccat(cstr, 'n');
176 } else {
177 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
178 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
179 cstr_ccat(cstr, '0' + (c & 7));
184 /* ------------------------------------------------------------------------- */
185 /* allocate a new token */
186 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
188 TokenSym *ts, **ptable;
189 int i;
191 if (tok_ident >= SYM_FIRST_ANOM)
192 error("memory full");
194 /* expand token table if needed */
195 i = tok_ident - TOK_IDENT;
196 if ((i % TOK_ALLOC_INCR) == 0) {
197 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
198 if (!ptable)
199 error("memory full");
200 table_ident = ptable;
203 ts = tcc_malloc(sizeof(TokenSym) + len);
204 table_ident[i] = ts;
205 ts->tok = tok_ident++;
206 ts->sym_define = NULL;
207 ts->sym_label = NULL;
208 ts->sym_struct = NULL;
209 ts->sym_identifier = NULL;
210 ts->len = len;
211 ts->hash_next = NULL;
212 memcpy(ts->str, str, len);
213 ts->str[len] = '\0';
214 *pts = ts;
215 return ts;
218 #define TOK_HASH_INIT 1
219 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
221 /* find a token and add it if not found */
222 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
224 TokenSym *ts, **pts;
225 int i;
226 unsigned int h;
228 h = TOK_HASH_INIT;
229 for(i=0;i<len;i++)
230 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
231 h &= (TOK_HASH_SIZE - 1);
233 pts = &hash_ident[h];
234 for(;;) {
235 ts = *pts;
236 if (!ts)
237 break;
238 if (ts->len == len && !memcmp(ts->str, str, len))
239 return ts;
240 pts = &(ts->hash_next);
242 return tok_alloc_new(pts, str, len);
245 /* XXX: buffer overflow */
246 /* XXX: float tokens */
247 ST_FUNC char *get_tok_str(int v, CValue *cv)
249 static char buf[STRING_MAX_SIZE + 1];
250 static CString cstr_buf;
251 CString *cstr;
252 char *p;
253 int i, len;
255 /* NOTE: to go faster, we give a fixed buffer for small strings */
256 cstr_reset(&cstr_buf);
257 cstr_buf.data = buf;
258 cstr_buf.size_allocated = sizeof(buf);
259 p = buf;
261 switch(v) {
262 case TOK_CINT:
263 case TOK_CUINT:
264 /* XXX: not quite exact, but only useful for testing */
265 sprintf(p, "%u", cv->ui);
266 break;
267 case TOK_CLLONG:
268 case TOK_CULLONG:
269 /* XXX: not quite exact, but only useful for testing */
270 #ifdef _WIN32
271 sprintf(p, "%u", (unsigned)cv->ull);
272 #else
273 sprintf(p, "%Lu", cv->ull);
274 #endif
275 break;
276 case TOK_LCHAR:
277 cstr_ccat(&cstr_buf, 'L');
278 case TOK_CCHAR:
279 cstr_ccat(&cstr_buf, '\'');
280 add_char(&cstr_buf, cv->i);
281 cstr_ccat(&cstr_buf, '\'');
282 cstr_ccat(&cstr_buf, '\0');
283 break;
284 case TOK_PPNUM:
285 cstr = cv->cstr;
286 len = cstr->size - 1;
287 for(i=0;i<len;i++)
288 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
289 cstr_ccat(&cstr_buf, '\0');
290 break;
291 case TOK_LSTR:
292 cstr_ccat(&cstr_buf, 'L');
293 case TOK_STR:
294 cstr = cv->cstr;
295 cstr_ccat(&cstr_buf, '\"');
296 if (v == TOK_STR) {
297 len = cstr->size - 1;
298 for(i=0;i<len;i++)
299 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
300 } else {
301 len = (cstr->size / sizeof(nwchar_t)) - 1;
302 for(i=0;i<len;i++)
303 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
305 cstr_ccat(&cstr_buf, '\"');
306 cstr_ccat(&cstr_buf, '\0');
307 break;
308 case TOK_LT:
309 v = '<';
310 goto addv;
311 case TOK_GT:
312 v = '>';
313 goto addv;
314 case TOK_DOTS:
315 return strcpy(p, "...");
316 case TOK_A_SHL:
317 return strcpy(p, "<<=");
318 case TOK_A_SAR:
319 return strcpy(p, ">>=");
320 default:
321 if (v < TOK_IDENT) {
322 /* search in two bytes table */
323 const unsigned char *q = tok_two_chars;
324 while (*q) {
325 if (q[2] == v) {
326 *p++ = q[0];
327 *p++ = q[1];
328 *p = '\0';
329 return buf;
331 q += 3;
333 addv:
334 *p++ = v;
335 *p = '\0';
336 } else if (v < tok_ident) {
337 return table_ident[v - TOK_IDENT]->str;
338 } else if (v >= SYM_FIRST_ANOM) {
339 /* special name for anonymous symbol */
340 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
341 } else {
342 /* should never happen */
343 return NULL;
345 break;
347 return cstr_buf.data;
350 /* fill input buffer and peek next char */
351 static int tcc_peekc_slow(BufferedFile *bf)
353 int len;
354 /* only tries to read if really end of buffer */
355 if (bf->buf_ptr >= bf->buf_end) {
356 if (bf->fd != -1) {
357 #if defined(PARSE_DEBUG)
358 len = 8;
359 #else
360 len = IO_BUF_SIZE;
361 #endif
362 len = read(bf->fd, bf->buffer, len);
363 if (len < 0)
364 len = 0;
365 } else {
366 len = 0;
368 total_bytes += len;
369 bf->buf_ptr = bf->buffer;
370 bf->buf_end = bf->buffer + len;
371 *bf->buf_end = CH_EOB;
373 if (bf->buf_ptr < bf->buf_end) {
374 return bf->buf_ptr[0];
375 } else {
376 bf->buf_ptr = bf->buf_end;
377 return CH_EOF;
381 /* return the current character, handling end of block if necessary
382 (but not stray) */
383 ST_FUNC int handle_eob(void)
385 return tcc_peekc_slow(file);
388 /* read next char from current input file and handle end of input buffer */
389 ST_INLN void inp(void)
391 ch = *(++(file->buf_ptr));
392 /* end of buffer/file handling */
393 if (ch == CH_EOB)
394 ch = handle_eob();
397 /* handle '\[\r]\n' */
398 static int handle_stray_noerror(void)
400 while (ch == '\\') {
401 inp();
402 if (ch == '\n') {
403 file->line_num++;
404 inp();
405 } else if (ch == '\r') {
406 inp();
407 if (ch != '\n')
408 goto fail;
409 file->line_num++;
410 inp();
411 } else {
412 fail:
413 return 1;
416 return 0;
419 static void handle_stray(void)
421 if (handle_stray_noerror())
422 error("stray '\\' in program");
425 /* skip the stray and handle the \\n case. Output an error if
426 incorrect char after the stray */
427 static int handle_stray1(uint8_t *p)
429 int c;
431 if (p >= file->buf_end) {
432 file->buf_ptr = p;
433 c = handle_eob();
434 p = file->buf_ptr;
435 if (c == '\\')
436 goto parse_stray;
437 } else {
438 parse_stray:
439 file->buf_ptr = p;
440 ch = *p;
441 handle_stray();
442 p = file->buf_ptr;
443 c = *p;
445 return c;
448 /* handle just the EOB case, but not stray */
449 #define PEEKC_EOB(c, p)\
451 p++;\
452 c = *p;\
453 if (c == '\\') {\
454 file->buf_ptr = p;\
455 c = handle_eob();\
456 p = file->buf_ptr;\
460 /* handle the complicated stray case */
461 #define PEEKC(c, p)\
463 p++;\
464 c = *p;\
465 if (c == '\\') {\
466 c = handle_stray1(p);\
467 p = file->buf_ptr;\
471 /* input with '\[\r]\n' handling. Note that this function cannot
472 handle other characters after '\', so you cannot call it inside
473 strings or comments */
474 ST_FUNC void minp(void)
476 inp();
477 if (ch == '\\')
478 handle_stray();
482 /* single line C++ comments */
483 static uint8_t *parse_line_comment(uint8_t *p)
485 int c;
487 p++;
488 for(;;) {
489 c = *p;
490 redo:
491 if (c == '\n' || c == CH_EOF) {
492 break;
493 } else if (c == '\\') {
494 file->buf_ptr = p;
495 c = handle_eob();
496 p = file->buf_ptr;
497 if (c == '\\') {
498 PEEKC_EOB(c, p);
499 if (c == '\n') {
500 file->line_num++;
501 PEEKC_EOB(c, p);
502 } else if (c == '\r') {
503 PEEKC_EOB(c, p);
504 if (c == '\n') {
505 file->line_num++;
506 PEEKC_EOB(c, p);
509 } else {
510 goto redo;
512 } else {
513 p++;
516 return p;
519 /* C comments */
520 ST_FUNC uint8_t *parse_comment(uint8_t *p)
522 int c;
524 p++;
525 for(;;) {
526 /* fast skip loop */
527 for(;;) {
528 c = *p;
529 if (c == '\n' || c == '*' || c == '\\')
530 break;
531 p++;
532 c = *p;
533 if (c == '\n' || c == '*' || c == '\\')
534 break;
535 p++;
537 /* now we can handle all the cases */
538 if (c == '\n') {
539 file->line_num++;
540 p++;
541 } else if (c == '*') {
542 p++;
543 for(;;) {
544 c = *p;
545 if (c == '*') {
546 p++;
547 } else if (c == '/') {
548 goto end_of_comment;
549 } else if (c == '\\') {
550 file->buf_ptr = p;
551 c = handle_eob();
552 p = file->buf_ptr;
553 if (c == '\\') {
554 /* skip '\[\r]\n', otherwise just skip the stray */
555 while (c == '\\') {
556 PEEKC_EOB(c, p);
557 if (c == '\n') {
558 file->line_num++;
559 PEEKC_EOB(c, p);
560 } else if (c == '\r') {
561 PEEKC_EOB(c, p);
562 if (c == '\n') {
563 file->line_num++;
564 PEEKC_EOB(c, p);
566 } else {
567 goto after_star;
571 } else {
572 break;
575 after_star: ;
576 } else {
577 /* stray, eob or eof */
578 file->buf_ptr = p;
579 c = handle_eob();
580 p = file->buf_ptr;
581 if (c == CH_EOF) {
582 error("unexpected end of file in comment");
583 } else if (c == '\\') {
584 p++;
588 end_of_comment:
589 p++;
590 return p;
593 #define cinp minp
595 static inline void skip_spaces(void)
597 while (is_space(ch))
598 cinp();
601 static inline int check_space(int t, int *spc)
603 if (is_space(t)) {
604 if (*spc)
605 return 1;
606 *spc = 1;
607 } else
608 *spc = 0;
609 return 0;
612 /* parse a string without interpreting escapes */
613 static uint8_t *parse_pp_string(uint8_t *p,
614 int sep, CString *str)
616 int c;
617 p++;
618 for(;;) {
619 c = *p;
620 if (c == sep) {
621 break;
622 } else if (c == '\\') {
623 file->buf_ptr = p;
624 c = handle_eob();
625 p = file->buf_ptr;
626 if (c == CH_EOF) {
627 unterminated_string:
628 /* XXX: indicate line number of start of string */
629 error("missing terminating %c character", sep);
630 } else if (c == '\\') {
631 /* escape : just skip \[\r]\n */
632 PEEKC_EOB(c, p);
633 if (c == '\n') {
634 file->line_num++;
635 p++;
636 } else if (c == '\r') {
637 PEEKC_EOB(c, p);
638 if (c != '\n')
639 expect("'\n' after '\r'");
640 file->line_num++;
641 p++;
642 } else if (c == CH_EOF) {
643 goto unterminated_string;
644 } else {
645 if (str) {
646 cstr_ccat(str, '\\');
647 cstr_ccat(str, c);
649 p++;
652 } else if (c == '\n') {
653 file->line_num++;
654 goto add_char;
655 } else if (c == '\r') {
656 PEEKC_EOB(c, p);
657 if (c != '\n') {
658 if (str)
659 cstr_ccat(str, '\r');
660 } else {
661 file->line_num++;
662 goto add_char;
664 } else {
665 add_char:
666 if (str)
667 cstr_ccat(str, c);
668 p++;
671 p++;
672 return p;
675 /* skip block of text until #else, #elif or #endif. skip also pairs of
676 #if/#endif */
677 static void preprocess_skip(void)
679 int a, start_of_line, c, in_warn_or_error;
680 uint8_t *p;
682 p = file->buf_ptr;
683 a = 0;
684 redo_start:
685 start_of_line = 1;
686 in_warn_or_error = 0;
687 for(;;) {
688 redo_no_start:
689 c = *p;
690 switch(c) {
691 case ' ':
692 case '\t':
693 case '\f':
694 case '\v':
695 case '\r':
696 p++;
697 goto redo_no_start;
698 case '\n':
699 file->line_num++;
700 p++;
701 goto redo_start;
702 case '\\':
703 file->buf_ptr = p;
704 c = handle_eob();
705 if (c == CH_EOF) {
706 expect("#endif");
707 } else if (c == '\\') {
708 ch = file->buf_ptr[0];
709 handle_stray_noerror();
711 p = file->buf_ptr;
712 goto redo_no_start;
713 /* skip strings */
714 case '\"':
715 case '\'':
716 if (in_warn_or_error)
717 goto _default;
718 p = parse_pp_string(p, c, NULL);
719 break;
720 /* skip comments */
721 case '/':
722 if (in_warn_or_error)
723 goto _default;
724 file->buf_ptr = p;
725 ch = *p;
726 minp();
727 p = file->buf_ptr;
728 if (ch == '*') {
729 p = parse_comment(p);
730 } else if (ch == '/') {
731 p = parse_line_comment(p);
733 break;
734 case '#':
735 p++;
736 if (start_of_line) {
737 file->buf_ptr = p;
738 next_nomacro();
739 p = file->buf_ptr;
740 if (a == 0 &&
741 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
742 goto the_end;
743 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
744 a++;
745 else if (tok == TOK_ENDIF)
746 a--;
747 else if( tok == TOK_ERROR || tok == TOK_WARNING)
748 in_warn_or_error = 1;
750 break;
751 _default:
752 default:
753 p++;
754 break;
756 start_of_line = 0;
758 the_end: ;
759 file->buf_ptr = p;
762 /* ParseState handling */
764 /* XXX: currently, no include file info is stored. Thus, we cannot display
765 accurate messages if the function or data definition spans multiple
766 files */
768 /* save current parse state in 's' */
769 ST_FUNC void save_parse_state(ParseState *s)
771 s->line_num = file->line_num;
772 s->macro_ptr = macro_ptr;
773 s->tok = tok;
774 s->tokc = tokc;
777 /* restore parse state from 's' */
778 ST_FUNC void restore_parse_state(ParseState *s)
780 file->line_num = s->line_num;
781 macro_ptr = s->macro_ptr;
782 tok = s->tok;
783 tokc = s->tokc;
786 /* return the number of additional 'ints' necessary to store the
787 token */
788 static inline int tok_ext_size(int t)
790 switch(t) {
791 /* 4 bytes */
792 case TOK_CINT:
793 case TOK_CUINT:
794 case TOK_CCHAR:
795 case TOK_LCHAR:
796 case TOK_CFLOAT:
797 case TOK_LINENUM:
798 return 1;
799 case TOK_STR:
800 case TOK_LSTR:
801 case TOK_PPNUM:
802 error("unsupported token");
803 return 1;
804 case TOK_CDOUBLE:
805 case TOK_CLLONG:
806 case TOK_CULLONG:
807 return 2;
808 case TOK_CLDOUBLE:
809 return LDOUBLE_SIZE / 4;
810 default:
811 return 0;
815 /* token string handling */
817 ST_INLN void tok_str_new(TokenString *s)
819 s->str = NULL;
820 s->len = 0;
821 s->allocated_len = 0;
822 s->last_line_num = -1;
825 ST_FUNC void tok_str_free(int *str)
827 tcc_free(str);
830 static int *tok_str_realloc(TokenString *s)
832 int *str, len;
834 if (s->allocated_len == 0) {
835 len = 8;
836 } else {
837 len = s->allocated_len * 2;
839 str = tcc_realloc(s->str, len * sizeof(int));
840 if (!str)
841 error("memory full");
842 s->allocated_len = len;
843 s->str = str;
844 return str;
847 ST_FUNC void tok_str_add(TokenString *s, int t)
849 int len, *str;
851 len = s->len;
852 str = s->str;
853 if (len >= s->allocated_len)
854 str = tok_str_realloc(s);
855 str[len++] = t;
856 s->len = len;
859 static void tok_str_add2(TokenString *s, int t, CValue *cv)
861 int len, *str;
863 len = s->len;
864 str = s->str;
866 /* allocate space for worst case */
867 if (len + TOK_MAX_SIZE > s->allocated_len)
868 str = tok_str_realloc(s);
869 str[len++] = t;
870 switch(t) {
871 case TOK_CINT:
872 case TOK_CUINT:
873 case TOK_CCHAR:
874 case TOK_LCHAR:
875 case TOK_CFLOAT:
876 case TOK_LINENUM:
877 str[len++] = cv->tab[0];
878 break;
879 case TOK_PPNUM:
880 case TOK_STR:
881 case TOK_LSTR:
883 int nb_words;
884 CString *cstr;
886 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
887 while ((len + nb_words) > s->allocated_len)
888 str = tok_str_realloc(s);
889 cstr = (CString *)(str + len);
890 cstr->data = NULL;
891 cstr->size = cv->cstr->size;
892 cstr->data_allocated = NULL;
893 cstr->size_allocated = cstr->size;
894 memcpy((char *)cstr + sizeof(CString),
895 cv->cstr->data, cstr->size);
896 len += nb_words;
898 break;
899 case TOK_CDOUBLE:
900 case TOK_CLLONG:
901 case TOK_CULLONG:
902 #if LDOUBLE_SIZE == 8
903 case TOK_CLDOUBLE:
904 #endif
905 str[len++] = cv->tab[0];
906 str[len++] = cv->tab[1];
907 break;
908 #if LDOUBLE_SIZE == 12
909 case TOK_CLDOUBLE:
910 str[len++] = cv->tab[0];
911 str[len++] = cv->tab[1];
912 str[len++] = cv->tab[2];
913 #elif LDOUBLE_SIZE == 16
914 case TOK_CLDOUBLE:
915 str[len++] = cv->tab[0];
916 str[len++] = cv->tab[1];
917 str[len++] = cv->tab[2];
918 str[len++] = cv->tab[3];
919 #elif LDOUBLE_SIZE != 8
920 #error add long double size support
921 #endif
922 break;
923 default:
924 break;
926 s->len = len;
929 /* add the current parse token in token string 's' */
930 ST_FUNC void tok_str_add_tok(TokenString *s)
932 CValue cval;
934 /* save line number info */
935 if (file->line_num != s->last_line_num) {
936 s->last_line_num = file->line_num;
937 cval.i = s->last_line_num;
938 tok_str_add2(s, TOK_LINENUM, &cval);
940 tok_str_add2(s, tok, &tokc);
943 /* get a token from an integer array and increment pointer
944 accordingly. we code it as a macro to avoid pointer aliasing. */
945 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
947 const int *p = *pp;
948 int n, *tab;
950 tab = cv->tab;
951 switch(*t = *p++) {
952 case TOK_CINT:
953 case TOK_CUINT:
954 case TOK_CCHAR:
955 case TOK_LCHAR:
956 case TOK_CFLOAT:
957 case TOK_LINENUM:
958 tab[0] = *p++;
959 break;
960 case TOK_STR:
961 case TOK_LSTR:
962 case TOK_PPNUM:
963 cv->cstr = (CString *)p;
964 cv->cstr->data = (char *)p + sizeof(CString);
965 p += (sizeof(CString) + cv->cstr->size + 3) >> 2;
966 break;
967 case TOK_CDOUBLE:
968 case TOK_CLLONG:
969 case TOK_CULLONG:
970 n = 2;
971 goto copy;
972 case TOK_CLDOUBLE:
973 #if LDOUBLE_SIZE == 16
974 n = 4;
975 #elif LDOUBLE_SIZE == 12
976 n = 3;
977 #elif LDOUBLE_SIZE == 8
978 n = 2;
979 #else
980 # error add long double size support
981 #endif
982 copy:
984 *tab++ = *p++;
985 while (--n);
986 break;
987 default:
988 break;
990 *pp = p;
993 static int macro_is_equal(const int *a, const int *b)
995 char buf[STRING_MAX_SIZE + 1];
996 CValue cv;
997 int t;
998 while (*a && *b) {
999 TOK_GET(&t, &a, &cv);
1000 pstrcpy(buf, sizeof buf, get_tok_str(t, &cv));
1001 TOK_GET(&t, &b, &cv);
1002 if (strcmp(buf, get_tok_str(t, &cv)))
1003 return 0;
1005 return !(*a || *b);
1008 /* defines handling */
1009 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1011 Sym *s;
1013 s = define_find(v);
1014 if (s && !macro_is_equal(s->d, str))
1015 warning("%s redefined", get_tok_str(v, NULL));
1017 s = sym_push2(&define_stack, v, macro_type, 0);
1018 s->d = str;
1019 s->next = first_arg;
1020 table_ident[v - TOK_IDENT]->sym_define = s;
1023 /* undefined a define symbol. Its name is just set to zero */
1024 ST_FUNC void define_undef(Sym *s)
1026 int v;
1027 v = s->v;
1028 if (v >= TOK_IDENT && v < tok_ident)
1029 table_ident[v - TOK_IDENT]->sym_define = NULL;
1030 s->v = 0;
1033 ST_INLN Sym *define_find(int v)
1035 v -= TOK_IDENT;
1036 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1037 return NULL;
1038 return table_ident[v]->sym_define;
1041 /* free define stack until top reaches 'b' */
1042 ST_FUNC void free_defines(Sym *b)
1044 Sym *top, *top1;
1045 int v;
1047 top = define_stack;
1048 while (top != b) {
1049 top1 = top->prev;
1050 /* do not free args or predefined defines */
1051 if (top->d)
1052 tok_str_free(top->d);
1053 v = top->v;
1054 if (v >= TOK_IDENT && v < tok_ident)
1055 table_ident[v - TOK_IDENT]->sym_define = NULL;
1056 sym_free(top);
1057 top = top1;
1059 define_stack = b;
1062 /* label lookup */
1063 ST_FUNC Sym *label_find(int v)
1065 v -= TOK_IDENT;
1066 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1067 return NULL;
1068 return table_ident[v]->sym_label;
1071 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1073 Sym *s, **ps;
1074 s = sym_push2(ptop, v, 0, 0);
1075 s->r = flags;
1076 ps = &table_ident[v - TOK_IDENT]->sym_label;
1077 if (ptop == &global_label_stack) {
1078 /* modify the top most local identifier, so that
1079 sym_identifier will point to 's' when popped */
1080 while (*ps != NULL)
1081 ps = &(*ps)->prev_tok;
1083 s->prev_tok = *ps;
1084 *ps = s;
1085 return s;
1088 /* pop labels until element last is reached. Look if any labels are
1089 undefined. Define symbols if '&&label' was used. */
1090 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1092 Sym *s, *s1;
1093 for(s = *ptop; s != slast; s = s1) {
1094 s1 = s->prev;
1095 if (s->r == LABEL_DECLARED) {
1096 warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1097 } else if (s->r == LABEL_FORWARD) {
1098 error("label '%s' used but not defined",
1099 get_tok_str(s->v, NULL));
1100 } else {
1101 if (s->c) {
1102 /* define corresponding symbol. A size of
1103 1 is put. */
1104 put_extern_sym(s, cur_text_section, s->jnext, 1);
1107 /* remove label */
1108 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1109 sym_free(s);
1111 *ptop = slast;
1114 /* eval an expression for #if/#elif */
1115 static int expr_preprocess(void)
1117 int c, t;
1118 TokenString str;
1120 tok_str_new(&str);
1121 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1122 next(); /* do macro subst */
1123 if (tok == TOK_DEFINED) {
1124 next_nomacro();
1125 t = tok;
1126 if (t == '(')
1127 next_nomacro();
1128 c = define_find(tok) != 0;
1129 if (t == '(')
1130 next_nomacro();
1131 tok = TOK_CINT;
1132 tokc.i = c;
1133 } else if (tok >= TOK_IDENT) {
1134 /* if undefined macro */
1135 tok = TOK_CINT;
1136 tokc.i = 0;
1138 tok_str_add_tok(&str);
1140 tok_str_add(&str, -1); /* simulate end of file */
1141 tok_str_add(&str, 0);
1142 /* now evaluate C constant expression */
1143 macro_ptr = str.str;
1144 next();
1145 c = expr_const();
1146 macro_ptr = NULL;
1147 tok_str_free(str.str);
1148 return c != 0;
1151 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1152 static void tok_print(int *str)
1154 int t;
1155 CValue cval;
1157 printf("<");
1158 while (1) {
1159 TOK_GET(&t, &str, &cval);
1160 if (!t)
1161 break;
1162 printf("%s", get_tok_str(t, &cval));
1164 printf(">\n");
1166 #endif
1168 /* parse after #define */
1169 ST_FUNC void parse_define(void)
1171 Sym *s, *first, **ps;
1172 int v, t, varg, is_vaargs, spc;
1173 TokenString str;
1175 v = tok;
1176 if (v < TOK_IDENT)
1177 error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1178 /* XXX: should check if same macro (ANSI) */
1179 first = NULL;
1180 t = MACRO_OBJ;
1181 /* '(' must be just after macro definition for MACRO_FUNC */
1182 next_nomacro_spc();
1183 if (tok == '(') {
1184 next_nomacro();
1185 ps = &first;
1186 while (tok != ')') {
1187 varg = tok;
1188 next_nomacro();
1189 is_vaargs = 0;
1190 if (varg == TOK_DOTS) {
1191 varg = TOK___VA_ARGS__;
1192 is_vaargs = 1;
1193 } else if (tok == TOK_DOTS && gnu_ext) {
1194 is_vaargs = 1;
1195 next_nomacro();
1197 if (varg < TOK_IDENT)
1198 error("badly punctuated parameter list");
1199 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1200 *ps = s;
1201 ps = &s->next;
1202 if (tok != ',')
1203 break;
1204 next_nomacro();
1206 if (tok == ')')
1207 next_nomacro_spc();
1208 t = MACRO_FUNC;
1210 tok_str_new(&str);
1211 spc = 2;
1212 /* EOF testing necessary for '-D' handling */
1213 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1214 /* remove spaces around ## and after '#' */
1215 if (TOK_TWOSHARPS == tok) {
1216 if (1 == spc)
1217 --str.len;
1218 spc = 2;
1219 } else if ('#' == tok) {
1220 spc = 2;
1221 } else if (check_space(tok, &spc)) {
1222 goto skip;
1224 tok_str_add2(&str, tok, &tokc);
1225 skip:
1226 next_nomacro_spc();
1228 if (spc == 1)
1229 --str.len; /* remove trailing space */
1230 tok_str_add(&str, 0);
1231 #ifdef PP_DEBUG
1232 printf("define %s %d: ", get_tok_str(v, NULL), t);
1233 tok_print(str.str);
1234 #endif
1235 define_push(v, t, str.str, first);
1238 static inline int hash_cached_include(int type, const char *filename)
1240 const unsigned char *s;
1241 unsigned int h;
1243 h = TOK_HASH_INIT;
1244 h = TOK_HASH_FUNC(h, type);
1245 s = filename;
1246 while (*s) {
1247 h = TOK_HASH_FUNC(h, *s);
1248 s++;
1250 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1251 return h;
1254 /* XXX: use a token or a hash table to accelerate matching ? */
1255 static CachedInclude *search_cached_include(TCCState *s1,
1256 int type, const char *filename)
1258 CachedInclude *e;
1259 int i, h;
1260 h = hash_cached_include(type, filename);
1261 i = s1->cached_includes_hash[h];
1262 for(;;) {
1263 if (i == 0)
1264 break;
1265 e = s1->cached_includes[i - 1];
1266 if (e->type == type && !PATHCMP(e->filename, filename))
1267 return e;
1268 i = e->hash_next;
1270 return NULL;
1273 static inline void add_cached_include(TCCState *s1, int type,
1274 const char *filename, int ifndef_macro)
1276 CachedInclude *e;
1277 int h;
1279 if (search_cached_include(s1, type, filename))
1280 return;
1281 #ifdef INC_DEBUG
1282 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
1283 #endif
1284 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1285 if (!e)
1286 return;
1287 e->type = type;
1288 strcpy(e->filename, filename);
1289 e->ifndef_macro = ifndef_macro;
1290 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1291 /* add in hash table */
1292 h = hash_cached_include(type, filename);
1293 e->hash_next = s1->cached_includes_hash[h];
1294 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1297 static void pragma_parse(TCCState *s1)
1299 int val;
1301 next();
1302 if (tok == TOK_pack) {
1304 This may be:
1305 #pragma pack(1) // set
1306 #pragma pack() // reset to default
1307 #pragma pack(push,1) // push & set
1308 #pragma pack(pop) // restore previous
1310 next();
1311 skip('(');
1312 if (tok == TOK_ASM_pop) {
1313 next();
1314 if (s1->pack_stack_ptr <= s1->pack_stack) {
1315 stk_error:
1316 error("out of pack stack");
1318 s1->pack_stack_ptr--;
1319 } else {
1320 val = 0;
1321 if (tok != ')') {
1322 if (tok == TOK_ASM_push) {
1323 next();
1324 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1325 goto stk_error;
1326 s1->pack_stack_ptr++;
1327 skip(',');
1329 if (tok != TOK_CINT) {
1330 pack_error:
1331 error("invalid pack pragma");
1333 val = tokc.i;
1334 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1335 goto pack_error;
1336 next();
1338 *s1->pack_stack_ptr = val;
1339 skip(')');
1344 /* is_bof is true if first non space token at beginning of file */
1345 ST_FUNC void preprocess(int is_bof)
1347 TCCState *s1 = tcc_state;
1348 int i, c, n, saved_parse_flags;
1349 char buf[1024], *q;
1350 Sym *s;
1352 saved_parse_flags = parse_flags;
1353 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
1354 PARSE_FLAG_LINEFEED;
1355 next_nomacro();
1356 redo:
1357 switch(tok) {
1358 case TOK_DEFINE:
1359 next_nomacro();
1360 parse_define();
1361 break;
1362 case TOK_UNDEF:
1363 next_nomacro();
1364 s = define_find(tok);
1365 /* undefine symbol by putting an invalid name */
1366 if (s)
1367 define_undef(s);
1368 break;
1369 case TOK_INCLUDE:
1370 case TOK_INCLUDE_NEXT:
1371 ch = file->buf_ptr[0];
1372 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1373 skip_spaces();
1374 if (ch == '<') {
1375 c = '>';
1376 goto read_name;
1377 } else if (ch == '\"') {
1378 c = ch;
1379 read_name:
1380 inp();
1381 q = buf;
1382 while (ch != c && ch != '\n' && ch != CH_EOF) {
1383 if ((q - buf) < sizeof(buf) - 1)
1384 *q++ = ch;
1385 if (ch == '\\') {
1386 if (handle_stray_noerror() == 0)
1387 --q;
1388 } else
1389 inp();
1391 *q = '\0';
1392 minp();
1393 #if 0
1394 /* eat all spaces and comments after include */
1395 /* XXX: slightly incorrect */
1396 while (ch1 != '\n' && ch1 != CH_EOF)
1397 inp();
1398 #endif
1399 } else {
1400 /* computed #include : either we have only strings or
1401 we have anything enclosed in '<>' */
1402 next();
1403 buf[0] = '\0';
1404 if (tok == TOK_STR) {
1405 while (tok != TOK_LINEFEED) {
1406 if (tok != TOK_STR) {
1407 include_syntax:
1408 error("'#include' expects \"FILENAME\" or <FILENAME>");
1410 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
1411 next();
1413 c = '\"';
1414 } else {
1415 int len;
1416 while (tok != TOK_LINEFEED) {
1417 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1418 next();
1420 len = strlen(buf);
1421 /* check syntax and remove '<>' */
1422 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1423 goto include_syntax;
1424 memmove(buf, buf + 1, len - 2);
1425 buf[len - 2] = '\0';
1426 c = '>';
1430 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1431 error("#include recursion too deep");
1433 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
1434 for (i = -2; i < n; ++i) {
1435 char buf1[sizeof file->filename];
1436 CachedInclude *e;
1437 const char *path;
1438 int size, fd;
1440 if (i == -2) {
1441 /* check absolute include path */
1442 if (!IS_ABSPATH(buf))
1443 continue;
1444 buf1[0] = 0;
1446 } else if (i == -1) {
1447 /* search in current dir if "header.h" */
1448 if (c != '\"')
1449 continue;
1450 size = tcc_basename(file->filename) - file->filename;
1451 memcpy(buf1, file->filename, size);
1452 buf1[size] = '\0';
1454 } else {
1455 /* search in all the include paths */
1456 if (i < s1->nb_include_paths)
1457 path = s1->include_paths[i];
1458 else
1459 path = s1->sysinclude_paths[i - s1->nb_include_paths];
1460 pstrcpy(buf1, sizeof(buf1), path);
1461 pstrcat(buf1, sizeof(buf1), "/");
1464 pstrcat(buf1, sizeof(buf1), buf);
1466 e = search_cached_include(s1, c, buf1);
1467 if (e && define_find(e->ifndef_macro)) {
1468 /* no need to parse the include because the 'ifndef macro'
1469 is defined */
1470 #ifdef INC_DEBUG
1471 printf("%s: skipping %s\n", file->filename, buf);
1472 #endif
1473 fd = 0;
1474 } else {
1475 fd = tcc_open(s1, buf1);
1476 if (fd < 0)
1477 continue;
1480 if (tok == TOK_INCLUDE_NEXT) {
1481 tok = TOK_INCLUDE;
1482 if (fd)
1483 tcc_close();
1484 continue;
1487 if (0 == fd)
1488 goto include_done;
1490 #ifdef INC_DEBUG
1491 printf("%s: including %s\n", file->filename, buf1);
1492 #endif
1493 /* update target deps */
1494 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1495 tcc_strdup(buf1));
1496 /* XXX: fix current line init */
1497 /* push current file in stack */
1498 *s1->include_stack_ptr++ = file->prev;
1499 file->inc_type = c;
1500 pstrcpy(file->inc_filename, sizeof(file->inc_filename), buf1);
1501 /* add include file debug info */
1502 if (s1->do_debug)
1503 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1504 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1505 ch = file->buf_ptr[0];
1506 goto the_end;
1508 error("include file '%s' not found", buf);
1509 include_done:
1510 break;
1511 case TOK_IFNDEF:
1512 c = 1;
1513 goto do_ifdef;
1514 case TOK_IF:
1515 c = expr_preprocess();
1516 goto do_if;
1517 case TOK_IFDEF:
1518 c = 0;
1519 do_ifdef:
1520 next_nomacro();
1521 if (tok < TOK_IDENT)
1522 error("invalid argument for '#if%sdef'", c ? "n" : "");
1523 if (is_bof) {
1524 if (c) {
1525 #ifdef INC_DEBUG
1526 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1527 #endif
1528 file->ifndef_macro = tok;
1531 c = (define_find(tok) != 0) ^ c;
1532 do_if:
1533 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1534 error("memory full");
1535 *s1->ifdef_stack_ptr++ = c;
1536 goto test_skip;
1537 case TOK_ELSE:
1538 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1539 error("#else without matching #if");
1540 if (s1->ifdef_stack_ptr[-1] & 2)
1541 error("#else after #else");
1542 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1543 goto test_else;
1544 case TOK_ELIF:
1545 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1546 error("#elif without matching #if");
1547 c = s1->ifdef_stack_ptr[-1];
1548 if (c > 1)
1549 error("#elif after #else");
1550 /* last #if/#elif expression was true: we skip */
1551 if (c == 1)
1552 goto skip;
1553 c = expr_preprocess();
1554 s1->ifdef_stack_ptr[-1] = c;
1555 test_else:
1556 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1557 file->ifndef_macro = 0;
1558 test_skip:
1559 if (!(c & 1)) {
1560 skip:
1561 preprocess_skip();
1562 is_bof = 0;
1563 goto redo;
1565 break;
1566 case TOK_ENDIF:
1567 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1568 error("#endif without matching #if");
1569 s1->ifdef_stack_ptr--;
1570 /* '#ifndef macro' was at the start of file. Now we check if
1571 an '#endif' is exactly at the end of file */
1572 if (file->ifndef_macro &&
1573 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1574 file->ifndef_macro_saved = file->ifndef_macro;
1575 /* need to set to zero to avoid false matches if another
1576 #ifndef at middle of file */
1577 file->ifndef_macro = 0;
1578 while (tok != TOK_LINEFEED)
1579 next_nomacro();
1580 tok_flags |= TOK_FLAG_ENDIF;
1581 goto the_end;
1583 break;
1584 case TOK_LINE:
1585 next();
1586 if (tok != TOK_CINT)
1587 error("#line");
1588 file->line_num = tokc.i - 1; /* the line number will be incremented after */
1589 next();
1590 if (tok != TOK_LINEFEED) {
1591 if (tok != TOK_STR)
1592 error("#line");
1593 pstrcpy(file->filename, sizeof(file->filename),
1594 (char *)tokc.cstr->data);
1596 break;
1597 case TOK_ERROR:
1598 case TOK_WARNING:
1599 c = tok;
1600 ch = file->buf_ptr[0];
1601 skip_spaces();
1602 q = buf;
1603 while (ch != '\n' && ch != CH_EOF) {
1604 if ((q - buf) < sizeof(buf) - 1)
1605 *q++ = ch;
1606 if (ch == '\\') {
1607 if (handle_stray_noerror() == 0)
1608 --q;
1609 } else
1610 inp();
1612 *q = '\0';
1613 if (c == TOK_ERROR)
1614 error("#error %s", buf);
1615 else
1616 warning("#warning %s", buf);
1617 break;
1618 case TOK_PRAGMA:
1619 pragma_parse(s1);
1620 break;
1621 default:
1622 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_PPNUM) {
1623 /* '!' is ignored to allow C scripts. numbers are ignored
1624 to emulate cpp behaviour */
1625 } else {
1626 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
1627 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1628 else {
1629 /* this is a gas line comment in an 'S' file. */
1630 file->buf_ptr = parse_line_comment(file->buf_ptr);
1631 goto the_end;
1634 break;
1636 /* ignore other preprocess commands or #! for C scripts */
1637 while (tok != TOK_LINEFEED)
1638 next_nomacro();
1639 the_end:
1640 parse_flags = saved_parse_flags;
1643 /* evaluate escape codes in a string. */
1644 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1646 int c, n;
1647 const uint8_t *p;
1649 p = buf;
1650 for(;;) {
1651 c = *p;
1652 if (c == '\0')
1653 break;
1654 if (c == '\\') {
1655 p++;
1656 /* escape */
1657 c = *p;
1658 switch(c) {
1659 case '0': case '1': case '2': case '3':
1660 case '4': case '5': case '6': case '7':
1661 /* at most three octal digits */
1662 n = c - '0';
1663 p++;
1664 c = *p;
1665 if (isoct(c)) {
1666 n = n * 8 + c - '0';
1667 p++;
1668 c = *p;
1669 if (isoct(c)) {
1670 n = n * 8 + c - '0';
1671 p++;
1674 c = n;
1675 goto add_char_nonext;
1676 case 'x':
1677 case 'u':
1678 case 'U':
1679 p++;
1680 n = 0;
1681 for(;;) {
1682 c = *p;
1683 if (c >= 'a' && c <= 'f')
1684 c = c - 'a' + 10;
1685 else if (c >= 'A' && c <= 'F')
1686 c = c - 'A' + 10;
1687 else if (isnum(c))
1688 c = c - '0';
1689 else
1690 break;
1691 n = n * 16 + c;
1692 p++;
1694 c = n;
1695 goto add_char_nonext;
1696 case 'a':
1697 c = '\a';
1698 break;
1699 case 'b':
1700 c = '\b';
1701 break;
1702 case 'f':
1703 c = '\f';
1704 break;
1705 case 'n':
1706 c = '\n';
1707 break;
1708 case 'r':
1709 c = '\r';
1710 break;
1711 case 't':
1712 c = '\t';
1713 break;
1714 case 'v':
1715 c = '\v';
1716 break;
1717 case 'e':
1718 if (!gnu_ext)
1719 goto invalid_escape;
1720 c = 27;
1721 break;
1722 case '\'':
1723 case '\"':
1724 case '\\':
1725 case '?':
1726 break;
1727 default:
1728 invalid_escape:
1729 if (c >= '!' && c <= '~')
1730 warning("unknown escape sequence: \'\\%c\'", c);
1731 else
1732 warning("unknown escape sequence: \'\\x%x\'", c);
1733 break;
1736 p++;
1737 add_char_nonext:
1738 if (!is_long)
1739 cstr_ccat(outstr, c);
1740 else
1741 cstr_wccat(outstr, c);
1743 /* add a trailing '\0' */
1744 if (!is_long)
1745 cstr_ccat(outstr, '\0');
1746 else
1747 cstr_wccat(outstr, '\0');
1750 /* we use 64 bit numbers */
1751 #define BN_SIZE 2
1753 /* bn = (bn << shift) | or_val */
1754 static void bn_lshift(unsigned int *bn, int shift, int or_val)
1756 int i;
1757 unsigned int v;
1758 for(i=0;i<BN_SIZE;i++) {
1759 v = bn[i];
1760 bn[i] = (v << shift) | or_val;
1761 or_val = v >> (32 - shift);
1765 static void bn_zero(unsigned int *bn)
1767 int i;
1768 for(i=0;i<BN_SIZE;i++) {
1769 bn[i] = 0;
1773 /* parse number in null terminated string 'p' and return it in the
1774 current token */
1775 static void parse_number(const char *p)
1777 int b, t, shift, frac_bits, s, exp_val, ch;
1778 char *q;
1779 unsigned int bn[BN_SIZE];
1780 double d;
1782 /* number */
1783 q = token_buf;
1784 ch = *p++;
1785 t = ch;
1786 ch = *p++;
1787 *q++ = t;
1788 b = 10;
1789 if (t == '.') {
1790 goto float_frac_parse;
1791 } else if (t == '0') {
1792 if (ch == 'x' || ch == 'X') {
1793 q--;
1794 ch = *p++;
1795 b = 16;
1796 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
1797 q--;
1798 ch = *p++;
1799 b = 2;
1802 /* parse all digits. cannot check octal numbers at this stage
1803 because of floating point constants */
1804 while (1) {
1805 if (ch >= 'a' && ch <= 'f')
1806 t = ch - 'a' + 10;
1807 else if (ch >= 'A' && ch <= 'F')
1808 t = ch - 'A' + 10;
1809 else if (isnum(ch))
1810 t = ch - '0';
1811 else
1812 break;
1813 if (t >= b)
1814 break;
1815 if (q >= token_buf + STRING_MAX_SIZE) {
1816 num_too_long:
1817 error("number too long");
1819 *q++ = ch;
1820 ch = *p++;
1822 if (ch == '.' ||
1823 ((ch == 'e' || ch == 'E') && b == 10) ||
1824 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
1825 if (b != 10) {
1826 /* NOTE: strtox should support that for hexa numbers, but
1827 non ISOC99 libcs do not support it, so we prefer to do
1828 it by hand */
1829 /* hexadecimal or binary floats */
1830 /* XXX: handle overflows */
1831 *q = '\0';
1832 if (b == 16)
1833 shift = 4;
1834 else
1835 shift = 2;
1836 bn_zero(bn);
1837 q = token_buf;
1838 while (1) {
1839 t = *q++;
1840 if (t == '\0') {
1841 break;
1842 } else if (t >= 'a') {
1843 t = t - 'a' + 10;
1844 } else if (t >= 'A') {
1845 t = t - 'A' + 10;
1846 } else {
1847 t = t - '0';
1849 bn_lshift(bn, shift, t);
1851 frac_bits = 0;
1852 if (ch == '.') {
1853 ch = *p++;
1854 while (1) {
1855 t = ch;
1856 if (t >= 'a' && t <= 'f') {
1857 t = t - 'a' + 10;
1858 } else if (t >= 'A' && t <= 'F') {
1859 t = t - 'A' + 10;
1860 } else if (t >= '0' && t <= '9') {
1861 t = t - '0';
1862 } else {
1863 break;
1865 if (t >= b)
1866 error("invalid digit");
1867 bn_lshift(bn, shift, t);
1868 frac_bits += shift;
1869 ch = *p++;
1872 if (ch != 'p' && ch != 'P')
1873 expect("exponent");
1874 ch = *p++;
1875 s = 1;
1876 exp_val = 0;
1877 if (ch == '+') {
1878 ch = *p++;
1879 } else if (ch == '-') {
1880 s = -1;
1881 ch = *p++;
1883 if (ch < '0' || ch > '9')
1884 expect("exponent digits");
1885 while (ch >= '0' && ch <= '9') {
1886 exp_val = exp_val * 10 + ch - '0';
1887 ch = *p++;
1889 exp_val = exp_val * s;
1891 /* now we can generate the number */
1892 /* XXX: should patch directly float number */
1893 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
1894 d = ldexp(d, exp_val - frac_bits);
1895 t = toup(ch);
1896 if (t == 'F') {
1897 ch = *p++;
1898 tok = TOK_CFLOAT;
1899 /* float : should handle overflow */
1900 tokc.f = (float)d;
1901 } else if (t == 'L') {
1902 ch = *p++;
1903 #ifdef TCC_TARGET_PE
1904 tok = TOK_CDOUBLE;
1905 tokc.d = d;
1906 #else
1907 tok = TOK_CLDOUBLE;
1908 /* XXX: not large enough */
1909 tokc.ld = (long double)d;
1910 #endif
1911 } else {
1912 tok = TOK_CDOUBLE;
1913 tokc.d = d;
1915 } else {
1916 /* decimal floats */
1917 if (ch == '.') {
1918 if (q >= token_buf + STRING_MAX_SIZE)
1919 goto num_too_long;
1920 *q++ = ch;
1921 ch = *p++;
1922 float_frac_parse:
1923 while (ch >= '0' && ch <= '9') {
1924 if (q >= token_buf + STRING_MAX_SIZE)
1925 goto num_too_long;
1926 *q++ = ch;
1927 ch = *p++;
1930 if (ch == 'e' || ch == 'E') {
1931 if (q >= token_buf + STRING_MAX_SIZE)
1932 goto num_too_long;
1933 *q++ = ch;
1934 ch = *p++;
1935 if (ch == '-' || ch == '+') {
1936 if (q >= token_buf + STRING_MAX_SIZE)
1937 goto num_too_long;
1938 *q++ = ch;
1939 ch = *p++;
1941 if (ch < '0' || ch > '9')
1942 expect("exponent digits");
1943 while (ch >= '0' && ch <= '9') {
1944 if (q >= token_buf + STRING_MAX_SIZE)
1945 goto num_too_long;
1946 *q++ = ch;
1947 ch = *p++;
1950 *q = '\0';
1951 t = toup(ch);
1952 errno = 0;
1953 if (t == 'F') {
1954 ch = *p++;
1955 tok = TOK_CFLOAT;
1956 tokc.f = strtof(token_buf, NULL);
1957 } else if (t == 'L') {
1958 ch = *p++;
1959 #ifdef TCC_TARGET_PE
1960 tok = TOK_CDOUBLE;
1961 tokc.d = strtod(token_buf, NULL);
1962 #else
1963 tok = TOK_CLDOUBLE;
1964 tokc.ld = strtold(token_buf, NULL);
1965 #endif
1966 } else {
1967 tok = TOK_CDOUBLE;
1968 tokc.d = strtod(token_buf, NULL);
1971 } else {
1972 unsigned long long n, n1;
1973 int lcount, ucount;
1975 /* integer number */
1976 *q = '\0';
1977 q = token_buf;
1978 if (b == 10 && *q == '0') {
1979 b = 8;
1980 q++;
1982 n = 0;
1983 while(1) {
1984 t = *q++;
1985 /* no need for checks except for base 10 / 8 errors */
1986 if (t == '\0') {
1987 break;
1988 } else if (t >= 'a') {
1989 t = t - 'a' + 10;
1990 } else if (t >= 'A') {
1991 t = t - 'A' + 10;
1992 } else {
1993 t = t - '0';
1994 if (t >= b)
1995 error("invalid digit");
1997 n1 = n;
1998 n = n * b + t;
1999 /* detect overflow */
2000 /* XXX: this test is not reliable */
2001 if (n < n1)
2002 error("integer constant overflow");
2005 /* XXX: not exactly ANSI compliant */
2006 if ((n & 0xffffffff00000000LL) != 0) {
2007 if ((n >> 63) != 0)
2008 tok = TOK_CULLONG;
2009 else
2010 tok = TOK_CLLONG;
2011 } else if (n > 0x7fffffff) {
2012 tok = TOK_CUINT;
2013 } else {
2014 tok = TOK_CINT;
2016 lcount = 0;
2017 ucount = 0;
2018 for(;;) {
2019 t = toup(ch);
2020 if (t == 'L') {
2021 if (lcount >= 2)
2022 error("three 'l's in integer constant");
2023 lcount++;
2024 if (lcount == 2) {
2025 if (tok == TOK_CINT)
2026 tok = TOK_CLLONG;
2027 else if (tok == TOK_CUINT)
2028 tok = TOK_CULLONG;
2030 ch = *p++;
2031 } else if (t == 'U') {
2032 if (ucount >= 1)
2033 error("two 'u's in integer constant");
2034 ucount++;
2035 if (tok == TOK_CINT)
2036 tok = TOK_CUINT;
2037 else if (tok == TOK_CLLONG)
2038 tok = TOK_CULLONG;
2039 ch = *p++;
2040 } else {
2041 break;
2044 if (tok == TOK_CINT || tok == TOK_CUINT)
2045 tokc.ui = n;
2046 else
2047 tokc.ull = n;
2049 if (ch)
2050 error("invalid number\n");
2054 #define PARSE2(c1, tok1, c2, tok2) \
2055 case c1: \
2056 PEEKC(c, p); \
2057 if (c == c2) { \
2058 p++; \
2059 tok = tok2; \
2060 } else { \
2061 tok = tok1; \
2063 break;
2065 /* return next token without macro substitution */
2066 static inline void next_nomacro1(void)
2068 int t, c, is_long;
2069 TokenSym *ts;
2070 uint8_t *p, *p1;
2071 unsigned int h;
2073 p = file->buf_ptr;
2074 redo_no_start:
2075 c = *p;
2076 switch(c) {
2077 case ' ':
2078 case '\t':
2079 tok = c;
2080 p++;
2081 goto keep_tok_flags;
2082 case '\f':
2083 case '\v':
2084 case '\r':
2085 p++;
2086 goto redo_no_start;
2087 case '\\':
2088 /* first look if it is in fact an end of buffer */
2089 if (p >= file->buf_end) {
2090 file->buf_ptr = p;
2091 handle_eob();
2092 p = file->buf_ptr;
2093 if (p >= file->buf_end)
2094 goto parse_eof;
2095 else
2096 goto redo_no_start;
2097 } else {
2098 file->buf_ptr = p;
2099 ch = *p;
2100 handle_stray();
2101 p = file->buf_ptr;
2102 goto redo_no_start;
2104 parse_eof:
2106 TCCState *s1 = tcc_state;
2107 if ((parse_flags & PARSE_FLAG_LINEFEED)
2108 && !(tok_flags & TOK_FLAG_EOF)) {
2109 tok_flags |= TOK_FLAG_EOF;
2110 tok = TOK_LINEFEED;
2111 goto keep_tok_flags;
2112 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2113 tok = TOK_EOF;
2114 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2115 error("missing #endif");
2116 } else if (s1->include_stack_ptr == s1->include_stack) {
2117 /* no include left : end of file. */
2118 tok = TOK_EOF;
2119 } else {
2120 tok_flags &= ~TOK_FLAG_EOF;
2121 /* pop include file */
2123 /* test if previous '#endif' was after a #ifdef at
2124 start of file */
2125 if (tok_flags & TOK_FLAG_ENDIF) {
2126 #ifdef INC_DEBUG
2127 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2128 #endif
2129 add_cached_include(s1, file->inc_type, file->inc_filename,
2130 file->ifndef_macro_saved);
2133 /* add end of include file debug info */
2134 if (tcc_state->do_debug) {
2135 put_stabd(N_EINCL, 0, 0);
2137 /* pop include stack */
2138 tcc_close();
2139 s1->include_stack_ptr--;
2140 p = file->buf_ptr;
2141 goto redo_no_start;
2144 break;
2146 case '\n':
2147 file->line_num++;
2148 tok_flags |= TOK_FLAG_BOL;
2149 p++;
2150 maybe_newline:
2151 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2152 goto redo_no_start;
2153 tok = TOK_LINEFEED;
2154 goto keep_tok_flags;
2156 case '#':
2157 /* XXX: simplify */
2158 PEEKC(c, p);
2159 if ((tok_flags & TOK_FLAG_BOL) &&
2160 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2161 file->buf_ptr = p;
2162 preprocess(tok_flags & TOK_FLAG_BOF);
2163 p = file->buf_ptr;
2164 goto maybe_newline;
2165 } else {
2166 if (c == '#') {
2167 p++;
2168 tok = TOK_TWOSHARPS;
2169 } else {
2170 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
2171 p = parse_line_comment(p - 1);
2172 goto redo_no_start;
2173 } else {
2174 tok = '#';
2178 break;
2180 case 'a': case 'b': case 'c': case 'd':
2181 case 'e': case 'f': case 'g': case 'h':
2182 case 'i': case 'j': case 'k': case 'l':
2183 case 'm': case 'n': case 'o': case 'p':
2184 case 'q': case 'r': case 's': case 't':
2185 case 'u': case 'v': case 'w': case 'x':
2186 case 'y': case 'z':
2187 case 'A': case 'B': case 'C': case 'D':
2188 case 'E': case 'F': case 'G': case 'H':
2189 case 'I': case 'J': case 'K':
2190 case 'M': case 'N': case 'O': case 'P':
2191 case 'Q': case 'R': case 'S': case 'T':
2192 case 'U': case 'V': case 'W': case 'X':
2193 case 'Y': case 'Z':
2194 case '_':
2195 parse_ident_fast:
2196 p1 = p;
2197 h = TOK_HASH_INIT;
2198 h = TOK_HASH_FUNC(h, c);
2199 p++;
2200 for(;;) {
2201 c = *p;
2202 if (!isidnum_table[c-CH_EOF])
2203 break;
2204 h = TOK_HASH_FUNC(h, c);
2205 p++;
2207 if (c != '\\') {
2208 TokenSym **pts;
2209 int len;
2211 /* fast case : no stray found, so we have the full token
2212 and we have already hashed it */
2213 len = p - p1;
2214 h &= (TOK_HASH_SIZE - 1);
2215 pts = &hash_ident[h];
2216 for(;;) {
2217 ts = *pts;
2218 if (!ts)
2219 break;
2220 if (ts->len == len && !memcmp(ts->str, p1, len))
2221 goto token_found;
2222 pts = &(ts->hash_next);
2224 ts = tok_alloc_new(pts, p1, len);
2225 token_found: ;
2226 } else {
2227 /* slower case */
2228 cstr_reset(&tokcstr);
2230 while (p1 < p) {
2231 cstr_ccat(&tokcstr, *p1);
2232 p1++;
2234 p--;
2235 PEEKC(c, p);
2236 parse_ident_slow:
2237 while (isidnum_table[c-CH_EOF]) {
2238 cstr_ccat(&tokcstr, c);
2239 PEEKC(c, p);
2241 ts = tok_alloc(tokcstr.data, tokcstr.size);
2243 tok = ts->tok;
2244 break;
2245 case 'L':
2246 t = p[1];
2247 if (t != '\\' && t != '\'' && t != '\"') {
2248 /* fast case */
2249 goto parse_ident_fast;
2250 } else {
2251 PEEKC(c, p);
2252 if (c == '\'' || c == '\"') {
2253 is_long = 1;
2254 goto str_const;
2255 } else {
2256 cstr_reset(&tokcstr);
2257 cstr_ccat(&tokcstr, 'L');
2258 goto parse_ident_slow;
2261 break;
2262 case '0': case '1': case '2': case '3':
2263 case '4': case '5': case '6': case '7':
2264 case '8': case '9':
2266 cstr_reset(&tokcstr);
2267 /* after the first digit, accept digits, alpha, '.' or sign if
2268 prefixed by 'eEpP' */
2269 parse_num:
2270 for(;;) {
2271 t = c;
2272 cstr_ccat(&tokcstr, c);
2273 PEEKC(c, p);
2274 if (!(isnum(c) || isid(c) || c == '.' ||
2275 ((c == '+' || c == '-') &&
2276 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
2277 break;
2279 /* We add a trailing '\0' to ease parsing */
2280 cstr_ccat(&tokcstr, '\0');
2281 tokc.cstr = &tokcstr;
2282 tok = TOK_PPNUM;
2283 break;
2284 case '.':
2285 /* special dot handling because it can also start a number */
2286 PEEKC(c, p);
2287 if (isnum(c)) {
2288 cstr_reset(&tokcstr);
2289 cstr_ccat(&tokcstr, '.');
2290 goto parse_num;
2291 } else if (c == '.') {
2292 PEEKC(c, p);
2293 if (c != '.')
2294 expect("'.'");
2295 PEEKC(c, p);
2296 tok = TOK_DOTS;
2297 } else {
2298 tok = '.';
2300 break;
2301 case '\'':
2302 case '\"':
2303 is_long = 0;
2304 str_const:
2306 CString str;
2307 int sep;
2309 sep = c;
2311 /* parse the string */
2312 cstr_new(&str);
2313 p = parse_pp_string(p, sep, &str);
2314 cstr_ccat(&str, '\0');
2316 /* eval the escape (should be done as TOK_PPNUM) */
2317 cstr_reset(&tokcstr);
2318 parse_escape_string(&tokcstr, str.data, is_long);
2319 cstr_free(&str);
2321 if (sep == '\'') {
2322 int char_size;
2323 /* XXX: make it portable */
2324 if (!is_long)
2325 char_size = 1;
2326 else
2327 char_size = sizeof(nwchar_t);
2328 if (tokcstr.size <= char_size)
2329 error("empty character constant");
2330 if (tokcstr.size > 2 * char_size)
2331 warning("multi-character character constant");
2332 if (!is_long) {
2333 tokc.i = *(int8_t *)tokcstr.data;
2334 tok = TOK_CCHAR;
2335 } else {
2336 tokc.i = *(nwchar_t *)tokcstr.data;
2337 tok = TOK_LCHAR;
2339 } else {
2340 tokc.cstr = &tokcstr;
2341 if (!is_long)
2342 tok = TOK_STR;
2343 else
2344 tok = TOK_LSTR;
2347 break;
2349 case '<':
2350 PEEKC(c, p);
2351 if (c == '=') {
2352 p++;
2353 tok = TOK_LE;
2354 } else if (c == '<') {
2355 PEEKC(c, p);
2356 if (c == '=') {
2357 p++;
2358 tok = TOK_A_SHL;
2359 } else {
2360 tok = TOK_SHL;
2362 } else {
2363 tok = TOK_LT;
2365 break;
2367 case '>':
2368 PEEKC(c, p);
2369 if (c == '=') {
2370 p++;
2371 tok = TOK_GE;
2372 } else if (c == '>') {
2373 PEEKC(c, p);
2374 if (c == '=') {
2375 p++;
2376 tok = TOK_A_SAR;
2377 } else {
2378 tok = TOK_SAR;
2380 } else {
2381 tok = TOK_GT;
2383 break;
2385 case '&':
2386 PEEKC(c, p);
2387 if (c == '&') {
2388 p++;
2389 tok = TOK_LAND;
2390 } else if (c == '=') {
2391 p++;
2392 tok = TOK_A_AND;
2393 } else {
2394 tok = '&';
2396 break;
2398 case '|':
2399 PEEKC(c, p);
2400 if (c == '|') {
2401 p++;
2402 tok = TOK_LOR;
2403 } else if (c == '=') {
2404 p++;
2405 tok = TOK_A_OR;
2406 } else {
2407 tok = '|';
2409 break;
2411 case '+':
2412 PEEKC(c, p);
2413 if (c == '+') {
2414 p++;
2415 tok = TOK_INC;
2416 } else if (c == '=') {
2417 p++;
2418 tok = TOK_A_ADD;
2419 } else {
2420 tok = '+';
2422 break;
2424 case '-':
2425 PEEKC(c, p);
2426 if (c == '-') {
2427 p++;
2428 tok = TOK_DEC;
2429 } else if (c == '=') {
2430 p++;
2431 tok = TOK_A_SUB;
2432 } else if (c == '>') {
2433 p++;
2434 tok = TOK_ARROW;
2435 } else {
2436 tok = '-';
2438 break;
2440 PARSE2('!', '!', '=', TOK_NE)
2441 PARSE2('=', '=', '=', TOK_EQ)
2442 PARSE2('*', '*', '=', TOK_A_MUL)
2443 PARSE2('%', '%', '=', TOK_A_MOD)
2444 PARSE2('^', '^', '=', TOK_A_XOR)
2446 /* comments or operator */
2447 case '/':
2448 PEEKC(c, p);
2449 if (c == '*') {
2450 p = parse_comment(p);
2451 /* comments replaced by a blank */
2452 tok = ' ';
2453 goto keep_tok_flags;
2454 } else if (c == '/') {
2455 p = parse_line_comment(p);
2456 tok = ' ';
2457 goto keep_tok_flags;
2458 } else if (c == '=') {
2459 p++;
2460 tok = TOK_A_DIV;
2461 } else {
2462 tok = '/';
2464 break;
2466 /* simple tokens */
2467 case '(':
2468 case ')':
2469 case '[':
2470 case ']':
2471 case '{':
2472 case '}':
2473 case ',':
2474 case ';':
2475 case ':':
2476 case '?':
2477 case '~':
2478 case '$': /* only used in assembler */
2479 case '@': /* dito */
2480 tok = c;
2481 p++;
2482 break;
2483 default:
2484 error("unrecognized character \\x%02x", c);
2485 break;
2487 tok_flags = 0;
2488 keep_tok_flags:
2489 file->buf_ptr = p;
2490 #if defined(PARSE_DEBUG)
2491 printf("token = %s\n", get_tok_str(tok, &tokc));
2492 #endif
2495 /* return next token without macro substitution. Can read input from
2496 macro_ptr buffer */
2497 static void next_nomacro_spc(void)
2499 if (macro_ptr) {
2500 redo:
2501 tok = *macro_ptr;
2502 if (tok) {
2503 TOK_GET(&tok, &macro_ptr, &tokc);
2504 if (tok == TOK_LINENUM) {
2505 file->line_num = tokc.i;
2506 goto redo;
2509 } else {
2510 next_nomacro1();
2514 ST_FUNC void next_nomacro(void)
2516 do {
2517 next_nomacro_spc();
2518 } while (is_space(tok));
2521 /* substitute args in macro_str and return allocated string */
2522 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2524 int last_tok, t, spc;
2525 const int *st;
2526 Sym *s;
2527 CValue cval;
2528 TokenString str;
2529 CString cstr;
2531 tok_str_new(&str);
2532 last_tok = 0;
2533 while(1) {
2534 TOK_GET(&t, &macro_str, &cval);
2535 if (!t)
2536 break;
2537 if (t == '#') {
2538 /* stringize */
2539 TOK_GET(&t, &macro_str, &cval);
2540 if (!t)
2541 break;
2542 s = sym_find2(args, t);
2543 if (s) {
2544 cstr_new(&cstr);
2545 st = s->d;
2546 spc = 0;
2547 while (*st) {
2548 TOK_GET(&t, &st, &cval);
2549 if (!check_space(t, &spc))
2550 cstr_cat(&cstr, get_tok_str(t, &cval));
2552 cstr.size -= spc;
2553 cstr_ccat(&cstr, '\0');
2554 #ifdef PP_DEBUG
2555 printf("stringize: %s\n", (char *)cstr.data);
2556 #endif
2557 /* add string */
2558 cval.cstr = &cstr;
2559 tok_str_add2(&str, TOK_STR, &cval);
2560 cstr_free(&cstr);
2561 } else {
2562 tok_str_add2(&str, t, &cval);
2564 } else if (t >= TOK_IDENT) {
2565 s = sym_find2(args, t);
2566 if (s) {
2567 st = s->d;
2568 /* if '##' is present before or after, no arg substitution */
2569 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
2570 /* special case for var arg macros : ## eats the
2571 ',' if empty VA_ARGS variable. */
2572 /* XXX: test of the ',' is not 100%
2573 reliable. should fix it to avoid security
2574 problems */
2575 if (gnu_ext && s->type.t &&
2576 last_tok == TOK_TWOSHARPS &&
2577 str.len >= 2 && str.str[str.len - 2] == ',') {
2578 if (*st == 0) {
2579 /* suppress ',' '##' */
2580 str.len -= 2;
2581 } else {
2582 /* suppress '##' and add variable */
2583 str.len--;
2584 goto add_var;
2586 } else {
2587 int t1;
2588 add_var:
2589 for(;;) {
2590 TOK_GET(&t1, &st, &cval);
2591 if (!t1)
2592 break;
2593 tok_str_add2(&str, t1, &cval);
2596 } else {
2597 /* NOTE: the stream cannot be read when macro
2598 substituing an argument */
2599 macro_subst(&str, nested_list, st, NULL);
2601 } else {
2602 tok_str_add(&str, t);
2604 } else {
2605 tok_str_add2(&str, t, &cval);
2607 last_tok = t;
2609 tok_str_add(&str, 0);
2610 return str.str;
2613 static char const ab_month_name[12][4] =
2615 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2616 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2619 /* do macro substitution of current token with macro 's' and add
2620 result to (tok_str,tok_len). 'nested_list' is the list of all
2621 macros we got inside to avoid recursing. Return non zero if no
2622 substitution needs to be done */
2623 static int macro_subst_tok(TokenString *tok_str,
2624 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
2626 Sym *args, *sa, *sa1;
2627 int mstr_allocated, parlevel, *mstr, t, t1, spc;
2628 const int *p;
2629 TokenString str;
2630 char *cstrval;
2631 CValue cval;
2632 CString cstr;
2633 char buf[32];
2635 /* if symbol is a macro, prepare substitution */
2636 /* special macros */
2637 if (tok == TOK___LINE__) {
2638 snprintf(buf, sizeof(buf), "%d", file->line_num);
2639 cstrval = buf;
2640 t1 = TOK_PPNUM;
2641 goto add_cstr1;
2642 } else if (tok == TOK___FILE__) {
2643 cstrval = file->filename;
2644 goto add_cstr;
2645 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
2646 time_t ti;
2647 struct tm *tm;
2649 time(&ti);
2650 tm = localtime(&ti);
2651 if (tok == TOK___DATE__) {
2652 snprintf(buf, sizeof(buf), "%s %2d %d",
2653 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
2654 } else {
2655 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
2656 tm->tm_hour, tm->tm_min, tm->tm_sec);
2658 cstrval = buf;
2659 add_cstr:
2660 t1 = TOK_STR;
2661 add_cstr1:
2662 cstr_new(&cstr);
2663 cstr_cat(&cstr, cstrval);
2664 cstr_ccat(&cstr, '\0');
2665 cval.cstr = &cstr;
2666 tok_str_add2(tok_str, t1, &cval);
2667 cstr_free(&cstr);
2668 } else {
2669 mstr = s->d;
2670 mstr_allocated = 0;
2671 if (s->type.t == MACRO_FUNC) {
2672 /* NOTE: we do not use next_nomacro to avoid eating the
2673 next token. XXX: find better solution */
2674 redo:
2675 if (macro_ptr) {
2676 p = macro_ptr;
2677 while (is_space(t = *p) || TOK_LINEFEED == t)
2678 ++p;
2679 if (t == 0 && can_read_stream) {
2680 /* end of macro stream: we must look at the token
2681 after in the file */
2682 struct macro_level *ml = *can_read_stream;
2683 macro_ptr = NULL;
2684 if (ml)
2686 macro_ptr = ml->p;
2687 ml->p = NULL;
2688 *can_read_stream = ml -> prev;
2690 goto redo;
2692 } else {
2693 /* XXX: incorrect with comments */
2694 ch = file->buf_ptr[0];
2695 while (is_space(ch) || ch == '\n')
2696 cinp();
2697 t = ch;
2699 if (t != '(') /* no macro subst */
2700 return -1;
2702 /* argument macro */
2703 next_nomacro();
2704 next_nomacro();
2705 args = NULL;
2706 sa = s->next;
2707 /* NOTE: empty args are allowed, except if no args */
2708 for(;;) {
2709 /* handle '()' case */
2710 if (!args && !sa && tok == ')')
2711 break;
2712 if (!sa)
2713 error("macro '%s' used with too many args",
2714 get_tok_str(s->v, 0));
2715 tok_str_new(&str);
2716 parlevel = spc = 0;
2717 /* NOTE: non zero sa->t indicates VA_ARGS */
2718 while ((parlevel > 0 ||
2719 (tok != ')' &&
2720 (tok != ',' || sa->type.t))) &&
2721 tok != -1) {
2722 if (tok == '(')
2723 parlevel++;
2724 else if (tok == ')')
2725 parlevel--;
2726 if (tok == TOK_LINEFEED)
2727 tok = ' ';
2728 if (!check_space(tok, &spc))
2729 tok_str_add2(&str, tok, &tokc);
2730 next_nomacro_spc();
2732 str.len -= spc;
2733 tok_str_add(&str, 0);
2734 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
2735 sa1->d = str.str;
2736 sa = sa->next;
2737 if (tok == ')') {
2738 /* special case for gcc var args: add an empty
2739 var arg argument if it is omitted */
2740 if (sa && sa->type.t && gnu_ext)
2741 continue;
2742 else
2743 break;
2745 if (tok != ',')
2746 expect(",");
2747 next_nomacro();
2749 if (sa) {
2750 error("macro '%s' used with too few args",
2751 get_tok_str(s->v, 0));
2754 /* now subst each arg */
2755 mstr = macro_arg_subst(nested_list, mstr, args);
2756 /* free memory */
2757 sa = args;
2758 while (sa) {
2759 sa1 = sa->prev;
2760 tok_str_free(sa->d);
2761 sym_free(sa);
2762 sa = sa1;
2764 mstr_allocated = 1;
2766 sym_push2(nested_list, s->v, 0, 0);
2767 macro_subst(tok_str, nested_list, mstr, can_read_stream);
2768 /* pop nested defined symbol */
2769 sa1 = *nested_list;
2770 *nested_list = sa1->prev;
2771 sym_free(sa1);
2772 if (mstr_allocated)
2773 tok_str_free(mstr);
2775 return 0;
2778 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2779 return the resulting string (which must be freed). */
2780 static inline int *macro_twosharps(const int *macro_str)
2782 const int *ptr;
2783 int t;
2784 CValue cval;
2785 TokenString macro_str1;
2786 CString cstr;
2787 int n;
2789 /* we search the first '##' */
2790 for(ptr = macro_str;;) {
2791 TOK_GET(&t, &ptr, &cval);
2792 if (t == TOK_TWOSHARPS)
2793 break;
2794 /* nothing more to do if end of string */
2795 if (t == 0)
2796 return NULL;
2799 /* we saw '##', so we need more processing to handle it */
2800 tok_str_new(&macro_str1);
2801 for(ptr = macro_str;;) {
2802 TOK_GET(&tok, &ptr, &tokc);
2803 if (tok == 0)
2804 break;
2805 if (tok == TOK_TWOSHARPS)
2806 continue;
2807 while (*ptr == TOK_TWOSHARPS) {
2808 do { t = *++ptr; } while (t == TOK_NOSUBST);
2810 if (t && t != TOK_TWOSHARPS) {
2811 TOK_GET(&t, &ptr, &cval);
2813 /* We concatenate the two tokens */
2814 cstr_new(&cstr);
2815 cstr_cat(&cstr, get_tok_str(tok, &tokc));
2816 n = cstr.size;
2817 cstr_cat(&cstr, get_tok_str(t, &cval));
2818 cstr_ccat(&cstr, '\0');
2820 tcc_open_bf(tcc_state, "<paste>", cstr.size);
2821 memcpy(file->buffer, cstr.data, cstr.size);
2822 for (;;) {
2823 next_nomacro1();
2824 if (0 == *file->buf_ptr)
2825 break;
2826 tok_str_add2(&macro_str1, tok, &tokc);
2827 warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2828 n, cstr.data, (char*)cstr.data + n);
2830 tcc_close();
2831 cstr_reset(&cstr);
2834 tok_str_add2(&macro_str1, tok, &tokc);
2836 tok_str_add(&macro_str1, 0);
2837 return macro_str1.str;
2841 /* do macro substitution of macro_str and add result to
2842 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2843 inside to avoid recursing. */
2844 static void macro_subst(TokenString *tok_str, Sym **nested_list,
2845 const int *macro_str, struct macro_level ** can_read_stream)
2847 Sym *s;
2848 int *macro_str1;
2849 const int *ptr;
2850 int t, ret, spc;
2851 CValue cval;
2852 struct macro_level ml;
2853 int force_blank;
2855 /* first scan for '##' operator handling */
2856 ptr = macro_str;
2857 macro_str1 = macro_twosharps(ptr);
2859 if (macro_str1)
2860 ptr = macro_str1;
2861 spc = 0;
2862 force_blank = 0;
2864 while (1) {
2865 /* NOTE: ptr == NULL can only happen if tokens are read from
2866 file stream due to a macro function call */
2867 if (ptr == NULL)
2868 break;
2869 TOK_GET(&t, &ptr, &cval);
2870 if (t == 0)
2871 break;
2872 if (t == TOK_NOSUBST) {
2873 /* following token has already been subst'd. just copy it on */
2874 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
2875 TOK_GET(&t, &ptr, &cval);
2876 goto no_subst;
2878 s = define_find(t);
2879 if (s != NULL) {
2880 /* if nested substitution, do nothing */
2881 if (sym_find2(*nested_list, t)) {
2882 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
2883 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
2884 goto no_subst;
2886 ml.p = macro_ptr;
2887 if (can_read_stream)
2888 ml.prev = *can_read_stream, *can_read_stream = &ml;
2889 macro_ptr = (int *)ptr;
2890 tok = t;
2891 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
2892 ptr = (int *)macro_ptr;
2893 macro_ptr = ml.p;
2894 if (can_read_stream && *can_read_stream == &ml)
2895 *can_read_stream = ml.prev;
2896 if (ret != 0)
2897 goto no_subst;
2898 if (parse_flags & PARSE_FLAG_SPACES)
2899 force_blank = 1;
2900 } else {
2901 no_subst:
2902 if (force_blank) {
2903 tok_str_add(tok_str, ' ');
2904 spc = 1;
2905 force_blank = 0;
2907 if (!check_space(t, &spc))
2908 tok_str_add2(tok_str, t, &cval);
2911 if (macro_str1)
2912 tok_str_free(macro_str1);
2915 /* return next token with macro substitution */
2916 ST_FUNC void next(void)
2918 Sym *nested_list, *s;
2919 TokenString str;
2920 struct macro_level *ml;
2922 redo:
2923 if (parse_flags & PARSE_FLAG_SPACES)
2924 next_nomacro_spc();
2925 else
2926 next_nomacro();
2927 if (!macro_ptr) {
2928 /* if not reading from macro substituted string, then try
2929 to substitute macros */
2930 if (tok >= TOK_IDENT &&
2931 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2932 s = define_find(tok);
2933 if (s) {
2934 /* we have a macro: we try to substitute */
2935 tok_str_new(&str);
2936 nested_list = NULL;
2937 ml = NULL;
2938 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
2939 /* substitution done, NOTE: maybe empty */
2940 tok_str_add(&str, 0);
2941 macro_ptr = str.str;
2942 macro_ptr_allocated = str.str;
2943 goto redo;
2947 } else {
2948 if (tok == 0) {
2949 /* end of macro or end of unget buffer */
2950 if (unget_buffer_enabled) {
2951 macro_ptr = unget_saved_macro_ptr;
2952 unget_buffer_enabled = 0;
2953 } else {
2954 /* end of macro string: free it */
2955 tok_str_free(macro_ptr_allocated);
2956 macro_ptr_allocated = NULL;
2957 macro_ptr = NULL;
2959 goto redo;
2960 } else if (tok == TOK_NOSUBST) {
2961 /* discard preprocessor's nosubst markers */
2962 goto redo;
2966 /* convert preprocessor tokens into C tokens */
2967 if (tok == TOK_PPNUM &&
2968 (parse_flags & PARSE_FLAG_TOK_NUM)) {
2969 parse_number((char *)tokc.cstr->data);
2973 /* push back current token and set current token to 'last_tok'. Only
2974 identifier case handled for labels. */
2975 ST_INLN void unget_tok(int last_tok)
2977 int i, n;
2978 int *q;
2979 unget_saved_macro_ptr = macro_ptr;
2980 unget_buffer_enabled = 1;
2981 q = unget_saved_buffer;
2982 macro_ptr = q;
2983 *q++ = tok;
2984 n = tok_ext_size(tok) - 1;
2985 for(i=0;i<n;i++)
2986 *q++ = tokc.tab[i];
2987 *q = 0; /* end of token string */
2988 tok = last_tok;
2992 /* better than nothing, but needs extension to handle '-E' option
2993 correctly too */
2994 ST_FUNC void preprocess_init(TCCState *s1)
2996 s1->include_stack_ptr = s1->include_stack;
2997 /* XXX: move that before to avoid having to initialize
2998 file->ifdef_stack_ptr ? */
2999 s1->ifdef_stack_ptr = s1->ifdef_stack;
3000 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3002 /* XXX: not ANSI compliant: bound checking says error */
3003 vtop = vstack - 1;
3004 s1->pack_stack[0] = 0;
3005 s1->pack_stack_ptr = s1->pack_stack;
3008 ST_FUNC void preprocess_new()
3010 int i, c;
3011 const char *p, *r;
3012 TokenSym *ts;
3014 /* init isid table */
3015 for(i=CH_EOF;i<256;i++)
3016 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
3018 /* add all tokens */
3019 table_ident = NULL;
3020 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3022 tok_ident = TOK_IDENT;
3023 p = tcc_keywords;
3024 while (*p) {
3025 r = p;
3026 for(;;) {
3027 c = *r++;
3028 if (c == '\0')
3029 break;
3031 ts = tok_alloc(p, r - p - 1);
3032 p = r;
3036 /* Preprocess the current file */
3037 ST_FUNC int tcc_preprocess(TCCState *s1)
3039 Sym *define_start;
3041 BufferedFile *file_ref, **iptr, **iptr_new;
3042 int token_seen, line_ref, d;
3043 const char *s;
3045 preprocess_init(s1);
3046 define_start = define_stack;
3047 ch = file->buf_ptr[0];
3048 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3049 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
3050 PARSE_FLAG_LINEFEED | PARSE_FLAG_SPACES;
3051 token_seen = 0;
3052 line_ref = 0;
3053 file_ref = NULL;
3054 iptr = s1->include_stack_ptr;
3056 for (;;) {
3057 next();
3058 if (tok == TOK_EOF) {
3059 break;
3060 } else if (file != file_ref) {
3061 goto print_line;
3062 } else if (tok == TOK_LINEFEED) {
3063 if (!token_seen)
3064 continue;
3065 ++line_ref;
3066 token_seen = 0;
3067 } else if (!token_seen) {
3068 d = file->line_num - line_ref;
3069 if (file != file_ref || d < 0 || d >= 8) {
3070 print_line:
3071 iptr_new = s1->include_stack_ptr;
3072 s = iptr_new > iptr ? " 1"
3073 : iptr_new < iptr ? " 2"
3074 : iptr_new > s1->include_stack ? " 3"
3075 : ""
3077 iptr = iptr_new;
3078 fprintf(s1->outfile, "# %d \"%s\"%s\n", file->line_num, file->filename, s);
3079 } else {
3080 while (d)
3081 fputs("\n", s1->outfile), --d;
3083 line_ref = (file_ref = file)->line_num;
3084 token_seen = tok != TOK_LINEFEED;
3085 if (!token_seen)
3086 continue;
3088 fputs(get_tok_str(tok, &tokc), s1->outfile);
3090 free_defines(define_start);
3091 return 0;