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
];
64 static int token_seen
;
66 static const char tcc_keywords
[] =
67 #define DEF(id, str) str "\0"
72 /* WARNING: the content of this string encodes token numbers */
73 static const unsigned char tok_two_chars
[] =
75 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
76 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
97 '.','.', 0xa8, // C++ token ?
98 '#','#', TOK_TWOSHARPS
,
103 struct macro_level
*prev
;
107 static void next_nomacro_spc(void);
108 static void macro_subst(
109 TokenString
*tok_str
,
111 const int *macro_str
,
112 struct macro_level
**can_read_stream
115 ST_FUNC
void skip(int c
)
118 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
122 ST_FUNC
void expect(const char *msg
)
124 tcc_error("%s expected", msg
);
127 /* ------------------------------------------------------------------------- */
128 /* CString handling */
129 static void cstr_realloc(CString
*cstr
, int new_size
)
134 size
= cstr
->size_allocated
;
136 size
= 8; /* no need to allocate a too small first string */
137 while (size
< new_size
)
139 data
= tcc_realloc(cstr
->data_allocated
, size
);
140 cstr
->data_allocated
= data
;
141 cstr
->size_allocated
= size
;
146 ST_FUNC
void cstr_ccat(CString
*cstr
, int ch
)
149 size
= cstr
->size
+ 1;
150 if (size
> cstr
->size_allocated
)
151 cstr_realloc(cstr
, size
);
152 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
156 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
)
168 /* add a wide char */
169 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
172 size
= cstr
->size
+ sizeof(nwchar_t
);
173 if (size
> cstr
->size_allocated
)
174 cstr_realloc(cstr
, size
);
175 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
179 ST_FUNC
void cstr_new(CString
*cstr
)
181 memset(cstr
, 0, sizeof(CString
));
184 /* free string and reset it to NULL */
185 ST_FUNC
void cstr_free(CString
*cstr
)
187 tcc_free(cstr
->data_allocated
);
191 /* reset string to empty */
192 ST_FUNC
void cstr_reset(CString
*cstr
)
198 static void add_char(CString
*cstr
, int c
)
200 if (c
== '\'' || c
== '\"' || c
== '\\') {
201 /* XXX: could be more precise if char or string */
202 cstr_ccat(cstr
, '\\');
204 if (c
>= 32 && c
<= 126) {
207 cstr_ccat(cstr
, '\\');
209 cstr_ccat(cstr
, 'n');
211 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
212 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
213 cstr_ccat(cstr
, '0' + (c
& 7));
218 /* ------------------------------------------------------------------------- */
219 /* allocate a new token */
220 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
222 TokenSym
*ts
, **ptable
;
225 if (tok_ident
>= SYM_FIRST_ANOM
)
226 tcc_error("memory full (symbols)");
228 /* expand token table if needed */
229 i
= tok_ident
- TOK_IDENT
;
230 if ((i
% TOK_ALLOC_INCR
) == 0) {
231 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
232 table_ident
= ptable
;
235 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
237 ts
->tok
= tok_ident
++;
238 ts
->sym_define
.data
= tcc_malloc(sizeof(Sym
*));
239 ts
->sym_define
.off
= 0;
240 ts
->sym_define
.data
[0] = NULL
;
241 ts
->sym_define
.size
= 1;
242 ts
->sym_label
= NULL
;
243 ts
->sym_struct
= NULL
;
244 ts
->sym_identifier
= NULL
;
246 ts
->hash_next
= NULL
;
247 memcpy(ts
->str
, str
, len
);
253 #define TOK_HASH_INIT 1
254 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
256 /* find a token and add it if not found */
257 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
265 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
266 h
&= (TOK_HASH_SIZE
- 1);
268 pts
= &hash_ident
[h
];
273 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
275 pts
= &(ts
->hash_next
);
277 return tok_alloc_new(pts
, str
, len
);
280 /* XXX: buffer overflow */
281 /* XXX: float tokens */
282 ST_FUNC
char *get_tok_str(int v
, CValue
*cv
)
284 static char buf
[STRING_MAX_SIZE
+ 1];
285 static CString cstr_buf
;
290 /* NOTE: to go faster, we give a fixed buffer for small strings */
291 cstr_reset(&cstr_buf
);
293 cstr_buf
.size_allocated
= sizeof(buf
);
296 /* just an explanation, should never happen:
297 if (v <= TOK_LINENUM && v >= TOK_CINT && cv == NULL)
298 tcc_error("internal error: get_tok_str"); */
303 /* XXX: not quite exact, but only useful for testing */
304 sprintf(p
, "%u", cv
->ui
);
308 /* XXX: not quite exact, but only useful for testing */
310 sprintf(p
, "%u", (unsigned)cv
->ull
);
312 sprintf(p
, "%llu", cv
->ull
);
316 cstr_ccat(&cstr_buf
, 'L');
318 cstr_ccat(&cstr_buf
, '\'');
319 add_char(&cstr_buf
, cv
->i
);
320 cstr_ccat(&cstr_buf
, '\'');
321 cstr_ccat(&cstr_buf
, '\0');
325 len
= cstr
->size
- 1;
327 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
328 cstr_ccat(&cstr_buf
, '\0');
331 cstr_ccat(&cstr_buf
, 'L');
334 cstr_ccat(&cstr_buf
, '\"');
336 len
= cstr
->size
- 1;
338 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
340 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
342 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
344 cstr_ccat(&cstr_buf
, '\"');
345 cstr_ccat(&cstr_buf
, '\0');
352 return NULL
; /* should not happen */
354 /* above tokens have value, the ones below don't */
363 return strcpy(p
, "...");
365 return strcpy(p
, "<<=");
367 return strcpy(p
, ">>=");
370 /* search in two bytes table */
371 const unsigned char *q
= tok_two_chars
;
384 } else if (v
< tok_ident
) {
385 return table_ident
[v
- TOK_IDENT
]->str
;
386 } else if (v
>= SYM_FIRST_ANOM
) {
387 /* special name for anonymous symbol */
388 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
390 /* should never happen */
395 return cstr_buf
.data
;
398 /* fill input buffer and peek next char */
399 static int tcc_peekc_slow(BufferedFile
*bf
)
402 /* only tries to read if really end of buffer */
403 if (bf
->buf_ptr
>= bf
->buf_end
) {
405 #if defined(PARSE_DEBUG)
410 len
= read(bf
->fd
, bf
->buffer
, len
);
417 bf
->buf_ptr
= bf
->buffer
;
418 bf
->buf_end
= bf
->buffer
+ len
;
419 *bf
->buf_end
= CH_EOB
;
421 if (bf
->buf_ptr
< bf
->buf_end
) {
422 return bf
->buf_ptr
[0];
424 bf
->buf_ptr
= bf
->buf_end
;
429 /* return the current character, handling end of block if necessary
431 ST_FUNC
int handle_eob(void)
433 return tcc_peekc_slow(file
);
436 /* read next char from current input file and handle end of input buffer */
437 ST_INLN
void inp(void)
439 ch
= *(++(file
->buf_ptr
));
440 /* end of buffer/file handling */
445 /* handle '\[\r]\n' */
446 static int handle_stray_noerror(void)
453 } else if (ch
== '\r') {
467 static void handle_stray(void)
469 if (handle_stray_noerror())
470 tcc_error("stray '\\' in program");
473 /* skip the stray and handle the \\n case. Output an error if
474 incorrect char after the stray */
475 static int handle_stray1(uint8_t *p
)
479 if (p
>= file
->buf_end
) {
496 /* handle just the EOB case, but not stray */
497 #define PEEKC_EOB(c, p)\
508 /* handle the complicated stray case */
514 c = handle_stray1(p);\
519 /* input with '\[\r]\n' handling. Note that this function cannot
520 handle other characters after '\', so you cannot call it inside
521 strings or comments */
522 ST_FUNC
void minp(void)
530 /* single line C++ comments */
531 static uint8_t *parse_line_comment(uint8_t *p
)
539 if (c
== '\n' || c
== CH_EOF
) {
541 } else if (c
== '\\') {
550 } else if (c
== '\r') {
568 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
577 if (c
== '\n' || c
== '*' || c
== '\\')
581 if (c
== '\n' || c
== '*' || c
== '\\')
585 /* now we can handle all the cases */
589 } else if (c
== '*') {
595 } else if (c
== '/') {
597 } else if (c
== '\\') {
602 /* skip '\[\r]\n', otherwise just skip the stray */
608 } else if (c
== '\r') {
625 /* stray, eob or eof */
630 tcc_error("unexpected end of file in comment");
631 } else if (c
== '\\') {
643 static inline void skip_spaces(void)
649 static inline int check_space(int t
, int *spc
)
660 /* parse a string without interpreting escapes */
661 static uint8_t *parse_pp_string(uint8_t *p
,
662 int sep
, CString
*str
)
670 } else if (c
== '\\') {
676 /* XXX: indicate line number of start of string */
677 tcc_error("missing terminating %c character", sep
);
678 } else if (c
== '\\') {
679 /* escape : just skip \[\r]\n */
684 } else if (c
== '\r') {
687 expect("'\n' after '\r'");
690 } else if (c
== CH_EOF
) {
691 goto unterminated_string
;
694 cstr_ccat(str
, '\\');
700 } else if (c
== '\n') {
703 } else if (c
== '\r') {
707 cstr_ccat(str
, '\r');
723 /* skip block of text until #else, #elif or #endif. skip also pairs of
725 static void preprocess_skip(void)
727 int a
, start_of_line
, c
, in_warn_or_error
;
734 in_warn_or_error
= 0;
755 } else if (c
== '\\') {
756 ch
= file
->buf_ptr
[0];
757 handle_stray_noerror();
764 if (in_warn_or_error
)
766 p
= parse_pp_string(p
, c
, NULL
);
770 if (in_warn_or_error
)
777 p
= parse_comment(p
);
778 } else if (ch
== '/') {
779 p
= parse_line_comment(p
);
789 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
791 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
793 else if (tok
== TOK_ENDIF
)
795 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
796 in_warn_or_error
= 1;
797 else if (tok
== TOK_LINEFEED
)
812 /* ParseState handling */
814 /* XXX: currently, no include file info is stored. Thus, we cannot display
815 accurate messages if the function or data definition spans multiple
818 /* save current parse state in 's' */
819 ST_FUNC
void save_parse_state(ParseState
*s
)
821 s
->line_num
= file
->line_num
;
822 s
->macro_ptr
= macro_ptr
;
827 /* restore parse state from 's' */
828 ST_FUNC
void restore_parse_state(ParseState
*s
)
830 file
->line_num
= s
->line_num
;
831 macro_ptr
= s
->macro_ptr
;
836 /* return the number of additional 'ints' necessary to store the
838 static inline int tok_ext_size(int t
)
852 tcc_error("unsupported token");
859 return LDOUBLE_SIZE
/ 4;
865 /* token string handling */
867 ST_INLN
void tok_str_new(TokenString
*s
)
871 s
->allocated_len
= 0;
872 s
->last_line_num
= -1;
875 ST_FUNC
void tok_str_free(int *str
)
880 static int *tok_str_realloc(TokenString
*s
)
884 if (s
->allocated_len
== 0) {
887 len
= s
->allocated_len
* 2;
889 str
= tcc_realloc(s
->str
, len
* sizeof(int));
890 s
->allocated_len
= len
;
895 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
901 if (len
>= s
->allocated_len
)
902 str
= tok_str_realloc(s
);
907 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
914 /* allocate space for worst case */
915 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
916 str
= tok_str_realloc(s
);
925 str
[len
++] = cv
->tab
[0];
934 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
935 while ((len
+ nb_words
) > s
->allocated_len
)
936 str
= tok_str_realloc(s
);
937 cstr
= (CString
*)(str
+ len
);
939 cstr
->size
= cv
->cstr
->size
;
940 cstr
->data_allocated
= NULL
;
941 cstr
->size_allocated
= cstr
->size
;
942 memcpy((char *)cstr
+ sizeof(CString
),
943 cv
->cstr
->data
, cstr
->size
);
950 #if LDOUBLE_SIZE == 8
953 str
[len
++] = cv
->tab
[0];
954 str
[len
++] = cv
->tab
[1];
956 #if LDOUBLE_SIZE == 12
958 str
[len
++] = cv
->tab
[0];
959 str
[len
++] = cv
->tab
[1];
960 str
[len
++] = cv
->tab
[2];
961 #elif LDOUBLE_SIZE == 16
963 str
[len
++] = cv
->tab
[0];
964 str
[len
++] = cv
->tab
[1];
965 str
[len
++] = cv
->tab
[2];
966 str
[len
++] = cv
->tab
[3];
967 #elif LDOUBLE_SIZE != 8
968 #error add long double size support
977 /* add the current parse token in token string 's' */
978 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
982 /* save line number info */
983 if (file
->line_num
!= s
->last_line_num
) {
984 s
->last_line_num
= file
->line_num
;
985 cval
.i
= s
->last_line_num
;
986 tok_str_add2(s
, TOK_LINENUM
, &cval
);
988 tok_str_add2(s
, tok
, &tokc
);
991 /* get a token from an integer array and increment pointer
992 accordingly. we code it as a macro to avoid pointer aliasing. */
993 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1011 cv
->cstr
= (CString
*)p
;
1012 cv
->cstr
->data
= (char *)p
+ sizeof(CString
);
1013 p
+= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
1021 #if LDOUBLE_SIZE == 16
1023 #elif LDOUBLE_SIZE == 12
1025 #elif LDOUBLE_SIZE == 8
1028 # error add long double size support
1041 static int macro_is_equal(const int *a
, const int *b
)
1043 char buf
[STRING_MAX_SIZE
+ 1];
1047 TOK_GET(&t
, &a
, &cv
);
1048 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1049 TOK_GET(&t
, &b
, &cv
);
1050 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1056 /* defines handling */
1057 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1062 if (s
&& !macro_is_equal(s
->d
, str
))
1063 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1064 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1066 s
->next
= first_arg
;
1067 def
= &table_ident
[v
- TOK_IDENT
]->sym_define
;
1068 def
->data
[def
->off
] = s
;
1071 /* undefined a define symbol. Its name is just set to zero */
1072 ST_FUNC
void define_undef(Sym
*s
)
1076 v
= s
->v
- TOK_IDENT
;
1077 if ((unsigned)v
< (unsigned)(tok_ident
- TOK_IDENT
)){
1078 def
= &table_ident
[v
]->sym_define
;
1079 def
->data
[def
->off
] = NULL
;
1083 ST_INLN Sym
*define_find(int v
)
1087 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1089 def
= &table_ident
[v
]->sym_define
;
1090 return def
->data
[def
->off
];
1093 /* free define stack until top reaches 'b' */
1094 ST_FUNC
void free_defines(Sym
*b
)
1103 /* do not free args or predefined defines */
1105 tok_str_free(top
->d
);
1106 v
= top
->v
- TOK_IDENT
;
1107 if ((unsigned)v
< (unsigned)(tok_ident
- TOK_IDENT
)){
1108 def
= &table_ident
[v
]->sym_define
;
1112 def
->data
[0] = NULL
;
1121 ST_FUNC Sym
*label_find(int v
)
1124 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1126 return table_ident
[v
]->sym_label
;
1129 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1132 s
= sym_push2(ptop
, v
, 0, 0);
1134 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1135 if (ptop
== &global_label_stack
) {
1136 /* modify the top most local identifier, so that
1137 sym_identifier will point to 's' when popped */
1139 ps
= &(*ps
)->prev_tok
;
1146 /* pop labels until element last is reached. Look if any labels are
1147 undefined. Define symbols if '&&label' was used. */
1148 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1151 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1153 if (s
->r
== LABEL_DECLARED
) {
1154 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1155 } else if (s
->r
== LABEL_FORWARD
) {
1156 tcc_error("label '%s' used but not defined",
1157 get_tok_str(s
->v
, NULL
));
1160 /* define corresponding symbol. A size of
1162 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1166 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1172 /* eval an expression for #if/#elif */
1173 static int expr_preprocess(void)
1179 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1180 next(); /* do macro subst */
1181 if (tok
== TOK_DEFINED
) {
1186 c
= define_find(tok
) != 0;
1191 } else if (tok
>= TOK_IDENT
) {
1192 /* if undefined macro */
1196 tok_str_add_tok(&str
);
1198 tok_str_add(&str
, -1); /* simulate end of file */
1199 tok_str_add(&str
, 0);
1200 /* now evaluate C constant expression */
1201 macro_ptr
= str
.str
;
1205 tok_str_free(str
.str
);
1209 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1210 static void tok_print(int *str
)
1217 TOK_GET(&t
, &str
, &cval
);
1220 printf("%s", get_tok_str(t
, &cval
));
1226 /* parse after #define */
1227 ST_FUNC
void parse_define(void)
1229 Sym
*s
, *first
, **ps
;
1230 int v
, t
, varg
, is_vaargs
, spc
, ptok
, macro_list_start
;
1235 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1236 /* XXX: should check if same macro (ANSI) */
1239 /* '(' must be just after macro definition for MACRO_FUNC */
1244 while (tok
!= ')') {
1248 if (varg
== TOK_DOTS
) {
1249 varg
= TOK___VA_ARGS__
;
1251 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1255 if (varg
< TOK_IDENT
)
1256 tcc_error("badly punctuated parameter list");
1257 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1270 /* EOF testing necessary for '-D' handling */
1272 macro_list_start
= 1;
1273 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1274 if (!macro_list_start
&& spc
== 2 && tok
== TOK_TWOSHARPS
)
1275 tcc_error("'##' invalid at start of macro");
1277 /* remove spaces around ## and after '#' */
1278 if (TOK_TWOSHARPS
== tok
) {
1282 } else if ('#' == tok
) {
1284 } else if (check_space(tok
, &spc
)) {
1287 tok_str_add2(&str
, tok
, &tokc
);
1290 macro_list_start
= 0;
1292 if (ptok
== TOK_TWOSHARPS
)
1293 tcc_error("'##' invalid at end of macro");
1295 --str
.len
; /* remove trailing space */
1296 tok_str_add(&str
, 0);
1298 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
1301 define_push(v
, t
, str
.str
, first
);
1304 static inline int hash_cached_include(const char *filename
)
1306 const unsigned char *s
;
1310 s
= (unsigned char *) filename
;
1312 h
= TOK_HASH_FUNC(h
, *s
);
1315 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1319 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1323 h
= hash_cached_include(filename
);
1324 i
= s1
->cached_includes_hash
[h
];
1328 e
= s1
->cached_includes
[i
- 1];
1329 if (0 == PATHCMP(e
->filename
, filename
))
1336 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1341 if (search_cached_include(s1
, filename
))
1344 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1346 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1347 strcpy(e
->filename
, filename
);
1348 e
->ifndef_macro
= ifndef_macro
;
1349 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1350 /* add in hash table */
1351 h
= hash_cached_include(filename
);
1352 e
->hash_next
= s1
->cached_includes_hash
[h
];
1353 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1356 /* is_bof is true if first non space token at beginning of file */
1357 ST_FUNC
void preprocess(int is_bof
)
1359 TCCState
*s1
= tcc_state
;
1360 int i
, c
, n
, saved_parse_flags
;
1361 uint8_t buf
[1024], *p
;
1364 saved_parse_flags
= parse_flags
;
1365 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
| PARSE_FLAG_LINEFEED
;
1375 s
= define_find(tok
);
1376 /* undefine symbol by putting an invalid name */
1381 case TOK_INCLUDE_NEXT
:
1382 ch
= file
->buf_ptr
[0];
1383 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1388 } else if (ch
== '\"') {
1393 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1394 if ((p
- buf
) < sizeof(buf
) - 1)
1397 if (handle_stray_noerror() == 0)
1403 goto include_syntax
;
1407 /* eat all spaces and comments after include */
1408 /* XXX: slightly incorrect */
1409 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1413 /* computed #include : either we have only strings or
1414 we have anything enclosed in '<>' */
1417 if (tok
== TOK_STR
) {
1418 while (tok
!= TOK_LINEFEED
) {
1419 if (tok
!= TOK_STR
) {
1421 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1423 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1429 while (tok
!= TOK_LINEFEED
) {
1430 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1434 /* check syntax and remove '<>' */
1435 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1436 goto include_syntax
;
1437 memmove(buf
, buf
+ 1, len
- 2);
1438 buf
[len
- 2] = '\0';
1443 tcc_error(" empty filename in #include");
1445 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1446 tcc_error("#include recursion too deep");
1447 /* store current file in stack, but increment stack later below */
1448 *s1
->include_stack_ptr
= file
;
1450 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1451 for (i
= -2; i
< n
; ++i
) {
1452 char buf1
[sizeof file
->filename
];
1458 /* check absolute include path */
1459 if (!IS_ABSPATH(buf
))
1462 i
= n
; /* force end loop */
1464 } else if (i
== -1) {
1465 /* search in current dir if "header.h" */
1468 path
= file
->filename
;
1469 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1472 /* search in all the include paths */
1473 if (i
< s1
->nb_include_paths
)
1474 path
= s1
->include_paths
[i
];
1476 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1477 pstrcpy(buf1
, sizeof(buf1
), path
);
1478 pstrcat(buf1
, sizeof(buf1
), "/");
1481 pstrcat(buf1
, sizeof(buf1
), buf
);
1483 if (tok
== TOK_INCLUDE_NEXT
)
1484 for (f
= s1
->include_stack_ptr
; f
>= s1
->include_stack
; --f
)
1485 if (0 == PATHCMP((*f
)->filename
, buf1
)) {
1487 printf("%s: #include_next skipping %s\n", file
->filename
, buf1
);
1489 goto include_trynext
;
1492 e
= search_cached_include(s1
, buf1
);
1493 if (e
&& define_find(e
->ifndef_macro
)) {
1494 /* no need to parse the include because the 'ifndef macro'
1497 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1502 if (tcc_open(s1
, buf1
) < 0)
1507 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1509 /* update target deps */
1510 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
, tcc_strdup(buf1
));
1511 /* push current file in stack */
1512 ++s1
->include_stack_ptr
;
1513 /* add include file debug info */
1515 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1516 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1517 ch
= file
->buf_ptr
[0];
1520 tcc_error("include file '%s' not found", buf
);
1527 c
= expr_preprocess();
1533 if (tok
< TOK_IDENT
)
1534 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1538 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1540 file
->ifndef_macro
= tok
;
1543 c
= !!define_find(tok
) ^ c
;
1545 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1546 tcc_error("memory full (ifdef)");
1547 *s1
->ifdef_stack_ptr
++ = c
;
1550 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1551 tcc_error("#else without matching #if");
1552 if (s1
->ifdef_stack_ptr
[-1] & 2)
1553 tcc_error("#else after #else");
1554 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1557 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1558 tcc_error("#elif without matching #if");
1559 c
= s1
->ifdef_stack_ptr
[-1];
1561 tcc_error("#elif after #else");
1562 /* last #if/#elif expression was true: we skip */
1565 c
= expr_preprocess();
1566 s1
->ifdef_stack_ptr
[-1] = c
;
1568 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1569 file
->ifndef_macro
= 0;
1579 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1580 tcc_error("#endif without matching #if");
1581 s1
->ifdef_stack_ptr
--;
1582 /* '#ifndef macro' was at the start of file. Now we check if
1583 an '#endif' is exactly at the end of file */
1584 if (file
->ifndef_macro
&&
1585 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1586 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1587 /* need to set to zero to avoid false matches if another
1588 #ifndef at middle of file */
1589 file
->ifndef_macro
= 0;
1590 tok_flags
|= TOK_FLAG_ENDIF
;
1593 if (tok
!= TOK_LINEFEED
)
1594 tcc_warning("Ignoring: %s", get_tok_str(tok
, &tokc
));
1598 if (tok
!= TOK_CINT
)
1600 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
1602 if (tok
!= TOK_LINEFEED
) {
1605 pstrcpy(file
->filename
, sizeof(file
->filename
), (char *)tokc
.cstr
->data
);
1611 ch
= file
->buf_ptr
[0];
1614 while (ch
!= '\n' && ch
!= CH_EOF
) {
1615 if ((p
- buf
) < sizeof(buf
) - 1)
1618 if (handle_stray_noerror() == 0)
1625 tcc_error("#error %s", buf
);
1627 tcc_warning("#warning %s", buf
);
1631 if (tok
== TOK_pack
&& s1
->output_type
!= TCC_OUTPUT_PREPROCESS
) {
1634 #pragma pack(1) // set
1635 #pragma pack() // reset to default
1636 #pragma pack(push,1) // push & set
1637 #pragma pack(pop) // restore previous
1641 if (tok
== TOK_ASM_pop
) {
1643 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1645 tcc_error("out of pack stack");
1647 s1
->pack_stack_ptr
--;
1651 if (tok
== TOK_ASM_push
) {
1653 s1
->pack_stack_ptr
++;
1654 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
)
1658 if (tok
!= TOK_CINT
) {
1660 tcc_error("invalid pack pragma");
1663 if (val
< 1 || val
> 16)
1665 if (val
< 1 || val
> 16)
1666 tcc_error("Value must be greater than 1 is less than or equal to 16");
1667 if ((val
& (val
- 1)) != 0)
1668 tcc_error("Value must be a power of 2 curtain");
1671 *s1
->pack_stack_ptr
= val
;
1674 }else if (tok
== TOK_PUSH_MACRO
|| tok
== TOK_POP_MACRO
) {
1680 ch
= file
->buf_ptr
[0];
1683 goto macro_xxx_syntax
;
1684 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1690 while (ch
!= '\"' && ch
!= '\n' && ch
!= CH_EOF
) {
1691 if ((p
- buf
) < sizeof(buf
) - 1)
1700 goto macro_xxx_syntax
;
1705 /* computed #pragma macro_xxx for #define xxx */
1708 while (tok
!= ')') {
1709 if (tok
!= TOK_STR
) {
1711 tcc_error("'macro_xxx' expects (\"NAME\")");
1713 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1719 tcc_error(" empty string in #pragma");
1722 while (is_space(*p
))
1726 if (!isidnum_table
[p
[0] - CH_EOF
])
1731 while (is_space(*p
))
1734 tcc_error("unrecognized string: %s", buf
);
1735 ts
= tok_alloc(p1
, len
);
1737 def
= &ts
->sym_define
;
1738 if(t
== TOK_PUSH_MACRO
){
1739 void *tmp
= def
->data
[def
->off
];
1741 if(def
->off
>= def
->size
){
1742 int size
= def
->size
;
1744 if (size
> MACRO_STACK_SIZE
)
1745 tcc_error("stack full");
1746 def
->data
= tcc_realloc(def
->data
, size
*sizeof(Sym
*));
1749 def
->data
[def
->off
] = tmp
;
1756 }else if(s1
->output_type
== TCC_OUTPUT_PREPROCESS
){
1757 fputs("#pragma ", s1
->ppfp
);
1758 while (tok
!= TOK_LINEFEED
){
1759 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);
1762 token_seen
= 0;//printf '\n'
1767 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_PPNUM
) {
1768 /* '!' is ignored to allow C scripts. numbers are ignored
1769 to emulate cpp behaviour */
1771 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
1772 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1774 /* this is a gas line comment in an 'S' file. */
1775 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1781 /* ignore other preprocess commands or #! for C scripts */
1782 while (tok
!= TOK_LINEFEED
)
1785 parse_flags
= saved_parse_flags
;
1788 /* evaluate escape codes in a string. */
1789 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1804 case '0': case '1': case '2': case '3':
1805 case '4': case '5': case '6': case '7':
1806 /* at most three octal digits */
1811 n
= n
* 8 + c
- '0';
1815 n
= n
* 8 + c
- '0';
1820 goto add_char_nonext
;
1828 if (c
>= 'a' && c
<= 'f')
1830 else if (c
>= 'A' && c
<= 'F')
1840 goto add_char_nonext
;
1864 goto invalid_escape
;
1874 if (c
>= '!' && c
<= '~')
1875 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1877 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1884 cstr_ccat(outstr
, c
);
1886 cstr_wccat(outstr
, c
);
1888 /* add a trailing '\0' */
1890 cstr_ccat(outstr
, '\0');
1892 cstr_wccat(outstr
, '\0');
1895 /* we use 64 bit numbers */
1898 /* bn = (bn << shift) | or_val */
1899 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
1903 for(i
=0;i
<BN_SIZE
;i
++) {
1905 bn
[i
] = (v
<< shift
) | or_val
;
1906 or_val
= v
>> (32 - shift
);
1910 static void bn_zero(unsigned int *bn
)
1913 for(i
=0;i
<BN_SIZE
;i
++) {
1918 /* parse number in null terminated string 'p' and return it in the
1920 static void parse_number(const char *p
)
1922 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
1924 unsigned int bn
[BN_SIZE
];
1935 goto float_frac_parse
;
1936 } else if (t
== '0') {
1937 if (ch
== 'x' || ch
== 'X') {
1941 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
1947 /* parse all digits. cannot check octal numbers at this stage
1948 because of floating point constants */
1950 if (ch
>= 'a' && ch
<= 'f')
1952 else if (ch
>= 'A' && ch
<= 'F')
1960 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
1962 tcc_error("number too long");
1968 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
1969 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
1971 /* NOTE: strtox should support that for hexa numbers, but
1972 non ISOC99 libcs do not support it, so we prefer to do
1974 /* hexadecimal or binary floats */
1975 /* XXX: handle overflows */
1987 } else if (t
>= 'a') {
1989 } else if (t
>= 'A') {
1994 bn_lshift(bn
, shift
, t
);
2001 if (t
>= 'a' && t
<= 'f') {
2003 } else if (t
>= 'A' && t
<= 'F') {
2005 } else if (t
>= '0' && t
<= '9') {
2011 tcc_error("invalid digit");
2012 bn_lshift(bn
, shift
, t
);
2017 if (ch
!= 'p' && ch
!= 'P')
2024 } else if (ch
== '-') {
2028 if (ch
< '0' || ch
> '9')
2029 expect("exponent digits");
2030 while (ch
>= '0' && ch
<= '9') {
2031 exp_val
= exp_val
* 10 + ch
- '0';
2034 exp_val
= exp_val
* s
;
2036 /* now we can generate the number */
2037 /* XXX: should patch directly float number */
2038 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2039 d
= ldexp(d
, exp_val
- frac_bits
);
2044 /* float : should handle overflow */
2046 } else if (t
== 'L') {
2048 #ifdef TCC_TARGET_PE
2053 /* XXX: not large enough */
2054 tokc
.ld
= (long double)d
;
2061 /* decimal floats */
2063 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2068 while (ch
>= '0' && ch
<= '9') {
2069 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2075 if (ch
== 'e' || ch
== 'E') {
2076 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2080 if (ch
== '-' || ch
== '+') {
2081 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2086 if (ch
< '0' || ch
> '9')
2087 expect("exponent digits");
2088 while (ch
>= '0' && ch
<= '9') {
2089 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2101 tokc
.f
= strtof(token_buf
, NULL
);
2102 } else if (t
== 'L') {
2104 #ifdef TCC_TARGET_PE
2106 tokc
.d
= strtod(token_buf
, NULL
);
2109 tokc
.ld
= strtold(token_buf
, NULL
);
2113 tokc
.d
= strtod(token_buf
, NULL
);
2117 unsigned long long n
, n1
;
2120 /* integer number */
2123 if (b
== 10 && *q
== '0') {
2130 /* no need for checks except for base 10 / 8 errors */
2133 } else if (t
>= 'a') {
2135 } else if (t
>= 'A') {
2140 tcc_error("invalid digit");
2144 /* detect overflow */
2145 /* XXX: this test is not reliable */
2147 tcc_error("integer constant overflow");
2150 /* XXX: not exactly ANSI compliant */
2151 if ((n
& 0xffffffff00000000LL
) != 0) {
2156 } else if (n
> 0x7fffffff) {
2167 tcc_error("three 'l's in integer constant");
2169 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2172 if (tok
== TOK_CINT
)
2174 else if (tok
== TOK_CUINT
)
2176 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2180 } else if (t
== 'U') {
2182 tcc_error("two 'u's in integer constant");
2184 if (tok
== TOK_CINT
)
2186 else if (tok
== TOK_CLLONG
)
2193 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2199 tcc_error("invalid number\n");
2203 #define PARSE2(c1, tok1, c2, tok2) \
2214 /* return next token without macro substitution */
2215 static inline void next_nomacro1(void)
2230 goto keep_tok_flags
;
2237 /* first look if it is in fact an end of buffer */
2238 if (p
>= file
->buf_end
) {
2242 if (p
>= file
->buf_end
)
2255 TCCState
*s1
= tcc_state
;
2256 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2257 && !(tok_flags
& TOK_FLAG_EOF
)) {
2258 tok_flags
|= TOK_FLAG_EOF
;
2260 goto keep_tok_flags
;
2261 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2263 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2264 tcc_error("missing #endif");
2265 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2266 /* no include left : end of file. */
2269 tok_flags
&= ~TOK_FLAG_EOF
;
2270 /* pop include file */
2272 /* test if previous '#endif' was after a #ifdef at
2274 if (tok_flags
& TOK_FLAG_ENDIF
) {
2276 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2278 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2279 tok_flags
&= ~TOK_FLAG_ENDIF
;
2282 /* add end of include file debug info */
2283 if (tcc_state
->do_debug
) {
2284 put_stabd(N_EINCL
, 0, 0);
2286 /* pop include stack */
2288 s1
->include_stack_ptr
--;
2297 tok_flags
|= TOK_FLAG_BOL
;
2300 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2303 goto keep_tok_flags
;
2308 if ((tok_flags
& TOK_FLAG_BOL
) &&
2309 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2311 preprocess(tok_flags
& TOK_FLAG_BOF
);
2317 tok
= TOK_TWOSHARPS
;
2319 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
2320 p
= parse_line_comment(p
- 1);
2329 case 'a': case 'b': case 'c': case 'd':
2330 case 'e': case 'f': case 'g': case 'h':
2331 case 'i': case 'j': case 'k': case 'l':
2332 case 'm': case 'n': case 'o': case 'p':
2333 case 'q': case 'r': case 's': case 't':
2334 case 'u': case 'v': case 'w': case 'x':
2336 case 'A': case 'B': case 'C': case 'D':
2337 case 'E': case 'F': case 'G': case 'H':
2338 case 'I': case 'J': case 'K':
2339 case 'M': case 'N': case 'O': case 'P':
2340 case 'Q': case 'R': case 'S': case 'T':
2341 case 'U': case 'V': case 'W': case 'X':
2347 h
= TOK_HASH_FUNC(h
, c
);
2351 if (!isidnum_table
[c
-CH_EOF
])
2353 h
= TOK_HASH_FUNC(h
, c
);
2360 /* fast case : no stray found, so we have the full token
2361 and we have already hashed it */
2363 h
&= (TOK_HASH_SIZE
- 1);
2364 pts
= &hash_ident
[h
];
2369 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2371 pts
= &(ts
->hash_next
);
2373 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2377 cstr_reset(&tokcstr
);
2380 cstr_ccat(&tokcstr
, *p1
);
2386 while (isidnum_table
[c
-CH_EOF
]) {
2387 cstr_ccat(&tokcstr
, c
);
2390 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2396 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2398 goto parse_ident_fast
;
2401 if (c
== '\'' || c
== '\"') {
2405 cstr_reset(&tokcstr
);
2406 cstr_ccat(&tokcstr
, 'L');
2407 goto parse_ident_slow
;
2411 case '0': case '1': case '2': case '3':
2412 case '4': case '5': case '6': case '7':
2415 cstr_reset(&tokcstr
);
2416 /* after the first digit, accept digits, alpha, '.' or sign if
2417 prefixed by 'eEpP' */
2421 cstr_ccat(&tokcstr
, c
);
2423 if (!(isnum(c
) || isid(c
) || c
== '.' ||
2424 ((c
== '+' || c
== '-') &&
2425 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
2428 /* We add a trailing '\0' to ease parsing */
2429 cstr_ccat(&tokcstr
, '\0');
2430 tokc
.cstr
= &tokcstr
;
2434 /* special dot handling because it can also start a number */
2437 cstr_reset(&tokcstr
);
2438 cstr_ccat(&tokcstr
, '.');
2440 } else if (c
== '.') {
2460 /* parse the string */
2462 p
= parse_pp_string(p
, sep
, &str
);
2463 cstr_ccat(&str
, '\0');
2465 /* eval the escape (should be done as TOK_PPNUM) */
2466 cstr_reset(&tokcstr
);
2467 parse_escape_string(&tokcstr
, str
.data
, is_long
);
2472 /* XXX: make it portable */
2476 char_size
= sizeof(nwchar_t
);
2477 if (tokcstr
.size
<= char_size
)
2478 tcc_error("empty character constant");
2479 if (tokcstr
.size
> 2 * char_size
)
2480 tcc_warning("multi-character character constant");
2482 tokc
.i
= *(int8_t *)tokcstr
.data
;
2485 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2489 tokc
.cstr
= &tokcstr
;
2503 } else if (c
== '<') {
2521 } else if (c
== '>') {
2539 } else if (c
== '=') {
2552 } else if (c
== '=') {
2565 } else if (c
== '=') {
2578 } else if (c
== '=') {
2581 } else if (c
== '>') {
2589 PARSE2('!', '!', '=', TOK_NE
)
2590 PARSE2('=', '=', '=', TOK_EQ
)
2591 PARSE2('*', '*', '=', TOK_A_MUL
)
2592 PARSE2('%', '%', '=', TOK_A_MOD
)
2593 PARSE2('^', '^', '=', TOK_A_XOR
)
2595 /* comments or operator */
2599 p
= parse_comment(p
);
2600 /* comments replaced by a blank */
2602 goto keep_tok_flags
;
2603 } else if (c
== '/') {
2604 p
= parse_line_comment(p
);
2606 goto keep_tok_flags
;
2607 } else if (c
== '=') {
2627 case '$': /* only used in assembler */
2628 case '@': /* dito */
2633 tcc_error("unrecognized character \\x%02x", c
);
2639 #if defined(PARSE_DEBUG)
2640 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2644 /* return next token without macro substitution. Can read input from
2646 static void next_nomacro_spc(void)
2652 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2653 if (tok
== TOK_LINENUM
) {
2654 file
->line_num
= tokc
.i
;
2663 ST_FUNC
void next_nomacro(void)
2667 } while (is_space(tok
));
2670 /* substitute arguments in replacement lists in macro_str by the values in
2671 args (field d) and return allocated string */
2672 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2674 int last_tok
, t
, spc
;
2684 TOK_GET(&t
, ¯o_str
, &cval
);
2689 TOK_GET(&t
, ¯o_str
, &cval
);
2692 s
= sym_find2(args
, t
);
2698 TOK_GET(&t
, &st
, &cval
);
2699 if (!check_space(t
, &spc
))
2700 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2703 cstr_ccat(&cstr
, '\0');
2705 printf("stringize: %s\n", (char *)cstr
.data
);
2709 tok_str_add2(&str
, TOK_STR
, &cval
);
2712 tok_str_add2(&str
, t
, &cval
);
2714 } else if (t
>= TOK_IDENT
) {
2715 s
= sym_find2(args
, t
);
2718 /* if '##' is present before or after, no arg substitution */
2719 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
2720 /* special case for var arg macros : ## eats the
2721 ',' if empty VA_ARGS variable. */
2722 /* XXX: test of the ',' is not 100%
2723 reliable. should fix it to avoid security
2725 if (gnu_ext
&& s
->type
.t
&&
2726 last_tok
== TOK_TWOSHARPS
&&
2727 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
2728 if (*st
== TOK_PLCHLDR
) {
2729 /* suppress ',' '##' */
2732 /* suppress '##' and add variable */
2740 TOK_GET(&t1
, &st
, &cval
);
2743 tok_str_add2(&str
, t1
, &cval
);
2747 /* NOTE: the stream cannot be read when macro
2748 substituing an argument */
2749 macro_subst(&str
, nested_list
, st
, NULL
);
2752 tok_str_add(&str
, t
);
2755 tok_str_add2(&str
, t
, &cval
);
2759 tok_str_add(&str
, 0);
2763 static char const ab_month_name
[12][4] =
2765 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2766 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2769 /* do macro substitution of current token with macro 's' and add
2770 result to (tok_str,tok_len). 'nested_list' is the list of all
2771 macros we got inside to avoid recursing. Return non zero if no
2772 substitution needs to be done */
2773 static int macro_subst_tok(TokenString
*tok_str
,
2774 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
2776 Sym
*args
, *sa
, *sa1
;
2777 int mstr_allocated
, parlevel
, *mstr
, t
, t1
, spc
;
2785 /* if symbol is a macro, prepare substitution */
2786 /* special macros */
2787 if (tok
== TOK___LINE__
) {
2788 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2792 } else if (tok
== TOK___FILE__
) {
2793 cstrval
= file
->filename
;
2795 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2800 tm
= localtime(&ti
);
2801 if (tok
== TOK___DATE__
) {
2802 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2803 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2805 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2806 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2813 cstr_cat(&cstr
, cstrval
);
2814 cstr_ccat(&cstr
, '\0');
2816 tok_str_add2(tok_str
, t1
, &cval
);
2821 if (s
->type
.t
== MACRO_FUNC
) {
2822 /* NOTE: we do not use next_nomacro to avoid eating the
2823 next token. XXX: find better solution */
2827 while (is_space(t
= *p
) || TOK_LINEFEED
== t
)
2829 if (t
== 0 && can_read_stream
) {
2830 /* end of macro stream: we must look at the token
2831 after in the file */
2832 struct macro_level
*ml
= *can_read_stream
;
2838 *can_read_stream
= ml
-> prev
;
2840 /* also, end of scope for nested defined symbol */
2841 (*nested_list
)->v
= -1;
2845 ch
= file
->buf_ptr
[0];
2846 while (is_space(ch
) || ch
== '\n' || ch
== '/')
2851 uint8_t *p
= file
->buf_ptr
;
2854 p
= parse_comment(p
);
2855 file
->buf_ptr
= p
- 1;
2856 } else if (c
== '/') {
2857 p
= parse_line_comment(p
);
2858 file
->buf_ptr
= p
- 1;
2866 if (t
!= '(') /* no macro subst */
2869 /* argument macro */
2874 /* NOTE: empty args are allowed, except if no args */
2876 /* handle '()' case */
2877 if (!args
&& !sa
&& tok
== ')')
2880 tcc_error("macro '%s' used with too many args",
2881 get_tok_str(s
->v
, 0));
2884 /* NOTE: non zero sa->t indicates VA_ARGS */
2885 while ((parlevel
> 0 ||
2887 (tok
!= ',' || sa
->type
.t
))) &&
2891 else if (tok
== ')')
2893 if (tok
== TOK_LINEFEED
)
2895 if (!check_space(tok
, &spc
))
2896 tok_str_add2(&str
, tok
, &tokc
);
2900 tok_str_add(&str
, TOK_PLCHLDR
);
2902 tok_str_add(&str
, 0);
2903 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
2907 /* special case for gcc var args: add an empty
2908 var arg argument if it is omitted */
2909 if (sa
&& sa
->type
.t
&& gnu_ext
)
2919 tcc_error("macro '%s' used with too few args",
2920 get_tok_str(s
->v
, 0));
2923 /* now subst each arg */
2924 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
2929 tok_str_free(sa
->d
);
2935 sym_push2(nested_list
, s
->v
, 0, 0);
2936 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
2937 /* pop nested defined symbol */
2939 *nested_list
= sa1
->prev
;
2947 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2948 return the resulting string (which must be freed). */
2949 static inline int *macro_twosharps(const int *macro_str
)
2953 TokenString macro_str1
;
2955 int n
, start_of_nosubsts
;
2957 /* we search the first '##' */
2958 for(ptr
= macro_str
;;) {
2960 TOK_GET(&t
, &ptr
, &cval
);
2961 if (t
== TOK_TWOSHARPS
)
2963 /* nothing more to do if end of string */
2968 /* we saw '##', so we need more processing to handle it */
2969 start_of_nosubsts
= -1;
2970 tok_str_new(¯o_str1
);
2971 for(ptr
= macro_str
;;) {
2972 TOK_GET(&tok
, &ptr
, &tokc
);
2975 if (tok
== TOK_TWOSHARPS
)
2977 if (tok
== TOK_NOSUBST
&& start_of_nosubsts
< 0)
2978 start_of_nosubsts
= macro_str1
.len
;
2979 while (*ptr
== TOK_TWOSHARPS
) {
2980 /* given 'a##b', remove nosubsts preceding 'a' */
2981 if (start_of_nosubsts
>= 0)
2982 macro_str1
.len
= start_of_nosubsts
;
2983 /* given 'a##b', skip '##' */
2985 /* given 'a##b', remove nosubsts preceding 'b' */
2986 while (t
== TOK_NOSUBST
)
2988 if (t
&& t
!= TOK_TWOSHARPS
) {
2990 TOK_GET(&t
, &ptr
, &cval
);
2991 /* We concatenate the two tokens */
2993 if (tok
!= TOK_PLCHLDR
)
2994 cstr_cat(&cstr
, get_tok_str(tok
, &tokc
));
2996 if (t
!= TOK_PLCHLDR
|| tok
== TOK_PLCHLDR
)
2997 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2998 cstr_ccat(&cstr
, '\0');
3000 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3001 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3004 if (0 == *file
->buf_ptr
)
3006 tok_str_add2(¯o_str1
, tok
, &tokc
);
3007 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
3008 n
, cstr
.data
, (char*)cstr
.data
+ n
);
3014 if (tok
!= TOK_NOSUBST
) {
3015 tok_str_add2(¯o_str1
, tok
, &tokc
);
3017 start_of_nosubsts
= -1;
3019 tok_str_add2(¯o_str1
, tok
, &tokc
);
3021 tok_str_add(¯o_str1
, 0);
3022 return macro_str1
.str
;
3026 /* do macro substitution of macro_str and add result to
3027 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3028 inside to avoid recursing. */
3029 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
3030 const int *macro_str
, struct macro_level
** can_read_stream
)
3037 struct macro_level ml
;
3040 /* first scan for '##' operator handling */
3042 macro_str1
= macro_twosharps(ptr
);
3050 /* NOTE: ptr == NULL can only happen if tokens are read from
3051 file stream due to a macro function call */
3054 TOK_GET(&t
, &ptr
, &cval
);
3057 if (t
== TOK_NOSUBST
) {
3058 /* following token has already been subst'd. just copy it on */
3059 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3060 TOK_GET(&t
, &ptr
, &cval
);
3065 /* if nested substitution, do nothing */
3066 if (sym_find2(*nested_list
, t
)) {
3067 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3068 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3072 if (can_read_stream
)
3073 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
3074 macro_ptr
= (int *)ptr
;
3076 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
3077 ptr
= (int *)macro_ptr
;
3079 if (can_read_stream
&& *can_read_stream
== &ml
)
3080 *can_read_stream
= ml
.prev
;
3083 if (parse_flags
& PARSE_FLAG_SPACES
)
3088 tok_str_add(tok_str
, ' ');
3092 if (!check_space(t
, &spc
))
3093 tok_str_add2(tok_str
, t
, &cval
);
3097 tok_str_free(macro_str1
);
3100 /* return next token with macro substitution */
3101 ST_FUNC
void next(void)
3103 Sym
*nested_list
, *s
;
3105 struct macro_level
*ml
;
3108 if (parse_flags
& PARSE_FLAG_SPACES
)
3113 /* if not reading from macro substituted string, then try
3114 to substitute macros */
3115 if (tok
>= TOK_IDENT
&&
3116 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3117 s
= define_find(tok
);
3119 /* we have a macro: we try to substitute */
3123 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
3124 /* substitution done, NOTE: maybe empty */
3125 tok_str_add(&str
, 0);
3126 macro_ptr
= str
.str
;
3127 macro_ptr_allocated
= str
.str
;
3134 /* end of macro or end of unget buffer */
3135 if (unget_buffer_enabled
) {
3136 macro_ptr
= unget_saved_macro_ptr
;
3137 unget_buffer_enabled
= 0;
3139 /* end of macro string: free it */
3140 tok_str_free(macro_ptr_allocated
);
3141 macro_ptr_allocated
= NULL
;
3145 } else if (tok
== TOK_NOSUBST
) {
3146 /* discard preprocessor's nosubst markers */
3151 /* convert preprocessor tokens into C tokens */
3152 if (tok
== TOK_PPNUM
&&
3153 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
3154 parse_number((char *)tokc
.cstr
->data
);
3158 /* push back current token and set current token to 'last_tok'. Only
3159 identifier case handled for labels. */
3160 ST_INLN
void unget_tok(int last_tok
)
3164 if (unget_buffer_enabled
)
3166 /* assert(macro_ptr == unget_saved_buffer + 1);
3167 assert(*macro_ptr == 0); */
3171 unget_saved_macro_ptr
= macro_ptr
;
3172 unget_buffer_enabled
= 1;
3174 q
= unget_saved_buffer
;
3177 n
= tok_ext_size(tok
) - 1;
3180 *q
= 0; /* end of token string */
3185 /* better than nothing, but needs extension to handle '-E' option
3187 ST_FUNC
void preprocess_init(TCCState
*s1
)
3189 s1
->include_stack_ptr
= s1
->include_stack
;
3190 /* XXX: move that before to avoid having to initialize
3191 file->ifdef_stack_ptr ? */
3192 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3193 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3196 s1
->pack_stack
[0] = 0;
3197 s1
->pack_stack_ptr
= s1
->pack_stack
;
3200 ST_FUNC
void preprocess_new(void)
3205 /* init isid table */
3206 for(i
=CH_EOF
;i
<256;i
++)
3207 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
3209 /* add all tokens */
3211 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3213 tok_ident
= TOK_IDENT
;
3222 tok_alloc(p
, r
- p
- 1);
3227 /* Preprocess the current file */
3228 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3232 BufferedFile
*file_ref
, **iptr
, **iptr_new
;
3236 preprocess_init(s1
);
3237 define_start
= define_stack
;
3238 ch
= file
->buf_ptr
[0];
3239 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3240 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
3241 PARSE_FLAG_LINEFEED
| PARSE_FLAG_SPACES
;
3244 iptr
= s1
->include_stack_ptr
;
3245 tok
= TOK_LINEFEED
; /* print line */
3249 if (tok
== TOK_EOF
) {
3251 } else if (file
!= file_ref
) {
3253 } else if (tok
== TOK_LINEFEED
) {
3258 } else if (token_seen
) {
3259 d
= file
->line_num
- line_ref
;
3260 if (file
!= file_ref
|| d
< 0 || d
>= 8) {
3262 iptr_new
= s1
->include_stack_ptr
;
3263 s
= iptr_new
> iptr
? " 1"
3264 : iptr_new
< iptr
? " 2"
3265 : iptr_new
> s1
->include_stack
? " 3"
3268 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", file
->line_num
, file
->filename
, s
);
3271 fputs("\n", s1
->ppfp
), --d
;
3273 line_ref
= (file_ref
= file
)->line_num
;
3274 token_seen
= tok
== TOK_LINEFEED
;
3278 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);
3280 free_defines(define_start
);