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
,
95 static void next_nomacro_spc(void);
97 ST_FUNC
void skip(int c
)
100 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
104 ST_FUNC
void expect(const char *msg
)
106 tcc_error("%s expected", msg
);
109 /* ------------------------------------------------------------------------- */
110 /* Custom allocator for tiny objects */
112 #ifndef __BOUNDS_CHECKING_ON
117 #define tal_free(al, p) tcc_free(p)
118 #define tal_realloc(al, p, size) tcc_realloc(p, size)
119 #define tal_new(a,b,c)
120 #define tal_delete(a)
122 #if !defined(MEM_DEBUG)
123 #define tal_free(al, p) tal_free_impl(al, p)
124 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
125 #define TAL_DEBUG_PARAMS
128 //#define TAL_INFO 1 /* collect and dump allocators stats */
129 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
130 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
131 #define TAL_DEBUG_PARAMS , const char *file, int line
132 #define TAL_DEBUG_FILE_LEN 40
135 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
136 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
137 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
138 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
139 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
140 #define CSTR_TAL_LIMIT 1024
142 typedef struct TinyAlloc
{
148 struct TinyAlloc
*next
, *top
;
157 typedef struct tal_header_t
{
160 int line_num
; /* negative line_num used for double free check */
161 char file_name
[TAL_DEBUG_FILE_LEN
+ 1];
165 /* ------------------------------------------------------------------------- */
167 static TinyAlloc
*tal_new(TinyAlloc
**pal
, unsigned limit
, unsigned size
)
169 TinyAlloc
*al
= tcc_mallocz(sizeof(TinyAlloc
));
170 al
->p
= al
->buffer
= tcc_malloc(size
);
177 static void tal_delete(TinyAlloc
*al
)
185 fprintf(stderr
, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
186 al
->limit
, al
->size
/ 1024.0 / 1024.0, al
->nb_peak
, al
->nb_total
, al
->nb_missed
,
187 (al
->peak_p
- al
->buffer
) * 100.0 / al
->size
);
190 if (al
->nb_allocs
> 0) {
192 fprintf(stderr
, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
193 al
->nb_allocs
, al
->limit
);
196 tal_header_t
*header
= (tal_header_t
*)p
;
197 if (header
->line_num
> 0) {
198 fprintf(stderr
, "%s:%d: chunk of %d bytes leaked\n",
199 header
->file_name
, header
->line_num
, header
->size
);
201 p
+= header
->size
+ sizeof(tal_header_t
);
209 tcc_free(al
->buffer
);
215 static void tal_free_impl(TinyAlloc
*al
, void *p TAL_DEBUG_PARAMS
)
220 if (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
) {
222 tal_header_t
*header
= (((tal_header_t
*)p
) - 1);
223 if (header
->line_num
< 0) {
224 fprintf(stderr
, "%s:%d: TAL_DEBUG: double frees chunk from\n",
226 fprintf(stderr
, "%s:%d: %d bytes\n",
227 header
->file_name
, (int)-header
->line_num
, (int)header
->size
);
229 header
->line_num
= -header
->line_num
;
234 } else if (al
->next
) {
242 static void *tal_realloc_impl(TinyAlloc
**pal
, void *p
, unsigned size TAL_DEBUG_PARAMS
)
244 tal_header_t
*header
;
247 unsigned adj_size
= (size
+ 3) & -4;
248 TinyAlloc
*al
= *pal
;
251 is_own
= (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
);
252 if ((!p
|| is_own
) && size
<= al
->limit
) {
253 if (al
->p
+ adj_size
+ sizeof(tal_header_t
) < al
->buffer
+ al
->size
) {
254 header
= (tal_header_t
*)al
->p
;
255 header
->size
= adj_size
;
257 { int ofs
= strlen(file
) - TAL_DEBUG_FILE_LEN
;
258 strncpy(header
->file_name
, file
+ (ofs
> 0 ? ofs
: 0), TAL_DEBUG_FILE_LEN
);
259 header
->file_name
[TAL_DEBUG_FILE_LEN
] = 0;
260 header
->line_num
= line
; }
262 ret
= al
->p
+ sizeof(tal_header_t
);
263 al
->p
+= adj_size
+ sizeof(tal_header_t
);
265 header
= (((tal_header_t
*)p
) - 1);
266 memcpy(ret
, p
, header
->size
);
268 header
->line_num
= -header
->line_num
;
274 if (al
->nb_peak
< al
->nb_allocs
)
275 al
->nb_peak
= al
->nb_allocs
;
276 if (al
->peak_p
< al
->p
)
283 ret
= tal_realloc(*pal
, 0, size
);
284 header
= (((tal_header_t
*)p
) - 1);
285 memcpy(ret
, p
, header
->size
);
287 header
->line_num
= -header
->line_num
;
294 TinyAlloc
*bottom
= al
, *next
= al
->top
? al
->top
: al
;
296 al
= tal_new(pal
, next
->limit
, next
->size
* 2);
304 ret
= tcc_malloc(size
);
305 header
= (((tal_header_t
*)p
) - 1);
306 memcpy(ret
, p
, header
->size
);
308 header
->line_num
= -header
->line_num
;
310 } else if (al
->next
) {
314 ret
= tcc_realloc(p
, size
);
323 /* ------------------------------------------------------------------------- */
324 /* CString handling */
325 static void cstr_realloc(CString
*cstr
, int new_size
)
329 size
= cstr
->size_allocated
;
331 size
= 8; /* no need to allocate a too small first string */
332 while (size
< new_size
)
334 cstr
->data
= tcc_realloc(cstr
->data
, size
);
335 cstr
->size_allocated
= size
;
339 ST_INLN
void cstr_ccat(CString
*cstr
, int ch
)
342 size
= cstr
->size
+ 1;
343 if (size
> cstr
->size_allocated
)
344 cstr_realloc(cstr
, size
);
345 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
349 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
, int len
)
353 len
= strlen(str
) + 1 + len
;
354 size
= cstr
->size
+ len
;
355 if (size
> cstr
->size_allocated
)
356 cstr_realloc(cstr
, size
);
357 memmove(((unsigned char *)cstr
->data
) + cstr
->size
, str
, len
);
361 /* add a wide char */
362 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
365 size
= cstr
->size
+ sizeof(nwchar_t
);
366 if (size
> cstr
->size_allocated
)
367 cstr_realloc(cstr
, size
);
368 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
372 ST_FUNC
void cstr_new(CString
*cstr
)
374 memset(cstr
, 0, sizeof(CString
));
377 /* free string and reset it to NULL */
378 ST_FUNC
void cstr_free(CString
*cstr
)
380 tcc_free(cstr
->data
);
384 /* reset string to empty */
385 ST_FUNC
void cstr_reset(CString
*cstr
)
390 ST_FUNC
int cstr_printf(CString
*cstr
, const char *fmt
, ...)
396 len
= vsnprintf(NULL
, 0, fmt
, v
);
398 size
= cstr
->size
+ len
+ 1;
399 if (size
> cstr
->size_allocated
)
400 cstr_realloc(cstr
, size
);
402 vsnprintf((char*)cstr
->data
+ cstr
->size
, size
, fmt
, v
);
409 static void add_char(CString
*cstr
, int c
)
411 if (c
== '\'' || c
== '\"' || c
== '\\') {
412 /* XXX: could be more precise if char or string */
413 cstr_ccat(cstr
, '\\');
415 if (c
>= 32 && c
<= 126) {
418 cstr_ccat(cstr
, '\\');
420 cstr_ccat(cstr
, 'n');
422 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
423 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
424 cstr_ccat(cstr
, '0' + (c
& 7));
429 /* ------------------------------------------------------------------------- */
430 /* allocate a new token */
431 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
433 TokenSym
*ts
, **ptable
;
436 if (tok_ident
>= SYM_FIRST_ANOM
)
437 tcc_error("memory full (symbols)");
439 /* expand token table if needed */
440 i
= tok_ident
- TOK_IDENT
;
441 if ((i
% TOK_ALLOC_INCR
) == 0) {
442 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
443 table_ident
= ptable
;
446 ts
= tal_realloc(toksym_alloc
, 0, sizeof(TokenSym
) + len
);
448 ts
->tok
= tok_ident
++;
449 ts
->sym_define
= NULL
;
450 ts
->sym_label
= NULL
;
451 ts
->sym_struct
= NULL
;
452 ts
->sym_identifier
= NULL
;
454 ts
->hash_next
= NULL
;
455 memcpy(ts
->str
, str
, len
);
461 #define TOK_HASH_INIT 1
462 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
465 /* find a token and add it if not found */
466 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
474 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
475 h
&= (TOK_HASH_SIZE
- 1);
477 pts
= &hash_ident
[h
];
482 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
484 pts
= &(ts
->hash_next
);
486 return tok_alloc_new(pts
, str
, len
);
489 /* XXX: buffer overflow */
490 /* XXX: float tokens */
491 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
496 cstr_reset(&cstr_buf
);
506 /* XXX: not quite exact, but only useful for testing */
508 sprintf(p
, "%u", (unsigned)cv
->i
);
510 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
514 cstr_ccat(&cstr_buf
, 'L');
516 cstr_ccat(&cstr_buf
, '\'');
517 add_char(&cstr_buf
, cv
->i
);
518 cstr_ccat(&cstr_buf
, '\'');
519 cstr_ccat(&cstr_buf
, '\0');
523 return (char*)cv
->str
.data
;
525 cstr_ccat(&cstr_buf
, 'L');
527 cstr_ccat(&cstr_buf
, '\"');
529 len
= cv
->str
.size
- 1;
531 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
533 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
535 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
537 cstr_ccat(&cstr_buf
, '\"');
538 cstr_ccat(&cstr_buf
, '\0');
542 cstr_cat(&cstr_buf
, "<float>", 0);
545 cstr_cat(&cstr_buf
, "<double>", 0);
548 cstr_cat(&cstr_buf
, "<long double>", 0);
551 cstr_cat(&cstr_buf
, "<linenumber>", 0);
554 /* above tokens have value, the ones below don't */
562 return strcpy(p
, "...");
564 return strcpy(p
, "<<=");
566 return strcpy(p
, ">>=");
568 return strcpy(p
, "<eof>");
571 /* search in two bytes table */
572 const unsigned char *q
= tok_two_chars
;
578 return cstr_buf
.data
;
583 sprintf(cstr_buf
.data
, "<%02x>", v
);
584 return cstr_buf
.data
;
589 } else if (v
< tok_ident
) {
590 return table_ident
[v
- TOK_IDENT
]->str
;
591 } else if (v
>= SYM_FIRST_ANOM
) {
592 /* special name for anonymous symbol */
593 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
595 /* should never happen */
600 return cstr_buf
.data
;
603 /* return the current character, handling end of block if necessary
605 static int handle_eob(void)
607 BufferedFile
*bf
= file
;
610 /* only tries to read if really end of buffer */
611 if (bf
->buf_ptr
>= bf
->buf_end
) {
613 #if defined(PARSE_DEBUG)
618 len
= read(bf
->fd
, bf
->buffer
, len
);
625 bf
->buf_ptr
= bf
->buffer
;
626 bf
->buf_end
= bf
->buffer
+ len
;
627 *bf
->buf_end
= CH_EOB
;
629 if (bf
->buf_ptr
< bf
->buf_end
) {
630 return bf
->buf_ptr
[0];
632 bf
->buf_ptr
= bf
->buf_end
;
637 /* read next char from current input file and handle end of input buffer */
638 static inline void inp(void)
640 ch
= *(++(file
->buf_ptr
));
641 /* end of buffer/file handling */
646 /* handle '\[\r]\n' */
647 static int handle_stray_noerror(void)
654 } else if (ch
== '\r') {
668 static void handle_stray(void)
670 if (handle_stray_noerror())
671 tcc_error("stray '\\' in program");
674 /* skip the stray and handle the \\n case. Output an error if
675 incorrect char after the stray */
676 static int handle_stray1(uint8_t *p
)
681 if (p
>= file
->buf_end
) {
688 if (handle_stray_noerror()) {
689 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
690 tcc_error("stray '\\' in program");
691 *--file
->buf_ptr
= '\\';
698 /* handle just the EOB case, but not stray */
699 #define PEEKC_EOB(c, p)\
710 /* handle the complicated stray case */
716 c = handle_stray1(p);\
721 /* input with '\[\r]\n' handling. Note that this function cannot
722 handle other characters after '\', so you cannot call it inside
723 strings or comments */
724 static void minp(void)
731 /* single line C++ comments */
732 static uint8_t *parse_line_comment(uint8_t *p
)
740 if (c
== '\n' || c
== CH_EOF
) {
742 } else if (c
== '\\') {
751 } else if (c
== '\r') {
769 static uint8_t *parse_comment(uint8_t *p
)
778 if (c
== '\n' || c
== '*' || c
== '\\')
782 if (c
== '\n' || c
== '*' || c
== '\\')
786 /* now we can handle all the cases */
790 } else if (c
== '*') {
796 } else if (c
== '/') {
798 } else if (c
== '\\') {
803 tcc_error("unexpected end of file in comment");
805 /* skip '\[\r]\n', otherwise just skip the stray */
811 } else if (c
== '\r') {
828 /* stray, eob or eof */
833 tcc_error("unexpected end of file in comment");
834 } else if (c
== '\\') {
844 ST_FUNC
int set_idnum(int c
, int val
)
846 int prev
= isidnum_table
[c
- CH_EOF
];
847 isidnum_table
[c
- CH_EOF
] = val
;
853 static inline void skip_spaces(void)
855 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
859 static inline int check_space(int t
, int *spc
)
861 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
870 /* parse a string without interpreting escapes */
871 static uint8_t *parse_pp_string(uint8_t *p
,
872 int sep
, CString
*str
)
880 } else if (c
== '\\') {
886 /* XXX: indicate line number of start of string */
887 tcc_error("missing terminating %c character", sep
);
888 } else if (c
== '\\') {
889 /* escape : just skip \[\r]\n */
894 } else if (c
== '\r') {
897 expect("'\n' after '\r'");
900 } else if (c
== CH_EOF
) {
901 goto unterminated_string
;
904 cstr_ccat(str
, '\\');
910 } else if (c
== '\n') {
913 } else if (c
== '\r') {
917 cstr_ccat(str
, '\r');
933 /* skip block of text until #else, #elif or #endif. skip also pairs of
935 static void preprocess_skip(void)
937 int a
, start_of_line
, c
, in_warn_or_error
;
944 in_warn_or_error
= 0;
965 } else if (c
== '\\') {
966 ch
= file
->buf_ptr
[0];
967 handle_stray_noerror();
974 if (in_warn_or_error
)
976 p
= parse_pp_string(p
, c
, NULL
);
980 if (in_warn_or_error
)
987 p
= parse_comment(p
);
988 } else if (ch
== '/') {
989 p
= parse_line_comment(p
);
999 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
1001 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
1003 else if (tok
== TOK_ENDIF
)
1005 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
1006 in_warn_or_error
= 1;
1007 else if (tok
== TOK_LINEFEED
)
1009 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1010 p
= parse_line_comment(p
- 1);
1011 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1012 p
= parse_line_comment(p
- 1);
1026 /* return the number of additional 'ints' necessary to store the
1028 static inline int tok_size(const int *p
)
1043 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
1046 return 1 + LONG_SIZE
/ 4;
1052 return 1 + LDOUBLE_SIZE
/ 4;
1059 /* token string handling */
1060 ST_INLN
void tok_str_new(TokenString
*s
)
1063 s
->len
= s
->lastlen
= 0;
1064 s
->allocated_len
= 0;
1065 s
->last_line_num
= -1;
1068 ST_FUNC TokenString
*tok_str_alloc(void)
1070 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1075 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1079 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1080 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1084 ST_FUNC
void tok_str_free_str(int *str
)
1086 tal_free(tokstr_alloc
, str
);
1089 ST_FUNC
void tok_str_free(TokenString
*str
)
1091 tok_str_free_str(str
->str
);
1092 tal_free(tokstr_alloc
, str
);
1095 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1099 size
= s
->allocated_len
;
1102 while (size
< new_size
)
1104 if (size
> s
->allocated_len
) {
1105 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1106 s
->allocated_len
= size
;
1112 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1118 if (len
>= s
->allocated_len
)
1119 str
= tok_str_realloc(s
, len
+ 1);
1124 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1127 str
->prev
= macro_stack
;
1128 str
->prev_ptr
= macro_ptr
;
1129 str
->save_line_num
= file
->line_num
;
1130 macro_ptr
= str
->str
;
1134 ST_FUNC
void end_macro(void)
1136 TokenString
*str
= macro_stack
;
1137 macro_stack
= str
->prev
;
1138 macro_ptr
= str
->prev_ptr
;
1139 file
->line_num
= str
->save_line_num
;
1140 if (str
->alloc
!= 0) {
1141 if (str
->alloc
== 2)
1142 str
->str
= NULL
; /* don't free */
1147 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1151 len
= s
->lastlen
= s
->len
;
1154 /* allocate space for worst case */
1155 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1156 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1169 str
[len
++] = cv
->tab
[0];
1176 /* Insert the string into the int array. */
1178 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1179 if (len
+ nb_words
>= s
->allocated_len
)
1180 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1181 str
[len
] = cv
->str
.size
;
1182 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1193 #if LDOUBLE_SIZE == 8
1196 str
[len
++] = cv
->tab
[0];
1197 str
[len
++] = cv
->tab
[1];
1199 #if LDOUBLE_SIZE == 12
1201 str
[len
++] = cv
->tab
[0];
1202 str
[len
++] = cv
->tab
[1];
1203 str
[len
++] = cv
->tab
[2];
1204 #elif LDOUBLE_SIZE == 16
1206 str
[len
++] = cv
->tab
[0];
1207 str
[len
++] = cv
->tab
[1];
1208 str
[len
++] = cv
->tab
[2];
1209 str
[len
++] = cv
->tab
[3];
1210 #elif LDOUBLE_SIZE != 8
1211 #error add long double size support
1220 /* add the current parse token in token string 's' */
1221 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1225 /* save line number info */
1226 if (file
->line_num
!= s
->last_line_num
) {
1227 s
->last_line_num
= file
->line_num
;
1228 cval
.i
= s
->last_line_num
;
1229 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1231 tok_str_add2(s
, tok
, &tokc
);
1234 /* get a token from an integer array and increment pointer. */
1235 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1255 cv
->i
= (unsigned)*p
++;
1264 cv
->str
.size
= *p
++;
1266 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1278 #if LDOUBLE_SIZE == 16
1280 #elif LDOUBLE_SIZE == 12
1282 #elif LDOUBLE_SIZE == 8
1285 # error add long double size support
1298 static int macro_is_equal(const int *a
, const int *b
)
1307 /* first time preallocate macro_equal_buf, next time only reset position to start */
1308 cstr_reset(¯o_equal_buf
);
1309 TOK_GET(&t
, &a
, &cv
);
1310 cstr_cat(¯o_equal_buf
, get_tok_str(t
, &cv
), 0);
1311 TOK_GET(&t
, &b
, &cv
);
1312 if (strcmp(macro_equal_buf
.data
, get_tok_str(t
, &cv
)))
1318 /* defines handling */
1319 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1324 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1326 s
->next
= first_arg
;
1327 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1329 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1330 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1333 /* undefined a define symbol. Its name is just set to zero */
1334 ST_FUNC
void define_undef(Sym
*s
)
1337 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1338 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1341 ST_INLN Sym
*define_find(int v
)
1344 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1346 return table_ident
[v
]->sym_define
;
1349 /* free define stack until top reaches 'b' */
1350 ST_FUNC
void free_defines(Sym
*b
)
1352 while (define_stack
!= b
) {
1353 Sym
*top
= define_stack
;
1354 define_stack
= top
->prev
;
1355 tok_str_free_str(top
->d
);
1362 ST_FUNC Sym
*label_find(int v
)
1365 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1367 return table_ident
[v
]->sym_label
;
1370 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1373 s
= sym_push2(ptop
, v
, 0, 0);
1375 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1376 if (ptop
== &global_label_stack
) {
1377 /* modify the top most local identifier, so that
1378 sym_identifier will point to 's' when popped */
1380 ps
= &(*ps
)->prev_tok
;
1387 /* pop labels until element last is reached. Look if any labels are
1388 undefined. Define symbols if '&&label' was used. */
1389 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
, int keep
)
1392 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1394 if (s
->r
== LABEL_DECLARED
) {
1395 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1396 } else if (s
->r
== LABEL_FORWARD
) {
1397 tcc_error("label '%s' used but not defined",
1398 get_tok_str(s
->v
, NULL
));
1401 /* define corresponding symbol. A size of
1403 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1407 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1415 /* fake the nth "#if defined test_..." for tcc -dt -run */
1416 static void maybe_run_test(TCCState
*s
)
1419 if (s
->include_stack_ptr
!= s
->include_stack
)
1421 p
= get_tok_str(tok
, NULL
);
1422 if (0 != memcmp(p
, "test_", 5))
1424 if (0 != --s
->run_test
)
1426 fprintf(s
->ppfp
, "\n[%s]\n" + !(s
->dflag
& 32), p
), fflush(s
->ppfp
);
1427 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1430 /* eval an expression for #if/#elif */
1431 static int expr_preprocess(void)
1436 str
= tok_str_alloc();
1438 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1439 next(); /* do macro subst */
1440 if (tok
== TOK_DEFINED
) {
1445 if (tok
< TOK_IDENT
)
1446 expect("identifier");
1447 if (tcc_state
->run_test
)
1448 maybe_run_test(tcc_state
);
1449 c
= define_find(tok
) != 0;
1457 } else if (tok
>= TOK_IDENT
) {
1458 /* if undefined macro */
1462 tok_str_add_tok(str
);
1465 tok_str_add(str
, -1); /* simulate end of file */
1466 tok_str_add(str
, 0);
1467 /* now evaluate C constant expression */
1468 begin_macro(str
, 1);
1476 /* parse after #define */
1477 ST_FUNC
void parse_define(void)
1479 Sym
*s
, *first
, **ps
;
1480 int v
, t
, varg
, is_vaargs
, spc
;
1481 int saved_parse_flags
= parse_flags
;
1484 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1485 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1486 /* XXX: should check if same macro (ANSI) */
1489 /* We have to parse the whole define as if not in asm mode, in particular
1490 no line comment with '#' must be ignored. Also for function
1491 macros the argument list must be parsed without '.' being an ID
1493 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1494 /* '(' must be just after macro definition for MACRO_FUNC */
1497 int dotid
= set_idnum('.', 0);
1500 if (tok
!= ')') for (;;) {
1504 if (varg
== TOK_DOTS
) {
1505 varg
= TOK___VA_ARGS__
;
1507 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1511 if (varg
< TOK_IDENT
)
1513 tcc_error("bad macro parameter list");
1514 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1519 if (tok
!= ',' || is_vaargs
)
1525 set_idnum('.', dotid
);
1530 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1531 /* The body of a macro definition should be parsed such that identifiers
1532 are parsed like the file mode determines (i.e. with '.' being an
1533 ID character in asm mode). But '#' should be retained instead of
1534 regarded as line comment leader, so still don't set ASM_FILE
1536 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1537 /* remove spaces around ## and after '#' */
1538 if (TOK_TWOSHARPS
== tok
) {
1545 } else if ('#' == tok
) {
1547 } else if (check_space(tok
, &spc
)) {
1550 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1555 parse_flags
= saved_parse_flags
;
1557 --tokstr_buf
.len
; /* remove trailing space */
1558 tok_str_add(&tokstr_buf
, 0);
1561 tcc_error("'##' cannot appear at either end of macro");
1562 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1565 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1567 const unsigned char *s
;
1573 s
= (unsigned char *) filename
;
1576 h
= TOK_HASH_FUNC(h
, toup(*s
));
1578 h
= TOK_HASH_FUNC(h
, *s
);
1582 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1584 i
= s1
->cached_includes_hash
[h
];
1588 e
= s1
->cached_includes
[i
- 1];
1589 if (0 == PATHCMP(e
->filename
, filename
))
1596 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1597 strcpy(e
->filename
, filename
);
1598 e
->ifndef_macro
= e
->once
= 0;
1599 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1600 /* add in hash table */
1601 e
->hash_next
= s1
->cached_includes_hash
[h
];
1602 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1604 printf("adding cached '%s'\n", filename
);
1609 static void pragma_parse(TCCState
*s1
)
1612 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1616 if (next(), tok
!= '(')
1618 if (next(), tok
!= TOK_STR
)
1620 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1621 if (next(), tok
!= ')')
1623 if (t
== TOK_push_macro
) {
1624 while (NULL
== (s
= define_find(v
)))
1625 define_push(v
, 0, NULL
, NULL
);
1626 s
->type
.ref
= s
; /* set push boundary */
1628 for (s
= define_stack
; s
; s
= s
->prev
)
1629 if (s
->v
== v
&& s
->type
.ref
== s
) {
1635 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1637 tcc_warning("unbalanced #pragma pop_macro");
1638 pp_debug_tok
= t
, pp_debug_symv
= v
;
1640 } else if (tok
== TOK_once
) {
1641 search_cached_include(s1
, file
->filename
, 1)->once
= pp_once
;
1643 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1644 /* tcc -E: keep pragmas below unchanged */
1646 unget_tok(TOK_PRAGMA
);
1648 unget_tok(TOK_LINEFEED
);
1650 } else if (tok
== TOK_pack
) {
1652 #pragma pack(1) // set
1653 #pragma pack() // reset to default
1654 #pragma pack(push,1) // push & set
1655 #pragma pack(pop) // restore previous */
1658 if (tok
== TOK_ASM_pop
) {
1660 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1662 tcc_error("out of pack stack");
1664 s1
->pack_stack_ptr
--;
1668 if (tok
== TOK_ASM_push
) {
1670 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1672 s1
->pack_stack_ptr
++;
1675 if (tok
!= TOK_CINT
)
1678 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1682 *s1
->pack_stack_ptr
= val
;
1687 } else if (tok
== TOK_comment
) {
1696 p
= tcc_strdup((char *)tokc
.str
.data
);
1701 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1703 if (t
== TOK_option
)
1704 tcc_set_options(s1
, p
);
1708 } else if (s1
->warn_unsupported
) {
1709 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1714 tcc_error("malformed #pragma directive");
1718 /* is_bof is true if first non space token at beginning of file */
1719 ST_FUNC
void preprocess(int is_bof
)
1721 TCCState
*s1
= tcc_state
;
1722 int i
, c
, n
, saved_parse_flags
;
1726 saved_parse_flags
= parse_flags
;
1727 parse_flags
= PARSE_FLAG_PREPROCESS
1728 | PARSE_FLAG_TOK_NUM
1729 | PARSE_FLAG_TOK_STR
1730 | PARSE_FLAG_LINEFEED
1731 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1740 pp_debug_symv
= tok
;
1746 pp_debug_symv
= tok
;
1747 s
= define_find(tok
);
1748 /* undefine symbol by putting an invalid name */
1753 case TOK_INCLUDE_NEXT
:
1754 ch
= file
->buf_ptr
[0];
1755 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1760 } else if (ch
== '\"') {
1765 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1766 if ((q
- buf
) < sizeof(buf
) - 1)
1769 if (handle_stray_noerror() == 0)
1777 /* eat all spaces and comments after include */
1778 /* XXX: slightly incorrect */
1779 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1784 /* computed #include : concatenate everything up to linefeed,
1785 the result must be one of the two accepted forms.
1786 Don't convert pp-tokens to tokens here. */
1787 parse_flags
= (PARSE_FLAG_PREPROCESS
1788 | PARSE_FLAG_LINEFEED
1789 | (parse_flags
& PARSE_FLAG_ASM_FILE
));
1792 while (tok
!= TOK_LINEFEED
) {
1793 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1797 /* check syntax and remove '<>|""' */
1798 if ((len
< 2 || ((buf
[0] != '"' || buf
[len
-1] != '"') &&
1799 (buf
[0] != '<' || buf
[len
-1] != '>'))))
1800 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1802 memmove(buf
, buf
+ 1, len
- 2);
1803 buf
[len
- 2] = '\0';
1806 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1807 tcc_error("#include recursion too deep");
1808 /* push current file on stack */
1809 *s1
->include_stack_ptr
++ = file
;
1810 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
: 0;
1811 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1812 for (; i
< n
; ++i
) {
1813 char buf1
[sizeof file
->filename
];
1818 /* check absolute include path */
1819 if (!IS_ABSPATH(buf
))
1823 } else if (i
== 1) {
1824 /* search in file's dir if "header.h" */
1827 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1828 path
= file
->true_filename
;
1829 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1832 /* search in all the include paths */
1833 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1834 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1835 pstrcpy(buf1
, sizeof(buf1
), path
);
1836 pstrcat(buf1
, sizeof(buf1
), "/");
1839 pstrcat(buf1
, sizeof(buf1
), buf
);
1840 e
= search_cached_include(s1
, buf1
, 0);
1841 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
== pp_once
)) {
1842 /* no need to parse the include because the 'ifndef macro'
1843 is defined (or had #pragma once) */
1845 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1850 if (tcc_open(s1
, buf1
) < 0)
1853 file
->include_next_index
= i
+ 1;
1855 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1857 /* update target deps */
1859 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1862 /* add include file debug info */
1863 tcc_debug_bincl(tcc_state
);
1864 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1865 ch
= file
->buf_ptr
[0];
1868 tcc_error("include file '%s' not found", buf
);
1870 --s1
->include_stack_ptr
;
1876 c
= expr_preprocess();
1882 if (tok
< TOK_IDENT
)
1883 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1887 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1889 file
->ifndef_macro
= tok
;
1892 c
= (define_find(tok
) != 0) ^ c
;
1894 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1895 tcc_error("memory full (ifdef)");
1896 *s1
->ifdef_stack_ptr
++ = c
;
1899 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1900 tcc_error("#else without matching #if");
1901 if (s1
->ifdef_stack_ptr
[-1] & 2)
1902 tcc_error("#else after #else");
1903 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1906 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1907 tcc_error("#elif without matching #if");
1908 c
= s1
->ifdef_stack_ptr
[-1];
1910 tcc_error("#elif after #else");
1911 /* last #if/#elif expression was true: we skip */
1915 c
= expr_preprocess();
1916 s1
->ifdef_stack_ptr
[-1] = c
;
1919 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1920 file
->ifndef_macro
= 0;
1929 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1930 tcc_error("#endif without matching #if");
1931 s1
->ifdef_stack_ptr
--;
1932 /* '#ifndef macro' was at the start of file. Now we check if
1933 an '#endif' is exactly at the end of file */
1934 if (file
->ifndef_macro
&&
1935 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1936 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1937 /* need to set to zero to avoid false matches if another
1938 #ifndef at middle of file */
1939 file
->ifndef_macro
= 0;
1940 while (tok
!= TOK_LINEFEED
)
1942 tok_flags
|= TOK_FLAG_ENDIF
;
1947 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1951 if (tok
!= TOK_CINT
)
1953 tcc_error("wrong #line format");
1957 if (tok
!= TOK_LINEFEED
) {
1958 if (tok
== TOK_STR
) {
1959 if (file
->true_filename
== file
->filename
)
1960 file
->true_filename
= tcc_strdup(file
->filename
);
1961 tcc_debug_putfile(s1
, (char *)tokc
.str
.data
);
1962 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1969 total_lines
+= file
->line_num
- n
;
1975 ch
= file
->buf_ptr
[0];
1978 while (ch
!= '\n' && ch
!= CH_EOF
) {
1979 if ((q
- buf
) < sizeof(buf
) - 1)
1982 if (handle_stray_noerror() == 0)
1989 tcc_error("#error %s", buf
);
1991 tcc_warning("#warning %s", buf
);
1999 /* ignore gas line comment in an 'S' file. */
2000 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
2002 if (tok
== '!' && is_bof
)
2003 /* '!' is ignored at beginning to allow C scripts. */
2005 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2007 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
2010 /* ignore other preprocess commands or #! for C scripts */
2011 while (tok
!= TOK_LINEFEED
)
2014 parse_flags
= saved_parse_flags
;
2017 /* evaluate escape codes in a string. */
2018 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2033 case '0': case '1': case '2': case '3':
2034 case '4': case '5': case '6': case '7':
2035 /* at most three octal digits */
2040 n
= n
* 8 + c
- '0';
2044 n
= n
* 8 + c
- '0';
2049 goto add_char_nonext
;
2057 if (c
>= 'a' && c
<= 'f')
2059 else if (c
>= 'A' && c
<= 'F')
2069 goto add_char_nonext
;
2093 goto invalid_escape
;
2103 if (c
>= '!' && c
<= '~')
2104 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2106 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2109 } else if (is_long
&& c
>= 0x80) {
2110 /* assume we are processing UTF-8 sequence */
2111 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2113 int cont
; /* count of continuation bytes */
2114 int skip
; /* how many bytes should skip when error occurred */
2117 /* decode leading byte */
2119 skip
= 1; goto invalid_utf8_sequence
;
2120 } else if (c
<= 0xDF) {
2121 cont
= 1; n
= c
& 0x1f;
2122 } else if (c
<= 0xEF) {
2123 cont
= 2; n
= c
& 0xf;
2124 } else if (c
<= 0xF4) {
2125 cont
= 3; n
= c
& 0x7;
2127 skip
= 1; goto invalid_utf8_sequence
;
2130 /* decode continuation bytes */
2131 for (i
= 1; i
<= cont
; i
++) {
2132 int l
= 0x80, h
= 0xBF;
2134 /* adjust limit for second byte */
2137 case 0xE0: l
= 0xA0; break;
2138 case 0xED: h
= 0x9F; break;
2139 case 0xF0: l
= 0x90; break;
2140 case 0xF4: h
= 0x8F; break;
2144 if (p
[i
] < l
|| p
[i
] > h
) {
2145 skip
= i
; goto invalid_utf8_sequence
;
2148 n
= (n
<< 6) | (p
[i
] & 0x3f);
2151 /* advance pointer */
2154 goto add_char_nonext
;
2156 /* error handling */
2157 invalid_utf8_sequence
:
2158 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c
);
2161 goto add_char_nonext
;
2167 cstr_ccat(outstr
, c
);
2169 #ifdef TCC_TARGET_PE
2170 /* store as UTF-16 */
2172 cstr_wccat(outstr
, c
);
2175 cstr_wccat(outstr
, (c
>> 10) + 0xD800);
2176 cstr_wccat(outstr
, (c
& 0x3FF) + 0xDC00);
2179 cstr_wccat(outstr
, c
);
2183 /* add a trailing '\0' */
2185 cstr_ccat(outstr
, '\0');
2187 cstr_wccat(outstr
, '\0');
2190 static void parse_string(const char *s
, int len
)
2192 uint8_t buf
[1000], *p
= buf
;
2195 if ((is_long
= *s
== 'L'))
2199 if (len
>= sizeof buf
)
2200 p
= tcc_malloc(len
+ 1);
2204 cstr_reset(&tokcstr
);
2205 parse_escape_string(&tokcstr
, p
, is_long
);
2210 int char_size
, i
, n
, c
;
2211 /* XXX: make it portable */
2213 tok
= TOK_CCHAR
, char_size
= 1;
2215 tok
= TOK_LCHAR
, char_size
= sizeof(nwchar_t
);
2216 n
= tokcstr
.size
/ char_size
- 1;
2218 tcc_error("empty character constant");
2220 tcc_warning("multi-character character constant");
2221 for (c
= i
= 0; i
< n
; ++i
) {
2223 c
= ((nwchar_t
*)tokcstr
.data
)[i
];
2225 c
= (c
<< 8) | ((char *)tokcstr
.data
)[i
];
2229 tokc
.str
.size
= tokcstr
.size
;
2230 tokc
.str
.data
= tokcstr
.data
;
2238 /* we use 64 bit numbers */
2241 /* bn = (bn << shift) | or_val */
2242 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2246 for(i
=0;i
<BN_SIZE
;i
++) {
2248 bn
[i
] = (v
<< shift
) | or_val
;
2249 or_val
= v
>> (32 - shift
);
2253 static void bn_zero(unsigned int *bn
)
2256 for(i
=0;i
<BN_SIZE
;i
++) {
2261 /* parse number in null terminated string 'p' and return it in the
2263 static void parse_number(const char *p
)
2265 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2267 unsigned int bn
[BN_SIZE
];
2278 goto float_frac_parse
;
2279 } else if (t
== '0') {
2280 if (ch
== 'x' || ch
== 'X') {
2284 } else if (tcc_state
->tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2290 /* parse all digits. cannot check octal numbers at this stage
2291 because of floating point constants */
2293 if (ch
>= 'a' && ch
<= 'f')
2295 else if (ch
>= 'A' && ch
<= 'F')
2303 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2305 tcc_error("number too long");
2311 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2312 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2314 /* NOTE: strtox should support that for hexa numbers, but
2315 non ISOC99 libcs do not support it, so we prefer to do
2317 /* hexadecimal or binary floats */
2318 /* XXX: handle overflows */
2330 } else if (t
>= 'a') {
2332 } else if (t
>= 'A') {
2337 bn_lshift(bn
, shift
, t
);
2344 if (t
>= 'a' && t
<= 'f') {
2346 } else if (t
>= 'A' && t
<= 'F') {
2348 } else if (t
>= '0' && t
<= '9') {
2354 tcc_error("invalid digit");
2355 bn_lshift(bn
, shift
, t
);
2360 if (ch
!= 'p' && ch
!= 'P')
2367 } else if (ch
== '-') {
2371 if (ch
< '0' || ch
> '9')
2372 expect("exponent digits");
2373 while (ch
>= '0' && ch
<= '9') {
2374 exp_val
= exp_val
* 10 + ch
- '0';
2377 exp_val
= exp_val
* s
;
2379 /* now we can generate the number */
2380 /* XXX: should patch directly float number */
2381 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2382 d
= ldexp(d
, exp_val
- frac_bits
);
2387 /* float : should handle overflow */
2389 } else if (t
== 'L') {
2391 #ifdef TCC_TARGET_PE
2396 /* XXX: not large enough */
2397 tokc
.ld
= (long double)d
;
2404 /* decimal floats */
2406 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2411 while (ch
>= '0' && ch
<= '9') {
2412 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2418 if (ch
== 'e' || ch
== 'E') {
2419 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2423 if (ch
== '-' || ch
== '+') {
2424 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2429 if (ch
< '0' || ch
> '9')
2430 expect("exponent digits");
2431 while (ch
>= '0' && ch
<= '9') {
2432 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2444 tokc
.f
= strtof(token_buf
, NULL
);
2445 } else if (t
== 'L') {
2447 #ifdef TCC_TARGET_PE
2449 tokc
.d
= strtod(token_buf
, NULL
);
2452 tokc
.ld
= strtold(token_buf
, NULL
);
2456 tokc
.d
= strtod(token_buf
, NULL
);
2460 unsigned long long n
, n1
;
2461 int lcount
, ucount
, ov
= 0;
2464 /* integer number */
2467 if (b
== 10 && *q
== '0') {
2474 /* no need for checks except for base 10 / 8 errors */
2484 tcc_error("invalid digit");
2487 /* detect overflow */
2488 if (n1
>= 0x1000000000000000ULL
&& n
/ b
!= n1
)
2492 /* Determine the characteristics (unsigned and/or 64bit) the type of
2493 the constant must have according to the constant suffix(es) */
2494 lcount
= ucount
= 0;
2500 tcc_error("three 'l's in integer constant");
2501 if (lcount
&& *(p
- 1) != ch
)
2502 tcc_error("incorrect integer suffix: %s", p1
);
2505 } else if (t
== 'U') {
2507 tcc_error("two 'u's in integer constant");
2515 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2516 if (ucount
== 0 && b
== 10) {
2517 if (lcount
<= (LONG_SIZE
== 4)) {
2518 if (n
>= 0x80000000U
)
2519 lcount
= (LONG_SIZE
== 4) + 1;
2521 if (n
>= 0x8000000000000000ULL
)
2524 if (lcount
<= (LONG_SIZE
== 4)) {
2525 if (n
>= 0x100000000ULL
)
2526 lcount
= (LONG_SIZE
== 4) + 1;
2527 else if (n
>= 0x80000000U
)
2530 if (n
>= 0x8000000000000000ULL
)
2535 tcc_warning("integer constant overflow");
2544 ++tok
; /* TOK_CU... */
2548 tcc_error("invalid number\n");
2552 #define PARSE2(c1, tok1, c2, tok2) \
2563 /* return next token without macro substitution */
2564 static inline void next_nomacro1(void)
2566 int t
, c
, is_long
, len
;
2579 if (parse_flags
& PARSE_FLAG_SPACES
)
2580 goto keep_tok_flags
;
2581 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2590 /* first look if it is in fact an end of buffer */
2591 c
= handle_stray1(p
);
2598 TCCState
*s1
= tcc_state
;
2599 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2600 && !(tok_flags
& TOK_FLAG_EOF
)) {
2601 tok_flags
|= TOK_FLAG_EOF
;
2603 goto keep_tok_flags
;
2604 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2606 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2607 tcc_error("missing #endif");
2608 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2609 /* no include left : end of file. */
2612 tok_flags
&= ~TOK_FLAG_EOF
;
2613 /* pop include file */
2615 /* test if previous '#endif' was after a #ifdef at
2617 if (tok_flags
& TOK_FLAG_ENDIF
) {
2619 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2621 search_cached_include(s1
, file
->filename
, 1)
2622 ->ifndef_macro
= file
->ifndef_macro_saved
;
2623 tok_flags
&= ~TOK_FLAG_ENDIF
;
2626 /* add end of include file debug info */
2627 tcc_debug_eincl(tcc_state
);
2628 /* pop include stack */
2630 s1
->include_stack_ptr
--;
2632 if (p
== file
->buffer
)
2633 tok_flags
= TOK_FLAG_BOF
|TOK_FLAG_BOL
;
2641 tok_flags
|= TOK_FLAG_BOL
;
2644 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2647 goto keep_tok_flags
;
2652 if ((tok_flags
& TOK_FLAG_BOL
) &&
2653 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2655 preprocess(tok_flags
& TOK_FLAG_BOF
);
2661 tok
= TOK_TWOSHARPS
;
2663 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2664 p
= parse_line_comment(p
- 1);
2673 /* dollar is allowed to start identifiers when not parsing asm */
2675 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2676 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2679 case 'a': case 'b': case 'c': case 'd':
2680 case 'e': case 'f': case 'g': case 'h':
2681 case 'i': case 'j': case 'k': case 'l':
2682 case 'm': case 'n': case 'o': case 'p':
2683 case 'q': case 'r': case 's': case 't':
2684 case 'u': case 'v': case 'w': case 'x':
2686 case 'A': case 'B': case 'C': case 'D':
2687 case 'E': case 'F': case 'G': case 'H':
2688 case 'I': case 'J': case 'K':
2689 case 'M': case 'N': case 'O': case 'P':
2690 case 'Q': case 'R': case 'S': case 'T':
2691 case 'U': case 'V': case 'W': case 'X':
2697 h
= TOK_HASH_FUNC(h
, c
);
2698 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2699 h
= TOK_HASH_FUNC(h
, c
);
2704 /* fast case : no stray found, so we have the full token
2705 and we have already hashed it */
2706 h
&= (TOK_HASH_SIZE
- 1);
2707 pts
= &hash_ident
[h
];
2712 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2714 pts
= &(ts
->hash_next
);
2716 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2720 cstr_reset(&tokcstr
);
2721 cstr_cat(&tokcstr
, (char *) p1
, len
);
2725 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2727 cstr_ccat(&tokcstr
, c
);
2730 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2736 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2738 goto parse_ident_fast
;
2741 if (c
== '\'' || c
== '\"') {
2745 cstr_reset(&tokcstr
);
2746 cstr_ccat(&tokcstr
, 'L');
2747 goto parse_ident_slow
;
2752 case '0': case '1': case '2': case '3':
2753 case '4': case '5': case '6': case '7':
2757 /* after the first digit, accept digits, alpha, '.' or sign if
2758 prefixed by 'eEpP' */
2760 cstr_reset(&tokcstr
);
2762 cstr_ccat(&tokcstr
, t
);
2763 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2765 || ((c
== '+' || c
== '-')
2766 && (((t
== 'e' || t
== 'E')
2767 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2768 /* 0xe+1 is 3 tokens in asm */
2769 && ((char*)tokcstr
.data
)[0] == '0'
2770 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2771 || t
== 'p' || t
== 'P'))))
2776 /* We add a trailing '\0' to ease parsing */
2777 cstr_ccat(&tokcstr
, '\0');
2778 tokc
.str
.size
= tokcstr
.size
;
2779 tokc
.str
.data
= tokcstr
.data
;
2784 /* special dot handling because it can also start a number */
2789 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2790 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2792 goto parse_ident_fast
;
2793 } else if (c
== '.') {
2799 *--p
= '.'; /* may underflow into file->unget[] */
2810 cstr_reset(&tokcstr
);
2812 cstr_ccat(&tokcstr
, 'L');
2813 cstr_ccat(&tokcstr
, c
);
2814 p
= parse_pp_string(p
, c
, &tokcstr
);
2815 cstr_ccat(&tokcstr
, c
);
2816 cstr_ccat(&tokcstr
, '\0');
2817 tokc
.str
.size
= tokcstr
.size
;
2818 tokc
.str
.data
= tokcstr
.data
;
2827 } else if (c
== '<') {
2844 } else if (c
== '>') {
2862 } else if (c
== '=') {
2875 } else if (c
== '=') {
2888 } else if (c
== '=') {
2901 } else if (c
== '=') {
2904 } else if (c
== '>') {
2912 PARSE2('!', '!', '=', TOK_NE
)
2913 PARSE2('=', '=', '=', TOK_EQ
)
2914 PARSE2('*', '*', '=', TOK_A_MUL
)
2915 PARSE2('%', '%', '=', TOK_A_MOD
)
2916 PARSE2('^', '^', '=', TOK_A_XOR
)
2918 /* comments or operator */
2922 p
= parse_comment(p
);
2923 /* comments replaced by a blank */
2925 goto keep_tok_flags
;
2926 } else if (c
== '/') {
2927 p
= parse_line_comment(p
);
2929 goto keep_tok_flags
;
2930 } else if (c
== '=') {
2950 case '@': /* only used in assembler */
2956 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
2957 goto parse_ident_fast
;
2958 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2960 tcc_error("unrecognized character \\x%02x", c
);
2966 #if defined(PARSE_DEBUG)
2967 printf("token = %d %s\n", tok
, get_tok_str(tok
, &tokc
));
2971 /* return next token without macro substitution. Can read input from
2973 static void next_nomacro_spc(void)
2979 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2980 if (tok
== TOK_LINENUM
) {
2981 file
->line_num
= tokc
.i
;
2988 //printf("token = %s\n", get_tok_str(tok, &tokc));
2991 ST_FUNC
void next_nomacro(void)
2995 } while (tok
< 256 && (isidnum_table
[tok
- CH_EOF
] & IS_SPC
));
2999 static void macro_subst(
3000 TokenString
*tok_str
,
3002 const int *macro_str
3005 /* substitute arguments in replacement lists in macro_str by the values in
3006 args (field d) and return allocated string */
3007 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
3019 TOK_GET(&t
, ¯o_str
, &cval
);
3024 TOK_GET(&t
, ¯o_str
, &cval
);
3027 s
= sym_find2(args
, t
);
3030 cstr_ccat(&cstr
, '\"');
3034 TOK_GET(&t
, &st
, &cval
);
3035 if (t
!= TOK_PLCHLDR
3037 && 0 == check_space(t
, &spc
)) {
3038 const char *s
= get_tok_str(t
, &cval
);
3040 if (t
== TOK_PPSTR
&& *s
!= '\'')
3041 add_char(&cstr
, *s
);
3043 cstr_ccat(&cstr
, *s
);
3049 cstr_ccat(&cstr
, '\"');
3050 cstr_ccat(&cstr
, '\0');
3052 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
3055 cval
.str
.size
= cstr
.size
;
3056 cval
.str
.data
= cstr
.data
;
3057 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
3061 expect("macro parameter after '#'");
3063 } else if (t
>= TOK_IDENT
) {
3064 s
= sym_find2(args
, t
);
3068 /* if '##' is present before or after, no arg substitution */
3069 if (*macro_str
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
3070 /* special case for var arg macros : ## eats the ','
3071 if empty VA_ARGS variable. */
3072 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
3074 /* suppress ',' '##' */
3077 /* suppress '##' and add variable */
3085 /* Expand arguments tokens and store them. In most
3086 cases we could also re-expand each argument if
3087 used multiple times, but not if the argument
3088 contains the __COUNTER__ macro. */
3090 sym_push2(&s
->next
, s
->v
, s
->type
.t
, 0);
3092 macro_subst(&str2
, nested_list
, st
);
3093 tok_str_add(&str2
, 0);
3094 s
->next
->d
= str2
.str
;
3100 TOK_GET(&t2
, &st
, &cval
);
3103 tok_str_add2(&str
, t2
, &cval
);
3105 if (str
.len
== l0
) /* expanded to empty string */
3106 tok_str_add(&str
, TOK_PLCHLDR
);
3108 tok_str_add(&str
, t
);
3111 tok_str_add2(&str
, t
, &cval
);
3115 tok_str_add(&str
, 0);
3119 static char const ab_month_name
[12][4] =
3121 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3122 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3125 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3131 if (t1
!= TOK_PLCHLDR
)
3132 cstr_cat(&cstr
, get_tok_str(t1
, v1
), -1);
3134 if (t2
!= TOK_PLCHLDR
)
3135 cstr_cat(&cstr
, get_tok_str(t2
, v2
), -1);
3136 cstr_ccat(&cstr
, '\0');
3138 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3139 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3143 if (0 == *file
->buf_ptr
)
3147 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3148 " preprocessing token", n
, cstr
.data
, (char*)cstr
.data
+ n
);
3153 //printf("paste <%s>\n", (char*)cstr.data);
3158 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3159 return the resulting string (which must be freed). */
3160 static inline int *macro_twosharps(const int *ptr0
)
3164 TokenString macro_str1
;
3165 int start_of_nosubsts
= -1;
3168 /* we search the first '##' */
3169 for (ptr
= ptr0
;;) {
3170 TOK_GET(&t
, &ptr
, &cval
);
3171 if (t
== TOK_PPJOIN
)
3177 tok_str_new(¯o_str1
);
3179 //tok_print(" $$$", ptr0);
3180 for (ptr
= ptr0
;;) {
3181 TOK_GET(&t
, &ptr
, &cval
);
3184 if (t
== TOK_PPJOIN
)
3186 while (*ptr
== TOK_PPJOIN
) {
3188 /* given 'a##b', remove nosubsts preceding 'a' */
3189 if (start_of_nosubsts
>= 0)
3190 macro_str1
.len
= start_of_nosubsts
;
3191 /* given 'a##b', remove nosubsts preceding 'b' */
3192 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3194 if (t1
&& t1
!= TOK_PPJOIN
) {
3195 TOK_GET(&t1
, &ptr
, &cv1
);
3196 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3197 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3198 t
= tok
, cval
= tokc
;
3200 tok_str_add2(¯o_str1
, t
, &cval
);
3206 if (t
== TOK_NOSUBST
) {
3207 if (start_of_nosubsts
< 0)
3208 start_of_nosubsts
= macro_str1
.len
;
3210 start_of_nosubsts
= -1;
3212 tok_str_add2(¯o_str1
, t
, &cval
);
3214 tok_str_add(¯o_str1
, 0);
3215 //tok_print(" ###", macro_str1.str);
3216 return macro_str1
.str
;
3219 /* peek or read [ws_str == NULL] next token from function macro call,
3220 walking up macro levels up to the file if necessary */
3221 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3229 p
= macro_ptr
, t
= *p
;
3231 while (is_space(t
) || TOK_LINEFEED
== t
|| TOK_PLCHLDR
== t
)
3232 tok_str_add(ws_str
, t
), t
= *++p
;
3236 /* also, end of scope for nested defined symbol */
3238 while (sa
&& sa
->v
== 0)
3247 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3250 uint8_t *p
= file
->buf_ptr
;
3253 p
= parse_comment(p
);
3254 file
->buf_ptr
= p
- 1;
3255 } else if (c
== '/') {
3256 p
= parse_line_comment(p
);
3257 file
->buf_ptr
= p
- 1;
3264 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3265 tok_str_add(ws_str
, ch
);
3279 /* do macro substitution of current token with macro 's' and add
3280 result to (tok_str,tok_len). 'nested_list' is the list of all
3281 macros we got inside to avoid recursing. Return non zero if no
3282 substitution needs to be done */
3283 static int macro_subst_tok(
3284 TokenString
*tok_str
,
3288 Sym
*args
, *sa
, *sa1
;
3289 int parlevel
, t
, t1
, spc
;
3296 /* if symbol is a macro, prepare substitution */
3297 /* special macros */
3298 if (tok
== TOK___LINE__
|| tok
== TOK___COUNTER__
) {
3299 t
= tok
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3300 snprintf(buf
, sizeof(buf
), "%d", t
);
3304 } else if (tok
== TOK___FILE__
) {
3305 cstrval
= file
->filename
;
3307 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3312 tm
= localtime(&ti
);
3313 if (tok
== TOK___DATE__
) {
3314 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3315 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3317 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3318 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3325 cstr_cat(&cstr
, cstrval
, 0);
3326 cval
.str
.size
= cstr
.size
;
3327 cval
.str
.data
= cstr
.data
;
3328 tok_str_add2(tok_str
, t1
, &cval
);
3331 int saved_parse_flags
= parse_flags
;
3332 int *joined_str
= NULL
;
3335 if (s
->type
.t
== MACRO_FUNC
) {
3336 /* whitespace between macro name and argument list */
3338 tok_str_new(&ws_str
);
3341 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3342 | PARSE_FLAG_ACCEPT_STRAYS
;
3344 /* get next token from argument stream */
3345 t
= next_argstream(nested_list
, &ws_str
);
3347 /* not a macro substitution after all, restore the
3348 * macro token plus all whitespace we've read.
3349 * whitespace is intentionally not merged to preserve
3351 parse_flags
= saved_parse_flags
;
3352 tok_str_add(tok_str
, tok
);
3353 if (parse_flags
& PARSE_FLAG_SPACES
) {
3355 for (i
= 0; i
< ws_str
.len
; i
++)
3356 tok_str_add(tok_str
, ws_str
.str
[i
]);
3358 tok_str_free_str(ws_str
.str
);
3361 tok_str_free_str(ws_str
.str
);
3364 next_nomacro(); /* eat '(' */
3365 } while (tok
== TOK_PLCHLDR
);
3367 /* argument macro */
3370 /* NOTE: empty args are allowed, except if no args */
3373 next_argstream(nested_list
, NULL
);
3374 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3376 /* handle '()' case */
3377 if (!args
&& !sa
&& tok
== ')')
3380 tcc_error("macro '%s' used with too many args",
3381 get_tok_str(s
->v
, 0));
3384 /* NOTE: non zero sa->t indicates VA_ARGS */
3385 while ((parlevel
> 0 ||
3387 (tok
!= ',' || sa
->type
.t
)))) {
3388 if (tok
== TOK_EOF
|| tok
== 0)
3392 else if (tok
== ')')
3394 if (tok
== TOK_LINEFEED
)
3396 if (!check_space(tok
, &spc
))
3397 tok_str_add2(&str
, tok
, &tokc
);
3398 next_argstream(nested_list
, NULL
);
3403 tok_str_add(&str
, -1);
3404 tok_str_add(&str
, 0);
3405 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3409 /* special case for gcc var args: add an empty
3410 var arg argument if it is omitted */
3411 if (sa
&& sa
->type
.t
&& gnu_ext
)
3419 tcc_error("macro '%s' used with too few args",
3420 get_tok_str(s
->v
, 0));
3423 parse_flags
= saved_parse_flags
;
3425 /* now subst each arg */
3426 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3431 tok_str_free_str(sa
->d
);
3433 tok_str_free_str(sa
->next
->d
);
3441 sym_push2(nested_list
, s
->v
, 0, 0);
3442 parse_flags
= saved_parse_flags
;
3443 joined_str
= macro_twosharps(mstr
);
3444 macro_subst(tok_str
, nested_list
, joined_str
? joined_str
: mstr
);
3446 /* pop nested defined symbol */
3448 *nested_list
= sa1
->prev
;
3451 tok_str_free_str(joined_str
);
3453 tok_str_free_str(mstr
);
3458 /* do macro substitution of macro_str and add result to
3459 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3460 inside to avoid recursing. */
3461 static void macro_subst(
3462 TokenString
*tok_str
,
3464 const int *macro_str
3468 int t
, spc
, nosubst
;
3474 TOK_GET(&t
, ¯o_str
, &cval
);
3478 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3483 /* if nested substitution, do nothing */
3484 if (sym_find2(*nested_list
, t
)) {
3485 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3486 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3491 TokenString
*str
= tok_str_alloc();
3492 str
->str
= (int*)macro_str
;
3493 begin_macro(str
, 2);
3496 macro_subst_tok(tok_str
, nested_list
, s
);
3498 if (macro_stack
!= str
) {
3499 /* already finished by reading function macro arguments */
3503 macro_str
= macro_ptr
;
3507 spc
= is_space(t
= tok_str
->str
[tok_str
->lastlen
]);
3509 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3510 tcc_error("stray '\\' in program");
3512 if (!check_space(t
, &spc
))
3513 tok_str_add2(tok_str
, t
, &cval
);
3516 if (nosubst
> 1 && (spc
|| (++nosubst
== 3 && t
== '(')))
3520 if (t
== TOK_NOSUBST
)
3523 /* GCC supports 'defined' as result of a macro substitution */
3524 if (t
== TOK_DEFINED
&& pp_expr
)
3529 /* return next token with macro substitution */
3530 ST_FUNC
void next(void)
3532 /* generate line number info */
3533 if (tcc_state
->do_debug
)
3534 tcc_debug_line(tcc_state
);
3536 if (parse_flags
& PARSE_FLAG_SPACES
)
3542 if (tok
== TOK_NOSUBST
|| tok
== TOK_PLCHLDR
) {
3543 /* discard preprocessor markers */
3545 } else if (tok
== 0) {
3546 /* end of macro or unget token string */
3550 } else if (tok
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3552 /* if reading from file, try to substitute macros */
3553 s
= define_find(tok
);
3555 Sym
*nested_list
= NULL
;
3557 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3558 tok_str_add(&tokstr_buf
, 0);
3559 begin_macro(&tokstr_buf
, 0);
3563 /* convert preprocessor tokens into C tokens */
3564 if (tok
== TOK_PPNUM
) {
3565 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3566 parse_number((char *)tokc
.str
.data
);
3567 } else if (tok
== TOK_PPSTR
) {
3568 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3569 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3573 /* push back current token and set current token to 'last_tok'. Only
3574 identifier case handled for labels. */
3575 ST_INLN
void unget_tok(int last_tok
)
3578 TokenString
*str
= tok_str_alloc();
3579 tok_str_add2(str
, tok
, &tokc
);
3580 tok_str_add(str
, 0);
3581 begin_macro(str
, 1);
3585 ST_FUNC
void preprocess_start(TCCState
*s1
, int is_asm
)
3591 s1
->include_stack_ptr
= s1
->include_stack
;
3592 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3593 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3596 pp_debug_tok
= pp_debug_symv
= 0;
3598 s1
->pack_stack
[0] = 0;
3599 s1
->pack_stack_ptr
= s1
->pack_stack
;
3601 set_idnum('$', s1
->dollars_in_identifiers
? IS_ID
: 0);
3602 set_idnum('.', is_asm
? IS_ID
: 0);
3605 if (s1
->cmdline_defs
.size
)
3606 cstr_cat(&cstr
, s1
->cmdline_defs
.data
, s1
->cmdline_defs
.size
);
3607 cstr_printf(&cstr
, "#define __BASE_FILE__ \"%s\"\n", file
->filename
);
3609 cstr_printf(&cstr
, "#define __ASSEMBLER__ 1\n");
3610 if (s1
->cmdline_incl
.size
)
3611 cstr_cat(&cstr
, s1
->cmdline_incl
.data
, s1
->cmdline_incl
.size
);
3612 //printf("%s\n", (char*)cstr.data);
3613 *s1
->include_stack_ptr
++ = file
;
3614 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3615 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3618 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3619 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3622 /* cleanup from error/setjmp */
3623 ST_FUNC
void preprocess_end(TCCState
*s1
)
3633 ST_FUNC
void tccpp_new(TCCState
*s
)
3638 /* init isid table */
3639 for(i
= CH_EOF
; i
<128; i
++)
3641 is_space(i
) ? IS_SPC
3646 for(i
= 128; i
<256; i
++)
3647 set_idnum(i
, IS_ID
);
3649 /* init allocators */
3650 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3651 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3653 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3654 memset(s
->cached_includes_hash
, 0, sizeof s
->cached_includes_hash
);
3656 cstr_new(&cstr_buf
);
3657 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3658 tok_str_new(&tokstr_buf
);
3659 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3661 tok_ident
= TOK_IDENT
;
3670 tok_alloc(p
, r
- p
- 1);
3674 /* we add dummy defines for some special macros to speed up tests
3675 and to have working defined() */
3676 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
3677 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
3678 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
3679 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
3680 define_push(TOK___COUNTER__
, MACRO_OBJ
, NULL
, NULL
);
3683 ST_FUNC
void tccpp_delete(TCCState
*s
)
3687 dynarray_reset(&s
->cached_includes
, &s
->nb_cached_includes
);
3690 n
= tok_ident
- TOK_IDENT
;
3691 if (n
> total_idents
)
3693 for(i
= 0; i
< n
; i
++)
3694 tal_free(toksym_alloc
, table_ident
[i
]);
3695 tcc_free(table_ident
);
3698 /* free static buffers */
3699 cstr_free(&tokcstr
);
3700 cstr_free(&cstr_buf
);
3701 cstr_free(¯o_equal_buf
);
3702 tok_str_free_str(tokstr_buf
.str
);
3704 /* free allocators */
3705 tal_delete(toksym_alloc
);
3706 toksym_alloc
= NULL
;
3707 tal_delete(tokstr_alloc
);
3708 tokstr_alloc
= NULL
;
3711 /* ------------------------------------------------------------------------- */
3712 /* tcc -E [-P[1]] [-dD} support */
3714 static void tok_print(const char *msg
, const int *str
)
3720 fp
= tcc_state
->ppfp
;
3721 fprintf(fp
, "%s", msg
);
3723 TOK_GET(&t
, &str
, &cval
);
3726 fprintf(fp
, " %s" + s
, get_tok_str(t
, &cval
)), s
= 1;
3731 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3733 int d
= f
->line_num
- f
->line_ref
;
3738 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3740 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3742 fputs("\n", s1
->ppfp
), --d
;
3743 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3744 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3746 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3747 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3749 f
->line_ref
= f
->line_num
;
3752 static void define_print(TCCState
*s1
, int v
)
3758 if (NULL
== s
|| NULL
== s
->d
)
3762 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3763 if (s
->type
.t
== MACRO_FUNC
) {
3768 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3775 tok_print("", s
->d
);
3778 static void pp_debug_defines(TCCState
*s1
)
3789 pp_line(s1
, file
, 0);
3790 file
->line_ref
= ++file
->line_num
;
3794 vs
= get_tok_str(v
, NULL
);
3795 if (t
== TOK_DEFINE
) {
3796 define_print(s1
, v
);
3797 } else if (t
== TOK_UNDEF
) {
3798 fprintf(fp
, "#undef %s\n", vs
);
3799 } else if (t
== TOK_push_macro
) {
3800 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3801 } else if (t
== TOK_pop_macro
) {
3802 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3807 static void pp_debug_builtins(TCCState
*s1
)
3810 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3811 define_print(s1
, v
);
3814 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3815 static int pp_need_space(int a
, int b
)
3817 return 'E' == a
? '+' == b
|| '-' == b
3818 : '+' == a
? TOK_INC
== b
|| '+' == b
3819 : '-' == a
? TOK_DEC
== b
|| '-' == b
3820 : a
>= TOK_IDENT
? b
>= TOK_IDENT
3821 : a
== TOK_PPNUM
? b
>= TOK_IDENT
3825 /* maybe hex like 0x1e */
3826 static int pp_check_he0xE(int t
, const char *p
)
3828 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3833 /* Preprocess the current file */
3834 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3836 BufferedFile
**iptr
;
3837 int token_seen
, spcs
, level
;
3841 parse_flags
= PARSE_FLAG_PREPROCESS
3842 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3843 | PARSE_FLAG_LINEFEED
3845 | PARSE_FLAG_ACCEPT_STRAYS
3847 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3848 capability to compile and run itself, provided all numbers are
3849 given as decimals. tcc -E -P10 will do. */
3850 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
3851 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
3854 /* for PP benchmarks */
3855 do next(); while (tok
!= TOK_EOF
);
3859 if (s1
->dflag
& 1) {
3860 pp_debug_builtins(s1
);
3864 token_seen
= TOK_LINEFEED
, spcs
= 0;
3865 pp_line(s1
, file
, 0);
3867 iptr
= s1
->include_stack_ptr
;
3872 level
= s1
->include_stack_ptr
- iptr
;
3875 pp_line(s1
, *iptr
, 0);
3876 pp_line(s1
, file
, level
);
3878 if (s1
->dflag
& 7) {
3879 pp_debug_defines(s1
);
3884 if (is_space(tok
)) {
3885 if (spcs
< sizeof white
- 1)
3886 white
[spcs
++] = tok
;
3888 } else if (tok
== TOK_LINEFEED
) {
3890 if (token_seen
== TOK_LINEFEED
)
3893 } else if (token_seen
== TOK_LINEFEED
) {
3894 pp_line(s1
, file
, 0);
3895 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
3896 white
[spcs
++] = ' ';
3899 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
3900 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
3901 token_seen
= pp_check_he0xE(tok
, p
);
3906 /* ------------------------------------------------------------------------- */