2 * TCC - Tiny C Compiler
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
24 /* #define to 1 to enable (see parse_pp_string()) */
25 #define ACCEPT_LF_IN_STRINGS 0
27 /********************************************************/
28 /* global variables */
30 ST_DATA
int tok_flags
;
31 ST_DATA
int parse_flags
;
33 ST_DATA
struct BufferedFile
*file
;
36 ST_DATA
const int *macro_ptr
;
37 ST_DATA CString tokcstr
; /* current parsed string, if any */
39 /* display benchmark infos */
40 ST_DATA
int tok_ident
;
41 ST_DATA TokenSym
**table_ident
;
43 /* ------------------------------------------------------------------------- */
45 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
46 static char token_buf
[STRING_MAX_SIZE
+ 1];
47 static CString cstr_buf
;
48 static TokenString tokstr_buf
;
49 static unsigned char isidnum_table
[256 - CH_EOF
];
50 static int pp_debug_tok
, pp_debug_symv
;
53 static int pp_counter
;
54 static void tok_print(const char *msg
, const int *str
);
56 static struct TinyAlloc
*toksym_alloc
;
57 static struct TinyAlloc
*tokstr_alloc
;
59 static TokenString
*macro_stack
;
61 static const char tcc_keywords
[] =
62 #define DEF(id, str) str "\0"
67 /* WARNING: the content of this string encodes token numbers */
68 static const unsigned char tok_two_chars
[] =
70 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
71 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
93 '#','#', TOK_TWOSHARPS
,
98 static void next_nomacro(void);
100 ST_FUNC
void skip(int c
)
103 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
107 ST_FUNC
void expect(const char *msg
)
109 tcc_error("%s expected", msg
);
112 /* ------------------------------------------------------------------------- */
113 /* Custom allocator for tiny objects */
118 #define tal_free(al, p) tcc_free(p)
119 #define tal_realloc(al, p, size) tcc_realloc(p, size)
120 #define tal_new(a,b,c)
121 #define tal_delete(a)
123 #if !defined(MEM_DEBUG)
124 #define tal_free(al, p) tal_free_impl(al, p)
125 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
126 #define TAL_DEBUG_PARAMS
129 //#define TAL_INFO 1 /* collect and dump allocators stats */
130 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
131 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
132 #define TAL_DEBUG_PARAMS , const char *file, int line
133 #define TAL_DEBUG_FILE_LEN 40
136 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
137 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
138 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
139 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
140 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
141 #define CSTR_TAL_LIMIT 1024
143 typedef struct TinyAlloc
{
149 struct TinyAlloc
*next
, *top
;
158 typedef struct tal_header_t
{
161 int line_num
; /* negative line_num used for double free check */
162 char file_name
[TAL_DEBUG_FILE_LEN
+ 1];
166 /* ------------------------------------------------------------------------- */
168 static TinyAlloc
*tal_new(TinyAlloc
**pal
, unsigned limit
, unsigned size
)
170 TinyAlloc
*al
= tcc_mallocz(sizeof(TinyAlloc
));
171 al
->p
= al
->buffer
= tcc_malloc(size
);
178 static void tal_delete(TinyAlloc
*al
)
186 fprintf(stderr
, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
187 al
->limit
, al
->size
/ 1024.0 / 1024.0, al
->nb_peak
, al
->nb_total
, al
->nb_missed
,
188 (al
->peak_p
- al
->buffer
) * 100.0 / al
->size
);
191 if (al
->nb_allocs
> 0) {
193 fprintf(stderr
, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
194 al
->nb_allocs
, al
->limit
);
197 tal_header_t
*header
= (tal_header_t
*)p
;
198 if (header
->line_num
> 0) {
199 fprintf(stderr
, "%s:%d: chunk of %d bytes leaked\n",
200 header
->file_name
, header
->line_num
, header
->size
);
202 p
+= header
->size
+ sizeof(tal_header_t
);
210 tcc_free(al
->buffer
);
216 static void tal_free_impl(TinyAlloc
*al
, void *p TAL_DEBUG_PARAMS
)
221 if (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
) {
223 tal_header_t
*header
= (((tal_header_t
*)p
) - 1);
224 if (header
->line_num
< 0) {
225 fprintf(stderr
, "%s:%d: TAL_DEBUG: double frees chunk from\n",
227 fprintf(stderr
, "%s:%d: %d bytes\n",
228 header
->file_name
, (int)-header
->line_num
, (int)header
->size
);
230 header
->line_num
= -header
->line_num
;
235 } else if (al
->next
) {
243 static void *tal_realloc_impl(TinyAlloc
**pal
, void *p
, unsigned size TAL_DEBUG_PARAMS
)
245 tal_header_t
*header
;
248 unsigned adj_size
= (size
+ 3) & -4;
249 TinyAlloc
*al
= *pal
;
252 is_own
= (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
);
253 if ((!p
|| is_own
) && size
<= al
->limit
) {
254 if (al
->p
- al
->buffer
+ adj_size
+ sizeof(tal_header_t
) < al
->size
) {
255 header
= (tal_header_t
*)al
->p
;
256 header
->size
= adj_size
;
258 { int ofs
= strlen(file
) - TAL_DEBUG_FILE_LEN
;
259 strncpy(header
->file_name
, file
+ (ofs
> 0 ? ofs
: 0), TAL_DEBUG_FILE_LEN
);
260 header
->file_name
[TAL_DEBUG_FILE_LEN
] = 0;
261 header
->line_num
= line
; }
263 ret
= al
->p
+ sizeof(tal_header_t
);
264 al
->p
+= adj_size
+ sizeof(tal_header_t
);
266 header
= (((tal_header_t
*)p
) - 1);
267 if (p
) memcpy(ret
, p
, header
->size
);
269 header
->line_num
= -header
->line_num
;
275 if (al
->nb_peak
< al
->nb_allocs
)
276 al
->nb_peak
= al
->nb_allocs
;
277 if (al
->peak_p
< al
->p
)
284 ret
= tal_realloc(*pal
, 0, size
);
285 header
= (((tal_header_t
*)p
) - 1);
286 if (p
) memcpy(ret
, p
, header
->size
);
288 header
->line_num
= -header
->line_num
;
295 TinyAlloc
*bottom
= al
, *next
= al
->top
? al
->top
: al
;
297 al
= tal_new(pal
, next
->limit
, next
->size
* 2);
305 ret
= tcc_malloc(size
);
306 header
= (((tal_header_t
*)p
) - 1);
307 if (p
) memcpy(ret
, p
, header
->size
);
309 header
->line_num
= -header
->line_num
;
311 } else if (al
->next
) {
315 ret
= tcc_realloc(p
, size
);
324 /* ------------------------------------------------------------------------- */
325 /* CString handling */
326 static void cstr_realloc(CString
*cstr
, int new_size
)
330 size
= cstr
->size_allocated
;
332 size
= 8; /* no need to allocate a too small first string */
333 while (size
< new_size
)
335 cstr
->data
= tcc_realloc(cstr
->data
, size
);
336 cstr
->size_allocated
= size
;
340 ST_INLN
void cstr_ccat(CString
*cstr
, int ch
)
343 size
= cstr
->size
+ 1;
344 if (size
> cstr
->size_allocated
)
345 cstr_realloc(cstr
, size
);
346 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
350 ST_INLN
char *unicode_to_utf8 (char *b
, uint32_t Uc
)
352 if (Uc
<0x80) *b
++=Uc
;
353 else if (Uc
<0x800) *b
++=192+Uc
/64, *b
++=128+Uc
%64;
354 else if (Uc
-0xd800u
<0x800) goto error
;
355 else if (Uc
<0x10000) *b
++=224+Uc
/4096, *b
++=128+Uc
/64%64, *b
++=128+Uc
%64;
356 else if (Uc
<0x110000) *b
++=240+Uc
/262144, *b
++=128+Uc
/4096%64, *b
++=128+Uc
/64%64, *b
++=128+Uc
%64;
357 else error
: tcc_error("0x%x is not a valid universal character", Uc
);
361 /* add a unicode character expanded into utf8 */
362 ST_INLN
void cstr_u8cat(CString
*cstr
, int ch
)
365 e
= unicode_to_utf8(buf
, (uint32_t)ch
);
366 cstr_cat(cstr
, buf
, e
- buf
);
369 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
, int len
)
373 len
= strlen(str
) + 1 + len
;
374 size
= cstr
->size
+ len
;
375 if (size
> cstr
->size_allocated
)
376 cstr_realloc(cstr
, size
);
377 memmove(((unsigned char *)cstr
->data
) + cstr
->size
, str
, len
);
381 /* add a wide char */
382 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
385 size
= cstr
->size
+ sizeof(nwchar_t
);
386 if (size
> cstr
->size_allocated
)
387 cstr_realloc(cstr
, size
);
388 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
392 ST_FUNC
void cstr_new(CString
*cstr
)
394 memset(cstr
, 0, sizeof(CString
));
397 /* free string and reset it to NULL */
398 ST_FUNC
void cstr_free(CString
*cstr
)
400 tcc_free(cstr
->data
);
403 /* reset string to empty */
404 ST_FUNC
void cstr_reset(CString
*cstr
)
409 ST_FUNC
int cstr_vprintf(CString
*cstr
, const char *fmt
, va_list ap
)
415 if (size
> cstr
->size_allocated
)
416 cstr_realloc(cstr
, size
);
417 size
= cstr
->size_allocated
- cstr
->size
;
419 len
= vsnprintf((char*)cstr
->data
+ cstr
->size
, size
, fmt
, v
);
421 if (len
>= 0 && len
< size
)
429 ST_FUNC
int cstr_printf(CString
*cstr
, const char *fmt
, ...)
433 len
= cstr_vprintf(cstr
, fmt
, ap
);
439 static void add_char(CString
*cstr
, int c
)
441 if (c
== '\'' || c
== '\"' || c
== '\\') {
442 /* XXX: could be more precise if char or string */
443 cstr_ccat(cstr
, '\\');
445 if (c
>= 32 && c
<= 126) {
448 cstr_ccat(cstr
, '\\');
450 cstr_ccat(cstr
, 'n');
452 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
453 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
454 cstr_ccat(cstr
, '0' + (c
& 7));
459 /* ------------------------------------------------------------------------- */
460 /* allocate a new token */
461 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
463 TokenSym
*ts
, **ptable
;
466 if (tok_ident
>= SYM_FIRST_ANOM
)
467 tcc_error("memory full (symbols)");
469 /* expand token table if needed */
470 i
= tok_ident
- TOK_IDENT
;
471 if ((i
% TOK_ALLOC_INCR
) == 0) {
472 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
473 table_ident
= ptable
;
476 ts
= tal_realloc(toksym_alloc
, 0, sizeof(TokenSym
) + len
);
478 ts
->tok
= tok_ident
++;
479 ts
->sym_define
= NULL
;
480 ts
->sym_label
= NULL
;
481 ts
->sym_struct
= NULL
;
482 ts
->sym_identifier
= NULL
;
484 ts
->hash_next
= NULL
;
485 memcpy(ts
->str
, str
, len
);
491 #define TOK_HASH_INIT 1
492 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
495 /* find a token and add it if not found */
496 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
504 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
505 h
&= (TOK_HASH_SIZE
- 1);
507 pts
= &hash_ident
[h
];
512 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
514 pts
= &(ts
->hash_next
);
516 return tok_alloc_new(pts
, str
, len
);
519 ST_FUNC
int tok_alloc_const(const char *str
)
521 return tok_alloc(str
, strlen(str
))->tok
;
525 /* XXX: buffer overflow */
526 /* XXX: float tokens */
527 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
532 cstr_reset(&cstr_buf
);
542 /* XXX: not quite exact, but only useful for testing */
544 sprintf(p
, "%u", (unsigned)cv
->i
);
546 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
550 cstr_ccat(&cstr_buf
, 'L');
552 cstr_ccat(&cstr_buf
, '\'');
553 add_char(&cstr_buf
, cv
->i
);
554 cstr_ccat(&cstr_buf
, '\'');
555 cstr_ccat(&cstr_buf
, '\0');
559 return (char*)cv
->str
.data
;
561 cstr_ccat(&cstr_buf
, 'L');
563 cstr_ccat(&cstr_buf
, '\"');
565 len
= cv
->str
.size
- 1;
567 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
569 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
571 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
573 cstr_ccat(&cstr_buf
, '\"');
574 cstr_ccat(&cstr_buf
, '\0');
578 return strcpy(p
, "<float>");
580 return strcpy(p
, "<double>");
582 return strcpy(p
, "<long double>");
584 return strcpy(p
, "<linenumber");
586 /* above tokens have value, the ones below don't */
594 return strcpy(p
, "...");
596 return strcpy(p
, "<<=");
598 return strcpy(p
, ">>=");
600 return strcpy(p
, "<eof>");
601 case 0: /* anonymous nameless symbols */
602 return strcpy(p
, "<no name>");
605 /* search in two bytes table */
606 const unsigned char *q
= tok_two_chars
;
612 return cstr_buf
.data
;
616 if (v
>= 127 || (v
< 32 && !is_space(v
) && v
!= '\n')) {
617 sprintf(p
, "<\\x%02x>", v
);
623 } else if (v
< tok_ident
) {
624 return table_ident
[v
- TOK_IDENT
]->str
;
625 } else if (v
>= SYM_FIRST_ANOM
) {
626 /* special name for anonymous symbol */
627 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
629 /* should never happen */
634 return cstr_buf
.data
;
637 static inline int check_space(int t
, int *spc
)
639 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
648 /* return the current character, handling end of block if necessary
650 static int handle_eob(void)
652 BufferedFile
*bf
= file
;
655 /* only tries to read if really end of buffer */
656 if (bf
->buf_ptr
>= bf
->buf_end
) {
658 #if defined(PARSE_DEBUG)
663 len
= read(bf
->fd
, bf
->buffer
, len
);
670 bf
->buf_ptr
= bf
->buffer
;
671 bf
->buf_end
= bf
->buffer
+ len
;
672 *bf
->buf_end
= CH_EOB
;
674 if (bf
->buf_ptr
< bf
->buf_end
) {
675 return bf
->buf_ptr
[0];
677 bf
->buf_ptr
= bf
->buf_end
;
682 /* read next char from current input file and handle end of input buffer */
683 static int next_c(void)
685 int ch
= *++file
->buf_ptr
;
686 /* end of buffer/file handling */
687 if (ch
== CH_EOB
&& file
->buf_ptr
>= file
->buf_end
)
692 /* input with '\[\r]\n' handling. */
693 static int handle_stray_noerror(int err
)
696 while ((ch
= next_c()) == '\\') {
706 *--file
->buf_ptr
= '\r';
709 tcc_error("stray '\\' in program");
710 /* may take advantage of 'BufferedFile.unget[4}' */
711 return *--file
->buf_ptr
= '\\';
717 #define ninp() handle_stray_noerror(0)
719 /* handle '\\' in strings, comments and skipped regions */
720 static int handle_bs(uint8_t **p
)
723 file
->buf_ptr
= *p
- 1;
729 /* skip the stray and handle the \\n case. Output an error if
730 incorrect char after the stray */
731 static int handle_stray(uint8_t **p
)
734 file
->buf_ptr
= *p
- 1;
735 c
= handle_stray_noerror(!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
));
740 /* handle the complicated stray case */
745 c = handle_stray(&p); \
748 static int skip_spaces(void)
754 } while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
);
758 /* single line C++ comments */
759 static uint8_t *parse_line_comment(uint8_t *p
)
766 if (c
== '\n' || c
== '\\')
769 if (c
== '\n' || c
== '\\')
784 static uint8_t *parse_comment(uint8_t *p
)
792 if (c
== '\n' || c
== '*' || c
== '\\')
795 if (c
== '\n' || c
== '*' || c
== '\\')
798 /* now we can handle all the cases */
801 } else if (c
== '*') {
814 tcc_error("unexpected end of file in comment");
822 /* parse a string without interpreting escapes */
823 static uint8_t *parse_pp_string(uint8_t *p
, int sep
, CString
*str
)
831 } else if (c
== '\\') {
835 /* XXX: indicate line number of start of string */
836 tok_flags
&= ~TOK_FLAG_BOL
;
837 tcc_error("missing terminating %c character", sep
);
838 } else if (c
== '\\') {
842 /* add char after '\\' unconditionally */
846 goto unterminated_string
;
852 } else if (c
== '\n') {
854 if (ACCEPT_LF_IN_STRINGS
) {
857 } else if (str
) { /* not skipping */
858 goto unterminated_string
;
860 //tcc_warning("missing terminating %c character", sep);
863 } else if (c
== '\r') {
870 goto unterminated_string
;
872 cstr_ccat(str
, '\r');
884 /* skip block of text until #else, #elif or #endif. skip also pairs of
886 static void preprocess_skip(void)
888 int a
, start_of_line
, c
, in_warn_or_error
;
895 in_warn_or_error
= 0;
921 if (in_warn_or_error
)
923 tok_flags
&= ~TOK_FLAG_BOL
;
924 p
= parse_pp_string(p
, c
, NULL
);
928 if (in_warn_or_error
)
933 p
= parse_comment(p
);
934 } else if (c
== '/') {
935 p
= parse_line_comment(p
);
945 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
947 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
949 else if (tok
== TOK_ENDIF
)
951 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
952 in_warn_or_error
= 1;
953 else if (tok
== TOK_LINEFEED
)
955 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
956 p
= parse_line_comment(p
- 1);
958 #if !defined(TCC_TARGET_ARM)
959 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
960 p
= parse_line_comment(p
- 1);
962 /* ARM assembly uses '#' for constants */
977 /* return the number of additional 'ints' necessary to store the
979 static inline int tok_size(const int *p
)
994 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
997 return 1 + LONG_SIZE
/ 4;
1003 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
1006 return 1 + LDOUBLE_SIZE
/ 4;
1014 /* token string handling */
1015 ST_INLN
void tok_str_new(TokenString
*s
)
1018 s
->len
= s
->lastlen
= 0;
1019 s
->allocated_len
= 0;
1020 s
->last_line_num
= -1;
1023 ST_FUNC TokenString
*tok_str_alloc(void)
1025 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1030 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1034 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1035 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1039 ST_FUNC
void tok_str_free_str(int *str
)
1041 tal_free(tokstr_alloc
, str
);
1044 ST_FUNC
void tok_str_free(TokenString
*str
)
1046 tok_str_free_str(str
->str
);
1047 tal_free(tokstr_alloc
, str
);
1050 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1054 size
= s
->allocated_len
;
1057 while (size
< new_size
)
1059 if (size
> s
->allocated_len
) {
1060 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1061 s
->allocated_len
= size
;
1067 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1073 if (len
>= s
->allocated_len
)
1074 str
= tok_str_realloc(s
, len
+ 1);
1079 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1082 str
->prev
= macro_stack
;
1083 str
->prev_ptr
= macro_ptr
;
1084 str
->save_line_num
= file
->line_num
;
1085 macro_ptr
= str
->str
;
1089 ST_FUNC
void end_macro(void)
1091 TokenString
*str
= macro_stack
;
1092 macro_stack
= str
->prev
;
1093 macro_ptr
= str
->prev_ptr
;
1094 file
->line_num
= str
->save_line_num
;
1095 str
->len
= 0; /* matters if str not alloced, may be tokstr_buf */
1096 if (str
->alloc
!= 0) {
1097 if (str
->alloc
== 2)
1098 str
->str
= NULL
; /* don't free */
1103 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1107 len
= s
->lastlen
= s
->len
;
1110 /* allocate space for worst case */
1111 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1112 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1125 str
[len
++] = cv
->tab
[0];
1132 /* Insert the string into the int array. */
1134 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1135 if (len
+ nb_words
>= s
->allocated_len
)
1136 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1137 str
[len
] = cv
->str
.size
;
1138 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1149 str
[len
++] = cv
->tab
[0];
1150 str
[len
++] = cv
->tab
[1];
1153 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1154 str
[len
++] = cv
->tab
[0];
1155 str
[len
++] = cv
->tab
[1];
1156 #elif LDOUBLE_SIZE == 12
1157 str
[len
++] = cv
->tab
[0];
1158 str
[len
++] = cv
->tab
[1];
1159 str
[len
++] = cv
->tab
[2];
1160 #elif LDOUBLE_SIZE == 16
1161 str
[len
++] = cv
->tab
[0];
1162 str
[len
++] = cv
->tab
[1];
1163 str
[len
++] = cv
->tab
[2];
1164 str
[len
++] = cv
->tab
[3];
1166 #error add long double size support
1175 /* add the current parse token in token string 's' */
1176 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1180 /* save line number info */
1181 if (file
->line_num
!= s
->last_line_num
) {
1182 s
->last_line_num
= file
->line_num
;
1183 cval
.i
= s
->last_line_num
;
1184 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1186 tok_str_add2(s
, tok
, &tokc
);
1189 /* get a token from an integer array and increment pointer. */
1190 static inline void tok_get(int *t
, const int **pp
, CValue
*cv
)
1210 cv
->i
= (unsigned)*p
++;
1219 cv
->str
.size
= *p
++;
1221 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1233 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1235 #elif LDOUBLE_SIZE == 12
1237 #elif LDOUBLE_SIZE == 16
1240 # error add long double size support
1254 # define TOK_GET(t,p,c) tok_get(t,p,c)
1256 # define TOK_GET(t,p,c) do { \
1258 if (TOK_HAS_VALUE(_t)) \
1261 *(t) = _t, ++*(p); \
1265 static int macro_is_equal(const int *a
, const int *b
)
1274 cstr_reset(&tokcstr
);
1275 TOK_GET(&t
, &a
, &cv
);
1276 cstr_cat(&tokcstr
, get_tok_str(t
, &cv
), 0);
1277 TOK_GET(&t
, &b
, &cv
);
1278 if (strcmp(tokcstr
.data
, get_tok_str(t
, &cv
)))
1284 /* defines handling */
1285 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1290 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1292 s
->next
= first_arg
;
1293 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1295 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1296 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1299 /* undefined a define symbol. Its name is just set to zero */
1300 ST_FUNC
void define_undef(Sym
*s
)
1303 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1304 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1307 ST_INLN Sym
*define_find(int v
)
1310 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1312 return table_ident
[v
]->sym_define
;
1315 /* free define stack until top reaches 'b' */
1316 ST_FUNC
void free_defines(Sym
*b
)
1318 while (define_stack
!= b
) {
1319 Sym
*top
= define_stack
;
1320 define_stack
= top
->prev
;
1321 tok_str_free_str(top
->d
);
1327 /* fake the nth "#if defined test_..." for tcc -dt -run */
1328 static void maybe_run_test(TCCState
*s
)
1331 if (s
->include_stack_ptr
!= s
->include_stack
)
1333 p
= get_tok_str(tok
, NULL
);
1334 if (0 != memcmp(p
, "test_", 5))
1336 if (0 != --s
->run_test
)
1338 fprintf(s
->ppfp
, &"\n[%s]\n"[!(s
->dflag
& 32)], p
), fflush(s
->ppfp
);
1339 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1342 static CachedInclude
*
1343 search_cached_include(TCCState
*s1
, const char *filename
, int add
);
1345 static int parse_include(TCCState
*s1
, int do_next
, int test
)
1348 char name
[1024], buf
[1024], *p
;
1352 if (c
== '<' || c
== '\"') {
1353 cstr_reset(&tokcstr
);
1354 file
->buf_ptr
= parse_pp_string(file
->buf_ptr
, c
== '<' ? '>' : c
, &tokcstr
);
1356 pstrncpy(name
, tokcstr
.data
, i
>= sizeof name
? sizeof name
- 1 : i
);
1359 /* computed #include : concatenate tokens until result is one of
1360 the two accepted forms. Don't convert pp-tokens to tokens here. */
1361 parse_flags
= PARSE_FLAG_PREPROCESS
1362 | PARSE_FLAG_LINEFEED
1363 | (parse_flags
& PARSE_FLAG_ASM_FILE
);
1367 p
= name
, i
= strlen(p
) - 1;
1369 && ((p
[0] == '"' && p
[i
] == '"')
1370 || (p
[0] == '<' && p
[i
] == '>')))
1372 if (tok
== TOK_LINEFEED
)
1373 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1374 pstrcat(name
, sizeof name
, get_tok_str(tok
, &tokc
));
1377 /* remove '<>|""' */
1378 memmove(p
, p
+ 1, i
- 1), p
[i
- 1] = 0;
1381 i
= do_next
? file
->include_next_index
: -1;
1385 /* check absolute include path */
1386 if (!IS_ABSPATH(name
))
1389 } else if (i
== 1) {
1390 /* search in file's dir if "header.h" */
1393 p
= file
->true_filename
;
1394 pstrncpy(buf
, p
, tcc_basename(p
) - p
);
1396 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1398 p
= s1
->include_paths
[j
];
1399 else if (k
< s1
->nb_sysinclude_paths
)
1400 p
= s1
->sysinclude_paths
[k
];
1404 tcc_error("include file '%s' not found", name
);
1405 pstrcpy(buf
, sizeof buf
, p
);
1406 pstrcat(buf
, sizeof buf
, "/");
1408 pstrcat(buf
, sizeof buf
, name
);
1409 e
= search_cached_include(s1
, buf
, 0);
1410 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
== pp_once
)) {
1411 /* no need to parse the include because the 'ifndef macro'
1412 is defined (or had #pragma once) */
1414 printf("%s: skipping cached %s\n", file
->filename
, buf
);
1418 if (tcc_open(s1
, buf
) >= 0)
1425 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1426 tcc_error("#include recursion too deep");
1427 /* push previous file on stack */
1428 *s1
->include_stack_ptr
++ = file
->prev
;
1429 file
->include_next_index
= i
;
1431 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1433 /* update target deps */
1435 BufferedFile
*bf
= file
;
1436 while (i
== 1 && (bf
= bf
->prev
))
1437 i
= bf
->include_next_index
;
1438 /* skip system include files */
1439 if (s1
->include_sys_deps
|| i
- 2 < s1
->nb_include_paths
)
1440 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1443 /* add include file debug info */
1444 tcc_debug_bincl(s1
);
1445 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1450 /* eval an expression for #if/#elif */
1451 static int expr_preprocess(TCCState
*s1
)
1456 str
= tok_str_alloc();
1458 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1459 next(); /* do macro subst */
1461 if (tok
== TOK_DEFINED
) {
1466 if (tok
< TOK_IDENT
)
1467 expect("identifier");
1471 if (define_find(tok
)
1472 || tok
== TOK___HAS_INCLUDE
1473 || tok
== TOK___HAS_INCLUDE_NEXT
)
1482 } else if (tok
== TOK___HAS_INCLUDE
||
1483 tok
== TOK___HAS_INCLUDE_NEXT
) {
1488 c
= parse_include(s1
, t
- TOK___HAS_INCLUDE
, 1);
1493 } else if (tok
>= TOK_IDENT
) {
1494 /* if undefined macro, replace with zero, check for func-like */
1498 tok_str_add_tok(str
);
1501 tcc_error("function-like macro '%s' is not defined",
1502 get_tok_str(t
, NULL
));
1505 tok_str_add_tok(str
);
1508 tok_str_add(str
, -1); /* simulate end of file */
1509 tok_str_add(str
, 0);
1510 /* now evaluate C constant expression */
1511 begin_macro(str
, 1);
1519 /* parse after #define */
1520 ST_FUNC
void parse_define(void)
1522 Sym
*s
, *first
, **ps
;
1523 int v
, t
, varg
, is_vaargs
, spc
;
1524 int saved_parse_flags
= parse_flags
;
1527 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1528 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1529 /* XXX: should check if same macro (ANSI) */
1532 /* We have to parse the whole define as if not in asm mode, in particular
1533 no line comment with '#' must be ignored. Also for function
1534 macros the argument list must be parsed without '.' being an ID
1536 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1537 /* '(' must be just after macro definition for MACRO_FUNC */
1539 parse_flags
&= ~PARSE_FLAG_SPACES
;
1541 int dotid
= set_idnum('.', 0);
1544 if (tok
!= ')') for (;;) {
1548 if (varg
== TOK_DOTS
) {
1549 varg
= TOK___VA_ARGS__
;
1551 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1555 if (varg
< TOK_IDENT
)
1557 tcc_error("bad macro parameter list");
1558 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1563 if (tok
!= ',' || is_vaargs
)
1567 parse_flags
|= PARSE_FLAG_SPACES
;
1570 set_idnum('.', dotid
);
1575 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1576 /* The body of a macro definition should be parsed such that identifiers
1577 are parsed like the file mode determines (i.e. with '.' being an
1578 ID character in asm mode). But '#' should be retained instead of
1579 regarded as line comment leader, so still don't set ASM_FILE
1581 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1582 /* remove spaces around ## and after '#' */
1583 if (TOK_TWOSHARPS
== tok
) {
1590 } else if ('#' == tok
) {
1592 } else if (check_space(tok
, &spc
)) {
1595 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1600 parse_flags
= saved_parse_flags
;
1602 --tokstr_buf
.len
; /* remove trailing space */
1603 tok_str_add(&tokstr_buf
, 0);
1606 tcc_error("'##' cannot appear at either end of macro");
1607 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1611 static unsigned long long calc_file_hash(const char *filename
)
1613 unsigned long long hash
= 14695981039346656037ull; // FNV_offset_basis;
1614 FILE *fp
= fopen (filename
, "rb");
1619 unsigned char temp
[IO_BUF_SIZE
];
1620 int i
, n
= fread(temp
, 1, sizeof(temp
), fp
);
1624 for (i
= 0; i
< n
; i
++)
1625 hash
= hash
* 1099511628211ull ^ temp
[i
]; // FNV_prime
1628 return hash
? hash
: 1ull;
1632 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1639 unsigned long long hash
= 0;
1642 /* This is needed for #pragmae once
1643 * We cannot use stat on windows because st_ino is not set correctly
1644 * so we calculate a hash of file contents.
1645 * This also works for hard/soft links as in gcc/clang.
1647 memset (&st
, 0, sizeof(st
));
1648 if (stat (filename
, &st
))
1650 h
= st
.st_size
& (CACHED_INCLUDES_HASH_SIZE
- 1);
1652 /* Only calculate file hash if file size same. */
1653 i
= s1
->cached_includes_hash
[h
];
1657 e
= s1
->cached_includes
[i
- 1];
1658 if (e
->st
.st_size
== st
.st_size
) {
1659 if (0 == PATHCMP(e
->filename
, filename
)) {
1664 e
->hash
= calc_file_hash(e
->filename
);
1666 hash
= calc_file_hash(filename
);
1672 i
= s1
->cached_includes_hash
[h
];
1676 e
= s1
->cached_includes
[i
- 1];
1678 if (e
->st
.st_size
== st
.st_size
&& e
->hash
== hash
)
1680 if (st
.st_dev
== e
->st
.st_dev
&& st
.st_ino
== e
->st
.st_ino
)
1689 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1694 strcpy(e
->filename
, filename
);
1695 e
->ifndef_macro
= e
->once
= 0;
1696 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1697 /* add in hash table */
1698 e
->hash_next
= s1
->cached_includes_hash
[h
];
1699 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1701 printf("adding cached '%s'\n", filename
);
1706 static void pragma_parse(TCCState
*s1
)
1709 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1713 if (next(), tok
!= '(')
1715 if (next(), tok
!= TOK_STR
)
1717 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1718 if (next(), tok
!= ')')
1720 if (t
== TOK_push_macro
) {
1721 while (NULL
== (s
= define_find(v
)))
1722 define_push(v
, 0, NULL
, NULL
);
1723 s
->type
.ref
= s
; /* set push boundary */
1725 for (s
= define_stack
; s
; s
= s
->prev
)
1726 if (s
->v
== v
&& s
->type
.ref
== s
) {
1732 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1734 tcc_warning("unbalanced #pragma pop_macro");
1735 pp_debug_tok
= t
, pp_debug_symv
= v
;
1737 } else if (tok
== TOK_once
) {
1738 search_cached_include(s1
, file
->filename
, 1)->once
= pp_once
;
1740 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1741 /* tcc -E: keep pragmas below unchanged */
1743 unget_tok(TOK_PRAGMA
);
1745 unget_tok(TOK_LINEFEED
);
1747 } else if (tok
== TOK_pack
) {
1749 #pragma pack(1) // set
1750 #pragma pack() // reset to default
1751 #pragma pack(push) // push current
1752 #pragma pack(push,1) // push & set
1753 #pragma pack(pop) // restore previous */
1756 if (tok
== TOK_ASM_pop
) {
1758 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1760 tcc_error("out of pack stack");
1762 s1
->pack_stack_ptr
--;
1766 if (tok
== TOK_ASM_push
) {
1768 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1770 val
= *s1
->pack_stack_ptr
++;
1775 if (tok
!= TOK_CINT
)
1778 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1783 *s1
->pack_stack_ptr
= val
;
1788 } else if (tok
== TOK_comment
) {
1797 p
= tcc_strdup((char *)tokc
.str
.data
);
1802 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1804 if (t
== TOK_option
)
1805 tcc_set_options(s1
, p
);
1810 tcc_warning_c(warn_unsupported
)("#pragma %s ignored", get_tok_str(tok
, &tokc
));
1814 tcc_error("malformed #pragma directive");
1818 /* is_bof is true if first non space token at beginning of file */
1819 ST_FUNC
void preprocess(int is_bof
)
1821 TCCState
*s1
= tcc_state
;
1822 int c
, n
, saved_parse_flags
;
1826 saved_parse_flags
= parse_flags
;
1827 parse_flags
= PARSE_FLAG_PREPROCESS
1828 | PARSE_FLAG_TOK_NUM
1829 | PARSE_FLAG_TOK_STR
1830 | PARSE_FLAG_LINEFEED
1831 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1840 pp_debug_symv
= tok
;
1846 pp_debug_symv
= tok
;
1847 s
= define_find(tok
);
1848 /* undefine symbol by putting an invalid name */
1853 case TOK_INCLUDE_NEXT
:
1854 parse_include(s1
, tok
- TOK_INCLUDE
, 0);
1860 c
= expr_preprocess(s1
);
1866 if (tok
< TOK_IDENT
)
1867 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1871 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1873 file
->ifndef_macro
= tok
;
1876 if (define_find(tok
)
1877 || tok
== TOK___HAS_INCLUDE
1878 || tok
== TOK___HAS_INCLUDE_NEXT
)
1881 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1882 tcc_error("memory full (ifdef)");
1883 *s1
->ifdef_stack_ptr
++ = c
;
1886 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1887 tcc_error("#else without matching #if");
1888 if (s1
->ifdef_stack_ptr
[-1] & 2)
1889 tcc_error("#else after #else");
1890 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1893 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1894 tcc_error("#elif without matching #if");
1895 c
= s1
->ifdef_stack_ptr
[-1];
1897 tcc_error("#elif after #else");
1898 /* last #if/#elif expression was true: we skip */
1902 c
= expr_preprocess(s1
);
1903 s1
->ifdef_stack_ptr
[-1] = c
;
1906 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1907 file
->ifndef_macro
= 0;
1916 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1917 tcc_error("#endif without matching #if");
1918 s1
->ifdef_stack_ptr
--;
1919 /* '#ifndef macro' was at the start of file. Now we check if
1920 an '#endif' is exactly at the end of file */
1921 if (file
->ifndef_macro
&&
1922 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1923 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1924 /* need to set to zero to avoid false matches if another
1925 #ifndef at middle of file */
1926 file
->ifndef_macro
= 0;
1927 while (tok
!= TOK_LINEFEED
)
1929 tok_flags
|= TOK_FLAG_ENDIF
;
1934 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1938 if (tok
!= TOK_CINT
)
1940 tcc_error("wrong #line format");
1944 if (tok
!= TOK_LINEFEED
) {
1945 if (tok
== TOK_STR
) {
1946 if (file
->true_filename
== file
->filename
)
1947 file
->true_filename
= tcc_strdup(file
->filename
);
1948 q
= (char *)tokc
.str
.data
;
1950 if (!IS_ABSPATH(q
)) {
1951 /* prepend directory from real file */
1952 pstrcpy(buf
, sizeof buf
, file
->true_filename
);
1953 *tcc_basename(buf
) = 0;
1955 pstrcat(buf
, sizeof buf
, q
);
1956 tcc_debug_putfile(s1
, buf
);
1957 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1964 total_lines
+= file
->line_num
- n
;
1971 while (c
!= '\n' && c
!= CH_EOF
) {
1972 if ((q
- buf
) < sizeof(buf
) - 1)
1977 if (tok
== TOK_ERROR
)
1978 tcc_error("#error %s", buf
);
1980 tcc_warning("#warning %s", buf
);
1988 /* ignore gas line comment in an 'S' file. */
1989 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
1991 if (tok
== '!' && is_bof
)
1992 /* '!' is ignored at beginning to allow C scripts. */
1994 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1996 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
1999 /* ignore other preprocess commands or #! for C scripts */
2000 while (tok
!= TOK_LINEFEED
)
2003 parse_flags
= saved_parse_flags
;
2006 /* evaluate escape codes in a string. */
2007 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2022 case '0': case '1': case '2': case '3':
2023 case '4': case '5': case '6': case '7':
2024 /* at most three octal digits */
2029 n
= n
* 8 + c
- '0';
2033 n
= n
* 8 + c
- '0';
2038 goto add_char_nonext
;
2039 case 'x': i
= 0; goto parse_hex_or_ucn
;
2040 case 'u': i
= 4; goto parse_hex_or_ucn
;
2041 case 'U': i
= 8; goto parse_hex_or_ucn
;
2047 if (c
>= 'a' && c
<= 'f')
2049 else if (c
>= 'A' && c
<= 'F')
2054 expect("more hex digits in universal-character-name");
2056 goto add_hex_or_ucn
;
2063 goto add_char_nonext
;
2065 cstr_u8cat(outstr
, n
);
2090 goto invalid_escape
;
2100 if (c
>= '!' && c
<= '~')
2101 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2103 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2106 } else if (is_long
&& c
>= 0x80) {
2107 /* assume we are processing UTF-8 sequence */
2108 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2110 int cont
; /* count of continuation bytes */
2111 int skip
; /* how many bytes should skip when error occurred */
2114 /* decode leading byte */
2116 skip
= 1; goto invalid_utf8_sequence
;
2117 } else if (c
<= 0xDF) {
2118 cont
= 1; n
= c
& 0x1f;
2119 } else if (c
<= 0xEF) {
2120 cont
= 2; n
= c
& 0xf;
2121 } else if (c
<= 0xF4) {
2122 cont
= 3; n
= c
& 0x7;
2124 skip
= 1; goto invalid_utf8_sequence
;
2127 /* decode continuation bytes */
2128 for (i
= 1; i
<= cont
; i
++) {
2129 int l
= 0x80, h
= 0xBF;
2131 /* adjust limit for second byte */
2134 case 0xE0: l
= 0xA0; break;
2135 case 0xED: h
= 0x9F; break;
2136 case 0xF0: l
= 0x90; break;
2137 case 0xF4: h
= 0x8F; break;
2141 if (p
[i
] < l
|| p
[i
] > h
) {
2142 skip
= i
; goto invalid_utf8_sequence
;
2145 n
= (n
<< 6) | (p
[i
] & 0x3f);
2148 /* advance pointer */
2151 goto add_char_nonext
;
2153 /* error handling */
2154 invalid_utf8_sequence
:
2155 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c
);
2158 goto add_char_nonext
;
2164 cstr_ccat(outstr
, c
);
2166 #ifdef TCC_TARGET_PE
2167 /* store as UTF-16 */
2169 cstr_wccat(outstr
, c
);
2172 cstr_wccat(outstr
, (c
>> 10) + 0xD800);
2173 cstr_wccat(outstr
, (c
& 0x3FF) + 0xDC00);
2176 cstr_wccat(outstr
, c
);
2180 /* add a trailing '\0' */
2182 cstr_ccat(outstr
, '\0');
2184 cstr_wccat(outstr
, '\0');
2187 static void parse_string(const char *s
, int len
)
2189 uint8_t buf
[1000], *p
= buf
;
2192 if ((is_long
= *s
== 'L'))
2196 if (len
>= sizeof buf
)
2197 p
= tcc_malloc(len
+ 1);
2201 cstr_reset(&tokcstr
);
2202 parse_escape_string(&tokcstr
, p
, is_long
);
2207 int char_size
, i
, n
, c
;
2208 /* XXX: make it portable */
2210 tok
= TOK_CCHAR
, char_size
= 1;
2212 tok
= TOK_LCHAR
, char_size
= sizeof(nwchar_t
);
2213 n
= tokcstr
.size
/ char_size
- 1;
2215 tcc_error("empty character constant");
2217 tcc_warning_c(warn_all
)("multi-character character constant");
2218 for (c
= i
= 0; i
< n
; ++i
) {
2220 c
= ((nwchar_t
*)tokcstr
.data
)[i
];
2222 c
= (c
<< 8) | ((char *)tokcstr
.data
)[i
];
2226 tokc
.str
.size
= tokcstr
.size
;
2227 tokc
.str
.data
= tokcstr
.data
;
2235 /* we use 64 bit numbers */
2238 /* bn = (bn << shift) | or_val */
2239 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2243 for(i
=0;i
<BN_SIZE
;i
++) {
2245 bn
[i
] = (v
<< shift
) | or_val
;
2246 or_val
= v
>> (32 - shift
);
2250 static void bn_zero(unsigned int *bn
)
2253 for(i
=0;i
<BN_SIZE
;i
++) {
2258 /* parse number in null terminated string 'p' and return it in the
2260 static void parse_number(const char *p
)
2262 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2264 unsigned int bn
[BN_SIZE
];
2275 goto float_frac_parse
;
2276 } else if (t
== '0') {
2277 if (ch
== 'x' || ch
== 'X') {
2281 } else if (tcc_state
->tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2287 /* parse all digits. cannot check octal numbers at this stage
2288 because of floating point constants */
2290 if (ch
>= 'a' && ch
<= 'f')
2292 else if (ch
>= 'A' && ch
<= 'F')
2300 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2302 tcc_error("number too long");
2308 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2309 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2311 /* NOTE: strtox should support that for hexa numbers, but
2312 non ISOC99 libcs do not support it, so we prefer to do
2314 /* hexadecimal or binary floats */
2315 /* XXX: handle overflows */
2327 } else if (t
>= 'a') {
2329 } else if (t
>= 'A') {
2334 bn_lshift(bn
, shift
, t
);
2341 if (t
>= 'a' && t
<= 'f') {
2343 } else if (t
>= 'A' && t
<= 'F') {
2345 } else if (t
>= '0' && t
<= '9') {
2351 tcc_error("invalid digit");
2352 bn_lshift(bn
, shift
, t
);
2357 if (ch
!= 'p' && ch
!= 'P')
2364 } else if (ch
== '-') {
2368 if (ch
< '0' || ch
> '9')
2369 expect("exponent digits");
2370 while (ch
>= '0' && ch
<= '9') {
2371 exp_val
= exp_val
* 10 + ch
- '0';
2374 exp_val
= exp_val
* s
;
2376 /* now we can generate the number */
2377 /* XXX: should patch directly float number */
2378 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2379 d
= ldexp(d
, exp_val
- frac_bits
);
2384 /* float : should handle overflow */
2386 } else if (t
== 'L') {
2389 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2392 /* XXX: not large enough */
2393 tokc
.ld
= (long double)d
;
2400 /* decimal floats */
2402 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2407 while (ch
>= '0' && ch
<= '9') {
2408 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2414 if (ch
== 'e' || ch
== 'E') {
2415 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2419 if (ch
== '-' || ch
== '+') {
2420 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2425 if (ch
< '0' || ch
> '9')
2426 expect("exponent digits");
2427 while (ch
>= '0' && ch
<= '9') {
2428 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2440 tokc
.f
= strtof(token_buf
, NULL
);
2441 } else if (t
== 'L') {
2444 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2445 tokc
.d
= strtod(token_buf
, NULL
);
2447 tokc
.ld
= strtold(token_buf
, NULL
);
2451 tokc
.d
= strtod(token_buf
, NULL
);
2455 unsigned long long n
, n1
;
2456 int lcount
, ucount
, ov
= 0;
2459 /* integer number */
2462 if (b
== 10 && *q
== '0') {
2469 /* no need for checks except for base 10 / 8 errors */
2479 tcc_error("invalid digit");
2482 /* detect overflow */
2483 if (n1
>= 0x1000000000000000ULL
&& n
/ b
!= n1
)
2487 /* Determine the characteristics (unsigned and/or 64bit) the type of
2488 the constant must have according to the constant suffix(es) */
2489 lcount
= ucount
= 0;
2495 tcc_error("three 'l's in integer constant");
2496 if (lcount
&& *(p
- 1) != ch
)
2497 tcc_error("incorrect integer suffix: %s", p1
);
2500 } else if (t
== 'U') {
2502 tcc_error("two 'u's in integer constant");
2510 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2511 if (ucount
== 0 && b
== 10) {
2512 if (lcount
<= (LONG_SIZE
== 4)) {
2513 if (n
>= 0x80000000U
)
2514 lcount
= (LONG_SIZE
== 4) + 1;
2516 if (n
>= 0x8000000000000000ULL
)
2519 if (lcount
<= (LONG_SIZE
== 4)) {
2520 if (n
>= 0x100000000ULL
)
2521 lcount
= (LONG_SIZE
== 4) + 1;
2522 else if (n
>= 0x80000000U
)
2525 if (n
>= 0x8000000000000000ULL
)
2530 tcc_warning("integer constant overflow");
2539 ++tok
; /* TOK_CU... */
2543 tcc_error("invalid number");
2547 #define PARSE2(c1, tok1, c2, tok2) \
2558 /* return next token without macro substitution */
2559 static inline void next_nomacro1(void)
2561 int t
, c
, is_long
, len
;
2575 if (parse_flags
& PARSE_FLAG_SPACES
)
2576 goto keep_tok_flags
;
2577 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2586 /* first look if it is in fact an end of buffer */
2587 c
= handle_stray(&p
);
2591 TCCState
*s1
= tcc_state
;
2592 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2593 && !(tok_flags
& TOK_FLAG_EOF
)) {
2594 tok_flags
|= TOK_FLAG_EOF
;
2596 goto keep_tok_flags
;
2597 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2599 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2600 tcc_error("missing #endif");
2601 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2602 /* no include left : end of file. */
2605 tok_flags
&= ~TOK_FLAG_EOF
;
2606 /* pop include file */
2608 /* test if previous '#endif' was after a #ifdef at
2610 if (tok_flags
& TOK_FLAG_ENDIF
) {
2612 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2614 search_cached_include(s1
, file
->filename
, 1)
2615 ->ifndef_macro
= file
->ifndef_macro_saved
;
2616 tok_flags
&= ~TOK_FLAG_ENDIF
;
2619 /* add end of include file debug info */
2620 tcc_debug_eincl(tcc_state
);
2621 /* pop include stack */
2623 s1
->include_stack_ptr
--;
2625 if (p
== file
->buffer
)
2626 tok_flags
= TOK_FLAG_BOF
;
2627 tok_flags
|= TOK_FLAG_BOL
;
2637 tok_flags
|= TOK_FLAG_BOL
;
2640 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2643 goto keep_tok_flags
;
2648 if ((tok_flags
& TOK_FLAG_BOL
) &&
2649 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2651 preprocess(tok_flags
& TOK_FLAG_BOF
);
2657 tok
= TOK_TWOSHARPS
;
2659 #if !defined(TCC_TARGET_ARM)
2660 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2661 p
= parse_line_comment(p
- 1);
2672 /* dollar is allowed to start identifiers when not parsing asm */
2674 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2675 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2678 case 'a': case 'b': case 'c': case 'd':
2679 case 'e': case 'f': case 'g': case 'h':
2680 case 'i': case 'j': case 'k': case 'l':
2681 case 'm': case 'n': case 'o': case 'p':
2682 case 'q': case 'r': case 's': case 't':
2683 case 'u': case 'v': case 'w': case 'x':
2685 case 'A': case 'B': case 'C': case 'D':
2686 case 'E': case 'F': case 'G': case 'H':
2687 case 'I': case 'J': case 'K':
2688 case 'M': case 'N': case 'O': case 'P':
2689 case 'Q': case 'R': case 'S': case 'T':
2690 case 'U': case 'V': case 'W': case 'X':
2696 h
= TOK_HASH_FUNC(h
, c
);
2697 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2698 h
= TOK_HASH_FUNC(h
, c
);
2703 /* fast case : no stray found, so we have the full token
2704 and we have already hashed it */
2705 h
&= (TOK_HASH_SIZE
- 1);
2706 pts
= &hash_ident
[h
];
2711 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2713 pts
= &(ts
->hash_next
);
2715 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2719 cstr_reset(&tokcstr
);
2720 cstr_cat(&tokcstr
, (char *) p1
, len
);
2724 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2726 cstr_ccat(&tokcstr
, c
);
2729 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2735 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2737 goto parse_ident_fast
;
2740 if (c
== '\'' || c
== '\"') {
2744 cstr_reset(&tokcstr
);
2745 cstr_ccat(&tokcstr
, 'L');
2746 goto parse_ident_slow
;
2751 case '0': case '1': case '2': case '3':
2752 case '4': case '5': case '6': case '7':
2756 /* after the first digit, accept digits, alpha, '.' or sign if
2757 prefixed by 'eEpP' */
2759 cstr_reset(&tokcstr
);
2761 cstr_ccat(&tokcstr
, t
);
2762 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2764 || ((c
== '+' || c
== '-')
2765 && (((t
== 'e' || t
== 'E')
2766 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2767 /* 0xe+1 is 3 tokens in asm */
2768 && ((char*)tokcstr
.data
)[0] == '0'
2769 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2770 || t
== 'p' || t
== 'P'))))
2775 /* We add a trailing '\0' to ease parsing */
2776 cstr_ccat(&tokcstr
, '\0');
2777 tokc
.str
.size
= tokcstr
.size
;
2778 tokc
.str
.data
= tokcstr
.data
;
2783 /* special dot handling because it can also start a number */
2788 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2789 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2791 goto parse_ident_fast
;
2792 } else if (c
== '.') {
2798 *--p
= '.'; /* may underflow into file->unget[] */
2809 cstr_reset(&tokcstr
);
2811 cstr_ccat(&tokcstr
, 'L');
2812 cstr_ccat(&tokcstr
, c
);
2813 p
= parse_pp_string(p
, c
, &tokcstr
);
2814 cstr_ccat(&tokcstr
, c
);
2815 cstr_ccat(&tokcstr
, '\0');
2816 tokc
.str
.size
= tokcstr
.size
;
2817 tokc
.str
.data
= tokcstr
.data
;
2826 } else if (c
== '<') {
2843 } else if (c
== '>') {
2861 } else if (c
== '=') {
2874 } else if (c
== '=') {
2887 } else if (c
== '=') {
2900 } else if (c
== '=') {
2903 } else if (c
== '>') {
2911 PARSE2('!', '!', '=', TOK_NE
)
2912 PARSE2('=', '=', '=', TOK_EQ
)
2913 PARSE2('*', '*', '=', TOK_A_MUL
)
2914 PARSE2('%', '%', '=', TOK_A_MOD
)
2915 PARSE2('^', '^', '=', TOK_A_XOR
)
2917 /* comments or operator */
2921 p
= parse_comment(p
);
2922 /* comments replaced by a blank */
2925 } else if (c
== '/') {
2926 p
= parse_line_comment(p
);
2929 } else if (c
== '=') {
2949 case '@': /* only used in assembler */
2955 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
2956 goto parse_ident_fast
;
2957 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2959 tcc_error("unrecognized character \\x%02x", c
);
2965 #if defined(PARSE_DEBUG)
2966 printf("token = %d %s\n", tok
, get_tok_str(tok
, &tokc
));
2970 static void macro_subst(
2971 TokenString
*tok_str
,
2973 const int *macro_str
2976 /* substitute arguments in replacement lists in macro_str by the values in
2977 args (field d) and return allocated string */
2978 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2989 TOK_GET(&t
, ¯o_str
, &cval
);
2994 TOK_GET(&t
, ¯o_str
, &cval
);
2997 s
= sym_find2(args
, t
);
2999 cstr_reset(&tokcstr
);
3000 cstr_ccat(&tokcstr
, '\"');
3004 TOK_GET(&t
, &st
, &cval
);
3005 if (t
!= TOK_PLCHLDR
3007 && 0 == check_space(t
, &spc
)) {
3008 const char *s
= get_tok_str(t
, &cval
);
3010 if (t
== TOK_PPSTR
&& *s
!= '\'')
3011 add_char(&tokcstr
, *s
);
3013 cstr_ccat(&tokcstr
, *s
);
3018 tokcstr
.size
-= spc
;
3019 cstr_ccat(&tokcstr
, '\"');
3020 cstr_ccat(&tokcstr
, '\0');
3022 printf("\nstringize: <%s>\n", (char *)tokcstr
.data
);
3025 cval
.str
.size
= tokcstr
.size
;
3026 cval
.str
.data
= tokcstr
.data
;
3027 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
3030 expect("macro parameter after '#'");
3032 } else if (t
>= TOK_IDENT
) {
3033 s
= sym_find2(args
, t
);
3036 /* if '##' is present before or after, no arg substitution */
3037 if (*macro_str
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
3038 /* special case for var arg macros : ## eats the ','
3039 if empty VA_ARGS variable. */
3040 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
3042 /* suppress ',' '##' */
3045 /* suppress '##' and add variable */
3053 /* Expand arguments tokens and store them. In most
3054 cases we could also re-expand each argument if
3055 used multiple times, but not if the argument
3056 contains the __COUNTER__ macro. */
3058 sym_push2(&s
->next
, s
->v
, s
->type
.t
, 0);
3060 macro_subst(&str2
, nested_list
, st
);
3061 tok_str_add(&str2
, 0);
3062 s
->next
->d
= str2
.str
;
3067 /* expanded to empty string */
3068 tok_str_add(&str
, TOK_PLCHLDR
);
3071 TOK_GET(&t2
, &st
, &cval
);
3074 tok_str_add2(&str
, t2
, &cval
);
3077 tok_str_add(&str
, t
);
3080 tok_str_add2(&str
, t
, &cval
);
3084 tok_str_add(&str
, 0);
3088 static char const ab_month_name
[12][4] =
3090 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3091 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3094 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3098 cstr_reset(&tokcstr
);
3099 if (t1
!= TOK_PLCHLDR
)
3100 cstr_cat(&tokcstr
, get_tok_str(t1
, v1
), -1);
3102 if (t2
!= TOK_PLCHLDR
)
3103 cstr_cat(&tokcstr
, get_tok_str(t2
, v2
), -1);
3104 cstr_ccat(&tokcstr
, '\0');
3105 //printf("paste <%s>\n", (char*)tokcstr.data);
3107 tcc_open_bf(tcc_state
, ":paste:", tokcstr
.size
);
3108 memcpy(file
->buffer
, tokcstr
.data
, tokcstr
.size
);
3112 if (0 == *file
->buf_ptr
)
3116 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3117 " preprocessing token", n
, file
->buffer
, file
->buffer
+ n
);
3125 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3126 return the resulting string (which must be freed). */
3127 static inline int *macro_twosharps(const int *ptr0
)
3131 TokenString macro_str1
;
3132 int start_of_nosubsts
= -1;
3135 /* we search the first '##' */
3136 for (ptr
= ptr0
;;) {
3137 TOK_GET(&t
, &ptr
, &cval
);
3138 if (t
== TOK_PPJOIN
)
3144 tok_str_new(¯o_str1
);
3146 //tok_print(" $$$", ptr0);
3147 for (ptr
= ptr0
;;) {
3148 TOK_GET(&t
, &ptr
, &cval
);
3151 if (t
== TOK_PPJOIN
)
3153 while (*ptr
== TOK_PPJOIN
) {
3155 /* given 'a##b', remove nosubsts preceding 'a' */
3156 if (start_of_nosubsts
>= 0)
3157 macro_str1
.len
= start_of_nosubsts
;
3158 /* given 'a##b', remove nosubsts preceding 'b' */
3159 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3161 if (t1
&& t1
!= TOK_PPJOIN
) {
3162 TOK_GET(&t1
, &ptr
, &cv1
);
3163 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3164 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3165 t
= tok
, cval
= tokc
;
3167 tok_str_add2(¯o_str1
, t
, &cval
);
3173 if (t
== TOK_NOSUBST
) {
3174 if (start_of_nosubsts
< 0)
3175 start_of_nosubsts
= macro_str1
.len
;
3177 start_of_nosubsts
= -1;
3179 tok_str_add2(¯o_str1
, t
, &cval
);
3181 tok_str_add(¯o_str1
, 0);
3182 //tok_print(" ###", macro_str1.str);
3183 return macro_str1
.str
;
3186 /* peek or read [ws_str == NULL] next token from function macro call,
3187 walking up macro levels up to the file if necessary */
3188 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3196 p
= macro_ptr
, t
= *p
;
3198 while (is_space(t
) || TOK_LINEFEED
== t
|| TOK_PLCHLDR
== t
)
3199 tok_str_add(ws_str
, t
), t
= *++p
;
3203 /* also, end of scope for nested defined symbol */
3205 while (sa
&& sa
->v
== 0)
3212 uint8_t *p
= file
->buf_ptr
;
3213 int ch
= handle_bs(&p
);
3215 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3220 p
= parse_comment(p
) - 1;
3221 } else if (c
== '/') {
3222 p
= parse_line_comment(p
) - 1;
3231 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3232 tok_str_add(ws_str
, ch
);
3247 /* do macro substitution of current token with macro 's' and add
3248 result to (tok_str,tok_len). 'nested_list' is the list of all
3249 macros we got inside to avoid recursing. Return non zero if no
3250 substitution needs to be done */
3251 static int macro_subst_tok(
3252 TokenString
*tok_str
,
3256 Sym
*args
, *sa
, *sa1
;
3257 int parlevel
, t
, t1
, spc
;
3263 /* if symbol is a macro, prepare substitution */
3264 /* special macros */
3265 if (tok
== TOK___LINE__
|| tok
== TOK___COUNTER__
) {
3266 t
= tok
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3267 snprintf(buf
, sizeof(buf
), "%d", t
);
3271 } else if (tok
== TOK___FILE__
) {
3272 cstrval
= file
->filename
;
3274 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3279 tm
= localtime(&ti
);
3280 if (tok
== TOK___DATE__
) {
3281 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3282 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3284 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3285 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3291 cstr_reset(&tokcstr
);
3292 cstr_cat(&tokcstr
, cstrval
, 0);
3293 cval
.str
.size
= tokcstr
.size
;
3294 cval
.str
.data
= tokcstr
.data
;
3295 tok_str_add2(tok_str
, t1
, &cval
);
3297 int saved_parse_flags
= parse_flags
;
3298 int *joined_str
= NULL
;
3301 if (s
->type
.t
== MACRO_FUNC
) {
3302 /* whitespace between macro name and argument list */
3304 tok_str_new(&ws_str
);
3307 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3308 | PARSE_FLAG_ACCEPT_STRAYS
;
3310 /* get next token from argument stream */
3311 t
= next_argstream(nested_list
, &ws_str
);
3313 /* not a macro substitution after all, restore the
3314 * macro token plus all whitespace we've read.
3315 * whitespace is intentionally not merged to preserve
3317 parse_flags
= saved_parse_flags
;
3318 tok_str_add(tok_str
, tok
);
3319 if (parse_flags
& PARSE_FLAG_SPACES
) {
3321 for (i
= 0; i
< ws_str
.len
; i
++)
3322 tok_str_add(tok_str
, ws_str
.str
[i
]);
3324 if (ws_str
.len
&& ws_str
.str
[ws_str
.len
- 1] == '\n')
3325 tok_flags
|= TOK_FLAG_BOL
;
3326 tok_str_free_str(ws_str
.str
);
3329 tok_str_free_str(ws_str
.str
);
3332 next_nomacro(); /* eat '(' */
3333 } while (tok
== TOK_PLCHLDR
|| is_space(tok
));
3335 /* argument macro */
3338 /* NOTE: empty args are allowed, except if no args */
3341 next_argstream(nested_list
, NULL
);
3342 } while (tok
== TOK_PLCHLDR
|| is_space(tok
) ||
3343 TOK_LINEFEED
== tok
);
3345 /* handle '()' case */
3346 if (!args
&& !sa
&& tok
== ')')
3349 tcc_error("macro '%s' used with too many args",
3350 get_tok_str(s
->v
, 0));
3353 /* NOTE: non zero sa->t indicates VA_ARGS */
3354 while ((parlevel
> 0 ||
3356 (tok
!= ',' || sa
->type
.t
)))) {
3357 if (tok
== TOK_EOF
|| tok
== 0)
3361 else if (tok
== ')')
3363 if (tok
== TOK_LINEFEED
)
3365 if (!check_space(tok
, &spc
))
3366 tok_str_add2(&str
, tok
, &tokc
);
3367 next_argstream(nested_list
, NULL
);
3372 tok_str_add(&str
, -1);
3373 tok_str_add(&str
, 0);
3374 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3378 /* special case for gcc var args: add an empty
3379 var arg argument if it is omitted */
3380 if (sa
&& sa
->type
.t
&& gnu_ext
)
3388 tcc_error("macro '%s' used with too few args",
3389 get_tok_str(s
->v
, 0));
3392 /* now subst each arg */
3393 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3398 tok_str_free_str(sa
->d
);
3400 tok_str_free_str(sa
->next
->d
);
3406 parse_flags
= saved_parse_flags
;
3409 sym_push2(nested_list
, s
->v
, 0, 0);
3410 parse_flags
= saved_parse_flags
;
3411 joined_str
= macro_twosharps(mstr
);
3412 macro_subst(tok_str
, nested_list
, joined_str
? joined_str
: mstr
);
3414 /* pop nested defined symbol */
3416 *nested_list
= sa1
->prev
;
3419 tok_str_free_str(joined_str
);
3421 tok_str_free_str(mstr
);
3426 /* do macro substitution of macro_str and add result to
3427 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3428 inside to avoid recursing. */
3429 static void macro_subst(
3430 TokenString
*tok_str
,
3432 const int *macro_str
3436 int t
, spc
, nosubst
;
3442 TOK_GET(&t
, ¯o_str
, &cval
);
3446 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3451 /* if nested substitution, do nothing */
3452 if (sym_find2(*nested_list
, t
)) {
3453 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3454 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3459 TokenString
*str
= tok_str_alloc();
3460 str
->str
= (int*)macro_str
;
3461 begin_macro(str
, 2);
3464 macro_subst_tok(tok_str
, nested_list
, s
);
3466 if (macro_stack
!= str
) {
3467 /* already finished by reading function macro arguments */
3471 macro_str
= macro_ptr
;
3475 spc
= is_space(t
= tok_str
->str
[tok_str
->lastlen
]);
3478 if (!check_space(t
, &spc
))
3479 tok_str_add2(tok_str
, t
, &cval
);
3482 if (nosubst
> 1 && (spc
|| (++nosubst
== 3 && t
== '(')))
3486 if (t
== TOK_NOSUBST
)
3489 /* GCC supports 'defined' as result of a macro substitution */
3490 if (t
== TOK_DEFINED
&& pp_expr
)
3495 /* return next token without macro substitution. Can read input from
3497 static void next_nomacro(void)
3503 if (TOK_HAS_VALUE(t
)) {
3504 tok_get(&tok
, ¯o_ptr
, &tokc
);
3505 if (t
== TOK_LINENUM
) {
3506 file
->line_num
= tokc
.i
;
3511 if (t
< TOK_IDENT
) {
3512 if (!(parse_flags
& PARSE_FLAG_SPACES
)
3513 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
))
3523 /* return next token with macro substitution */
3524 ST_FUNC
void next(void)
3531 if (!TOK_HAS_VALUE(t
)) {
3532 if (t
== TOK_NOSUBST
|| t
== TOK_PLCHLDR
) {
3533 /* discard preprocessor markers */
3535 } else if (t
== 0) {
3536 /* end of macro or unget token string */
3539 } else if (t
== '\\') {
3540 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3541 tcc_error("stray '\\' in program");
3545 } else if (t
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3546 /* if reading from file, try to substitute macros */
3547 Sym
*s
= define_find(t
);
3549 Sym
*nested_list
= NULL
;
3551 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3552 tok_str_add(&tokstr_buf
, 0);
3553 begin_macro(&tokstr_buf
, 0);
3558 /* convert preprocessor tokens into C tokens */
3559 if (t
== TOK_PPNUM
) {
3560 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3561 parse_number((char *)tokc
.str
.data
);
3562 } else if (t
== TOK_PPSTR
) {
3563 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3564 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3568 /* push back current token and set current token to 'last_tok'. Only
3569 identifier case handled for labels. */
3570 ST_INLN
void unget_tok(int last_tok
)
3573 TokenString
*str
= tok_str_alloc();
3574 tok_str_add2(str
, tok
, &tokc
);
3575 tok_str_add(str
, 0);
3576 begin_macro(str
, 1);
3580 /* ------------------------------------------------------------------------- */
3581 /* init preprocessor */
3583 static const char * const target_os_defs
=
3584 #ifdef TCC_TARGET_PE
3590 # if defined TCC_TARGET_MACHO
3592 # elif TARGETOS_FreeBSD
3594 # elif TARGETOS_FreeBSD_kernel
3595 "__FreeBSD_kernel__\0"
3596 # elif TARGETOS_NetBSD
3598 # elif TARGETOS_OpenBSD
3603 # if TARGETOS_ANDROID
3612 static void putdef(CString
*cs
, const char *p
)
3614 cstr_printf(cs
, "#define %s%s\n", p
, &" 1"[!!strchr(p
, ' ')*2]);
3617 static void putdefs(CString
*cs
, const char *p
)
3620 putdef(cs
, p
), p
= strchr(p
, 0) + 1;
3623 static void tcc_predefs(TCCState
*s1
, CString
*cs
, int is_asm
)
3627 sscanf(TCC_VERSION
, "%d.%d.%d", &a
, &b
, &c
);
3628 cstr_printf(cs
, "#define __TINYC__ %d\n", a
*10000 + b
*100 + c
);
3630 putdefs(cs
, target_machine_defs
);
3631 putdefs(cs
, target_os_defs
);
3633 #ifdef TCC_TARGET_ARM
3634 if (s1
->float_abi
== ARM_HARD_FLOAT
)
3635 putdef(cs
, "__ARM_PCS_VFP");
3638 putdef(cs
, "__ASSEMBLER__");
3639 if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
)
3640 putdef(cs
, "__TCC_PP__");
3641 if (s1
->output_type
== TCC_OUTPUT_MEMORY
)
3642 putdef(cs
, "__TCC_RUN__");
3643 #ifdef CONFIG_TCC_BACKTRACE
3644 if (s1
->do_backtrace
)
3645 putdef(cs
, "__TCC_BACKTRACE__");
3647 #ifdef CONFIG_TCC_BCHECK
3648 if (s1
->do_bounds_check
)
3649 putdef(cs
, "__TCC_BCHECK__");
3651 if (s1
->char_is_unsigned
)
3652 putdef(cs
, "__CHAR_UNSIGNED__");
3653 if (s1
->optimize
> 0)
3654 putdef(cs
, "__OPTIMIZE__");
3655 if (s1
->option_pthread
)
3656 putdef(cs
, "_REENTRANT");
3657 if (s1
->leading_underscore
)
3658 putdef(cs
, "__leading_underscore");
3659 cstr_printf(cs
, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE
);
3660 cstr_printf(cs
, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE
);
3662 putdef(cs
, "__STDC__");
3663 cstr_printf(cs
, "#define __STDC_VERSION__ %dL\n", s1
->cversion
);
3665 /* load more predefs and __builtins */
3666 #if CONFIG_TCC_PREDEFS
3667 #include "tccdefs_.h" /* include as strings */
3669 "#include <tccdefs.h>\n" /* load at runtime */
3673 cstr_printf(cs
, "#define __BASE_FILE__ \"%s\"\n", file
->filename
);
3676 ST_FUNC
void preprocess_start(TCCState
*s1
, int filetype
)
3678 int is_asm
= !!(filetype
& (AFF_TYPE_ASM
|AFF_TYPE_ASMPP
));
3682 s1
->include_stack_ptr
= s1
->include_stack
;
3683 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3684 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3687 pp_debug_tok
= pp_debug_symv
= 0;
3689 s1
->pack_stack
[0] = 0;
3690 s1
->pack_stack_ptr
= s1
->pack_stack
;
3692 set_idnum('$', !is_asm
&& s1
->dollars_in_identifiers
? IS_ID
: 0);
3693 set_idnum('.', is_asm
? IS_ID
: 0);
3695 if (!(filetype
& AFF_TYPE_ASM
)) {
3698 tcc_predefs(s1
, &cstr
, is_asm
);
3699 if (s1
->cmdline_defs
.size
)
3700 cstr_cat(&cstr
, s1
->cmdline_defs
.data
, s1
->cmdline_defs
.size
);
3701 if (s1
->cmdline_incl
.size
)
3702 cstr_cat(&cstr
, s1
->cmdline_incl
.data
, s1
->cmdline_incl
.size
);
3703 //printf("%s\n", (char*)cstr.data);
3704 *s1
->include_stack_ptr
++ = file
;
3705 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3706 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3710 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3711 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3714 /* cleanup from error/setjmp */
3715 ST_FUNC
void preprocess_end(TCCState
*s1
)
3725 ST_FUNC
int set_idnum(int c
, int val
)
3727 int prev
= isidnum_table
[c
- CH_EOF
];
3728 isidnum_table
[c
- CH_EOF
] = val
;
3732 ST_FUNC
void tccpp_new(TCCState
*s
)
3737 /* init isid table */
3738 for(i
= CH_EOF
; i
<128; i
++)
3740 is_space(i
) ? IS_SPC
3745 for(i
= 128; i
<256; i
++)
3746 set_idnum(i
, IS_ID
);
3748 /* init allocators */
3749 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3750 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3752 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3753 memset(s
->cached_includes_hash
, 0, sizeof s
->cached_includes_hash
);
3756 cstr_new(&cstr_buf
);
3757 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3758 tok_str_new(&tokstr_buf
);
3759 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3761 tok_ident
= TOK_IDENT
;
3770 tok_alloc(p
, r
- p
- 1);
3774 /* we add dummy defines for some special macros to speed up tests
3775 and to have working defined() */
3776 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
3777 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
3778 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
3779 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
3780 define_push(TOK___COUNTER__
, MACRO_OBJ
, NULL
, NULL
);
3783 ST_FUNC
void tccpp_delete(TCCState
*s
)
3787 dynarray_reset(&s
->cached_includes
, &s
->nb_cached_includes
);
3790 n
= tok_ident
- TOK_IDENT
;
3791 if (n
> total_idents
)
3793 for(i
= 0; i
< n
; i
++)
3794 tal_free(toksym_alloc
, table_ident
[i
]);
3795 tcc_free(table_ident
);
3798 /* free static buffers */
3799 cstr_free(&tokcstr
);
3800 cstr_free(&cstr_buf
);
3801 tok_str_free_str(tokstr_buf
.str
);
3803 /* free allocators */
3804 tal_delete(toksym_alloc
);
3805 toksym_alloc
= NULL
;
3806 tal_delete(tokstr_alloc
);
3807 tokstr_alloc
= NULL
;
3810 /* ------------------------------------------------------------------------- */
3811 /* tcc -E [-P[1]] [-dD} support */
3813 static void tok_print(const char *msg
, const int *str
)
3819 fp
= tcc_state
->ppfp
;
3820 fprintf(fp
, "%s", msg
);
3822 TOK_GET(&t
, &str
, &cval
);
3825 fprintf(fp
, &" %s"[s
], get_tok_str(t
, &cval
)), s
= 1;
3830 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3832 int d
= f
->line_num
- f
->line_ref
;
3837 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3839 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3841 fputs("\n", s1
->ppfp
), --d
;
3842 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3843 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3845 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3846 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3848 f
->line_ref
= f
->line_num
;
3851 static void define_print(TCCState
*s1
, int v
)
3857 if (NULL
== s
|| NULL
== s
->d
)
3861 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3862 if (s
->type
.t
== MACRO_FUNC
) {
3867 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3874 tok_print("", s
->d
);
3877 static void pp_debug_defines(TCCState
*s1
)
3888 pp_line(s1
, file
, 0);
3889 file
->line_ref
= ++file
->line_num
;
3893 vs
= get_tok_str(v
, NULL
);
3894 if (t
== TOK_DEFINE
) {
3895 define_print(s1
, v
);
3896 } else if (t
== TOK_UNDEF
) {
3897 fprintf(fp
, "#undef %s\n", vs
);
3898 } else if (t
== TOK_push_macro
) {
3899 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3900 } else if (t
== TOK_pop_macro
) {
3901 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3906 static void pp_debug_builtins(TCCState
*s1
)
3909 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3910 define_print(s1
, v
);
3913 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3914 static int pp_need_space(int a
, int b
)
3916 return 'E' == a
? '+' == b
|| '-' == b
3917 : '+' == a
? TOK_INC
== b
|| '+' == b
3918 : '-' == a
? TOK_DEC
== b
|| '-' == b
3919 : a
>= TOK_IDENT
? b
>= TOK_IDENT
3920 : a
== TOK_PPNUM
? b
>= TOK_IDENT
3924 /* maybe hex like 0x1e */
3925 static int pp_check_he0xE(int t
, const char *p
)
3927 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3932 /* Preprocess the current file */
3933 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3935 BufferedFile
**iptr
;
3936 int token_seen
, spcs
, level
;
3940 parse_flags
= PARSE_FLAG_PREPROCESS
3941 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3942 | PARSE_FLAG_LINEFEED
3944 | PARSE_FLAG_ACCEPT_STRAYS
3946 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3947 capability to compile and run itself, provided all numbers are
3948 given as decimals. tcc -E -P10 will do. */
3949 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
3950 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
3953 /* for PP benchmarks */
3954 do next(); while (tok
!= TOK_EOF
);
3958 if (s1
->dflag
& 1) {
3959 pp_debug_builtins(s1
);
3963 token_seen
= TOK_LINEFEED
, spcs
= 0, level
= 0;
3965 pp_line(s1
, file
->prev
, level
++);
3966 pp_line(s1
, file
, level
);
3968 iptr
= s1
->include_stack_ptr
;
3973 level
= s1
->include_stack_ptr
- iptr
;
3976 pp_line(s1
, *iptr
, 0);
3977 pp_line(s1
, file
, level
);
3979 if (s1
->dflag
& 7) {
3980 pp_debug_defines(s1
);
3985 if (is_space(tok
)) {
3986 if (spcs
< sizeof white
- 1)
3987 white
[spcs
++] = tok
;
3989 } else if (tok
== TOK_LINEFEED
) {
3991 if (token_seen
== TOK_LINEFEED
)
3994 } else if (token_seen
== TOK_LINEFEED
) {
3995 pp_line(s1
, file
, 0);
3996 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
3997 white
[spcs
++] = ' ';
4000 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
4001 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
4002 token_seen
= pp_check_he0xE(tok
, p
);
4007 /* ------------------------------------------------------------------------- */