Revert "pe: fix tcc not linking to user32 and gdi32"
[tinycc.git] / tccpp.c
blobcc54dee20721725fa67b15685c845e2ae314f401
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 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
74 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
76 struct macro_level {
77 struct macro_level *prev;
78 const int *p;
81 ST_FUNC void next_nomacro(void);
82 static void next_nomacro_spc(void);
83 static void macro_subst(
84 TokenString *tok_str,
85 Sym **nested_list,
86 const int *macro_str,
87 struct macro_level **can_read_stream
90 ST_FUNC void skip(int c)
92 if (tok != c)
93 tcc_error("'%c' expected (got \"%s\")", c, get_tok_str(tok, &tokc));
94 next();
97 ST_FUNC void expect(const char *msg)
99 tcc_error("%s expected", msg);
102 /* ------------------------------------------------------------------------- */
103 /* CString handling */
104 static void cstr_realloc(CString *cstr, int new_size)
106 int size;
107 void *data;
109 size = cstr->size_allocated;
110 if (size == 0)
111 size = 8; /* no need to allocate a too small first string */
112 while (size < new_size)
113 size = size * 2;
114 data = tcc_realloc(cstr->data_allocated, size);
115 cstr->data_allocated = data;
116 cstr->size_allocated = size;
117 cstr->data = data;
120 /* add a byte */
121 PUB_FUNC void cstr_ccat(CString *cstr, int ch)
123 int size;
124 size = cstr->size + 1;
125 if (size > cstr->size_allocated)
126 cstr_realloc(cstr, size);
127 ((unsigned char *)cstr->data)[size - 1] = ch;
128 cstr->size = size;
131 PUB_FUNC void cstr_cat(CString *cstr, const char *str)
133 int c;
134 for(;;) {
135 c = *str;
136 if (c == '\0')
137 break;
138 cstr_ccat(cstr, c);
139 str++;
143 /* add a wide char */
144 PUB_FUNC void cstr_wccat(CString *cstr, int ch)
146 int size;
147 size = cstr->size + sizeof(nwchar_t);
148 if (size > cstr->size_allocated)
149 cstr_realloc(cstr, size);
150 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
151 cstr->size = size;
154 PUB_FUNC void cstr_new(CString *cstr)
156 memset(cstr, 0, sizeof(CString));
159 /* free string and reset it to NULL */
160 PUB_FUNC void cstr_free(CString *cstr)
162 tcc_free(cstr->data_allocated);
163 cstr_new(cstr);
166 /* reset string to empty */
167 PUB_FUNC void cstr_reset(CString *cstr)
169 cstr->size = 0;
172 /* XXX: unicode ? */
173 static void add_char(CString *cstr, int c)
175 if (c == '\'' || c == '\"' || c == '\\') {
176 /* XXX: could be more precise if char or string */
177 cstr_ccat(cstr, '\\');
179 if (c >= 32 && c <= 126) {
180 cstr_ccat(cstr, c);
181 } else {
182 cstr_ccat(cstr, '\\');
183 if (c == '\n') {
184 cstr_ccat(cstr, 'n');
185 } else {
186 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
187 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
188 cstr_ccat(cstr, '0' + (c & 7));
193 /* ------------------------------------------------------------------------- */
194 /* allocate a new token */
195 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
197 TokenSym *ts, **ptable;
198 int i;
200 if (tok_ident >= SYM_FIRST_ANOM)
201 tcc_error("memory full");
203 /* expand token table if needed */
204 i = tok_ident - TOK_IDENT;
205 if ((i % TOK_ALLOC_INCR) == 0) {
206 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
207 table_ident = ptable;
210 ts = tcc_malloc(sizeof(TokenSym) + len);
211 table_ident[i] = ts;
212 ts->tok = tok_ident++;
213 ts->sym_define = NULL;
214 ts->sym_label = NULL;
215 ts->sym_struct = NULL;
216 ts->sym_identifier = NULL;
217 ts->len = len;
218 ts->hash_next = NULL;
219 memcpy(ts->str, str, len);
220 ts->str[len] = '\0';
221 *pts = ts;
222 return ts;
225 #define TOK_HASH_INIT 1
226 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
228 /* find a token and add it if not found */
229 ST_FUNC TokenSym *tok_alloc(const char *str, int len)
231 TokenSym *ts, **pts;
232 int i;
233 unsigned int h;
235 h = TOK_HASH_INIT;
236 for(i=0;i<len;i++)
237 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
238 h &= (TOK_HASH_SIZE - 1);
240 pts = &hash_ident[h];
241 for(;;) {
242 ts = *pts;
243 if (!ts)
244 break;
245 if (ts->len == len && !memcmp(ts->str, str, len))
246 return ts;
247 pts = &(ts->hash_next);
249 return tok_alloc_new(pts, str, len);
252 /* XXX: buffer overflow */
253 /* XXX: float tokens */
254 ST_FUNC char *get_tok_str(int v, CValue *cv)
256 static char buf[STRING_MAX_SIZE + 1];
257 static CString cstr_buf;
258 CString *cstr;
259 char *p;
260 int i, len;
262 /* NOTE: to go faster, we give a fixed buffer for small strings */
263 cstr_reset(&cstr_buf);
264 cstr_buf.data = buf;
265 cstr_buf.size_allocated = sizeof(buf);
266 p = buf;
268 switch(v) {
269 case TOK_CINT:
270 case TOK_CUINT:
271 /* XXX: not quite exact, but only useful for testing */
272 sprintf(p, "%u", cv->ui);
273 break;
274 case TOK_CLLONG:
275 case TOK_CULLONG:
276 /* XXX: not quite exact, but only useful for testing */
277 #ifdef _WIN32
278 sprintf(p, "%u", (unsigned)cv->ull);
279 #else
280 sprintf(p, "%Lu", cv->ull);
281 #endif
282 break;
283 case TOK_LCHAR:
284 cstr_ccat(&cstr_buf, 'L');
285 case TOK_CCHAR:
286 cstr_ccat(&cstr_buf, '\'');
287 add_char(&cstr_buf, cv->i);
288 cstr_ccat(&cstr_buf, '\'');
289 cstr_ccat(&cstr_buf, '\0');
290 break;
291 case TOK_PPNUM:
292 cstr = cv->cstr;
293 len = cstr->size - 1;
294 for(i=0;i<len;i++)
295 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
296 cstr_ccat(&cstr_buf, '\0');
297 break;
298 case TOK_LSTR:
299 cstr_ccat(&cstr_buf, 'L');
300 case TOK_STR:
301 cstr = cv->cstr;
302 cstr_ccat(&cstr_buf, '\"');
303 if (v == TOK_STR) {
304 len = cstr->size - 1;
305 for(i=0;i<len;i++)
306 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
307 } else {
308 len = (cstr->size / sizeof(nwchar_t)) - 1;
309 for(i=0;i<len;i++)
310 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
312 cstr_ccat(&cstr_buf, '\"');
313 cstr_ccat(&cstr_buf, '\0');
314 break;
315 case TOK_LT:
316 v = '<';
317 goto addv;
318 case TOK_GT:
319 v = '>';
320 goto addv;
321 case TOK_DOTS:
322 return strcpy(p, "...");
323 case TOK_A_SHL:
324 return strcpy(p, "<<=");
325 case TOK_A_SAR:
326 return strcpy(p, ">>=");
327 default:
328 if (v < TOK_IDENT) {
329 /* search in two bytes table */
330 const unsigned char *q = tok_two_chars;
331 while (*q) {
332 if (q[2] == v) {
333 *p++ = q[0];
334 *p++ = q[1];
335 *p = '\0';
336 return buf;
338 q += 3;
340 addv:
341 *p++ = v;
342 *p = '\0';
343 } else if (v < tok_ident) {
344 return table_ident[v - TOK_IDENT]->str;
345 } else if (v >= SYM_FIRST_ANOM) {
346 /* special name for anonymous symbol */
347 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
348 } else {
349 /* should never happen */
350 return NULL;
352 break;
354 return cstr_buf.data;
357 /* fill input buffer and peek next char */
358 static int tcc_peekc_slow(BufferedFile *bf)
360 int len;
361 /* only tries to read if really end of buffer */
362 if (bf->buf_ptr >= bf->buf_end) {
363 if (bf->fd.fd != -1) {
364 #if defined(PARSE_DEBUG)
365 len = 8;
366 #else
367 len = IO_BUF_SIZE;
368 #endif
369 len = vio_read(bf->fd, bf->buffer, len);
370 if (len < 0)
371 len = 0;
372 } else {
373 len = 0;
375 total_bytes += len;
376 bf->buf_ptr = bf->buffer;
377 bf->buf_end = bf->buffer + len;
378 *bf->buf_end = CH_EOB;
380 if (bf->buf_ptr < bf->buf_end) {
381 return bf->buf_ptr[0];
382 } else {
383 bf->buf_ptr = bf->buf_end;
384 return CH_EOF;
388 /* return the current character, handling end of block if necessary
389 (but not stray) */
390 ST_FUNC int handle_eob(void)
392 return tcc_peekc_slow(file);
395 /* read next char from current input file and handle end of input buffer */
396 ST_INLN void inp(void)
398 ch = *(++(file->buf_ptr));
399 /* end of buffer/file handling */
400 if (ch == CH_EOB)
401 ch = handle_eob();
404 /* handle '\[\r]\n' */
405 static int handle_stray_noerror(void)
407 while (ch == '\\') {
408 inp();
409 if (ch == '\n') {
410 file->line_num++;
411 inp();
412 } else if (ch == '\r') {
413 inp();
414 if (ch != '\n')
415 goto fail;
416 file->line_num++;
417 inp();
418 } else {
419 fail:
420 return 1;
423 return 0;
426 static void handle_stray(void)
428 if (handle_stray_noerror())
429 tcc_error("stray '\\' in program");
432 /* skip the stray and handle the \\n case. Output an error if
433 incorrect char after the stray */
434 static int handle_stray1(uint8_t *p)
436 int c;
438 if (p >= file->buf_end) {
439 file->buf_ptr = p;
440 c = handle_eob();
441 p = file->buf_ptr;
442 if (c == '\\')
443 goto parse_stray;
444 } else {
445 parse_stray:
446 file->buf_ptr = p;
447 ch = *p;
448 handle_stray();
449 p = file->buf_ptr;
450 c = *p;
452 return c;
455 /* handle just the EOB case, but not stray */
456 #define PEEKC_EOB(c, p)\
458 p++;\
459 c = *p;\
460 if (c == '\\') {\
461 file->buf_ptr = p;\
462 c = handle_eob();\
463 p = file->buf_ptr;\
467 /* handle the complicated stray case */
468 #define PEEKC(c, p)\
470 p++;\
471 c = *p;\
472 if (c == '\\') {\
473 c = handle_stray1(p);\
474 p = file->buf_ptr;\
478 /* input with '\[\r]\n' handling. Note that this function cannot
479 handle other characters after '\', so you cannot call it inside
480 strings or comments */
481 ST_FUNC void minp(void)
483 inp();
484 if (ch == '\\')
485 handle_stray();
489 /* single line C++ comments */
490 static uint8_t *parse_line_comment(uint8_t *p)
492 int c;
494 p++;
495 for(;;) {
496 c = *p;
497 redo:
498 if (c == '\n' || c == CH_EOF) {
499 break;
500 } else if (c == '\\') {
501 file->buf_ptr = p;
502 c = handle_eob();
503 p = file->buf_ptr;
504 if (c == '\\') {
505 PEEKC_EOB(c, p);
506 if (c == '\n') {
507 file->line_num++;
508 PEEKC_EOB(c, p);
509 } else if (c == '\r') {
510 PEEKC_EOB(c, p);
511 if (c == '\n') {
512 file->line_num++;
513 PEEKC_EOB(c, p);
516 } else {
517 goto redo;
519 } else {
520 p++;
523 return p;
526 /* C comments */
527 ST_FUNC uint8_t *parse_comment(uint8_t *p)
529 int c;
531 p++;
532 for(;;) {
533 /* fast skip loop */
534 for(;;) {
535 c = *p;
536 if (c == '\n' || c == '*' || c == '\\')
537 break;
538 p++;
539 c = *p;
540 if (c == '\n' || c == '*' || c == '\\')
541 break;
542 p++;
544 /* now we can handle all the cases */
545 if (c == '\n') {
546 file->line_num++;
547 p++;
548 } else if (c == '*') {
549 p++;
550 for(;;) {
551 c = *p;
552 if (c == '*') {
553 p++;
554 } else if (c == '/') {
555 goto end_of_comment;
556 } else if (c == '\\') {
557 file->buf_ptr = p;
558 c = handle_eob();
559 p = file->buf_ptr;
560 if (c == '\\') {
561 /* skip '\[\r]\n', otherwise just skip the stray */
562 while (c == '\\') {
563 PEEKC_EOB(c, p);
564 if (c == '\n') {
565 file->line_num++;
566 PEEKC_EOB(c, p);
567 } else if (c == '\r') {
568 PEEKC_EOB(c, p);
569 if (c == '\n') {
570 file->line_num++;
571 PEEKC_EOB(c, p);
573 } else {
574 goto after_star;
578 } else {
579 break;
582 after_star: ;
583 } else {
584 /* stray, eob or eof */
585 file->buf_ptr = p;
586 c = handle_eob();
587 p = file->buf_ptr;
588 if (c == CH_EOF) {
589 tcc_error("unexpected end of file in comment");
590 } else if (c == '\\') {
591 p++;
595 end_of_comment:
596 p++;
597 return p;
600 #define cinp minp
602 static inline void skip_spaces(void)
604 while (is_space(ch))
605 cinp();
608 static inline int check_space(int t, int *spc)
610 if (is_space(t)) {
611 if (*spc)
612 return 1;
613 *spc = 1;
614 } else
615 *spc = 0;
616 return 0;
619 /* parse a string without interpreting escapes */
620 static uint8_t *parse_pp_string(uint8_t *p,
621 int sep, CString *str)
623 int c;
624 p++;
625 for(;;) {
626 c = *p;
627 if (c == sep) {
628 break;
629 } else if (c == '\\') {
630 file->buf_ptr = p;
631 c = handle_eob();
632 p = file->buf_ptr;
633 if (c == CH_EOF) {
634 unterminated_string:
635 /* XXX: indicate line number of start of string */
636 tcc_error("missing terminating %c character", sep);
637 } else if (c == '\\') {
638 /* escape : just skip \[\r]\n */
639 PEEKC_EOB(c, p);
640 if (c == '\n') {
641 file->line_num++;
642 p++;
643 } else if (c == '\r') {
644 PEEKC_EOB(c, p);
645 if (c != '\n')
646 expect("'\n' after '\r'");
647 file->line_num++;
648 p++;
649 } else if (c == CH_EOF) {
650 goto unterminated_string;
651 } else {
652 if (str) {
653 cstr_ccat(str, '\\');
654 cstr_ccat(str, c);
656 p++;
659 } else if (c == '\n') {
660 file->line_num++;
661 goto add_char;
662 } else if (c == '\r') {
663 PEEKC_EOB(c, p);
664 if (c != '\n') {
665 if (str)
666 cstr_ccat(str, '\r');
667 } else {
668 file->line_num++;
669 goto add_char;
671 } else {
672 add_char:
673 if (str)
674 cstr_ccat(str, c);
675 p++;
678 p++;
679 return p;
682 /* skip block of text until #else, #elif or #endif. skip also pairs of
683 #if/#endif */
684 static void preprocess_skip(void)
686 int a, start_of_line, c, in_warn_or_error;
687 uint8_t *p;
689 p = file->buf_ptr;
690 a = 0;
691 redo_start:
692 start_of_line = 1;
693 in_warn_or_error = 0;
694 for(;;) {
695 redo_no_start:
696 c = *p;
697 switch(c) {
698 case ' ':
699 case '\t':
700 case '\f':
701 case '\v':
702 case '\r':
703 p++;
704 goto redo_no_start;
705 case '\n':
706 file->line_num++;
707 p++;
708 goto redo_start;
709 case '\\':
710 file->buf_ptr = p;
711 c = handle_eob();
712 if (c == CH_EOF) {
713 expect("#endif");
714 } else if (c == '\\') {
715 ch = file->buf_ptr[0];
716 handle_stray_noerror();
718 p = file->buf_ptr;
719 goto redo_no_start;
720 /* skip strings */
721 case '\"':
722 case '\'':
723 if (in_warn_or_error)
724 goto _default;
725 p = parse_pp_string(p, c, NULL);
726 break;
727 /* skip comments */
728 case '/':
729 if (in_warn_or_error)
730 goto _default;
731 file->buf_ptr = p;
732 ch = *p;
733 minp();
734 p = file->buf_ptr;
735 if (ch == '*') {
736 p = parse_comment(p);
737 } else if (ch == '/') {
738 p = parse_line_comment(p);
740 break;
741 case '#':
742 p++;
743 if (start_of_line) {
744 file->buf_ptr = p;
745 next_nomacro();
746 p = file->buf_ptr;
747 if (a == 0 &&
748 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
749 goto the_end;
750 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
751 a++;
752 else if (tok == TOK_ENDIF)
753 a--;
754 else if( tok == TOK_ERROR || tok == TOK_WARNING)
755 in_warn_or_error = 1;
756 else if (tok == TOK_LINEFEED)
757 goto redo_start;
759 break;
760 _default:
761 default:
762 p++;
763 break;
765 start_of_line = 0;
767 the_end: ;
768 file->buf_ptr = p;
771 /* ParseState handling */
773 /* XXX: currently, no include file info is stored. Thus, we cannot display
774 accurate messages if the function or data definition spans multiple
775 files */
777 /* save current parse state in 's' */
778 ST_FUNC void save_parse_state(ParseState *s)
780 s->line_num = file->line_num;
781 s->macro_ptr = macro_ptr;
782 s->tok = tok;
783 s->tokc = tokc;
786 /* restore parse state from 's' */
787 ST_FUNC void restore_parse_state(ParseState *s)
789 file->line_num = s->line_num;
790 macro_ptr = s->macro_ptr;
791 tok = s->tok;
792 tokc = s->tokc;
795 /* return the number of additional 'ints' necessary to store the
796 token */
797 static inline int tok_ext_size(int t)
799 switch(t) {
800 /* 4 bytes */
801 case TOK_CINT:
802 case TOK_CUINT:
803 case TOK_CCHAR:
804 case TOK_LCHAR:
805 case TOK_CFLOAT:
806 case TOK_LINENUM:
807 return 1;
808 case TOK_STR:
809 case TOK_LSTR:
810 case TOK_PPNUM:
811 tcc_error("unsupported token");
812 return 1;
813 case TOK_CDOUBLE:
814 case TOK_CLLONG:
815 case TOK_CULLONG:
816 return 2;
817 case TOK_CLDOUBLE:
818 return LDOUBLE_SIZE / 4;
819 default:
820 return 0;
824 /* token string handling */
826 ST_INLN void tok_str_new(TokenString *s)
828 s->str = NULL;
829 s->len = 0;
830 s->allocated_len = 0;
831 s->last_line_num = -1;
834 ST_FUNC void tok_str_free(int *str)
836 tcc_free(str);
839 static int *tok_str_realloc(TokenString *s)
841 int *str, len;
843 if (s->allocated_len == 0) {
844 len = 8;
845 } else {
846 len = s->allocated_len * 2;
848 str = tcc_realloc(s->str, len * sizeof(int));
849 s->allocated_len = len;
850 s->str = str;
851 return str;
854 ST_FUNC void tok_str_add(TokenString *s, int t)
856 int len, *str;
858 len = s->len;
859 str = s->str;
860 if (len >= s->allocated_len)
861 str = tok_str_realloc(s);
862 str[len++] = t;
863 s->len = len;
866 static void tok_str_add2(TokenString *s, int t, CValue *cv)
868 int len, *str;
870 len = s->len;
871 str = s->str;
873 /* allocate space for worst case */
874 if (len + TOK_MAX_SIZE > s->allocated_len)
875 str = tok_str_realloc(s);
876 str[len++] = t;
877 switch(t) {
878 case TOK_CINT:
879 case TOK_CUINT:
880 case TOK_CCHAR:
881 case TOK_LCHAR:
882 case TOK_CFLOAT:
883 case TOK_LINENUM:
884 str[len++] = cv->tab[0];
885 break;
886 case TOK_PPNUM:
887 case TOK_STR:
888 case TOK_LSTR:
890 int nb_words;
891 CString *cstr;
893 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
894 while ((len + nb_words) > s->allocated_len)
895 str = tok_str_realloc(s);
896 cstr = (CString *)(str + len);
897 cstr->data = NULL;
898 cstr->size = cv->cstr->size;
899 cstr->data_allocated = NULL;
900 cstr->size_allocated = cstr->size;
901 memcpy((char *)cstr + sizeof(CString),
902 cv->cstr->data, cstr->size);
903 len += nb_words;
905 break;
906 case TOK_CDOUBLE:
907 case TOK_CLLONG:
908 case TOK_CULLONG:
909 #if LDOUBLE_SIZE == 8
910 case TOK_CLDOUBLE:
911 #endif
912 str[len++] = cv->tab[0];
913 str[len++] = cv->tab[1];
914 break;
915 #if LDOUBLE_SIZE == 12
916 case TOK_CLDOUBLE:
917 str[len++] = cv->tab[0];
918 str[len++] = cv->tab[1];
919 str[len++] = cv->tab[2];
920 #elif LDOUBLE_SIZE == 16
921 case TOK_CLDOUBLE:
922 str[len++] = cv->tab[0];
923 str[len++] = cv->tab[1];
924 str[len++] = cv->tab[2];
925 str[len++] = cv->tab[3];
926 #elif LDOUBLE_SIZE != 8
927 #error add long double size support
928 #endif
929 break;
930 default:
931 break;
933 s->len = len;
936 /* add the current parse token in token string 's' */
937 ST_FUNC void tok_str_add_tok(TokenString *s)
939 CValue cval;
941 /* save line number info */
942 if (file->line_num != s->last_line_num) {
943 s->last_line_num = file->line_num;
944 cval.i = s->last_line_num;
945 tok_str_add2(s, TOK_LINENUM, &cval);
947 tok_str_add2(s, tok, &tokc);
950 /* get a token from an integer array and increment pointer
951 accordingly. we code it as a macro to avoid pointer aliasing. */
952 static inline void TOK_GET(int *t, const int **pp, CValue *cv)
954 const int *p = *pp;
955 int n, *tab;
957 tab = cv->tab;
958 switch(*t = *p++) {
959 case TOK_CINT:
960 case TOK_CUINT:
961 case TOK_CCHAR:
962 case TOK_LCHAR:
963 case TOK_CFLOAT:
964 case TOK_LINENUM:
965 tab[0] = *p++;
966 break;
967 case TOK_STR:
968 case TOK_LSTR:
969 case TOK_PPNUM:
970 cv->cstr = (CString *)p;
971 cv->cstr->data = (char *)p + sizeof(CString);
972 p += (sizeof(CString) + cv->cstr->size + 3) >> 2;
973 break;
974 case TOK_CDOUBLE:
975 case TOK_CLLONG:
976 case TOK_CULLONG:
977 n = 2;
978 goto copy;
979 case TOK_CLDOUBLE:
980 #if LDOUBLE_SIZE == 16
981 n = 4;
982 #elif LDOUBLE_SIZE == 12
983 n = 3;
984 #elif LDOUBLE_SIZE == 8
985 n = 2;
986 #else
987 # error add long double size support
988 #endif
989 copy:
991 *tab++ = *p++;
992 while (--n);
993 break;
994 default:
995 break;
997 *pp = p;
1000 static int macro_is_equal(const int *a, const int *b)
1002 char buf[STRING_MAX_SIZE + 1];
1003 CValue cv;
1004 int t;
1005 while (*a && *b) {
1006 TOK_GET(&t, &a, &cv);
1007 pstrcpy(buf, sizeof buf, get_tok_str(t, &cv));
1008 TOK_GET(&t, &b, &cv);
1009 if (strcmp(buf, get_tok_str(t, &cv)))
1010 return 0;
1012 return !(*a || *b);
1015 /* defines handling */
1016 ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg)
1018 Sym *s;
1020 s = define_find(v);
1021 if (s && !macro_is_equal(s->d, str))
1022 tcc_warning("%s redefined", get_tok_str(v, NULL));
1024 s = sym_push2(&define_stack, v, macro_type, 0);
1025 s->d = str;
1026 s->next = first_arg;
1027 table_ident[v - TOK_IDENT]->sym_define = s;
1030 /* undefined a define symbol. Its name is just set to zero */
1031 ST_FUNC void define_undef(Sym *s)
1033 int v;
1034 v = s->v;
1035 if (v >= TOK_IDENT && v < tok_ident)
1036 table_ident[v - TOK_IDENT]->sym_define = NULL;
1037 s->v = 0;
1040 ST_INLN Sym *define_find(int v)
1042 v -= TOK_IDENT;
1043 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1044 return NULL;
1045 return table_ident[v]->sym_define;
1048 /* free define stack until top reaches 'b' */
1049 ST_FUNC void free_defines(Sym *b)
1051 Sym *top, *top1;
1052 int v;
1054 top = define_stack;
1055 while (top != b) {
1056 top1 = top->prev;
1057 /* do not free args or predefined defines */
1058 if (top->d)
1059 tok_str_free(top->d);
1060 v = top->v;
1061 if (v >= TOK_IDENT && v < tok_ident)
1062 table_ident[v - TOK_IDENT]->sym_define = NULL;
1063 sym_free(top);
1064 top = top1;
1066 define_stack = b;
1069 /* label lookup */
1070 ST_FUNC Sym *label_find(int v)
1072 v -= TOK_IDENT;
1073 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1074 return NULL;
1075 return table_ident[v]->sym_label;
1078 ST_FUNC Sym *label_push(Sym **ptop, int v, int flags)
1080 Sym *s, **ps;
1081 s = sym_push2(ptop, v, 0, 0);
1082 s->r = flags;
1083 ps = &table_ident[v - TOK_IDENT]->sym_label;
1084 if (ptop == &global_label_stack) {
1085 /* modify the top most local identifier, so that
1086 sym_identifier will point to 's' when popped */
1087 while (*ps != NULL)
1088 ps = &(*ps)->prev_tok;
1090 s->prev_tok = *ps;
1091 *ps = s;
1092 return s;
1095 /* pop labels until element last is reached. Look if any labels are
1096 undefined. Define symbols if '&&label' was used. */
1097 ST_FUNC void label_pop(Sym **ptop, Sym *slast)
1099 Sym *s, *s1;
1100 for(s = *ptop; s != slast; s = s1) {
1101 s1 = s->prev;
1102 if (s->r == LABEL_DECLARED) {
1103 tcc_warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
1104 } else if (s->r == LABEL_FORWARD) {
1105 tcc_error("label '%s' used but not defined",
1106 get_tok_str(s->v, NULL));
1107 } else {
1108 if (s->c) {
1109 /* define corresponding symbol. A size of
1110 1 is put. */
1111 put_extern_sym(s, cur_text_section, s->jnext, 1);
1114 /* remove label */
1115 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
1116 sym_free(s);
1118 *ptop = slast;
1121 /* eval an expression for #if/#elif */
1122 static int expr_preprocess(void)
1124 int c, t;
1125 TokenString str;
1127 tok_str_new(&str);
1128 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1129 next(); /* do macro subst */
1130 if (tok == TOK_DEFINED) {
1131 next_nomacro();
1132 t = tok;
1133 if (t == '(')
1134 next_nomacro();
1135 c = define_find(tok) != 0;
1136 if (t == '(')
1137 next_nomacro();
1138 tok = TOK_CINT;
1139 tokc.i = c;
1140 } else if (tok >= TOK_IDENT) {
1141 /* if undefined macro */
1142 tok = TOK_CINT;
1143 tokc.i = 0;
1145 tok_str_add_tok(&str);
1147 tok_str_add(&str, -1); /* simulate end of file */
1148 tok_str_add(&str, 0);
1149 /* now evaluate C constant expression */
1150 macro_ptr = str.str;
1151 next();
1152 c = expr_const();
1153 macro_ptr = NULL;
1154 tok_str_free(str.str);
1155 return c != 0;
1158 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1159 static void tok_print(int *str)
1161 int t;
1162 CValue cval;
1164 printf("<");
1165 while (1) {
1166 TOK_GET(&t, &str, &cval);
1167 if (!t)
1168 break;
1169 printf("%s", get_tok_str(t, &cval));
1171 printf(">\n");
1173 #endif
1175 /* parse after #define */
1176 ST_FUNC void parse_define(void)
1178 Sym *s, *first, **ps;
1179 int v, t, varg, is_vaargs, spc;
1180 TokenString str;
1182 v = tok;
1183 if (v < TOK_IDENT)
1184 tcc_error("invalid macro name '%s'", get_tok_str(tok, &tokc));
1185 /* XXX: should check if same macro (ANSI) */
1186 first = NULL;
1187 t = MACRO_OBJ;
1188 /* '(' must be just after macro definition for MACRO_FUNC */
1189 next_nomacro_spc();
1190 if (tok == '(') {
1191 next_nomacro();
1192 ps = &first;
1193 while (tok != ')') {
1194 varg = tok;
1195 next_nomacro();
1196 is_vaargs = 0;
1197 if (varg == TOK_DOTS) {
1198 varg = TOK___VA_ARGS__;
1199 is_vaargs = 1;
1200 } else if (tok == TOK_DOTS && gnu_ext) {
1201 is_vaargs = 1;
1202 next_nomacro();
1204 if (varg < TOK_IDENT)
1205 tcc_error("badly punctuated parameter list");
1206 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
1207 *ps = s;
1208 ps = &s->next;
1209 if (tok != ',')
1210 break;
1211 next_nomacro();
1213 if (tok == ')')
1214 next_nomacro_spc();
1215 t = MACRO_FUNC;
1217 tok_str_new(&str);
1218 spc = 2;
1219 /* EOF testing necessary for '-D' handling */
1220 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
1221 /* remove spaces around ## and after '#' */
1222 if (TOK_TWOSHARPS == tok) {
1223 if (1 == spc)
1224 --str.len;
1225 spc = 2;
1226 } else if ('#' == tok) {
1227 spc = 2;
1228 } else if (check_space(tok, &spc)) {
1229 goto skip;
1231 tok_str_add2(&str, tok, &tokc);
1232 skip:
1233 next_nomacro_spc();
1235 if (spc == 1)
1236 --str.len; /* remove trailing space */
1237 tok_str_add(&str, 0);
1238 #ifdef PP_DEBUG
1239 printf("define %s %d: ", get_tok_str(v, NULL), t);
1240 tok_print(str.str);
1241 #endif
1242 define_push(v, t, str.str, first);
1245 static inline int hash_cached_include(const char *filename)
1247 const unsigned char *s;
1248 unsigned int h;
1250 h = TOK_HASH_INIT;
1251 s = filename;
1252 while (*s) {
1253 h = TOK_HASH_FUNC(h, *s);
1254 s++;
1256 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
1257 return h;
1260 static CachedInclude *search_cached_include(TCCState *s1, const char *filename)
1262 CachedInclude *e;
1263 int i, h;
1264 h = hash_cached_include(filename);
1265 i = s1->cached_includes_hash[h];
1266 for(;;) {
1267 if (i == 0)
1268 break;
1269 e = s1->cached_includes[i - 1];
1270 if (0 == PATHCMP(e->filename, filename))
1271 return e;
1272 i = e->hash_next;
1274 return NULL;
1277 static inline void add_cached_include(TCCState *s1, const char *filename, int ifndef_macro)
1279 CachedInclude *e;
1280 int h;
1282 if (search_cached_include(s1, filename))
1283 return;
1284 #ifdef INC_DEBUG
1285 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
1286 #endif
1287 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
1288 strcpy(e->filename, filename);
1289 e->ifndef_macro = ifndef_macro;
1290 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
1291 /* add in hash table */
1292 h = hash_cached_include(filename);
1293 e->hash_next = s1->cached_includes_hash[h];
1294 s1->cached_includes_hash[h] = s1->nb_cached_includes;
1297 static void pragma_parse(TCCState *s1)
1299 int val;
1301 next();
1302 if (tok == TOK_pack) {
1304 This may be:
1305 #pragma pack(1) // set
1306 #pragma pack() // reset to default
1307 #pragma pack(push,1) // push & set
1308 #pragma pack(pop) // restore previous
1310 next();
1311 skip('(');
1312 if (tok == TOK_ASM_pop) {
1313 next();
1314 if (s1->pack_stack_ptr <= s1->pack_stack) {
1315 stk_error:
1316 tcc_error("out of pack stack");
1318 s1->pack_stack_ptr--;
1319 } else {
1320 val = 0;
1321 if (tok != ')') {
1322 if (tok == TOK_ASM_push) {
1323 next();
1324 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
1325 goto stk_error;
1326 s1->pack_stack_ptr++;
1327 skip(',');
1329 if (tok != TOK_CINT) {
1330 pack_error:
1331 tcc_error("invalid pack pragma");
1333 val = tokc.i;
1334 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
1335 goto pack_error;
1336 next();
1338 *s1->pack_stack_ptr = val;
1339 skip(')');
1344 /* is_bof is true if first non space token at beginning of file */
1345 ST_FUNC void preprocess(int is_bof)
1347 TCCState *s1 = tcc_state;
1348 int i, c, n, saved_parse_flags;
1349 char buf[1024], *q;
1350 Sym *s;
1352 saved_parse_flags = parse_flags;
1353 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
1354 PARSE_FLAG_LINEFEED;
1355 next_nomacro();
1356 redo:
1357 switch(tok) {
1358 case TOK_DEFINE:
1359 next_nomacro();
1360 parse_define();
1361 break;
1362 case TOK_UNDEF:
1363 next_nomacro();
1364 s = define_find(tok);
1365 /* undefine symbol by putting an invalid name */
1366 if (s)
1367 define_undef(s);
1368 break;
1369 case TOK_INCLUDE:
1370 case TOK_INCLUDE_NEXT:
1371 ch = file->buf_ptr[0];
1372 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1373 skip_spaces();
1374 if (ch == '<') {
1375 c = '>';
1376 goto read_name;
1377 } else if (ch == '\"') {
1378 c = ch;
1379 read_name:
1380 inp();
1381 q = buf;
1382 while (ch != c && ch != '\n' && ch != CH_EOF) {
1383 if ((q - buf) < sizeof(buf) - 1)
1384 *q++ = ch;
1385 if (ch == '\\') {
1386 if (handle_stray_noerror() == 0)
1387 --q;
1388 } else
1389 inp();
1391 *q = '\0';
1392 minp();
1393 #if 0
1394 /* eat all spaces and comments after include */
1395 /* XXX: slightly incorrect */
1396 while (ch1 != '\n' && ch1 != CH_EOF)
1397 inp();
1398 #endif
1399 } else {
1400 /* computed #include : either we have only strings or
1401 we have anything enclosed in '<>' */
1402 next();
1403 buf[0] = '\0';
1404 if (tok == TOK_STR) {
1405 while (tok != TOK_LINEFEED) {
1406 if (tok != TOK_STR) {
1407 include_syntax:
1408 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1410 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
1411 next();
1413 c = '\"';
1414 } else {
1415 int len;
1416 while (tok != TOK_LINEFEED) {
1417 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
1418 next();
1420 len = strlen(buf);
1421 /* check syntax and remove '<>' */
1422 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
1423 goto include_syntax;
1424 memmove(buf, buf + 1, len - 2);
1425 buf[len - 2] = '\0';
1426 c = '>';
1430 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
1431 tcc_error("#include recursion too deep");
1432 /* store current file in stack, but increment stack later below */
1433 *s1->include_stack_ptr = file;
1435 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
1436 for (i = -2; i < n; ++i) {
1437 char buf1[sizeof file->filename];
1438 CachedInclude *e;
1439 BufferedFile **f;
1440 const char *path;
1441 int size;
1442 vio_fd fd;
1444 if (i == -2) {
1445 /* check absolute include path */
1446 if (!IS_ABSPATH(buf))
1447 continue;
1448 buf1[0] = 0;
1449 i = n; /* force end loop */
1451 } else if (i == -1) {
1452 /* search in current dir if "header.h" */
1453 if (c != '\"')
1454 continue;
1455 size = tcc_basename(file->filename) - file->filename;
1456 memcpy(buf1, file->filename, size);
1457 buf1[size] = '\0';
1459 } else {
1460 /* search in all the include paths */
1461 if (i < s1->nb_include_paths)
1462 path = s1->include_paths[i];
1463 else
1464 path = s1->sysinclude_paths[i - s1->nb_include_paths];
1465 pstrcpy(buf1, sizeof(buf1), path);
1466 pstrcat(buf1, sizeof(buf1), "/");
1469 pstrcat(buf1, sizeof(buf1), buf);
1471 if (tok == TOK_INCLUDE_NEXT)
1472 for (f = s1->include_stack_ptr; f >= s1->include_stack; --f)
1473 if (0 == PATHCMP((*f)->filename, buf1)) {
1474 #ifdef INC_DEBUG
1475 printf("%s: #include_next skipping %s\n", file->filename, buf1);
1476 #endif
1477 goto include_trynext;
1480 e = search_cached_include(s1, buf1);
1481 if (e && define_find(e->ifndef_macro)) {
1482 /* no need to parse the include because the 'ifndef macro'
1483 is defined */
1484 #ifdef INC_DEBUG
1485 printf("%s: skipping cached %s\n", file->filename, buf1);
1486 #endif
1487 vio_initialize(&fd);
1488 fd.fd = 0;
1489 goto include_done;
1492 fd = tcc_open(s1, buf1);
1493 if (fd.fd < 0)
1494 include_trynext:
1495 continue;
1497 #ifdef INC_DEBUG
1498 printf("%s: including %s\n", file->prev->filename, file->filename);
1499 #endif
1500 /* update target deps */
1501 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1502 tcc_strdup(buf1));
1503 /* push current file in stack */
1504 ++s1->include_stack_ptr;
1505 /* add include file debug info */
1506 if (s1->do_debug)
1507 put_stabs(file->filename, N_BINCL, 0, 0, 0);
1508 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
1509 ch = file->buf_ptr[0];
1510 goto the_end;
1512 tcc_error("include file '%s' not found", buf);
1513 include_done:
1514 break;
1515 case TOK_IFNDEF:
1516 c = 1;
1517 goto do_ifdef;
1518 case TOK_IF:
1519 c = expr_preprocess();
1520 goto do_if;
1521 case TOK_IFDEF:
1522 c = 0;
1523 do_ifdef:
1524 next_nomacro();
1525 if (tok < TOK_IDENT)
1526 tcc_error("invalid argument for '#if%sdef'", c ? "n" : "");
1527 if (is_bof) {
1528 if (c) {
1529 #ifdef INC_DEBUG
1530 printf("#ifndef %s\n", get_tok_str(tok, NULL));
1531 #endif
1532 file->ifndef_macro = tok;
1535 c = (define_find(tok) != 0) ^ c;
1536 do_if:
1537 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
1538 tcc_error("memory full");
1539 *s1->ifdef_stack_ptr++ = c;
1540 goto test_skip;
1541 case TOK_ELSE:
1542 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1543 tcc_error("#else without matching #if");
1544 if (s1->ifdef_stack_ptr[-1] & 2)
1545 tcc_error("#else after #else");
1546 c = (s1->ifdef_stack_ptr[-1] ^= 3);
1547 goto test_else;
1548 case TOK_ELIF:
1549 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
1550 tcc_error("#elif without matching #if");
1551 c = s1->ifdef_stack_ptr[-1];
1552 if (c > 1)
1553 tcc_error("#elif after #else");
1554 /* last #if/#elif expression was true: we skip */
1555 if (c == 1)
1556 goto skip;
1557 c = expr_preprocess();
1558 s1->ifdef_stack_ptr[-1] = c;
1559 test_else:
1560 if (s1->ifdef_stack_ptr == file->ifdef_stack_ptr + 1)
1561 file->ifndef_macro = 0;
1562 test_skip:
1563 if (!(c & 1)) {
1564 skip:
1565 preprocess_skip();
1566 is_bof = 0;
1567 goto redo;
1569 break;
1570 case TOK_ENDIF:
1571 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
1572 tcc_error("#endif without matching #if");
1573 s1->ifdef_stack_ptr--;
1574 /* '#ifndef macro' was at the start of file. Now we check if
1575 an '#endif' is exactly at the end of file */
1576 if (file->ifndef_macro &&
1577 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
1578 file->ifndef_macro_saved = file->ifndef_macro;
1579 /* need to set to zero to avoid false matches if another
1580 #ifndef at middle of file */
1581 file->ifndef_macro = 0;
1582 while (tok != TOK_LINEFEED)
1583 next_nomacro();
1584 tok_flags |= TOK_FLAG_ENDIF;
1585 goto the_end;
1587 break;
1588 case TOK_LINE:
1589 next();
1590 if (tok != TOK_CINT)
1591 tcc_error("#line");
1592 file->line_num = tokc.i - 1; /* the line number will be incremented after */
1593 next();
1594 if (tok != TOK_LINEFEED) {
1595 if (tok != TOK_STR)
1596 tcc_error("#line");
1597 pstrcpy(file->filename, sizeof(file->filename),
1598 (char *)tokc.cstr->data);
1600 break;
1601 case TOK_ERROR:
1602 case TOK_WARNING:
1603 c = tok;
1604 ch = file->buf_ptr[0];
1605 skip_spaces();
1606 q = buf;
1607 while (ch != '\n' && ch != CH_EOF) {
1608 if ((q - buf) < sizeof(buf) - 1)
1609 *q++ = ch;
1610 if (ch == '\\') {
1611 if (handle_stray_noerror() == 0)
1612 --q;
1613 } else
1614 inp();
1616 *q = '\0';
1617 if (c == TOK_ERROR)
1618 tcc_error("#error %s", buf);
1619 else
1620 tcc_warning("#warning %s", buf);
1621 break;
1622 case TOK_PRAGMA:
1623 pragma_parse(s1);
1624 break;
1625 default:
1626 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_PPNUM) {
1627 /* '!' is ignored to allow C scripts. numbers are ignored
1628 to emulate cpp behaviour */
1629 } else {
1630 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
1631 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
1632 else {
1633 /* this is a gas line comment in an 'S' file. */
1634 file->buf_ptr = parse_line_comment(file->buf_ptr);
1635 goto the_end;
1638 break;
1640 /* ignore other preprocess commands or #! for C scripts */
1641 while (tok != TOK_LINEFEED)
1642 next_nomacro();
1643 the_end:
1644 parse_flags = saved_parse_flags;
1647 /* evaluate escape codes in a string. */
1648 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
1650 int c, n;
1651 const uint8_t *p;
1653 p = buf;
1654 for(;;) {
1655 c = *p;
1656 if (c == '\0')
1657 break;
1658 if (c == '\\') {
1659 p++;
1660 /* escape */
1661 c = *p;
1662 switch(c) {
1663 case '0': case '1': case '2': case '3':
1664 case '4': case '5': case '6': case '7':
1665 /* at most three octal digits */
1666 n = c - '0';
1667 p++;
1668 c = *p;
1669 if (isoct(c)) {
1670 n = n * 8 + c - '0';
1671 p++;
1672 c = *p;
1673 if (isoct(c)) {
1674 n = n * 8 + c - '0';
1675 p++;
1678 c = n;
1679 goto add_char_nonext;
1680 case 'x':
1681 case 'u':
1682 case 'U':
1683 p++;
1684 n = 0;
1685 for(;;) {
1686 c = *p;
1687 if (c >= 'a' && c <= 'f')
1688 c = c - 'a' + 10;
1689 else if (c >= 'A' && c <= 'F')
1690 c = c - 'A' + 10;
1691 else if (isnum(c))
1692 c = c - '0';
1693 else
1694 break;
1695 n = n * 16 + c;
1696 p++;
1698 c = n;
1699 goto add_char_nonext;
1700 case 'a':
1701 c = '\a';
1702 break;
1703 case 'b':
1704 c = '\b';
1705 break;
1706 case 'f':
1707 c = '\f';
1708 break;
1709 case 'n':
1710 c = '\n';
1711 break;
1712 case 'r':
1713 c = '\r';
1714 break;
1715 case 't':
1716 c = '\t';
1717 break;
1718 case 'v':
1719 c = '\v';
1720 break;
1721 case 'e':
1722 if (!gnu_ext)
1723 goto invalid_escape;
1724 c = 27;
1725 break;
1726 case '\'':
1727 case '\"':
1728 case '\\':
1729 case '?':
1730 break;
1731 default:
1732 invalid_escape:
1733 if (c >= '!' && c <= '~')
1734 tcc_warning("unknown escape sequence: \'\\%c\'", c);
1735 else
1736 tcc_warning("unknown escape sequence: \'\\x%x\'", c);
1737 break;
1740 p++;
1741 add_char_nonext:
1742 if (!is_long)
1743 cstr_ccat(outstr, c);
1744 else
1745 cstr_wccat(outstr, c);
1747 /* add a trailing '\0' */
1748 if (!is_long)
1749 cstr_ccat(outstr, '\0');
1750 else
1751 cstr_wccat(outstr, '\0');
1754 /* we use 64 bit numbers */
1755 #define BN_SIZE 2
1757 /* bn = (bn << shift) | or_val */
1758 static void bn_lshift(unsigned int *bn, int shift, int or_val)
1760 int i;
1761 unsigned int v;
1762 for(i=0;i<BN_SIZE;i++) {
1763 v = bn[i];
1764 bn[i] = (v << shift) | or_val;
1765 or_val = v >> (32 - shift);
1769 static void bn_zero(unsigned int *bn)
1771 int i;
1772 for(i=0;i<BN_SIZE;i++) {
1773 bn[i] = 0;
1777 /* parse number in null terminated string 'p' and return it in the
1778 current token */
1779 static void parse_number(const char *p)
1781 int b, t, shift, frac_bits, s, exp_val, ch;
1782 char *q;
1783 unsigned int bn[BN_SIZE];
1784 double d;
1786 /* number */
1787 q = token_buf;
1788 ch = *p++;
1789 t = ch;
1790 ch = *p++;
1791 *q++ = t;
1792 b = 10;
1793 if (t == '.') {
1794 goto float_frac_parse;
1795 } else if (t == '0') {
1796 if (ch == 'x' || ch == 'X') {
1797 q--;
1798 ch = *p++;
1799 b = 16;
1800 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
1801 q--;
1802 ch = *p++;
1803 b = 2;
1806 /* parse all digits. cannot check octal numbers at this stage
1807 because of floating point constants */
1808 while (1) {
1809 if (ch >= 'a' && ch <= 'f')
1810 t = ch - 'a' + 10;
1811 else if (ch >= 'A' && ch <= 'F')
1812 t = ch - 'A' + 10;
1813 else if (isnum(ch))
1814 t = ch - '0';
1815 else
1816 break;
1817 if (t >= b)
1818 break;
1819 if (q >= token_buf + STRING_MAX_SIZE) {
1820 num_too_long:
1821 tcc_error("number too long");
1823 *q++ = ch;
1824 ch = *p++;
1826 if (ch == '.' ||
1827 ((ch == 'e' || ch == 'E') && b == 10) ||
1828 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
1829 if (b != 10) {
1830 /* NOTE: strtox should support that for hexa numbers, but
1831 non ISOC99 libcs do not support it, so we prefer to do
1832 it by hand */
1833 /* hexadecimal or binary floats */
1834 /* XXX: handle overflows */
1835 *q = '\0';
1836 if (b == 16)
1837 shift = 4;
1838 else
1839 shift = 2;
1840 bn_zero(bn);
1841 q = token_buf;
1842 while (1) {
1843 t = *q++;
1844 if (t == '\0') {
1845 break;
1846 } else if (t >= 'a') {
1847 t = t - 'a' + 10;
1848 } else if (t >= 'A') {
1849 t = t - 'A' + 10;
1850 } else {
1851 t = t - '0';
1853 bn_lshift(bn, shift, t);
1855 frac_bits = 0;
1856 if (ch == '.') {
1857 ch = *p++;
1858 while (1) {
1859 t = ch;
1860 if (t >= 'a' && t <= 'f') {
1861 t = t - 'a' + 10;
1862 } else if (t >= 'A' && t <= 'F') {
1863 t = t - 'A' + 10;
1864 } else if (t >= '0' && t <= '9') {
1865 t = t - '0';
1866 } else {
1867 break;
1869 if (t >= b)
1870 tcc_error("invalid digit");
1871 bn_lshift(bn, shift, t);
1872 frac_bits += shift;
1873 ch = *p++;
1876 if (ch != 'p' && ch != 'P')
1877 expect("exponent");
1878 ch = *p++;
1879 s = 1;
1880 exp_val = 0;
1881 if (ch == '+') {
1882 ch = *p++;
1883 } else if (ch == '-') {
1884 s = -1;
1885 ch = *p++;
1887 if (ch < '0' || ch > '9')
1888 expect("exponent digits");
1889 while (ch >= '0' && ch <= '9') {
1890 exp_val = exp_val * 10 + ch - '0';
1891 ch = *p++;
1893 exp_val = exp_val * s;
1895 /* now we can generate the number */
1896 /* XXX: should patch directly float number */
1897 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
1898 d = ldexp(d, exp_val - frac_bits);
1899 t = toup(ch);
1900 if (t == 'F') {
1901 ch = *p++;
1902 tok = TOK_CFLOAT;
1903 /* float : should handle overflow */
1904 tokc.f = (float)d;
1905 } else if (t == 'L') {
1906 ch = *p++;
1907 #ifdef TCC_TARGET_PE
1908 tok = TOK_CDOUBLE;
1909 tokc.d = d;
1910 #else
1911 tok = TOK_CLDOUBLE;
1912 /* XXX: not large enough */
1913 tokc.ld = (long double)d;
1914 #endif
1915 } else {
1916 tok = TOK_CDOUBLE;
1917 tokc.d = d;
1919 } else {
1920 /* decimal floats */
1921 if (ch == '.') {
1922 if (q >= token_buf + STRING_MAX_SIZE)
1923 goto num_too_long;
1924 *q++ = ch;
1925 ch = *p++;
1926 float_frac_parse:
1927 while (ch >= '0' && ch <= '9') {
1928 if (q >= token_buf + STRING_MAX_SIZE)
1929 goto num_too_long;
1930 *q++ = ch;
1931 ch = *p++;
1934 if (ch == 'e' || ch == 'E') {
1935 if (q >= token_buf + STRING_MAX_SIZE)
1936 goto num_too_long;
1937 *q++ = ch;
1938 ch = *p++;
1939 if (ch == '-' || ch == '+') {
1940 if (q >= token_buf + STRING_MAX_SIZE)
1941 goto num_too_long;
1942 *q++ = ch;
1943 ch = *p++;
1945 if (ch < '0' || ch > '9')
1946 expect("exponent digits");
1947 while (ch >= '0' && ch <= '9') {
1948 if (q >= token_buf + STRING_MAX_SIZE)
1949 goto num_too_long;
1950 *q++ = ch;
1951 ch = *p++;
1954 *q = '\0';
1955 t = toup(ch);
1956 errno = 0;
1957 if (t == 'F') {
1958 ch = *p++;
1959 tok = TOK_CFLOAT;
1960 tokc.f = strtof(token_buf, NULL);
1961 } else if (t == 'L') {
1962 ch = *p++;
1963 #ifdef TCC_TARGET_PE
1964 tok = TOK_CDOUBLE;
1965 tokc.d = strtod(token_buf, NULL);
1966 #else
1967 tok = TOK_CLDOUBLE;
1968 tokc.ld = strtold(token_buf, NULL);
1969 #endif
1970 } else {
1971 tok = TOK_CDOUBLE;
1972 tokc.d = strtod(token_buf, NULL);
1975 } else {
1976 unsigned long long n, n1;
1977 int lcount, ucount;
1979 /* integer number */
1980 *q = '\0';
1981 q = token_buf;
1982 if (b == 10 && *q == '0') {
1983 b = 8;
1984 q++;
1986 n = 0;
1987 while(1) {
1988 t = *q++;
1989 /* no need for checks except for base 10 / 8 errors */
1990 if (t == '\0') {
1991 break;
1992 } else if (t >= 'a') {
1993 t = t - 'a' + 10;
1994 } else if (t >= 'A') {
1995 t = t - 'A' + 10;
1996 } else {
1997 t = t - '0';
1998 if (t >= b)
1999 tcc_error("invalid digit");
2001 n1 = n;
2002 n = n * b + t;
2003 /* detect overflow */
2004 /* XXX: this test is not reliable */
2005 if (n < n1)
2006 tcc_error("integer constant overflow");
2009 /* XXX: not exactly ANSI compliant */
2010 if ((n & 0xffffffff00000000LL) != 0) {
2011 if ((n >> 63) != 0)
2012 tok = TOK_CULLONG;
2013 else
2014 tok = TOK_CLLONG;
2015 } else if (n > 0x7fffffff) {
2016 tok = TOK_CUINT;
2017 } else {
2018 tok = TOK_CINT;
2020 lcount = 0;
2021 ucount = 0;
2022 for(;;) {
2023 t = toup(ch);
2024 if (t == 'L') {
2025 if (lcount >= 2)
2026 tcc_error("three 'l's in integer constant");
2027 lcount++;
2028 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2029 if (lcount == 2) {
2030 #endif
2031 if (tok == TOK_CINT)
2032 tok = TOK_CLLONG;
2033 else if (tok == TOK_CUINT)
2034 tok = TOK_CULLONG;
2035 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2037 #endif
2038 ch = *p++;
2039 } else if (t == 'U') {
2040 if (ucount >= 1)
2041 tcc_error("two 'u's in integer constant");
2042 ucount++;
2043 if (tok == TOK_CINT)
2044 tok = TOK_CUINT;
2045 else if (tok == TOK_CLLONG)
2046 tok = TOK_CULLONG;
2047 ch = *p++;
2048 } else {
2049 break;
2052 if (tok == TOK_CINT || tok == TOK_CUINT)
2053 tokc.ui = n;
2054 else
2055 tokc.ull = n;
2057 if (ch)
2058 tcc_error("invalid number\n");
2062 #define PARSE2(c1, tok1, c2, tok2) \
2063 case c1: \
2064 PEEKC(c, p); \
2065 if (c == c2) { \
2066 p++; \
2067 tok = tok2; \
2068 } else { \
2069 tok = tok1; \
2071 break;
2073 /* return next token without macro substitution */
2074 static inline void next_nomacro1(void)
2076 int t, c, is_long;
2077 TokenSym *ts;
2078 uint8_t *p, *p1;
2079 unsigned int h;
2081 p = file->buf_ptr;
2082 redo_no_start:
2083 c = *p;
2084 switch(c) {
2085 case ' ':
2086 case '\t':
2087 tok = c;
2088 p++;
2089 goto keep_tok_flags;
2090 case '\f':
2091 case '\v':
2092 case '\r':
2093 p++;
2094 goto redo_no_start;
2095 case '\\':
2096 /* first look if it is in fact an end of buffer */
2097 if (p >= file->buf_end) {
2098 file->buf_ptr = p;
2099 handle_eob();
2100 p = file->buf_ptr;
2101 if (p >= file->buf_end)
2102 goto parse_eof;
2103 else
2104 goto redo_no_start;
2105 } else {
2106 file->buf_ptr = p;
2107 ch = *p;
2108 handle_stray();
2109 p = file->buf_ptr;
2110 goto redo_no_start;
2112 parse_eof:
2114 TCCState *s1 = tcc_state;
2115 if ((parse_flags & PARSE_FLAG_LINEFEED)
2116 && !(tok_flags & TOK_FLAG_EOF)) {
2117 tok_flags |= TOK_FLAG_EOF;
2118 tok = TOK_LINEFEED;
2119 goto keep_tok_flags;
2120 } else if (!(parse_flags & PARSE_FLAG_PREPROCESS)) {
2121 tok = TOK_EOF;
2122 } else if (s1->ifdef_stack_ptr != file->ifdef_stack_ptr) {
2123 tcc_error("missing #endif");
2124 } else if (s1->include_stack_ptr == s1->include_stack) {
2125 /* no include left : end of file. */
2126 tok = TOK_EOF;
2127 } else {
2128 tok_flags &= ~TOK_FLAG_EOF;
2129 /* pop include file */
2131 /* test if previous '#endif' was after a #ifdef at
2132 start of file */
2133 if (tok_flags & TOK_FLAG_ENDIF) {
2134 #ifdef INC_DEBUG
2135 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
2136 #endif
2137 add_cached_include(s1, file->filename, file->ifndef_macro_saved);
2138 tok_flags &= ~TOK_FLAG_ENDIF;
2141 /* add end of include file debug info */
2142 if (tcc_state->do_debug) {
2143 put_stabd(N_EINCL, 0, 0);
2145 /* pop include stack */
2146 tcc_close();
2147 s1->include_stack_ptr--;
2148 p = file->buf_ptr;
2149 goto redo_no_start;
2152 break;
2154 case '\n':
2155 file->line_num++;
2156 tok_flags |= TOK_FLAG_BOL;
2157 p++;
2158 maybe_newline:
2159 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
2160 goto redo_no_start;
2161 tok = TOK_LINEFEED;
2162 goto keep_tok_flags;
2164 case '#':
2165 /* XXX: simplify */
2166 PEEKC(c, p);
2167 if ((tok_flags & TOK_FLAG_BOL) &&
2168 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2169 file->buf_ptr = p;
2170 preprocess(tok_flags & TOK_FLAG_BOF);
2171 p = file->buf_ptr;
2172 goto maybe_newline;
2173 } else {
2174 if (c == '#') {
2175 p++;
2176 tok = TOK_TWOSHARPS;
2177 } else {
2178 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
2179 p = parse_line_comment(p - 1);
2180 goto redo_no_start;
2181 } else {
2182 tok = '#';
2186 break;
2188 case 'a': case 'b': case 'c': case 'd':
2189 case 'e': case 'f': case 'g': case 'h':
2190 case 'i': case 'j': case 'k': case 'l':
2191 case 'm': case 'n': case 'o': case 'p':
2192 case 'q': case 'r': case 's': case 't':
2193 case 'u': case 'v': case 'w': case 'x':
2194 case 'y': case 'z':
2195 case 'A': case 'B': case 'C': case 'D':
2196 case 'E': case 'F': case 'G': case 'H':
2197 case 'I': case 'J': case 'K':
2198 case 'M': case 'N': case 'O': case 'P':
2199 case 'Q': case 'R': case 'S': case 'T':
2200 case 'U': case 'V': case 'W': case 'X':
2201 case 'Y': case 'Z':
2202 case '_':
2203 parse_ident_fast:
2204 p1 = p;
2205 h = TOK_HASH_INIT;
2206 h = TOK_HASH_FUNC(h, c);
2207 p++;
2208 for(;;) {
2209 c = *p;
2210 if (!isidnum_table[c-CH_EOF])
2211 break;
2212 h = TOK_HASH_FUNC(h, c);
2213 p++;
2215 if (c != '\\') {
2216 TokenSym **pts;
2217 int len;
2219 /* fast case : no stray found, so we have the full token
2220 and we have already hashed it */
2221 len = p - p1;
2222 h &= (TOK_HASH_SIZE - 1);
2223 pts = &hash_ident[h];
2224 for(;;) {
2225 ts = *pts;
2226 if (!ts)
2227 break;
2228 if (ts->len == len && !memcmp(ts->str, p1, len))
2229 goto token_found;
2230 pts = &(ts->hash_next);
2232 ts = tok_alloc_new(pts, p1, len);
2233 token_found: ;
2234 } else {
2235 /* slower case */
2236 cstr_reset(&tokcstr);
2238 while (p1 < p) {
2239 cstr_ccat(&tokcstr, *p1);
2240 p1++;
2242 p--;
2243 PEEKC(c, p);
2244 parse_ident_slow:
2245 while (isidnum_table[c-CH_EOF]) {
2246 cstr_ccat(&tokcstr, c);
2247 PEEKC(c, p);
2249 ts = tok_alloc(tokcstr.data, tokcstr.size);
2251 tok = ts->tok;
2252 break;
2253 case 'L':
2254 t = p[1];
2255 if (t != '\\' && t != '\'' && t != '\"') {
2256 /* fast case */
2257 goto parse_ident_fast;
2258 } else {
2259 PEEKC(c, p);
2260 if (c == '\'' || c == '\"') {
2261 is_long = 1;
2262 goto str_const;
2263 } else {
2264 cstr_reset(&tokcstr);
2265 cstr_ccat(&tokcstr, 'L');
2266 goto parse_ident_slow;
2269 break;
2270 case '0': case '1': case '2': case '3':
2271 case '4': case '5': case '6': case '7':
2272 case '8': case '9':
2274 cstr_reset(&tokcstr);
2275 /* after the first digit, accept digits, alpha, '.' or sign if
2276 prefixed by 'eEpP' */
2277 parse_num:
2278 for(;;) {
2279 t = c;
2280 cstr_ccat(&tokcstr, c);
2281 PEEKC(c, p);
2282 if (!(isnum(c) || isid(c) || c == '.' ||
2283 ((c == '+' || c == '-') &&
2284 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
2285 break;
2287 /* We add a trailing '\0' to ease parsing */
2288 cstr_ccat(&tokcstr, '\0');
2289 tokc.cstr = &tokcstr;
2290 tok = TOK_PPNUM;
2291 break;
2292 case '.':
2293 /* special dot handling because it can also start a number */
2294 PEEKC(c, p);
2295 if (isnum(c)) {
2296 cstr_reset(&tokcstr);
2297 cstr_ccat(&tokcstr, '.');
2298 goto parse_num;
2299 } else if (c == '.') {
2300 PEEKC(c, p);
2301 if (c != '.')
2302 expect("'.'");
2303 PEEKC(c, p);
2304 tok = TOK_DOTS;
2305 } else {
2306 tok = '.';
2308 break;
2309 case '\'':
2310 case '\"':
2311 is_long = 0;
2312 str_const:
2314 CString str;
2315 int sep;
2317 sep = c;
2319 /* parse the string */
2320 cstr_new(&str);
2321 p = parse_pp_string(p, sep, &str);
2322 cstr_ccat(&str, '\0');
2324 /* eval the escape (should be done as TOK_PPNUM) */
2325 cstr_reset(&tokcstr);
2326 parse_escape_string(&tokcstr, str.data, is_long);
2327 cstr_free(&str);
2329 if (sep == '\'') {
2330 int char_size;
2331 /* XXX: make it portable */
2332 if (!is_long)
2333 char_size = 1;
2334 else
2335 char_size = sizeof(nwchar_t);
2336 if (tokcstr.size <= char_size)
2337 tcc_error("empty character constant");
2338 if (tokcstr.size > 2 * char_size)
2339 tcc_warning("multi-character character constant");
2340 if (!is_long) {
2341 tokc.i = *(int8_t *)tokcstr.data;
2342 tok = TOK_CCHAR;
2343 } else {
2344 tokc.i = *(nwchar_t *)tokcstr.data;
2345 tok = TOK_LCHAR;
2347 } else {
2348 tokc.cstr = &tokcstr;
2349 if (!is_long)
2350 tok = TOK_STR;
2351 else
2352 tok = TOK_LSTR;
2355 break;
2357 case '<':
2358 PEEKC(c, p);
2359 if (c == '=') {
2360 p++;
2361 tok = TOK_LE;
2362 } else if (c == '<') {
2363 PEEKC(c, p);
2364 if (c == '=') {
2365 p++;
2366 tok = TOK_A_SHL;
2367 } else {
2368 tok = TOK_SHL;
2370 } else {
2371 tok = TOK_LT;
2373 break;
2375 case '>':
2376 PEEKC(c, p);
2377 if (c == '=') {
2378 p++;
2379 tok = TOK_GE;
2380 } else if (c == '>') {
2381 PEEKC(c, p);
2382 if (c == '=') {
2383 p++;
2384 tok = TOK_A_SAR;
2385 } else {
2386 tok = TOK_SAR;
2388 } else {
2389 tok = TOK_GT;
2391 break;
2393 case '&':
2394 PEEKC(c, p);
2395 if (c == '&') {
2396 p++;
2397 tok = TOK_LAND;
2398 } else if (c == '=') {
2399 p++;
2400 tok = TOK_A_AND;
2401 } else {
2402 tok = '&';
2404 break;
2406 case '|':
2407 PEEKC(c, p);
2408 if (c == '|') {
2409 p++;
2410 tok = TOK_LOR;
2411 } else if (c == '=') {
2412 p++;
2413 tok = TOK_A_OR;
2414 } else {
2415 tok = '|';
2417 break;
2419 case '+':
2420 PEEKC(c, p);
2421 if (c == '+') {
2422 p++;
2423 tok = TOK_INC;
2424 } else if (c == '=') {
2425 p++;
2426 tok = TOK_A_ADD;
2427 } else {
2428 tok = '+';
2430 break;
2432 case '-':
2433 PEEKC(c, p);
2434 if (c == '-') {
2435 p++;
2436 tok = TOK_DEC;
2437 } else if (c == '=') {
2438 p++;
2439 tok = TOK_A_SUB;
2440 } else if (c == '>') {
2441 p++;
2442 tok = TOK_ARROW;
2443 } else {
2444 tok = '-';
2446 break;
2448 PARSE2('!', '!', '=', TOK_NE)
2449 PARSE2('=', '=', '=', TOK_EQ)
2450 PARSE2('*', '*', '=', TOK_A_MUL)
2451 PARSE2('%', '%', '=', TOK_A_MOD)
2452 PARSE2('^', '^', '=', TOK_A_XOR)
2454 /* comments or operator */
2455 case '/':
2456 PEEKC(c, p);
2457 if (c == '*') {
2458 p = parse_comment(p);
2459 /* comments replaced by a blank */
2460 tok = ' ';
2461 goto keep_tok_flags;
2462 } else if (c == '/') {
2463 p = parse_line_comment(p);
2464 tok = ' ';
2465 goto keep_tok_flags;
2466 } else if (c == '=') {
2467 p++;
2468 tok = TOK_A_DIV;
2469 } else {
2470 tok = '/';
2472 break;
2474 /* simple tokens */
2475 case '(':
2476 case ')':
2477 case '[':
2478 case ']':
2479 case '{':
2480 case '}':
2481 case ',':
2482 case ';':
2483 case ':':
2484 case '?':
2485 case '~':
2486 case '$': /* only used in assembler */
2487 case '@': /* dito */
2488 tok = c;
2489 p++;
2490 break;
2491 default:
2492 tcc_error("unrecognized character \\x%02x", c);
2493 break;
2495 tok_flags = 0;
2496 keep_tok_flags:
2497 file->buf_ptr = p;
2498 #if defined(PARSE_DEBUG)
2499 printf("token = %s\n", get_tok_str(tok, &tokc));
2500 #endif
2503 /* return next token without macro substitution. Can read input from
2504 macro_ptr buffer */
2505 static void next_nomacro_spc(void)
2507 if (macro_ptr) {
2508 redo:
2509 tok = *macro_ptr;
2510 if (tok) {
2511 TOK_GET(&tok, &macro_ptr, &tokc);
2512 if (tok == TOK_LINENUM) {
2513 file->line_num = tokc.i;
2514 goto redo;
2517 } else {
2518 next_nomacro1();
2522 ST_FUNC void next_nomacro(void)
2524 do {
2525 next_nomacro_spc();
2526 } while (is_space(tok));
2529 /* substitute args in macro_str and return allocated string */
2530 static int *macro_arg_subst(Sym **nested_list, const int *macro_str, Sym *args)
2532 int last_tok, t, spc;
2533 const int *st;
2534 Sym *s;
2535 CValue cval;
2536 TokenString str;
2537 CString cstr;
2539 tok_str_new(&str);
2540 last_tok = 0;
2541 while(1) {
2542 TOK_GET(&t, &macro_str, &cval);
2543 if (!t)
2544 break;
2545 if (t == '#') {
2546 /* stringize */
2547 TOK_GET(&t, &macro_str, &cval);
2548 if (!t)
2549 break;
2550 s = sym_find2(args, t);
2551 if (s) {
2552 cstr_new(&cstr);
2553 st = s->d;
2554 spc = 0;
2555 while (*st) {
2556 TOK_GET(&t, &st, &cval);
2557 if (!check_space(t, &spc))
2558 cstr_cat(&cstr, get_tok_str(t, &cval));
2560 cstr.size -= spc;
2561 cstr_ccat(&cstr, '\0');
2562 #ifdef PP_DEBUG
2563 printf("stringize: %s\n", (char *)cstr.data);
2564 #endif
2565 /* add string */
2566 cval.cstr = &cstr;
2567 tok_str_add2(&str, TOK_STR, &cval);
2568 cstr_free(&cstr);
2569 } else {
2570 tok_str_add2(&str, t, &cval);
2572 } else if (t >= TOK_IDENT) {
2573 s = sym_find2(args, t);
2574 if (s) {
2575 st = s->d;
2576 /* if '##' is present before or after, no arg substitution */
2577 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
2578 /* special case for var arg macros : ## eats the
2579 ',' if empty VA_ARGS variable. */
2580 /* XXX: test of the ',' is not 100%
2581 reliable. should fix it to avoid security
2582 problems */
2583 if (gnu_ext && s->type.t &&
2584 last_tok == TOK_TWOSHARPS &&
2585 str.len >= 2 && str.str[str.len - 2] == ',') {
2586 if (*st == 0) {
2587 /* suppress ',' '##' */
2588 str.len -= 2;
2589 } else {
2590 /* suppress '##' and add variable */
2591 str.len--;
2592 goto add_var;
2594 } else {
2595 int t1;
2596 add_var:
2597 for(;;) {
2598 TOK_GET(&t1, &st, &cval);
2599 if (!t1)
2600 break;
2601 tok_str_add2(&str, t1, &cval);
2604 } else {
2605 /* NOTE: the stream cannot be read when macro
2606 substituing an argument */
2607 macro_subst(&str, nested_list, st, NULL);
2609 } else {
2610 tok_str_add(&str, t);
2612 } else {
2613 tok_str_add2(&str, t, &cval);
2615 last_tok = t;
2617 tok_str_add(&str, 0);
2618 return str.str;
2621 static char const ab_month_name[12][4] =
2623 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2624 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2627 /* do macro substitution of current token with macro 's' and add
2628 result to (tok_str,tok_len). 'nested_list' is the list of all
2629 macros we got inside to avoid recursing. Return non zero if no
2630 substitution needs to be done */
2631 static int macro_subst_tok(TokenString *tok_str,
2632 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
2634 Sym *args, *sa, *sa1;
2635 int mstr_allocated, parlevel, *mstr, t, t1, spc;
2636 const int *p;
2637 TokenString str;
2638 char *cstrval;
2639 CValue cval;
2640 CString cstr;
2641 char buf[32];
2643 /* if symbol is a macro, prepare substitution */
2644 /* special macros */
2645 if (tok == TOK___LINE__) {
2646 snprintf(buf, sizeof(buf), "%d", file->line_num);
2647 cstrval = buf;
2648 t1 = TOK_PPNUM;
2649 goto add_cstr1;
2650 } else if (tok == TOK___FILE__) {
2651 cstrval = file->filename;
2652 goto add_cstr;
2653 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
2654 time_t ti;
2655 struct tm *tm;
2657 time(&ti);
2658 tm = localtime(&ti);
2659 if (tok == TOK___DATE__) {
2660 snprintf(buf, sizeof(buf), "%s %2d %d",
2661 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
2662 } else {
2663 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
2664 tm->tm_hour, tm->tm_min, tm->tm_sec);
2666 cstrval = buf;
2667 add_cstr:
2668 t1 = TOK_STR;
2669 add_cstr1:
2670 cstr_new(&cstr);
2671 cstr_cat(&cstr, cstrval);
2672 cstr_ccat(&cstr, '\0');
2673 cval.cstr = &cstr;
2674 tok_str_add2(tok_str, t1, &cval);
2675 cstr_free(&cstr);
2676 } else {
2677 mstr = s->d;
2678 mstr_allocated = 0;
2679 if (s->type.t == MACRO_FUNC) {
2680 /* NOTE: we do not use next_nomacro to avoid eating the
2681 next token. XXX: find better solution */
2682 redo:
2683 if (macro_ptr) {
2684 p = macro_ptr;
2685 while (is_space(t = *p) || TOK_LINEFEED == t)
2686 ++p;
2687 if (t == 0 && can_read_stream) {
2688 /* end of macro stream: we must look at the token
2689 after in the file */
2690 struct macro_level *ml = *can_read_stream;
2691 macro_ptr = NULL;
2692 if (ml)
2694 macro_ptr = ml->p;
2695 ml->p = NULL;
2696 *can_read_stream = ml -> prev;
2698 /* also, end of scope for nested defined symbol */
2699 (*nested_list)->v = -1;
2700 goto redo;
2702 } else {
2703 ch = file->buf_ptr[0];
2704 while (is_space(ch) || ch == '\n' || ch == '/')
2706 if (ch == '/')
2708 int c;
2709 uint8_t *p = file->buf_ptr;
2710 PEEKC(c, p);
2711 if (c == '*') {
2712 p = parse_comment(p);
2713 file->buf_ptr = p - 1;
2714 } else if (c == '/') {
2715 p = parse_line_comment(p);
2716 file->buf_ptr = p - 1;
2717 } else
2718 break;
2720 cinp();
2722 t = ch;
2724 if (t != '(') /* no macro subst */
2725 return -1;
2727 /* argument macro */
2728 next_nomacro();
2729 next_nomacro();
2730 args = NULL;
2731 sa = s->next;
2732 /* NOTE: empty args are allowed, except if no args */
2733 for(;;) {
2734 /* handle '()' case */
2735 if (!args && !sa && tok == ')')
2736 break;
2737 if (!sa)
2738 tcc_error("macro '%s' used with too many args",
2739 get_tok_str(s->v, 0));
2740 tok_str_new(&str);
2741 parlevel = spc = 0;
2742 /* NOTE: non zero sa->t indicates VA_ARGS */
2743 while ((parlevel > 0 ||
2744 (tok != ')' &&
2745 (tok != ',' || sa->type.t))) &&
2746 tok != -1) {
2747 if (tok == '(')
2748 parlevel++;
2749 else if (tok == ')')
2750 parlevel--;
2751 if (tok == TOK_LINEFEED)
2752 tok = ' ';
2753 if (!check_space(tok, &spc))
2754 tok_str_add2(&str, tok, &tokc);
2755 next_nomacro_spc();
2757 str.len -= spc;
2758 tok_str_add(&str, 0);
2759 sa1 = sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, 0);
2760 sa1->d = str.str;
2761 sa = sa->next;
2762 if (tok == ')') {
2763 /* special case for gcc var args: add an empty
2764 var arg argument if it is omitted */
2765 if (sa && sa->type.t && gnu_ext)
2766 continue;
2767 else
2768 break;
2770 if (tok != ',')
2771 expect(",");
2772 next_nomacro();
2774 if (sa) {
2775 tcc_error("macro '%s' used with too few args",
2776 get_tok_str(s->v, 0));
2779 /* now subst each arg */
2780 mstr = macro_arg_subst(nested_list, mstr, args);
2781 /* free memory */
2782 sa = args;
2783 while (sa) {
2784 sa1 = sa->prev;
2785 tok_str_free(sa->d);
2786 sym_free(sa);
2787 sa = sa1;
2789 mstr_allocated = 1;
2791 sym_push2(nested_list, s->v, 0, 0);
2792 macro_subst(tok_str, nested_list, mstr, can_read_stream);
2793 /* pop nested defined symbol */
2794 sa1 = *nested_list;
2795 *nested_list = sa1->prev;
2796 sym_free(sa1);
2797 if (mstr_allocated)
2798 tok_str_free(mstr);
2800 return 0;
2803 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2804 return the resulting string (which must be freed). */
2805 static inline int *macro_twosharps(const int *macro_str)
2807 const int *ptr;
2808 int t;
2809 CValue cval;
2810 TokenString macro_str1;
2811 CString cstr;
2812 int n, start_of_nosubsts;
2814 /* we search the first '##' */
2815 for(ptr = macro_str;;) {
2816 TOK_GET(&t, &ptr, &cval);
2817 if (t == TOK_TWOSHARPS)
2818 break;
2819 /* nothing more to do if end of string */
2820 if (t == 0)
2821 return NULL;
2824 /* we saw '##', so we need more processing to handle it */
2825 start_of_nosubsts = -1;
2826 tok_str_new(&macro_str1);
2827 for(ptr = macro_str;;) {
2828 TOK_GET(&tok, &ptr, &tokc);
2829 if (tok == 0)
2830 break;
2831 if (tok == TOK_TWOSHARPS)
2832 continue;
2833 if (tok == TOK_NOSUBST && start_of_nosubsts < 0)
2834 start_of_nosubsts = macro_str1.len;
2835 while (*ptr == TOK_TWOSHARPS) {
2836 /* given 'a##b', remove nosubsts preceding 'a' */
2837 if (start_of_nosubsts >= 0)
2838 macro_str1.len = start_of_nosubsts;
2839 /* given 'a##b', skip '##' */
2840 t = *++ptr;
2841 /* given 'a##b', remove nosubsts preceding 'b' */
2842 while (t == TOK_NOSUBST)
2843 t = *++ptr;
2845 if (t && t != TOK_TWOSHARPS) {
2846 TOK_GET(&t, &ptr, &cval);
2848 /* We concatenate the two tokens */
2849 cstr_new(&cstr);
2850 cstr_cat(&cstr, get_tok_str(tok, &tokc));
2851 n = cstr.size;
2852 cstr_cat(&cstr, get_tok_str(t, &cval));
2853 cstr_ccat(&cstr, '\0');
2855 tcc_open_bf(tcc_state, "<paste>", cstr.size);
2856 memcpy(file->buffer, cstr.data, cstr.size);
2857 for (;;) {
2858 next_nomacro1();
2859 if (0 == *file->buf_ptr)
2860 break;
2861 tok_str_add2(&macro_str1, tok, &tokc);
2862 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2863 n, cstr.data, (char*)cstr.data + n);
2865 tcc_close();
2866 cstr_free(&cstr);
2869 if (tok != TOK_NOSUBST)
2870 start_of_nosubsts = -1;
2871 tok_str_add2(&macro_str1, tok, &tokc);
2873 tok_str_add(&macro_str1, 0);
2874 return macro_str1.str;
2878 /* do macro substitution of macro_str and add result to
2879 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2880 inside to avoid recursing. */
2881 static void macro_subst(TokenString *tok_str, Sym **nested_list,
2882 const int *macro_str, struct macro_level ** can_read_stream)
2884 Sym *s;
2885 int *macro_str1;
2886 const int *ptr;
2887 int t, ret, spc;
2888 CValue cval;
2889 struct macro_level ml;
2890 int force_blank;
2892 /* first scan for '##' operator handling */
2893 ptr = macro_str;
2894 macro_str1 = macro_twosharps(ptr);
2896 if (macro_str1)
2897 ptr = macro_str1;
2898 spc = 0;
2899 force_blank = 0;
2901 while (1) {
2902 /* NOTE: ptr == NULL can only happen if tokens are read from
2903 file stream due to a macro function call */
2904 if (ptr == NULL)
2905 break;
2906 TOK_GET(&t, &ptr, &cval);
2907 if (t == 0)
2908 break;
2909 if (t == TOK_NOSUBST) {
2910 /* following token has already been subst'd. just copy it on */
2911 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
2912 TOK_GET(&t, &ptr, &cval);
2913 goto no_subst;
2915 s = define_find(t);
2916 if (s != NULL) {
2917 /* if nested substitution, do nothing */
2918 if (sym_find2(*nested_list, t)) {
2919 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
2920 tok_str_add2(tok_str, TOK_NOSUBST, NULL);
2921 goto no_subst;
2923 ml.p = macro_ptr;
2924 if (can_read_stream)
2925 ml.prev = *can_read_stream, *can_read_stream = &ml;
2926 macro_ptr = (int *)ptr;
2927 tok = t;
2928 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
2929 ptr = (int *)macro_ptr;
2930 macro_ptr = ml.p;
2931 if (can_read_stream && *can_read_stream == &ml)
2932 *can_read_stream = ml.prev;
2933 if (ret != 0)
2934 goto no_subst;
2935 if (parse_flags & PARSE_FLAG_SPACES)
2936 force_blank = 1;
2937 } else {
2938 no_subst:
2939 if (force_blank) {
2940 tok_str_add(tok_str, ' ');
2941 spc = 1;
2942 force_blank = 0;
2944 if (!check_space(t, &spc))
2945 tok_str_add2(tok_str, t, &cval);
2948 if (macro_str1)
2949 tok_str_free(macro_str1);
2952 /* return next token with macro substitution */
2953 ST_FUNC void next(void)
2955 Sym *nested_list, *s;
2956 TokenString str;
2957 struct macro_level *ml;
2959 redo:
2960 if (parse_flags & PARSE_FLAG_SPACES)
2961 next_nomacro_spc();
2962 else
2963 next_nomacro();
2964 if (!macro_ptr) {
2965 /* if not reading from macro substituted string, then try
2966 to substitute macros */
2967 if (tok >= TOK_IDENT &&
2968 (parse_flags & PARSE_FLAG_PREPROCESS)) {
2969 s = define_find(tok);
2970 if (s) {
2971 /* we have a macro: we try to substitute */
2972 tok_str_new(&str);
2973 nested_list = NULL;
2974 ml = NULL;
2975 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
2976 /* substitution done, NOTE: maybe empty */
2977 tok_str_add(&str, 0);
2978 macro_ptr = str.str;
2979 macro_ptr_allocated = str.str;
2980 goto redo;
2984 } else {
2985 if (tok == 0) {
2986 /* end of macro or end of unget buffer */
2987 if (unget_buffer_enabled) {
2988 macro_ptr = unget_saved_macro_ptr;
2989 unget_buffer_enabled = 0;
2990 } else {
2991 /* end of macro string: free it */
2992 tok_str_free(macro_ptr_allocated);
2993 macro_ptr_allocated = NULL;
2994 macro_ptr = NULL;
2996 goto redo;
2997 } else if (tok == TOK_NOSUBST) {
2998 /* discard preprocessor's nosubst markers */
2999 goto redo;
3003 /* convert preprocessor tokens into C tokens */
3004 if (tok == TOK_PPNUM &&
3005 (parse_flags & PARSE_FLAG_TOK_NUM)) {
3006 parse_number((char *)tokc.cstr->data);
3010 /* push back current token and set current token to 'last_tok'. Only
3011 identifier case handled for labels. */
3012 ST_INLN void unget_tok(int last_tok)
3014 int i, n;
3015 int *q;
3016 if (unget_buffer_enabled)
3018 /* assert(macro_ptr == unget_saved_buffer + 1);
3019 assert(*macro_ptr == 0); */
3021 else
3023 unget_saved_macro_ptr = macro_ptr;
3024 unget_buffer_enabled = 1;
3026 q = unget_saved_buffer;
3027 macro_ptr = q;
3028 *q++ = tok;
3029 n = tok_ext_size(tok) - 1;
3030 for(i=0;i<n;i++)
3031 *q++ = tokc.tab[i];
3032 *q = 0; /* end of token string */
3033 tok = last_tok;
3037 /* better than nothing, but needs extension to handle '-E' option
3038 correctly too */
3039 ST_FUNC void preprocess_init(TCCState *s1)
3041 s1->include_stack_ptr = s1->include_stack;
3042 /* XXX: move that before to avoid having to initialize
3043 file->ifdef_stack_ptr ? */
3044 s1->ifdef_stack_ptr = s1->ifdef_stack;
3045 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
3047 vtop = vstack - 1;
3048 s1->pack_stack[0] = 0;
3049 s1->pack_stack_ptr = s1->pack_stack;
3052 ST_FUNC void preprocess_new()
3054 int i, c;
3055 const char *p, *r;
3057 /* init isid table */
3058 for(i=CH_EOF;i<256;i++)
3059 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
3061 /* add all tokens */
3062 table_ident = NULL;
3063 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
3065 tok_ident = TOK_IDENT;
3066 p = tcc_keywords;
3067 while (*p) {
3068 r = p;
3069 for(;;) {
3070 c = *r++;
3071 if (c == '\0')
3072 break;
3074 tok_alloc(p, r - p - 1);
3075 p = r;
3079 /* Preprocess the current file */
3080 ST_FUNC int tcc_preprocess(TCCState *s1)
3082 Sym *define_start;
3084 BufferedFile *file_ref, **iptr, **iptr_new;
3085 int token_seen, line_ref, d;
3086 const char *s;
3088 preprocess_init(s1);
3089 define_start = define_stack;
3090 ch = file->buf_ptr[0];
3091 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
3092 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
3093 PARSE_FLAG_LINEFEED | PARSE_FLAG_SPACES;
3094 token_seen = 0;
3095 line_ref = 0;
3096 file_ref = NULL;
3097 iptr = s1->include_stack_ptr;
3099 for (;;) {
3100 next();
3101 if (tok == TOK_EOF) {
3102 break;
3103 } else if (file != file_ref) {
3104 goto print_line;
3105 } else if (tok == TOK_LINEFEED) {
3106 if (!token_seen)
3107 continue;
3108 ++line_ref;
3109 token_seen = 0;
3110 } else if (!token_seen) {
3111 d = file->line_num - line_ref;
3112 if (file != file_ref || d < 0 || d >= 8) {
3113 print_line:
3114 iptr_new = s1->include_stack_ptr;
3115 s = iptr_new > iptr ? " 1"
3116 : iptr_new < iptr ? " 2"
3117 : iptr_new > s1->include_stack ? " 3"
3118 : ""
3120 iptr = iptr_new;
3121 fprintf(s1->outfile, "# %d \"%s\"%s\n", file->line_num, file->filename, s);
3122 } else {
3123 while (d)
3124 fputs("\n", s1->outfile), --d;
3126 line_ref = (file_ref = file)->line_num;
3127 token_seen = tok != TOK_LINEFEED;
3128 if (!token_seen)
3129 continue;
3131 fputs(get_tok_str(tok, &tokc), s1->outfile);
3133 free_defines(define_start);
3134 return 0;