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";
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
;
435 ts
->sym_asm_label
= NULL
;
437 ts
->hash_next
= NULL
;
438 memcpy(ts
->str
, str
, len
);
444 #define TOK_HASH_INIT 1
445 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
448 /* find a token and add it if not found */
449 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
457 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
458 h
&= (TOK_HASH_SIZE
- 1);
460 pts
= &hash_ident
[h
];
465 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
467 pts
= &(ts
->hash_next
);
469 return tok_alloc_new(pts
, str
, len
);
472 /* XXX: buffer overflow */
473 /* XXX: float tokens */
474 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
479 cstr_reset(&cstr_buf
);
489 /* XXX: not quite exact, but only useful for testing */
491 sprintf(p
, "%u", (unsigned)cv
->i
);
493 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
497 cstr_ccat(&cstr_buf
, 'L');
499 cstr_ccat(&cstr_buf
, '\'');
500 add_char(&cstr_buf
, cv
->i
);
501 cstr_ccat(&cstr_buf
, '\'');
502 cstr_ccat(&cstr_buf
, '\0');
506 return (char*)cv
->str
.data
;
508 cstr_ccat(&cstr_buf
, 'L');
510 cstr_ccat(&cstr_buf
, '\"');
512 len
= cv
->str
.size
- 1;
514 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
516 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
518 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
520 cstr_ccat(&cstr_buf
, '\"');
521 cstr_ccat(&cstr_buf
, '\0');
525 cstr_cat(&cstr_buf
, "<float>", 0);
528 cstr_cat(&cstr_buf
, "<double>", 0);
531 cstr_cat(&cstr_buf
, "<long double>", 0);
534 cstr_cat(&cstr_buf
, "<linenumber>", 0);
537 /* above tokens have value, the ones below don't */
545 return strcpy(p
, "...");
547 return strcpy(p
, "<<=");
549 return strcpy(p
, ">>=");
551 return strcpy(p
, "<eof>");
554 /* search in two bytes table */
555 const unsigned char *q
= tok_two_chars
;
561 return cstr_buf
.data
;
566 sprintf(cstr_buf
.data
, "<%02x>", v
);
567 return cstr_buf
.data
;
572 } else if (v
< tok_ident
) {
573 return table_ident
[v
- TOK_IDENT
]->str
;
574 } else if (v
>= SYM_FIRST_ANOM
) {
575 /* special name for anonymous symbol */
576 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
578 /* should never happen */
583 return cstr_buf
.data
;
586 /* return the current character, handling end of block if necessary
588 ST_FUNC
int handle_eob(void)
590 BufferedFile
*bf
= file
;
593 /* only tries to read if really end of buffer */
594 if (bf
->buf_ptr
>= bf
->buf_end
) {
596 #if defined(PARSE_DEBUG)
601 len
= read(bf
->fd
, bf
->buffer
, len
);
608 bf
->buf_ptr
= bf
->buffer
;
609 bf
->buf_end
= bf
->buffer
+ len
;
610 *bf
->buf_end
= CH_EOB
;
612 if (bf
->buf_ptr
< bf
->buf_end
) {
613 return bf
->buf_ptr
[0];
615 bf
->buf_ptr
= bf
->buf_end
;
620 /* read next char from current input file and handle end of input buffer */
621 ST_INLN
void inp(void)
623 ch
= *(++(file
->buf_ptr
));
624 /* end of buffer/file handling */
629 /* handle '\[\r]\n' */
630 static int handle_stray_noerror(void)
637 } else if (ch
== '\r') {
651 static void handle_stray(void)
653 if (handle_stray_noerror())
654 tcc_error("stray '\\' in program");
657 /* skip the stray and handle the \\n case. Output an error if
658 incorrect char after the stray */
659 static int handle_stray1(uint8_t *p
)
664 if (p
>= file
->buf_end
) {
671 if (handle_stray_noerror()) {
672 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
673 tcc_error("stray '\\' in program");
674 *--file
->buf_ptr
= '\\';
681 /* handle just the EOB case, but not stray */
682 #define PEEKC_EOB(c, p)\
693 /* handle the complicated stray case */
699 c = handle_stray1(p);\
704 /* input with '\[\r]\n' handling. Note that this function cannot
705 handle other characters after '\', so you cannot call it inside
706 strings or comments */
707 ST_FUNC
void minp(void)
714 /* single line C++ comments */
715 static uint8_t *parse_line_comment(uint8_t *p
)
723 if (c
== '\n' || c
== CH_EOF
) {
725 } else if (c
== '\\') {
734 } else if (c
== '\r') {
752 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
761 if (c
== '\n' || c
== '*' || c
== '\\')
765 if (c
== '\n' || c
== '*' || c
== '\\')
769 /* now we can handle all the cases */
773 } else if (c
== '*') {
779 } else if (c
== '/') {
781 } else if (c
== '\\') {
786 tcc_error("unexpected end of file in comment");
788 /* skip '\[\r]\n', otherwise just skip the stray */
794 } else if (c
== '\r') {
811 /* stray, eob or eof */
816 tcc_error("unexpected end of file in comment");
817 } else if (c
== '\\') {
827 ST_FUNC
int set_idnum(int c
, int val
)
829 int prev
= isidnum_table
[c
- CH_EOF
];
830 isidnum_table
[c
- CH_EOF
] = val
;
836 static inline void skip_spaces(void)
838 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
842 static inline int check_space(int t
, int *spc
)
844 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
853 /* parse a string without interpreting escapes */
854 static uint8_t *parse_pp_string(uint8_t *p
,
855 int sep
, CString
*str
)
863 } else if (c
== '\\') {
869 /* XXX: indicate line number of start of string */
870 tcc_error("missing terminating %c character", sep
);
871 } else if (c
== '\\') {
872 /* escape : just skip \[\r]\n */
877 } else if (c
== '\r') {
880 expect("'\n' after '\r'");
883 } else if (c
== CH_EOF
) {
884 goto unterminated_string
;
887 cstr_ccat(str
, '\\');
893 } else if (c
== '\n') {
896 } else if (c
== '\r') {
900 cstr_ccat(str
, '\r');
916 /* skip block of text until #else, #elif or #endif. skip also pairs of
918 static void preprocess_skip(void)
920 int a
, start_of_line
, c
, in_warn_or_error
;
927 in_warn_or_error
= 0;
948 } else if (c
== '\\') {
949 ch
= file
->buf_ptr
[0];
950 handle_stray_noerror();
957 if (in_warn_or_error
)
959 p
= parse_pp_string(p
, c
, NULL
);
963 if (in_warn_or_error
)
970 p
= parse_comment(p
);
971 } else if (ch
== '/') {
972 p
= parse_line_comment(p
);
982 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
984 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
986 else if (tok
== TOK_ENDIF
)
988 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
989 in_warn_or_error
= 1;
990 else if (tok
== TOK_LINEFEED
)
992 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
993 p
= parse_line_comment(p
- 1);
994 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
995 p
= parse_line_comment(p
- 1);
1009 /* return the number of additional 'ints' necessary to store the
1011 static inline int tok_size(const int *p
)
1026 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
1029 return 1 + LONG_SIZE
/ 4;
1035 return 1 + LDOUBLE_SIZE
/ 4;
1042 /* token string handling */
1043 ST_INLN
void tok_str_new(TokenString
*s
)
1046 s
->len
= s
->lastlen
= 0;
1047 s
->allocated_len
= 0;
1048 s
->last_line_num
= -1;
1051 ST_FUNC TokenString
*tok_str_alloc(void)
1053 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1058 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1062 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1063 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1067 ST_FUNC
void tok_str_free_str(int *str
)
1069 tal_free(tokstr_alloc
, str
);
1072 ST_FUNC
void tok_str_free(TokenString
*str
)
1074 tok_str_free_str(str
->str
);
1075 tal_free(tokstr_alloc
, str
);
1078 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1082 size
= s
->allocated_len
;
1085 while (size
< new_size
)
1087 if (size
> s
->allocated_len
) {
1088 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1089 s
->allocated_len
= size
;
1095 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1101 if (len
>= s
->allocated_len
)
1102 str
= tok_str_realloc(s
, len
+ 1);
1107 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1110 str
->prev
= macro_stack
;
1111 str
->prev_ptr
= macro_ptr
;
1112 str
->save_line_num
= file
->line_num
;
1113 macro_ptr
= str
->str
;
1117 ST_FUNC
void end_macro(void)
1119 TokenString
*str
= macro_stack
;
1120 macro_stack
= str
->prev
;
1121 macro_ptr
= str
->prev_ptr
;
1122 file
->line_num
= str
->save_line_num
;
1123 if (str
->alloc
== 2) {
1124 str
->alloc
= 3; /* just mark as finished */
1130 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1134 len
= s
->lastlen
= s
->len
;
1137 /* allocate space for worst case */
1138 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1139 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1152 str
[len
++] = cv
->tab
[0];
1159 /* Insert the string into the int array. */
1161 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1162 if (len
+ nb_words
>= s
->allocated_len
)
1163 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1164 str
[len
] = cv
->str
.size
;
1165 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1176 #if LDOUBLE_SIZE == 8
1179 str
[len
++] = cv
->tab
[0];
1180 str
[len
++] = cv
->tab
[1];
1182 #if LDOUBLE_SIZE == 12
1184 str
[len
++] = cv
->tab
[0];
1185 str
[len
++] = cv
->tab
[1];
1186 str
[len
++] = cv
->tab
[2];
1187 #elif LDOUBLE_SIZE == 16
1189 str
[len
++] = cv
->tab
[0];
1190 str
[len
++] = cv
->tab
[1];
1191 str
[len
++] = cv
->tab
[2];
1192 str
[len
++] = cv
->tab
[3];
1193 #elif LDOUBLE_SIZE != 8
1194 #error add long double size support
1203 /* add the current parse token in token string 's' */
1204 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1208 /* save line number info */
1209 if (file
->line_num
!= s
->last_line_num
) {
1210 s
->last_line_num
= file
->line_num
;
1211 cval
.i
= s
->last_line_num
;
1212 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1214 tok_str_add2(s
, tok
, &tokc
);
1217 /* get a token from an integer array and increment pointer
1218 accordingly. we code it as a macro to avoid pointer aliasing. */
1219 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1239 cv
->i
= (unsigned)*p
++;
1248 cv
->str
.size
= *p
++;
1250 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1262 #if LDOUBLE_SIZE == 16
1264 #elif LDOUBLE_SIZE == 12
1266 #elif LDOUBLE_SIZE == 8
1269 # error add long double size support
1282 static int macro_is_equal(const int *a
, const int *b
)
1291 /* first time preallocate macro_equal_buf, next time only reset position to start */
1292 cstr_reset(¯o_equal_buf
);
1293 TOK_GET(&t
, &a
, &cv
);
1294 cstr_cat(¯o_equal_buf
, get_tok_str(t
, &cv
), 0);
1295 TOK_GET(&t
, &b
, &cv
);
1296 if (strcmp(macro_equal_buf
.data
, get_tok_str(t
, &cv
)))
1302 /* defines handling */
1303 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1308 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1310 s
->next
= first_arg
;
1311 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1313 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1314 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1317 /* undefined a define symbol. Its name is just set to zero */
1318 ST_FUNC
void define_undef(Sym
*s
)
1321 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1322 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1325 ST_INLN Sym
*define_find(int v
)
1328 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1330 return table_ident
[v
]->sym_define
;
1333 /* free define stack until top reaches 'b' */
1334 ST_FUNC
void free_defines(Sym
*b
)
1336 while (define_stack
!= b
) {
1337 Sym
*top
= define_stack
;
1338 define_stack
= top
->prev
;
1339 tok_str_free_str(top
->d
);
1344 /* restore remaining (-D or predefined) symbols if they were
1345 #undef'd in the file */
1348 if (v
>= TOK_IDENT
&& v
< tok_ident
) {
1349 Sym
**d
= &table_ident
[v
- TOK_IDENT
]->sym_define
;
1358 ST_FUNC Sym
*label_find(int v
)
1361 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1363 return table_ident
[v
]->sym_label
;
1366 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1369 s
= sym_push2(ptop
, v
, 0, 0);
1371 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1372 if (ptop
== &global_label_stack
) {
1373 /* modify the top most local identifier, so that
1374 sym_identifier will point to 's' when popped */
1376 ps
= &(*ps
)->prev_tok
;
1383 /* pop labels until element last is reached. Look if any labels are
1384 undefined. Define symbols if '&&label' was used. */
1385 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
, int keep
)
1388 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1390 if (s
->r
== LABEL_DECLARED
) {
1391 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1392 } else if (s
->r
== LABEL_FORWARD
) {
1393 tcc_error("label '%s' used but not defined",
1394 get_tok_str(s
->v
, NULL
));
1397 /* define corresponding symbol. A size of
1399 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1403 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1411 /* fake the nth "#if defined test_..." for tcc -dt -run */
1412 static void maybe_run_test(TCCState
*s
)
1415 if (s
->include_stack_ptr
!= s
->include_stack
)
1417 p
= get_tok_str(tok
, NULL
);
1418 if (0 != memcmp(p
, "test_", 5))
1420 if (0 != --s
->run_test
)
1422 fprintf(s
->ppfp
, "\n[%s]\n" + !(s
->dflag
& 32), p
), fflush(s
->ppfp
);
1423 define_push(tok
, MACRO_OBJ
, NULL
, NULL
);
1426 /* eval an expression for #if/#elif */
1427 static int expr_preprocess(void)
1432 str
= tok_str_alloc();
1434 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1435 next(); /* do macro subst */
1436 if (tok
== TOK_DEFINED
) {
1441 if (tok
< TOK_IDENT
)
1442 expect("identifier");
1443 if (tcc_state
->run_test
)
1444 maybe_run_test(tcc_state
);
1445 c
= define_find(tok
) != 0;
1453 } else if (tok
>= TOK_IDENT
) {
1454 /* if undefined macro */
1458 tok_str_add_tok(str
);
1461 tok_str_add(str
, -1); /* simulate end of file */
1462 tok_str_add(str
, 0);
1463 /* now evaluate C constant expression */
1464 begin_macro(str
, 1);
1472 /* parse after #define */
1473 ST_FUNC
void parse_define(void)
1475 Sym
*s
, *first
, **ps
;
1476 int v
, t
, varg
, is_vaargs
, spc
;
1477 int saved_parse_flags
= parse_flags
;
1480 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1481 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1482 /* XXX: should check if same macro (ANSI) */
1485 /* We have to parse the whole define as if not in asm mode, in particular
1486 no line comment with '#' must be ignored. Also for function
1487 macros the argument list must be parsed without '.' being an ID
1489 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1490 /* '(' must be just after macro definition for MACRO_FUNC */
1493 int dotid
= set_idnum('.', 0);
1496 if (tok
!= ')') for (;;) {
1500 if (varg
== TOK_DOTS
) {
1501 varg
= TOK___VA_ARGS__
;
1503 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1507 if (varg
< TOK_IDENT
)
1509 tcc_error("bad macro parameter list");
1510 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1515 if (tok
!= ',' || is_vaargs
)
1521 set_idnum('.', dotid
);
1526 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1527 /* The body of a macro definition should be parsed such that identifiers
1528 are parsed like the file mode determines (i.e. with '.' being an
1529 ID character in asm mode). But '#' should be retained instead of
1530 regarded as line comment leader, so still don't set ASM_FILE
1532 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1533 /* remove spaces around ## and after '#' */
1534 if (TOK_TWOSHARPS
== tok
) {
1541 } else if ('#' == tok
) {
1543 } else if (check_space(tok
, &spc
)) {
1546 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1551 parse_flags
= saved_parse_flags
;
1553 --tokstr_buf
.len
; /* remove trailing space */
1554 tok_str_add(&tokstr_buf
, 0);
1557 tcc_error("'##' cannot appear at either end of macro");
1558 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1561 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1563 const unsigned char *s
;
1569 s
= (unsigned char *) filename
;
1572 h
= TOK_HASH_FUNC(h
, toup(*s
));
1574 h
= TOK_HASH_FUNC(h
, *s
);
1578 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1580 i
= s1
->cached_includes_hash
[h
];
1584 e
= s1
->cached_includes
[i
- 1];
1585 if (0 == PATHCMP(e
->filename
, filename
))
1592 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1593 strcpy(e
->filename
, filename
);
1594 e
->ifndef_macro
= e
->once
= 0;
1595 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1596 /* add in hash table */
1597 e
->hash_next
= s1
->cached_includes_hash
[h
];
1598 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1600 printf("adding cached '%s'\n", filename
);
1605 static void pragma_parse(TCCState
*s1
)
1608 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1612 if (next(), tok
!= '(')
1614 if (next(), tok
!= TOK_STR
)
1616 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1617 if (next(), tok
!= ')')
1619 if (t
== TOK_push_macro
) {
1620 while (NULL
== (s
= define_find(v
)))
1621 define_push(v
, 0, NULL
, NULL
);
1622 s
->type
.ref
= s
; /* set push boundary */
1624 for (s
= define_stack
; s
; s
= s
->prev
)
1625 if (s
->v
== v
&& s
->type
.ref
== s
) {
1631 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1633 tcc_warning("unbalanced #pragma pop_macro");
1634 pp_debug_tok
= t
, pp_debug_symv
= v
;
1636 } else if (tok
== TOK_once
) {
1637 search_cached_include(s1
, file
->filename
, 1)->once
= pp_once
;
1639 } else if (s1
->output_type
== TCC_OUTPUT_PREPROCESS
) {
1640 /* tcc -E: keep pragmas below unchanged */
1642 unget_tok(TOK_PRAGMA
);
1644 unget_tok(TOK_LINEFEED
);
1646 } else if (tok
== TOK_pack
) {
1648 #pragma pack(1) // set
1649 #pragma pack() // reset to default
1650 #pragma pack(push,1) // push & set
1651 #pragma pack(pop) // restore previous */
1654 if (tok
== TOK_ASM_pop
) {
1656 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1658 tcc_error("out of pack stack");
1660 s1
->pack_stack_ptr
--;
1664 if (tok
== TOK_ASM_push
) {
1666 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1668 s1
->pack_stack_ptr
++;
1671 if (tok
!= TOK_CINT
)
1674 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1678 *s1
->pack_stack_ptr
= val
;
1683 } else if (tok
== TOK_comment
) {
1692 p
= tcc_strdup((char *)tokc
.str
.data
);
1697 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1699 if (t
== TOK_option
)
1700 tcc_set_options(s1
, p
);
1704 } else if (s1
->warn_unsupported
) {
1705 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1710 tcc_error("malformed #pragma directive");
1714 /* is_bof is true if first non space token at beginning of file */
1715 ST_FUNC
void preprocess(int is_bof
)
1717 TCCState
*s1
= tcc_state
;
1718 int i
, c
, n
, saved_parse_flags
;
1722 saved_parse_flags
= parse_flags
;
1723 parse_flags
= PARSE_FLAG_PREPROCESS
1724 | PARSE_FLAG_TOK_NUM
1725 | PARSE_FLAG_TOK_STR
1726 | PARSE_FLAG_LINEFEED
1727 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1736 pp_debug_symv
= tok
;
1742 pp_debug_symv
= tok
;
1743 s
= define_find(tok
);
1744 /* undefine symbol by putting an invalid name */
1749 case TOK_INCLUDE_NEXT
:
1750 ch
= file
->buf_ptr
[0];
1751 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1756 } else if (ch
== '\"') {
1761 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1762 if ((q
- buf
) < sizeof(buf
) - 1)
1765 if (handle_stray_noerror() == 0)
1773 /* eat all spaces and comments after include */
1774 /* XXX: slightly incorrect */
1775 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1780 /* computed #include : concatenate everything up to linefeed,
1781 the result must be one of the two accepted forms.
1782 Don't convert pp-tokens to tokens here. */
1783 parse_flags
= (PARSE_FLAG_PREPROCESS
1784 | PARSE_FLAG_LINEFEED
1785 | (parse_flags
& PARSE_FLAG_ASM_FILE
));
1788 while (tok
!= TOK_LINEFEED
) {
1789 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1793 /* check syntax and remove '<>|""' */
1794 if ((len
< 2 || ((buf
[0] != '"' || buf
[len
-1] != '"') &&
1795 (buf
[0] != '<' || buf
[len
-1] != '>'))))
1796 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1798 memmove(buf
, buf
+ 1, len
- 2);
1799 buf
[len
- 2] = '\0';
1802 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1803 tcc_error("#include recursion too deep");
1804 /* store current file in stack, but increment stack later below */
1805 *s1
->include_stack_ptr
= file
;
1806 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
: 0;
1807 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1808 for (; i
< n
; ++i
) {
1809 char buf1
[sizeof file
->filename
];
1814 /* check absolute include path */
1815 if (!IS_ABSPATH(buf
))
1819 } else if (i
== 1) {
1820 /* search in file's dir if "header.h" */
1823 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1824 path
= file
->true_filename
;
1825 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1828 /* search in all the include paths */
1829 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1830 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1831 pstrcpy(buf1
, sizeof(buf1
), path
);
1832 pstrcat(buf1
, sizeof(buf1
), "/");
1835 pstrcat(buf1
, sizeof(buf1
), buf
);
1836 e
= search_cached_include(s1
, buf1
, 0);
1837 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
== pp_once
)) {
1838 /* no need to parse the include because the 'ifndef macro'
1839 is defined (or had #pragma once) */
1841 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1846 if (tcc_open(s1
, buf1
) < 0)
1849 file
->include_next_index
= i
+ 1;
1851 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1853 /* update target deps */
1854 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1856 /* push current file in stack */
1857 ++s1
->include_stack_ptr
;
1858 /* add include file debug info */
1860 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1861 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1862 ch
= file
->buf_ptr
[0];
1865 tcc_error("include file '%s' not found", buf
);
1872 c
= expr_preprocess();
1878 if (tok
< TOK_IDENT
)
1879 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1883 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1885 file
->ifndef_macro
= tok
;
1888 c
= (define_find(tok
) != 0) ^ c
;
1890 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1891 tcc_error("memory full (ifdef)");
1892 *s1
->ifdef_stack_ptr
++ = c
;
1895 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1896 tcc_error("#else without matching #if");
1897 if (s1
->ifdef_stack_ptr
[-1] & 2)
1898 tcc_error("#else after #else");
1899 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1902 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1903 tcc_error("#elif without matching #if");
1904 c
= s1
->ifdef_stack_ptr
[-1];
1906 tcc_error("#elif after #else");
1907 /* last #if/#elif expression was true: we skip */
1911 c
= expr_preprocess();
1912 s1
->ifdef_stack_ptr
[-1] = c
;
1915 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1916 file
->ifndef_macro
= 0;
1925 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1926 tcc_error("#endif without matching #if");
1927 s1
->ifdef_stack_ptr
--;
1928 /* '#ifndef macro' was at the start of file. Now we check if
1929 an '#endif' is exactly at the end of file */
1930 if (file
->ifndef_macro
&&
1931 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1932 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1933 /* need to set to zero to avoid false matches if another
1934 #ifndef at middle of file */
1935 file
->ifndef_macro
= 0;
1936 while (tok
!= TOK_LINEFEED
)
1938 tok_flags
|= TOK_FLAG_ENDIF
;
1943 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1947 if (tok
!= TOK_CINT
)
1949 tcc_error("wrong #line format");
1953 if (tok
!= TOK_LINEFEED
) {
1954 if (tok
== TOK_STR
) {
1955 if (file
->true_filename
== file
->filename
)
1956 file
->true_filename
= tcc_strdup(file
->filename
);
1957 pstrcpy(file
->filename
, sizeof(file
->filename
), (char *)tokc
.str
.data
);
1958 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1965 total_lines
+= file
->line_num
- n
;
1968 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1973 ch
= file
->buf_ptr
[0];
1976 while (ch
!= '\n' && ch
!= CH_EOF
) {
1977 if ((q
- buf
) < sizeof(buf
) - 1)
1980 if (handle_stray_noerror() == 0)
1987 tcc_error("#error %s", buf
);
1989 tcc_warning("#warning %s", buf
);
1997 /* ignore gas line comment in an 'S' file. */
1998 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
2000 if (tok
== '!' && is_bof
)
2001 /* '!' is ignored at beginning to allow C scripts. */
2003 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2005 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
2008 /* ignore other preprocess commands or #! for C scripts */
2009 while (tok
!= TOK_LINEFEED
)
2012 parse_flags
= saved_parse_flags
;
2015 /* evaluate escape codes in a string. */
2016 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2031 case '0': case '1': case '2': case '3':
2032 case '4': case '5': case '6': case '7':
2033 /* at most three octal digits */
2038 n
= n
* 8 + c
- '0';
2042 n
= n
* 8 + c
- '0';
2047 goto add_char_nonext
;
2055 if (c
>= 'a' && c
<= 'f')
2057 else if (c
>= 'A' && c
<= 'F')
2067 goto add_char_nonext
;
2091 goto invalid_escape
;
2101 if (c
>= '!' && c
<= '~')
2102 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2104 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2107 } else if (is_long
&& c
>= 0x80) {
2108 /* assume we are processing UTF-8 sequence */
2109 /* reference: The Unicode Standard, Version 10.0, ch3.9 */
2111 int cont
; /* count of continuation bytes */
2112 int skip
; /* how many bytes should skip when error occurred */
2115 /* decode leading byte */
2117 skip
= 1; goto invalid_utf8_sequence
;
2118 } else if (c
<= 0xDF) {
2119 cont
= 1; n
= c
& 0x1f;
2120 } else if (c
<= 0xEF) {
2121 cont
= 2; n
= c
& 0xf;
2122 } else if (c
<= 0xF4) {
2123 cont
= 3; n
= c
& 0x7;
2125 skip
= 1; goto invalid_utf8_sequence
;
2128 /* decode continuation bytes */
2129 for (i
= 1; i
<= cont
; i
++) {
2130 int l
= 0x80, h
= 0xBF;
2132 /* adjust limit for second byte */
2135 case 0xE0: l
= 0xA0; break;
2136 case 0xED: h
= 0x9F; break;
2137 case 0xF0: l
= 0x90; break;
2138 case 0xF4: h
= 0x8F; break;
2142 if (p
[i
] < l
|| p
[i
] > h
) {
2143 skip
= i
; goto invalid_utf8_sequence
;
2146 n
= (n
<< 6) | (p
[i
] & 0x3f);
2149 /* advance pointer */
2152 goto add_char_nonext
;
2154 /* error handling */
2155 invalid_utf8_sequence
:
2156 tcc_warning("ill-formed UTF-8 subsequence starting with: \'\\x%x\'", c
);
2159 goto add_char_nonext
;
2165 cstr_ccat(outstr
, c
);
2167 #ifdef TCC_TARGET_PE
2168 /* store as UTF-16 */
2170 cstr_wccat(outstr
, c
);
2173 cstr_wccat(outstr
, (c
>> 10) + 0xD800);
2174 cstr_wccat(outstr
, (c
& 0x3FF) + 0xDC00);
2177 cstr_wccat(outstr
, c
);
2181 /* add a trailing '\0' */
2183 cstr_ccat(outstr
, '\0');
2185 cstr_wccat(outstr
, '\0');
2188 static void parse_string(const char *s
, int len
)
2190 uint8_t buf
[1000], *p
= buf
;
2193 if ((is_long
= *s
== 'L'))
2197 if (len
>= sizeof buf
)
2198 p
= tcc_malloc(len
+ 1);
2202 cstr_reset(&tokcstr
);
2203 parse_escape_string(&tokcstr
, p
, is_long
);
2208 int char_size
, i
, n
, c
;
2209 /* XXX: make it portable */
2211 tok
= TOK_CCHAR
, char_size
= 1;
2213 tok
= TOK_LCHAR
, char_size
= sizeof(nwchar_t
);
2214 n
= tokcstr
.size
/ char_size
- 1;
2216 tcc_error("empty character constant");
2218 tcc_warning("multi-character character constant");
2219 for (c
= i
= 0; i
< n
; ++i
) {
2221 c
= ((nwchar_t
*)tokcstr
.data
)[i
];
2223 c
= (c
<< 8) | ((char *)tokcstr
.data
)[i
];
2227 tokc
.str
.size
= tokcstr
.size
;
2228 tokc
.str
.data
= tokcstr
.data
;
2236 /* we use 64 bit numbers */
2239 /* bn = (bn << shift) | or_val */
2240 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2244 for(i
=0;i
<BN_SIZE
;i
++) {
2246 bn
[i
] = (v
<< shift
) | or_val
;
2247 or_val
= v
>> (32 - shift
);
2251 static void bn_zero(unsigned int *bn
)
2254 for(i
=0;i
<BN_SIZE
;i
++) {
2259 /* parse number in null terminated string 'p' and return it in the
2261 static void parse_number(const char *p
)
2263 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2265 unsigned int bn
[BN_SIZE
];
2276 goto float_frac_parse
;
2277 } else if (t
== '0') {
2278 if (ch
== 'x' || ch
== 'X') {
2282 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2288 /* parse all digits. cannot check octal numbers at this stage
2289 because of floating point constants */
2291 if (ch
>= 'a' && ch
<= 'f')
2293 else if (ch
>= 'A' && ch
<= 'F')
2301 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2303 tcc_error("number too long");
2309 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2310 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2312 /* NOTE: strtox should support that for hexa numbers, but
2313 non ISOC99 libcs do not support it, so we prefer to do
2315 /* hexadecimal or binary floats */
2316 /* XXX: handle overflows */
2328 } else if (t
>= 'a') {
2330 } else if (t
>= 'A') {
2335 bn_lshift(bn
, shift
, t
);
2342 if (t
>= 'a' && t
<= 'f') {
2344 } else if (t
>= 'A' && t
<= 'F') {
2346 } else if (t
>= '0' && t
<= '9') {
2352 tcc_error("invalid digit");
2353 bn_lshift(bn
, shift
, t
);
2358 if (ch
!= 'p' && ch
!= 'P')
2365 } else if (ch
== '-') {
2369 if (ch
< '0' || ch
> '9')
2370 expect("exponent digits");
2371 while (ch
>= '0' && ch
<= '9') {
2372 exp_val
= exp_val
* 10 + ch
- '0';
2375 exp_val
= exp_val
* s
;
2377 /* now we can generate the number */
2378 /* XXX: should patch directly float number */
2379 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2380 d
= ldexp(d
, exp_val
- frac_bits
);
2385 /* float : should handle overflow */
2387 } else if (t
== 'L') {
2389 #ifdef TCC_TARGET_PE
2394 /* XXX: not large enough */
2395 tokc
.ld
= (long double)d
;
2402 /* decimal floats */
2404 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2409 while (ch
>= '0' && ch
<= '9') {
2410 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2416 if (ch
== 'e' || ch
== 'E') {
2417 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2421 if (ch
== '-' || ch
== '+') {
2422 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2427 if (ch
< '0' || ch
> '9')
2428 expect("exponent digits");
2429 while (ch
>= '0' && ch
<= '9') {
2430 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2442 tokc
.f
= strtof(token_buf
, NULL
);
2443 } else if (t
== 'L') {
2445 #ifdef TCC_TARGET_PE
2447 tokc
.d
= strtod(token_buf
, NULL
);
2450 tokc
.ld
= strtold(token_buf
, NULL
);
2454 tokc
.d
= strtod(token_buf
, NULL
);
2458 unsigned long long n
, n1
;
2459 int lcount
, ucount
, ov
= 0;
2462 /* integer number */
2465 if (b
== 10 && *q
== '0') {
2472 /* no need for checks except for base 10 / 8 errors */
2482 tcc_error("invalid digit");
2485 /* detect overflow */
2486 if (n1
>= 0x1000000000000000ULL
&& n
/ b
!= n1
)
2490 /* Determine the characteristics (unsigned and/or 64bit) the type of
2491 the constant must have according to the constant suffix(es) */
2492 lcount
= ucount
= 0;
2498 tcc_error("three 'l's in integer constant");
2499 if (lcount
&& *(p
- 1) != ch
)
2500 tcc_error("incorrect integer suffix: %s", p1
);
2503 } else if (t
== 'U') {
2505 tcc_error("two 'u's in integer constant");
2513 /* Determine if it needs 64 bits and/or unsigned in order to fit */
2514 if (ucount
== 0 && b
== 10) {
2515 if (lcount
<= (LONG_SIZE
== 4)) {
2516 if (n
>= 0x80000000U
)
2517 lcount
= (LONG_SIZE
== 4) + 1;
2519 if (n
>= 0x8000000000000000ULL
)
2522 if (lcount
<= (LONG_SIZE
== 4)) {
2523 if (n
>= 0x100000000ULL
)
2524 lcount
= (LONG_SIZE
== 4) + 1;
2525 else if (n
>= 0x80000000U
)
2528 if (n
>= 0x8000000000000000ULL
)
2533 tcc_warning("integer constant overflow");
2542 ++tok
; /* TOK_CU... */
2546 tcc_error("invalid number\n");
2550 #define PARSE2(c1, tok1, c2, tok2) \
2561 /* return next token without macro substitution */
2562 static inline void next_nomacro1(void)
2564 int t
, c
, is_long
, len
;
2577 if (parse_flags
& PARSE_FLAG_SPACES
)
2578 goto keep_tok_flags
;
2579 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2588 /* first look if it is in fact an end of buffer */
2589 c
= handle_stray1(p
);
2596 TCCState
*s1
= tcc_state
;
2597 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2598 && !(tok_flags
& TOK_FLAG_EOF
)) {
2599 tok_flags
|= TOK_FLAG_EOF
;
2601 goto keep_tok_flags
;
2602 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2604 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2605 tcc_error("missing #endif");
2606 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2607 /* no include left : end of file. */
2610 tok_flags
&= ~TOK_FLAG_EOF
;
2611 /* pop include file */
2613 /* test if previous '#endif' was after a #ifdef at
2615 if (tok_flags
& TOK_FLAG_ENDIF
) {
2617 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2619 search_cached_include(s1
, file
->filename
, 1)
2620 ->ifndef_macro
= file
->ifndef_macro_saved
;
2621 tok_flags
&= ~TOK_FLAG_ENDIF
;
2624 /* add end of include file debug info */
2625 if (tcc_state
->do_debug
) {
2626 put_stabd(N_EINCL
, 0, 0);
2628 /* pop include stack */
2630 s1
->include_stack_ptr
--;
2632 if (p
== file
->buffer
)
2633 tok_flags
= TOK_FLAG_BOF
|TOK_FLAG_BOL
;
2641 tok_flags
|= TOK_FLAG_BOL
;
2644 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2647 goto keep_tok_flags
;
2652 if ((tok_flags
& TOK_FLAG_BOL
) &&
2653 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2655 preprocess(tok_flags
& TOK_FLAG_BOF
);
2661 tok
= TOK_TWOSHARPS
;
2663 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2664 p
= parse_line_comment(p
- 1);
2673 /* dollar is allowed to start identifiers when not parsing asm */
2675 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2676 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2679 case 'a': case 'b': case 'c': case 'd':
2680 case 'e': case 'f': case 'g': case 'h':
2681 case 'i': case 'j': case 'k': case 'l':
2682 case 'm': case 'n': case 'o': case 'p':
2683 case 'q': case 'r': case 's': case 't':
2684 case 'u': case 'v': case 'w': case 'x':
2686 case 'A': case 'B': case 'C': case 'D':
2687 case 'E': case 'F': case 'G': case 'H':
2688 case 'I': case 'J': case 'K':
2689 case 'M': case 'N': case 'O': case 'P':
2690 case 'Q': case 'R': case 'S': case 'T':
2691 case 'U': case 'V': case 'W': case 'X':
2697 h
= TOK_HASH_FUNC(h
, c
);
2698 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2699 h
= TOK_HASH_FUNC(h
, c
);
2704 /* fast case : no stray found, so we have the full token
2705 and we have already hashed it */
2706 h
&= (TOK_HASH_SIZE
- 1);
2707 pts
= &hash_ident
[h
];
2712 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2714 pts
= &(ts
->hash_next
);
2716 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2720 cstr_reset(&tokcstr
);
2721 cstr_cat(&tokcstr
, (char *) p1
, len
);
2725 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2727 cstr_ccat(&tokcstr
, c
);
2730 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2736 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2738 goto parse_ident_fast
;
2741 if (c
== '\'' || c
== '\"') {
2745 cstr_reset(&tokcstr
);
2746 cstr_ccat(&tokcstr
, 'L');
2747 goto parse_ident_slow
;
2752 case '0': case '1': case '2': case '3':
2753 case '4': case '5': case '6': case '7':
2757 /* after the first digit, accept digits, alpha, '.' or sign if
2758 prefixed by 'eEpP' */
2760 cstr_reset(&tokcstr
);
2762 cstr_ccat(&tokcstr
, t
);
2763 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2765 || ((c
== '+' || c
== '-')
2766 && (((t
== 'e' || t
== 'E')
2767 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2768 /* 0xe+1 is 3 tokens in asm */
2769 && ((char*)tokcstr
.data
)[0] == '0'
2770 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2771 || t
== 'p' || t
== 'P'))))
2776 /* We add a trailing '\0' to ease parsing */
2777 cstr_ccat(&tokcstr
, '\0');
2778 tokc
.str
.size
= tokcstr
.size
;
2779 tokc
.str
.data
= tokcstr
.data
;
2784 /* special dot handling because it can also start a number */
2789 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2790 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2792 goto parse_ident_fast
;
2793 } else if (c
== '.') {
2799 *--p
= '.'; /* may underflow into file->unget[] */
2810 cstr_reset(&tokcstr
);
2812 cstr_ccat(&tokcstr
, 'L');
2813 cstr_ccat(&tokcstr
, c
);
2814 p
= parse_pp_string(p
, c
, &tokcstr
);
2815 cstr_ccat(&tokcstr
, c
);
2816 cstr_ccat(&tokcstr
, '\0');
2817 tokc
.str
.size
= tokcstr
.size
;
2818 tokc
.str
.data
= tokcstr
.data
;
2827 } else if (c
== '<') {
2844 } else if (c
== '>') {
2862 } else if (c
== '=') {
2875 } else if (c
== '=') {
2888 } else if (c
== '=') {
2901 } else if (c
== '=') {
2904 } else if (c
== '>') {
2912 PARSE2('!', '!', '=', TOK_NE
)
2913 PARSE2('=', '=', '=', TOK_EQ
)
2914 PARSE2('*', '*', '=', TOK_A_MUL
)
2915 PARSE2('%', '%', '=', TOK_A_MOD
)
2916 PARSE2('^', '^', '=', TOK_A_XOR
)
2918 /* comments or operator */
2922 p
= parse_comment(p
);
2923 /* comments replaced by a blank */
2925 goto keep_tok_flags
;
2926 } else if (c
== '/') {
2927 p
= parse_line_comment(p
);
2929 goto keep_tok_flags
;
2930 } else if (c
== '=') {
2950 case '@': /* only used in assembler */
2956 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
2957 goto parse_ident_fast
;
2958 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2960 tcc_error("unrecognized character \\x%02x", c
);
2966 #if defined(PARSE_DEBUG)
2967 printf("token = %d %s\n", tok
, get_tok_str(tok
, &tokc
));
2971 /* return next token without macro substitution. Can read input from
2973 static void next_nomacro_spc(void)
2979 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2980 if (tok
== TOK_LINENUM
) {
2981 file
->line_num
= tokc
.i
;
2988 //printf("token = %s\n", get_tok_str(tok, &tokc));
2991 ST_FUNC
void next_nomacro(void)
2995 } while (tok
< 256 && (isidnum_table
[tok
- CH_EOF
] & IS_SPC
));
2999 static void macro_subst(
3000 TokenString
*tok_str
,
3002 const int *macro_str
3005 /* substitute arguments in replacement lists in macro_str by the values in
3006 args (field d) and return allocated string */
3007 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
3019 TOK_GET(&t
, ¯o_str
, &cval
);
3024 TOK_GET(&t
, ¯o_str
, &cval
);
3027 s
= sym_find2(args
, t
);
3030 cstr_ccat(&cstr
, '\"');
3034 TOK_GET(&t
, &st
, &cval
);
3035 if (t
!= TOK_PLCHLDR
3037 && 0 == check_space(t
, &spc
)) {
3038 const char *s
= get_tok_str(t
, &cval
);
3040 if (t
== TOK_PPSTR
&& *s
!= '\'')
3041 add_char(&cstr
, *s
);
3043 cstr_ccat(&cstr
, *s
);
3049 cstr_ccat(&cstr
, '\"');
3050 cstr_ccat(&cstr
, '\0');
3052 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
3055 cval
.str
.size
= cstr
.size
;
3056 cval
.str
.data
= cstr
.data
;
3057 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
3061 expect("macro parameter after '#'");
3063 } else if (t
>= TOK_IDENT
) {
3064 s
= sym_find2(args
, t
);
3068 /* if '##' is present before or after, no arg substitution */
3069 if (*macro_str
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
3070 /* special case for var arg macros : ## eats the ','
3071 if empty VA_ARGS variable. */
3072 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
3074 /* suppress ',' '##' */
3077 /* suppress '##' and add variable */
3085 /* Expand arguments tokens and store them. In most
3086 cases we could also re-expand each argument if
3087 used multiple times, but not if the argument
3088 contains the __COUNTER__ macro. */
3090 sym_push2(&s
->next
, s
->v
, s
->type
.t
, 0);
3092 macro_subst(&str2
, nested_list
, st
);
3093 tok_str_add(&str2
, 0);
3094 s
->next
->d
= str2
.str
;
3100 TOK_GET(&t2
, &st
, &cval
);
3103 tok_str_add2(&str
, t2
, &cval
);
3105 if (str
.len
== l0
) /* expanded to empty string */
3106 tok_str_add(&str
, TOK_PLCHLDR
);
3108 tok_str_add(&str
, t
);
3111 tok_str_add2(&str
, t
, &cval
);
3115 tok_str_add(&str
, 0);
3119 static char const ab_month_name
[12][4] =
3121 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3122 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3125 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3131 if (t1
!= TOK_PLCHLDR
)
3132 cstr_cat(&cstr
, get_tok_str(t1
, v1
), -1);
3134 if (t2
!= TOK_PLCHLDR
)
3135 cstr_cat(&cstr
, get_tok_str(t2
, v2
), -1);
3136 cstr_ccat(&cstr
, '\0');
3138 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3139 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3143 if (0 == *file
->buf_ptr
)
3147 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3148 " preprocessing token", n
, cstr
.data
, (char*)cstr
.data
+ n
);
3153 //printf("paste <%s>\n", (char*)cstr.data);
3158 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3159 return the resulting string (which must be freed). */
3160 static inline int *macro_twosharps(const int *ptr0
)
3164 TokenString macro_str1
;
3165 int start_of_nosubsts
= -1;
3168 /* we search the first '##' */
3169 for (ptr
= ptr0
;;) {
3170 TOK_GET(&t
, &ptr
, &cval
);
3171 if (t
== TOK_PPJOIN
)
3177 tok_str_new(¯o_str1
);
3179 //tok_print(" $$$", ptr0);
3180 for (ptr
= ptr0
;;) {
3181 TOK_GET(&t
, &ptr
, &cval
);
3184 if (t
== TOK_PPJOIN
)
3186 while (*ptr
== TOK_PPJOIN
) {
3188 /* given 'a##b', remove nosubsts preceding 'a' */
3189 if (start_of_nosubsts
>= 0)
3190 macro_str1
.len
= start_of_nosubsts
;
3191 /* given 'a##b', remove nosubsts preceding 'b' */
3192 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3194 if (t1
&& t1
!= TOK_PPJOIN
) {
3195 TOK_GET(&t1
, &ptr
, &cv1
);
3196 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3197 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3198 t
= tok
, cval
= tokc
;
3200 tok_str_add2(¯o_str1
, t
, &cval
);
3206 if (t
== TOK_NOSUBST
) {
3207 if (start_of_nosubsts
< 0)
3208 start_of_nosubsts
= macro_str1
.len
;
3210 start_of_nosubsts
= -1;
3212 tok_str_add2(¯o_str1
, t
, &cval
);
3214 tok_str_add(¯o_str1
, 0);
3215 //tok_print(" ###", macro_str1.str);
3216 return macro_str1
.str
;
3219 /* peek or read [ws_str == NULL] next token from function macro call,
3220 walking up macro levels up to the file if necessary */
3221 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3229 p
= macro_ptr
, t
= *p
;
3231 while (is_space(t
) || TOK_LINEFEED
== t
|| TOK_PLCHLDR
== t
)
3232 tok_str_add(ws_str
, t
), t
= *++p
;
3236 /* also, end of scope for nested defined symbol */
3238 while (sa
&& sa
->v
== 0)
3247 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3250 uint8_t *p
= file
->buf_ptr
;
3253 p
= parse_comment(p
);
3254 file
->buf_ptr
= p
- 1;
3255 } else if (c
== '/') {
3256 p
= parse_line_comment(p
);
3257 file
->buf_ptr
= p
- 1;
3264 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3265 tok_str_add(ws_str
, ch
);
3279 /* do macro substitution of current token with macro 's' and add
3280 result to (tok_str,tok_len). 'nested_list' is the list of all
3281 macros we got inside to avoid recursing. Return non zero if no
3282 substitution needs to be done */
3283 static int macro_subst_tok(
3284 TokenString
*tok_str
,
3288 Sym
*args
, *sa
, *sa1
;
3289 int parlevel
, t
, t1
, spc
;
3296 /* if symbol is a macro, prepare substitution */
3297 /* special macros */
3298 if (tok
== TOK___LINE__
|| tok
== TOK___COUNTER__
) {
3299 t
= tok
== TOK___LINE__
? file
->line_num
: pp_counter
++;
3300 snprintf(buf
, sizeof(buf
), "%d", t
);
3304 } else if (tok
== TOK___FILE__
) {
3305 cstrval
= file
->filename
;
3307 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3312 tm
= localtime(&ti
);
3313 if (tok
== TOK___DATE__
) {
3314 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3315 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3317 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3318 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3325 cstr_cat(&cstr
, cstrval
, 0);
3326 cval
.str
.size
= cstr
.size
;
3327 cval
.str
.data
= cstr
.data
;
3328 tok_str_add2(tok_str
, t1
, &cval
);
3331 int saved_parse_flags
= parse_flags
;
3332 int *joined_str
= NULL
;
3335 if (s
->type
.t
== MACRO_FUNC
) {
3336 /* whitespace between macro name and argument list */
3338 tok_str_new(&ws_str
);
3341 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3342 | PARSE_FLAG_ACCEPT_STRAYS
;
3344 /* get next token from argument stream */
3345 t
= next_argstream(nested_list
, &ws_str
);
3347 /* not a macro substitution after all, restore the
3348 * macro token plus all whitespace we've read.
3349 * whitespace is intentionally not merged to preserve
3351 parse_flags
= saved_parse_flags
;
3352 tok_str_add(tok_str
, tok
);
3353 if (parse_flags
& PARSE_FLAG_SPACES
) {
3355 for (i
= 0; i
< ws_str
.len
; i
++)
3356 tok_str_add(tok_str
, ws_str
.str
[i
]);
3358 tok_str_free_str(ws_str
.str
);
3361 tok_str_free_str(ws_str
.str
);
3364 next_nomacro(); /* eat '(' */
3365 } while (tok
== TOK_PLCHLDR
);
3367 /* argument macro */
3370 /* NOTE: empty args are allowed, except if no args */
3373 next_argstream(nested_list
, NULL
);
3374 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3376 /* handle '()' case */
3377 if (!args
&& !sa
&& tok
== ')')
3380 tcc_error("macro '%s' used with too many args",
3381 get_tok_str(s
->v
, 0));
3384 /* NOTE: non zero sa->t indicates VA_ARGS */
3385 while ((parlevel
> 0 ||
3387 (tok
!= ',' || sa
->type
.t
)))) {
3388 if (tok
== TOK_EOF
|| tok
== 0)
3392 else if (tok
== ')')
3394 if (tok
== TOK_LINEFEED
)
3396 if (!check_space(tok
, &spc
))
3397 tok_str_add2(&str
, tok
, &tokc
);
3398 next_argstream(nested_list
, NULL
);
3403 tok_str_add(&str
, -1);
3404 tok_str_add(&str
, 0);
3405 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3409 /* special case for gcc var args: add an empty
3410 var arg argument if it is omitted */
3411 if (sa
&& sa
->type
.t
&& gnu_ext
)
3419 tcc_error("macro '%s' used with too few args",
3420 get_tok_str(s
->v
, 0));
3423 parse_flags
= saved_parse_flags
;
3425 /* now subst each arg */
3426 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3431 tok_str_free_str(sa
->d
);
3433 tok_str_free_str(sa
->next
->d
);
3441 sym_push2(nested_list
, s
->v
, 0, 0);
3442 parse_flags
= saved_parse_flags
;
3443 joined_str
= macro_twosharps(mstr
);
3444 macro_subst(tok_str
, nested_list
, joined_str
? joined_str
: mstr
);
3446 /* pop nested defined symbol */
3448 *nested_list
= sa1
->prev
;
3451 tok_str_free_str(joined_str
);
3453 tok_str_free_str(mstr
);
3458 /* do macro substitution of macro_str and add result to
3459 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3460 inside to avoid recursing. */
3461 static void macro_subst(
3462 TokenString
*tok_str
,
3464 const int *macro_str
3468 int t
, spc
, nosubst
;
3474 TOK_GET(&t
, ¯o_str
, &cval
);
3478 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3483 /* if nested substitution, do nothing */
3484 if (sym_find2(*nested_list
, t
)) {
3485 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3486 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3492 str
.str
= (int*)macro_str
;
3493 begin_macro(&str
, 2);
3496 macro_subst_tok(tok_str
, nested_list
, s
);
3498 if (str
.alloc
== 3) {
3499 /* already finished by reading function macro arguments */
3503 macro_str
= macro_ptr
;
3507 spc
= is_space(t
= tok_str
->str
[tok_str
->lastlen
]);
3509 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3510 tcc_error("stray '\\' in program");
3512 if (!check_space(t
, &spc
))
3513 tok_str_add2(tok_str
, t
, &cval
);
3516 if (nosubst
> 1 && (spc
|| (++nosubst
== 3 && t
== '(')))
3520 if (t
== TOK_NOSUBST
)
3523 /* GCC supports 'defined' as result of a macro substitution */
3524 if (t
== TOK_DEFINED
&& pp_expr
)
3529 /* return next token with macro substitution */
3530 ST_FUNC
void next(void)
3533 if (parse_flags
& PARSE_FLAG_SPACES
)
3539 if (tok
== TOK_NOSUBST
|| tok
== TOK_PLCHLDR
) {
3540 /* discard preprocessor markers */
3542 } else if (tok
== 0) {
3543 /* end of macro or unget token string */
3547 } else if (tok
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3549 /* if reading from file, try to substitute macros */
3550 s
= define_find(tok
);
3552 Sym
*nested_list
= NULL
;
3554 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3555 tok_str_add(&tokstr_buf
, 0);
3556 begin_macro(&tokstr_buf
, 2);
3560 /* convert preprocessor tokens into C tokens */
3561 if (tok
== TOK_PPNUM
) {
3562 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3563 parse_number((char *)tokc
.str
.data
);
3564 } else if (tok
== TOK_PPSTR
) {
3565 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3566 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3570 /* push back current token and set current token to 'last_tok'. Only
3571 identifier case handled for labels. */
3572 ST_INLN
void unget_tok(int last_tok
)
3575 TokenString
*str
= tok_str_alloc();
3576 tok_str_add2(str
, tok
, &tokc
);
3577 tok_str_add(str
, 0);
3578 begin_macro(str
, 1);
3582 ST_FUNC
void preprocess_start(TCCState
*s1
, int is_asm
)
3587 s1
->include_stack_ptr
= s1
->include_stack
;
3588 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3589 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3592 pp_debug_tok
= pp_debug_symv
= 0;
3594 pvtop
= vtop
= vstack
- 1;
3595 s1
->pack_stack
[0] = 0;
3596 s1
->pack_stack_ptr
= s1
->pack_stack
;
3598 set_idnum('$', s1
->dollars_in_identifiers
? IS_ID
: 0);
3599 set_idnum('.', is_asm
? IS_ID
: 0);
3602 cstr_cat(&cstr
, "\"", -1);
3603 cstr_cat(&cstr
, file
->filename
, -1);
3604 cstr_cat(&cstr
, "\"", 0);
3605 tcc_define_symbol(s1
, "__BASE_FILE__", cstr
.data
);
3608 for (i
= 0; i
< s1
->nb_cmd_include_files
; i
++) {
3609 cstr_cat(&cstr
, "#include \"", -1);
3610 cstr_cat(&cstr
, s1
->cmd_include_files
[i
], -1);
3611 cstr_cat(&cstr
, "\"\n", -1);
3614 *s1
->include_stack_ptr
++ = file
;
3615 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3616 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3621 tcc_define_symbol(s1
, "__ASSEMBLER__", NULL
);
3623 parse_flags
= is_asm
? PARSE_FLAG_ASM_FILE
: 0;
3624 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3627 /* cleanup from error/setjmp */
3628 ST_FUNC
void preprocess_end(TCCState
*s1
)
3635 ST_FUNC
void tccpp_new(TCCState
*s
)
3640 /* might be used in error() before preprocess_start() */
3641 s
->include_stack_ptr
= s
->include_stack
;
3644 /* init isid table */
3645 for(i
= CH_EOF
; i
<128; i
++)
3647 is_space(i
) ? IS_SPC
3652 for(i
= 128; i
<256; i
++)
3653 set_idnum(i
, IS_ID
);
3655 /* init allocators */
3656 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3657 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3658 tal_new(&cstr_alloc
, CSTR_TAL_LIMIT
, CSTR_TAL_SIZE
);
3660 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3661 cstr_new(&cstr_buf
);
3662 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3663 tok_str_new(&tokstr_buf
);
3664 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3666 tok_ident
= TOK_IDENT
;
3675 tok_alloc(p
, r
- p
- 1);
3680 ST_FUNC
void tccpp_delete(TCCState
*s
)
3684 /* free -D and compiler defines */
3688 n
= tok_ident
- TOK_IDENT
;
3689 for(i
= 0; i
< n
; i
++)
3690 tal_free(toksym_alloc
, table_ident
[i
]);
3691 tcc_free(table_ident
);
3694 /* free static buffers */
3695 cstr_free(&tokcstr
);
3696 cstr_free(&cstr_buf
);
3697 cstr_free(¯o_equal_buf
);
3698 tok_str_free_str(tokstr_buf
.str
);
3700 /* free allocators */
3701 tal_delete(toksym_alloc
);
3702 toksym_alloc
= NULL
;
3703 tal_delete(tokstr_alloc
);
3704 tokstr_alloc
= NULL
;
3705 tal_delete(cstr_alloc
);
3709 /* ------------------------------------------------------------------------- */
3710 /* tcc -E [-P[1]] [-dD} support */
3712 static void tok_print(const char *msg
, const int *str
)
3718 fp
= tcc_state
->ppfp
;
3719 fprintf(fp
, "%s", msg
);
3721 TOK_GET(&t
, &str
, &cval
);
3724 fprintf(fp
, " %s" + s
, get_tok_str(t
, &cval
)), s
= 1;
3729 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3731 int d
= f
->line_num
- f
->line_ref
;
3736 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3738 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3740 fputs("\n", s1
->ppfp
), --d
;
3741 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3742 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3744 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3745 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3747 f
->line_ref
= f
->line_num
;
3750 static void define_print(TCCState
*s1
, int v
)
3756 if (NULL
== s
|| NULL
== s
->d
)
3760 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3761 if (s
->type
.t
== MACRO_FUNC
) {
3766 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3773 tok_print("", s
->d
);
3776 static void pp_debug_defines(TCCState
*s1
)
3787 pp_line(s1
, file
, 0);
3788 file
->line_ref
= ++file
->line_num
;
3792 vs
= get_tok_str(v
, NULL
);
3793 if (t
== TOK_DEFINE
) {
3794 define_print(s1
, v
);
3795 } else if (t
== TOK_UNDEF
) {
3796 fprintf(fp
, "#undef %s\n", vs
);
3797 } else if (t
== TOK_push_macro
) {
3798 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3799 } else if (t
== TOK_pop_macro
) {
3800 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3805 static void pp_debug_builtins(TCCState
*s1
)
3808 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3809 define_print(s1
, v
);
3812 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3813 static int pp_need_space(int a
, int b
)
3815 return 'E' == a
? '+' == b
|| '-' == b
3816 : '+' == a
? TOK_INC
== b
|| '+' == b
3817 : '-' == a
? TOK_DEC
== b
|| '-' == b
3818 : a
>= TOK_IDENT
? b
>= TOK_IDENT
3819 : a
== TOK_PPNUM
? b
>= TOK_IDENT
3823 /* maybe hex like 0x1e */
3824 static int pp_check_he0xE(int t
, const char *p
)
3826 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3831 /* Preprocess the current file */
3832 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3834 BufferedFile
**iptr
;
3835 int token_seen
, spcs
, level
;
3839 parse_flags
= PARSE_FLAG_PREPROCESS
3840 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3841 | PARSE_FLAG_LINEFEED
3843 | PARSE_FLAG_ACCEPT_STRAYS
3845 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3846 capability to compile and run itself, provided all numbers are
3847 given as decimals. tcc -E -P10 will do. */
3848 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
3849 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
3852 /* for PP benchmarks */
3853 do next(); while (tok
!= TOK_EOF
);
3857 if (s1
->dflag
& 1) {
3858 pp_debug_builtins(s1
);
3862 token_seen
= TOK_LINEFEED
, spcs
= 0;
3863 pp_line(s1
, file
, 0);
3865 iptr
= s1
->include_stack_ptr
;
3870 level
= s1
->include_stack_ptr
- iptr
;
3873 pp_line(s1
, *iptr
, 0);
3874 pp_line(s1
, file
, level
);
3876 if (s1
->dflag
& 7) {
3877 pp_debug_defines(s1
);
3882 if (is_space(tok
)) {
3883 if (spcs
< sizeof white
- 1)
3884 white
[spcs
++] = tok
;
3886 } else if (tok
== TOK_LINEFEED
) {
3888 if (token_seen
== TOK_LINEFEED
)
3891 } else if (token_seen
== TOK_LINEFEED
) {
3892 pp_line(s1
, file
, 0);
3893 } else if (spcs
== 0 && pp_need_space(token_seen
, tok
)) {
3894 white
[spcs
++] = ' ';
3897 white
[spcs
] = 0, fputs(white
, s1
->ppfp
), spcs
= 0;
3898 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
3899 token_seen
= pp_check_he0xE(tok
, p
);
3904 /* ------------------------------------------------------------------------- */