2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 /********************************************************/
24 /* global variables */
26 ST_DATA
int tok_flags
;
27 ST_DATA
int parse_flags
;
29 ST_DATA
struct BufferedFile
*file
;
32 ST_DATA
const int *macro_ptr
;
33 ST_DATA CString tokcstr
; /* current parsed string, if any */
35 /* display benchmark infos */
36 ST_DATA
int total_lines
;
37 ST_DATA
int total_bytes
;
38 ST_DATA
int tok_ident
;
39 ST_DATA TokenSym
**table_ident
;
41 /* ------------------------------------------------------------------------- */
43 static int *macro_ptr_allocated
;
44 static const int *unget_saved_macro_ptr
;
45 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
46 static int unget_buffer_enabled
;
47 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
48 static char token_buf
[STRING_MAX_SIZE
+ 1];
49 /* true if isid(c) || isnum(c) */
50 static unsigned char isidnum_table
[256-CH_EOF
];
52 static const char tcc_keywords
[] =
53 #define DEF(id, str) str "\0"
58 /* WARNING: the content of this string encodes token numbers */
59 static const unsigned char tok_two_chars
[] =
61 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
62 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
83 '.','.', 0xa8, // C++ token ?
84 '#','#', TOK_TWOSHARPS
,
90 struct macro_level
*prev
;
94 static void next_nomacro_spc(void);
95 static void macro_subst(
99 struct macro_level
**can_read_stream
102 ST_FUNC
void skip(int c
)
105 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
109 ST_FUNC
void expect(const char *msg
)
111 tcc_error("%s expected", msg
);
114 /* ------------------------------------------------------------------------- */
115 /* CString handling */
116 static void cstr_realloc(CString
*cstr
, int new_size
)
121 size
= cstr
->size_allocated
;
123 size
= 8; /* no need to allocate a too small first string */
124 while (size
< new_size
)
126 data
= tcc_realloc(cstr
->data_allocated
, size
);
127 cstr
->data_allocated
= data
;
128 cstr
->size_allocated
= size
;
133 ST_FUNC
void cstr_ccat(CString
*cstr
, int ch
)
136 size
= cstr
->size
+ 1;
137 if (size
> cstr
->size_allocated
)
138 cstr_realloc(cstr
, size
);
139 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
143 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
)
155 /* add a wide char */
156 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
159 size
= cstr
->size
+ sizeof(nwchar_t
);
160 if (size
> cstr
->size_allocated
)
161 cstr_realloc(cstr
, size
);
162 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
166 ST_FUNC
void cstr_new(CString
*cstr
)
168 memset(cstr
, 0, sizeof(CString
));
171 /* free string and reset it to NULL */
172 ST_FUNC
void cstr_free(CString
*cstr
)
174 tcc_free(cstr
->data_allocated
);
178 /* reset string to empty */
179 ST_FUNC
void cstr_reset(CString
*cstr
)
185 static void add_char(CString
*cstr
, int c
)
187 if (c
== '\'' || c
== '\"' || c
== '\\') {
188 /* XXX: could be more precise if char or string */
189 cstr_ccat(cstr
, '\\');
191 if (c
>= 32 && c
<= 126) {
194 cstr_ccat(cstr
, '\\');
196 cstr_ccat(cstr
, 'n');
198 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
199 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
200 cstr_ccat(cstr
, '0' + (c
& 7));
205 /* ------------------------------------------------------------------------- */
206 /* allocate a new token */
207 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
209 TokenSym
*ts
, **ptable
;
212 if (tok_ident
>= SYM_FIRST_ANOM
)
213 tcc_error("memory full (symbols)");
215 /* expand token table if needed */
216 i
= tok_ident
- TOK_IDENT
;
217 if ((i
% TOK_ALLOC_INCR
) == 0) {
218 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
219 table_ident
= ptable
;
222 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
224 ts
->tok
= tok_ident
++;
225 ts
->sym_define
= NULL
;
226 ts
->sym_label
= NULL
;
227 ts
->sym_struct
= NULL
;
228 ts
->sym_identifier
= NULL
;
230 ts
->hash_next
= NULL
;
231 memcpy(ts
->str
, str
, len
);
237 #define TOK_HASH_INIT 1
238 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
240 /* find a token and add it if not found */
241 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
249 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
250 h
&= (TOK_HASH_SIZE
- 1);
252 pts
= &hash_ident
[h
];
257 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
259 pts
= &(ts
->hash_next
);
261 return tok_alloc_new(pts
, str
, len
);
264 /* XXX: buffer overflow */
265 /* XXX: float tokens */
266 ST_FUNC
char *get_tok_str(int v
, CValue
*cv
)
268 static char buf
[STRING_MAX_SIZE
+ 1];
269 static CString cstr_buf
;
274 /* NOTE: to go faster, we give a fixed buffer for small strings */
275 cstr_reset(&cstr_buf
);
277 cstr_buf
.size_allocated
= sizeof(buf
);
280 /* just an explanation, should never happen:
281 if (v <= TOK_LINENUM && v >= TOK_CINT && cv == NULL)
282 tcc_error("internal error: get_tok_str"); */
287 /* XXX: not quite exact, but only useful for testing */
288 sprintf(p
, "%u", cv
->ui
);
292 /* XXX: not quite exact, but only useful for testing */
294 sprintf(p
, "%u", (unsigned)cv
->ull
);
296 sprintf(p
, "%llu", cv
->ull
);
300 cstr_ccat(&cstr_buf
, 'L');
302 cstr_ccat(&cstr_buf
, '\'');
303 add_char(&cstr_buf
, cv
->i
);
304 cstr_ccat(&cstr_buf
, '\'');
305 cstr_ccat(&cstr_buf
, '\0');
309 len
= cstr
->size
- 1;
311 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
312 cstr_ccat(&cstr_buf
, '\0');
315 cstr_ccat(&cstr_buf
, 'L');
318 cstr_ccat(&cstr_buf
, '\"');
320 len
= cstr
->size
- 1;
322 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
324 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
326 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
328 cstr_ccat(&cstr_buf
, '\"');
329 cstr_ccat(&cstr_buf
, '\0');
336 return NULL
; /* should not happen */
338 /* above tokens have value, the ones below don't */
347 return strcpy(p
, "...");
349 return strcpy(p
, "<<=");
351 return strcpy(p
, ">>=");
354 /* search in two bytes table */
355 const unsigned char *q
= tok_two_chars
;
368 } else if (v
< tok_ident
) {
369 return table_ident
[v
- TOK_IDENT
]->str
;
370 } else if (v
>= SYM_FIRST_ANOM
) {
371 /* special name for anonymous symbol */
372 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
374 /* should never happen */
379 return cstr_buf
.data
;
382 /* fill input buffer and peek next char */
383 static int tcc_peekc_slow(BufferedFile
*bf
)
386 /* only tries to read if really end of buffer */
387 if (bf
->buf_ptr
>= bf
->buf_end
) {
389 #if defined(PARSE_DEBUG)
394 len
= read(bf
->fd
, bf
->buffer
, len
);
401 bf
->buf_ptr
= bf
->buffer
;
402 bf
->buf_end
= bf
->buffer
+ len
;
403 *bf
->buf_end
= CH_EOB
;
405 if (bf
->buf_ptr
< bf
->buf_end
) {
406 return bf
->buf_ptr
[0];
408 bf
->buf_ptr
= bf
->buf_end
;
413 /* return the current character, handling end of block if necessary
415 ST_FUNC
int handle_eob(void)
417 return tcc_peekc_slow(file
);
420 /* read next char from current input file and handle end of input buffer */
421 ST_INLN
void inp(void)
423 ch
= *(++(file
->buf_ptr
));
424 /* end of buffer/file handling */
429 /* handle '\[\r]\n' */
430 static int handle_stray_noerror(void)
437 } else if (ch
== '\r') {
443 } else if (ch
== '#') {
453 static void handle_stray(void)
455 if (handle_stray_noerror())
456 tcc_error("stray '\\' in program");
459 /* skip the stray and handle the \\n case. Output an error if
460 incorrect char after the stray */
461 static int handle_stray1(uint8_t *p
)
465 if (p
>= file
->buf_end
) {
482 /* handle just the EOB case, but not stray */
483 #define PEEKC_EOB(c, p)\
494 /* handle the complicated stray case */
500 c = handle_stray1(p);\
505 /* input with '\[\r]\n' handling. Note that this function cannot
506 handle other characters after '\', so you cannot call it inside
507 strings or comments */
508 ST_FUNC
void minp(void)
516 /* single line C++ comments */
517 static uint8_t *parse_line_comment(uint8_t *p
)
525 if (c
== '\n' || c
== CH_EOF
) {
527 } else if (c
== '\\') {
536 } else if (c
== '\r') {
554 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
563 if (c
== '\n' || c
== '*' || c
== '\\')
567 if (c
== '\n' || c
== '*' || c
== '\\')
571 /* now we can handle all the cases */
575 } else if (c
== '*') {
581 } else if (c
== '/') {
583 } else if (c
== '\\') {
588 /* skip '\[\r]\n', otherwise just skip the stray */
594 } else if (c
== '\r') {
611 /* stray, eob or eof */
616 tcc_error("unexpected end of file in comment");
617 } else if (c
== '\\') {
629 static inline void skip_spaces(void)
635 static inline int check_space(int t
, int *spc
)
646 /* parse a string without interpreting escapes */
647 static uint8_t *parse_pp_string(uint8_t *p
,
648 int sep
, CString
*str
)
656 } else if (c
== '\\') {
662 /* XXX: indicate line number of start of string */
663 tcc_error("missing terminating %c character", sep
);
664 } else if (c
== '\\') {
665 /* escape : just skip \[\r]\n */
670 } else if (c
== '\r') {
673 expect("'\n' after '\r'");
676 } else if (c
== CH_EOF
) {
677 goto unterminated_string
;
680 cstr_ccat(str
, '\\');
686 } else if (c
== '\n') {
689 } else if (c
== '\r') {
693 cstr_ccat(str
, '\r');
709 /* skip block of text until #else, #elif or #endif. skip also pairs of
711 static void preprocess_skip(void)
713 int a
, start_of_line
, c
, in_warn_or_error
;
720 in_warn_or_error
= 0;
741 } else if (c
== '\\') {
742 ch
= file
->buf_ptr
[0];
743 handle_stray_noerror();
750 if (in_warn_or_error
)
752 p
= parse_pp_string(p
, c
, NULL
);
756 if (in_warn_or_error
)
763 p
= parse_comment(p
);
764 } else if (ch
== '/') {
765 p
= parse_line_comment(p
);
775 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
777 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
779 else if (tok
== TOK_ENDIF
)
781 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
782 in_warn_or_error
= 1;
783 else if (tok
== TOK_LINEFEED
)
785 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
786 p
= parse_line_comment(p
);
788 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
789 p
= parse_line_comment(p
);
802 /* ParseState handling */
804 /* XXX: currently, no include file info is stored. Thus, we cannot display
805 accurate messages if the function or data definition spans multiple
808 /* save current parse state in 's' */
809 ST_FUNC
void save_parse_state(ParseState
*s
)
811 s
->line_num
= file
->line_num
;
812 s
->macro_ptr
= macro_ptr
;
817 /* restore parse state from 's' */
818 ST_FUNC
void restore_parse_state(ParseState
*s
)
820 file
->line_num
= s
->line_num
;
821 macro_ptr
= s
->macro_ptr
;
826 /* return the number of additional 'ints' necessary to store the
828 static inline int tok_ext_size(int t
)
842 tcc_error("unsupported token");
849 return LDOUBLE_SIZE
/ 4;
855 /* token string handling */
857 ST_INLN
void tok_str_new(TokenString
*s
)
861 s
->allocated_len
= 0;
862 s
->last_line_num
= -1;
865 ST_FUNC
void tok_str_free(int *str
)
870 static int *tok_str_realloc(TokenString
*s
)
874 if (s
->allocated_len
== 0) {
877 len
= s
->allocated_len
* 2;
879 str
= tcc_realloc(s
->str
, len
* sizeof(int));
880 s
->allocated_len
= len
;
885 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
891 if (len
>= s
->allocated_len
)
892 str
= tok_str_realloc(s
);
897 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
904 /* allocate space for worst case */
905 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
906 str
= tok_str_realloc(s
);
915 str
[len
++] = cv
->tab
[0];
924 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
925 while ((len
+ nb_words
) > s
->allocated_len
)
926 str
= tok_str_realloc(s
);
927 cstr
= (CString
*)(str
+ len
);
929 cstr
->size
= cv
->cstr
->size
;
930 cstr
->data_allocated
= NULL
;
931 cstr
->size_allocated
= cstr
->size
;
932 memcpy((char *)cstr
+ sizeof(CString
),
933 cv
->cstr
->data
, cstr
->size
);
940 #if LDOUBLE_SIZE == 8
943 str
[len
++] = cv
->tab
[0];
944 str
[len
++] = cv
->tab
[1];
946 #if LDOUBLE_SIZE == 12
948 str
[len
++] = cv
->tab
[0];
949 str
[len
++] = cv
->tab
[1];
950 str
[len
++] = cv
->tab
[2];
951 #elif LDOUBLE_SIZE == 16
953 str
[len
++] = cv
->tab
[0];
954 str
[len
++] = cv
->tab
[1];
955 str
[len
++] = cv
->tab
[2];
956 str
[len
++] = cv
->tab
[3];
957 #elif LDOUBLE_SIZE != 8
958 #error add long double size support
967 /* add the current parse token in token string 's' */
968 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
972 /* save line number info */
973 if (file
->line_num
!= s
->last_line_num
) {
974 s
->last_line_num
= file
->line_num
;
975 cval
.i
= s
->last_line_num
;
976 tok_str_add2(s
, TOK_LINENUM
, &cval
);
978 tok_str_add2(s
, tok
, &tokc
);
981 /* get a token from an integer array and increment pointer
982 accordingly. we code it as a macro to avoid pointer aliasing. */
983 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1001 cv
->cstr
= (CString
*)p
;
1002 cv
->cstr
->data
= (char *)p
+ sizeof(CString
);
1003 p
+= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
1011 #if LDOUBLE_SIZE == 16
1013 #elif LDOUBLE_SIZE == 12
1015 #elif LDOUBLE_SIZE == 8
1018 # error add long double size support
1031 static int macro_is_equal(const int *a
, const int *b
)
1033 char buf
[STRING_MAX_SIZE
+ 1];
1037 TOK_GET(&t
, &a
, &cv
);
1038 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1039 TOK_GET(&t
, &b
, &cv
);
1040 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1046 static void define_print(Sym
*s
, int is_undef
)
1053 if (tcc_state
->dflag
== 0 || !s
|| !tcc_state
->ppfp
)
1057 c
= file
->line_num
- file
->line_ref
- 1;
1060 fputs("\n", tcc_state
->ppfp
);
1061 file
->line_ref
= file
->line_num
;
1066 fprintf(tcc_state
->ppfp
, "// #undef %s", get_tok_str(s
->v
, NULL
));
1070 fprintf(tcc_state
->ppfp
, "// #define %s", get_tok_str(s
->v
, NULL
));
1075 fprintf(tcc_state
->ppfp
, "%s%s", sep
, get_tok_str(arg
->v
& ~SYM_FIELD
, NULL
));
1079 fprintf(tcc_state
->ppfp
, ")");
1084 fprintf(tcc_state
->ppfp
, " ");
1087 TOK_GET(&t
, &str
, &cval
);
1090 fprintf(tcc_state
->ppfp
, "%s", get_tok_str(t
, &cval
));
1094 /* defines handling */
1095 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1100 if (s
&& !macro_is_equal(s
->d
, str
))
1101 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1103 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1105 s
->next
= first_arg
;
1106 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1110 /* undefined a define symbol. Its name is just set to zero */
1111 ST_FUNC
void define_undef(Sym
*s
)
1115 if (v
>= TOK_IDENT
&& v
< tok_ident
) {
1117 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1121 ST_INLN Sym
*define_find(int v
)
1124 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1126 return table_ident
[v
]->sym_define
;
1129 /* free define stack until top reaches 'b' */
1130 ST_FUNC
void free_defines(Sym
*b
)
1138 /* do not free args or predefined defines */
1140 tok_str_free(top
->d
);
1142 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1143 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1150 ST_FUNC
void print_defines(void)
1158 if (v
>= TOK_IDENT
&& v
< tok_ident
) {
1159 s
= table_ident
[v
- TOK_IDENT
]->sym_define
;
1167 ST_FUNC Sym
*label_find(int v
)
1170 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1172 return table_ident
[v
]->sym_label
;
1175 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1178 s
= sym_push2(ptop
, v
, 0, 0);
1180 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1181 if (ptop
== &global_label_stack
) {
1182 /* modify the top most local identifier, so that
1183 sym_identifier will point to 's' when popped */
1185 ps
= &(*ps
)->prev_tok
;
1192 /* pop labels until element last is reached. Look if any labels are
1193 undefined. Define symbols if '&&label' was used. */
1194 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1197 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1199 if (s
->r
== LABEL_DECLARED
) {
1200 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1201 } else if (s
->r
== LABEL_FORWARD
) {
1202 tcc_error("label '%s' used but not defined",
1203 get_tok_str(s
->v
, NULL
));
1206 /* define corresponding symbol. A size of
1208 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1212 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1218 /* eval an expression for #if/#elif */
1219 static int expr_preprocess(void)
1225 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1226 next(); /* do macro subst */
1227 if (tok
== TOK_DEFINED
) {
1232 c
= define_find(tok
) != 0;
1237 } else if (tok
>= TOK_IDENT
) {
1238 /* if undefined macro */
1242 tok_str_add_tok(&str
);
1244 tok_str_add(&str
, -1); /* simulate end of file */
1245 tok_str_add(&str
, 0);
1246 /* now evaluate C constant expression */
1247 macro_ptr
= str
.str
;
1251 tok_str_free(str
.str
);
1255 /* parse after #define */
1256 ST_FUNC
void parse_define(void)
1258 Sym
*s
, *first
, **ps
;
1259 int v
, t
, varg
, is_vaargs
, spc
, ptok
, macro_list_start
;
1264 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1265 /* XXX: should check if same macro (ANSI) */
1268 /* '(' must be just after macro definition for MACRO_FUNC */
1273 while (tok
!= ')') {
1277 if (varg
== TOK_DOTS
) {
1278 varg
= TOK___VA_ARGS__
;
1280 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1284 if (varg
< TOK_IDENT
)
1285 tcc_error( "\'%s\' may not appear in parameter list", get_tok_str(varg
, NULL
));
1286 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1298 /* EOF testing necessary for '-D' handling */
1300 macro_list_start
= 1;
1301 int old_parse_flags
= parse_flags
;
1302 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
;
1303 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1304 if (!macro_list_start
&& spc
== 2 && tok
== TOK_TWOSHARPS
)
1305 tcc_error("'##' invalid at start of macro");
1307 /* remove spaces around ## and after '#' */
1308 if (TOK_TWOSHARPS
== tok
) {
1312 } else if ('#' == tok
) {
1314 } else if (check_space(tok
, &spc
)) {
1317 tok_str_add2(&str
, tok
, &tokc
);
1320 macro_list_start
= 0;
1323 parse_flags
= old_parse_flags
;
1324 if (ptok
== TOK_TWOSHARPS
)
1325 tcc_error("'##' invalid at end of macro");
1327 --str
.len
; /* remove trailing space */
1328 tok_str_add(&str
, 0);
1329 define_push(v
, t
, str
.str
, first
);
1332 static inline int hash_cached_include(const char *filename
)
1334 const unsigned char *s
;
1338 s
= (unsigned char *) filename
;
1340 h
= TOK_HASH_FUNC(h
, *s
);
1343 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1347 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1351 h
= hash_cached_include(filename
);
1352 i
= s1
->cached_includes_hash
[h
];
1356 e
= s1
->cached_includes
[i
- 1];
1357 if (0 == PATHCMP(e
->filename
, filename
))
1364 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1369 if (search_cached_include(s1
, filename
))
1372 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1374 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1375 strcpy(e
->filename
, filename
);
1376 e
->ifndef_macro
= ifndef_macro
;
1377 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1378 /* add in hash table */
1379 h
= hash_cached_include(filename
);
1380 e
->hash_next
= s1
->cached_includes_hash
[h
];
1381 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1384 static void pragma_parse(TCCState
*s1
)
1387 if (tok
== TOK_pack
) {
1390 #pragma pack(1) // set
1391 #pragma pack() // reset to default
1392 #pragma pack(push,1) // push & set
1393 #pragma pack(pop) // restore previous
1397 if (tok
== TOK_ASM_pop
) {
1399 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1401 tcc_error("out of pack stack");
1403 s1
->pack_stack_ptr
--;
1407 if (tok
== TOK_ASM_push
) {
1409 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1411 s1
->pack_stack_ptr
++;
1414 if (tok
!= TOK_CINT
)
1417 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1421 *s1
->pack_stack_ptr
= val
;
1425 } else if (tok
== TOK_comment
) {
1426 if (s1
->ms_extensions
) {
1429 if (tok
== TOK_lib
) {
1432 if (tok
!= TOK_STR
) {
1433 tcc_error("invalid library specification");
1435 int len
= strlen((char *)tokc
.cstr
->data
);
1436 char *file
= tcc_malloc(len
+ 4); /* filetype, "-l", and \0 at the end */
1437 file
[0] = TCC_FILETYPE_BINARY
;
1440 strcpy(&file
[3],(char *)tokc
.cstr
->data
);
1441 dynarray_add((void ***)&s1
->files
, &s1
->nb_files
, file
);
1446 tcc_warning("unknown specifier '%s' in #pragma comment", get_tok_str(tok
, &tokc
));
1449 tcc_warning("#pragma comment(lib) is ignored");
1451 } else if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1455 if (next_nomacro(), tok
!= '(')
1457 if (next_nomacro(), tok
!= TOK_STR
)
1459 v
= tok_alloc(tokc
.cstr
->data
, tokc
.cstr
->size
- 1)->tok
;
1460 if (next_nomacro(), tok
!= ')')
1462 if (t
== TOK_push_macro
) {
1463 while (NULL
== (s
= define_find(v
)))
1464 define_push(v
, 0, NULL
, NULL
);
1465 s
->type
.ref
= s
; /* set push boundary */
1467 for (s
= define_stack
; s
; s
= s
->prev
)
1468 if (s
->v
== v
&& s
->type
.ref
== s
) {
1474 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1476 tcc_warning("unbalanced #pragma pop_macro");
1478 /* print info when tcc is called with "-E -dD" switches */
1479 if (s1
->dflag
&& s1
->ppfp
) {
1481 int c
= file
->line_num
- file
->line_ref
- 1;
1484 fputs("\n", tcc_state
->ppfp
);
1485 file
->line_ref
= file
->line_num
;
1488 fprintf(s1
->ppfp
, "// #pragma %s_macro(\"%s\")",
1489 (t
== TOK_push_macro
) ? "push" : "pop",
1490 get_tok_str(v
, NULL
));
1492 } else if (tok
== TOK_once
) {
1493 add_cached_include(s1
, file
->filename
, TOK_once
);
1495 tcc_warning("unknown #pragma %s", get_tok_str(tok
, &tokc
));
1499 tcc_error("malformed #pragma directive");
1502 /* is_bof is true if first non space token at beginning of file */
1503 ST_FUNC
void preprocess(int is_bof
)
1505 TCCState
*s1
= tcc_state
;
1506 int i
, c
, n
, saved_parse_flags
;
1510 saved_parse_flags
= parse_flags
;
1511 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
1512 PARSE_FLAG_LINEFEED
;
1513 parse_flags
|= (saved_parse_flags
& PARSE_FLAG_ASM_FILE
);
1523 s
= define_find(tok
);
1524 /* undefine symbol by putting an invalid name */
1529 case TOK_INCLUDE_NEXT
:
1530 ch
= file
->buf_ptr
[0];
1531 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1536 } else if (ch
== '\"') {
1541 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1542 if ((q
- buf
) < sizeof(buf
) - 1)
1545 if (handle_stray_noerror() == 0)
1553 /* eat all spaces and comments after include */
1554 /* XXX: slightly incorrect */
1555 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1559 /* computed #include : either we have only strings or
1560 we have anything enclosed in '<>' */
1563 if (tok
== TOK_STR
) {
1564 while (tok
!= TOK_LINEFEED
) {
1565 if (tok
!= TOK_STR
) {
1567 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1569 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1575 while (tok
!= TOK_LINEFEED
) {
1576 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1580 /* check syntax and remove '<>' */
1581 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1582 goto include_syntax
;
1583 memmove(buf
, buf
+ 1, len
- 2);
1584 buf
[len
- 2] = '\0';
1589 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1590 tcc_error("#include recursion too deep");
1591 /* store current file in stack, but increment stack later below */
1592 *s1
->include_stack_ptr
= file
;
1594 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1595 for (i
= -2; i
< n
; ++i
) {
1596 char buf1
[sizeof file
->filename
];
1602 /* check absolute include path */
1603 if (!IS_ABSPATH(buf
))
1606 i
= n
; /* force end loop */
1608 } else if (i
== -1) {
1609 /* search in current dir if "header.h" */
1612 path
= file
->filename
;
1613 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1616 /* search in all the include paths */
1617 if (i
< s1
->nb_include_paths
)
1618 path
= s1
->include_paths
[i
];
1620 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1621 pstrcpy(buf1
, sizeof(buf1
), path
);
1622 pstrcat(buf1
, sizeof(buf1
), "/");
1625 pstrcat(buf1
, sizeof(buf1
), buf
);
1627 if (tok
== TOK_INCLUDE_NEXT
)
1628 for (f
= s1
->include_stack_ptr
; f
>= s1
->include_stack
; --f
)
1629 if (0 == PATHCMP((*f
)->filename
, buf1
)) {
1631 printf("%s: #include_next skipping %s\n", file
->filename
, buf1
);
1633 goto include_trynext
;
1636 e
= search_cached_include(s1
, buf1
);
1637 if (e
&& (define_find(e
->ifndef_macro
) || e
->ifndef_macro
== TOK_once
)) {
1638 /* no need to parse the include because the 'ifndef macro'
1641 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1646 if (tcc_open(s1
, buf1
) < 0)
1651 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1653 /* update target deps */
1654 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1656 /* push current file in stack */
1657 ++s1
->include_stack_ptr
;
1658 /* add include file debug info */
1660 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1661 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1662 ch
= file
->buf_ptr
[0];
1665 tcc_error("include file '%s' not found", buf
);
1672 c
= expr_preprocess();
1678 if (tok
< TOK_IDENT
)
1679 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1683 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1685 file
->ifndef_macro
= tok
;
1688 c
= (define_find(tok
) != 0) ^ c
;
1690 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1691 tcc_error("memory full (ifdef)");
1692 *s1
->ifdef_stack_ptr
++ = c
;
1695 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1696 tcc_error("#else without matching #if");
1697 if (s1
->ifdef_stack_ptr
[-1] & 2)
1698 tcc_error("#else after #else");
1699 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1702 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1703 tcc_error("#elif without matching #if");
1704 c
= s1
->ifdef_stack_ptr
[-1];
1706 tcc_error("#elif after #else");
1707 /* last #if/#elif expression was true: we skip */
1710 c
= expr_preprocess();
1711 s1
->ifdef_stack_ptr
[-1] = c
;
1713 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1714 file
->ifndef_macro
= 0;
1724 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1725 tcc_error("#endif without matching #if");
1726 s1
->ifdef_stack_ptr
--;
1727 /* '#ifndef macro' was at the start of file. Now we check if
1728 an '#endif' is exactly at the end of file */
1729 if (file
->ifndef_macro
&&
1730 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1731 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1732 /* need to set to zero to avoid false matches if another
1733 #ifndef at middle of file */
1734 file
->ifndef_macro
= 0;
1735 while (tok
!= TOK_LINEFEED
)
1737 tok_flags
|= TOK_FLAG_ENDIF
;
1743 if (tok
!= TOK_CINT
)
1744 tcc_error("A #line format is wrong");
1746 if (tok
!= TOK_CINT
) {
1747 char *p
= tokc
.cstr
->data
;
1748 tokc
.i
= strtoul(p
, (char **)&p
, 10);
1751 file
->line_num
= tokc
.i
- 1;
1753 if (tok
!= TOK_LINEFEED
) {
1754 if (tok
!= TOK_STR
) {
1755 if ((parse_flags
& PARSE_FLAG_ASM_FILE
) == 0) {
1757 tcc_error("#line format is wrong");
1761 pstrcpy(file
->filename
, sizeof(file
->filename
),
1762 (char *)tokc
.cstr
->data
);
1765 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1770 ch
= file
->buf_ptr
[0];
1773 while (ch
!= '\n' && ch
!= CH_EOF
) {
1774 if ((q
- buf
) < sizeof(buf
) - 1)
1777 if (handle_stray_noerror() == 0)
1784 tcc_error("#error %s", buf
);
1786 tcc_warning("#warning %s", buf
);
1792 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_PPNUM
) {
1793 /* '!' is ignored to allow C scripts. numbers are ignored
1794 to emulate cpp behaviour */
1796 if (!(parse_flags
& PARSE_FLAG_ASM_FILE
))
1797 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1799 /* this is a gas line comment in an 'S' file. */
1800 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1806 /* ignore other preprocess commands or #! for C scripts */
1807 while (tok
!= TOK_LINEFEED
)
1810 parse_flags
= saved_parse_flags
;
1813 /* evaluate escape codes in a string. */
1814 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1829 case '0': case '1': case '2': case '3':
1830 case '4': case '5': case '6': case '7':
1831 /* at most three octal digits */
1836 n
= n
* 8 + c
- '0';
1840 n
= n
* 8 + c
- '0';
1845 goto add_char_nonext
;
1853 if (c
>= 'a' && c
<= 'f')
1855 else if (c
>= 'A' && c
<= 'F')
1865 goto add_char_nonext
;
1889 goto invalid_escape
;
1899 if (c
>= '!' && c
<= '~')
1900 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1902 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1909 cstr_ccat(outstr
, c
);
1911 cstr_wccat(outstr
, c
);
1913 /* add a trailing '\0' */
1915 cstr_ccat(outstr
, '\0');
1917 cstr_wccat(outstr
, '\0');
1920 /* we use 64 bit numbers */
1923 /* bn = (bn << shift) | or_val */
1924 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
1928 for(i
=0;i
<BN_SIZE
;i
++) {
1930 bn
[i
] = (v
<< shift
) | or_val
;
1931 or_val
= v
>> (32 - shift
);
1935 static void bn_zero(unsigned int *bn
)
1938 for(i
=0;i
<BN_SIZE
;i
++) {
1943 /* parse number in null terminated string 'p' and return it in the
1945 static void parse_number(const char *p
)
1947 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
1949 unsigned int bn
[BN_SIZE
];
1960 goto float_frac_parse
;
1961 } else if (t
== '0') {
1962 if (ch
== 'x' || ch
== 'X') {
1966 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
1972 /* parse all digits. cannot check octal numbers at this stage
1973 because of floating point constants */
1975 if (ch
>= 'a' && ch
<= 'f')
1977 else if (ch
>= 'A' && ch
<= 'F')
1985 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
1987 tcc_error("number too long");
1993 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
1994 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
1996 /* NOTE: strtox should support that for hexa numbers, but
1997 non ISOC99 libcs do not support it, so we prefer to do
1999 /* hexadecimal or binary floats */
2000 /* XXX: handle overflows */
2012 } else if (t
>= 'a') {
2014 } else if (t
>= 'A') {
2019 bn_lshift(bn
, shift
, t
);
2026 if (t
>= 'a' && t
<= 'f') {
2028 } else if (t
>= 'A' && t
<= 'F') {
2030 } else if (t
>= '0' && t
<= '9') {
2036 tcc_error("invalid digit");
2037 bn_lshift(bn
, shift
, t
);
2042 if (ch
!= 'p' && ch
!= 'P')
2049 } else if (ch
== '-') {
2053 if (ch
< '0' || ch
> '9')
2054 expect("exponent digits");
2055 while (ch
>= '0' && ch
<= '9') {
2056 exp_val
= exp_val
* 10 + ch
- '0';
2059 exp_val
= exp_val
* s
;
2061 /* now we can generate the number */
2062 /* XXX: should patch directly float number */
2063 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2064 d
= ldexp(d
, exp_val
- frac_bits
);
2069 /* float : should handle overflow */
2071 } else if (t
== 'L') {
2073 #ifdef TCC_TARGET_PE
2078 /* XXX: not large enough */
2079 tokc
.ld
= (long double)d
;
2086 /* decimal floats */
2088 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2093 while (ch
>= '0' && ch
<= '9') {
2094 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2100 if (ch
== 'e' || ch
== 'E') {
2101 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2105 if (ch
== '-' || ch
== '+') {
2106 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2111 if (ch
< '0' || ch
> '9')
2112 expect("exponent digits");
2113 while (ch
>= '0' && ch
<= '9') {
2114 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2126 tokc
.f
= strtof(token_buf
, NULL
);
2127 } else if (t
== 'L') {
2129 #ifdef TCC_TARGET_PE
2131 tokc
.d
= strtod(token_buf
, NULL
);
2134 tokc
.ld
= strtold(token_buf
, NULL
);
2138 tokc
.d
= strtod(token_buf
, NULL
);
2142 unsigned long long n
, n1
;
2143 int lcount
, ucount
, must_64bit
;
2146 /* integer number */
2149 if (b
== 10 && *q
== '0') {
2156 /* no need for checks except for base 10 / 8 errors */
2166 tcc_error("invalid digit");
2169 /* detect overflow */
2170 /* XXX: this test is not reliable */
2172 tcc_error("integer constant overflow");
2175 /* Determine the characteristics (unsigned and/or 64bit) the type of
2176 the constant must have according to the constant suffix(es) */
2177 lcount
= ucount
= must_64bit
= 0;
2183 tcc_error("three 'l's in integer constant");
2184 if (lcount
&& *(p
- 1) != ch
)
2185 tcc_error("incorrect integer suffix: %s", p1
);
2187 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2192 } else if (t
== 'U') {
2194 tcc_error("two 'u's in integer constant");
2202 /* Whether 64 bits are needed to hold the constant's value */
2203 if (n
& 0xffffffff00000000LL
|| must_64bit
) {
2211 /* Whether type must be unsigned to hold the constant's value */
2212 if (ucount
|| ((n1
>> 31) && (b
!= 10))) {
2213 if (tok
== TOK_CLLONG
)
2217 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2218 } else if (n1
>> 31) {
2219 if (tok
== TOK_CINT
)
2222 tcc_error("integer constant overflow");
2225 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2231 tcc_error("invalid number\n");
2235 #define PARSE2(c1, tok1, c2, tok2) \
2246 /* return next token without macro substitution */
2247 static inline void next_nomacro1(void)
2263 goto keep_tok_flags
;
2270 /* first look if it is in fact an end of buffer */
2271 if (p
>= file
->buf_end
) {
2275 if (p
>= file
->buf_end
)
2282 if (parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
) {
2283 if (handle_stray_noerror() != 0) {
2291 goto redo_no_start_2
;
2295 TCCState
*s1
= tcc_state
;
2296 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2297 && !(tok_flags
& TOK_FLAG_EOF
)) {
2298 tok_flags
|= TOK_FLAG_EOF
;
2300 goto keep_tok_flags
;
2301 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2303 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2304 tcc_error("missing #endif");
2305 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2306 /* no include left : end of file. */
2309 tok_flags
&= ~TOK_FLAG_EOF
;
2310 /* pop include file */
2312 /* test if previous '#endif' was after a #ifdef at
2314 if (tok_flags
& TOK_FLAG_ENDIF
) {
2316 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2318 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2319 tok_flags
&= ~TOK_FLAG_ENDIF
;
2322 /* add end of include file debug info */
2323 if (tcc_state
->do_debug
) {
2324 put_stabd(N_EINCL
, 0, 0);
2326 /* pop include stack */
2328 s1
->include_stack_ptr
--;
2337 tok_flags
|= TOK_FLAG_BOL
;
2340 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2343 goto keep_tok_flags
;
2348 if (is_space(c
) && (parse_flags
& PARSE_FLAG_ASM_FILE
)) {
2349 p
= parse_line_comment(p
);
2353 if ((tok_flags
& TOK_FLAG_BOL
) &&
2354 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2356 preprocess(tok_flags
& TOK_FLAG_BOF
);
2362 tok
= TOK_TWOSHARPS
;
2364 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2365 p
= parse_line_comment(p
- 1);
2374 /* dollar is allowed to start identifiers when not parsing asm */
2376 if (!tcc_state
->dollars_in_identifiers
2377 || (parse_flags
& PARSE_FLAG_ASM_FILE
)) goto parse_simple
;
2379 case 'a': case 'b': case 'c': case 'd':
2380 case 'e': case 'f': case 'g': case 'h':
2381 case 'i': case 'j': case 'k': case 'l':
2382 case 'm': case 'n': case 'o': case 'p':
2383 case 'q': case 'r': case 's': case 't':
2384 case 'u': case 'v': case 'w': case 'x':
2386 case 'A': case 'B': case 'C': case 'D':
2387 case 'E': case 'F': case 'G': case 'H':
2388 case 'I': case 'J': case 'K':
2389 case 'M': case 'N': case 'O': case 'P':
2390 case 'Q': case 'R': case 'S': case 'T':
2391 case 'U': case 'V': case 'W': case 'X':
2397 h
= TOK_HASH_FUNC(h
, c
);
2401 if (!isidnum_table
[c
-CH_EOF
]
2402 && (tcc_state
->dollars_in_identifiers
? (c
!= '$') : 1))
2404 h
= TOK_HASH_FUNC(h
, c
);
2411 /* fast case : no stray found, so we have the full token
2412 and we have already hashed it */
2414 h
&= (TOK_HASH_SIZE
- 1);
2415 pts
= &hash_ident
[h
];
2420 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2422 pts
= &(ts
->hash_next
);
2424 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2428 cstr_reset(&tokcstr
);
2431 cstr_ccat(&tokcstr
, *p1
);
2437 while (isidnum_table
[c
-CH_EOF
]
2438 || (tcc_state
->dollars_in_identifiers
? (c
== '$') : 0)) {
2439 cstr_ccat(&tokcstr
, c
);
2442 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2448 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2450 goto parse_ident_fast
;
2453 if (c
== '\'' || c
== '\"') {
2457 cstr_reset(&tokcstr
);
2458 cstr_ccat(&tokcstr
, 'L');
2459 goto parse_ident_slow
;
2463 case '0': case '1': case '2': case '3':
2464 case '4': case '5': case '6': case '7':
2467 cstr_reset(&tokcstr
);
2468 /* after the first digit, accept digits, alpha, '.' or sign if
2469 prefixed by 'eEpP' */
2473 cstr_ccat(&tokcstr
, c
);
2475 if (!(isnum(c
) || isid(c
) || c
== '.' ||
2476 ((c
== '+' || c
== '-') &&
2477 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
2480 /* We add a trailing '\0' to ease parsing */
2481 cstr_ccat(&tokcstr
, '\0');
2482 tokc
.cstr
= &tokcstr
;
2486 /* special dot handling because it can also start a number */
2489 cstr_reset(&tokcstr
);
2490 cstr_ccat(&tokcstr
, '.');
2492 } else if (c
== '.') {
2495 if ((parse_flags
& PARSE_FLAG_ASM_FILE
) == 0)
2516 /* parse the string */
2518 p
= parse_pp_string(p
, sep
, &str
);
2519 cstr_ccat(&str
, '\0');
2521 /* eval the escape (should be done as TOK_PPNUM) */
2522 cstr_reset(&tokcstr
);
2523 parse_escape_string(&tokcstr
, str
.data
, is_long
);
2528 /* XXX: make it portable */
2532 char_size
= sizeof(nwchar_t
);
2533 if (tokcstr
.size
<= char_size
)
2534 tcc_error("empty character constant");
2535 if (tokcstr
.size
> 2 * char_size
)
2536 tcc_warning("multi-character character constant");
2538 tokc
.i
= *(int8_t *)tokcstr
.data
;
2541 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2545 tokc
.cstr
= &tokcstr
;
2559 } else if (c
== '<') {
2577 } else if (c
== '>') {
2595 } else if (c
== '=') {
2608 } else if (c
== '=') {
2621 } else if (c
== '=') {
2634 } else if (c
== '=') {
2637 } else if (c
== '>') {
2645 PARSE2('!', '!', '=', TOK_NE
)
2646 PARSE2('=', '=', '=', TOK_EQ
)
2647 PARSE2('*', '*', '=', TOK_A_MUL
)
2648 PARSE2('%', '%', '=', TOK_A_MOD
)
2649 PARSE2('^', '^', '=', TOK_A_XOR
)
2651 /* comments or operator */
2655 p
= parse_comment(p
);
2656 /* comments replaced by a blank */
2658 goto keep_tok_flags
;
2659 } else if (c
== '/') {
2660 p
= parse_line_comment(p
);
2662 goto keep_tok_flags
;
2663 } else if (c
== '=') {
2683 case '@': /* only used in assembler */
2690 if ((parse_flags
& PARSE_FLAG_ASM_FILE
) == 0)
2691 tcc_error("unrecognized character \\x%02x", c
);
2701 #if defined(PARSE_DEBUG)
2702 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2706 /* return next token without macro substitution. Can read input from
2708 static void next_nomacro_spc(void)
2714 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2715 if (tok
== TOK_LINENUM
) {
2716 file
->line_num
= tokc
.i
;
2725 ST_FUNC
void next_nomacro(void)
2729 } while (is_space(tok
));
2732 /* substitute arguments in replacement lists in macro_str by the values in
2733 args (field d) and return allocated string */
2734 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2736 int last_tok
, t
, spc
;
2747 TOK_GET(&t
, ¯o_str
, &cval
);
2752 TOK_GET(&t
, ¯o_str
, &cval
);
2755 s
= sym_find2(args
, t
);
2761 TOK_GET(&t
, &st
, &cval
);
2762 if (t
!= TOK_PLCHLDR
&& !check_space(t
, &spc
))
2763 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2766 cstr_ccat(&cstr
, '\0');
2769 /* emulate GCC behaviour and parse escapes in the token string */
2770 parse_escape_string(&cstr2
, cstr
.data
, 0);
2773 tok_str_add2(&str
, TOK_STR
, &cval
);
2774 cstr_free(cval
.cstr
);
2776 tok_str_add2(&str
, t
, &cval
);
2778 } else if (t
>= TOK_IDENT
) {
2779 s
= sym_find2(args
, t
);
2782 /* if '##' is present before or after, no arg substitution */
2783 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
2784 /* special case for var arg macros : ## eats the
2785 ',' if empty VA_ARGS variable. */
2786 /* XXX: test of the ',' is not 100%
2787 reliable. should fix it to avoid security
2789 if (gnu_ext
&& s
->type
.t
&&
2790 last_tok
== TOK_TWOSHARPS
&&
2791 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
2793 tok_str_add(&str
, TOK_GNUCOMMA
);
2794 str
.str
[str
.len
] = 0; // not actually needed.
2799 TOK_GET(&t1
, &st
, &cval
);
2802 tok_str_add2(&str
, t1
, &cval
);
2805 /* NOTE: the stream cannot be read when macro
2806 substituing an argument */
2807 macro_subst(&str
, nested_list
, st
, NULL
);
2810 tok_str_add(&str
, t
);
2813 tok_str_add2(&str
, t
, &cval
);
2818 tok_str_add(&str
, TOK_PLCHLDR
);
2819 tok_str_add(&str
, 0);
2823 static char const ab_month_name
[12][4] =
2825 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2826 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2829 /* do macro substitution of current token with macro 's' and add
2830 result to (tok_str,tok_len). 'nested_list' is the list of all
2831 macros we got inside to avoid recursing. Return non zero if no
2832 substitution needs to be done */
2833 static int macro_subst_tok(TokenString
*tok_str
,
2834 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
2836 Sym
*args
, *sa
, *sa1
;
2837 int mstr_allocated
, parlevel
, *mstr
, t
, t1
, spc
;
2845 /* if symbol is a macro, prepare substitution */
2846 /* special macros */
2847 if (tok
== TOK___LINE__
) {
2848 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2852 } else if (tok
== TOK___FILE__
) {
2853 cstrval
= file
->filename
;
2855 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2860 tm
= localtime(&ti
);
2861 if (tok
== TOK___DATE__
) {
2862 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2863 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2865 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2866 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2873 cstr_cat(&cstr
, cstrval
);
2874 cstr_ccat(&cstr
, '\0');
2876 tok_str_add2(tok_str
, t1
, &cval
);
2880 int old_parse_flags
= parse_flags
;
2881 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
;
2885 if (s
->type
.t
== MACRO_FUNC
) {
2886 /* NOTE: we do not use next_nomacro to avoid eating the
2887 next token. XXX: find better solution */
2891 while (is_space(t
= *p
) || TOK_LINEFEED
== t
)
2893 if (t
== 0 && can_read_stream
) {
2894 /* end of macro stream: we must look at the token
2895 after in the file */
2896 struct macro_level
*ml
= *can_read_stream
;
2902 *can_read_stream
= ml
-> prev
;
2904 /* also, end of scope for nested defined symbol */
2905 (*nested_list
)->v
= -1;
2909 ch
= tcc_peekc_slow(file
);
2910 while (is_space(ch
) || ch
== '\n' || ch
== '/')
2915 uint8_t *p
= file
->buf_ptr
;
2918 p
= parse_comment(p
);
2919 file
->buf_ptr
= p
- 1;
2920 } else if (c
== '/') {
2921 p
= parse_line_comment(p
);
2922 file
->buf_ptr
= p
- 1;
2930 if (t
!= '(') /* no macro subst */
2933 /* argument macro */
2938 /* NOTE: empty args are allowed, except if no args */
2940 /* handle '()' case */
2941 if (!args
&& !sa
&& tok
== ')')
2944 tcc_error("macro '%s' used with too many args",
2945 get_tok_str(s
->v
, 0));
2948 /* NOTE: non zero sa->t indicates VA_ARGS */
2949 while ((parlevel
> 0 ||
2951 (tok
!= ',' || sa
->type
.t
))) &&
2956 else if (tok
== ')')
2958 if (tok
== TOK_LINEFEED
)
2960 if (tok
== TOK_EOF
|| tok
== 0)
2962 if (!check_space(tok
, &spc
))
2963 tok_str_add2(&str
, tok
, &tokc
);
2970 tok_str_add(&str
, TOK_PLCHLDR
);
2971 tok_str_add(&str
, 0);
2972 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
2976 /* special case for gcc var args: add an empty
2977 var arg argument if it is omitted */
2978 if (sa
&& sa
->type
.t
&& gnu_ext
)
2989 /* Argh! Not a macro invocation after all, at this
2990 * point, so put everything back onto mstr that's
2991 * been skipped since we saw the '(' )*/
2993 tok_str_add(&str
, mtok
);
2994 tok_str_add(&str
, '(');
2995 for (sa
= s
->next
; sa
; sa
= sa
->next
) {
2998 tok_str_add(&str
, *p
);
3010 tcc_error("macro '%s' used with too few args",
3011 get_tok_str(s
->v
, 0));
3014 /* now subst each arg */
3015 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3021 tok_str_free(sa
->d
);
3027 sym_push2(nested_list
, s
->v
, 0, 0);
3028 parse_flags
= old_parse_flags
;
3029 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
3030 /* pop nested defined symbol */
3032 *nested_list
= sa1
->prev
;
3040 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3041 return the resulting string (which must be freed). */
3042 static inline int *macro_twosharps(const int *macro_str
)
3047 TokenString macro_str1
;
3049 int n
, start_of_nosubsts
;
3051 /* we search the first '##' */
3052 for(ptr
= macro_str
;;) {
3054 TOK_GET(&t
, &ptr
, &cval
);
3055 if (t
== TOK_TWOSHARPS
)
3057 /* nothing more to do if end of string */
3062 /* we saw '##', so we need more processing to handle it */
3063 start_of_nosubsts
= -1;
3064 tok_str_new(¯o_str1
);
3065 for(ptr
= macro_str
;;) {
3066 TOK_GET(&tok
, &ptr
, &tokc
);
3069 if (tok
== TOK_NOSUBST
&& start_of_nosubsts
< 0)
3070 start_of_nosubsts
= macro_str1
.len
;
3071 while (*ptr
== TOK_TWOSHARPS
) {
3072 /* given 'a##b', remove nosubsts preceding 'a' */
3073 if (start_of_nosubsts
>= 0)
3074 macro_str1
.len
= start_of_nosubsts
;
3075 /* given 'a##b', skip '##' */
3077 /* given 'a##b', remove nosubsts preceding 'b' */
3078 while (t
== TOK_NOSUBST
)
3080 if (t
&& t
!= TOK_TWOSHARPS
) {
3082 TOK_GET(&t
, &ptr
, &cval
);
3083 /* We concatenate the two tokens */
3085 if (tok
!= TOK_PLCHLDR
)
3086 cstr_cat(&cstr
, get_tok_str(tok
, &tokc
));
3088 if (t
!= TOK_PLCHLDR
)
3089 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3090 cstr_ccat(&cstr
, '\0');
3092 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3093 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3095 if (0 == *file
->buf_ptr
)
3098 if (0 == *file
->buf_ptr
)
3100 tok_str_add2(¯o_str1
, tok
, &tokc
);
3101 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
3102 n
, cstr
.data
, (char*)cstr
.data
+ n
);
3107 if (tok
== TOK_TWOSHARPS
) {
3108 /* two sharps twosharped together tokenize to two
3109 * sharp tokens, not a twosharp token. */
3110 /* That's fun to say, but is it actually true? GCC
3111 * stringifies #define a # ## # ## # to "## #" (and a
3112 * warning), while we produce "###" (no warning) */
3113 tok_str_add(¯o_str1
, '#');
3117 if (tok
!= TOK_NOSUBST
) {
3118 tok_str_add2(¯o_str1
, tok
, &tokc
);
3120 start_of_nosubsts
= -1;
3122 tok_str_add2(¯o_str1
, tok
, &tokc
);
3124 tok_str_add(¯o_str1
, 0);
3125 return macro_str1
.str
;
3129 /* do macro substitution of macro_str and add result to
3130 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3131 inside to avoid recursing. */
3132 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
3133 const int *macro_str
, struct macro_level
** can_read_stream
)
3140 struct macro_level ml
;
3142 int gnucomma_index
= -1;
3144 /* first scan for '##' operator handling */
3146 macro_str1
= macro_twosharps(ptr
);
3154 /* NOTE: ptr == NULL can only happen if tokens are read from
3155 file stream due to a macro function call */
3158 TOK_GET(&t
, &ptr
, &cval
);
3161 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
)) {
3162 tcc_error("stray '\\' in program");
3164 if (t
== TOK_NOSUBST
) {
3165 /* following token has already been subst'd. just copy it on */
3166 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3167 TOK_GET(&t
, &ptr
, &cval
);
3170 if (t
== TOK_GNUCOMMA
) {
3171 if (gnucomma_index
!= -1)
3172 tcc_error("two GNU commas in the same macro");
3173 gnucomma_index
= tok_str
->len
;
3174 tok_str_add(tok_str
, ',');
3175 TOK_GET(&t
, &ptr
, &cval
);
3179 int old_length
= tok_str
->len
;
3180 /* if nested substitution, do nothing */
3181 if (sym_find2(*nested_list
, t
)) {
3182 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3183 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3187 if (can_read_stream
)
3188 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
3189 macro_ptr
= (int *)ptr
;
3191 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
3193 if (tok_str
->len
&& tok_str
->str
[tok_str
->len
-1] == ' ')
3195 ptr
= (int *)macro_ptr
;
3197 if (can_read_stream
&& *can_read_stream
== &ml
)
3198 *can_read_stream
= ml
.prev
;
3200 if (!check_space(t
, &spc
))
3201 tok_str_add2(tok_str
, t
, &cval
);
3202 tok_str_add(tok_str
, ' ');
3206 if (ret
== 0 && old_length
== tok_str
->len
)
3207 tok_str_add(tok_str
, TOK_PLCHLDR
);
3208 if (parse_flags
& PARSE_FLAG_SPACES
)
3209 force_blank
= 0; //1;
3213 tok_str_add(tok_str
, ' ');
3217 if (!check_space(t
, &spc
))
3218 tok_str_add2(tok_str
, t
, &cval
);
3220 if (gnucomma_index
!= -1 && tok_str
->len
>= gnucomma_index
+2) {
3221 if (tok_str
->str
[gnucomma_index
+1] == TOK_PLCHLDR
)
3223 gnucomma_index
= -1;
3225 if (tok_str
->len
&& tok_str
->str
[tok_str
->len
-1] == TOK_PLCHLDR
)
3229 tok_str_free(macro_str1
);
3232 /* return next token with macro substitution */
3233 ST_FUNC
void next(void)
3235 Sym
*nested_list
, *s
;
3237 struct macro_level
*ml
;
3240 if (parse_flags
& PARSE_FLAG_SPACES
)
3245 /* if not reading from macro substituted string, then try
3246 to substitute macros */
3247 if (tok
>= TOK_IDENT
&&
3248 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3249 s
= define_find(tok
);
3251 /* we have a macro: we try to substitute */
3255 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
3256 /* substitution done, NOTE: maybe empty */
3257 tok_str_add(&str
, 0);
3258 macro_ptr
= str
.str
;
3259 macro_ptr_allocated
= str
.str
;
3262 if (str
.len
&& str
.str
[str
.len
-1] == TOK_PLCHLDR
)
3268 /* end of macro or end of unget buffer */
3269 if (unget_buffer_enabled
) {
3270 macro_ptr
= unget_saved_macro_ptr
;
3271 unget_buffer_enabled
= 0;
3273 /* end of macro string: free it */
3274 tok_str_free(macro_ptr_allocated
);
3275 macro_ptr_allocated
= NULL
;
3279 } else if (tok
== TOK_NOSUBST
) {
3280 /* discard preprocessor's nosubst markers */
3285 /* convert preprocessor tokens into C tokens */
3286 if (tok
== TOK_PPNUM
&&
3287 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
3288 parse_number((char *)tokc
.cstr
->data
);
3292 /* push back current token and set current token to 'last_tok'. Only
3293 identifier case handled for labels. */
3294 ST_INLN
void unget_tok(int last_tok
)
3298 if (unget_buffer_enabled
)
3300 /* assert(macro_ptr == unget_saved_buffer + 1);
3301 assert(*macro_ptr == 0); */
3305 unget_saved_macro_ptr
= macro_ptr
;
3306 unget_buffer_enabled
= 1;
3308 q
= unget_saved_buffer
;
3311 n
= tok_ext_size(tok
) - 1;
3314 *q
= 0; /* end of token string */
3319 /* better than nothing, but needs extension to handle '-E' option
3321 ST_FUNC
void preprocess_init(TCCState
*s1
)
3323 s1
->include_stack_ptr
= s1
->include_stack
;
3324 /* XXX: move that before to avoid having to initialize
3325 file->ifdef_stack_ptr ? */
3326 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3327 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3330 s1
->pack_stack
[0] = 0;
3331 s1
->pack_stack_ptr
= s1
->pack_stack
;
3334 ST_FUNC
void preprocess_new(void)
3339 /* init isid table */
3341 for(i
=CH_EOF
;i
<256;i
++)
3342 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
3344 /* add all tokens */
3346 tcc_free (table_ident
);
3349 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3351 tok_ident
= TOK_IDENT
;
3360 tok_alloc(p
, r
- p
- 1);
3365 static void line_macro_output(BufferedFile
*f
, const char *s
, TCCState
*s1
)
3367 switch (s1
->Pflag
) {
3368 case LINE_MACRO_OUTPUT_FORMAT_STD
:
3369 /* "tcc -E -P1" case */
3370 fprintf(s1
->ppfp
, "# line %d \"%s\"\n", f
->line_num
, f
->filename
);
3373 case LINE_MACRO_OUTPUT_FORMAT_NONE
:
3374 /* "tcc -E -P" case: don't output a line directive */
3377 case LINE_MACRO_OUTPUT_FORMAT_GCC
:
3379 /* "tcc -E" case: a gcc standard by default */
3380 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
, s
);
3385 /* Preprocess the current file */
3386 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3388 BufferedFile
*file_ref
, **iptr
, **iptr_new
;
3392 preprocess_init(s1
);
3393 ch
= file
->buf_ptr
[0];
3394 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3395 parse_flags
&= PARSE_FLAG_ASM_FILE
;
3396 parse_flags
|= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_LINEFEED
| PARSE_FLAG_SPACES
;
3400 iptr
= s1
->include_stack_ptr
;
3404 if (tok
== TOK_EOF
) {
3406 } else if (file
!= file_ref
) {
3408 line_macro_output(file_ref
, "", s1
);
3410 } else if (tok
== TOK_LINEFEED
) {
3415 } else if (!token_seen
) {
3416 d
= file
->line_num
- file
->line_ref
;
3417 if (file
!= file_ref
|| d
>= 8) {
3420 if (tcc_state
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_GCC
) {
3421 iptr_new
= s1
->include_stack_ptr
;
3422 s
= iptr_new
> iptr
? " 1"
3423 : iptr_new
< iptr
? " 2"
3424 : iptr_new
> s1
->include_stack
? " 3"
3428 line_macro_output(file
, s
, s1
);
3431 fputs("\n", s1
->ppfp
), --d
;
3433 file
->line_ref
= (file_ref
= file
)->line_num
;
3434 token_seen
= tok
!= TOK_LINEFEED
;
3438 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);