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 ST_FUNC
int tok_alloc_const(const char *str
)
492 return tok_alloc(str
, strlen(str
))->tok
;
496 /* XXX: buffer overflow */
497 /* XXX: float tokens */
498 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
503 cstr_reset(&cstr_buf
);
513 /* XXX: not quite exact, but only useful for testing */
515 sprintf(p
, "%u", (unsigned)cv
->i
);
517 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
521 cstr_ccat(&cstr_buf
, 'L');
523 cstr_ccat(&cstr_buf
, '\'');
524 add_char(&cstr_buf
, cv
->i
);
525 cstr_ccat(&cstr_buf
, '\'');
526 cstr_ccat(&cstr_buf
, '\0');
530 return (char*)cv
->str
.data
;
532 cstr_ccat(&cstr_buf
, 'L');
534 cstr_ccat(&cstr_buf
, '\"');
536 len
= cv
->str
.size
- 1;
538 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
540 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
542 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
544 cstr_ccat(&cstr_buf
, '\"');
545 cstr_ccat(&cstr_buf
, '\0');
549 cstr_cat(&cstr_buf
, "<float>", 0);
552 cstr_cat(&cstr_buf
, "<double>", 0);
555 cstr_cat(&cstr_buf
, "<long double>", 0);
558 cstr_cat(&cstr_buf
, "<linenumber>", 0);
561 /* above tokens have value, the ones below don't */
569 return strcpy(p
, "...");
571 return strcpy(p
, "<<=");
573 return strcpy(p
, ">>=");
575 return strcpy(p
, "<eof>");
578 /* search in two bytes table */
579 const unsigned char *q
= tok_two_chars
;
585 return cstr_buf
.data
;
590 sprintf(cstr_buf
.data
, "<%02x>", v
);
591 return cstr_buf
.data
;
596 } else if (v
< tok_ident
) {
597 return table_ident
[v
- TOK_IDENT
]->str
;
598 } else if (v
>= SYM_FIRST_ANOM
) {
599 /* special name for anonymous symbol */
600 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
602 /* should never happen */
607 return cstr_buf
.data
;
610 /* return the current character, handling end of block if necessary
612 static int handle_eob(void)
614 BufferedFile
*bf
= file
;
617 /* only tries to read if really end of buffer */
618 if (bf
->buf_ptr
>= bf
->buf_end
) {
620 #if defined(PARSE_DEBUG)
625 len
= read(bf
->fd
, bf
->buffer
, len
);
632 bf
->buf_ptr
= bf
->buffer
;
633 bf
->buf_end
= bf
->buffer
+ len
;
634 *bf
->buf_end
= CH_EOB
;
636 if (bf
->buf_ptr
< bf
->buf_end
) {
637 return bf
->buf_ptr
[0];
639 bf
->buf_ptr
= bf
->buf_end
;
644 /* read next char from current input file and handle end of input buffer */
645 static inline void inp(void)
647 ch
= *(++(file
->buf_ptr
));
648 /* end of buffer/file handling */
653 /* handle '\[\r]\n' */
654 static int handle_stray_noerror(void)
661 } else if (ch
== '\r') {
675 static void handle_stray(void)
677 if (handle_stray_noerror())
678 tcc_error("stray '\\' in program");
681 /* skip the stray and handle the \\n case. Output an error if
682 incorrect char after the stray */
683 static int handle_stray1(uint8_t *p
)
688 if (p
>= file
->buf_end
) {
695 if (handle_stray_noerror()) {
696 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
697 tcc_error("stray '\\' in program");
698 *--file
->buf_ptr
= '\\';
705 /* handle just the EOB case, but not stray */
706 #define PEEKC_EOB(c, p)\
717 /* handle the complicated stray case */
723 c = handle_stray1(p);\
728 /* input with '\[\r]\n' handling. Note that this function cannot
729 handle other characters after '\', so you cannot call it inside
730 strings or comments */
731 static void minp(void)
738 /* single line C++ comments */
739 static uint8_t *parse_line_comment(uint8_t *p
)
747 if (c
== '\n' || c
== CH_EOF
) {
749 } else if (c
== '\\') {
758 } else if (c
== '\r') {
776 static uint8_t *parse_comment(uint8_t *p
)
785 if (c
== '\n' || c
== '*' || c
== '\\')
789 if (c
== '\n' || c
== '*' || c
== '\\')
793 /* now we can handle all the cases */
797 } else if (c
== '*') {
803 } else if (c
== '/') {
805 } else if (c
== '\\') {
810 tcc_error("unexpected end of file in comment");
812 /* skip '\[\r]\n', otherwise just skip the stray */
818 } else if (c
== '\r') {
835 /* stray, eob or eof */
840 tcc_error("unexpected end of file in comment");
841 } else if (c
== '\\') {
851 ST_FUNC
int set_idnum(int c
, int val
)
853 int prev
= isidnum_table
[c
- CH_EOF
];
854 isidnum_table
[c
- CH_EOF
] = val
;
860 static inline void skip_spaces(void)
862 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
866 static inline int check_space(int t
, int *spc
)
868 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
877 /* parse a string without interpreting escapes */
878 static uint8_t *parse_pp_string(uint8_t *p
,
879 int sep
, CString
*str
)
887 } else if (c
== '\\') {
893 /* XXX: indicate line number of start of string */
894 tcc_error("missing terminating %c character", sep
);
895 } else if (c
== '\\') {
896 /* escape : just skip \[\r]\n */
901 } else if (c
== '\r') {
904 expect("'\n' after '\r'");
907 } else if (c
== CH_EOF
) {
908 goto unterminated_string
;
911 cstr_ccat(str
, '\\');
917 } else if (c
== '\n') {
920 } else if (c
== '\r') {
924 cstr_ccat(str
, '\r');
940 /* skip block of text until #else, #elif or #endif. skip also pairs of
942 static void preprocess_skip(void)
944 int a
, start_of_line
, c
, in_warn_or_error
;
951 in_warn_or_error
= 0;
972 } else if (c
== '\\') {
973 ch
= file
->buf_ptr
[0];
974 handle_stray_noerror();
981 if (in_warn_or_error
)
983 p
= parse_pp_string(p
, c
, NULL
);
987 if (in_warn_or_error
)
994 p
= parse_comment(p
);
995 } else if (ch
== '/') {
996 p
= parse_line_comment(p
);
1001 if (start_of_line
) {
1006 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
1008 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
1010 else if (tok
== TOK_ENDIF
)
1012 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
1013 in_warn_or_error
= 1;
1014 else if (tok
== TOK_LINEFEED
)
1016 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1017 p
= parse_line_comment(p
- 1);
1019 #if !defined(TCC_TARGET_ARM)
1020 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1021 p
= parse_line_comment(p
- 1);
1023 /* ARM assembly uses '#' for constants */
1038 /* return the number of additional 'ints' necessary to store the
1040 static inline int tok_size(const int *p
)
1055 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
1058 return 1 + LONG_SIZE
/ 4;
1064 return 1 + LDOUBLE_SIZE
/ 4;
1071 /* token string handling */
1072 ST_INLN
void tok_str_new(TokenString
*s
)
1075 s
->len
= s
->lastlen
= 0;
1076 s
->allocated_len
= 0;
1077 s
->last_line_num
= -1;
1080 ST_FUNC TokenString
*tok_str_alloc(void)
1082 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1087 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1091 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1092 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1096 ST_FUNC
void tok_str_free_str(int *str
)
1098 tal_free(tokstr_alloc
, str
);
1101 ST_FUNC
void tok_str_free(TokenString
*str
)
1103 tok_str_free_str(str
->str
);
1104 tal_free(tokstr_alloc
, str
);
1107 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1111 size
= s
->allocated_len
;
1114 while (size
< new_size
)
1116 if (size
> s
->allocated_len
) {
1117 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1118 s
->allocated_len
= size
;
1124 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1130 if (len
>= s
->allocated_len
)
1131 str
= tok_str_realloc(s
, len
+ 1);
1136 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1139 str
->prev
= macro_stack
;
1140 str
->prev_ptr
= macro_ptr
;
1141 str
->save_line_num
= file
->line_num
;
1142 macro_ptr
= str
->str
;
1146 ST_FUNC
void end_macro(void)
1148 TokenString
*str
= macro_stack
;
1149 macro_stack
= str
->prev
;
1150 macro_ptr
= str
->prev_ptr
;
1151 file
->line_num
= str
->save_line_num
;
1152 if (str
->alloc
!= 0) {
1153 if (str
->alloc
== 2)
1154 str
->str
= NULL
; /* don't free */
1159 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1163 len
= s
->lastlen
= s
->len
;
1166 /* allocate space for worst case */
1167 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1168 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1181 str
[len
++] = cv
->tab
[0];
1188 /* Insert the string into the int array. */
1190 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1191 if (len
+ nb_words
>= s
->allocated_len
)
1192 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1193 str
[len
] = cv
->str
.size
;
1194 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1205 #if LDOUBLE_SIZE == 8
1208 str
[len
++] = cv
->tab
[0];
1209 str
[len
++] = cv
->tab
[1];
1211 #if LDOUBLE_SIZE == 12
1213 str
[len
++] = cv
->tab
[0];
1214 str
[len
++] = cv
->tab
[1];
1215 str
[len
++] = cv
->tab
[2];
1216 #elif LDOUBLE_SIZE == 16
1218 str
[len
++] = cv
->tab
[0];
1219 str
[len
++] = cv
->tab
[1];
1220 str
[len
++] = cv
->tab
[2];
1221 str
[len
++] = cv
->tab
[3];
1222 #elif LDOUBLE_SIZE != 8
1223 #error add long double size support
1232 /* add the current parse token in token string 's' */
1233 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1237 /* save line number info */
1238 if (file
->line_num
!= s
->last_line_num
) {
1239 s
->last_line_num
= file
->line_num
;
1240 cval
.i
= s
->last_line_num
;
1241 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1243 tok_str_add2(s
, tok
, &tokc
);
1246 /* get a token from an integer array and increment pointer. */
1247 static inline void tok_get(int *t
, const int **pp
, CValue
*cv
)
1267 cv
->i
= (unsigned)*p
++;
1276 cv
->str
.size
= *p
++;
1278 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1290 #if LDOUBLE_SIZE == 16
1292 #elif LDOUBLE_SIZE == 12
1294 #elif LDOUBLE_SIZE == 8
1297 # error add long double size support
1311 # define TOK_GET(t,p,c) tok_get(t,p,c)
1313 # define TOK_GET(t,p,c) do { \
1315 if (TOK_HAS_VALUE(_t)) \
1318 *(t) = _t, ++*(p); \
1322 static int macro_is_equal(const int *a
, const int *b
)
1331 /* first time preallocate macro_equal_buf, next time only reset position to start */
1332 cstr_reset(¯o_equal_buf
);
1333 TOK_GET(&t
, &a
, &cv
);
1334 cstr_cat(¯o_equal_buf
, get_tok_str(t
, &cv
), 0);
1335 TOK_GET(&t
, &b
, &cv
);
1336 if (strcmp(macro_equal_buf
.data
, get_tok_str(t
, &cv
)))
1342 /* defines handling */
1343 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1348 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1350 s
->next
= first_arg
;
1351 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1353 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1354 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1357 /* undefined a define symbol. Its name is just set to zero */
1358 ST_FUNC
void define_undef(Sym
*s
)
1361 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1362 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1365 ST_INLN Sym
*define_find(int v
)
1368 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1370 return table_ident
[v
]->sym_define
;
1373 /* free define stack until top reaches 'b' */
1374 ST_FUNC
void free_defines(Sym
*b
)
1376 while (define_stack
!= b
) {
1377 Sym
*top
= define_stack
;
1378 define_stack
= top
->prev
;
1379 tok_str_free_str(top
->d
);
1386 ST_FUNC Sym
*label_find(int v
)
1389 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1391 return table_ident
[v
]->sym_label
;
1394 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1397 s
= sym_push2(ptop
, v
, 0, 0);
1399 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1400 if (ptop
== &global_label_stack
) {
1401 /* modify the top most local identifier, so that
1402 sym_identifier will point to 's' when popped */
1404 ps
= &(*ps
)->prev_tok
;
1411 /* pop labels until element last is reached. Look if any labels are
1412 undefined. Define symbols if '&&label' was used. */
1413 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
, int keep
)
1416 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1418 if (s
->r
== LABEL_DECLARED
) {
1419 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1420 } else if (s
->r
== LABEL_FORWARD
) {
1421 tcc_error("label '%s' used but not defined",
1422 get_tok_str(s
->v
, NULL
));
1425 /* define corresponding symbol. A size of
1427 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1431 if (s
->r
!= LABEL_GONE
)
1432 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1442 /* fake the nth "#if defined test_..." for tcc -dt -run */
1443 static void maybe_run_test(TCCState
*s
)
1446 if (s
->include_stack_ptr
!= s
->include_stack
)
1448 p
= get_tok_str(tok
, NULL
);
1449 if (0 != memcmp(p
, "test_", 5))
1451 if (0 != --s
->run_test
)
1453 fprintf(s
->ppfp
, &"\n[%s]\n"[!(s
->dflag
& 32)], p
), fflush(s
->ppfp
);
1454 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1457 /* eval an expression for #if/#elif */
1458 static int expr_preprocess(void)
1463 str
= tok_str_alloc();
1465 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1466 next(); /* do macro subst */
1468 if (tok
== TOK_DEFINED
) {
1473 if (tok
< TOK_IDENT
)
1474 expect("identifier");
1475 if (tcc_state
->run_test
)
1476 maybe_run_test(tcc_state
);
1477 c
= define_find(tok
) != 0;
1485 } else if (1 && tok
== TOK___HAS_INCLUDE
) {
1486 next(); /* XXX check if correct to use expansion */
1488 while (tok
!= ')' && tok
!= TOK_EOF
)
1494 } else if (tok
>= TOK_IDENT
) {
1495 /* if undefined macro, replace with zero, check for func-like */
1499 tok_str_add_tok(str
);
1502 tcc_error("function-like macro '%s' is not defined",
1503 get_tok_str(t
, NULL
));
1506 tok_str_add_tok(str
);
1509 tok_str_add(str
, -1); /* simulate end of file */
1510 tok_str_add(str
, 0);
1511 /* now evaluate C constant expression */
1512 begin_macro(str
, 1);
1520 /* parse after #define */
1521 ST_FUNC
void parse_define(void)
1523 Sym
*s
, *first
, **ps
;
1524 int v
, t
, varg
, is_vaargs
, spc
;
1525 int saved_parse_flags
= parse_flags
;
1528 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1529 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1530 /* XXX: should check if same macro (ANSI) */
1533 /* We have to parse the whole define as if not in asm mode, in particular
1534 no line comment with '#' must be ignored. Also for function
1535 macros the argument list must be parsed without '.' being an ID
1537 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1538 /* '(' must be just after macro definition for MACRO_FUNC */
1540 parse_flags
&= ~PARSE_FLAG_SPACES
;
1542 int dotid
= set_idnum('.', 0);
1545 if (tok
!= ')') for (;;) {
1549 if (varg
== TOK_DOTS
) {
1550 varg
= TOK___VA_ARGS__
;
1552 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1556 if (varg
< TOK_IDENT
)
1558 tcc_error("bad macro parameter list");
1559 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1564 if (tok
!= ',' || is_vaargs
)
1568 parse_flags
|= PARSE_FLAG_SPACES
;
1571 set_idnum('.', dotid
);
1576 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1577 /* The body of a macro definition should be parsed such that identifiers
1578 are parsed like the file mode determines (i.e. with '.' being an
1579 ID character in asm mode). But '#' should be retained instead of
1580 regarded as line comment leader, so still don't set ASM_FILE
1582 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1583 /* remove spaces around ## and after '#' */
1584 if (TOK_TWOSHARPS
== tok
) {
1591 } else if ('#' == tok
) {
1593 } else if (check_space(tok
, &spc
)) {
1596 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1601 parse_flags
= saved_parse_flags
;
1603 --tokstr_buf
.len
; /* remove trailing space */
1604 tok_str_add(&tokstr_buf
, 0);
1607 tcc_error("'##' cannot appear at either end of macro");
1608 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1611 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1613 const unsigned char *s
;
1619 s
= (unsigned char *) filename
;
1622 h
= TOK_HASH_FUNC(h
, toup(*s
));
1624 h
= TOK_HASH_FUNC(h
, *s
);
1628 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1630 i
= s1
->cached_includes_hash
[h
];
1634 e
= s1
->cached_includes
[i
- 1];
1635 if (0 == PATHCMP(e
->filename
, filename
))
1642 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1643 strcpy(e
->filename
, filename
);
1644 e
->ifndef_macro
= e
->once
= 0;
1645 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1646 /* add in hash table */
1647 e
->hash_next
= s1
->cached_includes_hash
[h
];
1648 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1650 printf("adding cached '%s'\n", filename
);
1655 static void pragma_parse(TCCState
*s1
)
1658 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1662 if (next(), tok
!= '(')
1664 if (next(), tok
!= TOK_STR
)
1666 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1667 if (next(), tok
!= ')')
1669 if (t
== TOK_push_macro
) {
1670 while (NULL
== (s
= define_find(v
)))
1671 define_push(v
, 0, NULL
, NULL
);
1672 s
->type
.ref
= s
; /* set push boundary */
1674 for (s
= define_stack
; s
; s
= s
->prev
)
1675 if (s
->v
== v
&& s
->type
.ref
== s
) {
1681 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1683 tcc_warning("unbalanced #pragma pop_macro");
1684 pp_debug_tok
= t
, pp_debug_symv
= v
;
1686 } else if (tok
== TOK_once
) {
1687 search_cached_include(s1
, file
->filename
, 1)->once
= pp_once
;
1689 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1690 /* tcc -E: keep pragmas below unchanged */
1692 unget_tok(TOK_PRAGMA
);
1694 unget_tok(TOK_LINEFEED
);
1696 } else if (tok
== TOK_pack
) {
1698 #pragma pack(1) // set
1699 #pragma pack() // reset to default
1700 #pragma pack(push,1) // push & set
1701 #pragma pack(pop) // restore previous */
1704 if (tok
== TOK_ASM_pop
) {
1706 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1708 tcc_error("out of pack stack");
1710 s1
->pack_stack_ptr
--;
1714 if (tok
== TOK_ASM_push
) {
1716 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1718 s1
->pack_stack_ptr
++;
1721 if (tok
!= TOK_CINT
)
1724 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1728 *s1
->pack_stack_ptr
= val
;
1733 } else if (tok
== TOK_comment
) {
1742 p
= tcc_strdup((char *)tokc
.str
.data
);
1747 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1749 if (t
== TOK_option
)
1750 tcc_set_options(s1
, p
);
1754 } else if (s1
->warn_unsupported
) {
1755 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1760 tcc_error("malformed #pragma directive");
1764 /* is_bof is true if first non space token at beginning of file */
1765 ST_FUNC
void preprocess(int is_bof
)
1767 TCCState
*s1
= tcc_state
;
1768 int i
, c
, n
, saved_parse_flags
;
1772 saved_parse_flags
= parse_flags
;
1773 parse_flags
= PARSE_FLAG_PREPROCESS
1774 | PARSE_FLAG_TOK_NUM
1775 | PARSE_FLAG_TOK_STR
1776 | PARSE_FLAG_LINEFEED
1777 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1786 pp_debug_symv
= tok
;
1792 pp_debug_symv
= tok
;
1793 s
= define_find(tok
);
1794 /* undefine symbol by putting an invalid name */
1799 case TOK_INCLUDE_NEXT
:
1800 ch
= file
->buf_ptr
[0];
1801 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1806 } else if (ch
== '\"') {
1811 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1812 if ((q
- buf
) < sizeof(buf
) - 1)
1815 if (handle_stray_noerror() == 0)
1823 /* eat all spaces and comments after include */
1824 /* XXX: slightly incorrect */
1825 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1830 /* computed #include : concatenate everything up to linefeed,
1831 the result must be one of the two accepted forms.
1832 Don't convert pp-tokens to tokens here. */
1833 parse_flags
= (PARSE_FLAG_PREPROCESS
1834 | PARSE_FLAG_LINEFEED
1835 | (parse_flags
& PARSE_FLAG_ASM_FILE
));
1838 while (tok
!= TOK_LINEFEED
) {
1839 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1843 /* check syntax and remove '<>|""' */
1844 if ((len
< 2 || ((buf
[0] != '"' || buf
[len
-1] != '"') &&
1845 (buf
[0] != '<' || buf
[len
-1] != '>'))))
1846 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1848 memmove(buf
, buf
+ 1, len
- 2);
1849 buf
[len
- 2] = '\0';
1852 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1853 tcc_error("#include recursion too deep");
1854 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
+ 1 : 0;
1855 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1856 for (; i
< n
; ++i
) {
1857 char buf1
[sizeof file
->filename
];
1862 /* check absolute include path */
1863 if (!IS_ABSPATH(buf
))
1867 } else if (i
== 1) {
1868 /* search in file's dir if "header.h" */
1871 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1872 path
= file
->true_filename
;
1873 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1876 /* search in all the include paths */
1877 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1878 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1879 pstrcpy(buf1
, sizeof(buf1
), path
);
1880 pstrcat(buf1
, sizeof(buf1
), "/");
1883 pstrcat(buf1
, sizeof(buf1
), buf
);
1884 e
= search_cached_include(s1
, buf1
, 0);
1885 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
== pp_once
)) {
1886 /* no need to parse the include because the 'ifndef macro'
1887 is defined (or had #pragma once) */
1889 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1894 if (tcc_open(s1
, buf1
) < 0)
1896 /* push previous file on stack */
1897 *s1
->include_stack_ptr
++ = file
->prev
;
1898 file
->include_next_index
= i
;
1900 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1902 /* update target deps */
1904 BufferedFile
*bf
= file
;
1905 while (i
== 1 && (bf
= bf
->prev
))
1906 i
= bf
->include_next_index
;
1907 /* skip system include files */
1908 if (n
- i
> s1
->nb_sysinclude_paths
)
1909 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1912 /* add include file debug info */
1913 tcc_debug_bincl(tcc_state
);
1914 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1915 ch
= file
->buf_ptr
[0];
1918 tcc_error("include file '%s' not found", buf
);
1925 c
= expr_preprocess();
1931 if (tok
< TOK_IDENT
)
1932 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1936 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1938 file
->ifndef_macro
= tok
;
1941 c
= (define_find(tok
) != 0) ^ c
;
1943 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1944 tcc_error("memory full (ifdef)");
1945 *s1
->ifdef_stack_ptr
++ = c
;
1948 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1949 tcc_error("#else without matching #if");
1950 if (s1
->ifdef_stack_ptr
[-1] & 2)
1951 tcc_error("#else after #else");
1952 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1955 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1956 tcc_error("#elif without matching #if");
1957 c
= s1
->ifdef_stack_ptr
[-1];
1959 tcc_error("#elif after #else");
1960 /* last #if/#elif expression was true: we skip */
1964 c
= expr_preprocess();
1965 s1
->ifdef_stack_ptr
[-1] = c
;
1968 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1969 file
->ifndef_macro
= 0;
1978 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1979 tcc_error("#endif without matching #if");
1980 s1
->ifdef_stack_ptr
--;
1981 /* '#ifndef macro' was at the start of file. Now we check if
1982 an '#endif' is exactly at the end of file */
1983 if (file
->ifndef_macro
&&
1984 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1985 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1986 /* need to set to zero to avoid false matches if another
1987 #ifndef at middle of file */
1988 file
->ifndef_macro
= 0;
1989 while (tok
!= TOK_LINEFEED
)
1991 tok_flags
|= TOK_FLAG_ENDIF
;
1996 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
2000 if (tok
!= TOK_CINT
)
2002 tcc_error("wrong #line format");
2006 if (tok
!= TOK_LINEFEED
) {
2007 if (tok
== TOK_STR
) {
2008 if (file
->true_filename
== file
->filename
)
2009 file
->true_filename
= tcc_strdup(file
->filename
);
2010 /* prepend directory from real file */
2011 pstrcpy(buf
, sizeof buf
, file
->true_filename
);
2012 *tcc_basename(buf
) = 0;
2013 pstrcat(buf
, sizeof buf
, (char *)tokc
.str
.data
);
2014 tcc_debug_putfile(s1
, buf
);
2015 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2022 total_lines
+= file
->line_num
- n
;
2028 ch
= file
->buf_ptr
[0];
2031 while (ch
!= '\n' && ch
!= CH_EOF
) {
2032 if ((q
- buf
) < sizeof(buf
) - 1)
2035 if (handle_stray_noerror() == 0)
2042 tcc_error("#error %s", buf
);
2044 tcc_warning("#warning %s", buf
);
2052 /* ignore gas line comment in an 'S' file. */
2053 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
2055 if (tok
== '!' && is_bof
)
2056 /* '!' is ignored at beginning to allow C scripts. */
2058 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2060 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
2063 /* ignore other preprocess commands or #! for C scripts */
2064 while (tok
!= TOK_LINEFEED
)
2067 parse_flags
= saved_parse_flags
;
2070 /* evaluate escape codes in a string. */
2071 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2086 case '0': case '1': case '2': case '3':
2087 case '4': case '5': case '6': case '7':
2088 /* at most three octal digits */
2093 n
= n
* 8 + c
- '0';
2097 n
= n
* 8 + c
- '0';
2102 goto add_char_nonext
;
2110 if (c
>= 'a' && c
<= 'f')
2112 else if (c
>= 'A' && c
<= 'F')
2122 goto add_char_nonext
;
2146 goto invalid_escape
;
2156 if (c
>= '!' && c
<= '~')
2157 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2159 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2162 } else if (is_long
&& c
>= 0x80) {
2163 /* assume we are processing UTF-8 sequence */
2164 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2166 int cont
; /* count of continuation bytes */
2167 int skip
; /* how many bytes should skip when error occurred */
2170 /* decode leading byte */
2172 skip
= 1; goto invalid_utf8_sequence
;
2173 } else if (c
<= 0xDF) {
2174 cont
= 1; n
= c
& 0x1f;
2175 } else if (c
<= 0xEF) {
2176 cont
= 2; n
= c
& 0xf;
2177 } else if (c
<= 0xF4) {
2178 cont
= 3; n
= c
& 0x7;
2180 skip
= 1; goto invalid_utf8_sequence
;
2183 /* decode continuation bytes */
2184 for (i
= 1; i
<= cont
; i
++) {
2185 int l
= 0x80, h
= 0xBF;
2187 /* adjust limit for second byte */
2190 case 0xE0: l
= 0xA0; break;
2191 case 0xED: h
= 0x9F; break;
2192 case 0xF0: l
= 0x90; break;
2193 case 0xF4: h
= 0x8F; break;
2197 if (p
[i
] < l
|| p
[i
] > h
) {
2198 skip
= i
; goto invalid_utf8_sequence
;
2201 n
= (n
<< 6) | (p
[i
] & 0x3f);
2204 /* advance pointer */
2207 goto add_char_nonext
;
2209 /* error handling */
2210 invalid_utf8_sequence
:
2211 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c
);
2214 goto add_char_nonext
;
2220 cstr_ccat(outstr
, c
);
2222 #ifdef TCC_TARGET_PE
2223 /* store as UTF-16 */
2225 cstr_wccat(outstr
, c
);
2228 cstr_wccat(outstr
, (c
>> 10) + 0xD800);
2229 cstr_wccat(outstr
, (c
& 0x3FF) + 0xDC00);
2232 cstr_wccat(outstr
, c
);
2236 /* add a trailing '\0' */
2238 cstr_ccat(outstr
, '\0');
2240 cstr_wccat(outstr
, '\0');
2243 static void parse_string(const char *s
, int len
)
2245 uint8_t buf
[1000], *p
= buf
;
2248 if ((is_long
= *s
== 'L'))
2252 if (len
>= sizeof buf
)
2253 p
= tcc_malloc(len
+ 1);
2257 cstr_reset(&tokcstr
);
2258 parse_escape_string(&tokcstr
, p
, is_long
);
2263 int char_size
, i
, n
, c
;
2264 /* XXX: make it portable */
2266 tok
= TOK_CCHAR
, char_size
= 1;
2268 tok
= TOK_LCHAR
, char_size
= sizeof(nwchar_t
);
2269 n
= tokcstr
.size
/ char_size
- 1;
2271 tcc_error("empty character constant");
2273 tcc_warning("multi-character character constant");
2274 for (c
= i
= 0; i
< n
; ++i
) {
2276 c
= ((nwchar_t
*)tokcstr
.data
)[i
];
2278 c
= (c
<< 8) | ((char *)tokcstr
.data
)[i
];
2282 tokc
.str
.size
= tokcstr
.size
;
2283 tokc
.str
.data
= tokcstr
.data
;
2291 /* we use 64 bit numbers */
2294 /* bn = (bn << shift) | or_val */
2295 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2299 for(i
=0;i
<BN_SIZE
;i
++) {
2301 bn
[i
] = (v
<< shift
) | or_val
;
2302 or_val
= v
>> (32 - shift
);
2306 static void bn_zero(unsigned int *bn
)
2309 for(i
=0;i
<BN_SIZE
;i
++) {
2314 /* parse number in null terminated string 'p' and return it in the
2316 static void parse_number(const char *p
)
2318 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2320 unsigned int bn
[BN_SIZE
];
2331 goto float_frac_parse
;
2332 } else if (t
== '0') {
2333 if (ch
== 'x' || ch
== 'X') {
2337 } else if (tcc_state
->tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2343 /* parse all digits. cannot check octal numbers at this stage
2344 because of floating point constants */
2346 if (ch
>= 'a' && ch
<= 'f')
2348 else if (ch
>= 'A' && ch
<= 'F')
2356 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2358 tcc_error("number too long");
2364 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2365 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2367 /* NOTE: strtox should support that for hexa numbers, but
2368 non ISOC99 libcs do not support it, so we prefer to do
2370 /* hexadecimal or binary floats */
2371 /* XXX: handle overflows */
2383 } else if (t
>= 'a') {
2385 } else if (t
>= 'A') {
2390 bn_lshift(bn
, shift
, t
);
2397 if (t
>= 'a' && t
<= 'f') {
2399 } else if (t
>= 'A' && t
<= 'F') {
2401 } else if (t
>= '0' && t
<= '9') {
2407 tcc_error("invalid digit");
2408 bn_lshift(bn
, shift
, t
);
2413 if (ch
!= 'p' && ch
!= 'P')
2420 } else if (ch
== '-') {
2424 if (ch
< '0' || ch
> '9')
2425 expect("exponent digits");
2426 while (ch
>= '0' && ch
<= '9') {
2427 exp_val
= exp_val
* 10 + ch
- '0';
2430 exp_val
= exp_val
* s
;
2432 /* now we can generate the number */
2433 /* XXX: should patch directly float number */
2434 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2435 d
= ldexp(d
, exp_val
- frac_bits
);
2440 /* float : should handle overflow */
2442 } else if (t
== 'L') {
2444 #ifdef TCC_TARGET_PE
2449 /* XXX: not large enough */
2450 tokc
.ld
= (long double)d
;
2457 /* decimal floats */
2459 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2464 while (ch
>= '0' && ch
<= '9') {
2465 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2471 if (ch
== 'e' || ch
== 'E') {
2472 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2476 if (ch
== '-' || ch
== '+') {
2477 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2482 if (ch
< '0' || ch
> '9')
2483 expect("exponent digits");
2484 while (ch
>= '0' && ch
<= '9') {
2485 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2497 tokc
.f
= strtof(token_buf
, NULL
);
2498 } else if (t
== 'L') {
2500 #ifdef TCC_TARGET_PE
2502 tokc
.d
= strtod(token_buf
, NULL
);
2505 tokc
.ld
= strtold(token_buf
, NULL
);
2509 tokc
.d
= strtod(token_buf
, NULL
);
2513 unsigned long long n
, n1
;
2514 int lcount
, ucount
, ov
= 0;
2517 /* integer number */
2520 if (b
== 10 && *q
== '0') {
2527 /* no need for checks except for base 10 / 8 errors */
2537 tcc_error("invalid digit");
2540 /* detect overflow */
2541 if (n1
>= 0x1000000000000000ULL
&& n
/ b
!= n1
)
2545 /* Determine the characteristics (unsigned and/or 64bit) the type of
2546 the constant must have according to the constant suffix(es) */
2547 lcount
= ucount
= 0;
2553 tcc_error("three 'l's in integer constant");
2554 if (lcount
&& *(p
- 1) != ch
)
2555 tcc_error("incorrect integer suffix: %s", p1
);
2558 } else if (t
== 'U') {
2560 tcc_error("two 'u's in integer constant");
2568 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2569 if (ucount
== 0 && b
== 10) {
2570 if (lcount
<= (LONG_SIZE
== 4)) {
2571 if (n
>= 0x80000000U
)
2572 lcount
= (LONG_SIZE
== 4) + 1;
2574 if (n
>= 0x8000000000000000ULL
)
2577 if (lcount
<= (LONG_SIZE
== 4)) {
2578 if (n
>= 0x100000000ULL
)
2579 lcount
= (LONG_SIZE
== 4) + 1;
2580 else if (n
>= 0x80000000U
)
2583 if (n
>= 0x8000000000000000ULL
)
2588 tcc_warning("integer constant overflow");
2597 ++tok
; /* TOK_CU... */
2601 tcc_error("invalid number");
2605 #define PARSE2(c1, tok1, c2, tok2) \
2616 /* return next token without macro substitution */
2617 static inline void next_nomacro1(void)
2619 int t
, c
, is_long
, len
;
2633 if (parse_flags
& PARSE_FLAG_SPACES
)
2634 goto keep_tok_flags
;
2635 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2644 /* first look if it is in fact an end of buffer */
2645 c
= handle_stray1(p
);
2652 TCCState
*s1
= tcc_state
;
2653 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2654 && !(tok_flags
& TOK_FLAG_EOF
)) {
2655 tok_flags
|= TOK_FLAG_EOF
;
2657 goto keep_tok_flags
;
2658 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2660 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2661 tcc_error("missing #endif");
2662 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2663 /* no include left : end of file. */
2666 tok_flags
&= ~TOK_FLAG_EOF
;
2667 /* pop include file */
2669 /* test if previous '#endif' was after a #ifdef at
2671 if (tok_flags
& TOK_FLAG_ENDIF
) {
2673 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2675 search_cached_include(s1
, file
->filename
, 1)
2676 ->ifndef_macro
= file
->ifndef_macro_saved
;
2677 tok_flags
&= ~TOK_FLAG_ENDIF
;
2680 /* add end of include file debug info */
2681 tcc_debug_eincl(tcc_state
);
2682 /* pop include stack */
2684 s1
->include_stack_ptr
--;
2686 if (p
== file
->buffer
)
2687 tok_flags
= TOK_FLAG_BOF
|TOK_FLAG_BOL
;
2695 tok_flags
|= TOK_FLAG_BOL
;
2698 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2701 goto keep_tok_flags
;
2706 if ((tok_flags
& TOK_FLAG_BOL
) &&
2707 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2709 preprocess(tok_flags
& TOK_FLAG_BOF
);
2715 tok
= TOK_TWOSHARPS
;
2717 #if !defined(TCC_TARGET_ARM)
2718 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2719 p
= parse_line_comment(p
- 1);
2730 /* dollar is allowed to start identifiers when not parsing asm */
2732 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2733 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2736 case 'a': case 'b': case 'c': case 'd':
2737 case 'e': case 'f': case 'g': case 'h':
2738 case 'i': case 'j': case 'k': case 'l':
2739 case 'm': case 'n': case 'o': case 'p':
2740 case 'q': case 'r': case 's': case 't':
2741 case 'u': case 'v': case 'w': case 'x':
2743 case 'A': case 'B': case 'C': case 'D':
2744 case 'E': case 'F': case 'G': case 'H':
2745 case 'I': case 'J': case 'K':
2746 case 'M': case 'N': case 'O': case 'P':
2747 case 'Q': case 'R': case 'S': case 'T':
2748 case 'U': case 'V': case 'W': case 'X':
2754 h
= TOK_HASH_FUNC(h
, c
);
2755 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2756 h
= TOK_HASH_FUNC(h
, c
);
2761 /* fast case : no stray found, so we have the full token
2762 and we have already hashed it */
2763 h
&= (TOK_HASH_SIZE
- 1);
2764 pts
= &hash_ident
[h
];
2769 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2771 pts
= &(ts
->hash_next
);
2773 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2777 cstr_reset(&tokcstr
);
2778 cstr_cat(&tokcstr
, (char *) p1
, len
);
2782 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2784 cstr_ccat(&tokcstr
, c
);
2787 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2793 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2795 goto parse_ident_fast
;
2798 if (c
== '\'' || c
== '\"') {
2802 cstr_reset(&tokcstr
);
2803 cstr_ccat(&tokcstr
, 'L');
2804 goto parse_ident_slow
;
2809 case '0': case '1': case '2': case '3':
2810 case '4': case '5': case '6': case '7':
2814 /* after the first digit, accept digits, alpha, '.' or sign if
2815 prefixed by 'eEpP' */
2817 cstr_reset(&tokcstr
);
2819 cstr_ccat(&tokcstr
, t
);
2820 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2822 || ((c
== '+' || c
== '-')
2823 && (((t
== 'e' || t
== 'E')
2824 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2825 /* 0xe+1 is 3 tokens in asm */
2826 && ((char*)tokcstr
.data
)[0] == '0'
2827 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2828 || t
== 'p' || t
== 'P'))))
2833 /* We add a trailing '\0' to ease parsing */
2834 cstr_ccat(&tokcstr
, '\0');
2835 tokc
.str
.size
= tokcstr
.size
;
2836 tokc
.str
.data
= tokcstr
.data
;
2841 /* special dot handling because it can also start a number */
2846 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2847 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2849 goto parse_ident_fast
;
2850 } else if (c
== '.') {
2856 *--p
= '.'; /* may underflow into file->unget[] */
2867 cstr_reset(&tokcstr
);
2869 cstr_ccat(&tokcstr
, 'L');
2870 cstr_ccat(&tokcstr
, c
);
2871 p
= parse_pp_string(p
, c
, &tokcstr
);
2872 cstr_ccat(&tokcstr
, c
);
2873 cstr_ccat(&tokcstr
, '\0');
2874 tokc
.str
.size
= tokcstr
.size
;
2875 tokc
.str
.data
= tokcstr
.data
;
2884 } else if (c
== '<') {
2901 } else if (c
== '>') {
2919 } else if (c
== '=') {
2932 } else if (c
== '=') {
2945 } else if (c
== '=') {
2958 } else if (c
== '=') {
2961 } else if (c
== '>') {
2969 PARSE2('!', '!', '=', TOK_NE
)
2970 PARSE2('=', '=', '=', TOK_EQ
)
2971 PARSE2('*', '*', '=', TOK_A_MUL
)
2972 PARSE2('%', '%', '=', TOK_A_MOD
)
2973 PARSE2('^', '^', '=', TOK_A_XOR
)
2975 /* comments or operator */
2979 p
= parse_comment(p
);
2980 /* comments replaced by a blank */
2983 } else if (c
== '/') {
2984 p
= parse_line_comment(p
);
2987 } else if (c
== '=') {
3007 case '@': /* only used in assembler */
3013 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
3014 goto parse_ident_fast
;
3015 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
3017 tcc_error("unrecognized character \\x%02x", c
);
3023 #if defined(PARSE_DEBUG)
3024 printf("token = %d %s\n", tok
, get_tok_str(tok
, &tokc
));
3028 static void macro_subst(
3029 TokenString
*tok_str
,
3031 const int *macro_str
3034 /* substitute arguments in replacement lists in macro_str by the values in
3035 args (field d) and return allocated string */
3036 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
3048 TOK_GET(&t
, ¯o_str
, &cval
);
3053 TOK_GET(&t
, ¯o_str
, &cval
);
3056 s
= sym_find2(args
, t
);
3059 cstr_ccat(&cstr
, '\"');
3063 TOK_GET(&t
, &st
, &cval
);
3064 if (t
!= TOK_PLCHLDR
3066 && 0 == check_space(t
, &spc
)) {
3067 const char *s
= get_tok_str(t
, &cval
);
3069 if (t
== TOK_PPSTR
&& *s
!= '\'')
3070 add_char(&cstr
, *s
);
3072 cstr_ccat(&cstr
, *s
);
3078 cstr_ccat(&cstr
, '\"');
3079 cstr_ccat(&cstr
, '\0');
3081 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
3084 cval
.str
.size
= cstr
.size
;
3085 cval
.str
.data
= cstr
.data
;
3086 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
3090 expect("macro parameter after '#'");
3092 } else if (t
>= TOK_IDENT
) {
3093 s
= sym_find2(args
, t
);
3097 /* if '##' is present before or after, no arg substitution */
3098 if (*macro_str
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
3099 /* special case for var arg macros : ## eats the ','
3100 if empty VA_ARGS variable. */
3101 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
3103 /* suppress ',' '##' */
3106 /* suppress '##' and add variable */
3114 /* Expand arguments tokens and store them. In most
3115 cases we could also re-expand each argument if
3116 used multiple times, but not if the argument
3117 contains the __COUNTER__ macro. */
3119 sym_push2(&s
->next
, s
->v
, s
->type
.t
, 0);
3121 macro_subst(&str2
, nested_list
, st
);
3122 tok_str_add(&str2
, 0);
3123 s
->next
->d
= str2
.str
;
3129 TOK_GET(&t2
, &st
, &cval
);
3132 tok_str_add2(&str
, t2
, &cval
);
3134 if (str
.len
== l0
) /* expanded to empty string */
3135 tok_str_add(&str
, TOK_PLCHLDR
);
3137 tok_str_add(&str
, t
);
3140 tok_str_add2(&str
, t
, &cval
);
3144 tok_str_add(&str
, 0);
3148 static char const ab_month_name
[12][4] =
3150 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3151 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3154 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3160 if (t1
!= TOK_PLCHLDR
)
3161 cstr_cat(&cstr
, get_tok_str(t1
, v1
), -1);
3163 if (t2
!= TOK_PLCHLDR
)
3164 cstr_cat(&cstr
, get_tok_str(t2
, v2
), -1);
3165 cstr_ccat(&cstr
, '\0');
3167 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3168 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3172 if (0 == *file
->buf_ptr
)
3176 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3177 " preprocessing token", n
, (char *)cstr
.data
, (char*)cstr
.data
+ n
);
3182 //printf("paste <%s>\n", (char*)cstr.data);
3187 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3188 return the resulting string (which must be freed). */
3189 static inline int *macro_twosharps(const int *ptr0
)
3193 TokenString macro_str1
;
3194 int start_of_nosubsts
= -1;
3197 /* we search the first '##' */
3198 for (ptr
= ptr0
;;) {
3199 TOK_GET(&t
, &ptr
, &cval
);
3200 if (t
== TOK_PPJOIN
)
3206 tok_str_new(¯o_str1
);
3208 //tok_print(" $$$", ptr0);
3209 for (ptr
= ptr0
;;) {
3210 TOK_GET(&t
, &ptr
, &cval
);
3213 if (t
== TOK_PPJOIN
)
3215 while (*ptr
== TOK_PPJOIN
) {
3217 /* given 'a##b', remove nosubsts preceding 'a' */
3218 if (start_of_nosubsts
>= 0)
3219 macro_str1
.len
= start_of_nosubsts
;
3220 /* given 'a##b', remove nosubsts preceding 'b' */
3221 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3223 if (t1
&& t1
!= TOK_PPJOIN
) {
3224 TOK_GET(&t1
, &ptr
, &cv1
);
3225 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3226 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3227 t
= tok
, cval
= tokc
;
3229 tok_str_add2(¯o_str1
, t
, &cval
);
3235 if (t
== TOK_NOSUBST
) {
3236 if (start_of_nosubsts
< 0)
3237 start_of_nosubsts
= macro_str1
.len
;
3239 start_of_nosubsts
= -1;
3241 tok_str_add2(¯o_str1
, t
, &cval
);
3243 tok_str_add(¯o_str1
, 0);
3244 //tok_print(" ###", macro_str1.str);
3245 return macro_str1
.str
;
3248 /* peek or read [ws_str == NULL] next token from function macro call,
3249 walking up macro levels up to the file if necessary */
3250 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3258 p
= macro_ptr
, t
= *p
;
3260 while (is_space(t
) || TOK_LINEFEED
== t
|| TOK_PLCHLDR
== t
)
3261 tok_str_add(ws_str
, t
), t
= *++p
;
3265 /* also, end of scope for nested defined symbol */
3267 while (sa
&& sa
->v
== 0)
3276 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3279 uint8_t *p
= file
->buf_ptr
;
3282 p
= parse_comment(p
);
3283 file
->buf_ptr
= p
- 1;
3284 } else if (c
== '/') {
3285 p
= parse_line_comment(p
);
3286 file
->buf_ptr
= p
- 1;
3293 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3294 tok_str_add(ws_str
, ch
);
3308 /* do macro substitution of current token with macro 's' and add
3309 result to (tok_str,tok_len). 'nested_list' is the list of all
3310 macros we got inside to avoid recursing. Return non zero if no
3311 substitution needs to be done */
3312 static int macro_subst_tok(
3313 TokenString
*tok_str
,
3317 Sym
*args
, *sa
, *sa1
;
3318 int parlevel
, t
, t1
, spc
;
3325 /* if symbol is a macro, prepare substitution */
3326 /* special macros */
3327 if (tok
== TOK___LINE__
|| tok
== TOK___COUNTER__
) {
3328 t
= tok
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3329 snprintf(buf
, sizeof(buf
), "%d", t
);
3333 } else if (tok
== TOK___FILE__
) {
3334 cstrval
= file
->filename
;
3336 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3341 tm
= localtime(&ti
);
3342 if (tok
== TOK___DATE__
) {
3343 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3344 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3346 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3347 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3354 cstr_cat(&cstr
, cstrval
, 0);
3355 cval
.str
.size
= cstr
.size
;
3356 cval
.str
.data
= cstr
.data
;
3357 tok_str_add2(tok_str
, t1
, &cval
);
3360 int saved_parse_flags
= parse_flags
;
3361 int *joined_str
= NULL
;
3364 if (s
->type
.t
== MACRO_FUNC
) {
3365 /* whitespace between macro name and argument list */
3367 tok_str_new(&ws_str
);
3370 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3371 | PARSE_FLAG_ACCEPT_STRAYS
;
3373 /* get next token from argument stream */
3374 t
= next_argstream(nested_list
, &ws_str
);
3376 /* not a macro substitution after all, restore the
3377 * macro token plus all whitespace we've read.
3378 * whitespace is intentionally not merged to preserve
3380 parse_flags
= saved_parse_flags
;
3381 tok_str_add(tok_str
, tok
);
3382 if (parse_flags
& PARSE_FLAG_SPACES
) {
3384 for (i
= 0; i
< ws_str
.len
; i
++)
3385 tok_str_add(tok_str
, ws_str
.str
[i
]);
3387 tok_str_free_str(ws_str
.str
);
3390 tok_str_free_str(ws_str
.str
);
3393 next_nomacro(); /* eat '(' */
3394 } while (tok
== TOK_PLCHLDR
|| is_space(tok
));
3396 /* argument macro */
3399 /* NOTE: empty args are allowed, except if no args */
3402 next_argstream(nested_list
, NULL
);
3403 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3405 /* handle '()' case */
3406 if (!args
&& !sa
&& tok
== ')')
3409 tcc_error("macro '%s' used with too many args",
3410 get_tok_str(s
->v
, 0));
3413 /* NOTE: non zero sa->t indicates VA_ARGS */
3414 while ((parlevel
> 0 ||
3416 (tok
!= ',' || sa
->type
.t
)))) {
3417 if (tok
== TOK_EOF
|| tok
== 0)
3421 else if (tok
== ')')
3423 if (tok
== TOK_LINEFEED
)
3425 if (!check_space(tok
, &spc
))
3426 tok_str_add2(&str
, tok
, &tokc
);
3427 next_argstream(nested_list
, NULL
);
3432 tok_str_add(&str
, -1);
3433 tok_str_add(&str
, 0);
3434 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3438 /* special case for gcc var args: add an empty
3439 var arg argument if it is omitted */
3440 if (sa
&& sa
->type
.t
&& gnu_ext
)
3448 tcc_error("macro '%s' used with too few args",
3449 get_tok_str(s
->v
, 0));
3452 /* now subst each arg */
3453 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3458 tok_str_free_str(sa
->d
);
3460 tok_str_free_str(sa
->next
->d
);
3466 parse_flags
= saved_parse_flags
;
3469 sym_push2(nested_list
, s
->v
, 0, 0);
3470 parse_flags
= saved_parse_flags
;
3471 joined_str
= macro_twosharps(mstr
);
3472 macro_subst(tok_str
, nested_list
, joined_str
? joined_str
: mstr
);
3474 /* pop nested defined symbol */
3476 *nested_list
= sa1
->prev
;
3479 tok_str_free_str(joined_str
);
3481 tok_str_free_str(mstr
);
3486 /* do macro substitution of macro_str and add result to
3487 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3488 inside to avoid recursing. */
3489 static void macro_subst(
3490 TokenString
*tok_str
,
3492 const int *macro_str
3496 int t
, spc
, nosubst
;
3502 TOK_GET(&t
, ¯o_str
, &cval
);
3506 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3511 /* if nested substitution, do nothing */
3512 if (sym_find2(*nested_list
, t
)) {
3513 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3514 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3519 TokenString
*str
= tok_str_alloc();
3520 str
->str
= (int*)macro_str
;
3521 begin_macro(str
, 2);
3524 macro_subst_tok(tok_str
, nested_list
, s
);
3526 if (macro_stack
!= str
) {
3527 /* already finished by reading function macro arguments */
3531 macro_str
= macro_ptr
;
3535 spc
= is_space(t
= tok_str
->str
[tok_str
->lastlen
]);
3538 if (!check_space(t
, &spc
))
3539 tok_str_add2(tok_str
, t
, &cval
);
3542 if (nosubst
> 1 && (spc
|| (++nosubst
== 3 && t
== '(')))
3546 if (t
== TOK_NOSUBST
)
3549 /* GCC supports 'defined' as result of a macro substitution */
3550 if (t
== TOK_DEFINED
&& pp_expr
)
3555 /* return next token without macro substitution. Can read input from
3557 static void next_nomacro(void)
3563 if (TOK_HAS_VALUE(t
)) {
3564 tok_get(&tok
, ¯o_ptr
, &tokc
);
3565 if (t
== TOK_LINENUM
) {
3566 file
->line_num
= tokc
.i
;
3571 if (t
< TOK_IDENT
) {
3572 if (!(parse_flags
& PARSE_FLAG_SPACES
)
3573 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
))
3583 /* return next token with macro substitution */
3584 ST_FUNC
void next(void)
3591 if (!TOK_HAS_VALUE(t
)) {
3592 if (t
== TOK_NOSUBST
|| t
== TOK_PLCHLDR
) {
3593 /* discard preprocessor markers */
3595 } else if (t
== 0) {
3596 /* end of macro or unget token string */
3599 } else if (t
== '\\') {
3600 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3601 tcc_error("stray '\\' in program");
3605 } else if (t
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3606 /* if reading from file, try to substitute macros */
3607 Sym
*s
= define_find(t
);
3609 Sym
*nested_list
= NULL
;
3611 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3612 tok_str_add(&tokstr_buf
, 0);
3613 begin_macro(&tokstr_buf
, 0);
3618 /* convert preprocessor tokens into C tokens */
3619 if (t
== TOK_PPNUM
) {
3620 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3621 parse_number((char *)tokc
.str
.data
);
3622 } else if (t
== TOK_PPSTR
) {
3623 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3624 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3628 /* push back current token and set current token to 'last_tok'. Only
3629 identifier case handled for labels. */
3630 ST_INLN
void unget_tok(int last_tok
)
3633 TokenString
*str
= tok_str_alloc();
3634 tok_str_add2(str
, tok
, &tokc
);
3635 tok_str_add(str
, 0);
3636 begin_macro(str
, 1);
3640 /* ------------------------------------------------------------------------- */
3641 /* init preprocessor */
3643 static const char *target_os_defs
=
3644 #ifdef TCC_TARGET_PE
3650 # if defined TCC_TARGET_MACHO
3652 # elif TARGETOS_FreeBSD
3654 # elif TARGETOS_FreeBSD_kernel
3655 "__FreeBSD_kernel__\0"
3656 # elif TARGETOS_NetBSD
3658 # elif TARGETOS_OpenBSD
3669 static void putdef(CString
*cs
, const char *p
)
3671 cstr_printf(cs
, "#define %s%s\n", p
, &" 1"[!!strchr(p
, ' ')*2]);
3674 static void tcc_predefs(TCCState
*s1
, CString
*cs
, int is_asm
)
3677 const char *defs
[] = { target_machine_defs
, target_os_defs
, NULL
};
3680 sscanf(TCC_VERSION
, "%d.%d.%d", &a
, &b
, &c
);
3681 cstr_printf(cs
, "#define __TINYC__ %d\n", a
*10000 + b
*100 + c
);
3682 for (a
= 0; defs
[a
]; ++a
)
3683 for (p
= defs
[a
]; *p
; p
= strchr(p
, 0) + 1)
3685 #ifdef TCC_TARGET_ARM
3686 if (s1
->float_abi
== ARM_HARD_FLOAT
)
3687 putdef(cs
, "__ARM_PCS_VFP");
3690 putdef(cs
, "__ASSEMBLER__");
3691 if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
)
3692 putdef(cs
, "__TCC_PP__");
3693 if (s1
->output_type
== TCC_OUTPUT_MEMORY
)
3694 putdef(cs
, "__TCC_RUN__");
3695 if (s1
->char_is_unsigned
)
3696 putdef(cs
, "__CHAR_UNSIGNED__");
3697 if (s1
->optimize
> 0)
3698 putdef(cs
, "__OPTIMIZE__");
3699 if (s1
->option_pthread
)
3700 putdef(cs
, "_REENTRANT");
3701 if (s1
->leading_underscore
)
3702 putdef(cs
, "__leading_underscore");
3703 #ifdef CONFIG_TCC_BCHECK
3704 if (s1
->do_bounds_check
)
3705 putdef(cs
, "__BOUNDS_CHECKING_ON");
3707 cstr_printf(cs
, "#define __SIZEOF_POINTER__ %d\n", PTR_SIZE
);
3708 cstr_printf(cs
, "#define __SIZEOF_LONG__ %d\n", LONG_SIZE
);
3710 putdef(cs
, "__STDC__");
3711 cstr_printf(cs
, "#define __STDC_VERSION__ %dL\n", s1
->cversion
);
3713 /* load more predefs and __builtins */
3714 #if CONFIG_TCC_PREDEFS
3715 #include "tccdefs_.h" /* include as strings */
3717 "#include <tccdefs.h>\n" /* load at runtime */
3721 cstr_printf(cs
, "#define __BASE_FILE__ \"%s\"\n", file
->filename
);
3724 ST_FUNC
void preprocess_start(TCCState
*s1
, int filetype
)
3726 int is_asm
= !!(filetype
& (AFF_TYPE_ASM
|AFF_TYPE_ASMPP
));
3731 s1
->include_stack_ptr
= s1
->include_stack
;
3732 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3733 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3736 pp_debug_tok
= pp_debug_symv
= 0;
3738 s1
->pack_stack
[0] = 0;
3739 s1
->pack_stack_ptr
= s1
->pack_stack
;
3741 set_idnum('$', !is_asm
&& s1
->dollars_in_identifiers
? IS_ID
: 0);
3742 set_idnum('.', is_asm
? IS_ID
: 0);
3744 if (!(filetype
& AFF_TYPE_ASM
)) {
3746 tcc_predefs(s1
, &cstr
, is_asm
);
3747 if (s1
->cmdline_defs
.size
)
3748 cstr_cat(&cstr
, s1
->cmdline_defs
.data
, s1
->cmdline_defs
.size
);
3749 if (s1
->cmdline_incl
.size
)
3750 cstr_cat(&cstr
, s1
->cmdline_incl
.data
, s1
->cmdline_incl
.size
);
3751 //printf("%s\n", (char*)cstr.data);
3752 *s1
->include_stack_ptr
++ = file
;
3753 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3754 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3758 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3759 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3762 /* cleanup from error/setjmp */
3763 ST_FUNC
void preprocess_end(TCCState
*s1
)
3773 ST_FUNC
void tccpp_new(TCCState
*s
)
3778 /* init isid table */
3779 for(i
= CH_EOF
; i
<128; i
++)
3781 is_space(i
) ? IS_SPC
3786 for(i
= 128; i
<256; i
++)
3787 set_idnum(i
, IS_ID
);
3789 /* init allocators */
3790 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3791 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3793 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3794 memset(s
->cached_includes_hash
, 0, sizeof s
->cached_includes_hash
);
3796 cstr_new(&cstr_buf
);
3797 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3798 tok_str_new(&tokstr_buf
);
3799 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3801 tok_ident
= TOK_IDENT
;
3810 tok_alloc(p
, r
- p
- 1);
3814 /* we add dummy defines for some special macros to speed up tests
3815 and to have working defined() */
3816 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
3817 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
3818 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
3819 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
3820 define_push(TOK___COUNTER__
, MACRO_OBJ
, NULL
, NULL
);
3823 ST_FUNC
void tccpp_delete(TCCState
*s
)
3827 dynarray_reset(&s
->cached_includes
, &s
->nb_cached_includes
);
3830 n
= tok_ident
- TOK_IDENT
;
3831 if (n
> total_idents
)
3833 for(i
= 0; i
< n
; i
++)
3834 tal_free(toksym_alloc
, table_ident
[i
]);
3835 tcc_free(table_ident
);
3838 /* free static buffers */
3839 cstr_free(&tokcstr
);
3840 cstr_free(&cstr_buf
);
3841 cstr_free(¯o_equal_buf
);
3842 tok_str_free_str(tokstr_buf
.str
);
3844 /* free allocators */
3845 tal_delete(toksym_alloc
);
3846 toksym_alloc
= NULL
;
3847 tal_delete(tokstr_alloc
);
3848 tokstr_alloc
= NULL
;
3851 /* ------------------------------------------------------------------------- */
3852 /* tcc -E [-P[1]] [-dD} support */
3854 static void tok_print(const char *msg
, const int *str
)
3860 fp
= tcc_state
->ppfp
;
3861 fprintf(fp
, "%s", msg
);
3863 TOK_GET(&t
, &str
, &cval
);
3866 fprintf(fp
, &" %s"[s
], get_tok_str(t
, &cval
)), s
= 1;
3871 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3873 int d
= f
->line_num
- f
->line_ref
;
3878 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3880 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3882 fputs("\n", s1
->ppfp
), --d
;
3883 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3884 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3886 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3887 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3889 f
->line_ref
= f
->line_num
;
3892 static void define_print(TCCState
*s1
, int v
)
3898 if (NULL
== s
|| NULL
== s
->d
)
3902 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3903 if (s
->type
.t
== MACRO_FUNC
) {
3908 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3915 tok_print("", s
->d
);
3918 static void pp_debug_defines(TCCState
*s1
)
3929 pp_line(s1
, file
, 0);
3930 file
->line_ref
= ++file
->line_num
;
3934 vs
= get_tok_str(v
, NULL
);
3935 if (t
== TOK_DEFINE
) {
3936 define_print(s1
, v
);
3937 } else if (t
== TOK_UNDEF
) {
3938 fprintf(fp
, "#undef %s\n", vs
);
3939 } else if (t
== TOK_push_macro
) {
3940 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3941 } else if (t
== TOK_pop_macro
) {
3942 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3947 static void pp_debug_builtins(TCCState
*s1
)
3950 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3951 define_print(s1
, v
);
3954 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3955 static int pp_need_space(int a
, int b
)
3957 return 'E' == a
? '+' == b
|| '-' == b
3958 : '+' == a
? TOK_INC
== b
|| '+' == b
3959 : '-' == a
? TOK_DEC
== b
|| '-' == b
3960 : a
>= TOK_IDENT
? b
>= TOK_IDENT
3961 : a
== TOK_PPNUM
? b
>= TOK_IDENT
3965 /* maybe hex like 0x1e */
3966 static int pp_check_he0xE(int t
, const char *p
)
3968 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3973 /* Preprocess the current file */
3974 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3976 BufferedFile
**iptr
;
3977 int token_seen
, spcs
, level
;
3981 parse_flags
= PARSE_FLAG_PREPROCESS
3982 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3983 | PARSE_FLAG_LINEFEED
3985 | PARSE_FLAG_ACCEPT_STRAYS
3987 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3988 capability to compile and run itself, provided all numbers are
3989 given as decimals. tcc -E -P10 will do. */
3990 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
3991 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
3994 /* for PP benchmarks */
3995 do next(); while (tok
!= TOK_EOF
);
3999 if (s1
->dflag
& 1) {
4000 pp_debug_builtins(s1
);
4004 token_seen
= TOK_LINEFEED
, spcs
= 0, level
= 0;
4006 pp_line(s1
, file
->prev
, level
++);
4007 pp_line(s1
, file
, level
);
4009 iptr
= s1
->include_stack_ptr
;
4014 level
= s1
->include_stack_ptr
- iptr
;
4017 pp_line(s1
, *iptr
, 0);
4018 pp_line(s1
, file
, level
);
4020 if (s1
->dflag
& 7) {
4021 pp_debug_defines(s1
);
4026 if (is_space(tok
)) {
4027 if (spcs
< sizeof white
- 1)
4028 white
[spcs
++] = tok
;
4030 } else if (tok
== TOK_LINEFEED
) {
4032 if (token_seen
== TOK_LINEFEED
)
4035 } else if (token_seen
== TOK_LINEFEED
) {
4036 pp_line(s1
, file
, 0);
4037 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
4038 white
[spcs
++] = ' ';
4041 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
4042 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
4043 token_seen
= pp_check_he0xE(tok
, p
);
4048 /* ------------------------------------------------------------------------- */