tccgen.c: Recognise constant expressions with conditional operator.
[tinycc.git] / tccpp.c
blob8b78deb32fdc30db3c97e7966ddfd3f8292734b9
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 ST_DATA int parse_flags;
29 ST_DATA struct BufferedFile *file;
30 ST_DATA int ch, tok;
31 ST_DATA CValue tokc;
32 ST_DATA const int *macro_ptr;
33 ST_DATA CString tokcstr; /* current parsed string, if any */
35 /* display benchmark infos */
36 ST_DATA int total_lines;
37 ST_DATA int total_bytes;
38 ST_DATA int tok_ident;
39 ST_DATA TokenSym **table_ident;
41 /* ------------------------------------------------------------------------- */
43 static TokenSym *hash_ident[TOK_HASH_SIZE];
44 static char token_buf[STRING_MAX_SIZE + 1];
45 static unsigned char isidnum_table[256 - CH_EOF];
46 /* isidnum_table flags: */
47 #define IS_SPC 1
48 #define IS_ID 2
49 #define IS_NUM 4
51 static TokenString *macro_stack;
53 static const char tcc_keywords[] =
54 #define DEF(id, str) str "\0"
55 #include "tcctok.h"
56 #undef DEF
59 /* WARNING: the content of this string encodes token numbers */
60 static const unsigned char tok_two_chars[] =
61 /* outdated -- gr
62 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
63 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
64 */{
65 '<','=', TOK_LE,
66 '>','=', TOK_GE,
67 '!','=', TOK_NE,
68 '&','&', TOK_LAND,
69 '|','|', TOK_LOR,
70 '+','+', TOK_INC,
71 '-','-', TOK_DEC,
72 '=','=', TOK_EQ,
73 '<','<', TOK_SHL,
74 '>','>', TOK_SAR,
75 '+','=', TOK_A_ADD,
76 '-','=', TOK_A_SUB,
77 '*','=', TOK_A_MUL,
78 '/','=', TOK_A_DIV,
79 '%','=', TOK_A_MOD,
80 '&','=', TOK_A_AND,
81 '^','=', TOK_A_XOR,
82 '|','=', TOK_A_OR,
83 '-','>', TOK_ARROW,
84 '.','.', 0xa8, // C++ token ?
85 '#','#', TOK_TWOSHARPS,
89 static void next_nomacro_spc(void);
91 ST_FUNC void skip(int c)
93 if (tok != c)
94 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
95 next();
98 ST_FUNC void expect(const char *msg)
100 tcc_error("%s expected", msg);
103 ST_FUNC void begin_macro(TokenString *str, int alloc)
105 str->alloc = alloc;
106 str->prev = macro_stack;
107 str->prev_ptr = macro_ptr;
108 macro_ptr = str->str;
109 macro_stack = str;
112 ST_FUNC void end_macro(void)
114 TokenString *str = macro_stack;
115 macro_stack = str->prev;
116 macro_ptr = str->prev_ptr;
117 if (str->alloc == 2) {
118 str->alloc = 3; /* just mark as finished */
119 } else {
120 tok_str_free(str->str);
121 if (str->alloc == 1)
122 tcc_free(str);
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 const 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 switch(v) {
293 case TOK_CINT:
294 case TOK_CUINT:
295 /* XXX: not quite exact, but only useful for testing */
296 sprintf(p, "%llu", (unsigned long long)cv->i);
297 break;
298 case TOK_CLLONG:
299 case TOK_CULLONG:
300 /* XXX: not quite exact, but only useful for testing */
301 #ifdef _WIN32
302 sprintf(p, "%u", (unsigned)cv->i);
303 #else
304 sprintf(p, "%llu", (unsigned long long)cv->i);
305 #endif
306 break;
307 case TOK_LCHAR:
308 cstr_ccat(&cstr_buf, 'L');
309 case TOK_CCHAR:
310 cstr_ccat(&cstr_buf, '\'');
311 add_char(&cstr_buf, cv->i);
312 cstr_ccat(&cstr_buf, '\'');
313 cstr_ccat(&cstr_buf, '\0');
314 break;
315 case TOK_PPNUM:
316 case TOK_PPSTR:
317 return (char*)cv->cstr->data;
318 case TOK_LSTR:
319 cstr_ccat(&cstr_buf, 'L');
320 case TOK_STR:
321 cstr = cv->cstr;
322 cstr_ccat(&cstr_buf, '\"');
323 if (v == TOK_STR) {
324 len = cstr->size - 1;
325 for(i=0;i<len;i++)
326 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
327 } else {
328 len = (cstr->size / sizeof(nwchar_t)) - 1;
329 for(i=0;i<len;i++)
330 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
332 cstr_ccat(&cstr_buf, '\"');
333 cstr_ccat(&cstr_buf, '\0');
334 break;
336 case TOK_CFLOAT:
337 case TOK_CDOUBLE:
338 case TOK_CLDOUBLE:
339 case TOK_LINENUM:
340 return NULL; /* should not happen */
342 /* above tokens have value, the ones below don't */
344 case TOK_LT:
345 v = '<';
346 goto addv;
347 case TOK_GT:
348 v = '>';
349 goto addv;
350 case TOK_DOTS:
351 return strcpy(p, "...");
352 case TOK_A_SHL:
353 return strcpy(p, "<<=");
354 case TOK_A_SAR:
355 return strcpy(p, ">>=");
356 default:
357 if (v < TOK_IDENT) {
358 /* search in two bytes table */
359 const unsigned char *q = tok_two_chars;
360 while (*q) {
361 if (q[2] == v) {
362 *p++ = q[0];
363 *p++ = q[1];
364 *p = '\0';
365 return buf;
367 q += 3;
369 if (v >= 127) {
370 sprintf(buf, "<%02x>", v);
371 return buf;
373 addv:
374 *p++ = v;
375 *p = '\0';
376 } else if (v < tok_ident) {
377 return table_ident[v - TOK_IDENT]->str;
378 } else if (v >= SYM_FIRST_ANOM) {
379 /* special name for anonymous symbol */
380 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
381 } else {
382 /* should never happen */
383 return NULL;
385 break;
387 return cstr_buf.data;
390 /* return the current character, handling end of block if necessary
391 (but not stray) */
392 ST_FUNC int handle_eob(void)
394 BufferedFile *bf = file;
395 int len;
397 /* only tries to read if really end of buffer */
398 if (bf->buf_ptr >= bf->buf_end) {
399 if (bf->fd != -1) {
400 #if defined(PARSE_DEBUG)
401 len = 1;
402 #else
403 len = IO_BUF_SIZE;
404 #endif
405 len = read(bf->fd, bf->buffer, len);
406 if (len < 0)
407 len = 0;
408 } else {
409 len = 0;
411 total_bytes += len;
412 bf->buf_ptr = bf->buffer;
413 bf->buf_end = bf->buffer + len;
414 *bf->buf_end = CH_EOB;
416 if (bf->buf_ptr < bf->buf_end) {
417 return bf->buf_ptr[0];
418 } else {
419 bf->buf_ptr = bf->buf_end;
420 return CH_EOF;
424 /* read next char from current input file and handle end of input buffer */
425 ST_INLN void inp(void)
427 ch = *(++(file->buf_ptr));
428 /* end of buffer/file handling */
429 if (ch == CH_EOB)
430 ch = handle_eob();
433 /* handle '\[\r]\n' */
434 static int handle_stray_noerror(void)
436 while (ch == '\\') {
437 inp();
438 if (ch == '\n') {
439 file->line_num++;
440 inp();
441 } else if (ch == '\r') {
442 inp();
443 if (ch != '\n')
444 goto fail;
445 file->line_num++;
446 inp();
447 } else {
448 fail:
449 return 1;
452 return 0;
455 static void handle_stray(void)
457 if (handle_stray_noerror())
458 tcc_error("stray '\\' in program");
461 /* skip the stray and handle the \\n case. Output an error if
462 incorrect char after the stray */
463 static int handle_stray1(uint8_t *p)
465 int c;
467 file->buf_ptr = p;
468 if (p >= file->buf_end) {
469 c = handle_eob();
470 if (c != '\\')
471 return c;
472 p = file->buf_ptr;
474 ch = *p;
475 if (handle_stray_noerror()) {
476 if (!(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
477 tcc_error("stray '\\' in program");
478 *--file->buf_ptr = '\\';
480 p = file->buf_ptr;
481 c = *p;
482 return c;
485 /* handle just the EOB case, but not stray */
486 #define PEEKC_EOB(c, p)\
488 p++;\
489 c = *p;\
490 if (c == '\\') {\
491 file->buf_ptr = p;\
492 c = handle_eob();\
493 p = file->buf_ptr;\
497 /* handle the complicated stray case */
498 #define PEEKC(c, p)\
500 p++;\
501 c = *p;\
502 if (c == '\\') {\
503 c = handle_stray1(p);\
504 p = file->buf_ptr;\
508 /* input with '\[\r]\n' handling. Note that this function cannot
509 handle other characters after '\', so you cannot call it inside
510 strings or comments */
511 ST_FUNC void minp(void)
513 inp();
514 if (ch == '\\')
515 handle_stray();
519 /* single line C++ comments */
520 static uint8_t *parse_line_comment(uint8_t *p)
522 int c;
524 p++;
525 for(;;) {
526 c = *p;
527 redo:
528 if (c == '\n' || c == CH_EOF) {
529 break;
530 } else if (c == '\\') {
531 file->buf_ptr = p;
532 c = handle_eob();
533 p = file->buf_ptr;
534 if (c == '\\') {
535 PEEKC_EOB(c, p);
536 if (c == '\n') {
537 file->line_num++;
538 PEEKC_EOB(c, p);
539 } else if (c == '\r') {
540 PEEKC_EOB(c, p);
541 if (c == '\n') {
542 file->line_num++;
543 PEEKC_EOB(c, p);
546 } else {
547 goto redo;
549 } else {
550 p++;
553 return p;
556 /* C comments */
557 ST_FUNC uint8_t *parse_comment(uint8_t *p)
559 int c;
561 p++;
562 for(;;) {
563 /* fast skip loop */
564 for(;;) {
565 c = *p;
566 if (c == '\n' || c == '*' || c == '\\')
567 break;
568 p++;
569 c = *p;
570 if (c == '\n' || c == '*' || c == '\\')
571 break;
572 p++;
574 /* now we can handle all the cases */
575 if (c == '\n') {
576 file->line_num++;
577 p++;
578 } else if (c == '*') {
579 p++;
580 for(;;) {
581 c = *p;
582 if (c == '*') {
583 p++;
584 } else if (c == '/') {
585 goto end_of_comment;
586 } else if (c == '\\') {
587 file->buf_ptr = p;
588 c = handle_eob();
589 p = file->buf_ptr;
590 if (c == CH_EOF)
591 tcc_error("unexpected end of file in comment");
592 if (c == '\\') {
593 /* skip '\[\r]\n', otherwise just skip the stray */
594 while (c == '\\') {
595 PEEKC_EOB(c, p);
596 if (c == '\n') {
597 file->line_num++;
598 PEEKC_EOB(c, p);
599 } else if (c == '\r') {
600 PEEKC_EOB(c, p);
601 if (c == '\n') {
602 file->line_num++;
603 PEEKC_EOB(c, p);
605 } else {
606 goto after_star;
610 } else {
611 break;
614 after_star: ;
615 } else {
616 /* stray, eob or eof */
617 file->buf_ptr = p;
618 c = handle_eob();
619 p = file->buf_ptr;
620 if (c == CH_EOF) {
621 tcc_error("unexpected end of file in comment");
622 } else if (c == '\\') {
623 p++;
627 end_of_comment:
628 p++;
629 return p;
632 #define cinp minp
634 static inline void skip_spaces(void)
636 while (isidnum_table[ch - CH_EOF] & IS_SPC)
637 cinp();
640 static inline int check_space(int t, int *spc)
642 if (t < 256 && (isidnum_table[t - CH_EOF] & IS_SPC)) {
643 if (*spc)
644 return 1;
645 *spc = 1;
646 } else
647 *spc = 0;
648 return 0;
651 /* parse a string without interpreting escapes */
652 static uint8_t *parse_pp_string(uint8_t *p,
653 int sep, CString *str)
655 int c;
656 p++;
657 for(;;) {
658 c = *p;
659 if (c == sep) {
660 break;
661 } else if (c == '\\') {
662 file->buf_ptr = p;
663 c = handle_eob();
664 p = file->buf_ptr;
665 if (c == CH_EOF) {
666 unterminated_string:
667 /* XXX: indicate line number of start of string */
668 tcc_error("missing terminating %c character", sep);
669 } else if (c == '\\') {
670 /* escape : just skip \[\r]\n */
671 PEEKC_EOB(c, p);
672 if (c == '\n') {
673 file->line_num++;
674 p++;
675 } else if (c == '\r') {
676 PEEKC_EOB(c, p);
677 if (c != '\n')
678 expect("'\n' after '\r'");
679 file->line_num++;
680 p++;
681 } else if (c == CH_EOF) {
682 goto unterminated_string;
683 } else {
684 if (str) {
685 cstr_ccat(str, '\\');
686 cstr_ccat(str, c);
688 p++;
691 } else if (c == '\n') {
692 file->line_num++;
693 goto add_char;
694 } else if (c == '\r') {
695 PEEKC_EOB(c, p);
696 if (c != '\n') {
697 if (str)
698 cstr_ccat(str, '\r');
699 } else {
700 file->line_num++;
701 goto add_char;
703 } else {
704 add_char:
705 if (str)
706 cstr_ccat(str, c);
707 p++;
710 p++;
711 return p;
714 /* skip block of text until #else, #elif or #endif. skip also pairs of
715 #if/#endif */
716 static void preprocess_skip(void)
718 int a, start_of_line, c, in_warn_or_error;
719 uint8_t *p;
721 p = file->buf_ptr;
722 a = 0;
723 redo_start:
724 start_of_line = 1;
725 in_warn_or_error = 0;
726 for(;;) {
727 redo_no_start:
728 c = *p;
729 switch(c) {
730 case ' ':
731 case '\t':
732 case '\f':
733 case '\v':
734 case '\r':
735 p++;
736 goto redo_no_start;
737 case '\n':
738 file->line_num++;
739 p++;
740 goto redo_start;
741 case '\\':
742 file->buf_ptr = p;
743 c = handle_eob();
744 if (c == CH_EOF) {
745 expect("#endif");
746 } else if (c == '\\') {
747 ch = file->buf_ptr[0];
748 handle_stray_noerror();
750 p = file->buf_ptr;
751 goto redo_no_start;
752 /* skip strings */
753 case '\"':
754 case '\'':
755 if (in_warn_or_error)
756 goto _default;
757 p = parse_pp_string(p, c, NULL);
758 break;
759 /* skip comments */
760 case '/':
761 if (in_warn_or_error)
762 goto _default;
763 file->buf_ptr = p;
764 ch = *p;
765 minp();
766 p = file->buf_ptr;
767 if (ch == '*') {
768 p = parse_comment(p);
769 } else if (ch == '/') {
770 p = parse_line_comment(p);
772 break;
773 case '#':
774 p++;
775 if (start_of_line) {
776 file->buf_ptr = p;
777 next_nomacro();
778 p = file->buf_ptr;
779 if (a == 0 &&
780 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
781 goto the_end;
782 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
783 a++;
784 else if (tok == TOK_ENDIF)
785 a--;
786 else if( tok == TOK_ERROR || tok == TOK_WARNING)
787 in_warn_or_error = 1;
788 else if (tok == TOK_LINEFEED)
789 goto redo_start;
790 } else if (parse_flags & PARSE_FLAG_ASM_FILE)
791 p = parse_line_comment(p);
792 break;
793 _default:
794 default:
795 p++;
796 break;
798 start_of_line = 0;
800 the_end: ;
801 file->buf_ptr = p;
804 /* ParseState handling */
806 /* XXX: currently, no include file info is stored. Thus, we cannot display
807 accurate messages if the function or data definition spans multiple
808 files */
810 /* save current parse state in 's' */
811 ST_FUNC void save_parse_state(ParseState *s)
813 s->line_num = file->line_num;
814 s->macro_ptr = macro_ptr;
815 s->tok = tok;
816 s->tokc = tokc;
819 /* restore parse state from 's' */
820 ST_FUNC void restore_parse_state(ParseState *s)
822 file->line_num = s->line_num;
823 macro_ptr = s->macro_ptr;
824 tok = s->tok;
825 tokc = s->tokc;
828 /* return the number of additional 'ints' necessary to store the
829 token */
830 static inline int tok_size(const int *p)
832 switch(*p) {
833 /* 4 bytes */
834 case TOK_CINT:
835 case TOK_CUINT:
836 case TOK_CCHAR:
837 case TOK_LCHAR:
838 case TOK_CFLOAT:
839 case TOK_LINENUM:
840 return 1 + 1;
841 case TOK_STR:
842 case TOK_LSTR:
843 case TOK_PPNUM:
844 case TOK_PPSTR:
845 return 1 + ((sizeof(CString) + ((CString *)(p+1))->size + 3) >> 2);
846 case TOK_CDOUBLE:
847 case TOK_CLLONG:
848 case TOK_CULLONG:
849 return 1 + 2;
850 case TOK_CLDOUBLE:
851 return 1 + LDOUBLE_SIZE / 4;
852 default:
853 return 1 + 0;
857 /* token string handling */
859 ST_INLN void tok_str_new(TokenString *s)
861 s->str = NULL;
862 s->len = 0;
863 s->allocated_len = 0;
864 s->last_line_num = -1;
867 ST_FUNC void tok_str_free(int *str)
869 tcc_free(str);
872 static int *tok_str_realloc(TokenString *s)
874 int *str, len;
876 if (s->allocated_len == 0) {
877 len = 8;
878 } else {
879 len = s->allocated_len * 2;
881 str = tcc_realloc(s->str, len * sizeof(int));
882 s->allocated_len = len;
883 s->str = str;
884 return str;
887 ST_FUNC void tok_str_add(TokenString *s, int t)
889 int len, *str;
891 len = s->len;
892 str = s->str;
893 if (len >= s->allocated_len)
894 str = tok_str_realloc(s);
895 str[len++] = t;
896 s->len = len;
899 static void tok_str_add2(TokenString *s, int t, CValue *cv)
901 int len, *str;
903 len = s->len;
904 str = s->str;
906 /* allocate space for worst case */
907 if (len + TOK_MAX_SIZE > s->allocated_len)
908 str = tok_str_realloc(s);
909 str[len++] = t;
910 switch(t) {
911 case TOK_CINT:
912 case TOK_CUINT:
913 case TOK_CCHAR:
914 case TOK_LCHAR:
915 case TOK_CFLOAT:
916 case TOK_LINENUM:
917 str[len++] = cv->tab[0];
918 break;
919 case TOK_PPNUM:
920 case TOK_PPSTR:
921 case TOK_STR:
922 case TOK_LSTR:
924 int nb_words;
925 CString cstr;
927 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
928 while ((len + nb_words) > s->allocated_len)
929 str = tok_str_realloc(s);
930 /* XXX: Insert the CString into the int array.
931 It may end up incorrectly aligned. */
932 cstr.data = 0;
933 cstr.size = cv->cstr->size;
934 cstr.data_allocated = 0;
935 cstr.size_allocated = cstr.size;
936 memcpy(str + len, &cstr, sizeof(CString));
937 memcpy((char *)(str + len) + sizeof(CString),
938 cv->cstr->data, cstr.size);
939 len += nb_words;
941 break;
942 case TOK_CDOUBLE:
943 case TOK_CLLONG:
944 case TOK_CULLONG:
945 #if LDOUBLE_SIZE == 8
946 case TOK_CLDOUBLE:
947 #endif
948 str[len++] = cv->tab[0];
949 str[len++] = cv->tab[1];
950 break;
951 #if LDOUBLE_SIZE == 12
952 case TOK_CLDOUBLE:
953 str[len++] = cv->tab[0];
954 str[len++] = cv->tab[1];
955 str[len++] = cv->tab[2];
956 #elif LDOUBLE_SIZE == 16
957 case TOK_CLDOUBLE:
958 str[len++] = cv->tab[0];
959 str[len++] = cv->tab[1];
960 str[len++] = cv->tab[2];
961 str[len++] = cv->tab[3];
962 #elif LDOUBLE_SIZE != 8
963 #error add long double size support
964 #endif
965 break;
966 default:
967 break;
969 s->len = len;
972 /* add the current parse token in token string 's' */
973 ST_FUNC void tok_str_add_tok(TokenString *s)
975 CValue cval;
977 /* save line number info */
978 if (file->line_num != s->last_line_num) {
979 s->last_line_num = file->line_num;
980 cval.i = s->last_line_num;
981 tok_str_add2(s, TOK_LINENUM, &cval);
983 tok_str_add2(s, tok, &tokc);
986 /* get a token from an integer array and increment pointer
987 accordingly. we code it as a macro to avoid pointer aliasing. */
988 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
990 const int *p = *pp;
991 int n, *tab;
993 tab = cv->tab;
994 switch(*t = *p++) {
995 case TOK_CINT:
996 case TOK_CUINT:
997 case TOK_CCHAR:
998 case TOK_LCHAR:
999 case TOK_CFLOAT:
1000 case TOK_LINENUM:
1001 tab[0] = *p++;
1002 break;
1003 case TOK_STR:
1004 case TOK_LSTR:
1005 case TOK_PPNUM:
1006 case TOK_PPSTR:
1007 /* XXX: Illegal cast: the pointer p may not be correctly aligned! */
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 /* Calling this function is expensive, but it is not possible
1039 to read a token string backwards. */
1040 static int tok_last(const int *str0, const int *str1)
1042 const int *str = str0;
1043 int tok = 0;
1044 CValue cval;
1046 while (str < str1)
1047 TOK_GET(&tok, &str, &cval);
1048 return tok;
1051 static int macro_is_equal(const int *a, const int *b)
1053 char buf[STRING_MAX_SIZE + 1];
1054 CValue cv;
1055 int t;
1056 while (*a && *b) {
1057 TOK_GET(&t, &a, &cv);
1058 pstrcpy(buf, sizeof buf, get_tok_str(t, &cv));
1059 TOK_GET(&t, &b, &cv);
1060 if (strcmp(buf, get_tok_str(t, &cv)))
1061 return 0;
1063 return !(*a || *b);
1066 static void pp_line(TCCState *s1, BufferedFile *f, int level)
1068 int d = f->line_num - f->line_ref;
1069 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_NONE
1070 || (level == 0 && f->line_ref && d < 8))
1072 while (d > 0)
1073 fputs("\n", s1->ppfp), --d;
1075 else
1076 if (s1->Pflag == LINE_MACRO_OUTPUT_FORMAT_STD) {
1077 fprintf(s1->ppfp, "#line %d \"%s\"\n", f->line_num, f->filename);
1079 else {
1080 fprintf(s1->ppfp, "# %d \"%s\"%s\n", f->line_num, f->filename,
1081 level > 0 ? " 1" : level < 0 ? " 2" : "");
1083 f->line_ref = f->line_num;
1086 static void tok_print(const char *msg, const int *str)
1088 FILE *pr = tcc_state->ppfp;
1089 int t;
1090 CValue cval;
1092 fprintf(pr, "%s ", msg);
1093 while (str) {
1094 TOK_GET(&t, &str, &cval);
1095 if (!t)
1096 break;
1097 fprintf(pr,"%s", get_tok_str(t, &cval));
1099 fprintf(pr, "\n");
1102 static int define_print_prepared(Sym *s)
1104 if (!s || !tcc_state->ppfp || tcc_state->dflag == 0)
1105 return 0;
1107 if (s->v < TOK_IDENT || s->v >= tok_ident)
1108 return 0;
1110 if (file) {
1111 file->line_num--;
1112 pp_line(tcc_state, file, 0);
1113 file->line_ref = ++file->line_num;
1115 return 1;
1118 static void define_print(int v)
1120 FILE *pr = tcc_state->ppfp;
1121 Sym *s, *a;
1123 s = define_find(v);
1124 if (define_print_prepared(s) == 0)
1125 return;
1127 fprintf(pr, "// #define %s", get_tok_str(v, NULL));
1128 if (s->type.t == MACRO_FUNC) {
1129 a = s->next;
1130 fprintf(pr,"(");
1131 if (a)
1132 for (;;) {
1133 fprintf(pr,"%s", get_tok_str(a->v & ~SYM_FIELD, NULL));
1134 if (!(a = a->next))
1135 break;
1136 fprintf(pr,",");
1138 fprintf(pr,")");
1140 tok_print("", s->d);
1143 static void undef_print(int v)
1145 FILE *pr = tcc_state->ppfp;
1146 Sym *s;
1148 s = define_find(v);
1149 if (define_print_prepared(s) == 0)
1150 return;
1152 fprintf(pr, "// #undef %s\n", get_tok_str(s->v, NULL));
1155 ST_FUNC void print_defines(void)
1157 Sym *top = define_stack;
1158 while (top) {
1159 define_print(top->v);
1160 top = top->prev;
1164 /* defines handling */
1165 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1167 Sym *s;
1169 s = define_find(v);
1170 if (s && !macro_is_equal(s->d, str))
1171 tcc_warning("%s redefined", get_tok_str(v, NULL));
1173 s = sym_push2(&define_stack, v, macro_type, 0);
1174 s->d = str;
1175 s->next = first_arg;
1176 table_ident[v - TOK_IDENT]->sym_define = s;
1179 /* undefined a define symbol. Its name is just set to zero */
1180 ST_FUNC void define_undef(Sym *s)
1182 int v = s->v;
1183 undef_print(v);
1184 if (v >= TOK_IDENT && v < tok_ident)
1185 table_ident[v - TOK_IDENT]->sym_define = NULL;
1188 ST_INLN Sym *define_find(int v)
1190 v -= TOK_IDENT;
1191 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1192 return NULL;
1193 return table_ident[v]->sym_define;
1196 /* free define stack until top reaches 'b' */
1197 ST_FUNC void free_defines(Sym *b)
1199 Sym *top, *top1;
1200 int v;
1202 top = define_stack;
1203 while (top != b) {
1204 top1 = top->prev;
1205 /* do not free args or predefined defines */
1206 if (top->d)
1207 tok_str_free(top->d);
1208 v = top->v;
1209 if (v >= TOK_IDENT && v < tok_ident)
1210 table_ident[v - TOK_IDENT]->sym_define = NULL;
1211 sym_free(top);
1212 top = top1;
1214 define_stack = b;
1217 /* label lookup */
1218 ST_FUNC Sym *label_find(int v)
1220 v -= TOK_IDENT;
1221 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1222 return NULL;
1223 return table_ident[v]->sym_label;
1226 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1228 Sym *s, **ps;
1229 s = sym_push2(ptop, v, 0, 0);
1230 s->r = flags;
1231 ps = &table_ident[v - TOK_IDENT]->sym_label;
1232 if (ptop == &global_label_stack) {
1233 /* modify the top most local identifier, so that
1234 sym_identifier will point to 's' when popped */
1235 while (*ps != NULL)
1236 ps = &(*ps)->prev_tok;
1238 s->prev_tok = *ps;
1239 *ps = s;
1240 return s;
1243 /* pop labels until element last is reached. Look if any labels are
1244 undefined. Define symbols if '&&label' was used. */
1245 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1247 Sym *s, *s1;
1248 for(s = *ptop; s != slast; s = s1) {
1249 s1 = s->prev;
1250 if (s->r == LABEL_DECLARED) {
1251 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1252 } else if (s->r == LABEL_FORWARD) {
1253 tcc_error("label '%s' used but not defined",
1254 get_tok_str(s->v, NULL));
1255 } else {
1256 if (s->c) {
1257 /* define corresponding symbol. A size of
1258 1 is put. */
1259 put_extern_sym(s, cur_text_section, s->jnext, 1);
1262 /* remove label */
1263 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1264 sym_free(s);
1266 *ptop = slast;
1269 /* eval an expression for #if/#elif */
1270 static int expr_preprocess(void)
1272 int c, t;
1273 TokenString str;
1275 tok_str_new(&str);
1276 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1277 next(); /* do macro subst */
1278 if (tok == TOK_DEFINED) {
1279 next_nomacro();
1280 t = tok;
1281 if (t == '(')
1282 next_nomacro();
1283 c = define_find(tok) != 0;
1284 if (t == '(')
1285 next_nomacro();
1286 tok = TOK_CINT;
1287 tokc.i = c;
1288 } else if (tok >= TOK_IDENT) {
1289 /* if undefined macro */
1290 tok = TOK_CINT;
1291 tokc.i = 0;
1293 tok_str_add_tok(&str);
1295 tok_str_add(&str, -1); /* simulate end of file */
1296 tok_str_add(&str, 0);
1297 /* now evaluate C constant expression */
1298 begin_macro(&str, 0);
1299 next();
1300 c = expr_const();
1301 end_macro();
1302 return c != 0;
1306 /* parse after #define */
1307 ST_FUNC void parse_define(void)
1309 Sym *s, *first, **ps;
1310 int v, t, varg, is_vaargs, spc;
1311 int saved_parse_flags = parse_flags;
1312 TokenString str;
1314 v = tok;
1315 if (v < TOK_IDENT)
1316 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1317 /* XXX: should check if same macro (ANSI) */
1318 first = NULL;
1319 t = MACRO_OBJ;
1320 /* '(' must be just after macro definition for MACRO_FUNC */
1321 parse_flags |= PARSE_FLAG_SPACES;
1322 next_nomacro_spc();
1323 if (tok == '(') {
1324 next_nomacro();
1325 ps = &first;
1326 if (tok != ')') for (;;) {
1327 varg = tok;
1328 next_nomacro();
1329 is_vaargs = 0;
1330 if (varg == TOK_DOTS) {
1331 varg = TOK___VA_ARGS__;
1332 is_vaargs = 1;
1333 } else if (tok == TOK_DOTS && gnu_ext) {
1334 is_vaargs = 1;
1335 next_nomacro();
1337 if (varg < TOK_IDENT)
1338 bad_list:
1339 tcc_error("bad macro parameter list");
1340 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1341 *ps = s;
1342 ps = &s->next;
1343 if (tok == ')')
1344 break;
1345 if (tok != ',' || is_vaargs)
1346 goto bad_list;
1347 next_nomacro();
1349 next_nomacro_spc();
1350 t = MACRO_FUNC;
1352 tok_str_new(&str);
1353 spc = 2;
1354 parse_flags |= PARSE_FLAG_ACCEPT_STRAYS | PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED;
1355 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1356 /* remove spaces around ## and after '#' */
1357 if (TOK_TWOSHARPS == tok) {
1358 if (2 == spc)
1359 goto bad_twosharp;
1360 if (1 == spc)
1361 --str.len;
1362 spc = 3;
1363 } else if ('#' == tok) {
1364 spc = 4;
1365 } else if (check_space(tok, &spc)) {
1366 goto skip;
1368 tok_str_add2(&str, tok, &tokc);
1369 skip:
1370 next_nomacro_spc();
1373 parse_flags = saved_parse_flags;
1374 if (spc == 1)
1375 --str.len; /* remove trailing space */
1376 tok_str_add(&str, 0);
1377 if (3 == spc)
1378 bad_twosharp:
1379 tcc_error("'##' cannot appear at either end of macro");
1380 define_push(v, t, str.str, first);
1381 define_print(v);
1384 static inline int hash_cached_include(const char *filename)
1386 const unsigned char *s;
1387 unsigned int h;
1389 h = TOK_HASH_INIT;
1390 s = (unsigned char *) filename;
1391 while (*s) {
1392 h = TOK_HASH_FUNC(h, *s);
1393 s++;
1395 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1396 return h;
1399 static CachedInclude *search_cached_include(TCCState *s1, const char *filename)
1401 CachedInclude *e;
1402 int i, h;
1403 h = hash_cached_include(filename);
1404 i = s1->cached_includes_hash[h];
1405 for(;;) {
1406 if (i == 0)
1407 break;
1408 e = s1->cached_includes[i - 1];
1409 if (0 == PATHCMP(e->filename, filename))
1410 return e;
1411 i = e->hash_next;
1413 return NULL;
1416 static inline void add_cached_include(TCCState *s1, const char *filename, int ifndef_macro)
1418 CachedInclude *e;
1419 int h;
1421 if (search_cached_include(s1, filename))
1422 return;
1423 #ifdef INC_DEBUG
1424 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
1425 #endif
1426 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1427 strcpy(e->filename, filename);
1428 e->ifndef_macro = ifndef_macro;
1429 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1430 /* add in hash table */
1431 h = hash_cached_include(filename);
1432 e->hash_next = s1->cached_includes_hash[h];
1433 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1436 static void pragma_parse(TCCState *s1)
1438 next_nomacro();
1439 if (tok == TOK_push_macro || tok == TOK_pop_macro) {
1440 int t = tok, v;
1441 Sym *s;
1443 if (next(), tok != '(')
1444 goto pragma_err;
1445 if (next(), tok != TOK_STR)
1446 goto pragma_err;
1447 v = tok_alloc(tokc.cstr->data, tokc.cstr->size - 1)->tok;
1448 if (next(), tok != ')')
1449 goto pragma_err;
1450 if (t == TOK_push_macro) {
1451 while (NULL == (s = define_find(v)))
1452 define_push(v, 0, NULL, NULL);
1453 s->type.ref = s; /* set push boundary */
1454 } else {
1455 for (s = define_stack; s; s = s->prev)
1456 if (s->v == v && s->type.ref == s) {
1457 s->type.ref = NULL;
1458 break;
1461 if (s)
1462 table_ident[v - TOK_IDENT]->sym_define = s->d ? s : NULL;
1463 else
1464 tcc_warning("unbalanced #pragma pop_macro");
1466 } else if (tok == TOK_once) {
1467 add_cached_include(s1, file->filename, TOK_once);
1469 } else if (s1->ppfp) {
1470 /* tcc -E: keep pragmas below unchanged */
1471 unget_tok(' ');
1472 unget_tok(TOK_PRAGMA);
1473 unget_tok('#');
1474 unget_tok(TOK_LINEFEED);
1476 } else if (tok == TOK_pack) {
1477 /* This may be:
1478 #pragma pack(1) // set
1479 #pragma pack() // reset to default
1480 #pragma pack(push,1) // push & set
1481 #pragma pack(pop) // restore previous */
1482 next();
1483 skip('(');
1484 if (tok == TOK_ASM_pop) {
1485 next();
1486 if (s1->pack_stack_ptr <= s1->pack_stack) {
1487 stk_error:
1488 tcc_error("out of pack stack");
1490 s1->pack_stack_ptr--;
1491 } else {
1492 int val = 0;
1493 if (tok != ')') {
1494 if (tok == TOK_ASM_push) {
1495 next();
1496 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1497 goto stk_error;
1498 s1->pack_stack_ptr++;
1499 skip(',');
1501 if (tok != TOK_CINT)
1502 goto pragma_err;
1503 val = tokc.i;
1504 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1505 goto pragma_err;
1506 next();
1508 *s1->pack_stack_ptr = val;
1510 if (tok != ')')
1511 goto pragma_err;
1513 } else if (tok == TOK_comment) {
1514 char *file;
1515 next();
1516 skip('(');
1517 if (tok != TOK_lib)
1518 goto pragma_warn;
1519 next();
1520 skip(',');
1521 if (tok != TOK_STR)
1522 goto pragma_err;
1523 file = tcc_strdup((char *)tokc.cstr->data);
1524 dynarray_add((void ***)&s1->pragma_libs, &s1->nb_pragma_libs, file);
1525 next();
1526 if (tok != ')')
1527 goto pragma_err;
1528 } else {
1529 pragma_warn:
1530 if (s1->warn_unsupported)
1531 tcc_warning("#pragma %s is ignored", get_tok_str(tok, &tokc));
1533 return;
1535 pragma_err:
1536 tcc_error("malformed #pragma directive");
1537 return;
1540 /* is_bof is true if first non space token at beginning of file */
1541 ST_FUNC void preprocess(int is_bof)
1543 TCCState *s1 = tcc_state;
1544 int i, c, n, saved_parse_flags;
1545 char buf[1024], *q;
1546 Sym *s;
1548 saved_parse_flags = parse_flags;
1549 parse_flags = PARSE_FLAG_PREPROCESS
1550 | PARSE_FLAG_TOK_NUM
1551 | PARSE_FLAG_TOK_STR
1552 | PARSE_FLAG_LINEFEED
1553 | (parse_flags & PARSE_FLAG_ASM_FILE)
1556 next_nomacro();
1557 redo:
1558 switch(tok) {
1559 case TOK_DEFINE:
1560 next_nomacro();
1561 parse_define();
1562 break;
1563 case TOK_UNDEF:
1564 next_nomacro();
1565 s = define_find(tok);
1566 /* undefine symbol by putting an invalid name */
1567 if (s)
1568 define_undef(s);
1569 break;
1570 case TOK_INCLUDE:
1571 case TOK_INCLUDE_NEXT:
1572 ch = file->buf_ptr[0];
1573 skip_spaces(); /* XXX: incorrect if comments : use next_nomacro with a special mode */
1574 c = 0;
1575 if (ch == '<')
1576 c = '>';
1577 if (ch == '\"')
1578 c = ch;
1579 if (c) {
1580 inp();
1581 q = buf;
1582 while (ch != c && ch != '\n' && ch != CH_EOF) {
1583 if ((q - buf) < sizeof(buf) - 1)
1584 *q++ = ch;
1585 if (ch == '\\') {
1586 if (handle_stray_noerror() == 0)
1587 --q;
1588 } else
1589 inp();
1591 *q = '\0';
1592 minp();
1593 } else {
1594 /* computed #include : either we have only strings or
1595 we have anything enclosed in '<>' */
1596 next();
1597 buf[0] = '\0';
1598 if (tok == TOK_STR) {
1599 while (tok != TOK_LINEFEED) {
1600 if (tok != TOK_STR) {
1601 include_syntax:
1602 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1604 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
1605 next();
1607 c = '\"';
1608 } else {
1609 int len;
1610 while (tok != TOK_LINEFEED) {
1611 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1612 next();
1614 len = strlen(buf);
1615 /* check syntax and remove '<>' */
1616 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1617 goto include_syntax;
1618 memmove(buf, buf + 1, len - 2);
1619 buf[len - 2] = '\0';
1620 c = '>';
1624 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1625 tcc_error("#include recursion too deep");
1627 i = -2;
1628 if (tok == TOK_INCLUDE_NEXT)
1629 i = file->inc_path_index + 1;
1631 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
1632 for (; i < n; ++i) {
1633 char buf1[sizeof file->filename];
1634 CachedInclude *e;
1635 const char *path;
1637 if (i == -2) {
1638 /* check absolute include path */
1639 if (!IS_ABSPATH(buf))
1640 continue;
1641 buf1[0] = 0;
1642 i = n - 1; /* force end loop */
1644 } else if (i == -1) {
1645 /* search in current dir if "header.h" */
1646 if (c != '\"')
1647 continue;
1648 path = file->filename;
1649 pstrncpy(buf1, path, tcc_basename(path) - path);
1651 } else {
1652 /* search in all the include paths */
1653 if (i < s1->nb_include_paths)
1654 path = s1->include_paths[i];
1655 else
1656 path = s1->sysinclude_paths[i - s1->nb_include_paths];
1657 if (path == 0) continue;
1658 pstrcpy(buf1, sizeof(buf1), path);
1659 pstrcat(buf1, sizeof(buf1), "/");
1662 pstrcat(buf1, sizeof(buf1), buf);
1663 e = search_cached_include(s1, buf1);
1664 if (e && (define_find(e->ifndef_macro) || e->ifndef_macro == TOK_once))
1665 break; /* no need to parse the include */
1667 if (tcc_open(s1, buf1) < 0)
1668 continue;
1670 file->inc_path_index = i;
1671 *(s1->include_stack_ptr++) = file->prev;
1673 /* update target deps */
1674 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1675 tcc_strdup(buf1));
1677 /* add include file debug info */
1678 if (s1->do_debug)
1679 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1681 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1682 ch = file->buf_ptr[0];
1683 break;
1685 if (i >= n) tcc_error("include file '%s' not found", buf);
1686 goto the_end;
1687 case TOK_IFNDEF:
1688 c = 1;
1689 goto do_ifdef;
1690 case TOK_IF:
1691 c = expr_preprocess();
1692 goto do_if;
1693 case TOK_IFDEF:
1694 c = 0;
1695 do_ifdef:
1696 next_nomacro();
1697 if (tok < TOK_IDENT)
1698 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1699 if (is_bof) {
1700 if (c) {
1701 #ifdef INC_DEBUG
1702 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1703 #endif
1704 file->ifndef_macro = tok;
1707 c = (define_find(tok) != 0) ^ c;
1708 do_if:
1709 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1710 tcc_error("memory full (ifdef)");
1711 *s1->ifdef_stack_ptr++ = c;
1712 goto test_skip;
1713 case TOK_ELSE:
1714 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1715 tcc_error("#else without matching #if");
1716 if (s1->ifdef_stack_ptr[-1] & 2)
1717 tcc_error("#else after #else");
1718 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1719 goto test_else;
1720 case TOK_ELIF:
1721 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1722 tcc_error("#elif without matching #if");
1723 c = s1->ifdef_stack_ptr[-1];
1724 if (c > 1)
1725 tcc_error("#elif after #else");
1726 /* last #if/#elif expression was true: we skip */
1727 if (c == 1)
1728 goto skip;
1729 c = expr_preprocess();
1730 s1->ifdef_stack_ptr[-1] = c;
1731 test_else:
1732 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1733 file->ifndef_macro = 0;
1734 test_skip:
1735 if (!(c & 1)) {
1736 skip:
1737 preprocess_skip();
1738 is_bof = 0;
1739 goto redo;
1741 break;
1742 case TOK_ENDIF:
1743 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1744 tcc_error("#endif without matching #if");
1745 s1->ifdef_stack_ptr--;
1746 /* '#ifndef macro' was at the start of file. Now we check if
1747 an '#endif' is exactly at the end of file */
1748 if (file->ifndef_macro &&
1749 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1750 file->ifndef_macro_saved = file->ifndef_macro;
1751 /* need to set to zero to avoid false matches if another
1752 #ifndef at middle of file */
1753 file->ifndef_macro = 0;
1754 while (tok != TOK_LINEFEED)
1755 next_nomacro();
1756 tok_flags |= TOK_FLAG_ENDIF;
1757 goto the_end;
1759 break;
1760 case TOK_PPNUM:
1761 n = strtoul((char*)tokc.cstr->data, &q, 10);
1762 goto _line_num;
1763 case TOK_LINE:
1764 next();
1765 if (tok != TOK_CINT)
1766 _line_err:
1767 tcc_error("wrong #line format");
1768 n = tokc.i;
1769 _line_num:
1770 next();
1771 if (tok != TOK_LINEFEED) {
1772 if (tok == TOK_STR)
1773 pstrcpy(file->filename, sizeof(file->filename), (char *)tokc.cstr->data);
1774 else if (parse_flags & PARSE_FLAG_ASM_FILE)
1775 break;
1776 else
1777 goto _line_err;
1778 --n;
1780 if (file->fd > 0)
1781 total_lines += file->line_num - n;
1782 file->line_num = n;
1783 if (s1->do_debug)
1784 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1785 break;
1786 case TOK_ERROR:
1787 case TOK_WARNING:
1788 c = tok;
1789 ch = file->buf_ptr[0];
1790 skip_spaces();
1791 q = buf;
1792 while (ch != '\n' && ch != CH_EOF) {
1793 if ((q - buf) < sizeof(buf) - 1)
1794 *q++ = ch;
1795 if (ch == '\\') {
1796 if (handle_stray_noerror() == 0)
1797 --q;
1798 } else
1799 inp();
1801 *q = '\0';
1802 if (c == TOK_ERROR)
1803 tcc_error("#error %s", buf);
1804 else
1805 tcc_warning("#warning %s", buf);
1806 break;
1807 case TOK_PRAGMA:
1808 pragma_parse(s1);
1809 break;
1810 case TOK_LINEFEED:
1811 goto the_end;
1812 default:
1813 /* ignore gas line comment in an 'S' file. */
1814 if (saved_parse_flags & PARSE_FLAG_ASM_FILE)
1815 goto ignore;
1816 if (tok == '!' && is_bof)
1817 /* '!' is ignored at beginning to allow C scripts. */
1818 goto ignore;
1819 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1820 ignore:
1821 file->buf_ptr = parse_line_comment(file->buf_ptr);
1822 goto the_end;
1824 /* ignore other preprocess commands or #! for C scripts */
1825 while (tok != TOK_LINEFEED)
1826 next_nomacro();
1827 the_end:
1828 parse_flags = saved_parse_flags;
1831 /* evaluate escape codes in a string. */
1832 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1834 int c, n;
1835 const uint8_t *p;
1837 p = buf;
1838 for(;;) {
1839 c = *p;
1840 if (c == '\0')
1841 break;
1842 if (c == '\\') {
1843 p++;
1844 /* escape */
1845 c = *p;
1846 switch(c) {
1847 case '0': case '1': case '2': case '3':
1848 case '4': case '5': case '6': case '7':
1849 /* at most three octal digits */
1850 n = c - '0';
1851 p++;
1852 c = *p;
1853 if (isoct(c)) {
1854 n = n * 8 + c - '0';
1855 p++;
1856 c = *p;
1857 if (isoct(c)) {
1858 n = n * 8 + c - '0';
1859 p++;
1862 c = n;
1863 goto add_char_nonext;
1864 case 'x':
1865 case 'u':
1866 case 'U':
1867 p++;
1868 n = 0;
1869 for(;;) {
1870 c = *p;
1871 if (c >= 'a' && c <= 'f')
1872 c = c - 'a' + 10;
1873 else if (c >= 'A' && c <= 'F')
1874 c = c - 'A' + 10;
1875 else if (isnum(c))
1876 c = c - '0';
1877 else
1878 break;
1879 n = n * 16 + c;
1880 p++;
1882 c = n;
1883 goto add_char_nonext;
1884 case 'a':
1885 c = '\a';
1886 break;
1887 case 'b':
1888 c = '\b';
1889 break;
1890 case 'f':
1891 c = '\f';
1892 break;
1893 case 'n':
1894 c = '\n';
1895 break;
1896 case 'r':
1897 c = '\r';
1898 break;
1899 case 't':
1900 c = '\t';
1901 break;
1902 case 'v':
1903 c = '\v';
1904 break;
1905 case 'e':
1906 if (!gnu_ext)
1907 goto invalid_escape;
1908 c = 27;
1909 break;
1910 case '\'':
1911 case '\"':
1912 case '\\':
1913 case '?':
1914 break;
1915 default:
1916 invalid_escape:
1917 if (c >= '!' && c <= '~')
1918 tcc_warning("unknown escape sequence: \'\\%c\'", c);
1919 else
1920 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
1921 break;
1924 p++;
1925 add_char_nonext:
1926 if (!is_long)
1927 cstr_ccat(outstr, c);
1928 else
1929 cstr_wccat(outstr, c);
1931 /* add a trailing '\0' */
1932 if (!is_long)
1933 cstr_ccat(outstr, '\0');
1934 else
1935 cstr_wccat(outstr, '\0');
1938 void parse_string(const char *s, int len)
1940 uint8_t buf[1000], *p = buf;
1941 int is_long, sep;
1943 if ((is_long = *s == 'L'))
1944 ++s, --len;
1945 sep = *s++;
1946 len -= 2;
1947 if (len >= sizeof buf)
1948 p = tcc_malloc(len + 1);
1949 memcpy(p, s, len);
1950 p[len] = 0;
1952 cstr_reset(&tokcstr);
1953 parse_escape_string(&tokcstr, p, is_long);
1954 if (p != buf)
1955 tcc_free(p);
1957 if (sep == '\'') {
1958 int char_size;
1959 /* XXX: make it portable */
1960 if (!is_long)
1961 char_size = 1;
1962 else
1963 char_size = sizeof(nwchar_t);
1964 if (tokcstr.size <= char_size)
1965 tcc_error("empty character constant");
1966 if (tokcstr.size > 2 * char_size)
1967 tcc_warning("multi-character character constant");
1968 if (!is_long) {
1969 tokc.i = *(int8_t *)tokcstr.data;
1970 tok = TOK_CCHAR;
1971 } else {
1972 tokc.i = *(nwchar_t *)tokcstr.data;
1973 tok = TOK_LCHAR;
1975 } else {
1976 tokc.cstr = &tokcstr;
1977 if (!is_long)
1978 tok = TOK_STR;
1979 else
1980 tok = TOK_LSTR;
1984 /* we use 64 bit numbers */
1985 #define BN_SIZE 2
1987 /* bn = (bn << shift) | or_val */
1988 static void bn_lshift(unsigned int *bn, int shift, int or_val)
1990 int i;
1991 unsigned int v;
1992 for(i=0;i<BN_SIZE;i++) {
1993 v = bn[i];
1994 bn[i] = (v << shift) | or_val;
1995 or_val = v >> (32 - shift);
1999 static void bn_zero(unsigned int *bn)
2001 int i;
2002 for(i=0;i<BN_SIZE;i++) {
2003 bn[i] = 0;
2007 /* parse number in null terminated string 'p' and return it in the
2008 current token */
2009 static void parse_number(const char *p)
2011 int b, t, shift, frac_bits, s, exp_val, ch;
2012 char *q;
2013 unsigned int bn[BN_SIZE];
2014 double d;
2016 /* number */
2017 q = token_buf;
2018 ch = *p++;
2019 t = ch;
2020 ch = *p++;
2021 *q++ = t;
2022 b = 10;
2023 if (t == '.') {
2024 goto float_frac_parse;
2025 } else if (t == '0') {
2026 if (ch == 'x' || ch == 'X') {
2027 q--;
2028 ch = *p++;
2029 b = 16;
2030 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
2031 q--;
2032 ch = *p++;
2033 b = 2;
2036 /* parse all digits. cannot check octal numbers at this stage
2037 because of floating point constants */
2038 while (1) {
2039 if (ch >= 'a' && ch <= 'f')
2040 t = ch - 'a' + 10;
2041 else if (ch >= 'A' && ch <= 'F')
2042 t = ch - 'A' + 10;
2043 else if (isnum(ch))
2044 t = ch - '0';
2045 else
2046 break;
2047 if (t >= b)
2048 break;
2049 if (q >= token_buf + STRING_MAX_SIZE) {
2050 num_too_long:
2051 tcc_error("number too long");
2053 *q++ = ch;
2054 ch = *p++;
2056 if (ch == '.' ||
2057 ((ch == 'e' || ch == 'E') && b == 10) ||
2058 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
2059 if (b != 10) {
2060 /* NOTE: strtox should support that for hexa numbers, but
2061 non ISOC99 libcs do not support it, so we prefer to do
2062 it by hand */
2063 /* hexadecimal or binary floats */
2064 /* XXX: handle overflows */
2065 *q = '\0';
2066 if (b == 16)
2067 shift = 4;
2068 else
2069 shift = 1;
2070 bn_zero(bn);
2071 q = token_buf;
2072 while (1) {
2073 t = *q++;
2074 if (t == '\0') {
2075 break;
2076 } else if (t >= 'a') {
2077 t = t - 'a' + 10;
2078 } else if (t >= 'A') {
2079 t = t - 'A' + 10;
2080 } else {
2081 t = t - '0';
2083 bn_lshift(bn, shift, t);
2085 frac_bits = 0;
2086 if (ch == '.') {
2087 ch = *p++;
2088 while (1) {
2089 t = ch;
2090 if (t >= 'a' && t <= 'f') {
2091 t = t - 'a' + 10;
2092 } else if (t >= 'A' && t <= 'F') {
2093 t = t - 'A' + 10;
2094 } else if (t >= '0' && t <= '9') {
2095 t = t - '0';
2096 } else {
2097 break;
2099 if (t >= b)
2100 tcc_error("invalid digit");
2101 bn_lshift(bn, shift, t);
2102 frac_bits += shift;
2103 ch = *p++;
2106 if (ch != 'p' && ch != 'P')
2107 expect("exponent");
2108 ch = *p++;
2109 s = 1;
2110 exp_val = 0;
2111 if (ch == '+') {
2112 ch = *p++;
2113 } else if (ch == '-') {
2114 s = -1;
2115 ch = *p++;
2117 if (ch < '0' || ch > '9')
2118 expect("exponent digits");
2119 while (ch >= '0' && ch <= '9') {
2120 exp_val = exp_val * 10 + ch - '0';
2121 ch = *p++;
2123 exp_val = exp_val * s;
2125 /* now we can generate the number */
2126 /* XXX: should patch directly float number */
2127 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
2128 d = ldexp(d, exp_val - frac_bits);
2129 t = toup(ch);
2130 if (t == 'F') {
2131 ch = *p++;
2132 tok = TOK_CFLOAT;
2133 /* float : should handle overflow */
2134 tokc.f = (float)d;
2135 } else if (t == 'L') {
2136 ch = *p++;
2137 #ifdef TCC_TARGET_PE
2138 tok = TOK_CDOUBLE;
2139 tokc.d = d;
2140 #else
2141 tok = TOK_CLDOUBLE;
2142 /* XXX: not large enough */
2143 tokc.ld = (long double)d;
2144 #endif
2145 } else {
2146 tok = TOK_CDOUBLE;
2147 tokc.d = d;
2149 } else {
2150 /* decimal floats */
2151 if (ch == '.') {
2152 if (q >= token_buf + STRING_MAX_SIZE)
2153 goto num_too_long;
2154 *q++ = ch;
2155 ch = *p++;
2156 float_frac_parse:
2157 while (ch >= '0' && ch <= '9') {
2158 if (q >= token_buf + STRING_MAX_SIZE)
2159 goto num_too_long;
2160 *q++ = ch;
2161 ch = *p++;
2164 if (ch == 'e' || ch == 'E') {
2165 if (q >= token_buf + STRING_MAX_SIZE)
2166 goto num_too_long;
2167 *q++ = ch;
2168 ch = *p++;
2169 if (ch == '-' || ch == '+') {
2170 if (q >= token_buf + STRING_MAX_SIZE)
2171 goto num_too_long;
2172 *q++ = ch;
2173 ch = *p++;
2175 if (ch < '0' || ch > '9')
2176 expect("exponent digits");
2177 while (ch >= '0' && ch <= '9') {
2178 if (q >= token_buf + STRING_MAX_SIZE)
2179 goto num_too_long;
2180 *q++ = ch;
2181 ch = *p++;
2184 *q = '\0';
2185 t = toup(ch);
2186 errno = 0;
2187 if (t == 'F') {
2188 ch = *p++;
2189 tok = TOK_CFLOAT;
2190 tokc.f = strtof(token_buf, NULL);
2191 } else if (t == 'L') {
2192 ch = *p++;
2193 #ifdef TCC_TARGET_PE
2194 tok = TOK_CDOUBLE;
2195 tokc.d = strtod(token_buf, NULL);
2196 #else
2197 tok = TOK_CLDOUBLE;
2198 tokc.ld = strtold(token_buf, NULL);
2199 #endif
2200 } else {
2201 tok = TOK_CDOUBLE;
2202 tokc.d = strtod(token_buf, NULL);
2205 } else {
2206 unsigned long long n, n1;
2207 int lcount, ucount, must_64bit;
2208 const char *p1;
2210 /* integer number */
2211 *q = '\0';
2212 q = token_buf;
2213 if (b == 10 && *q == '0') {
2214 b = 8;
2215 q++;
2217 n = 0;
2218 while(1) {
2219 t = *q++;
2220 /* no need for checks except for base 10 / 8 errors */
2221 if (t == '\0')
2222 break;
2223 else if (t >= 'a')
2224 t = t - 'a' + 10;
2225 else if (t >= 'A')
2226 t = t - 'A' + 10;
2227 else
2228 t = t - '0';
2229 if (t >= b)
2230 tcc_error("invalid digit");
2231 n1 = n;
2232 n = n * b + t;
2233 /* detect overflow */
2234 /* XXX: this test is not reliable */
2235 if (n < n1)
2236 tcc_error("integer constant overflow");
2239 /* Determine the characteristics (unsigned and/or 64bit) the type of
2240 the constant must have according to the constant suffix(es) */
2241 lcount = ucount = must_64bit = 0;
2242 p1 = p;
2243 for(;;) {
2244 t = toup(ch);
2245 if (t == 'L') {
2246 if (lcount >= 2)
2247 tcc_error("three 'l's in integer constant");
2248 if (lcount && *(p - 1) != ch)
2249 tcc_error("incorrect integer suffix: %s", p1);
2250 lcount++;
2251 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2252 if (lcount == 2)
2253 #endif
2254 must_64bit = 1;
2255 ch = *p++;
2256 } else if (t == 'U') {
2257 if (ucount >= 1)
2258 tcc_error("two 'u's in integer constant");
2259 ucount++;
2260 ch = *p++;
2261 } else {
2262 break;
2266 /* Whether 64 bits are needed to hold the constant's value */
2267 if (n & 0xffffffff00000000LL || must_64bit) {
2268 tok = TOK_CLLONG;
2269 n1 = n >> 32;
2270 } else {
2271 tok = TOK_CINT;
2272 n1 = n;
2275 /* Whether type must be unsigned to hold the constant's value */
2276 if (ucount || ((n1 >> 31) && (b != 10))) {
2277 if (tok == TOK_CLLONG)
2278 tok = TOK_CULLONG;
2279 else
2280 tok = TOK_CUINT;
2281 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2282 } else if (n1 >> 31) {
2283 if (tok == TOK_CINT)
2284 tok = TOK_CLLONG;
2285 else
2286 tcc_error("integer constant overflow");
2289 if (tok == TOK_CINT || tok == TOK_CUINT)
2290 tokc.i = n;
2291 else
2292 tokc.i = n;
2294 if (ch)
2295 tcc_error("invalid number\n");
2299 #define PARSE2(c1, tok1, c2, tok2) \
2300 case c1: \
2301 PEEKC(c, p); \
2302 if (c == c2) { \
2303 p++; \
2304 tok = tok2; \
2305 } else { \
2306 tok = tok1; \
2308 break;
2310 /* return next token without macro substitution */
2311 static inline void next_nomacro1(void)
2313 int t, c, is_long;
2314 TokenSym *ts;
2315 uint8_t *p, *p1;
2316 unsigned int h;
2318 p = file->buf_ptr;
2319 redo_no_start:
2320 c = *p;
2321 switch(c) {
2322 case ' ':
2323 case '\t':
2324 tok = c;
2325 p++;
2326 if (parse_flags & PARSE_FLAG_SPACES)
2327 goto keep_tok_flags;
2328 while (isidnum_table[*p - CH_EOF] & IS_SPC)
2329 ++p;
2330 goto redo_no_start;
2331 case '\f':
2332 case '\v':
2333 case '\r':
2334 p++;
2335 goto redo_no_start;
2336 case '\\':
2337 /* first look if it is in fact an end of buffer */
2338 c = handle_stray1(p);
2339 p = file->buf_ptr;
2340 if (c == '\\')
2341 goto parse_simple;
2342 if (c != CH_EOF)
2343 goto redo_no_start;
2345 TCCState *s1 = tcc_state;
2346 if ((parse_flags & PARSE_FLAG_LINEFEED)
2347 && !(tok_flags & TOK_FLAG_EOF)) {
2348 tok_flags |= TOK_FLAG_EOF;
2349 tok = TOK_LINEFEED;
2350 goto keep_tok_flags;
2351 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2352 tok = TOK_EOF;
2353 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2354 tcc_error("missing #endif");
2355 } else if (s1->include_stack_ptr == s1->include_stack) {
2356 /* no include left : end of file. */
2357 tok = TOK_EOF;
2358 } else {
2359 tok_flags &= ~TOK_FLAG_EOF;
2360 /* pop include file */
2362 /* test if previous '#endif' was after a #ifdef at
2363 start of file */
2364 if (tok_flags & TOK_FLAG_ENDIF) {
2365 #ifdef INC_DEBUG
2366 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2367 #endif
2368 add_cached_include(s1, file->filename, file->ifndef_macro_saved);
2369 tok_flags &= ~TOK_FLAG_ENDIF;
2372 /* add end of include file debug info */
2373 if (tcc_state->do_debug) {
2374 put_stabd(N_EINCL, 0, 0);
2376 /* pop include stack */
2377 tcc_close();
2378 s1->include_stack_ptr--;
2379 p = file->buf_ptr;
2380 goto redo_no_start;
2383 break;
2385 case '\n':
2386 file->line_num++;
2387 tok_flags |= TOK_FLAG_BOL;
2388 p++;
2389 maybe_newline:
2390 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2391 goto redo_no_start;
2392 tok = TOK_LINEFEED;
2393 goto keep_tok_flags;
2395 case '#':
2396 /* XXX: simplify */
2397 PEEKC(c, p);
2398 if ((tok_flags & TOK_FLAG_BOL) &&
2399 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2400 file->buf_ptr = p;
2401 preprocess(tok_flags & TOK_FLAG_BOF);
2402 p = file->buf_ptr;
2403 goto maybe_newline;
2404 } else {
2405 if (c == '#') {
2406 p++;
2407 tok = TOK_TWOSHARPS;
2408 } else {
2409 if (parse_flags & PARSE_FLAG_ASM_FILE) {
2410 p = parse_line_comment(p - 1);
2411 goto redo_no_start;
2412 } else {
2413 tok = '#';
2417 break;
2419 /* dollar is allowed to start identifiers when not parsing asm */
2420 case '$':
2421 if (!(isidnum_table[c - CH_EOF] & IS_ID)
2422 || (parse_flags & PARSE_FLAG_ASM_FILE))
2423 goto parse_simple;
2425 case 'a': case 'b': case 'c': case 'd':
2426 case 'e': case 'f': case 'g': case 'h':
2427 case 'i': case 'j': case 'k': case 'l':
2428 case 'm': case 'n': case 'o': case 'p':
2429 case 'q': case 'r': case 's': case 't':
2430 case 'u': case 'v': case 'w': case 'x':
2431 case 'y': case 'z':
2432 case 'A': case 'B': case 'C': case 'D':
2433 case 'E': case 'F': case 'G': case 'H':
2434 case 'I': case 'J': case 'K':
2435 case 'M': case 'N': case 'O': case 'P':
2436 case 'Q': case 'R': case 'S': case 'T':
2437 case 'U': case 'V': case 'W': case 'X':
2438 case 'Y': case 'Z':
2439 case '_':
2440 parse_ident_fast:
2441 p1 = p;
2442 h = TOK_HASH_INIT;
2443 h = TOK_HASH_FUNC(h, c);
2444 while (c = *++p, isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2445 h = TOK_HASH_FUNC(h, c);
2446 if (c != '\\') {
2447 TokenSym **pts;
2448 int len;
2450 /* fast case : no stray found, so we have the full token
2451 and we have already hashed it */
2452 len = p - p1;
2453 h &= (TOK_HASH_SIZE - 1);
2454 pts = &hash_ident[h];
2455 for(;;) {
2456 ts = *pts;
2457 if (!ts)
2458 break;
2459 if (ts->len == len && !memcmp(ts->str, p1, len))
2460 goto token_found;
2461 pts = &(ts->hash_next);
2463 ts = tok_alloc_new(pts, (char *) p1, len);
2464 token_found: ;
2465 } else {
2466 /* slower case */
2467 cstr_reset(&tokcstr);
2469 while (p1 < p) {
2470 cstr_ccat(&tokcstr, *p1);
2471 p1++;
2473 p--;
2474 PEEKC(c, p);
2475 parse_ident_slow:
2476 while (isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM)) {
2477 cstr_ccat(&tokcstr, c);
2478 PEEKC(c, p);
2480 ts = tok_alloc(tokcstr.data, tokcstr.size);
2482 tok = ts->tok;
2483 break;
2484 case 'L':
2485 t = p[1];
2486 if (t != '\\' && t != '\'' && t != '\"') {
2487 /* fast case */
2488 goto parse_ident_fast;
2489 } else {
2490 PEEKC(c, p);
2491 if (c == '\'' || c == '\"') {
2492 is_long = 1;
2493 goto str_const;
2494 } else {
2495 cstr_reset(&tokcstr);
2496 cstr_ccat(&tokcstr, 'L');
2497 goto parse_ident_slow;
2500 break;
2502 case '0': case '1': case '2': case '3':
2503 case '4': case '5': case '6': case '7':
2504 case '8': case '9':
2505 cstr_reset(&tokcstr);
2506 /* after the first digit, accept digits, alpha, '.' or sign if
2507 prefixed by 'eEpP' */
2508 parse_num:
2509 for(;;) {
2510 t = c;
2511 cstr_ccat(&tokcstr, c);
2512 PEEKC(c, p);
2513 if (!((isidnum_table[c - CH_EOF] & (IS_ID|IS_NUM))
2514 || c == '.'
2515 || ((c == '+' || c == '-')
2516 && (t == 'e' || t == 'E' || t == 'p' || t == 'P')
2518 break;
2520 /* We add a trailing '\0' to ease parsing */
2521 cstr_ccat(&tokcstr, '\0');
2522 tokc.cstr = &tokcstr;
2523 tok = TOK_PPNUM;
2524 break;
2526 case '.':
2527 /* special dot handling because it can also start a number */
2528 PEEKC(c, p);
2529 if (isnum(c)) {
2530 cstr_reset(&tokcstr);
2531 cstr_ccat(&tokcstr, '.');
2532 goto parse_num;
2533 } else if ((c == '.') && (p[1] == '.')){
2534 PEEKC(c, p);
2535 PEEKC(c, p);
2536 tok = TOK_DOTS;
2537 } else {
2538 tok = '.';
2540 break;
2541 case '\'':
2542 case '\"':
2543 is_long = 0;
2544 str_const:
2545 cstr_reset(&tokcstr);
2546 if (is_long)
2547 cstr_ccat(&tokcstr, 'L');
2548 cstr_ccat(&tokcstr, c);
2549 p = parse_pp_string(p, c, &tokcstr);
2550 cstr_ccat(&tokcstr, c);
2551 cstr_ccat(&tokcstr, '\0');
2552 tokc.cstr = &tokcstr;
2553 tok = TOK_PPSTR;
2554 break;
2556 case '<':
2557 PEEKC(c, p);
2558 if (c == '=') {
2559 p++;
2560 tok = TOK_LE;
2561 } else if (c == '<') {
2562 PEEKC(c, p);
2563 if (c == '=') {
2564 p++;
2565 tok = TOK_A_SHL;
2566 } else {
2567 tok = TOK_SHL;
2569 } else {
2570 tok = TOK_LT;
2572 break;
2573 case '>':
2574 PEEKC(c, p);
2575 if (c == '=') {
2576 p++;
2577 tok = TOK_GE;
2578 } else if (c == '>') {
2579 PEEKC(c, p);
2580 if (c == '=') {
2581 p++;
2582 tok = TOK_A_SAR;
2583 } else {
2584 tok = TOK_SAR;
2586 } else {
2587 tok = TOK_GT;
2589 break;
2591 case '&':
2592 PEEKC(c, p);
2593 if (c == '&') {
2594 p++;
2595 tok = TOK_LAND;
2596 } else if (c == '=') {
2597 p++;
2598 tok = TOK_A_AND;
2599 } else {
2600 tok = '&';
2602 break;
2604 case '|':
2605 PEEKC(c, p);
2606 if (c == '|') {
2607 p++;
2608 tok = TOK_LOR;
2609 } else if (c == '=') {
2610 p++;
2611 tok = TOK_A_OR;
2612 } else {
2613 tok = '|';
2615 break;
2617 case '+':
2618 PEEKC(c, p);
2619 if (c == '+') {
2620 p++;
2621 tok = TOK_INC;
2622 } else if (c == '=') {
2623 p++;
2624 tok = TOK_A_ADD;
2625 } else {
2626 tok = '+';
2628 break;
2630 case '-':
2631 PEEKC(c, p);
2632 if (c == '-') {
2633 p++;
2634 tok = TOK_DEC;
2635 } else if (c == '=') {
2636 p++;
2637 tok = TOK_A_SUB;
2638 } else if (c == '>') {
2639 p++;
2640 tok = TOK_ARROW;
2641 } else {
2642 tok = '-';
2644 break;
2646 PARSE2('!', '!', '=', TOK_NE)
2647 PARSE2('=', '=', '=', TOK_EQ)
2648 PARSE2('*', '*', '=', TOK_A_MUL)
2649 PARSE2('%', '%', '=', TOK_A_MOD)
2650 PARSE2('^', '^', '=', TOK_A_XOR)
2652 /* comments or operator */
2653 case '/':
2654 PEEKC(c, p);
2655 if (c == '*') {
2656 p = parse_comment(p);
2657 /* comments replaced by a blank */
2658 tok = ' ';
2659 goto keep_tok_flags;
2660 } else if (c == '/') {
2661 p = parse_line_comment(p);
2662 tok = ' ';
2663 goto keep_tok_flags;
2664 } else if (c == '=') {
2665 p++;
2666 tok = TOK_A_DIV;
2667 } else {
2668 tok = '/';
2670 break;
2672 /* simple tokens */
2673 case '(':
2674 case ')':
2675 case '[':
2676 case ']':
2677 case '{':
2678 case '}':
2679 case ',':
2680 case ';':
2681 case ':':
2682 case '?':
2683 case '~':
2684 case '@': /* only used in assembler */
2685 parse_simple:
2686 tok = c;
2687 p++;
2688 break;
2689 default:
2690 tcc_error("unrecognized character \\x%02x", c);
2691 break;
2693 tok_flags = 0;
2694 keep_tok_flags:
2695 file->buf_ptr = p;
2696 #if defined(PARSE_DEBUG)
2697 printf("token = %s\n", get_tok_str(tok, &tokc));
2698 #endif
2701 /* return next token without macro substitution. Can read input from
2702 macro_ptr buffer */
2703 static void next_nomacro_spc(void)
2705 if (macro_ptr) {
2706 redo:
2707 tok = *macro_ptr;
2708 if (tok) {
2709 TOK_GET(&tok, &macro_ptr, &tokc);
2710 if (tok == TOK_LINENUM) {
2711 file->line_num = tokc.i;
2712 goto redo;
2715 } else {
2716 next_nomacro1();
2720 ST_FUNC void next_nomacro(void)
2722 do {
2723 next_nomacro_spc();
2724 } while (tok < 256 && (isidnum_table[tok - CH_EOF] & IS_SPC));
2728 static void macro_subst(
2729 TokenString *tok_str,
2730 Sym **nested_list,
2731 const int *macro_str,
2732 int can_read_stream
2735 /* substitute arguments in replacement lists in macro_str by the values in
2736 args (field d) and return allocated string */
2737 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2739 int t, t0, t1, spc;
2740 const int *st;
2741 Sym *s;
2742 CValue cval;
2743 TokenString str;
2744 CString cstr;
2746 tok_str_new(&str);
2747 t0 = t1 = 0;
2748 while(1) {
2749 TOK_GET(&t, &macro_str, &cval);
2750 if (!t)
2751 break;
2752 if (t == '#') {
2753 /* stringize */
2754 TOK_GET(&t, &macro_str, &cval);
2755 if (!t)
2756 goto bad_stringy;
2757 s = sym_find2(args, t);
2758 if (s) {
2759 cstr_new(&cstr);
2760 cstr_ccat(&cstr, '\"');
2761 st = s->d;
2762 spc = 0;
2763 while (*st) {
2764 TOK_GET(&t, &st, &cval);
2765 if (t != TOK_PLCHLDR
2766 && t != TOK_NOSUBST
2767 && 0 == check_space(t, &spc)) {
2768 const char *s = get_tok_str(t, &cval);
2769 while (*s) {
2770 if (t == TOK_PPSTR && *s != '\'')
2771 add_char(&cstr, *s);
2772 else
2773 cstr_ccat(&cstr, *s);
2774 ++s;
2778 cstr.size -= spc;
2779 cstr_ccat(&cstr, '\"');
2780 cstr_ccat(&cstr, '\0');
2781 #ifdef PP_DEBUG
2782 printf("\nstringize: <%s>\n", (char *)cstr.data);
2783 #endif
2784 /* add string */
2785 cval.cstr = &cstr;
2786 tok_str_add2(&str, TOK_PPSTR, &cval);
2787 cstr_free(cval.cstr);
2788 } else {
2789 bad_stringy:
2790 expect("macro parameter after '#'");
2792 } else if (t >= TOK_IDENT) {
2793 s = sym_find2(args, t);
2794 if (s) {
2795 int l0 = str.len;
2796 st = s->d;
2797 /* if '##' is present before or after, no arg substitution */
2798 if (*macro_str == TOK_TWOSHARPS || t1 == TOK_TWOSHARPS) {
2799 /* special case for var arg macros : ## eats the ','
2800 if empty VA_ARGS variable. */
2801 if (t1 == TOK_TWOSHARPS && t0 == ',' && gnu_ext && s->type.t) {
2802 if (*st == 0) {
2803 /* suppress ',' '##' */
2804 str.len -= 2;
2805 } else {
2806 /* suppress '##' and add variable */
2807 str.len--;
2808 goto add_var;
2810 } else {
2811 for(;;) {
2812 int t1;
2813 TOK_GET(&t1, &st, &cval);
2814 if (!t1)
2815 break;
2816 tok_str_add2(&str, t1, &cval);
2820 } else {
2821 add_var:
2822 /* NOTE: the stream cannot be read when macro
2823 substituing an argument */
2824 macro_subst(&str, nested_list, st, 0);
2826 if (str.len == l0) /* exanded to empty string */
2827 tok_str_add(&str, TOK_PLCHLDR);
2828 } else {
2829 tok_str_add(&str, t);
2831 } else {
2832 tok_str_add2(&str, t, &cval);
2834 t0 = t1, t1 = t;
2836 tok_str_add(&str, 0);
2837 return str.str;
2840 static char const ab_month_name[12][4] =
2842 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2843 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2846 /* peek or read [ws_str == NULL] next token from function macro call,
2847 walking up macro levels up to the file if necessary */
2848 static int next_argstream(Sym **nested_list, int can_read_stream, TokenString *ws_str)
2850 int t;
2851 const int *p;
2852 Sym *sa;
2854 for (;;) {
2855 if (macro_ptr) {
2856 p = macro_ptr, t = *p;
2857 if (ws_str) {
2858 while (is_space(t) || TOK_LINEFEED == t)
2859 tok_str_add(ws_str, t), t = *++p;
2861 if (t == 0 && can_read_stream) {
2862 end_macro();
2863 /* also, end of scope for nested defined symbol */
2864 sa = *nested_list;
2865 while (sa && sa->v == -1)
2866 sa = sa->prev;
2867 if (sa)
2868 sa->v = -1;
2869 continue;
2871 } else {
2872 ch = handle_eob();
2873 if (ws_str) {
2874 while (is_space(ch) || ch == '\n' || ch == '/') {
2875 if (ch == '/') {
2876 int c;
2877 uint8_t *p = file->buf_ptr;
2878 PEEKC(c, p);
2879 if (c == '*') {
2880 p = parse_comment(p);
2881 file->buf_ptr = p - 1;
2882 } else if (c == '/') {
2883 p = parse_line_comment(p);
2884 file->buf_ptr = p - 1;
2885 } else
2886 break;
2887 ch = ' ';
2889 tok_str_add(ws_str, ch);
2890 cinp();
2893 t = ch;
2896 if (ws_str)
2897 return t;
2898 next_nomacro_spc();
2899 return tok;
2903 /* do macro substitution of current token with macro 's' and add
2904 result to (tok_str,tok_len). 'nested_list' is the list of all
2905 macros we got inside to avoid recursing. Return non zero if no
2906 substitution needs to be done */
2907 static int macro_subst_tok(
2908 TokenString *tok_str,
2909 Sym **nested_list,
2910 Sym *s,
2911 int can_read_stream)
2913 Sym *args, *sa, *sa1;
2914 int parlevel, *mstr, t, t1, spc;
2915 TokenString str;
2916 char *cstrval;
2917 CValue cval;
2918 CString cstr;
2919 char buf[32];
2921 /* if symbol is a macro, prepare substitution */
2922 /* special macros */
2923 if (tok == TOK___LINE__) {
2924 snprintf(buf, sizeof(buf), "%d", file->line_num);
2925 cstrval = buf;
2926 t1 = TOK_PPNUM;
2927 goto add_cstr1;
2928 } else if (tok == TOK___FILE__) {
2929 cstrval = file->filename;
2930 goto add_cstr;
2931 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
2932 time_t ti;
2933 struct tm *tm;
2935 time(&ti);
2936 tm = localtime(&ti);
2937 if (tok == TOK___DATE__) {
2938 snprintf(buf, sizeof(buf), "%s %2d %d",
2939 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
2940 } else {
2941 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
2942 tm->tm_hour, tm->tm_min, tm->tm_sec);
2944 cstrval = buf;
2945 add_cstr:
2946 t1 = TOK_STR;
2947 add_cstr1:
2948 cstr_new(&cstr);
2949 cstr_cat(&cstr, cstrval);
2950 cstr_ccat(&cstr, '\0');
2951 cval.cstr = &cstr;
2952 tok_str_add2(tok_str, t1, &cval);
2953 cstr_free(&cstr);
2954 } else {
2955 int saved_parse_flags = parse_flags;
2957 mstr = s->d;
2958 if (s->type.t == MACRO_FUNC) {
2959 /* whitespace between macro name and argument list */
2960 TokenString ws_str;
2961 tok_str_new(&ws_str);
2963 spc = 0;
2964 parse_flags |= PARSE_FLAG_SPACES | PARSE_FLAG_LINEFEED
2965 | PARSE_FLAG_ACCEPT_STRAYS;
2967 /* get next token from argument stream */
2968 t = next_argstream(nested_list, can_read_stream, &ws_str);
2969 if (t != '(') {
2970 /* not a macro substitution after all, restore the
2971 * macro token plus all whitespace we've read.
2972 * whitespace is intentionally not merged to preserve
2973 * newlines. */
2974 parse_flags = saved_parse_flags;
2975 tok_str_add(tok_str, tok);
2976 if (parse_flags & PARSE_FLAG_SPACES) {
2977 int i;
2978 for (i = 0; i < ws_str.len; i++)
2979 tok_str_add(tok_str, ws_str.str[i]);
2981 tok_str_free(ws_str.str);
2982 return 0;
2983 } else {
2984 tok_str_free(ws_str.str);
2986 next_nomacro(); /* eat '(' */
2988 /* argument macro */
2989 args = NULL;
2990 sa = s->next;
2991 /* NOTE: empty args are allowed, except if no args */
2992 for(;;) {
2993 do {
2994 next_argstream(nested_list, can_read_stream, NULL);
2995 } while (is_space(tok) || TOK_LINEFEED == tok);
2996 empty_arg:
2997 /* handle '()' case */
2998 if (!args && !sa && tok == ')')
2999 break;
3000 if (!sa)
3001 tcc_error("macro '%s' used with too many args",
3002 get_tok_str(s->v, 0));
3003 tok_str_new(&str);
3004 parlevel = spc = 0;
3005 /* NOTE: non zero sa->t indicates VA_ARGS */
3006 while ((parlevel > 0 ||
3007 (tok != ')' &&
3008 (tok != ',' || sa->type.t)))) {
3009 if (tok == TOK_EOF || tok == 0)
3010 break;
3011 if (tok == '(')
3012 parlevel++;
3013 else if (tok == ')')
3014 parlevel--;
3015 if (tok == TOK_LINEFEED)
3016 tok = ' ';
3017 if (!check_space(tok, &spc))
3018 tok_str_add2(&str, tok, &tokc);
3019 next_argstream(nested_list, can_read_stream, NULL);
3021 if (parlevel)
3022 expect(")");
3023 str.len -= spc;
3024 tok_str_add(&str, 0);
3025 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
3026 sa1->d = str.str;
3027 sa = sa->next;
3028 if (tok == ')') {
3029 /* special case for gcc var args: add an empty
3030 var arg argument if it is omitted */
3031 if (sa && sa->type.t && gnu_ext)
3032 goto empty_arg;
3033 break;
3035 if (tok != ',')
3036 expect(",");
3038 if (sa) {
3039 tcc_error("macro '%s' used with too few args",
3040 get_tok_str(s->v, 0));
3043 parse_flags = saved_parse_flags;
3045 /* now subst each arg */
3046 mstr = macro_arg_subst(nested_list, mstr, args);
3047 /* free memory */
3048 sa = args;
3049 while (sa) {
3050 sa1 = sa->prev;
3051 tok_str_free(sa->d);
3052 sym_free(sa);
3053 sa = sa1;
3057 sym_push2(nested_list, s->v, 0, 0);
3058 parse_flags = saved_parse_flags;
3059 macro_subst(tok_str, nested_list, mstr, can_read_stream);
3061 /* pop nested defined symbol */
3062 sa1 = *nested_list;
3063 *nested_list = sa1->prev;
3064 sym_free(sa1);
3065 if (mstr != s->d)
3066 tok_str_free(mstr);
3068 return 0;
3071 int paste_tokens(int t1, CValue *v1, int t2, CValue *v2)
3073 CString cstr;
3074 int n;
3076 cstr_new(&cstr);
3077 if (t1 != TOK_PLCHLDR)
3078 cstr_cat(&cstr, get_tok_str(t1, v1));
3079 n = cstr.size;
3080 if (t2 != TOK_PLCHLDR)
3081 cstr_cat(&cstr, get_tok_str(t2, v2));
3082 cstr_ccat(&cstr, '\0');
3084 tcc_open_bf(tcc_state, ":paste:", cstr.size);
3085 memcpy(file->buffer, cstr.data, cstr.size);
3086 for (;;) {
3087 next_nomacro1();
3088 if (0 == *file->buf_ptr)
3089 break;
3090 if (is_space(tok))
3091 continue;
3092 tcc_warning("pasting <%.*s> and <%s> does not give a valid preprocessing token",
3093 n, cstr.data, (char*)cstr.data + n);
3094 break;
3096 tcc_close();
3098 //printf("paste <%s>\n", (char*)cstr.data);
3099 cstr_free(&cstr);
3100 return 0;
3103 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3104 return the resulting string (which must be freed). */
3105 static inline int *macro_twosharps(const int *ptr0)
3107 int t;
3108 CValue cval;
3109 TokenString macro_str1;
3110 int start_of_nosubsts = -1;
3111 const int *ptr;
3113 /* we search the first '##' */
3114 for (ptr = ptr0;;) {
3115 TOK_GET(&t, &ptr, &cval);
3116 if (t == TOK_TWOSHARPS)
3117 break;
3118 if (t == 0)
3119 return NULL;
3122 tok_str_new(&macro_str1);
3124 //tok_print(" $$$", ptr0);
3125 for (ptr = ptr0;;) {
3126 TOK_GET(&t, &ptr, &cval);
3127 if (t == 0)
3128 break;
3129 if (t == TOK_TWOSHARPS)
3130 continue;
3131 while (*ptr == TOK_TWOSHARPS) {
3132 int t1; CValue cv1;
3133 /* given 'a##b', remove nosubsts preceding 'a' */
3134 if (start_of_nosubsts >= 0)
3135 macro_str1.len = start_of_nosubsts;
3136 /* given 'a##b', remove nosubsts preceding 'b' */
3137 while ((t1 = *++ptr) == TOK_NOSUBST)
3139 if (t1 && t1 != TOK_TWOSHARPS
3140 && t1 != ':') /* 'a##:' don't build a new token */
3142 TOK_GET(&t1, &ptr, &cv1);
3143 if (t != TOK_PLCHLDR || t1 != TOK_PLCHLDR) {
3144 paste_tokens(t, &cval, t1, &cv1);
3145 t = tok, cval = tokc;
3149 if (t == TOK_NOSUBST) {
3150 if (start_of_nosubsts < 0)
3151 start_of_nosubsts = macro_str1.len;
3152 } else {
3153 start_of_nosubsts = -1;
3155 tok_str_add2(&macro_str1, t, &cval);
3157 tok_str_add(&macro_str1, 0);
3158 //tok_print(" ###", macro_str1.str);
3159 return macro_str1.str;
3162 /* do macro substitution of macro_str and add result to
3163 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3164 inside to avoid recursing. */
3165 static void macro_subst(
3166 TokenString *tok_str,
3167 Sym **nested_list,
3168 const int *macro_str,
3169 int can_read_stream
3172 Sym *s;
3173 const int *ptr;
3174 int t, spc, nosubst;
3175 CValue cval;
3176 int *macro_str1 = NULL;
3178 /* first scan for '##' operator handling */
3179 ptr = macro_str;
3180 spc = nosubst = 0;
3182 /* first scan for '##' operator handling */
3183 if (can_read_stream) {
3184 macro_str1 = macro_twosharps(ptr);
3185 if (macro_str1)
3186 ptr = macro_str1;
3189 while (1) {
3190 TOK_GET(&t, &ptr, &cval);
3191 if (t == 0)
3192 break;
3194 if (t >= TOK_IDENT && 0 == nosubst) {
3195 s = define_find(t);
3196 if (s == NULL)
3197 goto no_subst;
3199 /* if nested substitution, do nothing */
3200 if (sym_find2(*nested_list, t)) {
3201 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3202 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
3203 goto no_subst;
3207 TokenString str;
3208 str.str = (int*)ptr;
3209 begin_macro(&str, 2);
3211 tok = t;
3212 macro_subst_tok(tok_str, nested_list, s, can_read_stream);
3214 if (str.alloc == 3) {
3215 /* already finished by reading function macro arguments */
3216 break;
3219 ptr = macro_ptr;
3220 end_macro ();
3223 spc = (tok_str->len &&
3224 is_space(tok_last(tok_str->str,
3225 tok_str->str + tok_str->len)));
3227 } else {
3229 if (t == '\\' && !(parse_flags & PARSE_FLAG_ACCEPT_STRAYS))
3230 tcc_error("stray '\\' in program");
3232 no_subst:
3233 if (!check_space(t, &spc))
3234 tok_str_add2(tok_str, t, &cval);
3235 nosubst = 0;
3236 if (t == TOK_NOSUBST)
3237 nosubst = 1;
3240 if (macro_str1)
3241 tok_str_free(macro_str1);
3245 /* return next token with macro substitution */
3246 ST_FUNC void next(void)
3248 redo:
3249 if (parse_flags & PARSE_FLAG_SPACES)
3250 next_nomacro_spc();
3251 else
3252 next_nomacro();
3254 if (macro_ptr) {
3255 if (tok == TOK_NOSUBST || tok == TOK_PLCHLDR) {
3256 /* discard preprocessor markers */
3257 goto redo;
3258 } else if (tok == 0) {
3259 /* end of macro or unget token string */
3260 end_macro();
3261 goto redo;
3263 } else if (tok >= TOK_IDENT && (parse_flags & PARSE_FLAG_PREPROCESS)) {
3264 Sym *s;
3265 /* if reading from file, try to substitute macros */
3266 s = define_find(tok);
3267 if (s) {
3268 static TokenString str; /* using static string for speed */
3269 Sym *nested_list = NULL;
3270 tok_str_new(&str);
3271 nested_list = NULL;
3272 macro_subst_tok(&str, &nested_list, s, 1);
3273 tok_str_add(&str, 0);
3274 begin_macro(&str, 0);
3275 goto redo;
3278 /* convert preprocessor tokens into C tokens */
3279 if (tok == TOK_PPNUM) {
3280 if (parse_flags & PARSE_FLAG_TOK_NUM)
3281 parse_number((char *)tokc.cstr->data);
3282 } else if (tok == TOK_PPSTR) {
3283 if (parse_flags & PARSE_FLAG_TOK_STR)
3284 parse_string((char *)tokc.cstr->data, tokc.cstr->size - 1);
3288 /* push back current token and set current token to 'last_tok'. Only
3289 identifier case handled for labels. */
3290 ST_INLN void unget_tok(int last_tok)
3292 TokenString *str = tcc_malloc(sizeof *str);
3293 tok_str_new(str);
3294 tok_str_add2(str, tok, &tokc);
3295 tok_str_add(str, 0);
3296 begin_macro(str, 1);
3297 tok = last_tok;
3300 /* better than nothing, but needs extension to handle '-E' option
3301 correctly too */
3302 ST_FUNC void preprocess_init(TCCState *s1)
3304 s1->include_stack_ptr = s1->include_stack;
3305 /* XXX: move that before to avoid having to initialize
3306 file->ifdef_stack_ptr ? */
3307 s1->ifdef_stack_ptr = s1->ifdef_stack;
3308 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3310 pvtop = vtop = vstack - 1;
3311 s1->pack_stack[0] = 0;
3312 s1->pack_stack_ptr = s1->pack_stack;
3314 isidnum_table['$' - CH_EOF] =
3315 tcc_state->dollars_in_identifiers ? IS_ID : 0;
3318 ST_FUNC void preprocess_new(void)
3320 int i, c;
3321 const char *p, *r;
3323 /* init isid table */
3324 for(i = CH_EOF; i<256; i++)
3325 isidnum_table[i - CH_EOF]
3326 = is_space(i) ? IS_SPC
3327 : isid(i) ? IS_ID
3328 : isnum(i) ? IS_NUM
3329 : 0;
3331 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3333 tok_ident = TOK_IDENT;
3334 p = tcc_keywords;
3335 while (*p) {
3336 r = p;
3337 for(;;) {
3338 c = *r++;
3339 if (c == '\0')
3340 break;
3342 tok_alloc(p, r - p - 1);
3343 p = r;
3347 ST_FUNC void preprocess_delete(void)
3349 int i, n;
3351 /* free -D and compiler defines */
3352 free_defines(NULL);
3354 /* cleanup from error/setjmp */
3355 while (macro_stack)
3356 end_macro();
3357 macro_ptr = NULL;
3359 /* free tokens */
3360 n = tok_ident - TOK_IDENT;
3361 for(i = 0; i < n; i++)
3362 tcc_free(table_ident[i]);
3363 tcc_free(table_ident);
3364 table_ident = NULL;
3367 /* Preprocess the current file */
3368 ST_FUNC int tcc_preprocess(TCCState *s1)
3370 BufferedFile **iptr;
3371 int token_seen, spcs, level;
3373 preprocess_init(s1);
3374 ch = file->buf_ptr[0];
3375 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3376 parse_flags = PARSE_FLAG_PREPROCESS
3377 | (parse_flags & PARSE_FLAG_ASM_FILE)
3378 | PARSE_FLAG_LINEFEED
3379 | PARSE_FLAG_SPACES
3380 | PARSE_FLAG_ACCEPT_STRAYS
3383 #ifdef PP_BENCH
3384 do next(); while (tok != TOK_EOF); return 0;
3385 #endif
3387 token_seen = spcs = 0;
3388 pp_line(s1, file, 0);
3390 for (;;) {
3391 iptr = s1->include_stack_ptr;
3392 next();
3393 if (tok == TOK_EOF)
3394 break;
3395 level = s1->include_stack_ptr - iptr;
3396 if (level) {
3397 if (level > 0)
3398 pp_line(s1, *iptr, 0);
3399 pp_line(s1, file, level);
3402 if (0 == token_seen) {
3403 if (tok == ' ') {
3404 ++spcs;
3405 continue;
3407 if (tok == TOK_LINEFEED) {
3408 spcs = 0;
3409 continue;
3411 pp_line(s1, file, 0);
3412 while (spcs)
3413 fputs(" ", s1->ppfp), --spcs;
3414 token_seen = 1;
3416 } else if (tok == TOK_LINEFEED) {
3417 ++file->line_ref;
3418 token_seen = 0;
3421 fputs(get_tok_str(tok, &tokc), s1->ppfp);
3424 return 0;