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
= NULL
;
238 ts
->sym_label
= NULL
;
239 ts
->sym_struct
= NULL
;
240 ts
->sym_identifier
= NULL
;
242 ts
->hash_next
= NULL
;
243 memcpy(ts
->str
, str
, len
);
249 #define TOK_HASH_INIT 1
250 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
252 /* find a token and add it if not found */
253 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
261 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
262 h
&= (TOK_HASH_SIZE
- 1);
264 pts
= &hash_ident
[h
];
269 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
271 pts
= &(ts
->hash_next
);
273 return tok_alloc_new(pts
, str
, len
);
276 /* XXX: buffer overflow */
277 /* XXX: float tokens */
278 ST_FUNC
char *get_tok_str(int v
, CValue
*cv
)
280 static char buf
[STRING_MAX_SIZE
+ 1];
281 static CString cstr_buf
;
286 /* NOTE: to go faster, we give a fixed buffer for small strings */
287 cstr_reset(&cstr_buf
);
289 cstr_buf
.size_allocated
= sizeof(buf
);
292 /* just an explanation, should never happen:
293 if (v <= TOK_LINENUM && v >= TOK_CINT && cv == NULL)
294 tcc_error("internal error: get_tok_str"); */
299 /* XXX: not quite exact, but only useful for testing */
300 sprintf(p
, "%u", cv
->ui
);
304 /* XXX: not quite exact, but only useful for testing */
306 sprintf(p
, "%u", (unsigned)cv
->ull
);
308 sprintf(p
, "%llu", cv
->ull
);
312 cstr_ccat(&cstr_buf
, 'L');
314 cstr_ccat(&cstr_buf
, '\'');
315 add_char(&cstr_buf
, cv
->i
);
316 cstr_ccat(&cstr_buf
, '\'');
317 cstr_ccat(&cstr_buf
, '\0');
321 len
= cstr
->size
- 1;
323 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
324 cstr_ccat(&cstr_buf
, '\0');
327 cstr_ccat(&cstr_buf
, 'L');
330 cstr_ccat(&cstr_buf
, '\"');
332 len
= cstr
->size
- 1;
334 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
336 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
338 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
340 cstr_ccat(&cstr_buf
, '\"');
341 cstr_ccat(&cstr_buf
, '\0');
348 return NULL
; /* should not happen */
350 /* above tokens have value, the ones below don't */
359 return strcpy(p
, "...");
361 return strcpy(p
, "<<=");
363 return strcpy(p
, ">>=");
366 /* search in two bytes table */
367 const unsigned char *q
= tok_two_chars
;
380 } else if (v
< tok_ident
) {
381 return table_ident
[v
- TOK_IDENT
]->str
;
382 } else if (v
>= SYM_FIRST_ANOM
) {
383 /* special name for anonymous symbol */
384 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
386 /* should never happen */
391 return cstr_buf
.data
;
394 /* fill input buffer and peek next char */
395 static int tcc_peekc_slow(BufferedFile
*bf
)
398 /* only tries to read if really end of buffer */
399 if (bf
->buf_ptr
>= bf
->buf_end
) {
401 #if defined(PARSE_DEBUG)
406 len
= read(bf
->fd
, bf
->buffer
, len
);
413 bf
->buf_ptr
= bf
->buffer
;
414 bf
->buf_end
= bf
->buffer
+ len
;
415 *bf
->buf_end
= CH_EOB
;
417 if (bf
->buf_ptr
< bf
->buf_end
) {
418 return bf
->buf_ptr
[0];
420 bf
->buf_ptr
= bf
->buf_end
;
425 /* return the current character, handling end of block if necessary
427 ST_FUNC
int handle_eob(void)
429 return tcc_peekc_slow(file
);
432 /* read next char from current input file and handle end of input buffer */
433 ST_INLN
void inp(void)
435 ch
= *(++(file
->buf_ptr
));
436 /* end of buffer/file handling */
441 /* handle '\[\r]\n' */
442 static int handle_stray_noerror(void)
449 } else if (ch
== '\r') {
463 static void handle_stray(void)
465 if (handle_stray_noerror())
466 tcc_error("stray '\\' in program");
469 /* skip the stray and handle the \\n case. Output an error if
470 incorrect char after the stray */
471 static int handle_stray1(uint8_t *p
)
475 if (p
>= file
->buf_end
) {
492 /* handle just the EOB case, but not stray */
493 #define PEEKC_EOB(c, p)\
504 /* handle the complicated stray case */
510 c = handle_stray1(p);\
515 /* input with '\[\r]\n' handling. Note that this function cannot
516 handle other characters after '\', so you cannot call it inside
517 strings or comments */
518 ST_FUNC
void minp(void)
526 /* single line C++ comments */
527 static uint8_t *parse_line_comment(uint8_t *p
)
535 if (c
== '\n' || c
== CH_EOF
) {
537 } else if (c
== '\\') {
546 } else if (c
== '\r') {
564 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
573 if (c
== '\n' || c
== '*' || c
== '\\')
577 if (c
== '\n' || c
== '*' || c
== '\\')
581 /* now we can handle all the cases */
585 } else if (c
== '*') {
591 } else if (c
== '/') {
593 } else if (c
== '\\') {
598 /* skip '\[\r]\n', otherwise just skip the stray */
604 } else if (c
== '\r') {
621 /* stray, eob or eof */
626 tcc_error("unexpected end of file in comment");
627 } else if (c
== '\\') {
639 static inline void skip_spaces(void)
645 static inline int check_space(int t
, int *spc
)
656 /* parse a string without interpreting escapes */
657 static uint8_t *parse_pp_string(uint8_t *p
,
658 int sep
, CString
*str
)
666 } else if (c
== '\\') {
672 /* XXX: indicate line number of start of string */
673 tcc_error("missing terminating %c character", sep
);
674 } else if (c
== '\\') {
675 /* escape : just skip \[\r]\n */
680 } else if (c
== '\r') {
683 expect("'\n' after '\r'");
686 } else if (c
== CH_EOF
) {
687 goto unterminated_string
;
690 cstr_ccat(str
, '\\');
696 } else if (c
== '\n') {
699 } else if (c
== '\r') {
703 cstr_ccat(str
, '\r');
719 /* skip block of text until #else, #elif or #endif. skip also pairs of
721 static void preprocess_skip(void)
723 int a
, start_of_line
, c
, in_warn_or_error
;
730 in_warn_or_error
= 0;
751 } else if (c
== '\\') {
752 ch
= file
->buf_ptr
[0];
753 handle_stray_noerror();
760 if (in_warn_or_error
)
762 p
= parse_pp_string(p
, c
, NULL
);
766 if (in_warn_or_error
)
773 p
= parse_comment(p
);
774 } else if (ch
== '/') {
775 p
= parse_line_comment(p
);
785 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
787 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
789 else if (tok
== TOK_ENDIF
)
791 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
792 in_warn_or_error
= 1;
793 else if (tok
== TOK_LINEFEED
)
808 /* ParseState handling */
810 /* XXX: currently, no include file info is stored. Thus, we cannot display
811 accurate messages if the function or data definition spans multiple
814 /* save current parse state in 's' */
815 ST_FUNC
void save_parse_state(ParseState
*s
)
817 s
->line_num
= file
->line_num
;
818 s
->macro_ptr
= macro_ptr
;
823 /* restore parse state from 's' */
824 ST_FUNC
void restore_parse_state(ParseState
*s
)
826 file
->line_num
= s
->line_num
;
827 macro_ptr
= s
->macro_ptr
;
832 /* return the number of additional 'ints' necessary to store the
834 static inline int tok_ext_size(int t
)
848 tcc_error("unsupported token");
855 return LDOUBLE_SIZE
/ 4;
861 /* token string handling */
863 ST_INLN
void tok_str_new(TokenString
*s
)
867 s
->allocated_len
= 0;
868 s
->last_line_num
= -1;
871 ST_FUNC
void tok_str_free(int *str
)
876 static int *tok_str_realloc(TokenString
*s
)
880 if (s
->allocated_len
== 0) {
883 len
= s
->allocated_len
* 2;
885 str
= tcc_realloc(s
->str
, len
* sizeof(int));
886 s
->allocated_len
= len
;
891 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
897 if (len
>= s
->allocated_len
)
898 str
= tok_str_realloc(s
);
903 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
910 /* allocate space for worst case */
911 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
912 str
= tok_str_realloc(s
);
921 str
[len
++] = cv
->tab
[0];
930 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
931 while ((len
+ nb_words
) > s
->allocated_len
)
932 str
= tok_str_realloc(s
);
933 cstr
= (CString
*)(str
+ len
);
935 cstr
->size
= cv
->cstr
->size
;
936 cstr
->data_allocated
= NULL
;
937 cstr
->size_allocated
= cstr
->size
;
938 memcpy((char *)cstr
+ sizeof(CString
),
939 cv
->cstr
->data
, cstr
->size
);
946 #if LDOUBLE_SIZE == 8
949 str
[len
++] = cv
->tab
[0];
950 str
[len
++] = cv
->tab
[1];
952 #if LDOUBLE_SIZE == 12
954 str
[len
++] = cv
->tab
[0];
955 str
[len
++] = cv
->tab
[1];
956 str
[len
++] = cv
->tab
[2];
957 #elif LDOUBLE_SIZE == 16
959 str
[len
++] = cv
->tab
[0];
960 str
[len
++] = cv
->tab
[1];
961 str
[len
++] = cv
->tab
[2];
962 str
[len
++] = cv
->tab
[3];
963 #elif LDOUBLE_SIZE != 8
964 #error add long double size support
973 /* add the current parse token in token string 's' */
974 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
978 /* save line number info */
979 if (file
->line_num
!= s
->last_line_num
) {
980 s
->last_line_num
= file
->line_num
;
981 cval
.i
= s
->last_line_num
;
982 tok_str_add2(s
, TOK_LINENUM
, &cval
);
984 tok_str_add2(s
, tok
, &tokc
);
987 /* get a token from an integer array and increment pointer
988 accordingly. we code it as a macro to avoid pointer aliasing. */
989 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1007 cv
->cstr
= (CString
*)p
;
1008 cv
->cstr
->data
= (char *)p
+ sizeof(CString
);
1009 p
+= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
1017 #if LDOUBLE_SIZE == 16
1019 #elif LDOUBLE_SIZE == 12
1021 #elif LDOUBLE_SIZE == 8
1024 # error add long double size support
1037 static int macro_is_equal(const int *a
, const int *b
)
1039 char buf
[STRING_MAX_SIZE
+ 1];
1043 TOK_GET(&t
, &a
, &cv
);
1044 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1045 TOK_GET(&t
, &b
, &cv
);
1046 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1052 static void define_print(Sym
*s
, int is_undef
)
1059 if (tcc_state
->dflag
== 0 || !s
|| !tcc_state
->ppfp
)
1063 c
= file
->line_num
- file
->line_ref
- 1;
1066 fputs("\n", tcc_state
->ppfp
);
1067 file
->line_ref
= file
->line_num
;
1072 fprintf(tcc_state
->ppfp
, "// #undef %s\n", get_tok_str(s
->v
, NULL
));
1076 fprintf(tcc_state
->ppfp
, "// #define %s", get_tok_str(s
->v
, NULL
));
1081 fprintf(tcc_state
->ppfp
, "%s%s", sep
, get_tok_str(arg
->v
& ~SYM_FIELD
, NULL
));
1085 fprintf(tcc_state
->ppfp
, ")");
1090 fprintf(tcc_state
->ppfp
, " ");
1093 TOK_GET(&t
, &str
, &cval
);
1096 fprintf(tcc_state
->ppfp
, "%s", get_tok_str(t
, &cval
));
1098 fprintf(tcc_state
->ppfp
, "\n");
1101 /* defines handling */
1102 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1107 if (s
&& !macro_is_equal(s
->d
, str
))
1108 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1110 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1112 s
->next
= first_arg
;
1113 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1117 /* undefined a define symbol. Its name is just set to zero */
1118 ST_FUNC
void define_undef(Sym
*s
)
1122 if (v
>= TOK_IDENT
&& v
< tok_ident
) {
1124 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1129 ST_INLN Sym
*define_find(int v
)
1132 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1134 return table_ident
[v
]->sym_define
;
1137 /* free define stack until top reaches 'b' */
1138 ST_FUNC
void free_defines(Sym
*b
)
1146 /* do not free args or predefined defines */
1148 tok_str_free(top
->d
);
1150 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1151 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1158 void print_defines(void)
1166 if (v
>= TOK_IDENT
&& v
< tok_ident
) {
1167 s
= table_ident
[v
- TOK_IDENT
]->sym_define
;
1175 ST_FUNC Sym
*label_find(int v
)
1178 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1180 return table_ident
[v
]->sym_label
;
1183 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1186 s
= sym_push2(ptop
, v
, 0, 0);
1188 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1189 if (ptop
== &global_label_stack
) {
1190 /* modify the top most local identifier, so that
1191 sym_identifier will point to 's' when popped */
1193 ps
= &(*ps
)->prev_tok
;
1200 /* pop labels until element last is reached. Look if any labels are
1201 undefined. Define symbols if '&&label' was used. */
1202 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1205 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1207 if (s
->r
== LABEL_DECLARED
) {
1208 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1209 } else if (s
->r
== LABEL_FORWARD
) {
1210 tcc_error("label '%s' used but not defined",
1211 get_tok_str(s
->v
, NULL
));
1214 /* define corresponding symbol. A size of
1216 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1220 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1226 /* eval an expression for #if/#elif */
1227 static int expr_preprocess(void)
1233 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1234 next(); /* do macro subst */
1235 if (tok
== TOK_DEFINED
) {
1240 c
= define_find(tok
) != 0;
1245 } else if (tok
>= TOK_IDENT
) {
1246 /* if undefined macro */
1250 tok_str_add_tok(&str
);
1252 tok_str_add(&str
, -1); /* simulate end of file */
1253 tok_str_add(&str
, 0);
1254 /* now evaluate C constant expression */
1255 macro_ptr
= str
.str
;
1259 tok_str_free(str
.str
);
1263 /* parse after #define */
1264 ST_FUNC
void parse_define(void)
1266 Sym
*s
, *first
, **ps
;
1267 int v
, t
, varg
, is_vaargs
, spc
, ptok
, macro_list_start
;
1272 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1273 /* XXX: should check if same macro (ANSI) */
1276 /* '(' must be just after macro definition for MACRO_FUNC */
1281 while (tok
!= ')') {
1285 if (varg
== TOK_DOTS
) {
1286 varg
= TOK___VA_ARGS__
;
1288 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1292 if (varg
< TOK_IDENT
)
1293 tcc_error( "\'%s\' may not appear in parameter list", get_tok_str(varg
, NULL
));
1294 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1306 /* EOF testing necessary for '-D' handling */
1308 macro_list_start
= 1;
1309 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1310 if (!macro_list_start
&& spc
== 2 && tok
== TOK_TWOSHARPS
)
1311 tcc_error("'##' invalid at start of macro");
1313 /* remove spaces around ## and after '#' */
1314 if (TOK_TWOSHARPS
== tok
) {
1318 } else if ('#' == tok
) {
1320 } else if (check_space(tok
, &spc
)) {
1323 tok_str_add2(&str
, tok
, &tokc
);
1326 macro_list_start
= 0;
1328 if (ptok
== TOK_TWOSHARPS
)
1329 tcc_error("'##' invalid at end of macro");
1331 --str
.len
; /* remove trailing space */
1332 tok_str_add(&str
, 0);
1333 define_push(v
, t
, str
.str
, first
);
1336 static inline int hash_cached_include(const char *filename
)
1338 const unsigned char *s
;
1342 s
= (unsigned char *) filename
;
1344 h
= TOK_HASH_FUNC(h
, *s
);
1347 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1351 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1355 h
= hash_cached_include(filename
);
1356 i
= s1
->cached_includes_hash
[h
];
1360 e
= s1
->cached_includes
[i
- 1];
1361 if (0 == PATHCMP(e
->filename
, filename
))
1368 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1373 if (search_cached_include(s1
, filename
))
1376 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1378 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1379 strcpy(e
->filename
, filename
);
1380 e
->ifndef_macro
= ifndef_macro
;
1381 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1382 /* add in hash table */
1383 h
= hash_cached_include(filename
);
1384 e
->hash_next
= s1
->cached_includes_hash
[h
];
1385 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1388 static void pragma_parse(TCCState
*s1
)
1393 if (tok
== TOK_pack
) {
1396 #pragma pack(1) // set
1397 #pragma pack() // reset to default
1398 #pragma pack(push,1) // push & set
1399 #pragma pack(pop) // restore previous
1403 if (tok
== TOK_ASM_pop
) {
1405 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1407 tcc_error("out of pack stack");
1409 s1
->pack_stack_ptr
--;
1413 if (tok
== TOK_ASM_push
) {
1415 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1417 s1
->pack_stack_ptr
++;
1420 if (tok
!= TOK_CINT
) {
1422 tcc_error("invalid pack pragma");
1425 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1429 *s1
->pack_stack_ptr
= val
;
1435 /* is_bof is true if first non space token at beginning of file */
1436 ST_FUNC
void preprocess(int is_bof
)
1438 TCCState
*s1
= tcc_state
;
1439 int i
, c
, n
, saved_parse_flags
;
1443 saved_parse_flags
= parse_flags
;
1444 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
1445 PARSE_FLAG_LINEFEED
;
1455 s
= define_find(tok
);
1456 /* undefine symbol by putting an invalid name */
1461 case TOK_INCLUDE_NEXT
:
1462 ch
= file
->buf_ptr
[0];
1463 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1468 } else if (ch
== '\"') {
1473 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1474 if ((q
- buf
) < sizeof(buf
) - 1)
1477 if (handle_stray_noerror() == 0)
1485 /* eat all spaces and comments after include */
1486 /* XXX: slightly incorrect */
1487 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1491 /* computed #include : either we have only strings or
1492 we have anything enclosed in '<>' */
1495 if (tok
== TOK_STR
) {
1496 while (tok
!= TOK_LINEFEED
) {
1497 if (tok
!= TOK_STR
) {
1499 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1501 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1507 while (tok
!= TOK_LINEFEED
) {
1508 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1512 /* check syntax and remove '<>' */
1513 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1514 goto include_syntax
;
1515 memmove(buf
, buf
+ 1, len
- 2);
1516 buf
[len
- 2] = '\0';
1521 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1522 tcc_error("#include recursion too deep");
1523 /* store current file in stack, but increment stack later below */
1524 *s1
->include_stack_ptr
= file
;
1526 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1527 for (i
= -2; i
< n
; ++i
) {
1528 char buf1
[sizeof file
->filename
];
1534 /* check absolute include path */
1535 if (!IS_ABSPATH(buf
))
1538 i
= n
; /* force end loop */
1540 } else if (i
== -1) {
1541 /* search in current dir if "header.h" */
1544 path
= file
->filename
;
1545 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1548 /* search in all the include paths */
1549 if (i
< s1
->nb_include_paths
)
1550 path
= s1
->include_paths
[i
];
1552 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1553 pstrcpy(buf1
, sizeof(buf1
), path
);
1554 pstrcat(buf1
, sizeof(buf1
), "/");
1557 pstrcat(buf1
, sizeof(buf1
), buf
);
1559 if (tok
== TOK_INCLUDE_NEXT
)
1560 for (f
= s1
->include_stack_ptr
; f
>= s1
->include_stack
; --f
)
1561 if (0 == PATHCMP((*f
)->filename
, buf1
)) {
1563 printf("%s: #include_next skipping %s\n", file
->filename
, buf1
);
1565 goto include_trynext
;
1568 e
= search_cached_include(s1
, buf1
);
1569 if (e
&& define_find(e
->ifndef_macro
)) {
1570 /* no need to parse the include because the 'ifndef macro'
1573 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1578 if (tcc_open(s1
, buf1
) < 0)
1583 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1585 /* update target deps */
1586 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1588 /* push current file in stack */
1589 ++s1
->include_stack_ptr
;
1590 /* add include file debug info */
1592 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1593 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1594 ch
= file
->buf_ptr
[0];
1597 tcc_error("include file '%s' not found", buf
);
1604 c
= expr_preprocess();
1610 if (tok
< TOK_IDENT
)
1611 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1615 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1617 file
->ifndef_macro
= tok
;
1620 c
= (define_find(tok
) != 0) ^ c
;
1622 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1623 tcc_error("memory full (ifdef)");
1624 *s1
->ifdef_stack_ptr
++ = c
;
1627 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1628 tcc_error("#else without matching #if");
1629 if (s1
->ifdef_stack_ptr
[-1] & 2)
1630 tcc_error("#else after #else");
1631 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1634 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1635 tcc_error("#elif without matching #if");
1636 c
= s1
->ifdef_stack_ptr
[-1];
1638 tcc_error("#elif after #else");
1639 /* last #if/#elif expression was true: we skip */
1642 c
= expr_preprocess();
1643 s1
->ifdef_stack_ptr
[-1] = c
;
1645 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1646 file
->ifndef_macro
= 0;
1656 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1657 tcc_error("#endif without matching #if");
1658 s1
->ifdef_stack_ptr
--;
1659 /* '#ifndef macro' was at the start of file. Now we check if
1660 an '#endif' is exactly at the end of file */
1661 if (file
->ifndef_macro
&&
1662 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1663 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1664 /* need to set to zero to avoid false matches if another
1665 #ifndef at middle of file */
1666 file
->ifndef_macro
= 0;
1667 while (tok
!= TOK_LINEFEED
)
1669 tok_flags
|= TOK_FLAG_ENDIF
;
1675 if (tok
!= TOK_CINT
)
1676 tcc_error("A #line format is wrong");
1678 if (tok
!= TOK_CINT
) {
1679 char *p
= tokc
.cstr
->data
;
1680 tokc
.i
= strtoul(p
, (char **)&p
, 10);
1682 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
1684 if (tok
!= TOK_LINEFEED
) {
1687 pstrcpy(file
->filename
, sizeof(file
->filename
),
1688 (char *)tokc
.cstr
->data
);
1691 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1696 ch
= file
->buf_ptr
[0];
1699 while (ch
!= '\n' && ch
!= CH_EOF
) {
1700 if ((q
- buf
) < sizeof(buf
) - 1)
1703 if (handle_stray_noerror() == 0)
1710 tcc_error("#error %s", buf
);
1712 tcc_warning("#warning %s", buf
);
1718 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_PPNUM
) {
1719 /* '!' is ignored to allow C scripts. numbers are ignored
1720 to emulate cpp behaviour */
1722 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
1723 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1725 /* this is a gas line comment in an 'S' file. */
1726 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1732 /* ignore other preprocess commands or #! for C scripts */
1733 while (tok
!= TOK_LINEFEED
)
1736 parse_flags
= saved_parse_flags
;
1739 /* evaluate escape codes in a string. */
1740 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1755 case '0': case '1': case '2': case '3':
1756 case '4': case '5': case '6': case '7':
1757 /* at most three octal digits */
1762 n
= n
* 8 + c
- '0';
1766 n
= n
* 8 + c
- '0';
1771 goto add_char_nonext
;
1779 if (c
>= 'a' && c
<= 'f')
1781 else if (c
>= 'A' && c
<= 'F')
1791 goto add_char_nonext
;
1815 goto invalid_escape
;
1825 if (c
>= '!' && c
<= '~')
1826 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1828 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1835 cstr_ccat(outstr
, c
);
1837 cstr_wccat(outstr
, c
);
1839 /* add a trailing '\0' */
1841 cstr_ccat(outstr
, '\0');
1843 cstr_wccat(outstr
, '\0');
1846 /* we use 64 bit numbers */
1849 /* bn = (bn << shift) | or_val */
1850 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
1854 for(i
=0;i
<BN_SIZE
;i
++) {
1856 bn
[i
] = (v
<< shift
) | or_val
;
1857 or_val
= v
>> (32 - shift
);
1861 static void bn_zero(unsigned int *bn
)
1864 for(i
=0;i
<BN_SIZE
;i
++) {
1869 /* parse number in null terminated string 'p' and return it in the
1871 static void parse_number(const char *p
)
1873 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
1875 unsigned int bn
[BN_SIZE
];
1886 goto float_frac_parse
;
1887 } else if (t
== '0') {
1888 if (ch
== 'x' || ch
== 'X') {
1892 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
1898 /* parse all digits. cannot check octal numbers at this stage
1899 because of floating point constants */
1901 if (ch
>= 'a' && ch
<= 'f')
1903 else if (ch
>= 'A' && ch
<= 'F')
1911 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
1913 tcc_error("number too long");
1919 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
1920 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
1922 /* NOTE: strtox should support that for hexa numbers, but
1923 non ISOC99 libcs do not support it, so we prefer to do
1925 /* hexadecimal or binary floats */
1926 /* XXX: handle overflows */
1938 } else if (t
>= 'a') {
1940 } else if (t
>= 'A') {
1945 bn_lshift(bn
, shift
, t
);
1952 if (t
>= 'a' && t
<= 'f') {
1954 } else if (t
>= 'A' && t
<= 'F') {
1956 } else if (t
>= '0' && t
<= '9') {
1962 tcc_error("invalid digit");
1963 bn_lshift(bn
, shift
, t
);
1968 if (ch
!= 'p' && ch
!= 'P')
1975 } else if (ch
== '-') {
1979 if (ch
< '0' || ch
> '9')
1980 expect("exponent digits");
1981 while (ch
>= '0' && ch
<= '9') {
1982 exp_val
= exp_val
* 10 + ch
- '0';
1985 exp_val
= exp_val
* s
;
1987 /* now we can generate the number */
1988 /* XXX: should patch directly float number */
1989 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
1990 d
= ldexp(d
, exp_val
- frac_bits
);
1995 /* float : should handle overflow */
1997 } else if (t
== 'L') {
1999 #ifdef TCC_TARGET_PE
2004 /* XXX: not large enough */
2005 tokc
.ld
= (long double)d
;
2012 /* decimal floats */
2014 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2019 while (ch
>= '0' && ch
<= '9') {
2020 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2026 if (ch
== 'e' || ch
== 'E') {
2027 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2031 if (ch
== '-' || ch
== '+') {
2032 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2037 if (ch
< '0' || ch
> '9')
2038 expect("exponent digits");
2039 while (ch
>= '0' && ch
<= '9') {
2040 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2052 tokc
.f
= strtof(token_buf
, NULL
);
2053 } else if (t
== 'L') {
2055 #ifdef TCC_TARGET_PE
2057 tokc
.d
= strtod(token_buf
, NULL
);
2060 tokc
.ld
= strtold(token_buf
, NULL
);
2064 tokc
.d
= strtod(token_buf
, NULL
);
2068 unsigned long long n
, n1
;
2069 int lcount
, ucount
, must_64bit
;
2072 /* integer number */
2075 if (b
== 10 && *q
== '0') {
2082 /* no need for checks except for base 10 / 8 errors */
2092 tcc_error("invalid digit");
2095 /* detect overflow */
2096 /* XXX: this test is not reliable */
2098 tcc_error("integer constant overflow");
2101 /* Determine the characteristics (unsigned and/or 64bit) the type of
2102 the constant must have according to the constant suffix(es) */
2103 lcount
= ucount
= must_64bit
= 0;
2109 tcc_error("three 'l's in integer constant");
2110 if (lcount
&& *(p
- 1) != ch
)
2111 tcc_error("incorrect integer suffix: %s", p1
);
2113 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2118 } else if (t
== 'U') {
2120 tcc_error("two 'u's in integer constant");
2128 /* Whether 64 bits are needed to hold the constant's value */
2129 if (n
& 0xffffffff00000000LL
|| must_64bit
) {
2137 /* Whether type must be unsigned to hold the constant's value */
2138 if (ucount
|| ((n1
>> 31) && (b
!= 10))) {
2139 if (tok
== TOK_CLLONG
)
2143 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2144 } else if (n1
>> 31) {
2145 if (tok
== TOK_CINT
)
2148 tcc_error("integer constant overflow");
2151 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2157 tcc_error("invalid number\n");
2161 #define PARSE2(c1, tok1, c2, tok2) \
2172 /* return next token without macro substitution */
2173 static inline void next_nomacro1(void)
2188 goto keep_tok_flags
;
2195 /* first look if it is in fact an end of buffer */
2196 if (p
>= file
->buf_end
) {
2200 if (p
>= file
->buf_end
)
2213 TCCState
*s1
= tcc_state
;
2214 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2215 && !(tok_flags
& TOK_FLAG_EOF
)) {
2216 tok_flags
|= TOK_FLAG_EOF
;
2218 goto keep_tok_flags
;
2219 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2221 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2222 tcc_error("missing #endif");
2223 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2224 /* no include left : end of file. */
2227 tok_flags
&= ~TOK_FLAG_EOF
;
2228 /* pop include file */
2230 /* test if previous '#endif' was after a #ifdef at
2232 if (tok_flags
& TOK_FLAG_ENDIF
) {
2234 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2236 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2237 tok_flags
&= ~TOK_FLAG_ENDIF
;
2240 /* add end of include file debug info */
2241 if (tcc_state
->do_debug
) {
2242 put_stabd(N_EINCL
, 0, 0);
2244 /* pop include stack */
2246 s1
->include_stack_ptr
--;
2255 tok_flags
|= TOK_FLAG_BOL
;
2258 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2261 goto keep_tok_flags
;
2266 if ((tok_flags
& TOK_FLAG_BOL
) &&
2267 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2269 preprocess(tok_flags
& TOK_FLAG_BOF
);
2275 tok
= TOK_TWOSHARPS
;
2277 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
2278 p
= parse_line_comment(p
- 1);
2287 case 'a': case 'b': case 'c': case 'd':
2288 case 'e': case 'f': case 'g': case 'h':
2289 case 'i': case 'j': case 'k': case 'l':
2290 case 'm': case 'n': case 'o': case 'p':
2291 case 'q': case 'r': case 's': case 't':
2292 case 'u': case 'v': case 'w': case 'x':
2294 case 'A': case 'B': case 'C': case 'D':
2295 case 'E': case 'F': case 'G': case 'H':
2296 case 'I': case 'J': case 'K':
2297 case 'M': case 'N': case 'O': case 'P':
2298 case 'Q': case 'R': case 'S': case 'T':
2299 case 'U': case 'V': case 'W': case 'X':
2305 h
= TOK_HASH_FUNC(h
, c
);
2309 if (!isidnum_table
[c
-CH_EOF
])
2311 h
= TOK_HASH_FUNC(h
, c
);
2318 /* fast case : no stray found, so we have the full token
2319 and we have already hashed it */
2321 h
&= (TOK_HASH_SIZE
- 1);
2322 pts
= &hash_ident
[h
];
2327 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2329 pts
= &(ts
->hash_next
);
2331 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2335 cstr_reset(&tokcstr
);
2338 cstr_ccat(&tokcstr
, *p1
);
2344 while (isidnum_table
[c
-CH_EOF
]) {
2345 cstr_ccat(&tokcstr
, c
);
2348 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2354 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2356 goto parse_ident_fast
;
2359 if (c
== '\'' || c
== '\"') {
2363 cstr_reset(&tokcstr
);
2364 cstr_ccat(&tokcstr
, 'L');
2365 goto parse_ident_slow
;
2369 case '0': case '1': case '2': case '3':
2370 case '4': case '5': case '6': case '7':
2373 cstr_reset(&tokcstr
);
2374 /* after the first digit, accept digits, alpha, '.' or sign if
2375 prefixed by 'eEpP' */
2379 cstr_ccat(&tokcstr
, c
);
2381 if (!(isnum(c
) || isid(c
) || c
== '.' ||
2382 ((c
== '+' || c
== '-') &&
2383 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
2386 /* We add a trailing '\0' to ease parsing */
2387 cstr_ccat(&tokcstr
, '\0');
2388 tokc
.cstr
= &tokcstr
;
2392 /* special dot handling because it can also start a number */
2395 cstr_reset(&tokcstr
);
2396 cstr_ccat(&tokcstr
, '.');
2398 } else if (c
== '.') {
2418 /* parse the string */
2420 p
= parse_pp_string(p
, sep
, &str
);
2421 cstr_ccat(&str
, '\0');
2423 /* eval the escape (should be done as TOK_PPNUM) */
2424 cstr_reset(&tokcstr
);
2425 parse_escape_string(&tokcstr
, str
.data
, is_long
);
2430 /* XXX: make it portable */
2434 char_size
= sizeof(nwchar_t
);
2435 if (tokcstr
.size
<= char_size
)
2436 tcc_error("empty character constant");
2437 if (tokcstr
.size
> 2 * char_size
)
2438 tcc_warning("multi-character character constant");
2440 tokc
.i
= *(int8_t *)tokcstr
.data
;
2443 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2447 tokc
.cstr
= &tokcstr
;
2461 } else if (c
== '<') {
2479 } else if (c
== '>') {
2497 } else if (c
== '=') {
2510 } else if (c
== '=') {
2523 } else if (c
== '=') {
2536 } else if (c
== '=') {
2539 } else if (c
== '>') {
2547 PARSE2('!', '!', '=', TOK_NE
)
2548 PARSE2('=', '=', '=', TOK_EQ
)
2549 PARSE2('*', '*', '=', TOK_A_MUL
)
2550 PARSE2('%', '%', '=', TOK_A_MOD
)
2551 PARSE2('^', '^', '=', TOK_A_XOR
)
2553 /* comments or operator */
2557 p
= parse_comment(p
);
2558 /* comments replaced by a blank */
2560 goto keep_tok_flags
;
2561 } else if (c
== '/') {
2562 p
= parse_line_comment(p
);
2564 goto keep_tok_flags
;
2565 } else if (c
== '=') {
2585 case '$': /* only used in assembler */
2586 case '@': /* dito */
2591 tcc_error("unrecognized character \\x%02x", c
);
2597 #if defined(PARSE_DEBUG)
2598 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2602 /* return next token without macro substitution. Can read input from
2604 static void next_nomacro_spc(void)
2610 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2611 if (tok
== TOK_LINENUM
) {
2612 file
->line_num
= tokc
.i
;
2621 ST_FUNC
void next_nomacro(void)
2625 } while (is_space(tok
));
2628 /* substitute arguments in replacement lists in macro_str by the values in
2629 args (field d) and return allocated string */
2630 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2632 int last_tok
, t
, spc
;
2642 TOK_GET(&t
, ¯o_str
, &cval
);
2647 TOK_GET(&t
, ¯o_str
, &cval
);
2650 s
= sym_find2(args
, t
);
2656 TOK_GET(&t
, &st
, &cval
);
2657 if (!check_space(t
, &spc
))
2658 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2661 cstr_ccat(&cstr
, '\0');
2663 printf("stringize: %s\n", (char *)cstr
.data
);
2667 tok_str_add2(&str
, TOK_STR
, &cval
);
2670 tok_str_add2(&str
, t
, &cval
);
2672 } else if (t
>= TOK_IDENT
) {
2673 s
= sym_find2(args
, t
);
2676 /* if '##' is present before or after, no arg substitution */
2677 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
2678 /* special case for var arg macros : ## eats the
2679 ',' if empty VA_ARGS variable. */
2680 /* XXX: test of the ',' is not 100%
2681 reliable. should fix it to avoid security
2683 if (gnu_ext
&& s
->type
.t
&&
2684 last_tok
== TOK_TWOSHARPS
&&
2685 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
2686 if (*st
== TOK_PLCHLDR
) {
2687 /* suppress ',' '##' */
2690 /* suppress '##' and add variable */
2698 TOK_GET(&t1
, &st
, &cval
);
2701 tok_str_add2(&str
, t1
, &cval
);
2704 } else if (*st
!= TOK_PLCHLDR
) {
2705 /* NOTE: the stream cannot be read when macro
2706 substituing an argument */
2707 macro_subst(&str
, nested_list
, st
, NULL
);
2710 tok_str_add(&str
, t
);
2713 tok_str_add2(&str
, t
, &cval
);
2717 tok_str_add(&str
, 0);
2721 static char const ab_month_name
[12][4] =
2723 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2724 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2727 /* do macro substitution of current token with macro 's' and add
2728 result to (tok_str,tok_len). 'nested_list' is the list of all
2729 macros we got inside to avoid recursing. Return non zero if no
2730 substitution needs to be done */
2731 static int macro_subst_tok(TokenString
*tok_str
,
2732 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
2734 Sym
*args
, *sa
, *sa1
;
2735 int mstr_allocated
, parlevel
, *mstr
, t
, t1
, spc
;
2743 /* if symbol is a macro, prepare substitution */
2744 /* special macros */
2745 if (tok
== TOK___LINE__
) {
2746 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2750 } else if (tok
== TOK___FILE__
) {
2751 cstrval
= file
->filename
;
2753 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2758 tm
= localtime(&ti
);
2759 if (tok
== TOK___DATE__
) {
2760 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2761 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2763 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2764 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2771 cstr_cat(&cstr
, cstrval
);
2772 cstr_ccat(&cstr
, '\0');
2774 tok_str_add2(tok_str
, t1
, &cval
);
2779 if (s
->type
.t
== MACRO_FUNC
) {
2780 /* NOTE: we do not use next_nomacro to avoid eating the
2781 next token. XXX: find better solution */
2785 while (is_space(t
= *p
) || TOK_LINEFEED
== t
)
2787 if (t
== 0 && can_read_stream
) {
2788 /* end of macro stream: we must look at the token
2789 after in the file */
2790 struct macro_level
*ml
= *can_read_stream
;
2796 *can_read_stream
= ml
-> prev
;
2798 /* also, end of scope for nested defined symbol */
2799 (*nested_list
)->v
= -1;
2803 ch
= file
->buf_ptr
[0];
2804 while (is_space(ch
) || ch
== '\n' || ch
== '/')
2809 uint8_t *p
= file
->buf_ptr
;
2812 p
= parse_comment(p
);
2813 file
->buf_ptr
= p
- 1;
2814 } else if (c
== '/') {
2815 p
= parse_line_comment(p
);
2816 file
->buf_ptr
= p
- 1;
2824 if (t
!= '(') /* no macro subst */
2827 /* argument macro */
2832 /* NOTE: empty args are allowed, except if no args */
2834 /* handle '()' case */
2835 if (!args
&& !sa
&& tok
== ')')
2838 tcc_error("macro '%s' used with too many args",
2839 get_tok_str(s
->v
, 0));
2842 /* NOTE: non zero sa->t indicates VA_ARGS */
2843 while ((parlevel
> 0 ||
2845 (tok
!= ',' || sa
->type
.t
))) &&
2849 else if (tok
== ')')
2851 if (tok
== TOK_LINEFEED
)
2853 if (!check_space(tok
, &spc
))
2854 tok_str_add2(&str
, tok
, &tokc
);
2858 tok_str_add(&str
, TOK_PLCHLDR
);
2860 tok_str_add(&str
, 0);
2861 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
2865 /* special case for gcc var args: add an empty
2866 var arg argument if it is omitted */
2867 if (sa
&& sa
->type
.t
&& gnu_ext
)
2877 tcc_error("macro '%s' used with too few args",
2878 get_tok_str(s
->v
, 0));
2881 /* now subst each arg */
2882 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
2887 tok_str_free(sa
->d
);
2893 sym_push2(nested_list
, s
->v
, 0, 0);
2894 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
2895 /* pop nested defined symbol */
2897 *nested_list
= sa1
->prev
;
2905 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2906 return the resulting string (which must be freed). */
2907 static inline int *macro_twosharps(const int *macro_str
)
2911 TokenString macro_str1
;
2913 int n
, start_of_nosubsts
;
2915 /* we search the first '##' */
2916 for(ptr
= macro_str
;;) {
2918 TOK_GET(&t
, &ptr
, &cval
);
2919 if (t
== TOK_TWOSHARPS
)
2921 /* nothing more to do if end of string */
2926 /* we saw '##', so we need more processing to handle it */
2927 start_of_nosubsts
= -1;
2928 tok_str_new(¯o_str1
);
2929 for(ptr
= macro_str
;;) {
2930 TOK_GET(&tok
, &ptr
, &tokc
);
2933 if (tok
== TOK_TWOSHARPS
)
2935 if (tok
== TOK_NOSUBST
&& start_of_nosubsts
< 0)
2936 start_of_nosubsts
= macro_str1
.len
;
2937 while (*ptr
== TOK_TWOSHARPS
) {
2938 /* given 'a##b', remove nosubsts preceding 'a' */
2939 if (start_of_nosubsts
>= 0)
2940 macro_str1
.len
= start_of_nosubsts
;
2941 /* given 'a##b', skip '##' */
2943 /* given 'a##b', remove nosubsts preceding 'b' */
2944 while (t
== TOK_NOSUBST
)
2946 if (t
&& t
!= TOK_TWOSHARPS
) {
2948 TOK_GET(&t
, &ptr
, &cval
);
2949 /* We concatenate the two tokens */
2951 if (tok
!= TOK_PLCHLDR
)
2952 cstr_cat(&cstr
, get_tok_str(tok
, &tokc
));
2954 if (t
!= TOK_PLCHLDR
|| tok
== TOK_PLCHLDR
)
2955 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2956 cstr_ccat(&cstr
, '\0');
2958 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
2959 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
2962 if (0 == *file
->buf_ptr
)
2964 tok_str_add2(¯o_str1
, tok
, &tokc
);
2965 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2966 n
, cstr
.data
, (char*)cstr
.data
+ n
);
2972 if (tok
!= TOK_NOSUBST
) {
2973 tok_str_add2(¯o_str1
, tok
, &tokc
);
2975 start_of_nosubsts
= -1;
2977 tok_str_add2(¯o_str1
, tok
, &tokc
);
2979 tok_str_add(¯o_str1
, 0);
2980 return macro_str1
.str
;
2984 /* do macro substitution of macro_str and add result to
2985 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2986 inside to avoid recursing. */
2987 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
2988 const int *macro_str
, struct macro_level
** can_read_stream
)
2995 struct macro_level ml
;
2998 /* first scan for '##' operator handling */
3000 macro_str1
= macro_twosharps(ptr
);
3008 /* NOTE: ptr == NULL can only happen if tokens are read from
3009 file stream due to a macro function call */
3012 TOK_GET(&t
, &ptr
, &cval
);
3015 if (t
== TOK_NOSUBST
) {
3016 /* following token has already been subst'd. just copy it on */
3017 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3018 TOK_GET(&t
, &ptr
, &cval
);
3023 /* if nested substitution, do nothing */
3024 if (sym_find2(*nested_list
, t
)) {
3025 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3026 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3030 if (can_read_stream
)
3031 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
3032 macro_ptr
= (int *)ptr
;
3034 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
3035 ptr
= (int *)macro_ptr
;
3037 if (can_read_stream
&& *can_read_stream
== &ml
)
3038 *can_read_stream
= ml
.prev
;
3041 if (parse_flags
& PARSE_FLAG_SPACES
)
3046 tok_str_add(tok_str
, ' ');
3050 if (!check_space(t
, &spc
))
3051 tok_str_add2(tok_str
, t
, &cval
);
3055 tok_str_free(macro_str1
);
3058 /* return next token with macro substitution */
3059 ST_FUNC
void next(void)
3061 Sym
*nested_list
, *s
;
3063 struct macro_level
*ml
;
3066 if (parse_flags
& PARSE_FLAG_SPACES
)
3071 /* if not reading from macro substituted string, then try
3072 to substitute macros */
3073 if (tok
>= TOK_IDENT
&&
3074 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3075 s
= define_find(tok
);
3077 /* we have a macro: we try to substitute */
3081 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
3082 /* substitution done, NOTE: maybe empty */
3083 tok_str_add(&str
, 0);
3084 macro_ptr
= str
.str
;
3085 macro_ptr_allocated
= str
.str
;
3092 /* end of macro or end of unget buffer */
3093 if (unget_buffer_enabled
) {
3094 macro_ptr
= unget_saved_macro_ptr
;
3095 unget_buffer_enabled
= 0;
3097 /* end of macro string: free it */
3098 tok_str_free(macro_ptr_allocated
);
3099 macro_ptr_allocated
= NULL
;
3103 } else if (tok
== TOK_NOSUBST
) {
3104 /* discard preprocessor's nosubst markers */
3109 /* convert preprocessor tokens into C tokens */
3110 if (tok
== TOK_PPNUM
&&
3111 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
3112 parse_number((char *)tokc
.cstr
->data
);
3116 /* push back current token and set current token to 'last_tok'. Only
3117 identifier case handled for labels. */
3118 ST_INLN
void unget_tok(int last_tok
)
3122 if (unget_buffer_enabled
)
3124 /* assert(macro_ptr == unget_saved_buffer + 1);
3125 assert(*macro_ptr == 0); */
3129 unget_saved_macro_ptr
= macro_ptr
;
3130 unget_buffer_enabled
= 1;
3132 q
= unget_saved_buffer
;
3135 n
= tok_ext_size(tok
) - 1;
3138 *q
= 0; /* end of token string */
3143 /* better than nothing, but needs extension to handle '-E' option
3145 ST_FUNC
void preprocess_init(TCCState
*s1
)
3147 s1
->include_stack_ptr
= s1
->include_stack
;
3148 /* XXX: move that before to avoid having to initialize
3149 file->ifdef_stack_ptr ? */
3150 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3151 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3154 s1
->pack_stack
[0] = 0;
3155 s1
->pack_stack_ptr
= s1
->pack_stack
;
3158 ST_FUNC
void preprocess_new(void)
3163 /* init isid table */
3164 for(i
=CH_EOF
;i
<256;i
++)
3165 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
3167 /* add all tokens */
3169 tcc_free (table_ident
);
3172 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3174 tok_ident
= TOK_IDENT
;
3183 tok_alloc(p
, r
- p
- 1);
3188 static void line_macro_output(BufferedFile
*f
, const char *s
, TCCState
*s1
)
3190 switch (s1
->Pflag
) {
3191 case LINE_MACRO_OUTPUT_FORMAT_STD
:
3192 /* "tcc -E -P1" case */
3193 fprintf(s1
->ppfp
, "# line %d \"%s\"\n", f
->line_num
, f
->filename
);
3196 case LINE_MACRO_OUTPUT_FORMAT_NONE
:
3197 /* "tcc -E -P" case: don't output a line directive */
3200 case LINE_MACRO_OUTPUT_FORMAT_GCC
:
3202 /* "tcc -E" case: a gcc standard by default */
3203 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
, s
);
3208 /* Preprocess the current file */
3209 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3211 BufferedFile
*file_ref
, **iptr
, **iptr_new
;
3215 preprocess_init(s1
);
3216 ch
= file
->buf_ptr
[0];
3217 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3218 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
3219 PARSE_FLAG_LINEFEED
| PARSE_FLAG_SPACES
;
3223 iptr
= s1
->include_stack_ptr
;
3227 if (tok
== TOK_EOF
) {
3229 } else if (file
!= file_ref
) {
3231 line_macro_output(file_ref
, "", s1
);
3233 } else if (tok
== TOK_LINEFEED
) {
3238 } else if (!token_seen
) {
3239 d
= file
->line_num
- file
->line_ref
;
3240 if (file
!= file_ref
|| d
>= 8) {
3243 if (tcc_state
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_GCC
) {
3244 iptr_new
= s1
->include_stack_ptr
;
3245 s
= iptr_new
> iptr
? " 1"
3246 : iptr_new
< iptr
? " 2"
3247 : iptr_new
> s1
->include_stack
? " 3"
3251 line_macro_output(file
, s
, s1
);
3254 fputs("\n", s1
->ppfp
), --d
;
3256 file
->line_ref
= (file_ref
= file
)->line_num
;
3257 token_seen
= tok
!= TOK_LINEFEED
;
3261 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);