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);
56 static void parse_number(const char *p
);
57 static void parse_string(const char *p
, int len
);
59 static struct TinyAlloc
*toksym_alloc
;
60 static struct TinyAlloc
*tokstr_alloc
;
62 static TokenString
*macro_stack
;
64 static const char tcc_keywords
[] =
65 #define DEF(id, str) str "\0"
70 /* WARNING: the content of this string encodes token numbers */
71 static const unsigned char tok_two_chars
[] =
73 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
74 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
96 '#','#', TOK_TWOSHARPS
,
100 ST_FUNC
void skip(int c
)
104 pstrcpy(tmp
, sizeof tmp
, get_tok_str(c
, &tokc
));
105 tcc_error("'%s' expected (got \"%s\")", tmp
, get_tok_str(tok
, &tokc
));
110 ST_FUNC
void expect(const char *msg
)
112 tcc_error("%s expected", msg
);
115 /* ------------------------------------------------------------------------- */
116 /* Custom allocator for tiny objects */
121 #define tal_free(al, p) tcc_free(p)
122 #define tal_realloc(al, p, size) tcc_realloc(p, size)
123 #define tal_new(a,b,c)
124 #define tal_delete(a)
126 #if !defined(MEM_DEBUG)
127 #define tal_free(al, p) tal_free_impl(al, p)
128 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
129 #define TAL_DEBUG_PARAMS
131 #define TAL_DEBUG MEM_DEBUG
132 //#define TAL_INFO 1 /* collect and dump allocators stats */
133 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
134 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
135 #define TAL_DEBUG_PARAMS , const char *file, int line
136 #define TAL_DEBUG_FILE_LEN 40
139 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
140 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
141 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
142 #define TOKSTR_TAL_LIMIT 1024 /* 256 * sizeof(int) */
144 typedef struct TinyAlloc
{
150 struct TinyAlloc
*next
, *top
;
159 typedef struct tal_header_t
{
162 int line_num
; /* negative line_num used for double free check */
163 char file_name
[TAL_DEBUG_FILE_LEN
+ 1];
167 /* ------------------------------------------------------------------------- */
169 static TinyAlloc
*tal_new(TinyAlloc
**pal
, unsigned limit
, unsigned size
)
171 TinyAlloc
*al
= tcc_mallocz(sizeof(TinyAlloc
));
172 al
->p
= al
->buffer
= tcc_malloc(size
);
179 static void tal_delete(TinyAlloc
*al
)
187 fprintf(stderr
, "limit %4d size %7d nb_peak %5d nb_total %7d nb_missed %5d usage %5.1f%%\n",
188 al
->limit
, al
->size
, al
->nb_peak
, al
->nb_total
, al
->nb_missed
,
189 (al
->peak_p
- al
->buffer
) * 100.0 / al
->size
);
191 #if TAL_DEBUG && TAL_DEBUG != 3 /* do not check TAL leaks with -DMEM_DEBUG=3 */
192 if (al
->nb_allocs
> 0) {
194 fprintf(stderr
, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
195 al
->nb_allocs
, al
->limit
);
198 tal_header_t
*header
= (tal_header_t
*)p
;
199 if (header
->line_num
> 0) {
200 fprintf(stderr
, "%s:%d: chunk of %d bytes leaked\n",
201 header
->file_name
, header
->line_num
, header
->size
);
203 p
+= header
->size
+ sizeof(tal_header_t
);
211 tcc_free(al
->buffer
);
217 static void tal_free_impl(TinyAlloc
*al
, void *p TAL_DEBUG_PARAMS
)
222 if (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
) {
224 tal_header_t
*header
= (((tal_header_t
*)p
) - 1);
225 if (header
->line_num
< 0) {
226 fprintf(stderr
, "%s:%d: TAL_DEBUG: double frees chunk from\n",
228 fprintf(stderr
, "%s:%d: %d bytes\n",
229 header
->file_name
, (int)-header
->line_num
, (int)header
->size
);
231 header
->line_num
= -header
->line_num
;
236 } else if (al
->next
) {
244 static void *tal_realloc_impl(TinyAlloc
**pal
, void *p
, unsigned size TAL_DEBUG_PARAMS
)
246 tal_header_t
*header
;
249 unsigned adj_size
= (size
+ 3) & -4;
250 TinyAlloc
*al
= *pal
;
253 is_own
= (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
);
254 if ((!p
|| is_own
) && size
<= al
->limit
) {
255 if (al
->p
- al
->buffer
+ adj_size
+ sizeof(tal_header_t
) < al
->size
) {
256 header
= (tal_header_t
*)al
->p
;
257 header
->size
= adj_size
;
259 { int ofs
= strlen(file
) - TAL_DEBUG_FILE_LEN
;
260 strncpy(header
->file_name
, file
+ (ofs
> 0 ? ofs
: 0), TAL_DEBUG_FILE_LEN
);
261 header
->file_name
[TAL_DEBUG_FILE_LEN
] = 0;
262 header
->line_num
= line
; }
264 ret
= al
->p
+ sizeof(tal_header_t
);
265 al
->p
+= adj_size
+ sizeof(tal_header_t
);
267 header
= (((tal_header_t
*)p
) - 1);
268 if (p
) memcpy(ret
, p
, header
->size
);
270 header
->line_num
= -header
->line_num
;
276 if (al
->nb_peak
< al
->nb_allocs
)
277 al
->nb_peak
= al
->nb_allocs
;
278 if (al
->peak_p
< al
->p
)
285 ret
= tal_realloc(*pal
, 0, size
);
286 header
= (((tal_header_t
*)p
) - 1);
287 if (p
) memcpy(ret
, p
, header
->size
);
289 header
->line_num
= -header
->line_num
;
296 TinyAlloc
*bottom
= al
, *next
= al
->top
? al
->top
: al
;
298 al
= tal_new(pal
, next
->limit
, next
->size
* 2);
306 ret
= tcc_malloc(size
);
307 header
= (((tal_header_t
*)p
) - 1);
308 if (p
) memcpy(ret
, p
, header
->size
);
310 header
->line_num
= -header
->line_num
;
312 } else if (al
->next
) {
316 ret
= tcc_realloc(p
, size
);
325 /* ------------------------------------------------------------------------- */
326 /* CString handling */
327 static void cstr_realloc(CString
*cstr
, int new_size
)
331 size
= cstr
->size_allocated
;
333 size
= 8; /* no need to allocate a too small first string */
334 while (size
< new_size
)
336 cstr
->data
= tcc_realloc(cstr
->data
, size
);
337 cstr
->size_allocated
= size
;
341 ST_INLN
void cstr_ccat(CString
*cstr
, int ch
)
344 size
= cstr
->size
+ 1;
345 if (size
> cstr
->size_allocated
)
346 cstr_realloc(cstr
, size
);
347 cstr
->data
[size
- 1] = ch
;
351 ST_INLN
char *unicode_to_utf8 (char *b
, uint32_t Uc
)
353 if (Uc
<0x80) *b
++=Uc
;
354 else if (Uc
<0x800) *b
++=192+Uc
/64, *b
++=128+Uc
%64;
355 else if (Uc
-0xd800u
<0x800) goto error
;
356 else if (Uc
<0x10000) *b
++=224+Uc
/4096, *b
++=128+Uc
/64%64, *b
++=128+Uc
%64;
357 else if (Uc
<0x110000) *b
++=240+Uc
/262144, *b
++=128+Uc
/4096%64, *b
++=128+Uc
/64%64, *b
++=128+Uc
%64;
358 else error
: tcc_error("0x%x is not a valid universal character", Uc
);
362 /* add a unicode character expanded into utf8 */
363 ST_INLN
void cstr_u8cat(CString
*cstr
, int ch
)
366 e
= unicode_to_utf8(buf
, (uint32_t)ch
);
367 cstr_cat(cstr
, buf
, e
- buf
);
370 /* add string of 'len', or of its len/len+1 when 'len' == -1/0 */
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(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
*)(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(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;
912 if (in_warn_or_error
)
914 tok_flags
&= ~TOK_FLAG_BOL
;
915 p
= parse_pp_string(p
, c
, NULL
);
919 if (in_warn_or_error
)
924 p
= parse_comment(p
);
925 } else if (c
== '/') {
926 p
= parse_line_comment(p
);
936 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
938 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
940 else if (tok
== TOK_ENDIF
)
942 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
943 in_warn_or_error
= 1;
944 else if (tok
== TOK_LINEFEED
)
946 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
947 p
= parse_line_comment(p
- 1);
949 #if !defined(TCC_TARGET_ARM)
950 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
951 p
= parse_line_comment(p
- 1);
953 /* ARM assembly uses '#' for constants */
968 /* return the number of additional 'ints' necessary to store the
970 static inline int tok_size(const int *p
)
985 return 1 + 1 + (p
[1] + 3) / 4;
988 return 1 + LONG_SIZE
/ 4;
994 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
997 return 1 + LDOUBLE_SIZE
/ 4;
1005 /* token string handling */
1006 ST_INLN
void tok_str_new(TokenString
*s
)
1009 s
->len
= s
->need_spc
= 0;
1010 s
->allocated_len
= 0;
1011 s
->last_line_num
= -1;
1014 ST_FUNC TokenString
*tok_str_alloc(void)
1016 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1021 ST_FUNC
void tok_str_free_str(int *str
)
1023 tal_free(tokstr_alloc
, str
);
1026 ST_FUNC
void tok_str_free(TokenString
*str
)
1028 tok_str_free_str(str
->str
);
1029 tal_free(tokstr_alloc
, str
);
1032 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1036 size
= s
->allocated_len
;
1039 while (size
< new_size
)
1041 if (size
> s
->allocated_len
) {
1042 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1043 s
->allocated_len
= size
;
1049 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1055 if (len
>= s
->allocated_len
)
1056 str
= tok_str_realloc(s
, len
+ 1);
1061 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1064 str
->prev
= macro_stack
;
1065 str
->prev_ptr
= macro_ptr
;
1066 str
->save_line_num
= file
->line_num
;
1067 macro_ptr
= str
->str
;
1071 ST_FUNC
void end_macro(void)
1073 TokenString
*str
= macro_stack
;
1074 macro_stack
= str
->prev
;
1075 macro_ptr
= str
->prev_ptr
;
1076 file
->line_num
= str
->save_line_num
;
1077 if (str
->alloc
== 0) {
1078 /* matters if str not alloced, may be tokstr_buf */
1079 str
->len
= str
->need_spc
= 0;
1081 if (str
->alloc
== 2)
1082 str
->str
= NULL
; /* don't free */
1087 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1094 /* allocate space for worst case */
1095 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1096 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1109 str
[len
++] = cv
->tab
[0];
1116 /* Insert the string into the int array. */
1118 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1119 if (len
+ nb_words
>= s
->allocated_len
)
1120 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1121 str
[len
] = cv
->str
.size
;
1122 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1133 str
[len
++] = cv
->tab
[0];
1134 str
[len
++] = cv
->tab
[1];
1137 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1138 str
[len
++] = cv
->tab
[0];
1139 str
[len
++] = cv
->tab
[1];
1140 #elif LDOUBLE_SIZE == 12
1141 str
[len
++] = cv
->tab
[0];
1142 str
[len
++] = cv
->tab
[1];
1143 str
[len
++] = cv
->tab
[2];
1144 #elif LDOUBLE_SIZE == 16
1145 str
[len
++] = cv
->tab
[0];
1146 str
[len
++] = cv
->tab
[1];
1147 str
[len
++] = cv
->tab
[2];
1148 str
[len
++] = cv
->tab
[3];
1150 #error add long double size support
1159 /* add the current parse token in token string 's' */
1160 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1164 /* save line number info */
1165 if (file
->line_num
!= s
->last_line_num
) {
1166 s
->last_line_num
= file
->line_num
;
1167 cval
.i
= s
->last_line_num
;
1168 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1170 tok_str_add2(s
, tok
, &tokc
);
1173 /* like tok_str_add2(), add a space if needed */
1174 static void tok_str_add2_spc(TokenString
*s
, int t
, CValue
*cv
)
1176 if (s
->need_spc
== 3)
1177 tok_str_add(s
, ' ');
1179 tok_str_add2(s
, t
, cv
);
1182 /* get a token from an integer array and increment pointer. */
1183 static inline void tok_get(int *t
, const int **pp
, CValue
*cv
)
1203 cv
->i
= (unsigned)*p
++;
1212 cv
->str
.size
= *p
++;
1213 cv
->str
.data
= (char*)p
;
1214 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1226 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1228 #elif LDOUBLE_SIZE == 12
1230 #elif LDOUBLE_SIZE == 16
1233 # error add long double size support
1247 # define TOK_GET(t,p,c) tok_get(t,p,c)
1249 # define TOK_GET(t,p,c) do { \
1251 if (TOK_HAS_VALUE(_t)) \
1254 *(t) = _t, ++*(p); \
1258 static int macro_is_equal(const int *a
, const int *b
)
1267 cstr_reset(&tokcstr
);
1268 TOK_GET(&t
, &a
, &cv
);
1269 cstr_cat(&tokcstr
, get_tok_str(t
, &cv
), 0);
1270 TOK_GET(&t
, &b
, &cv
);
1271 if (strcmp(tokcstr
.data
, get_tok_str(t
, &cv
)))
1277 /* defines handling */
1278 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1283 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1285 s
->next
= first_arg
;
1286 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1288 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1289 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1292 /* undefined a define symbol. Its name is just set to zero */
1293 ST_FUNC
void define_undef(Sym
*s
)
1296 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1297 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1300 ST_INLN Sym
*define_find(int v
)
1303 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1305 return table_ident
[v
]->sym_define
;
1308 /* free define stack until top reaches 'b' */
1309 ST_FUNC
void free_defines(Sym
*b
)
1311 while (define_stack
!= b
) {
1312 Sym
*top
= define_stack
;
1313 define_stack
= top
->prev
;
1314 tok_str_free_str(top
->d
);
1320 /* fake the nth "#if defined test_..." for tcc -dt -run */
1321 static void maybe_run_test(TCCState
*s
)
1324 if (s
->include_stack_ptr
!= s
->include_stack
)
1326 p
= get_tok_str(tok
, NULL
);
1327 if (0 != memcmp(p
, "test_", 5))
1329 if (0 != --s
->run_test
)
1331 fprintf(s
->ppfp
, &"\n[%s]\n"[!(s
->dflag
& 32)], p
), fflush(s
->ppfp
);
1332 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1335 ST_FUNC
void skip_to_eol(int warn
)
1337 if (tok
== TOK_LINEFEED
)
1340 tcc_warning("extra tokens after directive");
1341 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
1345 static CachedInclude
*
1346 search_cached_include(TCCState
*s1
, const char *filename
, int add
);
1348 static int parse_include(TCCState
*s1
, int do_next
, int test
)
1351 char name
[1024], buf
[1024], *p
;
1355 if (c
== '<' || c
== '\"') {
1356 cstr_reset(&tokcstr
);
1357 file
->buf_ptr
= parse_pp_string(file
->buf_ptr
, c
== '<' ? '>' : c
, &tokcstr
);
1359 pstrncpy(name
, tokcstr
.data
, i
>= sizeof name
? sizeof name
- 1 : i
);
1362 /* computed #include : concatenate tokens until result is one of
1363 the two accepted forms. Don't convert pp-tokens to tokens here. */
1364 parse_flags
= PARSE_FLAG_PREPROCESS
1365 | PARSE_FLAG_LINEFEED
1366 | (parse_flags
& PARSE_FLAG_ASM_FILE
);
1370 p
= name
, i
= strlen(p
) - 1;
1372 && ((p
[0] == '"' && p
[i
] == '"')
1373 || (p
[0] == '<' && p
[i
] == '>')))
1375 if (tok
== TOK_LINEFEED
)
1376 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1377 pstrcat(name
, sizeof name
, get_tok_str(tok
, &tokc
));
1380 /* remove '<>|""' */
1381 memmove(p
, p
+ 1, i
- 1), p
[i
- 1] = 0;
1387 i
= do_next
? file
->include_next_index
: -1;
1391 /* check absolute include path */
1392 if (!IS_ABSPATH(name
))
1395 } else if (i
== 1) {
1396 /* search in file's dir if "header.h" */
1399 p
= file
->true_filename
;
1400 pstrncpy(buf
, p
, tcc_basename(p
) - p
);
1402 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1404 p
= s1
->include_paths
[j
];
1405 else if (k
< s1
->nb_sysinclude_paths
)
1406 p
= s1
->sysinclude_paths
[k
];
1410 tcc_error("include file '%s' not found", name
);
1411 pstrcpy(buf
, sizeof buf
, p
);
1412 pstrcat(buf
, sizeof buf
, "/");
1414 pstrcat(buf
, sizeof buf
, name
);
1415 e
= search_cached_include(s1
, buf
, 0);
1416 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
)) {
1417 /* no need to parse the include because the 'ifndef macro'
1418 is defined (or had #pragma once) */
1420 printf("%s: skipping cached %s\n", file
->filename
, buf
);
1424 if (tcc_open(s1
, buf
) >= 0)
1431 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1432 tcc_error("#include recursion too deep");
1433 /* push previous file on stack */
1434 *s1
->include_stack_ptr
++ = file
->prev
;
1435 file
->include_next_index
= i
;
1437 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1439 /* update target deps */
1441 BufferedFile
*bf
= file
;
1442 while (i
== 1 && (bf
= bf
->prev
))
1443 i
= bf
->include_next_index
;
1444 /* skip system include files */
1445 if (s1
->include_sys_deps
|| i
- 2 < s1
->nb_include_paths
)
1446 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1449 /* add include file debug info */
1450 tcc_debug_bincl(s1
);
1455 /* eval an expression for #if/#elif */
1456 static int expr_preprocess(TCCState
*s1
)
1462 str
= tok_str_alloc();
1465 next(); /* do macro subst */
1467 if (tok
< TOK_IDENT
) {
1468 if (tok
== TOK_LINEFEED
|| tok
== TOK_EOF
)
1470 if (tok
>= TOK_STR
&& tok
<= TOK_CLDOUBLE
)
1471 tcc_error("invalid constant in preprocessor expression");
1473 } else if (tok
== TOK_DEFINED
) {
1474 parse_flags
&= ~PARSE_FLAG_PREPROCESS
; /* no macro subst */
1479 parse_flags
|= PARSE_FLAG_PREPROCESS
;
1480 if (tok
< TOK_IDENT
)
1481 expect("identifier after 'defined'");
1485 if (define_find(tok
)
1486 || tok
== TOK___HAS_INCLUDE
1487 || tok
== TOK___HAS_INCLUDE_NEXT
)
1496 } else if (tok
== TOK___HAS_INCLUDE
||
1497 tok
== TOK___HAS_INCLUDE_NEXT
) {
1502 c
= parse_include(s1
, t
- TOK___HAS_INCLUDE
, 1);
1508 /* if undefined macro, replace with zero */
1512 tok_str_add_tok(str
);
1515 tcc_error("#%s with no expression", get_tok_str(t0
, 0));
1516 tok_str_add(str
, TOK_EOF
); /* simulate end of file */
1517 pp_expr
= t0
; /* redirect pre-processor expression error messages */
1519 /* now evaluate C constant expression */
1520 begin_macro(str
, 1);
1527 tok
= t
; /* restore LF or EOF */
1531 ST_FUNC
void pp_error(CString
*cs
)
1533 cstr_printf(cs
, "bad preprocessor expression: #%s", get_tok_str(pp_expr
, 0));
1534 macro_ptr
= macro_stack
->str
;
1535 while (next(), tok
!= TOK_EOF
)
1536 cstr_printf(cs
, " %s", get_tok_str(tok
, &tokc
));
1539 /* parse after #define */
1540 ST_FUNC
void parse_define(void)
1542 Sym
*s
, *first
, **ps
;
1543 int v
, t
, varg
, is_vaargs
, t0
;
1544 int saved_parse_flags
= parse_flags
;
1548 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1549 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1552 /* We have to parse the whole define as if not in asm mode, in particular
1553 no line comment with '#' must be ignored. Also for function
1554 macros the argument list must be parsed without '.' being an ID
1556 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1557 /* '(' must be just after macro definition for MACRO_FUNC */
1559 parse_flags
&= ~PARSE_FLAG_SPACES
;
1562 int dotid
= set_idnum('.', 0);
1565 if (tok
!= ')') for (;;) {
1569 if (varg
== TOK_DOTS
) {
1570 varg
= TOK___VA_ARGS__
;
1572 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1576 if (varg
< TOK_IDENT
)
1578 tcc_error("bad macro parameter list");
1579 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1584 if (tok
!= ',' || is_vaargs
)
1588 parse_flags
|= PARSE_FLAG_SPACES
;
1591 set_idnum('.', dotid
);
1594 /* The body of a macro definition should be parsed such that identifiers
1595 are parsed like the file mode determines (i.e. with '.' being an
1596 ID character in asm mode). But '#' should be retained instead of
1597 regarded as line comment leader, so still don't set ASM_FILE
1599 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1602 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1603 if (is_space(tok
)) {
1606 if (TOK_TWOSHARPS
== tok
) {
1612 tok_str_add2_spc(&str
, tok
, &tokc
);
1617 parse_flags
= saved_parse_flags
;
1618 tok_str_add(&str
, 0);
1619 if (t0
== TOK_PPJOIN
)
1621 tcc_error("'##' cannot appear at either end of macro");
1622 define_push(v
, t
, str
.str
, first
);
1623 //tok_print(str.str, "#define (%d) %s %d:", t | is_vaargs * 4, get_tok_str(v, 0));
1626 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1628 const char *s
, *basename
;
1633 s
= basename
= tcc_basename(filename
);
1635 while ((c
= (unsigned char)*s
) != 0) {
1637 h
= TOK_HASH_FUNC(h
, toup(c
));
1639 h
= TOK_HASH_FUNC(h
, c
);
1643 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1645 i
= s1
->cached_includes_hash
[h
];
1649 e
= s1
->cached_includes
[i
- 1];
1650 if (0 == PATHCMP(filename
, e
->filename
))
1653 && 0 == PATHCMP(basename
, tcc_basename(e
->filename
))
1654 && 0 == normalized_PATHCMP(filename
, e
->filename
)
1662 e
= tcc_malloc(sizeof(CachedInclude
) + (len
= strlen(filename
)));
1663 memcpy(e
->filename
, filename
, len
+ 1);
1664 e
->ifndef_macro
= e
->once
= 0;
1665 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1666 /* add in hash table */
1667 e
->hash_next
= s1
->cached_includes_hash
[h
];
1668 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1670 printf("adding cached '%s'\n", filename
);
1675 static int pragma_parse(TCCState
*s1
)
1678 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1682 if (next(), tok
!= '(')
1684 if (next(), tok
!= TOK_STR
)
1686 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1687 if (next(), tok
!= ')')
1689 if (t
== TOK_push_macro
) {
1690 while (NULL
== (s
= define_find(v
)))
1691 define_push(v
, 0, NULL
, NULL
);
1692 s
->type
.ref
= s
; /* set push boundary */
1694 for (s
= define_stack
; s
; s
= s
->prev
)
1695 if (s
->v
== v
&& s
->type
.ref
== s
) {
1701 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1703 tcc_warning("unbalanced #pragma pop_macro");
1704 pp_debug_tok
= t
, pp_debug_symv
= v
;
1706 } else if (tok
== TOK_once
) {
1707 search_cached_include(s1
, file
->true_filename
, 1)->once
= 1;
1709 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1710 /* tcc -E: keep pragmas below unchanged */
1712 unget_tok(TOK_PRAGMA
);
1714 unget_tok(TOK_LINEFEED
);
1717 } else if (tok
== TOK_pack
) {
1719 #pragma pack(1) // set
1720 #pragma pack() // reset to default
1721 #pragma pack(push) // push current
1722 #pragma pack(push,1) // push & set
1723 #pragma pack(pop) // restore previous */
1726 if (tok
== TOK_ASM_pop
) {
1728 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1730 tcc_error("out of pack stack");
1732 s1
->pack_stack_ptr
--;
1736 if (tok
== TOK_ASM_push
) {
1738 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1740 val
= *s1
->pack_stack_ptr
++;
1745 if (tok
!= TOK_CINT
)
1748 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1753 *s1
->pack_stack_ptr
= val
;
1758 } else if (tok
== TOK_comment
) {
1767 p
= tcc_strdup(tokc
.str
.data
);
1772 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1774 if (t
== TOK_option
)
1775 tcc_set_options(s1
, p
);
1780 tcc_warning_c(warn_all
)("#pragma %s ignored", get_tok_str(tok
, &tokc
));
1786 tcc_error("malformed #pragma directive");
1789 /* put alternative filename */
1790 ST_FUNC
void tccpp_putfile(const char *filename
)
1794 if (!IS_ABSPATH(filename
)) {
1795 /* prepend directory from real file */
1796 pstrcpy(buf
, sizeof buf
, file
->true_filename
);
1797 *tcc_basename(buf
) = 0;
1799 pstrcat(buf
, sizeof buf
, filename
);
1801 normalize_slashes(buf
);
1803 if (0 == strcmp(file
->filename
, buf
))
1805 //printf("new file '%s'\n", buf);
1806 if (file
->true_filename
== file
->filename
)
1807 file
->true_filename
= tcc_strdup(file
->filename
);
1808 pstrcpy(file
->filename
, sizeof file
->filename
, buf
);
1809 tcc_debug_newfile(tcc_state
);
1812 /* is_bof is true if first non space token at beginning of file */
1813 ST_FUNC
void preprocess(int is_bof
)
1815 TCCState
*s1
= tcc_state
;
1816 int c
, n
, saved_parse_flags
;
1820 saved_parse_flags
= parse_flags
;
1821 parse_flags
= PARSE_FLAG_PREPROCESS
1822 | PARSE_FLAG_TOK_NUM
1823 | PARSE_FLAG_TOK_STR
1824 | PARSE_FLAG_LINEFEED
1825 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1834 pp_debug_symv
= tok
;
1840 pp_debug_symv
= tok
;
1841 s
= define_find(tok
);
1842 /* undefine symbol by putting an invalid name */
1848 case TOK_INCLUDE_NEXT
:
1849 parse_include(s1
, tok
- TOK_INCLUDE
, 0);
1855 c
= expr_preprocess(s1
);
1861 if (tok
< TOK_IDENT
)
1862 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1866 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1868 file
->ifndef_macro
= tok
;
1871 if (define_find(tok
)
1872 || tok
== TOK___HAS_INCLUDE
1873 || tok
== TOK___HAS_INCLUDE_NEXT
)
1877 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1878 tcc_error("memory full (ifdef)");
1879 *s1
->ifdef_stack_ptr
++ = c
;
1883 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1884 tcc_error("#else without matching #if");
1885 if (s1
->ifdef_stack_ptr
[-1] & 2)
1886 tcc_error("#else after #else");
1887 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1890 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1891 tcc_error("#elif without matching #if");
1892 c
= s1
->ifdef_stack_ptr
[-1];
1894 tcc_error("#elif after #else");
1895 /* last #if/#elif expression was true: we skip */
1900 c
= expr_preprocess(s1
);
1901 s1
->ifdef_stack_ptr
[-1] = c
;
1904 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1905 file
->ifndef_macro
= 0;
1916 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1917 tcc_error("#endif without matching #if");
1918 s1
->ifdef_stack_ptr
--;
1919 /* '#ifndef macro' was at the start of file. Now we check if
1920 an '#endif' is exactly at the end of file */
1921 if (file
->ifndef_macro
&&
1922 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1923 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1924 /* need to set to zero to avoid false matches if another
1925 #ifndef at middle of file */
1926 file
->ifndef_macro
= 0;
1927 tok_flags
|= TOK_FLAG_ENDIF
;
1932 if (tok
!= TOK_PPNUM
)
1934 tcc_error("wrong #line format");
1936 parse_number(tokc
.str
.data
);
1939 if (tok
!= TOK_LINEFEED
) {
1940 if (tok
== TOK_PPSTR
&& tokc
.str
.data
[0] == '"') {
1941 tokc
.str
.data
[tokc
.str
.size
- 2] = 0;
1942 tccpp_putfile(tokc
.str
.data
+ 1);
1943 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1950 total_lines
+= file
->line_num
- n
;
1952 goto ignore
; /* skip optional level number */
1959 while (c
!= '\n' && c
!= CH_EOF
) {
1960 if ((q
- buf
) < sizeof(buf
) - 1)
1965 if (tok
== TOK_ERROR
)
1966 tcc_error("#error %s", buf
);
1968 tcc_warning("#warning %s", buf
);
1973 if (!pragma_parse(s1
))
1979 /* ignore gas line comment in an 'S' file. */
1980 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
1982 if (tok
== '!' && is_bof
)
1983 /* '#!' is ignored at beginning to allow C scripts. */
1985 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1992 parse_flags
= saved_parse_flags
;
1995 /* evaluate escape codes in a string. */
1996 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2011 case '0': case '1': case '2': case '3':
2012 case '4': case '5': case '6': case '7':
2013 /* at most three octal digits */
2018 n
= n
* 8 + c
- '0';
2022 n
= n
* 8 + c
- '0';
2027 goto add_char_nonext
;
2028 case 'x': i
= 0; goto parse_hex_or_ucn
;
2029 case 'u': i
= 4; goto parse_hex_or_ucn
;
2030 case 'U': i
= 8; goto parse_hex_or_ucn
;
2036 if (c
>= 'a' && c
<= 'f')
2038 else if (c
>= 'A' && c
<= 'F')
2043 expect("more hex digits in universal-character-name");
2045 goto add_hex_or_ucn
;
2052 goto add_char_nonext
;
2054 cstr_u8cat(outstr
, n
);
2079 goto invalid_escape
;
2089 if (c
>= '!' && c
<= '~')
2090 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2092 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2095 } else if (is_long
&& c
>= 0x80) {
2096 /* assume we are processing UTF-8 sequence */
2097 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2099 int cont
; /* count of continuation bytes */
2100 int skip
; /* how many bytes should skip when error occurred */
2103 /* decode leading byte */
2105 skip
= 1; goto invalid_utf8_sequence
;
2106 } else if (c
<= 0xDF) {
2107 cont
= 1; n
= c
& 0x1f;
2108 } else if (c
<= 0xEF) {
2109 cont
= 2; n
= c
& 0xf;
2110 } else if (c
<= 0xF4) {
2111 cont
= 3; n
= c
& 0x7;
2113 skip
= 1; goto invalid_utf8_sequence
;
2116 /* decode continuation bytes */
2117 for (i
= 1; i
<= cont
; i
++) {
2118 int l
= 0x80, h
= 0xBF;
2120 /* adjust limit for second byte */
2123 case 0xE0: l
= 0xA0; break;
2124 case 0xED: h
= 0x9F; break;
2125 case 0xF0: l
= 0x90; break;
2126 case 0xF4: h
= 0x8F; break;
2130 if (p
[i
] < l
|| p
[i
] > h
) {
2131 skip
= i
; goto invalid_utf8_sequence
;
2134 n
= (n
<< 6) | (p
[i
] & 0x3f);
2137 /* advance pointer */
2140 goto add_char_nonext
;
2142 /* error handling */
2143 invalid_utf8_sequence
:
2144 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c
);
2147 goto add_char_nonext
;
2153 cstr_ccat(outstr
, c
);
2155 #ifdef TCC_TARGET_PE
2156 /* store as UTF-16 */
2158 cstr_wccat(outstr
, c
);
2161 cstr_wccat(outstr
, (c
>> 10) + 0xD800);
2162 cstr_wccat(outstr
, (c
& 0x3FF) + 0xDC00);
2165 cstr_wccat(outstr
, c
);
2169 /* add a trailing '\0' */
2171 cstr_ccat(outstr
, '\0');
2173 cstr_wccat(outstr
, '\0');
2176 static void parse_string(const char *s
, int len
)
2178 uint8_t buf
[1000], *p
= buf
;
2181 if ((is_long
= *s
== 'L'))
2185 if (len
>= sizeof buf
)
2186 p
= tcc_malloc(len
+ 1);
2190 cstr_reset(&tokcstr
);
2191 parse_escape_string(&tokcstr
, p
, is_long
);
2196 int char_size
, i
, n
, c
;
2197 /* XXX: make it portable */
2199 tok
= TOK_CCHAR
, char_size
= 1;
2201 tok
= TOK_LCHAR
, char_size
= sizeof(nwchar_t
);
2202 n
= tokcstr
.size
/ char_size
- 1;
2204 tcc_error("empty character constant");
2206 tcc_warning_c(warn_all
)("multi-character character constant");
2207 for (c
= i
= 0; i
< n
; ++i
) {
2209 c
= ((nwchar_t
*)tokcstr
.data
)[i
];
2211 c
= (c
<< 8) | ((char *)tokcstr
.data
)[i
];
2215 tokc
.str
.size
= tokcstr
.size
;
2216 tokc
.str
.data
= tokcstr
.data
;
2224 /* we use 64 bit numbers */
2227 /* bn = (bn << shift) | or_val */
2228 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2232 for(i
=0;i
<BN_SIZE
;i
++) {
2234 bn
[i
] = (v
<< shift
) | or_val
;
2235 or_val
= v
>> (32 - shift
);
2239 static void bn_zero(unsigned int *bn
)
2242 for(i
=0;i
<BN_SIZE
;i
++) {
2247 /* parse number in null terminated string 'p' and return it in the
2249 static void parse_number(const char *p
)
2251 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2253 unsigned int bn
[BN_SIZE
];
2264 goto float_frac_parse
;
2265 } else if (t
== '0') {
2266 if (ch
== 'x' || ch
== 'X') {
2270 } else if (tcc_state
->tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2276 /* parse all digits. cannot check octal numbers at this stage
2277 because of floating point constants */
2279 if (ch
>= 'a' && ch
<= 'f')
2281 else if (ch
>= 'A' && ch
<= 'F')
2289 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2291 tcc_error("number too long");
2297 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2298 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2300 /* NOTE: strtox should support that for hexa numbers, but
2301 non ISOC99 libcs do not support it, so we prefer to do
2303 /* hexadecimal or binary floats */
2304 /* XXX: handle overflows */
2316 } else if (t
>= 'a') {
2318 } else if (t
>= 'A') {
2323 bn_lshift(bn
, shift
, t
);
2330 if (t
>= 'a' && t
<= 'f') {
2332 } else if (t
>= 'A' && t
<= 'F') {
2334 } else if (t
>= '0' && t
<= '9') {
2340 tcc_error("invalid digit");
2341 bn_lshift(bn
, shift
, t
);
2346 if (ch
!= 'p' && ch
!= 'P')
2353 } else if (ch
== '-') {
2357 if (ch
< '0' || ch
> '9')
2358 expect("exponent digits");
2359 while (ch
>= '0' && ch
<= '9') {
2360 exp_val
= exp_val
* 10 + ch
- '0';
2363 exp_val
= exp_val
* s
;
2365 /* now we can generate the number */
2366 /* XXX: should patch directly float number */
2367 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2368 d
= ldexp(d
, exp_val
- frac_bits
);
2373 /* float : should handle overflow */
2375 } else if (t
== 'L') {
2378 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2381 /* XXX: not large enough */
2382 tokc
.ld
= (long double)d
;
2389 /* decimal floats */
2391 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2396 while (ch
>= '0' && ch
<= '9') {
2397 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2403 if (ch
== 'e' || ch
== 'E') {
2404 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2408 if (ch
== '-' || ch
== '+') {
2409 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2414 if (ch
< '0' || ch
> '9')
2415 expect("exponent digits");
2416 while (ch
>= '0' && ch
<= '9') {
2417 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2429 tokc
.f
= strtof(token_buf
, NULL
);
2430 } else if (t
== 'L') {
2433 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2434 tokc
.d
= strtod(token_buf
, NULL
);
2436 tokc
.ld
= strtold(token_buf
, NULL
);
2440 tokc
.d
= strtod(token_buf
, NULL
);
2444 unsigned long long n
, n1
;
2445 int lcount
, ucount
, ov
= 0;
2448 /* integer number */
2451 if (b
== 10 && *q
== '0') {
2458 /* no need for checks except for base 10 / 8 errors */
2468 tcc_error("invalid digit");
2471 /* detect overflow */
2472 if (n1
>= 0x1000000000000000ULL
&& n
/ b
!= n1
)
2476 /* Determine the characteristics (unsigned and/or 64bit) the type of
2477 the constant must have according to the constant suffix(es) */
2478 lcount
= ucount
= 0;
2484 tcc_error("three 'l's in integer constant");
2485 if (lcount
&& *(p
- 1) != ch
)
2486 tcc_error("incorrect integer suffix: %s", p1
);
2489 } else if (t
== 'U') {
2491 tcc_error("two 'u's in integer constant");
2499 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2500 if (ucount
== 0 && b
== 10) {
2501 if (lcount
<= (LONG_SIZE
== 4)) {
2502 if (n
>= 0x80000000U
)
2503 lcount
= (LONG_SIZE
== 4) + 1;
2505 if (n
>= 0x8000000000000000ULL
)
2508 if (lcount
<= (LONG_SIZE
== 4)) {
2509 if (n
>= 0x100000000ULL
)
2510 lcount
= (LONG_SIZE
== 4) + 1;
2511 else if (n
>= 0x80000000U
)
2514 if (n
>= 0x8000000000000000ULL
)
2519 tcc_warning("integer constant overflow");
2528 ++tok
; /* TOK_CU... */
2532 tcc_error("invalid number");
2536 #define PARSE2(c1, tok1, c2, tok2) \
2547 /* return next token without macro substitution */
2548 static void next_nomacro(void)
2550 int t
, c
, is_long
, len
;
2564 if (parse_flags
& PARSE_FLAG_SPACES
)
2565 goto keep_tok_flags
;
2566 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2575 /* first look if it is in fact an end of buffer */
2576 c
= handle_stray(&p
);
2580 TCCState
*s1
= tcc_state
;
2581 if (!(tok_flags
& TOK_FLAG_BOL
)) {
2582 /* add implicit newline */
2584 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2586 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2587 tcc_error("missing #endif");
2588 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2589 /* no include left : end of file. */
2592 /* pop include file */
2594 /* test if previous '#endif' was after a #ifdef at
2596 if (tok_flags
& TOK_FLAG_ENDIF
) {
2598 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2600 search_cached_include(s1
, file
->true_filename
, 1)
2601 ->ifndef_macro
= file
->ifndef_macro_saved
;
2602 tok_flags
&= ~TOK_FLAG_ENDIF
;
2605 /* add end of include file debug info */
2606 tcc_debug_eincl(tcc_state
);
2607 /* pop include stack */
2609 s1
->include_stack_ptr
--;
2622 tok_flags
|= TOK_FLAG_BOL
;
2623 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2626 goto keep_tok_flags
;
2631 if ((tok_flags
& TOK_FLAG_BOL
) &&
2632 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2633 tok_flags
&= ~TOK_FLAG_BOL
;
2635 preprocess(tok_flags
& TOK_FLAG_BOF
);
2641 tok
= TOK_TWOSHARPS
;
2643 #if !defined(TCC_TARGET_ARM)
2644 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2645 p
= parse_line_comment(p
- 1);
2656 /* dollar is allowed to start identifiers when not parsing asm */
2658 if (!(isidnum_table
['$' - CH_EOF
] & IS_ID
)
2659 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2662 case 'a': case 'b': case 'c': case 'd':
2663 case 'e': case 'f': case 'g': case 'h':
2664 case 'i': case 'j': case 'k': case 'l':
2665 case 'm': case 'n': case 'o': case 'p':
2666 case 'q': case 'r': case 's': case 't':
2667 case 'u': case 'v': case 'w': case 'x':
2669 case 'A': case 'B': case 'C': case 'D':
2670 case 'E': case 'F': case 'G': case 'H':
2671 case 'I': case 'J': case 'K':
2672 case 'M': case 'N': case 'O': case 'P':
2673 case 'Q': case 'R': case 'S': case 'T':
2674 case 'U': case 'V': case 'W': case 'X':
2680 h
= TOK_HASH_FUNC(h
, c
);
2681 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2682 h
= TOK_HASH_FUNC(h
, c
);
2687 /* fast case : no stray found, so we have the full token
2688 and we have already hashed it */
2689 h
&= (TOK_HASH_SIZE
- 1);
2690 pts
= &hash_ident
[h
];
2695 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2697 pts
= &(ts
->hash_next
);
2699 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2703 cstr_reset(&tokcstr
);
2704 cstr_cat(&tokcstr
, (char *) p1
, len
);
2708 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2710 cstr_ccat(&tokcstr
, c
);
2713 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2719 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2721 goto parse_ident_fast
;
2724 if (c
== '\'' || c
== '\"') {
2728 cstr_reset(&tokcstr
);
2729 cstr_ccat(&tokcstr
, 'L');
2730 goto parse_ident_slow
;
2735 case '0': case '1': case '2': case '3':
2736 case '4': case '5': case '6': case '7':
2740 /* after the first digit, accept digits, alpha, '.' or sign if
2741 prefixed by 'eEpP' */
2743 cstr_reset(&tokcstr
);
2745 cstr_ccat(&tokcstr
, t
);
2746 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2748 || ((c
== '+' || c
== '-')
2749 && (((t
== 'e' || t
== 'E')
2750 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2751 /* 0xe+1 is 3 tokens in asm */
2752 && ((char*)tokcstr
.data
)[0] == '0'
2753 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2754 || t
== 'p' || t
== 'P'))))
2759 /* We add a trailing '\0' to ease parsing */
2760 cstr_ccat(&tokcstr
, '\0');
2761 tokc
.str
.size
= tokcstr
.size
;
2762 tokc
.str
.data
= tokcstr
.data
;
2767 /* special dot handling because it can also start a number */
2772 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2773 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2775 goto parse_ident_fast
;
2776 } else if (c
== '.') {
2782 *--p
= '.'; /* may underflow into file->unget[] */
2793 cstr_reset(&tokcstr
);
2795 cstr_ccat(&tokcstr
, 'L');
2796 cstr_ccat(&tokcstr
, c
);
2797 p
= parse_pp_string(p
, c
, &tokcstr
);
2798 cstr_ccat(&tokcstr
, c
);
2799 cstr_ccat(&tokcstr
, '\0');
2800 tokc
.str
.size
= tokcstr
.size
;
2801 tokc
.str
.data
= tokcstr
.data
;
2810 } else if (c
== '<') {
2827 } else if (c
== '>') {
2845 } else if (c
== '=') {
2858 } else if (c
== '=') {
2871 } else if (c
== '=') {
2884 } else if (c
== '=') {
2887 } else if (c
== '>') {
2895 PARSE2('!', '!', '=', TOK_NE
)
2896 PARSE2('=', '=', '=', TOK_EQ
)
2897 PARSE2('*', '*', '=', TOK_A_MUL
)
2898 PARSE2('%', '%', '=', TOK_A_MOD
)
2899 PARSE2('^', '^', '=', TOK_A_XOR
)
2901 /* comments or operator */
2905 p
= parse_comment(p
);
2906 /* comments replaced by a blank */
2909 } else if (c
== '/') {
2910 p
= parse_line_comment(p
);
2913 } else if (c
== '=') {
2933 case '@': /* only used in assembler */
2939 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
2940 goto parse_ident_fast
;
2941 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2943 tcc_error("unrecognized character \\x%02x", c
);
2949 #if defined(PARSE_DEBUG)
2950 printf("token = %d %s\n", tok
, get_tok_str(tok
, &tokc
));
2956 static void define_print(TCCState
*s1
, int v
);
2957 static void pp_print(const char *msg
, int v
, const int *str
)
2959 FILE *fp
= tcc_state
->ppfp
;
2961 if (msg
[0] == '#' && indent
== 0)
2963 else if (msg
[0] == '+')
2965 else if (msg
[0] == '-')
2968 fprintf(fp
, "%*s", indent
, "");
2969 if (msg
[0] == '#') {
2970 define_print(tcc_state
, v
);
2972 tok_print(str
, v
? "%s %s" : "%s", msg
, get_tok_str(v
, 0));
2975 #define PP_PRINT(x) pp_print x
2980 static int macro_subst(
2981 TokenString
*tok_str
,
2983 const int *macro_str
2986 /* substitute arguments in replacement lists in macro_str by the values in
2987 args (field d) and return allocated string */
2988 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2990 int t
, t0
, t1
, t2
, n
;
2997 PP_PRINT(("asubst:", 0, macro_str
));
2998 for (s
= args
, n
= 0; s
; s
= s
->prev
, ++n
);
3000 for (s
= args
, t
= 0; t
< n
; s
= s
->prev
, ++t
);
3001 tok_print(s
->d
, "%*s - arg: %s:", indent
, "", get_tok_str(s
->v
, 0));
3008 TOK_GET(&t
, ¯o_str
, &cval
);
3013 do t
= *macro_str
++; while (t
== ' ');
3014 s
= sym_find2(args
, t
);
3016 cstr_reset(&tokcstr
);
3017 cstr_ccat(&tokcstr
, '\"');
3019 while (*st
!= TOK_EOF
) {
3021 TOK_GET(&t
, &st
, &cval
);
3022 s
= get_tok_str(t
, &cval
);
3024 if (t
== TOK_PPSTR
&& *s
!= '\'')
3025 add_char(&tokcstr
, *s
);
3027 cstr_ccat(&tokcstr
, *s
);
3031 cstr_ccat(&tokcstr
, '\"');
3032 cstr_ccat(&tokcstr
, '\0');
3033 //printf("\nstringize: <%s>\n", (char *)tokcstr.data);
3035 cval
.str
.size
= tokcstr
.size
;
3036 cval
.str
.data
= tokcstr
.data
;
3037 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
3039 expect("macro parameter after '#'");
3041 } else if (t
>= TOK_IDENT
) {
3042 s
= sym_find2(args
, t
);
3046 while ((t2
= macro_str
[n
]) == ' ')
3048 /* if '##' is present before or after, no arg substitution */
3049 if (t2
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
3050 /* special case for var arg macros : ## eats the ','
3051 if empty VA_ARGS variable. */
3052 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
3053 int c
= str
.str
[str
.len
- 1];
3054 while (str
.str
[--str
.len
] != ',')
3056 if (*st
== TOK_EOF
) {
3057 /* suppress ',' '##' */
3059 /* suppress '##' and add variable */
3062 str
.str
[str
.len
++] = c
;
3067 tok_str_add(&str
, TOK_PLCHLDR
);
3072 /* Expand arguments tokens and store them. In most
3073 cases we could also re-expand each argument if
3074 used multiple times, but not if the argument
3075 contains the __COUNTER__ macro. */
3078 macro_subst(&str2
, nested_list
, st
);
3079 tok_str_add(&str2
, TOK_EOF
);
3084 while (*st
!= TOK_EOF
) {
3085 TOK_GET(&t2
, &st
, &cval
);
3086 tok_str_add2(&str
, t2
, &cval
);
3089 tok_str_add(&str
, t
);
3092 tok_str_add2(&str
, t
, &cval
);
3097 tok_str_add(&str
, 0);
3098 PP_PRINT(("areslt:", 0, str
.str
));
3102 /* handle the '##' operator. return the resulting string (which must be freed). */
3103 static inline int *macro_twosharps(const int *ptr0
)
3107 TokenString macro_str1
;
3110 tok_str_new(¯o_str1
);
3111 cstr_reset(&tokcstr
);
3112 for (ptr
= ptr0
;;) {
3113 TOK_GET(&t1
, &ptr
, &cv1
);
3118 while ((t2
= ptr
[n
]) == ' ')
3120 if (t2
!= TOK_PPJOIN
)
3123 while ((t2
= *++ptr
) == ' ' || t2
== TOK_PPJOIN
)
3125 TOK_GET(&t2
, &ptr
, &cv2
);
3126 if (t2
== TOK_PLCHLDR
)
3128 if (t1
!= TOK_PLCHLDR
) {
3129 cstr_cat(&tokcstr
, get_tok_str(t1
, &cv1
), -1);
3132 cstr_cat(&tokcstr
, get_tok_str(t2
, &cv2
), -1);
3135 cstr_ccat(&tokcstr
, 0);
3136 tcc_open_bf(tcc_state
, ":paste:", tokcstr
.size
);
3137 memcpy(file
->buffer
, tokcstr
.data
, tokcstr
.size
);
3138 tok_flags
= 0; /* don't interpret '#' */
3139 for (n
= 0;;n
= l
) {
3141 tok_str_add2(¯o_str1
, tok
, &tokc
);
3142 if (*file
->buf_ptr
== 0)
3144 tok_str_add(¯o_str1
, ' ');
3145 l
= file
->buf_ptr
- file
->buffer
;
3146 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3147 " preprocessing token", l
- n
, file
->buffer
+ n
, file
->buf_ptr
);
3150 cstr_reset(&tokcstr
);
3152 if (t1
!= TOK_PLCHLDR
)
3153 tok_str_add2(¯o_str1
, t1
, &cv1
);
3155 tok_str_add(¯o_str1
, 0);
3156 PP_PRINT(("pasted:", 0, macro_str1
.str
));
3157 return macro_str1
.str
;
3160 static int peek_file (TokenString
*ws_str
)
3162 uint8_t *p
= file
->buf_ptr
- 1;
3170 p
= parse_comment(p
);
3172 p
= parse_line_comment(p
);
3179 case ' ': case '\t':
3181 case '\f': case '\v': case '\r':
3184 file
->line_num
++, tok_flags
|= TOK_FLAG_BOL
;
3191 tok_str_add(ws_str
, c
);
3195 /* peek or read [ws_str == NULL] next token from function macro call,
3196 walking up macro levels up to the file if necessary */
3197 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3203 const int *m
= macro_ptr
;
3204 while ((t
= *m
) != 0) {
3210 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
3215 /* also, end of scope for nested defined symbol */
3218 *nested_list
= sa
->prev
, sym_free(sa
);
3221 return peek_file(ws_str
);
3224 if (tok
== '\t' || tok
== TOK_LINEFEED
)
3230 /* do macro substitution of current token with macro 's' and add
3231 result to (tok_str,tok_len). 'nested_list' is the list of all
3232 macros we got inside to avoid recursing. Return non zero if no
3233 substitution needs to be done */
3234 static int macro_subst_tok(
3235 TokenString
*tok_str
,
3242 PP_PRINT(("#", v
, s
->d
));
3249 if (s
->type
.t
& MACRO_FUNC
) {
3250 int saved_parse_flags
= parse_flags
;
3255 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3256 | PARSE_FLAG_ACCEPT_STRAYS
;
3259 /* peek next token from argument stream */
3260 t
= next_argstream(nested_list
, &str
);
3262 /* not a macro substitution after all, restore the
3263 * macro token plus all whitespace we've read.
3264 * whitespace is intentionally not merged to preserve
3266 parse_flags
= saved_parse_flags
;
3267 tok_str_add2_spc(tok_str
, v
, 0);
3268 if (parse_flags
& PARSE_FLAG_SPACES
)
3269 for (i
= 0; i
< str
.len
; i
++)
3270 tok_str_add(tok_str
, str
.str
[i
]);
3271 tok_str_free_str(str
.str
);
3274 tok_str_free_str(str
.str
);
3277 /* argument macro */
3280 /* NOTE: empty args are allowed, except if no args */
3281 i
= 2; /* eat '(' */
3284 t
= next_argstream(nested_list
, NULL
);
3285 } while (t
== ' ' || --i
);
3288 if (t
== ')') /* handle '()' case */
3290 tcc_error("macro '%s' used with too many args",
3296 /* NOTE: non zero sa->type.t indicates VA_ARGS */
3298 || (t
!= ')' && (t
!= ',' || sa
->type
.t
))) {
3300 tcc_error("EOF in invocation of macro '%s'",
3309 tok_str_add2_spc(&str
, t
, &tokc
);
3310 t
= next_argstream(nested_list
, NULL
);
3312 tok_str_add(&str
, TOK_EOF
);
3313 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3319 /* special case for gcc var args: add an empty
3320 var arg argument if it is omitted */
3321 if (sa
->type
.t
&& gnu_ext
)
3323 tcc_error("macro '%s' used with too few args",
3329 /* now subst each arg */
3330 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3335 tok_str_free_str(sa
->d
);
3336 tok_str_free_str(sa
->e
);
3340 parse_flags
= saved_parse_flags
;
3343 /* process '##'s (if present) */
3345 if (s
->type
.t
& MACRO_JOIN
)
3346 jstr
= macro_twosharps(mstr
);
3348 sa
= sym_push2(nested_list
, v
, 0, 0);
3349 ret
= macro_subst(tok_str
, nested_list
, jstr
);
3350 /* pop nested defined symbol */
3351 if (sa
== *nested_list
)
3352 *nested_list
= sa
->prev
, sym_free(sa
);
3355 tok_str_free_str(jstr
);
3357 tok_str_free_str(mstr
);
3362 char buf
[32], *cstrval
= buf
;
3364 /* special macros */
3365 if (v
== TOK___LINE__
|| v
== TOK___COUNTER__
) {
3366 t
= v
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3367 snprintf(buf
, sizeof(buf
), "%d", t
);
3371 } else if (v
== TOK___FILE__
) {
3372 cstrval
= file
->filename
;
3375 } else if (v
== TOK___DATE__
|| v
== TOK___TIME__
) {
3379 tm
= localtime(&ti
);
3380 if (v
== TOK___DATE__
) {
3381 static char const ab_month_name
[12][4] = {
3382 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3383 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3385 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3386 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3388 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3389 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3394 cval
.str
.size
= strlen(cstrval
) + 1;
3395 cval
.str
.data
= cstrval
;
3396 tok_str_add2_spc(tok_str
, t
, &cval
);
3402 /* do macro substitution of macro_str and add result to
3403 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3404 inside to avoid recursing. */
3405 static int macro_subst(
3406 TokenString
*tok_str
,
3408 const int *macro_str
3417 int tlen
= tok_str
->len
;
3418 PP_PRINT(("+expand:", 0, macro_str
));
3422 TOK_GET(&t
, ¯o_str
, &cval
);
3423 if (t
== 0 || t
== TOK_EOF
)
3425 if (t
>= TOK_IDENT
) {
3427 if (s
== NULL
|| nosubst
)
3429 /* if nested substitution, do nothing */
3430 if (sym_find2(*nested_list
, t
)) {
3431 /* and mark so it doesn't get subst'd again */
3435 str
= tok_str_alloc();
3436 str
->str
= (int*)macro_str
; /* setup stream for possible arguments */
3437 begin_macro(str
, 2);
3438 nosubst
= macro_subst_tok(tok_str
, nested_list
, s
);
3439 if (macro_stack
!= str
) {
3440 /* already finished by reading function macro arguments */
3443 macro_str
= macro_ptr
;
3445 } else if (t
== ' ') {
3446 if (parse_flags
& PARSE_FLAG_SPACES
)
3447 tok_str
->need_spc
|= 1;
3450 tok_str_add2_spc(tok_str
, t
, &cval
);
3451 if (nosubst
&& t
!= '(')
3453 /* GCC supports 'defined' as result of a macro substitution */
3454 if (t
== TOK_DEFINED
&& pp_expr
)
3460 tok_str_add(tok_str
, 0), --tok_str
->len
;
3461 PP_PRINT(("-result:", 0, tok_str
->str
+ tlen
));
3466 /* return next token with macro substitution */
3467 ST_FUNC
void next(void)
3473 if (TOK_HAS_VALUE(t
)) {
3474 tok_get(&tok
, ¯o_ptr
, &tokc
);
3475 if (t
== TOK_LINENUM
) {
3476 file
->line_num
= tokc
.i
;
3480 } else if (t
== 0) {
3481 /* end of macro or unget token string */
3484 } else if (t
== TOK_EOF
) {
3488 t
&= ~SYM_FIELD
; /* remove 'nosubst' marker */
3490 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3491 tcc_error("stray '\\' in program");
3500 if (t
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3501 /* if reading from file, try to substitute macros */
3502 Sym
*s
= define_find(t
);
3504 Sym
*nested_list
= NULL
;
3505 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3506 tok_str_add(&tokstr_buf
, 0);
3507 begin_macro(&tokstr_buf
, 0);
3514 /* convert preprocessor tokens into C tokens */
3515 if (t
== TOK_PPNUM
) {
3516 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3517 parse_number(tokc
.str
.data
);
3518 } else if (t
== TOK_PPSTR
) {
3519 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3520 parse_string(tokc
.str
.data
, tokc
.str
.size
- 1);
3524 /* push back current token and set current token to 'last_tok'. Only
3525 identifier case handled for labels. */
3526 ST_INLN
void unget_tok(int last_tok
)
3528 TokenString
*str
= &unget_buf
;
3530 if (str
->len
) /* use static buffer except if already in use */
3531 str
= tok_str_alloc(), alloc
= 1;
3533 tok_str_add2(str
, tok
, &tokc
);
3534 tok_str_add(str
, 0);
3535 begin_macro(str
, alloc
);
3539 /* ------------------------------------------------------------------------- */
3540 /* init preprocessor */
3542 static const char * const target_os_defs
=
3543 #ifdef TCC_TARGET_PE
3549 # if defined TCC_TARGET_MACHO
3551 # elif TARGETOS_FreeBSD
3553 # elif TARGETOS_FreeBSD_kernel
3554 "__FreeBSD_kernel__\0"
3555 # elif TARGETOS_NetBSD
3557 # elif TARGETOS_OpenBSD
3562 # if TARGETOS_ANDROID
3571 static void putdef(CString
*cs
, const char *p
)
3573 cstr_printf(cs
, "#define %s%s\n", p
, &" 1"[!!strchr(p
, ' ')*2]);
3576 static void putdefs(CString
*cs
, const char *p
)
3579 putdef(cs
, p
), p
= strchr(p
, 0) + 1;
3582 static void tcc_predefs(TCCState
*s1
, CString
*cs
, int is_asm
)
3584 cstr_printf(cs
, "#define __TINYC__ 9%.2s\n", TCC_VERSION
+ 4);
3585 putdefs(cs
, target_machine_defs
);
3586 putdefs(cs
, target_os_defs
);
3588 #ifdef TCC_TARGET_ARM
3589 if (s1
->float_abi
== ARM_HARD_FLOAT
)
3590 putdef(cs
, "__ARM_PCS_VFP");
3593 putdef(cs
, "__ASSEMBLER__");
3594 if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
)
3595 putdef(cs
, "__TCC_PP__");
3596 if (s1
->output_type
== TCC_OUTPUT_MEMORY
)
3597 putdef(cs
, "__TCC_RUN__");
3598 #ifdef CONFIG_TCC_BACKTRACE
3599 if (s1
->do_backtrace
)
3600 putdef(cs
, "__TCC_BACKTRACE__");
3602 #ifdef CONFIG_TCC_BCHECK
3603 if (s1
->do_bounds_check
)
3604 putdef(cs
, "__TCC_BCHECK__");
3606 if (s1
->char_is_unsigned
)
3607 putdef(cs
, "__CHAR_UNSIGNED__");
3608 if (s1
->optimize
> 0)
3609 putdef(cs
, "__OPTIMIZE__");
3610 if (s1
->option_pthread
)
3611 putdef(cs
, "_REENTRANT");
3612 if (s1
->leading_underscore
)
3613 putdef(cs
, "__leading_underscore");
3614 cstr_printf(cs
, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE
);
3615 cstr_printf(cs
, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE
);
3617 putdef(cs
, "__STDC__");
3618 cstr_printf(cs
, "#define __STDC_VERSION__ %dL\n", s1
->cversion
);
3620 /* load more predefs and __builtins */
3621 #if CONFIG_TCC_PREDEFS
3622 #include "tccdefs_.h" /* include as strings */
3624 "#include <tccdefs.h>\n" /* load at runtime */
3628 cstr_printf(cs
, "#define __BASE_FILE__ \"%s\"\n", file
->filename
);
3631 ST_FUNC
void preprocess_start(TCCState
*s1
, int filetype
)
3633 int is_asm
= !!(filetype
& (AFF_TYPE_ASM
|AFF_TYPE_ASMPP
));
3637 s1
->include_stack_ptr
= s1
->include_stack
;
3638 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3639 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3642 pp_debug_tok
= pp_debug_symv
= 0;
3643 s1
->pack_stack
[0] = 0;
3644 s1
->pack_stack_ptr
= s1
->pack_stack
;
3646 set_idnum('$', !is_asm
&& s1
->dollars_in_identifiers
? IS_ID
: 0);
3647 set_idnum('.', is_asm
? IS_ID
: 0);
3649 if (!(filetype
& AFF_TYPE_ASM
)) {
3652 tcc_predefs(s1
, &cstr
, is_asm
);
3653 if (s1
->cmdline_defs
.size
)
3654 cstr_cat(&cstr
, s1
->cmdline_defs
.data
, s1
->cmdline_defs
.size
);
3655 if (s1
->cmdline_incl
.size
)
3656 cstr_cat(&cstr
, s1
->cmdline_incl
.data
, s1
->cmdline_incl
.size
);
3657 //printf("%.*s\n", cstr.size, (char*)cstr.data);
3658 *s1
->include_stack_ptr
++ = file
;
3659 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3660 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3663 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3666 /* cleanup from error/setjmp */
3667 ST_FUNC
void preprocess_end(TCCState
*s1
)
3677 ST_FUNC
int set_idnum(int c
, int val
)
3679 int prev
= isidnum_table
[c
- CH_EOF
];
3680 isidnum_table
[c
- CH_EOF
] = val
;
3684 ST_FUNC
void tccpp_new(TCCState
*s
)
3689 /* init isid table */
3690 for(i
= CH_EOF
; i
<128; i
++)
3692 is_space(i
) ? IS_SPC
3697 for(i
= 128; i
<256; i
++)
3698 set_idnum(i
, IS_ID
);
3700 /* init allocators */
3701 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3702 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3704 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3705 memset(s
->cached_includes_hash
, 0, sizeof s
->cached_includes_hash
);
3708 cstr_new(&cstr_buf
);
3709 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3710 tok_str_new(&tokstr_buf
);
3711 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3712 tok_str_new(&unget_buf
);
3714 tok_ident
= TOK_IDENT
;
3723 tok_alloc(p
, r
- p
- 1);
3727 /* we add dummy defines for some special macros to speed up tests
3728 and to have working defined() */
3729 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
3730 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
3731 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
3732 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
3733 define_push(TOK___COUNTER__
, MACRO_OBJ
, NULL
, NULL
);
3736 ST_FUNC
void tccpp_delete(TCCState
*s
)
3740 dynarray_reset(&s
->cached_includes
, &s
->nb_cached_includes
);
3743 n
= tok_ident
- TOK_IDENT
;
3744 if (n
> total_idents
)
3746 for(i
= 0; i
< n
; i
++)
3747 tal_free(toksym_alloc
, table_ident
[i
]);
3748 tcc_free(table_ident
);
3751 /* free static buffers */
3752 cstr_free(&tokcstr
);
3753 cstr_free(&cstr_buf
);
3754 tok_str_free_str(tokstr_buf
.str
);
3755 tok_str_free_str(unget_buf
.str
);
3757 /* free allocators */
3758 tal_delete(toksym_alloc
);
3759 toksym_alloc
= NULL
;
3760 tal_delete(tokstr_alloc
);
3761 tokstr_alloc
= NULL
;
3764 /* ------------------------------------------------------------------------- */
3765 /* tcc -E [-P[1]] [-dD} support */
3767 static int pp_need_space(int a
, int b
);
3769 static void tok_print(const int *str
, const char *msg
, ...)
3771 FILE *fp
= tcc_state
->ppfp
;
3777 vfprintf(fp
, msg
, ap
);
3782 TOK_GET(&t
, &str
, &cval
);
3783 if (t
== 0 || t
== TOK_EOF
)
3785 if (pp_need_space(t0
, t
))
3787 fprintf(fp
, &" %s"[s
], t
== TOK_PLCHLDR
? "<>" : get_tok_str(t
, &cval
));
3793 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3795 int d
= f
->line_num
- f
->line_ref
;
3800 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3802 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3804 fputs("\n", s1
->ppfp
), --d
;
3805 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3806 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3808 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3809 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3811 f
->line_ref
= f
->line_num
;
3814 static void define_print(TCCState
*s1
, int v
)
3820 if (NULL
== s
|| NULL
== s
->d
)
3824 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3825 if (s
->type
.t
& MACRO_FUNC
) {
3830 fprintf(fp
,"%s", get_tok_str(a
->v
, NULL
));
3837 tok_print(s
->d
, "");
3840 static void pp_debug_defines(TCCState
*s1
)
3851 pp_line(s1
, file
, 0);
3852 file
->line_ref
= ++file
->line_num
;
3856 vs
= get_tok_str(v
, NULL
);
3857 if (t
== TOK_DEFINE
) {
3858 define_print(s1
, v
);
3859 } else if (t
== TOK_UNDEF
) {
3860 fprintf(fp
, "#undef %s\n", vs
);
3861 } else if (t
== TOK_push_macro
) {
3862 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3863 } else if (t
== TOK_pop_macro
) {
3864 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
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
|| a
== TOK_PPNUM
? b
>= TOK_IDENT
|| b
== TOK_PPNUM
3879 /* maybe hex like 0x1e */
3880 static int pp_check_he0xE(int t
, const char *p
)
3882 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3887 /* Preprocess the current file */
3888 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3890 BufferedFile
**iptr
;
3891 int token_seen
, spcs
, level
;
3895 parse_flags
= PARSE_FLAG_PREPROCESS
3896 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3897 | PARSE_FLAG_LINEFEED
3899 | PARSE_FLAG_ACCEPT_STRAYS
3901 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3902 capability to compile and run itself, provided all numbers are
3903 given as decimals. tcc -E -P10 will do. */
3904 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
3905 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
3908 /* for PP benchmarks */
3909 do next(); while (tok
!= TOK_EOF
);
3913 token_seen
= TOK_LINEFEED
, spcs
= 0, level
= 0;
3915 pp_line(s1
, file
->prev
, level
++);
3916 pp_line(s1
, file
, level
);
3919 iptr
= s1
->include_stack_ptr
;
3924 level
= s1
->include_stack_ptr
- iptr
;
3927 pp_line(s1
, *iptr
, 0);
3928 pp_line(s1
, file
, level
);
3930 if (s1
->dflag
& 7) {
3931 pp_debug_defines(s1
);
3936 if (is_space(tok
)) {
3937 if (spcs
< sizeof white
- 1)
3938 white
[spcs
++] = tok
;
3940 } else if (tok
== TOK_LINEFEED
) {
3942 if (token_seen
== TOK_LINEFEED
)
3945 } else if (token_seen
== TOK_LINEFEED
) {
3946 pp_line(s1
, file
, 0);
3947 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
3948 white
[spcs
++] = ' ';
3951 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
3952 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
3953 token_seen
= pp_check_he0xE(tok
, p
);
3958 /* ------------------------------------------------------------------------- */