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 */
115 #define tal_free(al, p) tcc_free(p)
116 #define tal_realloc(al, p, size) tcc_realloc(p, size)
117 #define tal_new(a,b,c)
118 #define tal_delete(a)
120 #if !defined(MEM_DEBUG)
121 #define tal_free(al, p) tal_free_impl(al, p)
122 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
123 #define TAL_DEBUG_PARAMS
126 //#define TAL_INFO 1 /* collect and dump allocators stats */
127 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
128 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
129 #define TAL_DEBUG_PARAMS , const char *file, int line
130 #define TAL_DEBUG_FILE_LEN 40
133 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
134 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
135 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
136 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
137 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
138 #define CSTR_TAL_LIMIT 1024
140 typedef struct TinyAlloc
{
146 struct TinyAlloc
*next
, *top
;
155 typedef struct tal_header_t
{
158 int line_num
; /* negative line_num used for double free check */
159 char file_name
[TAL_DEBUG_FILE_LEN
+ 1];
163 /* ------------------------------------------------------------------------- */
165 static TinyAlloc
*tal_new(TinyAlloc
**pal
, unsigned limit
, unsigned size
)
167 TinyAlloc
*al
= tcc_mallocz(sizeof(TinyAlloc
));
168 al
->p
= al
->buffer
= tcc_malloc(size
);
175 static void tal_delete(TinyAlloc
*al
)
183 fprintf(stderr
, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
184 al
->limit
, al
->size
/ 1024.0 / 1024.0, al
->nb_peak
, al
->nb_total
, al
->nb_missed
,
185 (al
->peak_p
- al
->buffer
) * 100.0 / al
->size
);
188 if (al
->nb_allocs
> 0) {
190 fprintf(stderr
, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
191 al
->nb_allocs
, al
->limit
);
194 tal_header_t
*header
= (tal_header_t
*)p
;
195 if (header
->line_num
> 0) {
196 fprintf(stderr
, "%s:%d: chunk of %d bytes leaked\n",
197 header
->file_name
, header
->line_num
, header
->size
);
199 p
+= header
->size
+ sizeof(tal_header_t
);
207 tcc_free(al
->buffer
);
213 static void tal_free_impl(TinyAlloc
*al
, void *p TAL_DEBUG_PARAMS
)
218 if (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
) {
220 tal_header_t
*header
= (((tal_header_t
*)p
) - 1);
221 if (header
->line_num
< 0) {
222 fprintf(stderr
, "%s:%d: TAL_DEBUG: double frees chunk from\n",
224 fprintf(stderr
, "%s:%d: %d bytes\n",
225 header
->file_name
, (int)-header
->line_num
, (int)header
->size
);
227 header
->line_num
= -header
->line_num
;
232 } else if (al
->next
) {
240 static void *tal_realloc_impl(TinyAlloc
**pal
, void *p
, unsigned size TAL_DEBUG_PARAMS
)
242 tal_header_t
*header
;
245 unsigned adj_size
= (size
+ 3) & -4;
246 TinyAlloc
*al
= *pal
;
249 is_own
= (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
);
250 if ((!p
|| is_own
) && size
<= al
->limit
) {
251 if (al
->p
- al
->buffer
+ adj_size
+ sizeof(tal_header_t
) < al
->size
) {
252 header
= (tal_header_t
*)al
->p
;
253 header
->size
= adj_size
;
255 { int ofs
= strlen(file
) - TAL_DEBUG_FILE_LEN
;
256 strncpy(header
->file_name
, file
+ (ofs
> 0 ? ofs
: 0), TAL_DEBUG_FILE_LEN
);
257 header
->file_name
[TAL_DEBUG_FILE_LEN
] = 0;
258 header
->line_num
= line
; }
260 ret
= al
->p
+ sizeof(tal_header_t
);
261 al
->p
+= adj_size
+ sizeof(tal_header_t
);
263 header
= (((tal_header_t
*)p
) - 1);
264 memcpy(ret
, p
, header
->size
);
266 header
->line_num
= -header
->line_num
;
272 if (al
->nb_peak
< al
->nb_allocs
)
273 al
->nb_peak
= al
->nb_allocs
;
274 if (al
->peak_p
< al
->p
)
281 ret
= tal_realloc(*pal
, 0, size
);
282 header
= (((tal_header_t
*)p
) - 1);
283 memcpy(ret
, p
, header
->size
);
285 header
->line_num
= -header
->line_num
;
292 TinyAlloc
*bottom
= al
, *next
= al
->top
? al
->top
: al
;
294 al
= tal_new(pal
, next
->limit
, next
->size
* 2);
302 ret
= tcc_malloc(size
);
303 header
= (((tal_header_t
*)p
) - 1);
304 memcpy(ret
, p
, header
->size
);
306 header
->line_num
= -header
->line_num
;
308 } else if (al
->next
) {
312 ret
= tcc_realloc(p
, size
);
321 /* ------------------------------------------------------------------------- */
322 /* CString handling */
323 static void cstr_realloc(CString
*cstr
, int new_size
)
327 size
= cstr
->size_allocated
;
329 size
= 8; /* no need to allocate a too small first string */
330 while (size
< new_size
)
332 cstr
->data
= tcc_realloc(cstr
->data
, size
);
333 cstr
->size_allocated
= size
;
337 ST_INLN
void cstr_ccat(CString
*cstr
, int ch
)
340 size
= cstr
->size
+ 1;
341 if (size
> cstr
->size_allocated
)
342 cstr_realloc(cstr
, size
);
343 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
347 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
, int len
)
351 len
= strlen(str
) + 1 + len
;
352 size
= cstr
->size
+ len
;
353 if (size
> cstr
->size_allocated
)
354 cstr_realloc(cstr
, size
);
355 memmove(((unsigned char *)cstr
->data
) + cstr
->size
, str
, len
);
359 /* add a wide char */
360 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
363 size
= cstr
->size
+ sizeof(nwchar_t
);
364 if (size
> cstr
->size_allocated
)
365 cstr_realloc(cstr
, size
);
366 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
370 ST_FUNC
void cstr_new(CString
*cstr
)
372 memset(cstr
, 0, sizeof(CString
));
375 /* free string and reset it to NULL */
376 ST_FUNC
void cstr_free(CString
*cstr
)
378 tcc_free(cstr
->data
);
382 /* reset string to empty */
383 ST_FUNC
void cstr_reset(CString
*cstr
)
388 ST_FUNC
int cstr_printf(CString
*cstr
, const char *fmt
, ...)
394 len
= vsnprintf(NULL
, 0, fmt
, v
);
396 size
= cstr
->size
+ len
+ 1;
397 if (size
> cstr
->size_allocated
)
398 cstr_realloc(cstr
, size
);
400 vsnprintf((char*)cstr
->data
+ cstr
->size
, size
, fmt
, v
);
407 static void add_char(CString
*cstr
, int c
)
409 if (c
== '\'' || c
== '\"' || c
== '\\') {
410 /* XXX: could be more precise if char or string */
411 cstr_ccat(cstr
, '\\');
413 if (c
>= 32 && c
<= 126) {
416 cstr_ccat(cstr
, '\\');
418 cstr_ccat(cstr
, 'n');
420 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
421 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
422 cstr_ccat(cstr
, '0' + (c
& 7));
427 /* ------------------------------------------------------------------------- */
428 /* allocate a new token */
429 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
431 TokenSym
*ts
, **ptable
;
434 if (tok_ident
>= SYM_FIRST_ANOM
)
435 tcc_error("memory full (symbols)");
437 /* expand token table if needed */
438 i
= tok_ident
- TOK_IDENT
;
439 if ((i
% TOK_ALLOC_INCR
) == 0) {
440 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
441 table_ident
= ptable
;
444 ts
= tal_realloc(toksym_alloc
, 0, sizeof(TokenSym
) + len
);
446 ts
->tok
= tok_ident
++;
447 ts
->sym_define
= NULL
;
448 ts
->sym_label
= NULL
;
449 ts
->sym_struct
= NULL
;
450 ts
->sym_identifier
= NULL
;
452 ts
->hash_next
= NULL
;
453 memcpy(ts
->str
, str
, len
);
459 #define TOK_HASH_INIT 1
460 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
463 /* find a token and add it if not found */
464 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
472 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
473 h
&= (TOK_HASH_SIZE
- 1);
475 pts
= &hash_ident
[h
];
480 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
482 pts
= &(ts
->hash_next
);
484 return tok_alloc_new(pts
, str
, len
);
487 /* XXX: buffer overflow */
488 /* XXX: float tokens */
489 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
494 cstr_reset(&cstr_buf
);
504 /* XXX: not quite exact, but only useful for testing */
506 sprintf(p
, "%u", (unsigned)cv
->i
);
508 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
512 cstr_ccat(&cstr_buf
, 'L');
514 cstr_ccat(&cstr_buf
, '\'');
515 add_char(&cstr_buf
, cv
->i
);
516 cstr_ccat(&cstr_buf
, '\'');
517 cstr_ccat(&cstr_buf
, '\0');
521 return (char*)cv
->str
.data
;
523 cstr_ccat(&cstr_buf
, 'L');
525 cstr_ccat(&cstr_buf
, '\"');
527 len
= cv
->str
.size
- 1;
529 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
531 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
533 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
535 cstr_ccat(&cstr_buf
, '\"');
536 cstr_ccat(&cstr_buf
, '\0');
540 cstr_cat(&cstr_buf
, "<float>", 0);
543 cstr_cat(&cstr_buf
, "<double>", 0);
546 cstr_cat(&cstr_buf
, "<long double>", 0);
549 cstr_cat(&cstr_buf
, "<linenumber>", 0);
552 /* above tokens have value, the ones below don't */
560 return strcpy(p
, "...");
562 return strcpy(p
, "<<=");
564 return strcpy(p
, ">>=");
566 return strcpy(p
, "<eof>");
569 /* search in two bytes table */
570 const unsigned char *q
= tok_two_chars
;
576 return cstr_buf
.data
;
581 sprintf(cstr_buf
.data
, "<%02x>", v
);
582 return cstr_buf
.data
;
587 } else if (v
< tok_ident
) {
588 return table_ident
[v
- TOK_IDENT
]->str
;
589 } else if (v
>= SYM_FIRST_ANOM
) {
590 /* special name for anonymous symbol */
591 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
593 /* should never happen */
598 return cstr_buf
.data
;
601 /* return the current character, handling end of block if necessary
603 static int handle_eob(void)
605 BufferedFile
*bf
= file
;
608 /* only tries to read if really end of buffer */
609 if (bf
->buf_ptr
>= bf
->buf_end
) {
611 #if defined(PARSE_DEBUG)
616 len
= read(bf
->fd
, bf
->buffer
, len
);
623 bf
->buf_ptr
= bf
->buffer
;
624 bf
->buf_end
= bf
->buffer
+ len
;
625 *bf
->buf_end
= CH_EOB
;
627 if (bf
->buf_ptr
< bf
->buf_end
) {
628 return bf
->buf_ptr
[0];
630 bf
->buf_ptr
= bf
->buf_end
;
635 /* read next char from current input file and handle end of input buffer */
636 static inline void inp(void)
638 ch
= *(++(file
->buf_ptr
));
639 /* end of buffer/file handling */
644 /* handle '\[\r]\n' */
645 static int handle_stray_noerror(void)
652 } else if (ch
== '\r') {
666 static void handle_stray(void)
668 if (handle_stray_noerror())
669 tcc_error("stray '\\' in program");
672 /* skip the stray and handle the \\n case. Output an error if
673 incorrect char after the stray */
674 static int handle_stray1(uint8_t *p
)
679 if (p
>= file
->buf_end
) {
686 if (handle_stray_noerror()) {
687 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
688 tcc_error("stray '\\' in program");
689 *--file
->buf_ptr
= '\\';
696 /* handle just the EOB case, but not stray */
697 #define PEEKC_EOB(c, p)\
708 /* handle the complicated stray case */
714 c = handle_stray1(p);\
719 /* input with '\[\r]\n' handling. Note that this function cannot
720 handle other characters after '\', so you cannot call it inside
721 strings or comments */
722 static void minp(void)
729 /* single line C++ comments */
730 static uint8_t *parse_line_comment(uint8_t *p
)
738 if (c
== '\n' || c
== CH_EOF
) {
740 } else if (c
== '\\') {
749 } else if (c
== '\r') {
767 static uint8_t *parse_comment(uint8_t *p
)
776 if (c
== '\n' || c
== '*' || c
== '\\')
780 if (c
== '\n' || c
== '*' || c
== '\\')
784 /* now we can handle all the cases */
788 } else if (c
== '*') {
794 } else if (c
== '/') {
796 } else if (c
== '\\') {
801 tcc_error("unexpected end of file in comment");
803 /* skip '\[\r]\n', otherwise just skip the stray */
809 } else if (c
== '\r') {
826 /* stray, eob or eof */
831 tcc_error("unexpected end of file in comment");
832 } else if (c
== '\\') {
842 ST_FUNC
int set_idnum(int c
, int val
)
844 int prev
= isidnum_table
[c
- CH_EOF
];
845 isidnum_table
[c
- CH_EOF
] = val
;
851 static inline void skip_spaces(void)
853 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
857 static inline int check_space(int t
, int *spc
)
859 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
868 /* parse a string without interpreting escapes */
869 static uint8_t *parse_pp_string(uint8_t *p
,
870 int sep
, CString
*str
)
878 } else if (c
== '\\') {
884 /* XXX: indicate line number of start of string */
885 tcc_error("missing terminating %c character", sep
);
886 } else if (c
== '\\') {
887 /* escape : just skip \[\r]\n */
892 } else if (c
== '\r') {
895 expect("'\n' after '\r'");
898 } else if (c
== CH_EOF
) {
899 goto unterminated_string
;
902 cstr_ccat(str
, '\\');
908 } else if (c
== '\n') {
911 } else if (c
== '\r') {
915 cstr_ccat(str
, '\r');
931 /* skip block of text until #else, #elif or #endif. skip also pairs of
933 static void preprocess_skip(void)
935 int a
, start_of_line
, c
, in_warn_or_error
;
942 in_warn_or_error
= 0;
963 } else if (c
== '\\') {
964 ch
= file
->buf_ptr
[0];
965 handle_stray_noerror();
972 if (in_warn_or_error
)
974 p
= parse_pp_string(p
, c
, NULL
);
978 if (in_warn_or_error
)
985 p
= parse_comment(p
);
986 } else if (ch
== '/') {
987 p
= parse_line_comment(p
);
997 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
999 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
1001 else if (tok
== TOK_ENDIF
)
1003 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
1004 in_warn_or_error
= 1;
1005 else if (tok
== TOK_LINEFEED
)
1007 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1008 p
= parse_line_comment(p
- 1);
1009 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1010 p
= parse_line_comment(p
- 1);
1024 /* return the number of additional 'ints' necessary to store the
1026 static inline int tok_size(const int *p
)
1041 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
1044 return 1 + LONG_SIZE
/ 4;
1050 return 1 + LDOUBLE_SIZE
/ 4;
1057 /* token string handling */
1058 ST_INLN
void tok_str_new(TokenString
*s
)
1061 s
->len
= s
->lastlen
= 0;
1062 s
->allocated_len
= 0;
1063 s
->last_line_num
= -1;
1066 ST_FUNC TokenString
*tok_str_alloc(void)
1068 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1073 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1077 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1078 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1082 ST_FUNC
void tok_str_free_str(int *str
)
1084 tal_free(tokstr_alloc
, str
);
1087 ST_FUNC
void tok_str_free(TokenString
*str
)
1089 tok_str_free_str(str
->str
);
1090 tal_free(tokstr_alloc
, str
);
1093 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1097 size
= s
->allocated_len
;
1100 while (size
< new_size
)
1102 if (size
> s
->allocated_len
) {
1103 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1104 s
->allocated_len
= size
;
1110 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1116 if (len
>= s
->allocated_len
)
1117 str
= tok_str_realloc(s
, len
+ 1);
1122 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1125 str
->prev
= macro_stack
;
1126 str
->prev_ptr
= macro_ptr
;
1127 str
->save_line_num
= file
->line_num
;
1128 macro_ptr
= str
->str
;
1132 ST_FUNC
void end_macro(void)
1134 TokenString
*str
= macro_stack
;
1135 macro_stack
= str
->prev
;
1136 macro_ptr
= str
->prev_ptr
;
1137 file
->line_num
= str
->save_line_num
;
1138 if (str
->alloc
!= 0) {
1139 if (str
->alloc
== 2)
1140 str
->str
= NULL
; /* don't free */
1145 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1149 len
= s
->lastlen
= s
->len
;
1152 /* allocate space for worst case */
1153 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1154 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1167 str
[len
++] = cv
->tab
[0];
1174 /* Insert the string into the int array. */
1176 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1177 if (len
+ nb_words
>= s
->allocated_len
)
1178 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1179 str
[len
] = cv
->str
.size
;
1180 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1191 #if LDOUBLE_SIZE == 8
1194 str
[len
++] = cv
->tab
[0];
1195 str
[len
++] = cv
->tab
[1];
1197 #if LDOUBLE_SIZE == 12
1199 str
[len
++] = cv
->tab
[0];
1200 str
[len
++] = cv
->tab
[1];
1201 str
[len
++] = cv
->tab
[2];
1202 #elif LDOUBLE_SIZE == 16
1204 str
[len
++] = cv
->tab
[0];
1205 str
[len
++] = cv
->tab
[1];
1206 str
[len
++] = cv
->tab
[2];
1207 str
[len
++] = cv
->tab
[3];
1208 #elif LDOUBLE_SIZE != 8
1209 #error add long double size support
1218 /* add the current parse token in token string 's' */
1219 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1223 /* save line number info */
1224 if (file
->line_num
!= s
->last_line_num
) {
1225 s
->last_line_num
= file
->line_num
;
1226 cval
.i
= s
->last_line_num
;
1227 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1229 tok_str_add2(s
, tok
, &tokc
);
1232 /* get a token from an integer array and increment pointer. */
1233 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1253 cv
->i
= (unsigned)*p
++;
1262 cv
->str
.size
= *p
++;
1264 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1276 #if LDOUBLE_SIZE == 16
1278 #elif LDOUBLE_SIZE == 12
1280 #elif LDOUBLE_SIZE == 8
1283 # error add long double size support
1296 static int macro_is_equal(const int *a
, const int *b
)
1305 /* first time preallocate macro_equal_buf, next time only reset position to start */
1306 cstr_reset(¯o_equal_buf
);
1307 TOK_GET(&t
, &a
, &cv
);
1308 cstr_cat(¯o_equal_buf
, get_tok_str(t
, &cv
), 0);
1309 TOK_GET(&t
, &b
, &cv
);
1310 if (strcmp(macro_equal_buf
.data
, get_tok_str(t
, &cv
)))
1316 /* defines handling */
1317 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1322 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1324 s
->next
= first_arg
;
1325 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1327 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1328 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1331 /* undefined a define symbol. Its name is just set to zero */
1332 ST_FUNC
void define_undef(Sym
*s
)
1335 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1336 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1339 ST_INLN Sym
*define_find(int v
)
1342 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1344 return table_ident
[v
]->sym_define
;
1347 /* free define stack until top reaches 'b' */
1348 ST_FUNC
void free_defines(Sym
*b
)
1350 while (define_stack
!= b
) {
1351 Sym
*top
= define_stack
;
1352 define_stack
= top
->prev
;
1353 tok_str_free_str(top
->d
);
1360 ST_FUNC Sym
*label_find(int v
)
1363 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1365 return table_ident
[v
]->sym_label
;
1368 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1371 s
= sym_push2(ptop
, v
, 0, 0);
1373 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1374 if (ptop
== &global_label_stack
) {
1375 /* modify the top most local identifier, so that
1376 sym_identifier will point to 's' when popped */
1378 ps
= &(*ps
)->prev_tok
;
1385 /* pop labels until element last is reached. Look if any labels are
1386 undefined. Define symbols if '&&label' was used. */
1387 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
, int keep
)
1390 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1392 if (s
->r
== LABEL_DECLARED
) {
1393 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1394 } else if (s
->r
== LABEL_FORWARD
) {
1395 tcc_error("label '%s' used but not defined",
1396 get_tok_str(s
->v
, NULL
));
1399 /* define corresponding symbol. A size of
1401 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1405 if (s
->r
!= LABEL_GONE
)
1406 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1416 /* fake the nth "#if defined test_..." for tcc -dt -run */
1417 static void maybe_run_test(TCCState
*s
)
1420 if (s
->include_stack_ptr
!= s
->include_stack
)
1422 p
= get_tok_str(tok
, NULL
);
1423 if (0 != memcmp(p
, "test_", 5))
1425 if (0 != --s
->run_test
)
1427 fprintf(s
->ppfp
, "\n[%s]\n" + !(s
->dflag
& 32), p
), fflush(s
->ppfp
);
1428 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1431 /* eval an expression for #if/#elif */
1432 static int expr_preprocess(void)
1437 str
= tok_str_alloc();
1439 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1440 next(); /* do macro subst */
1441 if (tok
== TOK_DEFINED
) {
1446 if (tok
< TOK_IDENT
)
1447 expect("identifier");
1448 if (tcc_state
->run_test
)
1449 maybe_run_test(tcc_state
);
1450 c
= define_find(tok
) != 0;
1458 } else if (tok
>= TOK_IDENT
) {
1459 /* if undefined macro */
1463 tok_str_add_tok(str
);
1466 tok_str_add(str
, -1); /* simulate end of file */
1467 tok_str_add(str
, 0);
1468 /* now evaluate C constant expression */
1469 begin_macro(str
, 1);
1477 /* parse after #define */
1478 ST_FUNC
void parse_define(void)
1480 Sym
*s
, *first
, **ps
;
1481 int v
, t
, varg
, is_vaargs
, spc
;
1482 int saved_parse_flags
= parse_flags
;
1485 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1486 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1487 /* XXX: should check if same macro (ANSI) */
1490 /* We have to parse the whole define as if not in asm mode, in particular
1491 no line comment with '#' must be ignored. Also for function
1492 macros the argument list must be parsed without '.' being an ID
1494 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1495 /* '(' must be just after macro definition for MACRO_FUNC */
1498 int dotid
= set_idnum('.', 0);
1501 if (tok
!= ')') for (;;) {
1505 if (varg
== TOK_DOTS
) {
1506 varg
= TOK___VA_ARGS__
;
1508 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1512 if (varg
< TOK_IDENT
)
1514 tcc_error("bad macro parameter list");
1515 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1520 if (tok
!= ',' || is_vaargs
)
1526 set_idnum('.', dotid
);
1531 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1532 /* The body of a macro definition should be parsed such that identifiers
1533 are parsed like the file mode determines (i.e. with '.' being an
1534 ID character in asm mode). But '#' should be retained instead of
1535 regarded as line comment leader, so still don't set ASM_FILE
1537 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1538 /* remove spaces around ## and after '#' */
1539 if (TOK_TWOSHARPS
== tok
) {
1546 } else if ('#' == tok
) {
1548 } else if (check_space(tok
, &spc
)) {
1551 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1556 parse_flags
= saved_parse_flags
;
1558 --tokstr_buf
.len
; /* remove trailing space */
1559 tok_str_add(&tokstr_buf
, 0);
1562 tcc_error("'##' cannot appear at either end of macro");
1563 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1566 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1568 const unsigned char *s
;
1574 s
= (unsigned char *) filename
;
1577 h
= TOK_HASH_FUNC(h
, toup(*s
));
1579 h
= TOK_HASH_FUNC(h
, *s
);
1583 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1585 i
= s1
->cached_includes_hash
[h
];
1589 e
= s1
->cached_includes
[i
- 1];
1590 if (0 == PATHCMP(e
->filename
, filename
))
1597 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1598 strcpy(e
->filename
, filename
);
1599 e
->ifndef_macro
= e
->once
= 0;
1600 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1601 /* add in hash table */
1602 e
->hash_next
= s1
->cached_includes_hash
[h
];
1603 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1605 printf("adding cached '%s'\n", filename
);
1610 static void pragma_parse(TCCState
*s1
)
1613 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1617 if (next(), tok
!= '(')
1619 if (next(), tok
!= TOK_STR
)
1621 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1622 if (next(), tok
!= ')')
1624 if (t
== TOK_push_macro
) {
1625 while (NULL
== (s
= define_find(v
)))
1626 define_push(v
, 0, NULL
, NULL
);
1627 s
->type
.ref
= s
; /* set push boundary */
1629 for (s
= define_stack
; s
; s
= s
->prev
)
1630 if (s
->v
== v
&& s
->type
.ref
== s
) {
1636 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1638 tcc_warning("unbalanced #pragma pop_macro");
1639 pp_debug_tok
= t
, pp_debug_symv
= v
;
1641 } else if (tok
== TOK_once
) {
1642 search_cached_include(s1
, file
->filename
, 1)->once
= pp_once
;
1644 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1645 /* tcc -E: keep pragmas below unchanged */
1647 unget_tok(TOK_PRAGMA
);
1649 unget_tok(TOK_LINEFEED
);
1651 } else if (tok
== TOK_pack
) {
1653 #pragma pack(1) // set
1654 #pragma pack() // reset to default
1655 #pragma pack(push,1) // push & set
1656 #pragma pack(pop) // restore previous */
1659 if (tok
== TOK_ASM_pop
) {
1661 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1663 tcc_error("out of pack stack");
1665 s1
->pack_stack_ptr
--;
1669 if (tok
== TOK_ASM_push
) {
1671 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1673 s1
->pack_stack_ptr
++;
1676 if (tok
!= TOK_CINT
)
1679 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1683 *s1
->pack_stack_ptr
= val
;
1688 } else if (tok
== TOK_comment
) {
1697 p
= tcc_strdup((char *)tokc
.str
.data
);
1702 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1704 if (t
== TOK_option
)
1705 tcc_set_options(s1
, p
);
1709 } else if (s1
->warn_unsupported
) {
1710 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1715 tcc_error("malformed #pragma directive");
1719 /* is_bof is true if first non space token at beginning of file */
1720 ST_FUNC
void preprocess(int is_bof
)
1722 TCCState
*s1
= tcc_state
;
1723 int i
, c
, n
, saved_parse_flags
;
1727 saved_parse_flags
= parse_flags
;
1728 parse_flags
= PARSE_FLAG_PREPROCESS
1729 | PARSE_FLAG_TOK_NUM
1730 | PARSE_FLAG_TOK_STR
1731 | PARSE_FLAG_LINEFEED
1732 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1741 pp_debug_symv
= tok
;
1747 pp_debug_symv
= tok
;
1748 s
= define_find(tok
);
1749 /* undefine symbol by putting an invalid name */
1754 case TOK_INCLUDE_NEXT
:
1755 ch
= file
->buf_ptr
[0];
1756 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1761 } else if (ch
== '\"') {
1766 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1767 if ((q
- buf
) < sizeof(buf
) - 1)
1770 if (handle_stray_noerror() == 0)
1778 /* eat all spaces and comments after include */
1779 /* XXX: slightly incorrect */
1780 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1785 /* computed #include : concatenate everything up to linefeed,
1786 the result must be one of the two accepted forms.
1787 Don't convert pp-tokens to tokens here. */
1788 parse_flags
= (PARSE_FLAG_PREPROCESS
1789 | PARSE_FLAG_LINEFEED
1790 | (parse_flags
& PARSE_FLAG_ASM_FILE
));
1793 while (tok
!= TOK_LINEFEED
) {
1794 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1798 /* check syntax and remove '<>|""' */
1799 if ((len
< 2 || ((buf
[0] != '"' || buf
[len
-1] != '"') &&
1800 (buf
[0] != '<' || buf
[len
-1] != '>'))))
1801 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1803 memmove(buf
, buf
+ 1, len
- 2);
1804 buf
[len
- 2] = '\0';
1807 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1808 tcc_error("#include recursion too deep");
1809 /* push current file on stack */
1810 *s1
->include_stack_ptr
++ = file
;
1811 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
: 0;
1812 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1813 for (; i
< n
; ++i
) {
1814 char buf1
[sizeof file
->filename
];
1819 /* check absolute include path */
1820 if (!IS_ABSPATH(buf
))
1824 } else if (i
== 1) {
1825 /* search in file's dir if "header.h" */
1828 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1829 path
= file
->true_filename
;
1830 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1833 /* search in all the include paths */
1834 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1835 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1836 pstrcpy(buf1
, sizeof(buf1
), path
);
1837 pstrcat(buf1
, sizeof(buf1
), "/");
1840 pstrcat(buf1
, sizeof(buf1
), buf
);
1841 e
= search_cached_include(s1
, buf1
, 0);
1842 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
== pp_once
)) {
1843 /* no need to parse the include because the 'ifndef macro'
1844 is defined (or had #pragma once) */
1846 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1851 if (tcc_open(s1
, buf1
) < 0)
1854 file
->include_next_index
= i
+ 1;
1856 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1858 /* update target deps */
1860 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1863 /* add include file debug info */
1864 tcc_debug_bincl(tcc_state
);
1865 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1866 ch
= file
->buf_ptr
[0];
1869 tcc_error("include file '%s' not found", buf
);
1871 --s1
->include_stack_ptr
;
1877 c
= expr_preprocess();
1883 if (tok
< TOK_IDENT
)
1884 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1888 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1890 file
->ifndef_macro
= tok
;
1893 c
= (define_find(tok
) != 0) ^ c
;
1895 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1896 tcc_error("memory full (ifdef)");
1897 *s1
->ifdef_stack_ptr
++ = c
;
1900 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1901 tcc_error("#else without matching #if");
1902 if (s1
->ifdef_stack_ptr
[-1] & 2)
1903 tcc_error("#else after #else");
1904 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1907 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1908 tcc_error("#elif without matching #if");
1909 c
= s1
->ifdef_stack_ptr
[-1];
1911 tcc_error("#elif after #else");
1912 /* last #if/#elif expression was true: we skip */
1916 c
= expr_preprocess();
1917 s1
->ifdef_stack_ptr
[-1] = c
;
1920 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1921 file
->ifndef_macro
= 0;
1930 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1931 tcc_error("#endif without matching #if");
1932 s1
->ifdef_stack_ptr
--;
1933 /* '#ifndef macro' was at the start of file. Now we check if
1934 an '#endif' is exactly at the end of file */
1935 if (file
->ifndef_macro
&&
1936 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1937 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1938 /* need to set to zero to avoid false matches if another
1939 #ifndef at middle of file */
1940 file
->ifndef_macro
= 0;
1941 while (tok
!= TOK_LINEFEED
)
1943 tok_flags
|= TOK_FLAG_ENDIF
;
1948 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1952 if (tok
!= TOK_CINT
)
1954 tcc_error("wrong #line format");
1958 if (tok
!= TOK_LINEFEED
) {
1959 if (tok
== TOK_STR
) {
1960 if (file
->true_filename
== file
->filename
)
1961 file
->true_filename
= tcc_strdup(file
->filename
);
1962 /* prepend directory from real file */
1963 pstrcpy(buf
, sizeof buf
, file
->true_filename
);
1964 *tcc_basename(buf
) = 0;
1965 pstrcat(buf
, sizeof buf
, (char *)tokc
.str
.data
);
1966 tcc_debug_putfile(s1
, buf
);
1967 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1974 total_lines
+= file
->line_num
- n
;
1980 ch
= file
->buf_ptr
[0];
1983 while (ch
!= '\n' && ch
!= CH_EOF
) {
1984 if ((q
- buf
) < sizeof(buf
) - 1)
1987 if (handle_stray_noerror() == 0)
1994 tcc_error("#error %s", buf
);
1996 tcc_warning("#warning %s", buf
);
2004 /* ignore gas line comment in an 'S' file. */
2005 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
2007 if (tok
== '!' && is_bof
)
2008 /* '!' is ignored at beginning to allow C scripts. */
2010 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2012 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
2015 /* ignore other preprocess commands or #! for C scripts */
2016 while (tok
!= TOK_LINEFEED
)
2019 parse_flags
= saved_parse_flags
;
2022 /* evaluate escape codes in a string. */
2023 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2038 case '0': case '1': case '2': case '3':
2039 case '4': case '5': case '6': case '7':
2040 /* at most three octal digits */
2045 n
= n
* 8 + c
- '0';
2049 n
= n
* 8 + c
- '0';
2054 goto add_char_nonext
;
2062 if (c
>= 'a' && c
<= 'f')
2064 else if (c
>= 'A' && c
<= 'F')
2074 goto add_char_nonext
;
2098 goto invalid_escape
;
2108 if (c
>= '!' && c
<= '~')
2109 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2111 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2114 } else if (is_long
&& c
>= 0x80) {
2115 /* assume we are processing UTF-8 sequence */
2116 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2118 int cont
; /* count of continuation bytes */
2119 int skip
; /* how many bytes should skip when error occurred */
2122 /* decode leading byte */
2124 skip
= 1; goto invalid_utf8_sequence
;
2125 } else if (c
<= 0xDF) {
2126 cont
= 1; n
= c
& 0x1f;
2127 } else if (c
<= 0xEF) {
2128 cont
= 2; n
= c
& 0xf;
2129 } else if (c
<= 0xF4) {
2130 cont
= 3; n
= c
& 0x7;
2132 skip
= 1; goto invalid_utf8_sequence
;
2135 /* decode continuation bytes */
2136 for (i
= 1; i
<= cont
; i
++) {
2137 int l
= 0x80, h
= 0xBF;
2139 /* adjust limit for second byte */
2142 case 0xE0: l
= 0xA0; break;
2143 case 0xED: h
= 0x9F; break;
2144 case 0xF0: l
= 0x90; break;
2145 case 0xF4: h
= 0x8F; break;
2149 if (p
[i
] < l
|| p
[i
] > h
) {
2150 skip
= i
; goto invalid_utf8_sequence
;
2153 n
= (n
<< 6) | (p
[i
] & 0x3f);
2156 /* advance pointer */
2159 goto add_char_nonext
;
2161 /* error handling */
2162 invalid_utf8_sequence
:
2163 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c
);
2166 goto add_char_nonext
;
2172 cstr_ccat(outstr
, c
);
2174 #ifdef TCC_TARGET_PE
2175 /* store as UTF-16 */
2177 cstr_wccat(outstr
, c
);
2180 cstr_wccat(outstr
, (c
>> 10) + 0xD800);
2181 cstr_wccat(outstr
, (c
& 0x3FF) + 0xDC00);
2184 cstr_wccat(outstr
, c
);
2188 /* add a trailing '\0' */
2190 cstr_ccat(outstr
, '\0');
2192 cstr_wccat(outstr
, '\0');
2195 static void parse_string(const char *s
, int len
)
2197 uint8_t buf
[1000], *p
= buf
;
2200 if ((is_long
= *s
== 'L'))
2204 if (len
>= sizeof buf
)
2205 p
= tcc_malloc(len
+ 1);
2209 cstr_reset(&tokcstr
);
2210 parse_escape_string(&tokcstr
, p
, is_long
);
2215 int char_size
, i
, n
, c
;
2216 /* XXX: make it portable */
2218 tok
= TOK_CCHAR
, char_size
= 1;
2220 tok
= TOK_LCHAR
, char_size
= sizeof(nwchar_t
);
2221 n
= tokcstr
.size
/ char_size
- 1;
2223 tcc_error("empty character constant");
2225 tcc_warning("multi-character character constant");
2226 for (c
= i
= 0; i
< n
; ++i
) {
2228 c
= ((nwchar_t
*)tokcstr
.data
)[i
];
2230 c
= (c
<< 8) | ((char *)tokcstr
.data
)[i
];
2234 tokc
.str
.size
= tokcstr
.size
;
2235 tokc
.str
.data
= tokcstr
.data
;
2243 /* we use 64 bit numbers */
2246 /* bn = (bn << shift) | or_val */
2247 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2251 for(i
=0;i
<BN_SIZE
;i
++) {
2253 bn
[i
] = (v
<< shift
) | or_val
;
2254 or_val
= v
>> (32 - shift
);
2258 static void bn_zero(unsigned int *bn
)
2261 for(i
=0;i
<BN_SIZE
;i
++) {
2266 /* parse number in null terminated string 'p' and return it in the
2268 static void parse_number(const char *p
)
2270 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2272 unsigned int bn
[BN_SIZE
];
2283 goto float_frac_parse
;
2284 } else if (t
== '0') {
2285 if (ch
== 'x' || ch
== 'X') {
2289 } else if (tcc_state
->tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2295 /* parse all digits. cannot check octal numbers at this stage
2296 because of floating point constants */
2298 if (ch
>= 'a' && ch
<= 'f')
2300 else if (ch
>= 'A' && ch
<= 'F')
2308 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2310 tcc_error("number too long");
2316 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2317 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2319 /* NOTE: strtox should support that for hexa numbers, but
2320 non ISOC99 libcs do not support it, so we prefer to do
2322 /* hexadecimal or binary floats */
2323 /* XXX: handle overflows */
2335 } else if (t
>= 'a') {
2337 } else if (t
>= 'A') {
2342 bn_lshift(bn
, shift
, t
);
2349 if (t
>= 'a' && t
<= 'f') {
2351 } else if (t
>= 'A' && t
<= 'F') {
2353 } else if (t
>= '0' && t
<= '9') {
2359 tcc_error("invalid digit");
2360 bn_lshift(bn
, shift
, t
);
2365 if (ch
!= 'p' && ch
!= 'P')
2372 } else if (ch
== '-') {
2376 if (ch
< '0' || ch
> '9')
2377 expect("exponent digits");
2378 while (ch
>= '0' && ch
<= '9') {
2379 exp_val
= exp_val
* 10 + ch
- '0';
2382 exp_val
= exp_val
* s
;
2384 /* now we can generate the number */
2385 /* XXX: should patch directly float number */
2386 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2387 d
= ldexp(d
, exp_val
- frac_bits
);
2392 /* float : should handle overflow */
2394 } else if (t
== 'L') {
2396 #ifdef TCC_TARGET_PE
2401 /* XXX: not large enough */
2402 tokc
.ld
= (long double)d
;
2409 /* decimal floats */
2411 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2416 while (ch
>= '0' && ch
<= '9') {
2417 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2423 if (ch
== 'e' || ch
== 'E') {
2424 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2428 if (ch
== '-' || ch
== '+') {
2429 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2434 if (ch
< '0' || ch
> '9')
2435 expect("exponent digits");
2436 while (ch
>= '0' && ch
<= '9') {
2437 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2449 tokc
.f
= strtof(token_buf
, NULL
);
2450 } else if (t
== 'L') {
2452 #ifdef TCC_TARGET_PE
2454 tokc
.d
= strtod(token_buf
, NULL
);
2457 tokc
.ld
= strtold(token_buf
, NULL
);
2461 tokc
.d
= strtod(token_buf
, NULL
);
2465 unsigned long long n
, n1
;
2466 int lcount
, ucount
, ov
= 0;
2469 /* integer number */
2472 if (b
== 10 && *q
== '0') {
2479 /* no need for checks except for base 10 / 8 errors */
2489 tcc_error("invalid digit");
2492 /* detect overflow */
2493 if (n1
>= 0x1000000000000000ULL
&& n
/ b
!= n1
)
2497 /* Determine the characteristics (unsigned and/or 64bit) the type of
2498 the constant must have according to the constant suffix(es) */
2499 lcount
= ucount
= 0;
2505 tcc_error("three 'l's in integer constant");
2506 if (lcount
&& *(p
- 1) != ch
)
2507 tcc_error("incorrect integer suffix: %s", p1
);
2510 } else if (t
== 'U') {
2512 tcc_error("two 'u's in integer constant");
2520 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2521 if (ucount
== 0 && b
== 10) {
2522 if (lcount
<= (LONG_SIZE
== 4)) {
2523 if (n
>= 0x80000000U
)
2524 lcount
= (LONG_SIZE
== 4) + 1;
2526 if (n
>= 0x8000000000000000ULL
)
2529 if (lcount
<= (LONG_SIZE
== 4)) {
2530 if (n
>= 0x100000000ULL
)
2531 lcount
= (LONG_SIZE
== 4) + 1;
2532 else if (n
>= 0x80000000U
)
2535 if (n
>= 0x8000000000000000ULL
)
2540 tcc_warning("integer constant overflow");
2549 ++tok
; /* TOK_CU... */
2553 tcc_error("invalid number\n");
2557 #define PARSE2(c1, tok1, c2, tok2) \
2568 /* return next token without macro substitution */
2569 static inline void next_nomacro1(void)
2571 int t
, c
, is_long
, len
;
2584 if (parse_flags
& PARSE_FLAG_SPACES
)
2585 goto keep_tok_flags
;
2586 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2595 /* first look if it is in fact an end of buffer */
2596 c
= handle_stray1(p
);
2603 TCCState
*s1
= tcc_state
;
2604 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2605 && !(tok_flags
& TOK_FLAG_EOF
)) {
2606 tok_flags
|= TOK_FLAG_EOF
;
2608 goto keep_tok_flags
;
2609 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2611 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2612 tcc_error("missing #endif");
2613 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2614 /* no include left : end of file. */
2617 tok_flags
&= ~TOK_FLAG_EOF
;
2618 /* pop include file */
2620 /* test if previous '#endif' was after a #ifdef at
2622 if (tok_flags
& TOK_FLAG_ENDIF
) {
2624 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2626 search_cached_include(s1
, file
->filename
, 1)
2627 ->ifndef_macro
= file
->ifndef_macro_saved
;
2628 tok_flags
&= ~TOK_FLAG_ENDIF
;
2631 /* add end of include file debug info */
2632 tcc_debug_eincl(tcc_state
);
2633 /* pop include stack */
2635 s1
->include_stack_ptr
--;
2637 if (p
== file
->buffer
)
2638 tok_flags
= TOK_FLAG_BOF
|TOK_FLAG_BOL
;
2646 tok_flags
|= TOK_FLAG_BOL
;
2649 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2652 goto keep_tok_flags
;
2657 if ((tok_flags
& TOK_FLAG_BOL
) &&
2658 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2660 preprocess(tok_flags
& TOK_FLAG_BOF
);
2666 tok
= TOK_TWOSHARPS
;
2668 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2669 p
= parse_line_comment(p
- 1);
2678 /* dollar is allowed to start identifiers when not parsing asm */
2680 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2681 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2684 case 'a': case 'b': case 'c': case 'd':
2685 case 'e': case 'f': case 'g': case 'h':
2686 case 'i': case 'j': case 'k': case 'l':
2687 case 'm': case 'n': case 'o': case 'p':
2688 case 'q': case 'r': case 's': case 't':
2689 case 'u': case 'v': case 'w': case 'x':
2691 case 'A': case 'B': case 'C': case 'D':
2692 case 'E': case 'F': case 'G': case 'H':
2693 case 'I': case 'J': case 'K':
2694 case 'M': case 'N': case 'O': case 'P':
2695 case 'Q': case 'R': case 'S': case 'T':
2696 case 'U': case 'V': case 'W': case 'X':
2702 h
= TOK_HASH_FUNC(h
, c
);
2703 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2704 h
= TOK_HASH_FUNC(h
, c
);
2709 /* fast case : no stray found, so we have the full token
2710 and we have already hashed it */
2711 h
&= (TOK_HASH_SIZE
- 1);
2712 pts
= &hash_ident
[h
];
2717 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2719 pts
= &(ts
->hash_next
);
2721 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2725 cstr_reset(&tokcstr
);
2726 cstr_cat(&tokcstr
, (char *) p1
, len
);
2730 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2732 cstr_ccat(&tokcstr
, c
);
2735 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2741 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2743 goto parse_ident_fast
;
2746 if (c
== '\'' || c
== '\"') {
2750 cstr_reset(&tokcstr
);
2751 cstr_ccat(&tokcstr
, 'L');
2752 goto parse_ident_slow
;
2757 case '0': case '1': case '2': case '3':
2758 case '4': case '5': case '6': case '7':
2762 /* after the first digit, accept digits, alpha, '.' or sign if
2763 prefixed by 'eEpP' */
2765 cstr_reset(&tokcstr
);
2767 cstr_ccat(&tokcstr
, t
);
2768 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2770 || ((c
== '+' || c
== '-')
2771 && (((t
== 'e' || t
== 'E')
2772 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2773 /* 0xe+1 is 3 tokens in asm */
2774 && ((char*)tokcstr
.data
)[0] == '0'
2775 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2776 || t
== 'p' || t
== 'P'))))
2781 /* We add a trailing '\0' to ease parsing */
2782 cstr_ccat(&tokcstr
, '\0');
2783 tokc
.str
.size
= tokcstr
.size
;
2784 tokc
.str
.data
= tokcstr
.data
;
2789 /* special dot handling because it can also start a number */
2794 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2795 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2797 goto parse_ident_fast
;
2798 } else if (c
== '.') {
2804 *--p
= '.'; /* may underflow into file->unget[] */
2815 cstr_reset(&tokcstr
);
2817 cstr_ccat(&tokcstr
, 'L');
2818 cstr_ccat(&tokcstr
, c
);
2819 p
= parse_pp_string(p
, c
, &tokcstr
);
2820 cstr_ccat(&tokcstr
, c
);
2821 cstr_ccat(&tokcstr
, '\0');
2822 tokc
.str
.size
= tokcstr
.size
;
2823 tokc
.str
.data
= tokcstr
.data
;
2832 } else if (c
== '<') {
2849 } else if (c
== '>') {
2867 } else if (c
== '=') {
2880 } else if (c
== '=') {
2893 } else if (c
== '=') {
2906 } else if (c
== '=') {
2909 } else if (c
== '>') {
2917 PARSE2('!', '!', '=', TOK_NE
)
2918 PARSE2('=', '=', '=', TOK_EQ
)
2919 PARSE2('*', '*', '=', TOK_A_MUL
)
2920 PARSE2('%', '%', '=', TOK_A_MOD
)
2921 PARSE2('^', '^', '=', TOK_A_XOR
)
2923 /* comments or operator */
2927 p
= parse_comment(p
);
2928 /* comments replaced by a blank */
2930 goto keep_tok_flags
;
2931 } else if (c
== '/') {
2932 p
= parse_line_comment(p
);
2934 goto keep_tok_flags
;
2935 } else if (c
== '=') {
2955 case '@': /* only used in assembler */
2961 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
2962 goto parse_ident_fast
;
2963 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2965 tcc_error("unrecognized character \\x%02x", c
);
2971 #if defined(PARSE_DEBUG)
2972 printf("token = %d %s\n", tok
, get_tok_str(tok
, &tokc
));
2976 /* return next token without macro substitution. Can read input from
2978 static void next_nomacro_spc(void)
2984 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2985 if (tok
== TOK_LINENUM
) {
2986 file
->line_num
= tokc
.i
;
2993 //printf("token = %s\n", get_tok_str(tok, &tokc));
2996 ST_FUNC
void next_nomacro(void)
3000 } while (tok
< 256 && (isidnum_table
[tok
- CH_EOF
] & IS_SPC
));
3004 static void macro_subst(
3005 TokenString
*tok_str
,
3007 const int *macro_str
3010 /* substitute arguments in replacement lists in macro_str by the values in
3011 args (field d) and return allocated string */
3012 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
3024 TOK_GET(&t
, ¯o_str
, &cval
);
3029 TOK_GET(&t
, ¯o_str
, &cval
);
3032 s
= sym_find2(args
, t
);
3035 cstr_ccat(&cstr
, '\"');
3039 TOK_GET(&t
, &st
, &cval
);
3040 if (t
!= TOK_PLCHLDR
3042 && 0 == check_space(t
, &spc
)) {
3043 const char *s
= get_tok_str(t
, &cval
);
3045 if (t
== TOK_PPSTR
&& *s
!= '\'')
3046 add_char(&cstr
, *s
);
3048 cstr_ccat(&cstr
, *s
);
3054 cstr_ccat(&cstr
, '\"');
3055 cstr_ccat(&cstr
, '\0');
3057 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
3060 cval
.str
.size
= cstr
.size
;
3061 cval
.str
.data
= cstr
.data
;
3062 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
3066 expect("macro parameter after '#'");
3068 } else if (t
>= TOK_IDENT
) {
3069 s
= sym_find2(args
, t
);
3073 /* if '##' is present before or after, no arg substitution */
3074 if (*macro_str
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
3075 /* special case for var arg macros : ## eats the ','
3076 if empty VA_ARGS variable. */
3077 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
3079 /* suppress ',' '##' */
3082 /* suppress '##' and add variable */
3090 /* Expand arguments tokens and store them. In most
3091 cases we could also re-expand each argument if
3092 used multiple times, but not if the argument
3093 contains the __COUNTER__ macro. */
3095 sym_push2(&s
->next
, s
->v
, s
->type
.t
, 0);
3097 macro_subst(&str2
, nested_list
, st
);
3098 tok_str_add(&str2
, 0);
3099 s
->next
->d
= str2
.str
;
3105 TOK_GET(&t2
, &st
, &cval
);
3108 tok_str_add2(&str
, t2
, &cval
);
3110 if (str
.len
== l0
) /* expanded to empty string */
3111 tok_str_add(&str
, TOK_PLCHLDR
);
3113 tok_str_add(&str
, t
);
3116 tok_str_add2(&str
, t
, &cval
);
3120 tok_str_add(&str
, 0);
3124 static char const ab_month_name
[12][4] =
3126 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3127 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3130 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3136 if (t1
!= TOK_PLCHLDR
)
3137 cstr_cat(&cstr
, get_tok_str(t1
, v1
), -1);
3139 if (t2
!= TOK_PLCHLDR
)
3140 cstr_cat(&cstr
, get_tok_str(t2
, v2
), -1);
3141 cstr_ccat(&cstr
, '\0');
3143 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3144 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3148 if (0 == *file
->buf_ptr
)
3152 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3153 " preprocessing token", n
, cstr
.data
, (char*)cstr
.data
+ n
);
3158 //printf("paste <%s>\n", (char*)cstr.data);
3163 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3164 return the resulting string (which must be freed). */
3165 static inline int *macro_twosharps(const int *ptr0
)
3169 TokenString macro_str1
;
3170 int start_of_nosubsts
= -1;
3173 /* we search the first '##' */
3174 for (ptr
= ptr0
;;) {
3175 TOK_GET(&t
, &ptr
, &cval
);
3176 if (t
== TOK_PPJOIN
)
3182 tok_str_new(¯o_str1
);
3184 //tok_print(" $$$", ptr0);
3185 for (ptr
= ptr0
;;) {
3186 TOK_GET(&t
, &ptr
, &cval
);
3189 if (t
== TOK_PPJOIN
)
3191 while (*ptr
== TOK_PPJOIN
) {
3193 /* given 'a##b', remove nosubsts preceding 'a' */
3194 if (start_of_nosubsts
>= 0)
3195 macro_str1
.len
= start_of_nosubsts
;
3196 /* given 'a##b', remove nosubsts preceding 'b' */
3197 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3199 if (t1
&& t1
!= TOK_PPJOIN
) {
3200 TOK_GET(&t1
, &ptr
, &cv1
);
3201 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3202 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3203 t
= tok
, cval
= tokc
;
3205 tok_str_add2(¯o_str1
, t
, &cval
);
3211 if (t
== TOK_NOSUBST
) {
3212 if (start_of_nosubsts
< 0)
3213 start_of_nosubsts
= macro_str1
.len
;
3215 start_of_nosubsts
= -1;
3217 tok_str_add2(¯o_str1
, t
, &cval
);
3219 tok_str_add(¯o_str1
, 0);
3220 //tok_print(" ###", macro_str1.str);
3221 return macro_str1
.str
;
3224 /* peek or read [ws_str == NULL] next token from function macro call,
3225 walking up macro levels up to the file if necessary */
3226 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3234 p
= macro_ptr
, t
= *p
;
3236 while (is_space(t
) || TOK_LINEFEED
== t
|| TOK_PLCHLDR
== t
)
3237 tok_str_add(ws_str
, t
), t
= *++p
;
3241 /* also, end of scope for nested defined symbol */
3243 while (sa
&& sa
->v
== 0)
3252 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3255 uint8_t *p
= file
->buf_ptr
;
3258 p
= parse_comment(p
);
3259 file
->buf_ptr
= p
- 1;
3260 } else if (c
== '/') {
3261 p
= parse_line_comment(p
);
3262 file
->buf_ptr
= p
- 1;
3269 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3270 tok_str_add(ws_str
, ch
);
3284 /* do macro substitution of current token with macro 's' and add
3285 result to (tok_str,tok_len). 'nested_list' is the list of all
3286 macros we got inside to avoid recursing. Return non zero if no
3287 substitution needs to be done */
3288 static int macro_subst_tok(
3289 TokenString
*tok_str
,
3293 Sym
*args
, *sa
, *sa1
;
3294 int parlevel
, t
, t1
, spc
;
3301 /* if symbol is a macro, prepare substitution */
3302 /* special macros */
3303 if (tok
== TOK___LINE__
|| tok
== TOK___COUNTER__
) {
3304 t
= tok
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3305 snprintf(buf
, sizeof(buf
), "%d", t
);
3309 } else if (tok
== TOK___FILE__
) {
3310 cstrval
= file
->filename
;
3312 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3317 tm
= localtime(&ti
);
3318 if (tok
== TOK___DATE__
) {
3319 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3320 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3322 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3323 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3330 cstr_cat(&cstr
, cstrval
, 0);
3331 cval
.str
.size
= cstr
.size
;
3332 cval
.str
.data
= cstr
.data
;
3333 tok_str_add2(tok_str
, t1
, &cval
);
3336 int saved_parse_flags
= parse_flags
;
3337 int *joined_str
= NULL
;
3340 if (s
->type
.t
== MACRO_FUNC
) {
3341 /* whitespace between macro name and argument list */
3343 tok_str_new(&ws_str
);
3346 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3347 | PARSE_FLAG_ACCEPT_STRAYS
;
3349 /* get next token from argument stream */
3350 t
= next_argstream(nested_list
, &ws_str
);
3352 /* not a macro substitution after all, restore the
3353 * macro token plus all whitespace we've read.
3354 * whitespace is intentionally not merged to preserve
3356 parse_flags
= saved_parse_flags
;
3357 tok_str_add(tok_str
, tok
);
3358 if (parse_flags
& PARSE_FLAG_SPACES
) {
3360 for (i
= 0; i
< ws_str
.len
; i
++)
3361 tok_str_add(tok_str
, ws_str
.str
[i
]);
3363 tok_str_free_str(ws_str
.str
);
3366 tok_str_free_str(ws_str
.str
);
3369 next_nomacro(); /* eat '(' */
3370 } while (tok
== TOK_PLCHLDR
);
3372 /* argument macro */
3375 /* NOTE: empty args are allowed, except if no args */
3378 next_argstream(nested_list
, NULL
);
3379 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3381 /* handle '()' case */
3382 if (!args
&& !sa
&& tok
== ')')
3385 tcc_error("macro '%s' used with too many args",
3386 get_tok_str(s
->v
, 0));
3389 /* NOTE: non zero sa->t indicates VA_ARGS */
3390 while ((parlevel
> 0 ||
3392 (tok
!= ',' || sa
->type
.t
)))) {
3393 if (tok
== TOK_EOF
|| tok
== 0)
3397 else if (tok
== ')')
3399 if (tok
== TOK_LINEFEED
)
3401 if (!check_space(tok
, &spc
))
3402 tok_str_add2(&str
, tok
, &tokc
);
3403 next_argstream(nested_list
, NULL
);
3408 tok_str_add(&str
, -1);
3409 tok_str_add(&str
, 0);
3410 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3414 /* special case for gcc var args: add an empty
3415 var arg argument if it is omitted */
3416 if (sa
&& sa
->type
.t
&& gnu_ext
)
3424 tcc_error("macro '%s' used with too few args",
3425 get_tok_str(s
->v
, 0));
3428 parse_flags
= saved_parse_flags
;
3430 /* now subst each arg */
3431 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3436 tok_str_free_str(sa
->d
);
3438 tok_str_free_str(sa
->next
->d
);
3446 sym_push2(nested_list
, s
->v
, 0, 0);
3447 parse_flags
= saved_parse_flags
;
3448 joined_str
= macro_twosharps(mstr
);
3449 macro_subst(tok_str
, nested_list
, joined_str
? joined_str
: mstr
);
3451 /* pop nested defined symbol */
3453 *nested_list
= sa1
->prev
;
3456 tok_str_free_str(joined_str
);
3458 tok_str_free_str(mstr
);
3463 /* do macro substitution of macro_str and add result to
3464 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3465 inside to avoid recursing. */
3466 static void macro_subst(
3467 TokenString
*tok_str
,
3469 const int *macro_str
3473 int t
, spc
, nosubst
;
3479 TOK_GET(&t
, ¯o_str
, &cval
);
3483 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3488 /* if nested substitution, do nothing */
3489 if (sym_find2(*nested_list
, t
)) {
3490 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3491 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3496 TokenString
*str
= tok_str_alloc();
3497 str
->str
= (int*)macro_str
;
3498 begin_macro(str
, 2);
3501 macro_subst_tok(tok_str
, nested_list
, s
);
3503 if (macro_stack
!= str
) {
3504 /* already finished by reading function macro arguments */
3508 macro_str
= macro_ptr
;
3512 spc
= is_space(t
= tok_str
->str
[tok_str
->lastlen
]);
3514 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3515 tcc_error("stray '\\' in program");
3517 if (!check_space(t
, &spc
))
3518 tok_str_add2(tok_str
, t
, &cval
);
3521 if (nosubst
> 1 && (spc
|| (++nosubst
== 3 && t
== '(')))
3525 if (t
== TOK_NOSUBST
)
3528 /* GCC supports 'defined' as result of a macro substitution */
3529 if (t
== TOK_DEFINED
&& pp_expr
)
3534 /* return next token with macro substitution */
3535 ST_FUNC
void next(void)
3538 if (parse_flags
& PARSE_FLAG_SPACES
)
3544 if (tok
== TOK_NOSUBST
|| tok
== TOK_PLCHLDR
) {
3545 /* discard preprocessor markers */
3547 } else if (tok
== 0) {
3548 /* end of macro or unget token string */
3552 } else if (tok
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3554 /* if reading from file, try to substitute macros */
3555 s
= define_find(tok
);
3557 Sym
*nested_list
= NULL
;
3559 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3560 tok_str_add(&tokstr_buf
, 0);
3561 begin_macro(&tokstr_buf
, 0);
3565 /* convert preprocessor tokens into C tokens */
3566 if (tok
== TOK_PPNUM
) {
3567 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3568 parse_number((char *)tokc
.str
.data
);
3569 } else if (tok
== TOK_PPSTR
) {
3570 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3571 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3575 /* push back current token and set current token to 'last_tok'. Only
3576 identifier case handled for labels. */
3577 ST_INLN
void unget_tok(int last_tok
)
3580 TokenString
*str
= tok_str_alloc();
3581 tok_str_add2(str
, tok
, &tokc
);
3582 tok_str_add(str
, 0);
3583 begin_macro(str
, 1);
3587 ST_FUNC
void preprocess_start(TCCState
*s1
, int is_asm
)
3593 s1
->include_stack_ptr
= s1
->include_stack
;
3594 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3595 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3598 pp_debug_tok
= pp_debug_symv
= 0;
3600 s1
->pack_stack
[0] = 0;
3601 s1
->pack_stack_ptr
= s1
->pack_stack
;
3603 set_idnum('$', s1
->dollars_in_identifiers
? IS_ID
: 0);
3604 set_idnum('.', is_asm
? IS_ID
: 0);
3607 if (s1
->cmdline_defs
.size
)
3608 cstr_cat(&cstr
, s1
->cmdline_defs
.data
, s1
->cmdline_defs
.size
);
3609 cstr_printf(&cstr
, "#define __BASE_FILE__ \"%s\"\n", file
->filename
);
3611 cstr_printf(&cstr
, "#define __ASSEMBLER__ 1\n");
3612 if (s1
->output_type
== TCC_OUTPUT_MEMORY
)
3613 cstr_printf(&cstr
, "#define __TCC_RUN__ 1\n");
3614 if (s1
->cmdline_incl
.size
)
3615 cstr_cat(&cstr
, s1
->cmdline_incl
.data
, s1
->cmdline_incl
.size
);
3616 //printf("%s\n", (char*)cstr.data);
3617 *s1
->include_stack_ptr
++ = file
;
3618 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3619 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3622 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3623 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3626 /* cleanup from error/setjmp */
3627 ST_FUNC
void preprocess_end(TCCState
*s1
)
3637 ST_FUNC
void tccpp_new(TCCState
*s
)
3642 /* init isid table */
3643 for(i
= CH_EOF
; i
<128; i
++)
3645 is_space(i
) ? IS_SPC
3650 for(i
= 128; i
<256; i
++)
3651 set_idnum(i
, IS_ID
);
3653 /* init allocators */
3654 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3655 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3657 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3658 memset(s
->cached_includes_hash
, 0, sizeof s
->cached_includes_hash
);
3660 cstr_new(&cstr_buf
);
3661 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3662 tok_str_new(&tokstr_buf
);
3663 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3665 tok_ident
= TOK_IDENT
;
3674 tok_alloc(p
, r
- p
- 1);
3678 /* we add dummy defines for some special macros to speed up tests
3679 and to have working defined() */
3680 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
3681 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
3682 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
3683 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
3684 define_push(TOK___COUNTER__
, MACRO_OBJ
, NULL
, NULL
);
3687 ST_FUNC
void tccpp_delete(TCCState
*s
)
3691 dynarray_reset(&s
->cached_includes
, &s
->nb_cached_includes
);
3694 n
= tok_ident
- TOK_IDENT
;
3695 if (n
> total_idents
)
3697 for(i
= 0; i
< n
; i
++)
3698 tal_free(toksym_alloc
, table_ident
[i
]);
3699 tcc_free(table_ident
);
3702 /* free static buffers */
3703 cstr_free(&tokcstr
);
3704 cstr_free(&cstr_buf
);
3705 cstr_free(¯o_equal_buf
);
3706 tok_str_free_str(tokstr_buf
.str
);
3708 /* free allocators */
3709 tal_delete(toksym_alloc
);
3710 toksym_alloc
= NULL
;
3711 tal_delete(tokstr_alloc
);
3712 tokstr_alloc
= NULL
;
3715 /* ------------------------------------------------------------------------- */
3716 /* tcc -E [-P[1]] [-dD} support */
3718 static void tok_print(const char *msg
, const int *str
)
3724 fp
= tcc_state
->ppfp
;
3725 fprintf(fp
, "%s", msg
);
3727 TOK_GET(&t
, &str
, &cval
);
3730 fprintf(fp
, " %s" + s
, get_tok_str(t
, &cval
)), s
= 1;
3735 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3737 int d
= f
->line_num
- f
->line_ref
;
3742 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3744 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3746 fputs("\n", s1
->ppfp
), --d
;
3747 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3748 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3750 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3751 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3753 f
->line_ref
= f
->line_num
;
3756 static void define_print(TCCState
*s1
, int v
)
3762 if (NULL
== s
|| NULL
== s
->d
)
3766 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3767 if (s
->type
.t
== MACRO_FUNC
) {
3772 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3779 tok_print("", s
->d
);
3782 static void pp_debug_defines(TCCState
*s1
)
3793 pp_line(s1
, file
, 0);
3794 file
->line_ref
= ++file
->line_num
;
3798 vs
= get_tok_str(v
, NULL
);
3799 if (t
== TOK_DEFINE
) {
3800 define_print(s1
, v
);
3801 } else if (t
== TOK_UNDEF
) {
3802 fprintf(fp
, "#undef %s\n", vs
);
3803 } else if (t
== TOK_push_macro
) {
3804 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3805 } else if (t
== TOK_pop_macro
) {
3806 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3811 static void pp_debug_builtins(TCCState
*s1
)
3814 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3815 define_print(s1
, v
);
3818 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3819 static int pp_need_space(int a
, int b
)
3821 return 'E' == a
? '+' == b
|| '-' == b
3822 : '+' == a
? TOK_INC
== b
|| '+' == b
3823 : '-' == a
? TOK_DEC
== b
|| '-' == b
3824 : a
>= TOK_IDENT
? b
>= TOK_IDENT
3825 : a
== TOK_PPNUM
? b
>= TOK_IDENT
3829 /* maybe hex like 0x1e */
3830 static int pp_check_he0xE(int t
, const char *p
)
3832 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3837 /* Preprocess the current file */
3838 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3840 BufferedFile
**iptr
;
3841 int token_seen
, spcs
, level
;
3845 parse_flags
= PARSE_FLAG_PREPROCESS
3846 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3847 | PARSE_FLAG_LINEFEED
3849 | PARSE_FLAG_ACCEPT_STRAYS
3851 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3852 capability to compile and run itself, provided all numbers are
3853 given as decimals. tcc -E -P10 will do. */
3854 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
3855 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
3858 /* for PP benchmarks */
3859 do next(); while (tok
!= TOK_EOF
);
3863 if (s1
->dflag
& 1) {
3864 pp_debug_builtins(s1
);
3868 token_seen
= TOK_LINEFEED
, spcs
= 0;
3869 pp_line(s1
, file
, 0);
3871 iptr
= s1
->include_stack_ptr
;
3876 level
= s1
->include_stack_ptr
- iptr
;
3879 pp_line(s1
, *iptr
, 0);
3880 pp_line(s1
, file
, level
);
3882 if (s1
->dflag
& 7) {
3883 pp_debug_defines(s1
);
3888 if (is_space(tok
)) {
3889 if (spcs
< sizeof white
- 1)
3890 white
[spcs
++] = tok
;
3892 } else if (tok
== TOK_LINEFEED
) {
3894 if (token_seen
== TOK_LINEFEED
)
3897 } else if (token_seen
== TOK_LINEFEED
) {
3898 pp_line(s1
, file
, 0);
3899 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
3900 white
[spcs
++] = ' ';
3903 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
3904 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
3905 token_seen
= pp_check_he0xE(tok
, p
);
3910 /* ------------------------------------------------------------------------- */