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 /* additional informations about token */
28 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
29 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
30 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
31 #define TOK_FLAG_EOF 0x0008 /* end of file */
33 ST_DATA
int parse_flags
;
34 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
35 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
36 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
37 token. line feed is also
39 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
40 #define PARSE_FLAG_SPACES 0x0010 /* next() returns space tokens (for -E) */
42 ST_DATA
struct BufferedFile
*file
;
45 ST_DATA
const int *macro_ptr
;
46 ST_DATA CString tokcstr
; /* current parsed string, if any */
48 /* display benchmark infos */
49 ST_DATA
int total_lines
;
50 ST_DATA
int total_bytes
;
51 ST_DATA
int tok_ident
;
52 ST_DATA TokenSym
**table_ident
;
54 /* ------------------------------------------------------------------------- */
56 static int *macro_ptr_allocated
;
57 static const int *unget_saved_macro_ptr
;
58 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
59 static int unget_buffer_enabled
;
60 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
61 static char token_buf
[STRING_MAX_SIZE
+ 1];
62 /* true if isid(c) || isnum(c) */
63 static unsigned char isidnum_table
[256-CH_EOF
];
65 static const char tcc_keywords
[] =
66 #define DEF(id, str) str "\0"
71 /* WARNING: the content of this string encodes token numbers */
72 static const unsigned char tok_two_chars
[] =
73 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
74 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
77 struct macro_level
*prev
;
81 ST_FUNC
void next_nomacro(void);
82 static void next_nomacro_spc(void);
83 static void macro_subst(
87 struct macro_level
**can_read_stream
90 ST_FUNC
void skip(int c
)
93 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
97 ST_FUNC
void expect(const char *msg
)
99 tcc_error("%s expected", msg
);
102 /* ------------------------------------------------------------------------- */
103 /* CString handling */
104 static void cstr_realloc(CString
*cstr
, int new_size
)
109 size
= cstr
->size_allocated
;
111 size
= 8; /* no need to allocate a too small first string */
112 while (size
< new_size
)
114 data
= tcc_realloc(cstr
->data_allocated
, size
);
116 tcc_error("memory full");
117 cstr
->data_allocated
= data
;
118 cstr
->size_allocated
= size
;
123 ST_INLN
void cstr_ccat(CString
*cstr
, int ch
)
126 size
= cstr
->size
+ 1;
127 if (size
> cstr
->size_allocated
)
128 cstr_realloc(cstr
, size
);
129 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
133 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
)
145 /* add a wide char */
146 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
149 size
= cstr
->size
+ sizeof(nwchar_t
);
150 if (size
> cstr
->size_allocated
)
151 cstr_realloc(cstr
, size
);
152 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
156 ST_FUNC
void cstr_new(CString
*cstr
)
158 memset(cstr
, 0, sizeof(CString
));
161 /* free string and reset it to NULL */
162 ST_FUNC
void cstr_free(CString
*cstr
)
164 tcc_free(cstr
->data_allocated
);
169 ST_FUNC
void add_char(CString
*cstr
, int c
)
171 if (c
== '\'' || c
== '\"' || c
== '\\') {
172 /* XXX: could be more precise if char or string */
173 cstr_ccat(cstr
, '\\');
175 if (c
>= 32 && c
<= 126) {
178 cstr_ccat(cstr
, '\\');
180 cstr_ccat(cstr
, 'n');
182 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
183 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
184 cstr_ccat(cstr
, '0' + (c
& 7));
189 /* ------------------------------------------------------------------------- */
190 /* allocate a new token */
191 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
193 TokenSym
*ts
, **ptable
;
196 if (tok_ident
>= SYM_FIRST_ANOM
)
197 tcc_error("memory full");
199 /* expand token table if needed */
200 i
= tok_ident
- TOK_IDENT
;
201 if ((i
% TOK_ALLOC_INCR
) == 0) {
202 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
204 tcc_error("memory full");
205 table_ident
= ptable
;
208 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
210 ts
->tok
= tok_ident
++;
211 ts
->sym_define
= NULL
;
212 ts
->sym_label
= NULL
;
213 ts
->sym_struct
= NULL
;
214 ts
->sym_identifier
= NULL
;
216 ts
->hash_next
= NULL
;
217 memcpy(ts
->str
, str
, len
);
223 #define TOK_HASH_INIT 1
224 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
226 /* find a token and add it if not found */
227 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
235 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
236 h
&= (TOK_HASH_SIZE
- 1);
238 pts
= &hash_ident
[h
];
243 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
245 pts
= &(ts
->hash_next
);
247 return tok_alloc_new(pts
, str
, len
);
250 /* XXX: buffer overflow */
251 /* XXX: float tokens */
252 ST_FUNC
char *get_tok_str(int v
, CValue
*cv
)
254 static char buf
[STRING_MAX_SIZE
+ 1];
255 static CString cstr_buf
;
260 /* NOTE: to go faster, we give a fixed buffer for small strings */
261 cstr_reset(&cstr_buf
);
263 cstr_buf
.size_allocated
= sizeof(buf
);
269 /* XXX: not quite exact, but only useful for testing */
270 sprintf(p
, "%u", cv
->ui
);
274 /* XXX: not quite exact, but only useful for testing */
276 sprintf(p
, "%u", (unsigned)cv
->ull
);
278 sprintf(p
, "%Lu", cv
->ull
);
282 cstr_ccat(&cstr_buf
, 'L');
284 cstr_ccat(&cstr_buf
, '\'');
285 add_char(&cstr_buf
, cv
->i
);
286 cstr_ccat(&cstr_buf
, '\'');
287 cstr_ccat(&cstr_buf
, '\0');
291 len
= cstr
->size
- 1;
293 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
294 cstr_ccat(&cstr_buf
, '\0');
297 cstr_ccat(&cstr_buf
, 'L');
300 cstr_ccat(&cstr_buf
, '\"');
302 len
= cstr
->size
- 1;
304 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
306 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
308 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
310 cstr_ccat(&cstr_buf
, '\"');
311 cstr_ccat(&cstr_buf
, '\0');
320 return strcpy(p
, "...");
322 return strcpy(p
, "<<=");
324 return strcpy(p
, ">>=");
327 /* search in two bytes table */
328 const unsigned char *q
= tok_two_chars
;
341 } else if (v
< tok_ident
) {
342 return table_ident
[v
- TOK_IDENT
]->str
;
343 } else if (v
>= SYM_FIRST_ANOM
) {
344 /* special name for anonymous symbol */
345 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
347 /* should never happen */
352 return cstr_buf
.data
;
355 /* fill input buffer and peek next char */
356 static int tcc_peekc_slow(BufferedFile
*bf
)
359 /* only tries to read if really end of buffer */
360 if (bf
->buf_ptr
>= bf
->buf_end
) {
362 #if defined(PARSE_DEBUG)
367 len
= read(bf
->fd
, bf
->buffer
, len
);
374 bf
->buf_ptr
= bf
->buffer
;
375 bf
->buf_end
= bf
->buffer
+ len
;
376 *bf
->buf_end
= CH_EOB
;
378 if (bf
->buf_ptr
< bf
->buf_end
) {
379 return bf
->buf_ptr
[0];
381 bf
->buf_ptr
= bf
->buf_end
;
386 /* return the current character, handling end of block if necessary
388 ST_FUNC
int handle_eob(void)
390 return tcc_peekc_slow(file
);
393 /* read next char from current input file and handle end of input buffer */
394 ST_INLN
void inp(void)
396 ch
= *(++(file
->buf_ptr
));
397 /* end of buffer/file handling */
402 /* handle '\[\r]\n' */
403 static int handle_stray_noerror(void)
410 } else if (ch
== '\r') {
424 static void handle_stray(void)
426 if (handle_stray_noerror())
427 tcc_error("stray '\\' in program");
430 /* skip the stray and handle the \\n case. Output an error if
431 incorrect char after the stray */
432 static int handle_stray1(uint8_t *p
)
436 if (p
>= file
->buf_end
) {
453 /* handle just the EOB case, but not stray */
454 #define PEEKC_EOB(c, p)\
465 /* handle the complicated stray case */
471 c = handle_stray1(p);\
476 /* input with '\[\r]\n' handling. Note that this function cannot
477 handle other characters after '\', so you cannot call it inside
478 strings or comments */
479 ST_FUNC
void minp(void)
487 /* single line C++ comments */
488 static uint8_t *parse_line_comment(uint8_t *p
)
496 if (c
== '\n' || c
== CH_EOF
) {
498 } else if (c
== '\\') {
507 } else if (c
== '\r') {
525 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
534 if (c
== '\n' || c
== '*' || c
== '\\')
538 if (c
== '\n' || c
== '*' || c
== '\\')
542 /* now we can handle all the cases */
546 } else if (c
== '*') {
552 } else if (c
== '/') {
554 } else if (c
== '\\') {
559 /* skip '\[\r]\n', otherwise just skip the stray */
565 } else if (c
== '\r') {
582 /* stray, eob or eof */
587 tcc_error("unexpected end of file in comment");
588 } else if (c
== '\\') {
600 static inline void skip_spaces(void)
606 static inline int check_space(int t
, int *spc
)
617 /* parse a string without interpreting escapes */
618 static uint8_t *parse_pp_string(uint8_t *p
,
619 int sep
, CString
*str
)
627 } else if (c
== '\\') {
633 /* XXX: indicate line number of start of string */
634 tcc_error("missing terminating %c character", sep
);
635 } else if (c
== '\\') {
636 /* escape : just skip \[\r]\n */
641 } else if (c
== '\r') {
644 expect("'\n' after '\r'");
647 } else if (c
== CH_EOF
) {
648 goto unterminated_string
;
651 cstr_ccat(str
, '\\');
657 } else if (c
== '\n') {
660 } else if (c
== '\r') {
664 cstr_ccat(str
, '\r');
680 /* skip block of text until #else, #elif or #endif. skip also pairs of
682 static void preprocess_skip(void)
684 int a
, start_of_line
, c
, in_warn_or_error
;
691 in_warn_or_error
= 0;
712 } else if (c
== '\\') {
713 ch
= file
->buf_ptr
[0];
714 handle_stray_noerror();
721 if (in_warn_or_error
)
723 p
= parse_pp_string(p
, c
, NULL
);
727 if (in_warn_or_error
)
734 p
= parse_comment(p
);
735 } else if (ch
== '/') {
736 p
= parse_line_comment(p
);
746 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
748 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
750 else if (tok
== TOK_ENDIF
)
752 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
753 in_warn_or_error
= 1;
754 else if (tok
== TOK_LINEFEED
)
769 /* ParseState handling */
771 /* XXX: currently, no include file info is stored. Thus, we cannot display
772 accurate messages if the function or data definition spans multiple
775 /* save current parse state in 's' */
776 ST_FUNC
void save_parse_state(ParseState
*s
)
778 s
->line_num
= file
->line_num
;
779 s
->macro_ptr
= macro_ptr
;
784 /* restore parse state from 's' */
785 ST_FUNC
void restore_parse_state(ParseState
*s
)
787 file
->line_num
= s
->line_num
;
788 macro_ptr
= s
->macro_ptr
;
793 /* return the number of additional 'ints' necessary to store the
795 static inline int tok_ext_size(int t
)
809 tcc_error("unsupported token");
816 return LDOUBLE_SIZE
/ 4;
822 /* token string handling */
824 ST_INLN
void tok_str_new(TokenString
*s
)
828 s
->allocated_len
= 0;
829 s
->last_line_num
= -1;
832 ST_FUNC
void tok_str_free(int *str
)
837 static int *tok_str_realloc(TokenString
*s
)
841 if (s
->allocated_len
== 0) {
844 len
= s
->allocated_len
* 2;
846 str
= tcc_realloc(s
->str
, len
* sizeof(int));
848 tcc_error("memory full");
849 s
->allocated_len
= len
;
854 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
860 if (len
>= s
->allocated_len
)
861 str
= tok_str_realloc(s
);
866 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
873 /* allocate space for worst case */
874 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
875 str
= tok_str_realloc(s
);
884 str
[len
++] = cv
->tab
[0];
893 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
894 while ((len
+ nb_words
) > s
->allocated_len
)
895 str
= tok_str_realloc(s
);
896 cstr
= (CString
*)(str
+ len
);
898 cstr
->size
= cv
->cstr
->size
;
899 cstr
->data_allocated
= NULL
;
900 cstr
->size_allocated
= cstr
->size
;
901 memcpy((char *)cstr
+ sizeof(CString
),
902 cv
->cstr
->data
, cstr
->size
);
909 #if LDOUBLE_SIZE == 8
912 str
[len
++] = cv
->tab
[0];
913 str
[len
++] = cv
->tab
[1];
915 #if LDOUBLE_SIZE == 12
917 str
[len
++] = cv
->tab
[0];
918 str
[len
++] = cv
->tab
[1];
919 str
[len
++] = cv
->tab
[2];
920 #elif LDOUBLE_SIZE == 16
922 str
[len
++] = cv
->tab
[0];
923 str
[len
++] = cv
->tab
[1];
924 str
[len
++] = cv
->tab
[2];
925 str
[len
++] = cv
->tab
[3];
926 #elif LDOUBLE_SIZE != 8
927 #error add long double size support
936 /* add the current parse token in token string 's' */
937 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
941 /* save line number info */
942 if (file
->line_num
!= s
->last_line_num
) {
943 s
->last_line_num
= file
->line_num
;
944 cval
.i
= s
->last_line_num
;
945 tok_str_add2(s
, TOK_LINENUM
, &cval
);
947 tok_str_add2(s
, tok
, &tokc
);
950 /* get a token from an integer array and increment pointer
951 accordingly. we code it as a macro to avoid pointer aliasing. */
952 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
970 cv
->cstr
= (CString
*)p
;
971 cv
->cstr
->data
= (char *)p
+ sizeof(CString
);
972 p
+= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
980 #if LDOUBLE_SIZE == 16
982 #elif LDOUBLE_SIZE == 12
984 #elif LDOUBLE_SIZE == 8
987 # error add long double size support
1000 static int macro_is_equal(const int *a
, const int *b
)
1002 char buf
[STRING_MAX_SIZE
+ 1];
1006 TOK_GET(&t
, &a
, &cv
);
1007 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1008 TOK_GET(&t
, &b
, &cv
);
1009 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1015 /* defines handling */
1016 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1021 if (s
&& !macro_is_equal(s
->d
, str
))
1022 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1024 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1026 s
->next
= first_arg
;
1027 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1030 /* undefined a define symbol. Its name is just set to zero */
1031 ST_FUNC
void define_undef(Sym
*s
)
1035 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1036 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1040 ST_INLN Sym
*define_find(int v
)
1043 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1045 return table_ident
[v
]->sym_define
;
1048 /* free define stack until top reaches 'b' */
1049 ST_FUNC
void free_defines(Sym
*b
)
1057 /* do not free args or predefined defines */
1059 tok_str_free(top
->d
);
1061 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1062 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1070 ST_FUNC Sym
*label_find(int v
)
1073 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1075 return table_ident
[v
]->sym_label
;
1078 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1081 s
= sym_push2(ptop
, v
, 0, 0);
1083 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1084 if (ptop
== &global_label_stack
) {
1085 /* modify the top most local identifier, so that
1086 sym_identifier will point to 's' when popped */
1088 ps
= &(*ps
)->prev_tok
;
1095 /* pop labels until element last is reached. Look if any labels are
1096 undefined. Define symbols if '&&label' was used. */
1097 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1100 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1102 if (s
->r
== LABEL_DECLARED
) {
1103 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1104 } else if (s
->r
== LABEL_FORWARD
) {
1105 tcc_error("label '%s' used but not defined",
1106 get_tok_str(s
->v
, NULL
));
1109 /* define corresponding symbol. A size of
1111 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1115 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1121 /* eval an expression for #if/#elif */
1122 static int expr_preprocess(void)
1128 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1129 next(); /* do macro subst */
1130 if (tok
== TOK_DEFINED
) {
1135 c
= define_find(tok
) != 0;
1140 } else if (tok
>= TOK_IDENT
) {
1141 /* if undefined macro */
1145 tok_str_add_tok(&str
);
1147 tok_str_add(&str
, -1); /* simulate end of file */
1148 tok_str_add(&str
, 0);
1149 /* now evaluate C constant expression */
1150 macro_ptr
= str
.str
;
1154 tok_str_free(str
.str
);
1158 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1159 static void tok_print(int *str
)
1166 TOK_GET(&t
, &str
, &cval
);
1169 printf("%s", get_tok_str(t
, &cval
));
1175 /* parse after #define */
1176 ST_FUNC
void parse_define(void)
1178 Sym
*s
, *first
, **ps
;
1179 int v
, t
, varg
, is_vaargs
, spc
;
1184 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1185 /* XXX: should check if same macro (ANSI) */
1188 /* '(' must be just after macro definition for MACRO_FUNC */
1193 while (tok
!= ')') {
1197 if (varg
== TOK_DOTS
) {
1198 varg
= TOK___VA_ARGS__
;
1200 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1204 if (varg
< TOK_IDENT
)
1205 tcc_error("badly punctuated parameter list");
1206 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1219 /* EOF testing necessary for '-D' handling */
1220 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1221 /* remove spaces around ## and after '#' */
1222 if (TOK_TWOSHARPS
== tok
) {
1226 } else if ('#' == tok
) {
1228 } else if (check_space(tok
, &spc
)) {
1231 tok_str_add2(&str
, tok
, &tokc
);
1236 --str
.len
; /* remove trailing space */
1237 tok_str_add(&str
, 0);
1239 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
1242 define_push(v
, t
, str
.str
, first
);
1245 static inline int hash_cached_include(int type
, const char *filename
)
1247 const unsigned char *s
;
1251 h
= TOK_HASH_FUNC(h
, type
);
1254 h
= TOK_HASH_FUNC(h
, *s
);
1257 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1261 /* XXX: use a token or a hash table to accelerate matching ? */
1262 static CachedInclude
*search_cached_include(TCCState
*s1
,
1263 int type
, const char *filename
)
1267 h
= hash_cached_include(type
, filename
);
1268 i
= s1
->cached_includes_hash
[h
];
1272 e
= s1
->cached_includes
[i
- 1];
1273 if (e
->type
== type
&& !PATHCMP(e
->filename
, filename
))
1280 static inline void add_cached_include(TCCState
*s1
, int type
,
1281 const char *filename
, int ifndef_macro
)
1286 if (search_cached_include(s1
, type
, filename
))
1289 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1291 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1295 strcpy(e
->filename
, filename
);
1296 e
->ifndef_macro
= ifndef_macro
;
1297 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1298 /* add in hash table */
1299 h
= hash_cached_include(type
, filename
);
1300 e
->hash_next
= s1
->cached_includes_hash
[h
];
1301 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1304 static void pragma_parse(TCCState
*s1
)
1309 if (tok
== TOK_pack
) {
1312 #pragma pack(1) // set
1313 #pragma pack() // reset to default
1314 #pragma pack(push,1) // push & set
1315 #pragma pack(pop) // restore previous
1319 if (tok
== TOK_ASM_pop
) {
1321 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1323 tcc_error("out of pack stack");
1325 s1
->pack_stack_ptr
--;
1329 if (tok
== TOK_ASM_push
) {
1331 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1333 s1
->pack_stack_ptr
++;
1336 if (tok
!= TOK_CINT
) {
1338 tcc_error("invalid pack pragma");
1341 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1345 *s1
->pack_stack_ptr
= val
;
1351 /* is_bof is true if first non space token at beginning of file */
1352 ST_FUNC
void preprocess(int is_bof
)
1354 TCCState
*s1
= tcc_state
;
1355 int i
, c
, n
, saved_parse_flags
;
1359 saved_parse_flags
= parse_flags
;
1360 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
1361 PARSE_FLAG_LINEFEED
;
1371 s
= define_find(tok
);
1372 /* undefine symbol by putting an invalid name */
1377 case TOK_INCLUDE_NEXT
:
1378 ch
= file
->buf_ptr
[0];
1379 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1384 } else if (ch
== '\"') {
1389 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1390 if ((q
- buf
) < sizeof(buf
) - 1)
1393 if (handle_stray_noerror() == 0)
1401 /* eat all spaces and comments after include */
1402 /* XXX: slightly incorrect */
1403 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1407 /* computed #include : either we have only strings or
1408 we have anything enclosed in '<>' */
1411 if (tok
== TOK_STR
) {
1412 while (tok
!= TOK_LINEFEED
) {
1413 if (tok
!= TOK_STR
) {
1415 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1417 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1423 while (tok
!= TOK_LINEFEED
) {
1424 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1428 /* check syntax and remove '<>' */
1429 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1430 goto include_syntax
;
1431 memmove(buf
, buf
+ 1, len
- 2);
1432 buf
[len
- 2] = '\0';
1437 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1438 tcc_error("#include recursion too deep");
1440 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1441 for (i
= -2; i
< n
; ++i
) {
1442 char buf1
[sizeof file
->filename
];
1448 /* check absolute include path */
1449 if (!IS_ABSPATH(buf
))
1453 } else if (i
== -1) {
1454 /* search in current dir if "header.h" */
1457 size
= tcc_basename(file
->filename
) - file
->filename
;
1458 memcpy(buf1
, file
->filename
, size
);
1462 /* search in all the include paths */
1463 if (i
< s1
->nb_include_paths
)
1464 path
= s1
->include_paths
[i
];
1466 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1467 pstrcpy(buf1
, sizeof(buf1
), path
);
1468 pstrcat(buf1
, sizeof(buf1
), "/");
1471 pstrcat(buf1
, sizeof(buf1
), buf
);
1473 e
= search_cached_include(s1
, c
, buf1
);
1474 if (e
&& define_find(e
->ifndef_macro
)) {
1475 /* no need to parse the include because the 'ifndef macro'
1478 printf("%s: skipping %s\n", file
->filename
, buf
);
1482 fd
= tcc_open(s1
, buf1
);
1487 if (tok
== TOK_INCLUDE_NEXT
) {
1498 printf("%s: including %s\n", file
->filename
, buf1
);
1500 /* update target deps */
1501 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1503 /* XXX: fix current line init */
1504 /* push current file in stack */
1505 *s1
->include_stack_ptr
++ = file
->prev
;
1507 pstrcpy(file
->inc_filename
, sizeof(file
->inc_filename
), buf1
);
1508 /* add include file debug info */
1510 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1511 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1512 ch
= file
->buf_ptr
[0];
1515 tcc_error("include file '%s' not found", buf
);
1522 c
= expr_preprocess();
1528 if (tok
< TOK_IDENT
)
1529 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1533 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1535 file
->ifndef_macro
= tok
;
1538 c
= (define_find(tok
) != 0) ^ c
;
1540 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1541 tcc_error("memory full");
1542 *s1
->ifdef_stack_ptr
++ = c
;
1545 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1546 tcc_error("#else without matching #if");
1547 if (s1
->ifdef_stack_ptr
[-1] & 2)
1548 tcc_error("#else after #else");
1549 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1552 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1553 tcc_error("#elif without matching #if");
1554 c
= s1
->ifdef_stack_ptr
[-1];
1556 tcc_error("#elif after #else");
1557 /* last #if/#elif expression was true: we skip */
1560 c
= expr_preprocess();
1561 s1
->ifdef_stack_ptr
[-1] = c
;
1563 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1564 file
->ifndef_macro
= 0;
1574 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1575 tcc_error("#endif without matching #if");
1576 s1
->ifdef_stack_ptr
--;
1577 /* '#ifndef macro' was at the start of file. Now we check if
1578 an '#endif' is exactly at the end of file */
1579 if (file
->ifndef_macro
&&
1580 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1581 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1582 /* need to set to zero to avoid false matches if another
1583 #ifndef at middle of file */
1584 file
->ifndef_macro
= 0;
1585 while (tok
!= TOK_LINEFEED
)
1587 tok_flags
|= TOK_FLAG_ENDIF
;
1593 if (tok
!= TOK_CINT
)
1595 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
1597 if (tok
!= TOK_LINEFEED
) {
1600 pstrcpy(file
->filename
, sizeof(file
->filename
),
1601 (char *)tokc
.cstr
->data
);
1607 ch
= file
->buf_ptr
[0];
1610 while (ch
!= '\n' && ch
!= CH_EOF
) {
1611 if ((q
- buf
) < sizeof(buf
) - 1)
1614 if (handle_stray_noerror() == 0)
1621 tcc_error("#error %s", buf
);
1623 tcc_warning("#warning %s", buf
);
1629 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_PPNUM
) {
1630 /* '!' is ignored to allow C scripts. numbers are ignored
1631 to emulate cpp behaviour */
1633 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
1634 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1636 /* this is a gas line comment in an 'S' file. */
1637 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1643 /* ignore other preprocess commands or #! for C scripts */
1644 while (tok
!= TOK_LINEFEED
)
1647 parse_flags
= saved_parse_flags
;
1650 /* evaluate escape codes in a string. */
1651 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1666 case '0': case '1': case '2': case '3':
1667 case '4': case '5': case '6': case '7':
1668 /* at most three octal digits */
1673 n
= n
* 8 + c
- '0';
1677 n
= n
* 8 + c
- '0';
1682 goto add_char_nonext
;
1690 if (c
>= 'a' && c
<= 'f')
1692 else if (c
>= 'A' && c
<= 'F')
1702 goto add_char_nonext
;
1726 goto invalid_escape
;
1736 if (c
>= '!' && c
<= '~')
1737 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1739 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1746 cstr_ccat(outstr
, c
);
1748 cstr_wccat(outstr
, c
);
1750 /* add a trailing '\0' */
1752 cstr_ccat(outstr
, '\0');
1754 cstr_wccat(outstr
, '\0');
1757 /* we use 64 bit numbers */
1760 /* bn = (bn << shift) | or_val */
1761 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
1765 for(i
=0;i
<BN_SIZE
;i
++) {
1767 bn
[i
] = (v
<< shift
) | or_val
;
1768 or_val
= v
>> (32 - shift
);
1772 static void bn_zero(unsigned int *bn
)
1775 for(i
=0;i
<BN_SIZE
;i
++) {
1780 /* parse number in null terminated string 'p' and return it in the
1782 static void parse_number(const char *p
)
1784 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
1786 unsigned int bn
[BN_SIZE
];
1797 goto float_frac_parse
;
1798 } else if (t
== '0') {
1799 if (ch
== 'x' || ch
== 'X') {
1803 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
1809 /* parse all digits. cannot check octal numbers at this stage
1810 because of floating point constants */
1812 if (ch
>= 'a' && ch
<= 'f')
1814 else if (ch
>= 'A' && ch
<= 'F')
1822 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
1824 tcc_error("number too long");
1830 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
1831 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
1833 /* NOTE: strtox should support that for hexa numbers, but
1834 non ISOC99 libcs do not support it, so we prefer to do
1836 /* hexadecimal or binary floats */
1837 /* XXX: handle overflows */
1849 } else if (t
>= 'a') {
1851 } else if (t
>= 'A') {
1856 bn_lshift(bn
, shift
, t
);
1863 if (t
>= 'a' && t
<= 'f') {
1865 } else if (t
>= 'A' && t
<= 'F') {
1867 } else if (t
>= '0' && t
<= '9') {
1873 tcc_error("invalid digit");
1874 bn_lshift(bn
, shift
, t
);
1879 if (ch
!= 'p' && ch
!= 'P')
1886 } else if (ch
== '-') {
1890 if (ch
< '0' || ch
> '9')
1891 expect("exponent digits");
1892 while (ch
>= '0' && ch
<= '9') {
1893 exp_val
= exp_val
* 10 + ch
- '0';
1896 exp_val
= exp_val
* s
;
1898 /* now we can generate the number */
1899 /* XXX: should patch directly float number */
1900 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
1901 d
= ldexp(d
, exp_val
- frac_bits
);
1906 /* float : should handle overflow */
1908 } else if (t
== 'L') {
1910 #ifdef TCC_TARGET_PE
1915 /* XXX: not large enough */
1916 tokc
.ld
= (long double)d
;
1923 /* decimal floats */
1925 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1930 while (ch
>= '0' && ch
<= '9') {
1931 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1937 if (ch
== 'e' || ch
== 'E') {
1938 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1942 if (ch
== '-' || ch
== '+') {
1943 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1948 if (ch
< '0' || ch
> '9')
1949 expect("exponent digits");
1950 while (ch
>= '0' && ch
<= '9') {
1951 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1963 tokc
.f
= strtof(token_buf
, NULL
);
1964 } else if (t
== 'L') {
1966 #ifdef TCC_TARGET_PE
1968 tokc
.d
= strtod(token_buf
, NULL
);
1971 tokc
.ld
= strtold(token_buf
, NULL
);
1975 tokc
.d
= strtod(token_buf
, NULL
);
1979 unsigned long long n
, n1
;
1982 /* integer number */
1985 if (b
== 10 && *q
== '0') {
1992 /* no need for checks except for base 10 / 8 errors */
1995 } else if (t
>= 'a') {
1997 } else if (t
>= 'A') {
2002 tcc_error("invalid digit");
2006 /* detect overflow */
2007 /* XXX: this test is not reliable */
2009 tcc_error("integer constant overflow");
2012 /* XXX: not exactly ANSI compliant */
2013 if ((n
& 0xffffffff00000000LL
) != 0) {
2018 } else if (n
> 0x7fffffff) {
2029 tcc_error("three 'l's in integer constant");
2032 if (tok
== TOK_CINT
)
2034 else if (tok
== TOK_CUINT
)
2038 } else if (t
== 'U') {
2040 tcc_error("two 'u's in integer constant");
2042 if (tok
== TOK_CINT
)
2044 else if (tok
== TOK_CLLONG
)
2051 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2057 tcc_error("invalid number\n");
2061 #define PARSE2(c1, tok1, c2, tok2) \
2072 /* return next token without macro substitution */
2073 static inline void next_nomacro1(void)
2088 goto keep_tok_flags
;
2095 /* first look if it is in fact an end of buffer */
2096 if (p
>= file
->buf_end
) {
2100 if (p
>= file
->buf_end
)
2113 TCCState
*s1
= tcc_state
;
2114 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2115 && !(tok_flags
& TOK_FLAG_EOF
)) {
2116 tok_flags
|= TOK_FLAG_EOF
;
2118 goto keep_tok_flags
;
2119 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2121 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2122 tcc_error("missing #endif");
2123 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2124 /* no include left : end of file. */
2127 tok_flags
&= ~TOK_FLAG_EOF
;
2128 /* pop include file */
2130 /* test if previous '#endif' was after a #ifdef at
2132 if (tok_flags
& TOK_FLAG_ENDIF
) {
2134 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2136 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
2137 file
->ifndef_macro_saved
);
2140 /* add end of include file debug info */
2141 if (tcc_state
->do_debug
) {
2142 put_stabd(N_EINCL
, 0, 0);
2144 /* pop include stack */
2146 s1
->include_stack_ptr
--;
2155 tok_flags
|= TOK_FLAG_BOL
;
2158 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2161 goto keep_tok_flags
;
2166 if ((tok_flags
& TOK_FLAG_BOL
) &&
2167 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2169 preprocess(tok_flags
& TOK_FLAG_BOF
);
2175 tok
= TOK_TWOSHARPS
;
2177 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
2178 p
= parse_line_comment(p
- 1);
2187 case 'a': case 'b': case 'c': case 'd':
2188 case 'e': case 'f': case 'g': case 'h':
2189 case 'i': case 'j': case 'k': case 'l':
2190 case 'm': case 'n': case 'o': case 'p':
2191 case 'q': case 'r': case 's': case 't':
2192 case 'u': case 'v': case 'w': case 'x':
2194 case 'A': case 'B': case 'C': case 'D':
2195 case 'E': case 'F': case 'G': case 'H':
2196 case 'I': case 'J': case 'K':
2197 case 'M': case 'N': case 'O': case 'P':
2198 case 'Q': case 'R': case 'S': case 'T':
2199 case 'U': case 'V': case 'W': case 'X':
2205 h
= TOK_HASH_FUNC(h
, c
);
2209 if (!isidnum_table
[c
-CH_EOF
])
2211 h
= TOK_HASH_FUNC(h
, c
);
2218 /* fast case : no stray found, so we have the full token
2219 and we have already hashed it */
2221 h
&= (TOK_HASH_SIZE
- 1);
2222 pts
= &hash_ident
[h
];
2227 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2229 pts
= &(ts
->hash_next
);
2231 ts
= tok_alloc_new(pts
, p1
, len
);
2235 cstr_reset(&tokcstr
);
2238 cstr_ccat(&tokcstr
, *p1
);
2244 while (isidnum_table
[c
-CH_EOF
]) {
2245 cstr_ccat(&tokcstr
, c
);
2248 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2254 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2256 goto parse_ident_fast
;
2259 if (c
== '\'' || c
== '\"') {
2263 cstr_reset(&tokcstr
);
2264 cstr_ccat(&tokcstr
, 'L');
2265 goto parse_ident_slow
;
2269 case '0': case '1': case '2': case '3':
2270 case '4': case '5': case '6': case '7':
2273 cstr_reset(&tokcstr
);
2274 /* after the first digit, accept digits, alpha, '.' or sign if
2275 prefixed by 'eEpP' */
2279 cstr_ccat(&tokcstr
, c
);
2281 if (!(isnum(c
) || isid(c
) || c
== '.' ||
2282 ((c
== '+' || c
== '-') &&
2283 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
2286 /* We add a trailing '\0' to ease parsing */
2287 cstr_ccat(&tokcstr
, '\0');
2288 tokc
.cstr
= &tokcstr
;
2292 /* special dot handling because it can also start a number */
2295 cstr_reset(&tokcstr
);
2296 cstr_ccat(&tokcstr
, '.');
2298 } else if (c
== '.') {
2318 /* parse the string */
2320 p
= parse_pp_string(p
, sep
, &str
);
2321 cstr_ccat(&str
, '\0');
2323 /* eval the escape (should be done as TOK_PPNUM) */
2324 cstr_reset(&tokcstr
);
2325 parse_escape_string(&tokcstr
, str
.data
, is_long
);
2330 /* XXX: make it portable */
2334 char_size
= sizeof(nwchar_t
);
2335 if (tokcstr
.size
<= char_size
)
2336 tcc_error("empty character constant");
2337 if (tokcstr
.size
> 2 * char_size
)
2338 tcc_warning("multi-character character constant");
2340 tokc
.i
= *(int8_t *)tokcstr
.data
;
2343 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2347 tokc
.cstr
= &tokcstr
;
2361 } else if (c
== '<') {
2379 } else if (c
== '>') {
2397 } else if (c
== '=') {
2410 } else if (c
== '=') {
2423 } else if (c
== '=') {
2436 } else if (c
== '=') {
2439 } else if (c
== '>') {
2447 PARSE2('!', '!', '=', TOK_NE
)
2448 PARSE2('=', '=', '=', TOK_EQ
)
2449 PARSE2('*', '*', '=', TOK_A_MUL
)
2450 PARSE2('%', '%', '=', TOK_A_MOD
)
2451 PARSE2('^', '^', '=', TOK_A_XOR
)
2453 /* comments or operator */
2457 p
= parse_comment(p
);
2458 /* comments replaced by a blank */
2460 goto keep_tok_flags
;
2461 } else if (c
== '/') {
2462 p
= parse_line_comment(p
);
2464 goto keep_tok_flags
;
2465 } else if (c
== '=') {
2485 case '$': /* only used in assembler */
2486 case '@': /* dito */
2491 tcc_error("unrecognized character \\x%02x", c
);
2497 #if defined(PARSE_DEBUG)
2498 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2502 /* return next token without macro substitution. Can read input from
2504 static void next_nomacro_spc(void)
2510 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2511 if (tok
== TOK_LINENUM
) {
2512 file
->line_num
= tokc
.i
;
2521 ST_FUNC
void next_nomacro(void)
2525 } while (is_space(tok
));
2528 /* substitute args in macro_str and return allocated string */
2529 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2531 int last_tok
, t
, spc
;
2541 TOK_GET(&t
, ¯o_str
, &cval
);
2546 TOK_GET(&t
, ¯o_str
, &cval
);
2549 s
= sym_find2(args
, t
);
2555 TOK_GET(&t
, &st
, &cval
);
2556 if (!check_space(t
, &spc
))
2557 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2560 cstr_ccat(&cstr
, '\0');
2562 printf("stringize: %s\n", (char *)cstr
.data
);
2566 tok_str_add2(&str
, TOK_STR
, &cval
);
2569 tok_str_add2(&str
, t
, &cval
);
2571 } else if (t
>= TOK_IDENT
) {
2572 s
= sym_find2(args
, t
);
2575 /* if '##' is present before or after, no arg substitution */
2576 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
2577 /* special case for var arg macros : ## eats the
2578 ',' if empty VA_ARGS variable. */
2579 /* XXX: test of the ',' is not 100%
2580 reliable. should fix it to avoid security
2582 if (gnu_ext
&& s
->type
.t
&&
2583 last_tok
== TOK_TWOSHARPS
&&
2584 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
2586 /* suppress ',' '##' */
2589 /* suppress '##' and add variable */
2597 TOK_GET(&t1
, &st
, &cval
);
2600 tok_str_add2(&str
, t1
, &cval
);
2604 /* NOTE: the stream cannot be read when macro
2605 substituing an argument */
2606 macro_subst(&str
, nested_list
, st
, NULL
);
2609 tok_str_add(&str
, t
);
2612 tok_str_add2(&str
, t
, &cval
);
2616 tok_str_add(&str
, 0);
2620 static char const ab_month_name
[12][4] =
2622 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2623 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2626 /* do macro substitution of current token with macro 's' and add
2627 result to (tok_str,tok_len). 'nested_list' is the list of all
2628 macros we got inside to avoid recursing. Return non zero if no
2629 substitution needs to be done */
2630 static int macro_subst_tok(TokenString
*tok_str
,
2631 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
2633 Sym
*args
, *sa
, *sa1
;
2634 int mstr_allocated
, parlevel
, *mstr
, t
, t1
, spc
;
2642 /* if symbol is a macro, prepare substitution */
2643 /* special macros */
2644 if (tok
== TOK___LINE__
) {
2645 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2649 } else if (tok
== TOK___FILE__
) {
2650 cstrval
= file
->filename
;
2652 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2657 tm
= localtime(&ti
);
2658 if (tok
== TOK___DATE__
) {
2659 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2660 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2662 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2663 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2670 cstr_cat(&cstr
, cstrval
);
2671 cstr_ccat(&cstr
, '\0');
2673 tok_str_add2(tok_str
, t1
, &cval
);
2678 if (s
->type
.t
== MACRO_FUNC
) {
2679 /* NOTE: we do not use next_nomacro to avoid eating the
2680 next token. XXX: find better solution */
2684 while (is_space(t
= *p
) || TOK_LINEFEED
== t
)
2686 if (t
== 0 && can_read_stream
) {
2687 /* end of macro stream: we must look at the token
2688 after in the file */
2689 struct macro_level
*ml
= *can_read_stream
;
2695 *can_read_stream
= ml
-> prev
;
2697 /* also, end of scope for nested defined symbol */
2698 (*nested_list
)->v
= -1;
2702 /* XXX: incorrect with comments */
2703 ch
= file
->buf_ptr
[0];
2704 while (is_space(ch
) || ch
== '\n')
2708 if (t
!= '(') /* no macro subst */
2711 /* argument macro */
2716 /* NOTE: empty args are allowed, except if no args */
2718 /* handle '()' case */
2719 if (!args
&& !sa
&& tok
== ')')
2722 tcc_error("macro '%s' used with too many args",
2723 get_tok_str(s
->v
, 0));
2726 /* NOTE: non zero sa->t indicates VA_ARGS */
2727 while ((parlevel
> 0 ||
2729 (tok
!= ',' || sa
->type
.t
))) &&
2733 else if (tok
== ')')
2735 if (tok
== TOK_LINEFEED
)
2737 if (!check_space(tok
, &spc
))
2738 tok_str_add2(&str
, tok
, &tokc
);
2742 tok_str_add(&str
, 0);
2743 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
2747 /* special case for gcc var args: add an empty
2748 var arg argument if it is omitted */
2749 if (sa
&& sa
->type
.t
&& gnu_ext
)
2759 tcc_error("macro '%s' used with too few args",
2760 get_tok_str(s
->v
, 0));
2763 /* now subst each arg */
2764 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
2769 tok_str_free(sa
->d
);
2775 sym_push2(nested_list
, s
->v
, 0, 0);
2776 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
2777 /* pop nested defined symbol */
2779 *nested_list
= sa1
->prev
;
2787 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2788 return the resulting string (which must be freed). */
2789 static inline int *macro_twosharps(const int *macro_str
)
2794 TokenString macro_str1
;
2796 int n
, start_of_nosubsts
;
2798 /* we search the first '##' */
2799 for(ptr
= macro_str
;;) {
2800 TOK_GET(&t
, &ptr
, &cval
);
2801 if (t
== TOK_TWOSHARPS
)
2803 /* nothing more to do if end of string */
2808 /* we saw '##', so we need more processing to handle it */
2809 start_of_nosubsts
= -1;
2810 tok_str_new(¯o_str1
);
2811 for(ptr
= macro_str
;;) {
2812 TOK_GET(&tok
, &ptr
, &tokc
);
2815 if (tok
== TOK_TWOSHARPS
)
2817 if (tok
== TOK_NOSUBST
&& start_of_nosubsts
< 0)
2818 start_of_nosubsts
= macro_str1
.len
;
2819 while (*ptr
== TOK_TWOSHARPS
) {
2820 /* given 'a##b', remove nosubsts preceding 'a' */
2821 if (start_of_nosubsts
>= 0)
2822 macro_str1
.len
= start_of_nosubsts
;
2823 /* given 'a##b', skip '##' */
2825 /* given 'a##b', remove nosubsts preceding 'b' */
2826 while (t
== TOK_NOSUBST
)
2829 if (t
&& t
!= TOK_TWOSHARPS
) {
2830 TOK_GET(&t
, &ptr
, &cval
);
2832 /* We concatenate the two tokens */
2834 cstr_cat(&cstr
, get_tok_str(tok
, &tokc
));
2836 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2837 cstr_ccat(&cstr
, '\0');
2839 tcc_open_bf(tcc_state
, "<paste>", cstr
.size
);
2840 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
2843 if (0 == *file
->buf_ptr
)
2845 tok_str_add2(¯o_str1
, tok
, &tokc
);
2846 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2847 n
, cstr
.data
, (char*)cstr
.data
+ n
);
2853 if (tok
!= TOK_NOSUBST
)
2854 start_of_nosubsts
= -1;
2855 tok_str_add2(¯o_str1
, tok
, &tokc
);
2857 tok_str_add(¯o_str1
, 0);
2858 return macro_str1
.str
;
2862 /* do macro substitution of macro_str and add result to
2863 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2864 inside to avoid recursing. */
2865 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
2866 const int *macro_str
, struct macro_level
** can_read_stream
)
2873 struct macro_level ml
;
2876 /* first scan for '##' operator handling */
2878 macro_str1
= macro_twosharps(ptr
);
2886 /* NOTE: ptr == NULL can only happen if tokens are read from
2887 file stream due to a macro function call */
2890 TOK_GET(&t
, &ptr
, &cval
);
2893 if (t
== TOK_NOSUBST
) {
2894 /* following token has already been subst'd. just copy it on */
2895 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
2896 TOK_GET(&t
, &ptr
, &cval
);
2901 /* if nested substitution, do nothing */
2902 if (sym_find2(*nested_list
, t
)) {
2903 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
2904 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
2908 if (can_read_stream
)
2909 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
2910 macro_ptr
= (int *)ptr
;
2912 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
2913 ptr
= (int *)macro_ptr
;
2915 if (can_read_stream
&& *can_read_stream
== &ml
)
2916 *can_read_stream
= ml
.prev
;
2919 if (parse_flags
& PARSE_FLAG_SPACES
)
2924 tok_str_add(tok_str
, ' ');
2928 if (!check_space(t
, &spc
))
2929 tok_str_add2(tok_str
, t
, &cval
);
2933 tok_str_free(macro_str1
);
2936 /* return next token with macro substitution */
2937 ST_FUNC
void next(void)
2939 Sym
*nested_list
, *s
;
2941 struct macro_level
*ml
;
2944 if (parse_flags
& PARSE_FLAG_SPACES
)
2949 /* if not reading from macro substituted string, then try
2950 to substitute macros */
2951 if (tok
>= TOK_IDENT
&&
2952 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2953 s
= define_find(tok
);
2955 /* we have a macro: we try to substitute */
2959 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
2960 /* substitution done, NOTE: maybe empty */
2961 tok_str_add(&str
, 0);
2962 macro_ptr
= str
.str
;
2963 macro_ptr_allocated
= str
.str
;
2970 /* end of macro or end of unget buffer */
2971 if (unget_buffer_enabled
) {
2972 macro_ptr
= unget_saved_macro_ptr
;
2973 unget_buffer_enabled
= 0;
2975 /* end of macro string: free it */
2976 tok_str_free(macro_ptr_allocated
);
2977 macro_ptr_allocated
= NULL
;
2981 } else if (tok
== TOK_NOSUBST
) {
2982 /* discard preprocessor's nosubst markers */
2987 /* convert preprocessor tokens into C tokens */
2988 if (tok
== TOK_PPNUM
&&
2989 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
2990 parse_number((char *)tokc
.cstr
->data
);
2994 /* push back current token and set current token to 'last_tok'. Only
2995 identifier case handled for labels. */
2996 ST_INLN
void unget_tok(int last_tok
)
3000 unget_saved_macro_ptr
= macro_ptr
;
3001 unget_buffer_enabled
= 1;
3002 q
= unget_saved_buffer
;
3005 n
= tok_ext_size(tok
) - 1;
3008 *q
= 0; /* end of token string */
3013 /* better than nothing, but needs extension to handle '-E' option
3015 ST_FUNC
void preprocess_init(TCCState
*s1
)
3017 s1
->include_stack_ptr
= s1
->include_stack
;
3018 /* XXX: move that before to avoid having to initialize
3019 file->ifdef_stack_ptr ? */
3020 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3021 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3023 /* XXX: not ANSI compliant: bound checking says error */
3025 s1
->pack_stack
[0] = 0;
3026 s1
->pack_stack_ptr
= s1
->pack_stack
;
3029 ST_FUNC
void preprocess_new()
3034 /* init isid table */
3035 for(i
=CH_EOF
;i
<256;i
++)
3036 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
3038 /* add all tokens */
3040 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3042 tok_ident
= TOK_IDENT
;
3051 tok_alloc(p
, r
- p
- 1);
3056 /* Preprocess the current file */
3057 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3061 BufferedFile
*file_ref
, **iptr
, **iptr_new
;
3062 int token_seen
, line_ref
, d
;
3065 preprocess_init(s1
);
3066 define_start
= define_stack
;
3067 ch
= file
->buf_ptr
[0];
3068 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3069 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
3070 PARSE_FLAG_LINEFEED
| PARSE_FLAG_SPACES
;
3074 iptr
= s1
->include_stack_ptr
;
3078 if (tok
== TOK_EOF
) {
3080 } else if (file
!= file_ref
) {
3082 } else if (tok
== TOK_LINEFEED
) {
3087 } else if (!token_seen
) {
3088 d
= file
->line_num
- line_ref
;
3089 if (file
!= file_ref
|| d
< 0 || d
>= 8) {
3091 iptr_new
= s1
->include_stack_ptr
;
3092 s
= iptr_new
> iptr
? " 1"
3093 : iptr_new
< iptr
? " 2"
3094 : iptr_new
> s1
->include_stack
? " 3"
3098 fprintf(s1
->outfile
, "# %d \"%s\"%s\n", file
->line_num
, file
->filename
, s
);
3101 fputs("\n", s1
->outfile
), --d
;
3103 line_ref
= (file_ref
= file
)->line_num
;
3104 token_seen
= tok
!= TOK_LINEFEED
;
3108 fputs(get_tok_str(tok
, &tokc
), s1
->outfile
);
3110 free_defines(define_start
);