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 /********************************************************/
25 /* global variables */
27 ST_DATA
int tok_flags
;
28 ST_DATA
int parse_flags
;
30 ST_DATA
struct BufferedFile
*file
;
33 ST_DATA
const int *macro_ptr
;
34 ST_DATA CString tokcstr
; /* current parsed string, if any */
36 /* display benchmark infos */
37 ST_DATA
int tok_ident
;
38 ST_DATA TokenSym
**table_ident
;
40 /* ------------------------------------------------------------------------- */
42 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
43 static char token_buf
[STRING_MAX_SIZE
+ 1];
44 static CString cstr_buf
;
45 static CString macro_equal_buf
;
46 static TokenString tokstr_buf
;
47 static unsigned char isidnum_table
[256 - CH_EOF
];
48 static int pp_debug_tok
, pp_debug_symv
;
51 static int pp_counter
;
52 static void tok_print(const char *msg
, const int *str
);
54 static struct TinyAlloc
*toksym_alloc
;
55 static struct TinyAlloc
*tokstr_alloc
;
57 static TokenString
*macro_stack
;
59 static const char tcc_keywords
[] =
60 #define DEF(id, str) str "\0"
65 /* WARNING: the content of this string encodes token numbers */
66 static const unsigned char tok_two_chars
[] =
68 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
69 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
91 '#','#', TOK_TWOSHARPS
,
96 static void next_nomacro(void);
98 ST_FUNC
void skip(int c
)
101 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
105 ST_FUNC
void expect(const char *msg
)
107 tcc_error("%s expected", msg
);
110 /* ------------------------------------------------------------------------- */
111 /* Custom allocator for tiny objects */
116 #define tal_free(al, p) tcc_free(p)
117 #define tal_realloc(al, p, size) tcc_realloc(p, size)
118 #define tal_new(a,b,c)
119 #define tal_delete(a)
121 #if !defined(MEM_DEBUG)
122 #define tal_free(al, p) tal_free_impl(al, p)
123 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
124 #define TAL_DEBUG_PARAMS
127 //#define TAL_INFO 1 /* collect and dump allocators stats */
128 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
129 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
130 #define TAL_DEBUG_PARAMS , const char *file, int line
131 #define TAL_DEBUG_FILE_LEN 40
134 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
135 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
136 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
137 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
138 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
139 #define CSTR_TAL_LIMIT 1024
141 typedef struct TinyAlloc
{
147 struct TinyAlloc
*next
, *top
;
156 typedef struct tal_header_t
{
159 int line_num
; /* negative line_num used for double free check */
160 char file_name
[TAL_DEBUG_FILE_LEN
+ 1];
164 /* ------------------------------------------------------------------------- */
166 static TinyAlloc
*tal_new(TinyAlloc
**pal
, unsigned limit
, unsigned size
)
168 TinyAlloc
*al
= tcc_mallocz(sizeof(TinyAlloc
));
169 al
->p
= al
->buffer
= tcc_malloc(size
);
176 static void tal_delete(TinyAlloc
*al
)
184 fprintf(stderr
, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
185 al
->limit
, al
->size
/ 1024.0 / 1024.0, al
->nb_peak
, al
->nb_total
, al
->nb_missed
,
186 (al
->peak_p
- al
->buffer
) * 100.0 / al
->size
);
189 if (al
->nb_allocs
> 0) {
191 fprintf(stderr
, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
192 al
->nb_allocs
, al
->limit
);
195 tal_header_t
*header
= (tal_header_t
*)p
;
196 if (header
->line_num
> 0) {
197 fprintf(stderr
, "%s:%d: chunk of %d bytes leaked\n",
198 header
->file_name
, header
->line_num
, header
->size
);
200 p
+= header
->size
+ sizeof(tal_header_t
);
208 tcc_free(al
->buffer
);
214 static void tal_free_impl(TinyAlloc
*al
, void *p TAL_DEBUG_PARAMS
)
219 if (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
) {
221 tal_header_t
*header
= (((tal_header_t
*)p
) - 1);
222 if (header
->line_num
< 0) {
223 fprintf(stderr
, "%s:%d: TAL_DEBUG: double frees chunk from\n",
225 fprintf(stderr
, "%s:%d: %d bytes\n",
226 header
->file_name
, (int)-header
->line_num
, (int)header
->size
);
228 header
->line_num
= -header
->line_num
;
233 } else if (al
->next
) {
241 static void *tal_realloc_impl(TinyAlloc
**pal
, void *p
, unsigned size TAL_DEBUG_PARAMS
)
243 tal_header_t
*header
;
246 unsigned adj_size
= (size
+ 3) & -4;
247 TinyAlloc
*al
= *pal
;
250 is_own
= (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
);
251 if ((!p
|| is_own
) && size
<= al
->limit
) {
252 if (al
->p
- al
->buffer
+ adj_size
+ sizeof(tal_header_t
) < al
->size
) {
253 header
= (tal_header_t
*)al
->p
;
254 header
->size
= adj_size
;
256 { int ofs
= strlen(file
) - TAL_DEBUG_FILE_LEN
;
257 strncpy(header
->file_name
, file
+ (ofs
> 0 ? ofs
: 0), TAL_DEBUG_FILE_LEN
);
258 header
->file_name
[TAL_DEBUG_FILE_LEN
] = 0;
259 header
->line_num
= line
; }
261 ret
= al
->p
+ sizeof(tal_header_t
);
262 al
->p
+= adj_size
+ sizeof(tal_header_t
);
264 header
= (((tal_header_t
*)p
) - 1);
265 if (p
) memcpy(ret
, p
, header
->size
);
267 header
->line_num
= -header
->line_num
;
273 if (al
->nb_peak
< al
->nb_allocs
)
274 al
->nb_peak
= al
->nb_allocs
;
275 if (al
->peak_p
< al
->p
)
282 ret
= tal_realloc(*pal
, 0, size
);
283 header
= (((tal_header_t
*)p
) - 1);
284 if (p
) memcpy(ret
, p
, header
->size
);
286 header
->line_num
= -header
->line_num
;
293 TinyAlloc
*bottom
= al
, *next
= al
->top
? al
->top
: al
;
295 al
= tal_new(pal
, next
->limit
, next
->size
* 2);
303 ret
= tcc_malloc(size
);
304 header
= (((tal_header_t
*)p
) - 1);
305 if (p
) memcpy(ret
, p
, header
->size
);
307 header
->line_num
= -header
->line_num
;
309 } else if (al
->next
) {
313 ret
= tcc_realloc(p
, size
);
322 /* ------------------------------------------------------------------------- */
323 /* CString handling */
324 static void cstr_realloc(CString
*cstr
, int new_size
)
328 size
= cstr
->size_allocated
;
330 size
= 8; /* no need to allocate a too small first string */
331 while (size
< new_size
)
333 cstr
->data
= tcc_realloc(cstr
->data
, size
);
334 cstr
->size_allocated
= size
;
338 ST_INLN
void cstr_ccat(CString
*cstr
, int ch
)
341 size
= cstr
->size
+ 1;
342 if (size
> cstr
->size_allocated
)
343 cstr_realloc(cstr
, size
);
344 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
348 ST_INLN
char *unicode_to_utf8 (char *b
, uint32_t Uc
)
350 if (Uc
<0x80) *b
++=Uc
;
351 else if (Uc
<0x800) *b
++=192+Uc
/64, *b
++=128+Uc
%64;
352 else if (Uc
-0xd800u
<0x800) goto error
;
353 else if (Uc
<0x10000) *b
++=224+Uc
/4096, *b
++=128+Uc
/64%64, *b
++=128+Uc
%64;
354 else if (Uc
<0x110000) *b
++=240+Uc
/262144, *b
++=128+Uc
/4096%64, *b
++=128+Uc
/64%64, *b
++=128+Uc
%64;
355 else error
: tcc_error("0x%x is not a valid universal character", Uc
);
359 /* add a unicode character expanded into utf8 */
360 ST_INLN
void cstr_u8cat(CString
*cstr
, int ch
)
363 e
= unicode_to_utf8(buf
, (uint32_t)ch
);
364 cstr_cat(cstr
, buf
, e
- buf
);
367 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
, int len
)
371 len
= strlen(str
) + 1 + len
;
372 size
= cstr
->size
+ len
;
373 if (size
> cstr
->size_allocated
)
374 cstr_realloc(cstr
, size
);
375 memmove(((unsigned char *)cstr
->data
) + cstr
->size
, str
, len
);
379 /* add a wide char */
380 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
383 size
= cstr
->size
+ sizeof(nwchar_t
);
384 if (size
> cstr
->size_allocated
)
385 cstr_realloc(cstr
, size
);
386 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
390 ST_FUNC
void cstr_new(CString
*cstr
)
392 memset(cstr
, 0, sizeof(CString
));
395 /* free string and reset it to NULL */
396 ST_FUNC
void cstr_free(CString
*cstr
)
398 tcc_free(cstr
->data
);
402 /* reset string to empty */
403 ST_FUNC
void cstr_reset(CString
*cstr
)
408 ST_FUNC
int cstr_vprintf(CString
*cstr
, const char *fmt
, va_list ap
)
414 if (size
> cstr
->size_allocated
)
415 cstr_realloc(cstr
, size
);
416 size
= cstr
->size_allocated
- cstr
->size
;
418 len
= vsnprintf((char*)cstr
->data
+ cstr
->size
, size
, fmt
, v
);
420 if (len
> 0 && len
< size
)
428 ST_FUNC
int cstr_printf(CString
*cstr
, const char *fmt
, ...)
432 len
= cstr_vprintf(cstr
, fmt
, ap
);
438 static void add_char(CString
*cstr
, int c
)
440 if (c
== '\'' || c
== '\"' || c
== '\\') {
441 /* XXX: could be more precise if char or string */
442 cstr_ccat(cstr
, '\\');
444 if (c
>= 32 && c
<= 126) {
447 cstr_ccat(cstr
, '\\');
449 cstr_ccat(cstr
, 'n');
451 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
452 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
453 cstr_ccat(cstr
, '0' + (c
& 7));
458 /* ------------------------------------------------------------------------- */
459 /* allocate a new token */
460 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
462 TokenSym
*ts
, **ptable
;
465 if (tok_ident
>= SYM_FIRST_ANOM
)
466 tcc_error("memory full (symbols)");
468 /* expand token table if needed */
469 i
= tok_ident
- TOK_IDENT
;
470 if ((i
% TOK_ALLOC_INCR
) == 0) {
471 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
472 table_ident
= ptable
;
475 ts
= tal_realloc(toksym_alloc
, 0, sizeof(TokenSym
) + len
);
477 ts
->tok
= tok_ident
++;
478 ts
->sym_define
= NULL
;
479 ts
->sym_label
= NULL
;
480 ts
->sym_struct
= NULL
;
481 ts
->sym_identifier
= NULL
;
483 ts
->hash_next
= NULL
;
484 memcpy(ts
->str
, str
, len
);
490 #define TOK_HASH_INIT 1
491 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
494 /* find a token and add it if not found */
495 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
503 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
504 h
&= (TOK_HASH_SIZE
- 1);
506 pts
= &hash_ident
[h
];
511 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
513 pts
= &(ts
->hash_next
);
515 return tok_alloc_new(pts
, str
, len
);
518 ST_FUNC
int tok_alloc_const(const char *str
)
520 return tok_alloc(str
, strlen(str
))->tok
;
524 /* XXX: buffer overflow */
525 /* XXX: float tokens */
526 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
531 cstr_reset(&cstr_buf
);
541 /* XXX: not quite exact, but only useful for testing */
543 sprintf(p
, "%u", (unsigned)cv
->i
);
545 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
549 cstr_ccat(&cstr_buf
, 'L');
551 cstr_ccat(&cstr_buf
, '\'');
552 add_char(&cstr_buf
, cv
->i
);
553 cstr_ccat(&cstr_buf
, '\'');
554 cstr_ccat(&cstr_buf
, '\0');
558 return (char*)cv
->str
.data
;
560 cstr_ccat(&cstr_buf
, 'L');
562 cstr_ccat(&cstr_buf
, '\"');
564 len
= cv
->str
.size
- 1;
566 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
568 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
570 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
572 cstr_ccat(&cstr_buf
, '\"');
573 cstr_ccat(&cstr_buf
, '\0');
577 cstr_cat(&cstr_buf
, "<float>", 0);
580 cstr_cat(&cstr_buf
, "<double>", 0);
583 cstr_cat(&cstr_buf
, "<long double>", 0);
586 cstr_cat(&cstr_buf
, "<linenumber>", 0);
589 /* above tokens have value, the ones below don't */
597 return strcpy(p
, "...");
599 return strcpy(p
, "<<=");
601 return strcpy(p
, ">>=");
603 return strcpy(p
, "<eof>");
606 /* search in two bytes table */
607 const unsigned char *q
= tok_two_chars
;
613 return cstr_buf
.data
;
618 sprintf(cstr_buf
.data
, "<%02x>", v
);
619 return cstr_buf
.data
;
623 case 0: /* nameless anonymous symbol */
625 } else if (v
< tok_ident
) {
626 return table_ident
[v
- TOK_IDENT
]->str
;
627 } else if (v
>= SYM_FIRST_ANOM
) {
628 /* special name for anonymous symbol */
629 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
631 /* should never happen */
636 return cstr_buf
.data
;
639 /* return the current character, handling end of block if necessary
641 static int handle_eob(void)
643 BufferedFile
*bf
= file
;
646 /* only tries to read if really end of buffer */
647 if (bf
->buf_ptr
>= bf
->buf_end
) {
649 #if defined(PARSE_DEBUG)
654 len
= read(bf
->fd
, bf
->buffer
, len
);
661 bf
->buf_ptr
= bf
->buffer
;
662 bf
->buf_end
= bf
->buffer
+ len
;
663 *bf
->buf_end
= CH_EOB
;
665 if (bf
->buf_ptr
< bf
->buf_end
) {
666 return bf
->buf_ptr
[0];
668 bf
->buf_ptr
= bf
->buf_end
;
673 /* read next char from current input file and handle end of input buffer */
674 static inline void inp(void)
676 ch
= *(++(file
->buf_ptr
));
677 /* end of buffer/file handling */
682 /* handle '\[\r]\n' */
683 static int handle_stray_noerror(void)
690 } else if (ch
== '\r') {
704 static void handle_stray(void)
706 if (handle_stray_noerror())
707 tcc_error("stray '\\' in program");
710 /* skip the stray and handle the \\n case. Output an error if
711 incorrect char after the stray */
712 static int handle_stray1(uint8_t *p
)
717 if (p
>= file
->buf_end
) {
724 if (handle_stray_noerror()) {
725 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
726 tcc_error("stray '\\' in program");
727 *--file
->buf_ptr
= '\\';
734 /* handle just the EOB case, but not stray */
735 #define PEEKC_EOB(c, p)\
746 /* handle the complicated stray case */
752 c = handle_stray1(p);\
757 /* input with '\[\r]\n' handling. Note that this function cannot
758 handle other characters after '\', so you cannot call it inside
759 strings or comments */
760 static void minp(void)
767 /* single line C++ comments */
768 static uint8_t *parse_line_comment(uint8_t *p
)
776 if (c
== '\n' || c
== CH_EOF
) {
778 } else if (c
== '\\') {
787 } else if (c
== '\r') {
805 static uint8_t *parse_comment(uint8_t *p
)
814 if (c
== '\n' || c
== '*' || c
== '\\')
818 if (c
== '\n' || c
== '*' || c
== '\\')
822 /* now we can handle all the cases */
826 } else if (c
== '*') {
832 } else if (c
== '/') {
834 } else if (c
== '\\') {
839 tcc_error("unexpected end of file in comment");
841 /* skip '\[\r]\n', otherwise just skip the stray */
847 } else if (c
== '\r') {
864 /* stray, eob or eof */
869 tcc_error("unexpected end of file in comment");
870 } else if (c
== '\\') {
880 ST_FUNC
int set_idnum(int c
, int val
)
882 int prev
= isidnum_table
[c
- CH_EOF
];
883 isidnum_table
[c
- CH_EOF
] = val
;
889 static inline void skip_spaces(void)
891 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
895 static inline int check_space(int t
, int *spc
)
897 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
906 /* parse a string without interpreting escapes */
907 static uint8_t *parse_pp_string(uint8_t *p
,
908 int sep
, CString
*str
)
916 } else if (c
== '\\') {
922 /* XXX: indicate line number of start of string */
923 tcc_error("missing terminating %c character", sep
);
924 } else if (c
== '\\') {
925 /* escape : just skip \[\r]\n */
930 } else if (c
== '\r') {
933 expect("'\n' after '\r'");
936 } else if (c
== CH_EOF
) {
937 goto unterminated_string
;
940 cstr_ccat(str
, '\\');
946 } else if (c
== '\n') {
949 } else if (c
== '\r') {
953 cstr_ccat(str
, '\r');
969 /* skip block of text until #else, #elif or #endif. skip also pairs of
971 static void preprocess_skip(void)
973 int a
, start_of_line
, c
, in_warn_or_error
;
980 in_warn_or_error
= 0;
1001 } else if (c
== '\\') {
1002 ch
= file
->buf_ptr
[0];
1003 handle_stray_noerror();
1010 if (in_warn_or_error
)
1012 p
= parse_pp_string(p
, c
, NULL
);
1016 if (in_warn_or_error
)
1023 p
= parse_comment(p
);
1024 } else if (ch
== '/') {
1025 p
= parse_line_comment(p
);
1030 if (start_of_line
) {
1035 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
1037 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
1039 else if (tok
== TOK_ENDIF
)
1041 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
1042 in_warn_or_error
= 1;
1043 else if (tok
== TOK_LINEFEED
)
1045 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1046 p
= parse_line_comment(p
- 1);
1048 #if !defined(TCC_TARGET_ARM)
1049 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1050 p
= parse_line_comment(p
- 1);
1052 /* ARM assembly uses '#' for constants */
1067 /* return the number of additional 'ints' necessary to store the
1069 static inline int tok_size(const int *p
)
1084 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
1087 return 1 + LONG_SIZE
/ 4;
1093 return 1 + LDOUBLE_SIZE
/ 4;
1100 /* token string handling */
1101 ST_INLN
void tok_str_new(TokenString
*s
)
1104 s
->len
= s
->lastlen
= 0;
1105 s
->allocated_len
= 0;
1106 s
->last_line_num
= -1;
1109 ST_FUNC TokenString
*tok_str_alloc(void)
1111 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1116 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1120 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1121 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1125 ST_FUNC
void tok_str_free_str(int *str
)
1127 tal_free(tokstr_alloc
, str
);
1130 ST_FUNC
void tok_str_free(TokenString
*str
)
1132 tok_str_free_str(str
->str
);
1133 tal_free(tokstr_alloc
, str
);
1136 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1140 size
= s
->allocated_len
;
1143 while (size
< new_size
)
1145 if (size
> s
->allocated_len
) {
1146 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1147 s
->allocated_len
= size
;
1153 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1159 if (len
>= s
->allocated_len
)
1160 str
= tok_str_realloc(s
, len
+ 1);
1165 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1168 str
->prev
= macro_stack
;
1169 str
->prev_ptr
= macro_ptr
;
1170 str
->save_line_num
= file
->line_num
;
1171 macro_ptr
= str
->str
;
1175 ST_FUNC
void end_macro(void)
1177 TokenString
*str
= macro_stack
;
1178 macro_stack
= str
->prev
;
1179 macro_ptr
= str
->prev_ptr
;
1180 file
->line_num
= str
->save_line_num
;
1181 if (str
->alloc
!= 0) {
1182 if (str
->alloc
== 2)
1183 str
->str
= NULL
; /* don't free */
1188 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1192 len
= s
->lastlen
= s
->len
;
1195 /* allocate space for worst case */
1196 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1197 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1210 str
[len
++] = cv
->tab
[0];
1217 /* Insert the string into the int array. */
1219 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1220 if (len
+ nb_words
>= s
->allocated_len
)
1221 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1222 str
[len
] = cv
->str
.size
;
1223 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1234 #if LDOUBLE_SIZE == 8
1237 str
[len
++] = cv
->tab
[0];
1238 str
[len
++] = cv
->tab
[1];
1240 #if LDOUBLE_SIZE == 12
1242 str
[len
++] = cv
->tab
[0];
1243 str
[len
++] = cv
->tab
[1];
1244 str
[len
++] = cv
->tab
[2];
1245 #elif LDOUBLE_SIZE == 16
1247 str
[len
++] = cv
->tab
[0];
1248 str
[len
++] = cv
->tab
[1];
1249 str
[len
++] = cv
->tab
[2];
1250 str
[len
++] = cv
->tab
[3];
1251 #elif LDOUBLE_SIZE != 8
1252 #error add long double size support
1261 /* add the current parse token in token string 's' */
1262 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1266 /* save line number info */
1267 if (file
->line_num
!= s
->last_line_num
) {
1268 s
->last_line_num
= file
->line_num
;
1269 cval
.i
= s
->last_line_num
;
1270 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1272 tok_str_add2(s
, tok
, &tokc
);
1275 /* get a token from an integer array and increment pointer. */
1276 static inline void tok_get(int *t
, const int **pp
, CValue
*cv
)
1296 cv
->i
= (unsigned)*p
++;
1305 cv
->str
.size
= *p
++;
1307 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1319 #if LDOUBLE_SIZE == 16
1321 #elif LDOUBLE_SIZE == 12
1323 #elif LDOUBLE_SIZE == 8
1326 # error add long double size support
1340 # define TOK_GET(t,p,c) tok_get(t,p,c)
1342 # define TOK_GET(t,p,c) do { \
1344 if (TOK_HAS_VALUE(_t)) \
1347 *(t) = _t, ++*(p); \
1351 static int macro_is_equal(const int *a
, const int *b
)
1360 /* first time preallocate macro_equal_buf, next time only reset position to start */
1361 cstr_reset(¯o_equal_buf
);
1362 TOK_GET(&t
, &a
, &cv
);
1363 cstr_cat(¯o_equal_buf
, get_tok_str(t
, &cv
), 0);
1364 TOK_GET(&t
, &b
, &cv
);
1365 if (strcmp(macro_equal_buf
.data
, get_tok_str(t
, &cv
)))
1371 /* defines handling */
1372 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1377 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1379 s
->next
= first_arg
;
1380 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1382 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1383 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1386 /* undefined a define symbol. Its name is just set to zero */
1387 ST_FUNC
void define_undef(Sym
*s
)
1390 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1391 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1394 ST_INLN Sym
*define_find(int v
)
1397 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1399 return table_ident
[v
]->sym_define
;
1402 /* free define stack until top reaches 'b' */
1403 ST_FUNC
void free_defines(Sym
*b
)
1405 while (define_stack
!= b
) {
1406 Sym
*top
= define_stack
;
1407 define_stack
= top
->prev
;
1408 tok_str_free_str(top
->d
);
1415 ST_FUNC Sym
*label_find(int v
)
1418 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1420 return table_ident
[v
]->sym_label
;
1423 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1426 s
= sym_push2(ptop
, v
, 0, 0);
1428 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1429 if (ptop
== &global_label_stack
) {
1430 /* modify the top most local identifier, so that
1431 sym_identifier will point to 's' when popped */
1433 ps
= &(*ps
)->prev_tok
;
1440 /* pop labels until element last is reached. Look if any labels are
1441 undefined. Define symbols if '&&label' was used. */
1442 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
, int keep
)
1445 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1447 if (s
->r
== LABEL_DECLARED
) {
1448 tcc_warning_c(warn_all
)("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1449 } else if (s
->r
== LABEL_FORWARD
) {
1450 tcc_error("label '%s' used but not defined",
1451 get_tok_str(s
->v
, NULL
));
1454 /* define corresponding symbol. A size of
1456 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1460 if (s
->r
!= LABEL_GONE
)
1461 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1471 /* fake the nth "#if defined test_..." for tcc -dt -run */
1472 static void maybe_run_test(TCCState
*s
)
1475 if (s
->include_stack_ptr
!= s
->include_stack
)
1477 p
= get_tok_str(tok
, NULL
);
1478 if (0 != memcmp(p
, "test_", 5))
1480 if (0 != --s
->run_test
)
1482 fprintf(s
->ppfp
, &"\n[%s]\n"[!(s
->dflag
& 32)], p
), fflush(s
->ppfp
);
1483 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1486 /* eval an expression for #if/#elif */
1487 static int expr_preprocess(void)
1492 str
= tok_str_alloc();
1494 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1495 next(); /* do macro subst */
1497 if (tok
== TOK_DEFINED
) {
1502 if (tok
< TOK_IDENT
)
1503 expect("identifier");
1504 if (tcc_state
->run_test
)
1505 maybe_run_test(tcc_state
);
1506 c
= define_find(tok
) != 0;
1514 } else if (1 && tok
== TOK___HAS_INCLUDE
) {
1515 next(); /* XXX check if correct to use expansion */
1517 while (tok
!= ')' && tok
!= TOK_EOF
)
1523 } else if (tok
>= TOK_IDENT
) {
1524 /* if undefined macro, replace with zero, check for func-like */
1528 tok_str_add_tok(str
);
1531 tcc_error("function-like macro '%s' is not defined",
1532 get_tok_str(t
, NULL
));
1535 tok_str_add_tok(str
);
1538 tok_str_add(str
, -1); /* simulate end of file */
1539 tok_str_add(str
, 0);
1540 /* now evaluate C constant expression */
1541 begin_macro(str
, 1);
1549 /* parse after #define */
1550 ST_FUNC
void parse_define(void)
1552 Sym
*s
, *first
, **ps
;
1553 int v
, t
, varg
, is_vaargs
, spc
;
1554 int saved_parse_flags
= parse_flags
;
1557 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1558 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1559 /* XXX: should check if same macro (ANSI) */
1562 /* We have to parse the whole define as if not in asm mode, in particular
1563 no line comment with '#' must be ignored. Also for function
1564 macros the argument list must be parsed without '.' being an ID
1566 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1567 /* '(' must be just after macro definition for MACRO_FUNC */
1569 parse_flags
&= ~PARSE_FLAG_SPACES
;
1571 int dotid
= set_idnum('.', 0);
1574 if (tok
!= ')') for (;;) {
1578 if (varg
== TOK_DOTS
) {
1579 varg
= TOK___VA_ARGS__
;
1581 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1585 if (varg
< TOK_IDENT
)
1587 tcc_error("bad macro parameter list");
1588 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1593 if (tok
!= ',' || is_vaargs
)
1597 parse_flags
|= PARSE_FLAG_SPACES
;
1600 set_idnum('.', dotid
);
1605 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1606 /* The body of a macro definition should be parsed such that identifiers
1607 are parsed like the file mode determines (i.e. with '.' being an
1608 ID character in asm mode). But '#' should be retained instead of
1609 regarded as line comment leader, so still don't set ASM_FILE
1611 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1612 /* remove spaces around ## and after '#' */
1613 if (TOK_TWOSHARPS
== tok
) {
1620 } else if ('#' == tok
) {
1622 } else if (check_space(tok
, &spc
)) {
1625 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1630 parse_flags
= saved_parse_flags
;
1632 --tokstr_buf
.len
; /* remove trailing space */
1633 tok_str_add(&tokstr_buf
, 0);
1636 tcc_error("'##' cannot appear at either end of macro");
1637 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1640 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1642 const unsigned char *s
;
1648 s
= (unsigned char *) filename
;
1651 h
= TOK_HASH_FUNC(h
, toup(*s
));
1653 h
= TOK_HASH_FUNC(h
, *s
);
1657 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1659 i
= s1
->cached_includes_hash
[h
];
1663 e
= s1
->cached_includes
[i
- 1];
1664 if (0 == PATHCMP(e
->filename
, filename
))
1671 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1672 strcpy(e
->filename
, filename
);
1673 e
->ifndef_macro
= e
->once
= 0;
1674 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1675 /* add in hash table */
1676 e
->hash_next
= s1
->cached_includes_hash
[h
];
1677 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1679 printf("adding cached '%s'\n", filename
);
1684 static void pragma_parse(TCCState
*s1
)
1687 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1691 if (next(), tok
!= '(')
1693 if (next(), tok
!= TOK_STR
)
1695 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1696 if (next(), tok
!= ')')
1698 if (t
== TOK_push_macro
) {
1699 while (NULL
== (s
= define_find(v
)))
1700 define_push(v
, 0, NULL
, NULL
);
1701 s
->type
.ref
= s
; /* set push boundary */
1703 for (s
= define_stack
; s
; s
= s
->prev
)
1704 if (s
->v
== v
&& s
->type
.ref
== s
) {
1710 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1712 tcc_warning("unbalanced #pragma pop_macro");
1713 pp_debug_tok
= t
, pp_debug_symv
= v
;
1715 } else if (tok
== TOK_once
) {
1716 search_cached_include(s1
, file
->filename
, 1)->once
= pp_once
;
1718 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1719 /* tcc -E: keep pragmas below unchanged */
1721 unget_tok(TOK_PRAGMA
);
1723 unget_tok(TOK_LINEFEED
);
1725 } else if (tok
== TOK_pack
) {
1727 #pragma pack(1) // set
1728 #pragma pack() // reset to default
1729 #pragma pack(push) // push current
1730 #pragma pack(push,1) // push & set
1731 #pragma pack(pop) // restore previous */
1734 if (tok
== TOK_ASM_pop
) {
1736 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1738 tcc_error("out of pack stack");
1740 s1
->pack_stack_ptr
--;
1744 if (tok
== TOK_ASM_push
) {
1746 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1748 val
= *s1
->pack_stack_ptr
++;
1753 if (tok
!= TOK_CINT
)
1756 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1761 *s1
->pack_stack_ptr
= val
;
1766 } else if (tok
== TOK_comment
) {
1775 p
= tcc_strdup((char *)tokc
.str
.data
);
1780 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1782 if (t
== TOK_option
)
1783 tcc_set_options(s1
, p
);
1788 tcc_warning_c(warn_unsupported
)("#pragma %s ignored", get_tok_str(tok
, &tokc
));
1792 tcc_error("malformed #pragma directive");
1796 /* is_bof is true if first non space token at beginning of file */
1797 ST_FUNC
void preprocess(int is_bof
)
1799 TCCState
*s1
= tcc_state
;
1800 int i
, c
, n
, saved_parse_flags
;
1804 saved_parse_flags
= parse_flags
;
1805 parse_flags
= PARSE_FLAG_PREPROCESS
1806 | PARSE_FLAG_TOK_NUM
1807 | PARSE_FLAG_TOK_STR
1808 | PARSE_FLAG_LINEFEED
1809 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1818 pp_debug_symv
= tok
;
1824 pp_debug_symv
= tok
;
1825 s
= define_find(tok
);
1826 /* undefine symbol by putting an invalid name */
1831 case TOK_INCLUDE_NEXT
:
1832 ch
= file
->buf_ptr
[0];
1833 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1838 } else if (ch
== '\"') {
1843 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1844 if ((q
- buf
) < sizeof(buf
) - 1)
1847 if (handle_stray_noerror() == 0)
1855 /* eat all spaces and comments after include */
1856 /* XXX: slightly incorrect */
1857 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1862 /* computed #include : concatenate everything up to linefeed,
1863 the result must be one of the two accepted forms.
1864 Don't convert pp-tokens to tokens here. */
1865 parse_flags
= (PARSE_FLAG_PREPROCESS
1866 | PARSE_FLAG_LINEFEED
1867 | (parse_flags
& PARSE_FLAG_ASM_FILE
));
1870 while (tok
!= TOK_LINEFEED
) {
1871 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1875 /* check syntax and remove '<>|""' */
1876 if ((len
< 2 || ((buf
[0] != '"' || buf
[len
-1] != '"') &&
1877 (buf
[0] != '<' || buf
[len
-1] != '>'))))
1878 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1880 memmove(buf
, buf
+ 1, len
- 2);
1881 buf
[len
- 2] = '\0';
1884 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1885 tcc_error("#include recursion too deep");
1886 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
+ 1 : 0;
1887 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1888 for (; i
< n
; ++i
) {
1889 char buf1
[sizeof file
->filename
];
1894 /* check absolute include path */
1895 if (!IS_ABSPATH(buf
))
1899 } else if (i
== 1) {
1900 /* search in file's dir if "header.h" */
1903 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1904 path
= file
->true_filename
;
1905 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1908 /* search in all the include paths */
1909 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1910 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1911 pstrcpy(buf1
, sizeof(buf1
), path
);
1912 pstrcat(buf1
, sizeof(buf1
), "/");
1915 pstrcat(buf1
, sizeof(buf1
), buf
);
1916 e
= search_cached_include(s1
, buf1
, 0);
1917 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
== pp_once
)) {
1918 /* no need to parse the include because the 'ifndef macro'
1919 is defined (or had #pragma once) */
1921 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1926 if (tcc_open(s1
, buf1
) < 0)
1928 /* push previous file on stack */
1929 *s1
->include_stack_ptr
++ = file
->prev
;
1930 file
->include_next_index
= i
;
1932 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1934 /* update target deps */
1936 BufferedFile
*bf
= file
;
1937 while (i
== 1 && (bf
= bf
->prev
))
1938 i
= bf
->include_next_index
;
1939 /* skip system include files */
1940 if (s1
->include_sys_deps
|| n
- i
> s1
->nb_sysinclude_paths
)
1941 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1944 /* add include file debug info */
1945 tcc_debug_bincl(tcc_state
);
1946 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1947 ch
= file
->buf_ptr
[0];
1950 tcc_error("include file '%s' not found", buf
);
1957 c
= expr_preprocess();
1963 if (tok
< TOK_IDENT
)
1964 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1968 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1970 file
->ifndef_macro
= tok
;
1973 c
= (define_find(tok
) != 0) ^ c
;
1975 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1976 tcc_error("memory full (ifdef)");
1977 *s1
->ifdef_stack_ptr
++ = c
;
1980 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1981 tcc_error("#else without matching #if");
1982 if (s1
->ifdef_stack_ptr
[-1] & 2)
1983 tcc_error("#else after #else");
1984 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1987 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1988 tcc_error("#elif without matching #if");
1989 c
= s1
->ifdef_stack_ptr
[-1];
1991 tcc_error("#elif after #else");
1992 /* last #if/#elif expression was true: we skip */
1996 c
= expr_preprocess();
1997 s1
->ifdef_stack_ptr
[-1] = c
;
2000 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
2001 file
->ifndef_macro
= 0;
2010 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2011 tcc_error("#endif without matching #if");
2012 s1
->ifdef_stack_ptr
--;
2013 /* '#ifndef macro' was at the start of file. Now we check if
2014 an '#endif' is exactly at the end of file */
2015 if (file
->ifndef_macro
&&
2016 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2017 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2018 /* need to set to zero to avoid false matches if another
2019 #ifndef at middle of file */
2020 file
->ifndef_macro
= 0;
2021 while (tok
!= TOK_LINEFEED
)
2023 tok_flags
|= TOK_FLAG_ENDIF
;
2028 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
2032 if (tok
!= TOK_CINT
)
2034 tcc_error("wrong #line format");
2038 if (tok
!= TOK_LINEFEED
) {
2039 if (tok
== TOK_STR
) {
2040 if (file
->true_filename
== file
->filename
)
2041 file
->true_filename
= tcc_strdup(file
->filename
);
2042 q
= (char *)tokc
.str
.data
;
2044 if (!IS_ABSPATH(q
)) {
2045 /* prepend directory from real file */
2046 pstrcpy(buf
, sizeof buf
, file
->true_filename
);
2047 *tcc_basename(buf
) = 0;
2049 pstrcat(buf
, sizeof buf
, q
);
2050 tcc_debug_putfile(s1
, buf
);
2051 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2058 total_lines
+= file
->line_num
- n
;
2064 ch
= file
->buf_ptr
[0];
2067 while (ch
!= '\n' && ch
!= CH_EOF
) {
2068 if ((q
- buf
) < sizeof(buf
) - 1)
2071 if (handle_stray_noerror() == 0)
2078 tcc_error("#error %s", buf
);
2080 tcc_warning("#warning %s", buf
);
2088 /* ignore gas line comment in an 'S' file. */
2089 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
2091 if (tok
== '!' && is_bof
)
2092 /* '!' is ignored at beginning to allow C scripts. */
2094 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2096 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
2099 /* ignore other preprocess commands or #! for C scripts */
2100 while (tok
!= TOK_LINEFEED
)
2103 parse_flags
= saved_parse_flags
;
2106 /* evaluate escape codes in a string. */
2107 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2122 case '0': case '1': case '2': case '3':
2123 case '4': case '5': case '6': case '7':
2124 /* at most three octal digits */
2129 n
= n
* 8 + c
- '0';
2133 n
= n
* 8 + c
- '0';
2138 goto add_char_nonext
;
2139 case 'x': i
= 0; goto parse_hex_or_ucn
;
2140 case 'u': i
= 4; goto parse_hex_or_ucn
;
2141 case 'U': i
= 8; goto parse_hex_or_ucn
;
2147 if (c
>= 'a' && c
<= 'f')
2149 else if (c
>= 'A' && c
<= 'F')
2154 expect("more hex digits in universal-character-name");
2157 goto add_char_nonext
;
2162 cstr_u8cat(outstr
, n
);
2187 goto invalid_escape
;
2197 if (c
>= '!' && c
<= '~')
2198 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2200 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2203 } else if (is_long
&& c
>= 0x80) {
2204 /* assume we are processing UTF-8 sequence */
2205 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2207 int cont
; /* count of continuation bytes */
2208 int skip
; /* how many bytes should skip when error occurred */
2211 /* decode leading byte */
2213 skip
= 1; goto invalid_utf8_sequence
;
2214 } else if (c
<= 0xDF) {
2215 cont
= 1; n
= c
& 0x1f;
2216 } else if (c
<= 0xEF) {
2217 cont
= 2; n
= c
& 0xf;
2218 } else if (c
<= 0xF4) {
2219 cont
= 3; n
= c
& 0x7;
2221 skip
= 1; goto invalid_utf8_sequence
;
2224 /* decode continuation bytes */
2225 for (i
= 1; i
<= cont
; i
++) {
2226 int l
= 0x80, h
= 0xBF;
2228 /* adjust limit for second byte */
2231 case 0xE0: l
= 0xA0; break;
2232 case 0xED: h
= 0x9F; break;
2233 case 0xF0: l
= 0x90; break;
2234 case 0xF4: h
= 0x8F; break;
2238 if (p
[i
] < l
|| p
[i
] > h
) {
2239 skip
= i
; goto invalid_utf8_sequence
;
2242 n
= (n
<< 6) | (p
[i
] & 0x3f);
2245 /* advance pointer */
2248 goto add_char_nonext
;
2250 /* error handling */
2251 invalid_utf8_sequence
:
2252 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c
);
2255 goto add_char_nonext
;
2261 cstr_ccat(outstr
, c
);
2263 #ifdef TCC_TARGET_PE
2264 /* store as UTF-16 */
2266 cstr_wccat(outstr
, c
);
2269 cstr_wccat(outstr
, (c
>> 10) + 0xD800);
2270 cstr_wccat(outstr
, (c
& 0x3FF) + 0xDC00);
2273 cstr_wccat(outstr
, c
);
2277 /* add a trailing '\0' */
2279 cstr_ccat(outstr
, '\0');
2281 cstr_wccat(outstr
, '\0');
2284 static void parse_string(const char *s
, int len
)
2286 uint8_t buf
[1000], *p
= buf
;
2289 if ((is_long
= *s
== 'L'))
2293 if (len
>= sizeof buf
)
2294 p
= tcc_malloc(len
+ 1);
2298 cstr_reset(&tokcstr
);
2299 parse_escape_string(&tokcstr
, p
, is_long
);
2304 int char_size
, i
, n
, c
;
2305 /* XXX: make it portable */
2307 tok
= TOK_CCHAR
, char_size
= 1;
2309 tok
= TOK_LCHAR
, char_size
= sizeof(nwchar_t
);
2310 n
= tokcstr
.size
/ char_size
- 1;
2312 tcc_error("empty character constant");
2314 tcc_warning_c(warn_all
)("multi-character character constant");
2315 for (c
= i
= 0; i
< n
; ++i
) {
2317 c
= ((nwchar_t
*)tokcstr
.data
)[i
];
2319 c
= (c
<< 8) | ((char *)tokcstr
.data
)[i
];
2323 tokc
.str
.size
= tokcstr
.size
;
2324 tokc
.str
.data
= tokcstr
.data
;
2332 /* we use 64 bit numbers */
2335 /* bn = (bn << shift) | or_val */
2336 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2340 for(i
=0;i
<BN_SIZE
;i
++) {
2342 bn
[i
] = (v
<< shift
) | or_val
;
2343 or_val
= v
>> (32 - shift
);
2347 static void bn_zero(unsigned int *bn
)
2350 for(i
=0;i
<BN_SIZE
;i
++) {
2355 /* parse number in null terminated string 'p' and return it in the
2357 static void parse_number(const char *p
)
2359 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2361 unsigned int bn
[BN_SIZE
];
2372 goto float_frac_parse
;
2373 } else if (t
== '0') {
2374 if (ch
== 'x' || ch
== 'X') {
2378 } else if (tcc_state
->tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2384 /* parse all digits. cannot check octal numbers at this stage
2385 because of floating point constants */
2387 if (ch
>= 'a' && ch
<= 'f')
2389 else if (ch
>= 'A' && ch
<= 'F')
2397 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2399 tcc_error("number too long");
2405 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2406 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2408 /* NOTE: strtox should support that for hexa numbers, but
2409 non ISOC99 libcs do not support it, so we prefer to do
2411 /* hexadecimal or binary floats */
2412 /* XXX: handle overflows */
2424 } else if (t
>= 'a') {
2426 } else if (t
>= 'A') {
2431 bn_lshift(bn
, shift
, t
);
2438 if (t
>= 'a' && t
<= 'f') {
2440 } else if (t
>= 'A' && t
<= 'F') {
2442 } else if (t
>= '0' && t
<= '9') {
2448 tcc_error("invalid digit");
2449 bn_lshift(bn
, shift
, t
);
2454 if (ch
!= 'p' && ch
!= 'P')
2461 } else if (ch
== '-') {
2465 if (ch
< '0' || ch
> '9')
2466 expect("exponent digits");
2467 while (ch
>= '0' && ch
<= '9') {
2468 exp_val
= exp_val
* 10 + ch
- '0';
2471 exp_val
= exp_val
* s
;
2473 /* now we can generate the number */
2474 /* XXX: should patch directly float number */
2475 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2476 d
= ldexp(d
, exp_val
- frac_bits
);
2481 /* float : should handle overflow */
2483 } else if (t
== 'L') {
2485 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2490 /* XXX: not large enough */
2491 tokc
.ld
= (long double)d
;
2498 /* decimal floats */
2500 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2505 while (ch
>= '0' && ch
<= '9') {
2506 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2512 if (ch
== 'e' || ch
== 'E') {
2513 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2517 if (ch
== '-' || ch
== '+') {
2518 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2523 if (ch
< '0' || ch
> '9')
2524 expect("exponent digits");
2525 while (ch
>= '0' && ch
<= '9') {
2526 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2538 tokc
.f
= strtof(token_buf
, NULL
);
2539 } else if (t
== 'L') {
2541 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2543 tokc
.d
= strtod(token_buf
, NULL
);
2546 tokc
.ld
= strtold(token_buf
, NULL
);
2550 tokc
.d
= strtod(token_buf
, NULL
);
2554 unsigned long long n
, n1
;
2555 int lcount
, ucount
, ov
= 0;
2558 /* integer number */
2561 if (b
== 10 && *q
== '0') {
2568 /* no need for checks except for base 10 / 8 errors */
2578 tcc_error("invalid digit");
2581 /* detect overflow */
2582 if (n1
>= 0x1000000000000000ULL
&& n
/ b
!= n1
)
2586 /* Determine the characteristics (unsigned and/or 64bit) the type of
2587 the constant must have according to the constant suffix(es) */
2588 lcount
= ucount
= 0;
2594 tcc_error("three 'l's in integer constant");
2595 if (lcount
&& *(p
- 1) != ch
)
2596 tcc_error("incorrect integer suffix: %s", p1
);
2599 } else if (t
== 'U') {
2601 tcc_error("two 'u's in integer constant");
2609 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2610 if (ucount
== 0 && b
== 10) {
2611 if (lcount
<= (LONG_SIZE
== 4)) {
2612 if (n
>= 0x80000000U
)
2613 lcount
= (LONG_SIZE
== 4) + 1;
2615 if (n
>= 0x8000000000000000ULL
)
2618 if (lcount
<= (LONG_SIZE
== 4)) {
2619 if (n
>= 0x100000000ULL
)
2620 lcount
= (LONG_SIZE
== 4) + 1;
2621 else if (n
>= 0x80000000U
)
2624 if (n
>= 0x8000000000000000ULL
)
2629 tcc_warning("integer constant overflow");
2638 ++tok
; /* TOK_CU... */
2642 tcc_error("invalid number");
2646 #define PARSE2(c1, tok1, c2, tok2) \
2657 /* return next token without macro substitution */
2658 static inline void next_nomacro1(void)
2660 int t
, c
, is_long
, len
;
2674 if (parse_flags
& PARSE_FLAG_SPACES
)
2675 goto keep_tok_flags
;
2676 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2685 /* first look if it is in fact an end of buffer */
2686 c
= handle_stray1(p
);
2693 TCCState
*s1
= tcc_state
;
2694 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2695 && !(tok_flags
& TOK_FLAG_EOF
)) {
2696 tok_flags
|= TOK_FLAG_EOF
;
2698 goto keep_tok_flags
;
2699 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2701 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2702 tcc_error("missing #endif");
2703 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2704 /* no include left : end of file. */
2707 tok_flags
&= ~TOK_FLAG_EOF
;
2708 /* pop include file */
2710 /* test if previous '#endif' was after a #ifdef at
2712 if (tok_flags
& TOK_FLAG_ENDIF
) {
2714 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2716 search_cached_include(s1
, file
->filename
, 1)
2717 ->ifndef_macro
= file
->ifndef_macro_saved
;
2718 tok_flags
&= ~TOK_FLAG_ENDIF
;
2721 /* add end of include file debug info */
2722 tcc_debug_eincl(tcc_state
);
2723 /* pop include stack */
2725 s1
->include_stack_ptr
--;
2727 if (p
== file
->buffer
)
2728 tok_flags
= TOK_FLAG_BOF
|TOK_FLAG_BOL
;
2736 tok_flags
|= TOK_FLAG_BOL
;
2739 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2742 goto keep_tok_flags
;
2747 if ((tok_flags
& TOK_FLAG_BOL
) &&
2748 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2750 preprocess(tok_flags
& TOK_FLAG_BOF
);
2756 tok
= TOK_TWOSHARPS
;
2758 #if !defined(TCC_TARGET_ARM)
2759 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2760 p
= parse_line_comment(p
- 1);
2771 /* dollar is allowed to start identifiers when not parsing asm */
2773 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2774 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2777 case 'a': case 'b': case 'c': case 'd':
2778 case 'e': case 'f': case 'g': case 'h':
2779 case 'i': case 'j': case 'k': case 'l':
2780 case 'm': case 'n': case 'o': case 'p':
2781 case 'q': case 'r': case 's': case 't':
2782 case 'u': case 'v': case 'w': case 'x':
2784 case 'A': case 'B': case 'C': case 'D':
2785 case 'E': case 'F': case 'G': case 'H':
2786 case 'I': case 'J': case 'K':
2787 case 'M': case 'N': case 'O': case 'P':
2788 case 'Q': case 'R': case 'S': case 'T':
2789 case 'U': case 'V': case 'W': case 'X':
2795 h
= TOK_HASH_FUNC(h
, c
);
2796 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2797 h
= TOK_HASH_FUNC(h
, c
);
2802 /* fast case : no stray found, so we have the full token
2803 and we have already hashed it */
2804 h
&= (TOK_HASH_SIZE
- 1);
2805 pts
= &hash_ident
[h
];
2810 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2812 pts
= &(ts
->hash_next
);
2814 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2818 cstr_reset(&tokcstr
);
2819 cstr_cat(&tokcstr
, (char *) p1
, len
);
2823 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2825 cstr_ccat(&tokcstr
, c
);
2828 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2834 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2836 goto parse_ident_fast
;
2839 if (c
== '\'' || c
== '\"') {
2843 cstr_reset(&tokcstr
);
2844 cstr_ccat(&tokcstr
, 'L');
2845 goto parse_ident_slow
;
2850 case '0': case '1': case '2': case '3':
2851 case '4': case '5': case '6': case '7':
2855 /* after the first digit, accept digits, alpha, '.' or sign if
2856 prefixed by 'eEpP' */
2858 cstr_reset(&tokcstr
);
2860 cstr_ccat(&tokcstr
, t
);
2861 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2863 || ((c
== '+' || c
== '-')
2864 && (((t
== 'e' || t
== 'E')
2865 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2866 /* 0xe+1 is 3 tokens in asm */
2867 && ((char*)tokcstr
.data
)[0] == '0'
2868 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2869 || t
== 'p' || t
== 'P'))))
2874 /* We add a trailing '\0' to ease parsing */
2875 cstr_ccat(&tokcstr
, '\0');
2876 tokc
.str
.size
= tokcstr
.size
;
2877 tokc
.str
.data
= tokcstr
.data
;
2882 /* special dot handling because it can also start a number */
2887 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2888 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2890 goto parse_ident_fast
;
2891 } else if (c
== '.') {
2897 *--p
= '.'; /* may underflow into file->unget[] */
2908 cstr_reset(&tokcstr
);
2910 cstr_ccat(&tokcstr
, 'L');
2911 cstr_ccat(&tokcstr
, c
);
2912 p
= parse_pp_string(p
, c
, &tokcstr
);
2913 cstr_ccat(&tokcstr
, c
);
2914 cstr_ccat(&tokcstr
, '\0');
2915 tokc
.str
.size
= tokcstr
.size
;
2916 tokc
.str
.data
= tokcstr
.data
;
2925 } else if (c
== '<') {
2942 } else if (c
== '>') {
2960 } else if (c
== '=') {
2973 } else if (c
== '=') {
2986 } else if (c
== '=') {
2999 } else if (c
== '=') {
3002 } else if (c
== '>') {
3010 PARSE2('!', '!', '=', TOK_NE
)
3011 PARSE2('=', '=', '=', TOK_EQ
)
3012 PARSE2('*', '*', '=', TOK_A_MUL
)
3013 PARSE2('%', '%', '=', TOK_A_MOD
)
3014 PARSE2('^', '^', '=', TOK_A_XOR
)
3016 /* comments or operator */
3020 p
= parse_comment(p
);
3021 /* comments replaced by a blank */
3024 } else if (c
== '/') {
3025 p
= parse_line_comment(p
);
3028 } else if (c
== '=') {
3048 case '@': /* only used in assembler */
3054 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
3055 goto parse_ident_fast
;
3056 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
3058 tcc_error("unrecognized character \\x%02x", c
);
3064 #if defined(PARSE_DEBUG)
3065 printf("token = %d %s\n", tok
, get_tok_str(tok
, &tokc
));
3069 static void macro_subst(
3070 TokenString
*tok_str
,
3072 const int *macro_str
3075 /* substitute arguments in replacement lists in macro_str by the values in
3076 args (field d) and return allocated string */
3077 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
3089 TOK_GET(&t
, ¯o_str
, &cval
);
3094 TOK_GET(&t
, ¯o_str
, &cval
);
3097 s
= sym_find2(args
, t
);
3100 cstr_ccat(&cstr
, '\"');
3104 TOK_GET(&t
, &st
, &cval
);
3105 if (t
!= TOK_PLCHLDR
3107 && 0 == check_space(t
, &spc
)) {
3108 const char *s
= get_tok_str(t
, &cval
);
3110 if (t
== TOK_PPSTR
&& *s
!= '\'')
3111 add_char(&cstr
, *s
);
3113 cstr_ccat(&cstr
, *s
);
3119 cstr_ccat(&cstr
, '\"');
3120 cstr_ccat(&cstr
, '\0');
3122 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
3125 cval
.str
.size
= cstr
.size
;
3126 cval
.str
.data
= cstr
.data
;
3127 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
3131 expect("macro parameter after '#'");
3133 } else if (t
>= TOK_IDENT
) {
3134 s
= sym_find2(args
, t
);
3138 /* if '##' is present before or after, no arg substitution */
3139 if (*macro_str
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
3140 /* special case for var arg macros : ## eats the ','
3141 if empty VA_ARGS variable. */
3142 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
3144 /* suppress ',' '##' */
3147 /* suppress '##' and add variable */
3155 /* Expand arguments tokens and store them. In most
3156 cases we could also re-expand each argument if
3157 used multiple times, but not if the argument
3158 contains the __COUNTER__ macro. */
3160 sym_push2(&s
->next
, s
->v
, s
->type
.t
, 0);
3162 macro_subst(&str2
, nested_list
, st
);
3163 tok_str_add(&str2
, 0);
3164 s
->next
->d
= str2
.str
;
3170 TOK_GET(&t2
, &st
, &cval
);
3173 tok_str_add2(&str
, t2
, &cval
);
3175 if (str
.len
== l0
) /* expanded to empty string */
3176 tok_str_add(&str
, TOK_PLCHLDR
);
3178 tok_str_add(&str
, t
);
3181 tok_str_add2(&str
, t
, &cval
);
3185 tok_str_add(&str
, 0);
3189 static char const ab_month_name
[12][4] =
3191 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3192 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3195 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3201 if (t1
!= TOK_PLCHLDR
)
3202 cstr_cat(&cstr
, get_tok_str(t1
, v1
), -1);
3204 if (t2
!= TOK_PLCHLDR
)
3205 cstr_cat(&cstr
, get_tok_str(t2
, v2
), -1);
3206 cstr_ccat(&cstr
, '\0');
3208 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3209 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3213 if (0 == *file
->buf_ptr
)
3217 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3218 " preprocessing token", n
, (char *)cstr
.data
, (char*)cstr
.data
+ n
);
3223 //printf("paste <%s>\n", (char*)cstr.data);
3228 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3229 return the resulting string (which must be freed). */
3230 static inline int *macro_twosharps(const int *ptr0
)
3234 TokenString macro_str1
;
3235 int start_of_nosubsts
= -1;
3238 /* we search the first '##' */
3239 for (ptr
= ptr0
;;) {
3240 TOK_GET(&t
, &ptr
, &cval
);
3241 if (t
== TOK_PPJOIN
)
3247 tok_str_new(¯o_str1
);
3249 //tok_print(" $$$", ptr0);
3250 for (ptr
= ptr0
;;) {
3251 TOK_GET(&t
, &ptr
, &cval
);
3254 if (t
== TOK_PPJOIN
)
3256 while (*ptr
== TOK_PPJOIN
) {
3258 /* given 'a##b', remove nosubsts preceding 'a' */
3259 if (start_of_nosubsts
>= 0)
3260 macro_str1
.len
= start_of_nosubsts
;
3261 /* given 'a##b', remove nosubsts preceding 'b' */
3262 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3264 if (t1
&& t1
!= TOK_PPJOIN
) {
3265 TOK_GET(&t1
, &ptr
, &cv1
);
3266 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3267 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3268 t
= tok
, cval
= tokc
;
3270 tok_str_add2(¯o_str1
, t
, &cval
);
3276 if (t
== TOK_NOSUBST
) {
3277 if (start_of_nosubsts
< 0)
3278 start_of_nosubsts
= macro_str1
.len
;
3280 start_of_nosubsts
= -1;
3282 tok_str_add2(¯o_str1
, t
, &cval
);
3284 tok_str_add(¯o_str1
, 0);
3285 //tok_print(" ###", macro_str1.str);
3286 return macro_str1
.str
;
3289 /* peek or read [ws_str == NULL] next token from function macro call,
3290 walking up macro levels up to the file if necessary */
3291 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3299 p
= macro_ptr
, t
= *p
;
3301 while (is_space(t
) || TOK_LINEFEED
== t
|| TOK_PLCHLDR
== t
)
3302 tok_str_add(ws_str
, t
), t
= *++p
;
3306 /* also, end of scope for nested defined symbol */
3308 while (sa
&& sa
->v
== 0)
3317 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3320 uint8_t *p
= file
->buf_ptr
;
3323 p
= parse_comment(p
);
3324 file
->buf_ptr
= p
- 1;
3325 } else if (c
== '/') {
3326 p
= parse_line_comment(p
);
3327 file
->buf_ptr
= p
- 1;
3334 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3335 tok_str_add(ws_str
, ch
);
3349 /* do macro substitution of current token with macro 's' and add
3350 result to (tok_str,tok_len). 'nested_list' is the list of all
3351 macros we got inside to avoid recursing. Return non zero if no
3352 substitution needs to be done */
3353 static int macro_subst_tok(
3354 TokenString
*tok_str
,
3358 Sym
*args
, *sa
, *sa1
;
3359 int parlevel
, t
, t1
, spc
;
3366 /* if symbol is a macro, prepare substitution */
3367 /* special macros */
3368 if (tok
== TOK___LINE__
|| tok
== TOK___COUNTER__
) {
3369 t
= tok
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3370 snprintf(buf
, sizeof(buf
), "%d", t
);
3374 } else if (tok
== TOK___FILE__
) {
3375 cstrval
= file
->filename
;
3377 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3382 tm
= localtime(&ti
);
3383 if (tok
== TOK___DATE__
) {
3384 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3385 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3387 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3388 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3395 cstr_cat(&cstr
, cstrval
, 0);
3396 cval
.str
.size
= cstr
.size
;
3397 cval
.str
.data
= cstr
.data
;
3398 tok_str_add2(tok_str
, t1
, &cval
);
3401 int saved_parse_flags
= parse_flags
;
3402 int *joined_str
= NULL
;
3405 if (s
->type
.t
== MACRO_FUNC
) {
3406 /* whitespace between macro name and argument list */
3408 tok_str_new(&ws_str
);
3411 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3412 | PARSE_FLAG_ACCEPT_STRAYS
;
3414 /* get next token from argument stream */
3415 t
= next_argstream(nested_list
, &ws_str
);
3417 /* not a macro substitution after all, restore the
3418 * macro token plus all whitespace we've read.
3419 * whitespace is intentionally not merged to preserve
3421 parse_flags
= saved_parse_flags
;
3422 tok_str_add(tok_str
, tok
);
3423 if (parse_flags
& PARSE_FLAG_SPACES
) {
3425 for (i
= 0; i
< ws_str
.len
; i
++)
3426 tok_str_add(tok_str
, ws_str
.str
[i
]);
3428 tok_str_free_str(ws_str
.str
);
3431 tok_str_free_str(ws_str
.str
);
3434 next_nomacro(); /* eat '(' */
3435 } while (tok
== TOK_PLCHLDR
|| is_space(tok
));
3437 /* argument macro */
3440 /* NOTE: empty args are allowed, except if no args */
3443 next_argstream(nested_list
, NULL
);
3444 } while (tok
== TOK_PLCHLDR
|| is_space(tok
) ||
3445 TOK_LINEFEED
== tok
);
3447 /* handle '()' case */
3448 if (!args
&& !sa
&& tok
== ')')
3451 tcc_error("macro '%s' used with too many args",
3452 get_tok_str(s
->v
, 0));
3455 /* NOTE: non zero sa->t indicates VA_ARGS */
3456 while ((parlevel
> 0 ||
3458 (tok
!= ',' || sa
->type
.t
)))) {
3459 if (tok
== TOK_EOF
|| tok
== 0)
3463 else if (tok
== ')')
3465 if (tok
== TOK_LINEFEED
)
3467 if (!check_space(tok
, &spc
))
3468 tok_str_add2(&str
, tok
, &tokc
);
3469 next_argstream(nested_list
, NULL
);
3474 tok_str_add(&str
, -1);
3475 tok_str_add(&str
, 0);
3476 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3480 /* special case for gcc var args: add an empty
3481 var arg argument if it is omitted */
3482 if (sa
&& sa
->type
.t
&& gnu_ext
)
3490 tcc_error("macro '%s' used with too few args",
3491 get_tok_str(s
->v
, 0));
3494 /* now subst each arg */
3495 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3500 tok_str_free_str(sa
->d
);
3502 tok_str_free_str(sa
->next
->d
);
3508 parse_flags
= saved_parse_flags
;
3511 sym_push2(nested_list
, s
->v
, 0, 0);
3512 parse_flags
= saved_parse_flags
;
3513 joined_str
= macro_twosharps(mstr
);
3514 macro_subst(tok_str
, nested_list
, joined_str
? joined_str
: mstr
);
3516 /* pop nested defined symbol */
3518 *nested_list
= sa1
->prev
;
3521 tok_str_free_str(joined_str
);
3523 tok_str_free_str(mstr
);
3528 /* do macro substitution of macro_str and add result to
3529 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3530 inside to avoid recursing. */
3531 static void macro_subst(
3532 TokenString
*tok_str
,
3534 const int *macro_str
3538 int t
, spc
, nosubst
;
3544 TOK_GET(&t
, ¯o_str
, &cval
);
3548 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3553 /* if nested substitution, do nothing */
3554 if (sym_find2(*nested_list
, t
)) {
3555 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3556 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3561 TokenString
*str
= tok_str_alloc();
3562 str
->str
= (int*)macro_str
;
3563 begin_macro(str
, 2);
3566 macro_subst_tok(tok_str
, nested_list
, s
);
3568 if (macro_stack
!= str
) {
3569 /* already finished by reading function macro arguments */
3573 macro_str
= macro_ptr
;
3577 spc
= is_space(t
= tok_str
->str
[tok_str
->lastlen
]);
3580 if (!check_space(t
, &spc
))
3581 tok_str_add2(tok_str
, t
, &cval
);
3584 if (nosubst
> 1 && (spc
|| (++nosubst
== 3 && t
== '(')))
3588 if (t
== TOK_NOSUBST
)
3591 /* GCC supports 'defined' as result of a macro substitution */
3592 if (t
== TOK_DEFINED
&& pp_expr
)
3597 /* return next token without macro substitution. Can read input from
3599 static void next_nomacro(void)
3605 if (TOK_HAS_VALUE(t
)) {
3606 tok_get(&tok
, ¯o_ptr
, &tokc
);
3607 if (t
== TOK_LINENUM
) {
3608 file
->line_num
= tokc
.i
;
3613 if (t
< TOK_IDENT
) {
3614 if (!(parse_flags
& PARSE_FLAG_SPACES
)
3615 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
))
3625 /* return next token with macro substitution */
3626 ST_FUNC
void next(void)
3633 if (!TOK_HAS_VALUE(t
)) {
3634 if (t
== TOK_NOSUBST
|| t
== TOK_PLCHLDR
) {
3635 /* discard preprocessor markers */
3637 } else if (t
== 0) {
3638 /* end of macro or unget token string */
3641 } else if (t
== '\\') {
3642 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3643 tcc_error("stray '\\' in program");
3647 } else if (t
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3648 /* if reading from file, try to substitute macros */
3649 Sym
*s
= define_find(t
);
3651 Sym
*nested_list
= NULL
;
3653 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3654 tok_str_add(&tokstr_buf
, 0);
3655 begin_macro(&tokstr_buf
, 0);
3660 /* convert preprocessor tokens into C tokens */
3661 if (t
== TOK_PPNUM
) {
3662 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3663 parse_number((char *)tokc
.str
.data
);
3664 } else if (t
== TOK_PPSTR
) {
3665 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3666 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3670 /* push back current token and set current token to 'last_tok'. Only
3671 identifier case handled for labels. */
3672 ST_INLN
void unget_tok(int last_tok
)
3675 TokenString
*str
= tok_str_alloc();
3676 tok_str_add2(str
, tok
, &tokc
);
3677 tok_str_add(str
, 0);
3678 begin_macro(str
, 1);
3682 /* ------------------------------------------------------------------------- */
3683 /* init preprocessor */
3685 static const char * const target_os_defs
=
3686 #ifdef TCC_TARGET_PE
3692 # if defined TCC_TARGET_MACHO
3694 # elif TARGETOS_FreeBSD
3696 # elif TARGETOS_FreeBSD_kernel
3697 "__FreeBSD_kernel__\0"
3698 # elif TARGETOS_NetBSD
3700 # elif TARGETOS_OpenBSD
3711 static void putdef(CString
*cs
, const char *p
)
3713 cstr_printf(cs
, "#define %s%s\n", p
, &" 1"[!!strchr(p
, ' ')*2]);
3716 static void tcc_predefs(TCCState
*s1
, CString
*cs
, int is_asm
)
3719 const char *defs
[] = { target_machine_defs
, target_os_defs
, NULL
};
3722 sscanf(TCC_VERSION
, "%d.%d.%d", &a
, &b
, &c
);
3723 cstr_printf(cs
, "#define __TINYC__ %d\n", a
*10000 + b
*100 + c
);
3724 for (a
= 0; defs
[a
]; ++a
)
3725 for (p
= defs
[a
]; *p
; p
= strchr(p
, 0) + 1)
3727 #ifdef TCC_TARGET_ARM
3728 if (s1
->float_abi
== ARM_HARD_FLOAT
)
3729 putdef(cs
, "__ARM_PCS_VFP");
3732 putdef(cs
, "__ASSEMBLER__");
3733 if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
)
3734 putdef(cs
, "__TCC_PP__");
3735 if (s1
->output_type
== TCC_OUTPUT_MEMORY
)
3736 putdef(cs
, "__TCC_RUN__");
3737 if (s1
->char_is_unsigned
)
3738 putdef(cs
, "__CHAR_UNSIGNED__");
3739 if (s1
->optimize
> 0)
3740 putdef(cs
, "__OPTIMIZE__");
3741 if (s1
->option_pthread
)
3742 putdef(cs
, "_REENTRANT");
3743 if (s1
->leading_underscore
)
3744 putdef(cs
, "__leading_underscore");
3745 #ifdef CONFIG_TCC_BCHECK
3746 if (s1
->do_bounds_check
)
3747 putdef(cs
, "__BOUNDS_CHECKING_ON");
3749 cstr_printf(cs
, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE
);
3750 cstr_printf(cs
, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE
);
3752 putdef(cs
, "__STDC__");
3753 cstr_printf(cs
, "#define __STDC_VERSION__ %dL\n", s1
->cversion
);
3755 /* load more predefs and __builtins */
3756 #if CONFIG_TCC_PREDEFS
3757 #include "tccdefs_.h" /* include as strings */
3759 "#include <tccdefs.h>\n" /* load at runtime */
3763 cstr_printf(cs
, "#define __BASE_FILE__ \"%s\"\n", file
->filename
);
3766 ST_FUNC
void preprocess_start(TCCState
*s1
, int filetype
)
3768 int is_asm
= !!(filetype
& (AFF_TYPE_ASM
|AFF_TYPE_ASMPP
));
3773 s1
->include_stack_ptr
= s1
->include_stack
;
3774 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3775 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3778 pp_debug_tok
= pp_debug_symv
= 0;
3780 s1
->pack_stack
[0] = 0;
3781 s1
->pack_stack_ptr
= s1
->pack_stack
;
3783 set_idnum('$', !is_asm
&& s1
->dollars_in_identifiers
? IS_ID
: 0);
3784 set_idnum('.', is_asm
? IS_ID
: 0);
3786 if (!(filetype
& AFF_TYPE_ASM
)) {
3788 tcc_predefs(s1
, &cstr
, is_asm
);
3789 if (s1
->cmdline_defs
.size
)
3790 cstr_cat(&cstr
, s1
->cmdline_defs
.data
, s1
->cmdline_defs
.size
);
3791 if (s1
->cmdline_incl
.size
)
3792 cstr_cat(&cstr
, s1
->cmdline_incl
.data
, s1
->cmdline_incl
.size
);
3793 //printf("%s\n", (char*)cstr.data);
3794 *s1
->include_stack_ptr
++ = file
;
3795 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3796 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3800 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3801 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3804 /* cleanup from error/setjmp */
3805 ST_FUNC
void preprocess_end(TCCState
*s1
)
3815 ST_FUNC
void tccpp_new(TCCState
*s
)
3820 /* init isid table */
3821 for(i
= CH_EOF
; i
<128; i
++)
3823 is_space(i
) ? IS_SPC
3828 for(i
= 128; i
<256; i
++)
3829 set_idnum(i
, IS_ID
);
3831 /* init allocators */
3832 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3833 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3835 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3836 memset(s
->cached_includes_hash
, 0, sizeof s
->cached_includes_hash
);
3838 cstr_new(&cstr_buf
);
3839 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3840 tok_str_new(&tokstr_buf
);
3841 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3843 tok_ident
= TOK_IDENT
;
3852 tok_alloc(p
, r
- p
- 1);
3856 /* we add dummy defines for some special macros to speed up tests
3857 and to have working defined() */
3858 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
3859 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
3860 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
3861 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
3862 define_push(TOK___COUNTER__
, MACRO_OBJ
, NULL
, NULL
);
3865 ST_FUNC
void tccpp_delete(TCCState
*s
)
3869 dynarray_reset(&s
->cached_includes
, &s
->nb_cached_includes
);
3872 n
= tok_ident
- TOK_IDENT
;
3873 if (n
> total_idents
)
3875 for(i
= 0; i
< n
; i
++)
3876 tal_free(toksym_alloc
, table_ident
[i
]);
3877 tcc_free(table_ident
);
3880 /* free static buffers */
3881 cstr_free(&tokcstr
);
3882 cstr_free(&cstr_buf
);
3883 cstr_free(¯o_equal_buf
);
3884 tok_str_free_str(tokstr_buf
.str
);
3886 /* free allocators */
3887 tal_delete(toksym_alloc
);
3888 toksym_alloc
= NULL
;
3889 tal_delete(tokstr_alloc
);
3890 tokstr_alloc
= NULL
;
3893 /* ------------------------------------------------------------------------- */
3894 /* tcc -E [-P[1]] [-dD} support */
3896 static void tok_print(const char *msg
, const int *str
)
3902 fp
= tcc_state
->ppfp
;
3903 fprintf(fp
, "%s", msg
);
3905 TOK_GET(&t
, &str
, &cval
);
3908 fprintf(fp
, &" %s"[s
], get_tok_str(t
, &cval
)), s
= 1;
3913 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3915 int d
= f
->line_num
- f
->line_ref
;
3920 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3922 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3924 fputs("\n", s1
->ppfp
), --d
;
3925 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3926 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3928 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3929 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3931 f
->line_ref
= f
->line_num
;
3934 static void define_print(TCCState
*s1
, int v
)
3940 if (NULL
== s
|| NULL
== s
->d
)
3944 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3945 if (s
->type
.t
== MACRO_FUNC
) {
3950 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3957 tok_print("", s
->d
);
3960 static void pp_debug_defines(TCCState
*s1
)
3971 pp_line(s1
, file
, 0);
3972 file
->line_ref
= ++file
->line_num
;
3976 vs
= get_tok_str(v
, NULL
);
3977 if (t
== TOK_DEFINE
) {
3978 define_print(s1
, v
);
3979 } else if (t
== TOK_UNDEF
) {
3980 fprintf(fp
, "#undef %s\n", vs
);
3981 } else if (t
== TOK_push_macro
) {
3982 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3983 } else if (t
== TOK_pop_macro
) {
3984 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3989 static void pp_debug_builtins(TCCState
*s1
)
3992 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3993 define_print(s1
, v
);
3996 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3997 static int pp_need_space(int a
, int b
)
3999 return 'E' == a
? '+' == b
|| '-' == b
4000 : '+' == a
? TOK_INC
== b
|| '+' == b
4001 : '-' == a
? TOK_DEC
== b
|| '-' == b
4002 : a
>= TOK_IDENT
? b
>= TOK_IDENT
4003 : a
== TOK_PPNUM
? b
>= TOK_IDENT
4007 /* maybe hex like 0x1e */
4008 static int pp_check_he0xE(int t
, const char *p
)
4010 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
4015 /* Preprocess the current file */
4016 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
4018 BufferedFile
**iptr
;
4019 int token_seen
, spcs
, level
;
4023 parse_flags
= PARSE_FLAG_PREPROCESS
4024 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
4025 | PARSE_FLAG_LINEFEED
4027 | PARSE_FLAG_ACCEPT_STRAYS
4029 /* Credits to Fabrice Bellard's initial revision to demonstrate its
4030 capability to compile and run itself, provided all numbers are
4031 given as decimals. tcc -E -P10 will do. */
4032 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
4033 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
4036 /* for PP benchmarks */
4037 do next(); while (tok
!= TOK_EOF
);
4041 if (s1
->dflag
& 1) {
4042 pp_debug_builtins(s1
);
4046 token_seen
= TOK_LINEFEED
, spcs
= 0, level
= 0;
4048 pp_line(s1
, file
->prev
, level
++);
4049 pp_line(s1
, file
, level
);
4051 iptr
= s1
->include_stack_ptr
;
4056 level
= s1
->include_stack_ptr
- iptr
;
4059 pp_line(s1
, *iptr
, 0);
4060 pp_line(s1
, file
, level
);
4062 if (s1
->dflag
& 7) {
4063 pp_debug_defines(s1
);
4068 if (is_space(tok
)) {
4069 if (spcs
< sizeof white
- 1)
4070 white
[spcs
++] = tok
;
4072 } else if (tok
== TOK_LINEFEED
) {
4074 if (token_seen
== TOK_LINEFEED
)
4077 } else if (token_seen
== TOK_LINEFEED
) {
4078 pp_line(s1
, file
, 0);
4079 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
4080 white
[spcs
++] = ' ';
4083 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
4084 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
4085 token_seen
= pp_check_he0xE(tok
, p
);
4090 /* ------------------------------------------------------------------------- */