Fixed typo from commit 0ac8aaab1bef770929e5592d02bc06d3a529952e
[tinycc.git] / tccpp.c
blobfbf109bddd0be0ca4d289f9f2dde7fe24ad9efe6
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;
977 memset(&cval, 0, sizeof(CValue));
979 /* save line number info */
980 if (file->line_num != s->last_line_num) {
981 s->last_line_num = file->line_num;
982 cval.i = s->last_line_num;
983 tok_str_add2(s, TOK_LINENUM, &cval);
985 tok_str_add2(s, tok, &tokc);
988 /* get a token from an integer array and increment pointer
989 accordingly. we code it as a macro to avoid pointer aliasing. */
990 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
992 const int *p = *pp;
993 int n, *tab;
995 tab = cv->tab;
996 switch(*t = *p++) {
997 case TOK_CINT:
998 case TOK_CUINT:
999 case TOK_CCHAR:
1000 case TOK_LCHAR:
1001 case TOK_CFLOAT:
1002 case TOK_LINENUM:
1003 tab[0] = *p++;
1004 break;
1005 case TOK_STR:
1006 case TOK_LSTR:
1007 case TOK_PPNUM:
1008 cv->cstr = (CString *)p;
1009 cv->cstr->data = (char *)p + sizeof(CString);
1010 p += (sizeof(CString) + cv->cstr->size + 3) >> 2;
1011 break;
1012 case TOK_CDOUBLE:
1013 case TOK_CLLONG:
1014 case TOK_CULLONG:
1015 n = 2;
1016 goto copy;
1017 case TOK_CLDOUBLE:
1018 #if LDOUBLE_SIZE == 16
1019 n = 4;
1020 #elif LDOUBLE_SIZE == 12
1021 n = 3;
1022 #elif LDOUBLE_SIZE == 8
1023 n = 2;
1024 #else
1025 # error add long double size support
1026 #endif
1027 copy:
1029 *tab++ = *p++;
1030 while (--n);
1031 break;
1032 default:
1033 break;
1035 *pp = p;
1038 static int macro_is_equal(const int *a, const int *b)
1040 char buf[STRING_MAX_SIZE + 1];
1041 int t;
1042 CValue cv;
1043 memset(&cv, 0, sizeof(CValue));
1044 while (*a && *b) {
1045 TOK_GET(&t, &a, &cv);
1046 pstrcpy(buf, sizeof buf, get_tok_str(t, &cv));
1047 TOK_GET(&t, &b, &cv);
1048 if (strcmp(buf, get_tok_str(t, &cv)))
1049 return 0;
1051 return !(*a || *b);
1054 /* defines handling */
1055 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1057 Sym *s;
1059 s = define_find(v);
1060 if (s && !macro_is_equal(s->d, str))
1061 tcc_warning("%s redefined", get_tok_str(v, NULL));
1063 s = sym_push2(&define_stack, v, macro_type, 0);
1064 s->d = str;
1065 s->next = first_arg;
1066 table_ident[v - TOK_IDENT]->sym_define = s;
1069 /* undefined a define symbol. Its name is just set to zero */
1070 ST_FUNC void define_undef(Sym *s)
1072 int v;
1073 v = s->v;
1074 if (v >= TOK_IDENT && v < tok_ident)
1075 table_ident[v - TOK_IDENT]->sym_define = NULL;
1076 s->v = 0;
1079 ST_INLN Sym *define_find(int v)
1081 v -= TOK_IDENT;
1082 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1083 return NULL;
1084 return table_ident[v]->sym_define;
1087 /* free define stack until top reaches 'b' */
1088 ST_FUNC void free_defines(Sym *b)
1090 Sym *top, *top1;
1091 int v;
1093 top = define_stack;
1094 while (top != b) {
1095 top1 = top->prev;
1096 /* do not free args or predefined defines */
1097 if (top->d)
1098 tok_str_free(top->d);
1099 v = top->v;
1100 if (v >= TOK_IDENT && v < tok_ident)
1101 table_ident[v - TOK_IDENT]->sym_define = NULL;
1102 sym_free(top);
1103 top = top1;
1105 define_stack = b;
1108 /* label lookup */
1109 ST_FUNC Sym *label_find(int v)
1111 v -= TOK_IDENT;
1112 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1113 return NULL;
1114 return table_ident[v]->sym_label;
1117 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1119 Sym *s, **ps;
1120 s = sym_push2(ptop, v, 0, 0);
1121 s->r = flags;
1122 ps = &table_ident[v - TOK_IDENT]->sym_label;
1123 if (ptop == &global_label_stack) {
1124 /* modify the top most local identifier, so that
1125 sym_identifier will point to 's' when popped */
1126 while (*ps != NULL)
1127 ps = &(*ps)->prev_tok;
1129 s->prev_tok = *ps;
1130 *ps = s;
1131 return s;
1134 /* pop labels until element last is reached. Look if any labels are
1135 undefined. Define symbols if '&&label' was used. */
1136 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1138 Sym *s, *s1;
1139 for(s = *ptop; s != slast; s = s1) {
1140 s1 = s->prev;
1141 if (s->r == LABEL_DECLARED) {
1142 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1143 } else if (s->r == LABEL_FORWARD) {
1144 tcc_error("label '%s' used but not defined",
1145 get_tok_str(s->v, NULL));
1146 } else {
1147 if (s->c) {
1148 /* define corresponding symbol. A size of
1149 1 is put. */
1150 put_extern_sym(s, cur_text_section, s->jnext, 1);
1153 /* remove label */
1154 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1155 sym_free(s);
1157 *ptop = slast;
1160 /* eval an expression for #if/#elif */
1161 static int expr_preprocess(void)
1163 int c, t;
1164 TokenString str;
1166 tok_str_new(&str);
1167 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1168 next(); /* do macro subst */
1169 if (tok == TOK_DEFINED) {
1170 next_nomacro();
1171 t = tok;
1172 if (t == '(')
1173 next_nomacro();
1174 c = define_find(tok) != 0;
1175 if (t == '(')
1176 next_nomacro();
1177 tok = TOK_CINT;
1178 tokc.i = c;
1179 } else if (tok >= TOK_IDENT) {
1180 /* if undefined macro */
1181 tok = TOK_CINT;
1182 tokc.i = 0;
1184 tok_str_add_tok(&str);
1186 tok_str_add(&str, -1); /* simulate end of file */
1187 tok_str_add(&str, 0);
1188 /* now evaluate C constant expression */
1189 macro_ptr = str.str;
1190 next();
1191 c = expr_const();
1192 macro_ptr = NULL;
1193 tok_str_free(str.str);
1194 return c != 0;
1197 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1198 static void tok_print(int *str)
1200 int t;
1201 CValue cval;
1202 memset(&cval, 0, sizeof(CValue));
1204 printf("<");
1205 while (1) {
1206 TOK_GET(&t, &str, &cval);
1207 if (!t)
1208 break;
1209 printf("%s", get_tok_str(t, &cval));
1211 printf(">\n");
1213 #endif
1215 /* parse after #define */
1216 ST_FUNC void parse_define(void)
1218 Sym *s, *first, **ps;
1219 int v, t, varg, is_vaargs, spc;
1220 TokenString str;
1222 v = tok;
1223 if (v < TOK_IDENT)
1224 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1225 /* XXX: should check if same macro (ANSI) */
1226 first = NULL;
1227 t = MACRO_OBJ;
1228 /* '(' must be just after macro definition for MACRO_FUNC */
1229 next_nomacro_spc();
1230 if (tok == '(') {
1231 next_nomacro();
1232 ps = &first;
1233 while (tok != ')') {
1234 varg = tok;
1235 next_nomacro();
1236 is_vaargs = 0;
1237 if (varg == TOK_DOTS) {
1238 varg = TOK___VA_ARGS__;
1239 is_vaargs = 1;
1240 } else if (tok == TOK_DOTS && gnu_ext) {
1241 is_vaargs = 1;
1242 next_nomacro();
1244 if (varg < TOK_IDENT)
1245 tcc_error("badly punctuated parameter list");
1246 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1247 *ps = s;
1248 ps = &s->next;
1249 if (tok != ',')
1250 break;
1251 next_nomacro();
1253 if (tok == ')')
1254 next_nomacro_spc();
1255 t = MACRO_FUNC;
1257 tok_str_new(&str);
1258 spc = 2;
1259 /* EOF testing necessary for '-D' handling */
1260 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1261 /* remove spaces around ## and after '#' */
1262 if (TOK_TWOSHARPS == tok) {
1263 if (1 == spc)
1264 --str.len;
1265 spc = 2;
1266 } else if ('#' == tok) {
1267 spc = 2;
1268 } else if (check_space(tok, &spc)) {
1269 goto skip;
1271 tok_str_add2(&str, tok, &tokc);
1272 skip:
1273 next_nomacro_spc();
1275 if (spc == 1)
1276 --str.len; /* remove trailing space */
1277 tok_str_add(&str, 0);
1278 #ifdef PP_DEBUG
1279 printf("define %s %d: ", get_tok_str(v, NULL), t);
1280 tok_print(str.str);
1281 #endif
1282 define_push(v, t, str.str, first);
1285 static inline int hash_cached_include(const char *filename)
1287 const unsigned char *s;
1288 unsigned int h;
1290 h = TOK_HASH_INIT;
1291 s = (unsigned char *) filename;
1292 while (*s) {
1293 h = TOK_HASH_FUNC(h, *s);
1294 s++;
1296 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1297 return h;
1300 static CachedInclude *search_cached_include(TCCState *s1, const char *filename)
1302 CachedInclude *e;
1303 int i, h;
1304 h = hash_cached_include(filename);
1305 i = s1->cached_includes_hash[h];
1306 for(;;) {
1307 if (i == 0)
1308 break;
1309 e = s1->cached_includes[i - 1];
1310 if (0 == PATHCMP(e->filename, filename))
1311 return e;
1312 i = e->hash_next;
1314 return NULL;
1317 static inline void add_cached_include(TCCState *s1, const char *filename, int ifndef_macro)
1319 CachedInclude *e;
1320 int h;
1322 if (search_cached_include(s1, filename))
1323 return;
1324 #ifdef INC_DEBUG
1325 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
1326 #endif
1327 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1328 strcpy(e->filename, filename);
1329 e->ifndef_macro = ifndef_macro;
1330 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1331 /* add in hash table */
1332 h = hash_cached_include(filename);
1333 e->hash_next = s1->cached_includes_hash[h];
1334 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1337 static void pragma_parse(TCCState *s1)
1339 int val;
1341 next();
1342 if (tok == TOK_pack) {
1344 This may be:
1345 #pragma pack(1) // set
1346 #pragma pack() // reset to default
1347 #pragma pack(push,1) // push & set
1348 #pragma pack(pop) // restore previous
1350 next();
1351 skip('(');
1352 if (tok == TOK_ASM_pop) {
1353 next();
1354 if (s1->pack_stack_ptr <= s1->pack_stack) {
1355 stk_error:
1356 tcc_error("out of pack stack");
1358 s1->pack_stack_ptr--;
1359 } else {
1360 val = 0;
1361 if (tok != ')') {
1362 if (tok == TOK_ASM_push) {
1363 next();
1364 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1365 goto stk_error;
1366 s1->pack_stack_ptr++;
1367 skip(',');
1369 if (tok != TOK_CINT) {
1370 pack_error:
1371 tcc_error("invalid pack pragma");
1373 val = tokc.i;
1374 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1375 goto pack_error;
1376 next();
1378 *s1->pack_stack_ptr = val;
1379 skip(')');
1384 /* is_bof is true if first non space token at beginning of file */
1385 ST_FUNC void preprocess(int is_bof)
1387 TCCState *s1 = tcc_state;
1388 int i, c, n, saved_parse_flags;
1389 char buf[1024], *q;
1390 Sym *s;
1392 saved_parse_flags = parse_flags;
1393 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
1394 PARSE_FLAG_LINEFEED;
1395 next_nomacro();
1396 redo:
1397 switch(tok) {
1398 case TOK_DEFINE:
1399 next_nomacro();
1400 parse_define();
1401 break;
1402 case TOK_UNDEF:
1403 next_nomacro();
1404 s = define_find(tok);
1405 /* undefine symbol by putting an invalid name */
1406 if (s)
1407 define_undef(s);
1408 break;
1409 case TOK_INCLUDE:
1410 case TOK_INCLUDE_NEXT:
1411 ch = file->buf_ptr[0];
1412 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1413 skip_spaces();
1414 if (ch == '<') {
1415 c = '>';
1416 goto read_name;
1417 } else if (ch == '\"') {
1418 c = ch;
1419 read_name:
1420 inp();
1421 q = buf;
1422 while (ch != c && ch != '\n' && ch != CH_EOF) {
1423 if ((q - buf) < sizeof(buf) - 1)
1424 *q++ = ch;
1425 if (ch == '\\') {
1426 if (handle_stray_noerror() == 0)
1427 --q;
1428 } else
1429 inp();
1431 *q = '\0';
1432 minp();
1433 #if 0
1434 /* eat all spaces and comments after include */
1435 /* XXX: slightly incorrect */
1436 while (ch1 != '\n' && ch1 != CH_EOF)
1437 inp();
1438 #endif
1439 } else {
1440 /* computed #include : either we have only strings or
1441 we have anything enclosed in '<>' */
1442 next();
1443 buf[0] = '\0';
1444 if (tok == TOK_STR) {
1445 while (tok != TOK_LINEFEED) {
1446 if (tok != TOK_STR) {
1447 include_syntax:
1448 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1450 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
1451 next();
1453 c = '\"';
1454 } else {
1455 int len;
1456 while (tok != TOK_LINEFEED) {
1457 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1458 next();
1460 len = strlen(buf);
1461 /* check syntax and remove '<>' */
1462 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1463 goto include_syntax;
1464 memmove(buf, buf + 1, len - 2);
1465 buf[len - 2] = '\0';
1466 c = '>';
1470 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1471 tcc_error("#include recursion too deep");
1472 /* store current file in stack, but increment stack later below */
1473 *s1->include_stack_ptr = file;
1475 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
1476 for (i = -2; i < n; ++i) {
1477 char buf1[sizeof file->filename];
1478 CachedInclude *e;
1479 BufferedFile **f;
1480 const char *path;
1482 if (i == -2) {
1483 /* check absolute include path */
1484 if (!IS_ABSPATH(buf))
1485 continue;
1486 buf1[0] = 0;
1487 i = n; /* force end loop */
1489 } else if (i == -1) {
1490 /* search in current dir if "header.h" */
1491 if (c != '\"')
1492 continue;
1493 path = file->filename;
1494 pstrncpy(buf1, path, tcc_basename(path) - path);
1496 } else {
1497 /* search in all the include paths */
1498 if (i < s1->nb_include_paths)
1499 path = s1->include_paths[i];
1500 else
1501 path = s1->sysinclude_paths[i - s1->nb_include_paths];
1502 pstrcpy(buf1, sizeof(buf1), path);
1503 pstrcat(buf1, sizeof(buf1), "/");
1506 pstrcat(buf1, sizeof(buf1), buf);
1508 if (tok == TOK_INCLUDE_NEXT)
1509 for (f = s1->include_stack_ptr; f >= s1->include_stack; --f)
1510 if (0 == PATHCMP((*f)->filename, buf1)) {
1511 #ifdef INC_DEBUG
1512 printf("%s: #include_next skipping %s\n", file->filename, buf1);
1513 #endif
1514 goto include_trynext;
1517 e = search_cached_include(s1, buf1);
1518 if (e && define_find(e->ifndef_macro)) {
1519 /* no need to parse the include because the 'ifndef macro'
1520 is defined */
1521 #ifdef INC_DEBUG
1522 printf("%s: skipping cached %s\n", file->filename, buf1);
1523 #endif
1524 goto include_done;
1527 if (tcc_open(s1, buf1) < 0)
1528 include_trynext:
1529 continue;
1531 #ifdef INC_DEBUG
1532 printf("%s: including %s\n", file->prev->filename, file->filename);
1533 #endif
1534 /* update target deps */
1535 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1536 tcc_strdup(buf1));
1537 /* push current file in stack */
1538 ++s1->include_stack_ptr;
1539 /* add include file debug info */
1540 if (s1->do_debug)
1541 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1542 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1543 ch = file->buf_ptr[0];
1544 goto the_end;
1546 tcc_error("include file '%s' not found", buf);
1547 include_done:
1548 break;
1549 case TOK_IFNDEF:
1550 c = 1;
1551 goto do_ifdef;
1552 case TOK_IF:
1553 c = expr_preprocess();
1554 goto do_if;
1555 case TOK_IFDEF:
1556 c = 0;
1557 do_ifdef:
1558 next_nomacro();
1559 if (tok < TOK_IDENT)
1560 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1561 if (is_bof) {
1562 if (c) {
1563 #ifdef INC_DEBUG
1564 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1565 #endif
1566 file->ifndef_macro = tok;
1569 c = (define_find(tok) != 0) ^ c;
1570 do_if:
1571 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1572 tcc_error("memory full (ifdef)");
1573 *s1->ifdef_stack_ptr++ = c;
1574 goto test_skip;
1575 case TOK_ELSE:
1576 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1577 tcc_error("#else without matching #if");
1578 if (s1->ifdef_stack_ptr[-1] & 2)
1579 tcc_error("#else after #else");
1580 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1581 goto test_else;
1582 case TOK_ELIF:
1583 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1584 tcc_error("#elif without matching #if");
1585 c = s1->ifdef_stack_ptr[-1];
1586 if (c > 1)
1587 tcc_error("#elif after #else");
1588 /* last #if/#elif expression was true: we skip */
1589 if (c == 1)
1590 goto skip;
1591 c = expr_preprocess();
1592 s1->ifdef_stack_ptr[-1] = c;
1593 test_else:
1594 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1595 file->ifndef_macro = 0;
1596 test_skip:
1597 if (!(c & 1)) {
1598 skip:
1599 preprocess_skip();
1600 is_bof = 0;
1601 goto redo;
1603 break;
1604 case TOK_ENDIF:
1605 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1606 tcc_error("#endif without matching #if");
1607 s1->ifdef_stack_ptr--;
1608 /* '#ifndef macro' was at the start of file. Now we check if
1609 an '#endif' is exactly at the end of file */
1610 if (file->ifndef_macro &&
1611 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1612 file->ifndef_macro_saved = file->ifndef_macro;
1613 /* need to set to zero to avoid false matches if another
1614 #ifndef at middle of file */
1615 file->ifndef_macro = 0;
1616 while (tok != TOK_LINEFEED)
1617 next_nomacro();
1618 tok_flags |= TOK_FLAG_ENDIF;
1619 goto the_end;
1621 break;
1622 case TOK_LINE:
1623 next();
1624 if (tok != TOK_CINT)
1625 tcc_error("#line");
1626 file->line_num = tokc.i - 1; /* the line number will be incremented after */
1627 next();
1628 if (tok != TOK_LINEFEED) {
1629 if (tok != TOK_STR)
1630 tcc_error("#line");
1631 pstrcpy(file->filename, sizeof(file->filename),
1632 (char *)tokc.cstr->data);
1634 break;
1635 case TOK_ERROR:
1636 case TOK_WARNING:
1637 c = tok;
1638 ch = file->buf_ptr[0];
1639 skip_spaces();
1640 q = buf;
1641 while (ch != '\n' && ch != CH_EOF) {
1642 if ((q - buf) < sizeof(buf) - 1)
1643 *q++ = ch;
1644 if (ch == '\\') {
1645 if (handle_stray_noerror() == 0)
1646 --q;
1647 } else
1648 inp();
1650 *q = '\0';
1651 if (c == TOK_ERROR)
1652 tcc_error("#error %s", buf);
1653 else
1654 tcc_warning("#warning %s", buf);
1655 break;
1656 case TOK_PRAGMA:
1657 pragma_parse(s1);
1658 break;
1659 default:
1660 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_PPNUM) {
1661 /* '!' is ignored to allow C scripts. numbers are ignored
1662 to emulate cpp behaviour */
1663 } else {
1664 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
1665 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1666 else {
1667 /* this is a gas line comment in an 'S' file. */
1668 file->buf_ptr = parse_line_comment(file->buf_ptr);
1669 goto the_end;
1672 break;
1674 /* ignore other preprocess commands or #! for C scripts */
1675 while (tok != TOK_LINEFEED)
1676 next_nomacro();
1677 the_end:
1678 parse_flags = saved_parse_flags;
1681 /* evaluate escape codes in a string. */
1682 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1684 int c, n;
1685 const uint8_t *p;
1687 p = buf;
1688 for(;;) {
1689 c = *p;
1690 if (c == '\0')
1691 break;
1692 if (c == '\\') {
1693 p++;
1694 /* escape */
1695 c = *p;
1696 switch(c) {
1697 case '0': case '1': case '2': case '3':
1698 case '4': case '5': case '6': case '7':
1699 /* at most three octal digits */
1700 n = c - '0';
1701 p++;
1702 c = *p;
1703 if (isoct(c)) {
1704 n = n * 8 + c - '0';
1705 p++;
1706 c = *p;
1707 if (isoct(c)) {
1708 n = n * 8 + c - '0';
1709 p++;
1712 c = n;
1713 goto add_char_nonext;
1714 case 'x':
1715 case 'u':
1716 case 'U':
1717 p++;
1718 n = 0;
1719 for(;;) {
1720 c = *p;
1721 if (c >= 'a' && c <= 'f')
1722 c = c - 'a' + 10;
1723 else if (c >= 'A' && c <= 'F')
1724 c = c - 'A' + 10;
1725 else if (isnum(c))
1726 c = c - '0';
1727 else
1728 break;
1729 n = n * 16 + c;
1730 p++;
1732 c = n;
1733 goto add_char_nonext;
1734 case 'a':
1735 c = '\a';
1736 break;
1737 case 'b':
1738 c = '\b';
1739 break;
1740 case 'f':
1741 c = '\f';
1742 break;
1743 case 'n':
1744 c = '\n';
1745 break;
1746 case 'r':
1747 c = '\r';
1748 break;
1749 case 't':
1750 c = '\t';
1751 break;
1752 case 'v':
1753 c = '\v';
1754 break;
1755 case 'e':
1756 if (!gnu_ext)
1757 goto invalid_escape;
1758 c = 27;
1759 break;
1760 case '\'':
1761 case '\"':
1762 case '\\':
1763 case '?':
1764 break;
1765 default:
1766 invalid_escape:
1767 if (c >= '!' && c <= '~')
1768 tcc_warning("unknown escape sequence: \'\\%c\'", c);
1769 else
1770 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
1771 break;
1774 p++;
1775 add_char_nonext:
1776 if (!is_long)
1777 cstr_ccat(outstr, c);
1778 else
1779 cstr_wccat(outstr, c);
1781 /* add a trailing '\0' */
1782 if (!is_long)
1783 cstr_ccat(outstr, '\0');
1784 else
1785 cstr_wccat(outstr, '\0');
1788 /* we use 64 bit numbers */
1789 #define BN_SIZE 2
1791 /* bn = (bn << shift) | or_val */
1792 static void bn_lshift(unsigned int *bn, int shift, int or_val)
1794 int i;
1795 unsigned int v;
1796 for(i=0;i<BN_SIZE;i++) {
1797 v = bn[i];
1798 bn[i] = (v << shift) | or_val;
1799 or_val = v >> (32 - shift);
1803 static void bn_zero(unsigned int *bn)
1805 int i;
1806 for(i=0;i<BN_SIZE;i++) {
1807 bn[i] = 0;
1811 /* parse number in null terminated string 'p' and return it in the
1812 current token */
1813 static void parse_number(const char *p)
1815 int b, t, shift, frac_bits, s, exp_val, ch;
1816 char *q;
1817 unsigned int bn[BN_SIZE];
1818 double d;
1820 /* number */
1821 q = token_buf;
1822 ch = *p++;
1823 t = ch;
1824 ch = *p++;
1825 *q++ = t;
1826 b = 10;
1827 if (t == '.') {
1828 goto float_frac_parse;
1829 } else if (t == '0') {
1830 if (ch == 'x' || ch == 'X') {
1831 q--;
1832 ch = *p++;
1833 b = 16;
1834 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
1835 q--;
1836 ch = *p++;
1837 b = 2;
1840 /* parse all digits. cannot check octal numbers at this stage
1841 because of floating point constants */
1842 while (1) {
1843 if (ch >= 'a' && ch <= 'f')
1844 t = ch - 'a' + 10;
1845 else if (ch >= 'A' && ch <= 'F')
1846 t = ch - 'A' + 10;
1847 else if (isnum(ch))
1848 t = ch - '0';
1849 else
1850 break;
1851 if (t >= b)
1852 break;
1853 if (q >= token_buf + STRING_MAX_SIZE) {
1854 num_too_long:
1855 tcc_error("number too long");
1857 *q++ = ch;
1858 ch = *p++;
1860 if (ch == '.' ||
1861 ((ch == 'e' || ch == 'E') && b == 10) ||
1862 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
1863 if (b != 10) {
1864 /* NOTE: strtox should support that for hexa numbers, but
1865 non ISOC99 libcs do not support it, so we prefer to do
1866 it by hand */
1867 /* hexadecimal or binary floats */
1868 /* XXX: handle overflows */
1869 *q = '\0';
1870 if (b == 16)
1871 shift = 4;
1872 else
1873 shift = 2;
1874 bn_zero(bn);
1875 q = token_buf;
1876 while (1) {
1877 t = *q++;
1878 if (t == '\0') {
1879 break;
1880 } else if (t >= 'a') {
1881 t = t - 'a' + 10;
1882 } else if (t >= 'A') {
1883 t = t - 'A' + 10;
1884 } else {
1885 t = t - '0';
1887 bn_lshift(bn, shift, t);
1889 frac_bits = 0;
1890 if (ch == '.') {
1891 ch = *p++;
1892 while (1) {
1893 t = ch;
1894 if (t >= 'a' && t <= 'f') {
1895 t = t - 'a' + 10;
1896 } else if (t >= 'A' && t <= 'F') {
1897 t = t - 'A' + 10;
1898 } else if (t >= '0' && t <= '9') {
1899 t = t - '0';
1900 } else {
1901 break;
1903 if (t >= b)
1904 tcc_error("invalid digit");
1905 bn_lshift(bn, shift, t);
1906 frac_bits += shift;
1907 ch = *p++;
1910 if (ch != 'p' && ch != 'P')
1911 expect("exponent");
1912 ch = *p++;
1913 s = 1;
1914 exp_val = 0;
1915 if (ch == '+') {
1916 ch = *p++;
1917 } else if (ch == '-') {
1918 s = -1;
1919 ch = *p++;
1921 if (ch < '0' || ch > '9')
1922 expect("exponent digits");
1923 while (ch >= '0' && ch <= '9') {
1924 exp_val = exp_val * 10 + ch - '0';
1925 ch = *p++;
1927 exp_val = exp_val * s;
1929 /* now we can generate the number */
1930 /* XXX: should patch directly float number */
1931 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
1932 d = ldexp(d, exp_val - frac_bits);
1933 t = toup(ch);
1934 if (t == 'F') {
1935 ch = *p++;
1936 tok = TOK_CFLOAT;
1937 /* float : should handle overflow */
1938 tokc.f = (float)d;
1939 } else if (t == 'L') {
1940 ch = *p++;
1941 #ifdef TCC_TARGET_PE
1942 tok = TOK_CDOUBLE;
1943 tokc.d = d;
1944 #else
1945 tok = TOK_CLDOUBLE;
1946 /* XXX: not large enough */
1947 tokc.ld = (long double)d;
1948 #endif
1949 } else {
1950 tok = TOK_CDOUBLE;
1951 tokc.d = d;
1953 } else {
1954 /* decimal floats */
1955 if (ch == '.') {
1956 if (q >= token_buf + STRING_MAX_SIZE)
1957 goto num_too_long;
1958 *q++ = ch;
1959 ch = *p++;
1960 float_frac_parse:
1961 while (ch >= '0' && ch <= '9') {
1962 if (q >= token_buf + STRING_MAX_SIZE)
1963 goto num_too_long;
1964 *q++ = ch;
1965 ch = *p++;
1968 if (ch == 'e' || ch == 'E') {
1969 if (q >= token_buf + STRING_MAX_SIZE)
1970 goto num_too_long;
1971 *q++ = ch;
1972 ch = *p++;
1973 if (ch == '-' || ch == '+') {
1974 if (q >= token_buf + STRING_MAX_SIZE)
1975 goto num_too_long;
1976 *q++ = ch;
1977 ch = *p++;
1979 if (ch < '0' || ch > '9')
1980 expect("exponent digits");
1981 while (ch >= '0' && ch <= '9') {
1982 if (q >= token_buf + STRING_MAX_SIZE)
1983 goto num_too_long;
1984 *q++ = ch;
1985 ch = *p++;
1988 *q = '\0';
1989 t = toup(ch);
1990 errno = 0;
1991 if (t == 'F') {
1992 ch = *p++;
1993 tok = TOK_CFLOAT;
1994 tokc.f = strtof(token_buf, NULL);
1995 } else if (t == 'L') {
1996 ch = *p++;
1997 #ifdef TCC_TARGET_PE
1998 tok = TOK_CDOUBLE;
1999 tokc.d = strtod(token_buf, NULL);
2000 #else
2001 tok = TOK_CLDOUBLE;
2002 tokc.ld = strtold(token_buf, NULL);
2003 #endif
2004 } else {
2005 tok = TOK_CDOUBLE;
2006 tokc.d = strtod(token_buf, NULL);
2009 } else {
2010 unsigned long long n, n1;
2011 int lcount, ucount;
2013 /* integer number */
2014 *q = '\0';
2015 q = token_buf;
2016 if (b == 10 && *q == '0') {
2017 b = 8;
2018 q++;
2020 n = 0;
2021 while(1) {
2022 t = *q++;
2023 /* no need for checks except for base 10 / 8 errors */
2024 if (t == '\0') {
2025 break;
2026 } else if (t >= 'a') {
2027 t = t - 'a' + 10;
2028 } else if (t >= 'A') {
2029 t = t - 'A' + 10;
2030 } else {
2031 t = t - '0';
2032 if (t >= b)
2033 tcc_error("invalid digit");
2035 n1 = n;
2036 n = n * b + t;
2037 /* detect overflow */
2038 /* XXX: this test is not reliable */
2039 if (n < n1)
2040 tcc_error("integer constant overflow");
2043 /* XXX: not exactly ANSI compliant */
2044 if ((n & 0xffffffff00000000LL) != 0) {
2045 if ((n >> 63) != 0)
2046 tok = TOK_CULLONG;
2047 else
2048 tok = TOK_CLLONG;
2049 } else if (n > 0x7fffffff) {
2050 tok = TOK_CUINT;
2051 } else {
2052 tok = TOK_CINT;
2054 lcount = 0;
2055 ucount = 0;
2056 for(;;) {
2057 t = toup(ch);
2058 if (t == 'L') {
2059 if (lcount >= 2)
2060 tcc_error("three 'l's in integer constant");
2061 lcount++;
2062 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2063 if (lcount == 2) {
2064 #endif
2065 if (tok == TOK_CINT)
2066 tok = TOK_CLLONG;
2067 else if (tok == TOK_CUINT)
2068 tok = TOK_CULLONG;
2069 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2071 #endif
2072 ch = *p++;
2073 } else if (t == 'U') {
2074 if (ucount >= 1)
2075 tcc_error("two 'u's in integer constant");
2076 ucount++;
2077 if (tok == TOK_CINT)
2078 tok = TOK_CUINT;
2079 else if (tok == TOK_CLLONG)
2080 tok = TOK_CULLONG;
2081 ch = *p++;
2082 } else {
2083 break;
2086 if (tok == TOK_CINT || tok == TOK_CUINT)
2087 tokc.ui = n;
2088 else
2089 tokc.ull = n;
2091 if (ch)
2092 tcc_error("invalid number\n");
2096 #define PARSE2(c1, tok1, c2, tok2) \
2097 case c1: \
2098 PEEKC(c, p); \
2099 if (c == c2) { \
2100 p++; \
2101 tok = tok2; \
2102 } else { \
2103 tok = tok1; \
2105 break;
2107 /* return next token without macro substitution */
2108 static inline void next_nomacro1(void)
2110 int t, c, is_long;
2111 TokenSym *ts;
2112 uint8_t *p, *p1;
2113 unsigned int h;
2115 p = file->buf_ptr;
2116 redo_no_start:
2117 c = *p;
2118 switch(c) {
2119 case ' ':
2120 case '\t':
2121 tok = c;
2122 p++;
2123 goto keep_tok_flags;
2124 case '\f':
2125 case '\v':
2126 case '\r':
2127 p++;
2128 goto redo_no_start;
2129 case '\\':
2130 /* first look if it is in fact an end of buffer */
2131 if (p >= file->buf_end) {
2132 file->buf_ptr = p;
2133 handle_eob();
2134 p = file->buf_ptr;
2135 if (p >= file->buf_end)
2136 goto parse_eof;
2137 else
2138 goto redo_no_start;
2139 } else {
2140 file->buf_ptr = p;
2141 ch = *p;
2142 handle_stray();
2143 p = file->buf_ptr;
2144 goto redo_no_start;
2146 parse_eof:
2148 TCCState *s1 = tcc_state;
2149 if ((parse_flags & PARSE_FLAG_LINEFEED)
2150 && !(tok_flags & TOK_FLAG_EOF)) {
2151 tok_flags |= TOK_FLAG_EOF;
2152 tok = TOK_LINEFEED;
2153 goto keep_tok_flags;
2154 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2155 tok = TOK_EOF;
2156 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2157 tcc_error("missing #endif");
2158 } else if (s1->include_stack_ptr == s1->include_stack) {
2159 /* no include left : end of file. */
2160 tok = TOK_EOF;
2161 } else {
2162 tok_flags &= ~TOK_FLAG_EOF;
2163 /* pop include file */
2165 /* test if previous '#endif' was after a #ifdef at
2166 start of file */
2167 if (tok_flags & TOK_FLAG_ENDIF) {
2168 #ifdef INC_DEBUG
2169 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2170 #endif
2171 add_cached_include(s1, file->filename, file->ifndef_macro_saved);
2172 tok_flags &= ~TOK_FLAG_ENDIF;
2175 /* add end of include file debug info */
2176 if (tcc_state->do_debug) {
2177 put_stabd(N_EINCL, 0, 0);
2179 /* pop include stack */
2180 tcc_close();
2181 s1->include_stack_ptr--;
2182 p = file->buf_ptr;
2183 goto redo_no_start;
2186 break;
2188 case '\n':
2189 file->line_num++;
2190 tok_flags |= TOK_FLAG_BOL;
2191 p++;
2192 maybe_newline:
2193 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2194 goto redo_no_start;
2195 tok = TOK_LINEFEED;
2196 goto keep_tok_flags;
2198 case '#':
2199 /* XXX: simplify */
2200 PEEKC(c, p);
2201 if ((tok_flags & TOK_FLAG_BOL) &&
2202 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2203 file->buf_ptr = p;
2204 preprocess(tok_flags & TOK_FLAG_BOF);
2205 p = file->buf_ptr;
2206 goto maybe_newline;
2207 } else {
2208 if (c == '#') {
2209 p++;
2210 tok = TOK_TWOSHARPS;
2211 } else {
2212 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
2213 p = parse_line_comment(p - 1);
2214 goto redo_no_start;
2215 } else {
2216 tok = '#';
2220 break;
2222 case 'a': case 'b': case 'c': case 'd':
2223 case 'e': case 'f': case 'g': case 'h':
2224 case 'i': case 'j': case 'k': case 'l':
2225 case 'm': case 'n': case 'o': case 'p':
2226 case 'q': case 'r': case 's': case 't':
2227 case 'u': case 'v': case 'w': case 'x':
2228 case 'y': case 'z':
2229 case 'A': case 'B': case 'C': case 'D':
2230 case 'E': case 'F': case 'G': case 'H':
2231 case 'I': case 'J': case 'K':
2232 case 'M': case 'N': case 'O': case 'P':
2233 case 'Q': case 'R': case 'S': case 'T':
2234 case 'U': case 'V': case 'W': case 'X':
2235 case 'Y': case 'Z':
2236 case '_':
2237 parse_ident_fast:
2238 p1 = p;
2239 h = TOK_HASH_INIT;
2240 h = TOK_HASH_FUNC(h, c);
2241 p++;
2242 for(;;) {
2243 c = *p;
2244 if (!isidnum_table[c-CH_EOF])
2245 break;
2246 h = TOK_HASH_FUNC(h, c);
2247 p++;
2249 if (c != '\\') {
2250 TokenSym **pts;
2251 int len;
2253 /* fast case : no stray found, so we have the full token
2254 and we have already hashed it */
2255 len = p - p1;
2256 h &= (TOK_HASH_SIZE - 1);
2257 pts = &hash_ident[h];
2258 for(;;) {
2259 ts = *pts;
2260 if (!ts)
2261 break;
2262 if (ts->len == len && !memcmp(ts->str, p1, len))
2263 goto token_found;
2264 pts = &(ts->hash_next);
2266 ts = tok_alloc_new(pts, (char *) p1, len);
2267 token_found: ;
2268 } else {
2269 /* slower case */
2270 cstr_reset(&tokcstr);
2272 while (p1 < p) {
2273 cstr_ccat(&tokcstr, *p1);
2274 p1++;
2276 p--;
2277 PEEKC(c, p);
2278 parse_ident_slow:
2279 while (isidnum_table[c-CH_EOF]) {
2280 cstr_ccat(&tokcstr, c);
2281 PEEKC(c, p);
2283 ts = tok_alloc(tokcstr.data, tokcstr.size);
2285 tok = ts->tok;
2286 break;
2287 case 'L':
2288 t = p[1];
2289 if (t != '\\' && t != '\'' && t != '\"') {
2290 /* fast case */
2291 goto parse_ident_fast;
2292 } else {
2293 PEEKC(c, p);
2294 if (c == '\'' || c == '\"') {
2295 is_long = 1;
2296 goto str_const;
2297 } else {
2298 cstr_reset(&tokcstr);
2299 cstr_ccat(&tokcstr, 'L');
2300 goto parse_ident_slow;
2303 break;
2304 case '0': case '1': case '2': case '3':
2305 case '4': case '5': case '6': case '7':
2306 case '8': case '9':
2308 cstr_reset(&tokcstr);
2309 /* after the first digit, accept digits, alpha, '.' or sign if
2310 prefixed by 'eEpP' */
2311 parse_num:
2312 for(;;) {
2313 t = c;
2314 cstr_ccat(&tokcstr, c);
2315 PEEKC(c, p);
2316 if (!(isnum(c) || isid(c) || c == '.' ||
2317 ((c == '+' || c == '-') &&
2318 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
2319 break;
2321 /* We add a trailing '\0' to ease parsing */
2322 cstr_ccat(&tokcstr, '\0');
2323 tokc.cstr = &tokcstr;
2324 tok = TOK_PPNUM;
2325 break;
2326 case '.':
2327 /* special dot handling because it can also start a number */
2328 PEEKC(c, p);
2329 if (isnum(c)) {
2330 cstr_reset(&tokcstr);
2331 cstr_ccat(&tokcstr, '.');
2332 goto parse_num;
2333 } else if (c == '.') {
2334 PEEKC(c, p);
2335 if (c != '.')
2336 expect("'.'");
2337 PEEKC(c, p);
2338 tok = TOK_DOTS;
2339 } else {
2340 tok = '.';
2342 break;
2343 case '\'':
2344 case '\"':
2345 is_long = 0;
2346 str_const:
2348 CString str;
2349 int sep;
2351 sep = c;
2353 /* parse the string */
2354 cstr_new(&str);
2355 p = parse_pp_string(p, sep, &str);
2356 cstr_ccat(&str, '\0');
2358 /* eval the escape (should be done as TOK_PPNUM) */
2359 cstr_reset(&tokcstr);
2360 parse_escape_string(&tokcstr, str.data, is_long);
2361 cstr_free(&str);
2363 if (sep == '\'') {
2364 int char_size;
2365 /* XXX: make it portable */
2366 if (!is_long)
2367 char_size = 1;
2368 else
2369 char_size = sizeof(nwchar_t);
2370 if (tokcstr.size <= char_size)
2371 tcc_error("empty character constant");
2372 if (tokcstr.size > 2 * char_size)
2373 tcc_warning("multi-character character constant");
2374 if (!is_long) {
2375 tokc.i = *(int8_t *)tokcstr.data;
2376 tok = TOK_CCHAR;
2377 } else {
2378 tokc.i = *(nwchar_t *)tokcstr.data;
2379 tok = TOK_LCHAR;
2381 } else {
2382 tokc.cstr = &tokcstr;
2383 if (!is_long)
2384 tok = TOK_STR;
2385 else
2386 tok = TOK_LSTR;
2389 break;
2391 case '<':
2392 PEEKC(c, p);
2393 if (c == '=') {
2394 p++;
2395 tok = TOK_LE;
2396 } else if (c == '<') {
2397 PEEKC(c, p);
2398 if (c == '=') {
2399 p++;
2400 tok = TOK_A_SHL;
2401 } else {
2402 tok = TOK_SHL;
2404 } else {
2405 tok = TOK_LT;
2407 break;
2409 case '>':
2410 PEEKC(c, p);
2411 if (c == '=') {
2412 p++;
2413 tok = TOK_GE;
2414 } else if (c == '>') {
2415 PEEKC(c, p);
2416 if (c == '=') {
2417 p++;
2418 tok = TOK_A_SAR;
2419 } else {
2420 tok = TOK_SAR;
2422 } else {
2423 tok = TOK_GT;
2425 break;
2427 case '&':
2428 PEEKC(c, p);
2429 if (c == '&') {
2430 p++;
2431 tok = TOK_LAND;
2432 } else if (c == '=') {
2433 p++;
2434 tok = TOK_A_AND;
2435 } else {
2436 tok = '&';
2438 break;
2440 case '|':
2441 PEEKC(c, p);
2442 if (c == '|') {
2443 p++;
2444 tok = TOK_LOR;
2445 } else if (c == '=') {
2446 p++;
2447 tok = TOK_A_OR;
2448 } else {
2449 tok = '|';
2451 break;
2453 case '+':
2454 PEEKC(c, p);
2455 if (c == '+') {
2456 p++;
2457 tok = TOK_INC;
2458 } else if (c == '=') {
2459 p++;
2460 tok = TOK_A_ADD;
2461 } else {
2462 tok = '+';
2464 break;
2466 case '-':
2467 PEEKC(c, p);
2468 if (c == '-') {
2469 p++;
2470 tok = TOK_DEC;
2471 } else if (c == '=') {
2472 p++;
2473 tok = TOK_A_SUB;
2474 } else if (c == '>') {
2475 p++;
2476 tok = TOK_ARROW;
2477 } else {
2478 tok = '-';
2480 break;
2482 PARSE2('!', '!', '=', TOK_NE)
2483 PARSE2('=', '=', '=', TOK_EQ)
2484 PARSE2('*', '*', '=', TOK_A_MUL)
2485 PARSE2('%', '%', '=', TOK_A_MOD)
2486 PARSE2('^', '^', '=', TOK_A_XOR)
2488 /* comments or operator */
2489 case '/':
2490 PEEKC(c, p);
2491 if (c == '*') {
2492 p = parse_comment(p);
2493 /* comments replaced by a blank */
2494 tok = ' ';
2495 goto keep_tok_flags;
2496 } else if (c == '/') {
2497 p = parse_line_comment(p);
2498 tok = ' ';
2499 goto keep_tok_flags;
2500 } else if (c == '=') {
2501 p++;
2502 tok = TOK_A_DIV;
2503 } else {
2504 tok = '/';
2506 break;
2508 /* simple tokens */
2509 case '(':
2510 case ')':
2511 case '[':
2512 case ']':
2513 case '{':
2514 case '}':
2515 case ',':
2516 case ';':
2517 case ':':
2518 case '?':
2519 case '~':
2520 case '$': /* only used in assembler */
2521 case '@': /* dito */
2522 tok = c;
2523 p++;
2524 break;
2525 default:
2526 tcc_error("unrecognized character \\x%02x", c);
2527 break;
2529 tok_flags = 0;
2530 keep_tok_flags:
2531 file->buf_ptr = p;
2532 #if defined(PARSE_DEBUG)
2533 printf("token = %s\n", get_tok_str(tok, &tokc));
2534 #endif
2537 /* return next token without macro substitution. Can read input from
2538 macro_ptr buffer */
2539 static void next_nomacro_spc(void)
2541 if (macro_ptr) {
2542 redo:
2543 tok = *macro_ptr;
2544 if (tok) {
2545 TOK_GET(&tok, &macro_ptr, &tokc);
2546 if (tok == TOK_LINENUM) {
2547 file->line_num = tokc.i;
2548 goto redo;
2551 } else {
2552 next_nomacro1();
2556 ST_FUNC void next_nomacro(void)
2558 do {
2559 next_nomacro_spc();
2560 } while (is_space(tok));
2563 /* substitute args in macro_str and return allocated string */
2564 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2566 int last_tok, t, spc;
2567 const int *st;
2568 Sym *s;
2569 TokenString str;
2570 CString cstr;
2571 CValue cval;
2572 memset(&cval, 0, sizeof(CValue));
2574 tok_str_new(&str);
2575 last_tok = 0;
2576 while(1) {
2577 TOK_GET(&t, &macro_str, &cval);
2578 if (!t)
2579 break;
2580 if (t == '#') {
2581 /* stringize */
2582 TOK_GET(&t, &macro_str, &cval);
2583 if (!t)
2584 break;
2585 s = sym_find2(args, t);
2586 if (s) {
2587 cstr_new(&cstr);
2588 st = s->d;
2589 spc = 0;
2590 while (*st) {
2591 TOK_GET(&t, &st, &cval);
2592 if (!check_space(t, &spc))
2593 cstr_cat(&cstr, get_tok_str(t, &cval));
2595 cstr.size -= spc;
2596 cstr_ccat(&cstr, '\0');
2597 #ifdef PP_DEBUG
2598 printf("stringize: %s\n", (char *)cstr.data);
2599 #endif
2600 /* add string */
2601 cval.cstr = &cstr;
2602 tok_str_add2(&str, TOK_STR, &cval);
2603 cstr_free(&cstr);
2604 } else {
2605 tok_str_add2(&str, t, &cval);
2607 } else if (t >= TOK_IDENT) {
2608 s = sym_find2(args, t);
2609 if (s) {
2610 st = s->d;
2611 /* if '##' is present before or after, no arg substitution */
2612 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
2613 /* special case for var arg macros : ## eats the
2614 ',' if empty VA_ARGS variable. */
2615 /* XXX: test of the ',' is not 100%
2616 reliable. should fix it to avoid security
2617 problems */
2618 if (gnu_ext && s->type.t &&
2619 last_tok == TOK_TWOSHARPS &&
2620 str.len >= 2 && str.str[str.len - 2] == ',') {
2621 if (*st == 0) {
2622 /* suppress ',' '##' */
2623 str.len -= 2;
2624 } else {
2625 /* suppress '##' and add variable */
2626 str.len--;
2627 goto add_var;
2629 } else {
2630 int t1;
2631 add_var:
2632 for(;;) {
2633 TOK_GET(&t1, &st, &cval);
2634 if (!t1)
2635 break;
2636 tok_str_add2(&str, t1, &cval);
2639 } else {
2640 /* NOTE: the stream cannot be read when macro
2641 substituing an argument */
2642 macro_subst(&str, nested_list, st, NULL);
2644 } else {
2645 tok_str_add(&str, t);
2647 } else {
2648 tok_str_add2(&str, t, &cval);
2650 last_tok = t;
2652 tok_str_add(&str, 0);
2653 return str.str;
2656 static char const ab_month_name[12][4] =
2658 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2659 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2662 /* do macro substitution of current token with macro 's' and add
2663 result to (tok_str,tok_len). 'nested_list' is the list of all
2664 macros we got inside to avoid recursing. Return non zero if no
2665 substitution needs to be done */
2666 static int macro_subst_tok(TokenString *tok_str,
2667 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
2669 Sym *args, *sa, *sa1;
2670 int mstr_allocated, parlevel, *mstr, t, t1, spc;
2671 const int *p;
2672 TokenString str;
2673 char *cstrval;
2674 CString cstr;
2675 char buf[32];
2676 CValue cval;
2677 memset(&cval, 0, sizeof(CValue));
2679 /* if symbol is a macro, prepare substitution */
2680 /* special macros */
2681 if (tok == TOK___LINE__) {
2682 snprintf(buf, sizeof(buf), "%d", file->line_num);
2683 cstrval = buf;
2684 t1 = TOK_PPNUM;
2685 goto add_cstr1;
2686 } else if (tok == TOK___FILE__) {
2687 cstrval = file->filename;
2688 goto add_cstr;
2689 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
2690 time_t ti;
2691 struct tm *tm;
2693 time(&ti);
2694 tm = localtime(&ti);
2695 if (tok == TOK___DATE__) {
2696 snprintf(buf, sizeof(buf), "%s %2d %d",
2697 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
2698 } else {
2699 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
2700 tm->tm_hour, tm->tm_min, tm->tm_sec);
2702 cstrval = buf;
2703 add_cstr:
2704 t1 = TOK_STR;
2705 add_cstr1:
2706 cstr_new(&cstr);
2707 cstr_cat(&cstr, cstrval);
2708 cstr_ccat(&cstr, '\0');
2709 cval.cstr = &cstr;
2710 tok_str_add2(tok_str, t1, &cval);
2711 cstr_free(&cstr);
2712 } else {
2713 mstr = s->d;
2714 mstr_allocated = 0;
2715 if (s->type.t == MACRO_FUNC) {
2716 /* NOTE: we do not use next_nomacro to avoid eating the
2717 next token. XXX: find better solution */
2718 redo:
2719 if (macro_ptr) {
2720 p = macro_ptr;
2721 while (is_space(t = *p) || TOK_LINEFEED == t)
2722 ++p;
2723 if (t == 0 && can_read_stream) {
2724 /* end of macro stream: we must look at the token
2725 after in the file */
2726 struct macro_level *ml = *can_read_stream;
2727 macro_ptr = NULL;
2728 if (ml)
2730 macro_ptr = ml->p;
2731 ml->p = NULL;
2732 *can_read_stream = ml -> prev;
2734 /* also, end of scope for nested defined symbol */
2735 (*nested_list)->v = -1;
2736 goto redo;
2738 } else {
2739 ch = file->buf_ptr[0];
2740 while (is_space(ch) || ch == '\n' || ch == '/')
2742 if (ch == '/')
2744 int c;
2745 uint8_t *p = file->buf_ptr;
2746 PEEKC(c, p);
2747 if (c == '*') {
2748 p = parse_comment(p);
2749 file->buf_ptr = p - 1;
2750 } else if (c == '/') {
2751 p = parse_line_comment(p);
2752 file->buf_ptr = p - 1;
2753 } else
2754 break;
2756 cinp();
2758 t = ch;
2760 if (t != '(') /* no macro subst */
2761 return -1;
2763 /* argument macro */
2764 next_nomacro();
2765 next_nomacro();
2766 args = NULL;
2767 sa = s->next;
2768 /* NOTE: empty args are allowed, except if no args */
2769 for(;;) {
2770 /* handle '()' case */
2771 if (!args && !sa && tok == ')')
2772 break;
2773 if (!sa)
2774 tcc_error("macro '%s' used with too many args",
2775 get_tok_str(s->v, 0));
2776 tok_str_new(&str);
2777 parlevel = spc = 0;
2778 /* NOTE: non zero sa->t indicates VA_ARGS */
2779 while ((parlevel > 0 ||
2780 (tok != ')' &&
2781 (tok != ',' || sa->type.t))) &&
2782 tok != -1) {
2783 if (tok == '(')
2784 parlevel++;
2785 else if (tok == ')')
2786 parlevel--;
2787 if (tok == TOK_LINEFEED)
2788 tok = ' ';
2789 if (!check_space(tok, &spc))
2790 tok_str_add2(&str, tok, &tokc);
2791 next_nomacro_spc();
2793 str.len -= spc;
2794 tok_str_add(&str, 0);
2795 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
2796 sa1->d = str.str;
2797 sa = sa->next;
2798 if (tok == ')') {
2799 /* special case for gcc var args: add an empty
2800 var arg argument if it is omitted */
2801 if (sa && sa->type.t && gnu_ext)
2802 continue;
2803 else
2804 break;
2806 if (tok != ',')
2807 expect(",");
2808 next_nomacro();
2810 if (sa) {
2811 tcc_error("macro '%s' used with too few args",
2812 get_tok_str(s->v, 0));
2815 /* now subst each arg */
2816 mstr = macro_arg_subst(nested_list, mstr, args);
2817 /* free memory */
2818 sa = args;
2819 while (sa) {
2820 sa1 = sa->prev;
2821 tok_str_free(sa->d);
2822 sym_free(sa);
2823 sa = sa1;
2825 mstr_allocated = 1;
2827 sym_push2(nested_list, s->v, 0, 0);
2828 macro_subst(tok_str, nested_list, mstr, can_read_stream);
2829 /* pop nested defined symbol */
2830 sa1 = *nested_list;
2831 *nested_list = sa1->prev;
2832 sym_free(sa1);
2833 if (mstr_allocated)
2834 tok_str_free(mstr);
2836 return 0;
2839 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2840 return the resulting string (which must be freed). */
2841 static inline int *macro_twosharps(const int *macro_str)
2843 const int *ptr;
2844 int t;
2845 TokenString macro_str1;
2846 CString cstr;
2847 int n, start_of_nosubsts;
2849 /* we search the first '##' */
2850 for(ptr = macro_str;;) {
2851 CValue cval;
2852 memset(&cval, 0, sizeof(CValue));
2853 TOK_GET(&t, &ptr, &cval);
2854 if (t == TOK_TWOSHARPS)
2855 break;
2856 /* nothing more to do if end of string */
2857 if (t == 0)
2858 return NULL;
2861 /* we saw '##', so we need more processing to handle it */
2862 start_of_nosubsts = -1;
2863 tok_str_new(&macro_str1);
2864 for(ptr = macro_str;;) {
2865 TOK_GET(&tok, &ptr, &tokc);
2866 if (tok == 0)
2867 break;
2868 if (tok == TOK_TWOSHARPS)
2869 continue;
2870 if (tok == TOK_NOSUBST && start_of_nosubsts < 0)
2871 start_of_nosubsts = macro_str1.len;
2872 while (*ptr == TOK_TWOSHARPS) {
2873 /* given 'a##b', remove nosubsts preceding 'a' */
2874 if (start_of_nosubsts >= 0)
2875 macro_str1.len = start_of_nosubsts;
2876 /* given 'a##b', skip '##' */
2877 t = *++ptr;
2878 /* given 'a##b', remove nosubsts preceding 'b' */
2879 while (t == TOK_NOSUBST)
2880 t = *++ptr;
2881 if (t && t != TOK_TWOSHARPS) {
2882 CValue cval;
2883 memset(&cval, 0, sizeof(CValue));
2884 TOK_GET(&t, &ptr, &cval);
2885 /* We concatenate the two tokens */
2886 cstr_new(&cstr);
2887 cstr_cat(&cstr, get_tok_str(tok, &tokc));
2888 n = cstr.size;
2889 cstr_cat(&cstr, get_tok_str(t, &cval));
2890 cstr_ccat(&cstr, '\0');
2892 tcc_open_bf(tcc_state, ":paste:", cstr.size);
2893 memcpy(file->buffer, cstr.data, cstr.size);
2894 for (;;) {
2895 next_nomacro1();
2896 if (0 == *file->buf_ptr)
2897 break;
2898 tok_str_add2(&macro_str1, tok, &tokc);
2899 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2900 n, cstr.data, (char*)cstr.data + n);
2902 tcc_close();
2903 cstr_free(&cstr);
2906 if (tok != TOK_NOSUBST)
2907 start_of_nosubsts = -1;
2908 tok_str_add2(&macro_str1, tok, &tokc);
2910 tok_str_add(&macro_str1, 0);
2911 return macro_str1.str;
2915 /* do macro substitution of macro_str and add result to
2916 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2917 inside to avoid recursing. */
2918 static void macro_subst(TokenString *tok_str, Sym **nested_list,
2919 const int *macro_str, struct macro_level ** can_read_stream)
2921 Sym *s;
2922 int *macro_str1;
2923 const int *ptr;
2924 int t, ret, spc;
2925 struct macro_level ml;
2926 int force_blank;
2927 CValue cval;
2928 memset(&cval, 0, sizeof(CValue));
2930 /* first scan for '##' operator handling */
2931 ptr = macro_str;
2932 macro_str1 = macro_twosharps(ptr);
2934 if (macro_str1)
2935 ptr = macro_str1;
2936 spc = 0;
2937 force_blank = 0;
2939 while (1) {
2940 /* NOTE: ptr == NULL can only happen if tokens are read from
2941 file stream due to a macro function call */
2942 if (ptr == NULL)
2943 break;
2944 TOK_GET(&t, &ptr, &cval);
2945 if (t == 0)
2946 break;
2947 if (t == TOK_NOSUBST) {
2948 /* following token has already been subst'd. just copy it on */
2949 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
2950 TOK_GET(&t, &ptr, &cval);
2951 goto no_subst;
2953 s = define_find(t);
2954 if (s != NULL) {
2955 /* if nested substitution, do nothing */
2956 if (sym_find2(*nested_list, t)) {
2957 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
2958 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
2959 goto no_subst;
2961 ml.p = macro_ptr;
2962 if (can_read_stream)
2963 ml.prev = *can_read_stream, *can_read_stream = &ml;
2964 macro_ptr = (int *)ptr;
2965 tok = t;
2966 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
2967 ptr = (int *)macro_ptr;
2968 macro_ptr = ml.p;
2969 if (can_read_stream && *can_read_stream == &ml)
2970 *can_read_stream = ml.prev;
2971 if (ret != 0)
2972 goto no_subst;
2973 if (parse_flags & PARSE_FLAG_SPACES)
2974 force_blank = 1;
2975 } else {
2976 no_subst:
2977 if (force_blank) {
2978 tok_str_add(tok_str, ' ');
2979 spc = 1;
2980 force_blank = 0;
2982 if (!check_space(t, &spc))
2983 tok_str_add2(tok_str, t, &cval);
2986 if (macro_str1)
2987 tok_str_free(macro_str1);
2990 /* return next token with macro substitution */
2991 ST_FUNC void next(void)
2993 Sym *nested_list, *s;
2994 TokenString str;
2995 struct macro_level *ml;
2997 redo:
2998 if (parse_flags & PARSE_FLAG_SPACES)
2999 next_nomacro_spc();
3000 else
3001 next_nomacro();
3002 if (!macro_ptr) {
3003 /* if not reading from macro substituted string, then try
3004 to substitute macros */
3005 if (tok >= TOK_IDENT &&
3006 (parse_flags & PARSE_FLAG_PREPROCESS)) {
3007 s = define_find(tok);
3008 if (s) {
3009 /* we have a macro: we try to substitute */
3010 tok_str_new(&str);
3011 nested_list = NULL;
3012 ml = NULL;
3013 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
3014 /* substitution done, NOTE: maybe empty */
3015 tok_str_add(&str, 0);
3016 macro_ptr = str.str;
3017 macro_ptr_allocated = str.str;
3018 goto redo;
3022 } else {
3023 if (tok == 0) {
3024 /* end of macro or end of unget buffer */
3025 if (unget_buffer_enabled) {
3026 macro_ptr = unget_saved_macro_ptr;
3027 unget_buffer_enabled = 0;
3028 } else {
3029 /* end of macro string: free it */
3030 tok_str_free(macro_ptr_allocated);
3031 macro_ptr_allocated = NULL;
3032 macro_ptr = NULL;
3034 goto redo;
3035 } else if (tok == TOK_NOSUBST) {
3036 /* discard preprocessor's nosubst markers */
3037 goto redo;
3041 /* convert preprocessor tokens into C tokens */
3042 if (tok == TOK_PPNUM &&
3043 (parse_flags & PARSE_FLAG_TOK_NUM)) {
3044 parse_number((char *)tokc.cstr->data);
3048 /* push back current token and set current token to 'last_tok'. Only
3049 identifier case handled for labels. */
3050 ST_INLN void unget_tok(int last_tok)
3052 int i, n;
3053 int *q;
3054 if (unget_buffer_enabled)
3056 /* assert(macro_ptr == unget_saved_buffer + 1);
3057 assert(*macro_ptr == 0); */
3059 else
3061 unget_saved_macro_ptr = macro_ptr;
3062 unget_buffer_enabled = 1;
3064 q = unget_saved_buffer;
3065 macro_ptr = q;
3066 *q++ = tok;
3067 n = tok_ext_size(tok) - 1;
3068 for(i=0;i<n;i++)
3069 *q++ = tokc.tab[i];
3070 *q = 0; /* end of token string */
3071 tok = last_tok;
3075 /* better than nothing, but needs extension to handle '-E' option
3076 correctly too */
3077 ST_FUNC void preprocess_init(TCCState *s1)
3079 s1->include_stack_ptr = s1->include_stack;
3080 /* XXX: move that before to avoid having to initialize
3081 file->ifdef_stack_ptr ? */
3082 s1->ifdef_stack_ptr = s1->ifdef_stack;
3083 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3085 vtop = vstack - 1;
3086 s1->pack_stack[0] = 0;
3087 s1->pack_stack_ptr = s1->pack_stack;
3090 ST_FUNC void preprocess_new(void)
3092 int i, c;
3093 const char *p, *r;
3095 /* init isid table */
3096 for(i=CH_EOF;i<256;i++)
3097 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
3099 /* add all tokens */
3100 table_ident = NULL;
3101 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3103 tok_ident = TOK_IDENT;
3104 p = tcc_keywords;
3105 while (*p) {
3106 r = p;
3107 for(;;) {
3108 c = *r++;
3109 if (c == '\0')
3110 break;
3112 tok_alloc(p, r - p - 1);
3113 p = r;
3117 /* Preprocess the current file */
3118 ST_FUNC int tcc_preprocess(TCCState *s1)
3120 Sym *define_start;
3122 BufferedFile *file_ref, **iptr, **iptr_new;
3123 int token_seen, line_ref, d;
3124 const char *s;
3126 preprocess_init(s1);
3127 define_start = define_stack;
3128 ch = file->buf_ptr[0];
3129 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3130 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
3131 PARSE_FLAG_LINEFEED | PARSE_FLAG_SPACES;
3132 token_seen = 0;
3133 line_ref = 0;
3134 file_ref = NULL;
3135 iptr = s1->include_stack_ptr;
3137 for (;;) {
3138 next();
3139 if (tok == TOK_EOF) {
3140 break;
3141 } else if (file != file_ref) {
3142 goto print_line;
3143 } else if (tok == TOK_LINEFEED) {
3144 if (!token_seen)
3145 continue;
3146 ++line_ref;
3147 token_seen = 0;
3148 } else if (!token_seen) {
3149 d = file->line_num - line_ref;
3150 if (file != file_ref || d < 0 || d >= 8) {
3151 print_line:
3152 iptr_new = s1->include_stack_ptr;
3153 s = iptr_new > iptr ? " 1"
3154 : iptr_new < iptr ? " 2"
3155 : iptr_new > s1->include_stack ? " 3"
3156 : ""
3158 iptr = iptr_new;
3159 fprintf(s1->ppfp, "# %d \"%s\"%s\n", file->line_num, file->filename, s);
3160 } else {
3161 while (d)
3162 fputs("\n", s1->ppfp), --d;
3164 line_ref = (file_ref = file)->line_num;
3165 token_seen = tok != TOK_LINEFEED;
3166 if (!token_seen)
3167 continue;
3169 fputs(get_tok_str(tok, &tokc), s1->ppfp);
3171 free_defines(define_start);
3172 return 0;