2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 /* #define to 1 to enable (see parse_pp_string()) */
25 #define ACCEPT_LF_IN_STRINGS 0
27 /********************************************************/
28 /* global variables */
30 ST_DATA
int tok_flags
;
31 ST_DATA
int parse_flags
;
33 ST_DATA
struct BufferedFile
*file
;
36 ST_DATA
const int *macro_ptr
;
37 ST_DATA CString tokcstr
; /* current parsed string, if any */
39 /* display benchmark infos */
40 ST_DATA
int tok_ident
;
41 ST_DATA TokenSym
**table_ident
;
43 /* ------------------------------------------------------------------------- */
45 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
46 static char token_buf
[STRING_MAX_SIZE
+ 1];
47 static CString cstr_buf
;
48 static TokenString tokstr_buf
;
49 static unsigned char isidnum_table
[256 - CH_EOF
];
50 static int pp_debug_tok
, pp_debug_symv
;
53 static int pp_counter
;
54 static void tok_print(const char *msg
, const int *str
);
56 static struct TinyAlloc
*toksym_alloc
;
57 static struct TinyAlloc
*tokstr_alloc
;
59 static TokenString
*macro_stack
;
61 static const char tcc_keywords
[] =
62 #define DEF(id, str) str "\0"
67 /* WARNING: the content of this string encodes token numbers */
68 static const unsigned char tok_two_chars
[] =
70 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
71 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
93 '#','#', TOK_TWOSHARPS
,
98 static void next_nomacro(void);
100 ST_FUNC
void skip(int c
)
103 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
107 ST_FUNC
void expect(const char *msg
)
109 tcc_error("%s expected", msg
);
112 /* ------------------------------------------------------------------------- */
113 /* Custom allocator for tiny objects */
118 #define tal_free(al, p) tcc_free(p)
119 #define tal_realloc(al, p, size) tcc_realloc(p, size)
120 #define tal_new(a,b,c)
121 #define tal_delete(a)
123 #if !defined(MEM_DEBUG)
124 #define tal_free(al, p) tal_free_impl(al, p)
125 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
126 #define TAL_DEBUG_PARAMS
129 //#define TAL_INFO 1 /* collect and dump allocators stats */
130 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
131 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
132 #define TAL_DEBUG_PARAMS , const char *file, int line
133 #define TAL_DEBUG_FILE_LEN 40
136 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
137 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
138 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
139 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
140 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
141 #define CSTR_TAL_LIMIT 1024
143 typedef struct TinyAlloc
{
149 struct TinyAlloc
*next
, *top
;
158 typedef struct tal_header_t
{
161 int line_num
; /* negative line_num used for double free check */
162 char file_name
[TAL_DEBUG_FILE_LEN
+ 1];
166 /* ------------------------------------------------------------------------- */
168 static TinyAlloc
*tal_new(TinyAlloc
**pal
, unsigned limit
, unsigned size
)
170 TinyAlloc
*al
= tcc_mallocz(sizeof(TinyAlloc
));
171 al
->p
= al
->buffer
= tcc_malloc(size
);
178 static void tal_delete(TinyAlloc
*al
)
186 fprintf(stderr
, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
187 al
->limit
, al
->size
/ 1024.0 / 1024.0, al
->nb_peak
, al
->nb_total
, al
->nb_missed
,
188 (al
->peak_p
- al
->buffer
) * 100.0 / al
->size
);
191 if (al
->nb_allocs
> 0) {
193 fprintf(stderr
, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
194 al
->nb_allocs
, al
->limit
);
197 tal_header_t
*header
= (tal_header_t
*)p
;
198 if (header
->line_num
> 0) {
199 fprintf(stderr
, "%s:%d: chunk of %d bytes leaked\n",
200 header
->file_name
, header
->line_num
, header
->size
);
202 p
+= header
->size
+ sizeof(tal_header_t
);
210 tcc_free(al
->buffer
);
216 static void tal_free_impl(TinyAlloc
*al
, void *p TAL_DEBUG_PARAMS
)
221 if (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
) {
223 tal_header_t
*header
= (((tal_header_t
*)p
) - 1);
224 if (header
->line_num
< 0) {
225 fprintf(stderr
, "%s:%d: TAL_DEBUG: double frees chunk from\n",
227 fprintf(stderr
, "%s:%d: %d bytes\n",
228 header
->file_name
, (int)-header
->line_num
, (int)header
->size
);
230 header
->line_num
= -header
->line_num
;
235 } else if (al
->next
) {
243 static void *tal_realloc_impl(TinyAlloc
**pal
, void *p
, unsigned size TAL_DEBUG_PARAMS
)
245 tal_header_t
*header
;
248 unsigned adj_size
= (size
+ 3) & -4;
249 TinyAlloc
*al
= *pal
;
252 is_own
= (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
);
253 if ((!p
|| is_own
) && size
<= al
->limit
) {
254 if (al
->p
- al
->buffer
+ adj_size
+ sizeof(tal_header_t
) < al
->size
) {
255 header
= (tal_header_t
*)al
->p
;
256 header
->size
= adj_size
;
258 { int ofs
= strlen(file
) - TAL_DEBUG_FILE_LEN
;
259 strncpy(header
->file_name
, file
+ (ofs
> 0 ? ofs
: 0), TAL_DEBUG_FILE_LEN
);
260 header
->file_name
[TAL_DEBUG_FILE_LEN
] = 0;
261 header
->line_num
= line
; }
263 ret
= al
->p
+ sizeof(tal_header_t
);
264 al
->p
+= adj_size
+ sizeof(tal_header_t
);
266 header
= (((tal_header_t
*)p
) - 1);
267 if (p
) memcpy(ret
, p
, header
->size
);
269 header
->line_num
= -header
->line_num
;
275 if (al
->nb_peak
< al
->nb_allocs
)
276 al
->nb_peak
= al
->nb_allocs
;
277 if (al
->peak_p
< al
->p
)
284 ret
= tal_realloc(*pal
, 0, size
);
285 header
= (((tal_header_t
*)p
) - 1);
286 if (p
) memcpy(ret
, p
, header
->size
);
288 header
->line_num
= -header
->line_num
;
295 TinyAlloc
*bottom
= al
, *next
= al
->top
? al
->top
: al
;
297 al
= tal_new(pal
, next
->limit
, next
->size
* 2);
305 ret
= tcc_malloc(size
);
306 header
= (((tal_header_t
*)p
) - 1);
307 if (p
) memcpy(ret
, p
, header
->size
);
309 header
->line_num
= -header
->line_num
;
311 } else if (al
->next
) {
315 ret
= tcc_realloc(p
, size
);
324 /* ------------------------------------------------------------------------- */
325 /* CString handling */
326 static void cstr_realloc(CString
*cstr
, int new_size
)
330 size
= cstr
->size_allocated
;
332 size
= 8; /* no need to allocate a too small first string */
333 while (size
< new_size
)
335 cstr
->data
= tcc_realloc(cstr
->data
, size
);
336 cstr
->size_allocated
= size
;
340 ST_INLN
void cstr_ccat(CString
*cstr
, int ch
)
343 size
= cstr
->size
+ 1;
344 if (size
> cstr
->size_allocated
)
345 cstr_realloc(cstr
, size
);
346 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
350 ST_INLN
char *unicode_to_utf8 (char *b
, uint32_t Uc
)
352 if (Uc
<0x80) *b
++=Uc
;
353 else if (Uc
<0x800) *b
++=192+Uc
/64, *b
++=128+Uc
%64;
354 else if (Uc
-0xd800u
<0x800) goto error
;
355 else if (Uc
<0x10000) *b
++=224+Uc
/4096, *b
++=128+Uc
/64%64, *b
++=128+Uc
%64;
356 else if (Uc
<0x110000) *b
++=240+Uc
/262144, *b
++=128+Uc
/4096%64, *b
++=128+Uc
/64%64, *b
++=128+Uc
%64;
357 else error
: tcc_error("0x%x is not a valid universal character", Uc
);
361 /* add a unicode character expanded into utf8 */
362 ST_INLN
void cstr_u8cat(CString
*cstr
, int ch
)
365 e
= unicode_to_utf8(buf
, (uint32_t)ch
);
366 cstr_cat(cstr
, buf
, e
- buf
);
369 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
, int len
)
373 len
= strlen(str
) + 1 + len
;
374 size
= cstr
->size
+ len
;
375 if (size
> cstr
->size_allocated
)
376 cstr_realloc(cstr
, size
);
377 memmove(((unsigned char *)cstr
->data
) + cstr
->size
, str
, len
);
381 /* add a wide char */
382 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
385 size
= cstr
->size
+ sizeof(nwchar_t
);
386 if (size
> cstr
->size_allocated
)
387 cstr_realloc(cstr
, size
);
388 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
392 ST_FUNC
void cstr_new(CString
*cstr
)
394 memset(cstr
, 0, sizeof(CString
));
397 /* free string and reset it to NULL */
398 ST_FUNC
void cstr_free(CString
*cstr
)
400 tcc_free(cstr
->data
);
403 /* reset string to empty */
404 ST_FUNC
void cstr_reset(CString
*cstr
)
409 ST_FUNC
int cstr_vprintf(CString
*cstr
, const char *fmt
, va_list ap
)
415 if (size
> cstr
->size_allocated
)
416 cstr_realloc(cstr
, size
);
417 size
= cstr
->size_allocated
- cstr
->size
;
419 len
= vsnprintf((char*)cstr
->data
+ cstr
->size
, size
, fmt
, v
);
421 if (len
>= 0 && len
< size
)
429 ST_FUNC
int cstr_printf(CString
*cstr
, const char *fmt
, ...)
433 len
= cstr_vprintf(cstr
, fmt
, ap
);
439 static void add_char(CString
*cstr
, int c
)
441 if (c
== '\'' || c
== '\"' || c
== '\\') {
442 /* XXX: could be more precise if char or string */
443 cstr_ccat(cstr
, '\\');
445 if (c
>= 32 && c
<= 126) {
448 cstr_ccat(cstr
, '\\');
450 cstr_ccat(cstr
, 'n');
452 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
453 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
454 cstr_ccat(cstr
, '0' + (c
& 7));
459 /* ------------------------------------------------------------------------- */
460 /* allocate a new token */
461 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
463 TokenSym
*ts
, **ptable
;
466 if (tok_ident
>= SYM_FIRST_ANOM
)
467 tcc_error("memory full (symbols)");
469 /* expand token table if needed */
470 i
= tok_ident
- TOK_IDENT
;
471 if ((i
% TOK_ALLOC_INCR
) == 0) {
472 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
473 table_ident
= ptable
;
476 ts
= tal_realloc(toksym_alloc
, 0, sizeof(TokenSym
) + len
);
478 ts
->tok
= tok_ident
++;
479 ts
->sym_define
= NULL
;
480 ts
->sym_label
= NULL
;
481 ts
->sym_struct
= NULL
;
482 ts
->sym_identifier
= NULL
;
484 ts
->hash_next
= NULL
;
485 memcpy(ts
->str
, str
, len
);
491 #define TOK_HASH_INIT 1
492 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
495 /* find a token and add it if not found */
496 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
504 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
505 h
&= (TOK_HASH_SIZE
- 1);
507 pts
= &hash_ident
[h
];
512 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
514 pts
= &(ts
->hash_next
);
516 return tok_alloc_new(pts
, str
, len
);
519 ST_FUNC
int tok_alloc_const(const char *str
)
521 return tok_alloc(str
, strlen(str
))->tok
;
525 /* XXX: buffer overflow */
526 /* XXX: float tokens */
527 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
532 cstr_reset(&cstr_buf
);
542 /* XXX: not quite exact, but only useful for testing */
544 sprintf(p
, "%u", (unsigned)cv
->i
);
546 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
550 cstr_ccat(&cstr_buf
, 'L');
552 cstr_ccat(&cstr_buf
, '\'');
553 add_char(&cstr_buf
, cv
->i
);
554 cstr_ccat(&cstr_buf
, '\'');
555 cstr_ccat(&cstr_buf
, '\0');
559 return (char*)cv
->str
.data
;
561 cstr_ccat(&cstr_buf
, 'L');
563 cstr_ccat(&cstr_buf
, '\"');
565 len
= cv
->str
.size
- 1;
567 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
569 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
571 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
573 cstr_ccat(&cstr_buf
, '\"');
574 cstr_ccat(&cstr_buf
, '\0');
578 return strcpy(p
, "<float>");
580 return strcpy(p
, "<double>");
582 return strcpy(p
, "<long double>");
584 return strcpy(p
, "<linenumber");
586 /* above tokens have value, the ones below don't */
594 return strcpy(p
, "...");
596 return strcpy(p
, "<<=");
598 return strcpy(p
, ">>=");
600 return strcpy(p
, "<eof>");
601 case 0: /* anonymous nameless symbols */
602 return strcpy(p
, "<no name>");
605 /* search in two bytes table */
606 const unsigned char *q
= tok_two_chars
;
612 return cstr_buf
.data
;
616 if (v
>= 127 || (v
< 32 && !is_space(v
) && v
!= '\n')) {
617 sprintf(p
, "<\\x%02x>", v
);
623 } else if (v
< tok_ident
) {
624 return table_ident
[v
- TOK_IDENT
]->str
;
625 } else if (v
>= SYM_FIRST_ANOM
) {
626 /* special name for anonymous symbol */
627 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
629 /* should never happen */
634 return cstr_buf
.data
;
637 static inline int check_space(int t
, int *spc
)
639 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
648 /* return the current character, handling end of block if necessary
650 static int handle_eob(void)
652 BufferedFile
*bf
= file
;
655 /* only tries to read if really end of buffer */
656 if (bf
->buf_ptr
>= bf
->buf_end
) {
658 #if defined(PARSE_DEBUG)
663 len
= read(bf
->fd
, bf
->buffer
, len
);
670 bf
->buf_ptr
= bf
->buffer
;
671 bf
->buf_end
= bf
->buffer
+ len
;
672 *bf
->buf_end
= CH_EOB
;
674 if (bf
->buf_ptr
< bf
->buf_end
) {
675 return bf
->buf_ptr
[0];
677 bf
->buf_ptr
= bf
->buf_end
;
682 /* read next char from current input file and handle end of input buffer */
683 static int next_c(void)
685 int ch
= *++file
->buf_ptr
;
686 /* end of buffer/file handling */
687 if (ch
== CH_EOB
&& file
->buf_ptr
>= file
->buf_end
)
692 /* input with '\[\r]\n' handling. */
693 static int handle_stray_noerror(int err
)
696 while ((ch
= next_c()) == '\\') {
706 *--file
->buf_ptr
= '\r';
709 tcc_error("stray '\\' in program");
710 /* may take advantage of 'BufferedFile.unget[4}' */
711 return *--file
->buf_ptr
= '\\';
717 #define ninp() handle_stray_noerror(0)
719 /* handle '\\' in strings, comments and skipped regions */
720 static int handle_bs(uint8_t **p
)
723 file
->buf_ptr
= *p
- 1;
729 /* skip the stray and handle the \\n case. Output an error if
730 incorrect char after the stray */
731 static int handle_stray(uint8_t **p
)
734 file
->buf_ptr
= *p
- 1;
735 c
= handle_stray_noerror(!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
));
740 /* handle the complicated stray case */
745 c = handle_stray(&p); \
748 static int skip_spaces(void)
754 } while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
);
758 /* single line C++ comments */
759 static uint8_t *parse_line_comment(uint8_t *p
)
766 if (c
== '\n' || c
== '\\')
769 if (c
== '\n' || c
== '\\')
784 static uint8_t *parse_comment(uint8_t *p
)
792 if (c
== '\n' || c
== '*' || c
== '\\')
795 if (c
== '\n' || c
== '*' || c
== '\\')
798 /* now we can handle all the cases */
801 } else if (c
== '*') {
814 tcc_error("unexpected end of file in comment");
822 /* parse a string without interpreting escapes */
823 static uint8_t *parse_pp_string(uint8_t *p
, int sep
, CString
*str
)
831 } else if (c
== '\\') {
835 /* XXX: indicate line number of start of string */
836 tok_flags
&= ~TOK_FLAG_BOL
;
837 tcc_error("missing terminating %c character", sep
);
838 } else if (c
== '\\') {
842 /* add char after '\\' unconditionally */
846 goto unterminated_string
;
852 } else if (c
== '\n') {
854 if (ACCEPT_LF_IN_STRINGS
) {
857 } else if (str
) { /* not skipping */
858 goto unterminated_string
;
860 //tcc_warning("missing terminating %c character", sep);
863 } else if (c
== '\r') {
870 goto unterminated_string
;
872 cstr_ccat(str
, '\r');
884 /* skip block of text until #else, #elif or #endif. skip also pairs of
886 static void preprocess_skip(void)
888 int a
, start_of_line
, c
, in_warn_or_error
;
895 in_warn_or_error
= 0;
921 if (in_warn_or_error
)
923 tok_flags
&= ~TOK_FLAG_BOL
;
924 p
= parse_pp_string(p
, c
, NULL
);
928 if (in_warn_or_error
)
933 p
= parse_comment(p
);
934 } else if (c
== '/') {
935 p
= parse_line_comment(p
);
945 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
947 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
949 else if (tok
== TOK_ENDIF
)
951 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
952 in_warn_or_error
= 1;
953 else if (tok
== TOK_LINEFEED
)
955 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
956 p
= parse_line_comment(p
- 1);
958 #if !defined(TCC_TARGET_ARM)
959 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
960 p
= parse_line_comment(p
- 1);
962 /* ARM assembly uses '#' for constants */
977 /* return the number of additional 'ints' necessary to store the
979 static inline int tok_size(const int *p
)
994 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
997 return 1 + LONG_SIZE
/ 4;
1003 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
1006 return 1 + LDOUBLE_SIZE
/ 4;
1014 /* token string handling */
1015 ST_INLN
void tok_str_new(TokenString
*s
)
1018 s
->len
= s
->lastlen
= 0;
1019 s
->allocated_len
= 0;
1020 s
->last_line_num
= -1;
1023 ST_FUNC TokenString
*tok_str_alloc(void)
1025 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1030 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1034 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1035 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1039 ST_FUNC
void tok_str_free_str(int *str
)
1041 tal_free(tokstr_alloc
, str
);
1044 ST_FUNC
void tok_str_free(TokenString
*str
)
1046 tok_str_free_str(str
->str
);
1047 tal_free(tokstr_alloc
, str
);
1050 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1054 size
= s
->allocated_len
;
1057 while (size
< new_size
)
1059 if (size
> s
->allocated_len
) {
1060 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1061 s
->allocated_len
= size
;
1067 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1073 if (len
>= s
->allocated_len
)
1074 str
= tok_str_realloc(s
, len
+ 1);
1079 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1082 str
->prev
= macro_stack
;
1083 str
->prev_ptr
= macro_ptr
;
1084 str
->save_line_num
= file
->line_num
;
1085 macro_ptr
= str
->str
;
1089 ST_FUNC
void end_macro(void)
1091 TokenString
*str
= macro_stack
;
1092 macro_stack
= str
->prev
;
1093 macro_ptr
= str
->prev_ptr
;
1094 file
->line_num
= str
->save_line_num
;
1095 str
->len
= 0; /* matters if str not alloced, may be tokstr_buf */
1096 if (str
->alloc
!= 0) {
1097 if (str
->alloc
== 2)
1098 str
->str
= NULL
; /* don't free */
1103 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1107 len
= s
->lastlen
= s
->len
;
1110 /* allocate space for worst case */
1111 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1112 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1125 str
[len
++] = cv
->tab
[0];
1132 /* Insert the string into the int array. */
1134 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1135 if (len
+ nb_words
>= s
->allocated_len
)
1136 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1137 str
[len
] = cv
->str
.size
;
1138 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1149 str
[len
++] = cv
->tab
[0];
1150 str
[len
++] = cv
->tab
[1];
1153 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1154 str
[len
++] = cv
->tab
[0];
1155 str
[len
++] = cv
->tab
[1];
1156 #elif LDOUBLE_SIZE == 12
1157 str
[len
++] = cv
->tab
[0];
1158 str
[len
++] = cv
->tab
[1];
1159 str
[len
++] = cv
->tab
[2];
1160 #elif LDOUBLE_SIZE == 16
1161 str
[len
++] = cv
->tab
[0];
1162 str
[len
++] = cv
->tab
[1];
1163 str
[len
++] = cv
->tab
[2];
1164 str
[len
++] = cv
->tab
[3];
1166 #error add long double size support
1175 /* add the current parse token in token string 's' */
1176 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1180 /* save line number info */
1181 if (file
->line_num
!= s
->last_line_num
) {
1182 s
->last_line_num
= file
->line_num
;
1183 cval
.i
= s
->last_line_num
;
1184 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1186 tok_str_add2(s
, tok
, &tokc
);
1189 /* get a token from an integer array and increment pointer. */
1190 static inline void tok_get(int *t
, const int **pp
, CValue
*cv
)
1210 cv
->i
= (unsigned)*p
++;
1219 cv
->str
.size
= *p
++;
1221 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1233 #if LDOUBLE_SIZE == 8 || defined TCC_USING_DOUBLE_FOR_LDOUBLE
1235 #elif LDOUBLE_SIZE == 12
1237 #elif LDOUBLE_SIZE == 16
1240 # error add long double size support
1254 # define TOK_GET(t,p,c) tok_get(t,p,c)
1256 # define TOK_GET(t,p,c) do { \
1258 if (TOK_HAS_VALUE(_t)) \
1261 *(t) = _t, ++*(p); \
1265 static int macro_is_equal(const int *a
, const int *b
)
1274 cstr_reset(&tokcstr
);
1275 TOK_GET(&t
, &a
, &cv
);
1276 cstr_cat(&tokcstr
, get_tok_str(t
, &cv
), 0);
1277 TOK_GET(&t
, &b
, &cv
);
1278 if (strcmp(tokcstr
.data
, get_tok_str(t
, &cv
)))
1284 /* defines handling */
1285 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1290 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1292 s
->next
= first_arg
;
1293 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1295 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1296 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1299 /* undefined a define symbol. Its name is just set to zero */
1300 ST_FUNC
void define_undef(Sym
*s
)
1303 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1304 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1307 ST_INLN Sym
*define_find(int v
)
1310 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1312 return table_ident
[v
]->sym_define
;
1315 /* free define stack until top reaches 'b' */
1316 ST_FUNC
void free_defines(Sym
*b
)
1318 while (define_stack
!= b
) {
1319 Sym
*top
= define_stack
;
1320 define_stack
= top
->prev
;
1321 tok_str_free_str(top
->d
);
1327 /* fake the nth "#if defined test_..." for tcc -dt -run */
1328 static void maybe_run_test(TCCState
*s
)
1331 if (s
->include_stack_ptr
!= s
->include_stack
)
1333 p
= get_tok_str(tok
, NULL
);
1334 if (0 != memcmp(p
, "test_", 5))
1336 if (0 != --s
->run_test
)
1338 fprintf(s
->ppfp
, &"\n[%s]\n"[!(s
->dflag
& 32)], p
), fflush(s
->ppfp
);
1339 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1342 static CachedInclude
*
1343 search_cached_include(TCCState
*s1
, const char *filename
, int add
);
1345 static int parse_include(TCCState
*s1
, int do_next
, int test
)
1348 char name
[1024], buf
[1024], *p
;
1352 if (c
== '<' || c
== '\"') {
1353 cstr_reset(&tokcstr
);
1354 file
->buf_ptr
= parse_pp_string(file
->buf_ptr
, c
== '<' ? '>' : c
, &tokcstr
);
1356 pstrncpy(name
, tokcstr
.data
, i
>= sizeof name
? sizeof name
- 1 : i
);
1359 /* computed #include : concatenate tokens until result is one of
1360 the two accepted forms. Don't convert pp-tokens to tokens here. */
1361 parse_flags
= PARSE_FLAG_PREPROCESS
1362 | PARSE_FLAG_LINEFEED
1363 | (parse_flags
& PARSE_FLAG_ASM_FILE
);
1367 p
= name
, i
= strlen(p
) - 1;
1369 && ((p
[0] == '"' && p
[i
] == '"')
1370 || (p
[0] == '<' && p
[i
] == '>')))
1372 if (tok
== TOK_LINEFEED
)
1373 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1374 pstrcat(name
, sizeof name
, get_tok_str(tok
, &tokc
));
1377 /* remove '<>|""' */
1378 memmove(p
, p
+ 1, i
- 1), p
[i
- 1] = 0;
1381 i
= do_next
? file
->include_next_index
: -1;
1385 /* check absolute include path */
1386 if (!IS_ABSPATH(name
))
1389 } else if (i
== 1) {
1390 /* search in file's dir if "header.h" */
1393 p
= file
->true_filename
;
1394 pstrncpy(buf
, p
, tcc_basename(p
) - p
);
1396 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1398 p
= s1
->include_paths
[j
];
1399 else if (k
< s1
->nb_sysinclude_paths
)
1400 p
= s1
->sysinclude_paths
[k
];
1404 tcc_error("include file '%s' not found", name
);
1405 pstrcpy(buf
, sizeof buf
, p
);
1406 pstrcat(buf
, sizeof buf
, "/");
1408 pstrcat(buf
, sizeof buf
, name
);
1409 e
= search_cached_include(s1
, buf
, 0);
1410 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
== pp_once
)) {
1411 /* no need to parse the include because the 'ifndef macro'
1412 is defined (or had #pragma once) */
1414 printf("%s: skipping cached %s\n", file
->filename
, buf
);
1418 if (tcc_open(s1
, buf
) >= 0)
1425 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1426 tcc_error("#include recursion too deep");
1427 /* push previous file on stack */
1428 *s1
->include_stack_ptr
++ = file
->prev
;
1429 file
->include_next_index
= i
;
1431 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1433 /* update target deps */
1435 BufferedFile
*bf
= file
;
1436 while (i
== 1 && (bf
= bf
->prev
))
1437 i
= bf
->include_next_index
;
1438 /* skip system include files */
1439 if (s1
->include_sys_deps
|| i
- 2 < s1
->nb_include_paths
)
1440 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1443 /* add include file debug info */
1444 tcc_debug_bincl(s1
);
1445 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1450 /* eval an expression for #if/#elif */
1451 static int expr_preprocess(TCCState
*s1
)
1456 str
= tok_str_alloc();
1458 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1459 next(); /* do macro subst */
1461 if (tok
== TOK_DEFINED
) {
1466 if (tok
< TOK_IDENT
)
1467 expect("identifier");
1471 if (define_find(tok
)
1472 || tok
== TOK___HAS_INCLUDE
1473 || tok
== TOK___HAS_INCLUDE_NEXT
)
1482 } else if (tok
== TOK___HAS_INCLUDE
||
1483 tok
== TOK___HAS_INCLUDE_NEXT
) {
1488 c
= parse_include(s1
, t
- TOK___HAS_INCLUDE
, 1);
1493 } else if (tok
>= TOK_IDENT
) {
1494 /* if undefined macro, replace with zero, check for func-like */
1498 tok_str_add_tok(str
);
1501 tcc_error("function-like macro '%s' is not defined",
1502 get_tok_str(t
, NULL
));
1505 tok_str_add_tok(str
);
1508 tok_str_add(str
, -1); /* simulate end of file */
1509 tok_str_add(str
, 0);
1510 /* now evaluate C constant expression */
1511 begin_macro(str
, 1);
1519 /* parse after #define */
1520 ST_FUNC
void parse_define(void)
1522 Sym
*s
, *first
, **ps
;
1523 int v
, t
, varg
, is_vaargs
, spc
;
1524 int saved_parse_flags
= parse_flags
;
1527 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1528 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1529 /* XXX: should check if same macro (ANSI) */
1532 /* We have to parse the whole define as if not in asm mode, in particular
1533 no line comment with '#' must be ignored. Also for function
1534 macros the argument list must be parsed without '.' being an ID
1536 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1537 /* '(' must be just after macro definition for MACRO_FUNC */
1539 parse_flags
&= ~PARSE_FLAG_SPACES
;
1541 int dotid
= set_idnum('.', 0);
1544 if (tok
!= ')') for (;;) {
1548 if (varg
== TOK_DOTS
) {
1549 varg
= TOK___VA_ARGS__
;
1551 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1555 if (varg
< TOK_IDENT
)
1557 tcc_error("bad macro parameter list");
1558 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1563 if (tok
!= ',' || is_vaargs
)
1567 parse_flags
|= PARSE_FLAG_SPACES
;
1570 set_idnum('.', dotid
);
1575 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1576 /* The body of a macro definition should be parsed such that identifiers
1577 are parsed like the file mode determines (i.e. with '.' being an
1578 ID character in asm mode). But '#' should be retained instead of
1579 regarded as line comment leader, so still don't set ASM_FILE
1581 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1582 /* remove spaces around ## and after '#' */
1583 if (TOK_TWOSHARPS
== tok
) {
1590 } else if ('#' == tok
) {
1592 } else if (check_space(tok
, &spc
)) {
1595 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1600 parse_flags
= saved_parse_flags
;
1602 --tokstr_buf
.len
; /* remove trailing space */
1603 tok_str_add(&tokstr_buf
, 0);
1606 tcc_error("'##' cannot appear at either end of macro");
1607 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1611 static unsigned long long calc_file_hash(const char *filename
)
1613 unsigned long long hash
= 14695981039346656037ull; // FNV_offset_basis;
1614 FILE *fp
= fopen (filename
, "rb");
1619 unsigned char temp
[IO_BUF_SIZE
];
1620 int i
, n
= fread(temp
, 1, sizeof(temp
), fp
);
1624 for (i
= 0; i
< n
; i
++)
1625 hash
= hash
* 1099511628211ull + temp
[i
]; // FNV_prime
1634 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1641 unsigned long long hash
= 0;
1644 /* This is needed for #pragmae once
1645 * We cannot use stat on windows because st_ino is not set correctly
1646 * so we calculate a hash of file contents.
1647 * This also works for hard/soft links as in gcc/clang.
1649 memset (&st
, 0, sizeof(st
));
1650 if (stat (filename
, &st
))
1652 h
= st
.st_size
& (CACHED_INCLUDES_HASH_SIZE
- 1);
1654 /* Only calculate file hash if file size same. */
1655 i
= s1
->cached_includes_hash
[h
];
1659 e
= s1
->cached_includes
[i
- 1];
1660 if (e
->st
.st_size
== st
.st_size
) {
1662 e
->hash
= calc_file_hash(e
->filename
);
1663 hash
= calc_file_hash(filename
);
1670 i
= s1
->cached_includes_hash
[h
];
1674 e
= s1
->cached_includes
[i
- 1];
1676 if (e
->st
.st_size
== st
.st_size
&& e
->hash
== hash
)
1678 if (st
.st_dev
== e
->st
.st_dev
&& st
.st_ino
== e
->st
.st_ino
)
1687 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1692 strcpy(e
->filename
, filename
);
1693 e
->ifndef_macro
= e
->once
= 0;
1694 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1695 /* add in hash table */
1696 e
->hash_next
= s1
->cached_includes_hash
[h
];
1697 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1699 printf("adding cached '%s'\n", filename
);
1704 static void pragma_parse(TCCState
*s1
)
1707 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1711 if (next(), tok
!= '(')
1713 if (next(), tok
!= TOK_STR
)
1715 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1716 if (next(), tok
!= ')')
1718 if (t
== TOK_push_macro
) {
1719 while (NULL
== (s
= define_find(v
)))
1720 define_push(v
, 0, NULL
, NULL
);
1721 s
->type
.ref
= s
; /* set push boundary */
1723 for (s
= define_stack
; s
; s
= s
->prev
)
1724 if (s
->v
== v
&& s
->type
.ref
== s
) {
1730 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1732 tcc_warning("unbalanced #pragma pop_macro");
1733 pp_debug_tok
= t
, pp_debug_symv
= v
;
1735 } else if (tok
== TOK_once
) {
1736 search_cached_include(s1
, file
->filename
, 1)->once
= pp_once
;
1738 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1739 /* tcc -E: keep pragmas below unchanged */
1741 unget_tok(TOK_PRAGMA
);
1743 unget_tok(TOK_LINEFEED
);
1745 } else if (tok
== TOK_pack
) {
1747 #pragma pack(1) // set
1748 #pragma pack() // reset to default
1749 #pragma pack(push) // push current
1750 #pragma pack(push,1) // push & set
1751 #pragma pack(pop) // restore previous */
1754 if (tok
== TOK_ASM_pop
) {
1756 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1758 tcc_error("out of pack stack");
1760 s1
->pack_stack_ptr
--;
1764 if (tok
== TOK_ASM_push
) {
1766 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1768 val
= *s1
->pack_stack_ptr
++;
1773 if (tok
!= TOK_CINT
)
1776 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1781 *s1
->pack_stack_ptr
= val
;
1786 } else if (tok
== TOK_comment
) {
1795 p
= tcc_strdup((char *)tokc
.str
.data
);
1800 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1802 if (t
== TOK_option
)
1803 tcc_set_options(s1
, p
);
1808 tcc_warning_c(warn_unsupported
)("#pragma %s ignored", get_tok_str(tok
, &tokc
));
1812 tcc_error("malformed #pragma directive");
1816 /* is_bof is true if first non space token at beginning of file */
1817 ST_FUNC
void preprocess(int is_bof
)
1819 TCCState
*s1
= tcc_state
;
1820 int c
, n
, saved_parse_flags
;
1824 saved_parse_flags
= parse_flags
;
1825 parse_flags
= PARSE_FLAG_PREPROCESS
1826 | PARSE_FLAG_TOK_NUM
1827 | PARSE_FLAG_TOK_STR
1828 | PARSE_FLAG_LINEFEED
1829 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1838 pp_debug_symv
= tok
;
1844 pp_debug_symv
= tok
;
1845 s
= define_find(tok
);
1846 /* undefine symbol by putting an invalid name */
1851 case TOK_INCLUDE_NEXT
:
1852 parse_include(s1
, tok
- TOK_INCLUDE
, 0);
1858 c
= expr_preprocess(s1
);
1864 if (tok
< TOK_IDENT
)
1865 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1869 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1871 file
->ifndef_macro
= tok
;
1874 if (define_find(tok
)
1875 || tok
== TOK___HAS_INCLUDE
1876 || tok
== TOK___HAS_INCLUDE_NEXT
)
1879 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1880 tcc_error("memory full (ifdef)");
1881 *s1
->ifdef_stack_ptr
++ = c
;
1884 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1885 tcc_error("#else without matching #if");
1886 if (s1
->ifdef_stack_ptr
[-1] & 2)
1887 tcc_error("#else after #else");
1888 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1891 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1892 tcc_error("#elif without matching #if");
1893 c
= s1
->ifdef_stack_ptr
[-1];
1895 tcc_error("#elif after #else");
1896 /* 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;
1914 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1915 tcc_error("#endif without matching #if");
1916 s1
->ifdef_stack_ptr
--;
1917 /* '#ifndef macro' was at the start of file. Now we check if
1918 an '#endif' is exactly at the end of file */
1919 if (file
->ifndef_macro
&&
1920 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1921 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1922 /* need to set to zero to avoid false matches if another
1923 #ifndef at middle of file */
1924 file
->ifndef_macro
= 0;
1925 while (tok
!= TOK_LINEFEED
)
1927 tok_flags
|= TOK_FLAG_ENDIF
;
1932 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1936 if (tok
!= TOK_CINT
)
1938 tcc_error("wrong #line format");
1942 if (tok
!= TOK_LINEFEED
) {
1943 if (tok
== TOK_STR
) {
1944 if (file
->true_filename
== file
->filename
)
1945 file
->true_filename
= tcc_strdup(file
->filename
);
1946 q
= (char *)tokc
.str
.data
;
1948 if (!IS_ABSPATH(q
)) {
1949 /* prepend directory from real file */
1950 pstrcpy(buf
, sizeof buf
, file
->true_filename
);
1951 *tcc_basename(buf
) = 0;
1953 pstrcat(buf
, sizeof buf
, q
);
1954 tcc_debug_putfile(s1
, buf
);
1955 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1962 total_lines
+= file
->line_num
- n
;
1969 while (c
!= '\n' && c
!= CH_EOF
) {
1970 if ((q
- buf
) < sizeof(buf
) - 1)
1975 if (tok
== TOK_ERROR
)
1976 tcc_error("#error %s", buf
);
1978 tcc_warning("#warning %s", buf
);
1986 /* ignore gas line comment in an 'S' file. */
1987 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
1989 if (tok
== '!' && is_bof
)
1990 /* '!' is ignored at beginning to allow C scripts. */
1992 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1994 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
1997 /* ignore other preprocess commands or #! for C scripts */
1998 while (tok
!= TOK_LINEFEED
)
2001 parse_flags
= saved_parse_flags
;
2004 /* evaluate escape codes in a string. */
2005 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2020 case '0': case '1': case '2': case '3':
2021 case '4': case '5': case '6': case '7':
2022 /* at most three octal digits */
2027 n
= n
* 8 + c
- '0';
2031 n
= n
* 8 + c
- '0';
2036 goto add_char_nonext
;
2037 case 'x': i
= 0; goto parse_hex_or_ucn
;
2038 case 'u': i
= 4; goto parse_hex_or_ucn
;
2039 case 'U': i
= 8; goto parse_hex_or_ucn
;
2045 if (c
>= 'a' && c
<= 'f')
2047 else if (c
>= 'A' && c
<= 'F')
2052 expect("more hex digits in universal-character-name");
2054 goto add_hex_or_ucn
;
2061 goto add_char_nonext
;
2063 cstr_u8cat(outstr
, n
);
2088 goto invalid_escape
;
2098 if (c
>= '!' && c
<= '~')
2099 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2101 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2104 } else if (is_long
&& c
>= 0x80) {
2105 /* assume we are processing UTF-8 sequence */
2106 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2108 int cont
; /* count of continuation bytes */
2109 int skip
; /* how many bytes should skip when error occurred */
2112 /* decode leading byte */
2114 skip
= 1; goto invalid_utf8_sequence
;
2115 } else if (c
<= 0xDF) {
2116 cont
= 1; n
= c
& 0x1f;
2117 } else if (c
<= 0xEF) {
2118 cont
= 2; n
= c
& 0xf;
2119 } else if (c
<= 0xF4) {
2120 cont
= 3; n
= c
& 0x7;
2122 skip
= 1; goto invalid_utf8_sequence
;
2125 /* decode continuation bytes */
2126 for (i
= 1; i
<= cont
; i
++) {
2127 int l
= 0x80, h
= 0xBF;
2129 /* adjust limit for second byte */
2132 case 0xE0: l
= 0xA0; break;
2133 case 0xED: h
= 0x9F; break;
2134 case 0xF0: l
= 0x90; break;
2135 case 0xF4: h
= 0x8F; break;
2139 if (p
[i
] < l
|| p
[i
] > h
) {
2140 skip
= i
; goto invalid_utf8_sequence
;
2143 n
= (n
<< 6) | (p
[i
] & 0x3f);
2146 /* advance pointer */
2149 goto add_char_nonext
;
2151 /* error handling */
2152 invalid_utf8_sequence
:
2153 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c
);
2156 goto add_char_nonext
;
2162 cstr_ccat(outstr
, c
);
2164 #ifdef TCC_TARGET_PE
2165 /* store as UTF-16 */
2167 cstr_wccat(outstr
, c
);
2170 cstr_wccat(outstr
, (c
>> 10) + 0xD800);
2171 cstr_wccat(outstr
, (c
& 0x3FF) + 0xDC00);
2174 cstr_wccat(outstr
, c
);
2178 /* add a trailing '\0' */
2180 cstr_ccat(outstr
, '\0');
2182 cstr_wccat(outstr
, '\0');
2185 static void parse_string(const char *s
, int len
)
2187 uint8_t buf
[1000], *p
= buf
;
2190 if ((is_long
= *s
== 'L'))
2194 if (len
>= sizeof buf
)
2195 p
= tcc_malloc(len
+ 1);
2199 cstr_reset(&tokcstr
);
2200 parse_escape_string(&tokcstr
, p
, is_long
);
2205 int char_size
, i
, n
, c
;
2206 /* XXX: make it portable */
2208 tok
= TOK_CCHAR
, char_size
= 1;
2210 tok
= TOK_LCHAR
, char_size
= sizeof(nwchar_t
);
2211 n
= tokcstr
.size
/ char_size
- 1;
2213 tcc_error("empty character constant");
2215 tcc_warning_c(warn_all
)("multi-character character constant");
2216 for (c
= i
= 0; i
< n
; ++i
) {
2218 c
= ((nwchar_t
*)tokcstr
.data
)[i
];
2220 c
= (c
<< 8) | ((char *)tokcstr
.data
)[i
];
2224 tokc
.str
.size
= tokcstr
.size
;
2225 tokc
.str
.data
= tokcstr
.data
;
2233 /* we use 64 bit numbers */
2236 /* bn = (bn << shift) | or_val */
2237 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2241 for(i
=0;i
<BN_SIZE
;i
++) {
2243 bn
[i
] = (v
<< shift
) | or_val
;
2244 or_val
= v
>> (32 - shift
);
2248 static void bn_zero(unsigned int *bn
)
2251 for(i
=0;i
<BN_SIZE
;i
++) {
2256 /* parse number in null terminated string 'p' and return it in the
2258 static void parse_number(const char *p
)
2260 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2262 unsigned int bn
[BN_SIZE
];
2273 goto float_frac_parse
;
2274 } else if (t
== '0') {
2275 if (ch
== 'x' || ch
== 'X') {
2279 } else if (tcc_state
->tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2285 /* parse all digits. cannot check octal numbers at this stage
2286 because of floating point constants */
2288 if (ch
>= 'a' && ch
<= 'f')
2290 else if (ch
>= 'A' && ch
<= 'F')
2298 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2300 tcc_error("number too long");
2306 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2307 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2309 /* NOTE: strtox should support that for hexa numbers, but
2310 non ISOC99 libcs do not support it, so we prefer to do
2312 /* hexadecimal or binary floats */
2313 /* XXX: handle overflows */
2325 } else if (t
>= 'a') {
2327 } else if (t
>= 'A') {
2332 bn_lshift(bn
, shift
, t
);
2339 if (t
>= 'a' && t
<= 'f') {
2341 } else if (t
>= 'A' && t
<= 'F') {
2343 } else if (t
>= '0' && t
<= '9') {
2349 tcc_error("invalid digit");
2350 bn_lshift(bn
, shift
, t
);
2355 if (ch
!= 'p' && ch
!= 'P')
2362 } else if (ch
== '-') {
2366 if (ch
< '0' || ch
> '9')
2367 expect("exponent digits");
2368 while (ch
>= '0' && ch
<= '9') {
2369 exp_val
= exp_val
* 10 + ch
- '0';
2372 exp_val
= exp_val
* s
;
2374 /* now we can generate the number */
2375 /* XXX: should patch directly float number */
2376 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2377 d
= ldexp(d
, exp_val
- frac_bits
);
2382 /* float : should handle overflow */
2384 } else if (t
== 'L') {
2387 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2390 /* XXX: not large enough */
2391 tokc
.ld
= (long double)d
;
2398 /* decimal floats */
2400 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2405 while (ch
>= '0' && ch
<= '9') {
2406 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2412 if (ch
== 'e' || ch
== 'E') {
2413 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2417 if (ch
== '-' || ch
== '+') {
2418 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2423 if (ch
< '0' || ch
> '9')
2424 expect("exponent digits");
2425 while (ch
>= '0' && ch
<= '9') {
2426 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2438 tokc
.f
= strtof(token_buf
, NULL
);
2439 } else if (t
== 'L') {
2442 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2443 tokc
.d
= strtod(token_buf
, NULL
);
2445 tokc
.ld
= strtold(token_buf
, NULL
);
2449 tokc
.d
= strtod(token_buf
, NULL
);
2453 unsigned long long n
, n1
;
2454 int lcount
, ucount
, ov
= 0;
2457 /* integer number */
2460 if (b
== 10 && *q
== '0') {
2467 /* no need for checks except for base 10 / 8 errors */
2477 tcc_error("invalid digit");
2480 /* detect overflow */
2481 if (n1
>= 0x1000000000000000ULL
&& n
/ b
!= n1
)
2485 /* Determine the characteristics (unsigned and/or 64bit) the type of
2486 the constant must have according to the constant suffix(es) */
2487 lcount
= ucount
= 0;
2493 tcc_error("three 'l's in integer constant");
2494 if (lcount
&& *(p
- 1) != ch
)
2495 tcc_error("incorrect integer suffix: %s", p1
);
2498 } else if (t
== 'U') {
2500 tcc_error("two 'u's in integer constant");
2508 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2509 if (ucount
== 0 && b
== 10) {
2510 if (lcount
<= (LONG_SIZE
== 4)) {
2511 if (n
>= 0x80000000U
)
2512 lcount
= (LONG_SIZE
== 4) + 1;
2514 if (n
>= 0x8000000000000000ULL
)
2517 if (lcount
<= (LONG_SIZE
== 4)) {
2518 if (n
>= 0x100000000ULL
)
2519 lcount
= (LONG_SIZE
== 4) + 1;
2520 else if (n
>= 0x80000000U
)
2523 if (n
>= 0x8000000000000000ULL
)
2528 tcc_warning("integer constant overflow");
2537 ++tok
; /* TOK_CU... */
2541 tcc_error("invalid number");
2545 #define PARSE2(c1, tok1, c2, tok2) \
2556 /* return next token without macro substitution */
2557 static inline void next_nomacro1(void)
2559 int t
, c
, is_long
, len
;
2573 if (parse_flags
& PARSE_FLAG_SPACES
)
2574 goto keep_tok_flags
;
2575 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2584 /* first look if it is in fact an end of buffer */
2585 c
= handle_stray(&p
);
2589 TCCState
*s1
= tcc_state
;
2590 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2591 && !(tok_flags
& TOK_FLAG_EOF
)) {
2592 tok_flags
|= TOK_FLAG_EOF
;
2594 goto keep_tok_flags
;
2595 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2597 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2598 tcc_error("missing #endif");
2599 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2600 /* no include left : end of file. */
2603 tok_flags
&= ~TOK_FLAG_EOF
;
2604 /* pop include file */
2606 /* test if previous '#endif' was after a #ifdef at
2608 if (tok_flags
& TOK_FLAG_ENDIF
) {
2610 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2612 search_cached_include(s1
, file
->filename
, 1)
2613 ->ifndef_macro
= file
->ifndef_macro_saved
;
2614 tok_flags
&= ~TOK_FLAG_ENDIF
;
2617 /* add end of include file debug info */
2618 tcc_debug_eincl(tcc_state
);
2619 /* pop include stack */
2621 s1
->include_stack_ptr
--;
2623 if (p
== file
->buffer
)
2624 tok_flags
= TOK_FLAG_BOF
;
2625 tok_flags
|= TOK_FLAG_BOL
;
2635 tok_flags
|= TOK_FLAG_BOL
;
2638 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2641 goto keep_tok_flags
;
2646 if ((tok_flags
& TOK_FLAG_BOL
) &&
2647 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2649 preprocess(tok_flags
& TOK_FLAG_BOF
);
2655 tok
= TOK_TWOSHARPS
;
2657 #if !defined(TCC_TARGET_ARM)
2658 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2659 p
= parse_line_comment(p
- 1);
2670 /* dollar is allowed to start identifiers when not parsing asm */
2672 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2673 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2676 case 'a': case 'b': case 'c': case 'd':
2677 case 'e': case 'f': case 'g': case 'h':
2678 case 'i': case 'j': case 'k': case 'l':
2679 case 'm': case 'n': case 'o': case 'p':
2680 case 'q': case 'r': case 's': case 't':
2681 case 'u': case 'v': case 'w': case 'x':
2683 case 'A': case 'B': case 'C': case 'D':
2684 case 'E': case 'F': case 'G': case 'H':
2685 case 'I': case 'J': case 'K':
2686 case 'M': case 'N': case 'O': case 'P':
2687 case 'Q': case 'R': case 'S': case 'T':
2688 case 'U': case 'V': case 'W': case 'X':
2694 h
= TOK_HASH_FUNC(h
, c
);
2695 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2696 h
= TOK_HASH_FUNC(h
, c
);
2701 /* fast case : no stray found, so we have the full token
2702 and we have already hashed it */
2703 h
&= (TOK_HASH_SIZE
- 1);
2704 pts
= &hash_ident
[h
];
2709 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2711 pts
= &(ts
->hash_next
);
2713 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2717 cstr_reset(&tokcstr
);
2718 cstr_cat(&tokcstr
, (char *) p1
, len
);
2722 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2724 cstr_ccat(&tokcstr
, c
);
2727 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2733 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2735 goto parse_ident_fast
;
2738 if (c
== '\'' || c
== '\"') {
2742 cstr_reset(&tokcstr
);
2743 cstr_ccat(&tokcstr
, 'L');
2744 goto parse_ident_slow
;
2749 case '0': case '1': case '2': case '3':
2750 case '4': case '5': case '6': case '7':
2754 /* after the first digit, accept digits, alpha, '.' or sign if
2755 prefixed by 'eEpP' */
2757 cstr_reset(&tokcstr
);
2759 cstr_ccat(&tokcstr
, t
);
2760 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2762 || ((c
== '+' || c
== '-')
2763 && (((t
== 'e' || t
== 'E')
2764 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2765 /* 0xe+1 is 3 tokens in asm */
2766 && ((char*)tokcstr
.data
)[0] == '0'
2767 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2768 || t
== 'p' || t
== 'P'))))
2773 /* We add a trailing '\0' to ease parsing */
2774 cstr_ccat(&tokcstr
, '\0');
2775 tokc
.str
.size
= tokcstr
.size
;
2776 tokc
.str
.data
= tokcstr
.data
;
2781 /* special dot handling because it can also start a number */
2786 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2787 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2789 goto parse_ident_fast
;
2790 } else if (c
== '.') {
2796 *--p
= '.'; /* may underflow into file->unget[] */
2807 cstr_reset(&tokcstr
);
2809 cstr_ccat(&tokcstr
, 'L');
2810 cstr_ccat(&tokcstr
, c
);
2811 p
= parse_pp_string(p
, c
, &tokcstr
);
2812 cstr_ccat(&tokcstr
, c
);
2813 cstr_ccat(&tokcstr
, '\0');
2814 tokc
.str
.size
= tokcstr
.size
;
2815 tokc
.str
.data
= tokcstr
.data
;
2824 } else if (c
== '<') {
2841 } else if (c
== '>') {
2859 } else if (c
== '=') {
2872 } else if (c
== '=') {
2885 } else if (c
== '=') {
2898 } else if (c
== '=') {
2901 } else if (c
== '>') {
2909 PARSE2('!', '!', '=', TOK_NE
)
2910 PARSE2('=', '=', '=', TOK_EQ
)
2911 PARSE2('*', '*', '=', TOK_A_MUL
)
2912 PARSE2('%', '%', '=', TOK_A_MOD
)
2913 PARSE2('^', '^', '=', TOK_A_XOR
)
2915 /* comments or operator */
2919 p
= parse_comment(p
);
2920 /* comments replaced by a blank */
2923 } else if (c
== '/') {
2924 p
= parse_line_comment(p
);
2927 } else if (c
== '=') {
2947 case '@': /* only used in assembler */
2953 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
2954 goto parse_ident_fast
;
2955 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2957 tcc_error("unrecognized character \\x%02x", c
);
2963 #if defined(PARSE_DEBUG)
2964 printf("token = %d %s\n", tok
, get_tok_str(tok
, &tokc
));
2968 static void macro_subst(
2969 TokenString
*tok_str
,
2971 const int *macro_str
2974 /* substitute arguments in replacement lists in macro_str by the values in
2975 args (field d) and return allocated string */
2976 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2987 TOK_GET(&t
, ¯o_str
, &cval
);
2992 TOK_GET(&t
, ¯o_str
, &cval
);
2995 s
= sym_find2(args
, t
);
2997 cstr_reset(&tokcstr
);
2998 cstr_ccat(&tokcstr
, '\"');
3002 TOK_GET(&t
, &st
, &cval
);
3003 if (t
!= TOK_PLCHLDR
3005 && 0 == check_space(t
, &spc
)) {
3006 const char *s
= get_tok_str(t
, &cval
);
3008 if (t
== TOK_PPSTR
&& *s
!= '\'')
3009 add_char(&tokcstr
, *s
);
3011 cstr_ccat(&tokcstr
, *s
);
3016 tokcstr
.size
-= spc
;
3017 cstr_ccat(&tokcstr
, '\"');
3018 cstr_ccat(&tokcstr
, '\0');
3020 printf("\nstringize: <%s>\n", (char *)tokcstr
.data
);
3023 cval
.str
.size
= tokcstr
.size
;
3024 cval
.str
.data
= tokcstr
.data
;
3025 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
3028 expect("macro parameter after '#'");
3030 } else if (t
>= TOK_IDENT
) {
3031 s
= sym_find2(args
, t
);
3034 /* if '##' is present before or after, no arg substitution */
3035 if (*macro_str
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
3036 /* special case for var arg macros : ## eats the ','
3037 if empty VA_ARGS variable. */
3038 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
3040 /* suppress ',' '##' */
3043 /* suppress '##' and add variable */
3051 /* Expand arguments tokens and store them. In most
3052 cases we could also re-expand each argument if
3053 used multiple times, but not if the argument
3054 contains the __COUNTER__ macro. */
3056 sym_push2(&s
->next
, s
->v
, s
->type
.t
, 0);
3058 macro_subst(&str2
, nested_list
, st
);
3059 tok_str_add(&str2
, 0);
3060 s
->next
->d
= str2
.str
;
3065 /* expanded to empty string */
3066 tok_str_add(&str
, TOK_PLCHLDR
);
3069 TOK_GET(&t2
, &st
, &cval
);
3072 tok_str_add2(&str
, t2
, &cval
);
3075 tok_str_add(&str
, t
);
3078 tok_str_add2(&str
, t
, &cval
);
3082 tok_str_add(&str
, 0);
3086 static char const ab_month_name
[12][4] =
3088 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3089 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3092 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3096 cstr_reset(&tokcstr
);
3097 if (t1
!= TOK_PLCHLDR
)
3098 cstr_cat(&tokcstr
, get_tok_str(t1
, v1
), -1);
3100 if (t2
!= TOK_PLCHLDR
)
3101 cstr_cat(&tokcstr
, get_tok_str(t2
, v2
), -1);
3102 cstr_ccat(&tokcstr
, '\0');
3103 //printf("paste <%s>\n", (char*)tokcstr.data);
3105 tcc_open_bf(tcc_state
, ":paste:", tokcstr
.size
);
3106 memcpy(file
->buffer
, tokcstr
.data
, tokcstr
.size
);
3110 if (0 == *file
->buf_ptr
)
3114 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3115 " preprocessing token", n
, file
->buffer
, file
->buffer
+ n
);
3123 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3124 return the resulting string (which must be freed). */
3125 static inline int *macro_twosharps(const int *ptr0
)
3129 TokenString macro_str1
;
3130 int start_of_nosubsts
= -1;
3133 /* we search the first '##' */
3134 for (ptr
= ptr0
;;) {
3135 TOK_GET(&t
, &ptr
, &cval
);
3136 if (t
== TOK_PPJOIN
)
3142 tok_str_new(¯o_str1
);
3144 //tok_print(" $$$", ptr0);
3145 for (ptr
= ptr0
;;) {
3146 TOK_GET(&t
, &ptr
, &cval
);
3149 if (t
== TOK_PPJOIN
)
3151 while (*ptr
== TOK_PPJOIN
) {
3153 /* given 'a##b', remove nosubsts preceding 'a' */
3154 if (start_of_nosubsts
>= 0)
3155 macro_str1
.len
= start_of_nosubsts
;
3156 /* given 'a##b', remove nosubsts preceding 'b' */
3157 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3159 if (t1
&& t1
!= TOK_PPJOIN
) {
3160 TOK_GET(&t1
, &ptr
, &cv1
);
3161 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3162 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3163 t
= tok
, cval
= tokc
;
3165 tok_str_add2(¯o_str1
, t
, &cval
);
3171 if (t
== TOK_NOSUBST
) {
3172 if (start_of_nosubsts
< 0)
3173 start_of_nosubsts
= macro_str1
.len
;
3175 start_of_nosubsts
= -1;
3177 tok_str_add2(¯o_str1
, t
, &cval
);
3179 tok_str_add(¯o_str1
, 0);
3180 //tok_print(" ###", macro_str1.str);
3181 return macro_str1
.str
;
3184 /* peek or read [ws_str == NULL] next token from function macro call,
3185 walking up macro levels up to the file if necessary */
3186 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3194 p
= macro_ptr
, t
= *p
;
3196 while (is_space(t
) || TOK_LINEFEED
== t
|| TOK_PLCHLDR
== t
)
3197 tok_str_add(ws_str
, t
), t
= *++p
;
3201 /* also, end of scope for nested defined symbol */
3203 while (sa
&& sa
->v
== 0)
3210 uint8_t *p
= file
->buf_ptr
;
3211 int ch
= handle_bs(&p
);
3213 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3218 p
= parse_comment(p
) - 1;
3219 } else if (c
== '/') {
3220 p
= parse_line_comment(p
) - 1;
3229 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3230 tok_str_add(ws_str
, ch
);
3245 /* do macro substitution of current token with macro 's' and add
3246 result to (tok_str,tok_len). 'nested_list' is the list of all
3247 macros we got inside to avoid recursing. Return non zero if no
3248 substitution needs to be done */
3249 static int macro_subst_tok(
3250 TokenString
*tok_str
,
3254 Sym
*args
, *sa
, *sa1
;
3255 int parlevel
, t
, t1
, spc
;
3261 /* if symbol is a macro, prepare substitution */
3262 /* special macros */
3263 if (tok
== TOK___LINE__
|| tok
== TOK___COUNTER__
) {
3264 t
= tok
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3265 snprintf(buf
, sizeof(buf
), "%d", t
);
3269 } else if (tok
== TOK___FILE__
) {
3270 cstrval
= file
->filename
;
3272 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3277 tm
= localtime(&ti
);
3278 if (tok
== TOK___DATE__
) {
3279 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3280 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3282 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3283 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3289 cstr_reset(&tokcstr
);
3290 cstr_cat(&tokcstr
, cstrval
, 0);
3291 cval
.str
.size
= tokcstr
.size
;
3292 cval
.str
.data
= tokcstr
.data
;
3293 tok_str_add2(tok_str
, t1
, &cval
);
3295 int saved_parse_flags
= parse_flags
;
3296 int *joined_str
= NULL
;
3299 if (s
->type
.t
== MACRO_FUNC
) {
3300 /* whitespace between macro name and argument list */
3302 tok_str_new(&ws_str
);
3305 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3306 | PARSE_FLAG_ACCEPT_STRAYS
;
3308 /* get next token from argument stream */
3309 t
= next_argstream(nested_list
, &ws_str
);
3311 /* not a macro substitution after all, restore the
3312 * macro token plus all whitespace we've read.
3313 * whitespace is intentionally not merged to preserve
3315 parse_flags
= saved_parse_flags
;
3316 tok_str_add(tok_str
, tok
);
3317 if (parse_flags
& PARSE_FLAG_SPACES
) {
3319 for (i
= 0; i
< ws_str
.len
; i
++)
3320 tok_str_add(tok_str
, ws_str
.str
[i
]);
3322 if (ws_str
.len
&& ws_str
.str
[ws_str
.len
- 1] == '\n')
3323 tok_flags
|= TOK_FLAG_BOL
;
3324 tok_str_free_str(ws_str
.str
);
3327 tok_str_free_str(ws_str
.str
);
3330 next_nomacro(); /* eat '(' */
3331 } while (tok
== TOK_PLCHLDR
|| is_space(tok
));
3333 /* argument macro */
3336 /* NOTE: empty args are allowed, except if no args */
3339 next_argstream(nested_list
, NULL
);
3340 } while (tok
== TOK_PLCHLDR
|| is_space(tok
) ||
3341 TOK_LINEFEED
== tok
);
3343 /* handle '()' case */
3344 if (!args
&& !sa
&& tok
== ')')
3347 tcc_error("macro '%s' used with too many args",
3348 get_tok_str(s
->v
, 0));
3351 /* NOTE: non zero sa->t indicates VA_ARGS */
3352 while ((parlevel
> 0 ||
3354 (tok
!= ',' || sa
->type
.t
)))) {
3355 if (tok
== TOK_EOF
|| tok
== 0)
3359 else if (tok
== ')')
3361 if (tok
== TOK_LINEFEED
)
3363 if (!check_space(tok
, &spc
))
3364 tok_str_add2(&str
, tok
, &tokc
);
3365 next_argstream(nested_list
, NULL
);
3370 tok_str_add(&str
, -1);
3371 tok_str_add(&str
, 0);
3372 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3376 /* special case for gcc var args: add an empty
3377 var arg argument if it is omitted */
3378 if (sa
&& sa
->type
.t
&& gnu_ext
)
3386 tcc_error("macro '%s' used with too few args",
3387 get_tok_str(s
->v
, 0));
3390 /* now subst each arg */
3391 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3396 tok_str_free_str(sa
->d
);
3398 tok_str_free_str(sa
->next
->d
);
3404 parse_flags
= saved_parse_flags
;
3407 sym_push2(nested_list
, s
->v
, 0, 0);
3408 parse_flags
= saved_parse_flags
;
3409 joined_str
= macro_twosharps(mstr
);
3410 macro_subst(tok_str
, nested_list
, joined_str
? joined_str
: mstr
);
3412 /* pop nested defined symbol */
3414 *nested_list
= sa1
->prev
;
3417 tok_str_free_str(joined_str
);
3419 tok_str_free_str(mstr
);
3424 /* do macro substitution of macro_str and add result to
3425 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3426 inside to avoid recursing. */
3427 static void macro_subst(
3428 TokenString
*tok_str
,
3430 const int *macro_str
3434 int t
, spc
, nosubst
;
3440 TOK_GET(&t
, ¯o_str
, &cval
);
3444 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3449 /* if nested substitution, do nothing */
3450 if (sym_find2(*nested_list
, t
)) {
3451 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3452 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3457 TokenString
*str
= tok_str_alloc();
3458 str
->str
= (int*)macro_str
;
3459 begin_macro(str
, 2);
3462 macro_subst_tok(tok_str
, nested_list
, s
);
3464 if (macro_stack
!= str
) {
3465 /* already finished by reading function macro arguments */
3469 macro_str
= macro_ptr
;
3473 spc
= is_space(t
= tok_str
->str
[tok_str
->lastlen
]);
3476 if (!check_space(t
, &spc
))
3477 tok_str_add2(tok_str
, t
, &cval
);
3480 if (nosubst
> 1 && (spc
|| (++nosubst
== 3 && t
== '(')))
3484 if (t
== TOK_NOSUBST
)
3487 /* GCC supports 'defined' as result of a macro substitution */
3488 if (t
== TOK_DEFINED
&& pp_expr
)
3493 /* return next token without macro substitution. Can read input from
3495 static void next_nomacro(void)
3501 if (TOK_HAS_VALUE(t
)) {
3502 tok_get(&tok
, ¯o_ptr
, &tokc
);
3503 if (t
== TOK_LINENUM
) {
3504 file
->line_num
= tokc
.i
;
3509 if (t
< TOK_IDENT
) {
3510 if (!(parse_flags
& PARSE_FLAG_SPACES
)
3511 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
))
3521 /* return next token with macro substitution */
3522 ST_FUNC
void next(void)
3529 if (!TOK_HAS_VALUE(t
)) {
3530 if (t
== TOK_NOSUBST
|| t
== TOK_PLCHLDR
) {
3531 /* discard preprocessor markers */
3533 } else if (t
== 0) {
3534 /* end of macro or unget token string */
3537 } else if (t
== '\\') {
3538 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3539 tcc_error("stray '\\' in program");
3543 } else if (t
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3544 /* if reading from file, try to substitute macros */
3545 Sym
*s
= define_find(t
);
3547 Sym
*nested_list
= NULL
;
3549 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3550 tok_str_add(&tokstr_buf
, 0);
3551 begin_macro(&tokstr_buf
, 0);
3556 /* convert preprocessor tokens into C tokens */
3557 if (t
== TOK_PPNUM
) {
3558 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3559 parse_number((char *)tokc
.str
.data
);
3560 } else if (t
== TOK_PPSTR
) {
3561 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3562 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3566 /* push back current token and set current token to 'last_tok'. Only
3567 identifier case handled for labels. */
3568 ST_INLN
void unget_tok(int last_tok
)
3571 TokenString
*str
= tok_str_alloc();
3572 tok_str_add2(str
, tok
, &tokc
);
3573 tok_str_add(str
, 0);
3574 begin_macro(str
, 1);
3578 /* ------------------------------------------------------------------------- */
3579 /* init preprocessor */
3581 static const char * const target_os_defs
=
3582 #ifdef TCC_TARGET_PE
3588 # if defined TCC_TARGET_MACHO
3590 # elif TARGETOS_FreeBSD
3592 # elif TARGETOS_FreeBSD_kernel
3593 "__FreeBSD_kernel__\0"
3594 # elif TARGETOS_NetBSD
3596 # elif TARGETOS_OpenBSD
3601 # if TARGETOS_ANDROID
3610 static void putdef(CString
*cs
, const char *p
)
3612 cstr_printf(cs
, "#define %s%s\n", p
, &" 1"[!!strchr(p
, ' ')*2]);
3615 static void putdefs(CString
*cs
, const char *p
)
3618 putdef(cs
, p
), p
= strchr(p
, 0) + 1;
3621 static void tcc_predefs(TCCState
*s1
, CString
*cs
, int is_asm
)
3625 sscanf(TCC_VERSION
, "%d.%d.%d", &a
, &b
, &c
);
3626 cstr_printf(cs
, "#define __TINYC__ %d\n", a
*10000 + b
*100 + c
);
3628 putdefs(cs
, target_machine_defs
);
3629 putdefs(cs
, target_os_defs
);
3631 #ifdef TCC_TARGET_ARM
3632 if (s1
->float_abi
== ARM_HARD_FLOAT
)
3633 putdef(cs
, "__ARM_PCS_VFP");
3636 putdef(cs
, "__ASSEMBLER__");
3637 if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
)
3638 putdef(cs
, "__TCC_PP__");
3639 if (s1
->output_type
== TCC_OUTPUT_MEMORY
)
3640 putdef(cs
, "__TCC_RUN__");
3641 #ifdef CONFIG_TCC_BACKTRACE
3642 if (s1
->do_backtrace
)
3643 putdef(cs
, "__TCC_BACKTRACE__");
3645 #ifdef CONFIG_TCC_BCHECK
3646 if (s1
->do_bounds_check
)
3647 putdef(cs
, "__TCC_BCHECK__");
3649 if (s1
->char_is_unsigned
)
3650 putdef(cs
, "__CHAR_UNSIGNED__");
3651 if (s1
->optimize
> 0)
3652 putdef(cs
, "__OPTIMIZE__");
3653 if (s1
->option_pthread
)
3654 putdef(cs
, "_REENTRANT");
3655 if (s1
->leading_underscore
)
3656 putdef(cs
, "__leading_underscore");
3657 cstr_printf(cs
, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE
);
3658 cstr_printf(cs
, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE
);
3660 putdef(cs
, "__STDC__");
3661 cstr_printf(cs
, "#define __STDC_VERSION__ %dL\n", s1
->cversion
);
3663 /* load more predefs and __builtins */
3664 #if CONFIG_TCC_PREDEFS
3665 #include "tccdefs_.h" /* include as strings */
3667 "#include <tccdefs.h>\n" /* load at runtime */
3671 cstr_printf(cs
, "#define __BASE_FILE__ \"%s\"\n", file
->filename
);
3674 ST_FUNC
void preprocess_start(TCCState
*s1
, int filetype
)
3676 int is_asm
= !!(filetype
& (AFF_TYPE_ASM
|AFF_TYPE_ASMPP
));
3680 s1
->include_stack_ptr
= s1
->include_stack
;
3681 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3682 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3685 pp_debug_tok
= pp_debug_symv
= 0;
3687 s1
->pack_stack
[0] = 0;
3688 s1
->pack_stack_ptr
= s1
->pack_stack
;
3690 set_idnum('$', !is_asm
&& s1
->dollars_in_identifiers
? IS_ID
: 0);
3691 set_idnum('.', is_asm
? IS_ID
: 0);
3693 if (!(filetype
& AFF_TYPE_ASM
)) {
3696 tcc_predefs(s1
, &cstr
, is_asm
);
3697 if (s1
->cmdline_defs
.size
)
3698 cstr_cat(&cstr
, s1
->cmdline_defs
.data
, s1
->cmdline_defs
.size
);
3699 if (s1
->cmdline_incl
.size
)
3700 cstr_cat(&cstr
, s1
->cmdline_incl
.data
, s1
->cmdline_incl
.size
);
3701 //printf("%s\n", (char*)cstr.data);
3702 *s1
->include_stack_ptr
++ = file
;
3703 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3704 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3708 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3709 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3712 /* cleanup from error/setjmp */
3713 ST_FUNC
void preprocess_end(TCCState
*s1
)
3723 ST_FUNC
int set_idnum(int c
, int val
)
3725 int prev
= isidnum_table
[c
- CH_EOF
];
3726 isidnum_table
[c
- CH_EOF
] = val
;
3730 ST_FUNC
void tccpp_new(TCCState
*s
)
3735 /* init isid table */
3736 for(i
= CH_EOF
; i
<128; i
++)
3738 is_space(i
) ? IS_SPC
3743 for(i
= 128; i
<256; i
++)
3744 set_idnum(i
, IS_ID
);
3746 /* init allocators */
3747 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3748 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3750 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3751 memset(s
->cached_includes_hash
, 0, sizeof s
->cached_includes_hash
);
3754 cstr_new(&cstr_buf
);
3755 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3756 tok_str_new(&tokstr_buf
);
3757 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3759 tok_ident
= TOK_IDENT
;
3768 tok_alloc(p
, r
- p
- 1);
3772 /* we add dummy defines for some special macros to speed up tests
3773 and to have working defined() */
3774 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
3775 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
3776 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
3777 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
3778 define_push(TOK___COUNTER__
, MACRO_OBJ
, NULL
, NULL
);
3781 ST_FUNC
void tccpp_delete(TCCState
*s
)
3785 dynarray_reset(&s
->cached_includes
, &s
->nb_cached_includes
);
3788 n
= tok_ident
- TOK_IDENT
;
3789 if (n
> total_idents
)
3791 for(i
= 0; i
< n
; i
++)
3792 tal_free(toksym_alloc
, table_ident
[i
]);
3793 tcc_free(table_ident
);
3796 /* free static buffers */
3797 cstr_free(&tokcstr
);
3798 cstr_free(&cstr_buf
);
3799 tok_str_free_str(tokstr_buf
.str
);
3801 /* free allocators */
3802 tal_delete(toksym_alloc
);
3803 toksym_alloc
= NULL
;
3804 tal_delete(tokstr_alloc
);
3805 tokstr_alloc
= NULL
;
3808 /* ------------------------------------------------------------------------- */
3809 /* tcc -E [-P[1]] [-dD} support */
3811 static void tok_print(const char *msg
, const int *str
)
3817 fp
= tcc_state
->ppfp
;
3818 fprintf(fp
, "%s", msg
);
3820 TOK_GET(&t
, &str
, &cval
);
3823 fprintf(fp
, &" %s"[s
], get_tok_str(t
, &cval
)), s
= 1;
3828 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3830 int d
= f
->line_num
- f
->line_ref
;
3835 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3837 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3839 fputs("\n", s1
->ppfp
), --d
;
3840 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3841 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3843 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3844 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3846 f
->line_ref
= f
->line_num
;
3849 static void define_print(TCCState
*s1
, int v
)
3855 if (NULL
== s
|| NULL
== s
->d
)
3859 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3860 if (s
->type
.t
== MACRO_FUNC
) {
3865 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3872 tok_print("", s
->d
);
3875 static void pp_debug_defines(TCCState
*s1
)
3886 pp_line(s1
, file
, 0);
3887 file
->line_ref
= ++file
->line_num
;
3891 vs
= get_tok_str(v
, NULL
);
3892 if (t
== TOK_DEFINE
) {
3893 define_print(s1
, v
);
3894 } else if (t
== TOK_UNDEF
) {
3895 fprintf(fp
, "#undef %s\n", vs
);
3896 } else if (t
== TOK_push_macro
) {
3897 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3898 } else if (t
== TOK_pop_macro
) {
3899 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3904 static void pp_debug_builtins(TCCState
*s1
)
3907 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3908 define_print(s1
, v
);
3911 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3912 static int pp_need_space(int a
, int b
)
3914 return 'E' == a
? '+' == b
|| '-' == b
3915 : '+' == a
? TOK_INC
== b
|| '+' == b
3916 : '-' == a
? TOK_DEC
== b
|| '-' == b
3917 : a
>= TOK_IDENT
? b
>= TOK_IDENT
3918 : a
== TOK_PPNUM
? b
>= TOK_IDENT
3922 /* maybe hex like 0x1e */
3923 static int pp_check_he0xE(int t
, const char *p
)
3925 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3930 /* Preprocess the current file */
3931 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3933 BufferedFile
**iptr
;
3934 int token_seen
, spcs
, level
;
3938 parse_flags
= PARSE_FLAG_PREPROCESS
3939 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3940 | PARSE_FLAG_LINEFEED
3942 | PARSE_FLAG_ACCEPT_STRAYS
3944 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3945 capability to compile and run itself, provided all numbers are
3946 given as decimals. tcc -E -P10 will do. */
3947 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
3948 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
3951 /* for PP benchmarks */
3952 do next(); while (tok
!= TOK_EOF
);
3956 if (s1
->dflag
& 1) {
3957 pp_debug_builtins(s1
);
3961 token_seen
= TOK_LINEFEED
, spcs
= 0, level
= 0;
3963 pp_line(s1
, file
->prev
, level
++);
3964 pp_line(s1
, file
, level
);
3966 iptr
= s1
->include_stack_ptr
;
3971 level
= s1
->include_stack_ptr
- iptr
;
3974 pp_line(s1
, *iptr
, 0);
3975 pp_line(s1
, file
, level
);
3977 if (s1
->dflag
& 7) {
3978 pp_debug_defines(s1
);
3983 if (is_space(tok
)) {
3984 if (spcs
< sizeof white
- 1)
3985 white
[spcs
++] = tok
;
3987 } else if (tok
== TOK_LINEFEED
) {
3989 if (token_seen
== TOK_LINEFEED
)
3992 } else if (token_seen
== TOK_LINEFEED
) {
3993 pp_line(s1
, file
, 0);
3994 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
3995 white
[spcs
++] = ' ';
3998 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
3999 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
4000 token_seen
= pp_check_he0xE(tok
, p
);
4005 /* ------------------------------------------------------------------------- */