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 TokenString tokstr_buf
;
47 static unsigned char isidnum_table
[256 - CH_EOF
];
48 static int pp_debug_tok
, pp_debug_symv
;
50 static void tok_print(const char *msg
, const int *str
);
52 static struct TinyAlloc
*toksym_alloc
;
53 static struct TinyAlloc
*tokstr_alloc
;
54 static struct TinyAlloc
*cstr_alloc
;
56 static TokenString
*macro_stack
;
58 static const char tcc_keywords
[] =
59 #define DEF(id, str) str "\0"
64 /* WARNING: the content of this string encodes token numbers */
65 static const unsigned char tok_two_chars
[] =
67 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
68 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
89 '.','.', 0xa8, // C++ token ?
90 '#','#', TOK_TWOSHARPS
,
94 static void next_nomacro_spc(void);
96 ST_FUNC
void skip(int c
)
99 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
103 ST_FUNC
void expect(const char *msg
)
105 tcc_error("%s expected", msg
);
108 /* ------------------------------------------------------------------------- */
109 /* Custom allocator for tiny objects */
114 #define tal_free(al, p) tcc_free(p)
115 #define tal_realloc(al, p, size) tcc_realloc(p, size)
116 #define tal_new(a,b,c)
117 #define tal_delete(a)
119 #if !defined(MEM_DEBUG)
120 #define tal_free(al, p) tal_free_impl(al, p)
121 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size)
122 #define TAL_DEBUG_PARAMS
125 //#define TAL_INFO 1 /* collect and dump allocators stats */
126 #define tal_free(al, p) tal_free_impl(al, p, __FILE__, __LINE__)
127 #define tal_realloc(al, p, size) tal_realloc_impl(&al, p, size, __FILE__, __LINE__)
128 #define TAL_DEBUG_PARAMS , const char *file, int line
129 #define TAL_DEBUG_FILE_LEN 15
132 #define TOKSYM_TAL_SIZE (768 * 1024) /* allocator for tiny TokenSym in table_ident */
133 #define TOKSTR_TAL_SIZE (768 * 1024) /* allocator for tiny TokenString instances */
134 #define CSTR_TAL_SIZE (256 * 1024) /* allocator for tiny CString instances */
135 #define TOKSYM_TAL_LIMIT 256 /* prefer unique limits to distinguish allocators debug msgs */
136 #define TOKSTR_TAL_LIMIT 128 /* 32 * sizeof(int) */
137 #define CSTR_TAL_LIMIT 1024
139 typedef struct TinyAlloc
{
145 struct TinyAlloc
*next
, *top
;
154 typedef struct tal_header_t
{
157 int line_num
; /* negative line_num used for double free check */
158 char file_name
[TAL_DEBUG_FILE_LEN
+ 1];
162 /* ------------------------------------------------------------------------- */
164 ST_FUNC TinyAlloc
*tal_new(TinyAlloc
**pal
, size_t limit
, size_t size
)
166 TinyAlloc
*al
= tcc_mallocz(sizeof(TinyAlloc
));
167 al
->p
= al
->buffer
= tcc_malloc(size
);
174 ST_FUNC
void tal_delete(TinyAlloc
*al
)
182 fprintf(stderr
, "limit=%5d, size=%5g MB, nb_peak=%6d, nb_total=%8d, nb_missed=%6d, usage=%5.1f%%\n",
183 al
->limit
, al
->size
/ 1024.0 / 1024.0, al
->nb_peak
, al
->nb_total
, al
->nb_missed
,
184 (al
->peak_p
- al
->buffer
) * 100.0 / al
->size
);
187 if (al
->nb_allocs
> 0) {
189 fprintf(stderr
, "TAL_DEBUG: mem leak %d chunks (limit= %d)\n",
190 al
->nb_allocs
, al
->limit
);
193 tal_header_t
*header
= (tal_header_t
*)p
;
194 if (header
->line_num
> 0) {
195 fprintf(stderr
, " file %s, line %u: %u bytes\n",
196 header
->file_name
, header
->line_num
, header
->size
);
198 p
+= header
->size
+ sizeof(tal_header_t
);
203 tcc_free(al
->buffer
);
209 ST_FUNC
void tal_free_impl(TinyAlloc
*al
, void *p TAL_DEBUG_PARAMS
)
214 if (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
) {
216 tal_header_t
*header
= (((tal_header_t
*)p
) - 1);
217 if (header
->line_num
< 0) {
218 fprintf(stderr
, "TAL_DEBUG: file %s, line %u double frees chunk from\n",
220 fprintf(stderr
, " file %s, line %u: %u bytes\n",
221 header
->file_name
, -header
->line_num
, header
->size
);
223 header
->line_num
= -header
->line_num
;
228 } else if (al
->next
) {
236 ST_FUNC
void *tal_realloc_impl(TinyAlloc
**pal
, void *p
, size_t size TAL_DEBUG_PARAMS
)
238 tal_header_t
*header
;
241 size_t adj_size
= (size
+ 3) & -4;
242 TinyAlloc
*al
= *pal
;
245 is_own
= (al
->buffer
<= (uint8_t *)p
&& (uint8_t *)p
< al
->buffer
+ al
->size
);
246 if ((!p
|| is_own
) && size
<= al
->limit
) {
247 if (al
->p
+ adj_size
+ sizeof(tal_header_t
) < al
->buffer
+ al
->size
) {
248 header
= (tal_header_t
*)al
->p
;
249 header
->size
= adj_size
;
251 { int ofs
= strlen(file
) - TAL_DEBUG_FILE_LEN
;
252 strncpy(header
->file_name
, file
+ (ofs
> 0 ? ofs
: 0), TAL_DEBUG_FILE_LEN
);
253 header
->file_name
[TAL_DEBUG_FILE_LEN
] = 0;
254 header
->line_num
= line
; }
256 ret
= al
->p
+ sizeof(tal_header_t
);
257 al
->p
+= adj_size
+ sizeof(tal_header_t
);
259 header
= (((tal_header_t
*)p
) - 1);
260 memcpy(ret
, p
, header
->size
);
262 header
->line_num
= -header
->line_num
;
268 if (al
->nb_peak
< al
->nb_allocs
)
269 al
->nb_peak
= al
->nb_allocs
;
270 if (al
->peak_p
< al
->p
)
277 ret
= tal_realloc(*pal
, 0, size
);
278 header
= (((tal_header_t
*)p
) - 1);
279 memcpy(ret
, p
, header
->size
);
281 header
->line_num
= -header
->line_num
;
288 TinyAlloc
*bottom
= al
, *next
= al
->top
? al
->top
: al
;
290 al
= tal_new(pal
, next
->limit
, next
->size
* 2);
298 ret
= tcc_malloc(size
);
299 header
= (((tal_header_t
*)p
) - 1);
300 memcpy(ret
, p
, header
->size
);
302 header
->line_num
= -header
->line_num
;
304 } else if (al
->next
) {
308 ret
= tcc_realloc(p
, size
);
317 /* ------------------------------------------------------------------------- */
318 /* CString handling */
319 static void cstr_realloc(CString
*cstr
, int new_size
)
323 size
= cstr
->size_allocated
;
325 size
= 8; /* no need to allocate a too small first string */
326 while (size
< new_size
)
328 cstr
->data
= tal_realloc(cstr_alloc
, cstr
->data
, size
);
329 cstr
->size_allocated
= size
;
333 ST_INLN
void cstr_ccat(CString
*cstr
, int ch
)
336 size
= cstr
->size
+ 1;
337 if (size
> cstr
->size_allocated
)
338 cstr_realloc(cstr
, size
);
339 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
343 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
, int len
)
347 len
= strlen(str
) + 1 + len
;
348 size
= cstr
->size
+ len
;
349 if (size
> cstr
->size_allocated
)
350 cstr_realloc(cstr
, size
);
351 memmove(((unsigned char *)cstr
->data
) + cstr
->size
, str
, len
);
355 /* add a wide char */
356 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
359 size
= cstr
->size
+ sizeof(nwchar_t
);
360 if (size
> cstr
->size_allocated
)
361 cstr_realloc(cstr
, size
);
362 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
366 ST_FUNC
void cstr_new(CString
*cstr
)
368 memset(cstr
, 0, sizeof(CString
));
371 /* free string and reset it to NULL */
372 ST_FUNC
void cstr_free(CString
*cstr
)
374 tal_free(cstr_alloc
, cstr
->data
);
378 /* reset string to empty */
379 ST_FUNC
void cstr_reset(CString
*cstr
)
385 static void add_char(CString
*cstr
, int c
)
387 if (c
== '\'' || c
== '\"' || c
== '\\') {
388 /* XXX: could be more precise if char or string */
389 cstr_ccat(cstr
, '\\');
391 if (c
>= 32 && c
<= 126) {
394 cstr_ccat(cstr
, '\\');
396 cstr_ccat(cstr
, 'n');
398 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
399 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
400 cstr_ccat(cstr
, '0' + (c
& 7));
405 /* ------------------------------------------------------------------------- */
406 /* allocate a new token */
407 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
409 TokenSym
*ts
, **ptable
;
412 if (tok_ident
>= SYM_FIRST_ANOM
)
413 tcc_error("memory full (symbols)");
415 /* expand token table if needed */
416 i
= tok_ident
- TOK_IDENT
;
417 if ((i
% TOK_ALLOC_INCR
) == 0) {
418 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
419 table_ident
= ptable
;
422 ts
= tal_realloc(toksym_alloc
, 0, sizeof(TokenSym
) + len
);
424 ts
->tok
= tok_ident
++;
425 ts
->sym_define
= NULL
;
426 ts
->sym_label
= NULL
;
427 ts
->sym_struct
= NULL
;
428 ts
->sym_identifier
= NULL
;
430 ts
->hash_next
= NULL
;
431 memcpy(ts
->str
, str
, len
);
437 #define TOK_HASH_INIT 1
438 #define TOK_HASH_FUNC(h, c) ((h) + ((h) << 5) + ((h) >> 27) + (c))
441 /* find a token and add it if not found */
442 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
450 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
451 h
&= (TOK_HASH_SIZE
- 1);
453 pts
= &hash_ident
[h
];
458 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
460 pts
= &(ts
->hash_next
);
462 return tok_alloc_new(pts
, str
, len
);
465 /* XXX: buffer overflow */
466 /* XXX: float tokens */
467 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
472 cstr_reset(&cstr_buf
);
480 /* XXX: not quite exact, but only useful for testing */
482 sprintf(p
, "%u", (unsigned)cv
->i
);
484 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
488 cstr_ccat(&cstr_buf
, 'L');
490 cstr_ccat(&cstr_buf
, '\'');
491 add_char(&cstr_buf
, cv
->i
);
492 cstr_ccat(&cstr_buf
, '\'');
493 cstr_ccat(&cstr_buf
, '\0');
497 return (char*)cv
->str
.data
;
499 cstr_ccat(&cstr_buf
, 'L');
501 cstr_ccat(&cstr_buf
, '\"');
503 len
= cv
->str
.size
- 1;
505 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
507 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
509 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
511 cstr_ccat(&cstr_buf
, '\"');
512 cstr_ccat(&cstr_buf
, '\0');
516 cstr_cat(&cstr_buf
, "<float>", 0);
519 cstr_cat(&cstr_buf
, "<double>", 0);
522 cstr_cat(&cstr_buf
, "<long double>", 0);
525 cstr_cat(&cstr_buf
, "<linenumber>", 0);
528 /* above tokens have value, the ones below don't */
537 return strcpy(p
, "...");
539 return strcpy(p
, "<<=");
541 return strcpy(p
, ">>=");
544 /* search in two bytes table */
545 const unsigned char *q
= tok_two_chars
;
551 return cstr_buf
.data
;
556 sprintf(cstr_buf
.data
, "<%02x>", v
);
557 return cstr_buf
.data
;
562 } else if (v
< tok_ident
) {
563 return table_ident
[v
- TOK_IDENT
]->str
;
564 } else if (v
>= SYM_FIRST_ANOM
) {
565 /* special name for anonymous symbol */
566 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
568 /* should never happen */
573 return cstr_buf
.data
;
576 /* return the current character, handling end of block if necessary
578 ST_FUNC
int handle_eob(void)
580 BufferedFile
*bf
= file
;
583 /* only tries to read if really end of buffer */
584 if (bf
->buf_ptr
>= bf
->buf_end
) {
586 #if defined(PARSE_DEBUG)
591 len
= read(bf
->fd
, bf
->buffer
, len
);
598 bf
->buf_ptr
= bf
->buffer
;
599 bf
->buf_end
= bf
->buffer
+ len
;
600 *bf
->buf_end
= CH_EOB
;
602 if (bf
->buf_ptr
< bf
->buf_end
) {
603 return bf
->buf_ptr
[0];
605 bf
->buf_ptr
= bf
->buf_end
;
610 /* read next char from current input file and handle end of input buffer */
611 ST_INLN
void inp(void)
613 ch
= *(++(file
->buf_ptr
));
614 /* end of buffer/file handling */
619 /* handle '\[\r]\n' */
620 static int handle_stray_noerror(void)
627 } else if (ch
== '\r') {
641 static void handle_stray(void)
643 if (handle_stray_noerror())
644 tcc_error("stray '\\' in program");
647 /* skip the stray and handle the \\n case. Output an error if
648 incorrect char after the stray */
649 static int handle_stray1(uint8_t *p
)
654 if (p
>= file
->buf_end
) {
661 if (handle_stray_noerror()) {
662 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
663 tcc_error("stray '\\' in program");
664 *--file
->buf_ptr
= '\\';
671 /* handle just the EOB case, but not stray */
672 #define PEEKC_EOB(c, p)\
683 /* handle the complicated stray case */
689 c = handle_stray1(p);\
694 /* input with '\[\r]\n' handling. Note that this function cannot
695 handle other characters after '\', so you cannot call it inside
696 strings or comments */
697 ST_FUNC
void minp(void)
704 /* single line C++ comments */
705 static uint8_t *parse_line_comment(uint8_t *p
)
713 if (c
== '\n' || c
== CH_EOF
) {
715 } else if (c
== '\\') {
724 } else if (c
== '\r') {
742 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
751 if (c
== '\n' || c
== '*' || c
== '\\')
755 if (c
== '\n' || c
== '*' || c
== '\\')
759 /* now we can handle all the cases */
763 } else if (c
== '*') {
769 } else if (c
== '/') {
771 } else if (c
== '\\') {
776 tcc_error("unexpected end of file in comment");
778 /* skip '\[\r]\n', otherwise just skip the stray */
784 } else if (c
== '\r') {
801 /* stray, eob or eof */
806 tcc_error("unexpected end of file in comment");
807 } else if (c
== '\\') {
817 ST_FUNC
void set_idnum(int c
, int val
)
819 isidnum_table
[c
- CH_EOF
] = val
;
824 static inline void skip_spaces(void)
826 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
830 static inline int check_space(int t
, int *spc
)
832 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
841 /* parse a string without interpreting escapes */
842 static uint8_t *parse_pp_string(uint8_t *p
,
843 int sep
, CString
*str
)
851 } else if (c
== '\\') {
857 /* XXX: indicate line number of start of string */
858 tcc_error("missing terminating %c character", sep
);
859 } else if (c
== '\\') {
860 /* escape : just skip \[\r]\n */
865 } else if (c
== '\r') {
868 expect("'\n' after '\r'");
871 } else if (c
== CH_EOF
) {
872 goto unterminated_string
;
875 cstr_ccat(str
, '\\');
881 } else if (c
== '\n') {
884 } else if (c
== '\r') {
888 cstr_ccat(str
, '\r');
904 /* skip block of text until #else, #elif or #endif. skip also pairs of
906 static void preprocess_skip(void)
908 int a
, start_of_line
, c
, in_warn_or_error
;
915 in_warn_or_error
= 0;
936 } else if (c
== '\\') {
937 ch
= file
->buf_ptr
[0];
938 handle_stray_noerror();
945 if (in_warn_or_error
)
947 p
= parse_pp_string(p
, c
, NULL
);
951 if (in_warn_or_error
)
958 p
= parse_comment(p
);
959 } else if (ch
== '/') {
960 p
= parse_line_comment(p
);
970 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
972 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
974 else if (tok
== TOK_ENDIF
)
976 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
977 in_warn_or_error
= 1;
978 else if (tok
== TOK_LINEFEED
)
980 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
981 p
= parse_line_comment(p
- 1);
982 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
983 p
= parse_line_comment(p
- 1);
996 /* ParseState handling */
998 /* XXX: currently, no include file info is stored. Thus, we cannot display
999 accurate messages if the function or data definition spans multiple
1002 /* save current parse state in 's' */
1003 ST_FUNC
void save_parse_state(ParseState
*s
)
1005 s
->line_num
= file
->line_num
;
1006 s
->macro_ptr
= macro_ptr
;
1011 /* restore parse state from 's' */
1012 ST_FUNC
void restore_parse_state(ParseState
*s
)
1014 file
->line_num
= s
->line_num
;
1015 macro_ptr
= s
->macro_ptr
;
1020 /* return the number of additional 'ints' necessary to store the
1022 static inline int tok_size(const int *p
)
1037 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
1043 return 1 + LDOUBLE_SIZE
/ 4;
1049 /* token string handling */
1051 ST_INLN
void tok_str_new(TokenString
*s
)
1055 s
->allocated_len
= 0;
1056 s
->last_line_num
= -1;
1059 ST_FUNC TokenString
*tok_str_alloc(void)
1061 TokenString
*str
= tal_realloc(tokstr_alloc
, 0, sizeof *str
);
1066 ST_FUNC
int *tok_str_dup(TokenString
*s
)
1070 str
= tal_realloc(tokstr_alloc
, 0, s
->len
* sizeof(int));
1071 memcpy(str
, s
->str
, s
->len
* sizeof(int));
1075 ST_FUNC
void tok_str_free_str(int *str
)
1077 tal_free(tokstr_alloc
, str
);
1080 ST_FUNC
void tok_str_free(TokenString
*str
)
1082 tok_str_free_str(str
->str
);
1083 tal_free(tokstr_alloc
, str
);
1086 ST_FUNC
int *tok_str_realloc(TokenString
*s
, int new_size
)
1090 size
= s
->allocated_len
;
1093 while (size
< new_size
)
1095 if (size
> s
->allocated_len
) {
1096 str
= tal_realloc(tokstr_alloc
, s
->str
, size
* sizeof(int));
1097 s
->allocated_len
= size
;
1103 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
1109 if (len
>= s
->allocated_len
)
1110 str
= tok_str_realloc(s
, len
+ 1);
1115 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
1118 str
->prev
= macro_stack
;
1119 str
->prev_ptr
= macro_ptr
;
1120 macro_ptr
= str
->str
;
1124 ST_FUNC
void end_macro(void)
1126 TokenString
*str
= macro_stack
;
1127 macro_stack
= str
->prev
;
1128 macro_ptr
= str
->prev_ptr
;
1129 if (str
->alloc
== 2) {
1130 str
->alloc
= 3; /* just mark as finished */
1136 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1143 /* allocate space for worst case */
1144 if (len
+ TOK_MAX_SIZE
>= s
->allocated_len
)
1145 str
= tok_str_realloc(s
, len
+ TOK_MAX_SIZE
+ 1);
1154 str
[len
++] = cv
->tab
[0];
1161 /* Insert the string into the int array. */
1163 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1164 if (len
+ nb_words
>= s
->allocated_len
)
1165 str
= tok_str_realloc(s
, len
+ nb_words
+ 1);
1166 str
[len
] = cv
->str
.size
;
1167 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
1174 #if LDOUBLE_SIZE == 8
1177 str
[len
++] = cv
->tab
[0];
1178 str
[len
++] = cv
->tab
[1];
1180 #if LDOUBLE_SIZE == 12
1182 str
[len
++] = cv
->tab
[0];
1183 str
[len
++] = cv
->tab
[1];
1184 str
[len
++] = cv
->tab
[2];
1185 #elif LDOUBLE_SIZE == 16
1187 str
[len
++] = cv
->tab
[0];
1188 str
[len
++] = cv
->tab
[1];
1189 str
[len
++] = cv
->tab
[2];
1190 str
[len
++] = cv
->tab
[3];
1191 #elif LDOUBLE_SIZE != 8
1192 #error add long double size support
1201 /* add the current parse token in token string 's' */
1202 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
1206 /* save line number info */
1207 if (file
->line_num
!= s
->last_line_num
) {
1208 s
->last_line_num
= file
->line_num
;
1209 cval
.i
= s
->last_line_num
;
1210 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1212 tok_str_add2(s
, tok
, &tokc
);
1215 /* get a token from an integer array and increment pointer
1216 accordingly. we code it as a macro to avoid pointer aliasing. */
1217 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1236 cv
->str
.size
= *p
++;
1238 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1246 #if LDOUBLE_SIZE == 16
1248 #elif LDOUBLE_SIZE == 12
1250 #elif LDOUBLE_SIZE == 8
1253 # error add long double size support
1266 /* Calling this function is expensive, but it is not possible
1267 to read a token string backwards. */
1268 static int tok_last(const int *str0
, const int *str1
)
1270 const int *str
= str0
;
1275 TOK_GET(&tok
, &str
, &cval
);
1279 static int macro_is_equal(const int *a
, const int *b
)
1283 static CString localbuf
;
1289 /* first time preallocate static localbuf, next time only reset position to start */
1290 cstr_reset(&localbuf
);
1291 TOK_GET(&t
, &a
, &cv
);
1292 cstr_cat(&localbuf
, get_tok_str(t
, &cv
), 0);
1293 TOK_GET(&t
, &b
, &cv
);
1294 if (strcmp(localbuf
.data
, get_tok_str(t
, &cv
)))
1300 /* defines handling */
1301 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1306 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1308 s
->next
= first_arg
;
1309 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1311 if (o
&& !macro_is_equal(o
->d
, s
->d
))
1312 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1315 /* undefined a define symbol. Its name is just set to zero */
1316 ST_FUNC
void define_undef(Sym
*s
)
1319 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1320 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1323 ST_INLN Sym
*define_find(int v
)
1326 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1328 return table_ident
[v
]->sym_define
;
1331 /* free define stack until top reaches 'b' */
1332 ST_FUNC
void free_defines(Sym
*b
)
1334 while (define_stack
!= b
) {
1335 Sym
*top
= define_stack
;
1336 define_stack
= top
->prev
;
1337 tok_str_free_str(top
->d
);
1342 /* restore remaining (-D or predefined) symbols */
1345 if (v
>= TOK_IDENT
&& v
< tok_ident
) {
1346 Sym
**d
= &table_ident
[v
- TOK_IDENT
]->sym_define
;
1355 ST_FUNC Sym
*label_find(int v
)
1358 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1360 return table_ident
[v
]->sym_label
;
1363 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1366 s
= sym_push2(ptop
, v
, 0, 0);
1368 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1369 if (ptop
== &global_label_stack
) {
1370 /* modify the top most local identifier, so that
1371 sym_identifier will point to 's' when popped */
1373 ps
= &(*ps
)->prev_tok
;
1380 /* pop labels until element last is reached. Look if any labels are
1381 undefined. Define symbols if '&&label' was used. */
1382 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1385 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1387 if (s
->r
== LABEL_DECLARED
) {
1388 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1389 } else if (s
->r
== LABEL_FORWARD
) {
1390 tcc_error("label '%s' used but not defined",
1391 get_tok_str(s
->v
, NULL
));
1394 /* define corresponding symbol. A size of
1396 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1400 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1406 /* eval an expression for #if/#elif */
1407 static int expr_preprocess(void)
1412 str
= tok_str_alloc();
1413 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1414 next(); /* do macro subst */
1415 if (tok
== TOK_DEFINED
) {
1420 c
= define_find(tok
) != 0;
1425 } else if (tok
>= TOK_IDENT
) {
1426 /* if undefined macro */
1430 tok_str_add_tok(str
);
1432 tok_str_add(str
, -1); /* simulate end of file */
1433 tok_str_add(str
, 0);
1434 /* now evaluate C constant expression */
1435 begin_macro(str
, 1);
1443 /* parse after #define */
1444 ST_FUNC
void parse_define(void)
1446 Sym
*s
, *first
, **ps
;
1447 int v
, t
, varg
, is_vaargs
, spc
;
1448 int saved_parse_flags
= parse_flags
;
1452 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1453 /* XXX: should check if same macro (ANSI) */
1456 /* We have to parse the whole define as if not in asm mode, in particular
1457 no line comment with '#' must be ignored. Also for function
1458 macros the argument list must be parsed without '.' being an ID
1460 parse_flags
= ((parse_flags
& ~PARSE_FLAG_ASM_FILE
) | PARSE_FLAG_SPACES
);
1461 /* '(' must be just after macro definition for MACRO_FUNC */
1467 if (tok
!= ')') for (;;) {
1471 if (varg
== TOK_DOTS
) {
1472 varg
= TOK___VA_ARGS__
;
1474 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1478 if (varg
< TOK_IDENT
)
1480 tcc_error("bad macro parameter list");
1481 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1486 if (tok
!= ',' || is_vaargs
)
1496 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1497 /* The body of a macro definition should be parsed such that identifiers
1498 are parsed like the file mode determines (i.e. with '.' being an
1499 ID character in asm mode). But '#' should be retained instead of
1500 regarded as line comment leader, so still don't set ASM_FILE
1502 set_idnum('.', (saved_parse_flags
& PARSE_FLAG_ASM_FILE
) ? IS_ID
: 0);
1503 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1504 /* remove spaces around ## and after '#' */
1505 if (TOK_TWOSHARPS
== tok
) {
1511 } else if ('#' == tok
) {
1513 } else if (check_space(tok
, &spc
)) {
1516 tok_str_add2(&tokstr_buf
, tok
, &tokc
);
1521 parse_flags
= saved_parse_flags
;
1523 --tokstr_buf
.len
; /* remove trailing space */
1524 tok_str_add(&tokstr_buf
, 0);
1527 tcc_error("'##' cannot appear at either end of macro");
1528 define_push(v
, t
, tok_str_dup(&tokstr_buf
), first
);
1531 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
, int add
)
1533 const unsigned char *s
;
1539 s
= (unsigned char *) filename
;
1542 h
= TOK_HASH_FUNC(h
, toup(*s
));
1544 h
= TOK_HASH_FUNC(h
, *s
);
1548 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1550 i
= s1
->cached_includes_hash
[h
];
1554 e
= s1
->cached_includes
[i
- 1];
1555 if (0 == PATHCMP(e
->filename
, filename
))
1562 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1563 strcpy(e
->filename
, filename
);
1564 e
->ifndef_macro
= e
->once
= 0;
1565 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1566 /* add in hash table */
1567 e
->hash_next
= s1
->cached_includes_hash
[h
];
1568 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1570 printf("adding cached '%s'\n", filename
);
1575 static void pragma_parse(TCCState
*s1
)
1578 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1582 if (next(), tok
!= '(')
1584 if (next(), tok
!= TOK_STR
)
1586 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1587 if (next(), tok
!= ')')
1589 if (t
== TOK_push_macro
) {
1590 while (NULL
== (s
= define_find(v
)))
1591 define_push(v
, 0, NULL
, NULL
);
1592 s
->type
.ref
= s
; /* set push boundary */
1594 for (s
= define_stack
; s
; s
= s
->prev
)
1595 if (s
->v
== v
&& s
->type
.ref
== s
) {
1601 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1603 tcc_warning("unbalanced #pragma pop_macro");
1604 pp_debug_tok
= t
, pp_debug_symv
= v
;
1606 } else if (tok
== TOK_once
) {
1607 search_cached_include(s1
, file
->filename
, 1)->once
= pp_once
;
1609 } else if (s1
->ppfp
) {
1610 /* tcc -E: keep pragmas below unchanged */
1612 unget_tok(TOK_PRAGMA
);
1614 unget_tok(TOK_LINEFEED
);
1616 } else if (tok
== TOK_pack
) {
1618 #pragma pack(1) // set
1619 #pragma pack() // reset to default
1620 #pragma pack(push,1) // push & set
1621 #pragma pack(pop) // restore previous */
1624 if (tok
== TOK_ASM_pop
) {
1626 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1628 tcc_error("out of pack stack");
1630 s1
->pack_stack_ptr
--;
1634 if (tok
== TOK_ASM_push
) {
1636 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1638 s1
->pack_stack_ptr
++;
1641 if (tok
!= TOK_CINT
)
1644 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1648 *s1
->pack_stack_ptr
= val
;
1653 } else if (tok
== TOK_comment
) {
1663 file
= tcc_strdup((char *)tokc
.str
.data
);
1664 dynarray_add((void ***)&s1
->pragma_libs
, &s1
->nb_pragma_libs
, file
);
1670 if (s1
->warn_unsupported
)
1671 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1676 tcc_error("malformed #pragma directive");
1680 /* is_bof is true if first non space token at beginning of file */
1681 ST_FUNC
void preprocess(int is_bof
)
1683 TCCState
*s1
= tcc_state
;
1684 int i
, c
, n
, saved_parse_flags
;
1688 saved_parse_flags
= parse_flags
;
1689 parse_flags
= PARSE_FLAG_PREPROCESS
1690 | PARSE_FLAG_TOK_NUM
1691 | PARSE_FLAG_TOK_STR
1692 | PARSE_FLAG_LINEFEED
1693 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1702 pp_debug_symv
= tok
;
1708 pp_debug_symv
= tok
;
1709 s
= define_find(tok
);
1710 /* undefine symbol by putting an invalid name */
1715 case TOK_INCLUDE_NEXT
:
1716 ch
= file
->buf_ptr
[0];
1717 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1722 } else if (ch
== '\"') {
1727 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1728 if ((q
- buf
) < sizeof(buf
) - 1)
1731 if (handle_stray_noerror() == 0)
1739 /* eat all spaces and comments after include */
1740 /* XXX: slightly incorrect */
1741 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1746 /* computed #include : concatenate everything up to linefeed,
1747 the result must be one of the two accepted forms.
1748 Don't convert pp-tokens to tokens here. */
1749 parse_flags
= (PARSE_FLAG_PREPROCESS
1750 | PARSE_FLAG_LINEFEED
1751 | (parse_flags
& PARSE_FLAG_ASM_FILE
));
1754 while (tok
!= TOK_LINEFEED
) {
1755 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1759 /* check syntax and remove '<>|""' */
1760 if ((len
< 2 || ((buf
[0] != '"' || buf
[len
-1] != '"') &&
1761 (buf
[0] != '<' || buf
[len
-1] != '>'))))
1762 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1764 memmove(buf
, buf
+ 1, len
- 2);
1765 buf
[len
- 2] = '\0';
1768 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1769 tcc_error("#include recursion too deep");
1770 /* store current file in stack, but increment stack later below */
1771 *s1
->include_stack_ptr
= file
;
1772 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
: 0;
1773 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1774 for (; i
< n
; ++i
) {
1775 char buf1
[sizeof file
->filename
];
1780 /* check absolute include path */
1781 if (!IS_ABSPATH(buf
))
1785 } else if (i
== 1) {
1786 /* search in file's dir if "header.h" */
1789 path
= file
->filename
;
1790 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1793 /* search in all the include paths */
1794 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1795 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1796 pstrcpy(buf1
, sizeof(buf1
), path
);
1797 pstrcat(buf1
, sizeof(buf1
), "/");
1800 pstrcat(buf1
, sizeof(buf1
), buf
);
1801 e
= search_cached_include(s1
, buf1
, 0);
1802 if (e
&& (define_find(e
->ifndef_macro
) || e
->once
== pp_once
)) {
1803 /* no need to parse the include because the 'ifndef macro'
1804 is defined (or had #pragma once) */
1806 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1811 if (tcc_open(s1
, buf1
) < 0)
1814 file
->include_next_index
= i
+ 1;
1816 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1818 /* update target deps */
1819 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1821 /* push current file in stack */
1822 ++s1
->include_stack_ptr
;
1823 /* add include file debug info */
1825 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1826 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1827 ch
= file
->buf_ptr
[0];
1830 tcc_error("include file '%s' not found", buf
);
1837 c
= expr_preprocess();
1843 if (tok
< TOK_IDENT
)
1844 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1848 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1850 file
->ifndef_macro
= tok
;
1853 c
= (define_find(tok
) != 0) ^ c
;
1855 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1856 tcc_error("memory full (ifdef)");
1857 *s1
->ifdef_stack_ptr
++ = c
;
1860 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1861 tcc_error("#else without matching #if");
1862 if (s1
->ifdef_stack_ptr
[-1] & 2)
1863 tcc_error("#else after #else");
1864 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1867 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1868 tcc_error("#elif without matching #if");
1869 c
= s1
->ifdef_stack_ptr
[-1];
1871 tcc_error("#elif after #else");
1872 /* last #if/#elif expression was true: we skip */
1876 c
= expr_preprocess();
1877 s1
->ifdef_stack_ptr
[-1] = c
;
1880 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1881 file
->ifndef_macro
= 0;
1890 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1891 tcc_error("#endif without matching #if");
1892 s1
->ifdef_stack_ptr
--;
1893 /* '#ifndef macro' was at the start of file. Now we check if
1894 an '#endif' is exactly at the end of file */
1895 if (file
->ifndef_macro
&&
1896 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1897 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1898 /* need to set to zero to avoid false matches if another
1899 #ifndef at middle of file */
1900 file
->ifndef_macro
= 0;
1901 while (tok
!= TOK_LINEFEED
)
1903 tok_flags
|= TOK_FLAG_ENDIF
;
1908 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1912 if (tok
!= TOK_CINT
)
1914 tcc_error("wrong #line format");
1918 if (tok
!= TOK_LINEFEED
) {
1920 pstrcpy(file
->filename
, sizeof(file
->filename
), (char *)tokc
.str
.data
);
1921 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1928 total_lines
+= file
->line_num
- n
;
1931 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1936 ch
= file
->buf_ptr
[0];
1939 while (ch
!= '\n' && ch
!= CH_EOF
) {
1940 if ((q
- buf
) < sizeof(buf
) - 1)
1943 if (handle_stray_noerror() == 0)
1950 tcc_error("#error %s", buf
);
1952 tcc_warning("#warning %s", buf
);
1960 /* ignore gas line comment in an 'S' file. */
1961 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
1963 if (tok
== '!' && is_bof
)
1964 /* '!' is ignored at beginning to allow C scripts. */
1966 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1968 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
- 1);
1971 /* ignore other preprocess commands or #! for C scripts */
1972 while (tok
!= TOK_LINEFEED
)
1975 parse_flags
= saved_parse_flags
;
1978 /* evaluate escape codes in a string. */
1979 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1994 case '0': case '1': case '2': case '3':
1995 case '4': case '5': case '6': case '7':
1996 /* at most three octal digits */
2001 n
= n
* 8 + c
- '0';
2005 n
= n
* 8 + c
- '0';
2010 goto add_char_nonext
;
2018 if (c
>= 'a' && c
<= 'f')
2020 else if (c
>= 'A' && c
<= 'F')
2030 goto add_char_nonext
;
2054 goto invalid_escape
;
2064 if (c
>= '!' && c
<= '~')
2065 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
2067 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
2074 cstr_ccat(outstr
, c
);
2076 cstr_wccat(outstr
, c
);
2078 /* add a trailing '\0' */
2080 cstr_ccat(outstr
, '\0');
2082 cstr_wccat(outstr
, '\0');
2085 static void parse_string(const char *s
, int len
)
2087 uint8_t buf
[1000], *p
= buf
;
2090 if ((is_long
= *s
== 'L'))
2094 if (len
>= sizeof buf
)
2095 p
= tcc_malloc(len
+ 1);
2099 cstr_reset(&tokcstr
);
2100 parse_escape_string(&tokcstr
, p
, is_long
);
2106 /* XXX: make it portable */
2110 char_size
= sizeof(nwchar_t
);
2111 if (tokcstr
.size
<= char_size
)
2112 tcc_error("empty character constant");
2113 if (tokcstr
.size
> 2 * char_size
)
2114 tcc_warning("multi-character character constant");
2116 tokc
.i
= *(int8_t *)tokcstr
.data
;
2119 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2123 tokc
.str
.size
= tokcstr
.size
;
2124 tokc
.str
.data
= tokcstr
.data
;
2132 /* we use 64 bit numbers */
2135 /* bn = (bn << shift) | or_val */
2136 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2140 for(i
=0;i
<BN_SIZE
;i
++) {
2142 bn
[i
] = (v
<< shift
) | or_val
;
2143 or_val
= v
>> (32 - shift
);
2147 static void bn_zero(unsigned int *bn
)
2150 for(i
=0;i
<BN_SIZE
;i
++) {
2155 /* parse number in null terminated string 'p' and return it in the
2157 static void parse_number(const char *p
)
2159 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2161 unsigned int bn
[BN_SIZE
];
2172 goto float_frac_parse
;
2173 } else if (t
== '0') {
2174 if (ch
== 'x' || ch
== 'X') {
2178 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2184 /* parse all digits. cannot check octal numbers at this stage
2185 because of floating point constants */
2187 if (ch
>= 'a' && ch
<= 'f')
2189 else if (ch
>= 'A' && ch
<= 'F')
2197 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2199 tcc_error("number too long");
2205 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2206 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2208 /* NOTE: strtox should support that for hexa numbers, but
2209 non ISOC99 libcs do not support it, so we prefer to do
2211 /* hexadecimal or binary floats */
2212 /* XXX: handle overflows */
2224 } else if (t
>= 'a') {
2226 } else if (t
>= 'A') {
2231 bn_lshift(bn
, shift
, t
);
2238 if (t
>= 'a' && t
<= 'f') {
2240 } else if (t
>= 'A' && t
<= 'F') {
2242 } else if (t
>= '0' && t
<= '9') {
2248 tcc_error("invalid digit");
2249 bn_lshift(bn
, shift
, t
);
2254 if (ch
!= 'p' && ch
!= 'P')
2261 } else if (ch
== '-') {
2265 if (ch
< '0' || ch
> '9')
2266 expect("exponent digits");
2267 while (ch
>= '0' && ch
<= '9') {
2268 exp_val
= exp_val
* 10 + ch
- '0';
2271 exp_val
= exp_val
* s
;
2273 /* now we can generate the number */
2274 /* XXX: should patch directly float number */
2275 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2276 d
= ldexp(d
, exp_val
- frac_bits
);
2281 /* float : should handle overflow */
2283 } else if (t
== 'L') {
2285 #ifdef TCC_TARGET_PE
2290 /* XXX: not large enough */
2291 tokc
.ld
= (long double)d
;
2298 /* decimal floats */
2300 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2305 while (ch
>= '0' && ch
<= '9') {
2306 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2312 if (ch
== 'e' || ch
== 'E') {
2313 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2317 if (ch
== '-' || ch
== '+') {
2318 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2323 if (ch
< '0' || ch
> '9')
2324 expect("exponent digits");
2325 while (ch
>= '0' && ch
<= '9') {
2326 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2338 tokc
.f
= strtof(token_buf
, NULL
);
2339 } else if (t
== 'L') {
2341 #ifdef TCC_TARGET_PE
2343 tokc
.d
= strtod(token_buf
, NULL
);
2346 tokc
.ld
= strtold(token_buf
, NULL
);
2350 tokc
.d
= strtod(token_buf
, NULL
);
2354 unsigned long long n
, n1
;
2355 int lcount
, ucount
, must_64bit
;
2358 /* integer number */
2361 if (b
== 10 && *q
== '0') {
2368 /* no need for checks except for base 10 / 8 errors */
2378 tcc_error("invalid digit");
2381 /* detect overflow */
2382 /* XXX: this test is not reliable */
2384 tcc_error("integer constant overflow");
2387 /* Determine the characteristics (unsigned and/or 64bit) the type of
2388 the constant must have according to the constant suffix(es) */
2389 lcount
= ucount
= must_64bit
= 0;
2395 tcc_error("three 'l's in integer constant");
2396 if (lcount
&& *(p
- 1) != ch
)
2397 tcc_error("incorrect integer suffix: %s", p1
);
2399 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2404 } else if (t
== 'U') {
2406 tcc_error("two 'u's in integer constant");
2414 /* Whether 64 bits are needed to hold the constant's value */
2415 if (n
& 0xffffffff00000000LL
|| must_64bit
) {
2423 /* Whether type must be unsigned to hold the constant's value */
2424 if (ucount
|| ((n1
>> 31) && (b
!= 10))) {
2425 if (tok
== TOK_CLLONG
)
2429 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2430 } else if (n1
>> 31) {
2431 if (tok
== TOK_CINT
)
2434 tcc_error("integer constant overflow");
2440 tcc_error("invalid number\n");
2444 #define PARSE2(c1, tok1, c2, tok2) \
2455 /* return next token without macro substitution */
2456 static inline void next_nomacro1(void)
2458 int t
, c
, is_long
, len
;
2471 if (parse_flags
& PARSE_FLAG_SPACES
)
2472 goto keep_tok_flags
;
2473 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2482 /* first look if it is in fact an end of buffer */
2483 c
= handle_stray1(p
);
2490 TCCState
*s1
= tcc_state
;
2491 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2492 && !(tok_flags
& TOK_FLAG_EOF
)) {
2493 tok_flags
|= TOK_FLAG_EOF
;
2495 goto keep_tok_flags
;
2496 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2498 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2499 tcc_error("missing #endif");
2500 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2501 /* no include left : end of file. */
2504 tok_flags
&= ~TOK_FLAG_EOF
;
2505 /* pop include file */
2507 /* test if previous '#endif' was after a #ifdef at
2509 if (tok_flags
& TOK_FLAG_ENDIF
) {
2511 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2513 search_cached_include(s1
, file
->filename
, 1)
2514 ->ifndef_macro
= file
->ifndef_macro_saved
;
2515 tok_flags
&= ~TOK_FLAG_ENDIF
;
2518 /* add end of include file debug info */
2519 if (tcc_state
->do_debug
) {
2520 put_stabd(N_EINCL
, 0, 0);
2522 /* pop include stack */
2524 s1
->include_stack_ptr
--;
2533 tok_flags
|= TOK_FLAG_BOL
;
2536 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2539 goto keep_tok_flags
;
2544 if ((tok_flags
& TOK_FLAG_BOL
) &&
2545 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2547 preprocess(tok_flags
& TOK_FLAG_BOF
);
2553 tok
= TOK_TWOSHARPS
;
2555 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2556 p
= parse_line_comment(p
- 1);
2565 /* dollar is allowed to start identifiers when not parsing asm */
2567 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2568 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2571 case 'a': case 'b': case 'c': case 'd':
2572 case 'e': case 'f': case 'g': case 'h':
2573 case 'i': case 'j': case 'k': case 'l':
2574 case 'm': case 'n': case 'o': case 'p':
2575 case 'q': case 'r': case 's': case 't':
2576 case 'u': case 'v': case 'w': case 'x':
2578 case 'A': case 'B': case 'C': case 'D':
2579 case 'E': case 'F': case 'G': case 'H':
2580 case 'I': case 'J': case 'K':
2581 case 'M': case 'N': case 'O': case 'P':
2582 case 'Q': case 'R': case 'S': case 'T':
2583 case 'U': case 'V': case 'W': case 'X':
2589 h
= TOK_HASH_FUNC(h
, c
);
2590 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2591 h
= TOK_HASH_FUNC(h
, c
);
2596 /* fast case : no stray found, so we have the full token
2597 and we have already hashed it */
2598 h
&= (TOK_HASH_SIZE
- 1);
2599 pts
= &hash_ident
[h
];
2604 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2606 pts
= &(ts
->hash_next
);
2608 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2612 cstr_reset(&tokcstr
);
2613 cstr_cat(&tokcstr
, p1
, len
);
2617 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2619 cstr_ccat(&tokcstr
, c
);
2622 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2628 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2630 goto parse_ident_fast
;
2633 if (c
== '\'' || c
== '\"') {
2637 cstr_reset(&tokcstr
);
2638 cstr_ccat(&tokcstr
, 'L');
2639 goto parse_ident_slow
;
2644 case '0': case '1': case '2': case '3':
2645 case '4': case '5': case '6': case '7':
2649 /* after the first digit, accept digits, alpha, '.' or sign if
2650 prefixed by 'eEpP' */
2652 cstr_reset(&tokcstr
);
2654 cstr_ccat(&tokcstr
, t
);
2655 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2657 || ((c
== '+' || c
== '-')
2658 && (((t
== 'e' || t
== 'E')
2659 && !(parse_flags
& PARSE_FLAG_ASM_FILE
2660 /* 0xe+1 is 3 tokens in asm */
2661 && ((char*)tokcstr
.data
)[0] == '0'
2662 && toup(((char*)tokcstr
.data
)[1]) == 'X'))
2663 || t
== 'p' || t
== 'P'))))
2668 /* We add a trailing '\0' to ease parsing */
2669 cstr_ccat(&tokcstr
, '\0');
2670 tokc
.str
.size
= tokcstr
.size
;
2671 tokc
.str
.data
= tokcstr
.data
;
2676 /* special dot handling because it can also start a number */
2681 } else if ((isidnum_table
['.' - CH_EOF
] & IS_ID
)
2682 && (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))) {
2684 goto parse_ident_fast
;
2685 } else if (c
== '.') {
2691 *--p
= '.'; /* may underflow into file->unget[] */
2702 cstr_reset(&tokcstr
);
2704 cstr_ccat(&tokcstr
, 'L');
2705 cstr_ccat(&tokcstr
, c
);
2706 p
= parse_pp_string(p
, c
, &tokcstr
);
2707 cstr_ccat(&tokcstr
, c
);
2708 cstr_ccat(&tokcstr
, '\0');
2709 tokc
.str
.size
= tokcstr
.size
;
2710 tokc
.str
.data
= tokcstr
.data
;
2719 } else if (c
== '<') {
2736 } else if (c
== '>') {
2754 } else if (c
== '=') {
2767 } else if (c
== '=') {
2780 } else if (c
== '=') {
2793 } else if (c
== '=') {
2796 } else if (c
== '>') {
2804 PARSE2('!', '!', '=', TOK_NE
)
2805 PARSE2('=', '=', '=', TOK_EQ
)
2806 PARSE2('*', '*', '=', TOK_A_MUL
)
2807 PARSE2('%', '%', '=', TOK_A_MOD
)
2808 PARSE2('^', '^', '=', TOK_A_XOR
)
2810 /* comments or operator */
2814 p
= parse_comment(p
);
2815 /* comments replaced by a blank */
2817 goto keep_tok_flags
;
2818 } else if (c
== '/') {
2819 p
= parse_line_comment(p
);
2821 goto keep_tok_flags
;
2822 } else if (c
== '=') {
2842 case '@': /* only used in assembler */
2848 if (c
>= 0x80 && c
<= 0xFF) /* utf8 identifiers */
2849 goto parse_ident_fast
;
2850 if (parse_flags
& PARSE_FLAG_ASM_FILE
)
2852 tcc_error("unrecognized character \\x%02x", c
);
2858 #if defined(PARSE_DEBUG)
2859 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2863 /* return next token without macro substitution. Can read input from
2865 static void next_nomacro_spc(void)
2871 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2872 if (tok
== TOK_LINENUM
) {
2873 file
->line_num
= tokc
.i
;
2882 ST_FUNC
void next_nomacro(void)
2886 } while (tok
< 256 && (isidnum_table
[tok
- CH_EOF
] & IS_SPC
));
2890 static void macro_subst(
2891 TokenString
*tok_str
,
2893 const int *macro_str
,
2897 /* substitute arguments in replacement lists in macro_str by the values in
2898 args (field d) and return allocated string */
2899 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2911 TOK_GET(&t
, ¯o_str
, &cval
);
2916 TOK_GET(&t
, ¯o_str
, &cval
);
2919 s
= sym_find2(args
, t
);
2922 cstr_ccat(&cstr
, '\"');
2926 TOK_GET(&t
, &st
, &cval
);
2927 if (t
!= TOK_PLCHLDR
2929 && 0 == check_space(t
, &spc
)) {
2930 const char *s
= get_tok_str(t
, &cval
);
2932 if (t
== TOK_PPSTR
&& *s
!= '\'')
2933 add_char(&cstr
, *s
);
2935 cstr_ccat(&cstr
, *s
);
2941 cstr_ccat(&cstr
, '\"');
2942 cstr_ccat(&cstr
, '\0');
2944 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
2947 cval
.str
.size
= cstr
.size
;
2948 cval
.str
.data
= cstr
.data
;
2949 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
2953 expect("macro parameter after '#'");
2955 } else if (t
>= TOK_IDENT
) {
2956 s
= sym_find2(args
, t
);
2960 /* if '##' is present before or after, no arg substitution */
2961 if (*macro_str
== TOK_TWOSHARPS
|| t1
== TOK_TWOSHARPS
) {
2962 /* special case for var arg macros : ## eats the ','
2963 if empty VA_ARGS variable. */
2964 if (t1
== TOK_TWOSHARPS
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
2966 /* suppress ',' '##' */
2969 /* suppress '##' and add variable */
2976 TOK_GET(&t1
, &st
, &cval
);
2979 tok_str_add2(&str
, t1
, &cval
);
2985 /* NOTE: the stream cannot be read when macro
2986 substituing an argument */
2987 macro_subst(&str
, nested_list
, st
, 0);
2989 if (str
.len
== l0
) /* exanded to empty string */
2990 tok_str_add(&str
, TOK_PLCHLDR
);
2992 tok_str_add(&str
, t
);
2995 tok_str_add2(&str
, t
, &cval
);
2999 tok_str_add(&str
, 0);
3003 static char const ab_month_name
[12][4] =
3005 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3006 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3009 /* peek or read [ws_str == NULL] next token from function macro call,
3010 walking up macro levels up to the file if necessary */
3011 static int next_argstream(Sym
**nested_list
, int can_read_stream
, TokenString
*ws_str
)
3019 p
= macro_ptr
, t
= *p
;
3021 while (is_space(t
) || TOK_LINEFEED
== t
)
3022 tok_str_add(ws_str
, t
), t
= *++p
;
3024 if (t
== 0 && can_read_stream
) {
3026 /* also, end of scope for nested defined symbol */
3028 while (sa
&& sa
->v
== 0)
3037 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
3040 uint8_t *p
= file
->buf_ptr
;
3043 p
= parse_comment(p
);
3044 file
->buf_ptr
= p
- 1;
3045 } else if (c
== '/') {
3046 p
= parse_line_comment(p
);
3047 file
->buf_ptr
= p
- 1;
3052 if (!(ch
== '\f' || ch
== '\v' || ch
== '\r'))
3053 tok_str_add(ws_str
, ch
);
3067 /* do macro substitution of current token with macro 's' and add
3068 result to (tok_str,tok_len). 'nested_list' is the list of all
3069 macros we got inside to avoid recursing. Return non zero if no
3070 substitution needs to be done */
3071 static int macro_subst_tok(
3072 TokenString
*tok_str
,
3075 int can_read_stream
)
3077 Sym
*args
, *sa
, *sa1
;
3078 int parlevel
, *mstr
, t
, t1
, spc
;
3085 /* if symbol is a macro, prepare substitution */
3086 /* special macros */
3087 if (tok
== TOK___LINE__
) {
3088 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
3092 } else if (tok
== TOK___FILE__
) {
3093 cstrval
= file
->filename
;
3095 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3100 tm
= localtime(&ti
);
3101 if (tok
== TOK___DATE__
) {
3102 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3103 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3105 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3106 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3113 cstr_cat(&cstr
, cstrval
, 0);
3114 cval
.str
.size
= cstr
.size
;
3115 cval
.str
.data
= cstr
.data
;
3116 tok_str_add2(tok_str
, t1
, &cval
);
3119 int saved_parse_flags
= parse_flags
;
3122 if (s
->type
.t
== MACRO_FUNC
) {
3123 /* whitespace between macro name and argument list */
3125 tok_str_new(&ws_str
);
3128 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3129 | PARSE_FLAG_ACCEPT_STRAYS
;
3131 /* get next token from argument stream */
3132 t
= next_argstream(nested_list
, can_read_stream
, &ws_str
);
3134 /* not a macro substitution after all, restore the
3135 * macro token plus all whitespace we've read.
3136 * whitespace is intentionally not merged to preserve
3138 parse_flags
= saved_parse_flags
;
3139 tok_str_add(tok_str
, tok
);
3140 if (parse_flags
& PARSE_FLAG_SPACES
) {
3142 for (i
= 0; i
< ws_str
.len
; i
++)
3143 tok_str_add(tok_str
, ws_str
.str
[i
]);
3145 tok_str_free_str(ws_str
.str
);
3148 tok_str_free_str(ws_str
.str
);
3150 next_nomacro(); /* eat '(' */
3152 /* argument macro */
3155 /* NOTE: empty args are allowed, except if no args */
3158 next_argstream(nested_list
, can_read_stream
, NULL
);
3159 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3161 /* handle '()' case */
3162 if (!args
&& !sa
&& tok
== ')')
3165 tcc_error("macro '%s' used with too many args",
3166 get_tok_str(s
->v
, 0));
3169 /* NOTE: non zero sa->t indicates VA_ARGS */
3170 while ((parlevel
> 0 ||
3172 (tok
!= ',' || sa
->type
.t
)))) {
3173 if (tok
== TOK_EOF
|| tok
== 0)
3177 else if (tok
== ')')
3179 if (tok
== TOK_LINEFEED
)
3181 if (!check_space(tok
, &spc
))
3182 tok_str_add2(&str
, tok
, &tokc
);
3183 next_argstream(nested_list
, can_read_stream
, NULL
);
3188 tok_str_add(&str
, 0);
3189 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3193 /* special case for gcc var args: add an empty
3194 var arg argument if it is omitted */
3195 if (sa
&& sa
->type
.t
&& gnu_ext
)
3203 tcc_error("macro '%s' used with too few args",
3204 get_tok_str(s
->v
, 0));
3207 parse_flags
= saved_parse_flags
;
3209 /* now subst each arg */
3210 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3215 tok_str_free_str(sa
->d
);
3221 sym_push2(nested_list
, s
->v
, 0, 0);
3222 parse_flags
= saved_parse_flags
;
3223 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
| 2);
3225 /* pop nested defined symbol */
3227 *nested_list
= sa1
->prev
;
3230 tok_str_free_str(mstr
);
3235 static int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3241 if (t1
!= TOK_PLCHLDR
)
3242 cstr_cat(&cstr
, get_tok_str(t1
, v1
), -1);
3244 if (t2
!= TOK_PLCHLDR
)
3245 cstr_cat(&cstr
, get_tok_str(t2
, v2
), -1);
3246 cstr_ccat(&cstr
, '\0');
3248 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3249 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3252 if (0 == *file
->buf_ptr
)
3256 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid"
3257 " preprocessing token", n
, cstr
.data
, (char*)cstr
.data
+ n
);
3262 //printf("paste <%s>\n", (char*)cstr.data);
3267 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3268 return the resulting string (which must be freed). */
3269 static inline int *macro_twosharps(const int *ptr0
)
3273 TokenString macro_str1
;
3274 int start_of_nosubsts
= -1;
3277 /* we search the first '##' */
3278 for (ptr
= ptr0
;;) {
3279 TOK_GET(&t
, &ptr
, &cval
);
3280 if (t
== TOK_TWOSHARPS
)
3286 tok_str_new(¯o_str1
);
3288 //tok_print(" $$$", ptr0);
3289 for (ptr
= ptr0
;;) {
3290 TOK_GET(&t
, &ptr
, &cval
);
3293 if (t
== TOK_TWOSHARPS
)
3295 while (*ptr
== TOK_TWOSHARPS
) {
3297 /* given 'a##b', remove nosubsts preceding 'a' */
3298 if (start_of_nosubsts
>= 0)
3299 macro_str1
.len
= start_of_nosubsts
;
3300 /* given 'a##b', remove nosubsts preceding 'b' */
3301 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3303 if (t1
&& t1
!= TOK_TWOSHARPS
) {
3304 TOK_GET(&t1
, &ptr
, &cv1
);
3305 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3306 if (paste_tokens(t
, &cval
, t1
, &cv1
)) {
3307 t
= tok
, cval
= tokc
;
3309 tok_str_add2(¯o_str1
, t
, &cval
);
3315 if (t
== TOK_NOSUBST
) {
3316 if (start_of_nosubsts
< 0)
3317 start_of_nosubsts
= macro_str1
.len
;
3319 start_of_nosubsts
= -1;
3321 tok_str_add2(¯o_str1
, t
, &cval
);
3323 tok_str_add(¯o_str1
, 0);
3324 //tok_print(" ###", macro_str1.str);
3325 return macro_str1
.str
;
3328 /* do macro substitution of macro_str and add result to
3329 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3330 inside to avoid recursing. */
3331 static void macro_subst(
3332 TokenString
*tok_str
,
3334 const int *macro_str
,
3340 int t
, spc
, nosubst
;
3342 int *macro_str1
= NULL
;
3344 /* first scan for '##' operator handling */
3348 /* first scan for '##' operator handling */
3349 if (can_read_stream
& 1) {
3350 macro_str1
= macro_twosharps(ptr
);
3356 TOK_GET(&t
, &ptr
, &cval
);
3360 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3365 /* if nested substitution, do nothing */
3366 if (sym_find2(*nested_list
, t
)) {
3367 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3368 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3374 str
.str
= (int*)ptr
;
3375 begin_macro(&str
, 2);
3378 macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
3380 if (str
.alloc
== 3) {
3381 /* already finished by reading function macro arguments */
3389 spc
= (tok_str
->len
&&
3390 is_space(tok_last(tok_str
->str
,
3391 tok_str
->str
+ tok_str
->len
)));
3395 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3396 tcc_error("stray '\\' in program");
3399 if (!check_space(t
, &spc
))
3400 tok_str_add2(tok_str
, t
, &cval
);
3402 if (t
== TOK_NOSUBST
)
3407 tok_str_free_str(macro_str1
);
3411 /* return next token with macro substitution */
3412 ST_FUNC
void next(void)
3415 if (parse_flags
& PARSE_FLAG_SPACES
)
3421 if (tok
== TOK_NOSUBST
|| tok
== TOK_PLCHLDR
) {
3422 /* discard preprocessor markers */
3424 } else if (tok
== 0) {
3425 /* end of macro or unget token string */
3429 } else if (tok
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3431 /* if reading from file, try to substitute macros */
3432 s
= define_find(tok
);
3434 Sym
*nested_list
= NULL
;
3436 macro_subst_tok(&tokstr_buf
, &nested_list
, s
, 1);
3437 tok_str_add(&tokstr_buf
, 0);
3438 begin_macro(&tokstr_buf
, 2);
3442 /* convert preprocessor tokens into C tokens */
3443 if (tok
== TOK_PPNUM
) {
3444 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3445 parse_number((char *)tokc
.str
.data
);
3446 } else if (tok
== TOK_PPSTR
) {
3447 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3448 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3452 /* push back current token and set current token to 'last_tok'. Only
3453 identifier case handled for labels. */
3454 ST_INLN
void unget_tok(int last_tok
)
3457 TokenString
*str
= tok_str_alloc();
3458 tok_str_add2(str
, tok
, &tokc
);
3459 tok_str_add(str
, 0);
3460 begin_macro(str
, 1);
3464 ST_FUNC
void preprocess_start(TCCState
*s1
)
3467 s1
->include_stack_ptr
= s1
->include_stack
;
3468 /* XXX: move that before to avoid having to initialize
3469 file->ifdef_stack_ptr ? */
3470 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3471 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3474 pvtop
= vtop
= vstack
- 1;
3475 s1
->pack_stack
[0] = 0;
3476 s1
->pack_stack_ptr
= s1
->pack_stack
;
3478 set_idnum('$', s1
->dollars_in_identifiers
? IS_ID
: 0);
3479 set_idnum('.', (parse_flags
& PARSE_FLAG_ASM_FILE
) ? IS_ID
: 0);
3480 buf
= tcc_malloc(3 + strlen(file
->filename
));
3481 sprintf(buf
, "\"%s\"", file
->filename
);
3482 tcc_undefine_symbol(s1
, "__BASE_FILE__");
3483 tcc_define_symbol(s1
, "__BASE_FILE__", buf
);
3485 if (s1
->nb_cmd_include_files
) {
3489 for (i
= 0; i
< s1
->nb_cmd_include_files
; i
++) {
3490 cstr_cat(&cstr
, "#include \"", -1);
3491 cstr_cat(&cstr
, s1
->cmd_include_files
[i
], -1);
3492 cstr_cat(&cstr
, "\"\n", -1);
3494 *s1
->include_stack_ptr
++ = file
;
3495 tcc_open_bf(s1
, "<command line>", cstr
.size
);
3496 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3501 ST_FUNC
void tccpp_new(TCCState
*s
)
3506 /* might be used in error() before preprocess_start() */
3507 s
->include_stack_ptr
= s
->include_stack
;
3509 /* init isid table */
3510 for(i
= CH_EOF
; i
<128; i
++)
3512 is_space(i
) ? IS_SPC
3517 for(i
= 128; i
<256; i
++)
3518 set_idnum(i
, IS_ID
);
3520 /* init allocators */
3521 tal_new(&toksym_alloc
, TOKSYM_TAL_LIMIT
, TOKSYM_TAL_SIZE
);
3522 tal_new(&tokstr_alloc
, TOKSTR_TAL_LIMIT
, TOKSTR_TAL_SIZE
);
3523 tal_new(&cstr_alloc
, CSTR_TAL_LIMIT
, CSTR_TAL_SIZE
);
3525 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3526 cstr_new(&cstr_buf
);
3527 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
3528 tok_str_new(&tokstr_buf
);
3529 tok_str_realloc(&tokstr_buf
, TOKSTR_MAX_SIZE
);
3531 tok_ident
= TOK_IDENT
;
3540 tok_alloc(p
, r
- p
- 1);
3545 ST_FUNC
void tccpp_delete(TCCState
*s
)
3549 /* free -D and compiler defines */
3552 /* cleanup from error/setjmp */
3558 n
= tok_ident
- TOK_IDENT
;
3559 for(i
= 0; i
< n
; i
++)
3560 tal_free(toksym_alloc
, table_ident
[i
]);
3561 tcc_free(table_ident
);
3564 /* free static buffers */
3565 cstr_free(&tokcstr
);
3566 cstr_free(&cstr_buf
);
3567 tok_str_free_str(tokstr_buf
.str
);
3569 /* free allocators */
3570 tal_delete(toksym_alloc
);
3571 toksym_alloc
= NULL
;
3572 tal_delete(tokstr_alloc
);
3573 tokstr_alloc
= NULL
;
3574 tal_delete(cstr_alloc
);
3578 /* ------------------------------------------------------------------------- */
3579 /* tcc -E [-P[1]] [-dD} support */
3581 static void tok_print(const char *msg
, const int *str
)
3587 fp
= tcc_state
->ppfp
;
3588 if (!fp
|| !tcc_state
->dflag
)
3591 fprintf(fp
, "%s ", msg
);
3593 TOK_GET(&t
, &str
, &cval
);
3596 fprintf(fp
,"%s", get_tok_str(t
, &cval
));
3601 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3603 int d
= f
->line_num
- f
->line_ref
;
3608 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
) {
3610 } else if (level
== 0 && f
->line_ref
&& d
< 8) {
3612 fputs("\n", s1
->ppfp
), --d
;
3613 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3614 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3616 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3617 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3619 f
->line_ref
= f
->line_num
;
3622 static void define_print(TCCState
*s1
, int v
)
3628 if (NULL
== s
|| NULL
== s
->d
)
3632 fprintf(fp
, "#define %s", get_tok_str(v
, NULL
));
3633 if (s
->type
.t
== MACRO_FUNC
) {
3638 fprintf(fp
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
3645 tok_print("", s
->d
);
3648 static void pp_debug_defines(TCCState
*s1
)
3659 pp_line(s1
, file
, 0);
3660 file
->line_ref
= ++file
->line_num
;
3664 vs
= get_tok_str(v
, NULL
);
3665 if (t
== TOK_DEFINE
) {
3666 define_print(s1
, v
);
3667 } else if (t
== TOK_UNDEF
) {
3668 fprintf(fp
, "#undef %s\n", vs
);
3669 } else if (t
== TOK_push_macro
) {
3670 fprintf(fp
, "#pragma push_macro(\"%s\")\n", vs
);
3671 } else if (t
== TOK_pop_macro
) {
3672 fprintf(fp
, "#pragma pop_macro(\"%s\")\n", vs
);
3677 static void pp_debug_builtins(TCCState
*s1
)
3680 for (v
= TOK_IDENT
; v
< tok_ident
; ++v
)
3681 define_print(s1
, v
);
3684 /* Add a space between tokens a and b to avoid unwanted textual pasting */
3685 static int pp_need_space(int a
, int b
)
3687 return 'E' == a
? '+' == b
|| '-' == b
3688 : '+' == a
? TOK_INC
== b
|| '+' == b
3689 : '-' == a
? TOK_DEC
== b
|| '-' == b
3690 : a
>= TOK_IDENT
? b
>= TOK_IDENT
3694 /* maybe hex like 0x1e */
3695 static int pp_check_he0xE(int t
, const char *p
)
3697 if (t
== TOK_PPNUM
&& toup(strchr(p
, 0)[-1]) == 'E')
3702 /* Preprocess the current file */
3703 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3705 BufferedFile
**iptr
;
3706 int token_seen
, spcs
, level
;
3710 preprocess_start(s1
);
3711 ch
= file
->buf_ptr
[0];
3712 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3713 parse_flags
= PARSE_FLAG_PREPROCESS
3714 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3715 | PARSE_FLAG_LINEFEED
3717 | PARSE_FLAG_ACCEPT_STRAYS
3719 define_start
= define_stack
;
3721 /* Credits to Fabrice Bellard's initial revision to demonstrate its
3722 capability to compile and run itself, provided all numbers are
3723 given as decimals. tcc -E -P10 will do. */
3724 if (s1
->Pflag
== 1 + 10)
3725 parse_flags
|= PARSE_FLAG_TOK_NUM
, s1
->Pflag
= 1;
3728 /* for PP benchmarks */
3729 do next(); while (tok
!= TOK_EOF
);
3730 free_defines(define_start
);
3734 if (s1
->dflag
& 1) {
3735 pp_debug_builtins(s1
);
3739 token_seen
= TOK_LINEFEED
, spcs
= 0;
3740 pp_line(s1
, file
, 0);
3743 iptr
= s1
->include_stack_ptr
;
3747 level
= s1
->include_stack_ptr
- iptr
;
3750 pp_line(s1
, *iptr
, 0);
3751 pp_line(s1
, file
, level
);
3755 pp_debug_defines(s1
);
3760 if (token_seen
== TOK_LINEFEED
) {
3765 if (tok
== TOK_LINEFEED
) {
3769 pp_line(s1
, file
, 0);
3770 } else if (tok
== TOK_LINEFEED
) {
3773 spcs
= pp_need_space(token_seen
, tok
);
3777 fputs(" ", s1
->ppfp
), --spcs
;
3778 fputs(p
= get_tok_str(tok
, &tokc
), s1
->ppfp
);
3779 token_seen
= pp_check_he0xE(tok
, p
);;
3781 /* reset define stack, but keep -D and built-ins */
3782 free_defines(define_start
);
3786 /* ------------------------------------------------------------------------- */