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 void tok_print(const char *msg
, const int *str
);
54 static struct TinyAlloc
*toksym_alloc
;
55 static struct TinyAlloc
*tokstr_alloc
;
56 static struct TinyAlloc
*cstr_alloc
;
58 static TokenString
*macro_stack
;
60 static const char tcc_keywords
[] =
61 #define DEF(id, str) str "\0"
66 /* WARNING: the content of this string encodes token numbers */
67 static const unsigned char tok_two_chars
[] =
69 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
70 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
91 '.','.', 0xa8, // C++ token ?
92 '#','#', TOK_TWOSHARPS
,
96 static void next_nomacro_spc(void);
98 ST_FUNC
void skip(int c
)
101 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
105 ST_FUNC
void expect(const char *msg
)
107 tcc_error("%s expected", msg
);
110 /* ------------------------------------------------------------------------- */
111 /* Custom allocator for tiny objects */
116 #define tal_free(al, p) tcc_free(p)
117 #define tal_realloc(al, p, size) tcc_realloc(p, size)
118 #define tal_new(a,b,c)
119 #define tal_delete(a)
121 #if !defined(MEM_DEBUG)
122 #define tal_free(al, p) tal_free_impl(al, p)
123 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
124 #define TAL_DEBUG_PARAMS
127 //#define TAL_INFO 1 /* collect and dump allocators stats */
128 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
129 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
130 #define TAL_DEBUG_PARAMS , const char *file, int line
131 #define TAL_DEBUG_FILE_LEN 40
134 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
135 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
136 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
137 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
138 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
139 #define CSTR_TAL_LIMIT 1024
141 typedef struct TinyAlloc
{
147 struct TinyAlloc
*next
, *top
;
156 typedef struct tal_header_t
{
159 int line_num
; /* negative line_num used for double free check */
160 char file_name
[TAL_DEBUG_FILE_LEN
+ 1];
164 /* ------------------------------------------------------------------------- */
166 static TinyAlloc
*tal_new(TinyAlloc
**pal
, unsigned limit
, unsigned size
)
168 TinyAlloc
*al
= tcc_mallocz(sizeof(TinyAlloc
));
169 al
->p
= al
->buffer
= tcc_malloc(size
);
176 static void tal_delete(TinyAlloc
*al
)
184 fprintf(stderr
, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
185 al
->limit
, al
->size
/ 1024.0 / 1024.0, al
->nb_peak
, al
->nb_total
, al
->nb_missed
,
186 (al
->peak_p
- al
->buffer
) * 100.0 / al
->size
);
189 if (al
->nb_allocs
> 0) {
191 fprintf(stderr
, "TAL_DEBUG: memory leak %d chunk(s) (limit= %d)\n",
192 al
->nb_allocs
, al
->limit
);
195 tal_header_t
*header
= (tal_header_t
*)p
;
196 if (header
->line_num
> 0) {
197 fprintf(stderr
, "%s:%d: chunk of %d bytes leaked\n",
198 header
->file_name
, header
->line_num
, header
->size
);
200 p
+= header
->size
+ sizeof(tal_header_t
);
208 tcc_free(al
->buffer
);
214 static void tal_free_impl(TinyAlloc
*al
, void *p TAL_DEBUG_PARAMS
)
219 if (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
) {
221 tal_header_t
*header
= (((tal_header_t
*)p
) - 1);
222 if (header
->line_num
< 0) {
223 fprintf(stderr
, "%s:%d: TAL_DEBUG: double frees chunk from\n",
225 fprintf(stderr
, "%s:%d: %d bytes\n",
226 header
->file_name
, (int)-header
->line_num
, (int)header
->size
);
228 header
->line_num
= -header
->line_num
;
233 } else if (al
->next
) {
241 static void *tal_realloc_impl(TinyAlloc
**pal
, void *p
, unsigned size TAL_DEBUG_PARAMS
)
243 tal_header_t
*header
;
246 unsigned adj_size
= (size
+ 3) & -4;
247 TinyAlloc
*al
= *pal
;
250 is_own
= (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
);
251 if ((!p
|| is_own
) && size
<= al
->limit
) {
252 if (al
->p
+ adj_size
+ sizeof(tal_header_t
) < al
->buffer
+ al
->size
) {
253 header
= (tal_header_t
*)al
->p
;
254 header
->size
= adj_size
;
256 { int ofs
= strlen(file
) - TAL_DEBUG_FILE_LEN
;
257 strncpy(header
->file_name
, file
+ (ofs
> 0 ? ofs
: 0), TAL_DEBUG_FILE_LEN
);
258 header
->file_name
[TAL_DEBUG_FILE_LEN
] = 0;
259 header
->line_num
= line
; }
261 ret
= al
->p
+ sizeof(tal_header_t
);
262 al
->p
+= adj_size
+ sizeof(tal_header_t
);
264 header
= (((tal_header_t
*)p
) - 1);
265 memcpy(ret
, p
, header
->size
);
267 header
->line_num
= -header
->line_num
;
273 if (al
->nb_peak
< al
->nb_allocs
)
274 al
->nb_peak
= al
->nb_allocs
;
275 if (al
->peak_p
< al
->p
)
282 ret
= tal_realloc(*pal
, 0, size
);
283 header
= (((tal_header_t
*)p
) - 1);
284 memcpy(ret
, p
, header
->size
);
286 header
->line_num
= -header
->line_num
;
293 TinyAlloc
*bottom
= al
, *next
= al
->top
? al
->top
: al
;
295 al
= tal_new(pal
, next
->limit
, next
->size
* 2);
303 ret
= tcc_malloc(size
);
304 header
= (((tal_header_t
*)p
) - 1);
305 memcpy(ret
, p
, header
->size
);
307 header
->line_num
= -header
->line_num
;
309 } else if (al
->next
) {
313 ret
= tcc_realloc(p
, size
);
322 /* ------------------------------------------------------------------------- */
323 /* CString handling */
324 static void cstr_realloc(CString
*cstr
, int new_size
)
328 size
= cstr
->size_allocated
;
330 size
= 8; /* no need to allocate a too small first string */
331 while (size
< new_size
)
333 cstr
->data
= tal_realloc(cstr_alloc
, cstr
->data
, size
);
334 cstr
->size_allocated
= size
;
338 ST_INLN
void cstr_ccat(CString
*cstr
, int ch
)
341 size
= cstr
->size
+ 1;
342 if (size
> cstr
->size_allocated
)
343 cstr_realloc(cstr
, size
);
344 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
348 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
, int len
)
352 len
= strlen(str
) + 1 + len
;
353 size
= cstr
->size
+ len
;
354 if (size
> cstr
->size_allocated
)
355 cstr_realloc(cstr
, size
);
356 memmove(((unsigned char *)cstr
->data
) + cstr
->size
, str
, len
);
360 /* add a wide char */
361 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
364 size
= cstr
->size
+ sizeof(nwchar_t
);
365 if (size
> cstr
->size_allocated
)
366 cstr_realloc(cstr
, size
);
367 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
371 ST_FUNC
void cstr_new(CString
*cstr
)
373 memset(cstr
, 0, sizeof(CString
));
376 /* free string and reset it to NULL */
377 ST_FUNC
void cstr_free(CString
*cstr
)
379 tal_free(cstr_alloc
, cstr
->data
);
383 /* reset string to empty */
384 ST_FUNC
void cstr_reset(CString
*cstr
)
390 static void add_char(CString
*cstr
, int c
)
392 if (c
== '\'' || c
== '\"' || c
== '\\') {
393 /* XXX: could be more precise if char or string */
394 cstr_ccat(cstr
, '\\');
396 if (c
>= 32 && c
<= 126) {
399 cstr_ccat(cstr
, '\\');
401 cstr_ccat(cstr
, 'n');
403 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
404 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
405 cstr_ccat(cstr
, '0' + (c
& 7));
410 /* ------------------------------------------------------------------------- */
411 /* allocate a new token */
412 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
414 TokenSym
*ts
, **ptable
;
417 if (tok_ident
>= SYM_FIRST_ANOM
)
418 tcc_error("memory full (symbols)");
420 /* expand token table if needed */
421 i
= tok_ident
- TOK_IDENT
;
422 if ((i
% TOK_ALLOC_INCR
) == 0) {
423 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
424 table_ident
= ptable
;
427 ts
= tal_realloc(toksym_alloc
, 0, sizeof(TokenSym
) + len
);
429 ts
->tok
= tok_ident
++;
430 ts
->sym_define
= NULL
;
431 ts
->sym_label
= NULL
;
432 ts
->sym_struct
= NULL
;
433 ts
->sym_identifier
= NULL
;
435 ts
->hash_next
= NULL
;
436 memcpy(ts
->str
, str
, len
);
442 #define TOK_HASH_INIT 1
443 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
446 /* find a token and add it if not found */
447 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
455 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
456 h
&= (TOK_HASH_SIZE
- 1);
458 pts
= &hash_ident
[h
];
463 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
465 pts
= &(ts
->hash_next
);
467 return tok_alloc_new(pts
, str
, len
);
470 /* XXX: buffer overflow */
471 /* XXX: float tokens */
472 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
477 cstr_reset(&cstr_buf
);
485 /* XXX: not quite exact, but only useful for testing */
487 sprintf(p
, "%u", (unsigned)cv
->i
);
489 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
493 cstr_ccat(&cstr_buf
, 'L');
495 cstr_ccat(&cstr_buf
, '\'');
496 add_char(&cstr_buf
, cv
->i
);
497 cstr_ccat(&cstr_buf
, '\'');
498 cstr_ccat(&cstr_buf
, '\0');
502 return (char*)cv
->str
.data
;
504 cstr_ccat(&cstr_buf
, 'L');
506 cstr_ccat(&cstr_buf
, '\"');
508 len
= cv
->str
.size
- 1;
510 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
512 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
514 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
516 cstr_ccat(&cstr_buf
, '\"');
517 cstr_ccat(&cstr_buf
, '\0');
521 cstr_cat(&cstr_buf
, "<float>", 0);
524 cstr_cat(&cstr_buf
, "<double>", 0);
527 cstr_cat(&cstr_buf
, "<long double>", 0);
530 cstr_cat(&cstr_buf
, "<linenumber>", 0);
533 /* above tokens have value, the ones below don't */
541 return strcpy(p
, "...");
543 return strcpy(p
, "<<=");
545 return strcpy(p
, ">>=");
547 return strcpy(p
, "<eof>");
550 /* search in two bytes table */
551 const unsigned char *q
= tok_two_chars
;
557 return cstr_buf
.data
;
562 sprintf(cstr_buf
.data
, "<%02x>", v
);
563 return cstr_buf
.data
;
568 } else if (v
< tok_ident
) {
569 return table_ident
[v
- TOK_IDENT
]->str
;
570 } else if (v
>= SYM_FIRST_ANOM
) {
571 /* special name for anonymous symbol */
572 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
574 /* should never happen */
579 return cstr_buf
.data
;
582 /* return the current character, handling end of block if necessary
584 ST_FUNC
int handle_eob(void)
586 BufferedFile
*bf
= file
;
589 /* only tries to read if really end of buffer */
590 if (bf
->buf_ptr
>= bf
->buf_end
) {
592 #if defined(PARSE_DEBUG)
597 len
= read(bf
->fd
, bf
->buffer
, len
);
604 bf
->buf_ptr
= bf
->buffer
;
605 bf
->buf_end
= bf
->buffer
+ len
;
606 *bf
->buf_end
= CH_EOB
;
608 if (bf
->buf_ptr
< bf
->buf_end
) {
609 return bf
->buf_ptr
[0];
611 bf
->buf_ptr
= bf
->buf_end
;
616 /* read next char from current input file and handle end of input buffer */
617 ST_INLN
void inp(void)
619 ch
= *(++(file
->buf_ptr
));
620 /* end of buffer/file handling */
625 /* handle '\[\r]\n' */
626 static int handle_stray_noerror(void)
633 } else if (ch
== '\r') {
647 static void handle_stray(void)
649 if (handle_stray_noerror())
650 tcc_error("stray '\\' in program");
653 /* skip the stray and handle the \\n case. Output an error if
654 incorrect char after the stray */
655 static int handle_stray1(uint8_t *p
)
660 if (p
>= file
->buf_end
) {
667 if (handle_stray_noerror()) {
668 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
669 tcc_error("stray '\\' in program");
670 *--file
->buf_ptr
= '\\';
677 /* handle just the EOB case, but not stray */
678 #define PEEKC_EOB(c, p)\
689 /* handle the complicated stray case */
695 c = handle_stray1(p);\
700 /* input with '\[\r]\n' handling. Note that this function cannot
701 handle other characters after '\', so you cannot call it inside
702 strings or comments */
703 ST_FUNC
void minp(void)
710 /* single line C++ comments */
711 static uint8_t *parse_line_comment(uint8_t *p
)
719 if (c
== '\n' || c
== CH_EOF
) {
721 } else if (c
== '\\') {
730 } else if (c
== '\r') {
748 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
757 if (c
== '\n' || c
== '*' || c
== '\\')
761 if (c
== '\n' || c
== '*' || c
== '\\')
765 /* now we can handle all the cases */
769 } else if (c
== '*') {
775 } else if (c
== '/') {
777 } else if (c
== '\\') {
782 tcc_error("unexpected end of file in comment");
784 /* skip '\[\r]\n', otherwise just skip the stray */
790 } else if (c
== '\r') {
807 /* stray, eob or eof */
812 tcc_error("unexpected end of file in comment");
813 } else if (c
== '\\') {
823 ST_FUNC
void set_idnum(int c
, int val
)
825 isidnum_table
[c
- CH_EOF
] = val
;
830 static inline void skip_spaces(void)
832 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
836 static inline int check_space(int t
, int *spc
)
838 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
847 /* parse a string without interpreting escapes */
848 static uint8_t *parse_pp_string(uint8_t *p
,
849 int sep
, CString
*str
)
857 } else if (c
== '\\') {
863 /* XXX: indicate line number of start of string */
864 tcc_error("missing terminating %c character", sep
);
865 } else if (c
== '\\') {
866 /* escape : just skip \[\r]\n */
871 } else if (c
== '\r') {
874 expect("'\n' after '\r'");
877 } else if (c
== CH_EOF
) {
878 goto unterminated_string
;
881 cstr_ccat(str
, '\\');
887 } else if (c
== '\n') {
890 } else if (c
== '\r') {
894 cstr_ccat(str
, '\r');
910 /* skip block of text until #else, #elif or #endif. skip also pairs of
912 static void preprocess_skip(void)
914 int a
, start_of_line
, c
, in_warn_or_error
;
921 in_warn_or_error
= 0;
942 } else if (c
== '\\') {
943 ch
= file
->buf_ptr
[0];
944 handle_stray_noerror();
951 if (in_warn_or_error
)
953 p
= parse_pp_string(p
, c
, NULL
);
957 if (in_warn_or_error
)
964 p
= parse_comment(p
);
965 } else if (ch
== '/') {
966 p
= parse_line_comment(p
);
976 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
978 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
980 else if (tok
== TOK_ENDIF
)
982 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
983 in_warn_or_error
= 1;
984 else if (tok
== TOK_LINEFEED
)
986 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
987 p
= parse_line_comment(p
- 1);
988 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
989 p
= parse_line_comment(p
- 1);
1002 /* ParseState handling */
1004 /* XXX: currently, no include file info is stored. Thus, we cannot display
1005 accurate messages if the function or data definition spans multiple
1008 /* save current parse state in 's' */
1009 ST_FUNC
void save_parse_state(ParseState
*s
)
1011 s
->line_num
= file
->line_num
;
1012 s
->macro_ptr
= macro_ptr
;
1017 /* restore parse state from 's' */
1018 ST_FUNC
void restore_parse_state(ParseState
*s
)
1020 file
->line_num
= s
->line_num
;
1021 macro_ptr
= s
->macro_ptr
;
1027 /* return the number of additional 'ints' necessary to store the
1029 static inline int tok_size(const int *p
)
1044 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
1050 return 1 + LDOUBLE_SIZE
/ 4;
1057 /* token string handling */
1058 ST_INLN
void tok_str_new(TokenString
*s
)
1061 s
->len
= s
->lastlen
= 0;
1062 s
->allocated_len
= 0;
1063 s
->last_line_num
= -1;
1066 ST_FUNC TokenString
*tok_str_alloc(void)
1068 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1073 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1077 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1078 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1082 ST_FUNC
void tok_str_free_str(int *str
)
1084 tal_free(tokstr_alloc
, str
);
1087 ST_FUNC
void tok_str_free(TokenString
*str
)
1089 tok_str_free_str(str
->str
);
1090 tal_free(tokstr_alloc
, str
);
1093 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1097 size
= s
->allocated_len
;
1100 while (size
< new_size
)
1102 if (size
> s
->allocated_len
) {
1103 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1104 s
->allocated_len
= size
;
1110 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1116 if (len
>= s
->allocated_len
)
1117 str
= tok_str_realloc(s
, len
+ 1);
1122 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1125 str
->prev
= macro_stack
;
1126 str
->prev_ptr
= macro_ptr
;
1127 macro_ptr
= str
->str
;
1131 ST_FUNC
void end_macro(void)
1133 TokenString
*str
= macro_stack
;
1134 macro_stack
= str
->prev
;
1135 macro_ptr
= str
->prev_ptr
;
1136 if (str
->alloc
== 2) {
1137 str
->alloc
= 3; /* just mark as finished */
1143 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1147 len
= s
->lastlen
= s
->len
;
1150 /* allocate space for worst case */
1151 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1152 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1161 str
[len
++] = cv
->tab
[0];
1168 /* Insert the string into the int array. */
1170 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1171 if (len
+ nb_words
>= s
->allocated_len
)
1172 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1173 str
[len
] = cv
->str
.size
;
1174 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1181 #if LDOUBLE_SIZE == 8
1184 str
[len
++] = cv
->tab
[0];
1185 str
[len
++] = cv
->tab
[1];
1187 #if LDOUBLE_SIZE == 12
1189 str
[len
++] = cv
->tab
[0];
1190 str
[len
++] = cv
->tab
[1];
1191 str
[len
++] = cv
->tab
[2];
1192 #elif LDOUBLE_SIZE == 16
1194 str
[len
++] = cv
->tab
[0];
1195 str
[len
++] = cv
->tab
[1];
1196 str
[len
++] = cv
->tab
[2];
1197 str
[len
++] = cv
->tab
[3];
1198 #elif LDOUBLE_SIZE != 8
1199 #error add long double size support
1208 /* add the current parse token in token string 's' */
1209 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1213 /* save line number info */
1214 if (file
->line_num
!= s
->last_line_num
) {
1215 s
->last_line_num
= file
->line_num
;
1216 cval
.i
= s
->last_line_num
;
1217 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1219 tok_str_add2(s
, tok
, &tokc
);
1222 /* get a token from an integer array and increment pointer
1223 accordingly. we code it as a macro to avoid pointer aliasing. */
1224 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1237 cv
->i
= (*t
== TOK_CUINT
) ? (unsigned)cv
->i
: (int)cv
->i
;
1246 cv
->str
.size
= *p
++;
1248 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1256 #if LDOUBLE_SIZE == 16
1258 #elif LDOUBLE_SIZE == 12
1260 #elif LDOUBLE_SIZE == 8
1263 # error add long double size support
1276 static int macro_is_equal(const int *a
, const int *b
)
1285 /* first time preallocate macro_equal_buf, next time only reset position to start */
1286 cstr_reset(¯o_equal_buf
);
1287 TOK_GET(&t
, &a
, &cv
);
1288 cstr_cat(¯o_equal_buf
, get_tok_str(t
, &cv
), 0);
1289 TOK_GET(&t
, &b
, &cv
);
1290 if (strcmp(macro_equal_buf
.data
, get_tok_str(t
, &cv
)))
1296 /* defines handling */
1297 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1302 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1304 s
->next
= first_arg
;
1305 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1307 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1308 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1311 /* undefined a define symbol. Its name is just set to zero */
1312 ST_FUNC
void define_undef(Sym
*s
)
1315 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1316 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1319 ST_INLN Sym
*define_find(int v
)
1322 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1324 return table_ident
[v
]->sym_define
;
1327 /* free define stack until top reaches 'b' */
1328 ST_FUNC
void free_defines(Sym
*b
)
1330 while (define_stack
!= b
) {
1331 Sym
*top
= define_stack
;
1332 define_stack
= top
->prev
;
1333 tok_str_free_str(top
->d
);
1338 /* restore remaining (-D or predefined) symbols if they were
1339 #undef'd in the file */
1342 if (v
>= TOK_IDENT
&& v
< tok_ident
) {
1343 Sym
**d
= &table_ident
[v
- TOK_IDENT
]->sym_define
;
1352 ST_FUNC Sym
*label_find(int v
)
1355 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1357 return table_ident
[v
]->sym_label
;
1360 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1363 s
= sym_push2(ptop
, v
, 0, 0);
1365 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1366 if (ptop
== &global_label_stack
) {
1367 /* modify the top most local identifier, so that
1368 sym_identifier will point to 's' when popped */
1370 ps
= &(*ps
)->prev_tok
;
1377 /* pop labels until element last is reached. Look if any labels are
1378 undefined. Define symbols if '&&label' was used. */
1379 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
, int keep
)
1382 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1384 if (s
->r
== LABEL_DECLARED
) {
1385 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1386 } else if (s
->r
== LABEL_FORWARD
) {
1387 tcc_error("label '%s' used but not defined",
1388 get_tok_str(s
->v
, NULL
));
1391 /* define corresponding symbol. A size of
1393 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1397 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1405 /* eval an expression for #if/#elif */
1406 static int expr_preprocess(void)
1411 str
= tok_str_alloc();
1413 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1414 next(); /* do macro subst */
1415 if (tok
== TOK_DEFINED
) {
1420 if (tok
< TOK_IDENT
)
1421 expect("identifier");
1422 c
= define_find(tok
) != 0;
1430 } else if (tok
>= TOK_IDENT
) {
1431 /* if undefined macro */
1435 tok_str_add_tok(str
);
1438 tok_str_add(str
, -1); /* simulate end of file */
1439 tok_str_add(str
, 0);
1440 /* now evaluate C constant expression */
1441 begin_macro(str
, 1);
1449 /* parse after #define */
1450 ST_FUNC
void parse_define(void)
1452 Sym
*s
, *first
, **ps
;
1453 int v
, t
, varg
, is_vaargs
, spc
;
1454 int saved_parse_flags
= parse_flags
;
1457 if (v
< TOK_IDENT
|| v
== TOK_DEFINED
)
1458 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1459 /* XXX: should check if same macro (ANSI) */
1462 /* We have to parse the whole define as if not in asm mode, in particular
1463 no line comment with '#' must be ignored. Also for function
1464 macros the argument list must be parsed without '.' being an ID
1466 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1467 /* '(' must be just after macro definition for MACRO_FUNC */
1473 if (tok
!= ')') for (;;) {
1477 if (varg
== TOK_DOTS
) {
1478 varg
= TOK___VA_ARGS__
;
1480 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1484 if (varg
< TOK_IDENT
)
1486 tcc_error("bad macro parameter list");
1487 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1492 if (tok
!= ',' || is_vaargs
)
1502 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1503 /* The body of a macro definition should be parsed such that identifiers
1504 are parsed like the file mode determines (i.e. with '.' being an
1505 ID character in asm mode). But '#' should be retained instead of
1506 regarded as line comment leader, so still don't set ASM_FILE
1508 set_idnum('.', (saved_parse_flags
& PARSE_FLAG_ASM_FILE
) ? IS_ID
: 0);
1509 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1510 /* remove spaces around ## and after '#' */
1511 if (TOK_TWOSHARPS
== tok
) {
1518 } else if ('#' == tok
) {
1520 } else if (check_space(tok
, &spc
)) {
1523 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1528 parse_flags
= saved_parse_flags
;
1530 --tokstr_buf
.len
; /* remove trailing space */
1531 tok_str_add(&tokstr_buf
, 0);
1534 tcc_error("'##' cannot appear at either end of macro");
1535 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1538 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1540 const unsigned char *s
;
1546 s
= (unsigned char *) filename
;
1549 h
= TOK_HASH_FUNC(h
, toup(*s
));
1551 h
= TOK_HASH_FUNC(h
, *s
);
1555 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1557 i
= s1
->cached_includes_hash
[h
];
1561 e
= s1
->cached_includes
[i
- 1];
1562 if (0 == PATHCMP(e
->filename
, filename
))
1569 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1570 strcpy(e
->filename
, filename
);
1571 e
->ifndef_macro
= e
->once
= 0;
1572 dynarray_add(&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1573 /* add in hash table */
1574 e
->hash_next
= s1
->cached_includes_hash
[h
];
1575 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1577 printf("adding cached '%s'\n", filename
);
1582 static void pragma_parse(TCCState
*s1
)
1585 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1589 if (next(), tok
!= '(')
1591 if (next(), tok
!= TOK_STR
)
1593 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1594 if (next(), tok
!= ')')
1596 if (t
== TOK_push_macro
) {
1597 while (NULL
== (s
= define_find(v
)))
1598 define_push(v
, 0, NULL
, NULL
);
1599 s
->type
.ref
= s
; /* set push boundary */
1601 for (s
= define_stack
; s
; s
= s
->prev
)
1602 if (s
->v
== v
&& s
->type
.ref
== s
) {
1608 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1610 tcc_warning("unbalanced #pragma pop_macro");
1611 pp_debug_tok
= t
, pp_debug_symv
= v
;
1613 } else if (tok
== TOK_once
) {
1614 search_cached_include(s1
, file
->filename
, 1)->once
= pp_once
;
1616 } else if (s1
->ppfp
) {
1617 /* tcc -E: keep pragmas below unchanged */
1619 unget_tok(TOK_PRAGMA
);
1621 unget_tok(TOK_LINEFEED
);
1623 } else if (tok
== TOK_pack
) {
1625 #pragma pack(1) // set
1626 #pragma pack() // reset to default
1627 #pragma pack(push,1) // push & set
1628 #pragma pack(pop) // restore previous */
1631 if (tok
== TOK_ASM_pop
) {
1633 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1635 tcc_error("out of pack stack");
1637 s1
->pack_stack_ptr
--;
1641 if (tok
== TOK_ASM_push
) {
1643 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1645 s1
->pack_stack_ptr
++;
1648 if (tok
!= TOK_CINT
)
1651 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1655 *s1
->pack_stack_ptr
= val
;
1660 } else if (tok
== TOK_comment
) {
1669 p
= tcc_strdup((char *)tokc
.str
.data
);
1674 dynarray_add(&s1
->pragma_libs
, &s1
->nb_pragma_libs
, p
);
1676 if (t
== TOK_option
)
1677 tcc_set_options(s1
, p
);
1681 } else if (s1
->warn_unsupported
) {
1682 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1687 tcc_error("malformed #pragma directive");
1691 /* is_bof is true if first non space token at beginning of file */
1692 ST_FUNC
void preprocess(int is_bof
)
1694 TCCState
*s1
= tcc_state
;
1695 int i
, c
, n
, saved_parse_flags
;
1699 saved_parse_flags
= parse_flags
;
1700 parse_flags
= PARSE_FLAG_PREPROCESS
1701 | PARSE_FLAG_TOK_NUM
1702 | PARSE_FLAG_TOK_STR
1703 | PARSE_FLAG_LINEFEED
1704 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1713 pp_debug_symv
= tok
;
1719 pp_debug_symv
= tok
;
1720 s
= define_find(tok
);
1721 /* undefine symbol by putting an invalid name */
1726 case TOK_INCLUDE_NEXT
:
1727 ch
= file
->buf_ptr
[0];
1728 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1733 } else if (ch
== '\"') {
1738 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1739 if ((q
- buf
) < sizeof(buf
) - 1)
1742 if (handle_stray_noerror() == 0)
1750 /* eat all spaces and comments after include */
1751 /* XXX: slightly incorrect */
1752 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1757 /* computed #include : concatenate everything up to linefeed,
1758 the result must be one of the two accepted forms.
1759 Don't convert pp-tokens to tokens here. */
1760 parse_flags
= (PARSE_FLAG_PREPROCESS
1761 | PARSE_FLAG_LINEFEED
1762 | (parse_flags
& PARSE_FLAG_ASM_FILE
));
1765 while (tok
!= TOK_LINEFEED
) {
1766 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1770 /* check syntax and remove '<>|""' */
1771 if ((len
< 2 || ((buf
[0] != '"' || buf
[len
-1] != '"') &&
1772 (buf
[0] != '<' || buf
[len
-1] != '>'))))
1773 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1775 memmove(buf
, buf
+ 1, len
- 2);
1776 buf
[len
- 2] = '\0';
1779 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1780 tcc_error("#include recursion too deep");
1781 /* store current file in stack, but increment stack later below */
1782 *s1
->include_stack_ptr
= file
;
1783 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
: 0;
1784 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1785 for (; i
< n
; ++i
) {
1786 char buf1
[sizeof file
->filename
];
1791 /* check absolute include path */
1792 if (!IS_ABSPATH(buf
))
1796 } else if (i
== 1) {
1797 /* search in file's dir if "header.h" */
1800 /* https://savannah.nongnu.org/bugs/index.php?50847 */
1801 path
= file
->true_filename
;
1802 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1805 /* search in all the include paths */
1806 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1807 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1808 pstrcpy(buf1
, sizeof(buf1
), path
);
1809 pstrcat(buf1
, sizeof(buf1
), "/");
1812 pstrcat(buf1
, sizeof(buf1
), buf
);
1813 e
= search_cached_include(s1
, buf1
, 0);
1814 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
== pp_once
)) {
1815 /* no need to parse the include because the 'ifndef macro'
1816 is defined (or had #pragma once) */
1818 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1823 if (tcc_open(s1
, buf1
) < 0)
1826 file
->include_next_index
= i
+ 1;
1828 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1830 /* update target deps */
1831 dynarray_add(&s1
->target_deps
, &s1
->nb_target_deps
,
1833 /* push current file in stack */
1834 ++s1
->include_stack_ptr
;
1835 /* add include file debug info */
1837 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1838 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1839 ch
= file
->buf_ptr
[0];
1842 tcc_error("include file '%s' not found", buf
);
1849 c
= expr_preprocess();
1855 if (tok
< TOK_IDENT
)
1856 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1860 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1862 file
->ifndef_macro
= tok
;
1865 c
= (define_find(tok
) != 0) ^ c
;
1867 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1868 tcc_error("memory full (ifdef)");
1869 *s1
->ifdef_stack_ptr
++ = c
;
1872 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1873 tcc_error("#else without matching #if");
1874 if (s1
->ifdef_stack_ptr
[-1] & 2)
1875 tcc_error("#else after #else");
1876 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1879 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1880 tcc_error("#elif without matching #if");
1881 c
= s1
->ifdef_stack_ptr
[-1];
1883 tcc_error("#elif after #else");
1884 /* last #if/#elif expression was true: we skip */
1888 c
= expr_preprocess();
1889 s1
->ifdef_stack_ptr
[-1] = c
;
1892 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1893 file
->ifndef_macro
= 0;
1902 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1903 tcc_error("#endif without matching #if");
1904 s1
->ifdef_stack_ptr
--;
1905 /* '#ifndef macro' was at the start of file. Now we check if
1906 an '#endif' is exactly at the end of file */
1907 if (file
->ifndef_macro
&&
1908 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1909 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1910 /* need to set to zero to avoid false matches if another
1911 #ifndef at middle of file */
1912 file
->ifndef_macro
= 0;
1913 while (tok
!= TOK_LINEFEED
)
1915 tok_flags
|= TOK_FLAG_ENDIF
;
1920 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1924 if (tok
!= TOK_CINT
)
1926 tcc_error("wrong #line format");
1930 if (tok
!= TOK_LINEFEED
) {
1931 if (tok
== TOK_STR
) {
1932 if (file
->true_filename
== file
->filename
)
1933 file
->true_filename
= tcc_strdup(file
->filename
);
1934 pstrcpy(file
->filename
, sizeof(file
->filename
), (char *)tokc
.str
.data
);
1935 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1942 total_lines
+= file
->line_num
- n
;
1945 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1950 ch
= file
->buf_ptr
[0];
1953 while (ch
!= '\n' && ch
!= CH_EOF
) {
1954 if ((q
- buf
) < sizeof(buf
) - 1)
1957 if (handle_stray_noerror() == 0)
1964 tcc_error("#error %s", buf
);
1966 tcc_warning("#warning %s", buf
);
1974 /* ignore gas line comment in an 'S' file. */
1975 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
1977 if (tok
== '!' && is_bof
)
1978 /* '!' is ignored at beginning to allow C scripts. */
1980 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1982 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
1985 /* ignore other preprocess commands or #! for C scripts */
1986 while (tok
!= TOK_LINEFEED
)
1989 parse_flags
= saved_parse_flags
;
1992 /* evaluate escape codes in a string. */
1993 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2008 case '0': case '1': case '2': case '3':
2009 case '4': case '5': case '6': case '7':
2010 /* at most three octal digits */
2015 n
= n
* 8 + c
- '0';
2019 n
= n
* 8 + c
- '0';
2024 goto add_char_nonext
;
2032 if (c
>= 'a' && c
<= 'f')
2034 else if (c
>= 'A' && c
<= 'F')
2044 goto add_char_nonext
;
2068 goto invalid_escape
;
2078 if (c
>= '!' && c
<= '~')
2079 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2081 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2088 cstr_ccat(outstr
, c
);
2090 cstr_wccat(outstr
, c
);
2092 /* add a trailing '\0' */
2094 cstr_ccat(outstr
, '\0');
2096 cstr_wccat(outstr
, '\0');
2099 static void parse_string(const char *s
, int len
)
2101 uint8_t buf
[1000], *p
= buf
;
2104 if ((is_long
= *s
== 'L'))
2108 if (len
>= sizeof buf
)
2109 p
= tcc_malloc(len
+ 1);
2113 cstr_reset(&tokcstr
);
2114 parse_escape_string(&tokcstr
, p
, is_long
);
2120 /* XXX: make it portable */
2124 char_size
= sizeof(nwchar_t
);
2125 if (tokcstr
.size
<= char_size
)
2126 tcc_error("empty character constant");
2127 if (tokcstr
.size
> 2 * char_size
)
2128 tcc_warning("multi-character character constant");
2130 tokc
.i
= *(int8_t *)tokcstr
.data
;
2133 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2137 tokc
.str
.size
= tokcstr
.size
;
2138 tokc
.str
.data
= tokcstr
.data
;
2146 /* we use 64 bit numbers */
2149 /* bn = (bn << shift) | or_val */
2150 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2154 for(i
=0;i
<BN_SIZE
;i
++) {
2156 bn
[i
] = (v
<< shift
) | or_val
;
2157 or_val
= v
>> (32 - shift
);
2161 static void bn_zero(unsigned int *bn
)
2164 for(i
=0;i
<BN_SIZE
;i
++) {
2169 /* parse number in null terminated string 'p' and return it in the
2171 static void parse_number(const char *p
)
2173 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2175 unsigned int bn
[BN_SIZE
];
2186 goto float_frac_parse
;
2187 } else if (t
== '0') {
2188 if (ch
== 'x' || ch
== 'X') {
2192 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2198 /* parse all digits. cannot check octal numbers at this stage
2199 because of floating point constants */
2201 if (ch
>= 'a' && ch
<= 'f')
2203 else if (ch
>= 'A' && ch
<= 'F')
2211 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2213 tcc_error("number too long");
2219 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2220 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2222 /* NOTE: strtox should support that for hexa numbers, but
2223 non ISOC99 libcs do not support it, so we prefer to do
2225 /* hexadecimal or binary floats */
2226 /* XXX: handle overflows */
2238 } else if (t
>= 'a') {
2240 } else if (t
>= 'A') {
2245 bn_lshift(bn
, shift
, t
);
2252 if (t
>= 'a' && t
<= 'f') {
2254 } else if (t
>= 'A' && t
<= 'F') {
2256 } else if (t
>= '0' && t
<= '9') {
2262 tcc_error("invalid digit");
2263 bn_lshift(bn
, shift
, t
);
2268 if (ch
!= 'p' && ch
!= 'P')
2275 } else if (ch
== '-') {
2279 if (ch
< '0' || ch
> '9')
2280 expect("exponent digits");
2281 while (ch
>= '0' && ch
<= '9') {
2282 exp_val
= exp_val
* 10 + ch
- '0';
2285 exp_val
= exp_val
* s
;
2287 /* now we can generate the number */
2288 /* XXX: should patch directly float number */
2289 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2290 d
= ldexp(d
, exp_val
- frac_bits
);
2295 /* float : should handle overflow */
2297 } else if (t
== 'L') {
2299 #ifdef TCC_TARGET_PE
2304 /* XXX: not large enough */
2305 tokc
.ld
= (long double)d
;
2312 /* decimal floats */
2314 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2319 while (ch
>= '0' && ch
<= '9') {
2320 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2326 if (ch
== 'e' || ch
== 'E') {
2327 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2331 if (ch
== '-' || ch
== '+') {
2332 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2337 if (ch
< '0' || ch
> '9')
2338 expect("exponent digits");
2339 while (ch
>= '0' && ch
<= '9') {
2340 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2352 tokc
.f
= strtof(token_buf
, NULL
);
2353 } else if (t
== 'L') {
2355 #ifdef TCC_TARGET_PE
2357 tokc
.d
= strtod(token_buf
, NULL
);
2360 tokc
.ld
= strtold(token_buf
, NULL
);
2364 tokc
.d
= strtod(token_buf
, NULL
);
2368 unsigned long long n
, n1
;
2369 int lcount
, ucount
, must_64bit
;
2372 /* integer number */
2375 if (b
== 10 && *q
== '0') {
2382 /* no need for checks except for base 10 / 8 errors */
2392 tcc_error("invalid digit");
2395 /* detect overflow */
2396 /* XXX: this test is not reliable */
2398 tcc_error("integer constant overflow");
2401 /* Determine the characteristics (unsigned and/or 64bit) the type of
2402 the constant must have according to the constant suffix(es) */
2403 lcount
= ucount
= must_64bit
= 0;
2409 tcc_error("three 'l's in integer constant");
2410 if (lcount
&& *(p
- 1) != ch
)
2411 tcc_error("incorrect integer suffix: %s", p1
);
2413 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2418 } else if (t
== 'U') {
2420 tcc_error("two 'u's in integer constant");
2428 /* Whether 64 bits are needed to hold the constant's value */
2429 if (n
& 0xffffffff00000000LL
|| must_64bit
) {
2437 /* Whether type must be unsigned to hold the constant's value */
2438 if (ucount
|| ((n1
>> 31) && (b
!= 10))) {
2439 if (tok
== TOK_CLLONG
)
2443 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2444 } else if (n1
>> 31) {
2445 if (tok
== TOK_CINT
)
2448 tcc_error("integer constant overflow");
2454 tcc_error("invalid number\n");
2458 #define PARSE2(c1, tok1, c2, tok2) \
2469 /* return next token without macro substitution */
2470 static inline void next_nomacro1(void)
2472 int t
, c
, is_long
, len
;
2485 if (parse_flags
& PARSE_FLAG_SPACES
)
2486 goto keep_tok_flags
;
2487 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2496 /* first look if it is in fact an end of buffer */
2497 c
= handle_stray1(p
);
2504 TCCState
*s1
= tcc_state
;
2505 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2506 && !(tok_flags
& TOK_FLAG_EOF
)) {
2507 tok_flags
|= TOK_FLAG_EOF
;
2509 goto keep_tok_flags
;
2510 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2512 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2513 tcc_error("missing #endif");
2514 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2515 /* no include left : end of file. */
2518 tok_flags
&= ~TOK_FLAG_EOF
;
2519 /* pop include file */
2521 /* test if previous '#endif' was after a #ifdef at
2523 if (tok_flags
& TOK_FLAG_ENDIF
) {
2525 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2527 search_cached_include(s1
, file
->filename
, 1)
2528 ->ifndef_macro
= file
->ifndef_macro_saved
;
2529 tok_flags
&= ~TOK_FLAG_ENDIF
;
2532 /* add end of include file debug info */
2533 if (tcc_state
->do_debug
) {
2534 put_stabd(N_EINCL
, 0, 0);
2536 /* pop include stack */
2538 s1
->include_stack_ptr
--;
2547 tok_flags
|= TOK_FLAG_BOL
;
2550 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2553 goto keep_tok_flags
;
2558 if ((tok_flags
& TOK_FLAG_BOL
) &&
2559 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2561 preprocess(tok_flags
& TOK_FLAG_BOF
);
2567 tok
= TOK_TWOSHARPS
;
2569 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2570 p
= parse_line_comment(p
- 1);
2579 /* dollar is allowed to start identifiers when not parsing asm */
2581 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2582 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2585 case 'a': case 'b': case 'c': case 'd':
2586 case 'e': case 'f': case 'g': case 'h':
2587 case 'i': case 'j': case 'k': case 'l':
2588 case 'm': case 'n': case 'o': case 'p':
2589 case 'q': case 'r': case 's': case 't':
2590 case 'u': case 'v': case 'w': case 'x':
2592 case 'A': case 'B': case 'C': case 'D':
2593 case 'E': case 'F': case 'G': case 'H':
2594 case 'I': case 'J': case 'K':
2595 case 'M': case 'N': case 'O': case 'P':
2596 case 'Q': case 'R': case 'S': case 'T':
2597 case 'U': case 'V': case 'W': case 'X':
2603 h
= TOK_HASH_FUNC(h
, c
);
2604 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2605 h
= TOK_HASH_FUNC(h
, c
);
2610 /* fast case : no stray found, so we have the full token
2611 and we have already hashed it */
2612 h
&= (TOK_HASH_SIZE
- 1);
2613 pts
= &hash_ident
[h
];
2618 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2620 pts
= &(ts
->hash_next
);
2622 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2626 cstr_reset(&tokcstr
);
2627 cstr_cat(&tokcstr
, (char *) p1
, len
);
2631 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2633 cstr_ccat(&tokcstr
, c
);
2636 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2642 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2644 goto parse_ident_fast
;
2647 if (c
== '\'' || c
== '\"') {
2651 cstr_reset(&tokcstr
);
2652 cstr_ccat(&tokcstr
, 'L');
2653 goto parse_ident_slow
;
2658 case '0': case '1': case '2': case '3':
2659 case '4': case '5': case '6': case '7':
2663 /* after the first digit, accept digits, alpha, '.' or sign if
2664 prefixed by 'eEpP' */
2666 cstr_reset(&tokcstr
);
2668 cstr_ccat(&tokcstr
, t
);
2669 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2671 || ((c
== '+' || c
== '-')
2672 && (((t
== 'e' || t
== 'E')
2673 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2674 /* 0xe+1 is 3 tokens in asm */
2675 && ((char*)tokcstr
.data
)[0] == '0'
2676 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2677 || t
== 'p' || t
== 'P'))))
2682 /* We add a trailing '\0' to ease parsing */
2683 cstr_ccat(&tokcstr
, '\0');
2684 tokc
.str
.size
= tokcstr
.size
;
2685 tokc
.str
.data
= tokcstr
.data
;
2690 /* special dot handling because it can also start a number */
2695 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2696 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2698 goto parse_ident_fast
;
2699 } else if (c
== '.') {
2705 *--p
= '.'; /* may underflow into file->unget[] */
2716 cstr_reset(&tokcstr
);
2718 cstr_ccat(&tokcstr
, 'L');
2719 cstr_ccat(&tokcstr
, c
);
2720 p
= parse_pp_string(p
, c
, &tokcstr
);
2721 cstr_ccat(&tokcstr
, c
);
2722 cstr_ccat(&tokcstr
, '\0');
2723 tokc
.str
.size
= tokcstr
.size
;
2724 tokc
.str
.data
= tokcstr
.data
;
2733 } else if (c
== '<') {
2750 } else if (c
== '>') {
2768 } else if (c
== '=') {
2781 } else if (c
== '=') {
2794 } else if (c
== '=') {
2807 } else if (c
== '=') {
2810 } else if (c
== '>') {
2818 PARSE2('!', '!', '=', TOK_NE
)
2819 PARSE2('=', '=', '=', TOK_EQ
)
2820 PARSE2('*', '*', '=', TOK_A_MUL
)
2821 PARSE2('%', '%', '=', TOK_A_MOD
)
2822 PARSE2('^', '^', '=', TOK_A_XOR
)
2824 /* comments or operator */
2828 p
= parse_comment(p
);
2829 /* comments replaced by a blank */
2831 goto keep_tok_flags
;
2832 } else if (c
== '/') {
2833 p
= parse_line_comment(p
);
2835 goto keep_tok_flags
;
2836 } else if (c
== '=') {
2856 case '@': /* only used in assembler */
2862 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
2863 goto parse_ident_fast
;
2864 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2866 tcc_error("unrecognized character \\x%02x", c
);
2872 #if defined(PARSE_DEBUG)
2873 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2877 /* return next token without macro substitution. Can read input from
2879 static void next_nomacro_spc(void)
2885 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2886 if (tok
== TOK_LINENUM
) {
2887 file
->line_num
= tokc
.i
;
2894 //printf("token = %s\n", get_tok_str(tok, &tokc));
2897 ST_FUNC
void next_nomacro(void)
2901 } while (tok
< 256 && (isidnum_table
[tok
- CH_EOF
] & IS_SPC
));
2905 static void macro_subst(
2906 TokenString
*tok_str
,
2908 const int *macro_str
2911 /* substitute arguments in replacement lists in macro_str by the values in
2912 args (field d) and return allocated string */
2913 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2925 TOK_GET(&t
, ¯o_str
, &cval
);
2930 TOK_GET(&t
, ¯o_str
, &cval
);
2933 s
= sym_find2(args
, t
);
2936 cstr_ccat(&cstr
, '\"');
2940 TOK_GET(&t
, &st
, &cval
);
2941 if (t
!= TOK_PLCHLDR
2943 && 0 == check_space(t
, &spc
)) {
2944 const char *s
= get_tok_str(t
, &cval
);
2946 if (t
== TOK_PPSTR
&& *s
!= '\'')
2947 add_char(&cstr
, *s
);
2949 cstr_ccat(&cstr
, *s
);
2955 cstr_ccat(&cstr
, '\"');
2956 cstr_ccat(&cstr
, '\0');
2958 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
2961 cval
.str
.size
= cstr
.size
;
2962 cval
.str
.data
= cstr
.data
;
2963 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
2967 expect("macro parameter after '#'");
2969 } else if (t
>= TOK_IDENT
) {
2970 s
= sym_find2(args
, t
);
2974 /* if '##' is present before or after, no arg substitution */
2975 if (*macro_str
== TOK_PPJOIN
|| t1
== TOK_PPJOIN
) {
2976 /* special case for var arg macros : ## eats the ','
2977 if empty VA_ARGS variable. */
2978 if (t1
== TOK_PPJOIN
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
2980 /* suppress ',' '##' */
2983 /* suppress '##' and add variable */
2991 /* Expand arguments tokens and store them. In most
2992 cases we could also re-expand each argument if
2993 used multiple times, but not if the argument
2994 contains the __COUNTER__ macro. */
2996 sym_push2(&s
->next
, s
->v
, s
->type
.t
, 0);
2998 macro_subst(&str2
, nested_list
, st
);
2999 tok_str_add(&str2
, 0);
3000 s
->next
->d
= str2
.str
;
3006 TOK_GET(&t2
, &st
, &cval
);
3009 tok_str_add2(&str
, t2
, &cval
);
3011 if (str
.len
== l0
) /* expanded to empty string */
3012 tok_str_add(&str
, TOK_PLCHLDR
);
3014 tok_str_add(&str
, t
);
3017 tok_str_add2(&str
, t
, &cval
);
3021 tok_str_add(&str
, 0);
3025 static char const ab_month_name
[12][4] =
3027 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3028 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3031 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3037 if (t1
!= TOK_PLCHLDR
)
3038 cstr_cat(&cstr
, get_tok_str(t1
, v1
), -1);
3040 if (t2
!= TOK_PLCHLDR
)
3041 cstr_cat(&cstr
, get_tok_str(t2
, v2
), -1);
3042 cstr_ccat(&cstr
, '\0');
3044 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3045 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3048 if (0 == *file
->buf_ptr
)
3052 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3053 " preprocessing token", n
, cstr
.data
, (char*)cstr
.data
+ n
);
3058 //printf("paste <%s>\n", (char*)cstr.data);
3063 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3064 return the resulting string (which must be freed). */
3065 static inline int *macro_twosharps(const int *ptr0
)
3069 TokenString macro_str1
;
3070 int start_of_nosubsts
= -1;
3073 /* we search the first '##' */
3074 for (ptr
= ptr0
;;) {
3075 TOK_GET(&t
, &ptr
, &cval
);
3076 if (t
== TOK_PPJOIN
)
3082 tok_str_new(¯o_str1
);
3084 //tok_print(" $$$", ptr0);
3085 for (ptr
= ptr0
;;) {
3086 TOK_GET(&t
, &ptr
, &cval
);
3089 if (t
== TOK_PPJOIN
)
3091 while (*ptr
== TOK_PPJOIN
) {
3093 /* given 'a##b', remove nosubsts preceding 'a' */
3094 if (start_of_nosubsts
>= 0)
3095 macro_str1
.len
= start_of_nosubsts
;
3096 /* given 'a##b', remove nosubsts preceding 'b' */
3097 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3099 if (t1
&& t1
!= TOK_PPJOIN
) {
3100 TOK_GET(&t1
, &ptr
, &cv1
);
3101 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3102 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3103 t
= tok
, cval
= tokc
;
3105 tok_str_add2(¯o_str1
, t
, &cval
);
3111 if (t
== TOK_NOSUBST
) {
3112 if (start_of_nosubsts
< 0)
3113 start_of_nosubsts
= macro_str1
.len
;
3115 start_of_nosubsts
= -1;
3117 tok_str_add2(¯o_str1
, t
, &cval
);
3119 tok_str_add(¯o_str1
, 0);
3120 //tok_print(" ###", macro_str1.str);
3121 return macro_str1
.str
;
3124 /* peek or read [ws_str == NULL] next token from function macro call,
3125 walking up macro levels up to the file if necessary */
3126 static int next_argstream(Sym
**nested_list
, TokenString
*ws_str
)
3134 p
= macro_ptr
, t
= *p
;
3136 while (is_space(t
) || TOK_LINEFEED
== t
|| TOK_PLCHLDR
== t
)
3137 tok_str_add(ws_str
, t
), t
= *++p
;
3141 /* also, end of scope for nested defined symbol */
3143 while (sa
&& sa
->v
== 0)
3152 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3155 uint8_t *p
= file
->buf_ptr
;
3158 p
= parse_comment(p
);
3159 file
->buf_ptr
= p
- 1;
3160 } else if (c
== '/') {
3161 p
= parse_line_comment(p
);
3162 file
->buf_ptr
= p
- 1;
3167 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3168 tok_str_add(ws_str
, ch
);
3182 /* do macro substitution of current token with macro 's' and add
3183 result to (tok_str,tok_len). 'nested_list' is the list of all
3184 macros we got inside to avoid recursing. Return non zero if no
3185 substitution needs to be done */
3186 static int macro_subst_tok(
3187 TokenString
*tok_str
,
3191 Sym
*args
, *sa
, *sa1
;
3192 int parlevel
, *mstr
, t
, t1
, spc
;
3200 /* if symbol is a macro, prepare substitution */
3201 /* special macros */
3202 if (tok
== TOK___LINE__
|| tok
== TOK___COUNTER__
) {
3203 t
= tok
== TOK___LINE__
? file
->line_num
: counter
++;
3204 snprintf(buf
, sizeof(buf
), "%d", t
);
3208 } else if (tok
== TOK___FILE__
) {
3209 cstrval
= file
->filename
;
3211 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3216 tm
= localtime(&ti
);
3217 if (tok
== TOK___DATE__
) {
3218 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3219 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3221 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3222 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3229 cstr_cat(&cstr
, cstrval
, 0);
3230 cval
.str
.size
= cstr
.size
;
3231 cval
.str
.data
= cstr
.data
;
3232 tok_str_add2(tok_str
, t1
, &cval
);
3235 int saved_parse_flags
= parse_flags
;
3236 int *joined_str
= NULL
;
3239 if (s
->type
.t
== MACRO_FUNC
) {
3240 /* whitespace between macro name and argument list */
3242 tok_str_new(&ws_str
);
3245 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3246 | PARSE_FLAG_ACCEPT_STRAYS
;
3248 /* get next token from argument stream */
3249 t
= next_argstream(nested_list
, &ws_str
);
3251 /* not a macro substitution after all, restore the
3252 * macro token plus all whitespace we've read.
3253 * whitespace is intentionally not merged to preserve
3255 parse_flags
= saved_parse_flags
;
3256 tok_str_add(tok_str
, tok
);
3257 if (parse_flags
& PARSE_FLAG_SPACES
) {
3259 for (i
= 0; i
< ws_str
.len
; i
++)
3260 tok_str_add(tok_str
, ws_str
.str
[i
]);
3262 tok_str_free_str(ws_str
.str
);
3265 tok_str_free_str(ws_str
.str
);
3268 next_nomacro(); /* eat '(' */
3269 } while (tok
== TOK_PLCHLDR
);
3271 /* argument macro */
3274 /* NOTE: empty args are allowed, except if no args */
3277 next_argstream(nested_list
, NULL
);
3278 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3280 /* handle '()' case */
3281 if (!args
&& !sa
&& tok
== ')')
3284 tcc_error("macro '%s' used with too many args",
3285 get_tok_str(s
->v
, 0));
3288 /* NOTE: non zero sa->t indicates VA_ARGS */
3289 while ((parlevel
> 0 ||
3291 (tok
!= ',' || sa
->type
.t
)))) {
3292 if (tok
== TOK_EOF
|| tok
== 0)
3296 else if (tok
== ')')
3298 if (tok
== TOK_LINEFEED
)
3300 if (!check_space(tok
, &spc
))
3301 tok_str_add2(&str
, tok
, &tokc
);
3302 next_argstream(nested_list
, NULL
);
3307 tok_str_add(&str
, -1);
3308 tok_str_add(&str
, 0);
3309 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3313 /* special case for gcc var args: add an empty
3314 var arg argument if it is omitted */
3315 if (sa
&& sa
->type
.t
&& gnu_ext
)
3323 tcc_error("macro '%s' used with too few args",
3324 get_tok_str(s
->v
, 0));
3327 parse_flags
= saved_parse_flags
;
3329 /* now subst each arg */
3330 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3335 tok_str_free_str(sa
->d
);
3337 tok_str_free_str(sa
->next
->d
);
3345 sym_push2(nested_list
, s
->v
, 0, 0);
3346 parse_flags
= saved_parse_flags
;
3347 joined_str
= macro_twosharps(mstr
);
3348 macro_subst(tok_str
, nested_list
, joined_str
? joined_str
: mstr
);
3350 /* pop nested defined symbol */
3352 *nested_list
= sa1
->prev
;
3355 tok_str_free_str(joined_str
);
3357 tok_str_free_str(mstr
);
3362 /* do macro substitution of macro_str and add result to
3363 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3364 inside to avoid recursing. */
3365 static void macro_subst(
3366 TokenString
*tok_str
,
3368 const int *macro_str
3372 int t
, spc
, nosubst
;
3378 TOK_GET(&t
, ¯o_str
, &cval
);
3382 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3387 /* if nested substitution, do nothing */
3388 if (sym_find2(*nested_list
, t
)) {
3389 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3390 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3396 str
.str
= (int*)macro_str
;
3397 begin_macro(&str
, 2);
3400 macro_subst_tok(tok_str
, nested_list
, s
);
3402 if (str
.alloc
== 3) {
3403 /* already finished by reading function macro arguments */
3407 macro_str
= macro_ptr
;
3411 spc
= is_space(t
= tok_str
->str
[tok_str
->lastlen
]);
3413 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3414 tcc_error("stray '\\' in program");
3416 if (!check_space(t
, &spc
))
3417 tok_str_add2(tok_str
, t
, &cval
);
3420 if (nosubst
> 1 && (spc
|| (++nosubst
== 3 && t
== '(')))
3424 if (t
== TOK_NOSUBST
)
3427 /* GCC supports 'defined' as result of a macto substitution */
3428 if (t
== TOK_DEFINED
&& pp_expr
)
3433 /* return next token with macro substitution */
3434 ST_FUNC
void next(void)
3437 if (parse_flags
& PARSE_FLAG_SPACES
)
3443 if (tok
== TOK_NOSUBST
|| tok
== TOK_PLCHLDR
) {
3444 /* discard preprocessor markers */
3446 } else if (tok
== 0) {
3447 /* end of macro or unget token string */
3451 } else if (tok
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3453 /* if reading from file, try to substitute macros */
3454 s
= define_find(tok
);
3456 Sym
*nested_list
= NULL
;
3458 macro_subst_tok(&tokstr_buf
, &nested_list
, s
);
3459 tok_str_add(&tokstr_buf
, 0);
3460 begin_macro(&tokstr_buf
, 2);
3464 /* convert preprocessor tokens into C tokens */
3465 if (tok
== TOK_PPNUM
) {
3466 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3467 parse_number((char *)tokc
.str
.data
);
3468 } else if (tok
== TOK_PPSTR
) {
3469 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3470 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3474 /* push back current token and set current token to 'last_tok'. Only
3475 identifier case handled for labels. */
3476 ST_INLN
void unget_tok(int last_tok
)
3479 TokenString
*str
= tok_str_alloc();
3480 tok_str_add2(str
, tok
, &tokc
);
3481 tok_str_add(str
, 0);
3482 begin_macro(str
, 1);
3486 ST_FUNC
void preprocess_start(TCCState
*s1
)
3490 s1
->include_stack_ptr
= s1
->include_stack
;
3491 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3492 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3494 pvtop
= vtop
= vstack
- 1;
3495 s1
->pack_stack
[0] = 0;
3496 s1
->pack_stack_ptr
= s1
->pack_stack
;
3498 set_idnum('$', s1
->dollars_in_identifiers
? IS_ID
: 0);
3499 set_idnum('.', (parse_flags
& PARSE_FLAG_ASM_FILE
) ? IS_ID
: 0);
3501 buf
= tcc_malloc(3 + strlen(file
->filename
));
3502 sprintf(buf
, "\"%s\"", file
->filename
);
3503 tcc_define_symbol(s1
, "__BASE_FILE__", buf
);
3506 if (s1
->nb_cmd_include_files
) {
3510 for (i
= 0; i
< s1
->nb_cmd_include_files
; i
++) {
3511 cstr_cat(&cstr
, "#include \"", -1);
3512 cstr_cat(&cstr
, s1
->cmd_include_files
[i
], -1);
3513 cstr_cat(&cstr
, "\"\n", -1);
3515 *s1
->include_stack_ptr
++ = file
;
3516 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3517 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3522 ST_FUNC
void tccpp_new(TCCState
*s
)
3527 /* might be used in error() before preprocess_start() */
3528 s
->include_stack_ptr
= s
->include_stack
;
3530 /* init isid table */
3531 for(i
= CH_EOF
; i
<128; i
++)
3533 is_space(i
) ? IS_SPC
3538 for(i
= 128; i
<256; i
++)
3539 set_idnum(i
, IS_ID
);
3541 /* init allocators */
3542 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3543 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3544 tal_new(&cstr_alloc
, CSTR_TAL_LIMIT
, CSTR_TAL_SIZE
);
3546 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3547 cstr_new(&cstr_buf
);
3548 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3549 tok_str_new(&tokstr_buf
);
3550 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3552 tok_ident
= TOK_IDENT
;
3561 tok_alloc(p
, r
- p
- 1);
3566 ST_FUNC
void tccpp_delete(TCCState
*s
)
3570 /* free -D and compiler defines */
3573 /* cleanup from error/setjmp */
3582 n
= tok_ident
- TOK_IDENT
;
3583 for(i
= 0; i
< n
; i
++)
3584 tal_free(toksym_alloc
, table_ident
[i
]);
3585 tcc_free(table_ident
);
3588 /* free static buffers */
3589 cstr_free(&tokcstr
);
3590 cstr_free(&cstr_buf
);
3591 cstr_free(¯o_equal_buf
);
3592 tok_str_free_str(tokstr_buf
.str
);
3594 /* free allocators */
3595 tal_delete(toksym_alloc
);
3596 toksym_alloc
= NULL
;
3597 tal_delete(tokstr_alloc
);
3598 tokstr_alloc
= NULL
;
3599 tal_delete(cstr_alloc
);
3603 /* ------------------------------------------------------------------------- */
3604 /* tcc -E [-P[1]] [-dD} support */
3606 static void tok_print(const char *msg
, const int *str
)
3612 fp
= tcc_state
->ppfp
;
3613 if (!fp
|| !tcc_state
->dflag
)
3616 fprintf(fp
, "%s ", msg
);
3618 TOK_GET(&t
, &str
, &cval
);
3621 fprintf(fp
,"%s", get_tok_str(t
, &cval
));
3626 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3628 int d
= f
->line_num
- f
->line_ref
;
3633 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3635 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3637 fputs("\n", s1
->ppfp
), --d
;
3638 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3639 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3641 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3642 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3644 f
->line_ref
= f
->line_num
;
3647 static void define_print(TCCState
*s1
, int v
)
3653 if (NULL
== s
|| NULL
== s
->d
)
3657 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3658 if (s
->type
.t
== MACRO_FUNC
) {
3663 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3670 tok_print("", s
->d
);
3673 static void pp_debug_defines(TCCState
*s1
)
3684 pp_line(s1
, file
, 0);
3685 file
->line_ref
= ++file
->line_num
;
3689 vs
= get_tok_str(v
, NULL
);
3690 if (t
== TOK_DEFINE
) {
3691 define_print(s1
, v
);
3692 } else if (t
== TOK_UNDEF
) {
3693 fprintf(fp
, "#undef %s\n", vs
);
3694 } else if (t
== TOK_push_macro
) {
3695 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3696 } else if (t
== TOK_pop_macro
) {
3697 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3702 static void pp_debug_builtins(TCCState
*s1
)
3705 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3706 define_print(s1
, v
);
3709 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3710 static int pp_need_space(int a
, int b
)
3712 return 'E' == a
? '+' == b
|| '-' == b
3713 : '+' == a
? TOK_INC
== b
|| '+' == b
3714 : '-' == a
? TOK_DEC
== b
|| '-' == b
3715 : a
>= TOK_IDENT
? b
>= TOK_IDENT
3716 : a
== TOK_PPNUM
? b
>= TOK_IDENT
3720 /* maybe hex like 0x1e */
3721 static int pp_check_he0xE(int t
, const char *p
)
3723 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3728 /* Preprocess the current file */
3729 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3731 BufferedFile
**iptr
;
3732 int token_seen
, spcs
, level
;
3736 define_start
= define_stack
;
3737 preprocess_start(s1
);
3739 ch
= file
->buf_ptr
[0];
3740 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3741 parse_flags
= PARSE_FLAG_PREPROCESS
3742 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3743 | PARSE_FLAG_LINEFEED
3745 | PARSE_FLAG_ACCEPT_STRAYS
3748 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3749 capability to compile and run itself, provided all numbers are
3750 given as decimals. tcc -E -P10 will do. */
3751 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_P10
)
3752 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
3755 /* for PP benchmarks */
3756 do next(); while (tok
!= TOK_EOF
);
3757 free_defines(define_start
);
3761 if (s1
->dflag
& 1) {
3762 pp_debug_builtins(s1
);
3766 token_seen
= TOK_LINEFEED
, spcs
= 0;
3767 pp_line(s1
, file
, 0);
3770 iptr
= s1
->include_stack_ptr
;
3774 level
= s1
->include_stack_ptr
- iptr
;
3777 pp_line(s1
, *iptr
, 0);
3778 pp_line(s1
, file
, level
);
3782 pp_debug_defines(s1
);
3787 if (token_seen
== TOK_LINEFEED
) {
3792 if (tok
== TOK_LINEFEED
) {
3796 pp_line(s1
, file
, 0);
3797 } else if (tok
== TOK_LINEFEED
) {
3800 spcs
= pp_need_space(token_seen
, tok
);
3804 fputs(" ", s1
->ppfp
), --spcs
;
3805 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
3806 token_seen
= pp_check_he0xE(tok
, p
);;
3808 /* reset define stack, but keep -D and built-ins */
3809 free_defines(define_start
);
3813 /* ------------------------------------------------------------------------- */