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
[] =
74 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
75 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
96 '.','.', 0xa8, // C++ token ?
97 '#','#', TOK_TWOSHARPS
,
102 struct macro_level
*prev
;
106 static void next_nomacro_spc(void);
107 static void macro_subst(
108 TokenString
*tok_str
,
110 const int *macro_str
,
111 struct macro_level
**can_read_stream
114 ST_FUNC
void skip(int c
)
117 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
121 ST_FUNC
void expect(const char *msg
)
123 tcc_error("%s expected", msg
);
126 /* ------------------------------------------------------------------------- */
127 /* CString handling */
128 static void cstr_realloc(CString
*cstr
, int new_size
)
133 size
= cstr
->size_allocated
;
135 size
= 8; /* no need to allocate a too small first string */
136 while (size
< new_size
)
138 data
= tcc_realloc(cstr
->data_allocated
, size
);
139 cstr
->data_allocated
= data
;
140 cstr
->size_allocated
= size
;
145 ST_FUNC
void cstr_ccat(CString
*cstr
, int ch
)
148 size
= cstr
->size
+ 1;
149 if (size
> cstr
->size_allocated
)
150 cstr_realloc(cstr
, size
);
151 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
155 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
)
167 /* add a wide char */
168 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
171 size
= cstr
->size
+ sizeof(nwchar_t
);
172 if (size
> cstr
->size_allocated
)
173 cstr_realloc(cstr
, size
);
174 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
178 ST_FUNC
void cstr_new(CString
*cstr
)
180 memset(cstr
, 0, sizeof(CString
));
183 /* free string and reset it to NULL */
184 ST_FUNC
void cstr_free(CString
*cstr
)
186 tcc_free(cstr
->data_allocated
);
190 /* reset string to empty */
191 ST_FUNC
void cstr_reset(CString
*cstr
)
197 static void add_char(CString
*cstr
, int c
)
199 if (c
== '\'' || c
== '\"' || c
== '\\') {
200 /* XXX: could be more precise if char or string */
201 cstr_ccat(cstr
, '\\');
203 if (c
>= 32 && c
<= 126) {
206 cstr_ccat(cstr
, '\\');
208 cstr_ccat(cstr
, 'n');
210 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
211 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
212 cstr_ccat(cstr
, '0' + (c
& 7));
217 /* ------------------------------------------------------------------------- */
218 /* allocate a new token */
219 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
221 TokenSym
*ts
, **ptable
;
224 if (tok_ident
>= SYM_FIRST_ANOM
)
225 tcc_error("memory full (symbols)");
227 /* expand token table if needed */
228 i
= tok_ident
- TOK_IDENT
;
229 if ((i
% TOK_ALLOC_INCR
) == 0) {
230 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
231 table_ident
= ptable
;
234 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
236 ts
->tok
= tok_ident
++;
237 ts
->sym_define
.data
= tcc_malloc(sizeof(Sym
*));
238 ts
->sym_define
.off
= 0;
239 ts
->sym_define
.data
[0] = NULL
;
240 ts
->sym_define
.size
= 1;
241 ts
->sym_label
= NULL
;
242 ts
->sym_struct
= NULL
;
243 ts
->sym_identifier
= NULL
;
245 ts
->hash_next
= NULL
;
246 memcpy(ts
->str
, str
, len
);
252 #define TOK_HASH_INIT 1
253 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
255 /* find a token and add it if not found */
256 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
264 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
265 h
&= (TOK_HASH_SIZE
- 1);
267 pts
= &hash_ident
[h
];
272 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
274 pts
= &(ts
->hash_next
);
276 return tok_alloc_new(pts
, str
, len
);
279 /* XXX: buffer overflow */
280 /* XXX: float tokens */
281 ST_FUNC
char *get_tok_str(int v
, CValue
*cv
)
283 static char buf
[STRING_MAX_SIZE
+ 1];
284 static CString cstr_buf
;
289 /* NOTE: to go faster, we give a fixed buffer for small strings */
290 cstr_reset(&cstr_buf
);
292 cstr_buf
.size_allocated
= sizeof(buf
);
295 /* just an explanation, should never happen:
296 if (v <= TOK_LINENUM && v >= TOK_CINT && cv == NULL)
297 tcc_error("internal error: get_tok_str"); */
302 /* XXX: not quite exact, but only useful for testing */
303 sprintf(p
, "%u", cv
->ui
);
307 /* XXX: not quite exact, but only useful for testing */
309 sprintf(p
, "%u", (unsigned)cv
->ull
);
311 sprintf(p
, "%llu", cv
->ull
);
315 cstr_ccat(&cstr_buf
, 'L');
317 cstr_ccat(&cstr_buf
, '\'');
318 add_char(&cstr_buf
, cv
->i
);
319 cstr_ccat(&cstr_buf
, '\'');
320 cstr_ccat(&cstr_buf
, '\0');
324 len
= cstr
->size
- 1;
326 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
327 cstr_ccat(&cstr_buf
, '\0');
330 cstr_ccat(&cstr_buf
, 'L');
333 cstr_ccat(&cstr_buf
, '\"');
335 len
= cstr
->size
- 1;
337 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
339 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
341 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
343 cstr_ccat(&cstr_buf
, '\"');
344 cstr_ccat(&cstr_buf
, '\0');
351 return NULL
; /* should not happen */
353 /* above tokens have value, the ones below don't */
362 return strcpy(p
, "...");
364 return strcpy(p
, "<<=");
366 return strcpy(p
, ">>=");
369 /* search in two bytes table */
370 const unsigned char *q
= tok_two_chars
;
383 } else if (v
< tok_ident
) {
384 return table_ident
[v
- TOK_IDENT
]->str
;
385 } else if (v
>= SYM_FIRST_ANOM
) {
386 /* special name for anonymous symbol */
387 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
389 /* should never happen */
394 return cstr_buf
.data
;
397 /* fill input buffer and peek next char */
398 static int tcc_peekc_slow(BufferedFile
*bf
)
401 /* only tries to read if really end of buffer */
402 if (bf
->buf_ptr
>= bf
->buf_end
) {
404 #if defined(PARSE_DEBUG)
409 len
= read(bf
->fd
, bf
->buffer
, len
);
416 bf
->buf_ptr
= bf
->buffer
;
417 bf
->buf_end
= bf
->buffer
+ len
;
418 *bf
->buf_end
= CH_EOB
;
420 if (bf
->buf_ptr
< bf
->buf_end
) {
421 return bf
->buf_ptr
[0];
423 bf
->buf_ptr
= bf
->buf_end
;
428 /* return the current character, handling end of block if necessary
430 ST_FUNC
int handle_eob(void)
432 return tcc_peekc_slow(file
);
435 /* read next char from current input file and handle end of input buffer */
436 ST_INLN
void inp(void)
438 ch
= *(++(file
->buf_ptr
));
439 /* end of buffer/file handling */
444 /* handle '\[\r]\n' */
445 static int handle_stray_noerror(void)
452 } else if (ch
== '\r') {
466 static void handle_stray(void)
468 if (handle_stray_noerror())
469 tcc_error("stray '\\' in program");
472 /* skip the stray and handle the \\n case. Output an error if
473 incorrect char after the stray */
474 static int handle_stray1(uint8_t *p
)
478 if (p
>= file
->buf_end
) {
495 /* handle just the EOB case, but not stray */
496 #define PEEKC_EOB(c, p)\
507 /* handle the complicated stray case */
513 c = handle_stray1(p);\
518 /* input with '\[\r]\n' handling. Note that this function cannot
519 handle other characters after '\', so you cannot call it inside
520 strings or comments */
521 ST_FUNC
void minp(void)
529 /* single line C++ comments */
530 static uint8_t *parse_line_comment(uint8_t *p
)
538 if (c
== '\n' || c
== CH_EOF
) {
540 } else if (c
== '\\') {
549 } else if (c
== '\r') {
567 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
576 if (c
== '\n' || c
== '*' || c
== '\\')
580 if (c
== '\n' || c
== '*' || c
== '\\')
584 /* now we can handle all the cases */
588 } else if (c
== '*') {
594 } else if (c
== '/') {
596 } else if (c
== '\\') {
601 /* skip '\[\r]\n', otherwise just skip the stray */
607 } else if (c
== '\r') {
624 /* stray, eob or eof */
629 tcc_error("unexpected end of file in comment");
630 } else if (c
== '\\') {
642 static inline void skip_spaces(void)
648 static inline int check_space(int t
, int *spc
)
659 /* parse a string without interpreting escapes */
660 static uint8_t *parse_pp_string(uint8_t *p
,
661 int sep
, CString
*str
)
669 } else if (c
== '\\') {
675 /* XXX: indicate line number of start of string */
676 tcc_error("missing terminating %c character", sep
);
677 } else if (c
== '\\') {
678 /* escape : just skip \[\r]\n */
683 } else if (c
== '\r') {
686 expect("'\n' after '\r'");
689 } else if (c
== CH_EOF
) {
690 goto unterminated_string
;
693 cstr_ccat(str
, '\\');
699 } else if (c
== '\n') {
702 } else if (c
== '\r') {
706 cstr_ccat(str
, '\r');
722 /* skip block of text until #else, #elif or #endif. skip also pairs of
724 static void preprocess_skip(void)
726 int a
, start_of_line
, c
, in_warn_or_error
;
733 in_warn_or_error
= 0;
754 } else if (c
== '\\') {
755 ch
= file
->buf_ptr
[0];
756 handle_stray_noerror();
763 if (in_warn_or_error
)
765 p
= parse_pp_string(p
, c
, NULL
);
769 if (in_warn_or_error
)
776 p
= parse_comment(p
);
777 } else if (ch
== '/') {
778 p
= parse_line_comment(p
);
788 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
790 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
792 else if (tok
== TOK_ENDIF
)
794 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
795 in_warn_or_error
= 1;
796 else if (tok
== TOK_LINEFEED
)
811 /* ParseState handling */
813 /* XXX: currently, no include file info is stored. Thus, we cannot display
814 accurate messages if the function or data definition spans multiple
817 /* save current parse state in 's' */
818 ST_FUNC
void save_parse_state(ParseState
*s
)
820 s
->line_num
= file
->line_num
;
821 s
->macro_ptr
= macro_ptr
;
826 /* restore parse state from 's' */
827 ST_FUNC
void restore_parse_state(ParseState
*s
)
829 file
->line_num
= s
->line_num
;
830 macro_ptr
= s
->macro_ptr
;
835 /* return the number of additional 'ints' necessary to store the
837 static inline int tok_ext_size(int t
)
851 tcc_error("unsupported token");
858 return LDOUBLE_SIZE
/ 4;
864 /* token string handling */
866 ST_INLN
void tok_str_new(TokenString
*s
)
870 s
->allocated_len
= 0;
871 s
->last_line_num
= -1;
874 ST_FUNC
void tok_str_free(int *str
)
879 static int *tok_str_realloc(TokenString
*s
)
883 if (s
->allocated_len
== 0) {
886 len
= s
->allocated_len
* 2;
888 str
= tcc_realloc(s
->str
, len
* sizeof(int));
889 s
->allocated_len
= len
;
894 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
900 if (len
>= s
->allocated_len
)
901 str
= tok_str_realloc(s
);
906 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
913 /* allocate space for worst case */
914 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
915 str
= tok_str_realloc(s
);
924 str
[len
++] = cv
->tab
[0];
933 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
934 while ((len
+ nb_words
) > s
->allocated_len
)
935 str
= tok_str_realloc(s
);
936 cstr
= (CString
*)(str
+ len
);
938 cstr
->size
= cv
->cstr
->size
;
939 cstr
->data_allocated
= NULL
;
940 cstr
->size_allocated
= cstr
->size
;
941 memcpy((char *)cstr
+ sizeof(CString
),
942 cv
->cstr
->data
, cstr
->size
);
949 #if LDOUBLE_SIZE == 8
952 str
[len
++] = cv
->tab
[0];
953 str
[len
++] = cv
->tab
[1];
955 #if LDOUBLE_SIZE == 12
957 str
[len
++] = cv
->tab
[0];
958 str
[len
++] = cv
->tab
[1];
959 str
[len
++] = cv
->tab
[2];
960 #elif LDOUBLE_SIZE == 16
962 str
[len
++] = cv
->tab
[0];
963 str
[len
++] = cv
->tab
[1];
964 str
[len
++] = cv
->tab
[2];
965 str
[len
++] = cv
->tab
[3];
966 #elif LDOUBLE_SIZE != 8
967 #error add long double size support
976 /* add the current parse token in token string 's' */
977 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
981 /* save line number info */
982 if (file
->line_num
!= s
->last_line_num
) {
983 s
->last_line_num
= file
->line_num
;
984 cval
.i
= s
->last_line_num
;
985 tok_str_add2(s
, TOK_LINENUM
, &cval
);
987 tok_str_add2(s
, tok
, &tokc
);
990 /* get a token from an integer array and increment pointer
991 accordingly. we code it as a macro to avoid pointer aliasing. */
992 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1010 cv
->cstr
= (CString
*)p
;
1011 cv
->cstr
->data
= (char *)p
+ sizeof(CString
);
1012 p
+= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
1020 #if LDOUBLE_SIZE == 16
1022 #elif LDOUBLE_SIZE == 12
1024 #elif LDOUBLE_SIZE == 8
1027 # error add long double size support
1040 static int macro_is_equal(const int *a
, const int *b
)
1042 char buf
[STRING_MAX_SIZE
+ 1];
1046 TOK_GET(&t
, &a
, &cv
);
1047 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1048 TOK_GET(&t
, &b
, &cv
);
1049 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1055 /* defines handling */
1056 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1061 if (s
&& !macro_is_equal(s
->d
, str
))
1062 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1063 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1065 s
->next
= first_arg
;
1066 def
= &table_ident
[v
- TOK_IDENT
]->sym_define
;
1067 def
->data
[def
->off
] = s
;
1070 /* undefined a define symbol. Its name is just set to zero */
1071 ST_FUNC
void define_undef(Sym
*s
)
1075 v
= s
->v
- TOK_IDENT
;
1076 if ((unsigned)v
< (unsigned)(tok_ident
- TOK_IDENT
)){
1077 def
= &table_ident
[v
]->sym_define
;
1078 def
->data
[def
->off
] = NULL
;
1082 ST_INLN Sym
*define_find(int v
)
1086 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1088 def
= &table_ident
[v
]->sym_define
;
1089 return def
->data
[def
->off
];
1092 /* free define stack until top reaches 'b' */
1093 ST_FUNC
void free_defines(Sym
*b
)
1102 /* do not free args or predefined defines */
1104 tok_str_free(top
->d
);
1105 v
= top
->v
- TOK_IDENT
;
1106 if ((unsigned)v
< (unsigned)(tok_ident
- TOK_IDENT
)){
1107 def
= &table_ident
[v
]->sym_define
;
1111 def
->data
[0] = NULL
;
1120 ST_FUNC Sym
*label_find(int v
)
1123 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1125 return table_ident
[v
]->sym_label
;
1128 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1131 s
= sym_push2(ptop
, v
, 0, 0);
1133 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1134 if (ptop
== &global_label_stack
) {
1135 /* modify the top most local identifier, so that
1136 sym_identifier will point to 's' when popped */
1138 ps
= &(*ps
)->prev_tok
;
1145 /* pop labels until element last is reached. Look if any labels are
1146 undefined. Define symbols if '&&label' was used. */
1147 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1150 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1152 if (s
->r
== LABEL_DECLARED
) {
1153 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1154 } else if (s
->r
== LABEL_FORWARD
) {
1155 tcc_error("label '%s' used but not defined",
1156 get_tok_str(s
->v
, NULL
));
1159 /* define corresponding symbol. A size of
1161 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1165 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1171 /* eval an expression for #if/#elif */
1172 static int expr_preprocess(void)
1178 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1179 next(); /* do macro subst */
1180 if (tok
== TOK_DEFINED
) {
1185 c
= define_find(tok
) != 0;
1190 } else if (tok
>= TOK_IDENT
) {
1191 /* if undefined macro */
1195 tok_str_add_tok(&str
);
1197 tok_str_add(&str
, -1); /* simulate end of file */
1198 tok_str_add(&str
, 0);
1199 /* now evaluate C constant expression */
1200 macro_ptr
= str
.str
;
1204 tok_str_free(str
.str
);
1208 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1209 static void tok_print(int *str
)
1216 TOK_GET(&t
, &str
, &cval
);
1219 printf("%s", get_tok_str(t
, &cval
));
1225 /* parse after #define */
1226 ST_FUNC
void parse_define(void)
1228 Sym
*s
, *first
, **ps
;
1229 int v
, t
, varg
, is_vaargs
, spc
, ptok
, macro_list_start
;
1234 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1235 /* XXX: should check if same macro (ANSI) */
1238 /* '(' must be just after macro definition for MACRO_FUNC */
1243 while (tok
!= ')') {
1247 if (varg
== TOK_DOTS
) {
1248 varg
= TOK___VA_ARGS__
;
1250 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1254 if (varg
< TOK_IDENT
)
1255 tcc_error("badly punctuated parameter list");
1256 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1269 /* EOF testing necessary for '-D' handling */
1271 macro_list_start
= 1;
1272 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1273 if (!macro_list_start
&& spc
== 2 && tok
== TOK_TWOSHARPS
)
1274 tcc_error("'##' invalid at start of macro");
1276 /* remove spaces around ## and after '#' */
1277 if (TOK_TWOSHARPS
== tok
) {
1281 } else if ('#' == tok
) {
1283 } else if (check_space(tok
, &spc
)) {
1286 tok_str_add2(&str
, tok
, &tokc
);
1289 macro_list_start
= 0;
1291 if (ptok
== TOK_TWOSHARPS
)
1292 tcc_error("'##' invalid at end of macro");
1294 --str
.len
; /* remove trailing space */
1295 tok_str_add(&str
, 0);
1297 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
1300 define_push(v
, t
, str
.str
, first
);
1303 static inline int hash_cached_include(const char *filename
)
1305 const unsigned char *s
;
1309 s
= (unsigned char *) filename
;
1311 h
= TOK_HASH_FUNC(h
, *s
);
1314 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1318 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1322 h
= hash_cached_include(filename
);
1323 i
= s1
->cached_includes_hash
[h
];
1327 e
= s1
->cached_includes
[i
- 1];
1328 if (0 == PATHCMP(e
->filename
, filename
))
1335 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1340 if (search_cached_include(s1
, filename
))
1343 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1345 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1346 strcpy(e
->filename
, filename
);
1347 e
->ifndef_macro
= ifndef_macro
;
1348 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1349 /* add in hash table */
1350 h
= hash_cached_include(filename
);
1351 e
->hash_next
= s1
->cached_includes_hash
[h
];
1352 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1355 /* is_bof is true if first non space token at beginning of file */
1356 ST_FUNC
void preprocess(int is_bof
)
1358 TCCState
*s1
= tcc_state
;
1359 int i
, c
, n
, saved_parse_flags
;
1360 uint8_t buf
[1024], *p
;
1363 saved_parse_flags
= parse_flags
;
1364 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
| PARSE_FLAG_LINEFEED
;
1374 s
= define_find(tok
);
1375 /* undefine symbol by putting an invalid name */
1380 case TOK_INCLUDE_NEXT
:
1381 ch
= file
->buf_ptr
[0];
1382 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1387 } else if (ch
== '\"') {
1392 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1393 if ((p
- buf
) < sizeof(buf
) - 1)
1396 if (handle_stray_noerror() == 0)
1402 goto include_syntax
;
1406 /* eat all spaces and comments after include */
1407 /* XXX: slightly incorrect */
1408 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1412 /* computed #include : either we have only strings or
1413 we have anything enclosed in '<>' */
1416 if (tok
== TOK_STR
) {
1417 while (tok
!= TOK_LINEFEED
) {
1418 if (tok
!= TOK_STR
) {
1420 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1422 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1428 while (tok
!= TOK_LINEFEED
) {
1429 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1433 /* check syntax and remove '<>' */
1434 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1435 goto include_syntax
;
1436 memmove(buf
, buf
+ 1, len
- 2);
1437 buf
[len
- 2] = '\0';
1442 tcc_error(" empty filename in #include");
1444 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1445 tcc_error("#include recursion too deep");
1446 /* store current file in stack, but increment stack later below */
1447 *s1
->include_stack_ptr
= file
;
1449 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1450 for (i
= -2; i
< n
; ++i
) {
1451 char buf1
[sizeof file
->filename
];
1457 /* check absolute include path */
1458 if (!IS_ABSPATH(buf
))
1461 i
= n
; /* force end loop */
1463 } else if (i
== -1) {
1464 /* search in current dir if "header.h" */
1467 path
= file
->filename
;
1468 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1471 /* search in all the include paths */
1472 if (i
< s1
->nb_include_paths
)
1473 path
= s1
->include_paths
[i
];
1475 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1476 pstrcpy(buf1
, sizeof(buf1
), path
);
1477 pstrcat(buf1
, sizeof(buf1
), "/");
1480 pstrcat(buf1
, sizeof(buf1
), buf
);
1482 if (tok
== TOK_INCLUDE_NEXT
)
1483 for (f
= s1
->include_stack_ptr
; f
>= s1
->include_stack
; --f
)
1484 if (0 == PATHCMP((*f
)->filename
, buf1
)) {
1486 printf("%s: #include_next skipping %s\n", file
->filename
, buf1
);
1488 goto include_trynext
;
1491 e
= search_cached_include(s1
, buf1
);
1492 if (e
&& define_find(e
->ifndef_macro
)) {
1493 /* no need to parse the include because the 'ifndef macro'
1496 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1501 if (tcc_open(s1
, buf1
) < 0)
1506 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1508 /* update target deps */
1509 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
, tcc_strdup(buf1
));
1510 /* push current file in stack */
1511 ++s1
->include_stack_ptr
;
1512 /* add include file debug info */
1514 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1515 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1516 ch
= file
->buf_ptr
[0];
1519 tcc_error("include file '%s' not found", buf
);
1526 c
= expr_preprocess();
1532 if (tok
< TOK_IDENT
)
1533 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1537 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1539 file
->ifndef_macro
= tok
;
1542 c
= !!define_find(tok
) ^ c
;
1544 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1545 tcc_error("memory full (ifdef)");
1546 *s1
->ifdef_stack_ptr
++ = c
;
1549 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1550 tcc_error("#else without matching #if");
1551 if (s1
->ifdef_stack_ptr
[-1] & 2)
1552 tcc_error("#else after #else");
1553 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1556 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1557 tcc_error("#elif without matching #if");
1558 c
= s1
->ifdef_stack_ptr
[-1];
1560 tcc_error("#elif after #else");
1561 /* last #if/#elif expression was true: we skip */
1564 c
= expr_preprocess();
1565 s1
->ifdef_stack_ptr
[-1] = c
;
1567 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1568 file
->ifndef_macro
= 0;
1578 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1579 tcc_error("#endif without matching #if");
1580 s1
->ifdef_stack_ptr
--;
1581 /* '#ifndef macro' was at the start of file. Now we check if
1582 an '#endif' is exactly at the end of file */
1583 if (file
->ifndef_macro
&&
1584 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1585 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1586 /* need to set to zero to avoid false matches if another
1587 #ifndef at middle of file */
1588 file
->ifndef_macro
= 0;
1589 tok_flags
|= TOK_FLAG_ENDIF
;
1592 if (tok
!= TOK_LINEFEED
)
1593 tcc_warning("Ignoring: %s", get_tok_str(tok
, &tokc
));
1597 if (tok
!= TOK_CINT
)
1599 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
1601 if (tok
!= TOK_LINEFEED
) {
1604 pstrcpy(file
->filename
, sizeof(file
->filename
), (char *)tokc
.cstr
->data
);
1610 ch
= file
->buf_ptr
[0];
1613 while (ch
!= '\n' && ch
!= CH_EOF
) {
1614 if ((p
- buf
) < sizeof(buf
) - 1)
1617 if (handle_stray_noerror() == 0)
1624 tcc_error("#error %s", buf
);
1626 tcc_warning("#warning %s", buf
);
1630 if (tok
== TOK_pack
&& s1
->output_type
!= TCC_OUTPUT_PREPROCESS
) {
1633 #pragma pack(1) // set
1634 #pragma pack() // reset to default
1635 #pragma pack(push,1) // push & set
1636 #pragma pack(pop) // restore previous
1640 if (tok
== TOK_ASM_pop
) {
1642 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1644 tcc_error("out of pack stack");
1646 s1
->pack_stack_ptr
--;
1650 if (tok
== TOK_ASM_push
) {
1652 s1
->pack_stack_ptr
++;
1653 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
)
1657 if (tok
!= TOK_CINT
) {
1659 tcc_error("invalid pack pragma");
1662 if (val
< 1 || val
> 16)
1664 if (val
< 1 || val
> 16)
1665 tcc_error("Value must be greater than 1 is less than or equal to 16");
1666 if ((val
& (val
- 1)) != 0)
1667 tcc_error("Value must be a power of 2 curtain");
1670 *s1
->pack_stack_ptr
= val
;
1673 }else if (tok
== TOK_PUSH_MACRO
|| tok
== TOK_POP_MACRO
) {
1679 ch
= file
->buf_ptr
[0];
1682 goto macro_xxx_syntax
;
1683 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1689 while (ch
!= '\"' && ch
!= '\n' && ch
!= CH_EOF
) {
1690 if ((p
- buf
) < sizeof(buf
) - 1)
1699 goto macro_xxx_syntax
;
1704 /* computed #pragma macro_xxx for #define xxx */
1707 while (tok
!= ')') {
1708 if (tok
!= TOK_STR
) {
1710 tcc_error("'macro_xxx' expects (\"NAME\")");
1712 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1718 tcc_error(" empty string in #pragma");
1721 while (is_space(*p
))
1725 if (!isidnum_table
[p
[0] - CH_EOF
])
1730 while (is_space(*p
))
1733 tcc_error("unrecognized string: %s", buf
);
1734 ts
= tok_alloc(p1
, len
);
1736 def
= &ts
->sym_define
;
1737 if(t
== TOK_PUSH_MACRO
){
1738 void *tmp
= def
->data
[def
->off
];
1740 if(def
->off
>= def
->size
){
1741 int size
= def
->size
;
1743 if (size
> MACRO_STACK_SIZE
)
1744 tcc_error("stack full");
1745 def
->data
= tcc_realloc(def
->data
, size
*sizeof(Sym
*));
1748 def
->data
[def
->off
] = tmp
;
1755 }else if(s1
->output_type
== TCC_OUTPUT_PREPROCESS
){
1756 fputs("#pragma ", s1
->ppfp
);
1757 while (tok
!= TOK_LINEFEED
){
1758 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);
1761 fputs("\n", s1
->ppfp
);
1766 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_PPNUM
) {
1767 /* '!' is ignored to allow C scripts. numbers are ignored
1768 to emulate cpp behaviour */
1770 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
1771 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1773 /* this is a gas line comment in an 'S' file. */
1774 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1780 /* ignore other preprocess commands or #! for C scripts */
1781 while (tok
!= TOK_LINEFEED
)
1784 parse_flags
= saved_parse_flags
;
1787 /* evaluate escape codes in a string. */
1788 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1803 case '0': case '1': case '2': case '3':
1804 case '4': case '5': case '6': case '7':
1805 /* at most three octal digits */
1810 n
= n
* 8 + c
- '0';
1814 n
= n
* 8 + c
- '0';
1819 goto add_char_nonext
;
1827 if (c
>= 'a' && c
<= 'f')
1829 else if (c
>= 'A' && c
<= 'F')
1839 goto add_char_nonext
;
1863 goto invalid_escape
;
1873 if (c
>= '!' && c
<= '~')
1874 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1876 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1883 cstr_ccat(outstr
, c
);
1885 cstr_wccat(outstr
, c
);
1887 /* add a trailing '\0' */
1889 cstr_ccat(outstr
, '\0');
1891 cstr_wccat(outstr
, '\0');
1894 /* we use 64 bit numbers */
1897 /* bn = (bn << shift) | or_val */
1898 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
1902 for(i
=0;i
<BN_SIZE
;i
++) {
1904 bn
[i
] = (v
<< shift
) | or_val
;
1905 or_val
= v
>> (32 - shift
);
1909 static void bn_zero(unsigned int *bn
)
1912 for(i
=0;i
<BN_SIZE
;i
++) {
1917 /* parse number in null terminated string 'p' and return it in the
1919 static void parse_number(const char *p
)
1921 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
1923 unsigned int bn
[BN_SIZE
];
1934 goto float_frac_parse
;
1935 } else if (t
== '0') {
1936 if (ch
== 'x' || ch
== 'X') {
1940 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
1946 /* parse all digits. cannot check octal numbers at this stage
1947 because of floating point constants */
1949 if (ch
>= 'a' && ch
<= 'f')
1951 else if (ch
>= 'A' && ch
<= 'F')
1959 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
1961 tcc_error("number too long");
1967 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
1968 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
1970 /* NOTE: strtox should support that for hexa numbers, but
1971 non ISOC99 libcs do not support it, so we prefer to do
1973 /* hexadecimal or binary floats */
1974 /* XXX: handle overflows */
1986 } else if (t
>= 'a') {
1988 } else if (t
>= 'A') {
1993 bn_lshift(bn
, shift
, t
);
2000 if (t
>= 'a' && t
<= 'f') {
2002 } else if (t
>= 'A' && t
<= 'F') {
2004 } else if (t
>= '0' && t
<= '9') {
2010 tcc_error("invalid digit");
2011 bn_lshift(bn
, shift
, t
);
2016 if (ch
!= 'p' && ch
!= 'P')
2023 } else if (ch
== '-') {
2027 if (ch
< '0' || ch
> '9')
2028 expect("exponent digits");
2029 while (ch
>= '0' && ch
<= '9') {
2030 exp_val
= exp_val
* 10 + ch
- '0';
2033 exp_val
= exp_val
* s
;
2035 /* now we can generate the number */
2036 /* XXX: should patch directly float number */
2037 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2038 d
= ldexp(d
, exp_val
- frac_bits
);
2043 /* float : should handle overflow */
2045 } else if (t
== 'L') {
2047 #ifdef TCC_TARGET_PE
2052 /* XXX: not large enough */
2053 tokc
.ld
= (long double)d
;
2060 /* decimal floats */
2062 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2067 while (ch
>= '0' && ch
<= '9') {
2068 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2074 if (ch
== 'e' || ch
== 'E') {
2075 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2079 if (ch
== '-' || ch
== '+') {
2080 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2085 if (ch
< '0' || ch
> '9')
2086 expect("exponent digits");
2087 while (ch
>= '0' && ch
<= '9') {
2088 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2100 tokc
.f
= strtof(token_buf
, NULL
);
2101 } else if (t
== 'L') {
2103 #ifdef TCC_TARGET_PE
2105 tokc
.d
= strtod(token_buf
, NULL
);
2108 tokc
.ld
= strtold(token_buf
, NULL
);
2112 tokc
.d
= strtod(token_buf
, NULL
);
2116 unsigned long long n
, n1
;
2119 /* integer number */
2122 if (b
== 10 && *q
== '0') {
2129 /* no need for checks except for base 10 / 8 errors */
2132 } else if (t
>= 'a') {
2134 } else if (t
>= 'A') {
2139 tcc_error("invalid digit");
2143 /* detect overflow */
2144 /* XXX: this test is not reliable */
2146 tcc_error("integer constant overflow");
2149 /* XXX: not exactly ANSI compliant */
2150 if ((n
& 0xffffffff00000000LL
) != 0) {
2155 } else if (n
> 0x7fffffff) {
2166 tcc_error("three 'l's in integer constant");
2168 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2171 if (tok
== TOK_CINT
)
2173 else if (tok
== TOK_CUINT
)
2175 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2179 } else if (t
== 'U') {
2181 tcc_error("two 'u's in integer constant");
2183 if (tok
== TOK_CINT
)
2185 else if (tok
== TOK_CLLONG
)
2192 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2198 tcc_error("invalid number\n");
2202 #define PARSE2(c1, tok1, c2, tok2) \
2213 /* return next token without macro substitution */
2214 static inline void next_nomacro1(void)
2229 goto keep_tok_flags
;
2236 /* first look if it is in fact an end of buffer */
2237 if (p
>= file
->buf_end
) {
2241 if (p
>= file
->buf_end
)
2254 TCCState
*s1
= tcc_state
;
2255 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2256 && !(tok_flags
& TOK_FLAG_EOF
)) {
2257 tok_flags
|= TOK_FLAG_EOF
;
2259 goto keep_tok_flags
;
2260 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2262 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2263 tcc_error("missing #endif");
2264 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2265 /* no include left : end of file. */
2268 tok_flags
&= ~TOK_FLAG_EOF
;
2269 /* pop include file */
2271 /* test if previous '#endif' was after a #ifdef at
2273 if (tok_flags
& TOK_FLAG_ENDIF
) {
2275 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2277 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2278 tok_flags
&= ~TOK_FLAG_ENDIF
;
2281 /* add end of include file debug info */
2282 if (tcc_state
->do_debug
) {
2283 put_stabd(N_EINCL
, 0, 0);
2285 /* pop include stack */
2287 s1
->include_stack_ptr
--;
2296 tok_flags
|= TOK_FLAG_BOL
;
2299 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2302 goto keep_tok_flags
;
2307 if ((tok_flags
& TOK_FLAG_BOL
) &&
2308 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2310 preprocess(tok_flags
& TOK_FLAG_BOF
);
2316 tok
= TOK_TWOSHARPS
;
2318 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
2319 p
= parse_line_comment(p
- 1);
2328 case 'a': case 'b': case 'c': case 'd':
2329 case 'e': case 'f': case 'g': case 'h':
2330 case 'i': case 'j': case 'k': case 'l':
2331 case 'm': case 'n': case 'o': case 'p':
2332 case 'q': case 'r': case 's': case 't':
2333 case 'u': case 'v': case 'w': case 'x':
2335 case 'A': case 'B': case 'C': case 'D':
2336 case 'E': case 'F': case 'G': case 'H':
2337 case 'I': case 'J': case 'K':
2338 case 'M': case 'N': case 'O': case 'P':
2339 case 'Q': case 'R': case 'S': case 'T':
2340 case 'U': case 'V': case 'W': case 'X':
2346 h
= TOK_HASH_FUNC(h
, c
);
2350 if (!isidnum_table
[c
-CH_EOF
])
2352 h
= TOK_HASH_FUNC(h
, c
);
2359 /* fast case : no stray found, so we have the full token
2360 and we have already hashed it */
2362 h
&= (TOK_HASH_SIZE
- 1);
2363 pts
= &hash_ident
[h
];
2368 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2370 pts
= &(ts
->hash_next
);
2372 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2376 cstr_reset(&tokcstr
);
2379 cstr_ccat(&tokcstr
, *p1
);
2385 while (isidnum_table
[c
-CH_EOF
]) {
2386 cstr_ccat(&tokcstr
, c
);
2389 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2395 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2397 goto parse_ident_fast
;
2400 if (c
== '\'' || c
== '\"') {
2404 cstr_reset(&tokcstr
);
2405 cstr_ccat(&tokcstr
, 'L');
2406 goto parse_ident_slow
;
2410 case '0': case '1': case '2': case '3':
2411 case '4': case '5': case '6': case '7':
2414 cstr_reset(&tokcstr
);
2415 /* after the first digit, accept digits, alpha, '.' or sign if
2416 prefixed by 'eEpP' */
2420 cstr_ccat(&tokcstr
, c
);
2422 if (!(isnum(c
) || isid(c
) || c
== '.' ||
2423 ((c
== '+' || c
== '-') &&
2424 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
2427 /* We add a trailing '\0' to ease parsing */
2428 cstr_ccat(&tokcstr
, '\0');
2429 tokc
.cstr
= &tokcstr
;
2433 /* special dot handling because it can also start a number */
2436 cstr_reset(&tokcstr
);
2437 cstr_ccat(&tokcstr
, '.');
2439 } else if (c
== '.') {
2459 /* parse the string */
2461 p
= parse_pp_string(p
, sep
, &str
);
2462 cstr_ccat(&str
, '\0');
2464 /* eval the escape (should be done as TOK_PPNUM) */
2465 cstr_reset(&tokcstr
);
2466 parse_escape_string(&tokcstr
, str
.data
, is_long
);
2471 /* XXX: make it portable */
2475 char_size
= sizeof(nwchar_t
);
2476 if (tokcstr
.size
<= char_size
)
2477 tcc_error("empty character constant");
2478 if (tokcstr
.size
> 2 * char_size
)
2479 tcc_warning("multi-character character constant");
2481 tokc
.i
= *(int8_t *)tokcstr
.data
;
2484 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2488 tokc
.cstr
= &tokcstr
;
2502 } else if (c
== '<') {
2520 } else if (c
== '>') {
2538 } else if (c
== '=') {
2551 } else if (c
== '=') {
2564 } else if (c
== '=') {
2577 } else if (c
== '=') {
2580 } else if (c
== '>') {
2588 PARSE2('!', '!', '=', TOK_NE
)
2589 PARSE2('=', '=', '=', TOK_EQ
)
2590 PARSE2('*', '*', '=', TOK_A_MUL
)
2591 PARSE2('%', '%', '=', TOK_A_MOD
)
2592 PARSE2('^', '^', '=', TOK_A_XOR
)
2594 /* comments or operator */
2598 p
= parse_comment(p
);
2599 /* comments replaced by a blank */
2601 goto keep_tok_flags
;
2602 } else if (c
== '/') {
2603 p
= parse_line_comment(p
);
2605 goto keep_tok_flags
;
2606 } else if (c
== '=') {
2626 case '$': /* only used in assembler */
2627 case '@': /* dito */
2632 tcc_error("unrecognized character \\x%02x", c
);
2638 #if defined(PARSE_DEBUG)
2639 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2643 /* return next token without macro substitution. Can read input from
2645 static void next_nomacro_spc(void)
2651 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2652 if (tok
== TOK_LINENUM
) {
2653 file
->line_num
= tokc
.i
;
2662 ST_FUNC
void next_nomacro(void)
2666 } while (is_space(tok
));
2669 /* substitute arguments in replacement lists in macro_str by the values in
2670 args (field d) and return allocated string */
2671 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2673 int last_tok
, t
, spc
;
2683 TOK_GET(&t
, ¯o_str
, &cval
);
2688 TOK_GET(&t
, ¯o_str
, &cval
);
2691 s
= sym_find2(args
, t
);
2697 TOK_GET(&t
, &st
, &cval
);
2698 if (!check_space(t
, &spc
))
2699 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2702 cstr_ccat(&cstr
, '\0');
2704 printf("stringize: %s\n", (char *)cstr
.data
);
2708 tok_str_add2(&str
, TOK_STR
, &cval
);
2711 tok_str_add2(&str
, t
, &cval
);
2713 } else if (t
>= TOK_IDENT
) {
2714 s
= sym_find2(args
, t
);
2717 /* if '##' is present before or after, no arg substitution */
2718 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
2719 /* special case for var arg macros : ## eats the
2720 ',' if empty VA_ARGS variable. */
2721 /* XXX: test of the ',' is not 100%
2722 reliable. should fix it to avoid security
2724 if (gnu_ext
&& s
->type
.t
&&
2725 last_tok
== TOK_TWOSHARPS
&&
2726 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
2727 if (*st
== TOK_PLCHLDR
) {
2728 /* suppress ',' '##' */
2731 /* suppress '##' and add variable */
2739 TOK_GET(&t1
, &st
, &cval
);
2742 tok_str_add2(&str
, t1
, &cval
);
2746 /* NOTE: the stream cannot be read when macro
2747 substituing an argument */
2748 macro_subst(&str
, nested_list
, st
, NULL
);
2751 tok_str_add(&str
, t
);
2754 tok_str_add2(&str
, t
, &cval
);
2758 tok_str_add(&str
, 0);
2762 static char const ab_month_name
[12][4] =
2764 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2765 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2768 /* do macro substitution of current token with macro 's' and add
2769 result to (tok_str,tok_len). 'nested_list' is the list of all
2770 macros we got inside to avoid recursing. Return non zero if no
2771 substitution needs to be done */
2772 static int macro_subst_tok(TokenString
*tok_str
,
2773 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
2775 Sym
*args
, *sa
, *sa1
;
2776 int mstr_allocated
, parlevel
, *mstr
, t
, t1
, spc
;
2784 /* if symbol is a macro, prepare substitution */
2785 /* special macros */
2786 if (tok
== TOK___LINE__
) {
2787 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2791 } else if (tok
== TOK___FILE__
) {
2792 cstrval
= file
->filename
;
2794 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2799 tm
= localtime(&ti
);
2800 if (tok
== TOK___DATE__
) {
2801 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2802 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2804 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2805 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2812 cstr_cat(&cstr
, cstrval
);
2813 cstr_ccat(&cstr
, '\0');
2815 tok_str_add2(tok_str
, t1
, &cval
);
2820 if (s
->type
.t
== MACRO_FUNC
) {
2821 /* NOTE: we do not use next_nomacro to avoid eating the
2822 next token. XXX: find better solution */
2826 while (is_space(t
= *p
) || TOK_LINEFEED
== t
)
2828 if (t
== 0 && can_read_stream
) {
2829 /* end of macro stream: we must look at the token
2830 after in the file */
2831 struct macro_level
*ml
= *can_read_stream
;
2837 *can_read_stream
= ml
-> prev
;
2839 /* also, end of scope for nested defined symbol */
2840 (*nested_list
)->v
= -1;
2844 ch
= file
->buf_ptr
[0];
2845 while (is_space(ch
) || ch
== '\n' || ch
== '/')
2850 uint8_t *p
= file
->buf_ptr
;
2853 p
= parse_comment(p
);
2854 file
->buf_ptr
= p
- 1;
2855 } else if (c
== '/') {
2856 p
= parse_line_comment(p
);
2857 file
->buf_ptr
= p
- 1;
2865 if (t
!= '(') /* no macro subst */
2868 /* argument macro */
2873 /* NOTE: empty args are allowed, except if no args */
2875 /* handle '()' case */
2876 if (!args
&& !sa
&& tok
== ')')
2879 tcc_error("macro '%s' used with too many args",
2880 get_tok_str(s
->v
, 0));
2883 /* NOTE: non zero sa->t indicates VA_ARGS */
2884 while ((parlevel
> 0 ||
2886 (tok
!= ',' || sa
->type
.t
))) &&
2890 else if (tok
== ')')
2892 if (tok
== TOK_LINEFEED
)
2894 if (!check_space(tok
, &spc
))
2895 tok_str_add2(&str
, tok
, &tokc
);
2899 tok_str_add(&str
, TOK_PLCHLDR
);
2901 tok_str_add(&str
, 0);
2902 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
2906 /* special case for gcc var args: add an empty
2907 var arg argument if it is omitted */
2908 if (sa
&& sa
->type
.t
&& gnu_ext
)
2918 tcc_error("macro '%s' used with too few args",
2919 get_tok_str(s
->v
, 0));
2922 /* now subst each arg */
2923 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
2928 tok_str_free(sa
->d
);
2934 sym_push2(nested_list
, s
->v
, 0, 0);
2935 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
2936 /* pop nested defined symbol */
2938 *nested_list
= sa1
->prev
;
2946 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2947 return the resulting string (which must be freed). */
2948 static inline int *macro_twosharps(const int *macro_str
)
2952 TokenString macro_str1
;
2954 int n
, start_of_nosubsts
;
2956 /* we search the first '##' */
2957 for(ptr
= macro_str
;;) {
2959 TOK_GET(&t
, &ptr
, &cval
);
2960 if (t
== TOK_TWOSHARPS
)
2962 /* nothing more to do if end of string */
2967 /* we saw '##', so we need more processing to handle it */
2968 start_of_nosubsts
= -1;
2969 tok_str_new(¯o_str1
);
2970 for(ptr
= macro_str
;;) {
2971 TOK_GET(&tok
, &ptr
, &tokc
);
2974 if (tok
== TOK_TWOSHARPS
)
2976 if (tok
== TOK_NOSUBST
&& start_of_nosubsts
< 0)
2977 start_of_nosubsts
= macro_str1
.len
;
2978 while (*ptr
== TOK_TWOSHARPS
) {
2979 /* given 'a##b', remove nosubsts preceding 'a' */
2980 if (start_of_nosubsts
>= 0)
2981 macro_str1
.len
= start_of_nosubsts
;
2982 /* given 'a##b', skip '##' */
2984 /* given 'a##b', remove nosubsts preceding 'b' */
2985 while (t
== TOK_NOSUBST
)
2987 if (t
&& t
!= TOK_TWOSHARPS
) {
2989 TOK_GET(&t
, &ptr
, &cval
);
2990 /* We concatenate the two tokens */
2992 if (tok
!= TOK_PLCHLDR
)
2993 cstr_cat(&cstr
, get_tok_str(tok
, &tokc
));
2995 if (t
!= TOK_PLCHLDR
|| tok
== TOK_PLCHLDR
)
2996 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2997 cstr_ccat(&cstr
, '\0');
2999 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3000 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3003 if (0 == *file
->buf_ptr
)
3005 tok_str_add2(¯o_str1
, tok
, &tokc
);
3006 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
3007 n
, cstr
.data
, (char*)cstr
.data
+ n
);
3013 if (tok
!= TOK_NOSUBST
) {
3014 tok_str_add2(¯o_str1
, tok
, &tokc
);
3016 start_of_nosubsts
= -1;
3018 tok_str_add2(¯o_str1
, tok
, &tokc
);
3020 tok_str_add(¯o_str1
, 0);
3021 return macro_str1
.str
;
3025 /* do macro substitution of macro_str and add result to
3026 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3027 inside to avoid recursing. */
3028 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
3029 const int *macro_str
, struct macro_level
** can_read_stream
)
3036 struct macro_level ml
;
3039 /* first scan for '##' operator handling */
3041 macro_str1
= macro_twosharps(ptr
);
3049 /* NOTE: ptr == NULL can only happen if tokens are read from
3050 file stream due to a macro function call */
3053 TOK_GET(&t
, &ptr
, &cval
);
3056 if (t
== TOK_NOSUBST
) {
3057 /* following token has already been subst'd. just copy it on */
3058 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3059 TOK_GET(&t
, &ptr
, &cval
);
3064 /* if nested substitution, do nothing */
3065 if (sym_find2(*nested_list
, t
)) {
3066 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3067 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3071 if (can_read_stream
)
3072 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
3073 macro_ptr
= (int *)ptr
;
3075 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
3076 ptr
= (int *)macro_ptr
;
3078 if (can_read_stream
&& *can_read_stream
== &ml
)
3079 *can_read_stream
= ml
.prev
;
3082 if (parse_flags
& PARSE_FLAG_SPACES
)
3087 tok_str_add(tok_str
, ' ');
3091 if (!check_space(t
, &spc
))
3092 tok_str_add2(tok_str
, t
, &cval
);
3096 tok_str_free(macro_str1
);
3099 /* return next token with macro substitution */
3100 ST_FUNC
void next(void)
3102 Sym
*nested_list
, *s
;
3104 struct macro_level
*ml
;
3107 if (parse_flags
& PARSE_FLAG_SPACES
)
3112 /* if not reading from macro substituted string, then try
3113 to substitute macros */
3114 if (tok
>= TOK_IDENT
&&
3115 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3116 s
= define_find(tok
);
3118 /* we have a macro: we try to substitute */
3122 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
3123 /* substitution done, NOTE: maybe empty */
3124 tok_str_add(&str
, 0);
3125 macro_ptr
= str
.str
;
3126 macro_ptr_allocated
= str
.str
;
3133 /* end of macro or end of unget buffer */
3134 if (unget_buffer_enabled
) {
3135 macro_ptr
= unget_saved_macro_ptr
;
3136 unget_buffer_enabled
= 0;
3138 /* end of macro string: free it */
3139 tok_str_free(macro_ptr_allocated
);
3140 macro_ptr_allocated
= NULL
;
3144 } else if (tok
== TOK_NOSUBST
) {
3145 /* discard preprocessor's nosubst markers */
3150 /* convert preprocessor tokens into C tokens */
3151 if (tok
== TOK_PPNUM
&&
3152 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
3153 parse_number((char *)tokc
.cstr
->data
);
3157 /* push back current token and set current token to 'last_tok'. Only
3158 identifier case handled for labels. */
3159 ST_INLN
void unget_tok(int last_tok
)
3163 if (unget_buffer_enabled
)
3165 /* assert(macro_ptr == unget_saved_buffer + 1);
3166 assert(*macro_ptr == 0); */
3170 unget_saved_macro_ptr
= macro_ptr
;
3171 unget_buffer_enabled
= 1;
3173 q
= unget_saved_buffer
;
3176 n
= tok_ext_size(tok
) - 1;
3179 *q
= 0; /* end of token string */
3184 /* better than nothing, but needs extension to handle '-E' option
3186 ST_FUNC
void preprocess_init(TCCState
*s1
)
3188 s1
->include_stack_ptr
= s1
->include_stack
;
3189 /* XXX: move that before to avoid having to initialize
3190 file->ifdef_stack_ptr ? */
3191 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3192 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3195 s1
->pack_stack
[0] = 0;
3196 s1
->pack_stack_ptr
= s1
->pack_stack
;
3199 ST_FUNC
void preprocess_new(void)
3204 /* init isid table */
3205 for(i
=CH_EOF
;i
<256;i
++)
3206 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
3208 /* add all tokens */
3210 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3212 tok_ident
= TOK_IDENT
;
3221 tok_alloc(p
, r
- p
- 1);
3226 /* Preprocess the current file */
3227 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3231 BufferedFile
*file_ref
, **iptr
, **iptr_new
;
3232 int token_seen
, line_ref
, d
;
3235 preprocess_init(s1
);
3236 define_start
= define_stack
;
3237 ch
= file
->buf_ptr
[0];
3238 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3239 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
3240 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
);