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) return b
;
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;
358 /* add a unicode character expanded into utf8 */
359 ST_INLN
void cstr_u8cat(CString
*cstr
, int ch
)
362 e
= unicode_to_utf8(buf
, (uint32_t)ch
);
363 cstr_cat(cstr
, buf
, e
- buf
);
366 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
, int len
)
370 len
= strlen(str
) + 1 + len
;
371 size
= cstr
->size
+ len
;
372 if (size
> cstr
->size_allocated
)
373 cstr_realloc(cstr
, size
);
374 memmove(((unsigned char *)cstr
->data
) + cstr
->size
, str
, len
);
378 /* add a wide char */
379 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
382 size
= cstr
->size
+ sizeof(nwchar_t
);
383 if (size
> cstr
->size_allocated
)
384 cstr_realloc(cstr
, size
);
385 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
389 ST_FUNC
void cstr_new(CString
*cstr
)
391 memset(cstr
, 0, sizeof(CString
));
394 /* free string and reset it to NULL */
395 ST_FUNC
void cstr_free(CString
*cstr
)
397 tcc_free(cstr
->data
);
401 /* reset string to empty */
402 ST_FUNC
void cstr_reset(CString
*cstr
)
407 ST_FUNC
int cstr_printf(CString
*cstr
, const char *fmt
, ...)
413 if (size
> cstr
->size_allocated
)
414 cstr_realloc(cstr
, size
);
415 size
= cstr
->size_allocated
- cstr
->size
;
417 len
= vsnprintf((char*)cstr
->data
+ cstr
->size
, size
, fmt
, v
);
419 if (len
> 0 && len
< size
)
428 static void add_char(CString
*cstr
, int c
)
430 if (c
== '\'' || c
== '\"' || c
== '\\') {
431 /* XXX: could be more precise if char or string */
432 cstr_ccat(cstr
, '\\');
434 if (c
>= 32 && c
<= 126) {
437 cstr_ccat(cstr
, '\\');
439 cstr_ccat(cstr
, 'n');
441 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
442 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
443 cstr_ccat(cstr
, '0' + (c
& 7));
448 /* ------------------------------------------------------------------------- */
449 /* allocate a new token */
450 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
452 TokenSym
*ts
, **ptable
;
455 if (tok_ident
>= SYM_FIRST_ANOM
)
456 tcc_error("memory full (symbols)");
458 /* expand token table if needed */
459 i
= tok_ident
- TOK_IDENT
;
460 if ((i
% TOK_ALLOC_INCR
) == 0) {
461 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
462 table_ident
= ptable
;
465 ts
= tal_realloc(toksym_alloc
, 0, sizeof(TokenSym
) + len
);
467 ts
->tok
= tok_ident
++;
468 ts
->sym_define
= NULL
;
469 ts
->sym_label
= NULL
;
470 ts
->sym_struct
= NULL
;
471 ts
->sym_identifier
= NULL
;
473 ts
->hash_next
= NULL
;
474 memcpy(ts
->str
, str
, len
);
480 #define TOK_HASH_INIT 1
481 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
484 /* find a token and add it if not found */
485 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
493 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
494 h
&= (TOK_HASH_SIZE
- 1);
496 pts
= &hash_ident
[h
];
501 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
503 pts
= &(ts
->hash_next
);
505 return tok_alloc_new(pts
, str
, len
);
508 ST_FUNC
int tok_alloc_const(const char *str
)
510 return tok_alloc(str
, strlen(str
))->tok
;
514 /* XXX: buffer overflow */
515 /* XXX: float tokens */
516 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
521 cstr_reset(&cstr_buf
);
531 /* XXX: not quite exact, but only useful for testing */
533 sprintf(p
, "%u", (unsigned)cv
->i
);
535 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
539 cstr_ccat(&cstr_buf
, 'L');
541 cstr_ccat(&cstr_buf
, '\'');
542 add_char(&cstr_buf
, cv
->i
);
543 cstr_ccat(&cstr_buf
, '\'');
544 cstr_ccat(&cstr_buf
, '\0');
548 return (char*)cv
->str
.data
;
550 cstr_ccat(&cstr_buf
, 'L');
552 cstr_ccat(&cstr_buf
, '\"');
554 len
= cv
->str
.size
- 1;
556 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
558 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
560 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
562 cstr_ccat(&cstr_buf
, '\"');
563 cstr_ccat(&cstr_buf
, '\0');
567 cstr_cat(&cstr_buf
, "<float>", 0);
570 cstr_cat(&cstr_buf
, "<double>", 0);
573 cstr_cat(&cstr_buf
, "<long double>", 0);
576 cstr_cat(&cstr_buf
, "<linenumber>", 0);
579 /* above tokens have value, the ones below don't */
587 return strcpy(p
, "...");
589 return strcpy(p
, "<<=");
591 return strcpy(p
, ">>=");
593 return strcpy(p
, "<eof>");
596 /* search in two bytes table */
597 const unsigned char *q
= tok_two_chars
;
603 return cstr_buf
.data
;
608 sprintf(cstr_buf
.data
, "<%02x>", v
);
609 return cstr_buf
.data
;
613 case 0: /* nameless anonymous symbol */
615 } else if (v
< tok_ident
) {
616 return table_ident
[v
- TOK_IDENT
]->str
;
617 } else if (v
>= SYM_FIRST_ANOM
) {
618 /* special name for anonymous symbol */
619 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
621 /* should never happen */
626 return cstr_buf
.data
;
629 /* return the current character, handling end of block if necessary
631 static int handle_eob(void)
633 BufferedFile
*bf
= file
;
636 /* only tries to read if really end of buffer */
637 if (bf
->buf_ptr
>= bf
->buf_end
) {
639 #if defined(PARSE_DEBUG)
644 len
= read(bf
->fd
, bf
->buffer
, len
);
651 bf
->buf_ptr
= bf
->buffer
;
652 bf
->buf_end
= bf
->buffer
+ len
;
653 *bf
->buf_end
= CH_EOB
;
655 if (bf
->buf_ptr
< bf
->buf_end
) {
656 return bf
->buf_ptr
[0];
658 bf
->buf_ptr
= bf
->buf_end
;
663 /* read next char from current input file and handle end of input buffer */
664 static inline void inp(void)
666 ch
= *(++(file
->buf_ptr
));
667 /* end of buffer/file handling */
672 /* handle '\[\r]\n' */
673 static int handle_stray_noerror(void)
680 } else if (ch
== '\r') {
694 static void handle_stray(void)
696 if (handle_stray_noerror())
697 tcc_error("stray '\\' in program");
700 /* skip the stray and handle the \\n case. Output an error if
701 incorrect char after the stray */
702 static int handle_stray1(uint8_t *p
)
707 if (p
>= file
->buf_end
) {
714 if (handle_stray_noerror()) {
715 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
716 tcc_error("stray '\\' in program");
717 *--file
->buf_ptr
= '\\';
724 /* handle just the EOB case, but not stray */
725 #define PEEKC_EOB(c, p)\
736 /* handle the complicated stray case */
742 c = handle_stray1(p);\
747 /* input with '\[\r]\n' handling. Note that this function cannot
748 handle other characters after '\', so you cannot call it inside
749 strings or comments */
750 static void minp(void)
757 /* single line C++ comments */
758 static uint8_t *parse_line_comment(uint8_t *p
)
766 if (c
== '\n' || c
== CH_EOF
) {
768 } else if (c
== '\\') {
777 } else if (c
== '\r') {
795 static uint8_t *parse_comment(uint8_t *p
)
804 if (c
== '\n' || c
== '*' || c
== '\\')
808 if (c
== '\n' || c
== '*' || c
== '\\')
812 /* now we can handle all the cases */
816 } else if (c
== '*') {
822 } else if (c
== '/') {
824 } else if (c
== '\\') {
829 tcc_error("unexpected end of file in comment");
831 /* skip '\[\r]\n', otherwise just skip the stray */
837 } else if (c
== '\r') {
854 /* stray, eob or eof */
859 tcc_error("unexpected end of file in comment");
860 } else if (c
== '\\') {
870 ST_FUNC
int set_idnum(int c
, int val
)
872 int prev
= isidnum_table
[c
- CH_EOF
];
873 isidnum_table
[c
- CH_EOF
] = val
;
879 static inline void skip_spaces(void)
881 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
885 static inline int check_space(int t
, int *spc
)
887 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
896 /* parse a string without interpreting escapes */
897 static uint8_t *parse_pp_string(uint8_t *p
,
898 int sep
, CString
*str
)
906 } else if (c
== '\\') {
912 /* XXX: indicate line number of start of string */
913 tcc_error("missing terminating %c character", sep
);
914 } else if (c
== '\\') {
915 /* escape : just skip \[\r]\n */
920 } else if (c
== '\r') {
923 expect("'\n' after '\r'");
926 } else if (c
== CH_EOF
) {
927 goto unterminated_string
;
930 cstr_ccat(str
, '\\');
936 } else if (c
== '\n') {
939 } else if (c
== '\r') {
943 cstr_ccat(str
, '\r');
959 /* skip block of text until #else, #elif or #endif. skip also pairs of
961 static void preprocess_skip(void)
963 int a
, start_of_line
, c
, in_warn_or_error
;
970 in_warn_or_error
= 0;
991 } else if (c
== '\\') {
992 ch
= file
->buf_ptr
[0];
993 handle_stray_noerror();
1000 if (in_warn_or_error
)
1002 p
= parse_pp_string(p
, c
, NULL
);
1006 if (in_warn_or_error
)
1013 p
= parse_comment(p
);
1014 } else if (ch
== '/') {
1015 p
= parse_line_comment(p
);
1020 if (start_of_line
) {
1025 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
1027 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
1029 else if (tok
== TOK_ENDIF
)
1031 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
1032 in_warn_or_error
= 1;
1033 else if (tok
== TOK_LINEFEED
)
1035 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1036 p
= parse_line_comment(p
- 1);
1038 #if !defined(TCC_TARGET_ARM)
1039 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1040 p
= parse_line_comment(p
- 1);
1042 /* ARM assembly uses '#' for constants */
1057 /* return the number of additional 'ints' necessary to store the
1059 static inline int tok_size(const int *p
)
1074 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
1077 return 1 + LONG_SIZE
/ 4;
1083 return 1 + LDOUBLE_SIZE
/ 4;
1090 /* token string handling */
1091 ST_INLN
void tok_str_new(TokenString
*s
)
1094 s
->len
= s
->lastlen
= 0;
1095 s
->allocated_len
= 0;
1096 s
->last_line_num
= -1;
1099 ST_FUNC TokenString
*tok_str_alloc(void)
1101 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1106 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1110 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1111 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1115 ST_FUNC
void tok_str_free_str(int *str
)
1117 tal_free(tokstr_alloc
, str
);
1120 ST_FUNC
void tok_str_free(TokenString
*str
)
1122 tok_str_free_str(str
->str
);
1123 tal_free(tokstr_alloc
, str
);
1126 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1130 size
= s
->allocated_len
;
1133 while (size
< new_size
)
1135 if (size
> s
->allocated_len
) {
1136 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1137 s
->allocated_len
= size
;
1143 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1149 if (len
>= s
->allocated_len
)
1150 str
= tok_str_realloc(s
, len
+ 1);
1155 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1158 str
->prev
= macro_stack
;
1159 str
->prev_ptr
= macro_ptr
;
1160 str
->save_line_num
= file
->line_num
;
1161 macro_ptr
= str
->str
;
1165 ST_FUNC
void end_macro(void)
1167 TokenString
*str
= macro_stack
;
1168 macro_stack
= str
->prev
;
1169 macro_ptr
= str
->prev_ptr
;
1170 file
->line_num
= str
->save_line_num
;
1171 if (str
->alloc
!= 0) {
1172 if (str
->alloc
== 2)
1173 str
->str
= NULL
; /* don't free */
1178 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1182 len
= s
->lastlen
= s
->len
;
1185 /* allocate space for worst case */
1186 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1187 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1200 str
[len
++] = cv
->tab
[0];
1207 /* Insert the string into the int array. */
1209 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1210 if (len
+ nb_words
>= s
->allocated_len
)
1211 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1212 str
[len
] = cv
->str
.size
;
1213 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1224 #if LDOUBLE_SIZE == 8
1227 str
[len
++] = cv
->tab
[0];
1228 str
[len
++] = cv
->tab
[1];
1230 #if LDOUBLE_SIZE == 12
1232 str
[len
++] = cv
->tab
[0];
1233 str
[len
++] = cv
->tab
[1];
1234 str
[len
++] = cv
->tab
[2];
1235 #elif LDOUBLE_SIZE == 16
1237 str
[len
++] = cv
->tab
[0];
1238 str
[len
++] = cv
->tab
[1];
1239 str
[len
++] = cv
->tab
[2];
1240 str
[len
++] = cv
->tab
[3];
1241 #elif LDOUBLE_SIZE != 8
1242 #error add long double size support
1251 /* add the current parse token in token string 's' */
1252 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1256 /* save line number info */
1257 if (file
->line_num
!= s
->last_line_num
) {
1258 s
->last_line_num
= file
->line_num
;
1259 cval
.i
= s
->last_line_num
;
1260 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1262 tok_str_add2(s
, tok
, &tokc
);
1265 /* get a token from an integer array and increment pointer. */
1266 static inline void tok_get(int *t
, const int **pp
, CValue
*cv
)
1286 cv
->i
= (unsigned)*p
++;
1295 cv
->str
.size
= *p
++;
1297 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1309 #if LDOUBLE_SIZE == 16
1311 #elif LDOUBLE_SIZE == 12
1313 #elif LDOUBLE_SIZE == 8
1316 # error add long double size support
1330 # define TOK_GET(t,p,c) tok_get(t,p,c)
1332 # define TOK_GET(t,p,c) do { \
1334 if (TOK_HAS_VALUE(_t)) \
1337 *(t) = _t, ++*(p); \
1341 static int macro_is_equal(const int *a
, const int *b
)
1350 /* first time preallocate macro_equal_buf, next time only reset position to start */
1351 cstr_reset(¯o_equal_buf
);
1352 TOK_GET(&t
, &a
, &cv
);
1353 cstr_cat(¯o_equal_buf
, get_tok_str(t
, &cv
), 0);
1354 TOK_GET(&t
, &b
, &cv
);
1355 if (strcmp(macro_equal_buf
.data
, get_tok_str(t
, &cv
)))
1361 /* defines handling */
1362 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1367 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1369 s
->next
= first_arg
;
1370 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1372 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1373 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1376 /* undefined a define symbol. Its name is just set to zero */
1377 ST_FUNC
void define_undef(Sym
*s
)
1380 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1381 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1384 ST_INLN Sym
*define_find(int v
)
1387 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1389 return table_ident
[v
]->sym_define
;
1392 /* free define stack until top reaches 'b' */
1393 ST_FUNC
void free_defines(Sym
*b
)
1395 while (define_stack
!= b
) {
1396 Sym
*top
= define_stack
;
1397 define_stack
= top
->prev
;
1398 tok_str_free_str(top
->d
);
1405 ST_FUNC Sym
*label_find(int v
)
1408 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1410 return table_ident
[v
]->sym_label
;
1413 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1416 s
= sym_push2(ptop
, v
, 0, 0);
1418 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1419 if (ptop
== &global_label_stack
) {
1420 /* modify the top most local identifier, so that
1421 sym_identifier will point to 's' when popped */
1423 ps
= &(*ps
)->prev_tok
;
1430 /* pop labels until element last is reached. Look if any labels are
1431 undefined. Define symbols if '&&label' was used. */
1432 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
, int keep
)
1435 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1437 if (s
->r
== LABEL_DECLARED
) {
1438 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1439 } else if (s
->r
== LABEL_FORWARD
) {
1440 tcc_error("label '%s' used but not defined",
1441 get_tok_str(s
->v
, NULL
));
1444 /* define corresponding symbol. A size of
1446 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1450 if (s
->r
!= LABEL_GONE
)
1451 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1461 /* fake the nth "#if defined test_..." for tcc -dt -run */
1462 static void maybe_run_test(TCCState
*s
)
1465 if (s
->include_stack_ptr
!= s
->include_stack
)
1467 p
= get_tok_str(tok
, NULL
);
1468 if (0 != memcmp(p
, "test_", 5))
1470 if (0 != --s
->run_test
)
1472 fprintf(s
->ppfp
, &"\n[%s]\n"[!(s
->dflag
& 32)], p
), fflush(s
->ppfp
);
1473 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1476 /* eval an expression for #if/#elif */
1477 static int expr_preprocess(void)
1482 str
= tok_str_alloc();
1484 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1485 next(); /* do macro subst */
1487 if (tok
== TOK_DEFINED
) {
1492 if (tok
< TOK_IDENT
)
1493 expect("identifier");
1494 if (tcc_state
->run_test
)
1495 maybe_run_test(tcc_state
);
1496 c
= define_find(tok
) != 0;
1504 } else if (1 && tok
== TOK___HAS_INCLUDE
) {
1505 next(); /* XXX check if correct to use expansion */
1507 while (tok
!= ')' && tok
!= TOK_EOF
)
1513 } else if (tok
>= TOK_IDENT
) {
1514 /* if undefined macro, replace with zero, check for func-like */
1518 tok_str_add_tok(str
);
1521 tcc_error("function-like macro '%s' is not defined",
1522 get_tok_str(t
, NULL
));
1525 tok_str_add_tok(str
);
1528 tok_str_add(str
, -1); /* simulate end of file */
1529 tok_str_add(str
, 0);
1530 /* now evaluate C constant expression */
1531 begin_macro(str
, 1);
1539 /* parse after #define */
1540 ST_FUNC
void parse_define(void)
1542 Sym
*s
, *first
, **ps
;
1543 int v
, t
, varg
, is_vaargs
, spc
;
1544 int saved_parse_flags
= parse_flags
;
1547 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1548 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1549 /* XXX: should check if same macro (ANSI) */
1552 /* We have to parse the whole define as if not in asm mode, in particular
1553 no line comment with '#' must be ignored. Also for function
1554 macros the argument list must be parsed without '.' being an ID
1556 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1557 /* '(' must be just after macro definition for MACRO_FUNC */
1559 parse_flags
&= ~PARSE_FLAG_SPACES
;
1561 int dotid
= set_idnum('.', 0);
1564 if (tok
!= ')') for (;;) {
1568 if (varg
== TOK_DOTS
) {
1569 varg
= TOK___VA_ARGS__
;
1571 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1575 if (varg
< TOK_IDENT
)
1577 tcc_error("bad macro parameter list");
1578 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1583 if (tok
!= ',' || is_vaargs
)
1587 parse_flags
|= PARSE_FLAG_SPACES
;
1590 set_idnum('.', dotid
);
1595 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1596 /* The body of a macro definition should be parsed such that identifiers
1597 are parsed like the file mode determines (i.e. with '.' being an
1598 ID character in asm mode). But '#' should be retained instead of
1599 regarded as line comment leader, so still don't set ASM_FILE
1601 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1602 /* remove spaces around ## and after '#' */
1603 if (TOK_TWOSHARPS
== tok
) {
1610 } else if ('#' == tok
) {
1612 } else if (check_space(tok
, &spc
)) {
1615 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1620 parse_flags
= saved_parse_flags
;
1622 --tokstr_buf
.len
; /* remove trailing space */
1623 tok_str_add(&tokstr_buf
, 0);
1626 tcc_error("'##' cannot appear at either end of macro");
1627 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1630 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1632 const unsigned char *s
;
1638 s
= (unsigned char *) filename
;
1641 h
= TOK_HASH_FUNC(h
, toup(*s
));
1643 h
= TOK_HASH_FUNC(h
, *s
);
1647 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1649 i
= s1
->cached_includes_hash
[h
];
1653 e
= s1
->cached_includes
[i
- 1];
1654 if (0 == PATHCMP(e
->filename
, filename
))
1661 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1662 strcpy(e
->filename
, filename
);
1663 e
->ifndef_macro
= e
->once
= 0;
1664 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1665 /* add in hash table */
1666 e
->hash_next
= s1
->cached_includes_hash
[h
];
1667 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1669 printf("adding cached '%s'\n", filename
);
1674 static void pragma_parse(TCCState
*s1
)
1677 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1681 if (next(), tok
!= '(')
1683 if (next(), tok
!= TOK_STR
)
1685 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1686 if (next(), tok
!= ')')
1688 if (t
== TOK_push_macro
) {
1689 while (NULL
== (s
= define_find(v
)))
1690 define_push(v
, 0, NULL
, NULL
);
1691 s
->type
.ref
= s
; /* set push boundary */
1693 for (s
= define_stack
; s
; s
= s
->prev
)
1694 if (s
->v
== v
&& s
->type
.ref
== s
) {
1700 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1702 tcc_warning("unbalanced #pragma pop_macro");
1703 pp_debug_tok
= t
, pp_debug_symv
= v
;
1705 } else if (tok
== TOK_once
) {
1706 search_cached_include(s1
, file
->filename
, 1)->once
= pp_once
;
1708 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1709 /* tcc -E: keep pragmas below unchanged */
1711 unget_tok(TOK_PRAGMA
);
1713 unget_tok(TOK_LINEFEED
);
1715 } else if (tok
== TOK_pack
) {
1717 #pragma pack(1) // set
1718 #pragma pack() // reset to default
1719 #pragma pack(push,1) // push & set
1720 #pragma pack(pop) // restore previous */
1723 if (tok
== TOK_ASM_pop
) {
1725 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1727 tcc_error("out of pack stack");
1729 s1
->pack_stack_ptr
--;
1733 if (tok
== TOK_ASM_push
) {
1735 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1737 s1
->pack_stack_ptr
++;
1740 if (tok
!= TOK_CINT
)
1743 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1747 *s1
->pack_stack_ptr
= val
;
1752 } else if (tok
== TOK_comment
) {
1761 p
= tcc_strdup((char *)tokc
.str
.data
);
1766 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1768 if (t
== TOK_option
)
1769 tcc_set_options(s1
, p
);
1773 } else if (s1
->warn_unsupported
) {
1774 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1779 tcc_error("malformed #pragma directive");
1783 /* is_bof is true if first non space token at beginning of file */
1784 ST_FUNC
void preprocess(int is_bof
)
1786 TCCState
*s1
= tcc_state
;
1787 int i
, c
, n
, saved_parse_flags
;
1791 saved_parse_flags
= parse_flags
;
1792 parse_flags
= PARSE_FLAG_PREPROCESS
1793 | PARSE_FLAG_TOK_NUM
1794 | PARSE_FLAG_TOK_STR
1795 | PARSE_FLAG_LINEFEED
1796 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1805 pp_debug_symv
= tok
;
1811 pp_debug_symv
= tok
;
1812 s
= define_find(tok
);
1813 /* undefine symbol by putting an invalid name */
1818 case TOK_INCLUDE_NEXT
:
1819 ch
= file
->buf_ptr
[0];
1820 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1825 } else if (ch
== '\"') {
1830 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1831 if ((q
- buf
) < sizeof(buf
) - 1)
1834 if (handle_stray_noerror() == 0)
1842 /* eat all spaces and comments after include */
1843 /* XXX: slightly incorrect */
1844 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1849 /* computed #include : concatenate everything up to linefeed,
1850 the result must be one of the two accepted forms.
1851 Don't convert pp-tokens to tokens here. */
1852 parse_flags
= (PARSE_FLAG_PREPROCESS
1853 | PARSE_FLAG_LINEFEED
1854 | (parse_flags
& PARSE_FLAG_ASM_FILE
));
1857 while (tok
!= TOK_LINEFEED
) {
1858 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1862 /* check syntax and remove '<>|""' */
1863 if ((len
< 2 || ((buf
[0] != '"' || buf
[len
-1] != '"') &&
1864 (buf
[0] != '<' || buf
[len
-1] != '>'))))
1865 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1867 memmove(buf
, buf
+ 1, len
- 2);
1868 buf
[len
- 2] = '\0';
1871 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1872 tcc_error("#include recursion too deep");
1873 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
+ 1 : 0;
1874 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1875 for (; i
< n
; ++i
) {
1876 char buf1
[sizeof file
->filename
];
1881 /* check absolute include path */
1882 if (!IS_ABSPATH(buf
))
1886 } else if (i
== 1) {
1887 /* search in file's dir if "header.h" */
1890 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1891 path
= file
->true_filename
;
1892 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1895 /* search in all the include paths */
1896 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1897 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1898 pstrcpy(buf1
, sizeof(buf1
), path
);
1899 pstrcat(buf1
, sizeof(buf1
), "/");
1902 pstrcat(buf1
, sizeof(buf1
), buf
);
1903 e
= search_cached_include(s1
, buf1
, 0);
1904 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
== pp_once
)) {
1905 /* no need to parse the include because the 'ifndef macro'
1906 is defined (or had #pragma once) */
1908 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1913 if (tcc_open(s1
, buf1
) < 0)
1915 /* push previous file on stack */
1916 *s1
->include_stack_ptr
++ = file
->prev
;
1917 file
->include_next_index
= i
;
1919 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1921 /* update target deps */
1923 BufferedFile
*bf
= file
;
1924 while (i
== 1 && (bf
= bf
->prev
))
1925 i
= bf
->include_next_index
;
1926 /* skip system include files */
1927 if (n
- i
> s1
->nb_sysinclude_paths
)
1928 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1931 /* add include file debug info */
1932 tcc_debug_bincl(tcc_state
);
1933 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1934 ch
= file
->buf_ptr
[0];
1937 tcc_error("include file '%s' not found", buf
);
1944 c
= expr_preprocess();
1950 if (tok
< TOK_IDENT
)
1951 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1955 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1957 file
->ifndef_macro
= tok
;
1960 c
= (define_find(tok
) != 0) ^ c
;
1962 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1963 tcc_error("memory full (ifdef)");
1964 *s1
->ifdef_stack_ptr
++ = c
;
1967 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1968 tcc_error("#else without matching #if");
1969 if (s1
->ifdef_stack_ptr
[-1] & 2)
1970 tcc_error("#else after #else");
1971 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1974 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1975 tcc_error("#elif without matching #if");
1976 c
= s1
->ifdef_stack_ptr
[-1];
1978 tcc_error("#elif after #else");
1979 /* last #if/#elif expression was true: we skip */
1983 c
= expr_preprocess();
1984 s1
->ifdef_stack_ptr
[-1] = c
;
1987 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1988 file
->ifndef_macro
= 0;
1997 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1998 tcc_error("#endif without matching #if");
1999 s1
->ifdef_stack_ptr
--;
2000 /* '#ifndef macro' was at the start of file. Now we check if
2001 an '#endif' is exactly at the end of file */
2002 if (file
->ifndef_macro
&&
2003 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2004 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2005 /* need to set to zero to avoid false matches if another
2006 #ifndef at middle of file */
2007 file
->ifndef_macro
= 0;
2008 while (tok
!= TOK_LINEFEED
)
2010 tok_flags
|= TOK_FLAG_ENDIF
;
2015 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
2019 if (tok
!= TOK_CINT
)
2021 tcc_error("wrong #line format");
2025 if (tok
!= TOK_LINEFEED
) {
2026 if (tok
== TOK_STR
) {
2027 if (file
->true_filename
== file
->filename
)
2028 file
->true_filename
= tcc_strdup(file
->filename
);
2029 /* prepend directory from real file */
2030 pstrcpy(buf
, sizeof buf
, file
->true_filename
);
2031 *tcc_basename(buf
) = 0;
2032 pstrcat(buf
, sizeof buf
, (char *)tokc
.str
.data
);
2033 tcc_debug_putfile(s1
, buf
);
2034 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2041 total_lines
+= file
->line_num
- n
;
2047 ch
= file
->buf_ptr
[0];
2050 while (ch
!= '\n' && ch
!= CH_EOF
) {
2051 if ((q
- buf
) < sizeof(buf
) - 1)
2054 if (handle_stray_noerror() == 0)
2061 tcc_error("#error %s", buf
);
2063 tcc_warning("#warning %s", buf
);
2071 /* ignore gas line comment in an 'S' file. */
2072 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
2074 if (tok
== '!' && is_bof
)
2075 /* '!' is ignored at beginning to allow C scripts. */
2077 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2079 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
2082 /* ignore other preprocess commands or #! for C scripts */
2083 while (tok
!= TOK_LINEFEED
)
2086 parse_flags
= saved_parse_flags
;
2089 /* evaluate escape codes in a string. */
2090 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2105 case '0': case '1': case '2': case '3':
2106 case '4': case '5': case '6': case '7':
2107 /* at most three octal digits */
2112 n
= n
* 8 + c
- '0';
2116 n
= n
* 8 + c
- '0';
2121 goto add_char_nonext
;
2122 case 'x': i
= 0; goto parse_hex_or_ucn
;
2123 case 'u': i
= 4; goto parse_hex_or_ucn
;
2124 case 'U': i
= 8; goto parse_hex_or_ucn
;
2130 if (c
>= 'a' && c
<= 'f')
2132 else if (c
>= 'A' && c
<= 'F')
2137 expect("more hex digits in universal-character-name");
2140 goto add_char_nonext
;
2145 cstr_u8cat(outstr
, n
);
2170 goto invalid_escape
;
2180 if (c
>= '!' && c
<= '~')
2181 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2183 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2186 } else if (is_long
&& c
>= 0x80) {
2187 /* assume we are processing UTF-8 sequence */
2188 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2190 int cont
; /* count of continuation bytes */
2191 int skip
; /* how many bytes should skip when error occurred */
2194 /* decode leading byte */
2196 skip
= 1; goto invalid_utf8_sequence
;
2197 } else if (c
<= 0xDF) {
2198 cont
= 1; n
= c
& 0x1f;
2199 } else if (c
<= 0xEF) {
2200 cont
= 2; n
= c
& 0xf;
2201 } else if (c
<= 0xF4) {
2202 cont
= 3; n
= c
& 0x7;
2204 skip
= 1; goto invalid_utf8_sequence
;
2207 /* decode continuation bytes */
2208 for (i
= 1; i
<= cont
; i
++) {
2209 int l
= 0x80, h
= 0xBF;
2211 /* adjust limit for second byte */
2214 case 0xE0: l
= 0xA0; break;
2215 case 0xED: h
= 0x9F; break;
2216 case 0xF0: l
= 0x90; break;
2217 case 0xF4: h
= 0x8F; break;
2221 if (p
[i
] < l
|| p
[i
] > h
) {
2222 skip
= i
; goto invalid_utf8_sequence
;
2225 n
= (n
<< 6) | (p
[i
] & 0x3f);
2228 /* advance pointer */
2231 goto add_char_nonext
;
2233 /* error handling */
2234 invalid_utf8_sequence
:
2235 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c
);
2238 goto add_char_nonext
;
2244 cstr_ccat(outstr
, c
);
2246 #ifdef TCC_TARGET_PE
2247 /* store as UTF-16 */
2249 cstr_wccat(outstr
, c
);
2252 cstr_wccat(outstr
, (c
>> 10) + 0xD800);
2253 cstr_wccat(outstr
, (c
& 0x3FF) + 0xDC00);
2256 cstr_wccat(outstr
, c
);
2260 /* add a trailing '\0' */
2262 cstr_ccat(outstr
, '\0');
2264 cstr_wccat(outstr
, '\0');
2267 static void parse_string(const char *s
, int len
)
2269 uint8_t buf
[1000], *p
= buf
;
2272 if ((is_long
= *s
== 'L'))
2276 if (len
>= sizeof buf
)
2277 p
= tcc_malloc(len
+ 1);
2281 cstr_reset(&tokcstr
);
2282 parse_escape_string(&tokcstr
, p
, is_long
);
2287 int char_size
, i
, n
, c
;
2288 /* XXX: make it portable */
2290 tok
= TOK_CCHAR
, char_size
= 1;
2292 tok
= TOK_LCHAR
, char_size
= sizeof(nwchar_t
);
2293 n
= tokcstr
.size
/ char_size
- 1;
2295 tcc_error("empty character constant");
2297 tcc_warning("multi-character character constant");
2298 for (c
= i
= 0; i
< n
; ++i
) {
2300 c
= ((nwchar_t
*)tokcstr
.data
)[i
];
2302 c
= (c
<< 8) | ((char *)tokcstr
.data
)[i
];
2306 tokc
.str
.size
= tokcstr
.size
;
2307 tokc
.str
.data
= tokcstr
.data
;
2315 /* we use 64 bit numbers */
2318 /* bn = (bn << shift) | or_val */
2319 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2323 for(i
=0;i
<BN_SIZE
;i
++) {
2325 bn
[i
] = (v
<< shift
) | or_val
;
2326 or_val
= v
>> (32 - shift
);
2330 static void bn_zero(unsigned int *bn
)
2333 for(i
=0;i
<BN_SIZE
;i
++) {
2338 /* parse number in null terminated string 'p' and return it in the
2340 static void parse_number(const char *p
)
2342 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2344 unsigned int bn
[BN_SIZE
];
2355 goto float_frac_parse
;
2356 } else if (t
== '0') {
2357 if (ch
== 'x' || ch
== 'X') {
2361 } else if (tcc_state
->tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2367 /* parse all digits. cannot check octal numbers at this stage
2368 because of floating point constants */
2370 if (ch
>= 'a' && ch
<= 'f')
2372 else if (ch
>= 'A' && ch
<= 'F')
2380 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2382 tcc_error("number too long");
2388 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2389 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2391 /* NOTE: strtox should support that for hexa numbers, but
2392 non ISOC99 libcs do not support it, so we prefer to do
2394 /* hexadecimal or binary floats */
2395 /* XXX: handle overflows */
2407 } else if (t
>= 'a') {
2409 } else if (t
>= 'A') {
2414 bn_lshift(bn
, shift
, t
);
2421 if (t
>= 'a' && t
<= 'f') {
2423 } else if (t
>= 'A' && t
<= 'F') {
2425 } else if (t
>= '0' && t
<= '9') {
2431 tcc_error("invalid digit");
2432 bn_lshift(bn
, shift
, t
);
2437 if (ch
!= 'p' && ch
!= 'P')
2444 } else if (ch
== '-') {
2448 if (ch
< '0' || ch
> '9')
2449 expect("exponent digits");
2450 while (ch
>= '0' && ch
<= '9') {
2451 exp_val
= exp_val
* 10 + ch
- '0';
2454 exp_val
= exp_val
* s
;
2456 /* now we can generate the number */
2457 /* XXX: should patch directly float number */
2458 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2459 d
= ldexp(d
, exp_val
- frac_bits
);
2464 /* float : should handle overflow */
2466 } else if (t
== 'L') {
2468 #ifdef TCC_TARGET_PE
2473 /* XXX: not large enough */
2474 tokc
.ld
= (long double)d
;
2481 /* decimal floats */
2483 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2488 while (ch
>= '0' && ch
<= '9') {
2489 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2495 if (ch
== 'e' || ch
== 'E') {
2496 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2500 if (ch
== '-' || ch
== '+') {
2501 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2506 if (ch
< '0' || ch
> '9')
2507 expect("exponent digits");
2508 while (ch
>= '0' && ch
<= '9') {
2509 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2521 tokc
.f
= strtof(token_buf
, NULL
);
2522 } else if (t
== 'L') {
2524 #ifdef TCC_TARGET_PE
2526 tokc
.d
= strtod(token_buf
, NULL
);
2529 tokc
.ld
= strtold(token_buf
, NULL
);
2533 tokc
.d
= strtod(token_buf
, NULL
);
2537 unsigned long long n
, n1
;
2538 int lcount
, ucount
, ov
= 0;
2541 /* integer number */
2544 if (b
== 10 && *q
== '0') {
2551 /* no need for checks except for base 10 / 8 errors */
2561 tcc_error("invalid digit");
2564 /* detect overflow */
2565 if (n1
>= 0x1000000000000000ULL
&& n
/ b
!= n1
)
2569 /* Determine the characteristics (unsigned and/or 64bit) the type of
2570 the constant must have according to the constant suffix(es) */
2571 lcount
= ucount
= 0;
2577 tcc_error("three 'l's in integer constant");
2578 if (lcount
&& *(p
- 1) != ch
)
2579 tcc_error("incorrect integer suffix: %s", p1
);
2582 } else if (t
== 'U') {
2584 tcc_error("two 'u's in integer constant");
2592 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2593 if (ucount
== 0 && b
== 10) {
2594 if (lcount
<= (LONG_SIZE
== 4)) {
2595 if (n
>= 0x80000000U
)
2596 lcount
= (LONG_SIZE
== 4) + 1;
2598 if (n
>= 0x8000000000000000ULL
)
2601 if (lcount
<= (LONG_SIZE
== 4)) {
2602 if (n
>= 0x100000000ULL
)
2603 lcount
= (LONG_SIZE
== 4) + 1;
2604 else if (n
>= 0x80000000U
)
2607 if (n
>= 0x8000000000000000ULL
)
2612 tcc_warning("integer constant overflow");
2621 ++tok
; /* TOK_CU... */
2625 tcc_error("invalid number");
2629 #define PARSE2(c1, tok1, c2, tok2) \
2640 /* return next token without macro substitution */
2641 static inline void next_nomacro1(void)
2643 int t
, c
, is_long
, len
;
2657 if (parse_flags
& PARSE_FLAG_SPACES
)
2658 goto keep_tok_flags
;
2659 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2668 /* first look if it is in fact an end of buffer */
2669 c
= handle_stray1(p
);
2676 TCCState
*s1
= tcc_state
;
2677 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2678 && !(tok_flags
& TOK_FLAG_EOF
)) {
2679 tok_flags
|= TOK_FLAG_EOF
;
2681 goto keep_tok_flags
;
2682 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2684 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2685 tcc_error("missing #endif");
2686 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2687 /* no include left : end of file. */
2690 tok_flags
&= ~TOK_FLAG_EOF
;
2691 /* pop include file */
2693 /* test if previous '#endif' was after a #ifdef at
2695 if (tok_flags
& TOK_FLAG_ENDIF
) {
2697 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2699 search_cached_include(s1
, file
->filename
, 1)
2700 ->ifndef_macro
= file
->ifndef_macro_saved
;
2701 tok_flags
&= ~TOK_FLAG_ENDIF
;
2704 /* add end of include file debug info */
2705 tcc_debug_eincl(tcc_state
);
2706 /* pop include stack */
2708 s1
->include_stack_ptr
--;
2710 if (p
== file
->buffer
)
2711 tok_flags
= TOK_FLAG_BOF
|TOK_FLAG_BOL
;
2719 tok_flags
|= TOK_FLAG_BOL
;
2722 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2725 goto keep_tok_flags
;
2730 if ((tok_flags
& TOK_FLAG_BOL
) &&
2731 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2733 preprocess(tok_flags
& TOK_FLAG_BOF
);
2739 tok
= TOK_TWOSHARPS
;
2741 #if !defined(TCC_TARGET_ARM)
2742 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2743 p
= parse_line_comment(p
- 1);
2754 /* dollar is allowed to start identifiers when not parsing asm */
2756 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2757 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2760 case 'a': case 'b': case 'c': case 'd':
2761 case 'e': case 'f': case 'g': case 'h':
2762 case 'i': case 'j': case 'k': case 'l':
2763 case 'm': case 'n': case 'o': case 'p':
2764 case 'q': case 'r': case 's': case 't':
2765 case 'u': case 'v': case 'w': case 'x':
2767 case 'A': case 'B': case 'C': case 'D':
2768 case 'E': case 'F': case 'G': case 'H':
2769 case 'I': case 'J': case 'K':
2770 case 'M': case 'N': case 'O': case 'P':
2771 case 'Q': case 'R': case 'S': case 'T':
2772 case 'U': case 'V': case 'W': case 'X':
2778 h
= TOK_HASH_FUNC(h
, c
);
2779 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2780 h
= TOK_HASH_FUNC(h
, c
);
2785 /* fast case : no stray found, so we have the full token
2786 and we have already hashed it */
2787 h
&= (TOK_HASH_SIZE
- 1);
2788 pts
= &hash_ident
[h
];
2793 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2795 pts
= &(ts
->hash_next
);
2797 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2801 cstr_reset(&tokcstr
);
2802 cstr_cat(&tokcstr
, (char *) p1
, len
);
2806 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2808 cstr_ccat(&tokcstr
, c
);
2811 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2817 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2819 goto parse_ident_fast
;
2822 if (c
== '\'' || c
== '\"') {
2826 cstr_reset(&tokcstr
);
2827 cstr_ccat(&tokcstr
, 'L');
2828 goto parse_ident_slow
;
2833 case '0': case '1': case '2': case '3':
2834 case '4': case '5': case '6': case '7':
2838 /* after the first digit, accept digits, alpha, '.' or sign if
2839 prefixed by 'eEpP' */
2841 cstr_reset(&tokcstr
);
2843 cstr_ccat(&tokcstr
, t
);
2844 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2846 || ((c
== '+' || c
== '-')
2847 && (((t
== 'e' || t
== 'E')
2848 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2849 /* 0xe+1 is 3 tokens in asm */
2850 && ((char*)tokcstr
.data
)[0] == '0'
2851 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2852 || t
== 'p' || t
== 'P'))))
2857 /* We add a trailing '\0' to ease parsing */
2858 cstr_ccat(&tokcstr
, '\0');
2859 tokc
.str
.size
= tokcstr
.size
;
2860 tokc
.str
.data
= tokcstr
.data
;
2865 /* special dot handling because it can also start a number */
2870 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2871 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2873 goto parse_ident_fast
;
2874 } else if (c
== '.') {
2880 *--p
= '.'; /* may underflow into file->unget[] */
2891 cstr_reset(&tokcstr
);
2893 cstr_ccat(&tokcstr
, 'L');
2894 cstr_ccat(&tokcstr
, c
);
2895 p
= parse_pp_string(p
, c
, &tokcstr
);
2896 cstr_ccat(&tokcstr
, c
);
2897 cstr_ccat(&tokcstr
, '\0');
2898 tokc
.str
.size
= tokcstr
.size
;
2899 tokc
.str
.data
= tokcstr
.data
;
2908 } else if (c
== '<') {
2925 } else if (c
== '>') {
2943 } else if (c
== '=') {
2956 } else if (c
== '=') {
2969 } else if (c
== '=') {
2982 } else if (c
== '=') {
2985 } else if (c
== '>') {
2993 PARSE2('!', '!', '=', TOK_NE
)
2994 PARSE2('=', '=', '=', TOK_EQ
)
2995 PARSE2('*', '*', '=', TOK_A_MUL
)
2996 PARSE2('%', '%', '=', TOK_A_MOD
)
2997 PARSE2('^', '^', '=', TOK_A_XOR
)
2999 /* comments or operator */
3003 p
= parse_comment(p
);
3004 /* comments replaced by a blank */
3007 } else if (c
== '/') {
3008 p
= parse_line_comment(p
);
3011 } else if (c
== '=') {
3031 case '@': /* only used in assembler */
3037 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
3038 goto parse_ident_fast
;
3039 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
3041 tcc_error("unrecognized character \\x%02x", c
);
3047 #if defined(PARSE_DEBUG)
3048 printf("token = %d %s\n", tok
, get_tok_str(tok
, &tokc
));
3052 static void macro_subst(
3053 TokenString
*tok_str
,
3055 const int *macro_str
3058 /* substitute arguments in replacement lists in macro_str by the values in
3059 args (field d) and return allocated string */
3060 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
3072 TOK_GET(&t
, ¯o_str
, &cval
);
3077 TOK_GET(&t
, ¯o_str
, &cval
);
3080 s
= sym_find2(args
, t
);
3083 cstr_ccat(&cstr
, '\"');
3087 TOK_GET(&t
, &st
, &cval
);
3088 if (t
!= TOK_PLCHLDR
3090 && 0 == check_space(t
, &spc
)) {
3091 const char *s
= get_tok_str(t
, &cval
);
3093 if (t
== TOK_PPSTR
&& *s
!= '\'')
3094 add_char(&cstr
, *s
);
3096 cstr_ccat(&cstr
, *s
);
3102 cstr_ccat(&cstr
, '\"');
3103 cstr_ccat(&cstr
, '\0');
3105 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
3108 cval
.str
.size
= cstr
.size
;
3109 cval
.str
.data
= cstr
.data
;
3110 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
3114 expect("macro parameter after '#'");
3116 } else if (t
>= TOK_IDENT
) {
3117 s
= sym_find2(args
, t
);
3121 /* if '##' is present before or after, no arg substitution */
3122 if (*macro_str
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
3123 /* special case for var arg macros : ## eats the ','
3124 if empty VA_ARGS variable. */
3125 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
3127 /* suppress ',' '##' */
3130 /* suppress '##' and add variable */
3138 /* Expand arguments tokens and store them. In most
3139 cases we could also re-expand each argument if
3140 used multiple times, but not if the argument
3141 contains the __COUNTER__ macro. */
3143 sym_push2(&s
->next
, s
->v
, s
->type
.t
, 0);
3145 macro_subst(&str2
, nested_list
, st
);
3146 tok_str_add(&str2
, 0);
3147 s
->next
->d
= str2
.str
;
3153 TOK_GET(&t2
, &st
, &cval
);
3156 tok_str_add2(&str
, t2
, &cval
);
3158 if (str
.len
== l0
) /* expanded to empty string */
3159 tok_str_add(&str
, TOK_PLCHLDR
);
3161 tok_str_add(&str
, t
);
3164 tok_str_add2(&str
, t
, &cval
);
3168 tok_str_add(&str
, 0);
3172 static char const ab_month_name
[12][4] =
3174 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3175 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3178 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3184 if (t1
!= TOK_PLCHLDR
)
3185 cstr_cat(&cstr
, get_tok_str(t1
, v1
), -1);
3187 if (t2
!= TOK_PLCHLDR
)
3188 cstr_cat(&cstr
, get_tok_str(t2
, v2
), -1);
3189 cstr_ccat(&cstr
, '\0');
3191 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3192 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3196 if (0 == *file
->buf_ptr
)
3200 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3201 " preprocessing token", n
, (char *)cstr
.data
, (char*)cstr
.data
+ n
);
3206 //printf("paste <%s>\n", (char*)cstr.data);
3211 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3212 return the resulting string (which must be freed). */
3213 static inline int *macro_twosharps(const int *ptr0
)
3217 TokenString macro_str1
;
3218 int start_of_nosubsts
= -1;
3221 /* we search the first '##' */
3222 for (ptr
= ptr0
;;) {
3223 TOK_GET(&t
, &ptr
, &cval
);
3224 if (t
== TOK_PPJOIN
)
3230 tok_str_new(¯o_str1
);
3232 //tok_print(" $$$", ptr0);
3233 for (ptr
= ptr0
;;) {
3234 TOK_GET(&t
, &ptr
, &cval
);
3237 if (t
== TOK_PPJOIN
)
3239 while (*ptr
== TOK_PPJOIN
) {
3241 /* given 'a##b', remove nosubsts preceding 'a' */
3242 if (start_of_nosubsts
>= 0)
3243 macro_str1
.len
= start_of_nosubsts
;
3244 /* given 'a##b', remove nosubsts preceding 'b' */
3245 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3247 if (t1
&& t1
!= TOK_PPJOIN
) {
3248 TOK_GET(&t1
, &ptr
, &cv1
);
3249 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3250 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3251 t
= tok
, cval
= tokc
;
3253 tok_str_add2(¯o_str1
, t
, &cval
);
3259 if (t
== TOK_NOSUBST
) {
3260 if (start_of_nosubsts
< 0)
3261 start_of_nosubsts
= macro_str1
.len
;
3263 start_of_nosubsts
= -1;
3265 tok_str_add2(¯o_str1
, t
, &cval
);
3267 tok_str_add(¯o_str1
, 0);
3268 //tok_print(" ###", macro_str1.str);
3269 return macro_str1
.str
;
3272 /* peek or read [ws_str == NULL] next token from function macro call,
3273 walking up macro levels up to the file if necessary */
3274 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3282 p
= macro_ptr
, t
= *p
;
3284 while (is_space(t
) || TOK_LINEFEED
== t
|| TOK_PLCHLDR
== t
)
3285 tok_str_add(ws_str
, t
), t
= *++p
;
3289 /* also, end of scope for nested defined symbol */
3291 while (sa
&& sa
->v
== 0)
3300 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3303 uint8_t *p
= file
->buf_ptr
;
3306 p
= parse_comment(p
);
3307 file
->buf_ptr
= p
- 1;
3308 } else if (c
== '/') {
3309 p
= parse_line_comment(p
);
3310 file
->buf_ptr
= p
- 1;
3317 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3318 tok_str_add(ws_str
, ch
);
3332 /* do macro substitution of current token with macro 's' and add
3333 result to (tok_str,tok_len). 'nested_list' is the list of all
3334 macros we got inside to avoid recursing. Return non zero if no
3335 substitution needs to be done */
3336 static int macro_subst_tok(
3337 TokenString
*tok_str
,
3341 Sym
*args
, *sa
, *sa1
;
3342 int parlevel
, t
, t1
, spc
;
3349 /* if symbol is a macro, prepare substitution */
3350 /* special macros */
3351 if (tok
== TOK___LINE__
|| tok
== TOK___COUNTER__
) {
3352 t
= tok
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3353 snprintf(buf
, sizeof(buf
), "%d", t
);
3357 } else if (tok
== TOK___FILE__
) {
3358 cstrval
= file
->filename
;
3360 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3365 tm
= localtime(&ti
);
3366 if (tok
== TOK___DATE__
) {
3367 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3368 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3370 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3371 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3378 cstr_cat(&cstr
, cstrval
, 0);
3379 cval
.str
.size
= cstr
.size
;
3380 cval
.str
.data
= cstr
.data
;
3381 tok_str_add2(tok_str
, t1
, &cval
);
3384 int saved_parse_flags
= parse_flags
;
3385 int *joined_str
= NULL
;
3388 if (s
->type
.t
== MACRO_FUNC
) {
3389 /* whitespace between macro name and argument list */
3391 tok_str_new(&ws_str
);
3394 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3395 | PARSE_FLAG_ACCEPT_STRAYS
;
3397 /* get next token from argument stream */
3398 t
= next_argstream(nested_list
, &ws_str
);
3400 /* not a macro substitution after all, restore the
3401 * macro token plus all whitespace we've read.
3402 * whitespace is intentionally not merged to preserve
3404 parse_flags
= saved_parse_flags
;
3405 tok_str_add(tok_str
, tok
);
3406 if (parse_flags
& PARSE_FLAG_SPACES
) {
3408 for (i
= 0; i
< ws_str
.len
; i
++)
3409 tok_str_add(tok_str
, ws_str
.str
[i
]);
3411 tok_str_free_str(ws_str
.str
);
3414 tok_str_free_str(ws_str
.str
);
3417 next_nomacro(); /* eat '(' */
3418 } while (tok
== TOK_PLCHLDR
|| is_space(tok
));
3420 /* argument macro */
3423 /* NOTE: empty args are allowed, except if no args */
3426 next_argstream(nested_list
, NULL
);
3427 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3429 /* handle '()' case */
3430 if (!args
&& !sa
&& tok
== ')')
3433 tcc_error("macro '%s' used with too many args",
3434 get_tok_str(s
->v
, 0));
3437 /* NOTE: non zero sa->t indicates VA_ARGS */
3438 while ((parlevel
> 0 ||
3440 (tok
!= ',' || sa
->type
.t
)))) {
3441 if (tok
== TOK_EOF
|| tok
== 0)
3445 else if (tok
== ')')
3447 if (tok
== TOK_LINEFEED
)
3449 if (!check_space(tok
, &spc
))
3450 tok_str_add2(&str
, tok
, &tokc
);
3451 next_argstream(nested_list
, NULL
);
3456 tok_str_add(&str
, -1);
3457 tok_str_add(&str
, 0);
3458 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3462 /* special case for gcc var args: add an empty
3463 var arg argument if it is omitted */
3464 if (sa
&& sa
->type
.t
&& gnu_ext
)
3472 tcc_error("macro '%s' used with too few args",
3473 get_tok_str(s
->v
, 0));
3476 /* now subst each arg */
3477 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3482 tok_str_free_str(sa
->d
);
3484 tok_str_free_str(sa
->next
->d
);
3490 parse_flags
= saved_parse_flags
;
3493 sym_push2(nested_list
, s
->v
, 0, 0);
3494 parse_flags
= saved_parse_flags
;
3495 joined_str
= macro_twosharps(mstr
);
3496 macro_subst(tok_str
, nested_list
, joined_str
? joined_str
: mstr
);
3498 /* pop nested defined symbol */
3500 *nested_list
= sa1
->prev
;
3503 tok_str_free_str(joined_str
);
3505 tok_str_free_str(mstr
);
3510 /* do macro substitution of macro_str and add result to
3511 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3512 inside to avoid recursing. */
3513 static void macro_subst(
3514 TokenString
*tok_str
,
3516 const int *macro_str
3520 int t
, spc
, nosubst
;
3526 TOK_GET(&t
, ¯o_str
, &cval
);
3530 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3535 /* if nested substitution, do nothing */
3536 if (sym_find2(*nested_list
, t
)) {
3537 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3538 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3543 TokenString
*str
= tok_str_alloc();
3544 str
->str
= (int*)macro_str
;
3545 begin_macro(str
, 2);
3548 macro_subst_tok(tok_str
, nested_list
, s
);
3550 if (macro_stack
!= str
) {
3551 /* already finished by reading function macro arguments */
3555 macro_str
= macro_ptr
;
3559 spc
= is_space(t
= tok_str
->str
[tok_str
->lastlen
]);
3562 if (!check_space(t
, &spc
))
3563 tok_str_add2(tok_str
, t
, &cval
);
3566 if (nosubst
> 1 && (spc
|| (++nosubst
== 3 && t
== '(')))
3570 if (t
== TOK_NOSUBST
)
3573 /* GCC supports 'defined' as result of a macro substitution */
3574 if (t
== TOK_DEFINED
&& pp_expr
)
3579 /* return next token without macro substitution. Can read input from
3581 static void next_nomacro(void)
3587 if (TOK_HAS_VALUE(t
)) {
3588 tok_get(&tok
, ¯o_ptr
, &tokc
);
3589 if (t
== TOK_LINENUM
) {
3590 file
->line_num
= tokc
.i
;
3595 if (t
< TOK_IDENT
) {
3596 if (!(parse_flags
& PARSE_FLAG_SPACES
)
3597 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
))
3607 /* return next token with macro substitution */
3608 ST_FUNC
void next(void)
3615 if (!TOK_HAS_VALUE(t
)) {
3616 if (t
== TOK_NOSUBST
|| t
== TOK_PLCHLDR
) {
3617 /* discard preprocessor markers */
3619 } else if (t
== 0) {
3620 /* end of macro or unget token string */
3623 } else if (t
== '\\') {
3624 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3625 tcc_error("stray '\\' in program");
3629 } else if (t
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3630 /* if reading from file, try to substitute macros */
3631 Sym
*s
= define_find(t
);
3633 Sym
*nested_list
= NULL
;
3635 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3636 tok_str_add(&tokstr_buf
, 0);
3637 begin_macro(&tokstr_buf
, 0);
3642 /* convert preprocessor tokens into C tokens */
3643 if (t
== TOK_PPNUM
) {
3644 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3645 parse_number((char *)tokc
.str
.data
);
3646 } else if (t
== TOK_PPSTR
) {
3647 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3648 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3652 /* push back current token and set current token to 'last_tok'. Only
3653 identifier case handled for labels. */
3654 ST_INLN
void unget_tok(int last_tok
)
3657 TokenString
*str
= tok_str_alloc();
3658 tok_str_add2(str
, tok
, &tokc
);
3659 tok_str_add(str
, 0);
3660 begin_macro(str
, 1);
3664 /* ------------------------------------------------------------------------- */
3665 /* init preprocessor */
3667 static const char * const target_os_defs
=
3668 #ifdef TCC_TARGET_PE
3674 # if defined TCC_TARGET_MACHO
3676 # elif TARGETOS_FreeBSD
3678 # elif TARGETOS_FreeBSD_kernel
3679 "__FreeBSD_kernel__\0"
3680 # elif TARGETOS_NetBSD
3682 # elif TARGETOS_OpenBSD
3693 static void putdef(CString
*cs
, const char *p
)
3695 cstr_printf(cs
, "#define %s%s\n", p
, &" 1"[!!strchr(p
, ' ')*2]);
3698 static void tcc_predefs(TCCState
*s1
, CString
*cs
, int is_asm
)
3701 const char *defs
[] = { target_machine_defs
, target_os_defs
, NULL
};
3704 sscanf(TCC_VERSION
, "%d.%d.%d", &a
, &b
, &c
);
3705 cstr_printf(cs
, "#define __TINYC__ %d\n", a
*10000 + b
*100 + c
);
3706 for (a
= 0; defs
[a
]; ++a
)
3707 for (p
= defs
[a
]; *p
; p
= strchr(p
, 0) + 1)
3709 #ifdef TCC_TARGET_ARM
3710 if (s1
->float_abi
== ARM_HARD_FLOAT
)
3711 putdef(cs
, "__ARM_PCS_VFP");
3714 putdef(cs
, "__ASSEMBLER__");
3715 if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
)
3716 putdef(cs
, "__TCC_PP__");
3717 if (s1
->output_type
== TCC_OUTPUT_MEMORY
)
3718 putdef(cs
, "__TCC_RUN__");
3719 if (s1
->char_is_unsigned
)
3720 putdef(cs
, "__CHAR_UNSIGNED__");
3721 if (s1
->optimize
> 0)
3722 putdef(cs
, "__OPTIMIZE__");
3723 if (s1
->option_pthread
)
3724 putdef(cs
, "_REENTRANT");
3725 if (s1
->leading_underscore
)
3726 putdef(cs
, "__leading_underscore");
3727 #ifdef CONFIG_TCC_BCHECK
3728 if (s1
->do_bounds_check
)
3729 putdef(cs
, "__BOUNDS_CHECKING_ON");
3731 cstr_printf(cs
, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE
);
3732 cstr_printf(cs
, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE
);
3734 putdef(cs
, "__STDC__");
3735 cstr_printf(cs
, "#define __STDC_VERSION__ %dL\n", s1
->cversion
);
3737 /* load more predefs and __builtins */
3738 #if CONFIG_TCC_PREDEFS
3739 #include "tccdefs_.h" /* include as strings */
3741 "#include <tccdefs.h>\n" /* load at runtime */
3745 cstr_printf(cs
, "#define __BASE_FILE__ \"%s\"\n", file
->filename
);
3748 ST_FUNC
void preprocess_start(TCCState
*s1
, int filetype
)
3750 int is_asm
= !!(filetype
& (AFF_TYPE_ASM
|AFF_TYPE_ASMPP
));
3755 s1
->include_stack_ptr
= s1
->include_stack
;
3756 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3757 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3760 pp_debug_tok
= pp_debug_symv
= 0;
3762 s1
->pack_stack
[0] = 0;
3763 s1
->pack_stack_ptr
= s1
->pack_stack
;
3765 set_idnum('$', !is_asm
&& s1
->dollars_in_identifiers
? IS_ID
: 0);
3766 set_idnum('.', is_asm
? IS_ID
: 0);
3768 if (!(filetype
& AFF_TYPE_ASM
)) {
3770 tcc_predefs(s1
, &cstr
, is_asm
);
3771 if (s1
->cmdline_defs
.size
)
3772 cstr_cat(&cstr
, s1
->cmdline_defs
.data
, s1
->cmdline_defs
.size
);
3773 if (s1
->cmdline_incl
.size
)
3774 cstr_cat(&cstr
, s1
->cmdline_incl
.data
, s1
->cmdline_incl
.size
);
3775 //printf("%s\n", (char*)cstr.data);
3776 *s1
->include_stack_ptr
++ = file
;
3777 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3778 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3782 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3783 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3786 /* cleanup from error/setjmp */
3787 ST_FUNC
void preprocess_end(TCCState
*s1
)
3797 ST_FUNC
void tccpp_new(TCCState
*s
)
3802 /* init isid table */
3803 for(i
= CH_EOF
; i
<128; i
++)
3805 is_space(i
) ? IS_SPC
3810 for(i
= 128; i
<256; i
++)
3811 set_idnum(i
, IS_ID
);
3813 /* init allocators */
3814 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3815 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3817 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3818 memset(s
->cached_includes_hash
, 0, sizeof s
->cached_includes_hash
);
3820 cstr_new(&cstr_buf
);
3821 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3822 tok_str_new(&tokstr_buf
);
3823 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3825 tok_ident
= TOK_IDENT
;
3834 tok_alloc(p
, r
- p
- 1);
3838 /* we add dummy defines for some special macros to speed up tests
3839 and to have working defined() */
3840 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
3841 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
3842 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
3843 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
3844 define_push(TOK___COUNTER__
, MACRO_OBJ
, NULL
, NULL
);
3847 ST_FUNC
void tccpp_delete(TCCState
*s
)
3851 dynarray_reset(&s
->cached_includes
, &s
->nb_cached_includes
);
3854 n
= tok_ident
- TOK_IDENT
;
3855 if (n
> total_idents
)
3857 for(i
= 0; i
< n
; i
++)
3858 tal_free(toksym_alloc
, table_ident
[i
]);
3859 tcc_free(table_ident
);
3862 /* free static buffers */
3863 cstr_free(&tokcstr
);
3864 cstr_free(&cstr_buf
);
3865 cstr_free(¯o_equal_buf
);
3866 tok_str_free_str(tokstr_buf
.str
);
3868 /* free allocators */
3869 tal_delete(toksym_alloc
);
3870 toksym_alloc
= NULL
;
3871 tal_delete(tokstr_alloc
);
3872 tokstr_alloc
= NULL
;
3875 /* ------------------------------------------------------------------------- */
3876 /* tcc -E [-P[1]] [-dD} support */
3878 static void tok_print(const char *msg
, const int *str
)
3884 fp
= tcc_state
->ppfp
;
3885 fprintf(fp
, "%s", msg
);
3887 TOK_GET(&t
, &str
, &cval
);
3890 fprintf(fp
, &" %s"[s
], get_tok_str(t
, &cval
)), s
= 1;
3895 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3897 int d
= f
->line_num
- f
->line_ref
;
3902 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3904 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3906 fputs("\n", s1
->ppfp
), --d
;
3907 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3908 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3910 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3911 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3913 f
->line_ref
= f
->line_num
;
3916 static void define_print(TCCState
*s1
, int v
)
3922 if (NULL
== s
|| NULL
== s
->d
)
3926 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3927 if (s
->type
.t
== MACRO_FUNC
) {
3932 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3939 tok_print("", s
->d
);
3942 static void pp_debug_defines(TCCState
*s1
)
3953 pp_line(s1
, file
, 0);
3954 file
->line_ref
= ++file
->line_num
;
3958 vs
= get_tok_str(v
, NULL
);
3959 if (t
== TOK_DEFINE
) {
3960 define_print(s1
, v
);
3961 } else if (t
== TOK_UNDEF
) {
3962 fprintf(fp
, "#undef %s\n", vs
);
3963 } else if (t
== TOK_push_macro
) {
3964 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3965 } else if (t
== TOK_pop_macro
) {
3966 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3971 static void pp_debug_builtins(TCCState
*s1
)
3974 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3975 define_print(s1
, v
);
3978 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3979 static int pp_need_space(int a
, int b
)
3981 return 'E' == a
? '+' == b
|| '-' == b
3982 : '+' == a
? TOK_INC
== b
|| '+' == b
3983 : '-' == a
? TOK_DEC
== b
|| '-' == b
3984 : a
>= TOK_IDENT
? b
>= TOK_IDENT
3985 : a
== TOK_PPNUM
? b
>= TOK_IDENT
3989 /* maybe hex like 0x1e */
3990 static int pp_check_he0xE(int t
, const char *p
)
3992 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3997 /* Preprocess the current file */
3998 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
4000 BufferedFile
**iptr
;
4001 int token_seen
, spcs
, level
;
4005 parse_flags
= PARSE_FLAG_PREPROCESS
4006 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
4007 | PARSE_FLAG_LINEFEED
4009 | PARSE_FLAG_ACCEPT_STRAYS
4011 /* Credits to Fabrice Bellard's initial revision to demonstrate its
4012 capability to compile and run itself, provided all numbers are
4013 given as decimals. tcc -E -P10 will do. */
4014 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
4015 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
4018 /* for PP benchmarks */
4019 do next(); while (tok
!= TOK_EOF
);
4023 if (s1
->dflag
& 1) {
4024 pp_debug_builtins(s1
);
4028 token_seen
= TOK_LINEFEED
, spcs
= 0, level
= 0;
4030 pp_line(s1
, file
->prev
, level
++);
4031 pp_line(s1
, file
, level
);
4033 iptr
= s1
->include_stack_ptr
;
4038 level
= s1
->include_stack_ptr
- iptr
;
4041 pp_line(s1
, *iptr
, 0);
4042 pp_line(s1
, file
, level
);
4044 if (s1
->dflag
& 7) {
4045 pp_debug_defines(s1
);
4050 if (is_space(tok
)) {
4051 if (spcs
< sizeof white
- 1)
4052 white
[spcs
++] = tok
;
4054 } else if (tok
== TOK_LINEFEED
) {
4056 if (token_seen
== TOK_LINEFEED
)
4059 } else if (token_seen
== TOK_LINEFEED
) {
4060 pp_line(s1
, file
, 0);
4061 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
4062 white
[spcs
++] = ' ';
4065 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
4066 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
4067 token_seen
= pp_check_he0xE(tok
, p
);
4072 /* ------------------------------------------------------------------------- */