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
;
52 static int pp_counter
;
53 static void tok_print(const char *msg
, const int *str
);
55 static struct TinyAlloc
*toksym_alloc
;
56 static struct TinyAlloc
*tokstr_alloc
;
58 static TokenString
*macro_stack
;
60 static const char tcc_keywords
[] =
61 #define DEF(id, str) str "\0"
66 /* WARNING: the content of this string encodes token numbers */
67 static const unsigned char tok_two_chars
[] =
69 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
70 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
92 '#','#', TOK_TWOSHARPS
,
97 static void next_nomacro(void);
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
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
);
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>");
607 /* search in two bytes table */
608 const unsigned char *q
= tok_two_chars
;
614 return cstr_buf
.data
;
618 if (v
>= 127 || (v
< 32 && !is_space(v
) && v
!= '\n')) {
619 sprintf(p
, "<\\x%02x>", v
);
625 } else if (v
< tok_ident
) {
626 return table_ident
[v
- TOK_IDENT
]->str
;
627 } else if (v
>= SYM_FIRST_ANOM
) {
628 /* special name for anonymous symbol */
629 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
631 /* should never happen */
636 return cstr_buf
.data
;
639 static inline int check_space(int t
, int *spc
)
641 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
650 /* return the current character, handling end of block if necessary
652 static int handle_eob(void)
654 BufferedFile
*bf
= file
;
657 /* only tries to read if really end of buffer */
658 if (bf
->buf_ptr
>= bf
->buf_end
) {
660 #if defined(PARSE_DEBUG)
665 len
= read(bf
->fd
, bf
->buffer
, len
);
672 bf
->buf_ptr
= bf
->buffer
;
673 bf
->buf_end
= bf
->buffer
+ len
;
674 *bf
->buf_end
= CH_EOB
;
676 if (bf
->buf_ptr
< bf
->buf_end
) {
677 return bf
->buf_ptr
[0];
679 bf
->buf_ptr
= bf
->buf_end
;
684 /* read next char from current input file and handle end of input buffer */
685 static int next_c(void)
687 int ch
= *++file
->buf_ptr
;
688 /* end of buffer/file handling */
689 if (ch
== CH_EOB
&& file
->buf_ptr
>= file
->buf_end
)
694 /* input with '\[\r]\n' handling. */
695 static int handle_stray_noerror(int err
)
698 while ((ch
= next_c()) == '\\') {
708 *--file
->buf_ptr
= '\r';
711 tcc_error("stray '\\' in program");
712 /* may take advantage of 'BufferedFile.unget[4}' */
713 return *--file
->buf_ptr
= '\\';
719 #define ninp() handle_stray_noerror(0)
721 /* handle '\\' in strings, comments and skipped regions */
722 static int handle_bs(uint8_t **p
)
725 file
->buf_ptr
= *p
- 1;
731 /* skip the stray and handle the \\n case. Output an error if
732 incorrect char after the stray */
733 static int handle_stray(uint8_t **p
)
736 file
->buf_ptr
= *p
- 1;
737 c
= handle_stray_noerror(!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
));
742 /* handle the complicated stray case */
747 c = handle_stray(&p); \
750 static int skip_spaces(void)
756 } while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
);
760 /* single line C++ comments */
761 static uint8_t *parse_line_comment(uint8_t *p
)
768 if (c
== '\n' || c
== '\\')
771 if (c
== '\n' || c
== '\\')
786 static uint8_t *parse_comment(uint8_t *p
)
794 if (c
== '\n' || c
== '*' || c
== '\\')
797 if (c
== '\n' || c
== '*' || c
== '\\')
800 /* now we can handle all the cases */
803 } else if (c
== '*') {
816 tcc_error("unexpected end of file in comment");
824 /* parse a string without interpreting escapes */
825 static uint8_t *parse_pp_string(uint8_t *p
, int sep
, CString
*str
)
833 } else if (c
== '\\') {
837 /* XXX: indicate line number of start of string */
838 tok_flags
&= ~TOK_FLAG_BOL
;
839 tcc_error("missing terminating %c character", sep
);
840 } else if (c
== '\\') {
844 /* add char after '\\' unconditionally */
848 goto unterminated_string
;
854 } else if (c
== '\n') {
856 if (ACCEPT_LF_IN_STRINGS
) {
859 } else if (str
) { /* not skipping */
860 goto unterminated_string
;
862 //tcc_warning("missing terminating %c character", sep);
865 } else if (c
== '\r') {
872 goto unterminated_string
;
874 cstr_ccat(str
, '\r');
886 /* skip block of text until #else, #elif or #endif. skip also pairs of
888 static void preprocess_skip(void)
890 int a
, start_of_line
, c
, in_warn_or_error
;
897 in_warn_or_error
= 0;
923 if (in_warn_or_error
)
925 tok_flags
&= ~TOK_FLAG_BOL
;
926 p
= parse_pp_string(p
, c
, NULL
);
930 if (in_warn_or_error
)
935 p
= parse_comment(p
);
936 } else if (c
== '/') {
937 p
= parse_line_comment(p
);
947 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
949 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
951 else if (tok
== TOK_ENDIF
)
953 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
954 in_warn_or_error
= 1;
955 else if (tok
== TOK_LINEFEED
)
957 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
958 p
= parse_line_comment(p
- 1);
960 #if !defined(TCC_TARGET_ARM)
961 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
962 p
= parse_line_comment(p
- 1);
964 /* ARM assembly uses '#' for constants */
979 /* return the number of additional 'ints' necessary to store the
981 static inline int tok_size(const int *p
)
996 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
999 return 1 + LONG_SIZE
/ 4;
1005 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
1008 return 1 + LDOUBLE_SIZE
/ 4;
1016 /* token string handling */
1017 ST_INLN
void tok_str_new(TokenString
*s
)
1020 s
->len
= s
->lastlen
= 0;
1021 s
->allocated_len
= 0;
1022 s
->last_line_num
= -1;
1025 ST_FUNC TokenString
*tok_str_alloc(void)
1027 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1032 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1036 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1037 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1041 ST_FUNC
void tok_str_free_str(int *str
)
1043 tal_free(tokstr_alloc
, str
);
1046 ST_FUNC
void tok_str_free(TokenString
*str
)
1048 tok_str_free_str(str
->str
);
1049 tal_free(tokstr_alloc
, str
);
1052 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1056 size
= s
->allocated_len
;
1059 while (size
< new_size
)
1061 if (size
> s
->allocated_len
) {
1062 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1063 s
->allocated_len
= size
;
1069 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1075 if (len
>= s
->allocated_len
)
1076 str
= tok_str_realloc(s
, len
+ 1);
1081 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1084 str
->prev
= macro_stack
;
1085 str
->prev_ptr
= macro_ptr
;
1086 str
->save_line_num
= file
->line_num
;
1087 macro_ptr
= str
->str
;
1091 ST_FUNC
void end_macro(void)
1093 TokenString
*str
= macro_stack
;
1094 macro_stack
= str
->prev
;
1095 macro_ptr
= str
->prev_ptr
;
1096 file
->line_num
= str
->save_line_num
;
1097 str
->len
= 0; /* matters if str not alloced, may be tokstr_buf */
1098 if (str
->alloc
!= 0) {
1099 if (str
->alloc
== 2)
1100 str
->str
= NULL
; /* don't free */
1105 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1109 len
= s
->lastlen
= s
->len
;
1112 /* allocate space for worst case */
1113 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1114 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1127 str
[len
++] = cv
->tab
[0];
1134 /* Insert the string into the int array. */
1136 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1137 if (len
+ nb_words
>= s
->allocated_len
)
1138 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1139 str
[len
] = cv
->str
.size
;
1140 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1151 str
[len
++] = cv
->tab
[0];
1152 str
[len
++] = cv
->tab
[1];
1155 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1156 str
[len
++] = cv
->tab
[0];
1157 str
[len
++] = cv
->tab
[1];
1158 #elif LDOUBLE_SIZE == 12
1159 str
[len
++] = cv
->tab
[0];
1160 str
[len
++] = cv
->tab
[1];
1161 str
[len
++] = cv
->tab
[2];
1162 #elif LDOUBLE_SIZE == 16
1163 str
[len
++] = cv
->tab
[0];
1164 str
[len
++] = cv
->tab
[1];
1165 str
[len
++] = cv
->tab
[2];
1166 str
[len
++] = cv
->tab
[3];
1168 #error add long double size support
1177 /* add the current parse token in token string 's' */
1178 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1182 /* save line number info */
1183 if (file
->line_num
!= s
->last_line_num
) {
1184 s
->last_line_num
= file
->line_num
;
1185 cval
.i
= s
->last_line_num
;
1186 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1188 tok_str_add2(s
, tok
, &tokc
);
1191 /* get a token from an integer array and increment pointer. */
1192 static inline void tok_get(int *t
, const int **pp
, CValue
*cv
)
1212 cv
->i
= (unsigned)*p
++;
1221 cv
->str
.size
= *p
++;
1223 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1235 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1237 #elif LDOUBLE_SIZE == 12
1239 #elif LDOUBLE_SIZE == 16
1242 # error add long double size support
1256 # define TOK_GET(t,p,c) tok_get(t,p,c)
1258 # define TOK_GET(t,p,c) do { \
1260 if (TOK_HAS_VALUE(_t)) \
1263 *(t) = _t, ++*(p); \
1267 static int macro_is_equal(const int *a
, const int *b
)
1276 cstr_reset(&tokcstr
);
1277 TOK_GET(&t
, &a
, &cv
);
1278 cstr_cat(&tokcstr
, get_tok_str(t
, &cv
), 0);
1279 TOK_GET(&t
, &b
, &cv
);
1280 if (strcmp(tokcstr
.data
, get_tok_str(t
, &cv
)))
1286 /* defines handling */
1287 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1292 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1294 s
->next
= first_arg
;
1295 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1297 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1298 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1301 /* undefined a define symbol. Its name is just set to zero */
1302 ST_FUNC
void define_undef(Sym
*s
)
1305 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1306 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1309 ST_INLN Sym
*define_find(int v
)
1312 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1314 return table_ident
[v
]->sym_define
;
1317 /* free define stack until top reaches 'b' */
1318 ST_FUNC
void free_defines(Sym
*b
)
1320 while (define_stack
!= b
) {
1321 Sym
*top
= define_stack
;
1322 define_stack
= top
->prev
;
1323 tok_str_free_str(top
->d
);
1329 /* fake the nth "#if defined test_..." for tcc -dt -run */
1330 static void maybe_run_test(TCCState
*s
)
1333 if (s
->include_stack_ptr
!= s
->include_stack
)
1335 p
= get_tok_str(tok
, NULL
);
1336 if (0 != memcmp(p
, "test_", 5))
1338 if (0 != --s
->run_test
)
1340 fprintf(s
->ppfp
, &"\n[%s]\n"[!(s
->dflag
& 32)], p
), fflush(s
->ppfp
);
1341 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1344 static CachedInclude
*
1345 search_cached_include(TCCState
*s1
, const char *filename
, int add
);
1347 static int parse_include(TCCState
*s1
, int do_next
, int test
)
1350 char name
[1024], buf
[1024], *p
;
1354 if (c
== '<' || c
== '\"') {
1355 cstr_reset(&tokcstr
);
1356 file
->buf_ptr
= parse_pp_string(file
->buf_ptr
, c
== '<' ? '>' : c
, &tokcstr
);
1358 pstrncpy(name
, tokcstr
.data
, i
>= sizeof name
? sizeof name
- 1 : i
);
1361 /* computed #include : concatenate tokens until result is one of
1362 the two accepted forms. Don't convert pp-tokens to tokens here. */
1363 parse_flags
= PARSE_FLAG_PREPROCESS
1364 | PARSE_FLAG_LINEFEED
1365 | (parse_flags
& PARSE_FLAG_ASM_FILE
);
1369 p
= name
, i
= strlen(p
) - 1;
1371 && ((p
[0] == '"' && p
[i
] == '"')
1372 || (p
[0] == '<' && p
[i
] == '>')))
1374 if (tok
== TOK_LINEFEED
)
1375 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1376 pstrcat(name
, sizeof name
, get_tok_str(tok
, &tokc
));
1379 /* remove '<>|""' */
1380 memmove(p
, p
+ 1, i
- 1), p
[i
- 1] = 0;
1383 i
= do_next
? file
->include_next_index
: -1;
1387 /* check absolute include path */
1388 if (!IS_ABSPATH(name
))
1391 } else if (i
== 1) {
1392 /* search in file's dir if "header.h" */
1395 p
= file
->true_filename
;
1396 pstrncpy(buf
, p
, tcc_basename(p
) - p
);
1398 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1400 p
= s1
->include_paths
[j
];
1401 else if (k
< s1
->nb_sysinclude_paths
)
1402 p
= s1
->sysinclude_paths
[k
];
1406 tcc_error("include file '%s' not found", name
);
1407 pstrcpy(buf
, sizeof buf
, p
);
1408 pstrcat(buf
, sizeof buf
, "/");
1410 pstrcat(buf
, sizeof buf
, name
);
1411 e
= search_cached_include(s1
, buf
, 0);
1412 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
)) {
1413 /* no need to parse the include because the 'ifndef macro'
1414 is defined (or had #pragma once) */
1416 printf("%s: skipping cached %s\n", file
->filename
, buf
);
1420 if (tcc_open(s1
, buf
) >= 0)
1427 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1428 tcc_error("#include recursion too deep");
1429 /* push previous file on stack */
1430 *s1
->include_stack_ptr
++ = file
->prev
;
1431 file
->include_next_index
= i
;
1433 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1435 /* update target deps */
1437 BufferedFile
*bf
= file
;
1438 while (i
== 1 && (bf
= bf
->prev
))
1439 i
= bf
->include_next_index
;
1440 /* skip system include files */
1441 if (s1
->include_sys_deps
|| i
- 2 < s1
->nb_include_paths
)
1442 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1445 /* add include file debug info */
1446 tcc_debug_bincl(s1
);
1447 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1452 /* eval an expression for #if/#elif */
1453 static int expr_preprocess(TCCState
*s1
)
1458 str
= tok_str_alloc();
1460 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1461 next(); /* do macro subst */
1463 if (tok
< TOK_IDENT
) {
1464 if (tok
>= TOK_STR
&& tok
<= TOK_CLDOUBLE
)
1465 tcc_error("invalid constant in preprocessor expression");
1466 } else if (tok
== TOK_DEFINED
) {
1471 if (tok
< TOK_IDENT
)
1472 expect("identifier");
1476 if (define_find(tok
)
1477 || tok
== TOK___HAS_INCLUDE
1478 || tok
== TOK___HAS_INCLUDE_NEXT
)
1487 } else if (tok
== TOK___HAS_INCLUDE
||
1488 tok
== TOK___HAS_INCLUDE_NEXT
) {
1493 c
= parse_include(s1
, t
- TOK___HAS_INCLUDE
, 1);
1499 /* if undefined macro, replace with zero, check for func-like */
1503 tok_str_add_tok(str
);
1506 tcc_error("function-like macro '%s' is not defined",
1507 get_tok_str(t
, NULL
));
1510 tok_str_add_tok(str
);
1513 tok_str_add(str
, -1); /* simulate end of file */
1514 tok_str_add(str
, 0);
1515 /* now evaluate C constant expression */
1516 begin_macro(str
, 1);
1524 /* parse after #define */
1525 ST_FUNC
void parse_define(void)
1527 Sym
*s
, *first
, **ps
;
1528 int v
, t
, varg
, is_vaargs
, spc
;
1529 int saved_parse_flags
= parse_flags
;
1532 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1533 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1534 /* XXX: should check if same macro (ANSI) */
1537 /* We have to parse the whole define as if not in asm mode, in particular
1538 no line comment with '#' must be ignored. Also for function
1539 macros the argument list must be parsed without '.' being an ID
1541 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1542 /* '(' must be just after macro definition for MACRO_FUNC */
1544 parse_flags
&= ~PARSE_FLAG_SPACES
;
1546 int dotid
= set_idnum('.', 0);
1549 if (tok
!= ')') for (;;) {
1553 if (varg
== TOK_DOTS
) {
1554 varg
= TOK___VA_ARGS__
;
1556 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1560 if (varg
< TOK_IDENT
)
1562 tcc_error("bad macro parameter list");
1563 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1568 if (tok
!= ',' || is_vaargs
)
1572 parse_flags
|= PARSE_FLAG_SPACES
;
1575 set_idnum('.', dotid
);
1580 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1581 /* The body of a macro definition should be parsed such that identifiers
1582 are parsed like the file mode determines (i.e. with '.' being an
1583 ID character in asm mode). But '#' should be retained instead of
1584 regarded as line comment leader, so still don't set ASM_FILE
1586 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1587 /* remove spaces around ## and after '#' */
1588 if (TOK_TWOSHARPS
== tok
) {
1595 } else if ('#' == tok
) {
1597 } else if (check_space(tok
, &spc
)) {
1600 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1605 parse_flags
= saved_parse_flags
;
1607 --tokstr_buf
.len
; /* remove trailing space */
1608 tok_str_add(&tokstr_buf
, 0);
1611 tcc_error("'##' cannot appear at either end of macro");
1612 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1615 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1617 const char *s
, *basename
;
1622 s
= basename
= tcc_basename(filename
);
1624 while ((c
= (unsigned char)*s
) != 0) {
1626 h
= TOK_HASH_FUNC(h
, toup(c
));
1628 h
= TOK_HASH_FUNC(h
, c
);
1632 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1634 i
= s1
->cached_includes_hash
[h
];
1638 e
= s1
->cached_includes
[i
- 1];
1639 if (0 == PATHCMP(filename
, e
->filename
))
1642 && 0 == PATHCMP(basename
, tcc_basename(e
->filename
))
1643 && 0 == normalized_PATHCMP(filename
, e
->filename
)
1651 e
= tcc_malloc(sizeof(CachedInclude
) + (len
= strlen(filename
)));
1652 memcpy(e
->filename
, filename
, len
+ 1);
1653 e
->ifndef_macro
= e
->once
= 0;
1654 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1655 /* add in hash table */
1656 e
->hash_next
= s1
->cached_includes_hash
[h
];
1657 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1659 printf("adding cached '%s'\n", filename
);
1664 static void pragma_parse(TCCState
*s1
)
1667 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1671 if (next(), tok
!= '(')
1673 if (next(), tok
!= TOK_STR
)
1675 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1676 if (next(), tok
!= ')')
1678 if (t
== TOK_push_macro
) {
1679 while (NULL
== (s
= define_find(v
)))
1680 define_push(v
, 0, NULL
, NULL
);
1681 s
->type
.ref
= s
; /* set push boundary */
1683 for (s
= define_stack
; s
; s
= s
->prev
)
1684 if (s
->v
== v
&& s
->type
.ref
== s
) {
1690 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1692 tcc_warning("unbalanced #pragma pop_macro");
1693 pp_debug_tok
= t
, pp_debug_symv
= v
;
1695 } else if (tok
== TOK_once
) {
1696 search_cached_include(s1
, file
->filename
, 1)->once
= 1;
1698 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1699 /* tcc -E: keep pragmas below unchanged */
1701 unget_tok(TOK_PRAGMA
);
1703 unget_tok(TOK_LINEFEED
);
1705 } else if (tok
== TOK_pack
) {
1707 #pragma pack(1) // set
1708 #pragma pack() // reset to default
1709 #pragma pack(push) // push current
1710 #pragma pack(push,1) // push & set
1711 #pragma pack(pop) // restore previous */
1714 if (tok
== TOK_ASM_pop
) {
1716 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1718 tcc_error("out of pack stack");
1720 s1
->pack_stack_ptr
--;
1724 if (tok
== TOK_ASM_push
) {
1726 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1728 val
= *s1
->pack_stack_ptr
++;
1733 if (tok
!= TOK_CINT
)
1736 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1741 *s1
->pack_stack_ptr
= val
;
1746 } else if (tok
== TOK_comment
) {
1755 p
= tcc_strdup((char *)tokc
.str
.data
);
1760 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1762 if (t
== TOK_option
)
1763 tcc_set_options(s1
, p
);
1768 tcc_warning_c(warn_unsupported
)("#pragma %s ignored", get_tok_str(tok
, &tokc
));
1772 tcc_error("malformed #pragma directive");
1776 /* is_bof is true if first non space token at beginning of file */
1777 ST_FUNC
void preprocess(int is_bof
)
1779 TCCState
*s1
= tcc_state
;
1780 int c
, n
, saved_parse_flags
;
1784 saved_parse_flags
= parse_flags
;
1785 parse_flags
= PARSE_FLAG_PREPROCESS
1786 | PARSE_FLAG_TOK_NUM
1787 | PARSE_FLAG_TOK_STR
1788 | PARSE_FLAG_LINEFEED
1789 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1798 pp_debug_symv
= tok
;
1804 pp_debug_symv
= tok
;
1805 s
= define_find(tok
);
1806 /* undefine symbol by putting an invalid name */
1811 case TOK_INCLUDE_NEXT
:
1812 parse_include(s1
, tok
- TOK_INCLUDE
, 0);
1818 c
= expr_preprocess(s1
);
1824 if (tok
< TOK_IDENT
)
1825 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1829 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1831 file
->ifndef_macro
= tok
;
1834 if (define_find(tok
)
1835 || tok
== TOK___HAS_INCLUDE
1836 || tok
== TOK___HAS_INCLUDE_NEXT
)
1839 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1840 tcc_error("memory full (ifdef)");
1841 *s1
->ifdef_stack_ptr
++ = c
;
1844 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1845 tcc_error("#else without matching #if");
1846 if (s1
->ifdef_stack_ptr
[-1] & 2)
1847 tcc_error("#else after #else");
1848 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1851 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1852 tcc_error("#elif without matching #if");
1853 c
= s1
->ifdef_stack_ptr
[-1];
1855 tcc_error("#elif after #else");
1856 /* last #if/#elif expression was true: we skip */
1860 c
= expr_preprocess(s1
);
1861 s1
->ifdef_stack_ptr
[-1] = c
;
1864 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1865 file
->ifndef_macro
= 0;
1874 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1875 tcc_error("#endif without matching #if");
1876 s1
->ifdef_stack_ptr
--;
1877 /* '#ifndef macro' was at the start of file. Now we check if
1878 an '#endif' is exactly at the end of file */
1879 if (file
->ifndef_macro
&&
1880 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1881 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1882 /* need to set to zero to avoid false matches if another
1883 #ifndef at middle of file */
1884 file
->ifndef_macro
= 0;
1885 while (tok
!= TOK_LINEFEED
)
1887 tok_flags
|= TOK_FLAG_ENDIF
;
1892 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1896 if (tok
!= TOK_CINT
)
1898 tcc_error("wrong #line format");
1902 if (tok
!= TOK_LINEFEED
) {
1903 if (tok
== TOK_STR
) {
1904 if (file
->true_filename
== file
->filename
)
1905 file
->true_filename
= tcc_strdup(file
->filename
);
1906 q
= (char *)tokc
.str
.data
;
1908 if (!IS_ABSPATH(q
)) {
1909 /* prepend directory from real file */
1910 pstrcpy(buf
, sizeof buf
, file
->true_filename
);
1911 *tcc_basename(buf
) = 0;
1913 pstrcat(buf
, sizeof buf
, q
);
1914 tcc_debug_putfile(s1
, buf
);
1915 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1922 total_lines
+= file
->line_num
- n
;
1929 while (c
!= '\n' && c
!= CH_EOF
) {
1930 if ((q
- buf
) < sizeof(buf
) - 1)
1935 if (tok
== TOK_ERROR
)
1936 tcc_error("#error %s", buf
);
1938 tcc_warning("#warning %s", buf
);
1946 /* ignore gas line comment in an 'S' file. */
1947 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
1949 if (tok
== '!' && is_bof
)
1950 /* '!' is ignored at beginning to allow C scripts. */
1952 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1954 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
1957 /* ignore other preprocess commands or #! for C scripts */
1958 while (tok
!= TOK_LINEFEED
)
1961 parse_flags
= saved_parse_flags
;
1964 /* evaluate escape codes in a string. */
1965 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1980 case '0': case '1': case '2': case '3':
1981 case '4': case '5': case '6': case '7':
1982 /* at most three octal digits */
1987 n
= n
* 8 + c
- '0';
1991 n
= n
* 8 + c
- '0';
1996 goto add_char_nonext
;
1997 case 'x': i
= 0; goto parse_hex_or_ucn
;
1998 case 'u': i
= 4; goto parse_hex_or_ucn
;
1999 case 'U': i
= 8; goto parse_hex_or_ucn
;
2005 if (c
>= 'a' && c
<= 'f')
2007 else if (c
>= 'A' && c
<= 'F')
2012 expect("more hex digits in universal-character-name");
2014 goto add_hex_or_ucn
;
2021 goto add_char_nonext
;
2023 cstr_u8cat(outstr
, n
);
2048 goto invalid_escape
;
2058 if (c
>= '!' && c
<= '~')
2059 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2061 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2064 } else if (is_long
&& c
>= 0x80) {
2065 /* assume we are processing UTF-8 sequence */
2066 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2068 int cont
; /* count of continuation bytes */
2069 int skip
; /* how many bytes should skip when error occurred */
2072 /* decode leading byte */
2074 skip
= 1; goto invalid_utf8_sequence
;
2075 } else if (c
<= 0xDF) {
2076 cont
= 1; n
= c
& 0x1f;
2077 } else if (c
<= 0xEF) {
2078 cont
= 2; n
= c
& 0xf;
2079 } else if (c
<= 0xF4) {
2080 cont
= 3; n
= c
& 0x7;
2082 skip
= 1; goto invalid_utf8_sequence
;
2085 /* decode continuation bytes */
2086 for (i
= 1; i
<= cont
; i
++) {
2087 int l
= 0x80, h
= 0xBF;
2089 /* adjust limit for second byte */
2092 case 0xE0: l
= 0xA0; break;
2093 case 0xED: h
= 0x9F; break;
2094 case 0xF0: l
= 0x90; break;
2095 case 0xF4: h
= 0x8F; break;
2099 if (p
[i
] < l
|| p
[i
] > h
) {
2100 skip
= i
; goto invalid_utf8_sequence
;
2103 n
= (n
<< 6) | (p
[i
] & 0x3f);
2106 /* advance pointer */
2109 goto add_char_nonext
;
2111 /* error handling */
2112 invalid_utf8_sequence
:
2113 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c
);
2116 goto add_char_nonext
;
2122 cstr_ccat(outstr
, c
);
2124 #ifdef TCC_TARGET_PE
2125 /* store as UTF-16 */
2127 cstr_wccat(outstr
, c
);
2130 cstr_wccat(outstr
, (c
>> 10) + 0xD800);
2131 cstr_wccat(outstr
, (c
& 0x3FF) + 0xDC00);
2134 cstr_wccat(outstr
, c
);
2138 /* add a trailing '\0' */
2140 cstr_ccat(outstr
, '\0');
2142 cstr_wccat(outstr
, '\0');
2145 static void parse_string(const char *s
, int len
)
2147 uint8_t buf
[1000], *p
= buf
;
2150 if ((is_long
= *s
== 'L'))
2154 if (len
>= sizeof buf
)
2155 p
= tcc_malloc(len
+ 1);
2159 cstr_reset(&tokcstr
);
2160 parse_escape_string(&tokcstr
, p
, is_long
);
2165 int char_size
, i
, n
, c
;
2166 /* XXX: make it portable */
2168 tok
= TOK_CCHAR
, char_size
= 1;
2170 tok
= TOK_LCHAR
, char_size
= sizeof(nwchar_t
);
2171 n
= tokcstr
.size
/ char_size
- 1;
2173 tcc_error("empty character constant");
2175 tcc_warning_c(warn_all
)("multi-character character constant");
2176 for (c
= i
= 0; i
< n
; ++i
) {
2178 c
= ((nwchar_t
*)tokcstr
.data
)[i
];
2180 c
= (c
<< 8) | ((char *)tokcstr
.data
)[i
];
2184 tokc
.str
.size
= tokcstr
.size
;
2185 tokc
.str
.data
= tokcstr
.data
;
2193 /* we use 64 bit numbers */
2196 /* bn = (bn << shift) | or_val */
2197 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2201 for(i
=0;i
<BN_SIZE
;i
++) {
2203 bn
[i
] = (v
<< shift
) | or_val
;
2204 or_val
= v
>> (32 - shift
);
2208 static void bn_zero(unsigned int *bn
)
2211 for(i
=0;i
<BN_SIZE
;i
++) {
2216 /* parse number in null terminated string 'p' and return it in the
2218 static void parse_number(const char *p
)
2220 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2222 unsigned int bn
[BN_SIZE
];
2233 goto float_frac_parse
;
2234 } else if (t
== '0') {
2235 if (ch
== 'x' || ch
== 'X') {
2239 } else if (tcc_state
->tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2245 /* parse all digits. cannot check octal numbers at this stage
2246 because of floating point constants */
2248 if (ch
>= 'a' && ch
<= 'f')
2250 else if (ch
>= 'A' && ch
<= 'F')
2258 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2260 tcc_error("number too long");
2266 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2267 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2269 /* NOTE: strtox should support that for hexa numbers, but
2270 non ISOC99 libcs do not support it, so we prefer to do
2272 /* hexadecimal or binary floats */
2273 /* XXX: handle overflows */
2285 } else if (t
>= 'a') {
2287 } else if (t
>= 'A') {
2292 bn_lshift(bn
, shift
, t
);
2299 if (t
>= 'a' && t
<= 'f') {
2301 } else if (t
>= 'A' && t
<= 'F') {
2303 } else if (t
>= '0' && t
<= '9') {
2309 tcc_error("invalid digit");
2310 bn_lshift(bn
, shift
, t
);
2315 if (ch
!= 'p' && ch
!= 'P')
2322 } else if (ch
== '-') {
2326 if (ch
< '0' || ch
> '9')
2327 expect("exponent digits");
2328 while (ch
>= '0' && ch
<= '9') {
2329 exp_val
= exp_val
* 10 + ch
- '0';
2332 exp_val
= exp_val
* s
;
2334 /* now we can generate the number */
2335 /* XXX: should patch directly float number */
2336 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2337 d
= ldexp(d
, exp_val
- frac_bits
);
2342 /* float : should handle overflow */
2344 } else if (t
== 'L') {
2347 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2350 /* XXX: not large enough */
2351 tokc
.ld
= (long double)d
;
2358 /* decimal floats */
2360 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2365 while (ch
>= '0' && ch
<= '9') {
2366 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2372 if (ch
== 'e' || ch
== 'E') {
2373 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2377 if (ch
== '-' || ch
== '+') {
2378 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2383 if (ch
< '0' || ch
> '9')
2384 expect("exponent digits");
2385 while (ch
>= '0' && ch
<= '9') {
2386 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2398 tokc
.f
= strtof(token_buf
, NULL
);
2399 } else if (t
== 'L') {
2402 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2403 tokc
.d
= strtod(token_buf
, NULL
);
2405 tokc
.ld
= strtold(token_buf
, NULL
);
2409 tokc
.d
= strtod(token_buf
, NULL
);
2413 unsigned long long n
, n1
;
2414 int lcount
, ucount
, ov
= 0;
2417 /* integer number */
2420 if (b
== 10 && *q
== '0') {
2427 /* no need for checks except for base 10 / 8 errors */
2437 tcc_error("invalid digit");
2440 /* detect overflow */
2441 if (n1
>= 0x1000000000000000ULL
&& n
/ b
!= n1
)
2445 /* Determine the characteristics (unsigned and/or 64bit) the type of
2446 the constant must have according to the constant suffix(es) */
2447 lcount
= ucount
= 0;
2453 tcc_error("three 'l's in integer constant");
2454 if (lcount
&& *(p
- 1) != ch
)
2455 tcc_error("incorrect integer suffix: %s", p1
);
2458 } else if (t
== 'U') {
2460 tcc_error("two 'u's in integer constant");
2468 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2469 if (ucount
== 0 && b
== 10) {
2470 if (lcount
<= (LONG_SIZE
== 4)) {
2471 if (n
>= 0x80000000U
)
2472 lcount
= (LONG_SIZE
== 4) + 1;
2474 if (n
>= 0x8000000000000000ULL
)
2477 if (lcount
<= (LONG_SIZE
== 4)) {
2478 if (n
>= 0x100000000ULL
)
2479 lcount
= (LONG_SIZE
== 4) + 1;
2480 else if (n
>= 0x80000000U
)
2483 if (n
>= 0x8000000000000000ULL
)
2488 tcc_warning("integer constant overflow");
2497 ++tok
; /* TOK_CU... */
2501 tcc_error("invalid number");
2505 #define PARSE2(c1, tok1, c2, tok2) \
2516 /* return next token without macro substitution */
2517 static inline void next_nomacro1(void)
2519 int t
, c
, is_long
, len
;
2533 if (parse_flags
& PARSE_FLAG_SPACES
)
2534 goto keep_tok_flags
;
2535 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2544 /* first look if it is in fact an end of buffer */
2545 c
= handle_stray(&p
);
2549 TCCState
*s1
= tcc_state
;
2550 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2551 && !(tok_flags
& TOK_FLAG_EOF
)) {
2552 tok_flags
|= TOK_FLAG_EOF
;
2554 goto keep_tok_flags
;
2555 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2557 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2558 tcc_error("missing #endif");
2559 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2560 /* no include left : end of file. */
2563 tok_flags
&= ~TOK_FLAG_EOF
;
2564 /* pop include file */
2566 /* test if previous '#endif' was after a #ifdef at
2568 if (tok_flags
& TOK_FLAG_ENDIF
) {
2570 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2572 search_cached_include(s1
, file
->filename
, 1)
2573 ->ifndef_macro
= file
->ifndef_macro_saved
;
2574 tok_flags
&= ~TOK_FLAG_ENDIF
;
2577 /* add end of include file debug info */
2578 tcc_debug_eincl(tcc_state
);
2579 /* pop include stack */
2581 s1
->include_stack_ptr
--;
2583 if (p
== file
->buffer
)
2584 tok_flags
= TOK_FLAG_BOF
;
2585 tok_flags
|= TOK_FLAG_BOL
;
2595 tok_flags
|= TOK_FLAG_BOL
;
2598 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2601 goto keep_tok_flags
;
2606 if ((tok_flags
& TOK_FLAG_BOL
) &&
2607 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2609 preprocess(tok_flags
& TOK_FLAG_BOF
);
2615 tok
= TOK_TWOSHARPS
;
2617 #if !defined(TCC_TARGET_ARM)
2618 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2619 p
= parse_line_comment(p
- 1);
2630 /* dollar is allowed to start identifiers when not parsing asm */
2632 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2633 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2636 case 'a': case 'b': case 'c': case 'd':
2637 case 'e': case 'f': case 'g': case 'h':
2638 case 'i': case 'j': case 'k': case 'l':
2639 case 'm': case 'n': case 'o': case 'p':
2640 case 'q': case 'r': case 's': case 't':
2641 case 'u': case 'v': case 'w': case 'x':
2643 case 'A': case 'B': case 'C': case 'D':
2644 case 'E': case 'F': case 'G': case 'H':
2645 case 'I': case 'J': case 'K':
2646 case 'M': case 'N': case 'O': case 'P':
2647 case 'Q': case 'R': case 'S': case 'T':
2648 case 'U': case 'V': case 'W': case 'X':
2654 h
= TOK_HASH_FUNC(h
, c
);
2655 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2656 h
= TOK_HASH_FUNC(h
, c
);
2661 /* fast case : no stray found, so we have the full token
2662 and we have already hashed it */
2663 h
&= (TOK_HASH_SIZE
- 1);
2664 pts
= &hash_ident
[h
];
2669 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2671 pts
= &(ts
->hash_next
);
2673 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2677 cstr_reset(&tokcstr
);
2678 cstr_cat(&tokcstr
, (char *) p1
, len
);
2682 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2684 cstr_ccat(&tokcstr
, c
);
2687 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2693 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2695 goto parse_ident_fast
;
2698 if (c
== '\'' || c
== '\"') {
2702 cstr_reset(&tokcstr
);
2703 cstr_ccat(&tokcstr
, 'L');
2704 goto parse_ident_slow
;
2709 case '0': case '1': case '2': case '3':
2710 case '4': case '5': case '6': case '7':
2714 /* after the first digit, accept digits, alpha, '.' or sign if
2715 prefixed by 'eEpP' */
2717 cstr_reset(&tokcstr
);
2719 cstr_ccat(&tokcstr
, t
);
2720 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2722 || ((c
== '+' || c
== '-')
2723 && (((t
== 'e' || t
== 'E')
2724 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2725 /* 0xe+1 is 3 tokens in asm */
2726 && ((char*)tokcstr
.data
)[0] == '0'
2727 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2728 || t
== 'p' || t
== 'P'))))
2733 /* We add a trailing '\0' to ease parsing */
2734 cstr_ccat(&tokcstr
, '\0');
2735 tokc
.str
.size
= tokcstr
.size
;
2736 tokc
.str
.data
= tokcstr
.data
;
2741 /* special dot handling because it can also start a number */
2746 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2747 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2749 goto parse_ident_fast
;
2750 } else if (c
== '.') {
2756 *--p
= '.'; /* may underflow into file->unget[] */
2767 cstr_reset(&tokcstr
);
2769 cstr_ccat(&tokcstr
, 'L');
2770 cstr_ccat(&tokcstr
, c
);
2771 p
= parse_pp_string(p
, c
, &tokcstr
);
2772 cstr_ccat(&tokcstr
, c
);
2773 cstr_ccat(&tokcstr
, '\0');
2774 tokc
.str
.size
= tokcstr
.size
;
2775 tokc
.str
.data
= tokcstr
.data
;
2784 } else if (c
== '<') {
2801 } else if (c
== '>') {
2819 } else if (c
== '=') {
2832 } else if (c
== '=') {
2845 } else if (c
== '=') {
2858 } else if (c
== '=') {
2861 } else if (c
== '>') {
2869 PARSE2('!', '!', '=', TOK_NE
)
2870 PARSE2('=', '=', '=', TOK_EQ
)
2871 PARSE2('*', '*', '=', TOK_A_MUL
)
2872 PARSE2('%', '%', '=', TOK_A_MOD
)
2873 PARSE2('^', '^', '=', TOK_A_XOR
)
2875 /* comments or operator */
2879 p
= parse_comment(p
);
2880 /* comments replaced by a blank */
2883 } else if (c
== '/') {
2884 p
= parse_line_comment(p
);
2887 } else if (c
== '=') {
2907 case '@': /* only used in assembler */
2913 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
2914 goto parse_ident_fast
;
2915 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2917 tcc_error("unrecognized character \\x%02x", c
);
2923 #if defined(PARSE_DEBUG)
2924 printf("token = %d %s\n", tok
, get_tok_str(tok
, &tokc
));
2928 static void macro_subst(
2929 TokenString
*tok_str
,
2931 const int *macro_str
2934 /* substitute arguments in replacement lists in macro_str by the values in
2935 args (field d) and return allocated string */
2936 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2947 TOK_GET(&t
, ¯o_str
, &cval
);
2952 TOK_GET(&t
, ¯o_str
, &cval
);
2955 s
= sym_find2(args
, t
);
2957 cstr_reset(&tokcstr
);
2958 cstr_ccat(&tokcstr
, '\"');
2962 TOK_GET(&t
, &st
, &cval
);
2963 if (t
!= TOK_NOSUBST
2964 && 0 == check_space(t
, &spc
)) {
2965 const char *s
= get_tok_str(t
, &cval
);
2967 if (t
== TOK_PPSTR
&& *s
!= '\'')
2968 add_char(&tokcstr
, *s
);
2970 cstr_ccat(&tokcstr
, *s
);
2975 tokcstr
.size
-= spc
;
2976 cstr_ccat(&tokcstr
, '\"');
2977 cstr_ccat(&tokcstr
, '\0');
2979 printf("\nstringize: <%s>\n", (char *)tokcstr
.data
);
2982 cval
.str
.size
= tokcstr
.size
;
2983 cval
.str
.data
= tokcstr
.data
;
2984 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
2987 expect("macro parameter after '#'");
2989 } else if (t
>= TOK_IDENT
) {
2990 s
= sym_find2(args
, t
);
2993 /* if '##' is present before or after, no arg substitution */
2994 if (*macro_str
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
2995 /* special case for var arg macros : ## eats the ','
2996 if empty VA_ARGS variable. */
2997 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
2999 /* suppress ',' '##' */
3002 /* suppress '##' and add variable */
3007 if (*st
<= 0) /* expanded to empty string */
3008 tok_str_add(&str
, TOK_PLCHLDR
);
3013 /* Expand arguments tokens and store them. In most
3014 cases we could also re-expand each argument if
3015 used multiple times, but not if the argument
3016 contains the __COUNTER__ macro. */
3018 sym_push2(&s
->next
, s
->v
, s
->type
.t
, 0);
3020 macro_subst(&str2
, nested_list
, st
);
3021 tok_str_add(&str2
, 0);
3022 s
->next
->d
= str2
.str
;
3028 TOK_GET(&t2
, &st
, &cval
);
3031 tok_str_add2(&str
, t2
, &cval
);
3034 tok_str_add(&str
, t
);
3037 tok_str_add2(&str
, t
, &cval
);
3041 tok_str_add(&str
, 0);
3045 static char const ab_month_name
[12][4] =
3047 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3048 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3051 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3055 cstr_reset(&tokcstr
);
3056 if (t1
!= TOK_PLCHLDR
)
3057 cstr_cat(&tokcstr
, get_tok_str(t1
, v1
), -1);
3059 if (t2
!= TOK_PLCHLDR
)
3060 cstr_cat(&tokcstr
, get_tok_str(t2
, v2
), -1);
3061 cstr_ccat(&tokcstr
, '\0');
3062 //printf("paste <%s>\n", (char*)tokcstr.data);
3064 tcc_open_bf(tcc_state
, ":paste:", tokcstr
.size
);
3065 memcpy(file
->buffer
, tokcstr
.data
, tokcstr
.size
);
3069 if (0 == *file
->buf_ptr
)
3073 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3074 " preprocessing token", n
, file
->buffer
, file
->buffer
+ n
);
3082 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3083 return the resulting string (which must be freed). */
3084 static inline int *macro_twosharps(const int *ptr0
)
3088 TokenString macro_str1
;
3089 int start_of_nosubsts
= -1;
3092 /* we search the first '##' */
3093 for (ptr
= ptr0
;;) {
3094 TOK_GET(&t
, &ptr
, &cval
);
3095 if (t
== TOK_PPJOIN
)
3101 tok_str_new(¯o_str1
);
3103 //tok_print(" $$$", ptr0);
3104 for (ptr
= ptr0
;;) {
3105 TOK_GET(&t
, &ptr
, &cval
);
3108 if (t
== TOK_PPJOIN
)
3110 while (*ptr
== TOK_PPJOIN
) {
3112 /* given 'a##b', remove nosubsts preceding 'a' */
3113 if (start_of_nosubsts
>= 0)
3114 macro_str1
.len
= start_of_nosubsts
;
3115 /* given 'a##b', remove nosubsts preceding 'b' */
3116 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3118 if (t1
&& t1
!= TOK_PPJOIN
) {
3119 TOK_GET(&t1
, &ptr
, &cv1
);
3120 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3121 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3122 t
= tok
, cval
= tokc
;
3124 tok_str_add2(¯o_str1
, t
, &cval
);
3130 if (t
== TOK_NOSUBST
) {
3131 if (start_of_nosubsts
< 0)
3132 start_of_nosubsts
= macro_str1
.len
;
3134 start_of_nosubsts
= -1;
3136 if (t
!= TOK_PLCHLDR
)
3137 tok_str_add2(¯o_str1
, t
, &cval
);
3139 tok_str_add(¯o_str1
, 0);
3140 //tok_print(" ###", macro_str1.str);
3141 return macro_str1
.str
;
3144 /* peek or read [ws_str == NULL] next token from function macro call,
3145 walking up macro levels up to the file if necessary */
3146 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3154 p
= macro_ptr
, t
= *p
;
3156 while (is_space(t
) || TOK_LINEFEED
== t
)
3157 tok_str_add(ws_str
, t
), t
= *++p
;
3161 /* also, end of scope for nested defined symbol */
3163 while (sa
&& sa
->v
== 0)
3170 uint8_t *p
= file
->buf_ptr
;
3171 int ch
= handle_bs(&p
);
3173 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3178 p
= parse_comment(p
) - 1;
3179 } else if (c
== '/') {
3180 p
= parse_line_comment(p
) - 1;
3189 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3190 tok_str_add(ws_str
, ch
);
3205 /* do macro substitution of current token with macro 's' and add
3206 result to (tok_str,tok_len). 'nested_list' is the list of all
3207 macros we got inside to avoid recursing. Return non zero if no
3208 substitution needs to be done */
3209 static int macro_subst_tok(
3210 TokenString
*tok_str
,
3214 Sym
*args
, *sa
, *sa1
;
3215 int parlevel
, t
, t1
, spc
;
3221 /* if symbol is a macro, prepare substitution */
3222 /* special macros */
3223 if (tok
== TOK___LINE__
|| tok
== TOK___COUNTER__
) {
3224 t
= tok
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3225 snprintf(buf
, sizeof(buf
), "%d", t
);
3229 } else if (tok
== TOK___FILE__
) {
3230 cstrval
= file
->filename
;
3232 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3237 tm
= localtime(&ti
);
3238 if (tok
== TOK___DATE__
) {
3239 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3240 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3242 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3243 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3249 cstr_reset(&tokcstr
);
3250 cstr_cat(&tokcstr
, cstrval
, 0);
3251 cval
.str
.size
= tokcstr
.size
;
3252 cval
.str
.data
= tokcstr
.data
;
3253 tok_str_add2(tok_str
, t1
, &cval
);
3255 int saved_parse_flags
= parse_flags
;
3256 int *joined_str
= NULL
;
3259 if (s
->type
.t
== MACRO_FUNC
) {
3260 /* whitespace between macro name and argument list */
3262 tok_str_new(&ws_str
);
3265 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3266 | PARSE_FLAG_ACCEPT_STRAYS
;
3268 /* get next token from argument stream */
3269 t
= next_argstream(nested_list
, &ws_str
);
3271 /* not a macro substitution after all, restore the
3272 * macro token plus all whitespace we've read.
3273 * whitespace is intentionally not merged to preserve
3275 parse_flags
= saved_parse_flags
;
3276 tok_str_add(tok_str
, tok
);
3277 if (parse_flags
& PARSE_FLAG_SPACES
) {
3279 for (i
= 0; i
< ws_str
.len
; i
++)
3280 tok_str_add(tok_str
, ws_str
.str
[i
]);
3282 if (ws_str
.len
&& ws_str
.str
[ws_str
.len
- 1] == '\n')
3283 tok_flags
|= TOK_FLAG_BOL
;
3284 tok_str_free_str(ws_str
.str
);
3287 tok_str_free_str(ws_str
.str
);
3290 next_nomacro(); /* eat '(' */
3291 } while (is_space(tok
));
3293 /* argument macro */
3296 /* NOTE: empty args are allowed, except if no args */
3299 next_argstream(nested_list
, NULL
);
3300 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3302 /* handle '()' case */
3303 if (!args
&& !sa
&& tok
== ')')
3306 tcc_error("macro '%s' used with too many args",
3307 get_tok_str(s
->v
, 0));
3310 /* NOTE: non zero sa->t indicates VA_ARGS */
3311 while ((parlevel
> 0 ||
3313 (tok
!= ',' || sa
->type
.t
)))) {
3314 if (tok
== TOK_EOF
|| tok
== 0)
3318 else if (tok
== ')')
3320 if (tok
== TOK_LINEFEED
)
3322 if (!check_space(tok
, &spc
))
3323 tok_str_add2(&str
, tok
, &tokc
);
3324 next_argstream(nested_list
, NULL
);
3329 tok_str_add(&str
, -1);
3330 tok_str_add(&str
, 0);
3331 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3335 /* special case for gcc var args: add an empty
3336 var arg argument if it is omitted */
3337 if (sa
&& sa
->type
.t
&& gnu_ext
)
3345 tcc_error("macro '%s' used with too few args",
3346 get_tok_str(s
->v
, 0));
3349 /* now subst each arg */
3350 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3355 tok_str_free_str(sa
->d
);
3357 tok_str_free_str(sa
->next
->d
);
3363 parse_flags
= saved_parse_flags
;
3366 sym_push2(nested_list
, s
->v
, 0, 0);
3367 parse_flags
= saved_parse_flags
;
3368 joined_str
= macro_twosharps(mstr
);
3369 macro_subst(tok_str
, nested_list
, joined_str
? joined_str
: mstr
);
3371 /* pop nested defined symbol */
3373 *nested_list
= sa1
->prev
;
3376 tok_str_free_str(joined_str
);
3378 tok_str_free_str(mstr
);
3383 /* do macro substitution of macro_str and add result to
3384 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3385 inside to avoid recursing. */
3386 static void macro_subst(
3387 TokenString
*tok_str
,
3389 const int *macro_str
3393 int t
, spc
, nosubst
;
3399 TOK_GET(&t
, ¯o_str
, &cval
);
3403 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3408 /* if nested substitution, do nothing */
3409 if (sym_find2(*nested_list
, t
)) {
3410 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3411 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3416 TokenString
*str
= tok_str_alloc();
3417 str
->str
= (int*)macro_str
;
3418 begin_macro(str
, 2);
3421 macro_subst_tok(tok_str
, nested_list
, s
);
3423 if (macro_stack
!= str
) {
3424 /* already finished by reading function macro arguments */
3428 macro_str
= macro_ptr
;
3432 spc
= is_space(t
= tok_str
->str
[tok_str
->lastlen
]);
3435 if (!check_space(t
, &spc
))
3436 tok_str_add2(tok_str
, t
, &cval
);
3439 if (nosubst
> 1 && (spc
|| (++nosubst
== 3 && t
== '(')))
3443 if (t
== TOK_NOSUBST
)
3446 /* GCC supports 'defined' as result of a macro substitution */
3447 if (t
== TOK_DEFINED
&& pp_expr
)
3452 /* return next token without macro substitution. Can read input from
3454 static void next_nomacro(void)
3460 if (TOK_HAS_VALUE(t
)) {
3461 tok_get(&tok
, ¯o_ptr
, &tokc
);
3462 if (t
== TOK_LINENUM
) {
3463 file
->line_num
= tokc
.i
;
3468 if (t
< TOK_IDENT
) {
3469 if (!(parse_flags
& PARSE_FLAG_SPACES
)
3470 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
))
3480 /* return next token with macro substitution */
3481 ST_FUNC
void next(void)
3488 if (!TOK_HAS_VALUE(t
)) {
3489 if (t
== TOK_NOSUBST
) {
3490 /* discard preprocessor markers */
3492 } else if (t
== 0) {
3493 /* end of macro or unget token string */
3496 } else if (t
== '\\') {
3497 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3498 tcc_error("stray '\\' in program");
3502 } else if (t
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3503 /* if reading from file, try to substitute macros */
3504 Sym
*s
= define_find(t
);
3506 Sym
*nested_list
= NULL
;
3508 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3509 tok_str_add(&tokstr_buf
, 0);
3510 begin_macro(&tokstr_buf
, 0);
3515 /* convert preprocessor tokens into C tokens */
3516 if (t
== TOK_PPNUM
) {
3517 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3518 parse_number((char *)tokc
.str
.data
);
3519 } else if (t
== TOK_PPSTR
) {
3520 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3521 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3525 /* push back current token and set current token to 'last_tok'. Only
3526 identifier case handled for labels. */
3527 ST_INLN
void unget_tok(int last_tok
)
3530 TokenString
*str
= tok_str_alloc();
3531 tok_str_add2(str
, tok
, &tokc
);
3532 tok_str_add(str
, 0);
3533 begin_macro(str
, 1);
3537 /* ------------------------------------------------------------------------- */
3538 /* init preprocessor */
3540 static const char * const target_os_defs
=
3541 #ifdef TCC_TARGET_PE
3547 # if defined TCC_TARGET_MACHO
3549 # elif TARGETOS_FreeBSD
3551 # elif TARGETOS_FreeBSD_kernel
3552 "__FreeBSD_kernel__\0"
3553 # elif TARGETOS_NetBSD
3555 # elif TARGETOS_OpenBSD
3560 # if TARGETOS_ANDROID
3569 static void putdef(CString
*cs
, const char *p
)
3571 cstr_printf(cs
, "#define %s%s\n", p
, &" 1"[!!strchr(p
, ' ')*2]);
3574 static void putdefs(CString
*cs
, const char *p
)
3577 putdef(cs
, p
), p
= strchr(p
, 0) + 1;
3580 static void tcc_predefs(TCCState
*s1
, CString
*cs
, int is_asm
)
3584 sscanf(TCC_VERSION
, "%d.%d.%d", &a
, &b
, &c
);
3585 cstr_printf(cs
, "#define __TINYC__ %d\n", a
*10000 + b
*100 + c
);
3587 putdefs(cs
, target_machine_defs
);
3588 putdefs(cs
, target_os_defs
);
3590 #ifdef TCC_TARGET_ARM
3591 if (s1
->float_abi
== ARM_HARD_FLOAT
)
3592 putdef(cs
, "__ARM_PCS_VFP");
3595 putdef(cs
, "__ASSEMBLER__");
3596 if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
)
3597 putdef(cs
, "__TCC_PP__");
3598 if (s1
->output_type
== TCC_OUTPUT_MEMORY
)
3599 putdef(cs
, "__TCC_RUN__");
3600 #ifdef CONFIG_TCC_BACKTRACE
3601 if (s1
->do_backtrace
)
3602 putdef(cs
, "__TCC_BACKTRACE__");
3604 #ifdef CONFIG_TCC_BCHECK
3605 if (s1
->do_bounds_check
)
3606 putdef(cs
, "__TCC_BCHECK__");
3608 if (s1
->char_is_unsigned
)
3609 putdef(cs
, "__CHAR_UNSIGNED__");
3610 if (s1
->optimize
> 0)
3611 putdef(cs
, "__OPTIMIZE__");
3612 if (s1
->option_pthread
)
3613 putdef(cs
, "_REENTRANT");
3614 if (s1
->leading_underscore
)
3615 putdef(cs
, "__leading_underscore");
3616 cstr_printf(cs
, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE
);
3617 cstr_printf(cs
, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE
);
3619 putdef(cs
, "__STDC__");
3620 cstr_printf(cs
, "#define __STDC_VERSION__ %dL\n", s1
->cversion
);
3622 /* load more predefs and __builtins */
3623 #if CONFIG_TCC_PREDEFS
3624 #include "tccdefs_.h" /* include as strings */
3626 "#include <tccdefs.h>\n" /* load at runtime */
3630 cstr_printf(cs
, "#define __BASE_FILE__ \"%s\"\n", file
->filename
);
3633 ST_FUNC
void preprocess_start(TCCState
*s1
, int filetype
)
3635 int is_asm
= !!(filetype
& (AFF_TYPE_ASM
|AFF_TYPE_ASMPP
));
3639 s1
->include_stack_ptr
= s1
->include_stack
;
3640 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3641 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3644 pp_debug_tok
= pp_debug_symv
= 0;
3645 s1
->pack_stack
[0] = 0;
3646 s1
->pack_stack_ptr
= s1
->pack_stack
;
3648 set_idnum('$', !is_asm
&& s1
->dollars_in_identifiers
? IS_ID
: 0);
3649 set_idnum('.', is_asm
? IS_ID
: 0);
3651 if (!(filetype
& AFF_TYPE_ASM
)) {
3654 tcc_predefs(s1
, &cstr
, is_asm
);
3655 if (s1
->cmdline_defs
.size
)
3656 cstr_cat(&cstr
, s1
->cmdline_defs
.data
, s1
->cmdline_defs
.size
);
3657 if (s1
->cmdline_incl
.size
)
3658 cstr_cat(&cstr
, s1
->cmdline_incl
.data
, s1
->cmdline_incl
.size
);
3659 //printf("%s\n", (char*)cstr.data);
3660 *s1
->include_stack_ptr
++ = file
;
3661 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3662 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3666 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3667 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3670 /* cleanup from error/setjmp */
3671 ST_FUNC
void preprocess_end(TCCState
*s1
)
3681 ST_FUNC
int set_idnum(int c
, int val
)
3683 int prev
= isidnum_table
[c
- CH_EOF
];
3684 isidnum_table
[c
- CH_EOF
] = val
;
3688 ST_FUNC
void tccpp_new(TCCState
*s
)
3693 /* init isid table */
3694 for(i
= CH_EOF
; i
<128; i
++)
3696 is_space(i
) ? IS_SPC
3701 for(i
= 128; i
<256; i
++)
3702 set_idnum(i
, IS_ID
);
3704 /* init allocators */
3705 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3706 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3708 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3709 memset(s
->cached_includes_hash
, 0, sizeof s
->cached_includes_hash
);
3712 cstr_new(&cstr_buf
);
3713 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3714 tok_str_new(&tokstr_buf
);
3715 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3717 tok_ident
= TOK_IDENT
;
3726 tok_alloc(p
, r
- p
- 1);
3730 /* we add dummy defines for some special macros to speed up tests
3731 and to have working defined() */
3732 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
3733 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
3734 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
3735 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
3736 define_push(TOK___COUNTER__
, MACRO_OBJ
, NULL
, NULL
);
3739 ST_FUNC
void tccpp_delete(TCCState
*s
)
3743 dynarray_reset(&s
->cached_includes
, &s
->nb_cached_includes
);
3746 n
= tok_ident
- TOK_IDENT
;
3747 if (n
> total_idents
)
3749 for(i
= 0; i
< n
; i
++)
3750 tal_free(toksym_alloc
, table_ident
[i
]);
3751 tcc_free(table_ident
);
3754 /* free static buffers */
3755 cstr_free(&tokcstr
);
3756 cstr_free(&cstr_buf
);
3757 tok_str_free_str(tokstr_buf
.str
);
3759 /* free allocators */
3760 tal_delete(toksym_alloc
);
3761 toksym_alloc
= NULL
;
3762 tal_delete(tokstr_alloc
);
3763 tokstr_alloc
= NULL
;
3766 /* ------------------------------------------------------------------------- */
3767 /* tcc -E [-P[1]] [-dD} support */
3769 static void tok_print(const char *msg
, const int *str
)
3775 fp
= tcc_state
->ppfp
;
3776 fprintf(fp
, "%s", msg
);
3778 TOK_GET(&t
, &str
, &cval
);
3781 fprintf(fp
, &" %s"[s
], get_tok_str(t
, &cval
)), s
= 1;
3786 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3788 int d
= f
->line_num
- f
->line_ref
;
3793 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3795 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3797 fputs("\n", s1
->ppfp
), --d
;
3798 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3799 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3801 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3802 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3804 f
->line_ref
= f
->line_num
;
3807 static void define_print(TCCState
*s1
, int v
)
3813 if (NULL
== s
|| NULL
== s
->d
)
3817 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3818 if (s
->type
.t
== MACRO_FUNC
) {
3823 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3830 tok_print("", s
->d
);
3833 static void pp_debug_defines(TCCState
*s1
)
3844 pp_line(s1
, file
, 0);
3845 file
->line_ref
= ++file
->line_num
;
3849 vs
= get_tok_str(v
, NULL
);
3850 if (t
== TOK_DEFINE
) {
3851 define_print(s1
, v
);
3852 } else if (t
== TOK_UNDEF
) {
3853 fprintf(fp
, "#undef %s\n", vs
);
3854 } else if (t
== TOK_push_macro
) {
3855 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3856 } else if (t
== TOK_pop_macro
) {
3857 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3862 static void pp_debug_builtins(TCCState
*s1
)
3865 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3866 define_print(s1
, v
);
3869 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3870 static int pp_need_space(int a
, int b
)
3872 return 'E' == a
? '+' == b
|| '-' == b
3873 : '+' == a
? TOK_INC
== b
|| '+' == b
3874 : '-' == a
? TOK_DEC
== b
|| '-' == b
3875 : a
>= TOK_IDENT
? b
>= TOK_IDENT
3876 : a
== TOK_PPNUM
? b
>= TOK_IDENT
3880 /* maybe hex like 0x1e */
3881 static int pp_check_he0xE(int t
, const char *p
)
3883 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3888 /* Preprocess the current file */
3889 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3891 BufferedFile
**iptr
;
3892 int token_seen
, spcs
, level
;
3896 parse_flags
= PARSE_FLAG_PREPROCESS
3897 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3898 | PARSE_FLAG_LINEFEED
3900 | PARSE_FLAG_ACCEPT_STRAYS
3902 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3903 capability to compile and run itself, provided all numbers are
3904 given as decimals. tcc -E -P10 will do. */
3905 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
3906 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
3909 /* for PP benchmarks */
3910 do next(); while (tok
!= TOK_EOF
);
3914 if (s1
->dflag
& 1) {
3915 pp_debug_builtins(s1
);
3919 token_seen
= TOK_LINEFEED
, spcs
= 0, level
= 0;
3921 pp_line(s1
, file
->prev
, level
++);
3922 pp_line(s1
, file
, level
);
3924 iptr
= s1
->include_stack_ptr
;
3929 level
= s1
->include_stack_ptr
- iptr
;
3932 pp_line(s1
, *iptr
, 0);
3933 pp_line(s1
, file
, level
);
3935 if (s1
->dflag
& 7) {
3936 pp_debug_defines(s1
);
3941 if (is_space(tok
)) {
3942 if (spcs
< sizeof white
- 1)
3943 white
[spcs
++] = tok
;
3945 } else if (tok
== TOK_LINEFEED
) {
3947 if (token_seen
== TOK_LINEFEED
)
3950 } else if (token_seen
== TOK_LINEFEED
) {
3951 pp_line(s1
, file
, 0);
3952 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
3953 white
[spcs
++] = ' ';
3956 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
3957 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
3958 token_seen
= pp_check_he0xE(tok
, p
);
3963 /* ------------------------------------------------------------------------- */