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
23 /********************************************************/
24 /* global variables */
26 ST_DATA
int tok_flags
;
27 ST_DATA
int parse_flags
;
29 ST_DATA
struct BufferedFile
*file
;
32 ST_DATA
const int *macro_ptr
;
33 ST_DATA CString tokcstr
; /* current parsed string, if any */
35 /* display benchmark infos */
36 ST_DATA
int total_lines
;
37 ST_DATA
int total_bytes
;
38 ST_DATA
int tok_ident
;
39 ST_DATA TokenSym
**table_ident
;
41 /* ------------------------------------------------------------------------- */
43 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
44 static char token_buf
[STRING_MAX_SIZE
+ 1];
45 static CString cstr_buf
;
46 static CString macro_equal_buf
;
47 static TokenString tokstr_buf
;
48 static unsigned char isidnum_table
[256 - CH_EOF
];
49 static int pp_debug_tok
, pp_debug_symv
;
52 static int pp_counter
;
53 static void tok_print(const char *msg
, const int *str
);
55 static struct TinyAlloc
*toksym_alloc
;
56 static struct TinyAlloc
*tokstr_alloc
;
57 static struct TinyAlloc
*cstr_alloc
;
59 static TokenString
*macro_stack
;
61 static const char tcc_keywords
[] =
62 #define DEF(id, str) str "\0"
67 /* WARNING: the content of this string encodes token numbers */
68 static const unsigned char tok_two_chars
[] =
70 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
71 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
92 '.','.', 0xa8, // C++ token ?
93 '#','#', TOK_TWOSHARPS
,
97 static void next_nomacro_spc(void);
99 ST_FUNC
void skip(int c
)
102 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
106 ST_FUNC
void expect(const char *msg
)
108 tcc_error("%s expected", msg
);
111 /* ------------------------------------------------------------------------- */
112 /* Custom allocator for tiny objects */
117 #define tal_free(al, p) tcc_free(p)
118 #define tal_realloc(al, p, size) tcc_realloc(p, size)
119 #define tal_new(a,b,c)
120 #define tal_delete(a)
122 #if !defined(MEM_DEBUG)
123 #define tal_free(al, p) tal_free_impl(al, p)
124 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
125 #define TAL_DEBUG_PARAMS
128 //#define TAL_INFO 1 /* collect and dump allocators stats */
129 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
130 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
131 #define TAL_DEBUG_PARAMS , const char *file, int line
132 #define TAL_DEBUG_FILE_LEN 40
135 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
136 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
137 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
138 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
139 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
140 #define CSTR_TAL_LIMIT 1024
142 typedef struct TinyAlloc
{
148 struct TinyAlloc
*next
, *top
;
157 typedef struct tal_header_t
{
160 int line_num
; /* negative line_num used for double free check */
161 char file_name
[TAL_DEBUG_FILE_LEN
+ 1];
165 /* ------------------------------------------------------------------------- */
167 static TinyAlloc
*tal_new(TinyAlloc
**pal
, unsigned limit
, unsigned size
)
169 TinyAlloc
*al
= tcc_mallocz(sizeof(TinyAlloc
));
170 al
->p
= al
->buffer
= tcc_malloc(size
);
177 static void tal_delete(TinyAlloc
*al
)
185 fprintf(stderr
, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
186 al
->limit
, al
->size
/ 1024.0 / 1024.0, al
->nb_peak
, al
->nb_total
, al
->nb_missed
,
187 (al
->peak_p
- al
->buffer
) * 100.0 / al
->size
);
190 if (al
->nb_allocs
> 0) {
192 fprintf(stderr
, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
193 al
->nb_allocs
, al
->limit
);
196 tal_header_t
*header
= (tal_header_t
*)p
;
197 if (header
->line_num
> 0) {
198 fprintf(stderr
, "%s:%d: chunk of %d bytes leaked\n",
199 header
->file_name
, header
->line_num
, header
->size
);
201 p
+= header
->size
+ sizeof(tal_header_t
);
209 tcc_free(al
->buffer
);
215 static void tal_free_impl(TinyAlloc
*al
, void *p TAL_DEBUG_PARAMS
)
220 if (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
) {
222 tal_header_t
*header
= (((tal_header_t
*)p
) - 1);
223 if (header
->line_num
< 0) {
224 fprintf(stderr
, "%s:%d: TAL_DEBUG: double frees chunk from\n",
226 fprintf(stderr
, "%s:%d: %d bytes\n",
227 header
->file_name
, (int)-header
->line_num
, (int)header
->size
);
229 header
->line_num
= -header
->line_num
;
234 } else if (al
->next
) {
242 static void *tal_realloc_impl(TinyAlloc
**pal
, void *p
, unsigned size TAL_DEBUG_PARAMS
)
244 tal_header_t
*header
;
247 unsigned adj_size
= (size
+ 3) & -4;
248 TinyAlloc
*al
= *pal
;
251 is_own
= (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
);
252 if ((!p
|| is_own
) && size
<= al
->limit
) {
253 if (al
->p
+ adj_size
+ sizeof(tal_header_t
) < al
->buffer
+ al
->size
) {
254 header
= (tal_header_t
*)al
->p
;
255 header
->size
= adj_size
;
257 { int ofs
= strlen(file
) - TAL_DEBUG_FILE_LEN
;
258 strncpy(header
->file_name
, file
+ (ofs
> 0 ? ofs
: 0), TAL_DEBUG_FILE_LEN
);
259 header
->file_name
[TAL_DEBUG_FILE_LEN
] = 0;
260 header
->line_num
= line
; }
262 ret
= al
->p
+ sizeof(tal_header_t
);
263 al
->p
+= adj_size
+ sizeof(tal_header_t
);
265 header
= (((tal_header_t
*)p
) - 1);
266 memcpy(ret
, p
, header
->size
);
268 header
->line_num
= -header
->line_num
;
274 if (al
->nb_peak
< al
->nb_allocs
)
275 al
->nb_peak
= al
->nb_allocs
;
276 if (al
->peak_p
< al
->p
)
283 ret
= tal_realloc(*pal
, 0, size
);
284 header
= (((tal_header_t
*)p
) - 1);
285 memcpy(ret
, p
, header
->size
);
287 header
->line_num
= -header
->line_num
;
294 TinyAlloc
*bottom
= al
, *next
= al
->top
? al
->top
: al
;
296 al
= tal_new(pal
, next
->limit
, next
->size
* 2);
304 ret
= tcc_malloc(size
);
305 header
= (((tal_header_t
*)p
) - 1);
306 memcpy(ret
, p
, header
->size
);
308 header
->line_num
= -header
->line_num
;
310 } else if (al
->next
) {
314 ret
= tcc_realloc(p
, size
);
323 /* ------------------------------------------------------------------------- */
324 /* CString handling */
325 static void cstr_realloc(CString
*cstr
, int new_size
)
329 size
= cstr
->size_allocated
;
331 size
= 8; /* no need to allocate a too small first string */
332 while (size
< new_size
)
334 cstr
->data
= tal_realloc(cstr_alloc
, cstr
->data
, size
);
335 cstr
->size_allocated
= size
;
339 ST_INLN
void cstr_ccat(CString
*cstr
, int ch
)
342 size
= cstr
->size
+ 1;
343 if (size
> cstr
->size_allocated
)
344 cstr_realloc(cstr
, size
);
345 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
349 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
, int len
)
353 len
= strlen(str
) + 1 + len
;
354 size
= cstr
->size
+ len
;
355 if (size
> cstr
->size_allocated
)
356 cstr_realloc(cstr
, size
);
357 memmove(((unsigned char *)cstr
->data
) + cstr
->size
, str
, len
);
361 /* add a wide char */
362 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
365 size
= cstr
->size
+ sizeof(nwchar_t
);
366 if (size
> cstr
->size_allocated
)
367 cstr_realloc(cstr
, size
);
368 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
372 ST_FUNC
void cstr_new(CString
*cstr
)
374 memset(cstr
, 0, sizeof(CString
));
377 /* free string and reset it to NULL */
378 ST_FUNC
void cstr_free(CString
*cstr
)
380 tal_free(cstr_alloc
, cstr
->data
);
384 /* reset string to empty */
385 ST_FUNC
void cstr_reset(CString
*cstr
)
391 static void add_char(CString
*cstr
, int c
)
393 if (c
== '\'' || c
== '\"' || c
== '\\') {
394 /* XXX: could be more precise if char or string */
395 cstr_ccat(cstr
, '\\');
397 if (c
>= 32 && c
<= 126) {
400 cstr_ccat(cstr
, '\\');
402 cstr_ccat(cstr
, 'n');
404 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
405 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
406 cstr_ccat(cstr
, '0' + (c
& 7));
411 /* ------------------------------------------------------------------------- */
412 /* allocate a new token */
413 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
415 TokenSym
*ts
, **ptable
;
418 if (tok_ident
>= SYM_FIRST_ANOM
)
419 tcc_error("memory full (symbols)");
421 /* expand token table if needed */
422 i
= tok_ident
- TOK_IDENT
;
423 if ((i
% TOK_ALLOC_INCR
) == 0) {
424 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
425 table_ident
= ptable
;
428 ts
= tal_realloc(toksym_alloc
, 0, sizeof(TokenSym
) + len
);
430 ts
->tok
= tok_ident
++;
431 ts
->sym_define
= NULL
;
432 ts
->sym_label
= NULL
;
433 ts
->sym_struct
= NULL
;
434 ts
->sym_identifier
= NULL
;
436 ts
->hash_next
= NULL
;
437 memcpy(ts
->str
, str
, len
);
443 #define TOK_HASH_INIT 1
444 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
447 /* find a token and add it if not found */
448 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
456 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
457 h
&= (TOK_HASH_SIZE
- 1);
459 pts
= &hash_ident
[h
];
464 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
466 pts
= &(ts
->hash_next
);
468 return tok_alloc_new(pts
, str
, len
);
471 /* XXX: buffer overflow */
472 /* XXX: float tokens */
473 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
478 cstr_reset(&cstr_buf
);
488 /* XXX: not quite exact, but only useful for testing */
490 sprintf(p
, "%u", (unsigned)cv
->i
);
492 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
496 cstr_ccat(&cstr_buf
, 'L');
498 cstr_ccat(&cstr_buf
, '\'');
499 add_char(&cstr_buf
, cv
->i
);
500 cstr_ccat(&cstr_buf
, '\'');
501 cstr_ccat(&cstr_buf
, '\0');
505 return (char*)cv
->str
.data
;
507 cstr_ccat(&cstr_buf
, 'L');
509 cstr_ccat(&cstr_buf
, '\"');
511 len
= cv
->str
.size
- 1;
513 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
515 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
517 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
519 cstr_ccat(&cstr_buf
, '\"');
520 cstr_ccat(&cstr_buf
, '\0');
524 cstr_cat(&cstr_buf
, "<float>", 0);
527 cstr_cat(&cstr_buf
, "<double>", 0);
530 cstr_cat(&cstr_buf
, "<long double>", 0);
533 cstr_cat(&cstr_buf
, "<linenumber>", 0);
536 /* above tokens have value, the ones below don't */
544 return strcpy(p
, "...");
546 return strcpy(p
, "<<=");
548 return strcpy(p
, ">>=");
550 return strcpy(p
, "<eof>");
553 /* search in two bytes table */
554 const unsigned char *q
= tok_two_chars
;
560 return cstr_buf
.data
;
565 sprintf(cstr_buf
.data
, "<%02x>", v
);
566 return cstr_buf
.data
;
571 } else if (v
< tok_ident
) {
572 return table_ident
[v
- TOK_IDENT
]->str
;
573 } else if (v
>= SYM_FIRST_ANOM
) {
574 /* special name for anonymous symbol */
575 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
577 /* should never happen */
582 return cstr_buf
.data
;
585 /* return the current character, handling end of block if necessary
587 ST_FUNC
int handle_eob(void)
589 BufferedFile
*bf
= file
;
592 /* only tries to read if really end of buffer */
593 if (bf
->buf_ptr
>= bf
->buf_end
) {
595 #if defined(PARSE_DEBUG)
600 len
= read(bf
->fd
, bf
->buffer
, len
);
607 bf
->buf_ptr
= bf
->buffer
;
608 bf
->buf_end
= bf
->buffer
+ len
;
609 *bf
->buf_end
= CH_EOB
;
611 if (bf
->buf_ptr
< bf
->buf_end
) {
612 return bf
->buf_ptr
[0];
614 bf
->buf_ptr
= bf
->buf_end
;
619 /* read next char from current input file and handle end of input buffer */
620 ST_INLN
void inp(void)
622 ch
= *(++(file
->buf_ptr
));
623 /* end of buffer/file handling */
628 /* handle '\[\r]\n' */
629 static int handle_stray_noerror(void)
636 } else if (ch
== '\r') {
650 static void handle_stray(void)
652 if (handle_stray_noerror())
653 tcc_error("stray '\\' in program");
656 /* skip the stray and handle the \\n case. Output an error if
657 incorrect char after the stray */
658 static int handle_stray1(uint8_t *p
)
663 if (p
>= file
->buf_end
) {
670 if (handle_stray_noerror()) {
671 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
672 tcc_error("stray '\\' in program");
673 *--file
->buf_ptr
= '\\';
680 /* handle just the EOB case, but not stray */
681 #define PEEKC_EOB(c, p)\
692 /* handle the complicated stray case */
698 c = handle_stray1(p);\
703 /* input with '\[\r]\n' handling. Note that this function cannot
704 handle other characters after '\', so you cannot call it inside
705 strings or comments */
706 ST_FUNC
void minp(void)
713 /* single line C++ comments */
714 static uint8_t *parse_line_comment(uint8_t *p
)
722 if (c
== '\n' || c
== CH_EOF
) {
724 } else if (c
== '\\') {
733 } else if (c
== '\r') {
751 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
760 if (c
== '\n' || c
== '*' || c
== '\\')
764 if (c
== '\n' || c
== '*' || c
== '\\')
768 /* now we can handle all the cases */
772 } else if (c
== '*') {
778 } else if (c
== '/') {
780 } else if (c
== '\\') {
785 tcc_error("unexpected end of file in comment");
787 /* skip '\[\r]\n', otherwise just skip the stray */
793 } else if (c
== '\r') {
810 /* stray, eob or eof */
815 tcc_error("unexpected end of file in comment");
816 } else if (c
== '\\') {
826 ST_FUNC
int set_idnum(int c
, int val
)
828 int prev
= isidnum_table
[c
- CH_EOF
];
829 isidnum_table
[c
- CH_EOF
] = val
;
835 static inline void skip_spaces(void)
837 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
841 static inline int check_space(int t
, int *spc
)
843 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
852 /* parse a string without interpreting escapes */
853 static uint8_t *parse_pp_string(uint8_t *p
,
854 int sep
, CString
*str
)
862 } else if (c
== '\\') {
868 /* XXX: indicate line number of start of string */
869 tcc_error("missing terminating %c character", sep
);
870 } else if (c
== '\\') {
871 /* escape : just skip \[\r]\n */
876 } else if (c
== '\r') {
879 expect("'\n' after '\r'");
882 } else if (c
== CH_EOF
) {
883 goto unterminated_string
;
886 cstr_ccat(str
, '\\');
892 } else if (c
== '\n') {
895 } else if (c
== '\r') {
899 cstr_ccat(str
, '\r');
915 /* skip block of text until #else, #elif or #endif. skip also pairs of
917 static void preprocess_skip(void)
919 int a
, start_of_line
, c
, in_warn_or_error
;
926 in_warn_or_error
= 0;
947 } else if (c
== '\\') {
948 ch
= file
->buf_ptr
[0];
949 handle_stray_noerror();
956 if (in_warn_or_error
)
958 p
= parse_pp_string(p
, c
, NULL
);
962 if (in_warn_or_error
)
969 p
= parse_comment(p
);
970 } else if (ch
== '/') {
971 p
= parse_line_comment(p
);
981 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
983 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
985 else if (tok
== TOK_ENDIF
)
987 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
988 in_warn_or_error
= 1;
989 else if (tok
== TOK_LINEFEED
)
991 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
992 p
= parse_line_comment(p
- 1);
993 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
994 p
= parse_line_comment(p
- 1);
1008 /* return the number of additional 'ints' necessary to store the
1010 static inline int tok_size(const int *p
)
1020 #ifndef TCC_LONG_ARE_64_BIT
1029 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
1033 #ifdef TCC_LONG_ARE_64_BIT
1039 return 1 + LDOUBLE_SIZE
/ 4;
1046 /* token string handling */
1047 ST_INLN
void tok_str_new(TokenString
*s
)
1050 s
->len
= s
->lastlen
= 0;
1051 s
->allocated_len
= 0;
1052 s
->last_line_num
= -1;
1055 ST_FUNC TokenString
*tok_str_alloc(void)
1057 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1062 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1066 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1067 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1071 ST_FUNC
void tok_str_free_str(int *str
)
1073 tal_free(tokstr_alloc
, str
);
1076 ST_FUNC
void tok_str_free(TokenString
*str
)
1078 tok_str_free_str(str
->str
);
1079 tal_free(tokstr_alloc
, str
);
1082 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1086 size
= s
->allocated_len
;
1089 while (size
< new_size
)
1091 if (size
> s
->allocated_len
) {
1092 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1093 s
->allocated_len
= size
;
1099 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1105 if (len
>= s
->allocated_len
)
1106 str
= tok_str_realloc(s
, len
+ 1);
1111 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1114 str
->prev
= macro_stack
;
1115 str
->prev_ptr
= macro_ptr
;
1116 str
->save_line_num
= file
->line_num
;
1117 macro_ptr
= str
->str
;
1121 ST_FUNC
void end_macro(void)
1123 TokenString
*str
= macro_stack
;
1124 macro_stack
= str
->prev
;
1125 macro_ptr
= str
->prev_ptr
;
1126 file
->line_num
= str
->save_line_num
;
1127 if (str
->alloc
== 2) {
1128 str
->alloc
= 3; /* just mark as finished */
1134 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1138 len
= s
->lastlen
= s
->len
;
1141 /* allocate space for worst case */
1142 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1143 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1152 #ifndef TCC_LONG_ARE_64_BIT
1156 str
[len
++] = cv
->tab
[0];
1163 /* Insert the string into the int array. */
1165 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1166 if (len
+ nb_words
>= s
->allocated_len
)
1167 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1168 str
[len
] = cv
->str
.size
;
1169 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1176 #ifdef TCC_LONG_ARE_64_BIT
1180 #if LDOUBLE_SIZE == 8
1183 str
[len
++] = cv
->tab
[0];
1184 str
[len
++] = cv
->tab
[1];
1186 #if LDOUBLE_SIZE == 12
1188 str
[len
++] = cv
->tab
[0];
1189 str
[len
++] = cv
->tab
[1];
1190 str
[len
++] = cv
->tab
[2];
1191 #elif LDOUBLE_SIZE == 16
1193 str
[len
++] = cv
->tab
[0];
1194 str
[len
++] = cv
->tab
[1];
1195 str
[len
++] = cv
->tab
[2];
1196 str
[len
++] = cv
->tab
[3];
1197 #elif LDOUBLE_SIZE != 8
1198 #error add long double size support
1207 /* add the current parse token in token string 's' */
1208 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1212 /* save line number info */
1213 if (file
->line_num
!= s
->last_line_num
) {
1214 s
->last_line_num
= file
->line_num
;
1215 cval
.i
= s
->last_line_num
;
1216 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1218 tok_str_add2(s
, tok
, &tokc
);
1221 /* get a token from an integer array and increment pointer
1222 accordingly. we code it as a macro to avoid pointer aliasing. */
1223 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1235 #ifndef TCC_LONG_ARE_64_BIT
1240 cv
->i
= (*t
== TOK_CUINT
) ? (unsigned)cv
->i
: (int)cv
->i
;
1249 cv
->str
.size
= *p
++;
1251 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1256 #ifdef TCC_LONG_ARE_64_BIT
1263 #if LDOUBLE_SIZE == 16
1265 #elif LDOUBLE_SIZE == 12
1267 #elif LDOUBLE_SIZE == 8
1270 # error add long double size support
1283 static int macro_is_equal(const int *a
, const int *b
)
1292 /* first time preallocate macro_equal_buf, next time only reset position to start */
1293 cstr_reset(¯o_equal_buf
);
1294 TOK_GET(&t
, &a
, &cv
);
1295 cstr_cat(¯o_equal_buf
, get_tok_str(t
, &cv
), 0);
1296 TOK_GET(&t
, &b
, &cv
);
1297 if (strcmp(macro_equal_buf
.data
, get_tok_str(t
, &cv
)))
1303 /* defines handling */
1304 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1309 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1311 s
->next
= first_arg
;
1312 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1314 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1315 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1318 /* undefined a define symbol. Its name is just set to zero */
1319 ST_FUNC
void define_undef(Sym
*s
)
1322 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1323 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1326 ST_INLN Sym
*define_find(int v
)
1329 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1331 return table_ident
[v
]->sym_define
;
1334 /* free define stack until top reaches 'b' */
1335 ST_FUNC
void free_defines(Sym
*b
)
1337 while (define_stack
!= b
) {
1338 Sym
*top
= define_stack
;
1339 define_stack
= top
->prev
;
1340 tok_str_free_str(top
->d
);
1345 /* restore remaining (-D or predefined) symbols if they were
1346 #undef'd in the file */
1349 if (v
>= TOK_IDENT
&& v
< tok_ident
) {
1350 Sym
**d
= &table_ident
[v
- TOK_IDENT
]->sym_define
;
1359 ST_FUNC Sym
*label_find(int v
)
1362 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1364 return table_ident
[v
]->sym_label
;
1367 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1370 s
= sym_push2(ptop
, v
, 0, 0);
1372 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1373 if (ptop
== &global_label_stack
) {
1374 /* modify the top most local identifier, so that
1375 sym_identifier will point to 's' when popped */
1377 ps
= &(*ps
)->prev_tok
;
1384 /* pop labels until element last is reached. Look if any labels are
1385 undefined. Define symbols if '&&label' was used. */
1386 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
, int keep
)
1389 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1391 if (s
->r
== LABEL_DECLARED
) {
1392 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1393 } else if (s
->r
== LABEL_FORWARD
) {
1394 tcc_error("label '%s' used but not defined",
1395 get_tok_str(s
->v
, NULL
));
1398 /* define corresponding symbol. A size of
1400 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1404 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1412 /* fake the nth "#if defined test_..." for tcc -dt -run */
1413 static void maybe_run_test(TCCState
*s
)
1416 if (s
->include_stack_ptr
!= s
->include_stack
)
1418 p
= get_tok_str(tok
, NULL
);
1419 if (0 != memcmp(p
, "test_", 5))
1421 if (0 != --s
->run_test
)
1423 fprintf(s
->ppfp
, "\n[%s]\n" + !(s
->dflag
& 32), p
), fflush(s
->ppfp
);
1424 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1427 /* eval an expression for #if/#elif */
1428 static int expr_preprocess(void)
1433 str
= tok_str_alloc();
1435 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1436 next(); /* do macro subst */
1437 if (tok
== TOK_DEFINED
) {
1442 if (tok
< TOK_IDENT
)
1443 expect("identifier");
1444 if (tcc_state
->run_test
)
1445 maybe_run_test(tcc_state
);
1446 c
= define_find(tok
) != 0;
1454 } else if (tok
>= TOK_IDENT
) {
1455 /* if undefined macro */
1459 tok_str_add_tok(str
);
1462 tok_str_add(str
, -1); /* simulate end of file */
1463 tok_str_add(str
, 0);
1464 /* now evaluate C constant expression */
1465 begin_macro(str
, 1);
1473 /* parse after #define */
1474 ST_FUNC
void parse_define(void)
1476 Sym
*s
, *first
, **ps
;
1477 int v
, t
, varg
, is_vaargs
, spc
;
1478 int saved_parse_flags
= parse_flags
;
1481 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1482 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1483 /* XXX: should check if same macro (ANSI) */
1486 /* We have to parse the whole define as if not in asm mode, in particular
1487 no line comment with '#' must be ignored. Also for function
1488 macros the argument list must be parsed without '.' being an ID
1490 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1491 /* '(' must be just after macro definition for MACRO_FUNC */
1494 int dotid
= set_idnum('.', 0);
1497 if (tok
!= ')') for (;;) {
1501 if (varg
== TOK_DOTS
) {
1502 varg
= TOK___VA_ARGS__
;
1504 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1508 if (varg
< TOK_IDENT
)
1510 tcc_error("bad macro parameter list");
1511 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1516 if (tok
!= ',' || is_vaargs
)
1522 set_idnum('.', dotid
);
1527 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1528 /* The body of a macro definition should be parsed such that identifiers
1529 are parsed like the file mode determines (i.e. with '.' being an
1530 ID character in asm mode). But '#' should be retained instead of
1531 regarded as line comment leader, so still don't set ASM_FILE
1533 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1534 /* remove spaces around ## and after '#' */
1535 if (TOK_TWOSHARPS
== tok
) {
1542 } else if ('#' == tok
) {
1544 } else if (check_space(tok
, &spc
)) {
1547 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1552 parse_flags
= saved_parse_flags
;
1554 --tokstr_buf
.len
; /* remove trailing space */
1555 tok_str_add(&tokstr_buf
, 0);
1558 tcc_error("'##' cannot appear at either end of macro");
1559 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1562 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1564 const unsigned char *s
;
1570 s
= (unsigned char *) filename
;
1573 h
= TOK_HASH_FUNC(h
, toup(*s
));
1575 h
= TOK_HASH_FUNC(h
, *s
);
1579 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1581 i
= s1
->cached_includes_hash
[h
];
1585 e
= s1
->cached_includes
[i
- 1];
1586 if (0 == PATHCMP(e
->filename
, filename
))
1593 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1594 strcpy(e
->filename
, filename
);
1595 e
->ifndef_macro
= e
->once
= 0;
1596 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1597 /* add in hash table */
1598 e
->hash_next
= s1
->cached_includes_hash
[h
];
1599 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1601 printf("adding cached '%s'\n", filename
);
1606 static void pragma_parse(TCCState
*s1
)
1609 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1613 if (next(), tok
!= '(')
1615 if (next(), tok
!= TOK_STR
)
1617 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1618 if (next(), tok
!= ')')
1620 if (t
== TOK_push_macro
) {
1621 while (NULL
== (s
= define_find(v
)))
1622 define_push(v
, 0, NULL
, NULL
);
1623 s
->type
.ref
= s
; /* set push boundary */
1625 for (s
= define_stack
; s
; s
= s
->prev
)
1626 if (s
->v
== v
&& s
->type
.ref
== s
) {
1632 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1634 tcc_warning("unbalanced #pragma pop_macro");
1635 pp_debug_tok
= t
, pp_debug_symv
= v
;
1637 } else if (tok
== TOK_once
) {
1638 search_cached_include(s1
, file
->filename
, 1)->once
= pp_once
;
1640 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1641 /* tcc -E: keep pragmas below unchanged */
1643 unget_tok(TOK_PRAGMA
);
1645 unget_tok(TOK_LINEFEED
);
1647 } else if (tok
== TOK_pack
) {
1649 #pragma pack(1) // set
1650 #pragma pack() // reset to default
1651 #pragma pack(push,1) // push & set
1652 #pragma pack(pop) // restore previous */
1655 if (tok
== TOK_ASM_pop
) {
1657 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1659 tcc_error("out of pack stack");
1661 s1
->pack_stack_ptr
--;
1665 if (tok
== TOK_ASM_push
) {
1667 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1669 s1
->pack_stack_ptr
++;
1672 if (tok
!= TOK_CINT
)
1675 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1679 *s1
->pack_stack_ptr
= val
;
1684 } else if (tok
== TOK_comment
) {
1693 p
= tcc_strdup((char *)tokc
.str
.data
);
1698 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1700 if (t
== TOK_option
)
1701 tcc_set_options(s1
, p
);
1705 } else if (s1
->warn_unsupported
) {
1706 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1711 tcc_error("malformed #pragma directive");
1715 /* is_bof is true if first non space token at beginning of file */
1716 ST_FUNC
void preprocess(int is_bof
)
1718 TCCState
*s1
= tcc_state
;
1719 int i
, c
, n
, saved_parse_flags
;
1723 saved_parse_flags
= parse_flags
;
1724 parse_flags
= PARSE_FLAG_PREPROCESS
1725 | PARSE_FLAG_TOK_NUM
1726 | PARSE_FLAG_TOK_STR
1727 | PARSE_FLAG_LINEFEED
1728 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1737 pp_debug_symv
= tok
;
1743 pp_debug_symv
= tok
;
1744 s
= define_find(tok
);
1745 /* undefine symbol by putting an invalid name */
1750 case TOK_INCLUDE_NEXT
:
1751 ch
= file
->buf_ptr
[0];
1752 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1757 } else if (ch
== '\"') {
1762 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1763 if ((q
- buf
) < sizeof(buf
) - 1)
1766 if (handle_stray_noerror() == 0)
1774 /* eat all spaces and comments after include */
1775 /* XXX: slightly incorrect */
1776 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1781 /* computed #include : concatenate everything up to linefeed,
1782 the result must be one of the two accepted forms.
1783 Don't convert pp-tokens to tokens here. */
1784 parse_flags
= (PARSE_FLAG_PREPROCESS
1785 | PARSE_FLAG_LINEFEED
1786 | (parse_flags
& PARSE_FLAG_ASM_FILE
));
1789 while (tok
!= TOK_LINEFEED
) {
1790 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1794 /* check syntax and remove '<>|""' */
1795 if ((len
< 2 || ((buf
[0] != '"' || buf
[len
-1] != '"') &&
1796 (buf
[0] != '<' || buf
[len
-1] != '>'))))
1797 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1799 memmove(buf
, buf
+ 1, len
- 2);
1800 buf
[len
- 2] = '\0';
1803 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1804 tcc_error("#include recursion too deep");
1805 /* store current file in stack, but increment stack later below */
1806 *s1
->include_stack_ptr
= file
;
1807 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
: 0;
1808 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1809 for (; i
< n
; ++i
) {
1810 char buf1
[sizeof file
->filename
];
1815 /* check absolute include path */
1816 if (!IS_ABSPATH(buf
))
1820 } else if (i
== 1) {
1821 /* search in file's dir if "header.h" */
1824 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1825 path
= file
->true_filename
;
1826 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1829 /* search in all the include paths */
1830 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1831 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1832 pstrcpy(buf1
, sizeof(buf1
), path
);
1833 pstrcat(buf1
, sizeof(buf1
), "/");
1836 pstrcat(buf1
, sizeof(buf1
), buf
);
1837 e
= search_cached_include(s1
, buf1
, 0);
1838 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
== pp_once
)) {
1839 /* no need to parse the include because the 'ifndef macro'
1840 is defined (or had #pragma once) */
1842 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1847 if (tcc_open(s1
, buf1
) < 0)
1850 file
->include_next_index
= i
+ 1;
1852 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1854 /* update target deps */
1855 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1857 /* push current file in stack */
1858 ++s1
->include_stack_ptr
;
1859 /* add include file debug info */
1861 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1862 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1863 ch
= file
->buf_ptr
[0];
1866 tcc_error("include file '%s' not found", buf
);
1873 c
= expr_preprocess();
1879 if (tok
< TOK_IDENT
)
1880 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1884 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1886 file
->ifndef_macro
= tok
;
1889 c
= (define_find(tok
) != 0) ^ c
;
1891 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1892 tcc_error("memory full (ifdef)");
1893 *s1
->ifdef_stack_ptr
++ = c
;
1896 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1897 tcc_error("#else without matching #if");
1898 if (s1
->ifdef_stack_ptr
[-1] & 2)
1899 tcc_error("#else after #else");
1900 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1903 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1904 tcc_error("#elif without matching #if");
1905 c
= s1
->ifdef_stack_ptr
[-1];
1907 tcc_error("#elif after #else");
1908 /* last #if/#elif expression was true: we skip */
1912 c
= expr_preprocess();
1913 s1
->ifdef_stack_ptr
[-1] = c
;
1916 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1917 file
->ifndef_macro
= 0;
1926 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1927 tcc_error("#endif without matching #if");
1928 s1
->ifdef_stack_ptr
--;
1929 /* '#ifndef macro' was at the start of file. Now we check if
1930 an '#endif' is exactly at the end of file */
1931 if (file
->ifndef_macro
&&
1932 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1933 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1934 /* need to set to zero to avoid false matches if another
1935 #ifndef at middle of file */
1936 file
->ifndef_macro
= 0;
1937 while (tok
!= TOK_LINEFEED
)
1939 tok_flags
|= TOK_FLAG_ENDIF
;
1944 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1948 if (tok
!= TOK_CINT
)
1950 tcc_error("wrong #line format");
1954 if (tok
!= TOK_LINEFEED
) {
1955 if (tok
== TOK_STR
) {
1956 if (file
->true_filename
== file
->filename
)
1957 file
->true_filename
= tcc_strdup(file
->filename
);
1958 pstrcpy(file
->filename
, sizeof(file
->filename
), (char *)tokc
.str
.data
);
1959 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1966 total_lines
+= file
->line_num
- n
;
1969 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1974 ch
= file
->buf_ptr
[0];
1977 while (ch
!= '\n' && ch
!= CH_EOF
) {
1978 if ((q
- buf
) < sizeof(buf
) - 1)
1981 if (handle_stray_noerror() == 0)
1988 tcc_error("#error %s", buf
);
1990 tcc_warning("#warning %s", buf
);
1998 /* ignore gas line comment in an 'S' file. */
1999 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
2001 if (tok
== '!' && is_bof
)
2002 /* '!' is ignored at beginning to allow C scripts. */
2004 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2006 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
2009 /* ignore other preprocess commands or #! for C scripts */
2010 while (tok
!= TOK_LINEFEED
)
2013 parse_flags
= saved_parse_flags
;
2016 /* evaluate escape codes in a string. */
2017 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2032 case '0': case '1': case '2': case '3':
2033 case '4': case '5': case '6': case '7':
2034 /* at most three octal digits */
2039 n
= n
* 8 + c
- '0';
2043 n
= n
* 8 + c
- '0';
2048 goto add_char_nonext
;
2056 if (c
>= 'a' && c
<= 'f')
2058 else if (c
>= 'A' && c
<= 'F')
2068 goto add_char_nonext
;
2092 goto invalid_escape
;
2102 if (c
>= '!' && c
<= '~')
2103 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2105 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2112 cstr_ccat(outstr
, c
);
2114 cstr_wccat(outstr
, c
);
2116 /* add a trailing '\0' */
2118 cstr_ccat(outstr
, '\0');
2120 cstr_wccat(outstr
, '\0');
2123 static void parse_string(const char *s
, int len
)
2125 uint8_t buf
[1000], *p
= buf
;
2128 if ((is_long
= *s
== 'L'))
2132 if (len
>= sizeof buf
)
2133 p
= tcc_malloc(len
+ 1);
2137 cstr_reset(&tokcstr
);
2138 parse_escape_string(&tokcstr
, p
, is_long
);
2144 /* XXX: make it portable */
2148 char_size
= sizeof(nwchar_t
);
2149 if (tokcstr
.size
<= char_size
)
2150 tcc_error("empty character constant");
2151 if (tokcstr
.size
> 2 * char_size
)
2152 tcc_warning("multi-character character constant");
2154 tokc
.i
= *(int8_t *)tokcstr
.data
;
2157 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2161 tokc
.str
.size
= tokcstr
.size
;
2162 tokc
.str
.data
= tokcstr
.data
;
2170 /* we use 64 bit numbers */
2173 /* bn = (bn << shift) | or_val */
2174 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2178 for(i
=0;i
<BN_SIZE
;i
++) {
2180 bn
[i
] = (v
<< shift
) | or_val
;
2181 or_val
= v
>> (32 - shift
);
2185 static void bn_zero(unsigned int *bn
)
2188 for(i
=0;i
<BN_SIZE
;i
++) {
2193 /* parse number in null terminated string 'p' and return it in the
2195 static void parse_number(const char *p
)
2197 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2199 unsigned int bn
[BN_SIZE
];
2210 goto float_frac_parse
;
2211 } else if (t
== '0') {
2212 if (ch
== 'x' || ch
== 'X') {
2216 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2222 /* parse all digits. cannot check octal numbers at this stage
2223 because of floating point constants */
2225 if (ch
>= 'a' && ch
<= 'f')
2227 else if (ch
>= 'A' && ch
<= 'F')
2235 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2237 tcc_error("number too long");
2243 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2244 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2246 /* NOTE: strtox should support that for hexa numbers, but
2247 non ISOC99 libcs do not support it, so we prefer to do
2249 /* hexadecimal or binary floats */
2250 /* XXX: handle overflows */
2262 } else if (t
>= 'a') {
2264 } else if (t
>= 'A') {
2269 bn_lshift(bn
, shift
, t
);
2276 if (t
>= 'a' && t
<= 'f') {
2278 } else if (t
>= 'A' && t
<= 'F') {
2280 } else if (t
>= '0' && t
<= '9') {
2286 tcc_error("invalid digit");
2287 bn_lshift(bn
, shift
, t
);
2292 if (ch
!= 'p' && ch
!= 'P')
2299 } else if (ch
== '-') {
2303 if (ch
< '0' || ch
> '9')
2304 expect("exponent digits");
2305 while (ch
>= '0' && ch
<= '9') {
2306 exp_val
= exp_val
* 10 + ch
- '0';
2309 exp_val
= exp_val
* s
;
2311 /* now we can generate the number */
2312 /* XXX: should patch directly float number */
2313 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2314 d
= ldexp(d
, exp_val
- frac_bits
);
2319 /* float : should handle overflow */
2321 } else if (t
== 'L') {
2323 #ifdef TCC_TARGET_PE
2328 /* XXX: not large enough */
2329 tokc
.ld
= (long double)d
;
2336 /* decimal floats */
2338 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2343 while (ch
>= '0' && ch
<= '9') {
2344 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2350 if (ch
== 'e' || ch
== 'E') {
2351 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2355 if (ch
== '-' || ch
== '+') {
2356 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2361 if (ch
< '0' || ch
> '9')
2362 expect("exponent digits");
2363 while (ch
>= '0' && ch
<= '9') {
2364 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2376 tokc
.f
= strtof(token_buf
, NULL
);
2377 } else if (t
== 'L') {
2379 #ifdef TCC_TARGET_PE
2381 tokc
.d
= strtod(token_buf
, NULL
);
2384 tokc
.ld
= strtold(token_buf
, NULL
);
2388 tokc
.d
= strtod(token_buf
, NULL
);
2392 unsigned long long n
, n1
;
2393 int lcount
, ucount
, must_64bit
;
2396 /* integer number */
2399 if (b
== 10 && *q
== '0') {
2406 /* no need for checks except for base 10 / 8 errors */
2416 tcc_error("invalid digit");
2419 /* detect overflow */
2420 /* XXX: this test is not reliable */
2422 tcc_error("integer constant overflow");
2425 /* Determine the characteristics (unsigned and/or 64bit) the type of
2426 the constant must have according to the constant suffix(es) */
2427 lcount
= ucount
= must_64bit
= 0;
2433 tcc_error("three 'l's in integer constant");
2434 if (lcount
&& *(p
- 1) != ch
)
2435 tcc_error("incorrect integer suffix: %s", p1
);
2440 } else if (t
== 'U') {
2442 tcc_error("two 'u's in integer constant");
2450 /* Whether 64 bits are needed to hold the constant's value */
2451 if (n
& 0xffffffff00000000LL
|| must_64bit
) {
2454 } else if (lcount
) {
2455 #ifdef TCC_LONG_ARE_64_BIT
2466 /* Whether type must be unsigned to hold the constant's value */
2467 if (ucount
|| ((n1
>> 31) && (b
!= 10))) {
2468 if (tok
== TOK_CLLONG
)
2470 else if (tok
== TOK_CLONG
)
2474 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2475 } else if (n1
>> 31) {
2476 if (tok
== TOK_CINT
)
2479 tcc_error("integer constant overflow");
2485 tcc_error("invalid number\n");
2489 #define PARSE2(c1, tok1, c2, tok2) \
2500 /* return next token without macro substitution */
2501 static inline void next_nomacro1(void)
2503 int t
, c
, is_long
, len
;
2516 if (parse_flags
& PARSE_FLAG_SPACES
)
2517 goto keep_tok_flags
;
2518 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2527 /* first look if it is in fact an end of buffer */
2528 c
= handle_stray1(p
);
2535 TCCState
*s1
= tcc_state
;
2536 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2537 && !(tok_flags
& TOK_FLAG_EOF
)) {
2538 tok_flags
|= TOK_FLAG_EOF
;
2540 goto keep_tok_flags
;
2541 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2543 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2544 tcc_error("missing #endif");
2545 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2546 /* no include left : end of file. */
2549 tok_flags
&= ~TOK_FLAG_EOF
;
2550 /* pop include file */
2552 /* test if previous '#endif' was after a #ifdef at
2554 if (tok_flags
& TOK_FLAG_ENDIF
) {
2556 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2558 search_cached_include(s1
, file
->filename
, 1)
2559 ->ifndef_macro
= file
->ifndef_macro_saved
;
2560 tok_flags
&= ~TOK_FLAG_ENDIF
;
2563 /* add end of include file debug info */
2564 if (tcc_state
->do_debug
) {
2565 put_stabd(N_EINCL
, 0, 0);
2567 /* pop include stack */
2569 s1
->include_stack_ptr
--;
2578 tok_flags
|= TOK_FLAG_BOL
;
2581 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2584 goto keep_tok_flags
;
2589 if ((tok_flags
& TOK_FLAG_BOL
) &&
2590 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2592 preprocess(tok_flags
& TOK_FLAG_BOF
);
2598 tok
= TOK_TWOSHARPS
;
2600 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2601 p
= parse_line_comment(p
- 1);
2610 /* dollar is allowed to start identifiers when not parsing asm */
2612 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2613 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2616 case 'a': case 'b': case 'c': case 'd':
2617 case 'e': case 'f': case 'g': case 'h':
2618 case 'i': case 'j': case 'k': case 'l':
2619 case 'm': case 'n': case 'o': case 'p':
2620 case 'q': case 'r': case 's': case 't':
2621 case 'u': case 'v': case 'w': case 'x':
2623 case 'A': case 'B': case 'C': case 'D':
2624 case 'E': case 'F': case 'G': case 'H':
2625 case 'I': case 'J': case 'K':
2626 case 'M': case 'N': case 'O': case 'P':
2627 case 'Q': case 'R': case 'S': case 'T':
2628 case 'U': case 'V': case 'W': case 'X':
2634 h
= TOK_HASH_FUNC(h
, c
);
2635 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2636 h
= TOK_HASH_FUNC(h
, c
);
2641 /* fast case : no stray found, so we have the full token
2642 and we have already hashed it */
2643 h
&= (TOK_HASH_SIZE
- 1);
2644 pts
= &hash_ident
[h
];
2649 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2651 pts
= &(ts
->hash_next
);
2653 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2657 cstr_reset(&tokcstr
);
2658 cstr_cat(&tokcstr
, (char *) p1
, len
);
2662 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2664 cstr_ccat(&tokcstr
, c
);
2667 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2673 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2675 goto parse_ident_fast
;
2678 if (c
== '\'' || c
== '\"') {
2682 cstr_reset(&tokcstr
);
2683 cstr_ccat(&tokcstr
, 'L');
2684 goto parse_ident_slow
;
2689 case '0': case '1': case '2': case '3':
2690 case '4': case '5': case '6': case '7':
2694 /* after the first digit, accept digits, alpha, '.' or sign if
2695 prefixed by 'eEpP' */
2697 cstr_reset(&tokcstr
);
2699 cstr_ccat(&tokcstr
, t
);
2700 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2702 || ((c
== '+' || c
== '-')
2703 && (((t
== 'e' || t
== 'E')
2704 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2705 /* 0xe+1 is 3 tokens in asm */
2706 && ((char*)tokcstr
.data
)[0] == '0'
2707 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2708 || t
== 'p' || t
== 'P'))))
2713 /* We add a trailing '\0' to ease parsing */
2714 cstr_ccat(&tokcstr
, '\0');
2715 tokc
.str
.size
= tokcstr
.size
;
2716 tokc
.str
.data
= tokcstr
.data
;
2721 /* special dot handling because it can also start a number */
2726 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2727 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2729 goto parse_ident_fast
;
2730 } else if (c
== '.') {
2736 *--p
= '.'; /* may underflow into file->unget[] */
2747 cstr_reset(&tokcstr
);
2749 cstr_ccat(&tokcstr
, 'L');
2750 cstr_ccat(&tokcstr
, c
);
2751 p
= parse_pp_string(p
, c
, &tokcstr
);
2752 cstr_ccat(&tokcstr
, c
);
2753 cstr_ccat(&tokcstr
, '\0');
2754 tokc
.str
.size
= tokcstr
.size
;
2755 tokc
.str
.data
= tokcstr
.data
;
2764 } else if (c
== '<') {
2781 } else if (c
== '>') {
2799 } else if (c
== '=') {
2812 } else if (c
== '=') {
2825 } else if (c
== '=') {
2838 } else if (c
== '=') {
2841 } else if (c
== '>') {
2849 PARSE2('!', '!', '=', TOK_NE
)
2850 PARSE2('=', '=', '=', TOK_EQ
)
2851 PARSE2('*', '*', '=', TOK_A_MUL
)
2852 PARSE2('%', '%', '=', TOK_A_MOD
)
2853 PARSE2('^', '^', '=', TOK_A_XOR
)
2855 /* comments or operator */
2859 p
= parse_comment(p
);
2860 /* comments replaced by a blank */
2862 goto keep_tok_flags
;
2863 } else if (c
== '/') {
2864 p
= parse_line_comment(p
);
2866 goto keep_tok_flags
;
2867 } else if (c
== '=') {
2887 case '@': /* only used in assembler */
2893 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
2894 goto parse_ident_fast
;
2895 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2897 tcc_error("unrecognized character \\x%02x", c
);
2903 #if defined(PARSE_DEBUG)
2904 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2908 /* return next token without macro substitution. Can read input from
2910 static void next_nomacro_spc(void)
2916 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2917 if (tok
== TOK_LINENUM
) {
2918 file
->line_num
= tokc
.i
;
2925 //printf("token = %s\n", get_tok_str(tok, &tokc));
2928 ST_FUNC
void next_nomacro(void)
2932 } while (tok
< 256 && (isidnum_table
[tok
- CH_EOF
] & IS_SPC
));
2936 static void macro_subst(
2937 TokenString
*tok_str
,
2939 const int *macro_str
2942 /* substitute arguments in replacement lists in macro_str by the values in
2943 args (field d) and return allocated string */
2944 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2956 TOK_GET(&t
, ¯o_str
, &cval
);
2961 TOK_GET(&t
, ¯o_str
, &cval
);
2964 s
= sym_find2(args
, t
);
2967 cstr_ccat(&cstr
, '\"');
2971 TOK_GET(&t
, &st
, &cval
);
2972 if (t
!= TOK_PLCHLDR
2974 && 0 == check_space(t
, &spc
)) {
2975 const char *s
= get_tok_str(t
, &cval
);
2977 if (t
== TOK_PPSTR
&& *s
!= '\'')
2978 add_char(&cstr
, *s
);
2980 cstr_ccat(&cstr
, *s
);
2986 cstr_ccat(&cstr
, '\"');
2987 cstr_ccat(&cstr
, '\0');
2989 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
2992 cval
.str
.size
= cstr
.size
;
2993 cval
.str
.data
= cstr
.data
;
2994 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
2998 expect("macro parameter after '#'");
3000 } else if (t
>= TOK_IDENT
) {
3001 s
= sym_find2(args
, t
);
3005 /* if '##' is present before or after, no arg substitution */
3006 if (*macro_str
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
3007 /* special case for var arg macros : ## eats the ','
3008 if empty VA_ARGS variable. */
3009 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
3011 /* suppress ',' '##' */
3014 /* suppress '##' and add variable */
3022 /* Expand arguments tokens and store them. In most
3023 cases we could also re-expand each argument if
3024 used multiple times, but not if the argument
3025 contains the __COUNTER__ macro. */
3027 sym_push2(&s
->next
, s
->v
, s
->type
.t
, 0);
3029 macro_subst(&str2
, nested_list
, st
);
3030 tok_str_add(&str2
, 0);
3031 s
->next
->d
= str2
.str
;
3037 TOK_GET(&t2
, &st
, &cval
);
3040 tok_str_add2(&str
, t2
, &cval
);
3042 if (str
.len
== l0
) /* expanded to empty string */
3043 tok_str_add(&str
, TOK_PLCHLDR
);
3045 tok_str_add(&str
, t
);
3048 tok_str_add2(&str
, t
, &cval
);
3052 tok_str_add(&str
, 0);
3056 static char const ab_month_name
[12][4] =
3058 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3059 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3062 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3068 if (t1
!= TOK_PLCHLDR
)
3069 cstr_cat(&cstr
, get_tok_str(t1
, v1
), -1);
3071 if (t2
!= TOK_PLCHLDR
)
3072 cstr_cat(&cstr
, get_tok_str(t2
, v2
), -1);
3073 cstr_ccat(&cstr
, '\0');
3075 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3076 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3080 if (0 == *file
->buf_ptr
)
3084 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3085 " preprocessing token", n
, cstr
.data
, (char*)cstr
.data
+ n
);
3090 //printf("paste <%s>\n", (char*)cstr.data);
3095 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3096 return the resulting string (which must be freed). */
3097 static inline int *macro_twosharps(const int *ptr0
)
3101 TokenString macro_str1
;
3102 int start_of_nosubsts
= -1;
3105 /* we search the first '##' */
3106 for (ptr
= ptr0
;;) {
3107 TOK_GET(&t
, &ptr
, &cval
);
3108 if (t
== TOK_PPJOIN
)
3114 tok_str_new(¯o_str1
);
3116 //tok_print(" $$$", ptr0);
3117 for (ptr
= ptr0
;;) {
3118 TOK_GET(&t
, &ptr
, &cval
);
3121 if (t
== TOK_PPJOIN
)
3123 while (*ptr
== TOK_PPJOIN
) {
3125 /* given 'a##b', remove nosubsts preceding 'a' */
3126 if (start_of_nosubsts
>= 0)
3127 macro_str1
.len
= start_of_nosubsts
;
3128 /* given 'a##b', remove nosubsts preceding 'b' */
3129 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3131 if (t1
&& t1
!= TOK_PPJOIN
) {
3132 TOK_GET(&t1
, &ptr
, &cv1
);
3133 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3134 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3135 t
= tok
, cval
= tokc
;
3137 tok_str_add2(¯o_str1
, t
, &cval
);
3143 if (t
== TOK_NOSUBST
) {
3144 if (start_of_nosubsts
< 0)
3145 start_of_nosubsts
= macro_str1
.len
;
3147 start_of_nosubsts
= -1;
3149 tok_str_add2(¯o_str1
, t
, &cval
);
3151 tok_str_add(¯o_str1
, 0);
3152 //tok_print(" ###", macro_str1.str);
3153 return macro_str1
.str
;
3156 /* peek or read [ws_str == NULL] next token from function macro call,
3157 walking up macro levels up to the file if necessary */
3158 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3166 p
= macro_ptr
, t
= *p
;
3168 while (is_space(t
) || TOK_LINEFEED
== t
|| TOK_PLCHLDR
== t
)
3169 tok_str_add(ws_str
, t
), t
= *++p
;
3173 /* also, end of scope for nested defined symbol */
3175 while (sa
&& sa
->v
== 0)
3184 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3187 uint8_t *p
= file
->buf_ptr
;
3190 p
= parse_comment(p
);
3191 file
->buf_ptr
= p
- 1;
3192 } else if (c
== '/') {
3193 p
= parse_line_comment(p
);
3194 file
->buf_ptr
= p
- 1;
3201 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3202 tok_str_add(ws_str
, ch
);
3216 /* do macro substitution of current token with macro 's' and add
3217 result to (tok_str,tok_len). 'nested_list' is the list of all
3218 macros we got inside to avoid recursing. Return non zero if no
3219 substitution needs to be done */
3220 static int macro_subst_tok(
3221 TokenString
*tok_str
,
3225 Sym
*args
, *sa
, *sa1
;
3226 int parlevel
, t
, t1
, spc
;
3233 /* if symbol is a macro, prepare substitution */
3234 /* special macros */
3235 if (tok
== TOK___LINE__
|| tok
== TOK___COUNTER__
) {
3236 t
= tok
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3237 snprintf(buf
, sizeof(buf
), "%d", t
);
3241 } else if (tok
== TOK___FILE__
) {
3242 cstrval
= file
->filename
;
3244 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3249 tm
= localtime(&ti
);
3250 if (tok
== TOK___DATE__
) {
3251 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3252 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3254 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3255 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3262 cstr_cat(&cstr
, cstrval
, 0);
3263 cval
.str
.size
= cstr
.size
;
3264 cval
.str
.data
= cstr
.data
;
3265 tok_str_add2(tok_str
, t1
, &cval
);
3268 int saved_parse_flags
= parse_flags
;
3269 int *joined_str
= NULL
;
3272 if (s
->type
.t
== MACRO_FUNC
) {
3273 /* whitespace between macro name and argument list */
3275 tok_str_new(&ws_str
);
3278 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3279 | PARSE_FLAG_ACCEPT_STRAYS
;
3281 /* get next token from argument stream */
3282 t
= next_argstream(nested_list
, &ws_str
);
3284 /* not a macro substitution after all, restore the
3285 * macro token plus all whitespace we've read.
3286 * whitespace is intentionally not merged to preserve
3288 parse_flags
= saved_parse_flags
;
3289 tok_str_add(tok_str
, tok
);
3290 if (parse_flags
& PARSE_FLAG_SPACES
) {
3292 for (i
= 0; i
< ws_str
.len
; i
++)
3293 tok_str_add(tok_str
, ws_str
.str
[i
]);
3295 tok_str_free_str(ws_str
.str
);
3298 tok_str_free_str(ws_str
.str
);
3301 next_nomacro(); /* eat '(' */
3302 } while (tok
== TOK_PLCHLDR
);
3304 /* argument macro */
3307 /* NOTE: empty args are allowed, except if no args */
3310 next_argstream(nested_list
, NULL
);
3311 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3313 /* handle '()' case */
3314 if (!args
&& !sa
&& tok
== ')')
3317 tcc_error("macro '%s' used with too many args",
3318 get_tok_str(s
->v
, 0));
3321 /* NOTE: non zero sa->t indicates VA_ARGS */
3322 while ((parlevel
> 0 ||
3324 (tok
!= ',' || sa
->type
.t
)))) {
3325 if (tok
== TOK_EOF
|| tok
== 0)
3329 else if (tok
== ')')
3331 if (tok
== TOK_LINEFEED
)
3333 if (!check_space(tok
, &spc
))
3334 tok_str_add2(&str
, tok
, &tokc
);
3335 next_argstream(nested_list
, NULL
);
3340 tok_str_add(&str
, -1);
3341 tok_str_add(&str
, 0);
3342 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3346 /* special case for gcc var args: add an empty
3347 var arg argument if it is omitted */
3348 if (sa
&& sa
->type
.t
&& gnu_ext
)
3356 tcc_error("macro '%s' used with too few args",
3357 get_tok_str(s
->v
, 0));
3360 parse_flags
= saved_parse_flags
;
3362 /* now subst each arg */
3363 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3368 tok_str_free_str(sa
->d
);
3370 tok_str_free_str(sa
->next
->d
);
3378 sym_push2(nested_list
, s
->v
, 0, 0);
3379 parse_flags
= saved_parse_flags
;
3380 joined_str
= macro_twosharps(mstr
);
3381 macro_subst(tok_str
, nested_list
, joined_str
? joined_str
: mstr
);
3383 /* pop nested defined symbol */
3385 *nested_list
= sa1
->prev
;
3388 tok_str_free_str(joined_str
);
3390 tok_str_free_str(mstr
);
3395 /* do macro substitution of macro_str and add result to
3396 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3397 inside to avoid recursing. */
3398 static void macro_subst(
3399 TokenString
*tok_str
,
3401 const int *macro_str
3405 int t
, spc
, nosubst
;
3411 TOK_GET(&t
, ¯o_str
, &cval
);
3415 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3420 /* if nested substitution, do nothing */
3421 if (sym_find2(*nested_list
, t
)) {
3422 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3423 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3429 str
.str
= (int*)macro_str
;
3430 begin_macro(&str
, 2);
3433 macro_subst_tok(tok_str
, nested_list
, s
);
3435 if (str
.alloc
== 3) {
3436 /* already finished by reading function macro arguments */
3440 macro_str
= macro_ptr
;
3444 spc
= is_space(t
= tok_str
->str
[tok_str
->lastlen
]);
3446 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3447 tcc_error("stray '\\' in program");
3449 if (!check_space(t
, &spc
))
3450 tok_str_add2(tok_str
, t
, &cval
);
3453 if (nosubst
> 1 && (spc
|| (++nosubst
== 3 && t
== '(')))
3457 if (t
== TOK_NOSUBST
)
3460 /* GCC supports 'defined' as result of a macto substitution */
3461 if (t
== TOK_DEFINED
&& pp_expr
)
3466 /* return next token with macro substitution */
3467 ST_FUNC
void next(void)
3470 if (parse_flags
& PARSE_FLAG_SPACES
)
3476 if (tok
== TOK_NOSUBST
|| tok
== TOK_PLCHLDR
) {
3477 /* discard preprocessor markers */
3479 } else if (tok
== 0) {
3480 /* end of macro or unget token string */
3484 } else if (tok
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3486 /* if reading from file, try to substitute macros */
3487 s
= define_find(tok
);
3489 Sym
*nested_list
= NULL
;
3491 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3492 tok_str_add(&tokstr_buf
, 0);
3493 begin_macro(&tokstr_buf
, 2);
3497 /* convert preprocessor tokens into C tokens */
3498 if (tok
== TOK_PPNUM
) {
3499 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3500 parse_number((char *)tokc
.str
.data
);
3501 } else if (tok
== TOK_PPSTR
) {
3502 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3503 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3507 /* push back current token and set current token to 'last_tok'. Only
3508 identifier case handled for labels. */
3509 ST_INLN
void unget_tok(int last_tok
)
3512 TokenString
*str
= tok_str_alloc();
3513 tok_str_add2(str
, tok
, &tokc
);
3514 tok_str_add(str
, 0);
3515 begin_macro(str
, 1);
3519 ST_FUNC
void preprocess_start(TCCState
*s1
, int is_asm
)
3523 s1
->include_stack_ptr
= s1
->include_stack
;
3524 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3525 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3528 pp_debug_tok
= pp_debug_symv
= 0;
3530 pvtop
= vtop
= vstack
- 1;
3531 s1
->pack_stack
[0] = 0;
3532 s1
->pack_stack_ptr
= s1
->pack_stack
;
3534 set_idnum('$', s1
->dollars_in_identifiers
? IS_ID
: 0);
3535 set_idnum('.', is_asm
? IS_ID
: 0);
3537 buf
= tcc_malloc(3 + strlen(file
->filename
));
3538 sprintf(buf
, "\"%s\"", file
->filename
);
3539 tcc_define_symbol(s1
, "__BASE_FILE__", buf
);
3542 if (s1
->nb_cmd_include_files
) {
3546 for (i
= 0; i
< s1
->nb_cmd_include_files
; i
++) {
3547 cstr_cat(&cstr
, "#include \"", -1);
3548 cstr_cat(&cstr
, s1
->cmd_include_files
[i
], -1);
3549 cstr_cat(&cstr
, "\"\n", -1);
3551 *s1
->include_stack_ptr
++ = file
;
3552 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3553 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3558 tcc_define_symbol(s1
, "__ASSEMBLER__", NULL
);
3560 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3561 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3564 /* cleanup from error/setjmp */
3565 ST_FUNC
void preprocess_end(TCCState
*s1
)
3572 ST_FUNC
void tccpp_new(TCCState
*s
)
3577 /* might be used in error() before preprocess_start() */
3578 s
->include_stack_ptr
= s
->include_stack
;
3581 /* init isid table */
3582 for(i
= CH_EOF
; i
<128; i
++)
3584 is_space(i
) ? IS_SPC
3589 for(i
= 128; i
<256; i
++)
3590 set_idnum(i
, IS_ID
);
3592 /* init allocators */
3593 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3594 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3595 tal_new(&cstr_alloc
, CSTR_TAL_LIMIT
, CSTR_TAL_SIZE
);
3597 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3598 cstr_new(&cstr_buf
);
3599 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3600 tok_str_new(&tokstr_buf
);
3601 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3603 tok_ident
= TOK_IDENT
;
3612 tok_alloc(p
, r
- p
- 1);
3617 ST_FUNC
void tccpp_delete(TCCState
*s
)
3621 /* free -D and compiler defines */
3625 n
= tok_ident
- TOK_IDENT
;
3626 for(i
= 0; i
< n
; i
++)
3627 tal_free(toksym_alloc
, table_ident
[i
]);
3628 tcc_free(table_ident
);
3631 /* free static buffers */
3632 cstr_free(&tokcstr
);
3633 cstr_free(&cstr_buf
);
3634 cstr_free(¯o_equal_buf
);
3635 tok_str_free_str(tokstr_buf
.str
);
3637 /* free allocators */
3638 tal_delete(toksym_alloc
);
3639 toksym_alloc
= NULL
;
3640 tal_delete(tokstr_alloc
);
3641 tokstr_alloc
= NULL
;
3642 tal_delete(cstr_alloc
);
3646 /* ------------------------------------------------------------------------- */
3647 /* tcc -E [-P[1]] [-dD} support */
3649 static void tok_print(const char *msg
, const int *str
)
3655 fp
= tcc_state
->ppfp
;
3656 fprintf(fp
, "%s", msg
);
3658 TOK_GET(&t
, &str
, &cval
);
3661 fprintf(fp
, " %s" + s
, get_tok_str(t
, &cval
)), s
= 1;
3666 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3668 int d
= f
->line_num
- f
->line_ref
;
3673 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3675 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3677 fputs("\n", s1
->ppfp
), --d
;
3678 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3679 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3681 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3682 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3684 f
->line_ref
= f
->line_num
;
3687 static void define_print(TCCState
*s1
, int v
)
3693 if (NULL
== s
|| NULL
== s
->d
)
3697 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3698 if (s
->type
.t
== MACRO_FUNC
) {
3703 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3710 tok_print("", s
->d
);
3713 static void pp_debug_defines(TCCState
*s1
)
3724 pp_line(s1
, file
, 0);
3725 file
->line_ref
= ++file
->line_num
;
3729 vs
= get_tok_str(v
, NULL
);
3730 if (t
== TOK_DEFINE
) {
3731 define_print(s1
, v
);
3732 } else if (t
== TOK_UNDEF
) {
3733 fprintf(fp
, "#undef %s\n", vs
);
3734 } else if (t
== TOK_push_macro
) {
3735 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3736 } else if (t
== TOK_pop_macro
) {
3737 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3742 static void pp_debug_builtins(TCCState
*s1
)
3745 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3746 define_print(s1
, v
);
3749 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3750 static int pp_need_space(int a
, int b
)
3752 return 'E' == a
? '+' == b
|| '-' == b
3753 : '+' == a
? TOK_INC
== b
|| '+' == b
3754 : '-' == a
? TOK_DEC
== b
|| '-' == b
3755 : a
>= TOK_IDENT
? b
>= TOK_IDENT
3756 : a
== TOK_PPNUM
? b
>= TOK_IDENT
3760 /* maybe hex like 0x1e */
3761 static int pp_check_he0xE(int t
, const char *p
)
3763 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3768 /* Preprocess the current file */
3769 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3771 BufferedFile
**iptr
;
3772 int token_seen
, spcs
, level
;
3776 parse_flags
= PARSE_FLAG_PREPROCESS
3777 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3778 | PARSE_FLAG_LINEFEED
3780 | PARSE_FLAG_ACCEPT_STRAYS
3782 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3783 capability to compile and run itself, provided all numbers are
3784 given as decimals. tcc -E -P10 will do. */
3785 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
3786 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
3789 /* for PP benchmarks */
3790 do next(); while (tok
!= TOK_EOF
);
3794 if (s1
->dflag
& 1) {
3795 pp_debug_builtins(s1
);
3799 token_seen
= TOK_LINEFEED
, spcs
= 0;
3800 pp_line(s1
, file
, 0);
3802 iptr
= s1
->include_stack_ptr
;
3807 level
= s1
->include_stack_ptr
- iptr
;
3810 pp_line(s1
, *iptr
, 0);
3811 pp_line(s1
, file
, level
);
3813 if (s1
->dflag
& 7) {
3814 pp_debug_defines(s1
);
3819 if (is_space(tok
)) {
3820 if (spcs
< sizeof white
- 1)
3821 white
[spcs
++] = tok
;
3823 } else if (tok
== TOK_LINEFEED
) {
3825 if (token_seen
== TOK_LINEFEED
)
3828 } else if (token_seen
== TOK_LINEFEED
) {
3829 pp_line(s1
, file
, 0);
3830 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
3831 white
[spcs
++] = ' ';
3834 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
3835 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
3836 token_seen
= pp_check_he0xE(tok
, p
);
3841 /* ------------------------------------------------------------------------- */