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