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
;
44 /* ------------------------------------------------------------------------- */
46 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
47 static char token_buf
[STRING_MAX_SIZE
+ 1];
48 static CString cstr_buf
;
49 static TokenString tokstr_buf
;
50 static TokenString unget_buf
;
51 static unsigned char isidnum_table
[256 - CH_EOF
];
52 static int pp_debug_tok
, pp_debug_symv
;
53 static int pp_counter
;
54 static void tok_print(const int *str
, const char *msg
, ...);
55 static void next_nomacro(void);
57 static struct TinyAlloc
*toksym_alloc
;
58 static struct TinyAlloc
*tokstr_alloc
;
60 static TokenString
*macro_stack
;
62 static const char tcc_keywords
[] =
63 #define DEF(id, str) str "\0"
68 /* WARNING: the content of this string encodes token numbers */
69 static const unsigned char tok_two_chars
[] =
71 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
72 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
94 '#','#', TOK_TWOSHARPS
,
99 ST_FUNC
void skip(int c
)
103 pstrcpy(tmp
, sizeof tmp
, get_tok_str(c
, &tokc
));
104 tcc_error("'%s' expected (got \"%s\")", tmp
, get_tok_str(tok
, &tokc
));
109 ST_FUNC
void expect(const char *msg
)
111 tcc_error("%s expected", msg
);
114 /* ------------------------------------------------------------------------- */
115 /* Custom allocator for tiny objects */
120 #define tal_free(al, p) tcc_free(p)
121 #define tal_realloc(al, p, size) tcc_realloc(p, size)
122 #define tal_new(a,b,c)
123 #define tal_delete(a)
125 #if !defined(MEM_DEBUG)
126 #define tal_free(al, p) tal_free_impl(al, p)
127 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
128 #define TAL_DEBUG_PARAMS
130 #define TAL_DEBUG MEM_DEBUG
131 //#define TAL_INFO 1 /* collect and dump allocators stats */
132 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
133 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
134 #define TAL_DEBUG_PARAMS , const char *file, int line
135 #define TAL_DEBUG_FILE_LEN 40
138 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
139 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
140 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
141 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
142 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
143 #define CSTR_TAL_LIMIT 1024
145 typedef struct TinyAlloc
{
151 struct TinyAlloc
*next
, *top
;
160 typedef struct tal_header_t
{
163 int line_num
; /* negative line_num used for double free check */
164 char file_name
[TAL_DEBUG_FILE_LEN
+ 1];
168 /* ------------------------------------------------------------------------- */
170 static TinyAlloc
*tal_new(TinyAlloc
**pal
, unsigned limit
, unsigned size
)
172 TinyAlloc
*al
= tcc_mallocz(sizeof(TinyAlloc
));
173 al
->p
= al
->buffer
= tcc_malloc(size
);
180 static void tal_delete(TinyAlloc
*al
)
188 fprintf(stderr
, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
189 al
->limit
, al
->size
/ 1024.0 / 1024.0, al
->nb_peak
, al
->nb_total
, al
->nb_missed
,
190 (al
->peak_p
- al
->buffer
) * 100.0 / al
->size
);
192 #if TAL_DEBUG && TAL_DEBUG != 3 /* do not check TAL leaks with -DMEM_DEBUG=3 */
193 if (al
->nb_allocs
> 0) {
195 fprintf(stderr
, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
196 al
->nb_allocs
, al
->limit
);
199 tal_header_t
*header
= (tal_header_t
*)p
;
200 if (header
->line_num
> 0) {
201 fprintf(stderr
, "%s:%d: chunk of %d bytes leaked\n",
202 header
->file_name
, header
->line_num
, header
->size
);
204 p
+= header
->size
+ sizeof(tal_header_t
);
212 tcc_free(al
->buffer
);
218 static void tal_free_impl(TinyAlloc
*al
, void *p TAL_DEBUG_PARAMS
)
223 if (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
) {
225 tal_header_t
*header
= (((tal_header_t
*)p
) - 1);
226 if (header
->line_num
< 0) {
227 fprintf(stderr
, "%s:%d: TAL_DEBUG: double frees chunk from\n",
229 fprintf(stderr
, "%s:%d: %d bytes\n",
230 header
->file_name
, (int)-header
->line_num
, (int)header
->size
);
232 header
->line_num
= -header
->line_num
;
237 } else if (al
->next
) {
245 static void *tal_realloc_impl(TinyAlloc
**pal
, void *p
, unsigned size TAL_DEBUG_PARAMS
)
247 tal_header_t
*header
;
250 unsigned adj_size
= (size
+ 3) & -4;
251 TinyAlloc
*al
= *pal
;
254 is_own
= (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
);
255 if ((!p
|| is_own
) && size
<= al
->limit
) {
256 if (al
->p
- al
->buffer
+ adj_size
+ sizeof(tal_header_t
) < al
->size
) {
257 header
= (tal_header_t
*)al
->p
;
258 header
->size
= adj_size
;
260 { int ofs
= strlen(file
) - TAL_DEBUG_FILE_LEN
;
261 strncpy(header
->file_name
, file
+ (ofs
> 0 ? ofs
: 0), TAL_DEBUG_FILE_LEN
);
262 header
->file_name
[TAL_DEBUG_FILE_LEN
] = 0;
263 header
->line_num
= line
; }
265 ret
= al
->p
+ sizeof(tal_header_t
);
266 al
->p
+= adj_size
+ sizeof(tal_header_t
);
268 header
= (((tal_header_t
*)p
) - 1);
269 if (p
) memcpy(ret
, p
, header
->size
);
271 header
->line_num
= -header
->line_num
;
277 if (al
->nb_peak
< al
->nb_allocs
)
278 al
->nb_peak
= al
->nb_allocs
;
279 if (al
->peak_p
< al
->p
)
286 ret
= tal_realloc(*pal
, 0, size
);
287 header
= (((tal_header_t
*)p
) - 1);
288 if (p
) memcpy(ret
, p
, header
->size
);
290 header
->line_num
= -header
->line_num
;
297 TinyAlloc
*bottom
= al
, *next
= al
->top
? al
->top
: al
;
299 al
= tal_new(pal
, next
->limit
, next
->size
* 2);
307 ret
= tcc_malloc(size
);
308 header
= (((tal_header_t
*)p
) - 1);
309 if (p
) memcpy(ret
, p
, header
->size
);
311 header
->line_num
= -header
->line_num
;
313 } else if (al
->next
) {
317 ret
= tcc_realloc(p
, size
);
326 /* ------------------------------------------------------------------------- */
327 /* CString handling */
328 static void cstr_realloc(CString
*cstr
, int new_size
)
332 size
= cstr
->size_allocated
;
334 size
= 8; /* no need to allocate a too small first string */
335 while (size
< new_size
)
337 cstr
->data
= tcc_realloc(cstr
->data
, size
);
338 cstr
->size_allocated
= size
;
342 ST_INLN
void cstr_ccat(CString
*cstr
, int ch
)
345 size
= cstr
->size
+ 1;
346 if (size
> cstr
->size_allocated
)
347 cstr_realloc(cstr
, size
);
348 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
352 ST_INLN
char *unicode_to_utf8 (char *b
, uint32_t Uc
)
354 if (Uc
<0x80) *b
++=Uc
;
355 else if (Uc
<0x800) *b
++=192+Uc
/64, *b
++=128+Uc
%64;
356 else if (Uc
-0xd800u
<0x800) goto error
;
357 else if (Uc
<0x10000) *b
++=224+Uc
/4096, *b
++=128+Uc
/64%64, *b
++=128+Uc
%64;
358 else if (Uc
<0x110000) *b
++=240+Uc
/262144, *b
++=128+Uc
/4096%64, *b
++=128+Uc
/64%64, *b
++=128+Uc
%64;
359 else error
: tcc_error("0x%x is not a valid universal character", Uc
);
363 /* add a unicode character expanded into utf8 */
364 ST_INLN
void cstr_u8cat(CString
*cstr
, int ch
)
367 e
= unicode_to_utf8(buf
, (uint32_t)ch
);
368 cstr_cat(cstr
, buf
, e
- buf
);
371 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
, int len
)
375 len
= strlen(str
) + 1 + len
;
376 size
= cstr
->size
+ len
;
377 if (size
> cstr
->size_allocated
)
378 cstr_realloc(cstr
, size
);
379 memmove(((unsigned char *)cstr
->data
) + cstr
->size
, str
, len
);
383 /* add a wide char */
384 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
387 size
= cstr
->size
+ sizeof(nwchar_t
);
388 if (size
> cstr
->size_allocated
)
389 cstr_realloc(cstr
, size
);
390 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
394 ST_FUNC
void cstr_new(CString
*cstr
)
396 memset(cstr
, 0, sizeof(CString
));
399 /* free string and reset it to NULL */
400 ST_FUNC
void cstr_free(CString
*cstr
)
402 tcc_free(cstr
->data
);
405 /* reset string to empty */
406 ST_FUNC
void cstr_reset(CString
*cstr
)
411 ST_FUNC
int cstr_vprintf(CString
*cstr
, const char *fmt
, va_list ap
)
417 if (size
> cstr
->size_allocated
)
418 cstr_realloc(cstr
, size
);
419 size
= cstr
->size_allocated
- cstr
->size
;
421 len
= vsnprintf((char*)cstr
->data
+ cstr
->size
, size
, fmt
, v
);
423 if (len
>= 0 && len
< size
)
431 ST_FUNC
int cstr_printf(CString
*cstr
, const char *fmt
, ...)
435 len
= cstr_vprintf(cstr
, fmt
, ap
);
441 static void add_char(CString
*cstr
, int c
)
443 if (c
== '\'' || c
== '\"' || c
== '\\') {
444 /* XXX: could be more precise if char or string */
445 cstr_ccat(cstr
, '\\');
447 if (c
>= 32 && c
<= 126) {
450 cstr_ccat(cstr
, '\\');
452 cstr_ccat(cstr
, 'n');
454 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
455 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
456 cstr_ccat(cstr
, '0' + (c
& 7));
461 /* ------------------------------------------------------------------------- */
462 /* allocate a new token */
463 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
465 TokenSym
*ts
, **ptable
;
468 if (tok_ident
>= SYM_FIRST_ANOM
)
469 tcc_error("memory full (symbols)");
471 /* expand token table if needed */
472 i
= tok_ident
- TOK_IDENT
;
473 if ((i
% TOK_ALLOC_INCR
) == 0) {
474 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
475 table_ident
= ptable
;
478 ts
= tal_realloc(toksym_alloc
, 0, sizeof(TokenSym
) + len
);
480 ts
->tok
= tok_ident
++;
481 ts
->sym_define
= NULL
;
482 ts
->sym_label
= NULL
;
483 ts
->sym_struct
= NULL
;
484 ts
->sym_identifier
= NULL
;
486 ts
->hash_next
= NULL
;
487 memcpy(ts
->str
, str
, len
);
493 #define TOK_HASH_INIT 1
494 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
497 /* find a token and add it if not found */
498 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
506 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
507 h
&= (TOK_HASH_SIZE
- 1);
509 pts
= &hash_ident
[h
];
514 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
516 pts
= &(ts
->hash_next
);
518 return tok_alloc_new(pts
, str
, len
);
521 ST_FUNC
int tok_alloc_const(const char *str
)
523 return tok_alloc(str
, strlen(str
))->tok
;
527 /* XXX: buffer overflow */
528 /* XXX: float tokens */
529 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
534 cstr_reset(&cstr_buf
);
544 /* XXX: not quite exact, but only useful for testing */
546 sprintf(p
, "%u", (unsigned)cv
->i
);
548 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
552 cstr_ccat(&cstr_buf
, 'L');
554 cstr_ccat(&cstr_buf
, '\'');
555 add_char(&cstr_buf
, cv
->i
);
556 cstr_ccat(&cstr_buf
, '\'');
557 cstr_ccat(&cstr_buf
, '\0');
561 return (char*)cv
->str
.data
;
563 cstr_ccat(&cstr_buf
, 'L');
565 cstr_ccat(&cstr_buf
, '\"');
567 len
= cv
->str
.size
- 1;
569 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
571 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
573 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
575 cstr_ccat(&cstr_buf
, '\"');
576 cstr_ccat(&cstr_buf
, '\0');
580 return strcpy(p
, "<float>");
582 return strcpy(p
, "<double>");
584 return strcpy(p
, "<long double>");
586 return strcpy(p
, "<linenumber>");
588 /* above tokens have value, the ones below don't */
596 return strcpy(p
, "...");
598 return strcpy(p
, "<<=");
600 return strcpy(p
, ">>=");
602 return strcpy(p
, "<eof>");
603 case 0: /* anonymous nameless symbols */
604 return strcpy(p
, "<no name>");
606 v
&= ~(SYM_FIELD
| SYM_STRUCT
);
608 /* search in two bytes table */
609 const unsigned char *q
= tok_two_chars
;
615 return cstr_buf
.data
;
619 if (v
>= 127 || (v
< 32 && !is_space(v
) && v
!= '\n')) {
620 sprintf(p
, "<\\x%02x>", v
);
626 } else if (v
< tok_ident
) {
627 return table_ident
[v
- TOK_IDENT
]->str
;
628 } else if (v
>= SYM_FIRST_ANOM
) {
629 /* special name for anonymous symbol */
630 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
632 /* should never happen */
637 return cstr_buf
.data
;
640 /* return the current character, handling end of block if necessary
642 static int handle_eob(void)
644 BufferedFile
*bf
= file
;
647 /* only tries to read if really end of buffer */
648 if (bf
->buf_ptr
>= bf
->buf_end
) {
650 #if defined(PARSE_DEBUG)
655 len
= read(bf
->fd
, bf
->buffer
, len
);
662 bf
->buf_ptr
= bf
->buffer
;
663 bf
->buf_end
= bf
->buffer
+ len
;
664 *bf
->buf_end
= CH_EOB
;
666 if (bf
->buf_ptr
< bf
->buf_end
) {
667 return bf
->buf_ptr
[0];
669 bf
->buf_ptr
= bf
->buf_end
;
674 /* read next char from current input file and handle end of input buffer */
675 static int next_c(void)
677 int ch
= *++file
->buf_ptr
;
678 /* end of buffer/file handling */
679 if (ch
== CH_EOB
&& file
->buf_ptr
>= file
->buf_end
)
684 /* input with '\[\r]\n' handling. */
685 static int handle_stray_noerror(int err
)
688 while ((ch
= next_c()) == '\\') {
698 *--file
->buf_ptr
= '\r';
701 tcc_error("stray '\\' in program");
702 /* may take advantage of 'BufferedFile.unget[4}' */
703 return *--file
->buf_ptr
= '\\';
709 #define ninp() handle_stray_noerror(0)
711 /* handle '\\' in strings, comments and skipped regions */
712 static int handle_bs(uint8_t **p
)
715 file
->buf_ptr
= *p
- 1;
721 /* skip the stray and handle the \\n case. Output an error if
722 incorrect char after the stray */
723 static int handle_stray(uint8_t **p
)
726 file
->buf_ptr
= *p
- 1;
727 c
= handle_stray_noerror(!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
));
732 /* handle the complicated stray case */
737 c = handle_stray(&p); \
740 static int skip_spaces(void)
746 } while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
);
750 /* single line C++ comments */
751 static uint8_t *parse_line_comment(uint8_t *p
)
758 if (c
== '\n' || c
== '\\')
761 if (c
== '\n' || c
== '\\')
776 static uint8_t *parse_comment(uint8_t *p
)
784 if (c
== '\n' || c
== '*' || c
== '\\')
787 if (c
== '\n' || c
== '*' || c
== '\\')
790 /* now we can handle all the cases */
793 } else if (c
== '*') {
806 tcc_error("unexpected end of file in comment");
814 /* parse a string without interpreting escapes */
815 static uint8_t *parse_pp_string(uint8_t *p
, int sep
, CString
*str
)
823 } else if (c
== '\\') {
827 /* XXX: indicate line number of start of string */
828 tok_flags
&= ~TOK_FLAG_BOL
;
829 tcc_error("missing terminating %c character", sep
);
830 } else if (c
== '\\') {
834 /* add char after '\\' unconditionally */
838 goto unterminated_string
;
844 } else if (c
== '\n') {
846 if (ACCEPT_LF_IN_STRINGS
) {
849 } else if (str
) { /* not skipping */
850 goto unterminated_string
;
852 //tcc_warning("missing terminating %c character", sep);
855 } else if (c
== '\r') {
862 goto unterminated_string
;
864 cstr_ccat(str
, '\r');
876 /* skip block of text until #else, #elif or #endif. skip also pairs of
878 static void preprocess_skip(void)
880 int a
, start_of_line
, c
, in_warn_or_error
;
887 in_warn_or_error
= 0;
913 if (in_warn_or_error
)
915 tok_flags
&= ~TOK_FLAG_BOL
;
916 p
= parse_pp_string(p
, c
, NULL
);
920 if (in_warn_or_error
)
925 p
= parse_comment(p
);
926 } else if (c
== '/') {
927 p
= parse_line_comment(p
);
937 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
939 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
941 else if (tok
== TOK_ENDIF
)
943 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
944 in_warn_or_error
= 1;
945 else if (tok
== TOK_LINEFEED
)
947 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
948 p
= parse_line_comment(p
- 1);
950 #if !defined(TCC_TARGET_ARM)
951 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
952 p
= parse_line_comment(p
- 1);
954 /* ARM assembly uses '#' for constants */
969 /* return the number of additional 'ints' necessary to store the
971 static inline int tok_size(const int *p
)
986 return 1 + 1 + (p
[1] + 3) / 4;
989 return 1 + LONG_SIZE
/ 4;
995 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
998 return 1 + LDOUBLE_SIZE
/ 4;
1006 /* token string handling */
1007 ST_INLN
void tok_str_new(TokenString
*s
)
1010 s
->len
= s
->need_spc
= 0;
1011 s
->allocated_len
= 0;
1012 s
->last_line_num
= -1;
1015 ST_FUNC TokenString
*tok_str_alloc(void)
1017 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1022 ST_FUNC
void tok_str_free_str(int *str
)
1024 tal_free(tokstr_alloc
, str
);
1027 ST_FUNC
void tok_str_free(TokenString
*str
)
1029 tok_str_free_str(str
->str
);
1030 tal_free(tokstr_alloc
, str
);
1033 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1037 size
= s
->allocated_len
;
1040 while (size
< new_size
)
1042 if (size
> s
->allocated_len
) {
1043 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1044 s
->allocated_len
= size
;
1050 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1056 if (len
>= s
->allocated_len
)
1057 str
= tok_str_realloc(s
, len
+ 1);
1062 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1065 str
->prev
= macro_stack
;
1066 str
->prev_ptr
= macro_ptr
;
1067 str
->save_line_num
= file
->line_num
;
1068 macro_ptr
= str
->str
;
1072 ST_FUNC
void end_macro(void)
1074 TokenString
*str
= macro_stack
;
1075 macro_stack
= str
->prev
;
1076 macro_ptr
= str
->prev_ptr
;
1077 file
->line_num
= str
->save_line_num
;
1078 if (str
->alloc
== 0) {
1079 /* matters if str not alloced, may be tokstr_buf */
1080 str
->len
= str
->need_spc
= 0;
1082 if (str
->alloc
== 2)
1083 str
->str
= NULL
; /* don't free */
1088 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1095 /* allocate space for worst case */
1096 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1097 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1110 str
[len
++] = cv
->tab
[0];
1117 /* Insert the string into the int array. */
1119 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1120 if (len
+ nb_words
>= s
->allocated_len
)
1121 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1122 str
[len
] = cv
->str
.size
;
1123 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1134 str
[len
++] = cv
->tab
[0];
1135 str
[len
++] = cv
->tab
[1];
1138 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1139 str
[len
++] = cv
->tab
[0];
1140 str
[len
++] = cv
->tab
[1];
1141 #elif LDOUBLE_SIZE == 12
1142 str
[len
++] = cv
->tab
[0];
1143 str
[len
++] = cv
->tab
[1];
1144 str
[len
++] = cv
->tab
[2];
1145 #elif LDOUBLE_SIZE == 16
1146 str
[len
++] = cv
->tab
[0];
1147 str
[len
++] = cv
->tab
[1];
1148 str
[len
++] = cv
->tab
[2];
1149 str
[len
++] = cv
->tab
[3];
1151 #error add long double size support
1160 /* add the current parse token in token string 's' */
1161 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1165 /* save line number info */
1166 if (file
->line_num
!= s
->last_line_num
) {
1167 s
->last_line_num
= file
->line_num
;
1168 cval
.i
= s
->last_line_num
;
1169 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1171 tok_str_add2(s
, tok
, &tokc
);
1174 /* like tok_str_add2(), add a space if needed */
1175 static void tok_str_add2_spc(TokenString
*s
, int t
, CValue
*cv
)
1177 if (s
->need_spc
== 3)
1178 tok_str_add(s
, ' ');
1180 tok_str_add2(s
, t
, cv
);
1183 /* get a token from an integer array and increment pointer. */
1184 static inline void tok_get(int *t
, const int **pp
, CValue
*cv
)
1204 cv
->i
= (unsigned)*p
++;
1213 cv
->str
.size
= *p
++;
1215 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1227 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1229 #elif LDOUBLE_SIZE == 12
1231 #elif LDOUBLE_SIZE == 16
1234 # error add long double size support
1248 # define TOK_GET(t,p,c) tok_get(t,p,c)
1250 # define TOK_GET(t,p,c) do { \
1252 if (TOK_HAS_VALUE(_t)) \
1255 *(t) = _t, ++*(p); \
1259 static int macro_is_equal(const int *a
, const int *b
)
1268 cstr_reset(&tokcstr
);
1269 TOK_GET(&t
, &a
, &cv
);
1270 cstr_cat(&tokcstr
, get_tok_str(t
, &cv
), 0);
1271 TOK_GET(&t
, &b
, &cv
);
1272 if (strcmp(tokcstr
.data
, get_tok_str(t
, &cv
)))
1278 /* defines handling */
1279 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1284 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1286 s
->next
= first_arg
;
1287 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1289 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1290 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1293 /* undefined a define symbol. Its name is just set to zero */
1294 ST_FUNC
void define_undef(Sym
*s
)
1297 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1298 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1301 ST_INLN Sym
*define_find(int v
)
1304 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1306 return table_ident
[v
]->sym_define
;
1309 /* free define stack until top reaches 'b' */
1310 ST_FUNC
void free_defines(Sym
*b
)
1312 while (define_stack
!= b
) {
1313 Sym
*top
= define_stack
;
1314 define_stack
= top
->prev
;
1315 tok_str_free_str(top
->d
);
1321 /* fake the nth "#if defined test_..." for tcc -dt -run */
1322 static void maybe_run_test(TCCState
*s
)
1325 if (s
->include_stack_ptr
!= s
->include_stack
)
1327 p
= get_tok_str(tok
, NULL
);
1328 if (0 != memcmp(p
, "test_", 5))
1330 if (0 != --s
->run_test
)
1332 fprintf(s
->ppfp
, &"\n[%s]\n"[!(s
->dflag
& 32)], p
), fflush(s
->ppfp
);
1333 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1336 static CachedInclude
*
1337 search_cached_include(TCCState
*s1
, const char *filename
, int add
);
1339 static int parse_include(TCCState
*s1
, int do_next
, int test
)
1342 char name
[1024], buf
[1024], *p
;
1346 if (c
== '<' || c
== '\"') {
1347 cstr_reset(&tokcstr
);
1348 file
->buf_ptr
= parse_pp_string(file
->buf_ptr
, c
== '<' ? '>' : c
, &tokcstr
);
1350 pstrncpy(name
, tokcstr
.data
, i
>= sizeof name
? sizeof name
- 1 : i
);
1353 /* computed #include : concatenate tokens until result is one of
1354 the two accepted forms. Don't convert pp-tokens to tokens here. */
1355 parse_flags
= PARSE_FLAG_PREPROCESS
1356 | PARSE_FLAG_LINEFEED
1357 | (parse_flags
& PARSE_FLAG_ASM_FILE
);
1361 p
= name
, i
= strlen(p
) - 1;
1363 && ((p
[0] == '"' && p
[i
] == '"')
1364 || (p
[0] == '<' && p
[i
] == '>')))
1366 if (tok
== TOK_LINEFEED
)
1367 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1368 pstrcat(name
, sizeof name
, get_tok_str(tok
, &tokc
));
1371 /* remove '<>|""' */
1372 memmove(p
, p
+ 1, i
- 1), p
[i
- 1] = 0;
1375 i
= do_next
? file
->include_next_index
: -1;
1379 /* check absolute include path */
1380 if (!IS_ABSPATH(name
))
1383 } else if (i
== 1) {
1384 /* search in file's dir if "header.h" */
1387 p
= file
->true_filename
;
1388 pstrncpy(buf
, p
, tcc_basename(p
) - p
);
1390 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1392 p
= s1
->include_paths
[j
];
1393 else if (k
< s1
->nb_sysinclude_paths
)
1394 p
= s1
->sysinclude_paths
[k
];
1398 tcc_error("include file '%s' not found", name
);
1399 pstrcpy(buf
, sizeof buf
, p
);
1400 pstrcat(buf
, sizeof buf
, "/");
1402 pstrcat(buf
, sizeof buf
, name
);
1403 e
= search_cached_include(s1
, buf
, 0);
1404 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
)) {
1405 /* no need to parse the include because the 'ifndef macro'
1406 is defined (or had #pragma once) */
1408 printf("%s: skipping cached %s\n", file
->filename
, buf
);
1412 if (tcc_open(s1
, buf
) >= 0)
1419 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1420 tcc_error("#include recursion too deep");
1421 /* push previous file on stack */
1422 *s1
->include_stack_ptr
++ = file
->prev
;
1423 file
->include_next_index
= i
;
1425 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1427 /* update target deps */
1429 BufferedFile
*bf
= file
;
1430 while (i
== 1 && (bf
= bf
->prev
))
1431 i
= bf
->include_next_index
;
1432 /* skip system include files */
1433 if (s1
->include_sys_deps
|| i
- 2 < s1
->nb_include_paths
)
1434 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1437 /* add include file debug info */
1438 tcc_debug_bincl(s1
);
1443 /* eval an expression for #if/#elif */
1444 static int expr_preprocess(TCCState
*s1
)
1450 str
= tok_str_alloc();
1453 next(); /* do macro subst */
1455 if (tok
< TOK_IDENT
) {
1456 if (tok
== TOK_LINEFEED
|| tok
== TOK_EOF
)
1458 if (tok
>= TOK_STR
&& tok
<= TOK_CLDOUBLE
)
1459 tcc_error("invalid constant in preprocessor expression");
1461 } else if (tok
== TOK_DEFINED
) {
1462 parse_flags
&= ~PARSE_FLAG_PREPROCESS
; /* no macro subst */
1467 parse_flags
|= PARSE_FLAG_PREPROCESS
;
1468 if (tok
< TOK_IDENT
)
1469 expect("identifier after 'defined'");
1473 if (define_find(tok
)
1474 || tok
== TOK___HAS_INCLUDE
1475 || tok
== TOK___HAS_INCLUDE_NEXT
)
1484 } else if (tok
== TOK___HAS_INCLUDE
||
1485 tok
== TOK___HAS_INCLUDE_NEXT
) {
1490 c
= parse_include(s1
, t
- TOK___HAS_INCLUDE
, 1);
1496 /* if undefined macro, replace with zero */
1500 tok_str_add_tok(str
);
1503 tcc_error("#%s with no expression", get_tok_str(t0
, 0));
1504 tok_str_add(str
, TOK_EOF
); /* simulate end of file */
1505 pp_expr
= t0
; /* redirect pre-processor expression error messages */
1507 /* now evaluate C constant expression */
1508 begin_macro(str
, 1);
1515 tok
= t
; /* restore LF or EOF */
1519 ST_FUNC
void pp_error(CString
*cs
)
1521 cstr_printf(cs
, "bad preprocessor expression: #%s", get_tok_str(pp_expr
, 0));
1522 macro_ptr
= macro_stack
->str
;
1523 while (next(), tok
!= TOK_EOF
)
1524 cstr_printf(cs
, " %s", get_tok_str(tok
, &tokc
));
1527 /* parse after #define */
1528 ST_FUNC
void parse_define(void)
1530 Sym
*s
, *first
, **ps
;
1531 int v
, t
, varg
, is_vaargs
, t0
;
1532 int saved_parse_flags
= parse_flags
;
1536 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1537 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1540 /* We have to parse the whole define as if not in asm mode, in particular
1541 no line comment with '#' must be ignored. Also for function
1542 macros the argument list must be parsed without '.' being an ID
1544 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1545 /* '(' must be just after macro definition for MACRO_FUNC */
1547 parse_flags
&= ~PARSE_FLAG_SPACES
;
1550 int dotid
= set_idnum('.', 0);
1553 if (tok
!= ')') for (;;) {
1557 if (varg
== TOK_DOTS
) {
1558 varg
= TOK___VA_ARGS__
;
1560 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1564 if (varg
< TOK_IDENT
)
1566 tcc_error("bad macro parameter list");
1567 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1572 if (tok
!= ',' || is_vaargs
)
1576 parse_flags
|= PARSE_FLAG_SPACES
;
1579 set_idnum('.', dotid
);
1582 /* The body of a macro definition should be parsed such that identifiers
1583 are parsed like the file mode determines (i.e. with '.' being an
1584 ID character in asm mode). But '#' should be retained instead of
1585 regarded as line comment leader, so still don't set ASM_FILE
1587 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1590 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1591 if (is_space(tok
)) {
1594 if (TOK_TWOSHARPS
== tok
) {
1600 tok_str_add2_spc(&str
, tok
, &tokc
);
1605 parse_flags
= saved_parse_flags
;
1606 tok_str_add(&str
, 0);
1607 if (t0
== TOK_PPJOIN
)
1609 tcc_error("'##' cannot appear at either end of macro");
1610 define_push(v
, t
, str
.str
, first
);
1611 //tok_print(str.str, "#define (%d) %s %d:", t | is_vaargs * 4, get_tok_str(v, 0));
1614 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1616 const char *s
, *basename
;
1621 s
= basename
= tcc_basename(filename
);
1623 while ((c
= (unsigned char)*s
) != 0) {
1625 h
= TOK_HASH_FUNC(h
, toup(c
));
1627 h
= TOK_HASH_FUNC(h
, c
);
1631 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1633 i
= s1
->cached_includes_hash
[h
];
1637 e
= s1
->cached_includes
[i
- 1];
1638 if (0 == PATHCMP(filename
, e
->filename
))
1641 && 0 == PATHCMP(basename
, tcc_basename(e
->filename
))
1642 && 0 == normalized_PATHCMP(filename
, e
->filename
)
1650 e
= tcc_malloc(sizeof(CachedInclude
) + (len
= strlen(filename
)));
1651 memcpy(e
->filename
, filename
, len
+ 1);
1652 e
->ifndef_macro
= e
->once
= 0;
1653 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1654 /* add in hash table */
1655 e
->hash_next
= s1
->cached_includes_hash
[h
];
1656 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1658 printf("adding cached '%s'\n", filename
);
1663 static void pragma_parse(TCCState
*s1
)
1666 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1670 if (next(), tok
!= '(')
1672 if (next(), tok
!= TOK_STR
)
1674 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1675 if (next(), tok
!= ')')
1677 if (t
== TOK_push_macro
) {
1678 while (NULL
== (s
= define_find(v
)))
1679 define_push(v
, 0, NULL
, NULL
);
1680 s
->type
.ref
= s
; /* set push boundary */
1682 for (s
= define_stack
; s
; s
= s
->prev
)
1683 if (s
->v
== v
&& s
->type
.ref
== s
) {
1689 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1691 tcc_warning("unbalanced #pragma pop_macro");
1692 pp_debug_tok
= t
, pp_debug_symv
= v
;
1694 } else if (tok
== TOK_once
) {
1695 search_cached_include(s1
, file
->filename
, 1)->once
= 1;
1697 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1698 /* tcc -E: keep pragmas below unchanged */
1700 unget_tok(TOK_PRAGMA
);
1702 unget_tok(TOK_LINEFEED
);
1704 } else if (tok
== TOK_pack
) {
1706 #pragma pack(1) // set
1707 #pragma pack() // reset to default
1708 #pragma pack(push) // push current
1709 #pragma pack(push,1) // push & set
1710 #pragma pack(pop) // restore previous */
1713 if (tok
== TOK_ASM_pop
) {
1715 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1717 tcc_error("out of pack stack");
1719 s1
->pack_stack_ptr
--;
1723 if (tok
== TOK_ASM_push
) {
1725 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1727 val
= *s1
->pack_stack_ptr
++;
1732 if (tok
!= TOK_CINT
)
1735 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1740 *s1
->pack_stack_ptr
= val
;
1745 } else if (tok
== TOK_comment
) {
1754 p
= tcc_strdup((char *)tokc
.str
.data
);
1759 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1761 if (t
== TOK_option
)
1762 tcc_set_options(s1
, p
);
1767 tcc_warning_c(warn_unsupported
)("#pragma %s ignored", get_tok_str(tok
, &tokc
));
1771 tcc_error("malformed #pragma directive");
1775 /* is_bof is true if first non space token at beginning of file */
1776 ST_FUNC
void preprocess(int is_bof
)
1778 TCCState
*s1
= tcc_state
;
1779 int c
, n
, saved_parse_flags
;
1783 saved_parse_flags
= parse_flags
;
1784 parse_flags
= PARSE_FLAG_PREPROCESS
1785 | PARSE_FLAG_TOK_NUM
1786 | PARSE_FLAG_TOK_STR
1787 | PARSE_FLAG_LINEFEED
1788 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1797 pp_debug_symv
= tok
;
1803 pp_debug_symv
= tok
;
1804 s
= define_find(tok
);
1805 /* undefine symbol by putting an invalid name */
1810 case TOK_INCLUDE_NEXT
:
1811 parse_include(s1
, tok
- TOK_INCLUDE
, 0);
1817 c
= expr_preprocess(s1
);
1823 if (tok
< TOK_IDENT
)
1824 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1828 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1830 file
->ifndef_macro
= tok
;
1833 if (define_find(tok
)
1834 || tok
== TOK___HAS_INCLUDE
1835 || tok
== TOK___HAS_INCLUDE_NEXT
)
1838 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1839 tcc_error("memory full (ifdef)");
1840 *s1
->ifdef_stack_ptr
++ = c
;
1843 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1844 tcc_error("#else without matching #if");
1845 if (s1
->ifdef_stack_ptr
[-1] & 2)
1846 tcc_error("#else after #else");
1847 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1850 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1851 tcc_error("#elif without matching #if");
1852 c
= s1
->ifdef_stack_ptr
[-1];
1854 tcc_error("#elif after #else");
1855 /* last #if/#elif expression was true: we skip */
1859 c
= expr_preprocess(s1
);
1860 s1
->ifdef_stack_ptr
[-1] = c
;
1863 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1864 file
->ifndef_macro
= 0;
1873 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1874 tcc_error("#endif without matching #if");
1875 s1
->ifdef_stack_ptr
--;
1876 /* '#ifndef macro' was at the start of file. Now we check if
1877 an '#endif' is exactly at the end of file */
1878 if (file
->ifndef_macro
&&
1879 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1880 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1881 /* need to set to zero to avoid false matches if another
1882 #ifndef at middle of file */
1883 file
->ifndef_macro
= 0;
1884 while (tok
!= TOK_LINEFEED
)
1886 tok_flags
|= TOK_FLAG_ENDIF
;
1891 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1895 if (tok
!= TOK_CINT
)
1897 tcc_error("wrong #line format");
1901 if (tok
!= TOK_LINEFEED
) {
1902 if (tok
== TOK_STR
) {
1903 if (file
->true_filename
== file
->filename
)
1904 file
->true_filename
= tcc_strdup(file
->filename
);
1905 q
= (char *)tokc
.str
.data
;
1907 if (!IS_ABSPATH(q
)) {
1908 /* prepend directory from real file */
1909 pstrcpy(buf
, sizeof buf
, file
->true_filename
);
1910 *tcc_basename(buf
) = 0;
1912 pstrcat(buf
, sizeof buf
, q
);
1913 tcc_debug_putfile(s1
, buf
);
1914 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1921 total_lines
+= file
->line_num
- n
;
1928 while (c
!= '\n' && c
!= CH_EOF
) {
1929 if ((q
- buf
) < sizeof(buf
) - 1)
1934 if (tok
== TOK_ERROR
)
1935 tcc_error("#error %s", buf
);
1937 tcc_warning("#warning %s", buf
);
1945 /* ignore gas line comment in an 'S' file. */
1946 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
1948 if (tok
== '!' && is_bof
)
1949 /* '!' is ignored at beginning to allow C scripts. */
1951 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1953 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
1956 /* ignore other preprocess commands or #! for C scripts */
1957 while (tok
!= TOK_LINEFEED
)
1960 parse_flags
= saved_parse_flags
;
1963 /* evaluate escape codes in a string. */
1964 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1979 case '0': case '1': case '2': case '3':
1980 case '4': case '5': case '6': case '7':
1981 /* at most three octal digits */
1986 n
= n
* 8 + c
- '0';
1990 n
= n
* 8 + c
- '0';
1995 goto add_char_nonext
;
1996 case 'x': i
= 0; goto parse_hex_or_ucn
;
1997 case 'u': i
= 4; goto parse_hex_or_ucn
;
1998 case 'U': i
= 8; goto parse_hex_or_ucn
;
2004 if (c
>= 'a' && c
<= 'f')
2006 else if (c
>= 'A' && c
<= 'F')
2011 expect("more hex digits in universal-character-name");
2013 goto add_hex_or_ucn
;
2020 goto add_char_nonext
;
2022 cstr_u8cat(outstr
, n
);
2047 goto invalid_escape
;
2057 if (c
>= '!' && c
<= '~')
2058 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2060 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2063 } else if (is_long
&& c
>= 0x80) {
2064 /* assume we are processing UTF-8 sequence */
2065 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2067 int cont
; /* count of continuation bytes */
2068 int skip
; /* how many bytes should skip when error occurred */
2071 /* decode leading byte */
2073 skip
= 1; goto invalid_utf8_sequence
;
2074 } else if (c
<= 0xDF) {
2075 cont
= 1; n
= c
& 0x1f;
2076 } else if (c
<= 0xEF) {
2077 cont
= 2; n
= c
& 0xf;
2078 } else if (c
<= 0xF4) {
2079 cont
= 3; n
= c
& 0x7;
2081 skip
= 1; goto invalid_utf8_sequence
;
2084 /* decode continuation bytes */
2085 for (i
= 1; i
<= cont
; i
++) {
2086 int l
= 0x80, h
= 0xBF;
2088 /* adjust limit for second byte */
2091 case 0xE0: l
= 0xA0; break;
2092 case 0xED: h
= 0x9F; break;
2093 case 0xF0: l
= 0x90; break;
2094 case 0xF4: h
= 0x8F; break;
2098 if (p
[i
] < l
|| p
[i
] > h
) {
2099 skip
= i
; goto invalid_utf8_sequence
;
2102 n
= (n
<< 6) | (p
[i
] & 0x3f);
2105 /* advance pointer */
2108 goto add_char_nonext
;
2110 /* error handling */
2111 invalid_utf8_sequence
:
2112 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c
);
2115 goto add_char_nonext
;
2121 cstr_ccat(outstr
, c
);
2123 #ifdef TCC_TARGET_PE
2124 /* store as UTF-16 */
2126 cstr_wccat(outstr
, c
);
2129 cstr_wccat(outstr
, (c
>> 10) + 0xD800);
2130 cstr_wccat(outstr
, (c
& 0x3FF) + 0xDC00);
2133 cstr_wccat(outstr
, c
);
2137 /* add a trailing '\0' */
2139 cstr_ccat(outstr
, '\0');
2141 cstr_wccat(outstr
, '\0');
2144 static void parse_string(const char *s
, int len
)
2146 uint8_t buf
[1000], *p
= buf
;
2149 if ((is_long
= *s
== 'L'))
2153 if (len
>= sizeof buf
)
2154 p
= tcc_malloc(len
+ 1);
2158 cstr_reset(&tokcstr
);
2159 parse_escape_string(&tokcstr
, p
, is_long
);
2164 int char_size
, i
, n
, c
;
2165 /* XXX: make it portable */
2167 tok
= TOK_CCHAR
, char_size
= 1;
2169 tok
= TOK_LCHAR
, char_size
= sizeof(nwchar_t
);
2170 n
= tokcstr
.size
/ char_size
- 1;
2172 tcc_error("empty character constant");
2174 tcc_warning_c(warn_all
)("multi-character character constant");
2175 for (c
= i
= 0; i
< n
; ++i
) {
2177 c
= ((nwchar_t
*)tokcstr
.data
)[i
];
2179 c
= (c
<< 8) | ((char *)tokcstr
.data
)[i
];
2183 tokc
.str
.size
= tokcstr
.size
;
2184 tokc
.str
.data
= tokcstr
.data
;
2192 /* we use 64 bit numbers */
2195 /* bn = (bn << shift) | or_val */
2196 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2200 for(i
=0;i
<BN_SIZE
;i
++) {
2202 bn
[i
] = (v
<< shift
) | or_val
;
2203 or_val
= v
>> (32 - shift
);
2207 static void bn_zero(unsigned int *bn
)
2210 for(i
=0;i
<BN_SIZE
;i
++) {
2215 /* parse number in null terminated string 'p' and return it in the
2217 static void parse_number(const char *p
)
2219 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2221 unsigned int bn
[BN_SIZE
];
2232 goto float_frac_parse
;
2233 } else if (t
== '0') {
2234 if (ch
== 'x' || ch
== 'X') {
2238 } else if (tcc_state
->tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2244 /* parse all digits. cannot check octal numbers at this stage
2245 because of floating point constants */
2247 if (ch
>= 'a' && ch
<= 'f')
2249 else if (ch
>= 'A' && ch
<= 'F')
2257 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2259 tcc_error("number too long");
2265 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2266 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2268 /* NOTE: strtox should support that for hexa numbers, but
2269 non ISOC99 libcs do not support it, so we prefer to do
2271 /* hexadecimal or binary floats */
2272 /* XXX: handle overflows */
2284 } else if (t
>= 'a') {
2286 } else if (t
>= 'A') {
2291 bn_lshift(bn
, shift
, t
);
2298 if (t
>= 'a' && t
<= 'f') {
2300 } else if (t
>= 'A' && t
<= 'F') {
2302 } else if (t
>= '0' && t
<= '9') {
2308 tcc_error("invalid digit");
2309 bn_lshift(bn
, shift
, t
);
2314 if (ch
!= 'p' && ch
!= 'P')
2321 } else if (ch
== '-') {
2325 if (ch
< '0' || ch
> '9')
2326 expect("exponent digits");
2327 while (ch
>= '0' && ch
<= '9') {
2328 exp_val
= exp_val
* 10 + ch
- '0';
2331 exp_val
= exp_val
* s
;
2333 /* now we can generate the number */
2334 /* XXX: should patch directly float number */
2335 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2336 d
= ldexp(d
, exp_val
- frac_bits
);
2341 /* float : should handle overflow */
2343 } else if (t
== 'L') {
2346 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2349 /* XXX: not large enough */
2350 tokc
.ld
= (long double)d
;
2357 /* decimal floats */
2359 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2364 while (ch
>= '0' && ch
<= '9') {
2365 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2371 if (ch
== 'e' || ch
== 'E') {
2372 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2376 if (ch
== '-' || ch
== '+') {
2377 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2382 if (ch
< '0' || ch
> '9')
2383 expect("exponent digits");
2384 while (ch
>= '0' && ch
<= '9') {
2385 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2397 tokc
.f
= strtof(token_buf
, NULL
);
2398 } else if (t
== 'L') {
2401 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2402 tokc
.d
= strtod(token_buf
, NULL
);
2404 tokc
.ld
= strtold(token_buf
, NULL
);
2408 tokc
.d
= strtod(token_buf
, NULL
);
2412 unsigned long long n
, n1
;
2413 int lcount
, ucount
, ov
= 0;
2416 /* integer number */
2419 if (b
== 10 && *q
== '0') {
2426 /* no need for checks except for base 10 / 8 errors */
2436 tcc_error("invalid digit");
2439 /* detect overflow */
2440 if (n1
>= 0x1000000000000000ULL
&& n
/ b
!= n1
)
2444 /* Determine the characteristics (unsigned and/or 64bit) the type of
2445 the constant must have according to the constant suffix(es) */
2446 lcount
= ucount
= 0;
2452 tcc_error("three 'l's in integer constant");
2453 if (lcount
&& *(p
- 1) != ch
)
2454 tcc_error("incorrect integer suffix: %s", p1
);
2457 } else if (t
== 'U') {
2459 tcc_error("two 'u's in integer constant");
2467 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2468 if (ucount
== 0 && b
== 10) {
2469 if (lcount
<= (LONG_SIZE
== 4)) {
2470 if (n
>= 0x80000000U
)
2471 lcount
= (LONG_SIZE
== 4) + 1;
2473 if (n
>= 0x8000000000000000ULL
)
2476 if (lcount
<= (LONG_SIZE
== 4)) {
2477 if (n
>= 0x100000000ULL
)
2478 lcount
= (LONG_SIZE
== 4) + 1;
2479 else if (n
>= 0x80000000U
)
2482 if (n
>= 0x8000000000000000ULL
)
2487 tcc_warning("integer constant overflow");
2496 ++tok
; /* TOK_CU... */
2500 tcc_error("invalid number");
2504 #define PARSE2(c1, tok1, c2, tok2) \
2515 /* return next token without macro substitution */
2516 static void next_nomacro(void)
2518 int t
, c
, is_long
, len
;
2532 if (parse_flags
& PARSE_FLAG_SPACES
)
2533 goto keep_tok_flags
;
2534 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2543 /* first look if it is in fact an end of buffer */
2544 c
= handle_stray(&p
);
2548 TCCState
*s1
= tcc_state
;
2549 if (!(tok_flags
& TOK_FLAG_BOL
)) {
2550 /* add implicit newline */
2552 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2554 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2555 tcc_error("missing #endif");
2556 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2557 /* no include left : end of file. */
2560 /* pop include file */
2562 /* test if previous '#endif' was after a #ifdef at
2564 if (tok_flags
& TOK_FLAG_ENDIF
) {
2566 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2568 search_cached_include(s1
, file
->filename
, 1)
2569 ->ifndef_macro
= file
->ifndef_macro_saved
;
2570 tok_flags
&= ~TOK_FLAG_ENDIF
;
2573 /* add end of include file debug info */
2574 tcc_debug_eincl(tcc_state
);
2575 /* pop include stack */
2577 s1
->include_stack_ptr
--;
2590 tok_flags
|= TOK_FLAG_BOL
;
2591 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2594 goto keep_tok_flags
;
2599 if ((tok_flags
& TOK_FLAG_BOL
) &&
2600 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2601 tok_flags
&= ~TOK_FLAG_BOL
;
2603 preprocess(tok_flags
& TOK_FLAG_BOF
);
2609 tok
= TOK_TWOSHARPS
;
2611 #if !defined(TCC_TARGET_ARM)
2612 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2613 p
= parse_line_comment(p
- 1);
2624 /* dollar is allowed to start identifiers when not parsing asm */
2626 if (!(isidnum_table
['$' - CH_EOF
] & IS_ID
)
2627 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2630 case 'a': case 'b': case 'c': case 'd':
2631 case 'e': case 'f': case 'g': case 'h':
2632 case 'i': case 'j': case 'k': case 'l':
2633 case 'm': case 'n': case 'o': case 'p':
2634 case 'q': case 'r': case 's': case 't':
2635 case 'u': case 'v': case 'w': case 'x':
2637 case 'A': case 'B': case 'C': case 'D':
2638 case 'E': case 'F': case 'G': case 'H':
2639 case 'I': case 'J': case 'K':
2640 case 'M': case 'N': case 'O': case 'P':
2641 case 'Q': case 'R': case 'S': case 'T':
2642 case 'U': case 'V': case 'W': case 'X':
2648 h
= TOK_HASH_FUNC(h
, c
);
2649 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2650 h
= TOK_HASH_FUNC(h
, c
);
2655 /* fast case : no stray found, so we have the full token
2656 and we have already hashed it */
2657 h
&= (TOK_HASH_SIZE
- 1);
2658 pts
= &hash_ident
[h
];
2663 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2665 pts
= &(ts
->hash_next
);
2667 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2671 cstr_reset(&tokcstr
);
2672 cstr_cat(&tokcstr
, (char *) p1
, len
);
2676 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2678 cstr_ccat(&tokcstr
, c
);
2681 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2687 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2689 goto parse_ident_fast
;
2692 if (c
== '\'' || c
== '\"') {
2696 cstr_reset(&tokcstr
);
2697 cstr_ccat(&tokcstr
, 'L');
2698 goto parse_ident_slow
;
2703 case '0': case '1': case '2': case '3':
2704 case '4': case '5': case '6': case '7':
2708 /* after the first digit, accept digits, alpha, '.' or sign if
2709 prefixed by 'eEpP' */
2711 cstr_reset(&tokcstr
);
2713 cstr_ccat(&tokcstr
, t
);
2714 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2716 || ((c
== '+' || c
== '-')
2717 && (((t
== 'e' || t
== 'E')
2718 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2719 /* 0xe+1 is 3 tokens in asm */
2720 && ((char*)tokcstr
.data
)[0] == '0'
2721 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2722 || t
== 'p' || t
== 'P'))))
2727 /* We add a trailing '\0' to ease parsing */
2728 cstr_ccat(&tokcstr
, '\0');
2729 tokc
.str
.size
= tokcstr
.size
;
2730 tokc
.str
.data
= tokcstr
.data
;
2735 /* special dot handling because it can also start a number */
2740 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2741 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2743 goto parse_ident_fast
;
2744 } else if (c
== '.') {
2750 *--p
= '.'; /* may underflow into file->unget[] */
2761 cstr_reset(&tokcstr
);
2763 cstr_ccat(&tokcstr
, 'L');
2764 cstr_ccat(&tokcstr
, c
);
2765 p
= parse_pp_string(p
, c
, &tokcstr
);
2766 cstr_ccat(&tokcstr
, c
);
2767 cstr_ccat(&tokcstr
, '\0');
2768 tokc
.str
.size
= tokcstr
.size
;
2769 tokc
.str
.data
= tokcstr
.data
;
2778 } else if (c
== '<') {
2795 } else if (c
== '>') {
2813 } else if (c
== '=') {
2826 } else if (c
== '=') {
2839 } else if (c
== '=') {
2852 } else if (c
== '=') {
2855 } else if (c
== '>') {
2863 PARSE2('!', '!', '=', TOK_NE
)
2864 PARSE2('=', '=', '=', TOK_EQ
)
2865 PARSE2('*', '*', '=', TOK_A_MUL
)
2866 PARSE2('%', '%', '=', TOK_A_MOD
)
2867 PARSE2('^', '^', '=', TOK_A_XOR
)
2869 /* comments or operator */
2873 p
= parse_comment(p
);
2874 /* comments replaced by a blank */
2877 } else if (c
== '/') {
2878 p
= parse_line_comment(p
);
2881 } else if (c
== '=') {
2901 case '@': /* only used in assembler */
2907 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
2908 goto parse_ident_fast
;
2909 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2911 tcc_error("unrecognized character \\x%02x", c
);
2917 #if defined(PARSE_DEBUG)
2918 printf("token = %d %s\n", tok
, get_tok_str(tok
, &tokc
));
2924 static void define_print(TCCState
*s1
, int v
);
2925 static void pp_print(const char *msg
, int v
, const int *str
)
2927 FILE *fp
= tcc_state
->ppfp
;
2929 if (msg
[0] == '#' && indent
== 0)
2931 else if (msg
[0] == '+')
2933 else if (msg
[0] == '-')
2936 fprintf(fp
, "%*s", indent
, "");
2937 if (msg
[0] == '#') {
2938 define_print(tcc_state
, v
);
2940 tok_print(str
, v
? "%s %s" : "%s", msg
, get_tok_str(v
, 0));
2943 #define PP_PRINT(x) pp_print x
2948 static int macro_subst(
2949 TokenString
*tok_str
,
2951 const int *macro_str
2954 /* substitute arguments in replacement lists in macro_str by the values in
2955 args (field d) and return allocated string */
2956 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2958 int t
, t0
, t1
, t2
, n
;
2965 PP_PRINT(("asubst:", 0, macro_str
));
2966 for (s
= args
, n
= 0; s
; s
= s
->prev
, ++n
);
2968 for (s
= args
, t
= 0; t
< n
; s
= s
->prev
, ++t
);
2969 tok_print(s
->d
, "%*s - arg: %s:", indent
, "", get_tok_str(s
->v
, 0));
2976 TOK_GET(&t
, ¯o_str
, &cval
);
2981 do t
= *macro_str
++; while (t
== ' ');
2982 s
= sym_find2(args
, t
);
2984 cstr_reset(&tokcstr
);
2985 cstr_ccat(&tokcstr
, '\"');
2987 while (*st
!= TOK_EOF
) {
2989 TOK_GET(&t
, &st
, &cval
);
2990 s
= get_tok_str(t
, &cval
);
2992 if (t
== TOK_PPSTR
&& *s
!= '\'')
2993 add_char(&tokcstr
, *s
);
2995 cstr_ccat(&tokcstr
, *s
);
2999 cstr_ccat(&tokcstr
, '\"');
3000 cstr_ccat(&tokcstr
, '\0');
3001 //printf("\nstringize: <%s>\n", (char *)tokcstr.data);
3003 cval
.str
.size
= tokcstr
.size
;
3004 cval
.str
.data
= tokcstr
.data
;
3005 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
3007 expect("macro parameter after '#'");
3009 } else if (t
>= TOK_IDENT
) {
3010 s
= sym_find2(args
, t
);
3014 while ((t2
= macro_str
[n
]) == ' ')
3016 /* if '##' is present before or after, no arg substitution */
3017 if (t2
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
3018 /* special case for var arg macros : ## eats the ','
3019 if empty VA_ARGS variable. */
3020 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
3021 int c
= str
.str
[str
.len
- 1];
3022 while (str
.str
[--str
.len
] != ',')
3024 if (*st
== TOK_EOF
) {
3025 /* suppress ',' '##' */
3027 /* suppress '##' and add variable */
3030 str
.str
[str
.len
++] = c
;
3035 tok_str_add(&str
, TOK_PLCHLDR
);
3040 /* Expand arguments tokens and store them. In most
3041 cases we could also re-expand each argument if
3042 used multiple times, but not if the argument
3043 contains the __COUNTER__ macro. */
3046 macro_subst(&str2
, nested_list
, st
);
3047 tok_str_add(&str2
, TOK_EOF
);
3052 while (*st
!= TOK_EOF
) {
3053 TOK_GET(&t2
, &st
, &cval
);
3054 tok_str_add2(&str
, t2
, &cval
);
3057 tok_str_add(&str
, t
);
3060 tok_str_add2(&str
, t
, &cval
);
3065 tok_str_add(&str
, 0);
3066 PP_PRINT(("areslt:", 0, str
.str
));
3070 /* handle the '##' operator. return the resulting string (which must be freed). */
3071 static inline int *macro_twosharps(const int *ptr0
)
3075 TokenString macro_str1
;
3078 tok_str_new(¯o_str1
);
3079 for (ptr
= ptr0
;;) {
3080 TOK_GET(&t1
, &ptr
, &cv1
);
3085 while ((t2
= ptr
[n
]) == ' ')
3087 if (t2
!= TOK_PPJOIN
)
3090 while ((t2
= *++ptr
) == ' ' || t2
== TOK_PPJOIN
)
3092 TOK_GET(&t2
, &ptr
, &cv2
);
3093 if (t1
== TOK_PLCHLDR
&& t2
== TOK_PLCHLDR
)
3095 cstr_reset(&tokcstr
);
3096 if (t1
!= TOK_PLCHLDR
)
3097 cstr_cat(&tokcstr
, get_tok_str(t1
, &cv1
), -1);
3099 if (t2
!= TOK_PLCHLDR
)
3100 cstr_cat(&tokcstr
, get_tok_str(t2
, &cv2
), -1);
3101 cstr_ccat(&tokcstr
, '\0');
3102 //printf("paste <%s>\n", (char*)tokcstr.data);
3103 tcc_open_bf(tcc_state
, ":paste:", tokcstr
.size
);
3104 memcpy(file
->buffer
, tokcstr
.data
, tokcstr
.size
);
3105 tok_flags
= 0; /* don't interpret '#' */
3107 if (*file
->buf_ptr
== 0) {
3108 t1
= tok
, cv1
= tokc
;
3110 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3111 " preprocessing token", n
, file
->buffer
, file
->buffer
+ n
);
3112 tok_str_add2(¯o_str1
, t1
, &cv1
);
3117 if (t1
!= TOK_PLCHLDR
)
3118 tok_str_add2(¯o_str1
, t1
, &cv1
);
3120 tok_str_add(¯o_str1
, 0);
3121 PP_PRINT(("pasted:", 0, macro_str1
.str
));
3122 return macro_str1
.str
;
3125 static int peek_file (TokenString
*ws_str
)
3127 uint8_t *p
= file
->buf_ptr
- 1;
3135 p
= parse_comment(p
);
3137 p
= parse_line_comment(p
);
3144 case ' ': case '\t':
3146 case '\f': case '\v': case '\r':
3149 file
->line_num
++, tok_flags
|= TOK_FLAG_BOL
;
3156 tok_str_add(ws_str
, c
);
3160 /* peek or read [ws_str == NULL] next token from function macro call,
3161 walking up macro levels up to the file if necessary */
3162 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3168 const int *m
= macro_ptr
;
3169 while ((t
= *m
) != 0) {
3175 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
3180 /* also, end of scope for nested defined symbol */
3183 *nested_list
= sa
->prev
, sym_free(sa
);
3186 return peek_file(ws_str
);
3189 if (tok
== '\t' || tok
== TOK_LINEFEED
)
3195 /* do macro substitution of current token with macro 's' and add
3196 result to (tok_str,tok_len). 'nested_list' is the list of all
3197 macros we got inside to avoid recursing. Return non zero if no
3198 substitution needs to be done */
3199 static int macro_subst_tok(
3200 TokenString
*tok_str
,
3207 PP_PRINT(("#", v
, s
->d
));
3214 if (s
->type
.t
& MACRO_FUNC
) {
3215 int saved_parse_flags
= parse_flags
;
3220 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3221 | PARSE_FLAG_ACCEPT_STRAYS
;
3224 /* peek next token from argument stream */
3225 t
= next_argstream(nested_list
, &str
);
3227 /* not a macro substitution after all, restore the
3228 * macro token plus all whitespace we've read.
3229 * whitespace is intentionally not merged to preserve
3231 parse_flags
= saved_parse_flags
;
3232 tok_str_add2_spc(tok_str
, v
, 0);
3233 if (parse_flags
& PARSE_FLAG_SPACES
)
3234 for (i
= 0; i
< str
.len
; i
++)
3235 tok_str_add(tok_str
, str
.str
[i
]);
3236 tok_str_free_str(str
.str
);
3239 tok_str_free_str(str
.str
);
3242 /* argument macro */
3245 /* NOTE: empty args are allowed, except if no args */
3246 i
= 2; /* eat '(' */
3249 t
= next_argstream(nested_list
, NULL
);
3250 } while (t
== ' ' || --i
);
3253 if (t
== ')') /* handle '()' case */
3255 tcc_error("macro '%s' used with too many args",
3261 /* NOTE: non zero sa->type.t indicates VA_ARGS */
3263 || (t
!= ')' && (t
!= ',' || sa
->type
.t
))) {
3265 tcc_error("EOF in invocation of macro '%s'",
3274 tok_str_add2_spc(&str
, t
, &tokc
);
3275 t
= next_argstream(nested_list
, NULL
);
3277 tok_str_add(&str
, TOK_EOF
);
3278 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3284 /* special case for gcc var args: add an empty
3285 var arg argument if it is omitted */
3286 if (sa
->type
.t
&& gnu_ext
)
3288 tcc_error("macro '%s' used with too few args",
3294 /* now subst each arg */
3295 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3300 tok_str_free_str(sa
->d
);
3301 tok_str_free_str(sa
->e
);
3305 parse_flags
= saved_parse_flags
;
3308 /* process '##'s (if present) */
3310 if (s
->type
.t
& MACRO_JOIN
)
3311 jstr
= macro_twosharps(mstr
);
3313 sa
= sym_push2(nested_list
, v
, 0, 0);
3314 ret
= macro_subst(tok_str
, nested_list
, jstr
);
3315 /* pop nested defined symbol */
3316 if (sa
== *nested_list
)
3317 *nested_list
= sa
->prev
, sym_free(sa
);
3320 tok_str_free_str(jstr
);
3322 tok_str_free_str(mstr
);
3327 char buf
[32], *cstrval
= buf
;
3329 /* special macros */
3330 if (v
== TOK___LINE__
|| v
== TOK___COUNTER__
) {
3331 t
= v
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3332 snprintf(buf
, sizeof(buf
), "%d", t
);
3336 } else if (v
== TOK___FILE__
) {
3337 cstrval
= file
->filename
;
3340 } else if (v
== TOK___DATE__
|| v
== TOK___TIME__
) {
3344 tm
= localtime(&ti
);
3345 if (v
== TOK___DATE__
) {
3346 static char const ab_month_name
[12][4] = {
3347 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3348 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3350 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3351 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3353 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3354 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3359 cval
.str
.size
= strlen(cstrval
) + 1;
3360 cval
.str
.data
= cstrval
;
3361 tok_str_add2_spc(tok_str
, t
, &cval
);
3367 /* do macro substitution of macro_str and add result to
3368 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3369 inside to avoid recursing. */
3370 static int macro_subst(
3371 TokenString
*tok_str
,
3373 const int *macro_str
3382 int tlen
= tok_str
->len
;
3383 PP_PRINT(("+expand:", 0, macro_str
));
3387 TOK_GET(&t
, ¯o_str
, &cval
);
3388 if (t
== 0 || t
== TOK_EOF
)
3390 if (t
>= TOK_IDENT
) {
3392 if (s
== NULL
|| nosubst
)
3394 /* if nested substitution, do nothing */
3395 if (sym_find2(*nested_list
, t
)) {
3396 /* and mark so it doesn't get subst'd again */
3400 str
= tok_str_alloc();
3401 str
->str
= (int*)macro_str
; /* setup stream for possible arguments */
3402 begin_macro(str
, 2);
3403 nosubst
= macro_subst_tok(tok_str
, nested_list
, s
);
3404 if (macro_stack
!= str
) {
3405 /* already finished by reading function macro arguments */
3408 macro_str
= macro_ptr
;
3410 } else if (t
== ' ') {
3411 if (parse_flags
& PARSE_FLAG_SPACES
)
3412 tok_str
->need_spc
|= 1;
3415 tok_str_add2_spc(tok_str
, t
, &cval
);
3416 if (nosubst
&& t
!= '(')
3418 /* GCC supports 'defined' as result of a macro substitution */
3419 if (t
== TOK_DEFINED
&& pp_expr
)
3425 tok_str_add(tok_str
, 0), --tok_str
->len
;
3426 PP_PRINT(("-result:", 0, tok_str
->str
+ tlen
));
3431 /* return next token with macro substitution */
3432 ST_FUNC
void next(void)
3438 if (TOK_HAS_VALUE(t
)) {
3439 tok_get(&tok
, ¯o_ptr
, &tokc
);
3440 if (t
== TOK_LINENUM
) {
3441 file
->line_num
= tokc
.i
;
3445 } else if (t
== 0) {
3446 /* end of macro or unget token string */
3449 } else if (t
== TOK_EOF
) {
3453 if (t
>= TOK_IDENT
) {
3454 t
&= ~SYM_FIELD
; /* remove 'nosubst' marker */
3455 } else if (t
== '\\') {
3456 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3457 tcc_error("stray '\\' in program");
3466 if (t
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3467 /* if reading from file, try to substitute macros */
3468 Sym
*s
= define_find(t
);
3470 Sym
*nested_list
= NULL
;
3471 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3472 tok_str_add(&tokstr_buf
, 0);
3473 begin_macro(&tokstr_buf
, 0);
3480 /* convert preprocessor tokens into C tokens */
3481 if (t
== TOK_PPNUM
) {
3482 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3483 parse_number((char *)tokc
.str
.data
);
3484 } else if (t
== TOK_PPSTR
) {
3485 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3486 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3490 /* push back current token and set current token to 'last_tok'. Only
3491 identifier case handled for labels. */
3492 ST_INLN
void unget_tok(int last_tok
)
3494 TokenString
*str
= &unget_buf
;
3496 if (str
->len
) /* use static buffer except if already in use */
3497 str
= tok_str_alloc(), alloc
= 1;
3499 tok_str_add2(str
, tok
, &tokc
);
3500 tok_str_add(str
, 0);
3501 begin_macro(str
, alloc
);
3505 /* ------------------------------------------------------------------------- */
3506 /* init preprocessor */
3508 static const char * const target_os_defs
=
3509 #ifdef TCC_TARGET_PE
3515 # if defined TCC_TARGET_MACHO
3517 # elif TARGETOS_FreeBSD
3519 # elif TARGETOS_FreeBSD_kernel
3520 "__FreeBSD_kernel__\0"
3521 # elif TARGETOS_NetBSD
3523 # elif TARGETOS_OpenBSD
3528 # if TARGETOS_ANDROID
3537 static void putdef(CString
*cs
, const char *p
)
3539 cstr_printf(cs
, "#define %s%s\n", p
, &" 1"[!!strchr(p
, ' ')*2]);
3542 static void putdefs(CString
*cs
, const char *p
)
3545 putdef(cs
, p
), p
= strchr(p
, 0) + 1;
3548 static void tcc_predefs(TCCState
*s1
, CString
*cs
, int is_asm
)
3550 cstr_printf(cs
, "#define __TINYC__ 9%.2s\n", TCC_VERSION
+ 4);
3551 putdefs(cs
, target_machine_defs
);
3552 putdefs(cs
, target_os_defs
);
3554 #ifdef TCC_TARGET_ARM
3555 if (s1
->float_abi
== ARM_HARD_FLOAT
)
3556 putdef(cs
, "__ARM_PCS_VFP");
3559 putdef(cs
, "__ASSEMBLER__");
3560 if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
)
3561 putdef(cs
, "__TCC_PP__");
3562 if (s1
->output_type
== TCC_OUTPUT_MEMORY
)
3563 putdef(cs
, "__TCC_RUN__");
3564 #ifdef CONFIG_TCC_BACKTRACE
3565 if (s1
->do_backtrace
)
3566 putdef(cs
, "__TCC_BACKTRACE__");
3568 #ifdef CONFIG_TCC_BCHECK
3569 if (s1
->do_bounds_check
)
3570 putdef(cs
, "__TCC_BCHECK__");
3572 if (s1
->char_is_unsigned
)
3573 putdef(cs
, "__CHAR_UNSIGNED__");
3574 if (s1
->optimize
> 0)
3575 putdef(cs
, "__OPTIMIZE__");
3576 if (s1
->option_pthread
)
3577 putdef(cs
, "_REENTRANT");
3578 if (s1
->leading_underscore
)
3579 putdef(cs
, "__leading_underscore");
3580 cstr_printf(cs
, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE
);
3581 cstr_printf(cs
, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE
);
3583 putdef(cs
, "__STDC__");
3584 cstr_printf(cs
, "#define __STDC_VERSION__ %dL\n", s1
->cversion
);
3586 /* load more predefs and __builtins */
3587 #if CONFIG_TCC_PREDEFS
3588 #include "tccdefs_.h" /* include as strings */
3590 "#include <tccdefs.h>\n" /* load at runtime */
3594 cstr_printf(cs
, "#define __BASE_FILE__ \"%s\"\n", file
->filename
);
3597 ST_FUNC
void preprocess_start(TCCState
*s1
, int filetype
)
3599 int is_asm
= !!(filetype
& (AFF_TYPE_ASM
|AFF_TYPE_ASMPP
));
3603 s1
->include_stack_ptr
= s1
->include_stack
;
3604 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3605 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3608 pp_debug_tok
= pp_debug_symv
= 0;
3609 s1
->pack_stack
[0] = 0;
3610 s1
->pack_stack_ptr
= s1
->pack_stack
;
3612 set_idnum('$', !is_asm
&& s1
->dollars_in_identifiers
? IS_ID
: 0);
3613 set_idnum('.', is_asm
? IS_ID
: 0);
3615 if (!(filetype
& AFF_TYPE_ASM
)) {
3618 tcc_predefs(s1
, &cstr
, is_asm
);
3619 if (s1
->cmdline_defs
.size
)
3620 cstr_cat(&cstr
, s1
->cmdline_defs
.data
, s1
->cmdline_defs
.size
);
3621 if (s1
->cmdline_incl
.size
)
3622 cstr_cat(&cstr
, s1
->cmdline_incl
.data
, s1
->cmdline_incl
.size
);
3623 //printf("%.*s\n", cstr.size, (char*)cstr.data);
3624 *s1
->include_stack_ptr
++ = file
;
3625 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3626 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3629 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3632 /* cleanup from error/setjmp */
3633 ST_FUNC
void preprocess_end(TCCState
*s1
)
3643 ST_FUNC
int set_idnum(int c
, int val
)
3645 int prev
= isidnum_table
[c
- CH_EOF
];
3646 isidnum_table
[c
- CH_EOF
] = val
;
3650 ST_FUNC
void tccpp_new(TCCState
*s
)
3655 /* init isid table */
3656 for(i
= CH_EOF
; i
<128; i
++)
3658 is_space(i
) ? IS_SPC
3663 for(i
= 128; i
<256; i
++)
3664 set_idnum(i
, IS_ID
);
3666 /* init allocators */
3667 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3668 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3670 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3671 memset(s
->cached_includes_hash
, 0, sizeof s
->cached_includes_hash
);
3674 cstr_new(&cstr_buf
);
3675 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3676 tok_str_new(&tokstr_buf
);
3677 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3678 tok_str_new(&unget_buf
);
3680 tok_ident
= TOK_IDENT
;
3689 tok_alloc(p
, r
- p
- 1);
3693 /* we add dummy defines for some special macros to speed up tests
3694 and to have working defined() */
3695 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
3696 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
3697 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
3698 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
3699 define_push(TOK___COUNTER__
, MACRO_OBJ
, NULL
, NULL
);
3702 ST_FUNC
void tccpp_delete(TCCState
*s
)
3706 dynarray_reset(&s
->cached_includes
, &s
->nb_cached_includes
);
3709 n
= tok_ident
- TOK_IDENT
;
3710 if (n
> total_idents
)
3712 for(i
= 0; i
< n
; i
++)
3713 tal_free(toksym_alloc
, table_ident
[i
]);
3714 tcc_free(table_ident
);
3717 /* free static buffers */
3718 cstr_free(&tokcstr
);
3719 cstr_free(&cstr_buf
);
3720 tok_str_free_str(tokstr_buf
.str
);
3721 tok_str_free_str(unget_buf
.str
);
3723 /* free allocators */
3724 tal_delete(toksym_alloc
);
3725 toksym_alloc
= NULL
;
3726 tal_delete(tokstr_alloc
);
3727 tokstr_alloc
= NULL
;
3730 /* ------------------------------------------------------------------------- */
3731 /* tcc -E [-P[1]] [-dD} support */
3733 static int pp_need_space(int a
, int b
);
3735 static void tok_print(const int *str
, const char *msg
, ...)
3737 FILE *fp
= tcc_state
->ppfp
;
3743 vfprintf(fp
, msg
, ap
);
3748 TOK_GET(&t
, &str
, &cval
);
3749 if (t
== 0 || t
== TOK_EOF
)
3751 if (pp_need_space(t0
, t
))
3753 fprintf(fp
, &" %s"[s
], t
== TOK_PLCHLDR
? "<>" : get_tok_str(t
, &cval
));
3759 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3761 int d
= f
->line_num
- f
->line_ref
;
3766 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3768 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3770 fputs("\n", s1
->ppfp
), --d
;
3771 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3772 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3774 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3775 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3777 f
->line_ref
= f
->line_num
;
3780 static void define_print(TCCState
*s1
, int v
)
3786 if (NULL
== s
|| NULL
== s
->d
)
3790 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3791 if (s
->type
.t
& MACRO_FUNC
) {
3796 fprintf(fp
,"%s", get_tok_str(a
->v
, NULL
));
3803 tok_print(s
->d
, "");
3806 static void pp_debug_defines(TCCState
*s1
)
3817 pp_line(s1
, file
, 0);
3818 file
->line_ref
= ++file
->line_num
;
3822 vs
= get_tok_str(v
, NULL
);
3823 if (t
== TOK_DEFINE
) {
3824 define_print(s1
, v
);
3825 } else if (t
== TOK_UNDEF
) {
3826 fprintf(fp
, "#undef %s\n", vs
);
3827 } else if (t
== TOK_push_macro
) {
3828 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3829 } else if (t
== TOK_pop_macro
) {
3830 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3835 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3836 static int pp_need_space(int a
, int b
)
3838 return 'E' == a
? '+' == b
|| '-' == b
3839 : '+' == a
? TOK_INC
== b
|| '+' == b
3840 : '-' == a
? TOK_DEC
== b
|| '-' == b
3841 : a
>= TOK_IDENT
|| a
== TOK_PPNUM
? b
>= TOK_IDENT
|| b
== TOK_PPNUM
3845 /* maybe hex like 0x1e */
3846 static int pp_check_he0xE(int t
, const char *p
)
3848 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3853 /* Preprocess the current file */
3854 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3856 BufferedFile
**iptr
;
3857 int token_seen
, spcs
, level
;
3861 parse_flags
= PARSE_FLAG_PREPROCESS
3862 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3863 | PARSE_FLAG_LINEFEED
3865 | PARSE_FLAG_ACCEPT_STRAYS
3867 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3868 capability to compile and run itself, provided all numbers are
3869 given as decimals. tcc -E -P10 will do. */
3870 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
3871 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
3874 /* for PP benchmarks */
3875 do next(); while (tok
!= TOK_EOF
);
3879 token_seen
= TOK_LINEFEED
, spcs
= 0, level
= 0;
3881 pp_line(s1
, file
->prev
, level
++);
3882 pp_line(s1
, file
, level
);
3885 iptr
= s1
->include_stack_ptr
;
3890 level
= s1
->include_stack_ptr
- iptr
;
3893 pp_line(s1
, *iptr
, 0);
3894 pp_line(s1
, file
, level
);
3896 if (s1
->dflag
& 7) {
3897 pp_debug_defines(s1
);
3902 if (is_space(tok
)) {
3903 if (spcs
< sizeof white
- 1)
3904 white
[spcs
++] = tok
;
3906 } else if (tok
== TOK_LINEFEED
) {
3908 if (token_seen
== TOK_LINEFEED
)
3911 } else if (token_seen
== TOK_LINEFEED
) {
3912 pp_line(s1
, file
, 0);
3913 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
3914 white
[spcs
++] = ' ';
3917 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
3918 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
3919 token_seen
= pp_check_he0xE(tok
, p
);
3924 /* ------------------------------------------------------------------------- */