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_FUNC
void cstr_cat(CString
*cstr
, const char *str
, int len
)
352 len
= strlen(str
) + 1 + len
;
353 size
= cstr
->size
+ len
;
354 if (size
> cstr
->size_allocated
)
355 cstr_realloc(cstr
, size
);
356 memmove(((unsigned char *)cstr
->data
) + cstr
->size
, str
, len
);
360 /* add a wide char */
361 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
364 size
= cstr
->size
+ sizeof(nwchar_t
);
365 if (size
> cstr
->size_allocated
)
366 cstr_realloc(cstr
, size
);
367 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
371 ST_FUNC
void cstr_new(CString
*cstr
)
373 memset(cstr
, 0, sizeof(CString
));
376 /* free string and reset it to NULL */
377 ST_FUNC
void cstr_free(CString
*cstr
)
379 tcc_free(cstr
->data
);
383 /* reset string to empty */
384 ST_FUNC
void cstr_reset(CString
*cstr
)
389 ST_FUNC
int cstr_printf(CString
*cstr
, const char *fmt
, ...)
395 if (size
> cstr
->size_allocated
)
396 cstr_realloc(cstr
, size
);
397 size
= cstr
->size_allocated
- cstr
->size
;
399 len
= vsnprintf((char*)cstr
->data
+ cstr
->size
, size
, fmt
, v
);
401 if (len
> 0 && len
< size
)
410 static void add_char(CString
*cstr
, int c
)
412 if (c
== '\'' || c
== '\"' || c
== '\\') {
413 /* XXX: could be more precise if char or string */
414 cstr_ccat(cstr
, '\\');
416 if (c
>= 32 && c
<= 126) {
419 cstr_ccat(cstr
, '\\');
421 cstr_ccat(cstr
, 'n');
423 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
424 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
425 cstr_ccat(cstr
, '0' + (c
& 7));
430 /* ------------------------------------------------------------------------- */
431 /* allocate a new token */
432 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
434 TokenSym
*ts
, **ptable
;
437 if (tok_ident
>= SYM_FIRST_ANOM
)
438 tcc_error("memory full (symbols)");
440 /* expand token table if needed */
441 i
= tok_ident
- TOK_IDENT
;
442 if ((i
% TOK_ALLOC_INCR
) == 0) {
443 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
444 table_ident
= ptable
;
447 ts
= tal_realloc(toksym_alloc
, 0, sizeof(TokenSym
) + len
);
449 ts
->tok
= tok_ident
++;
450 ts
->sym_define
= NULL
;
451 ts
->sym_label
= NULL
;
452 ts
->sym_struct
= NULL
;
453 ts
->sym_identifier
= NULL
;
455 ts
->hash_next
= NULL
;
456 memcpy(ts
->str
, str
, len
);
462 #define TOK_HASH_INIT 1
463 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
466 /* find a token and add it if not found */
467 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
475 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
476 h
&= (TOK_HASH_SIZE
- 1);
478 pts
= &hash_ident
[h
];
483 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
485 pts
= &(ts
->hash_next
);
487 return tok_alloc_new(pts
, str
, len
);
490 /* XXX: buffer overflow */
491 /* XXX: float tokens */
492 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
497 cstr_reset(&cstr_buf
);
507 /* XXX: not quite exact, but only useful for testing */
509 sprintf(p
, "%u", (unsigned)cv
->i
);
511 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
515 cstr_ccat(&cstr_buf
, 'L');
517 cstr_ccat(&cstr_buf
, '\'');
518 add_char(&cstr_buf
, cv
->i
);
519 cstr_ccat(&cstr_buf
, '\'');
520 cstr_ccat(&cstr_buf
, '\0');
524 return (char*)cv
->str
.data
;
526 cstr_ccat(&cstr_buf
, 'L');
528 cstr_ccat(&cstr_buf
, '\"');
530 len
= cv
->str
.size
- 1;
532 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
534 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
536 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
538 cstr_ccat(&cstr_buf
, '\"');
539 cstr_ccat(&cstr_buf
, '\0');
543 cstr_cat(&cstr_buf
, "<float>", 0);
546 cstr_cat(&cstr_buf
, "<double>", 0);
549 cstr_cat(&cstr_buf
, "<long double>", 0);
552 cstr_cat(&cstr_buf
, "<linenumber>", 0);
555 /* above tokens have value, the ones below don't */
563 return strcpy(p
, "...");
565 return strcpy(p
, "<<=");
567 return strcpy(p
, ">>=");
569 return strcpy(p
, "<eof>");
572 /* search in two bytes table */
573 const unsigned char *q
= tok_two_chars
;
579 return cstr_buf
.data
;
584 sprintf(cstr_buf
.data
, "<%02x>", v
);
585 return cstr_buf
.data
;
590 } else if (v
< tok_ident
) {
591 return table_ident
[v
- TOK_IDENT
]->str
;
592 } else if (v
>= SYM_FIRST_ANOM
) {
593 /* special name for anonymous symbol */
594 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
596 /* should never happen */
601 return cstr_buf
.data
;
604 /* return the current character, handling end of block if necessary
606 static int handle_eob(void)
608 BufferedFile
*bf
= file
;
611 /* only tries to read if really end of buffer */
612 if (bf
->buf_ptr
>= bf
->buf_end
) {
614 #if defined(PARSE_DEBUG)
619 len
= read(bf
->fd
, bf
->buffer
, len
);
626 bf
->buf_ptr
= bf
->buffer
;
627 bf
->buf_end
= bf
->buffer
+ len
;
628 *bf
->buf_end
= CH_EOB
;
630 if (bf
->buf_ptr
< bf
->buf_end
) {
631 return bf
->buf_ptr
[0];
633 bf
->buf_ptr
= bf
->buf_end
;
638 /* read next char from current input file and handle end of input buffer */
639 static inline void inp(void)
641 ch
= *(++(file
->buf_ptr
));
642 /* end of buffer/file handling */
647 /* handle '\[\r]\n' */
648 static int handle_stray_noerror(void)
655 } else if (ch
== '\r') {
669 static void handle_stray(void)
671 if (handle_stray_noerror())
672 tcc_error("stray '\\' in program");
675 /* skip the stray and handle the \\n case. Output an error if
676 incorrect char after the stray */
677 static int handle_stray1(uint8_t *p
)
682 if (p
>= file
->buf_end
) {
689 if (handle_stray_noerror()) {
690 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
691 tcc_error("stray '\\' in program");
692 *--file
->buf_ptr
= '\\';
699 /* handle just the EOB case, but not stray */
700 #define PEEKC_EOB(c, p)\
711 /* handle the complicated stray case */
717 c = handle_stray1(p);\
722 /* input with '\[\r]\n' handling. Note that this function cannot
723 handle other characters after '\', so you cannot call it inside
724 strings or comments */
725 static void minp(void)
732 /* single line C++ comments */
733 static uint8_t *parse_line_comment(uint8_t *p
)
741 if (c
== '\n' || c
== CH_EOF
) {
743 } else if (c
== '\\') {
752 } else if (c
== '\r') {
770 static uint8_t *parse_comment(uint8_t *p
)
779 if (c
== '\n' || c
== '*' || c
== '\\')
783 if (c
== '\n' || c
== '*' || c
== '\\')
787 /* now we can handle all the cases */
791 } else if (c
== '*') {
797 } else if (c
== '/') {
799 } else if (c
== '\\') {
804 tcc_error("unexpected end of file in comment");
806 /* skip '\[\r]\n', otherwise just skip the stray */
812 } else if (c
== '\r') {
829 /* stray, eob or eof */
834 tcc_error("unexpected end of file in comment");
835 } else if (c
== '\\') {
845 ST_FUNC
int set_idnum(int c
, int val
)
847 int prev
= isidnum_table
[c
- CH_EOF
];
848 isidnum_table
[c
- CH_EOF
] = val
;
854 static inline void skip_spaces(void)
856 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
860 static inline int check_space(int t
, int *spc
)
862 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
871 /* parse a string without interpreting escapes */
872 static uint8_t *parse_pp_string(uint8_t *p
,
873 int sep
, CString
*str
)
881 } else if (c
== '\\') {
887 /* XXX: indicate line number of start of string */
888 tcc_error("missing terminating %c character", sep
);
889 } else if (c
== '\\') {
890 /* escape : just skip \[\r]\n */
895 } else if (c
== '\r') {
898 expect("'\n' after '\r'");
901 } else if (c
== CH_EOF
) {
902 goto unterminated_string
;
905 cstr_ccat(str
, '\\');
911 } else if (c
== '\n') {
914 } else if (c
== '\r') {
918 cstr_ccat(str
, '\r');
934 /* skip block of text until #else, #elif or #endif. skip also pairs of
936 static void preprocess_skip(void)
938 int a
, start_of_line
, c
, in_warn_or_error
;
945 in_warn_or_error
= 0;
966 } else if (c
== '\\') {
967 ch
= file
->buf_ptr
[0];
968 handle_stray_noerror();
975 if (in_warn_or_error
)
977 p
= parse_pp_string(p
, c
, NULL
);
981 if (in_warn_or_error
)
988 p
= parse_comment(p
);
989 } else if (ch
== '/') {
990 p
= parse_line_comment(p
);
1000 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
1002 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
1004 else if (tok
== TOK_ENDIF
)
1006 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
1007 in_warn_or_error
= 1;
1008 else if (tok
== TOK_LINEFEED
)
1010 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1011 p
= parse_line_comment(p
- 1);
1012 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1013 p
= parse_line_comment(p
- 1);
1027 /* return the number of additional 'ints' necessary to store the
1029 static inline int tok_size(const int *p
)
1044 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
1047 return 1 + LONG_SIZE
/ 4;
1053 return 1 + LDOUBLE_SIZE
/ 4;
1060 /* token string handling */
1061 ST_INLN
void tok_str_new(TokenString
*s
)
1064 s
->len
= s
->lastlen
= 0;
1065 s
->allocated_len
= 0;
1066 s
->last_line_num
= -1;
1069 ST_FUNC TokenString
*tok_str_alloc(void)
1071 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1076 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1080 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1081 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1085 ST_FUNC
void tok_str_free_str(int *str
)
1087 tal_free(tokstr_alloc
, str
);
1090 ST_FUNC
void tok_str_free(TokenString
*str
)
1092 tok_str_free_str(str
->str
);
1093 tal_free(tokstr_alloc
, str
);
1096 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1100 size
= s
->allocated_len
;
1103 while (size
< new_size
)
1105 if (size
> s
->allocated_len
) {
1106 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1107 s
->allocated_len
= size
;
1113 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1119 if (len
>= s
->allocated_len
)
1120 str
= tok_str_realloc(s
, len
+ 1);
1125 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1128 str
->prev
= macro_stack
;
1129 str
->prev_ptr
= macro_ptr
;
1130 str
->save_line_num
= file
->line_num
;
1131 macro_ptr
= str
->str
;
1135 ST_FUNC
void end_macro(void)
1137 TokenString
*str
= macro_stack
;
1138 macro_stack
= str
->prev
;
1139 macro_ptr
= str
->prev_ptr
;
1140 file
->line_num
= str
->save_line_num
;
1141 if (str
->alloc
!= 0) {
1142 if (str
->alloc
== 2)
1143 str
->str
= NULL
; /* don't free */
1148 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1152 len
= s
->lastlen
= s
->len
;
1155 /* allocate space for worst case */
1156 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1157 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1170 str
[len
++] = cv
->tab
[0];
1177 /* Insert the string into the int array. */
1179 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1180 if (len
+ nb_words
>= s
->allocated_len
)
1181 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1182 str
[len
] = cv
->str
.size
;
1183 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1194 #if LDOUBLE_SIZE == 8
1197 str
[len
++] = cv
->tab
[0];
1198 str
[len
++] = cv
->tab
[1];
1200 #if LDOUBLE_SIZE == 12
1202 str
[len
++] = cv
->tab
[0];
1203 str
[len
++] = cv
->tab
[1];
1204 str
[len
++] = cv
->tab
[2];
1205 #elif LDOUBLE_SIZE == 16
1207 str
[len
++] = cv
->tab
[0];
1208 str
[len
++] = cv
->tab
[1];
1209 str
[len
++] = cv
->tab
[2];
1210 str
[len
++] = cv
->tab
[3];
1211 #elif LDOUBLE_SIZE != 8
1212 #error add long double size support
1221 /* add the current parse token in token string 's' */
1222 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1226 /* save line number info */
1227 if (file
->line_num
!= s
->last_line_num
) {
1228 s
->last_line_num
= file
->line_num
;
1229 cval
.i
= s
->last_line_num
;
1230 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1232 tok_str_add2(s
, tok
, &tokc
);
1235 /* get a token from an integer array and increment pointer. */
1236 static inline void tok_get(int *t
, const int **pp
, CValue
*cv
)
1256 cv
->i
= (unsigned)*p
++;
1265 cv
->str
.size
= *p
++;
1267 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1279 #if LDOUBLE_SIZE == 16
1281 #elif LDOUBLE_SIZE == 12
1283 #elif LDOUBLE_SIZE == 8
1286 # error add long double size support
1300 # define TOK_GET(t,p,c) tok_get(t,p,c)
1302 # define TOK_GET(t,p,c) do { \
1304 if (TOK_HAS_VALUE(_t)) \
1307 *(t) = _t, ++*(p); \
1311 static int macro_is_equal(const int *a
, const int *b
)
1320 /* first time preallocate macro_equal_buf, next time only reset position to start */
1321 cstr_reset(¯o_equal_buf
);
1322 TOK_GET(&t
, &a
, &cv
);
1323 cstr_cat(¯o_equal_buf
, get_tok_str(t
, &cv
), 0);
1324 TOK_GET(&t
, &b
, &cv
);
1325 if (strcmp(macro_equal_buf
.data
, get_tok_str(t
, &cv
)))
1331 /* defines handling */
1332 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1337 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1339 s
->next
= first_arg
;
1340 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1342 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1343 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1346 /* undefined a define symbol. Its name is just set to zero */
1347 ST_FUNC
void define_undef(Sym
*s
)
1350 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1351 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1354 ST_INLN Sym
*define_find(int v
)
1357 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1359 return table_ident
[v
]->sym_define
;
1362 /* free define stack until top reaches 'b' */
1363 ST_FUNC
void free_defines(Sym
*b
)
1365 while (define_stack
!= b
) {
1366 Sym
*top
= define_stack
;
1367 define_stack
= top
->prev
;
1368 tok_str_free_str(top
->d
);
1375 ST_FUNC Sym
*label_find(int v
)
1378 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1380 return table_ident
[v
]->sym_label
;
1383 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1386 s
= sym_push2(ptop
, v
, 0, 0);
1388 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1389 if (ptop
== &global_label_stack
) {
1390 /* modify the top most local identifier, so that
1391 sym_identifier will point to 's' when popped */
1393 ps
= &(*ps
)->prev_tok
;
1400 /* pop labels until element last is reached. Look if any labels are
1401 undefined. Define symbols if '&&label' was used. */
1402 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
, int keep
)
1405 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1407 if (s
->r
== LABEL_DECLARED
) {
1408 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1409 } else if (s
->r
== LABEL_FORWARD
) {
1410 tcc_error("label '%s' used but not defined",
1411 get_tok_str(s
->v
, NULL
));
1414 /* define corresponding symbol. A size of
1416 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1420 if (s
->r
!= LABEL_GONE
)
1421 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1431 /* fake the nth "#if defined test_..." for tcc -dt -run */
1432 static void maybe_run_test(TCCState
*s
)
1435 if (s
->include_stack_ptr
!= s
->include_stack
)
1437 p
= get_tok_str(tok
, NULL
);
1438 if (0 != memcmp(p
, "test_", 5))
1440 if (0 != --s
->run_test
)
1442 fprintf(s
->ppfp
, &"\n[%s]\n"[!(s
->dflag
& 32)], p
), fflush(s
->ppfp
);
1443 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1446 /* eval an expression for #if/#elif */
1447 static int expr_preprocess(void)
1452 str
= tok_str_alloc();
1454 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1455 next(); /* do macro subst */
1457 if (tok
== TOK_DEFINED
) {
1462 if (tok
< TOK_IDENT
)
1463 expect("identifier");
1464 if (tcc_state
->run_test
)
1465 maybe_run_test(tcc_state
);
1466 c
= define_find(tok
) != 0;
1474 } else if (1 && tok
== TOK___HAS_INCLUDE
) {
1475 next(); /* XXX check if correct to use expansion */
1477 while (tok
!= ')' && tok
!= TOK_EOF
)
1483 } else if (tok
>= TOK_IDENT
) {
1484 /* if undefined macro, replace with zero, check for func-like */
1488 tok_str_add_tok(str
);
1491 tcc_error("function-like macro '%s' is not defined",
1492 get_tok_str(t
, NULL
));
1495 tok_str_add_tok(str
);
1498 tok_str_add(str
, -1); /* simulate end of file */
1499 tok_str_add(str
, 0);
1500 /* now evaluate C constant expression */
1501 begin_macro(str
, 1);
1509 /* parse after #define */
1510 ST_FUNC
void parse_define(void)
1512 Sym
*s
, *first
, **ps
;
1513 int v
, t
, varg
, is_vaargs
, spc
;
1514 int saved_parse_flags
= parse_flags
;
1517 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1518 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1519 /* XXX: should check if same macro (ANSI) */
1522 /* We have to parse the whole define as if not in asm mode, in particular
1523 no line comment with '#' must be ignored. Also for function
1524 macros the argument list must be parsed without '.' being an ID
1526 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1527 /* '(' must be just after macro definition for MACRO_FUNC */
1529 parse_flags
&= ~PARSE_FLAG_SPACES
;
1531 int dotid
= set_idnum('.', 0);
1534 if (tok
!= ')') for (;;) {
1538 if (varg
== TOK_DOTS
) {
1539 varg
= TOK___VA_ARGS__
;
1541 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1545 if (varg
< TOK_IDENT
)
1547 tcc_error("bad macro parameter list");
1548 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1553 if (tok
!= ',' || is_vaargs
)
1557 parse_flags
|= PARSE_FLAG_SPACES
;
1560 set_idnum('.', dotid
);
1565 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1566 /* The body of a macro definition should be parsed such that identifiers
1567 are parsed like the file mode determines (i.e. with '.' being an
1568 ID character in asm mode). But '#' should be retained instead of
1569 regarded as line comment leader, so still don't set ASM_FILE
1571 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1572 /* remove spaces around ## and after '#' */
1573 if (TOK_TWOSHARPS
== tok
) {
1580 } else if ('#' == tok
) {
1582 } else if (check_space(tok
, &spc
)) {
1585 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1590 parse_flags
= saved_parse_flags
;
1592 --tokstr_buf
.len
; /* remove trailing space */
1593 tok_str_add(&tokstr_buf
, 0);
1596 tcc_error("'##' cannot appear at either end of macro");
1597 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1600 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1602 const unsigned char *s
;
1608 s
= (unsigned char *) filename
;
1611 h
= TOK_HASH_FUNC(h
, toup(*s
));
1613 h
= TOK_HASH_FUNC(h
, *s
);
1617 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1619 i
= s1
->cached_includes_hash
[h
];
1623 e
= s1
->cached_includes
[i
- 1];
1624 if (0 == PATHCMP(e
->filename
, filename
))
1631 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1632 strcpy(e
->filename
, filename
);
1633 e
->ifndef_macro
= e
->once
= 0;
1634 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1635 /* add in hash table */
1636 e
->hash_next
= s1
->cached_includes_hash
[h
];
1637 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1639 printf("adding cached '%s'\n", filename
);
1644 static void pragma_parse(TCCState
*s1
)
1647 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1651 if (next(), tok
!= '(')
1653 if (next(), tok
!= TOK_STR
)
1655 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1656 if (next(), tok
!= ')')
1658 if (t
== TOK_push_macro
) {
1659 while (NULL
== (s
= define_find(v
)))
1660 define_push(v
, 0, NULL
, NULL
);
1661 s
->type
.ref
= s
; /* set push boundary */
1663 for (s
= define_stack
; s
; s
= s
->prev
)
1664 if (s
->v
== v
&& s
->type
.ref
== s
) {
1670 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1672 tcc_warning("unbalanced #pragma pop_macro");
1673 pp_debug_tok
= t
, pp_debug_symv
= v
;
1675 } else if (tok
== TOK_once
) {
1676 search_cached_include(s1
, file
->filename
, 1)->once
= pp_once
;
1678 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1679 /* tcc -E: keep pragmas below unchanged */
1681 unget_tok(TOK_PRAGMA
);
1683 unget_tok(TOK_LINEFEED
);
1685 } else if (tok
== TOK_pack
) {
1687 #pragma pack(1) // set
1688 #pragma pack() // reset to default
1689 #pragma pack(push,1) // push & set
1690 #pragma pack(pop) // restore previous */
1693 if (tok
== TOK_ASM_pop
) {
1695 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1697 tcc_error("out of pack stack");
1699 s1
->pack_stack_ptr
--;
1703 if (tok
== TOK_ASM_push
) {
1705 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1707 s1
->pack_stack_ptr
++;
1710 if (tok
!= TOK_CINT
)
1713 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1717 *s1
->pack_stack_ptr
= val
;
1722 } else if (tok
== TOK_comment
) {
1731 p
= tcc_strdup((char *)tokc
.str
.data
);
1736 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1738 if (t
== TOK_option
)
1739 tcc_set_options(s1
, p
);
1743 } else if (s1
->warn_unsupported
) {
1744 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1749 tcc_error("malformed #pragma directive");
1753 /* is_bof is true if first non space token at beginning of file */
1754 ST_FUNC
void preprocess(int is_bof
)
1756 TCCState
*s1
= tcc_state
;
1757 int i
, c
, n
, saved_parse_flags
;
1761 saved_parse_flags
= parse_flags
;
1762 parse_flags
= PARSE_FLAG_PREPROCESS
1763 | PARSE_FLAG_TOK_NUM
1764 | PARSE_FLAG_TOK_STR
1765 | PARSE_FLAG_LINEFEED
1766 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1775 pp_debug_symv
= tok
;
1781 pp_debug_symv
= tok
;
1782 s
= define_find(tok
);
1783 /* undefine symbol by putting an invalid name */
1788 case TOK_INCLUDE_NEXT
:
1789 ch
= file
->buf_ptr
[0];
1790 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1795 } else if (ch
== '\"') {
1800 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1801 if ((q
- buf
) < sizeof(buf
) - 1)
1804 if (handle_stray_noerror() == 0)
1812 /* eat all spaces and comments after include */
1813 /* XXX: slightly incorrect */
1814 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1819 /* computed #include : concatenate everything up to linefeed,
1820 the result must be one of the two accepted forms.
1821 Don't convert pp-tokens to tokens here. */
1822 parse_flags
= (PARSE_FLAG_PREPROCESS
1823 | PARSE_FLAG_LINEFEED
1824 | (parse_flags
& PARSE_FLAG_ASM_FILE
));
1827 while (tok
!= TOK_LINEFEED
) {
1828 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1832 /* check syntax and remove '<>|""' */
1833 if ((len
< 2 || ((buf
[0] != '"' || buf
[len
-1] != '"') &&
1834 (buf
[0] != '<' || buf
[len
-1] != '>'))))
1835 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1837 memmove(buf
, buf
+ 1, len
- 2);
1838 buf
[len
- 2] = '\0';
1841 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1842 tcc_error("#include recursion too deep");
1843 /* push current file on stack */
1844 *s1
->include_stack_ptr
++ = file
;
1845 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
+ 1 : 0;
1846 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1847 for (; i
< n
; ++i
) {
1848 char buf1
[sizeof file
->filename
];
1853 /* check absolute include path */
1854 if (!IS_ABSPATH(buf
))
1858 } else if (i
== 1) {
1859 /* search in file's dir if "header.h" */
1862 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1863 path
= file
->true_filename
;
1864 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1867 /* search in all the include paths */
1868 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1869 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1870 pstrcpy(buf1
, sizeof(buf1
), path
);
1871 pstrcat(buf1
, sizeof(buf1
), "/");
1874 pstrcat(buf1
, sizeof(buf1
), buf
);
1875 e
= search_cached_include(s1
, buf1
, 0);
1876 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
== pp_once
)) {
1877 /* no need to parse the include because the 'ifndef macro'
1878 is defined (or had #pragma once) */
1880 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1885 if (tcc_open(s1
, buf1
) < 0)
1888 file
->include_next_index
= i
;
1890 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1892 /* update target deps */
1894 BufferedFile
*bf
= file
;
1895 while (i
== 1 && (bf
= bf
->prev
))
1896 i
= bf
->include_next_index
;
1897 /* skip system include files */
1898 if (n
- i
> s1
->nb_sysinclude_paths
)
1899 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1902 /* add include file debug info */
1903 tcc_debug_bincl(tcc_state
);
1904 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1905 ch
= file
->buf_ptr
[0];
1908 tcc_error("include file '%s' not found", buf
);
1910 --s1
->include_stack_ptr
;
1916 c
= expr_preprocess();
1922 if (tok
< TOK_IDENT
)
1923 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1927 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1929 file
->ifndef_macro
= tok
;
1932 c
= (define_find(tok
) != 0) ^ c
;
1934 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1935 tcc_error("memory full (ifdef)");
1936 *s1
->ifdef_stack_ptr
++ = c
;
1939 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1940 tcc_error("#else without matching #if");
1941 if (s1
->ifdef_stack_ptr
[-1] & 2)
1942 tcc_error("#else after #else");
1943 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1946 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1947 tcc_error("#elif without matching #if");
1948 c
= s1
->ifdef_stack_ptr
[-1];
1950 tcc_error("#elif after #else");
1951 /* last #if/#elif expression was true: we skip */
1955 c
= expr_preprocess();
1956 s1
->ifdef_stack_ptr
[-1] = c
;
1959 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1960 file
->ifndef_macro
= 0;
1969 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1970 tcc_error("#endif without matching #if");
1971 s1
->ifdef_stack_ptr
--;
1972 /* '#ifndef macro' was at the start of file. Now we check if
1973 an '#endif' is exactly at the end of file */
1974 if (file
->ifndef_macro
&&
1975 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1976 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1977 /* need to set to zero to avoid false matches if another
1978 #ifndef at middle of file */
1979 file
->ifndef_macro
= 0;
1980 while (tok
!= TOK_LINEFEED
)
1982 tok_flags
|= TOK_FLAG_ENDIF
;
1987 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1991 if (tok
!= TOK_CINT
)
1993 tcc_error("wrong #line format");
1997 if (tok
!= TOK_LINEFEED
) {
1998 if (tok
== TOK_STR
) {
1999 if (file
->true_filename
== file
->filename
)
2000 file
->true_filename
= tcc_strdup(file
->filename
);
2001 /* prepend directory from real file */
2002 pstrcpy(buf
, sizeof buf
, file
->true_filename
);
2003 *tcc_basename(buf
) = 0;
2004 pstrcat(buf
, sizeof buf
, (char *)tokc
.str
.data
);
2005 tcc_debug_putfile(s1
, buf
);
2006 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2013 total_lines
+= file
->line_num
- n
;
2019 ch
= file
->buf_ptr
[0];
2022 while (ch
!= '\n' && ch
!= CH_EOF
) {
2023 if ((q
- buf
) < sizeof(buf
) - 1)
2026 if (handle_stray_noerror() == 0)
2033 tcc_error("#error %s", buf
);
2035 tcc_warning("#warning %s", buf
);
2043 /* ignore gas line comment in an 'S' file. */
2044 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
2046 if (tok
== '!' && is_bof
)
2047 /* '!' is ignored at beginning to allow C scripts. */
2049 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2051 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
2054 /* ignore other preprocess commands or #! for C scripts */
2055 while (tok
!= TOK_LINEFEED
)
2058 parse_flags
= saved_parse_flags
;
2061 /* evaluate escape codes in a string. */
2062 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2077 case '0': case '1': case '2': case '3':
2078 case '4': case '5': case '6': case '7':
2079 /* at most three octal digits */
2084 n
= n
* 8 + c
- '0';
2088 n
= n
* 8 + c
- '0';
2093 goto add_char_nonext
;
2101 if (c
>= 'a' && c
<= 'f')
2103 else if (c
>= 'A' && c
<= 'F')
2113 goto add_char_nonext
;
2137 goto invalid_escape
;
2147 if (c
>= '!' && c
<= '~')
2148 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2150 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2153 } else if (is_long
&& c
>= 0x80) {
2154 /* assume we are processing UTF-8 sequence */
2155 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2157 int cont
; /* count of continuation bytes */
2158 int skip
; /* how many bytes should skip when error occurred */
2161 /* decode leading byte */
2163 skip
= 1; goto invalid_utf8_sequence
;
2164 } else if (c
<= 0xDF) {
2165 cont
= 1; n
= c
& 0x1f;
2166 } else if (c
<= 0xEF) {
2167 cont
= 2; n
= c
& 0xf;
2168 } else if (c
<= 0xF4) {
2169 cont
= 3; n
= c
& 0x7;
2171 skip
= 1; goto invalid_utf8_sequence
;
2174 /* decode continuation bytes */
2175 for (i
= 1; i
<= cont
; i
++) {
2176 int l
= 0x80, h
= 0xBF;
2178 /* adjust limit for second byte */
2181 case 0xE0: l
= 0xA0; break;
2182 case 0xED: h
= 0x9F; break;
2183 case 0xF0: l
= 0x90; break;
2184 case 0xF4: h
= 0x8F; break;
2188 if (p
[i
] < l
|| p
[i
] > h
) {
2189 skip
= i
; goto invalid_utf8_sequence
;
2192 n
= (n
<< 6) | (p
[i
] & 0x3f);
2195 /* advance pointer */
2198 goto add_char_nonext
;
2200 /* error handling */
2201 invalid_utf8_sequence
:
2202 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c
);
2205 goto add_char_nonext
;
2211 cstr_ccat(outstr
, c
);
2213 #ifdef TCC_TARGET_PE
2214 /* store as UTF-16 */
2216 cstr_wccat(outstr
, c
);
2219 cstr_wccat(outstr
, (c
>> 10) + 0xD800);
2220 cstr_wccat(outstr
, (c
& 0x3FF) + 0xDC00);
2223 cstr_wccat(outstr
, c
);
2227 /* add a trailing '\0' */
2229 cstr_ccat(outstr
, '\0');
2231 cstr_wccat(outstr
, '\0');
2234 static void parse_string(const char *s
, int len
)
2236 uint8_t buf
[1000], *p
= buf
;
2239 if ((is_long
= *s
== 'L'))
2243 if (len
>= sizeof buf
)
2244 p
= tcc_malloc(len
+ 1);
2248 cstr_reset(&tokcstr
);
2249 parse_escape_string(&tokcstr
, p
, is_long
);
2254 int char_size
, i
, n
, c
;
2255 /* XXX: make it portable */
2257 tok
= TOK_CCHAR
, char_size
= 1;
2259 tok
= TOK_LCHAR
, char_size
= sizeof(nwchar_t
);
2260 n
= tokcstr
.size
/ char_size
- 1;
2262 tcc_error("empty character constant");
2264 tcc_warning("multi-character character constant");
2265 for (c
= i
= 0; i
< n
; ++i
) {
2267 c
= ((nwchar_t
*)tokcstr
.data
)[i
];
2269 c
= (c
<< 8) | ((char *)tokcstr
.data
)[i
];
2273 tokc
.str
.size
= tokcstr
.size
;
2274 tokc
.str
.data
= tokcstr
.data
;
2282 /* we use 64 bit numbers */
2285 /* bn = (bn << shift) | or_val */
2286 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2290 for(i
=0;i
<BN_SIZE
;i
++) {
2292 bn
[i
] = (v
<< shift
) | or_val
;
2293 or_val
= v
>> (32 - shift
);
2297 static void bn_zero(unsigned int *bn
)
2300 for(i
=0;i
<BN_SIZE
;i
++) {
2305 /* parse number in null terminated string 'p' and return it in the
2307 static void parse_number(const char *p
)
2309 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2311 unsigned int bn
[BN_SIZE
];
2322 goto float_frac_parse
;
2323 } else if (t
== '0') {
2324 if (ch
== 'x' || ch
== 'X') {
2328 } else if (tcc_state
->tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2334 /* parse all digits. cannot check octal numbers at this stage
2335 because of floating point constants */
2337 if (ch
>= 'a' && ch
<= 'f')
2339 else if (ch
>= 'A' && ch
<= 'F')
2347 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2349 tcc_error("number too long");
2355 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2356 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2358 /* NOTE: strtox should support that for hexa numbers, but
2359 non ISOC99 libcs do not support it, so we prefer to do
2361 /* hexadecimal or binary floats */
2362 /* XXX: handle overflows */
2374 } else if (t
>= 'a') {
2376 } else if (t
>= 'A') {
2381 bn_lshift(bn
, shift
, t
);
2388 if (t
>= 'a' && t
<= 'f') {
2390 } else if (t
>= 'A' && t
<= 'F') {
2392 } else if (t
>= '0' && t
<= '9') {
2398 tcc_error("invalid digit");
2399 bn_lshift(bn
, shift
, t
);
2404 if (ch
!= 'p' && ch
!= 'P')
2411 } else if (ch
== '-') {
2415 if (ch
< '0' || ch
> '9')
2416 expect("exponent digits");
2417 while (ch
>= '0' && ch
<= '9') {
2418 exp_val
= exp_val
* 10 + ch
- '0';
2421 exp_val
= exp_val
* s
;
2423 /* now we can generate the number */
2424 /* XXX: should patch directly float number */
2425 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2426 d
= ldexp(d
, exp_val
- frac_bits
);
2431 /* float : should handle overflow */
2433 } else if (t
== 'L') {
2435 #ifdef TCC_TARGET_PE
2440 /* XXX: not large enough */
2441 tokc
.ld
= (long double)d
;
2448 /* decimal floats */
2450 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2455 while (ch
>= '0' && ch
<= '9') {
2456 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2462 if (ch
== 'e' || ch
== 'E') {
2463 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2467 if (ch
== '-' || ch
== '+') {
2468 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2473 if (ch
< '0' || ch
> '9')
2474 expect("exponent digits");
2475 while (ch
>= '0' && ch
<= '9') {
2476 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2488 tokc
.f
= strtof(token_buf
, NULL
);
2489 } else if (t
== 'L') {
2491 #ifdef TCC_TARGET_PE
2493 tokc
.d
= strtod(token_buf
, NULL
);
2496 tokc
.ld
= strtold(token_buf
, NULL
);
2500 tokc
.d
= strtod(token_buf
, NULL
);
2504 unsigned long long n
, n1
;
2505 int lcount
, ucount
, ov
= 0;
2508 /* integer number */
2511 if (b
== 10 && *q
== '0') {
2518 /* no need for checks except for base 10 / 8 errors */
2528 tcc_error("invalid digit");
2531 /* detect overflow */
2532 if (n1
>= 0x1000000000000000ULL
&& n
/ b
!= n1
)
2536 /* Determine the characteristics (unsigned and/or 64bit) the type of
2537 the constant must have according to the constant suffix(es) */
2538 lcount
= ucount
= 0;
2544 tcc_error("three 'l's in integer constant");
2545 if (lcount
&& *(p
- 1) != ch
)
2546 tcc_error("incorrect integer suffix: %s", p1
);
2549 } else if (t
== 'U') {
2551 tcc_error("two 'u's in integer constant");
2559 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2560 if (ucount
== 0 && b
== 10) {
2561 if (lcount
<= (LONG_SIZE
== 4)) {
2562 if (n
>= 0x80000000U
)
2563 lcount
= (LONG_SIZE
== 4) + 1;
2565 if (n
>= 0x8000000000000000ULL
)
2568 if (lcount
<= (LONG_SIZE
== 4)) {
2569 if (n
>= 0x100000000ULL
)
2570 lcount
= (LONG_SIZE
== 4) + 1;
2571 else if (n
>= 0x80000000U
)
2574 if (n
>= 0x8000000000000000ULL
)
2579 tcc_warning("integer constant overflow");
2588 ++tok
; /* TOK_CU... */
2592 tcc_error("invalid number");
2596 #define PARSE2(c1, tok1, c2, tok2) \
2607 /* return next token without macro substitution */
2608 static inline void next_nomacro1(void)
2610 int t
, c
, is_long
, len
;
2624 if (parse_flags
& PARSE_FLAG_SPACES
)
2625 goto keep_tok_flags
;
2626 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2635 /* first look if it is in fact an end of buffer */
2636 c
= handle_stray1(p
);
2643 TCCState
*s1
= tcc_state
;
2644 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2645 && !(tok_flags
& TOK_FLAG_EOF
)) {
2646 tok_flags
|= TOK_FLAG_EOF
;
2648 goto keep_tok_flags
;
2649 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2651 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2652 tcc_error("missing #endif");
2653 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2654 /* no include left : end of file. */
2657 tok_flags
&= ~TOK_FLAG_EOF
;
2658 /* pop include file */
2660 /* test if previous '#endif' was after a #ifdef at
2662 if (tok_flags
& TOK_FLAG_ENDIF
) {
2664 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2666 search_cached_include(s1
, file
->filename
, 1)
2667 ->ifndef_macro
= file
->ifndef_macro_saved
;
2668 tok_flags
&= ~TOK_FLAG_ENDIF
;
2671 /* add end of include file debug info */
2672 tcc_debug_eincl(tcc_state
);
2673 /* pop include stack */
2675 s1
->include_stack_ptr
--;
2677 if (p
== file
->buffer
)
2678 tok_flags
= TOK_FLAG_BOF
|TOK_FLAG_BOL
;
2686 tok_flags
|= TOK_FLAG_BOL
;
2689 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2692 goto keep_tok_flags
;
2697 if ((tok_flags
& TOK_FLAG_BOL
) &&
2698 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2700 preprocess(tok_flags
& TOK_FLAG_BOF
);
2706 tok
= TOK_TWOSHARPS
;
2708 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2709 p
= parse_line_comment(p
- 1);
2718 /* dollar is allowed to start identifiers when not parsing asm */
2720 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2721 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2724 case 'a': case 'b': case 'c': case 'd':
2725 case 'e': case 'f': case 'g': case 'h':
2726 case 'i': case 'j': case 'k': case 'l':
2727 case 'm': case 'n': case 'o': case 'p':
2728 case 'q': case 'r': case 's': case 't':
2729 case 'u': case 'v': case 'w': case 'x':
2731 case 'A': case 'B': case 'C': case 'D':
2732 case 'E': case 'F': case 'G': case 'H':
2733 case 'I': case 'J': case 'K':
2734 case 'M': case 'N': case 'O': case 'P':
2735 case 'Q': case 'R': case 'S': case 'T':
2736 case 'U': case 'V': case 'W': case 'X':
2742 h
= TOK_HASH_FUNC(h
, c
);
2743 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2744 h
= TOK_HASH_FUNC(h
, c
);
2749 /* fast case : no stray found, so we have the full token
2750 and we have already hashed it */
2751 h
&= (TOK_HASH_SIZE
- 1);
2752 pts
= &hash_ident
[h
];
2757 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2759 pts
= &(ts
->hash_next
);
2761 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2765 cstr_reset(&tokcstr
);
2766 cstr_cat(&tokcstr
, (char *) p1
, len
);
2770 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2772 cstr_ccat(&tokcstr
, c
);
2775 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2781 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2783 goto parse_ident_fast
;
2786 if (c
== '\'' || c
== '\"') {
2790 cstr_reset(&tokcstr
);
2791 cstr_ccat(&tokcstr
, 'L');
2792 goto parse_ident_slow
;
2797 case '0': case '1': case '2': case '3':
2798 case '4': case '5': case '6': case '7':
2802 /* after the first digit, accept digits, alpha, '.' or sign if
2803 prefixed by 'eEpP' */
2805 cstr_reset(&tokcstr
);
2807 cstr_ccat(&tokcstr
, t
);
2808 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2810 || ((c
== '+' || c
== '-')
2811 && (((t
== 'e' || t
== 'E')
2812 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2813 /* 0xe+1 is 3 tokens in asm */
2814 && ((char*)tokcstr
.data
)[0] == '0'
2815 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2816 || t
== 'p' || t
== 'P'))))
2821 /* We add a trailing '\0' to ease parsing */
2822 cstr_ccat(&tokcstr
, '\0');
2823 tokc
.str
.size
= tokcstr
.size
;
2824 tokc
.str
.data
= tokcstr
.data
;
2829 /* special dot handling because it can also start a number */
2834 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2835 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2837 goto parse_ident_fast
;
2838 } else if (c
== '.') {
2844 *--p
= '.'; /* may underflow into file->unget[] */
2855 cstr_reset(&tokcstr
);
2857 cstr_ccat(&tokcstr
, 'L');
2858 cstr_ccat(&tokcstr
, c
);
2859 p
= parse_pp_string(p
, c
, &tokcstr
);
2860 cstr_ccat(&tokcstr
, c
);
2861 cstr_ccat(&tokcstr
, '\0');
2862 tokc
.str
.size
= tokcstr
.size
;
2863 tokc
.str
.data
= tokcstr
.data
;
2872 } else if (c
== '<') {
2889 } else if (c
== '>') {
2907 } else if (c
== '=') {
2920 } else if (c
== '=') {
2933 } else if (c
== '=') {
2946 } else if (c
== '=') {
2949 } else if (c
== '>') {
2957 PARSE2('!', '!', '=', TOK_NE
)
2958 PARSE2('=', '=', '=', TOK_EQ
)
2959 PARSE2('*', '*', '=', TOK_A_MUL
)
2960 PARSE2('%', '%', '=', TOK_A_MOD
)
2961 PARSE2('^', '^', '=', TOK_A_XOR
)
2963 /* comments or operator */
2967 p
= parse_comment(p
);
2968 /* comments replaced by a blank */
2971 } else if (c
== '/') {
2972 p
= parse_line_comment(p
);
2975 } else if (c
== '=') {
2995 case '@': /* only used in assembler */
3001 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
3002 goto parse_ident_fast
;
3003 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
3005 tcc_error("unrecognized character \\x%02x", c
);
3011 #if defined(PARSE_DEBUG)
3012 printf("token = %d %s\n", tok
, get_tok_str(tok
, &tokc
));
3016 static void macro_subst(
3017 TokenString
*tok_str
,
3019 const int *macro_str
3022 /* substitute arguments in replacement lists in macro_str by the values in
3023 args (field d) and return allocated string */
3024 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
3036 TOK_GET(&t
, ¯o_str
, &cval
);
3041 TOK_GET(&t
, ¯o_str
, &cval
);
3044 s
= sym_find2(args
, t
);
3047 cstr_ccat(&cstr
, '\"');
3051 TOK_GET(&t
, &st
, &cval
);
3052 if (t
!= TOK_PLCHLDR
3054 && 0 == check_space(t
, &spc
)) {
3055 const char *s
= get_tok_str(t
, &cval
);
3057 if (t
== TOK_PPSTR
&& *s
!= '\'')
3058 add_char(&cstr
, *s
);
3060 cstr_ccat(&cstr
, *s
);
3066 cstr_ccat(&cstr
, '\"');
3067 cstr_ccat(&cstr
, '\0');
3069 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
3072 cval
.str
.size
= cstr
.size
;
3073 cval
.str
.data
= cstr
.data
;
3074 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
3078 expect("macro parameter after '#'");
3080 } else if (t
>= TOK_IDENT
) {
3081 s
= sym_find2(args
, t
);
3085 /* if '##' is present before or after, no arg substitution */
3086 if (*macro_str
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
3087 /* special case for var arg macros : ## eats the ','
3088 if empty VA_ARGS variable. */
3089 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
3091 /* suppress ',' '##' */
3094 /* suppress '##' and add variable */
3102 /* Expand arguments tokens and store them. In most
3103 cases we could also re-expand each argument if
3104 used multiple times, but not if the argument
3105 contains the __COUNTER__ macro. */
3107 sym_push2(&s
->next
, s
->v
, s
->type
.t
, 0);
3109 macro_subst(&str2
, nested_list
, st
);
3110 tok_str_add(&str2
, 0);
3111 s
->next
->d
= str2
.str
;
3117 TOK_GET(&t2
, &st
, &cval
);
3120 tok_str_add2(&str
, t2
, &cval
);
3122 if (str
.len
== l0
) /* expanded to empty string */
3123 tok_str_add(&str
, TOK_PLCHLDR
);
3125 tok_str_add(&str
, t
);
3128 tok_str_add2(&str
, t
, &cval
);
3132 tok_str_add(&str
, 0);
3136 static char const ab_month_name
[12][4] =
3138 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3139 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3142 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3148 if (t1
!= TOK_PLCHLDR
)
3149 cstr_cat(&cstr
, get_tok_str(t1
, v1
), -1);
3151 if (t2
!= TOK_PLCHLDR
)
3152 cstr_cat(&cstr
, get_tok_str(t2
, v2
), -1);
3153 cstr_ccat(&cstr
, '\0');
3155 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3156 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3160 if (0 == *file
->buf_ptr
)
3164 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3165 " preprocessing token", n
, (char *)cstr
.data
, (char*)cstr
.data
+ n
);
3170 //printf("paste <%s>\n", (char*)cstr.data);
3175 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3176 return the resulting string (which must be freed). */
3177 static inline int *macro_twosharps(const int *ptr0
)
3181 TokenString macro_str1
;
3182 int start_of_nosubsts
= -1;
3185 /* we search the first '##' */
3186 for (ptr
= ptr0
;;) {
3187 TOK_GET(&t
, &ptr
, &cval
);
3188 if (t
== TOK_PPJOIN
)
3194 tok_str_new(¯o_str1
);
3196 //tok_print(" $$$", ptr0);
3197 for (ptr
= ptr0
;;) {
3198 TOK_GET(&t
, &ptr
, &cval
);
3201 if (t
== TOK_PPJOIN
)
3203 while (*ptr
== TOK_PPJOIN
) {
3205 /* given 'a##b', remove nosubsts preceding 'a' */
3206 if (start_of_nosubsts
>= 0)
3207 macro_str1
.len
= start_of_nosubsts
;
3208 /* given 'a##b', remove nosubsts preceding 'b' */
3209 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3211 if (t1
&& t1
!= TOK_PPJOIN
) {
3212 TOK_GET(&t1
, &ptr
, &cv1
);
3213 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3214 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3215 t
= tok
, cval
= tokc
;
3217 tok_str_add2(¯o_str1
, t
, &cval
);
3223 if (t
== TOK_NOSUBST
) {
3224 if (start_of_nosubsts
< 0)
3225 start_of_nosubsts
= macro_str1
.len
;
3227 start_of_nosubsts
= -1;
3229 tok_str_add2(¯o_str1
, t
, &cval
);
3231 tok_str_add(¯o_str1
, 0);
3232 //tok_print(" ###", macro_str1.str);
3233 return macro_str1
.str
;
3236 /* peek or read [ws_str == NULL] next token from function macro call,
3237 walking up macro levels up to the file if necessary */
3238 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3246 p
= macro_ptr
, t
= *p
;
3248 while (is_space(t
) || TOK_LINEFEED
== t
|| TOK_PLCHLDR
== t
)
3249 tok_str_add(ws_str
, t
), t
= *++p
;
3253 /* also, end of scope for nested defined symbol */
3255 while (sa
&& sa
->v
== 0)
3264 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3267 uint8_t *p
= file
->buf_ptr
;
3270 p
= parse_comment(p
);
3271 file
->buf_ptr
= p
- 1;
3272 } else if (c
== '/') {
3273 p
= parse_line_comment(p
);
3274 file
->buf_ptr
= p
- 1;
3281 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3282 tok_str_add(ws_str
, ch
);
3296 /* do macro substitution of current token with macro 's' and add
3297 result to (tok_str,tok_len). 'nested_list' is the list of all
3298 macros we got inside to avoid recursing. Return non zero if no
3299 substitution needs to be done */
3300 static int macro_subst_tok(
3301 TokenString
*tok_str
,
3305 Sym
*args
, *sa
, *sa1
;
3306 int parlevel
, t
, t1
, spc
;
3313 /* if symbol is a macro, prepare substitution */
3314 /* special macros */
3315 if (tok
== TOK___LINE__
|| tok
== TOK___COUNTER__
) {
3316 t
= tok
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3317 snprintf(buf
, sizeof(buf
), "%d", t
);
3321 } else if (tok
== TOK___FILE__
) {
3322 cstrval
= file
->filename
;
3324 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3329 tm
= localtime(&ti
);
3330 if (tok
== TOK___DATE__
) {
3331 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3332 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3334 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3335 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3342 cstr_cat(&cstr
, cstrval
, 0);
3343 cval
.str
.size
= cstr
.size
;
3344 cval
.str
.data
= cstr
.data
;
3345 tok_str_add2(tok_str
, t1
, &cval
);
3348 int saved_parse_flags
= parse_flags
;
3349 int *joined_str
= NULL
;
3352 if (s
->type
.t
== MACRO_FUNC
) {
3353 /* whitespace between macro name and argument list */
3355 tok_str_new(&ws_str
);
3358 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3359 | PARSE_FLAG_ACCEPT_STRAYS
;
3361 /* get next token from argument stream */
3362 t
= next_argstream(nested_list
, &ws_str
);
3364 /* not a macro substitution after all, restore the
3365 * macro token plus all whitespace we've read.
3366 * whitespace is intentionally not merged to preserve
3368 parse_flags
= saved_parse_flags
;
3369 tok_str_add(tok_str
, tok
);
3370 if (parse_flags
& PARSE_FLAG_SPACES
) {
3372 for (i
= 0; i
< ws_str
.len
; i
++)
3373 tok_str_add(tok_str
, ws_str
.str
[i
]);
3375 tok_str_free_str(ws_str
.str
);
3378 tok_str_free_str(ws_str
.str
);
3381 next_nomacro(); /* eat '(' */
3382 } while (tok
== TOK_PLCHLDR
|| is_space(tok
));
3384 /* argument macro */
3387 /* NOTE: empty args are allowed, except if no args */
3390 next_argstream(nested_list
, NULL
);
3391 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3393 /* handle '()' case */
3394 if (!args
&& !sa
&& tok
== ')')
3397 tcc_error("macro '%s' used with too many args",
3398 get_tok_str(s
->v
, 0));
3401 /* NOTE: non zero sa->t indicates VA_ARGS */
3402 while ((parlevel
> 0 ||
3404 (tok
!= ',' || sa
->type
.t
)))) {
3405 if (tok
== TOK_EOF
|| tok
== 0)
3409 else if (tok
== ')')
3411 if (tok
== TOK_LINEFEED
)
3413 if (!check_space(tok
, &spc
))
3414 tok_str_add2(&str
, tok
, &tokc
);
3415 next_argstream(nested_list
, NULL
);
3420 tok_str_add(&str
, -1);
3421 tok_str_add(&str
, 0);
3422 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3426 /* special case for gcc var args: add an empty
3427 var arg argument if it is omitted */
3428 if (sa
&& sa
->type
.t
&& gnu_ext
)
3436 tcc_error("macro '%s' used with too few args",
3437 get_tok_str(s
->v
, 0));
3440 /* now subst each arg */
3441 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3446 tok_str_free_str(sa
->d
);
3448 tok_str_free_str(sa
->next
->d
);
3454 parse_flags
= saved_parse_flags
;
3457 sym_push2(nested_list
, s
->v
, 0, 0);
3458 parse_flags
= saved_parse_flags
;
3459 joined_str
= macro_twosharps(mstr
);
3460 macro_subst(tok_str
, nested_list
, joined_str
? joined_str
: mstr
);
3462 /* pop nested defined symbol */
3464 *nested_list
= sa1
->prev
;
3467 tok_str_free_str(joined_str
);
3469 tok_str_free_str(mstr
);
3474 /* do macro substitution of macro_str and add result to
3475 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3476 inside to avoid recursing. */
3477 static void macro_subst(
3478 TokenString
*tok_str
,
3480 const int *macro_str
3484 int t
, spc
, nosubst
;
3490 TOK_GET(&t
, ¯o_str
, &cval
);
3494 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3499 /* if nested substitution, do nothing */
3500 if (sym_find2(*nested_list
, t
)) {
3501 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3502 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3507 TokenString
*str
= tok_str_alloc();
3508 str
->str
= (int*)macro_str
;
3509 begin_macro(str
, 2);
3512 macro_subst_tok(tok_str
, nested_list
, s
);
3514 if (macro_stack
!= str
) {
3515 /* already finished by reading function macro arguments */
3519 macro_str
= macro_ptr
;
3523 spc
= is_space(t
= tok_str
->str
[tok_str
->lastlen
]);
3526 if (!check_space(t
, &spc
))
3527 tok_str_add2(tok_str
, t
, &cval
);
3530 if (nosubst
> 1 && (spc
|| (++nosubst
== 3 && t
== '(')))
3534 if (t
== TOK_NOSUBST
)
3537 /* GCC supports 'defined' as result of a macro substitution */
3538 if (t
== TOK_DEFINED
&& pp_expr
)
3543 /* return next token without macro substitution. Can read input from
3545 static void next_nomacro(void)
3551 if (TOK_HAS_VALUE(t
)) {
3552 tok_get(&tok
, ¯o_ptr
, &tokc
);
3553 if (t
== TOK_LINENUM
) {
3554 file
->line_num
= tokc
.i
;
3559 if (t
< TOK_IDENT
) {
3560 if (!(parse_flags
& PARSE_FLAG_SPACES
)
3561 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
))
3571 /* return next token with macro substitution */
3572 ST_FUNC
void next(void)
3579 if (!TOK_HAS_VALUE(t
)) {
3580 if (t
== TOK_NOSUBST
|| t
== TOK_PLCHLDR
) {
3581 /* discard preprocessor markers */
3583 } else if (t
== 0) {
3584 /* end of macro or unget token string */
3587 } else if (t
== '\\') {
3588 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3589 tcc_error("stray '\\' in program");
3593 } else if (t
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3594 /* if reading from file, try to substitute macros */
3595 Sym
*s
= define_find(t
);
3597 Sym
*nested_list
= NULL
;
3599 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3600 tok_str_add(&tokstr_buf
, 0);
3601 begin_macro(&tokstr_buf
, 0);
3606 /* convert preprocessor tokens into C tokens */
3607 if (t
== TOK_PPNUM
) {
3608 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3609 parse_number((char *)tokc
.str
.data
);
3610 } else if (t
== TOK_PPSTR
) {
3611 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3612 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3616 /* push back current token and set current token to 'last_tok'. Only
3617 identifier case handled for labels. */
3618 ST_INLN
void unget_tok(int last_tok
)
3621 TokenString
*str
= tok_str_alloc();
3622 tok_str_add2(str
, tok
, &tokc
);
3623 tok_str_add(str
, 0);
3624 begin_macro(str
, 1);
3628 static void tcc_predefs(TCCState
*s1
, CString
*cs
, int is_asm
)
3632 sscanf(TCC_VERSION
, "%d.%d.%d", &a
, &b
, &c
);
3633 cstr_printf(cs
, "#define __TINYC__ %d\n", a
*10000 + b
*100 + c
);
3635 /* target machine */
3636 #if defined TCC_TARGET_I386
3637 "#define __i386__ 1\n"
3638 "#define __i386 1\n"
3639 #elif defined TCC_TARGET_X86_64
3640 "#define __x86_64__ 1\n"
3641 "#define __amd64__ 1\n"
3642 #elif defined TCC_TARGET_ARM
3643 "#define __ARM_ARCH_4__ 1\n"
3644 "#define __arm_elf__ 1\n"
3645 "#define __arm_elf 1\n"
3646 "#define arm_elf 1\n"
3647 "#define __arm__ 1\n"
3650 "#define __APCS_32__ 1\n"
3651 "#define __ARMEL__ 1\n"
3652 # if defined TCC_ARM_EABI
3653 "#define __ARM_EABI__ 1\n"
3655 #elif defined TCC_TARGET_ARM64
3656 "#define __aarch64__ 1\n"
3657 #elif defined TCC_TARGET_C67
3658 "#define __C67__ 1\n"
3659 #elif defined TCC_TARGET_RISCV64
3660 "#define __riscv 1\n"
3661 "#define __riscv_xlen 64\n"
3662 "#define __riscv_flen 64\n"
3663 "#define __riscv_div 1\n"
3664 "#define __riscv_mul 1\n"
3665 "#define __riscv_fdiv 1\n"
3666 "#define __riscv_fsqrt 1\n"
3667 "#define __riscv_float_abi_double 1\n"
3670 #ifdef TCC_TARGET_ARM
3671 if (s1
->float_abi
== ARM_HARD_FLOAT
)
3672 cstr_printf(cs
, "#define __ARM_PCS_VFP 1\n");
3675 /* target platform */
3676 #ifdef TCC_TARGET_PE
3677 "#define _WIN32 1\n"
3679 "#define __unix__ 1\n"
3680 "#define __unix 1\n"
3681 # if defined TCC_TARGET_MACHO
3682 "#define __APPLE__ 1\n"
3683 # elif TARGETOS_FreeBSD
3684 "#define __FreeBSD__ 12\n"
3685 # elif TARGETOS_FreeBSD_kernel
3686 "#define __FreeBSD_kernel__ 1\n"
3687 # elif TARGETOS_NetBSD
3688 "#define __NetBSD__ 1\n"
3689 # elif TARGETOS_OpenBSD
3690 "#define __OpenBSD__ 1\n"
3692 "#define __linux__ 1\n"
3693 "#define __linux 1\n"
3698 cstr_printf(cs
, "#define __ASSEMBLER__ 1\n");
3699 if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
)
3700 cstr_printf(cs
, "#define __TCC_PP__ 1\n");
3701 if (s1
->output_type
== TCC_OUTPUT_MEMORY
)
3702 cstr_printf(cs
, "#define __TCC_RUN__ 1\n");
3703 if (s1
->char_is_unsigned
)
3704 cstr_printf(cs
, "#define __CHAR_UNSIGNED__ 1\n");
3705 if (s1
->optimize
> 0)
3706 cstr_printf(cs
, "#define __OPTIMIZE__ 1\n");
3707 if (s1
->option_pthread
)
3708 cstr_printf(cs
, "#define _REENTRANT 1\n");
3709 if (s1
->leading_underscore
)
3710 cstr_printf(cs
, "#define __leading_underscore 1\n");
3711 #ifdef CONFIG_TCC_BCHECK
3712 if (s1
->do_bounds_check
)
3713 cstr_printf(cs
, "#define __BOUNDS_CHECKING_ON 1\n");
3715 cstr_printf(cs
, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE
);
3716 cstr_printf(cs
, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE
);
3718 cstr_printf(cs
, "#define __STDC__ 1\n");
3719 cstr_printf(cs
, "#define __STDC_VERSION__ %dL\n", s1
->cversion
);
3721 /* load more predefs and __builtins */
3722 #if CONFIG_TCC_PREDEFS
3723 #include "tccdefs_.h" /* include as strings */
3725 "#include <tccdefs.h>\n" /* load at runtime */
3729 cstr_printf(cs
, "#define __BASE_FILE__ \"%s\"\n", file
->filename
);
3732 ST_FUNC
void preprocess_start(TCCState
*s1
, int filetype
)
3734 int is_asm
= !!(filetype
& (AFF_TYPE_ASM
|AFF_TYPE_ASMPP
));
3739 s1
->include_stack_ptr
= s1
->include_stack
;
3740 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3741 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3744 pp_debug_tok
= pp_debug_symv
= 0;
3746 s1
->pack_stack
[0] = 0;
3747 s1
->pack_stack_ptr
= s1
->pack_stack
;
3749 set_idnum('$', !is_asm
&& s1
->dollars_in_identifiers
? IS_ID
: 0);
3750 set_idnum('.', is_asm
? IS_ID
: 0);
3752 if (!(filetype
& AFF_TYPE_ASM
)) {
3754 tcc_predefs(s1
, &cstr
, is_asm
);
3755 if (s1
->cmdline_defs
.size
)
3756 cstr_cat(&cstr
, s1
->cmdline_defs
.data
, s1
->cmdline_defs
.size
);
3757 if (s1
->cmdline_incl
.size
)
3758 cstr_cat(&cstr
, s1
->cmdline_incl
.data
, s1
->cmdline_incl
.size
);
3759 //printf("%s\n", (char*)cstr.data);
3760 *s1
->include_stack_ptr
++ = file
;
3761 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3762 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3766 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3767 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3770 /* cleanup from error/setjmp */
3771 ST_FUNC
void preprocess_end(TCCState
*s1
)
3781 ST_FUNC
void tccpp_new(TCCState
*s
)
3786 /* init isid table */
3787 for(i
= CH_EOF
; i
<128; i
++)
3789 is_space(i
) ? IS_SPC
3794 for(i
= 128; i
<256; i
++)
3795 set_idnum(i
, IS_ID
);
3797 /* init allocators */
3798 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3799 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3801 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3802 memset(s
->cached_includes_hash
, 0, sizeof s
->cached_includes_hash
);
3804 cstr_new(&cstr_buf
);
3805 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3806 tok_str_new(&tokstr_buf
);
3807 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3809 tok_ident
= TOK_IDENT
;
3818 tok_alloc(p
, r
- p
- 1);
3822 /* we add dummy defines for some special macros to speed up tests
3823 and to have working defined() */
3824 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
3825 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
3826 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
3827 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
3828 define_push(TOK___COUNTER__
, MACRO_OBJ
, NULL
, NULL
);
3831 ST_FUNC
void tccpp_delete(TCCState
*s
)
3835 dynarray_reset(&s
->cached_includes
, &s
->nb_cached_includes
);
3838 n
= tok_ident
- TOK_IDENT
;
3839 if (n
> total_idents
)
3841 for(i
= 0; i
< n
; i
++)
3842 tal_free(toksym_alloc
, table_ident
[i
]);
3843 tcc_free(table_ident
);
3846 /* free static buffers */
3847 cstr_free(&tokcstr
);
3848 cstr_free(&cstr_buf
);
3849 cstr_free(¯o_equal_buf
);
3850 tok_str_free_str(tokstr_buf
.str
);
3852 /* free allocators */
3853 tal_delete(toksym_alloc
);
3854 toksym_alloc
= NULL
;
3855 tal_delete(tokstr_alloc
);
3856 tokstr_alloc
= NULL
;
3859 /* ------------------------------------------------------------------------- */
3860 /* tcc -E [-P[1]] [-dD} support */
3862 static void tok_print(const char *msg
, const int *str
)
3868 fp
= tcc_state
->ppfp
;
3869 fprintf(fp
, "%s", msg
);
3871 TOK_GET(&t
, &str
, &cval
);
3874 fprintf(fp
, &" %s"[s
], get_tok_str(t
, &cval
)), s
= 1;
3879 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3881 int d
= f
->line_num
- f
->line_ref
;
3886 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3888 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3890 fputs("\n", s1
->ppfp
), --d
;
3891 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3892 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3894 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3895 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3897 f
->line_ref
= f
->line_num
;
3900 static void define_print(TCCState
*s1
, int v
)
3906 if (NULL
== s
|| NULL
== s
->d
)
3910 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3911 if (s
->type
.t
== MACRO_FUNC
) {
3916 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3923 tok_print("", s
->d
);
3926 static void pp_debug_defines(TCCState
*s1
)
3937 pp_line(s1
, file
, 0);
3938 file
->line_ref
= ++file
->line_num
;
3942 vs
= get_tok_str(v
, NULL
);
3943 if (t
== TOK_DEFINE
) {
3944 define_print(s1
, v
);
3945 } else if (t
== TOK_UNDEF
) {
3946 fprintf(fp
, "#undef %s\n", vs
);
3947 } else if (t
== TOK_push_macro
) {
3948 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3949 } else if (t
== TOK_pop_macro
) {
3950 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3955 static void pp_debug_builtins(TCCState
*s1
)
3958 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3959 define_print(s1
, v
);
3962 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3963 static int pp_need_space(int a
, int b
)
3965 return 'E' == a
? '+' == b
|| '-' == b
3966 : '+' == a
? TOK_INC
== b
|| '+' == b
3967 : '-' == a
? TOK_DEC
== b
|| '-' == b
3968 : a
>= TOK_IDENT
? b
>= TOK_IDENT
3969 : a
== TOK_PPNUM
? b
>= TOK_IDENT
3973 /* maybe hex like 0x1e */
3974 static int pp_check_he0xE(int t
, const char *p
)
3976 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3981 /* Preprocess the current file */
3982 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3984 BufferedFile
**iptr
;
3985 int token_seen
, spcs
, level
;
3989 parse_flags
= PARSE_FLAG_PREPROCESS
3990 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3991 | PARSE_FLAG_LINEFEED
3993 | PARSE_FLAG_ACCEPT_STRAYS
3995 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3996 capability to compile and run itself, provided all numbers are
3997 given as decimals. tcc -E -P10 will do. */
3998 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
3999 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
4002 /* for PP benchmarks */
4003 do next(); while (tok
!= TOK_EOF
);
4007 if (s1
->dflag
& 1) {
4008 pp_debug_builtins(s1
);
4012 token_seen
= TOK_LINEFEED
, spcs
= 0, level
= 0;
4014 pp_line(s1
, file
->prev
, level
++);
4015 pp_line(s1
, file
, level
);
4017 iptr
= s1
->include_stack_ptr
;
4022 level
= s1
->include_stack_ptr
- iptr
;
4025 pp_line(s1
, *iptr
, 0);
4026 pp_line(s1
, file
, level
);
4028 if (s1
->dflag
& 7) {
4029 pp_debug_defines(s1
);
4034 if (is_space(tok
)) {
4035 if (spcs
< sizeof white
- 1)
4036 white
[spcs
++] = tok
;
4038 } else if (tok
== TOK_LINEFEED
) {
4040 if (token_seen
== TOK_LINEFEED
)
4043 } else if (token_seen
== TOK_LINEFEED
) {
4044 pp_line(s1
, file
, 0);
4045 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
4046 white
[spcs
++] = ' ';
4049 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
4050 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
4051 token_seen
= pp_check_he0xE(tok
, p
);
4056 /* ------------------------------------------------------------------------- */