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
,
89 struct macro_level
*prev
;
93 static void next_nomacro_spc(void);
94 static void macro_subst(
98 struct macro_level
**can_read_stream
101 ST_FUNC
void skip(int c
)
104 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
108 ST_FUNC
void expect(const char *msg
)
110 tcc_error("%s expected", msg
);
113 /* ------------------------------------------------------------------------- */
114 /* CString handling */
115 static void cstr_realloc(CString
*cstr
, int new_size
)
120 size
= cstr
->size_allocated
;
122 size
= 8; /* no need to allocate a too small first string */
123 while (size
< new_size
)
125 data
= tcc_realloc(cstr
->data_allocated
, size
);
126 cstr
->data_allocated
= data
;
127 cstr
->size_allocated
= size
;
132 ST_FUNC
void cstr_ccat(CString
*cstr
, int ch
)
135 size
= cstr
->size
+ 1;
136 if (size
> cstr
->size_allocated
)
137 cstr_realloc(cstr
, size
);
138 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
142 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
)
154 /* add a wide char */
155 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
158 size
= cstr
->size
+ sizeof(nwchar_t
);
159 if (size
> cstr
->size_allocated
)
160 cstr_realloc(cstr
, size
);
161 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
165 ST_FUNC
void cstr_new(CString
*cstr
)
167 memset(cstr
, 0, sizeof(CString
));
170 /* free string and reset it to NULL */
171 ST_FUNC
void cstr_free(CString
*cstr
)
173 tcc_free(cstr
->data_allocated
);
177 /* reset string to empty */
178 ST_FUNC
void cstr_reset(CString
*cstr
)
184 static void add_char(CString
*cstr
, int c
)
186 if (c
== '\'' || c
== '\"' || c
== '\\') {
187 /* XXX: could be more precise if char or string */
188 cstr_ccat(cstr
, '\\');
190 if (c
>= 32 && c
<= 126) {
193 cstr_ccat(cstr
, '\\');
195 cstr_ccat(cstr
, 'n');
197 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
198 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
199 cstr_ccat(cstr
, '0' + (c
& 7));
204 /* ------------------------------------------------------------------------- */
205 /* allocate a new token */
206 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
208 TokenSym
*ts
, **ptable
;
211 if (tok_ident
>= SYM_FIRST_ANOM
)
212 tcc_error("memory full (symbols)");
214 /* expand token table if needed */
215 i
= tok_ident
- TOK_IDENT
;
216 if ((i
% TOK_ALLOC_INCR
) == 0) {
217 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
218 table_ident
= ptable
;
221 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
223 ts
->tok
= tok_ident
++;
224 ts
->sym_define
= NULL
;
225 ts
->sym_define_stack
= 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') {
451 static void handle_stray(void)
453 if (handle_stray_noerror())
454 tcc_error("stray '\\' in program");
457 /* skip the stray and handle the \\n case. Output an error if
458 incorrect char after the stray */
459 static int handle_stray1(uint8_t *p
)
463 if (p
>= file
->buf_end
) {
480 /* handle just the EOB case, but not stray */
481 #define PEEKC_EOB(c, p)\
492 /* handle the complicated stray case */
498 c = handle_stray1(p);\
503 /* input with '\[\r]\n' handling. Note that this function cannot
504 handle other characters after '\', so you cannot call it inside
505 strings or comments */
506 ST_FUNC
void minp(void)
514 /* single line C++ comments */
515 static uint8_t *parse_line_comment(uint8_t *p
)
523 if (c
== '\n' || c
== CH_EOF
) {
525 } else if (c
== '\\') {
534 } else if (c
== '\r') {
552 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
561 if (c
== '\n' || c
== '*' || c
== '\\')
565 if (c
== '\n' || c
== '*' || c
== '\\')
569 /* now we can handle all the cases */
573 } else if (c
== '*') {
579 } else if (c
== '/') {
581 } else if (c
== '\\') {
586 /* skip '\[\r]\n', otherwise just skip the stray */
592 } else if (c
== '\r') {
609 /* stray, eob or eof */
614 tcc_error("unexpected end of file in comment");
615 } else if (c
== '\\') {
627 static inline void skip_spaces(void)
633 static inline int check_space(int t
, int *spc
)
644 /* parse a string without interpreting escapes */
645 static uint8_t *parse_pp_string(uint8_t *p
,
646 int sep
, CString
*str
)
654 } else if (c
== '\\') {
660 /* XXX: indicate line number of start of string */
661 tcc_error("missing terminating %c character", sep
);
662 } else if (c
== '\\') {
663 /* escape : just skip \[\r]\n */
668 } else if (c
== '\r') {
671 expect("'\n' after '\r'");
674 } else if (c
== CH_EOF
) {
675 goto unterminated_string
;
678 cstr_ccat(str
, '\\');
684 } else if (c
== '\n') {
687 } else if (c
== '\r') {
691 cstr_ccat(str
, '\r');
707 /* skip block of text until #else, #elif or #endif. skip also pairs of
709 static void preprocess_skip(void)
711 int a
, start_of_line
, c
, in_warn_or_error
;
718 in_warn_or_error
= 0;
739 } else if (c
== '\\') {
740 ch
= file
->buf_ptr
[0];
741 handle_stray_noerror();
748 if (in_warn_or_error
)
750 p
= parse_pp_string(p
, c
, NULL
);
754 if (in_warn_or_error
)
761 p
= parse_comment(p
);
762 } else if (ch
== '/') {
763 p
= parse_line_comment(p
);
773 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
775 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
777 else if (tok
== TOK_ENDIF
)
779 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
780 in_warn_or_error
= 1;
781 else if (tok
== TOK_LINEFEED
)
783 else if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
)
784 p
= parse_line_comment(p
);
786 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
787 p
= parse_line_comment(p
);
800 /* ParseState handling */
802 /* XXX: currently, no include file info is stored. Thus, we cannot display
803 accurate messages if the function or data definition spans multiple
806 /* save current parse state in 's' */
807 ST_FUNC
void save_parse_state(ParseState
*s
)
809 s
->line_num
= file
->line_num
;
810 s
->macro_ptr
= macro_ptr
;
815 /* restore parse state from 's' */
816 ST_FUNC
void restore_parse_state(ParseState
*s
)
818 file
->line_num
= s
->line_num
;
819 macro_ptr
= s
->macro_ptr
;
824 /* return the number of additional 'ints' necessary to store the
826 static inline int tok_ext_size(int t
)
840 tcc_error("unsupported token");
847 return LDOUBLE_SIZE
/ 4;
853 /* token string handling */
855 ST_INLN
void tok_str_new(TokenString
*s
)
859 s
->allocated_len
= 0;
860 s
->last_line_num
= -1;
863 ST_FUNC
void tok_str_free(int *str
)
868 static int *tok_str_realloc(TokenString
*s
)
872 if (s
->allocated_len
== 0) {
875 len
= s
->allocated_len
* 2;
877 str
= tcc_realloc(s
->str
, len
* sizeof(int));
878 s
->allocated_len
= len
;
883 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
889 if (len
>= s
->allocated_len
)
890 str
= tok_str_realloc(s
);
895 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
902 /* allocate space for worst case */
903 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
904 str
= tok_str_realloc(s
);
913 str
[len
++] = cv
->tab
[0];
922 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
923 while ((len
+ nb_words
) > s
->allocated_len
)
924 str
= tok_str_realloc(s
);
925 cstr
= (CString
*)(str
+ len
);
927 cstr
->size
= cv
->cstr
->size
;
928 cstr
->data_allocated
= NULL
;
929 cstr
->size_allocated
= cstr
->size
;
930 memcpy((char *)cstr
+ sizeof(CString
),
931 cv
->cstr
->data
, cstr
->size
);
938 #if LDOUBLE_SIZE == 8
941 str
[len
++] = cv
->tab
[0];
942 str
[len
++] = cv
->tab
[1];
944 #if LDOUBLE_SIZE == 12
946 str
[len
++] = cv
->tab
[0];
947 str
[len
++] = cv
->tab
[1];
948 str
[len
++] = cv
->tab
[2];
949 #elif LDOUBLE_SIZE == 16
951 str
[len
++] = cv
->tab
[0];
952 str
[len
++] = cv
->tab
[1];
953 str
[len
++] = cv
->tab
[2];
954 str
[len
++] = cv
->tab
[3];
955 #elif LDOUBLE_SIZE != 8
956 #error add long double size support
965 /* add the current parse token in token string 's' */
966 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
970 /* save line number info */
971 if (file
->line_num
!= s
->last_line_num
) {
972 s
->last_line_num
= file
->line_num
;
973 cval
.i
= s
->last_line_num
;
974 tok_str_add2(s
, TOK_LINENUM
, &cval
);
976 tok_str_add2(s
, tok
, &tokc
);
979 /* get a token from an integer array and increment pointer
980 accordingly. we code it as a macro to avoid pointer aliasing. */
981 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
999 cv
->cstr
= (CString
*)p
;
1000 cv
->cstr
->data
= (char *)p
+ sizeof(CString
);
1001 p
+= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
1009 #if LDOUBLE_SIZE == 16
1011 #elif LDOUBLE_SIZE == 12
1013 #elif LDOUBLE_SIZE == 8
1016 # error add long double size support
1029 static int macro_is_equal(const int *a
, const int *b
)
1031 char buf
[STRING_MAX_SIZE
+ 1];
1035 TOK_GET(&t
, &a
, &cv
);
1036 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1037 TOK_GET(&t
, &b
, &cv
);
1038 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1044 static void define_print(Sym
*s
, int is_undef
)
1051 if (tcc_state
->dflag
== 0 || !s
|| !tcc_state
->ppfp
)
1055 c
= file
->line_num
- file
->line_ref
- 1;
1058 fputs("\n", tcc_state
->ppfp
);
1059 file
->line_ref
= file
->line_num
;
1064 fprintf(tcc_state
->ppfp
, "// #undef %s\n", get_tok_str(s
->v
, NULL
));
1068 fprintf(tcc_state
->ppfp
, "// #define %s", get_tok_str(s
->v
, NULL
));
1073 fprintf(tcc_state
->ppfp
, "%s%s", sep
, get_tok_str(arg
->v
& ~SYM_FIELD
, NULL
));
1077 fprintf(tcc_state
->ppfp
, ")");
1082 fprintf(tcc_state
->ppfp
, " ");
1085 TOK_GET(&t
, &str
, &cval
);
1088 fprintf(tcc_state
->ppfp
, "%s", get_tok_str(t
, &cval
));
1090 fprintf(tcc_state
->ppfp
, "\n");
1093 /* defines handling */
1094 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1099 if (s
&& !macro_is_equal(s
->d
, str
))
1100 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1102 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1104 s
->next
= first_arg
;
1105 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1109 /* undefined a define symbol. Its name is just set to zero */
1110 ST_FUNC
void define_undef(Sym
*s
)
1114 if (v
>= TOK_IDENT
&& v
< tok_ident
) {
1116 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 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1302 if (!macro_list_start
&& spc
== 2 && tok
== TOK_TWOSHARPS
)
1303 tcc_error("'##' invalid at start of macro");
1305 /* remove spaces around ## and after '#' */
1306 if (TOK_TWOSHARPS
== tok
) {
1310 } else if ('#' == tok
) {
1312 } else if (check_space(tok
, &spc
)) {
1315 tok_str_add2(&str
, tok
, &tokc
);
1318 macro_list_start
= 0;
1320 if (ptok
== TOK_TWOSHARPS
)
1321 tcc_error("'##' invalid at end of macro");
1323 --str
.len
; /* remove trailing space */
1324 tok_str_add(&str
, 0);
1325 define_push(v
, t
, str
.str
, first
);
1328 static inline int hash_cached_include(const char *filename
)
1330 const unsigned char *s
;
1334 s
= (unsigned char *) filename
;
1336 h
= TOK_HASH_FUNC(h
, *s
);
1339 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1343 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1347 h
= hash_cached_include(filename
);
1348 i
= s1
->cached_includes_hash
[h
];
1352 e
= s1
->cached_includes
[i
- 1];
1353 if (0 == PATHCMP(e
->filename
, filename
))
1360 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1365 if (search_cached_include(s1
, filename
))
1368 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1370 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1371 strcpy(e
->filename
, filename
);
1372 e
->ifndef_macro
= ifndef_macro
;
1373 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1374 /* add in hash table */
1375 h
= hash_cached_include(filename
);
1376 e
->hash_next
= s1
->cached_includes_hash
[h
];
1377 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1380 static void pragma_parse(TCCState
*s1
)
1385 if (tok
== TOK_pack
) {
1388 #pragma pack(1) // set
1389 #pragma pack() // reset to default
1390 #pragma pack(push,1) // push & set
1391 #pragma pack(pop) // restore previous
1395 if (tok
== TOK_ASM_pop
) {
1397 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1399 tcc_error("out of pack stack");
1401 s1
->pack_stack_ptr
--;
1405 if (tok
== TOK_ASM_push
) {
1407 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1409 s1
->pack_stack_ptr
++;
1412 if (tok
!= TOK_CINT
) {
1414 tcc_error("invalid pack pragma");
1417 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1421 *s1
->pack_stack_ptr
= val
;
1424 } else if (tok
== TOK_comment
) {
1425 if (s1
->ms_extensions
) {
1428 if (tok
== TOK_lib
) {
1431 if (tok
!= TOK_STR
) {
1432 tcc_error("invalid library specification");
1434 int len
= strlen((char *)tokc
.cstr
->data
);
1435 char *file
= tcc_malloc(len
+ 4); /* filetype, "-l", and \0 at the end */
1436 file
[0] = TCC_FILETYPE_BINARY
;
1439 strcpy(&file
[3],(char *)tokc
.cstr
->data
);
1440 dynarray_add((void ***)&s1
->files
, &s1
->nb_files
, file
);
1445 tcc_warning("unknown specifier '%s' in #pragma comment", get_tok_str(tok
, &tokc
));
1448 tcc_warning("#pragma comment(lib) is ignored");
1450 } else if ((tok
== TOK_push_macro
) || (tok
== TOK_pop_macro
)) {
1451 int push_macro
= (tok
== TOK_push_macro
);
1454 if (tok
!= TOK_STR
) {
1457 int len
= strlen((char *)tokc
.cstr
->data
);
1458 tcc_open_bf(s1
, "<push_pop_macro>", len
);
1459 memcpy(file
->buffer
, tokc
.cstr
->data
, len
);
1460 ch
= file
->buf_ptr
[0];
1462 if (tok
>= TOK_IDENT
) {
1463 Sym
*s
= table_ident
[tok
- TOK_IDENT
]->sym_define
;
1464 Sym
*ss
= table_ident
[tok
- TOK_IDENT
]->sym_define_stack
;
1468 table_ident
[tok
- TOK_IDENT
]->sym_define_stack
= s
;
1472 table_ident
[tok
- TOK_IDENT
]->sym_define
= ss
;
1473 table_ident
[tok
- TOK_IDENT
]->sym_define_stack
= ss
->prev_tok
;
1482 tcc_warning("unknown #pragma %s", get_tok_str(tok
, &tokc
));
1486 /* is_bof is true if first non space token at beginning of file */
1487 ST_FUNC
void preprocess(int is_bof
)
1489 TCCState
*s1
= tcc_state
;
1490 int i
, c
, n
, saved_parse_flags
;
1494 saved_parse_flags
= parse_flags
;
1495 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
1496 PARSE_FLAG_LINEFEED
;
1497 parse_flags
|= (saved_parse_flags
& (PARSE_FLAG_ASM_FILE
| PARSE_FLAG_ASM_COMMENTS
));
1507 s
= define_find(tok
);
1508 /* undefine symbol by putting an invalid name */
1513 case TOK_INCLUDE_NEXT
:
1514 ch
= file
->buf_ptr
[0];
1515 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1520 } else if (ch
== '\"') {
1525 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1526 if ((q
- buf
) < sizeof(buf
) - 1)
1529 if (handle_stray_noerror() == 0)
1537 /* eat all spaces and comments after include */
1538 /* XXX: slightly incorrect */
1539 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1543 /* computed #include : either we have only strings or
1544 we have anything enclosed in '<>' */
1547 if (tok
== TOK_STR
) {
1548 while (tok
!= TOK_LINEFEED
) {
1549 if (tok
!= TOK_STR
) {
1551 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1553 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1559 while (tok
!= TOK_LINEFEED
) {
1560 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1564 /* check syntax and remove '<>' */
1565 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1566 goto include_syntax
;
1567 memmove(buf
, buf
+ 1, len
- 2);
1568 buf
[len
- 2] = '\0';
1573 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1574 tcc_error("#include recursion too deep");
1575 /* store current file in stack, but increment stack later below */
1576 *s1
->include_stack_ptr
= file
;
1578 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1579 for (i
= -2; i
< n
; ++i
) {
1580 char buf1
[sizeof file
->filename
];
1586 /* check absolute include path */
1587 if (!IS_ABSPATH(buf
))
1590 i
= n
; /* force end loop */
1592 } else if (i
== -1) {
1593 /* search in current dir if "header.h" */
1596 path
= file
->filename
;
1597 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1600 /* search in all the include paths */
1601 if (i
< s1
->nb_include_paths
)
1602 path
= s1
->include_paths
[i
];
1604 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1605 pstrcpy(buf1
, sizeof(buf1
), path
);
1606 pstrcat(buf1
, sizeof(buf1
), "/");
1609 pstrcat(buf1
, sizeof(buf1
), buf
);
1611 if (tok
== TOK_INCLUDE_NEXT
)
1612 for (f
= s1
->include_stack_ptr
; f
>= s1
->include_stack
; --f
)
1613 if (0 == PATHCMP((*f
)->filename
, buf1
)) {
1615 printf("%s: #include_next skipping %s\n", file
->filename
, buf1
);
1617 goto include_trynext
;
1620 e
= search_cached_include(s1
, buf1
);
1621 if (e
&& define_find(e
->ifndef_macro
)) {
1622 /* no need to parse the include because the 'ifndef macro'
1625 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1630 if (tcc_open(s1
, buf1
) < 0)
1635 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1637 /* update target deps */
1638 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1640 /* push current file in stack */
1641 ++s1
->include_stack_ptr
;
1642 /* add include file debug info */
1644 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1645 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1646 ch
= file
->buf_ptr
[0];
1649 tcc_error("include file '%s' not found", buf
);
1656 c
= expr_preprocess();
1662 if (tok
< TOK_IDENT
)
1663 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1667 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1669 file
->ifndef_macro
= tok
;
1672 c
= (define_find(tok
) != 0) ^ c
;
1674 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1675 tcc_error("memory full (ifdef)");
1676 *s1
->ifdef_stack_ptr
++ = c
;
1679 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1680 tcc_error("#else without matching #if");
1681 if (s1
->ifdef_stack_ptr
[-1] & 2)
1682 tcc_error("#else after #else");
1683 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1686 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1687 tcc_error("#elif without matching #if");
1688 c
= s1
->ifdef_stack_ptr
[-1];
1690 tcc_error("#elif after #else");
1691 /* last #if/#elif expression was true: we skip */
1694 c
= expr_preprocess();
1695 s1
->ifdef_stack_ptr
[-1] = c
;
1697 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1698 file
->ifndef_macro
= 0;
1708 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1709 tcc_error("#endif without matching #if");
1710 s1
->ifdef_stack_ptr
--;
1711 /* '#ifndef macro' was at the start of file. Now we check if
1712 an '#endif' is exactly at the end of file */
1713 if (file
->ifndef_macro
&&
1714 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1715 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1716 /* need to set to zero to avoid false matches if another
1717 #ifndef at middle of file */
1718 file
->ifndef_macro
= 0;
1719 while (tok
!= TOK_LINEFEED
)
1721 tok_flags
|= TOK_FLAG_ENDIF
;
1727 if (tok
!= TOK_CINT
)
1728 tcc_error("A #line format is wrong");
1730 if (tok
!= TOK_CINT
) {
1731 char *p
= tokc
.cstr
->data
;
1732 tokc
.i
= strtoul(p
, (char **)&p
, 10);
1735 file
->line_num
= tokc
.i
- 1;
1737 if (tok
!= TOK_LINEFEED
) {
1738 if (tok
!= TOK_STR
) {
1739 if ((parse_flags
& PARSE_FLAG_ASM_COMMENTS
) == 0) {
1741 tcc_error("#line format is wrong");
1745 pstrcpy(file
->filename
, sizeof(file
->filename
),
1746 (char *)tokc
.cstr
->data
);
1749 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1754 ch
= file
->buf_ptr
[0];
1757 while (ch
!= '\n' && ch
!= CH_EOF
) {
1758 if ((q
- buf
) < sizeof(buf
) - 1)
1761 if (handle_stray_noerror() == 0)
1768 tcc_error("#error %s", buf
);
1770 tcc_warning("#warning %s", buf
);
1776 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_PPNUM
) {
1777 /* '!' is ignored to allow C scripts. numbers are ignored
1778 to emulate cpp behaviour */
1780 if (!(parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
1781 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1783 /* this is a gas line comment in an 'S' file. */
1784 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1790 /* ignore other preprocess commands or #! for C scripts */
1791 while (tok
!= TOK_LINEFEED
)
1794 parse_flags
= saved_parse_flags
;
1797 /* evaluate escape codes in a string. */
1798 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1813 case '0': case '1': case '2': case '3':
1814 case '4': case '5': case '6': case '7':
1815 /* at most three octal digits */
1820 n
= n
* 8 + c
- '0';
1824 n
= n
* 8 + c
- '0';
1829 goto add_char_nonext
;
1837 if (c
>= 'a' && c
<= 'f')
1839 else if (c
>= 'A' && c
<= 'F')
1849 goto add_char_nonext
;
1873 goto invalid_escape
;
1883 if (c
>= '!' && c
<= '~')
1884 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1886 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1893 cstr_ccat(outstr
, c
);
1895 cstr_wccat(outstr
, c
);
1897 /* add a trailing '\0' */
1899 cstr_ccat(outstr
, '\0');
1901 cstr_wccat(outstr
, '\0');
1904 /* we use 64 bit numbers */
1907 /* bn = (bn << shift) | or_val */
1908 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
1912 for(i
=0;i
<BN_SIZE
;i
++) {
1914 bn
[i
] = (v
<< shift
) | or_val
;
1915 or_val
= v
>> (32 - shift
);
1919 static void bn_zero(unsigned int *bn
)
1922 for(i
=0;i
<BN_SIZE
;i
++) {
1927 /* parse number in null terminated string 'p' and return it in the
1929 static void parse_number(const char *p
)
1931 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
1933 unsigned int bn
[BN_SIZE
];
1944 goto float_frac_parse
;
1945 } else if (t
== '0') {
1946 if (ch
== 'x' || ch
== 'X') {
1950 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
1956 /* parse all digits. cannot check octal numbers at this stage
1957 because of floating point constants */
1959 if (ch
>= 'a' && ch
<= 'f')
1961 else if (ch
>= 'A' && ch
<= 'F')
1969 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
1971 tcc_error("number too long");
1977 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
1978 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
1980 /* NOTE: strtox should support that for hexa numbers, but
1981 non ISOC99 libcs do not support it, so we prefer to do
1983 /* hexadecimal or binary floats */
1984 /* XXX: handle overflows */
1996 } else if (t
>= 'a') {
1998 } else if (t
>= 'A') {
2003 bn_lshift(bn
, shift
, t
);
2010 if (t
>= 'a' && t
<= 'f') {
2012 } else if (t
>= 'A' && t
<= 'F') {
2014 } else if (t
>= '0' && t
<= '9') {
2020 tcc_error("invalid digit");
2021 bn_lshift(bn
, shift
, t
);
2026 if (ch
!= 'p' && ch
!= 'P')
2033 } else if (ch
== '-') {
2037 if (ch
< '0' || ch
> '9')
2038 expect("exponent digits");
2039 while (ch
>= '0' && ch
<= '9') {
2040 exp_val
= exp_val
* 10 + ch
- '0';
2043 exp_val
= exp_val
* s
;
2045 /* now we can generate the number */
2046 /* XXX: should patch directly float number */
2047 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2048 d
= ldexp(d
, exp_val
- frac_bits
);
2053 /* float : should handle overflow */
2055 } else if (t
== 'L') {
2057 #ifdef TCC_TARGET_PE
2062 /* XXX: not large enough */
2063 tokc
.ld
= (long double)d
;
2070 /* decimal floats */
2072 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2077 while (ch
>= '0' && ch
<= '9') {
2078 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2084 if (ch
== 'e' || ch
== 'E') {
2085 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2089 if (ch
== '-' || ch
== '+') {
2090 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2095 if (ch
< '0' || ch
> '9')
2096 expect("exponent digits");
2097 while (ch
>= '0' && ch
<= '9') {
2098 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2110 tokc
.f
= strtof(token_buf
, NULL
);
2111 } else if (t
== 'L') {
2113 #ifdef TCC_TARGET_PE
2115 tokc
.d
= strtod(token_buf
, NULL
);
2118 tokc
.ld
= strtold(token_buf
, NULL
);
2122 tokc
.d
= strtod(token_buf
, NULL
);
2126 unsigned long long n
, n1
;
2127 int lcount
, ucount
, must_64bit
;
2130 /* integer number */
2133 if (b
== 10 && *q
== '0') {
2140 /* no need for checks except for base 10 / 8 errors */
2150 tcc_error("invalid digit");
2153 /* detect overflow */
2154 /* XXX: this test is not reliable */
2156 tcc_error("integer constant overflow");
2159 /* Determine the characteristics (unsigned and/or 64bit) the type of
2160 the constant must have according to the constant suffix(es) */
2161 lcount
= ucount
= must_64bit
= 0;
2167 tcc_error("three 'l's in integer constant");
2168 if (lcount
&& *(p
- 1) != ch
)
2169 tcc_error("incorrect integer suffix: %s", p1
);
2171 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2176 } else if (t
== 'U') {
2178 tcc_error("two 'u's in integer constant");
2186 /* Whether 64 bits are needed to hold the constant's value */
2187 if (n
& 0xffffffff00000000LL
|| must_64bit
) {
2195 /* Whether type must be unsigned to hold the constant's value */
2196 if (ucount
|| ((n1
>> 31) && (b
!= 10))) {
2197 if (tok
== TOK_CLLONG
)
2201 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2202 } else if (n1
>> 31) {
2203 if (tok
== TOK_CINT
)
2206 tcc_error("integer constant overflow");
2209 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2215 tcc_error("invalid number\n");
2219 #define PARSE2(c1, tok1, c2, tok2) \
2230 /* return next token without macro substitution */
2231 static inline void next_nomacro1(void)
2246 goto keep_tok_flags
;
2253 /* first look if it is in fact an end of buffer */
2254 if (p
>= file
->buf_end
) {
2258 if (p
>= file
->buf_end
)
2271 TCCState
*s1
= tcc_state
;
2272 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2273 && !(tok_flags
& TOK_FLAG_EOF
)) {
2274 tok_flags
|= TOK_FLAG_EOF
;
2276 goto keep_tok_flags
;
2277 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2279 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2280 tcc_error("missing #endif");
2281 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2282 /* no include left : end of file. */
2285 tok_flags
&= ~TOK_FLAG_EOF
;
2286 /* pop include file */
2288 /* test if previous '#endif' was after a #ifdef at
2290 if (tok_flags
& TOK_FLAG_ENDIF
) {
2292 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2294 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2295 tok_flags
&= ~TOK_FLAG_ENDIF
;
2298 /* add end of include file debug info */
2299 if (tcc_state
->do_debug
) {
2300 put_stabd(N_EINCL
, 0, 0);
2302 /* pop include stack */
2304 s1
->include_stack_ptr
--;
2313 tok_flags
|= TOK_FLAG_BOL
;
2316 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2319 goto keep_tok_flags
;
2324 if (is_space(c
) && (parse_flags
& PARSE_FLAG_ASM_FILE
)) {
2325 p
= parse_line_comment(p
);
2329 if ((tok_flags
& TOK_FLAG_BOL
) &&
2330 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2332 preprocess(tok_flags
& TOK_FLAG_BOF
);
2338 tok
= TOK_TWOSHARPS
;
2340 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
2341 p
= parse_line_comment(p
- 1);
2350 /* dollar is allowed to start identifiers when not parsing asm */
2352 if (!tcc_state
->dollars_in_identifiers
2353 || (parse_flags
& PARSE_FLAG_ASM_FILE
)) goto parse_simple
;
2355 case 'a': case 'b': case 'c': case 'd':
2356 case 'e': case 'f': case 'g': case 'h':
2357 case 'i': case 'j': case 'k': case 'l':
2358 case 'm': case 'n': case 'o': case 'p':
2359 case 'q': case 'r': case 's': case 't':
2360 case 'u': case 'v': case 'w': case 'x':
2362 case 'A': case 'B': case 'C': case 'D':
2363 case 'E': case 'F': case 'G': case 'H':
2364 case 'I': case 'J': case 'K':
2365 case 'M': case 'N': case 'O': case 'P':
2366 case 'Q': case 'R': case 'S': case 'T':
2367 case 'U': case 'V': case 'W': case 'X':
2373 h
= TOK_HASH_FUNC(h
, c
);
2377 if (!isidnum_table
[c
-CH_EOF
]
2378 && (tcc_state
->dollars_in_identifiers
? (c
!= '$') : 1))
2380 h
= TOK_HASH_FUNC(h
, c
);
2387 /* fast case : no stray found, so we have the full token
2388 and we have already hashed it */
2390 h
&= (TOK_HASH_SIZE
- 1);
2391 pts
= &hash_ident
[h
];
2396 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2398 pts
= &(ts
->hash_next
);
2400 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2404 cstr_reset(&tokcstr
);
2407 cstr_ccat(&tokcstr
, *p1
);
2413 while (isidnum_table
[c
-CH_EOF
]
2414 || (tcc_state
->dollars_in_identifiers
? (c
== '$') : 0)) {
2415 cstr_ccat(&tokcstr
, c
);
2418 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2424 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2426 goto parse_ident_fast
;
2429 if (c
== '\'' || c
== '\"') {
2433 cstr_reset(&tokcstr
);
2434 cstr_ccat(&tokcstr
, 'L');
2435 goto parse_ident_slow
;
2439 case '0': case '1': case '2': case '3':
2440 case '4': case '5': case '6': case '7':
2443 cstr_reset(&tokcstr
);
2444 /* after the first digit, accept digits, alpha, '.' or sign if
2445 prefixed by 'eEpP' */
2449 cstr_ccat(&tokcstr
, c
);
2451 if (!(isnum(c
) || isid(c
) || c
== '.' ||
2452 ((c
== '+' || c
== '-') &&
2453 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
2456 /* We add a trailing '\0' to ease parsing */
2457 cstr_ccat(&tokcstr
, '\0');
2458 tokc
.cstr
= &tokcstr
;
2462 /* special dot handling because it can also start a number */
2465 cstr_reset(&tokcstr
);
2466 cstr_ccat(&tokcstr
, '.');
2468 } else if (c
== '.') {
2471 if ((parse_flags
& PARSE_FLAG_ASM_COMMENTS
) == 0)
2492 /* parse the string */
2494 p
= parse_pp_string(p
, sep
, &str
);
2495 cstr_ccat(&str
, '\0');
2497 /* eval the escape (should be done as TOK_PPNUM) */
2498 cstr_reset(&tokcstr
);
2499 parse_escape_string(&tokcstr
, str
.data
, is_long
);
2504 /* XXX: make it portable */
2508 char_size
= sizeof(nwchar_t
);
2509 if (tokcstr
.size
<= char_size
)
2510 tcc_error("empty character constant");
2511 if (tokcstr
.size
> 2 * char_size
)
2512 tcc_warning("multi-character character constant");
2514 tokc
.i
= *(int8_t *)tokcstr
.data
;
2517 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2521 tokc
.cstr
= &tokcstr
;
2535 } else if (c
== '<') {
2553 } else if (c
== '>') {
2571 } else if (c
== '=') {
2584 } else if (c
== '=') {
2597 } else if (c
== '=') {
2610 } else if (c
== '=') {
2613 } else if (c
== '>') {
2621 PARSE2('!', '!', '=', TOK_NE
)
2622 PARSE2('=', '=', '=', TOK_EQ
)
2623 PARSE2('*', '*', '=', TOK_A_MUL
)
2624 PARSE2('%', '%', '=', TOK_A_MOD
)
2625 PARSE2('^', '^', '=', TOK_A_XOR
)
2627 /* comments or operator */
2631 p
= parse_comment(p
);
2632 /* comments replaced by a blank */
2634 goto keep_tok_flags
;
2635 } else if (c
== '/') {
2636 p
= parse_line_comment(p
);
2638 goto keep_tok_flags
;
2639 } else if (c
== '=') {
2659 case '@': /* only used in assembler */
2665 if ((parse_flags
& PARSE_FLAG_ASM_FILE
) == 0)
2666 tcc_error("unrecognized character \\x%02x", c
);
2676 #if defined(PARSE_DEBUG)
2677 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2681 /* return next token without macro substitution. Can read input from
2683 static void next_nomacro_spc(void)
2689 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2690 if (tok
== TOK_LINENUM
) {
2691 file
->line_num
= tokc
.i
;
2700 ST_FUNC
void next_nomacro(void)
2704 } while (is_space(tok
));
2707 /* substitute arguments in replacement lists in macro_str by the values in
2708 args (field d) and return allocated string */
2709 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2711 int last_tok
, t
, spc
;
2721 TOK_GET(&t
, ¯o_str
, &cval
);
2726 TOK_GET(&t
, ¯o_str
, &cval
);
2729 s
= sym_find2(args
, t
);
2735 TOK_GET(&t
, &st
, &cval
);
2736 if (!check_space(t
, &spc
))
2737 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2740 cstr_ccat(&cstr
, '\0');
2742 printf("stringize: %s\n", (char *)cstr
.data
);
2746 tok_str_add2(&str
, TOK_STR
, &cval
);
2749 tok_str_add2(&str
, t
, &cval
);
2751 } else if (t
>= TOK_IDENT
) {
2752 s
= sym_find2(args
, t
);
2755 /* if '##' is present before or after, no arg substitution */
2756 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
2757 /* special case for var arg macros : ## eats the
2758 ',' if empty VA_ARGS variable. */
2759 /* XXX: test of the ',' is not 100%
2760 reliable. should fix it to avoid security
2762 if (gnu_ext
&& s
->type
.t
&&
2763 last_tok
== TOK_TWOSHARPS
&&
2764 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
2765 if (*st
== TOK_PLCHLDR
) {
2766 /* suppress ',' '##' */
2769 /* suppress '##' and add variable */
2777 TOK_GET(&t1
, &st
, &cval
);
2780 tok_str_add2(&str
, t1
, &cval
);
2783 } else if (*st
!= TOK_PLCHLDR
) {
2784 /* NOTE: the stream cannot be read when macro
2785 substituing an argument */
2786 macro_subst(&str
, nested_list
, st
, NULL
);
2789 tok_str_add(&str
, t
);
2792 tok_str_add2(&str
, t
, &cval
);
2796 tok_str_add(&str
, 0);
2800 static char const ab_month_name
[12][4] =
2802 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2803 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2806 /* do macro substitution of current token with macro 's' and add
2807 result to (tok_str,tok_len). 'nested_list' is the list of all
2808 macros we got inside to avoid recursing. Return non zero if no
2809 substitution needs to be done */
2810 static int macro_subst_tok(TokenString
*tok_str
,
2811 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
2813 Sym
*args
, *sa
, *sa1
;
2814 int mstr_allocated
, parlevel
, *mstr
, t
, t1
, spc
;
2822 /* if symbol is a macro, prepare substitution */
2823 /* special macros */
2824 if (tok
== TOK___LINE__
) {
2825 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2829 } else if (tok
== TOK___FILE__
) {
2830 cstrval
= file
->filename
;
2832 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2837 tm
= localtime(&ti
);
2838 if (tok
== TOK___DATE__
) {
2839 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2840 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2842 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2843 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2850 cstr_cat(&cstr
, cstrval
);
2851 cstr_ccat(&cstr
, '\0');
2853 tok_str_add2(tok_str
, t1
, &cval
);
2858 if (s
->type
.t
== MACRO_FUNC
) {
2859 /* NOTE: we do not use next_nomacro to avoid eating the
2860 next token. XXX: find better solution */
2864 while (is_space(t
= *p
) || TOK_LINEFEED
== t
)
2866 if (t
== 0 && can_read_stream
) {
2867 /* end of macro stream: we must look at the token
2868 after in the file */
2869 struct macro_level
*ml
= *can_read_stream
;
2875 *can_read_stream
= ml
-> prev
;
2877 /* also, end of scope for nested defined symbol */
2878 (*nested_list
)->v
= -1;
2882 ch
= file
->buf_ptr
[0];
2883 while (is_space(ch
) || ch
== '\n' || ch
== '/')
2888 uint8_t *p
= file
->buf_ptr
;
2891 p
= parse_comment(p
);
2892 file
->buf_ptr
= p
- 1;
2893 } else if (c
== '/') {
2894 p
= parse_line_comment(p
);
2895 file
->buf_ptr
= p
- 1;
2903 if (t
!= '(') /* no macro subst */
2906 /* argument macro */
2911 /* NOTE: empty args are allowed, except if no args */
2913 /* handle '()' case */
2914 if (!args
&& !sa
&& tok
== ')')
2917 tcc_error("macro '%s' used with too many args",
2918 get_tok_str(s
->v
, 0));
2921 /* NOTE: non zero sa->t indicates VA_ARGS */
2922 while ((parlevel
> 0 ||
2924 (tok
!= ',' || sa
->type
.t
))) &&
2928 else if (tok
== ')')
2930 if (tok
== TOK_LINEFEED
)
2932 if (!check_space(tok
, &spc
))
2933 tok_str_add2(&str
, tok
, &tokc
);
2937 tok_str_add(&str
, TOK_PLCHLDR
);
2939 tok_str_add(&str
, 0);
2940 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
2944 /* special case for gcc var args: add an empty
2945 var arg argument if it is omitted */
2946 if (sa
&& sa
->type
.t
&& gnu_ext
)
2956 tcc_error("macro '%s' used with too few args",
2957 get_tok_str(s
->v
, 0));
2960 /* now subst each arg */
2961 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
2966 tok_str_free(sa
->d
);
2972 sym_push2(nested_list
, s
->v
, 0, 0);
2973 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
2974 /* pop nested defined symbol */
2976 *nested_list
= sa1
->prev
;
2984 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2985 return the resulting string (which must be freed). */
2986 static inline int *macro_twosharps(const int *macro_str
)
2990 TokenString macro_str1
;
2992 int n
, start_of_nosubsts
;
2994 /* we search the first '##' */
2995 for(ptr
= macro_str
;;) {
2997 TOK_GET(&t
, &ptr
, &cval
);
2998 if (t
== TOK_TWOSHARPS
)
3000 /* nothing more to do if end of string */
3005 /* we saw '##', so we need more processing to handle it */
3006 start_of_nosubsts
= -1;
3007 tok_str_new(¯o_str1
);
3008 for(ptr
= macro_str
;;) {
3009 TOK_GET(&tok
, &ptr
, &tokc
);
3012 if (tok
== TOK_TWOSHARPS
)
3014 if (tok
== TOK_NOSUBST
&& start_of_nosubsts
< 0)
3015 start_of_nosubsts
= macro_str1
.len
;
3016 while (*ptr
== TOK_TWOSHARPS
) {
3017 /* given 'a##b', remove nosubsts preceding 'a' */
3018 if (start_of_nosubsts
>= 0)
3019 macro_str1
.len
= start_of_nosubsts
;
3020 /* given 'a##b', skip '##' */
3022 /* given 'a##b', remove nosubsts preceding 'b' */
3023 while (t
== TOK_NOSUBST
)
3025 if (t
&& t
!= TOK_TWOSHARPS
) {
3027 TOK_GET(&t
, &ptr
, &cval
);
3028 /* We concatenate the two tokens */
3030 if (tok
!= TOK_PLCHLDR
)
3031 cstr_cat(&cstr
, get_tok_str(tok
, &tokc
));
3033 if (t
!= TOK_PLCHLDR
|| tok
== TOK_PLCHLDR
)
3034 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3035 cstr_ccat(&cstr
, '\0');
3037 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3038 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3041 if (0 == *file
->buf_ptr
)
3043 tok_str_add2(¯o_str1
, tok
, &tokc
);
3044 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
3045 n
, cstr
.data
, (char*)cstr
.data
+ n
);
3051 if (tok
!= TOK_NOSUBST
) {
3052 tok_str_add2(¯o_str1
, tok
, &tokc
);
3054 start_of_nosubsts
= -1;
3056 tok_str_add2(¯o_str1
, tok
, &tokc
);
3058 tok_str_add(¯o_str1
, 0);
3059 return macro_str1
.str
;
3063 /* do macro substitution of macro_str and add result to
3064 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3065 inside to avoid recursing. */
3066 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
3067 const int *macro_str
, struct macro_level
** can_read_stream
)
3074 struct macro_level ml
;
3077 /* first scan for '##' operator handling */
3079 macro_str1
= macro_twosharps(ptr
);
3087 /* NOTE: ptr == NULL can only happen if tokens are read from
3088 file stream due to a macro function call */
3091 TOK_GET(&t
, &ptr
, &cval
);
3094 if (t
== TOK_NOSUBST
) {
3095 /* following token has already been subst'd. just copy it on */
3096 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3097 TOK_GET(&t
, &ptr
, &cval
);
3102 /* if nested substitution, do nothing */
3103 if (sym_find2(*nested_list
, t
)) {
3104 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3105 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3109 if (can_read_stream
)
3110 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
3111 macro_ptr
= (int *)ptr
;
3113 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
3114 ptr
= (int *)macro_ptr
;
3116 if (can_read_stream
&& *can_read_stream
== &ml
)
3117 *can_read_stream
= ml
.prev
;
3120 if (parse_flags
& PARSE_FLAG_SPACES
)
3125 tok_str_add(tok_str
, ' ');
3129 if (!check_space(t
, &spc
))
3130 tok_str_add2(tok_str
, t
, &cval
);
3134 tok_str_free(macro_str1
);
3137 /* return next token with macro substitution */
3138 ST_FUNC
void next(void)
3140 Sym
*nested_list
, *s
;
3142 struct macro_level
*ml
;
3145 if (parse_flags
& PARSE_FLAG_SPACES
)
3150 /* if not reading from macro substituted string, then try
3151 to substitute macros */
3152 if (tok
>= TOK_IDENT
&&
3153 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3154 s
= define_find(tok
);
3156 /* we have a macro: we try to substitute */
3160 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
3161 /* substitution done, NOTE: maybe empty */
3162 tok_str_add(&str
, 0);
3163 macro_ptr
= str
.str
;
3164 macro_ptr_allocated
= str
.str
;
3171 /* end of macro or end of unget buffer */
3172 if (unget_buffer_enabled
) {
3173 macro_ptr
= unget_saved_macro_ptr
;
3174 unget_buffer_enabled
= 0;
3176 /* end of macro string: free it */
3177 tok_str_free(macro_ptr_allocated
);
3178 macro_ptr_allocated
= NULL
;
3182 } else if (tok
== TOK_NOSUBST
) {
3183 /* discard preprocessor's nosubst markers */
3188 /* convert preprocessor tokens into C tokens */
3189 if (tok
== TOK_PPNUM
&&
3190 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
3191 parse_number((char *)tokc
.cstr
->data
);
3195 /* push back current token and set current token to 'last_tok'. Only
3196 identifier case handled for labels. */
3197 ST_INLN
void unget_tok(int last_tok
)
3201 if (unget_buffer_enabled
)
3203 /* assert(macro_ptr == unget_saved_buffer + 1);
3204 assert(*macro_ptr == 0); */
3208 unget_saved_macro_ptr
= macro_ptr
;
3209 unget_buffer_enabled
= 1;
3211 q
= unget_saved_buffer
;
3214 n
= tok_ext_size(tok
) - 1;
3217 *q
= 0; /* end of token string */
3222 /* better than nothing, but needs extension to handle '-E' option
3224 ST_FUNC
void preprocess_init(TCCState
*s1
)
3226 s1
->include_stack_ptr
= s1
->include_stack
;
3227 /* XXX: move that before to avoid having to initialize
3228 file->ifdef_stack_ptr ? */
3229 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3230 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3233 s1
->pack_stack
[0] = 0;
3234 s1
->pack_stack_ptr
= s1
->pack_stack
;
3237 ST_FUNC
void preprocess_new(void)
3242 /* init isid table */
3244 for(i
=CH_EOF
;i
<256;i
++)
3245 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
3247 /* add all tokens */
3249 tcc_free (table_ident
);
3252 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3254 tok_ident
= TOK_IDENT
;
3263 tok_alloc(p
, r
- p
- 1);
3268 static void line_macro_output(BufferedFile
*f
, const char *s
, TCCState
*s1
)
3270 switch (s1
->Pflag
) {
3271 case LINE_MACRO_OUTPUT_FORMAT_STD
:
3272 /* "tcc -E -P1" case */
3273 fprintf(s1
->ppfp
, "# line %d \"%s\"\n", f
->line_num
, f
->filename
);
3276 case LINE_MACRO_OUTPUT_FORMAT_NONE
:
3277 /* "tcc -E -P" case: don't output a line directive */
3280 case LINE_MACRO_OUTPUT_FORMAT_GCC
:
3282 /* "tcc -E" case: a gcc standard by default */
3283 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
, s
);
3288 /* Preprocess the current file */
3289 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3291 BufferedFile
*file_ref
, **iptr
, **iptr_new
;
3295 preprocess_init(s1
);
3296 ch
= file
->buf_ptr
[0];
3297 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3298 parse_flags
= (parse_flags
& PARSE_FLAG_ASM_FILE
);
3299 parse_flags
|= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
3300 PARSE_FLAG_LINEFEED
| PARSE_FLAG_SPACES
;
3304 iptr
= s1
->include_stack_ptr
;
3308 if (tok
== TOK_EOF
) {
3310 } else if (file
!= file_ref
) {
3312 line_macro_output(file_ref
, "", s1
);
3314 } else if (tok
== TOK_LINEFEED
) {
3319 } else if (!token_seen
) {
3320 d
= file
->line_num
- file
->line_ref
;
3321 if (file
!= file_ref
|| d
>= 8) {
3324 if (tcc_state
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_GCC
) {
3325 iptr_new
= s1
->include_stack_ptr
;
3326 s
= iptr_new
> iptr
? " 1"
3327 : iptr_new
< iptr
? " 2"
3328 : iptr_new
> s1
->include_stack
? " 3"
3332 line_macro_output(file
, s
, s1
);
3335 fputs("\n", s1
->ppfp
), --d
;
3337 file
->line_ref
= (file_ref
= file
)->line_num
;
3338 token_seen
= tok
!= TOK_LINEFEED
;
3342 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);