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