tccgen: x86_64: fix garbage in the SValue upper bits
[tinycc.git] / tccpp.c
blob7144ee43848898c72b30c8c650027a2b42ed2408
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;
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 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1258 /* remove spaces around ## and after '#' */
1259 if (TOK_TWOSHARPS == tok) {
1260 if (1 == spc)
1261 --str.len;
1262 spc = 2;
1263 } else if ('#' == tok) {
1264 spc = 2;
1265 } else if (check_space(tok, &spc)) {
1266 goto skip;
1268 tok_str_add2(&str, tok, &tokc);
1269 skip:
1270 next_nomacro_spc();
1272 if (spc == 1)
1273 --str.len; /* remove trailing space */
1274 tok_str_add(&str, 0);
1275 #ifdef PP_DEBUG
1276 printf("define %s %d: ", get_tok_str(v, NULL), t);
1277 tok_print(str.str);
1278 #endif
1279 define_push(v, t, str.str, first);
1282 static inline int hash_cached_include(const char *filename)
1284 const unsigned char *s;
1285 unsigned int h;
1287 h = TOK_HASH_INIT;
1288 s = (unsigned char *) filename;
1289 while (*s) {
1290 h = TOK_HASH_FUNC(h, *s);
1291 s++;
1293 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1294 return h;
1297 static CachedInclude *search_cached_include(TCCState *s1, const char *filename)
1299 CachedInclude *e;
1300 int i, h;
1301 h = hash_cached_include(filename);
1302 i = s1->cached_includes_hash[h];
1303 for(;;) {
1304 if (i == 0)
1305 break;
1306 e = s1->cached_includes[i - 1];
1307 if (0 == PATHCMP(e->filename, filename))
1308 return e;
1309 i = e->hash_next;
1311 return NULL;
1314 static inline void add_cached_include(TCCState *s1, const char *filename, int ifndef_macro)
1316 CachedInclude *e;
1317 int h;
1319 if (search_cached_include(s1, filename))
1320 return;
1321 #ifdef INC_DEBUG
1322 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
1323 #endif
1324 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1325 strcpy(e->filename, filename);
1326 e->ifndef_macro = ifndef_macro;
1327 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1328 /* add in hash table */
1329 h = hash_cached_include(filename);
1330 e->hash_next = s1->cached_includes_hash[h];
1331 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1334 static void pragma_parse(TCCState *s1)
1336 int val;
1338 next();
1339 if (tok == TOK_pack) {
1341 This may be:
1342 #pragma pack(1) // set
1343 #pragma pack() // reset to default
1344 #pragma pack(push,1) // push & set
1345 #pragma pack(pop) // restore previous
1347 next();
1348 skip('(');
1349 if (tok == TOK_ASM_pop) {
1350 next();
1351 if (s1->pack_stack_ptr <= s1->pack_stack) {
1352 stk_error:
1353 tcc_error("out of pack stack");
1355 s1->pack_stack_ptr--;
1356 } else {
1357 val = 0;
1358 if (tok != ')') {
1359 if (tok == TOK_ASM_push) {
1360 next();
1361 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1362 goto stk_error;
1363 s1->pack_stack_ptr++;
1364 skip(',');
1366 if (tok != TOK_CINT) {
1367 pack_error:
1368 tcc_error("invalid pack pragma");
1370 val = tokc.i;
1371 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1372 goto pack_error;
1373 next();
1375 *s1->pack_stack_ptr = val;
1376 skip(')');
1381 /* is_bof is true if first non space token at beginning of file */
1382 ST_FUNC void preprocess(int is_bof)
1384 TCCState *s1 = tcc_state;
1385 int i, c, n, saved_parse_flags;
1386 char buf[1024], *q;
1387 Sym *s;
1389 saved_parse_flags = parse_flags;
1390 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
1391 PARSE_FLAG_LINEFEED;
1392 next_nomacro();
1393 redo:
1394 switch(tok) {
1395 case TOK_DEFINE:
1396 next_nomacro();
1397 parse_define();
1398 break;
1399 case TOK_UNDEF:
1400 next_nomacro();
1401 s = define_find(tok);
1402 /* undefine symbol by putting an invalid name */
1403 if (s)
1404 define_undef(s);
1405 break;
1406 case TOK_INCLUDE:
1407 case TOK_INCLUDE_NEXT:
1408 ch = file->buf_ptr[0];
1409 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1410 skip_spaces();
1411 if (ch == '<') {
1412 c = '>';
1413 goto read_name;
1414 } else if (ch == '\"') {
1415 c = ch;
1416 read_name:
1417 inp();
1418 q = buf;
1419 while (ch != c && ch != '\n' && ch != CH_EOF) {
1420 if ((q - buf) < sizeof(buf) - 1)
1421 *q++ = ch;
1422 if (ch == '\\') {
1423 if (handle_stray_noerror() == 0)
1424 --q;
1425 } else
1426 inp();
1428 *q = '\0';
1429 minp();
1430 #if 0
1431 /* eat all spaces and comments after include */
1432 /* XXX: slightly incorrect */
1433 while (ch1 != '\n' && ch1 != CH_EOF)
1434 inp();
1435 #endif
1436 } else {
1437 /* computed #include : either we have only strings or
1438 we have anything enclosed in '<>' */
1439 next();
1440 buf[0] = '\0';
1441 if (tok == TOK_STR) {
1442 while (tok != TOK_LINEFEED) {
1443 if (tok != TOK_STR) {
1444 include_syntax:
1445 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1447 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
1448 next();
1450 c = '\"';
1451 } else {
1452 int len;
1453 while (tok != TOK_LINEFEED) {
1454 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1455 next();
1457 len = strlen(buf);
1458 /* check syntax and remove '<>' */
1459 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1460 goto include_syntax;
1461 memmove(buf, buf + 1, len - 2);
1462 buf[len - 2] = '\0';
1463 c = '>';
1467 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1468 tcc_error("#include recursion too deep");
1469 /* store current file in stack, but increment stack later below */
1470 *s1->include_stack_ptr = file;
1472 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
1473 for (i = -2; i < n; ++i) {
1474 char buf1[sizeof file->filename];
1475 CachedInclude *e;
1476 BufferedFile **f;
1477 const char *path;
1479 if (i == -2) {
1480 /* check absolute include path */
1481 if (!IS_ABSPATH(buf))
1482 continue;
1483 buf1[0] = 0;
1484 i = n; /* force end loop */
1486 } else if (i == -1) {
1487 /* search in current dir if "header.h" */
1488 if (c != '\"')
1489 continue;
1490 path = file->filename;
1491 pstrncpy(buf1, path, tcc_basename(path) - path);
1493 } else {
1494 /* search in all the include paths */
1495 if (i < s1->nb_include_paths)
1496 path = s1->include_paths[i];
1497 else
1498 path = s1->sysinclude_paths[i - s1->nb_include_paths];
1499 pstrcpy(buf1, sizeof(buf1), path);
1500 pstrcat(buf1, sizeof(buf1), "/");
1503 pstrcat(buf1, sizeof(buf1), buf);
1505 if (tok == TOK_INCLUDE_NEXT)
1506 for (f = s1->include_stack_ptr; f >= s1->include_stack; --f)
1507 if (0 == PATHCMP((*f)->filename, buf1)) {
1508 #ifdef INC_DEBUG
1509 printf("%s: #include_next skipping %s\n", file->filename, buf1);
1510 #endif
1511 goto include_trynext;
1514 e = search_cached_include(s1, buf1);
1515 if (e && define_find(e->ifndef_macro)) {
1516 /* no need to parse the include because the 'ifndef macro'
1517 is defined */
1518 #ifdef INC_DEBUG
1519 printf("%s: skipping cached %s\n", file->filename, buf1);
1520 #endif
1521 goto include_done;
1524 if (tcc_open(s1, buf1) < 0)
1525 include_trynext:
1526 continue;
1528 #ifdef INC_DEBUG
1529 printf("%s: including %s\n", file->prev->filename, file->filename);
1530 #endif
1531 /* update target deps */
1532 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1533 tcc_strdup(buf1));
1534 /* push current file in stack */
1535 ++s1->include_stack_ptr;
1536 /* add include file debug info */
1537 if (s1->do_debug)
1538 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1539 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1540 ch = file->buf_ptr[0];
1541 goto the_end;
1543 tcc_error("include file '%s' not found", buf);
1544 include_done:
1545 break;
1546 case TOK_IFNDEF:
1547 c = 1;
1548 goto do_ifdef;
1549 case TOK_IF:
1550 c = expr_preprocess();
1551 goto do_if;
1552 case TOK_IFDEF:
1553 c = 0;
1554 do_ifdef:
1555 next_nomacro();
1556 if (tok < TOK_IDENT)
1557 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1558 if (is_bof) {
1559 if (c) {
1560 #ifdef INC_DEBUG
1561 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1562 #endif
1563 file->ifndef_macro = tok;
1566 c = (define_find(tok) != 0) ^ c;
1567 do_if:
1568 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1569 tcc_error("memory full (ifdef)");
1570 *s1->ifdef_stack_ptr++ = c;
1571 goto test_skip;
1572 case TOK_ELSE:
1573 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1574 tcc_error("#else without matching #if");
1575 if (s1->ifdef_stack_ptr[-1] & 2)
1576 tcc_error("#else after #else");
1577 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1578 goto test_else;
1579 case TOK_ELIF:
1580 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1581 tcc_error("#elif without matching #if");
1582 c = s1->ifdef_stack_ptr[-1];
1583 if (c > 1)
1584 tcc_error("#elif after #else");
1585 /* last #if/#elif expression was true: we skip */
1586 if (c == 1)
1587 goto skip;
1588 c = expr_preprocess();
1589 s1->ifdef_stack_ptr[-1] = c;
1590 test_else:
1591 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1592 file->ifndef_macro = 0;
1593 test_skip:
1594 if (!(c & 1)) {
1595 skip:
1596 preprocess_skip();
1597 is_bof = 0;
1598 goto redo;
1600 break;
1601 case TOK_ENDIF:
1602 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1603 tcc_error("#endif without matching #if");
1604 s1->ifdef_stack_ptr--;
1605 /* '#ifndef macro' was at the start of file. Now we check if
1606 an '#endif' is exactly at the end of file */
1607 if (file->ifndef_macro &&
1608 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1609 file->ifndef_macro_saved = file->ifndef_macro;
1610 /* need to set to zero to avoid false matches if another
1611 #ifndef at middle of file */
1612 file->ifndef_macro = 0;
1613 while (tok != TOK_LINEFEED)
1614 next_nomacro();
1615 tok_flags |= TOK_FLAG_ENDIF;
1616 goto the_end;
1618 break;
1619 case TOK_LINE:
1620 next();
1621 if (tok != TOK_CINT)
1622 tcc_error("#line");
1623 file->line_num = tokc.i - 1; /* the line number will be incremented after */
1624 next();
1625 if (tok != TOK_LINEFEED) {
1626 if (tok != TOK_STR)
1627 tcc_error("#line");
1628 pstrcpy(file->filename, sizeof(file->filename),
1629 (char *)tokc.cstr->data);
1631 break;
1632 case TOK_ERROR:
1633 case TOK_WARNING:
1634 c = tok;
1635 ch = file->buf_ptr[0];
1636 skip_spaces();
1637 q = buf;
1638 while (ch != '\n' && ch != CH_EOF) {
1639 if ((q - buf) < sizeof(buf) - 1)
1640 *q++ = ch;
1641 if (ch == '\\') {
1642 if (handle_stray_noerror() == 0)
1643 --q;
1644 } else
1645 inp();
1647 *q = '\0';
1648 if (c == TOK_ERROR)
1649 tcc_error("#error %s", buf);
1650 else
1651 tcc_warning("#warning %s", buf);
1652 break;
1653 case TOK_PRAGMA:
1654 pragma_parse(s1);
1655 break;
1656 default:
1657 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_PPNUM) {
1658 /* '!' is ignored to allow C scripts. numbers are ignored
1659 to emulate cpp behaviour */
1660 } else {
1661 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
1662 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1663 else {
1664 /* this is a gas line comment in an 'S' file. */
1665 file->buf_ptr = parse_line_comment(file->buf_ptr);
1666 goto the_end;
1669 break;
1671 /* ignore other preprocess commands or #! for C scripts */
1672 while (tok != TOK_LINEFEED)
1673 next_nomacro();
1674 the_end:
1675 parse_flags = saved_parse_flags;
1678 /* evaluate escape codes in a string. */
1679 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1681 int c, n;
1682 const uint8_t *p;
1684 p = buf;
1685 for(;;) {
1686 c = *p;
1687 if (c == '\0')
1688 break;
1689 if (c == '\\') {
1690 p++;
1691 /* escape */
1692 c = *p;
1693 switch(c) {
1694 case '0': case '1': case '2': case '3':
1695 case '4': case '5': case '6': case '7':
1696 /* at most three octal digits */
1697 n = c - '0';
1698 p++;
1699 c = *p;
1700 if (isoct(c)) {
1701 n = n * 8 + c - '0';
1702 p++;
1703 c = *p;
1704 if (isoct(c)) {
1705 n = n * 8 + c - '0';
1706 p++;
1709 c = n;
1710 goto add_char_nonext;
1711 case 'x':
1712 case 'u':
1713 case 'U':
1714 p++;
1715 n = 0;
1716 for(;;) {
1717 c = *p;
1718 if (c >= 'a' && c <= 'f')
1719 c = c - 'a' + 10;
1720 else if (c >= 'A' && c <= 'F')
1721 c = c - 'A' + 10;
1722 else if (isnum(c))
1723 c = c - '0';
1724 else
1725 break;
1726 n = n * 16 + c;
1727 p++;
1729 c = n;
1730 goto add_char_nonext;
1731 case 'a':
1732 c = '\a';
1733 break;
1734 case 'b':
1735 c = '\b';
1736 break;
1737 case 'f':
1738 c = '\f';
1739 break;
1740 case 'n':
1741 c = '\n';
1742 break;
1743 case 'r':
1744 c = '\r';
1745 break;
1746 case 't':
1747 c = '\t';
1748 break;
1749 case 'v':
1750 c = '\v';
1751 break;
1752 case 'e':
1753 if (!gnu_ext)
1754 goto invalid_escape;
1755 c = 27;
1756 break;
1757 case '\'':
1758 case '\"':
1759 case '\\':
1760 case '?':
1761 break;
1762 default:
1763 invalid_escape:
1764 if (c >= '!' && c <= '~')
1765 tcc_warning("unknown escape sequence: \'\\%c\'", c);
1766 else
1767 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
1768 break;
1771 p++;
1772 add_char_nonext:
1773 if (!is_long)
1774 cstr_ccat(outstr, c);
1775 else
1776 cstr_wccat(outstr, c);
1778 /* add a trailing '\0' */
1779 if (!is_long)
1780 cstr_ccat(outstr, '\0');
1781 else
1782 cstr_wccat(outstr, '\0');
1785 /* we use 64 bit numbers */
1786 #define BN_SIZE 2
1788 /* bn = (bn << shift) | or_val */
1789 static void bn_lshift(unsigned int *bn, int shift, int or_val)
1791 int i;
1792 unsigned int v;
1793 for(i=0;i<BN_SIZE;i++) {
1794 v = bn[i];
1795 bn[i] = (v << shift) | or_val;
1796 or_val = v >> (32 - shift);
1800 static void bn_zero(unsigned int *bn)
1802 int i;
1803 for(i=0;i<BN_SIZE;i++) {
1804 bn[i] = 0;
1808 /* parse number in null terminated string 'p' and return it in the
1809 current token */
1810 static void parse_number(const char *p)
1812 int b, t, shift, frac_bits, s, exp_val, ch;
1813 char *q;
1814 unsigned int bn[BN_SIZE];
1815 double d;
1817 /* number */
1818 q = token_buf;
1819 ch = *p++;
1820 t = ch;
1821 ch = *p++;
1822 *q++ = t;
1823 b = 10;
1824 if (t == '.') {
1825 goto float_frac_parse;
1826 } else if (t == '0') {
1827 if (ch == 'x' || ch == 'X') {
1828 q--;
1829 ch = *p++;
1830 b = 16;
1831 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
1832 q--;
1833 ch = *p++;
1834 b = 2;
1837 /* parse all digits. cannot check octal numbers at this stage
1838 because of floating point constants */
1839 while (1) {
1840 if (ch >= 'a' && ch <= 'f')
1841 t = ch - 'a' + 10;
1842 else if (ch >= 'A' && ch <= 'F')
1843 t = ch - 'A' + 10;
1844 else if (isnum(ch))
1845 t = ch - '0';
1846 else
1847 break;
1848 if (t >= b)
1849 break;
1850 if (q >= token_buf + STRING_MAX_SIZE) {
1851 num_too_long:
1852 tcc_error("number too long");
1854 *q++ = ch;
1855 ch = *p++;
1857 if (ch == '.' ||
1858 ((ch == 'e' || ch == 'E') && b == 10) ||
1859 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
1860 if (b != 10) {
1861 /* NOTE: strtox should support that for hexa numbers, but
1862 non ISOC99 libcs do not support it, so we prefer to do
1863 it by hand */
1864 /* hexadecimal or binary floats */
1865 /* XXX: handle overflows */
1866 *q = '\0';
1867 if (b == 16)
1868 shift = 4;
1869 else
1870 shift = 2;
1871 bn_zero(bn);
1872 q = token_buf;
1873 while (1) {
1874 t = *q++;
1875 if (t == '\0') {
1876 break;
1877 } else if (t >= 'a') {
1878 t = t - 'a' + 10;
1879 } else if (t >= 'A') {
1880 t = t - 'A' + 10;
1881 } else {
1882 t = t - '0';
1884 bn_lshift(bn, shift, t);
1886 frac_bits = 0;
1887 if (ch == '.') {
1888 ch = *p++;
1889 while (1) {
1890 t = ch;
1891 if (t >= 'a' && t <= 'f') {
1892 t = t - 'a' + 10;
1893 } else if (t >= 'A' && t <= 'F') {
1894 t = t - 'A' + 10;
1895 } else if (t >= '0' && t <= '9') {
1896 t = t - '0';
1897 } else {
1898 break;
1900 if (t >= b)
1901 tcc_error("invalid digit");
1902 bn_lshift(bn, shift, t);
1903 frac_bits += shift;
1904 ch = *p++;
1907 if (ch != 'p' && ch != 'P')
1908 expect("exponent");
1909 ch = *p++;
1910 s = 1;
1911 exp_val = 0;
1912 if (ch == '+') {
1913 ch = *p++;
1914 } else if (ch == '-') {
1915 s = -1;
1916 ch = *p++;
1918 if (ch < '0' || ch > '9')
1919 expect("exponent digits");
1920 while (ch >= '0' && ch <= '9') {
1921 exp_val = exp_val * 10 + ch - '0';
1922 ch = *p++;
1924 exp_val = exp_val * s;
1926 /* now we can generate the number */
1927 /* XXX: should patch directly float number */
1928 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
1929 d = ldexp(d, exp_val - frac_bits);
1930 t = toup(ch);
1931 if (t == 'F') {
1932 ch = *p++;
1933 tok = TOK_CFLOAT;
1934 /* float : should handle overflow */
1935 tokc.f = (float)d;
1936 } else if (t == 'L') {
1937 ch = *p++;
1938 #ifdef TCC_TARGET_PE
1939 tok = TOK_CDOUBLE;
1940 tokc.d = d;
1941 #else
1942 tok = TOK_CLDOUBLE;
1943 /* XXX: not large enough */
1944 tokc.ld = (long double)d;
1945 #endif
1946 } else {
1947 tok = TOK_CDOUBLE;
1948 tokc.d = d;
1950 } else {
1951 /* decimal floats */
1952 if (ch == '.') {
1953 if (q >= token_buf + STRING_MAX_SIZE)
1954 goto num_too_long;
1955 *q++ = ch;
1956 ch = *p++;
1957 float_frac_parse:
1958 while (ch >= '0' && ch <= '9') {
1959 if (q >= token_buf + STRING_MAX_SIZE)
1960 goto num_too_long;
1961 *q++ = ch;
1962 ch = *p++;
1965 if (ch == 'e' || ch == 'E') {
1966 if (q >= token_buf + STRING_MAX_SIZE)
1967 goto num_too_long;
1968 *q++ = ch;
1969 ch = *p++;
1970 if (ch == '-' || ch == '+') {
1971 if (q >= token_buf + STRING_MAX_SIZE)
1972 goto num_too_long;
1973 *q++ = ch;
1974 ch = *p++;
1976 if (ch < '0' || ch > '9')
1977 expect("exponent digits");
1978 while (ch >= '0' && ch <= '9') {
1979 if (q >= token_buf + STRING_MAX_SIZE)
1980 goto num_too_long;
1981 *q++ = ch;
1982 ch = *p++;
1985 *q = '\0';
1986 t = toup(ch);
1987 errno = 0;
1988 if (t == 'F') {
1989 ch = *p++;
1990 tok = TOK_CFLOAT;
1991 tokc.f = strtof(token_buf, NULL);
1992 } else if (t == 'L') {
1993 ch = *p++;
1994 #ifdef TCC_TARGET_PE
1995 tok = TOK_CDOUBLE;
1996 tokc.d = strtod(token_buf, NULL);
1997 #else
1998 tok = TOK_CLDOUBLE;
1999 tokc.ld = strtold(token_buf, NULL);
2000 #endif
2001 } else {
2002 tok = TOK_CDOUBLE;
2003 tokc.d = strtod(token_buf, NULL);
2006 } else {
2007 unsigned long long n, n1;
2008 int lcount, ucount;
2010 /* integer number */
2011 *q = '\0';
2012 q = token_buf;
2013 if (b == 10 && *q == '0') {
2014 b = 8;
2015 q++;
2017 n = 0;
2018 while(1) {
2019 t = *q++;
2020 /* no need for checks except for base 10 / 8 errors */
2021 if (t == '\0') {
2022 break;
2023 } else if (t >= 'a') {
2024 t = t - 'a' + 10;
2025 } else if (t >= 'A') {
2026 t = t - 'A' + 10;
2027 } else {
2028 t = t - '0';
2029 if (t >= b)
2030 tcc_error("invalid digit");
2032 n1 = n;
2033 n = n * b + t;
2034 /* detect overflow */
2035 /* XXX: this test is not reliable */
2036 if (n < n1)
2037 tcc_error("integer constant overflow");
2040 /* XXX: not exactly ANSI compliant */
2041 if ((n & 0xffffffff00000000LL) != 0) {
2042 if ((n >> 63) != 0)
2043 tok = TOK_CULLONG;
2044 else
2045 tok = TOK_CLLONG;
2046 } else if (n > 0x7fffffff) {
2047 tok = TOK_CUINT;
2048 } else {
2049 tok = TOK_CINT;
2051 lcount = 0;
2052 ucount = 0;
2053 for(;;) {
2054 t = toup(ch);
2055 if (t == 'L') {
2056 if (lcount >= 2)
2057 tcc_error("three 'l's in integer constant");
2058 lcount++;
2059 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2060 if (lcount == 2) {
2061 #endif
2062 if (tok == TOK_CINT)
2063 tok = TOK_CLLONG;
2064 else if (tok == TOK_CUINT)
2065 tok = TOK_CULLONG;
2066 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2068 #endif
2069 ch = *p++;
2070 } else if (t == 'U') {
2071 if (ucount >= 1)
2072 tcc_error("two 'u's in integer constant");
2073 ucount++;
2074 if (tok == TOK_CINT)
2075 tok = TOK_CUINT;
2076 else if (tok == TOK_CLLONG)
2077 tok = TOK_CULLONG;
2078 ch = *p++;
2079 } else {
2080 break;
2083 if (tok == TOK_CINT || tok == TOK_CUINT)
2084 tokc.ui = n;
2085 else
2086 tokc.ull = n;
2088 if (ch)
2089 tcc_error("invalid number\n");
2093 #define PARSE2(c1, tok1, c2, tok2) \
2094 case c1: \
2095 PEEKC(c, p); \
2096 if (c == c2) { \
2097 p++; \
2098 tok = tok2; \
2099 } else { \
2100 tok = tok1; \
2102 break;
2104 /* return next token without macro substitution */
2105 static inline void next_nomacro1(void)
2107 int t, c, is_long;
2108 TokenSym *ts;
2109 uint8_t *p, *p1;
2110 unsigned int h;
2112 p = file->buf_ptr;
2113 redo_no_start:
2114 c = *p;
2115 switch(c) {
2116 case ' ':
2117 case '\t':
2118 tok = c;
2119 p++;
2120 goto keep_tok_flags;
2121 case '\f':
2122 case '\v':
2123 case '\r':
2124 p++;
2125 goto redo_no_start;
2126 case '\\':
2127 /* first look if it is in fact an end of buffer */
2128 if (p >= file->buf_end) {
2129 file->buf_ptr = p;
2130 handle_eob();
2131 p = file->buf_ptr;
2132 if (p >= file->buf_end)
2133 goto parse_eof;
2134 else
2135 goto redo_no_start;
2136 } else {
2137 file->buf_ptr = p;
2138 ch = *p;
2139 handle_stray();
2140 p = file->buf_ptr;
2141 goto redo_no_start;
2143 parse_eof:
2145 TCCState *s1 = tcc_state;
2146 if ((parse_flags & PARSE_FLAG_LINEFEED)
2147 && !(tok_flags & TOK_FLAG_EOF)) {
2148 tok_flags |= TOK_FLAG_EOF;
2149 tok = TOK_LINEFEED;
2150 goto keep_tok_flags;
2151 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2152 tok = TOK_EOF;
2153 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2154 tcc_error("missing #endif");
2155 } else if (s1->include_stack_ptr == s1->include_stack) {
2156 /* no include left : end of file. */
2157 tok = TOK_EOF;
2158 } else {
2159 tok_flags &= ~TOK_FLAG_EOF;
2160 /* pop include file */
2162 /* test if previous '#endif' was after a #ifdef at
2163 start of file */
2164 if (tok_flags & TOK_FLAG_ENDIF) {
2165 #ifdef INC_DEBUG
2166 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2167 #endif
2168 add_cached_include(s1, file->filename, file->ifndef_macro_saved);
2169 tok_flags &= ~TOK_FLAG_ENDIF;
2172 /* add end of include file debug info */
2173 if (tcc_state->do_debug) {
2174 put_stabd(N_EINCL, 0, 0);
2176 /* pop include stack */
2177 tcc_close();
2178 s1->include_stack_ptr--;
2179 p = file->buf_ptr;
2180 goto redo_no_start;
2183 break;
2185 case '\n':
2186 file->line_num++;
2187 tok_flags |= TOK_FLAG_BOL;
2188 p++;
2189 maybe_newline:
2190 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2191 goto redo_no_start;
2192 tok = TOK_LINEFEED;
2193 goto keep_tok_flags;
2195 case '#':
2196 /* XXX: simplify */
2197 PEEKC(c, p);
2198 if ((tok_flags & TOK_FLAG_BOL) &&
2199 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2200 file->buf_ptr = p;
2201 preprocess(tok_flags & TOK_FLAG_BOF);
2202 p = file->buf_ptr;
2203 goto maybe_newline;
2204 } else {
2205 if (c == '#') {
2206 p++;
2207 tok = TOK_TWOSHARPS;
2208 } else {
2209 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
2210 p = parse_line_comment(p - 1);
2211 goto redo_no_start;
2212 } else {
2213 tok = '#';
2217 break;
2219 case 'a': case 'b': case 'c': case 'd':
2220 case 'e': case 'f': case 'g': case 'h':
2221 case 'i': case 'j': case 'k': case 'l':
2222 case 'm': case 'n': case 'o': case 'p':
2223 case 'q': case 'r': case 's': case 't':
2224 case 'u': case 'v': case 'w': case 'x':
2225 case 'y': case 'z':
2226 case 'A': case 'B': case 'C': case 'D':
2227 case 'E': case 'F': case 'G': case 'H':
2228 case 'I': case 'J': case 'K':
2229 case 'M': case 'N': case 'O': case 'P':
2230 case 'Q': case 'R': case 'S': case 'T':
2231 case 'U': case 'V': case 'W': case 'X':
2232 case 'Y': case 'Z':
2233 case '_':
2234 parse_ident_fast:
2235 p1 = p;
2236 h = TOK_HASH_INIT;
2237 h = TOK_HASH_FUNC(h, c);
2238 p++;
2239 for(;;) {
2240 c = *p;
2241 if (!isidnum_table[c-CH_EOF])
2242 break;
2243 h = TOK_HASH_FUNC(h, c);
2244 p++;
2246 if (c != '\\') {
2247 TokenSym **pts;
2248 int len;
2250 /* fast case : no stray found, so we have the full token
2251 and we have already hashed it */
2252 len = p - p1;
2253 h &= (TOK_HASH_SIZE - 1);
2254 pts = &hash_ident[h];
2255 for(;;) {
2256 ts = *pts;
2257 if (!ts)
2258 break;
2259 if (ts->len == len && !memcmp(ts->str, p1, len))
2260 goto token_found;
2261 pts = &(ts->hash_next);
2263 ts = tok_alloc_new(pts, (char *) p1, len);
2264 token_found: ;
2265 } else {
2266 /* slower case */
2267 cstr_reset(&tokcstr);
2269 while (p1 < p) {
2270 cstr_ccat(&tokcstr, *p1);
2271 p1++;
2273 p--;
2274 PEEKC(c, p);
2275 parse_ident_slow:
2276 while (isidnum_table[c-CH_EOF]) {
2277 cstr_ccat(&tokcstr, c);
2278 PEEKC(c, p);
2280 ts = tok_alloc(tokcstr.data, tokcstr.size);
2282 tok = ts->tok;
2283 break;
2284 case 'L':
2285 t = p[1];
2286 if (t != '\\' && t != '\'' && t != '\"') {
2287 /* fast case */
2288 goto parse_ident_fast;
2289 } else {
2290 PEEKC(c, p);
2291 if (c == '\'' || c == '\"') {
2292 is_long = 1;
2293 goto str_const;
2294 } else {
2295 cstr_reset(&tokcstr);
2296 cstr_ccat(&tokcstr, 'L');
2297 goto parse_ident_slow;
2300 break;
2301 case '0': case '1': case '2': case '3':
2302 case '4': case '5': case '6': case '7':
2303 case '8': case '9':
2305 cstr_reset(&tokcstr);
2306 /* after the first digit, accept digits, alpha, '.' or sign if
2307 prefixed by 'eEpP' */
2308 parse_num:
2309 for(;;) {
2310 t = c;
2311 cstr_ccat(&tokcstr, c);
2312 PEEKC(c, p);
2313 if (!(isnum(c) || isid(c) || c == '.' ||
2314 ((c == '+' || c == '-') &&
2315 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
2316 break;
2318 /* We add a trailing '\0' to ease parsing */
2319 cstr_ccat(&tokcstr, '\0');
2320 tokc.cstr = &tokcstr;
2321 tok = TOK_PPNUM;
2322 break;
2323 case '.':
2324 /* special dot handling because it can also start a number */
2325 PEEKC(c, p);
2326 if (isnum(c)) {
2327 cstr_reset(&tokcstr);
2328 cstr_ccat(&tokcstr, '.');
2329 goto parse_num;
2330 } else if (c == '.') {
2331 PEEKC(c, p);
2332 if (c != '.')
2333 expect("'.'");
2334 PEEKC(c, p);
2335 tok = TOK_DOTS;
2336 } else {
2337 tok = '.';
2339 break;
2340 case '\'':
2341 case '\"':
2342 is_long = 0;
2343 str_const:
2345 CString str;
2346 int sep;
2348 sep = c;
2350 /* parse the string */
2351 cstr_new(&str);
2352 p = parse_pp_string(p, sep, &str);
2353 cstr_ccat(&str, '\0');
2355 /* eval the escape (should be done as TOK_PPNUM) */
2356 cstr_reset(&tokcstr);
2357 parse_escape_string(&tokcstr, str.data, is_long);
2358 cstr_free(&str);
2360 if (sep == '\'') {
2361 int char_size;
2362 /* XXX: make it portable */
2363 if (!is_long)
2364 char_size = 1;
2365 else
2366 char_size = sizeof(nwchar_t);
2367 if (tokcstr.size <= char_size)
2368 tcc_error("empty character constant");
2369 if (tokcstr.size > 2 * char_size)
2370 tcc_warning("multi-character character constant");
2371 if (!is_long) {
2372 tokc.i = *(int8_t *)tokcstr.data;
2373 tok = TOK_CCHAR;
2374 } else {
2375 tokc.i = *(nwchar_t *)tokcstr.data;
2376 tok = TOK_LCHAR;
2378 } else {
2379 tokc.cstr = &tokcstr;
2380 if (!is_long)
2381 tok = TOK_STR;
2382 else
2383 tok = TOK_LSTR;
2386 break;
2388 case '<':
2389 PEEKC(c, p);
2390 if (c == '=') {
2391 p++;
2392 tok = TOK_LE;
2393 } else if (c == '<') {
2394 PEEKC(c, p);
2395 if (c == '=') {
2396 p++;
2397 tok = TOK_A_SHL;
2398 } else {
2399 tok = TOK_SHL;
2401 } else {
2402 tok = TOK_LT;
2404 break;
2406 case '>':
2407 PEEKC(c, p);
2408 if (c == '=') {
2409 p++;
2410 tok = TOK_GE;
2411 } else if (c == '>') {
2412 PEEKC(c, p);
2413 if (c == '=') {
2414 p++;
2415 tok = TOK_A_SAR;
2416 } else {
2417 tok = TOK_SAR;
2419 } else {
2420 tok = TOK_GT;
2422 break;
2424 case '&':
2425 PEEKC(c, p);
2426 if (c == '&') {
2427 p++;
2428 tok = TOK_LAND;
2429 } else if (c == '=') {
2430 p++;
2431 tok = TOK_A_AND;
2432 } else {
2433 tok = '&';
2435 break;
2437 case '|':
2438 PEEKC(c, p);
2439 if (c == '|') {
2440 p++;
2441 tok = TOK_LOR;
2442 } else if (c == '=') {
2443 p++;
2444 tok = TOK_A_OR;
2445 } else {
2446 tok = '|';
2448 break;
2450 case '+':
2451 PEEKC(c, p);
2452 if (c == '+') {
2453 p++;
2454 tok = TOK_INC;
2455 } else if (c == '=') {
2456 p++;
2457 tok = TOK_A_ADD;
2458 } else {
2459 tok = '+';
2461 break;
2463 case '-':
2464 PEEKC(c, p);
2465 if (c == '-') {
2466 p++;
2467 tok = TOK_DEC;
2468 } else if (c == '=') {
2469 p++;
2470 tok = TOK_A_SUB;
2471 } else if (c == '>') {
2472 p++;
2473 tok = TOK_ARROW;
2474 } else {
2475 tok = '-';
2477 break;
2479 PARSE2('!', '!', '=', TOK_NE)
2480 PARSE2('=', '=', '=', TOK_EQ)
2481 PARSE2('*', '*', '=', TOK_A_MUL)
2482 PARSE2('%', '%', '=', TOK_A_MOD)
2483 PARSE2('^', '^', '=', TOK_A_XOR)
2485 /* comments or operator */
2486 case '/':
2487 PEEKC(c, p);
2488 if (c == '*') {
2489 p = parse_comment(p);
2490 /* comments replaced by a blank */
2491 tok = ' ';
2492 goto keep_tok_flags;
2493 } else if (c == '/') {
2494 p = parse_line_comment(p);
2495 tok = ' ';
2496 goto keep_tok_flags;
2497 } else if (c == '=') {
2498 p++;
2499 tok = TOK_A_DIV;
2500 } else {
2501 tok = '/';
2503 break;
2505 /* simple tokens */
2506 case '(':
2507 case ')':
2508 case '[':
2509 case ']':
2510 case '{':
2511 case '}':
2512 case ',':
2513 case ';':
2514 case ':':
2515 case '?':
2516 case '~':
2517 case '$': /* only used in assembler */
2518 case '@': /* dito */
2519 tok = c;
2520 p++;
2521 break;
2522 default:
2523 tcc_error("unrecognized character \\x%02x", c);
2524 break;
2526 tok_flags = 0;
2527 keep_tok_flags:
2528 file->buf_ptr = p;
2529 #if defined(PARSE_DEBUG)
2530 printf("token = %s\n", get_tok_str(tok, &tokc));
2531 #endif
2534 /* return next token without macro substitution. Can read input from
2535 macro_ptr buffer */
2536 static void next_nomacro_spc(void)
2538 if (macro_ptr) {
2539 redo:
2540 tok = *macro_ptr;
2541 if (tok) {
2542 TOK_GET(&tok, &macro_ptr, &tokc);
2543 if (tok == TOK_LINENUM) {
2544 file->line_num = tokc.i;
2545 goto redo;
2548 } else {
2549 next_nomacro1();
2553 ST_FUNC void next_nomacro(void)
2555 do {
2556 next_nomacro_spc();
2557 } while (is_space(tok));
2560 /* substitute args in macro_str and return allocated string */
2561 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2563 int last_tok, t, spc;
2564 const int *st;
2565 Sym *s;
2566 CValue cval;
2567 TokenString str;
2568 CString cstr;
2570 tok_str_new(&str);
2571 last_tok = 0;
2572 while(1) {
2573 TOK_GET(&t, &macro_str, &cval);
2574 if (!t)
2575 break;
2576 if (t == '#') {
2577 /* stringize */
2578 TOK_GET(&t, &macro_str, &cval);
2579 if (!t)
2580 break;
2581 s = sym_find2(args, t);
2582 if (s) {
2583 cstr_new(&cstr);
2584 st = s->d;
2585 spc = 0;
2586 while (*st) {
2587 TOK_GET(&t, &st, &cval);
2588 if (!check_space(t, &spc))
2589 cstr_cat(&cstr, get_tok_str(t, &cval));
2591 cstr.size -= spc;
2592 cstr_ccat(&cstr, '\0');
2593 #ifdef PP_DEBUG
2594 printf("stringize: %s\n", (char *)cstr.data);
2595 #endif
2596 /* add string */
2597 cval.cstr = &cstr;
2598 tok_str_add2(&str, TOK_STR, &cval);
2599 cstr_free(&cstr);
2600 } else {
2601 tok_str_add2(&str, t, &cval);
2603 } else if (t >= TOK_IDENT) {
2604 s = sym_find2(args, t);
2605 if (s) {
2606 st = s->d;
2607 /* if '##' is present before or after, no arg substitution */
2608 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
2609 /* special case for var arg macros : ## eats the
2610 ',' if empty VA_ARGS variable. */
2611 /* XXX: test of the ',' is not 100%
2612 reliable. should fix it to avoid security
2613 problems */
2614 if (gnu_ext && s->type.t &&
2615 last_tok == TOK_TWOSHARPS &&
2616 str.len >= 2 && str.str[str.len - 2] == ',') {
2617 if (*st == 0) {
2618 /* suppress ',' '##' */
2619 str.len -= 2;
2620 } else {
2621 /* suppress '##' and add variable */
2622 str.len--;
2623 goto add_var;
2625 } else {
2626 int t1;
2627 add_var:
2628 for(;;) {
2629 TOK_GET(&t1, &st, &cval);
2630 if (!t1)
2631 break;
2632 tok_str_add2(&str, t1, &cval);
2635 } else {
2636 /* NOTE: the stream cannot be read when macro
2637 substituing an argument */
2638 macro_subst(&str, nested_list, st, NULL);
2640 } else {
2641 tok_str_add(&str, t);
2643 } else {
2644 tok_str_add2(&str, t, &cval);
2646 last_tok = t;
2648 tok_str_add(&str, 0);
2649 return str.str;
2652 static char const ab_month_name[12][4] =
2654 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2655 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2658 /* do macro substitution of current token with macro 's' and add
2659 result to (tok_str,tok_len). 'nested_list' is the list of all
2660 macros we got inside to avoid recursing. Return non zero if no
2661 substitution needs to be done */
2662 static int macro_subst_tok(TokenString *tok_str,
2663 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
2665 Sym *args, *sa, *sa1;
2666 int mstr_allocated, parlevel, *mstr, t, t1, spc;
2667 const int *p;
2668 TokenString str;
2669 char *cstrval;
2670 CValue cval;
2671 CString cstr;
2672 char buf[32];
2674 /* if symbol is a macro, prepare substitution */
2675 /* special macros */
2676 if (tok == TOK___LINE__) {
2677 snprintf(buf, sizeof(buf), "%d", file->line_num);
2678 cstrval = buf;
2679 t1 = TOK_PPNUM;
2680 goto add_cstr1;
2681 } else if (tok == TOK___FILE__) {
2682 cstrval = file->filename;
2683 goto add_cstr;
2684 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
2685 time_t ti;
2686 struct tm *tm;
2688 time(&ti);
2689 tm = localtime(&ti);
2690 if (tok == TOK___DATE__) {
2691 snprintf(buf, sizeof(buf), "%s %2d %d",
2692 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
2693 } else {
2694 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
2695 tm->tm_hour, tm->tm_min, tm->tm_sec);
2697 cstrval = buf;
2698 add_cstr:
2699 t1 = TOK_STR;
2700 add_cstr1:
2701 cstr_new(&cstr);
2702 cstr_cat(&cstr, cstrval);
2703 cstr_ccat(&cstr, '\0');
2704 cval.cstr = &cstr;
2705 tok_str_add2(tok_str, t1, &cval);
2706 cstr_free(&cstr);
2707 } else {
2708 mstr = s->d;
2709 mstr_allocated = 0;
2710 if (s->type.t == MACRO_FUNC) {
2711 /* NOTE: we do not use next_nomacro to avoid eating the
2712 next token. XXX: find better solution */
2713 redo:
2714 if (macro_ptr) {
2715 p = macro_ptr;
2716 while (is_space(t = *p) || TOK_LINEFEED == t)
2717 ++p;
2718 if (t == 0 && can_read_stream) {
2719 /* end of macro stream: we must look at the token
2720 after in the file */
2721 struct macro_level *ml = *can_read_stream;
2722 macro_ptr = NULL;
2723 if (ml)
2725 macro_ptr = ml->p;
2726 ml->p = NULL;
2727 *can_read_stream = ml -> prev;
2729 /* also, end of scope for nested defined symbol */
2730 (*nested_list)->v = -1;
2731 goto redo;
2733 } else {
2734 ch = file->buf_ptr[0];
2735 while (is_space(ch) || ch == '\n' || ch == '/')
2737 if (ch == '/')
2739 int c;
2740 uint8_t *p = file->buf_ptr;
2741 PEEKC(c, p);
2742 if (c == '*') {
2743 p = parse_comment(p);
2744 file->buf_ptr = p - 1;
2745 } else if (c == '/') {
2746 p = parse_line_comment(p);
2747 file->buf_ptr = p - 1;
2748 } else
2749 break;
2751 cinp();
2753 t = ch;
2755 if (t != '(') /* no macro subst */
2756 return -1;
2758 /* argument macro */
2759 next_nomacro();
2760 next_nomacro();
2761 args = NULL;
2762 sa = s->next;
2763 /* NOTE: empty args are allowed, except if no args */
2764 for(;;) {
2765 /* handle '()' case */
2766 if (!args && !sa && tok == ')')
2767 break;
2768 if (!sa)
2769 tcc_error("macro '%s' used with too many args",
2770 get_tok_str(s->v, 0));
2771 tok_str_new(&str);
2772 parlevel = spc = 0;
2773 /* NOTE: non zero sa->t indicates VA_ARGS */
2774 while ((parlevel > 0 ||
2775 (tok != ')' &&
2776 (tok != ',' || sa->type.t))) &&
2777 tok != -1) {
2778 if (tok == '(')
2779 parlevel++;
2780 else if (tok == ')')
2781 parlevel--;
2782 if (tok == TOK_LINEFEED)
2783 tok = ' ';
2784 if (!check_space(tok, &spc))
2785 tok_str_add2(&str, tok, &tokc);
2786 next_nomacro_spc();
2788 str.len -= spc;
2789 tok_str_add(&str, 0);
2790 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
2791 sa1->d = str.str;
2792 sa = sa->next;
2793 if (tok == ')') {
2794 /* special case for gcc var args: add an empty
2795 var arg argument if it is omitted */
2796 if (sa && sa->type.t && gnu_ext)
2797 continue;
2798 else
2799 break;
2801 if (tok != ',')
2802 expect(",");
2803 next_nomacro();
2805 if (sa) {
2806 tcc_error("macro '%s' used with too few args",
2807 get_tok_str(s->v, 0));
2810 /* now subst each arg */
2811 mstr = macro_arg_subst(nested_list, mstr, args);
2812 /* free memory */
2813 sa = args;
2814 while (sa) {
2815 sa1 = sa->prev;
2816 tok_str_free(sa->d);
2817 sym_free(sa);
2818 sa = sa1;
2820 mstr_allocated = 1;
2822 sym_push2(nested_list, s->v, 0, 0);
2823 macro_subst(tok_str, nested_list, mstr, can_read_stream);
2824 /* pop nested defined symbol */
2825 sa1 = *nested_list;
2826 *nested_list = sa1->prev;
2827 sym_free(sa1);
2828 if (mstr_allocated)
2829 tok_str_free(mstr);
2831 return 0;
2834 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2835 return the resulting string (which must be freed). */
2836 static inline int *macro_twosharps(const int *macro_str)
2838 const int *ptr;
2839 int t;
2840 TokenString macro_str1;
2841 CString cstr;
2842 int n, start_of_nosubsts;
2844 /* we search the first '##' */
2845 for(ptr = macro_str;;) {
2846 CValue cval;
2847 TOK_GET(&t, &ptr, &cval);
2848 if (t == TOK_TWOSHARPS)
2849 break;
2850 /* nothing more to do if end of string */
2851 if (t == 0)
2852 return NULL;
2855 /* we saw '##', so we need more processing to handle it */
2856 start_of_nosubsts = -1;
2857 tok_str_new(&macro_str1);
2858 for(ptr = macro_str;;) {
2859 TOK_GET(&tok, &ptr, &tokc);
2860 if (tok == 0)
2861 break;
2862 if (tok == TOK_TWOSHARPS)
2863 continue;
2864 if (tok == TOK_NOSUBST && start_of_nosubsts < 0)
2865 start_of_nosubsts = macro_str1.len;
2866 while (*ptr == TOK_TWOSHARPS) {
2867 /* given 'a##b', remove nosubsts preceding 'a' */
2868 if (start_of_nosubsts >= 0)
2869 macro_str1.len = start_of_nosubsts;
2870 /* given 'a##b', skip '##' */
2871 t = *++ptr;
2872 /* given 'a##b', remove nosubsts preceding 'b' */
2873 while (t == TOK_NOSUBST)
2874 t = *++ptr;
2875 if (t && t != TOK_TWOSHARPS) {
2876 CValue cval;
2877 TOK_GET(&t, &ptr, &cval);
2878 /* We concatenate the two tokens */
2879 cstr_new(&cstr);
2880 cstr_cat(&cstr, get_tok_str(tok, &tokc));
2881 n = cstr.size;
2882 cstr_cat(&cstr, get_tok_str(t, &cval));
2883 cstr_ccat(&cstr, '\0');
2885 tcc_open_bf(tcc_state, ":paste:", cstr.size);
2886 memcpy(file->buffer, cstr.data, cstr.size);
2887 for (;;) {
2888 next_nomacro1();
2889 if (0 == *file->buf_ptr)
2890 break;
2891 tok_str_add2(&macro_str1, tok, &tokc);
2892 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2893 n, cstr.data, (char*)cstr.data + n);
2895 tcc_close();
2896 cstr_free(&cstr);
2899 if (tok != TOK_NOSUBST)
2900 start_of_nosubsts = -1;
2901 tok_str_add2(&macro_str1, tok, &tokc);
2903 tok_str_add(&macro_str1, 0);
2904 return macro_str1.str;
2908 /* do macro substitution of macro_str and add result to
2909 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2910 inside to avoid recursing. */
2911 static void macro_subst(TokenString *tok_str, Sym **nested_list,
2912 const int *macro_str, struct macro_level ** can_read_stream)
2914 Sym *s;
2915 int *macro_str1;
2916 const int *ptr;
2917 int t, ret, spc;
2918 CValue cval;
2919 struct macro_level ml;
2920 int force_blank;
2922 /* first scan for '##' operator handling */
2923 ptr = macro_str;
2924 macro_str1 = macro_twosharps(ptr);
2926 if (macro_str1)
2927 ptr = macro_str1;
2928 spc = 0;
2929 force_blank = 0;
2931 while (1) {
2932 /* NOTE: ptr == NULL can only happen if tokens are read from
2933 file stream due to a macro function call */
2934 if (ptr == NULL)
2935 break;
2936 TOK_GET(&t, &ptr, &cval);
2937 if (t == 0)
2938 break;
2939 if (t == TOK_NOSUBST) {
2940 /* following token has already been subst'd. just copy it on */
2941 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
2942 TOK_GET(&t, &ptr, &cval);
2943 goto no_subst;
2945 s = define_find(t);
2946 if (s != NULL) {
2947 /* if nested substitution, do nothing */
2948 if (sym_find2(*nested_list, t)) {
2949 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
2950 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
2951 goto no_subst;
2953 ml.p = macro_ptr;
2954 if (can_read_stream)
2955 ml.prev = *can_read_stream, *can_read_stream = &ml;
2956 macro_ptr = (int *)ptr;
2957 tok = t;
2958 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
2959 ptr = (int *)macro_ptr;
2960 macro_ptr = ml.p;
2961 if (can_read_stream && *can_read_stream == &ml)
2962 *can_read_stream = ml.prev;
2963 if (ret != 0)
2964 goto no_subst;
2965 if (parse_flags & PARSE_FLAG_SPACES)
2966 force_blank = 1;
2967 } else {
2968 no_subst:
2969 if (force_blank) {
2970 tok_str_add(tok_str, ' ');
2971 spc = 1;
2972 force_blank = 0;
2974 if (!check_space(t, &spc))
2975 tok_str_add2(tok_str, t, &cval);
2978 if (macro_str1)
2979 tok_str_free(macro_str1);
2982 /* return next token with macro substitution */
2983 ST_FUNC void next(void)
2985 Sym *nested_list, *s;
2986 TokenString str;
2987 struct macro_level *ml;
2989 redo:
2990 if (parse_flags & PARSE_FLAG_SPACES)
2991 next_nomacro_spc();
2992 else
2993 next_nomacro();
2994 if (!macro_ptr) {
2995 /* if not reading from macro substituted string, then try
2996 to substitute macros */
2997 if (tok >= TOK_IDENT &&
2998 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2999 s = define_find(tok);
3000 if (s) {
3001 /* we have a macro: we try to substitute */
3002 tok_str_new(&str);
3003 nested_list = NULL;
3004 ml = NULL;
3005 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
3006 /* substitution done, NOTE: maybe empty */
3007 tok_str_add(&str, 0);
3008 macro_ptr = str.str;
3009 macro_ptr_allocated = str.str;
3010 goto redo;
3014 } else {
3015 if (tok == 0) {
3016 /* end of macro or end of unget buffer */
3017 if (unget_buffer_enabled) {
3018 macro_ptr = unget_saved_macro_ptr;
3019 unget_buffer_enabled = 0;
3020 } else {
3021 /* end of macro string: free it */
3022 tok_str_free(macro_ptr_allocated);
3023 macro_ptr_allocated = NULL;
3024 macro_ptr = NULL;
3026 goto redo;
3027 } else if (tok == TOK_NOSUBST) {
3028 /* discard preprocessor's nosubst markers */
3029 goto redo;
3033 /* convert preprocessor tokens into C tokens */
3034 if (tok == TOK_PPNUM &&
3035 (parse_flags & PARSE_FLAG_TOK_NUM)) {
3036 parse_number((char *)tokc.cstr->data);
3040 /* push back current token and set current token to 'last_tok'. Only
3041 identifier case handled for labels. */
3042 ST_INLN void unget_tok(int last_tok)
3044 int i, n;
3045 int *q;
3046 if (unget_buffer_enabled)
3048 /* assert(macro_ptr == unget_saved_buffer + 1);
3049 assert(*macro_ptr == 0); */
3051 else
3053 unget_saved_macro_ptr = macro_ptr;
3054 unget_buffer_enabled = 1;
3056 q = unget_saved_buffer;
3057 macro_ptr = q;
3058 *q++ = tok;
3059 n = tok_ext_size(tok) - 1;
3060 for(i=0;i<n;i++)
3061 *q++ = tokc.tab[i];
3062 *q = 0; /* end of token string */
3063 tok = last_tok;
3067 /* better than nothing, but needs extension to handle '-E' option
3068 correctly too */
3069 ST_FUNC void preprocess_init(TCCState *s1)
3071 s1->include_stack_ptr = s1->include_stack;
3072 /* XXX: move that before to avoid having to initialize
3073 file->ifdef_stack_ptr ? */
3074 s1->ifdef_stack_ptr = s1->ifdef_stack;
3075 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3077 vtop = vstack - 1;
3078 s1->pack_stack[0] = 0;
3079 s1->pack_stack_ptr = s1->pack_stack;
3082 ST_FUNC void preprocess_new(void)
3084 int i, c;
3085 const char *p, *r;
3087 /* init isid table */
3088 for(i=CH_EOF;i<256;i++)
3089 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
3091 /* add all tokens */
3092 table_ident = NULL;
3093 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3095 tok_ident = TOK_IDENT;
3096 p = tcc_keywords;
3097 while (*p) {
3098 r = p;
3099 for(;;) {
3100 c = *r++;
3101 if (c == '\0')
3102 break;
3104 tok_alloc(p, r - p - 1);
3105 p = r;
3109 /* Preprocess the current file */
3110 ST_FUNC int tcc_preprocess(TCCState *s1)
3112 Sym *define_start;
3114 BufferedFile *file_ref, **iptr, **iptr_new;
3115 int token_seen, line_ref, d;
3116 const char *s;
3118 preprocess_init(s1);
3119 define_start = define_stack;
3120 ch = file->buf_ptr[0];
3121 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3122 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
3123 PARSE_FLAG_LINEFEED | PARSE_FLAG_SPACES;
3124 token_seen = 0;
3125 line_ref = 0;
3126 file_ref = NULL;
3127 iptr = s1->include_stack_ptr;
3129 for (;;) {
3130 next();
3131 if (tok == TOK_EOF) {
3132 break;
3133 } else if (file != file_ref) {
3134 goto print_line;
3135 } else if (tok == TOK_LINEFEED) {
3136 if (!token_seen)
3137 continue;
3138 ++line_ref;
3139 token_seen = 0;
3140 } else if (!token_seen) {
3141 d = file->line_num - line_ref;
3142 if (file != file_ref || d < 0 || d >= 8) {
3143 print_line:
3144 iptr_new = s1->include_stack_ptr;
3145 s = iptr_new > iptr ? " 1"
3146 : iptr_new < iptr ? " 2"
3147 : iptr_new > s1->include_stack ? " 3"
3148 : ""
3150 iptr = iptr_new;
3151 fprintf(s1->ppfp, "# %d \"%s\"%s\n", file->line_num, file->filename, s);
3152 } else {
3153 while (d)
3154 fputs("\n", s1->ppfp), --d;
3156 line_ref = (file_ref = file)->line_num;
3157 token_seen = tok != TOK_LINEFEED;
3158 if (!token_seen)
3159 continue;
3161 fputs(get_tok_str(tok, &tokc), s1->ppfp);
3163 free_defines(define_start);
3164 return 0;