Revert the many un-reviewed commits starting from early April
[tinycc.git] / tccpp.c
blob2da65cd2204939d2d1250755d74b0dad3ecd1037
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 /* outdated -- gr
74 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
75 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
76 */{
77 '<','=', TOK_LE,
78 '>','=', TOK_GE,
79 '!','=', TOK_NE,
80 '&','&', TOK_LAND,
81 '|','|', TOK_LOR,
82 '+','+', TOK_INC,
83 '-','-', TOK_DEC,
84 '=','=', TOK_EQ,
85 '<','<', TOK_SHL,
86 '>','>', TOK_SAR,
87 '+','=', TOK_A_ADD,
88 '-','=', TOK_A_SUB,
89 '*','=', TOK_A_MUL,
90 '/','=', TOK_A_DIV,
91 '%','=', TOK_A_MOD,
92 '&','=', TOK_A_AND,
93 '^','=', TOK_A_XOR,
94 '|','=', TOK_A_OR,
95 '-','>', TOK_ARROW,
96 '.','.', 0xa8, // C++ token ?
97 '#','#', TOK_TWOSHARPS,
101 struct macro_level {
102 struct macro_level *prev;
103 const int *p;
106 static void next_nomacro_spc(void);
107 static void macro_subst(
108 TokenString *tok_str,
109 Sym **nested_list,
110 const int *macro_str,
111 struct macro_level **can_read_stream
114 ST_FUNC void skip(int c)
116 if (tok != c)
117 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
118 next();
121 ST_FUNC void expect(const char *msg)
123 tcc_error("%s expected", msg);
126 /* ------------------------------------------------------------------------- */
127 /* CString handling */
128 static void cstr_realloc(CString *cstr, int new_size)
130 int size;
131 void *data;
133 size = cstr->size_allocated;
134 if (size == 0)
135 size = 8; /* no need to allocate a too small first string */
136 while (size < new_size)
137 size = size * 2;
138 data = tcc_realloc(cstr->data_allocated, size);
139 cstr->data_allocated = data;
140 cstr->size_allocated = size;
141 cstr->data = data;
144 /* add a byte */
145 ST_FUNC void cstr_ccat(CString *cstr, int ch)
147 int size;
148 size = cstr->size + 1;
149 if (size > cstr->size_allocated)
150 cstr_realloc(cstr, size);
151 ((unsigned char *)cstr->data)[size - 1] = ch;
152 cstr->size = size;
155 ST_FUNC void cstr_cat(CString *cstr, const char *str)
157 int c;
158 for(;;) {
159 c = *str;
160 if (c == '\0')
161 break;
162 cstr_ccat(cstr, c);
163 str++;
167 /* add a wide char */
168 ST_FUNC void cstr_wccat(CString *cstr, int ch)
170 int size;
171 size = cstr->size + sizeof(nwchar_t);
172 if (size > cstr->size_allocated)
173 cstr_realloc(cstr, size);
174 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
175 cstr->size = size;
178 ST_FUNC void cstr_new(CString *cstr)
180 memset(cstr, 0, sizeof(CString));
183 /* free string and reset it to NULL */
184 ST_FUNC void cstr_free(CString *cstr)
186 tcc_free(cstr->data_allocated);
187 cstr_new(cstr);
190 /* reset string to empty */
191 ST_FUNC void cstr_reset(CString *cstr)
193 cstr->size = 0;
196 /* XXX: unicode ? */
197 static void add_char(CString *cstr, int c)
199 if (c == '\'' || c == '\"' || c == '\\') {
200 /* XXX: could be more precise if char or string */
201 cstr_ccat(cstr, '\\');
203 if (c >= 32 && c <= 126) {
204 cstr_ccat(cstr, c);
205 } else {
206 cstr_ccat(cstr, '\\');
207 if (c == '\n') {
208 cstr_ccat(cstr, 'n');
209 } else {
210 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
211 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
212 cstr_ccat(cstr, '0' + (c & 7));
217 /* ------------------------------------------------------------------------- */
218 /* allocate a new token */
219 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
221 TokenSym *ts, **ptable;
222 int i;
224 if (tok_ident >= SYM_FIRST_ANOM)
225 tcc_error("memory full (symbols)");
227 /* expand token table if needed */
228 i = tok_ident - TOK_IDENT;
229 if ((i % TOK_ALLOC_INCR) == 0) {
230 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
231 table_ident = ptable;
234 ts = tcc_malloc(sizeof(TokenSym) + len);
235 table_ident[i] = ts;
236 ts->tok = tok_ident++;
237 ts->sym_define = NULL;
238 ts->sym_label = NULL;
239 ts->sym_struct = NULL;
240 ts->sym_identifier = NULL;
241 ts->len = len;
242 ts->hash_next = NULL;
243 memcpy(ts->str, str, len);
244 ts->str[len] = '\0';
245 *pts = ts;
246 return ts;
249 #define TOK_HASH_INIT 1
250 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
252 /* find a token and add it if not found */
253 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
255 TokenSym *ts, **pts;
256 int i;
257 unsigned int h;
259 h = TOK_HASH_INIT;
260 for(i=0;i<len;i++)
261 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
262 h &= (TOK_HASH_SIZE - 1);
264 pts = &hash_ident[h];
265 for(;;) {
266 ts = *pts;
267 if (!ts)
268 break;
269 if (ts->len == len && !memcmp(ts->str, str, len))
270 return ts;
271 pts = &(ts->hash_next);
273 return tok_alloc_new(pts, str, len);
276 /* XXX: buffer overflow */
277 /* XXX: float tokens */
278 ST_FUNC char *get_tok_str(int v, CValue *cv)
280 static char buf[STRING_MAX_SIZE + 1];
281 static CString cstr_buf;
282 CString *cstr;
283 char *p;
284 int i, len;
286 /* NOTE: to go faster, we give a fixed buffer for small strings */
287 cstr_reset(&cstr_buf);
288 cstr_buf.data = buf;
289 cstr_buf.size_allocated = sizeof(buf);
290 p = buf;
292 /* just an explanation, should never happen:
293 if (v <= TOK_LINENUM && v >= TOK_CINT && cv == NULL)
294 tcc_error("internal error: get_tok_str"); */
296 switch(v) {
297 case TOK_CINT:
298 case TOK_CUINT:
299 /* XXX: not quite exact, but only useful for testing */
300 sprintf(p, "%u", cv->ui);
301 break;
302 case TOK_CLLONG:
303 case TOK_CULLONG:
304 /* XXX: not quite exact, but only useful for testing */
305 #ifdef _WIN32
306 sprintf(p, "%u", (unsigned)cv->ull);
307 #else
308 sprintf(p, "%llu", cv->ull);
309 #endif
310 break;
311 case TOK_LCHAR:
312 cstr_ccat(&cstr_buf, 'L');
313 case TOK_CCHAR:
314 cstr_ccat(&cstr_buf, '\'');
315 add_char(&cstr_buf, cv->i);
316 cstr_ccat(&cstr_buf, '\'');
317 cstr_ccat(&cstr_buf, '\0');
318 break;
319 case TOK_PPNUM:
320 cstr = cv->cstr;
321 len = cstr->size - 1;
322 for(i=0;i<len;i++)
323 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
324 cstr_ccat(&cstr_buf, '\0');
325 break;
326 case TOK_LSTR:
327 cstr_ccat(&cstr_buf, 'L');
328 case TOK_STR:
329 cstr = cv->cstr;
330 cstr_ccat(&cstr_buf, '\"');
331 if (v == TOK_STR) {
332 len = cstr->size - 1;
333 for(i=0;i<len;i++)
334 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
335 } else {
336 len = (cstr->size / sizeof(nwchar_t)) - 1;
337 for(i=0;i<len;i++)
338 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
340 cstr_ccat(&cstr_buf, '\"');
341 cstr_ccat(&cstr_buf, '\0');
342 break;
344 case TOK_CFLOAT:
345 case TOK_CDOUBLE:
346 case TOK_CLDOUBLE:
347 case TOK_LINENUM:
348 return NULL; /* should not happen */
350 /* above tokens have value, the ones below don't */
352 case TOK_LT:
353 v = '<';
354 goto addv;
355 case TOK_GT:
356 v = '>';
357 goto addv;
358 case TOK_DOTS:
359 return strcpy(p, "...");
360 case TOK_A_SHL:
361 return strcpy(p, "<<=");
362 case TOK_A_SAR:
363 return strcpy(p, ">>=");
364 default:
365 if (v < TOK_IDENT) {
366 /* search in two bytes table */
367 const unsigned char *q = tok_two_chars;
368 while (*q) {
369 if (q[2] == v) {
370 *p++ = q[0];
371 *p++ = q[1];
372 *p = '\0';
373 return buf;
375 q += 3;
377 addv:
378 *p++ = v;
379 *p = '\0';
380 } else if (v < tok_ident) {
381 return table_ident[v - TOK_IDENT]->str;
382 } else if (v >= SYM_FIRST_ANOM) {
383 /* special name for anonymous symbol */
384 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
385 } else {
386 /* should never happen */
387 return NULL;
389 break;
391 return cstr_buf.data;
394 /* fill input buffer and peek next char */
395 static int tcc_peekc_slow(BufferedFile *bf)
397 int len;
398 /* only tries to read if really end of buffer */
399 if (bf->buf_ptr >= bf->buf_end) {
400 if (bf->fd != -1) {
401 #if defined(PARSE_DEBUG)
402 len = 8;
403 #else
404 len = IO_BUF_SIZE;
405 #endif
406 len = read(bf->fd, bf->buffer, len);
407 if (len < 0)
408 len = 0;
409 } else {
410 len = 0;
412 total_bytes += len;
413 bf->buf_ptr = bf->buffer;
414 bf->buf_end = bf->buffer + len;
415 *bf->buf_end = CH_EOB;
417 if (bf->buf_ptr < bf->buf_end) {
418 return bf->buf_ptr[0];
419 } else {
420 bf->buf_ptr = bf->buf_end;
421 return CH_EOF;
425 /* return the current character, handling end of block if necessary
426 (but not stray) */
427 ST_FUNC int handle_eob(void)
429 return tcc_peekc_slow(file);
432 /* read next char from current input file and handle end of input buffer */
433 ST_INLN void inp(void)
435 ch = *(++(file->buf_ptr));
436 /* end of buffer/file handling */
437 if (ch == CH_EOB)
438 ch = handle_eob();
441 /* handle '\[\r]\n' */
442 static int handle_stray_noerror(void)
444 while (ch == '\\') {
445 inp();
446 if (ch == '\n') {
447 file->line_num++;
448 inp();
449 } else if (ch == '\r') {
450 inp();
451 if (ch != '\n')
452 goto fail;
453 file->line_num++;
454 inp();
455 } else {
456 fail:
457 return 1;
460 return 0;
463 static void handle_stray(void)
465 if (handle_stray_noerror())
466 tcc_error("stray '\\' in program");
469 /* skip the stray and handle the \\n case. Output an error if
470 incorrect char after the stray */
471 static int handle_stray1(uint8_t *p)
473 int c;
475 if (p >= file->buf_end) {
476 file->buf_ptr = p;
477 c = handle_eob();
478 p = file->buf_ptr;
479 if (c == '\\')
480 goto parse_stray;
481 } else {
482 parse_stray:
483 file->buf_ptr = p;
484 ch = *p;
485 handle_stray();
486 p = file->buf_ptr;
487 c = *p;
489 return c;
492 /* handle just the EOB case, but not stray */
493 #define PEEKC_EOB(c, p)\
495 p++;\
496 c = *p;\
497 if (c == '\\') {\
498 file->buf_ptr = p;\
499 c = handle_eob();\
500 p = file->buf_ptr;\
504 /* handle the complicated stray case */
505 #define PEEKC(c, p)\
507 p++;\
508 c = *p;\
509 if (c == '\\') {\
510 c = handle_stray1(p);\
511 p = file->buf_ptr;\
515 /* input with '\[\r]\n' handling. Note that this function cannot
516 handle other characters after '\', so you cannot call it inside
517 strings or comments */
518 ST_FUNC void minp(void)
520 inp();
521 if (ch == '\\')
522 handle_stray();
526 /* single line C++ comments */
527 static uint8_t *parse_line_comment(uint8_t *p)
529 int c;
531 p++;
532 for(;;) {
533 c = *p;
534 redo:
535 if (c == '\n' || c == CH_EOF) {
536 break;
537 } else if (c == '\\') {
538 file->buf_ptr = p;
539 c = handle_eob();
540 p = file->buf_ptr;
541 if (c == '\\') {
542 PEEKC_EOB(c, p);
543 if (c == '\n') {
544 file->line_num++;
545 PEEKC_EOB(c, p);
546 } else if (c == '\r') {
547 PEEKC_EOB(c, p);
548 if (c == '\n') {
549 file->line_num++;
550 PEEKC_EOB(c, p);
553 } else {
554 goto redo;
556 } else {
557 p++;
560 return p;
563 /* C comments */
564 ST_FUNC uint8_t *parse_comment(uint8_t *p)
566 int c;
568 p++;
569 for(;;) {
570 /* fast skip loop */
571 for(;;) {
572 c = *p;
573 if (c == '\n' || c == '*' || c == '\\')
574 break;
575 p++;
576 c = *p;
577 if (c == '\n' || c == '*' || c == '\\')
578 break;
579 p++;
581 /* now we can handle all the cases */
582 if (c == '\n') {
583 file->line_num++;
584 p++;
585 } else if (c == '*') {
586 p++;
587 for(;;) {
588 c = *p;
589 if (c == '*') {
590 p++;
591 } else if (c == '/') {
592 goto end_of_comment;
593 } else if (c == '\\') {
594 file->buf_ptr = p;
595 c = handle_eob();
596 p = file->buf_ptr;
597 if (c == '\\') {
598 /* skip '\[\r]\n', otherwise just skip the stray */
599 while (c == '\\') {
600 PEEKC_EOB(c, p);
601 if (c == '\n') {
602 file->line_num++;
603 PEEKC_EOB(c, p);
604 } else if (c == '\r') {
605 PEEKC_EOB(c, p);
606 if (c == '\n') {
607 file->line_num++;
608 PEEKC_EOB(c, p);
610 } else {
611 goto after_star;
615 } else {
616 break;
619 after_star: ;
620 } else {
621 /* stray, eob or eof */
622 file->buf_ptr = p;
623 c = handle_eob();
624 p = file->buf_ptr;
625 if (c == CH_EOF) {
626 tcc_error("unexpected end of file in comment");
627 } else if (c == '\\') {
628 p++;
632 end_of_comment:
633 p++;
634 return p;
637 #define cinp minp
639 static inline void skip_spaces(void)
641 while (is_space(ch))
642 cinp();
645 static inline int check_space(int t, int *spc)
647 if (is_space(t)) {
648 if (*spc)
649 return 1;
650 *spc = 1;
651 } else
652 *spc = 0;
653 return 0;
656 /* parse a string without interpreting escapes */
657 static uint8_t *parse_pp_string(uint8_t *p,
658 int sep, CString *str)
660 int c;
661 p++;
662 for(;;) {
663 c = *p;
664 if (c == sep) {
665 break;
666 } else if (c == '\\') {
667 file->buf_ptr = p;
668 c = handle_eob();
669 p = file->buf_ptr;
670 if (c == CH_EOF) {
671 unterminated_string:
672 /* XXX: indicate line number of start of string */
673 tcc_error("missing terminating %c character", sep);
674 } else if (c == '\\') {
675 /* escape : just skip \[\r]\n */
676 PEEKC_EOB(c, p);
677 if (c == '\n') {
678 file->line_num++;
679 p++;
680 } else if (c == '\r') {
681 PEEKC_EOB(c, p);
682 if (c != '\n')
683 expect("'\n' after '\r'");
684 file->line_num++;
685 p++;
686 } else if (c == CH_EOF) {
687 goto unterminated_string;
688 } else {
689 if (str) {
690 cstr_ccat(str, '\\');
691 cstr_ccat(str, c);
693 p++;
696 } else if (c == '\n') {
697 file->line_num++;
698 goto add_char;
699 } else if (c == '\r') {
700 PEEKC_EOB(c, p);
701 if (c != '\n') {
702 if (str)
703 cstr_ccat(str, '\r');
704 } else {
705 file->line_num++;
706 goto add_char;
708 } else {
709 add_char:
710 if (str)
711 cstr_ccat(str, c);
712 p++;
715 p++;
716 return p;
719 /* skip block of text until #else, #elif or #endif. skip also pairs of
720 #if/#endif */
721 static void preprocess_skip(void)
723 int a, start_of_line, c, in_warn_or_error;
724 uint8_t *p;
726 p = file->buf_ptr;
727 a = 0;
728 redo_start:
729 start_of_line = 1;
730 in_warn_or_error = 0;
731 for(;;) {
732 redo_no_start:
733 c = *p;
734 switch(c) {
735 case ' ':
736 case '\t':
737 case '\f':
738 case '\v':
739 case '\r':
740 p++;
741 goto redo_no_start;
742 case '\n':
743 file->line_num++;
744 p++;
745 goto redo_start;
746 case '\\':
747 file->buf_ptr = p;
748 c = handle_eob();
749 if (c == CH_EOF) {
750 expect("#endif");
751 } else if (c == '\\') {
752 ch = file->buf_ptr[0];
753 handle_stray_noerror();
755 p = file->buf_ptr;
756 goto redo_no_start;
757 /* skip strings */
758 case '\"':
759 case '\'':
760 if (in_warn_or_error)
761 goto _default;
762 p = parse_pp_string(p, c, NULL);
763 break;
764 /* skip comments */
765 case '/':
766 if (in_warn_or_error)
767 goto _default;
768 file->buf_ptr = p;
769 ch = *p;
770 minp();
771 p = file->buf_ptr;
772 if (ch == '*') {
773 p = parse_comment(p);
774 } else if (ch == '/') {
775 p = parse_line_comment(p);
777 break;
778 case '#':
779 p++;
780 if (start_of_line) {
781 file->buf_ptr = p;
782 next_nomacro();
783 p = file->buf_ptr;
784 if (a == 0 &&
785 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
786 goto the_end;
787 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
788 a++;
789 else if (tok == TOK_ENDIF)
790 a--;
791 else if( tok == TOK_ERROR || tok == TOK_WARNING)
792 in_warn_or_error = 1;
793 else if (tok == TOK_LINEFEED)
794 goto redo_start;
796 break;
797 _default:
798 default:
799 p++;
800 break;
802 start_of_line = 0;
804 the_end: ;
805 file->buf_ptr = p;
808 /* ParseState handling */
810 /* XXX: currently, no include file info is stored. Thus, we cannot display
811 accurate messages if the function or data definition spans multiple
812 files */
814 /* save current parse state in 's' */
815 ST_FUNC void save_parse_state(ParseState *s)
817 s->line_num = file->line_num;
818 s->macro_ptr = macro_ptr;
819 s->tok = tok;
820 s->tokc = tokc;
823 /* restore parse state from 's' */
824 ST_FUNC void restore_parse_state(ParseState *s)
826 file->line_num = s->line_num;
827 macro_ptr = s->macro_ptr;
828 tok = s->tok;
829 tokc = s->tokc;
832 /* return the number of additional 'ints' necessary to store the
833 token */
834 static inline int tok_ext_size(int t)
836 switch(t) {
837 /* 4 bytes */
838 case TOK_CINT:
839 case TOK_CUINT:
840 case TOK_CCHAR:
841 case TOK_LCHAR:
842 case TOK_CFLOAT:
843 case TOK_LINENUM:
844 return 1;
845 case TOK_STR:
846 case TOK_LSTR:
847 case TOK_PPNUM:
848 tcc_error("unsupported token");
849 return 1;
850 case TOK_CDOUBLE:
851 case TOK_CLLONG:
852 case TOK_CULLONG:
853 return 2;
854 case TOK_CLDOUBLE:
855 return LDOUBLE_SIZE / 4;
856 default:
857 return 0;
861 /* token string handling */
863 ST_INLN void tok_str_new(TokenString *s)
865 s->str = NULL;
866 s->len = 0;
867 s->allocated_len = 0;
868 s->last_line_num = -1;
871 ST_FUNC void tok_str_free(int *str)
873 tcc_free(str);
876 static int *tok_str_realloc(TokenString *s)
878 int *str, len;
880 if (s->allocated_len == 0) {
881 len = 8;
882 } else {
883 len = s->allocated_len * 2;
885 str = tcc_realloc(s->str, len * sizeof(int));
886 s->allocated_len = len;
887 s->str = str;
888 return str;
891 ST_FUNC void tok_str_add(TokenString *s, int t)
893 int len, *str;
895 len = s->len;
896 str = s->str;
897 if (len >= s->allocated_len)
898 str = tok_str_realloc(s);
899 str[len++] = t;
900 s->len = len;
903 static void tok_str_add2(TokenString *s, int t, CValue *cv)
905 int len, *str;
907 len = s->len;
908 str = s->str;
910 /* allocate space for worst case */
911 if (len + TOK_MAX_SIZE > s->allocated_len)
912 str = tok_str_realloc(s);
913 str[len++] = t;
914 switch(t) {
915 case TOK_CINT:
916 case TOK_CUINT:
917 case TOK_CCHAR:
918 case TOK_LCHAR:
919 case TOK_CFLOAT:
920 case TOK_LINENUM:
921 str[len++] = cv->tab[0];
922 break;
923 case TOK_PPNUM:
924 case TOK_STR:
925 case TOK_LSTR:
927 int nb_words;
928 CString *cstr;
930 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
931 while ((len + nb_words) > s->allocated_len)
932 str = tok_str_realloc(s);
933 cstr = (CString *)(str + len);
934 cstr->data = NULL;
935 cstr->size = cv->cstr->size;
936 cstr->data_allocated = NULL;
937 cstr->size_allocated = cstr->size;
938 memcpy((char *)cstr + sizeof(CString),
939 cv->cstr->data, cstr->size);
940 len += nb_words;
942 break;
943 case TOK_CDOUBLE:
944 case TOK_CLLONG:
945 case TOK_CULLONG:
946 #if LDOUBLE_SIZE == 8
947 case TOK_CLDOUBLE:
948 #endif
949 str[len++] = cv->tab[0];
950 str[len++] = cv->tab[1];
951 break;
952 #if LDOUBLE_SIZE == 12
953 case TOK_CLDOUBLE:
954 str[len++] = cv->tab[0];
955 str[len++] = cv->tab[1];
956 str[len++] = cv->tab[2];
957 #elif LDOUBLE_SIZE == 16
958 case TOK_CLDOUBLE:
959 str[len++] = cv->tab[0];
960 str[len++] = cv->tab[1];
961 str[len++] = cv->tab[2];
962 str[len++] = cv->tab[3];
963 #elif LDOUBLE_SIZE != 8
964 #error add long double size support
965 #endif
966 break;
967 default:
968 break;
970 s->len = len;
973 /* add the current parse token in token string 's' */
974 ST_FUNC void tok_str_add_tok(TokenString *s)
976 CValue cval;
978 /* save line number info */
979 if (file->line_num != s->last_line_num) {
980 s->last_line_num = file->line_num;
981 cval.i = s->last_line_num;
982 tok_str_add2(s, TOK_LINENUM, &cval);
984 tok_str_add2(s, tok, &tokc);
987 /* get a token from an integer array and increment pointer
988 accordingly. we code it as a macro to avoid pointer aliasing. */
989 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
991 const int *p = *pp;
992 int n, *tab;
994 tab = cv->tab;
995 switch(*t = *p++) {
996 case TOK_CINT:
997 case TOK_CUINT:
998 case TOK_CCHAR:
999 case TOK_LCHAR:
1000 case TOK_CFLOAT:
1001 case TOK_LINENUM:
1002 tab[0] = *p++;
1003 break;
1004 case TOK_STR:
1005 case TOK_LSTR:
1006 case TOK_PPNUM:
1007 cv->cstr = (CString *)p;
1008 cv->cstr->data = (char *)p + sizeof(CString);
1009 p += (sizeof(CString) + cv->cstr->size + 3) >> 2;
1010 break;
1011 case TOK_CDOUBLE:
1012 case TOK_CLLONG:
1013 case TOK_CULLONG:
1014 n = 2;
1015 goto copy;
1016 case TOK_CLDOUBLE:
1017 #if LDOUBLE_SIZE == 16
1018 n = 4;
1019 #elif LDOUBLE_SIZE == 12
1020 n = 3;
1021 #elif LDOUBLE_SIZE == 8
1022 n = 2;
1023 #else
1024 # error add long double size support
1025 #endif
1026 copy:
1028 *tab++ = *p++;
1029 while (--n);
1030 break;
1031 default:
1032 break;
1034 *pp = p;
1037 static int macro_is_equal(const int *a, const int *b)
1039 char buf[STRING_MAX_SIZE + 1];
1040 CValue cv;
1041 int t;
1042 while (*a && *b) {
1043 TOK_GET(&t, &a, &cv);
1044 pstrcpy(buf, sizeof buf, get_tok_str(t, &cv));
1045 TOK_GET(&t, &b, &cv);
1046 if (strcmp(buf, get_tok_str(t, &cv)))
1047 return 0;
1049 return !(*a || *b);
1052 /* defines handling */
1053 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1055 Sym *s;
1057 s = define_find(v);
1058 if (s && !macro_is_equal(s->d, str))
1059 tcc_warning("%s redefined", get_tok_str(v, NULL));
1061 s = sym_push2(&define_stack, v, macro_type, 0);
1062 s->d = str;
1063 s->next = first_arg;
1064 table_ident[v - TOK_IDENT]->sym_define = s;
1067 /* undefined a define symbol. Its name is just set to zero */
1068 ST_FUNC void define_undef(Sym *s)
1070 int v;
1071 v = s->v;
1072 if (v >= TOK_IDENT && v < tok_ident)
1073 table_ident[v - TOK_IDENT]->sym_define = NULL;
1074 s->v = 0;
1077 ST_INLN Sym *define_find(int v)
1079 v -= TOK_IDENT;
1080 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1081 return NULL;
1082 return table_ident[v]->sym_define;
1085 /* free define stack until top reaches 'b' */
1086 ST_FUNC void free_defines(Sym *b)
1088 Sym *top, *top1;
1089 int v;
1091 top = define_stack;
1092 while (top != b) {
1093 top1 = top->prev;
1094 /* do not free args or predefined defines */
1095 if (top->d)
1096 tok_str_free(top->d);
1097 v = top->v;
1098 if (v >= TOK_IDENT && v < tok_ident)
1099 table_ident[v - TOK_IDENT]->sym_define = NULL;
1100 sym_free(top);
1101 top = top1;
1103 define_stack = b;
1106 /* label lookup */
1107 ST_FUNC Sym *label_find(int v)
1109 v -= TOK_IDENT;
1110 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1111 return NULL;
1112 return table_ident[v]->sym_label;
1115 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1117 Sym *s, **ps;
1118 s = sym_push2(ptop, v, 0, 0);
1119 s->r = flags;
1120 ps = &table_ident[v - TOK_IDENT]->sym_label;
1121 if (ptop == &global_label_stack) {
1122 /* modify the top most local identifier, so that
1123 sym_identifier will point to 's' when popped */
1124 while (*ps != NULL)
1125 ps = &(*ps)->prev_tok;
1127 s->prev_tok = *ps;
1128 *ps = s;
1129 return s;
1132 /* pop labels until element last is reached. Look if any labels are
1133 undefined. Define symbols if '&&label' was used. */
1134 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1136 Sym *s, *s1;
1137 for(s = *ptop; s != slast; s = s1) {
1138 s1 = s->prev;
1139 if (s->r == LABEL_DECLARED) {
1140 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1141 } else if (s->r == LABEL_FORWARD) {
1142 tcc_error("label '%s' used but not defined",
1143 get_tok_str(s->v, NULL));
1144 } else {
1145 if (s->c) {
1146 /* define corresponding symbol. A size of
1147 1 is put. */
1148 put_extern_sym(s, cur_text_section, s->jnext, 1);
1151 /* remove label */
1152 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1153 sym_free(s);
1155 *ptop = slast;
1158 /* eval an expression for #if/#elif */
1159 static int expr_preprocess(void)
1161 int c, t;
1162 TokenString str;
1164 tok_str_new(&str);
1165 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1166 next(); /* do macro subst */
1167 if (tok == TOK_DEFINED) {
1168 next_nomacro();
1169 t = tok;
1170 if (t == '(')
1171 next_nomacro();
1172 c = define_find(tok) != 0;
1173 if (t == '(')
1174 next_nomacro();
1175 tok = TOK_CINT;
1176 tokc.i = c;
1177 } else if (tok >= TOK_IDENT) {
1178 /* if undefined macro */
1179 tok = TOK_CINT;
1180 tokc.i = 0;
1182 tok_str_add_tok(&str);
1184 tok_str_add(&str, -1); /* simulate end of file */
1185 tok_str_add(&str, 0);
1186 /* now evaluate C constant expression */
1187 macro_ptr = str.str;
1188 next();
1189 c = expr_const();
1190 macro_ptr = NULL;
1191 tok_str_free(str.str);
1192 return c != 0;
1195 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1196 static void tok_print(int *str)
1198 int t;
1199 CValue cval;
1201 printf("<");
1202 while (1) {
1203 TOK_GET(&t, &str, &cval);
1204 if (!t)
1205 break;
1206 printf("%s", get_tok_str(t, &cval));
1208 printf(">\n");
1210 #endif
1212 /* parse after #define */
1213 ST_FUNC void parse_define(void)
1215 Sym *s, *first, **ps;
1216 int v, t, varg, is_vaargs, spc, ptok, macro_list_start;
1217 TokenString str;
1219 v = tok;
1220 if (v < TOK_IDENT)
1221 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1222 /* XXX: should check if same macro (ANSI) */
1223 first = NULL;
1224 t = MACRO_OBJ;
1225 /* '(' must be just after macro definition for MACRO_FUNC */
1226 next_nomacro_spc();
1227 if (tok == '(') {
1228 next_nomacro();
1229 ps = &first;
1230 while (tok != ')') {
1231 varg = tok;
1232 next_nomacro();
1233 is_vaargs = 0;
1234 if (varg == TOK_DOTS) {
1235 varg = TOK___VA_ARGS__;
1236 is_vaargs = 1;
1237 } else if (tok == TOK_DOTS && gnu_ext) {
1238 is_vaargs = 1;
1239 next_nomacro();
1241 if (varg < TOK_IDENT)
1242 tcc_error("badly punctuated parameter list");
1243 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1244 *ps = s;
1245 ps = &s->next;
1246 if (tok != ',')
1247 break;
1248 next_nomacro();
1250 if (tok == ')')
1251 next_nomacro_spc();
1252 t = MACRO_FUNC;
1254 tok_str_new(&str);
1255 spc = 2;
1256 /* EOF testing necessary for '-D' handling */
1257 ptok = 0;
1258 macro_list_start = 1;
1259 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1260 if (!macro_list_start && spc == 2 && tok == TOK_TWOSHARPS)
1261 tcc_error("'##' invalid at start of macro");
1262 ptok = tok;
1263 /* remove spaces around ## and after '#' */
1264 if (TOK_TWOSHARPS == tok) {
1265 if (1 == spc)
1266 --str.len;
1267 spc = 2;
1268 } else if ('#' == tok) {
1269 spc = 2;
1270 } else if (check_space(tok, &spc)) {
1271 goto skip;
1273 tok_str_add2(&str, tok, &tokc);
1274 skip:
1275 next_nomacro_spc();
1276 macro_list_start = 0;
1278 if (ptok == TOK_TWOSHARPS)
1279 tcc_error("'##' invalid at end of macro");
1280 if (spc == 1)
1281 --str.len; /* remove trailing space */
1282 tok_str_add(&str, 0);
1283 #ifdef PP_DEBUG
1284 printf("define %s %d: ", get_tok_str(v, NULL), t);
1285 tok_print(str.str);
1286 #endif
1287 define_push(v, t, str.str, first);
1290 static inline int hash_cached_include(const char *filename)
1292 const unsigned char *s;
1293 unsigned int h;
1295 h = TOK_HASH_INIT;
1296 s = (unsigned char *) filename;
1297 while (*s) {
1298 h = TOK_HASH_FUNC(h, *s);
1299 s++;
1301 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1302 return h;
1305 static CachedInclude *search_cached_include(TCCState *s1, const char *filename)
1307 CachedInclude *e;
1308 int i, h;
1309 h = hash_cached_include(filename);
1310 i = s1->cached_includes_hash[h];
1311 for(;;) {
1312 if (i == 0)
1313 break;
1314 e = s1->cached_includes[i - 1];
1315 if (0 == PATHCMP(e->filename, filename))
1316 return e;
1317 i = e->hash_next;
1319 return NULL;
1322 static inline void add_cached_include(TCCState *s1, const char *filename, int ifndef_macro)
1324 CachedInclude *e;
1325 int h;
1327 if (search_cached_include(s1, filename))
1328 return;
1329 #ifdef INC_DEBUG
1330 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
1331 #endif
1332 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1333 strcpy(e->filename, filename);
1334 e->ifndef_macro = ifndef_macro;
1335 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1336 /* add in hash table */
1337 h = hash_cached_include(filename);
1338 e->hash_next = s1->cached_includes_hash[h];
1339 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1342 static void pragma_parse(TCCState *s1)
1344 int val;
1346 next();
1347 if (tok == TOK_pack) {
1349 This may be:
1350 #pragma pack(1) // set
1351 #pragma pack() // reset to default
1352 #pragma pack(push,1) // push & set
1353 #pragma pack(pop) // restore previous
1355 next();
1356 skip('(');
1357 if (tok == TOK_ASM_pop) {
1358 next();
1359 if (s1->pack_stack_ptr <= s1->pack_stack) {
1360 stk_error:
1361 tcc_error("out of pack stack");
1363 s1->pack_stack_ptr--;
1364 } else {
1365 val = 0;
1366 if (tok != ')') {
1367 if (tok == TOK_ASM_push) {
1368 next();
1369 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1370 goto stk_error;
1371 s1->pack_stack_ptr++;
1372 skip(',');
1374 if (tok != TOK_CINT) {
1375 pack_error:
1376 tcc_error("invalid pack pragma");
1378 val = tokc.i;
1379 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1380 goto pack_error;
1381 next();
1383 *s1->pack_stack_ptr = val;
1384 skip(')');
1389 /* is_bof is true if first non space token at beginning of file */
1390 ST_FUNC void preprocess(int is_bof)
1392 TCCState *s1 = tcc_state;
1393 int i, c, n, saved_parse_flags;
1394 char buf[1024], *q;
1395 Sym *s;
1397 saved_parse_flags = parse_flags;
1398 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
1399 PARSE_FLAG_LINEFEED;
1400 next_nomacro();
1401 redo:
1402 switch(tok) {
1403 case TOK_DEFINE:
1404 next_nomacro();
1405 parse_define();
1406 break;
1407 case TOK_UNDEF:
1408 next_nomacro();
1409 s = define_find(tok);
1410 /* undefine symbol by putting an invalid name */
1411 if (s)
1412 define_undef(s);
1413 break;
1414 case TOK_INCLUDE:
1415 case TOK_INCLUDE_NEXT:
1416 ch = file->buf_ptr[0];
1417 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1418 skip_spaces();
1419 if (ch == '<') {
1420 c = '>';
1421 goto read_name;
1422 } else if (ch == '\"') {
1423 c = ch;
1424 read_name:
1425 inp();
1426 q = buf;
1427 while (ch != c && ch != '\n' && ch != CH_EOF) {
1428 if ((q - buf) < sizeof(buf) - 1)
1429 *q++ = ch;
1430 if (ch == '\\') {
1431 if (handle_stray_noerror() == 0)
1432 --q;
1433 } else
1434 inp();
1436 *q = '\0';
1437 minp();
1438 #if 0
1439 /* eat all spaces and comments after include */
1440 /* XXX: slightly incorrect */
1441 while (ch1 != '\n' && ch1 != CH_EOF)
1442 inp();
1443 #endif
1444 } else {
1445 /* computed #include : either we have only strings or
1446 we have anything enclosed in '<>' */
1447 next();
1448 buf[0] = '\0';
1449 if (tok == TOK_STR) {
1450 while (tok != TOK_LINEFEED) {
1451 if (tok != TOK_STR) {
1452 include_syntax:
1453 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1455 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
1456 next();
1458 c = '\"';
1459 } else {
1460 int len;
1461 while (tok != TOK_LINEFEED) {
1462 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1463 next();
1465 len = strlen(buf);
1466 /* check syntax and remove '<>' */
1467 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1468 goto include_syntax;
1469 memmove(buf, buf + 1, len - 2);
1470 buf[len - 2] = '\0';
1471 c = '>';
1475 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1476 tcc_error("#include recursion too deep");
1477 /* store current file in stack, but increment stack later below */
1478 *s1->include_stack_ptr = file;
1480 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
1481 for (i = -2; i < n; ++i) {
1482 char buf1[sizeof file->filename];
1483 CachedInclude *e;
1484 BufferedFile **f;
1485 const char *path;
1487 if (i == -2) {
1488 /* check absolute include path */
1489 if (!IS_ABSPATH(buf))
1490 continue;
1491 buf1[0] = 0;
1492 i = n; /* force end loop */
1494 } else if (i == -1) {
1495 /* search in current dir if "header.h" */
1496 if (c != '\"')
1497 continue;
1498 path = file->filename;
1499 pstrncpy(buf1, path, tcc_basename(path) - path);
1501 } else {
1502 /* search in all the include paths */
1503 if (i < s1->nb_include_paths)
1504 path = s1->include_paths[i];
1505 else
1506 path = s1->sysinclude_paths[i - s1->nb_include_paths];
1507 pstrcpy(buf1, sizeof(buf1), path);
1508 pstrcat(buf1, sizeof(buf1), "/");
1511 pstrcat(buf1, sizeof(buf1), buf);
1513 if (tok == TOK_INCLUDE_NEXT)
1514 for (f = s1->include_stack_ptr; f >= s1->include_stack; --f)
1515 if (0 == PATHCMP((*f)->filename, buf1)) {
1516 #ifdef INC_DEBUG
1517 printf("%s: #include_next skipping %s\n", file->filename, buf1);
1518 #endif
1519 goto include_trynext;
1522 e = search_cached_include(s1, buf1);
1523 if (e && define_find(e->ifndef_macro)) {
1524 /* no need to parse the include because the 'ifndef macro'
1525 is defined */
1526 #ifdef INC_DEBUG
1527 printf("%s: skipping cached %s\n", file->filename, buf1);
1528 #endif
1529 goto include_done;
1532 if (tcc_open(s1, buf1) < 0)
1533 include_trynext:
1534 continue;
1536 #ifdef INC_DEBUG
1537 printf("%s: including %s\n", file->prev->filename, file->filename);
1538 #endif
1539 /* update target deps */
1540 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1541 tcc_strdup(buf1));
1542 /* push current file in stack */
1543 ++s1->include_stack_ptr;
1544 /* add include file debug info */
1545 if (s1->do_debug)
1546 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1547 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1548 ch = file->buf_ptr[0];
1549 goto the_end;
1551 tcc_error("include file '%s' not found", buf);
1552 include_done:
1553 break;
1554 case TOK_IFNDEF:
1555 c = 1;
1556 goto do_ifdef;
1557 case TOK_IF:
1558 c = expr_preprocess();
1559 goto do_if;
1560 case TOK_IFDEF:
1561 c = 0;
1562 do_ifdef:
1563 next_nomacro();
1564 if (tok < TOK_IDENT)
1565 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1566 if (is_bof) {
1567 if (c) {
1568 #ifdef INC_DEBUG
1569 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1570 #endif
1571 file->ifndef_macro = tok;
1574 c = (define_find(tok) != 0) ^ c;
1575 do_if:
1576 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1577 tcc_error("memory full (ifdef)");
1578 *s1->ifdef_stack_ptr++ = c;
1579 goto test_skip;
1580 case TOK_ELSE:
1581 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1582 tcc_error("#else without matching #if");
1583 if (s1->ifdef_stack_ptr[-1] & 2)
1584 tcc_error("#else after #else");
1585 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1586 goto test_else;
1587 case TOK_ELIF:
1588 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1589 tcc_error("#elif without matching #if");
1590 c = s1->ifdef_stack_ptr[-1];
1591 if (c > 1)
1592 tcc_error("#elif after #else");
1593 /* last #if/#elif expression was true: we skip */
1594 if (c == 1)
1595 goto skip;
1596 c = expr_preprocess();
1597 s1->ifdef_stack_ptr[-1] = c;
1598 test_else:
1599 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1600 file->ifndef_macro = 0;
1601 test_skip:
1602 if (!(c & 1)) {
1603 skip:
1604 preprocess_skip();
1605 is_bof = 0;
1606 goto redo;
1608 break;
1609 case TOK_ENDIF:
1610 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1611 tcc_error("#endif without matching #if");
1612 s1->ifdef_stack_ptr--;
1613 /* '#ifndef macro' was at the start of file. Now we check if
1614 an '#endif' is exactly at the end of file */
1615 if (file->ifndef_macro &&
1616 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1617 file->ifndef_macro_saved = file->ifndef_macro;
1618 /* need to set to zero to avoid false matches if another
1619 #ifndef at middle of file */
1620 file->ifndef_macro = 0;
1621 while (tok != TOK_LINEFEED)
1622 next_nomacro();
1623 tok_flags |= TOK_FLAG_ENDIF;
1624 goto the_end;
1626 break;
1627 case TOK_LINE:
1628 next();
1629 if (tok != TOK_CINT)
1630 tcc_error("#line");
1631 file->line_num = tokc.i - 1; /* the line number will be incremented after */
1632 next();
1633 if (tok != TOK_LINEFEED) {
1634 if (tok != TOK_STR)
1635 tcc_error("#line");
1636 pstrcpy(file->filename, sizeof(file->filename),
1637 (char *)tokc.cstr->data);
1639 break;
1640 case TOK_ERROR:
1641 case TOK_WARNING:
1642 c = tok;
1643 ch = file->buf_ptr[0];
1644 skip_spaces();
1645 q = buf;
1646 while (ch != '\n' && ch != CH_EOF) {
1647 if ((q - buf) < sizeof(buf) - 1)
1648 *q++ = ch;
1649 if (ch == '\\') {
1650 if (handle_stray_noerror() == 0)
1651 --q;
1652 } else
1653 inp();
1655 *q = '\0';
1656 if (c == TOK_ERROR)
1657 tcc_error("#error %s", buf);
1658 else
1659 tcc_warning("#warning %s", buf);
1660 break;
1661 case TOK_PRAGMA:
1662 pragma_parse(s1);
1663 break;
1664 default:
1665 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_PPNUM) {
1666 /* '!' is ignored to allow C scripts. numbers are ignored
1667 to emulate cpp behaviour */
1668 } else {
1669 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
1670 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1671 else {
1672 /* this is a gas line comment in an 'S' file. */
1673 file->buf_ptr = parse_line_comment(file->buf_ptr);
1674 goto the_end;
1677 break;
1679 /* ignore other preprocess commands or #! for C scripts */
1680 while (tok != TOK_LINEFEED)
1681 next_nomacro();
1682 the_end:
1683 parse_flags = saved_parse_flags;
1686 /* evaluate escape codes in a string. */
1687 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1689 int c, n;
1690 const uint8_t *p;
1692 p = buf;
1693 for(;;) {
1694 c = *p;
1695 if (c == '\0')
1696 break;
1697 if (c == '\\') {
1698 p++;
1699 /* escape */
1700 c = *p;
1701 switch(c) {
1702 case '0': case '1': case '2': case '3':
1703 case '4': case '5': case '6': case '7':
1704 /* at most three octal digits */
1705 n = c - '0';
1706 p++;
1707 c = *p;
1708 if (isoct(c)) {
1709 n = n * 8 + c - '0';
1710 p++;
1711 c = *p;
1712 if (isoct(c)) {
1713 n = n * 8 + c - '0';
1714 p++;
1717 c = n;
1718 goto add_char_nonext;
1719 case 'x':
1720 case 'u':
1721 case 'U':
1722 p++;
1723 n = 0;
1724 for(;;) {
1725 c = *p;
1726 if (c >= 'a' && c <= 'f')
1727 c = c - 'a' + 10;
1728 else if (c >= 'A' && c <= 'F')
1729 c = c - 'A' + 10;
1730 else if (isnum(c))
1731 c = c - '0';
1732 else
1733 break;
1734 n = n * 16 + c;
1735 p++;
1737 c = n;
1738 goto add_char_nonext;
1739 case 'a':
1740 c = '\a';
1741 break;
1742 case 'b':
1743 c = '\b';
1744 break;
1745 case 'f':
1746 c = '\f';
1747 break;
1748 case 'n':
1749 c = '\n';
1750 break;
1751 case 'r':
1752 c = '\r';
1753 break;
1754 case 't':
1755 c = '\t';
1756 break;
1757 case 'v':
1758 c = '\v';
1759 break;
1760 case 'e':
1761 if (!gnu_ext)
1762 goto invalid_escape;
1763 c = 27;
1764 break;
1765 case '\'':
1766 case '\"':
1767 case '\\':
1768 case '?':
1769 break;
1770 default:
1771 invalid_escape:
1772 if (c >= '!' && c <= '~')
1773 tcc_warning("unknown escape sequence: \'\\%c\'", c);
1774 else
1775 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
1776 break;
1779 p++;
1780 add_char_nonext:
1781 if (!is_long)
1782 cstr_ccat(outstr, c);
1783 else
1784 cstr_wccat(outstr, c);
1786 /* add a trailing '\0' */
1787 if (!is_long)
1788 cstr_ccat(outstr, '\0');
1789 else
1790 cstr_wccat(outstr, '\0');
1793 /* we use 64 bit numbers */
1794 #define BN_SIZE 2
1796 /* bn = (bn << shift) | or_val */
1797 static void bn_lshift(unsigned int *bn, int shift, int or_val)
1799 int i;
1800 unsigned int v;
1801 for(i=0;i<BN_SIZE;i++) {
1802 v = bn[i];
1803 bn[i] = (v << shift) | or_val;
1804 or_val = v >> (32 - shift);
1808 static void bn_zero(unsigned int *bn)
1810 int i;
1811 for(i=0;i<BN_SIZE;i++) {
1812 bn[i] = 0;
1816 /* parse number in null terminated string 'p' and return it in the
1817 current token */
1818 static void parse_number(const char *p)
1820 int b, t, shift, frac_bits, s, exp_val, ch;
1821 char *q;
1822 unsigned int bn[BN_SIZE];
1823 double d;
1825 /* number */
1826 q = token_buf;
1827 ch = *p++;
1828 t = ch;
1829 ch = *p++;
1830 *q++ = t;
1831 b = 10;
1832 if (t == '.') {
1833 goto float_frac_parse;
1834 } else if (t == '0') {
1835 if (ch == 'x' || ch == 'X') {
1836 q--;
1837 ch = *p++;
1838 b = 16;
1839 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
1840 q--;
1841 ch = *p++;
1842 b = 2;
1845 /* parse all digits. cannot check octal numbers at this stage
1846 because of floating point constants */
1847 while (1) {
1848 if (ch >= 'a' && ch <= 'f')
1849 t = ch - 'a' + 10;
1850 else if (ch >= 'A' && ch <= 'F')
1851 t = ch - 'A' + 10;
1852 else if (isnum(ch))
1853 t = ch - '0';
1854 else
1855 break;
1856 if (t >= b)
1857 break;
1858 if (q >= token_buf + STRING_MAX_SIZE) {
1859 num_too_long:
1860 tcc_error("number too long");
1862 *q++ = ch;
1863 ch = *p++;
1865 if (ch == '.' ||
1866 ((ch == 'e' || ch == 'E') && b == 10) ||
1867 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
1868 if (b != 10) {
1869 /* NOTE: strtox should support that for hexa numbers, but
1870 non ISOC99 libcs do not support it, so we prefer to do
1871 it by hand */
1872 /* hexadecimal or binary floats */
1873 /* XXX: handle overflows */
1874 *q = '\0';
1875 if (b == 16)
1876 shift = 4;
1877 else
1878 shift = 2;
1879 bn_zero(bn);
1880 q = token_buf;
1881 while (1) {
1882 t = *q++;
1883 if (t == '\0') {
1884 break;
1885 } else if (t >= 'a') {
1886 t = t - 'a' + 10;
1887 } else if (t >= 'A') {
1888 t = t - 'A' + 10;
1889 } else {
1890 t = t - '0';
1892 bn_lshift(bn, shift, t);
1894 frac_bits = 0;
1895 if (ch == '.') {
1896 ch = *p++;
1897 while (1) {
1898 t = ch;
1899 if (t >= 'a' && t <= 'f') {
1900 t = t - 'a' + 10;
1901 } else if (t >= 'A' && t <= 'F') {
1902 t = t - 'A' + 10;
1903 } else if (t >= '0' && t <= '9') {
1904 t = t - '0';
1905 } else {
1906 break;
1908 if (t >= b)
1909 tcc_error("invalid digit");
1910 bn_lshift(bn, shift, t);
1911 frac_bits += shift;
1912 ch = *p++;
1915 if (ch != 'p' && ch != 'P')
1916 expect("exponent");
1917 ch = *p++;
1918 s = 1;
1919 exp_val = 0;
1920 if (ch == '+') {
1921 ch = *p++;
1922 } else if (ch == '-') {
1923 s = -1;
1924 ch = *p++;
1926 if (ch < '0' || ch > '9')
1927 expect("exponent digits");
1928 while (ch >= '0' && ch <= '9') {
1929 exp_val = exp_val * 10 + ch - '0';
1930 ch = *p++;
1932 exp_val = exp_val * s;
1934 /* now we can generate the number */
1935 /* XXX: should patch directly float number */
1936 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
1937 d = ldexp(d, exp_val - frac_bits);
1938 t = toup(ch);
1939 if (t == 'F') {
1940 ch = *p++;
1941 tok = TOK_CFLOAT;
1942 /* float : should handle overflow */
1943 tokc.f = (float)d;
1944 } else if (t == 'L') {
1945 ch = *p++;
1946 #ifdef TCC_TARGET_PE
1947 tok = TOK_CDOUBLE;
1948 tokc.d = d;
1949 #else
1950 tok = TOK_CLDOUBLE;
1951 /* XXX: not large enough */
1952 tokc.ld = (long double)d;
1953 #endif
1954 } else {
1955 tok = TOK_CDOUBLE;
1956 tokc.d = d;
1958 } else {
1959 /* decimal floats */
1960 if (ch == '.') {
1961 if (q >= token_buf + STRING_MAX_SIZE)
1962 goto num_too_long;
1963 *q++ = ch;
1964 ch = *p++;
1965 float_frac_parse:
1966 while (ch >= '0' && ch <= '9') {
1967 if (q >= token_buf + STRING_MAX_SIZE)
1968 goto num_too_long;
1969 *q++ = ch;
1970 ch = *p++;
1973 if (ch == 'e' || ch == 'E') {
1974 if (q >= token_buf + STRING_MAX_SIZE)
1975 goto num_too_long;
1976 *q++ = ch;
1977 ch = *p++;
1978 if (ch == '-' || ch == '+') {
1979 if (q >= token_buf + STRING_MAX_SIZE)
1980 goto num_too_long;
1981 *q++ = ch;
1982 ch = *p++;
1984 if (ch < '0' || ch > '9')
1985 expect("exponent digits");
1986 while (ch >= '0' && ch <= '9') {
1987 if (q >= token_buf + STRING_MAX_SIZE)
1988 goto num_too_long;
1989 *q++ = ch;
1990 ch = *p++;
1993 *q = '\0';
1994 t = toup(ch);
1995 errno = 0;
1996 if (t == 'F') {
1997 ch = *p++;
1998 tok = TOK_CFLOAT;
1999 tokc.f = strtof(token_buf, NULL);
2000 } else if (t == 'L') {
2001 ch = *p++;
2002 #ifdef TCC_TARGET_PE
2003 tok = TOK_CDOUBLE;
2004 tokc.d = strtod(token_buf, NULL);
2005 #else
2006 tok = TOK_CLDOUBLE;
2007 tokc.ld = strtold(token_buf, NULL);
2008 #endif
2009 } else {
2010 tok = TOK_CDOUBLE;
2011 tokc.d = strtod(token_buf, NULL);
2014 } else {
2015 unsigned long long n, n1;
2016 int lcount, ucount;
2018 /* integer number */
2019 *q = '\0';
2020 q = token_buf;
2021 if (b == 10 && *q == '0') {
2022 b = 8;
2023 q++;
2025 n = 0;
2026 while(1) {
2027 t = *q++;
2028 /* no need for checks except for base 10 / 8 errors */
2029 if (t == '\0') {
2030 break;
2031 } else if (t >= 'a') {
2032 t = t - 'a' + 10;
2033 } else if (t >= 'A') {
2034 t = t - 'A' + 10;
2035 } else {
2036 t = t - '0';
2037 if (t >= b)
2038 tcc_error("invalid digit");
2040 n1 = n;
2041 n = n * b + t;
2042 /* detect overflow */
2043 /* XXX: this test is not reliable */
2044 if (n < n1)
2045 tcc_error("integer constant overflow");
2048 /* XXX: not exactly ANSI compliant */
2049 if ((n & 0xffffffff00000000LL) != 0) {
2050 if ((n >> 63) != 0)
2051 tok = TOK_CULLONG;
2052 else
2053 tok = TOK_CLLONG;
2054 } else if (n > 0x7fffffff) {
2055 tok = TOK_CUINT;
2056 } else {
2057 tok = TOK_CINT;
2059 lcount = 0;
2060 ucount = 0;
2061 for(;;) {
2062 t = toup(ch);
2063 if (t == 'L') {
2064 if (lcount >= 2)
2065 tcc_error("three 'l's in integer constant");
2066 lcount++;
2067 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2068 if (lcount == 2) {
2069 #endif
2070 if (tok == TOK_CINT)
2071 tok = TOK_CLLONG;
2072 else if (tok == TOK_CUINT)
2073 tok = TOK_CULLONG;
2074 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2076 #endif
2077 ch = *p++;
2078 } else if (t == 'U') {
2079 if (ucount >= 1)
2080 tcc_error("two 'u's in integer constant");
2081 ucount++;
2082 if (tok == TOK_CINT)
2083 tok = TOK_CUINT;
2084 else if (tok == TOK_CLLONG)
2085 tok = TOK_CULLONG;
2086 ch = *p++;
2087 } else {
2088 break;
2091 if (tok == TOK_CINT || tok == TOK_CUINT)
2092 tokc.ui = n;
2093 else
2094 tokc.ull = n;
2096 if (ch)
2097 tcc_error("invalid number\n");
2101 #define PARSE2(c1, tok1, c2, tok2) \
2102 case c1: \
2103 PEEKC(c, p); \
2104 if (c == c2) { \
2105 p++; \
2106 tok = tok2; \
2107 } else { \
2108 tok = tok1; \
2110 break;
2112 /* return next token without macro substitution */
2113 static inline void next_nomacro1(void)
2115 int t, c, is_long;
2116 TokenSym *ts;
2117 uint8_t *p, *p1;
2118 unsigned int h;
2120 p = file->buf_ptr;
2121 redo_no_start:
2122 c = *p;
2123 switch(c) {
2124 case ' ':
2125 case '\t':
2126 tok = c;
2127 p++;
2128 goto keep_tok_flags;
2129 case '\f':
2130 case '\v':
2131 case '\r':
2132 p++;
2133 goto redo_no_start;
2134 case '\\':
2135 /* first look if it is in fact an end of buffer */
2136 if (p >= file->buf_end) {
2137 file->buf_ptr = p;
2138 handle_eob();
2139 p = file->buf_ptr;
2140 if (p >= file->buf_end)
2141 goto parse_eof;
2142 else
2143 goto redo_no_start;
2144 } else {
2145 file->buf_ptr = p;
2146 ch = *p;
2147 handle_stray();
2148 p = file->buf_ptr;
2149 goto redo_no_start;
2151 parse_eof:
2153 TCCState *s1 = tcc_state;
2154 if ((parse_flags & PARSE_FLAG_LINEFEED)
2155 && !(tok_flags & TOK_FLAG_EOF)) {
2156 tok_flags |= TOK_FLAG_EOF;
2157 tok = TOK_LINEFEED;
2158 goto keep_tok_flags;
2159 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2160 tok = TOK_EOF;
2161 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2162 tcc_error("missing #endif");
2163 } else if (s1->include_stack_ptr == s1->include_stack) {
2164 /* no include left : end of file. */
2165 tok = TOK_EOF;
2166 } else {
2167 tok_flags &= ~TOK_FLAG_EOF;
2168 /* pop include file */
2170 /* test if previous '#endif' was after a #ifdef at
2171 start of file */
2172 if (tok_flags & TOK_FLAG_ENDIF) {
2173 #ifdef INC_DEBUG
2174 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2175 #endif
2176 add_cached_include(s1, file->filename, file->ifndef_macro_saved);
2177 tok_flags &= ~TOK_FLAG_ENDIF;
2180 /* add end of include file debug info */
2181 if (tcc_state->do_debug) {
2182 put_stabd(N_EINCL, 0, 0);
2184 /* pop include stack */
2185 tcc_close();
2186 s1->include_stack_ptr--;
2187 p = file->buf_ptr;
2188 goto redo_no_start;
2191 break;
2193 case '\n':
2194 file->line_num++;
2195 tok_flags |= TOK_FLAG_BOL;
2196 p++;
2197 maybe_newline:
2198 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2199 goto redo_no_start;
2200 tok = TOK_LINEFEED;
2201 goto keep_tok_flags;
2203 case '#':
2204 /* XXX: simplify */
2205 PEEKC(c, p);
2206 if ((tok_flags & TOK_FLAG_BOL) &&
2207 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2208 file->buf_ptr = p;
2209 preprocess(tok_flags & TOK_FLAG_BOF);
2210 p = file->buf_ptr;
2211 goto maybe_newline;
2212 } else {
2213 if (c == '#') {
2214 p++;
2215 tok = TOK_TWOSHARPS;
2216 } else {
2217 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
2218 p = parse_line_comment(p - 1);
2219 goto redo_no_start;
2220 } else {
2221 tok = '#';
2225 break;
2227 case 'a': case 'b': case 'c': case 'd':
2228 case 'e': case 'f': case 'g': case 'h':
2229 case 'i': case 'j': case 'k': case 'l':
2230 case 'm': case 'n': case 'o': case 'p':
2231 case 'q': case 'r': case 's': case 't':
2232 case 'u': case 'v': case 'w': case 'x':
2233 case 'y': case 'z':
2234 case 'A': case 'B': case 'C': case 'D':
2235 case 'E': case 'F': case 'G': case 'H':
2236 case 'I': case 'J': case 'K':
2237 case 'M': case 'N': case 'O': case 'P':
2238 case 'Q': case 'R': case 'S': case 'T':
2239 case 'U': case 'V': case 'W': case 'X':
2240 case 'Y': case 'Z':
2241 case '_':
2242 parse_ident_fast:
2243 p1 = p;
2244 h = TOK_HASH_INIT;
2245 h = TOK_HASH_FUNC(h, c);
2246 p++;
2247 for(;;) {
2248 c = *p;
2249 if (!isidnum_table[c-CH_EOF])
2250 break;
2251 h = TOK_HASH_FUNC(h, c);
2252 p++;
2254 if (c != '\\') {
2255 TokenSym **pts;
2256 int len;
2258 /* fast case : no stray found, so we have the full token
2259 and we have already hashed it */
2260 len = p - p1;
2261 h &= (TOK_HASH_SIZE - 1);
2262 pts = &hash_ident[h];
2263 for(;;) {
2264 ts = *pts;
2265 if (!ts)
2266 break;
2267 if (ts->len == len && !memcmp(ts->str, p1, len))
2268 goto token_found;
2269 pts = &(ts->hash_next);
2271 ts = tok_alloc_new(pts, (char *) p1, len);
2272 token_found: ;
2273 } else {
2274 /* slower case */
2275 cstr_reset(&tokcstr);
2277 while (p1 < p) {
2278 cstr_ccat(&tokcstr, *p1);
2279 p1++;
2281 p--;
2282 PEEKC(c, p);
2283 parse_ident_slow:
2284 while (isidnum_table[c-CH_EOF]) {
2285 cstr_ccat(&tokcstr, c);
2286 PEEKC(c, p);
2288 ts = tok_alloc(tokcstr.data, tokcstr.size);
2290 tok = ts->tok;
2291 break;
2292 case 'L':
2293 t = p[1];
2294 if (t != '\\' && t != '\'' && t != '\"') {
2295 /* fast case */
2296 goto parse_ident_fast;
2297 } else {
2298 PEEKC(c, p);
2299 if (c == '\'' || c == '\"') {
2300 is_long = 1;
2301 goto str_const;
2302 } else {
2303 cstr_reset(&tokcstr);
2304 cstr_ccat(&tokcstr, 'L');
2305 goto parse_ident_slow;
2308 break;
2309 case '0': case '1': case '2': case '3':
2310 case '4': case '5': case '6': case '7':
2311 case '8': case '9':
2313 cstr_reset(&tokcstr);
2314 /* after the first digit, accept digits, alpha, '.' or sign if
2315 prefixed by 'eEpP' */
2316 parse_num:
2317 for(;;) {
2318 t = c;
2319 cstr_ccat(&tokcstr, c);
2320 PEEKC(c, p);
2321 if (!(isnum(c) || isid(c) || c == '.' ||
2322 ((c == '+' || c == '-') &&
2323 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
2324 break;
2326 /* We add a trailing '\0' to ease parsing */
2327 cstr_ccat(&tokcstr, '\0');
2328 tokc.cstr = &tokcstr;
2329 tok = TOK_PPNUM;
2330 break;
2331 case '.':
2332 /* special dot handling because it can also start a number */
2333 PEEKC(c, p);
2334 if (isnum(c)) {
2335 cstr_reset(&tokcstr);
2336 cstr_ccat(&tokcstr, '.');
2337 goto parse_num;
2338 } else if (c == '.') {
2339 PEEKC(c, p);
2340 if (c != '.')
2341 expect("'.'");
2342 PEEKC(c, p);
2343 tok = TOK_DOTS;
2344 } else {
2345 tok = '.';
2347 break;
2348 case '\'':
2349 case '\"':
2350 is_long = 0;
2351 str_const:
2353 CString str;
2354 int sep;
2356 sep = c;
2358 /* parse the string */
2359 cstr_new(&str);
2360 p = parse_pp_string(p, sep, &str);
2361 cstr_ccat(&str, '\0');
2363 /* eval the escape (should be done as TOK_PPNUM) */
2364 cstr_reset(&tokcstr);
2365 parse_escape_string(&tokcstr, str.data, is_long);
2366 cstr_free(&str);
2368 if (sep == '\'') {
2369 int char_size;
2370 /* XXX: make it portable */
2371 if (!is_long)
2372 char_size = 1;
2373 else
2374 char_size = sizeof(nwchar_t);
2375 if (tokcstr.size <= char_size)
2376 tcc_error("empty character constant");
2377 if (tokcstr.size > 2 * char_size)
2378 tcc_warning("multi-character character constant");
2379 if (!is_long) {
2380 tokc.i = *(int8_t *)tokcstr.data;
2381 tok = TOK_CCHAR;
2382 } else {
2383 tokc.i = *(nwchar_t *)tokcstr.data;
2384 tok = TOK_LCHAR;
2386 } else {
2387 tokc.cstr = &tokcstr;
2388 if (!is_long)
2389 tok = TOK_STR;
2390 else
2391 tok = TOK_LSTR;
2394 break;
2396 case '<':
2397 PEEKC(c, p);
2398 if (c == '=') {
2399 p++;
2400 tok = TOK_LE;
2401 } else if (c == '<') {
2402 PEEKC(c, p);
2403 if (c == '=') {
2404 p++;
2405 tok = TOK_A_SHL;
2406 } else {
2407 tok = TOK_SHL;
2409 } else {
2410 tok = TOK_LT;
2412 break;
2414 case '>':
2415 PEEKC(c, p);
2416 if (c == '=') {
2417 p++;
2418 tok = TOK_GE;
2419 } else if (c == '>') {
2420 PEEKC(c, p);
2421 if (c == '=') {
2422 p++;
2423 tok = TOK_A_SAR;
2424 } else {
2425 tok = TOK_SAR;
2427 } else {
2428 tok = TOK_GT;
2430 break;
2432 case '&':
2433 PEEKC(c, p);
2434 if (c == '&') {
2435 p++;
2436 tok = TOK_LAND;
2437 } else if (c == '=') {
2438 p++;
2439 tok = TOK_A_AND;
2440 } else {
2441 tok = '&';
2443 break;
2445 case '|':
2446 PEEKC(c, p);
2447 if (c == '|') {
2448 p++;
2449 tok = TOK_LOR;
2450 } else if (c == '=') {
2451 p++;
2452 tok = TOK_A_OR;
2453 } else {
2454 tok = '|';
2456 break;
2458 case '+':
2459 PEEKC(c, p);
2460 if (c == '+') {
2461 p++;
2462 tok = TOK_INC;
2463 } else if (c == '=') {
2464 p++;
2465 tok = TOK_A_ADD;
2466 } else {
2467 tok = '+';
2469 break;
2471 case '-':
2472 PEEKC(c, p);
2473 if (c == '-') {
2474 p++;
2475 tok = TOK_DEC;
2476 } else if (c == '=') {
2477 p++;
2478 tok = TOK_A_SUB;
2479 } else if (c == '>') {
2480 p++;
2481 tok = TOK_ARROW;
2482 } else {
2483 tok = '-';
2485 break;
2487 PARSE2('!', '!', '=', TOK_NE)
2488 PARSE2('=', '=', '=', TOK_EQ)
2489 PARSE2('*', '*', '=', TOK_A_MUL)
2490 PARSE2('%', '%', '=', TOK_A_MOD)
2491 PARSE2('^', '^', '=', TOK_A_XOR)
2493 /* comments or operator */
2494 case '/':
2495 PEEKC(c, p);
2496 if (c == '*') {
2497 p = parse_comment(p);
2498 /* comments replaced by a blank */
2499 tok = ' ';
2500 goto keep_tok_flags;
2501 } else if (c == '/') {
2502 p = parse_line_comment(p);
2503 tok = ' ';
2504 goto keep_tok_flags;
2505 } else if (c == '=') {
2506 p++;
2507 tok = TOK_A_DIV;
2508 } else {
2509 tok = '/';
2511 break;
2513 /* simple tokens */
2514 case '(':
2515 case ')':
2516 case '[':
2517 case ']':
2518 case '{':
2519 case '}':
2520 case ',':
2521 case ';':
2522 case ':':
2523 case '?':
2524 case '~':
2525 case '$': /* only used in assembler */
2526 case '@': /* dito */
2527 tok = c;
2528 p++;
2529 break;
2530 default:
2531 tcc_error("unrecognized character \\x%02x", c);
2532 break;
2534 tok_flags = 0;
2535 keep_tok_flags:
2536 file->buf_ptr = p;
2537 #if defined(PARSE_DEBUG)
2538 printf("token = %s\n", get_tok_str(tok, &tokc));
2539 #endif
2542 /* return next token without macro substitution. Can read input from
2543 macro_ptr buffer */
2544 static void next_nomacro_spc(void)
2546 if (macro_ptr) {
2547 redo:
2548 tok = *macro_ptr;
2549 if (tok) {
2550 TOK_GET(&tok, &macro_ptr, &tokc);
2551 if (tok == TOK_LINENUM) {
2552 file->line_num = tokc.i;
2553 goto redo;
2556 } else {
2557 next_nomacro1();
2561 ST_FUNC void next_nomacro(void)
2563 do {
2564 next_nomacro_spc();
2565 } while (is_space(tok));
2568 /* substitute arguments in replacement lists in macro_str by the values in
2569 args (field d) and return allocated string */
2570 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2572 int last_tok, t, spc;
2573 const int *st;
2574 Sym *s;
2575 CValue cval;
2576 TokenString str;
2577 CString cstr;
2579 tok_str_new(&str);
2580 last_tok = 0;
2581 while(1) {
2582 TOK_GET(&t, &macro_str, &cval);
2583 if (!t)
2584 break;
2585 if (t == '#') {
2586 /* stringize */
2587 TOK_GET(&t, &macro_str, &cval);
2588 if (!t)
2589 break;
2590 s = sym_find2(args, t);
2591 if (s) {
2592 cstr_new(&cstr);
2593 st = s->d;
2594 spc = 0;
2595 while (*st) {
2596 TOK_GET(&t, &st, &cval);
2597 if (!check_space(t, &spc))
2598 cstr_cat(&cstr, get_tok_str(t, &cval));
2600 cstr.size -= spc;
2601 cstr_ccat(&cstr, '\0');
2602 #ifdef PP_DEBUG
2603 printf("stringize: %s\n", (char *)cstr.data);
2604 #endif
2605 /* add string */
2606 cval.cstr = &cstr;
2607 tok_str_add2(&str, TOK_STR, &cval);
2608 cstr_free(&cstr);
2609 } else {
2610 tok_str_add2(&str, t, &cval);
2612 } else if (t >= TOK_IDENT) {
2613 s = sym_find2(args, t);
2614 if (s) {
2615 st = s->d;
2616 /* if '##' is present before or after, no arg substitution */
2617 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
2618 /* special case for var arg macros : ## eats the
2619 ',' if empty VA_ARGS variable. */
2620 /* XXX: test of the ',' is not 100%
2621 reliable. should fix it to avoid security
2622 problems */
2623 if (gnu_ext && s->type.t &&
2624 last_tok == TOK_TWOSHARPS &&
2625 str.len >= 2 && str.str[str.len - 2] == ',') {
2626 if (*st == TOK_PLCHLDR) {
2627 /* suppress ',' '##' */
2628 str.len -= 2;
2629 } else {
2630 /* suppress '##' and add variable */
2631 str.len--;
2632 goto add_var;
2634 } else {
2635 int t1;
2636 add_var:
2637 for(;;) {
2638 TOK_GET(&t1, &st, &cval);
2639 if (!t1)
2640 break;
2641 tok_str_add2(&str, t1, &cval);
2644 } else {
2645 /* NOTE: the stream cannot be read when macro
2646 substituing an argument */
2647 macro_subst(&str, nested_list, st, NULL);
2649 } else {
2650 tok_str_add(&str, t);
2652 } else {
2653 tok_str_add2(&str, t, &cval);
2655 last_tok = t;
2657 tok_str_add(&str, 0);
2658 return str.str;
2661 static char const ab_month_name[12][4] =
2663 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2664 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2667 /* do macro substitution of current token with macro 's' and add
2668 result to (tok_str,tok_len). 'nested_list' is the list of all
2669 macros we got inside to avoid recursing. Return non zero if no
2670 substitution needs to be done */
2671 static int macro_subst_tok(TokenString *tok_str,
2672 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
2674 Sym *args, *sa, *sa1;
2675 int mstr_allocated, parlevel, *mstr, t, t1, spc;
2676 const int *p;
2677 TokenString str;
2678 char *cstrval;
2679 CValue cval;
2680 CString cstr;
2681 char buf[32];
2683 /* if symbol is a macro, prepare substitution */
2684 /* special macros */
2685 if (tok == TOK___LINE__) {
2686 snprintf(buf, sizeof(buf), "%d", file->line_num);
2687 cstrval = buf;
2688 t1 = TOK_PPNUM;
2689 goto add_cstr1;
2690 } else if (tok == TOK___FILE__) {
2691 cstrval = file->filename;
2692 goto add_cstr;
2693 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
2694 time_t ti;
2695 struct tm *tm;
2697 time(&ti);
2698 tm = localtime(&ti);
2699 if (tok == TOK___DATE__) {
2700 snprintf(buf, sizeof(buf), "%s %2d %d",
2701 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
2702 } else {
2703 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
2704 tm->tm_hour, tm->tm_min, tm->tm_sec);
2706 cstrval = buf;
2707 add_cstr:
2708 t1 = TOK_STR;
2709 add_cstr1:
2710 cstr_new(&cstr);
2711 cstr_cat(&cstr, cstrval);
2712 cstr_ccat(&cstr, '\0');
2713 cval.cstr = &cstr;
2714 tok_str_add2(tok_str, t1, &cval);
2715 cstr_free(&cstr);
2716 } else {
2717 mstr = s->d;
2718 mstr_allocated = 0;
2719 if (s->type.t == MACRO_FUNC) {
2720 /* NOTE: we do not use next_nomacro to avoid eating the
2721 next token. XXX: find better solution */
2722 redo:
2723 if (macro_ptr) {
2724 p = macro_ptr;
2725 while (is_space(t = *p) || TOK_LINEFEED == t)
2726 ++p;
2727 if (t == 0 && can_read_stream) {
2728 /* end of macro stream: we must look at the token
2729 after in the file */
2730 struct macro_level *ml = *can_read_stream;
2731 macro_ptr = NULL;
2732 if (ml)
2734 macro_ptr = ml->p;
2735 ml->p = NULL;
2736 *can_read_stream = ml -> prev;
2738 /* also, end of scope for nested defined symbol */
2739 (*nested_list)->v = -1;
2740 goto redo;
2742 } else {
2743 ch = file->buf_ptr[0];
2744 while (is_space(ch) || ch == '\n' || ch == '/')
2746 if (ch == '/')
2748 int c;
2749 uint8_t *p = file->buf_ptr;
2750 PEEKC(c, p);
2751 if (c == '*') {
2752 p = parse_comment(p);
2753 file->buf_ptr = p - 1;
2754 } else if (c == '/') {
2755 p = parse_line_comment(p);
2756 file->buf_ptr = p - 1;
2757 } else
2758 break;
2760 cinp();
2762 t = ch;
2764 if (t != '(') /* no macro subst */
2765 return -1;
2767 /* argument macro */
2768 next_nomacro();
2769 next_nomacro();
2770 args = NULL;
2771 sa = s->next;
2772 /* NOTE: empty args are allowed, except if no args */
2773 for(;;) {
2774 /* handle '()' case */
2775 if (!args && !sa && tok == ')')
2776 break;
2777 if (!sa)
2778 tcc_error("macro '%s' used with too many args",
2779 get_tok_str(s->v, 0));
2780 tok_str_new(&str);
2781 parlevel = spc = 0;
2782 /* NOTE: non zero sa->t indicates VA_ARGS */
2783 while ((parlevel > 0 ||
2784 (tok != ')' &&
2785 (tok != ',' || sa->type.t))) &&
2786 tok != -1) {
2787 if (tok == '(')
2788 parlevel++;
2789 else if (tok == ')')
2790 parlevel--;
2791 if (tok == TOK_LINEFEED)
2792 tok = ' ';
2793 if (!check_space(tok, &spc))
2794 tok_str_add2(&str, tok, &tokc);
2795 next_nomacro_spc();
2797 if (!str.len)
2798 tok_str_add(&str, TOK_PLCHLDR);
2799 str.len -= spc;
2800 tok_str_add(&str, 0);
2801 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
2802 sa1->d = str.str;
2803 sa = sa->next;
2804 if (tok == ')') {
2805 /* special case for gcc var args: add an empty
2806 var arg argument if it is omitted */
2807 if (sa && sa->type.t && gnu_ext)
2808 continue;
2809 else
2810 break;
2812 if (tok != ',')
2813 expect(",");
2814 next_nomacro();
2816 if (sa) {
2817 tcc_error("macro '%s' used with too few args",
2818 get_tok_str(s->v, 0));
2821 /* now subst each arg */
2822 mstr = macro_arg_subst(nested_list, mstr, args);
2823 /* free memory */
2824 sa = args;
2825 while (sa) {
2826 sa1 = sa->prev;
2827 tok_str_free(sa->d);
2828 sym_free(sa);
2829 sa = sa1;
2831 mstr_allocated = 1;
2833 sym_push2(nested_list, s->v, 0, 0);
2834 macro_subst(tok_str, nested_list, mstr, can_read_stream);
2835 /* pop nested defined symbol */
2836 sa1 = *nested_list;
2837 *nested_list = sa1->prev;
2838 sym_free(sa1);
2839 if (mstr_allocated)
2840 tok_str_free(mstr);
2842 return 0;
2845 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2846 return the resulting string (which must be freed). */
2847 static inline int *macro_twosharps(const int *macro_str)
2849 const int *ptr;
2850 int t;
2851 TokenString macro_str1;
2852 CString cstr;
2853 int n, start_of_nosubsts;
2855 /* we search the first '##' */
2856 for(ptr = macro_str;;) {
2857 CValue cval;
2858 TOK_GET(&t, &ptr, &cval);
2859 if (t == TOK_TWOSHARPS)
2860 break;
2861 /* nothing more to do if end of string */
2862 if (t == 0)
2863 return NULL;
2866 /* we saw '##', so we need more processing to handle it */
2867 start_of_nosubsts = -1;
2868 tok_str_new(&macro_str1);
2869 for(ptr = macro_str;;) {
2870 TOK_GET(&tok, &ptr, &tokc);
2871 if (tok == 0)
2872 break;
2873 if (tok == TOK_TWOSHARPS)
2874 continue;
2875 if (tok == TOK_NOSUBST && start_of_nosubsts < 0)
2876 start_of_nosubsts = macro_str1.len;
2877 while (*ptr == TOK_TWOSHARPS) {
2878 /* given 'a##b', remove nosubsts preceding 'a' */
2879 if (start_of_nosubsts >= 0)
2880 macro_str1.len = start_of_nosubsts;
2881 /* given 'a##b', skip '##' */
2882 t = *++ptr;
2883 /* given 'a##b', remove nosubsts preceding 'b' */
2884 while (t == TOK_NOSUBST)
2885 t = *++ptr;
2886 if (t && t != TOK_TWOSHARPS) {
2887 CValue cval;
2888 TOK_GET(&t, &ptr, &cval);
2889 /* We concatenate the two tokens */
2890 cstr_new(&cstr);
2891 if (tok != TOK_PLCHLDR)
2892 cstr_cat(&cstr, get_tok_str(tok, &tokc));
2893 n = cstr.size;
2894 if (t != TOK_PLCHLDR || tok == TOK_PLCHLDR)
2895 cstr_cat(&cstr, get_tok_str(t, &cval));
2896 cstr_ccat(&cstr, '\0');
2898 tcc_open_bf(tcc_state, ":paste:", cstr.size);
2899 memcpy(file->buffer, cstr.data, cstr.size);
2900 for (;;) {
2901 next_nomacro1();
2902 if (0 == *file->buf_ptr)
2903 break;
2904 tok_str_add2(&macro_str1, tok, &tokc);
2905 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2906 n, cstr.data, (char*)cstr.data + n);
2908 tcc_close();
2909 cstr_free(&cstr);
2912 if (tok != TOK_NOSUBST) {
2913 tok_str_add2(&macro_str1, tok, &tokc);
2914 tok = ' ';
2915 start_of_nosubsts = -1;
2917 tok_str_add2(&macro_str1, tok, &tokc);
2919 tok_str_add(&macro_str1, 0);
2920 return macro_str1.str;
2924 /* do macro substitution of macro_str and add result to
2925 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2926 inside to avoid recursing. */
2927 static void macro_subst(TokenString *tok_str, Sym **nested_list,
2928 const int *macro_str, struct macro_level ** can_read_stream)
2930 Sym *s;
2931 int *macro_str1;
2932 const int *ptr;
2933 int t, ret, spc;
2934 CValue cval;
2935 struct macro_level ml;
2936 int force_blank;
2938 /* first scan for '##' operator handling */
2939 ptr = macro_str;
2940 macro_str1 = macro_twosharps(ptr);
2942 if (macro_str1)
2943 ptr = macro_str1;
2944 spc = 0;
2945 force_blank = 0;
2947 while (1) {
2948 /* NOTE: ptr == NULL can only happen if tokens are read from
2949 file stream due to a macro function call */
2950 if (ptr == NULL)
2951 break;
2952 TOK_GET(&t, &ptr, &cval);
2953 if (t == 0)
2954 break;
2955 if (t == TOK_NOSUBST) {
2956 /* following token has already been subst'd. just copy it on */
2957 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
2958 TOK_GET(&t, &ptr, &cval);
2959 goto no_subst;
2961 s = define_find(t);
2962 if (s != NULL) {
2963 /* if nested substitution, do nothing */
2964 if (sym_find2(*nested_list, t)) {
2965 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
2966 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
2967 goto no_subst;
2969 ml.p = macro_ptr;
2970 if (can_read_stream)
2971 ml.prev = *can_read_stream, *can_read_stream = &ml;
2972 macro_ptr = (int *)ptr;
2973 tok = t;
2974 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
2975 ptr = (int *)macro_ptr;
2976 macro_ptr = ml.p;
2977 if (can_read_stream && *can_read_stream == &ml)
2978 *can_read_stream = ml.prev;
2979 if (ret != 0)
2980 goto no_subst;
2981 if (parse_flags & PARSE_FLAG_SPACES)
2982 force_blank = 1;
2983 } else {
2984 no_subst:
2985 if (force_blank) {
2986 tok_str_add(tok_str, ' ');
2987 spc = 1;
2988 force_blank = 0;
2990 if (!check_space(t, &spc))
2991 tok_str_add2(tok_str, t, &cval);
2994 if (macro_str1)
2995 tok_str_free(macro_str1);
2998 /* return next token with macro substitution */
2999 ST_FUNC void next(void)
3001 Sym *nested_list, *s;
3002 TokenString str;
3003 struct macro_level *ml;
3005 redo:
3006 if (parse_flags & PARSE_FLAG_SPACES)
3007 next_nomacro_spc();
3008 else
3009 next_nomacro();
3010 if (!macro_ptr) {
3011 /* if not reading from macro substituted string, then try
3012 to substitute macros */
3013 if (tok >= TOK_IDENT &&
3014 (parse_flags & PARSE_FLAG_PREPROCESS)) {
3015 s = define_find(tok);
3016 if (s) {
3017 /* we have a macro: we try to substitute */
3018 tok_str_new(&str);
3019 nested_list = NULL;
3020 ml = NULL;
3021 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
3022 /* substitution done, NOTE: maybe empty */
3023 tok_str_add(&str, 0);
3024 macro_ptr = str.str;
3025 macro_ptr_allocated = str.str;
3026 goto redo;
3030 } else {
3031 if (tok == 0) {
3032 /* end of macro or end of unget buffer */
3033 if (unget_buffer_enabled) {
3034 macro_ptr = unget_saved_macro_ptr;
3035 unget_buffer_enabled = 0;
3036 } else {
3037 /* end of macro string: free it */
3038 tok_str_free(macro_ptr_allocated);
3039 macro_ptr_allocated = NULL;
3040 macro_ptr = NULL;
3042 goto redo;
3043 } else if (tok == TOK_NOSUBST) {
3044 /* discard preprocessor's nosubst markers */
3045 goto redo;
3049 /* convert preprocessor tokens into C tokens */
3050 if (tok == TOK_PPNUM &&
3051 (parse_flags & PARSE_FLAG_TOK_NUM)) {
3052 parse_number((char *)tokc.cstr->data);
3056 /* push back current token and set current token to 'last_tok'. Only
3057 identifier case handled for labels. */
3058 ST_INLN void unget_tok(int last_tok)
3060 int i, n;
3061 int *q;
3062 if (unget_buffer_enabled)
3064 /* assert(macro_ptr == unget_saved_buffer + 1);
3065 assert(*macro_ptr == 0); */
3067 else
3069 unget_saved_macro_ptr = macro_ptr;
3070 unget_buffer_enabled = 1;
3072 q = unget_saved_buffer;
3073 macro_ptr = q;
3074 *q++ = tok;
3075 n = tok_ext_size(tok) - 1;
3076 for(i=0;i<n;i++)
3077 *q++ = tokc.tab[i];
3078 *q = 0; /* end of token string */
3079 tok = last_tok;
3083 /* better than nothing, but needs extension to handle '-E' option
3084 correctly too */
3085 ST_FUNC void preprocess_init(TCCState *s1)
3087 s1->include_stack_ptr = s1->include_stack;
3088 /* XXX: move that before to avoid having to initialize
3089 file->ifdef_stack_ptr ? */
3090 s1->ifdef_stack_ptr = s1->ifdef_stack;
3091 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3093 vtop = vstack - 1;
3094 s1->pack_stack[0] = 0;
3095 s1->pack_stack_ptr = s1->pack_stack;
3098 ST_FUNC void preprocess_new(void)
3100 int i, c;
3101 const char *p, *r;
3103 /* init isid table */
3104 for(i=CH_EOF;i<256;i++)
3105 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
3107 /* add all tokens */
3108 table_ident = NULL;
3109 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3111 tok_ident = TOK_IDENT;
3112 p = tcc_keywords;
3113 while (*p) {
3114 r = p;
3115 for(;;) {
3116 c = *r++;
3117 if (c == '\0')
3118 break;
3120 tok_alloc(p, r - p - 1);
3121 p = r;
3125 /* Preprocess the current file */
3126 ST_FUNC int tcc_preprocess(TCCState *s1)
3128 Sym *define_start;
3130 BufferedFile *file_ref, **iptr, **iptr_new;
3131 int token_seen, line_ref, d;
3132 const char *s;
3134 preprocess_init(s1);
3135 define_start = define_stack;
3136 ch = file->buf_ptr[0];
3137 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3138 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
3139 PARSE_FLAG_LINEFEED | PARSE_FLAG_SPACES;
3140 token_seen = 0;
3141 line_ref = 0;
3142 file_ref = NULL;
3143 iptr = s1->include_stack_ptr;
3145 for (;;) {
3146 next();
3147 if (tok == TOK_EOF) {
3148 break;
3149 } else if (file != file_ref) {
3150 goto print_line;
3151 } else if (tok == TOK_LINEFEED) {
3152 if (!token_seen)
3153 continue;
3154 ++line_ref;
3155 token_seen = 0;
3156 } else if (!token_seen) {
3157 d = file->line_num - line_ref;
3158 if (file != file_ref || d < 0 || d >= 8) {
3159 print_line:
3160 iptr_new = s1->include_stack_ptr;
3161 s = iptr_new > iptr ? " 1"
3162 : iptr_new < iptr ? " 2"
3163 : iptr_new > s1->include_stack ? " 3"
3164 : ""
3166 iptr = iptr_new;
3167 fprintf(s1->ppfp, "# %d \"%s\"%s\n", file->line_num, file->filename, s);
3168 } else {
3169 while (d)
3170 fputs("\n", s1->ppfp), --d;
3172 line_ref = (file_ref = file)->line_num;
3173 token_seen = tok != TOK_LINEFEED;
3174 if (!token_seen)
3175 continue;
3177 fputs(get_tok_str(tok, &tokc), s1->ppfp);
3179 free_defines(define_start);
3180 return 0;