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_vprintf(CString
*cstr
, const char *fmt
, va_list ap
)
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
)
427 ST_FUNC
int cstr_printf(CString
*cstr
, const char *fmt
, ...)
431 len
= cstr_vprintf(cstr
, fmt
, ap
);
437 static void add_char(CString
*cstr
, int c
)
439 if (c
== '\'' || c
== '\"' || c
== '\\') {
440 /* XXX: could be more precise if char or string */
441 cstr_ccat(cstr
, '\\');
443 if (c
>= 32 && c
<= 126) {
446 cstr_ccat(cstr
, '\\');
448 cstr_ccat(cstr
, 'n');
450 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
451 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
452 cstr_ccat(cstr
, '0' + (c
& 7));
457 /* ------------------------------------------------------------------------- */
458 /* allocate a new token */
459 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
461 TokenSym
*ts
, **ptable
;
464 if (tok_ident
>= SYM_FIRST_ANOM
)
465 tcc_error("memory full (symbols)");
467 /* expand token table if needed */
468 i
= tok_ident
- TOK_IDENT
;
469 if ((i
% TOK_ALLOC_INCR
) == 0) {
470 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
471 table_ident
= ptable
;
474 ts
= tal_realloc(toksym_alloc
, 0, sizeof(TokenSym
) + len
);
476 ts
->tok
= tok_ident
++;
477 ts
->sym_define
= NULL
;
478 ts
->sym_label
= NULL
;
479 ts
->sym_struct
= NULL
;
480 ts
->sym_identifier
= NULL
;
482 ts
->hash_next
= NULL
;
483 memcpy(ts
->str
, str
, len
);
489 #define TOK_HASH_INIT 1
490 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
493 /* find a token and add it if not found */
494 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
502 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
503 h
&= (TOK_HASH_SIZE
- 1);
505 pts
= &hash_ident
[h
];
510 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
512 pts
= &(ts
->hash_next
);
514 return tok_alloc_new(pts
, str
, len
);
517 ST_FUNC
int tok_alloc_const(const char *str
)
519 return tok_alloc(str
, strlen(str
))->tok
;
523 /* XXX: buffer overflow */
524 /* XXX: float tokens */
525 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
530 cstr_reset(&cstr_buf
);
540 /* XXX: not quite exact, but only useful for testing */
542 sprintf(p
, "%u", (unsigned)cv
->i
);
544 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
548 cstr_ccat(&cstr_buf
, 'L');
550 cstr_ccat(&cstr_buf
, '\'');
551 add_char(&cstr_buf
, cv
->i
);
552 cstr_ccat(&cstr_buf
, '\'');
553 cstr_ccat(&cstr_buf
, '\0');
557 return (char*)cv
->str
.data
;
559 cstr_ccat(&cstr_buf
, 'L');
561 cstr_ccat(&cstr_buf
, '\"');
563 len
= cv
->str
.size
- 1;
565 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
567 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
569 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
571 cstr_ccat(&cstr_buf
, '\"');
572 cstr_ccat(&cstr_buf
, '\0');
576 cstr_cat(&cstr_buf
, "<float>", 0);
579 cstr_cat(&cstr_buf
, "<double>", 0);
582 cstr_cat(&cstr_buf
, "<long double>", 0);
585 cstr_cat(&cstr_buf
, "<linenumber>", 0);
588 /* above tokens have value, the ones below don't */
596 return strcpy(p
, "...");
598 return strcpy(p
, "<<=");
600 return strcpy(p
, ">>=");
602 return strcpy(p
, "<eof>");
605 /* search in two bytes table */
606 const unsigned char *q
= tok_two_chars
;
612 return cstr_buf
.data
;
617 sprintf(cstr_buf
.data
, "<%02x>", v
);
618 return cstr_buf
.data
;
622 case 0: /* nameless anonymous symbol */
624 } else if (v
< tok_ident
) {
625 return table_ident
[v
- TOK_IDENT
]->str
;
626 } else if (v
>= SYM_FIRST_ANOM
) {
627 /* special name for anonymous symbol */
628 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
630 /* should never happen */
635 return cstr_buf
.data
;
638 /* return the current character, handling end of block if necessary
640 static int handle_eob(void)
642 BufferedFile
*bf
= file
;
645 /* only tries to read if really end of buffer */
646 if (bf
->buf_ptr
>= bf
->buf_end
) {
648 #if defined(PARSE_DEBUG)
653 len
= read(bf
->fd
, bf
->buffer
, len
);
660 bf
->buf_ptr
= bf
->buffer
;
661 bf
->buf_end
= bf
->buffer
+ len
;
662 *bf
->buf_end
= CH_EOB
;
664 if (bf
->buf_ptr
< bf
->buf_end
) {
665 return bf
->buf_ptr
[0];
667 bf
->buf_ptr
= bf
->buf_end
;
672 /* read next char from current input file and handle end of input buffer */
673 static inline void inp(void)
675 ch
= *(++(file
->buf_ptr
));
676 /* end of buffer/file handling */
681 /* handle '\[\r]\n' */
682 static int handle_stray_noerror(void)
689 } else if (ch
== '\r') {
703 static void handle_stray(void)
705 if (handle_stray_noerror())
706 tcc_error("stray '\\' in program");
709 /* skip the stray and handle the \\n case. Output an error if
710 incorrect char after the stray */
711 static int handle_stray1(uint8_t *p
)
716 if (p
>= file
->buf_end
) {
723 if (handle_stray_noerror()) {
724 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
725 tcc_error("stray '\\' in program");
726 *--file
->buf_ptr
= '\\';
733 /* handle just the EOB case, but not stray */
734 #define PEEKC_EOB(c, p)\
745 /* handle the complicated stray case */
751 c = handle_stray1(p);\
756 /* input with '\[\r]\n' handling. Note that this function cannot
757 handle other characters after '\', so you cannot call it inside
758 strings or comments */
759 static void minp(void)
766 /* single line C++ comments */
767 static uint8_t *parse_line_comment(uint8_t *p
)
775 if (c
== '\n' || c
== CH_EOF
) {
777 } else if (c
== '\\') {
786 } else if (c
== '\r') {
804 static uint8_t *parse_comment(uint8_t *p
)
813 if (c
== '\n' || c
== '*' || c
== '\\')
817 if (c
== '\n' || c
== '*' || c
== '\\')
821 /* now we can handle all the cases */
825 } else if (c
== '*') {
831 } else if (c
== '/') {
833 } else if (c
== '\\') {
838 tcc_error("unexpected end of file in comment");
840 /* skip '\[\r]\n', otherwise just skip the stray */
846 } else if (c
== '\r') {
863 /* stray, eob or eof */
868 tcc_error("unexpected end of file in comment");
869 } else if (c
== '\\') {
879 ST_FUNC
int set_idnum(int c
, int val
)
881 int prev
= isidnum_table
[c
- CH_EOF
];
882 isidnum_table
[c
- CH_EOF
] = val
;
888 static inline void skip_spaces(void)
890 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
894 static inline int check_space(int t
, int *spc
)
896 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
905 /* parse a string without interpreting escapes */
906 static uint8_t *parse_pp_string(uint8_t *p
,
907 int sep
, CString
*str
)
915 } else if (c
== '\\') {
921 /* XXX: indicate line number of start of string */
922 tcc_error("missing terminating %c character", sep
);
923 } else if (c
== '\\') {
924 /* escape : just skip \[\r]\n */
929 } else if (c
== '\r') {
932 expect("'\n' after '\r'");
935 } else if (c
== CH_EOF
) {
936 goto unterminated_string
;
939 cstr_ccat(str
, '\\');
945 } else if (c
== '\n') {
948 } else if (c
== '\r') {
952 cstr_ccat(str
, '\r');
968 /* skip block of text until #else, #elif or #endif. skip also pairs of
970 static void preprocess_skip(void)
972 int a
, start_of_line
, c
, in_warn_or_error
;
979 in_warn_or_error
= 0;
1000 } else if (c
== '\\') {
1001 ch
= file
->buf_ptr
[0];
1002 handle_stray_noerror();
1009 if (in_warn_or_error
)
1011 p
= parse_pp_string(p
, c
, NULL
);
1015 if (in_warn_or_error
)
1022 p
= parse_comment(p
);
1023 } else if (ch
== '/') {
1024 p
= parse_line_comment(p
);
1029 if (start_of_line
) {
1034 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
1036 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
1038 else if (tok
== TOK_ENDIF
)
1040 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
1041 in_warn_or_error
= 1;
1042 else if (tok
== TOK_LINEFEED
)
1044 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1045 p
= parse_line_comment(p
- 1);
1047 #if !defined(TCC_TARGET_ARM)
1048 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1049 p
= parse_line_comment(p
- 1);
1051 /* ARM assembly uses '#' for constants */
1066 /* return the number of additional 'ints' necessary to store the
1068 static inline int tok_size(const int *p
)
1083 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
1086 return 1 + LONG_SIZE
/ 4;
1092 return 1 + LDOUBLE_SIZE
/ 4;
1099 /* token string handling */
1100 ST_INLN
void tok_str_new(TokenString
*s
)
1103 s
->len
= s
->lastlen
= 0;
1104 s
->allocated_len
= 0;
1105 s
->last_line_num
= -1;
1108 ST_FUNC TokenString
*tok_str_alloc(void)
1110 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1115 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1119 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1120 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1124 ST_FUNC
void tok_str_free_str(int *str
)
1126 tal_free(tokstr_alloc
, str
);
1129 ST_FUNC
void tok_str_free(TokenString
*str
)
1131 tok_str_free_str(str
->str
);
1132 tal_free(tokstr_alloc
, str
);
1135 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1139 size
= s
->allocated_len
;
1142 while (size
< new_size
)
1144 if (size
> s
->allocated_len
) {
1145 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1146 s
->allocated_len
= size
;
1152 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1158 if (len
>= s
->allocated_len
)
1159 str
= tok_str_realloc(s
, len
+ 1);
1164 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1167 str
->prev
= macro_stack
;
1168 str
->prev_ptr
= macro_ptr
;
1169 str
->save_line_num
= file
->line_num
;
1170 macro_ptr
= str
->str
;
1174 ST_FUNC
void end_macro(void)
1176 TokenString
*str
= macro_stack
;
1177 macro_stack
= str
->prev
;
1178 macro_ptr
= str
->prev_ptr
;
1179 file
->line_num
= str
->save_line_num
;
1180 if (str
->alloc
!= 0) {
1181 if (str
->alloc
== 2)
1182 str
->str
= NULL
; /* don't free */
1187 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1191 len
= s
->lastlen
= s
->len
;
1194 /* allocate space for worst case */
1195 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1196 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1209 str
[len
++] = cv
->tab
[0];
1216 /* Insert the string into the int array. */
1218 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1219 if (len
+ nb_words
>= s
->allocated_len
)
1220 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1221 str
[len
] = cv
->str
.size
;
1222 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1233 #if LDOUBLE_SIZE == 8
1236 str
[len
++] = cv
->tab
[0];
1237 str
[len
++] = cv
->tab
[1];
1239 #if LDOUBLE_SIZE == 12
1241 str
[len
++] = cv
->tab
[0];
1242 str
[len
++] = cv
->tab
[1];
1243 str
[len
++] = cv
->tab
[2];
1244 #elif LDOUBLE_SIZE == 16
1246 str
[len
++] = cv
->tab
[0];
1247 str
[len
++] = cv
->tab
[1];
1248 str
[len
++] = cv
->tab
[2];
1249 str
[len
++] = cv
->tab
[3];
1250 #elif LDOUBLE_SIZE != 8
1251 #error add long double size support
1260 /* add the current parse token in token string 's' */
1261 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1265 /* save line number info */
1266 if (file
->line_num
!= s
->last_line_num
) {
1267 s
->last_line_num
= file
->line_num
;
1268 cval
.i
= s
->last_line_num
;
1269 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1271 tok_str_add2(s
, tok
, &tokc
);
1274 /* get a token from an integer array and increment pointer. */
1275 static inline void tok_get(int *t
, const int **pp
, CValue
*cv
)
1295 cv
->i
= (unsigned)*p
++;
1304 cv
->str
.size
= *p
++;
1306 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1318 #if LDOUBLE_SIZE == 16
1320 #elif LDOUBLE_SIZE == 12
1322 #elif LDOUBLE_SIZE == 8
1325 # error add long double size support
1339 # define TOK_GET(t,p,c) tok_get(t,p,c)
1341 # define TOK_GET(t,p,c) do { \
1343 if (TOK_HAS_VALUE(_t)) \
1346 *(t) = _t, ++*(p); \
1350 static int macro_is_equal(const int *a
, const int *b
)
1359 /* first time preallocate macro_equal_buf, next time only reset position to start */
1360 cstr_reset(¯o_equal_buf
);
1361 TOK_GET(&t
, &a
, &cv
);
1362 cstr_cat(¯o_equal_buf
, get_tok_str(t
, &cv
), 0);
1363 TOK_GET(&t
, &b
, &cv
);
1364 if (strcmp(macro_equal_buf
.data
, get_tok_str(t
, &cv
)))
1370 /* defines handling */
1371 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1376 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1378 s
->next
= first_arg
;
1379 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1381 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1382 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1385 /* undefined a define symbol. Its name is just set to zero */
1386 ST_FUNC
void define_undef(Sym
*s
)
1389 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1390 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1393 ST_INLN Sym
*define_find(int v
)
1396 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1398 return table_ident
[v
]->sym_define
;
1401 /* free define stack until top reaches 'b' */
1402 ST_FUNC
void free_defines(Sym
*b
)
1404 while (define_stack
!= b
) {
1405 Sym
*top
= define_stack
;
1406 define_stack
= top
->prev
;
1407 tok_str_free_str(top
->d
);
1414 ST_FUNC Sym
*label_find(int v
)
1417 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1419 return table_ident
[v
]->sym_label
;
1422 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1425 s
= sym_push2(ptop
, v
, 0, 0);
1427 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1428 if (ptop
== &global_label_stack
) {
1429 /* modify the top most local identifier, so that
1430 sym_identifier will point to 's' when popped */
1432 ps
= &(*ps
)->prev_tok
;
1439 /* pop labels until element last is reached. Look if any labels are
1440 undefined. Define symbols if '&&label' was used. */
1441 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
, int keep
)
1444 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1446 if (s
->r
== LABEL_DECLARED
) {
1447 tcc_warning_c(warn_all
)("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1448 } else if (s
->r
== LABEL_FORWARD
) {
1449 tcc_error("label '%s' used but not defined",
1450 get_tok_str(s
->v
, NULL
));
1453 /* define corresponding symbol. A size of
1455 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1459 if (s
->r
!= LABEL_GONE
)
1460 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1470 /* fake the nth "#if defined test_..." for tcc -dt -run */
1471 static void maybe_run_test(TCCState
*s
)
1474 if (s
->include_stack_ptr
!= s
->include_stack
)
1476 p
= get_tok_str(tok
, NULL
);
1477 if (0 != memcmp(p
, "test_", 5))
1479 if (0 != --s
->run_test
)
1481 fprintf(s
->ppfp
, &"\n[%s]\n"[!(s
->dflag
& 32)], p
), fflush(s
->ppfp
);
1482 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1485 /* eval an expression for #if/#elif */
1486 static int expr_preprocess(void)
1491 str
= tok_str_alloc();
1493 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1494 next(); /* do macro subst */
1496 if (tok
== TOK_DEFINED
) {
1501 if (tok
< TOK_IDENT
)
1502 expect("identifier");
1503 if (tcc_state
->run_test
)
1504 maybe_run_test(tcc_state
);
1505 c
= define_find(tok
) != 0;
1513 } else if (1 && tok
== TOK___HAS_INCLUDE
) {
1514 next(); /* XXX check if correct to use expansion */
1516 while (tok
!= ')' && tok
!= TOK_EOF
)
1522 } else if (tok
>= TOK_IDENT
) {
1523 /* if undefined macro, replace with zero, check for func-like */
1527 tok_str_add_tok(str
);
1530 tcc_error("function-like macro '%s' is not defined",
1531 get_tok_str(t
, NULL
));
1534 tok_str_add_tok(str
);
1537 tok_str_add(str
, -1); /* simulate end of file */
1538 tok_str_add(str
, 0);
1539 /* now evaluate C constant expression */
1540 begin_macro(str
, 1);
1548 /* parse after #define */
1549 ST_FUNC
void parse_define(void)
1551 Sym
*s
, *first
, **ps
;
1552 int v
, t
, varg
, is_vaargs
, spc
;
1553 int saved_parse_flags
= parse_flags
;
1556 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1557 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1558 /* XXX: should check if same macro (ANSI) */
1561 /* We have to parse the whole define as if not in asm mode, in particular
1562 no line comment with '#' must be ignored. Also for function
1563 macros the argument list must be parsed without '.' being an ID
1565 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1566 /* '(' must be just after macro definition for MACRO_FUNC */
1568 parse_flags
&= ~PARSE_FLAG_SPACES
;
1570 int dotid
= set_idnum('.', 0);
1573 if (tok
!= ')') for (;;) {
1577 if (varg
== TOK_DOTS
) {
1578 varg
= TOK___VA_ARGS__
;
1580 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1584 if (varg
< TOK_IDENT
)
1586 tcc_error("bad macro parameter list");
1587 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1592 if (tok
!= ',' || is_vaargs
)
1596 parse_flags
|= PARSE_FLAG_SPACES
;
1599 set_idnum('.', dotid
);
1604 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1605 /* The body of a macro definition should be parsed such that identifiers
1606 are parsed like the file mode determines (i.e. with '.' being an
1607 ID character in asm mode). But '#' should be retained instead of
1608 regarded as line comment leader, so still don't set ASM_FILE
1610 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1611 /* remove spaces around ## and after '#' */
1612 if (TOK_TWOSHARPS
== tok
) {
1619 } else if ('#' == tok
) {
1621 } else if (check_space(tok
, &spc
)) {
1624 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1629 parse_flags
= saved_parse_flags
;
1631 --tokstr_buf
.len
; /* remove trailing space */
1632 tok_str_add(&tokstr_buf
, 0);
1635 tcc_error("'##' cannot appear at either end of macro");
1636 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1639 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1641 const unsigned char *s
;
1647 s
= (unsigned char *) filename
;
1650 h
= TOK_HASH_FUNC(h
, toup(*s
));
1652 h
= TOK_HASH_FUNC(h
, *s
);
1656 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1658 i
= s1
->cached_includes_hash
[h
];
1662 e
= s1
->cached_includes
[i
- 1];
1663 if (0 == PATHCMP(e
->filename
, filename
))
1670 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1671 strcpy(e
->filename
, filename
);
1672 e
->ifndef_macro
= e
->once
= 0;
1673 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1674 /* add in hash table */
1675 e
->hash_next
= s1
->cached_includes_hash
[h
];
1676 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1678 printf("adding cached '%s'\n", filename
);
1683 static void pragma_parse(TCCState
*s1
)
1686 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1690 if (next(), tok
!= '(')
1692 if (next(), tok
!= TOK_STR
)
1694 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1695 if (next(), tok
!= ')')
1697 if (t
== TOK_push_macro
) {
1698 while (NULL
== (s
= define_find(v
)))
1699 define_push(v
, 0, NULL
, NULL
);
1700 s
->type
.ref
= s
; /* set push boundary */
1702 for (s
= define_stack
; s
; s
= s
->prev
)
1703 if (s
->v
== v
&& s
->type
.ref
== s
) {
1709 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1711 tcc_warning("unbalanced #pragma pop_macro");
1712 pp_debug_tok
= t
, pp_debug_symv
= v
;
1714 } else if (tok
== TOK_once
) {
1715 search_cached_include(s1
, file
->filename
, 1)->once
= pp_once
;
1717 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1718 /* tcc -E: keep pragmas below unchanged */
1720 unget_tok(TOK_PRAGMA
);
1722 unget_tok(TOK_LINEFEED
);
1724 } else if (tok
== TOK_pack
) {
1726 #pragma pack(1) // set
1727 #pragma pack() // reset to default
1728 #pragma pack(push) // push current
1729 #pragma pack(push,1) // push & set
1730 #pragma pack(pop) // restore previous */
1733 if (tok
== TOK_ASM_pop
) {
1735 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1737 tcc_error("out of pack stack");
1739 s1
->pack_stack_ptr
--;
1743 if (tok
== TOK_ASM_push
) {
1745 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1747 val
= *s1
->pack_stack_ptr
++;
1752 if (tok
!= TOK_CINT
)
1755 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1760 *s1
->pack_stack_ptr
= val
;
1765 } else if (tok
== TOK_comment
) {
1774 p
= tcc_strdup((char *)tokc
.str
.data
);
1779 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1781 if (t
== TOK_option
)
1782 tcc_set_options(s1
, p
);
1787 tcc_warning_c(warn_unsupported
)("#pragma %s ignored", get_tok_str(tok
, &tokc
));
1791 tcc_error("malformed #pragma directive");
1795 /* is_bof is true if first non space token at beginning of file */
1796 ST_FUNC
void preprocess(int is_bof
)
1798 TCCState
*s1
= tcc_state
;
1799 int i
, c
, n
, saved_parse_flags
;
1803 saved_parse_flags
= parse_flags
;
1804 parse_flags
= PARSE_FLAG_PREPROCESS
1805 | PARSE_FLAG_TOK_NUM
1806 | PARSE_FLAG_TOK_STR
1807 | PARSE_FLAG_LINEFEED
1808 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1817 pp_debug_symv
= tok
;
1823 pp_debug_symv
= tok
;
1824 s
= define_find(tok
);
1825 /* undefine symbol by putting an invalid name */
1830 case TOK_INCLUDE_NEXT
:
1831 ch
= file
->buf_ptr
[0];
1832 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1837 } else if (ch
== '\"') {
1842 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1843 if ((q
- buf
) < sizeof(buf
) - 1)
1846 if (handle_stray_noerror() == 0)
1854 /* eat all spaces and comments after include */
1855 /* XXX: slightly incorrect */
1856 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1861 /* computed #include : concatenate everything up to linefeed,
1862 the result must be one of the two accepted forms.
1863 Don't convert pp-tokens to tokens here. */
1864 parse_flags
= (PARSE_FLAG_PREPROCESS
1865 | PARSE_FLAG_LINEFEED
1866 | (parse_flags
& PARSE_FLAG_ASM_FILE
));
1869 while (tok
!= TOK_LINEFEED
) {
1870 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1874 /* check syntax and remove '<>|""' */
1875 if ((len
< 2 || ((buf
[0] != '"' || buf
[len
-1] != '"') &&
1876 (buf
[0] != '<' || buf
[len
-1] != '>'))))
1877 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1879 memmove(buf
, buf
+ 1, len
- 2);
1880 buf
[len
- 2] = '\0';
1883 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1884 tcc_error("#include recursion too deep");
1885 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
+ 1 : 0;
1886 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1887 for (; i
< n
; ++i
) {
1888 char buf1
[sizeof file
->filename
];
1893 /* check absolute include path */
1894 if (!IS_ABSPATH(buf
))
1898 } else if (i
== 1) {
1899 /* search in file's dir if "header.h" */
1902 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1903 path
= file
->true_filename
;
1904 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1907 /* search in all the include paths */
1908 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1909 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1910 pstrcpy(buf1
, sizeof(buf1
), path
);
1911 pstrcat(buf1
, sizeof(buf1
), "/");
1914 pstrcat(buf1
, sizeof(buf1
), buf
);
1915 e
= search_cached_include(s1
, buf1
, 0);
1916 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
== pp_once
)) {
1917 /* no need to parse the include because the 'ifndef macro'
1918 is defined (or had #pragma once) */
1920 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1925 if (tcc_open(s1
, buf1
) < 0)
1927 /* push previous file on stack */
1928 *s1
->include_stack_ptr
++ = file
->prev
;
1929 file
->include_next_index
= i
;
1931 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1933 /* update target deps */
1935 BufferedFile
*bf
= file
;
1936 while (i
== 1 && (bf
= bf
->prev
))
1937 i
= bf
->include_next_index
;
1938 /* skip system include files */
1939 if (s1
->include_sys_deps
|| n
- i
> s1
->nb_sysinclude_paths
)
1940 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1943 /* add include file debug info */
1944 tcc_debug_bincl(tcc_state
);
1945 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1946 ch
= file
->buf_ptr
[0];
1949 tcc_error("include file '%s' not found", buf
);
1956 c
= expr_preprocess();
1962 if (tok
< TOK_IDENT
)
1963 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1967 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1969 file
->ifndef_macro
= tok
;
1972 c
= (define_find(tok
) != 0) ^ c
;
1974 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1975 tcc_error("memory full (ifdef)");
1976 *s1
->ifdef_stack_ptr
++ = c
;
1979 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1980 tcc_error("#else without matching #if");
1981 if (s1
->ifdef_stack_ptr
[-1] & 2)
1982 tcc_error("#else after #else");
1983 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1986 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1987 tcc_error("#elif without matching #if");
1988 c
= s1
->ifdef_stack_ptr
[-1];
1990 tcc_error("#elif after #else");
1991 /* last #if/#elif expression was true: we skip */
1995 c
= expr_preprocess();
1996 s1
->ifdef_stack_ptr
[-1] = c
;
1999 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
2000 file
->ifndef_macro
= 0;
2009 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2010 tcc_error("#endif without matching #if");
2011 s1
->ifdef_stack_ptr
--;
2012 /* '#ifndef macro' was at the start of file. Now we check if
2013 an '#endif' is exactly at the end of file */
2014 if (file
->ifndef_macro
&&
2015 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2016 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2017 /* need to set to zero to avoid false matches if another
2018 #ifndef at middle of file */
2019 file
->ifndef_macro
= 0;
2020 while (tok
!= TOK_LINEFEED
)
2022 tok_flags
|= TOK_FLAG_ENDIF
;
2027 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
2031 if (tok
!= TOK_CINT
)
2033 tcc_error("wrong #line format");
2037 if (tok
!= TOK_LINEFEED
) {
2038 if (tok
== TOK_STR
) {
2039 if (file
->true_filename
== file
->filename
)
2040 file
->true_filename
= tcc_strdup(file
->filename
);
2041 /* prepend directory from real file */
2042 pstrcpy(buf
, sizeof buf
, file
->true_filename
);
2043 *tcc_basename(buf
) = 0;
2044 pstrcat(buf
, sizeof buf
, (char *)tokc
.str
.data
);
2045 tcc_debug_putfile(s1
, buf
);
2046 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2053 total_lines
+= file
->line_num
- n
;
2059 ch
= file
->buf_ptr
[0];
2062 while (ch
!= '\n' && ch
!= CH_EOF
) {
2063 if ((q
- buf
) < sizeof(buf
) - 1)
2066 if (handle_stray_noerror() == 0)
2073 tcc_error("#error %s", buf
);
2075 tcc_warning("#warning %s", buf
);
2083 /* ignore gas line comment in an 'S' file. */
2084 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
2086 if (tok
== '!' && is_bof
)
2087 /* '!' is ignored at beginning to allow C scripts. */
2089 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2091 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
2094 /* ignore other preprocess commands or #! for C scripts */
2095 while (tok
!= TOK_LINEFEED
)
2098 parse_flags
= saved_parse_flags
;
2101 /* evaluate escape codes in a string. */
2102 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2117 case '0': case '1': case '2': case '3':
2118 case '4': case '5': case '6': case '7':
2119 /* at most three octal digits */
2124 n
= n
* 8 + c
- '0';
2128 n
= n
* 8 + c
- '0';
2133 goto add_char_nonext
;
2134 case 'x': i
= 0; goto parse_hex_or_ucn
;
2135 case 'u': i
= 4; goto parse_hex_or_ucn
;
2136 case 'U': i
= 8; goto parse_hex_or_ucn
;
2142 if (c
>= 'a' && c
<= 'f')
2144 else if (c
>= 'A' && c
<= 'F')
2149 expect("more hex digits in universal-character-name");
2152 goto add_char_nonext
;
2157 cstr_u8cat(outstr
, n
);
2182 goto invalid_escape
;
2192 if (c
>= '!' && c
<= '~')
2193 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2195 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2198 } else if (is_long
&& c
>= 0x80) {
2199 /* assume we are processing UTF-8 sequence */
2200 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2202 int cont
; /* count of continuation bytes */
2203 int skip
; /* how many bytes should skip when error occurred */
2206 /* decode leading byte */
2208 skip
= 1; goto invalid_utf8_sequence
;
2209 } else if (c
<= 0xDF) {
2210 cont
= 1; n
= c
& 0x1f;
2211 } else if (c
<= 0xEF) {
2212 cont
= 2; n
= c
& 0xf;
2213 } else if (c
<= 0xF4) {
2214 cont
= 3; n
= c
& 0x7;
2216 skip
= 1; goto invalid_utf8_sequence
;
2219 /* decode continuation bytes */
2220 for (i
= 1; i
<= cont
; i
++) {
2221 int l
= 0x80, h
= 0xBF;
2223 /* adjust limit for second byte */
2226 case 0xE0: l
= 0xA0; break;
2227 case 0xED: h
= 0x9F; break;
2228 case 0xF0: l
= 0x90; break;
2229 case 0xF4: h
= 0x8F; break;
2233 if (p
[i
] < l
|| p
[i
] > h
) {
2234 skip
= i
; goto invalid_utf8_sequence
;
2237 n
= (n
<< 6) | (p
[i
] & 0x3f);
2240 /* advance pointer */
2243 goto add_char_nonext
;
2245 /* error handling */
2246 invalid_utf8_sequence
:
2247 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c
);
2250 goto add_char_nonext
;
2256 cstr_ccat(outstr
, c
);
2258 #ifdef TCC_TARGET_PE
2259 /* store as UTF-16 */
2261 cstr_wccat(outstr
, c
);
2264 cstr_wccat(outstr
, (c
>> 10) + 0xD800);
2265 cstr_wccat(outstr
, (c
& 0x3FF) + 0xDC00);
2268 cstr_wccat(outstr
, c
);
2272 /* add a trailing '\0' */
2274 cstr_ccat(outstr
, '\0');
2276 cstr_wccat(outstr
, '\0');
2279 static void parse_string(const char *s
, int len
)
2281 uint8_t buf
[1000], *p
= buf
;
2284 if ((is_long
= *s
== 'L'))
2288 if (len
>= sizeof buf
)
2289 p
= tcc_malloc(len
+ 1);
2293 cstr_reset(&tokcstr
);
2294 parse_escape_string(&tokcstr
, p
, is_long
);
2299 int char_size
, i
, n
, c
;
2300 /* XXX: make it portable */
2302 tok
= TOK_CCHAR
, char_size
= 1;
2304 tok
= TOK_LCHAR
, char_size
= sizeof(nwchar_t
);
2305 n
= tokcstr
.size
/ char_size
- 1;
2307 tcc_error("empty character constant");
2309 tcc_warning_c(warn_all
)("multi-character character constant");
2310 for (c
= i
= 0; i
< n
; ++i
) {
2312 c
= ((nwchar_t
*)tokcstr
.data
)[i
];
2314 c
= (c
<< 8) | ((char *)tokcstr
.data
)[i
];
2318 tokc
.str
.size
= tokcstr
.size
;
2319 tokc
.str
.data
= tokcstr
.data
;
2327 /* we use 64 bit numbers */
2330 /* bn = (bn << shift) | or_val */
2331 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2335 for(i
=0;i
<BN_SIZE
;i
++) {
2337 bn
[i
] = (v
<< shift
) | or_val
;
2338 or_val
= v
>> (32 - shift
);
2342 static void bn_zero(unsigned int *bn
)
2345 for(i
=0;i
<BN_SIZE
;i
++) {
2350 /* parse number in null terminated string 'p' and return it in the
2352 static void parse_number(const char *p
)
2354 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2356 unsigned int bn
[BN_SIZE
];
2367 goto float_frac_parse
;
2368 } else if (t
== '0') {
2369 if (ch
== 'x' || ch
== 'X') {
2373 } else if (tcc_state
->tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2379 /* parse all digits. cannot check octal numbers at this stage
2380 because of floating point constants */
2382 if (ch
>= 'a' && ch
<= 'f')
2384 else if (ch
>= 'A' && ch
<= 'F')
2392 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2394 tcc_error("number too long");
2400 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2401 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2403 /* NOTE: strtox should support that for hexa numbers, but
2404 non ISOC99 libcs do not support it, so we prefer to do
2406 /* hexadecimal or binary floats */
2407 /* XXX: handle overflows */
2419 } else if (t
>= 'a') {
2421 } else if (t
>= 'A') {
2426 bn_lshift(bn
, shift
, t
);
2433 if (t
>= 'a' && t
<= 'f') {
2435 } else if (t
>= 'A' && t
<= 'F') {
2437 } else if (t
>= '0' && t
<= '9') {
2443 tcc_error("invalid digit");
2444 bn_lshift(bn
, shift
, t
);
2449 if (ch
!= 'p' && ch
!= 'P')
2456 } else if (ch
== '-') {
2460 if (ch
< '0' || ch
> '9')
2461 expect("exponent digits");
2462 while (ch
>= '0' && ch
<= '9') {
2463 exp_val
= exp_val
* 10 + ch
- '0';
2466 exp_val
= exp_val
* s
;
2468 /* now we can generate the number */
2469 /* XXX: should patch directly float number */
2470 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2471 d
= ldexp(d
, exp_val
- frac_bits
);
2476 /* float : should handle overflow */
2478 } else if (t
== 'L') {
2480 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2485 /* XXX: not large enough */
2486 tokc
.ld
= (long double)d
;
2493 /* decimal floats */
2495 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2500 while (ch
>= '0' && ch
<= '9') {
2501 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2507 if (ch
== 'e' || ch
== 'E') {
2508 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2512 if (ch
== '-' || ch
== '+') {
2513 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2518 if (ch
< '0' || ch
> '9')
2519 expect("exponent digits");
2520 while (ch
>= '0' && ch
<= '9') {
2521 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2533 tokc
.f
= strtof(token_buf
, NULL
);
2534 } else if (t
== 'L') {
2536 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
2538 tokc
.d
= strtod(token_buf
, NULL
);
2541 tokc
.ld
= strtold(token_buf
, NULL
);
2545 tokc
.d
= strtod(token_buf
, NULL
);
2549 unsigned long long n
, n1
;
2550 int lcount
, ucount
, ov
= 0;
2553 /* integer number */
2556 if (b
== 10 && *q
== '0') {
2563 /* no need for checks except for base 10 / 8 errors */
2573 tcc_error("invalid digit");
2576 /* detect overflow */
2577 if (n1
>= 0x1000000000000000ULL
&& n
/ b
!= n1
)
2581 /* Determine the characteristics (unsigned and/or 64bit) the type of
2582 the constant must have according to the constant suffix(es) */
2583 lcount
= ucount
= 0;
2589 tcc_error("three 'l's in integer constant");
2590 if (lcount
&& *(p
- 1) != ch
)
2591 tcc_error("incorrect integer suffix: %s", p1
);
2594 } else if (t
== 'U') {
2596 tcc_error("two 'u's in integer constant");
2604 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2605 if (ucount
== 0 && b
== 10) {
2606 if (lcount
<= (LONG_SIZE
== 4)) {
2607 if (n
>= 0x80000000U
)
2608 lcount
= (LONG_SIZE
== 4) + 1;
2610 if (n
>= 0x8000000000000000ULL
)
2613 if (lcount
<= (LONG_SIZE
== 4)) {
2614 if (n
>= 0x100000000ULL
)
2615 lcount
= (LONG_SIZE
== 4) + 1;
2616 else if (n
>= 0x80000000U
)
2619 if (n
>= 0x8000000000000000ULL
)
2624 tcc_warning("integer constant overflow");
2633 ++tok
; /* TOK_CU... */
2637 tcc_error("invalid number");
2641 #define PARSE2(c1, tok1, c2, tok2) \
2652 /* return next token without macro substitution */
2653 static inline void next_nomacro1(void)
2655 int t
, c
, is_long
, len
;
2669 if (parse_flags
& PARSE_FLAG_SPACES
)
2670 goto keep_tok_flags
;
2671 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2680 /* first look if it is in fact an end of buffer */
2681 c
= handle_stray1(p
);
2688 TCCState
*s1
= tcc_state
;
2689 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2690 && !(tok_flags
& TOK_FLAG_EOF
)) {
2691 tok_flags
|= TOK_FLAG_EOF
;
2693 goto keep_tok_flags
;
2694 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2696 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2697 tcc_error("missing #endif");
2698 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2699 /* no include left : end of file. */
2702 tok_flags
&= ~TOK_FLAG_EOF
;
2703 /* pop include file */
2705 /* test if previous '#endif' was after a #ifdef at
2707 if (tok_flags
& TOK_FLAG_ENDIF
) {
2709 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2711 search_cached_include(s1
, file
->filename
, 1)
2712 ->ifndef_macro
= file
->ifndef_macro_saved
;
2713 tok_flags
&= ~TOK_FLAG_ENDIF
;
2716 /* add end of include file debug info */
2717 tcc_debug_eincl(tcc_state
);
2718 /* pop include stack */
2720 s1
->include_stack_ptr
--;
2722 if (p
== file
->buffer
)
2723 tok_flags
= TOK_FLAG_BOF
|TOK_FLAG_BOL
;
2731 tok_flags
|= TOK_FLAG_BOL
;
2734 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2737 goto keep_tok_flags
;
2742 if ((tok_flags
& TOK_FLAG_BOL
) &&
2743 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2745 preprocess(tok_flags
& TOK_FLAG_BOF
);
2751 tok
= TOK_TWOSHARPS
;
2753 #if !defined(TCC_TARGET_ARM)
2754 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2755 p
= parse_line_comment(p
- 1);
2766 /* dollar is allowed to start identifiers when not parsing asm */
2768 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2769 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2772 case 'a': case 'b': case 'c': case 'd':
2773 case 'e': case 'f': case 'g': case 'h':
2774 case 'i': case 'j': case 'k': case 'l':
2775 case 'm': case 'n': case 'o': case 'p':
2776 case 'q': case 'r': case 's': case 't':
2777 case 'u': case 'v': case 'w': case 'x':
2779 case 'A': case 'B': case 'C': case 'D':
2780 case 'E': case 'F': case 'G': case 'H':
2781 case 'I': case 'J': case 'K':
2782 case 'M': case 'N': case 'O': case 'P':
2783 case 'Q': case 'R': case 'S': case 'T':
2784 case 'U': case 'V': case 'W': case 'X':
2790 h
= TOK_HASH_FUNC(h
, c
);
2791 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2792 h
= TOK_HASH_FUNC(h
, c
);
2797 /* fast case : no stray found, so we have the full token
2798 and we have already hashed it */
2799 h
&= (TOK_HASH_SIZE
- 1);
2800 pts
= &hash_ident
[h
];
2805 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2807 pts
= &(ts
->hash_next
);
2809 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2813 cstr_reset(&tokcstr
);
2814 cstr_cat(&tokcstr
, (char *) p1
, len
);
2818 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2820 cstr_ccat(&tokcstr
, c
);
2823 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2829 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2831 goto parse_ident_fast
;
2834 if (c
== '\'' || c
== '\"') {
2838 cstr_reset(&tokcstr
);
2839 cstr_ccat(&tokcstr
, 'L');
2840 goto parse_ident_slow
;
2845 case '0': case '1': case '2': case '3':
2846 case '4': case '5': case '6': case '7':
2850 /* after the first digit, accept digits, alpha, '.' or sign if
2851 prefixed by 'eEpP' */
2853 cstr_reset(&tokcstr
);
2855 cstr_ccat(&tokcstr
, t
);
2856 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2858 || ((c
== '+' || c
== '-')
2859 && (((t
== 'e' || t
== 'E')
2860 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2861 /* 0xe+1 is 3 tokens in asm */
2862 && ((char*)tokcstr
.data
)[0] == '0'
2863 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2864 || t
== 'p' || t
== 'P'))))
2869 /* We add a trailing '\0' to ease parsing */
2870 cstr_ccat(&tokcstr
, '\0');
2871 tokc
.str
.size
= tokcstr
.size
;
2872 tokc
.str
.data
= tokcstr
.data
;
2877 /* special dot handling because it can also start a number */
2882 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2883 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2885 goto parse_ident_fast
;
2886 } else if (c
== '.') {
2892 *--p
= '.'; /* may underflow into file->unget[] */
2903 cstr_reset(&tokcstr
);
2905 cstr_ccat(&tokcstr
, 'L');
2906 cstr_ccat(&tokcstr
, c
);
2907 p
= parse_pp_string(p
, c
, &tokcstr
);
2908 cstr_ccat(&tokcstr
, c
);
2909 cstr_ccat(&tokcstr
, '\0');
2910 tokc
.str
.size
= tokcstr
.size
;
2911 tokc
.str
.data
= tokcstr
.data
;
2920 } else if (c
== '<') {
2937 } else if (c
== '>') {
2955 } else if (c
== '=') {
2968 } else if (c
== '=') {
2981 } else if (c
== '=') {
2994 } else if (c
== '=') {
2997 } else if (c
== '>') {
3005 PARSE2('!', '!', '=', TOK_NE
)
3006 PARSE2('=', '=', '=', TOK_EQ
)
3007 PARSE2('*', '*', '=', TOK_A_MUL
)
3008 PARSE2('%', '%', '=', TOK_A_MOD
)
3009 PARSE2('^', '^', '=', TOK_A_XOR
)
3011 /* comments or operator */
3015 p
= parse_comment(p
);
3016 /* comments replaced by a blank */
3019 } else if (c
== '/') {
3020 p
= parse_line_comment(p
);
3023 } else if (c
== '=') {
3043 case '@': /* only used in assembler */
3049 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
3050 goto parse_ident_fast
;
3051 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
3053 tcc_error("unrecognized character \\x%02x", c
);
3059 #if defined(PARSE_DEBUG)
3060 printf("token = %d %s\n", tok
, get_tok_str(tok
, &tokc
));
3064 static void macro_subst(
3065 TokenString
*tok_str
,
3067 const int *macro_str
3070 /* substitute arguments in replacement lists in macro_str by the values in
3071 args (field d) and return allocated string */
3072 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
3084 TOK_GET(&t
, ¯o_str
, &cval
);
3089 TOK_GET(&t
, ¯o_str
, &cval
);
3092 s
= sym_find2(args
, t
);
3095 cstr_ccat(&cstr
, '\"');
3099 TOK_GET(&t
, &st
, &cval
);
3100 if (t
!= TOK_PLCHLDR
3102 && 0 == check_space(t
, &spc
)) {
3103 const char *s
= get_tok_str(t
, &cval
);
3105 if (t
== TOK_PPSTR
&& *s
!= '\'')
3106 add_char(&cstr
, *s
);
3108 cstr_ccat(&cstr
, *s
);
3114 cstr_ccat(&cstr
, '\"');
3115 cstr_ccat(&cstr
, '\0');
3117 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
3120 cval
.str
.size
= cstr
.size
;
3121 cval
.str
.data
= cstr
.data
;
3122 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
3126 expect("macro parameter after '#'");
3128 } else if (t
>= TOK_IDENT
) {
3129 s
= sym_find2(args
, t
);
3133 /* if '##' is present before or after, no arg substitution */
3134 if (*macro_str
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
3135 /* special case for var arg macros : ## eats the ','
3136 if empty VA_ARGS variable. */
3137 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
3139 /* suppress ',' '##' */
3142 /* suppress '##' and add variable */
3150 /* Expand arguments tokens and store them. In most
3151 cases we could also re-expand each argument if
3152 used multiple times, but not if the argument
3153 contains the __COUNTER__ macro. */
3155 sym_push2(&s
->next
, s
->v
, s
->type
.t
, 0);
3157 macro_subst(&str2
, nested_list
, st
);
3158 tok_str_add(&str2
, 0);
3159 s
->next
->d
= str2
.str
;
3165 TOK_GET(&t2
, &st
, &cval
);
3168 tok_str_add2(&str
, t2
, &cval
);
3170 if (str
.len
== l0
) /* expanded to empty string */
3171 tok_str_add(&str
, TOK_PLCHLDR
);
3173 tok_str_add(&str
, t
);
3176 tok_str_add2(&str
, t
, &cval
);
3180 tok_str_add(&str
, 0);
3184 static char const ab_month_name
[12][4] =
3186 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3187 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3190 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3196 if (t1
!= TOK_PLCHLDR
)
3197 cstr_cat(&cstr
, get_tok_str(t1
, v1
), -1);
3199 if (t2
!= TOK_PLCHLDR
)
3200 cstr_cat(&cstr
, get_tok_str(t2
, v2
), -1);
3201 cstr_ccat(&cstr
, '\0');
3203 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3204 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3208 if (0 == *file
->buf_ptr
)
3212 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3213 " preprocessing token", n
, (char *)cstr
.data
, (char*)cstr
.data
+ n
);
3218 //printf("paste <%s>\n", (char*)cstr.data);
3223 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3224 return the resulting string (which must be freed). */
3225 static inline int *macro_twosharps(const int *ptr0
)
3229 TokenString macro_str1
;
3230 int start_of_nosubsts
= -1;
3233 /* we search the first '##' */
3234 for (ptr
= ptr0
;;) {
3235 TOK_GET(&t
, &ptr
, &cval
);
3236 if (t
== TOK_PPJOIN
)
3242 tok_str_new(¯o_str1
);
3244 //tok_print(" $$$", ptr0);
3245 for (ptr
= ptr0
;;) {
3246 TOK_GET(&t
, &ptr
, &cval
);
3249 if (t
== TOK_PPJOIN
)
3251 while (*ptr
== TOK_PPJOIN
) {
3253 /* given 'a##b', remove nosubsts preceding 'a' */
3254 if (start_of_nosubsts
>= 0)
3255 macro_str1
.len
= start_of_nosubsts
;
3256 /* given 'a##b', remove nosubsts preceding 'b' */
3257 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3259 if (t1
&& t1
!= TOK_PPJOIN
) {
3260 TOK_GET(&t1
, &ptr
, &cv1
);
3261 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3262 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3263 t
= tok
, cval
= tokc
;
3265 tok_str_add2(¯o_str1
, t
, &cval
);
3271 if (t
== TOK_NOSUBST
) {
3272 if (start_of_nosubsts
< 0)
3273 start_of_nosubsts
= macro_str1
.len
;
3275 start_of_nosubsts
= -1;
3277 tok_str_add2(¯o_str1
, t
, &cval
);
3279 tok_str_add(¯o_str1
, 0);
3280 //tok_print(" ###", macro_str1.str);
3281 return macro_str1
.str
;
3284 /* peek or read [ws_str == NULL] next token from function macro call,
3285 walking up macro levels up to the file if necessary */
3286 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3294 p
= macro_ptr
, t
= *p
;
3296 while (is_space(t
) || TOK_LINEFEED
== t
|| TOK_PLCHLDR
== t
)
3297 tok_str_add(ws_str
, t
), t
= *++p
;
3301 /* also, end of scope for nested defined symbol */
3303 while (sa
&& sa
->v
== 0)
3312 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3315 uint8_t *p
= file
->buf_ptr
;
3318 p
= parse_comment(p
);
3319 file
->buf_ptr
= p
- 1;
3320 } else if (c
== '/') {
3321 p
= parse_line_comment(p
);
3322 file
->buf_ptr
= p
- 1;
3329 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3330 tok_str_add(ws_str
, ch
);
3344 /* do macro substitution of current token with macro 's' and add
3345 result to (tok_str,tok_len). 'nested_list' is the list of all
3346 macros we got inside to avoid recursing. Return non zero if no
3347 substitution needs to be done */
3348 static int macro_subst_tok(
3349 TokenString
*tok_str
,
3353 Sym
*args
, *sa
, *sa1
;
3354 int parlevel
, t
, t1
, spc
;
3361 /* if symbol is a macro, prepare substitution */
3362 /* special macros */
3363 if (tok
== TOK___LINE__
|| tok
== TOK___COUNTER__
) {
3364 t
= tok
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3365 snprintf(buf
, sizeof(buf
), "%d", t
);
3369 } else if (tok
== TOK___FILE__
) {
3370 cstrval
= file
->filename
;
3372 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3377 tm
= localtime(&ti
);
3378 if (tok
== TOK___DATE__
) {
3379 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3380 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3382 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3383 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3390 cstr_cat(&cstr
, cstrval
, 0);
3391 cval
.str
.size
= cstr
.size
;
3392 cval
.str
.data
= cstr
.data
;
3393 tok_str_add2(tok_str
, t1
, &cval
);
3396 int saved_parse_flags
= parse_flags
;
3397 int *joined_str
= NULL
;
3400 if (s
->type
.t
== MACRO_FUNC
) {
3401 /* whitespace between macro name and argument list */
3403 tok_str_new(&ws_str
);
3406 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3407 | PARSE_FLAG_ACCEPT_STRAYS
;
3409 /* get next token from argument stream */
3410 t
= next_argstream(nested_list
, &ws_str
);
3412 /* not a macro substitution after all, restore the
3413 * macro token plus all whitespace we've read.
3414 * whitespace is intentionally not merged to preserve
3416 parse_flags
= saved_parse_flags
;
3417 tok_str_add(tok_str
, tok
);
3418 if (parse_flags
& PARSE_FLAG_SPACES
) {
3420 for (i
= 0; i
< ws_str
.len
; i
++)
3421 tok_str_add(tok_str
, ws_str
.str
[i
]);
3423 tok_str_free_str(ws_str
.str
);
3426 tok_str_free_str(ws_str
.str
);
3429 next_nomacro(); /* eat '(' */
3430 } while (tok
== TOK_PLCHLDR
|| is_space(tok
));
3432 /* argument macro */
3435 /* NOTE: empty args are allowed, except if no args */
3438 next_argstream(nested_list
, NULL
);
3439 } while (tok
== TOK_PLCHLDR
|| is_space(tok
) ||
3440 TOK_LINEFEED
== tok
);
3442 /* handle '()' case */
3443 if (!args
&& !sa
&& tok
== ')')
3446 tcc_error("macro '%s' used with too many args",
3447 get_tok_str(s
->v
, 0));
3450 /* NOTE: non zero sa->t indicates VA_ARGS */
3451 while ((parlevel
> 0 ||
3453 (tok
!= ',' || sa
->type
.t
)))) {
3454 if (tok
== TOK_EOF
|| tok
== 0)
3458 else if (tok
== ')')
3460 if (tok
== TOK_LINEFEED
)
3462 if (!check_space(tok
, &spc
))
3463 tok_str_add2(&str
, tok
, &tokc
);
3464 next_argstream(nested_list
, NULL
);
3469 tok_str_add(&str
, -1);
3470 tok_str_add(&str
, 0);
3471 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3475 /* special case for gcc var args: add an empty
3476 var arg argument if it is omitted */
3477 if (sa
&& sa
->type
.t
&& gnu_ext
)
3485 tcc_error("macro '%s' used with too few args",
3486 get_tok_str(s
->v
, 0));
3489 /* now subst each arg */
3490 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3495 tok_str_free_str(sa
->d
);
3497 tok_str_free_str(sa
->next
->d
);
3503 parse_flags
= saved_parse_flags
;
3506 sym_push2(nested_list
, s
->v
, 0, 0);
3507 parse_flags
= saved_parse_flags
;
3508 joined_str
= macro_twosharps(mstr
);
3509 macro_subst(tok_str
, nested_list
, joined_str
? joined_str
: mstr
);
3511 /* pop nested defined symbol */
3513 *nested_list
= sa1
->prev
;
3516 tok_str_free_str(joined_str
);
3518 tok_str_free_str(mstr
);
3523 /* do macro substitution of macro_str and add result to
3524 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3525 inside to avoid recursing. */
3526 static void macro_subst(
3527 TokenString
*tok_str
,
3529 const int *macro_str
3533 int t
, spc
, nosubst
;
3539 TOK_GET(&t
, ¯o_str
, &cval
);
3543 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3548 /* if nested substitution, do nothing */
3549 if (sym_find2(*nested_list
, t
)) {
3550 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3551 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3556 TokenString
*str
= tok_str_alloc();
3557 str
->str
= (int*)macro_str
;
3558 begin_macro(str
, 2);
3561 macro_subst_tok(tok_str
, nested_list
, s
);
3563 if (macro_stack
!= str
) {
3564 /* already finished by reading function macro arguments */
3568 macro_str
= macro_ptr
;
3572 spc
= is_space(t
= tok_str
->str
[tok_str
->lastlen
]);
3575 if (!check_space(t
, &spc
))
3576 tok_str_add2(tok_str
, t
, &cval
);
3579 if (nosubst
> 1 && (spc
|| (++nosubst
== 3 && t
== '(')))
3583 if (t
== TOK_NOSUBST
)
3586 /* GCC supports 'defined' as result of a macro substitution */
3587 if (t
== TOK_DEFINED
&& pp_expr
)
3592 /* return next token without macro substitution. Can read input from
3594 static void next_nomacro(void)
3600 if (TOK_HAS_VALUE(t
)) {
3601 tok_get(&tok
, ¯o_ptr
, &tokc
);
3602 if (t
== TOK_LINENUM
) {
3603 file
->line_num
= tokc
.i
;
3608 if (t
< TOK_IDENT
) {
3609 if (!(parse_flags
& PARSE_FLAG_SPACES
)
3610 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
))
3620 /* return next token with macro substitution */
3621 ST_FUNC
void next(void)
3628 if (!TOK_HAS_VALUE(t
)) {
3629 if (t
== TOK_NOSUBST
|| t
== TOK_PLCHLDR
) {
3630 /* discard preprocessor markers */
3632 } else if (t
== 0) {
3633 /* end of macro or unget token string */
3636 } else if (t
== '\\') {
3637 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3638 tcc_error("stray '\\' in program");
3642 } else if (t
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3643 /* if reading from file, try to substitute macros */
3644 Sym
*s
= define_find(t
);
3646 Sym
*nested_list
= NULL
;
3648 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3649 tok_str_add(&tokstr_buf
, 0);
3650 begin_macro(&tokstr_buf
, 0);
3655 /* convert preprocessor tokens into C tokens */
3656 if (t
== TOK_PPNUM
) {
3657 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3658 parse_number((char *)tokc
.str
.data
);
3659 } else if (t
== TOK_PPSTR
) {
3660 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3661 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3665 /* push back current token and set current token to 'last_tok'. Only
3666 identifier case handled for labels. */
3667 ST_INLN
void unget_tok(int last_tok
)
3670 TokenString
*str
= tok_str_alloc();
3671 tok_str_add2(str
, tok
, &tokc
);
3672 tok_str_add(str
, 0);
3673 begin_macro(str
, 1);
3677 /* ------------------------------------------------------------------------- */
3678 /* init preprocessor */
3680 static const char * const target_os_defs
=
3681 #ifdef TCC_TARGET_PE
3687 # if defined TCC_TARGET_MACHO
3689 # elif TARGETOS_FreeBSD
3691 # elif TARGETOS_FreeBSD_kernel
3692 "__FreeBSD_kernel__\0"
3693 # elif TARGETOS_NetBSD
3695 # elif TARGETOS_OpenBSD
3706 static void putdef(CString
*cs
, const char *p
)
3708 cstr_printf(cs
, "#define %s%s\n", p
, &" 1"[!!strchr(p
, ' ')*2]);
3711 static void tcc_predefs(TCCState
*s1
, CString
*cs
, int is_asm
)
3714 const char *defs
[] = { target_machine_defs
, target_os_defs
, NULL
};
3717 sscanf(TCC_VERSION
, "%d.%d.%d", &a
, &b
, &c
);
3718 cstr_printf(cs
, "#define __TINYC__ %d\n", a
*10000 + b
*100 + c
);
3719 for (a
= 0; defs
[a
]; ++a
)
3720 for (p
= defs
[a
]; *p
; p
= strchr(p
, 0) + 1)
3722 #ifdef TCC_TARGET_ARM
3723 if (s1
->float_abi
== ARM_HARD_FLOAT
)
3724 putdef(cs
, "__ARM_PCS_VFP");
3727 putdef(cs
, "__ASSEMBLER__");
3728 if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
)
3729 putdef(cs
, "__TCC_PP__");
3730 if (s1
->output_type
== TCC_OUTPUT_MEMORY
)
3731 putdef(cs
, "__TCC_RUN__");
3732 if (s1
->char_is_unsigned
)
3733 putdef(cs
, "__CHAR_UNSIGNED__");
3734 if (s1
->optimize
> 0)
3735 putdef(cs
, "__OPTIMIZE__");
3736 if (s1
->optimize
== 's')
3737 putdef(cs
, "__OPTIMIZE_SIZE__");
3738 if (s1
->option_pthread
)
3739 putdef(cs
, "_REENTRANT");
3740 if (s1
->leading_underscore
)
3741 putdef(cs
, "__leading_underscore");
3742 #ifdef CONFIG_TCC_BCHECK
3743 if (s1
->do_bounds_check
)
3744 putdef(cs
, "__BOUNDS_CHECKING_ON");
3746 cstr_printf(cs
, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE
);
3747 cstr_printf(cs
, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE
);
3749 putdef(cs
, "__STDC__");
3750 cstr_printf(cs
, "#define __STDC_VERSION__ %dL\n", s1
->cversion
);
3752 /* load more predefs and __builtins */
3753 #if CONFIG_TCC_PREDEFS
3754 #include "tccdefs_.h" /* include as strings */
3756 "#include <tccdefs.h>\n" /* load at runtime */
3760 cstr_printf(cs
, "#define __BASE_FILE__ \"%s\"\n", file
->filename
);
3763 ST_FUNC
void preprocess_start(TCCState
*s1
, int filetype
)
3765 int is_asm
= !!(filetype
& (AFF_TYPE_ASM
|AFF_TYPE_ASMPP
));
3770 s1
->include_stack_ptr
= s1
->include_stack
;
3771 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3772 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3775 pp_debug_tok
= pp_debug_symv
= 0;
3777 s1
->pack_stack
[0] = 0;
3778 s1
->pack_stack_ptr
= s1
->pack_stack
;
3780 set_idnum('$', !is_asm
&& s1
->dollars_in_identifiers
? IS_ID
: 0);
3781 set_idnum('.', is_asm
? IS_ID
: 0);
3783 if (!(filetype
& AFF_TYPE_ASM
)) {
3785 tcc_predefs(s1
, &cstr
, is_asm
);
3786 if (s1
->cmdline_defs
.size
)
3787 cstr_cat(&cstr
, s1
->cmdline_defs
.data
, s1
->cmdline_defs
.size
);
3788 if (s1
->cmdline_incl
.size
)
3789 cstr_cat(&cstr
, s1
->cmdline_incl
.data
, s1
->cmdline_incl
.size
);
3790 //printf("%s\n", (char*)cstr.data);
3791 *s1
->include_stack_ptr
++ = file
;
3792 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3793 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3797 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3798 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3801 /* cleanup from error/setjmp */
3802 ST_FUNC
void preprocess_end(TCCState
*s1
)
3812 ST_FUNC
void tccpp_new(TCCState
*s
)
3817 /* init isid table */
3818 for(i
= CH_EOF
; i
<128; i
++)
3820 is_space(i
) ? IS_SPC
3825 for(i
= 128; i
<256; i
++)
3826 set_idnum(i
, IS_ID
);
3828 /* init allocators */
3829 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3830 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3832 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3833 memset(s
->cached_includes_hash
, 0, sizeof s
->cached_includes_hash
);
3835 cstr_new(&cstr_buf
);
3836 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3837 tok_str_new(&tokstr_buf
);
3838 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3840 tok_ident
= TOK_IDENT
;
3849 tok_alloc(p
, r
- p
- 1);
3853 /* we add dummy defines for some special macros to speed up tests
3854 and to have working defined() */
3855 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
3856 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
3857 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
3858 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
3859 define_push(TOK___COUNTER__
, MACRO_OBJ
, NULL
, NULL
);
3862 ST_FUNC
void tccpp_delete(TCCState
*s
)
3866 dynarray_reset(&s
->cached_includes
, &s
->nb_cached_includes
);
3869 n
= tok_ident
- TOK_IDENT
;
3870 if (n
> total_idents
)
3872 for(i
= 0; i
< n
; i
++)
3873 tal_free(toksym_alloc
, table_ident
[i
]);
3874 tcc_free(table_ident
);
3877 /* free static buffers */
3878 cstr_free(&tokcstr
);
3879 cstr_free(&cstr_buf
);
3880 cstr_free(¯o_equal_buf
);
3881 tok_str_free_str(tokstr_buf
.str
);
3883 /* free allocators */
3884 tal_delete(toksym_alloc
);
3885 toksym_alloc
= NULL
;
3886 tal_delete(tokstr_alloc
);
3887 tokstr_alloc
= NULL
;
3890 /* ------------------------------------------------------------------------- */
3891 /* tcc -E [-P[1]] [-dD} support */
3893 static void tok_print(const char *msg
, const int *str
)
3899 fp
= tcc_state
->ppfp
;
3900 fprintf(fp
, "%s", msg
);
3902 TOK_GET(&t
, &str
, &cval
);
3905 fprintf(fp
, &" %s"[s
], get_tok_str(t
, &cval
)), s
= 1;
3910 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3912 int d
= f
->line_num
- f
->line_ref
;
3917 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3919 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3921 fputs("\n", s1
->ppfp
), --d
;
3922 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3923 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3925 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3926 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3928 f
->line_ref
= f
->line_num
;
3931 static void define_print(TCCState
*s1
, int v
)
3937 if (NULL
== s
|| NULL
== s
->d
)
3941 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3942 if (s
->type
.t
== MACRO_FUNC
) {
3947 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3954 tok_print("", s
->d
);
3957 static void pp_debug_defines(TCCState
*s1
)
3968 pp_line(s1
, file
, 0);
3969 file
->line_ref
= ++file
->line_num
;
3973 vs
= get_tok_str(v
, NULL
);
3974 if (t
== TOK_DEFINE
) {
3975 define_print(s1
, v
);
3976 } else if (t
== TOK_UNDEF
) {
3977 fprintf(fp
, "#undef %s\n", vs
);
3978 } else if (t
== TOK_push_macro
) {
3979 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3980 } else if (t
== TOK_pop_macro
) {
3981 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3986 static void pp_debug_builtins(TCCState
*s1
)
3989 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3990 define_print(s1
, v
);
3993 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3994 static int pp_need_space(int a
, int b
)
3996 return 'E' == a
? '+' == b
|| '-' == b
3997 : '+' == a
? TOK_INC
== b
|| '+' == b
3998 : '-' == a
? TOK_DEC
== b
|| '-' == b
3999 : a
>= TOK_IDENT
? b
>= TOK_IDENT
4000 : a
== TOK_PPNUM
? b
>= TOK_IDENT
4004 /* maybe hex like 0x1e */
4005 static int pp_check_he0xE(int t
, const char *p
)
4007 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
4012 /* Preprocess the current file */
4013 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
4015 BufferedFile
**iptr
;
4016 int token_seen
, spcs
, level
;
4020 parse_flags
= PARSE_FLAG_PREPROCESS
4021 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
4022 | PARSE_FLAG_LINEFEED
4024 | PARSE_FLAG_ACCEPT_STRAYS
4026 /* Credits to Fabrice Bellard's initial revision to demonstrate its
4027 capability to compile and run itself, provided all numbers are
4028 given as decimals. tcc -E -P10 will do. */
4029 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
4030 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
4033 /* for PP benchmarks */
4034 do next(); while (tok
!= TOK_EOF
);
4038 if (s1
->dflag
& 1) {
4039 pp_debug_builtins(s1
);
4043 token_seen
= TOK_LINEFEED
, spcs
= 0, level
= 0;
4045 pp_line(s1
, file
->prev
, level
++);
4046 pp_line(s1
, file
, level
);
4048 iptr
= s1
->include_stack_ptr
;
4053 level
= s1
->include_stack_ptr
- iptr
;
4056 pp_line(s1
, *iptr
, 0);
4057 pp_line(s1
, file
, level
);
4059 if (s1
->dflag
& 7) {
4060 pp_debug_defines(s1
);
4065 if (is_space(tok
)) {
4066 if (spcs
< sizeof white
- 1)
4067 white
[spcs
++] = tok
;
4069 } else if (tok
== TOK_LINEFEED
) {
4071 if (token_seen
== TOK_LINEFEED
)
4074 } else if (token_seen
== TOK_LINEFEED
) {
4075 pp_line(s1
, file
, 0);
4076 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
4077 white
[spcs
++] = ' ';
4080 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
4081 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
4082 token_seen
= pp_check_he0xE(tok
, p
);
4087 /* ------------------------------------------------------------------------- */