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 TokenSym
*hash_ident
[TOK_HASH_SIZE
];
44 static char token_buf
[STRING_MAX_SIZE
+ 1];
45 static unsigned char isidnum_table
[256 - CH_EOF
];
46 /* isidnum_table flags: */
51 static TokenString
*macro_stack
;
53 static const char tcc_keywords
[] =
54 #define DEF(id, str) str "\0"
59 /* WARNING: the content of this string encodes token numbers */
60 static const unsigned char tok_two_chars
[] =
62 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
63 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
84 '.','.', 0xa8, // C++ token ?
85 '#','#', TOK_TWOSHARPS
,
89 static void next_nomacro_spc(void);
91 ST_FUNC
void skip(int c
)
94 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
98 ST_FUNC
void expect(const char *msg
)
100 tcc_error("%s expected", msg
);
103 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
106 str
->prev
= macro_stack
;
107 str
->prev_ptr
= macro_ptr
;
108 macro_ptr
= str
->str
;
112 ST_FUNC
void end_macro(void)
114 TokenString
*str
= macro_stack
;
115 macro_stack
= str
->prev
;
116 macro_ptr
= str
->prev_ptr
;
117 if (str
->alloc
== 2) {
118 str
->alloc
= 3; /* just mark as finished */
120 tok_str_free(str
->str
);
126 /* ------------------------------------------------------------------------- */
127 /* CString handling */
128 static void cstr_realloc(CString
*cstr
, int new_size
)
133 size
= cstr
->size_allocated
;
135 size
= 8; /* no need to allocate a too small first string */
136 while (size
< new_size
)
138 data
= tcc_realloc(cstr
->data_allocated
, size
);
139 cstr
->data_allocated
= data
;
140 cstr
->size_allocated
= size
;
145 ST_FUNC
void cstr_ccat(CString
*cstr
, int ch
)
148 size
= cstr
->size
+ 1;
149 if (size
> cstr
->size_allocated
)
150 cstr_realloc(cstr
, size
);
151 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
155 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
)
167 /* add a wide char */
168 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
171 size
= cstr
->size
+ sizeof(nwchar_t
);
172 if (size
> cstr
->size_allocated
)
173 cstr_realloc(cstr
, size
);
174 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
178 ST_FUNC
void cstr_new(CString
*cstr
)
180 memset(cstr
, 0, sizeof(CString
));
183 /* free string and reset it to NULL */
184 ST_FUNC
void cstr_free(CString
*cstr
)
186 tcc_free(cstr
->data_allocated
);
190 /* reset string to empty */
191 ST_FUNC
void cstr_reset(CString
*cstr
)
197 static void add_char(CString
*cstr
, int c
)
199 if (c
== '\'' || c
== '\"' || c
== '\\') {
200 /* XXX: could be more precise if char or string */
201 cstr_ccat(cstr
, '\\');
203 if (c
>= 32 && c
<= 126) {
206 cstr_ccat(cstr
, '\\');
208 cstr_ccat(cstr
, 'n');
210 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
211 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
212 cstr_ccat(cstr
, '0' + (c
& 7));
217 /* ------------------------------------------------------------------------- */
218 /* allocate a new token */
219 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
221 TokenSym
*ts
, **ptable
;
224 if (tok_ident
>= SYM_FIRST_ANOM
)
225 tcc_error("memory full (symbols)");
227 /* expand token table if needed */
228 i
= tok_ident
- TOK_IDENT
;
229 if ((i
% TOK_ALLOC_INCR
) == 0) {
230 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
231 table_ident
= ptable
;
234 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
236 ts
->tok
= tok_ident
++;
237 ts
->sym_define
= NULL
;
238 ts
->sym_label
= NULL
;
239 ts
->sym_struct
= NULL
;
240 ts
->sym_identifier
= NULL
;
242 ts
->hash_next
= NULL
;
243 memcpy(ts
->str
, str
, len
);
249 #define TOK_HASH_INIT 1
250 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
252 /* find a token and add it if not found */
253 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
261 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
262 h
&= (TOK_HASH_SIZE
- 1);
264 pts
= &hash_ident
[h
];
269 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
271 pts
= &(ts
->hash_next
);
273 return tok_alloc_new(pts
, str
, len
);
276 /* XXX: buffer overflow */
277 /* XXX: float tokens */
278 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
280 static char buf
[STRING_MAX_SIZE
+ 1];
281 static CString cstr_buf
;
286 /* NOTE: to go faster, we give a fixed buffer for small strings */
287 cstr_reset(&cstr_buf
);
289 cstr_buf
.size_allocated
= sizeof(buf
);
295 /* XXX: not quite exact, but only useful for testing */
296 sprintf(p
, "%u", cv
->ui
);
300 /* XXX: not quite exact, but only useful for testing */
302 sprintf(p
, "%u", (unsigned)cv
->ull
);
304 sprintf(p
, "%llu", cv
->ull
);
308 cstr_ccat(&cstr_buf
, 'L');
310 cstr_ccat(&cstr_buf
, '\'');
311 add_char(&cstr_buf
, cv
->i
);
312 cstr_ccat(&cstr_buf
, '\'');
313 cstr_ccat(&cstr_buf
, '\0');
317 return (char*)cv
->cstr
->data
;
319 cstr_ccat(&cstr_buf
, 'L');
322 cstr_ccat(&cstr_buf
, '\"');
324 len
= cstr
->size
- 1;
326 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
328 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
330 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
332 cstr_ccat(&cstr_buf
, '\"');
333 cstr_ccat(&cstr_buf
, '\0');
340 return NULL
; /* should not happen */
342 /* above tokens have value, the ones below don't */
351 return strcpy(p
, "...");
353 return strcpy(p
, "<<=");
355 return strcpy(p
, ">>=");
358 /* search in two bytes table */
359 const unsigned char *q
= tok_two_chars
;
370 sprintf(buf
, "<%02x>", v
);
376 } else if (v
< tok_ident
) {
377 return table_ident
[v
- TOK_IDENT
]->str
;
378 } else if (v
>= SYM_FIRST_ANOM
) {
379 /* special name for anonymous symbol */
380 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
382 /* should never happen */
387 return cstr_buf
.data
;
390 /* return the current character, handling end of block if necessary
392 ST_FUNC
int handle_eob(void)
394 BufferedFile
*bf
= file
;
397 /* only tries to read if really end of buffer */
398 if (bf
->buf_ptr
>= bf
->buf_end
) {
400 #if defined(PARSE_DEBUG)
405 len
= read(bf
->fd
, bf
->buffer
, len
);
412 bf
->buf_ptr
= bf
->buffer
;
413 bf
->buf_end
= bf
->buffer
+ len
;
414 *bf
->buf_end
= CH_EOB
;
416 if (bf
->buf_ptr
< bf
->buf_end
) {
417 return bf
->buf_ptr
[0];
419 bf
->buf_ptr
= bf
->buf_end
;
424 /* read next char from current input file and handle end of input buffer */
425 ST_INLN
void inp(void)
427 ch
= *(++(file
->buf_ptr
));
428 /* end of buffer/file handling */
433 /* handle '\[\r]\n' */
434 static int handle_stray_noerror(void)
441 } else if (ch
== '\r') {
455 static void handle_stray(void)
457 if (handle_stray_noerror())
458 tcc_error("stray '\\' in program");
461 /* skip the stray and handle the \\n case. Output an error if
462 incorrect char after the stray */
463 static int handle_stray1(uint8_t *p
)
468 if (p
>= file
->buf_end
) {
475 if (handle_stray_noerror()) {
476 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
477 tcc_error("stray '\\' in program");
478 *--file
->buf_ptr
= '\\';
485 /* handle just the EOB case, but not stray */
486 #define PEEKC_EOB(c, p)\
497 /* handle the complicated stray case */
503 c = handle_stray1(p);\
508 /* input with '\[\r]\n' handling. Note that this function cannot
509 handle other characters after '\', so you cannot call it inside
510 strings or comments */
511 ST_FUNC
void minp(void)
519 /* single line C++ comments */
520 static uint8_t *parse_line_comment(uint8_t *p
)
528 if (c
== '\n' || c
== CH_EOF
) {
530 } else if (c
== '\\') {
539 } else if (c
== '\r') {
557 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
566 if (c
== '\n' || c
== '*' || c
== '\\')
570 if (c
== '\n' || c
== '*' || c
== '\\')
574 /* now we can handle all the cases */
578 } else if (c
== '*') {
584 } else if (c
== '/') {
586 } else if (c
== '\\') {
591 /* skip '\[\r]\n', otherwise just skip the stray */
597 } else if (c
== '\r') {
614 /* stray, eob or eof */
619 tcc_error("unexpected end of file in comment");
620 } else if (c
== '\\') {
632 static inline void skip_spaces(void)
634 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
638 static inline int check_space(int t
, int *spc
)
640 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
649 /* parse a string without interpreting escapes */
650 static uint8_t *parse_pp_string(uint8_t *p
,
651 int sep
, CString
*str
)
659 } else if (c
== '\\') {
665 /* XXX: indicate line number of start of string */
666 tcc_error("missing terminating %c character", sep
);
667 } else if (c
== '\\') {
668 /* escape : just skip \[\r]\n */
673 } else if (c
== '\r') {
676 expect("'\n' after '\r'");
679 } else if (c
== CH_EOF
) {
680 goto unterminated_string
;
683 cstr_ccat(str
, '\\');
689 } else if (c
== '\n') {
692 } else if (c
== '\r') {
696 cstr_ccat(str
, '\r');
712 /* skip block of text until #else, #elif or #endif. skip also pairs of
714 static void preprocess_skip(void)
716 int a
, start_of_line
, c
, in_warn_or_error
;
723 in_warn_or_error
= 0;
744 } else if (c
== '\\') {
745 ch
= file
->buf_ptr
[0];
746 handle_stray_noerror();
753 if (in_warn_or_error
)
755 p
= parse_pp_string(p
, c
, NULL
);
759 if (in_warn_or_error
)
766 p
= parse_comment(p
);
767 } else if (ch
== '/') {
768 p
= parse_line_comment(p
);
778 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
780 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
782 else if (tok
== TOK_ENDIF
)
784 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
785 in_warn_or_error
= 1;
786 else if (tok
== TOK_LINEFEED
)
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_size(const int *p
)
843 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
849 return 1 + 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];
925 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
926 while ((len
+ nb_words
) > s
->allocated_len
)
927 str
= tok_str_realloc(s
);
928 cstr
= (CString
*)(str
+ len
);
930 cstr
->size
= cv
->cstr
->size
;
931 cstr
->data_allocated
= NULL
;
932 cstr
->size_allocated
= cstr
->size
;
933 memcpy((char *)cstr
+ sizeof(CString
),
934 cv
->cstr
->data
, cstr
->size
);
941 #if LDOUBLE_SIZE == 8
944 str
[len
++] = cv
->tab
[0];
945 str
[len
++] = cv
->tab
[1];
947 #if LDOUBLE_SIZE == 12
949 str
[len
++] = cv
->tab
[0];
950 str
[len
++] = cv
->tab
[1];
951 str
[len
++] = cv
->tab
[2];
952 #elif LDOUBLE_SIZE == 16
954 str
[len
++] = cv
->tab
[0];
955 str
[len
++] = cv
->tab
[1];
956 str
[len
++] = cv
->tab
[2];
957 str
[len
++] = cv
->tab
[3];
958 #elif LDOUBLE_SIZE != 8
959 #error add long double size support
968 /* add the current parse token in token string 's' */
969 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
973 /* save line number info */
974 if (file
->line_num
!= s
->last_line_num
) {
975 s
->last_line_num
= file
->line_num
;
976 cval
.i
= s
->last_line_num
;
977 tok_str_add2(s
, TOK_LINENUM
, &cval
);
979 tok_str_add2(s
, tok
, &tokc
);
982 /* get a token from an integer array and increment pointer
983 accordingly. we code it as a macro to avoid pointer aliasing. */
984 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1003 cv
->cstr
= (CString
*)p
;
1004 cv
->cstr
->data
= (char *)p
+ sizeof(CString
);
1005 p
+= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
1013 #if LDOUBLE_SIZE == 16
1015 #elif LDOUBLE_SIZE == 12
1017 #elif LDOUBLE_SIZE == 8
1020 # error add long double size support
1033 static int macro_is_equal(const int *a
, const int *b
)
1035 char buf
[STRING_MAX_SIZE
+ 1];
1039 TOK_GET(&t
, &a
, &cv
);
1040 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1041 TOK_GET(&t
, &b
, &cv
);
1042 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1048 /* defines handling */
1049 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1054 if (s
&& !macro_is_equal(s
->d
, str
))
1055 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1057 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1059 s
->next
= first_arg
;
1060 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1063 /* undefined a define symbol. Its name is just set to zero */
1064 ST_FUNC
void define_undef(Sym
*s
)
1068 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1069 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1072 ST_INLN Sym
*define_find(int v
)
1075 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1077 return table_ident
[v
]->sym_define
;
1080 /* free define stack until top reaches 'b' */
1081 ST_FUNC
void free_defines(Sym
*b
)
1089 /* do not free args or predefined defines */
1091 tok_str_free(top
->d
);
1093 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1094 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1102 ST_FUNC Sym
*label_find(int v
)
1105 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1107 return table_ident
[v
]->sym_label
;
1110 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1113 s
= sym_push2(ptop
, v
, 0, 0);
1115 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1116 if (ptop
== &global_label_stack
) {
1117 /* modify the top most local identifier, so that
1118 sym_identifier will point to 's' when popped */
1120 ps
= &(*ps
)->prev_tok
;
1127 /* pop labels until element last is reached. Look if any labels are
1128 undefined. Define symbols if '&&label' was used. */
1129 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1132 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1134 if (s
->r
== LABEL_DECLARED
) {
1135 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1136 } else if (s
->r
== LABEL_FORWARD
) {
1137 tcc_error("label '%s' used but not defined",
1138 get_tok_str(s
->v
, NULL
));
1141 /* define corresponding symbol. A size of
1143 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1147 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1153 /* eval an expression for #if/#elif */
1154 static int expr_preprocess(void)
1160 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1161 next(); /* do macro subst */
1162 if (tok
== TOK_DEFINED
) {
1167 c
= define_find(tok
) != 0;
1172 } else if (tok
>= TOK_IDENT
) {
1173 /* if undefined macro */
1177 tok_str_add_tok(&str
);
1179 tok_str_add(&str
, -1); /* simulate end of file */
1180 tok_str_add(&str
, 0);
1181 /* now evaluate C constant expression */
1182 begin_macro(&str
, 0);
1191 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1192 static void tok_print(const char *msg
, const int *str
)
1199 TOK_GET(&t
, &str
, &cval
);
1202 printf("%s", get_tok_str(t
, &cval
));
1207 static void define_print(int v
)
1212 printf("#define %s", get_tok_str(v
, NULL
));
1213 if (s
->type
.t
== MACRO_FUNC
) {
1218 printf("%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
1225 tok_print("", s
->d
);
1229 /* parse after #define */
1230 ST_FUNC
void parse_define(void)
1232 Sym
*s
, *first
, **ps
;
1233 int v
, t
, varg
, is_vaargs
, spc
;
1234 int saved_parse_flags
= parse_flags
;
1239 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1240 /* XXX: should check if same macro (ANSI) */
1243 /* '(' must be just after macro definition for MACRO_FUNC */
1244 parse_flags
|= PARSE_FLAG_SPACES
;
1249 if (tok
!= ')') for (;;) {
1253 if (varg
== TOK_DOTS
) {
1254 varg
= TOK___VA_ARGS__
;
1256 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1260 if (varg
< TOK_IDENT
)
1262 tcc_error("bad macro parameter list");
1263 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1268 if (tok
!= ',' || is_vaargs
)
1277 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1278 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1279 /* remove spaces around ## and after '#' */
1280 if (TOK_TWOSHARPS
== tok
) {
1286 } else if ('#' == tok
) {
1288 } else if (check_space(tok
, &spc
)) {
1291 tok_str_add2(&str
, tok
, &tokc
);
1296 parse_flags
= saved_parse_flags
;
1298 --str
.len
; /* remove trailing space */
1299 tok_str_add(&str
, 0);
1302 tcc_error("'##' cannot appear at either end of macro");
1303 define_push(v
, t
, str
.str
, first
);
1309 static inline int hash_cached_include(const char *filename
)
1311 const unsigned char *s
;
1315 s
= (unsigned char *) filename
;
1317 h
= TOK_HASH_FUNC(h
, *s
);
1320 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1324 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1328 h
= hash_cached_include(filename
);
1329 i
= s1
->cached_includes_hash
[h
];
1333 e
= s1
->cached_includes
[i
- 1];
1334 if (0 == PATHCMP(e
->filename
, filename
))
1341 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1346 if (search_cached_include(s1
, filename
))
1349 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1351 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1352 strcpy(e
->filename
, filename
);
1353 e
->ifndef_macro
= ifndef_macro
;
1354 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1355 /* add in hash table */
1356 h
= hash_cached_include(filename
);
1357 e
->hash_next
= s1
->cached_includes_hash
[h
];
1358 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1361 static void pragma_parse(TCCState
*s1
)
1364 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1368 if (next(), tok
!= '(')
1370 if (next(), tok
!= TOK_STR
)
1372 v
= tok_alloc(tokc
.cstr
->data
, tokc
.cstr
->size
- 1)->tok
;
1373 if (next(), tok
!= ')')
1375 if (t
== TOK_push_macro
) {
1376 while (NULL
== (s
= define_find(v
)))
1377 define_push(v
, 0, NULL
, NULL
);
1378 s
->type
.ref
= s
; /* set push boundary */
1380 for (s
= define_stack
; s
; s
= s
->prev
)
1381 if (s
->v
== v
&& s
->type
.ref
== s
) {
1387 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1389 tcc_warning("unbalanced #pragma pop_macro");
1391 } else if (tok
== TOK_once
) {
1392 add_cached_include(s1
, file
->filename
, TOK_once
);
1394 } else if (s1
->ppfp
) {
1395 /* tcc -E: keep pragmas below unchanged */
1397 unget_tok(TOK_PRAGMA
);
1399 unget_tok(TOK_LINEFEED
);
1401 } else if (tok
== TOK_pack
) {
1403 #pragma pack(1) // set
1404 #pragma pack() // reset to default
1405 #pragma pack(push,1) // push & set
1406 #pragma pack(pop) // restore previous */
1409 if (tok
== TOK_ASM_pop
) {
1411 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1413 tcc_error("out of pack stack");
1415 s1
->pack_stack_ptr
--;
1419 if (tok
== TOK_ASM_push
) {
1421 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1423 s1
->pack_stack_ptr
++;
1426 if (tok
!= TOK_CINT
)
1429 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1433 *s1
->pack_stack_ptr
= val
;
1438 } else if (tok
== TOK_comment
) {
1448 file
= tcc_strdup((char *)tokc
.cstr
->data
);
1449 dynarray_add((void ***)&s1
->pragma_libs
, &s1
->nb_pragma_libs
, file
);
1455 if (s1
->warn_unsupported
)
1456 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1461 tcc_error("malformed #pragma directive");
1465 /* is_bof is true if first non space token at beginning of file */
1466 ST_FUNC
void preprocess(int is_bof
)
1468 TCCState
*s1
= tcc_state
;
1469 int i
, c
, n
, saved_parse_flags
;
1473 saved_parse_flags
= parse_flags
;
1474 parse_flags
= PARSE_FLAG_PREPROCESS
1475 | PARSE_FLAG_TOK_NUM
1476 | PARSE_FLAG_TOK_STR
1477 | PARSE_FLAG_LINEFEED
1478 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1490 s
= define_find(tok
);
1491 /* undefine symbol by putting an invalid name */
1496 case TOK_INCLUDE_NEXT
:
1497 ch
= file
->buf_ptr
[0];
1498 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1503 } else if (ch
== '\"') {
1508 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1509 if ((q
- buf
) < sizeof(buf
) - 1)
1512 if (handle_stray_noerror() == 0)
1520 /* eat all spaces and comments after include */
1521 /* XXX: slightly incorrect */
1522 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1526 /* computed #include : either we have only strings or
1527 we have anything enclosed in '<>' */
1530 if (tok
== TOK_STR
) {
1531 while (tok
!= TOK_LINEFEED
) {
1532 if (tok
!= TOK_STR
) {
1534 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1536 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1542 while (tok
!= TOK_LINEFEED
) {
1543 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1547 /* check syntax and remove '<>' */
1548 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1549 goto include_syntax
;
1550 memmove(buf
, buf
+ 1, len
- 2);
1551 buf
[len
- 2] = '\0';
1556 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1557 tcc_error("#include recursion too deep");
1558 /* store current file in stack, but increment stack later below */
1559 *s1
->include_stack_ptr
= file
;
1561 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1562 for (i
= -2; i
< n
; ++i
) {
1563 char buf1
[sizeof file
->filename
];
1569 /* check absolute include path */
1570 if (!IS_ABSPATH(buf
))
1573 i
= n
; /* force end loop */
1575 } else if (i
== -1) {
1576 /* search in current dir if "header.h" */
1579 path
= file
->filename
;
1580 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1583 /* search in all the include paths */
1584 if (i
< s1
->nb_include_paths
)
1585 path
= s1
->include_paths
[i
];
1587 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1588 pstrcpy(buf1
, sizeof(buf1
), path
);
1589 pstrcat(buf1
, sizeof(buf1
), "/");
1592 pstrcat(buf1
, sizeof(buf1
), buf
);
1594 if (tok
== TOK_INCLUDE_NEXT
)
1595 for (f
= s1
->include_stack_ptr
; f
>= s1
->include_stack
; --f
)
1596 if (0 == PATHCMP((*f
)->filename
, buf1
)) {
1598 printf("%s: #include_next skipping %s\n", file
->filename
, buf1
);
1600 goto include_trynext
;
1603 e
= search_cached_include(s1
, buf1
);
1604 if (e
&& (define_find(e
->ifndef_macro
) || e
->ifndef_macro
== TOK_once
)) {
1605 /* no need to parse the include because the 'ifndef macro'
1608 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1613 if (tcc_open(s1
, buf1
) < 0)
1618 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1620 /* update target deps */
1621 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1623 /* push current file in stack */
1624 ++s1
->include_stack_ptr
;
1625 /* add include file debug info */
1627 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1628 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1629 ch
= file
->buf_ptr
[0];
1632 tcc_error("include file '%s' not found", buf
);
1639 c
= expr_preprocess();
1645 if (tok
< TOK_IDENT
)
1646 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1650 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1652 file
->ifndef_macro
= tok
;
1655 c
= (define_find(tok
) != 0) ^ c
;
1657 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1658 tcc_error("memory full (ifdef)");
1659 *s1
->ifdef_stack_ptr
++ = c
;
1662 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1663 tcc_error("#else without matching #if");
1664 if (s1
->ifdef_stack_ptr
[-1] & 2)
1665 tcc_error("#else after #else");
1666 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1669 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1670 tcc_error("#elif without matching #if");
1671 c
= s1
->ifdef_stack_ptr
[-1];
1673 tcc_error("#elif after #else");
1674 /* last #if/#elif expression was true: we skip */
1677 c
= expr_preprocess();
1678 s1
->ifdef_stack_ptr
[-1] = c
;
1680 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1681 file
->ifndef_macro
= 0;
1691 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1692 tcc_error("#endif without matching #if");
1693 s1
->ifdef_stack_ptr
--;
1694 /* '#ifndef macro' was at the start of file. Now we check if
1695 an '#endif' is exactly at the end of file */
1696 if (file
->ifndef_macro
&&
1697 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1698 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1699 /* need to set to zero to avoid false matches if another
1700 #ifndef at middle of file */
1701 file
->ifndef_macro
= 0;
1702 while (tok
!= TOK_LINEFEED
)
1704 tok_flags
|= TOK_FLAG_ENDIF
;
1709 n
= strtoul((char*)tokc
.cstr
->data
, &q
, 10);
1713 if (tok
!= TOK_CINT
)
1715 tcc_error("wrong #line format");
1719 if (tok
!= TOK_LINEFEED
) {
1721 pstrcpy(file
->filename
, sizeof(file
->filename
), (char *)tokc
.cstr
->data
);
1722 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1729 total_lines
+= file
->line_num
- n
;
1732 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1737 ch
= file
->buf_ptr
[0];
1740 while (ch
!= '\n' && ch
!= CH_EOF
) {
1741 if ((q
- buf
) < sizeof(buf
) - 1)
1744 if (handle_stray_noerror() == 0)
1751 tcc_error("#error %s", buf
);
1753 tcc_warning("#warning %s", buf
);
1761 /* ignore gas line comment in an 'S' file. */
1762 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
1764 if (tok
== '!' && is_bof
)
1765 /* '!' is ignored at beginning to allow C scripts. */
1767 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1769 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1772 /* ignore other preprocess commands or #! for C scripts */
1773 while (tok
!= TOK_LINEFEED
)
1776 parse_flags
= saved_parse_flags
;
1779 /* evaluate escape codes in a string. */
1780 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1795 case '0': case '1': case '2': case '3':
1796 case '4': case '5': case '6': case '7':
1797 /* at most three octal digits */
1802 n
= n
* 8 + c
- '0';
1806 n
= n
* 8 + c
- '0';
1811 goto add_char_nonext
;
1819 if (c
>= 'a' && c
<= 'f')
1821 else if (c
>= 'A' && c
<= 'F')
1831 goto add_char_nonext
;
1855 goto invalid_escape
;
1865 if (c
>= '!' && c
<= '~')
1866 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1868 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1875 cstr_ccat(outstr
, c
);
1877 cstr_wccat(outstr
, c
);
1879 /* add a trailing '\0' */
1881 cstr_ccat(outstr
, '\0');
1883 cstr_wccat(outstr
, '\0');
1886 void parse_string(const char *s
, int len
)
1888 uint8_t buf
[1000], *p
= buf
;
1891 if ((is_long
= *s
== 'L'))
1895 if (len
>= sizeof buf
)
1896 p
= tcc_malloc(len
+ 1);
1900 cstr_reset(&tokcstr
);
1901 parse_escape_string(&tokcstr
, p
, is_long
);
1907 /* XXX: make it portable */
1911 char_size
= sizeof(nwchar_t
);
1912 if (tokcstr
.size
<= char_size
)
1913 tcc_error("empty character constant");
1914 if (tokcstr
.size
> 2 * char_size
)
1915 tcc_warning("multi-character character constant");
1917 tokc
.i
= *(int8_t *)tokcstr
.data
;
1920 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
1924 tokc
.cstr
= &tokcstr
;
1932 /* we use 64 bit numbers */
1935 /* bn = (bn << shift) | or_val */
1936 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
1940 for(i
=0;i
<BN_SIZE
;i
++) {
1942 bn
[i
] = (v
<< shift
) | or_val
;
1943 or_val
= v
>> (32 - shift
);
1947 static void bn_zero(unsigned int *bn
)
1950 for(i
=0;i
<BN_SIZE
;i
++) {
1955 /* parse number in null terminated string 'p' and return it in the
1957 static void parse_number(const char *p
)
1959 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
1961 unsigned int bn
[BN_SIZE
];
1972 goto float_frac_parse
;
1973 } else if (t
== '0') {
1974 if (ch
== 'x' || ch
== 'X') {
1978 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
1984 /* parse all digits. cannot check octal numbers at this stage
1985 because of floating point constants */
1987 if (ch
>= 'a' && ch
<= 'f')
1989 else if (ch
>= 'A' && ch
<= 'F')
1997 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
1999 tcc_error("number too long");
2005 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2006 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2008 /* NOTE: strtox should support that for hexa numbers, but
2009 non ISOC99 libcs do not support it, so we prefer to do
2011 /* hexadecimal or binary floats */
2012 /* XXX: handle overflows */
2024 } else if (t
>= 'a') {
2026 } else if (t
>= 'A') {
2031 bn_lshift(bn
, shift
, t
);
2038 if (t
>= 'a' && t
<= 'f') {
2040 } else if (t
>= 'A' && t
<= 'F') {
2042 } else if (t
>= '0' && t
<= '9') {
2048 tcc_error("invalid digit");
2049 bn_lshift(bn
, shift
, t
);
2054 if (ch
!= 'p' && ch
!= 'P')
2061 } else if (ch
== '-') {
2065 if (ch
< '0' || ch
> '9')
2066 expect("exponent digits");
2067 while (ch
>= '0' && ch
<= '9') {
2068 exp_val
= exp_val
* 10 + ch
- '0';
2071 exp_val
= exp_val
* s
;
2073 /* now we can generate the number */
2074 /* XXX: should patch directly float number */
2075 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2076 d
= ldexp(d
, exp_val
- frac_bits
);
2081 /* float : should handle overflow */
2083 } else if (t
== 'L') {
2085 #ifdef TCC_TARGET_PE
2090 /* XXX: not large enough */
2091 tokc
.ld
= (long double)d
;
2098 /* decimal floats */
2100 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2105 while (ch
>= '0' && ch
<= '9') {
2106 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2112 if (ch
== 'e' || ch
== 'E') {
2113 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2117 if (ch
== '-' || ch
== '+') {
2118 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2123 if (ch
< '0' || ch
> '9')
2124 expect("exponent digits");
2125 while (ch
>= '0' && ch
<= '9') {
2126 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2138 tokc
.f
= strtof(token_buf
, NULL
);
2139 } else if (t
== 'L') {
2141 #ifdef TCC_TARGET_PE
2143 tokc
.d
= strtod(token_buf
, NULL
);
2146 tokc
.ld
= strtold(token_buf
, NULL
);
2150 tokc
.d
= strtod(token_buf
, NULL
);
2154 unsigned long long n
, n1
;
2155 int lcount
, ucount
, must_64bit
;
2158 /* integer number */
2161 if (b
== 10 && *q
== '0') {
2168 /* no need for checks except for base 10 / 8 errors */
2178 tcc_error("invalid digit");
2181 /* detect overflow */
2182 /* XXX: this test is not reliable */
2184 tcc_error("integer constant overflow");
2187 /* Determine the characteristics (unsigned and/or 64bit) the type of
2188 the constant must have according to the constant suffix(es) */
2189 lcount
= ucount
= must_64bit
= 0;
2195 tcc_error("three 'l's in integer constant");
2196 if (lcount
&& *(p
- 1) != ch
)
2197 tcc_error("incorrect integer suffix: %s", p1
);
2199 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2204 } else if (t
== 'U') {
2206 tcc_error("two 'u's in integer constant");
2214 /* Whether 64 bits are needed to hold the constant's value */
2215 if (n
& 0xffffffff00000000LL
|| must_64bit
) {
2223 /* Whether type must be unsigned to hold the constant's value */
2224 if (ucount
|| ((n1
>> 31) && (b
!= 10))) {
2225 if (tok
== TOK_CLLONG
)
2229 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2230 } else if (n1
>> 31) {
2231 if (tok
== TOK_CINT
)
2234 tcc_error("integer constant overflow");
2237 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2243 tcc_error("invalid number\n");
2247 #define PARSE2(c1, tok1, c2, tok2) \
2258 /* return next token without macro substitution */
2259 static inline void next_nomacro1(void)
2274 if (parse_flags
& PARSE_FLAG_SPACES
)
2275 goto keep_tok_flags
;
2276 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2285 /* first look if it is in fact an end of buffer */
2286 c
= handle_stray1(p
);
2293 TCCState
*s1
= tcc_state
;
2294 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2295 && !(tok_flags
& TOK_FLAG_EOF
)) {
2296 tok_flags
|= TOK_FLAG_EOF
;
2298 goto keep_tok_flags
;
2299 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2301 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2302 tcc_error("missing #endif");
2303 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2304 /* no include left : end of file. */
2307 tok_flags
&= ~TOK_FLAG_EOF
;
2308 /* pop include file */
2310 /* test if previous '#endif' was after a #ifdef at
2312 if (tok_flags
& TOK_FLAG_ENDIF
) {
2314 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2316 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2317 tok_flags
&= ~TOK_FLAG_ENDIF
;
2320 /* add end of include file debug info */
2321 if (tcc_state
->do_debug
) {
2322 put_stabd(N_EINCL
, 0, 0);
2324 /* pop include stack */
2326 s1
->include_stack_ptr
--;
2335 tok_flags
|= TOK_FLAG_BOL
;
2338 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2341 goto keep_tok_flags
;
2346 if ((tok_flags
& TOK_FLAG_BOL
) &&
2347 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2349 preprocess(tok_flags
& TOK_FLAG_BOF
);
2355 tok
= TOK_TWOSHARPS
;
2357 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2358 p
= parse_line_comment(p
- 1);
2367 /* dollar is allowed to start identifiers when not parsing asm */
2369 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2370 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2373 case 'a': case 'b': case 'c': case 'd':
2374 case 'e': case 'f': case 'g': case 'h':
2375 case 'i': case 'j': case 'k': case 'l':
2376 case 'm': case 'n': case 'o': case 'p':
2377 case 'q': case 'r': case 's': case 't':
2378 case 'u': case 'v': case 'w': case 'x':
2380 case 'A': case 'B': case 'C': case 'D':
2381 case 'E': case 'F': case 'G': case 'H':
2382 case 'I': case 'J': case 'K':
2383 case 'M': case 'N': case 'O': case 'P':
2384 case 'Q': case 'R': case 'S': case 'T':
2385 case 'U': case 'V': case 'W': case 'X':
2391 h
= TOK_HASH_FUNC(h
, c
);
2392 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2393 h
= TOK_HASH_FUNC(h
, c
);
2398 /* fast case : no stray found, so we have the full token
2399 and we have already hashed it */
2401 h
&= (TOK_HASH_SIZE
- 1);
2402 pts
= &hash_ident
[h
];
2407 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2409 pts
= &(ts
->hash_next
);
2411 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2415 cstr_reset(&tokcstr
);
2418 cstr_ccat(&tokcstr
, *p1
);
2424 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
)) {
2425 cstr_ccat(&tokcstr
, c
);
2428 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2434 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2436 goto parse_ident_fast
;
2439 if (c
== '\'' || c
== '\"') {
2443 cstr_reset(&tokcstr
);
2444 cstr_ccat(&tokcstr
, 'L');
2445 goto parse_ident_slow
;
2450 case '0': case '1': case '2': case '3':
2451 case '4': case '5': case '6': case '7':
2453 cstr_reset(&tokcstr
);
2454 /* after the first digit, accept digits, alpha, '.' or sign if
2455 prefixed by 'eEpP' */
2459 cstr_ccat(&tokcstr
, c
);
2461 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2463 || ((c
== '+' || c
== '-')
2464 && (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P')
2468 /* We add a trailing '\0' to ease parsing */
2469 cstr_ccat(&tokcstr
, '\0');
2470 tokc
.cstr
= &tokcstr
;
2475 /* special dot handling because it can also start a number */
2478 cstr_reset(&tokcstr
);
2479 cstr_ccat(&tokcstr
, '.');
2481 } else if (c
== '.') {
2495 cstr_reset(&tokcstr
);
2497 cstr_ccat(&tokcstr
, 'L');
2498 cstr_ccat(&tokcstr
, c
);
2499 p
= parse_pp_string(p
, c
, &tokcstr
);
2500 cstr_ccat(&tokcstr
, c
);
2501 cstr_ccat(&tokcstr
, '\0');
2502 tokc
.cstr
= &tokcstr
;
2511 } else if (c
== '<') {
2528 } else if (c
== '>') {
2546 } else if (c
== '=') {
2559 } else if (c
== '=') {
2572 } else if (c
== '=') {
2585 } else if (c
== '=') {
2588 } else if (c
== '>') {
2596 PARSE2('!', '!', '=', TOK_NE
)
2597 PARSE2('=', '=', '=', TOK_EQ
)
2598 PARSE2('*', '*', '=', TOK_A_MUL
)
2599 PARSE2('%', '%', '=', TOK_A_MOD
)
2600 PARSE2('^', '^', '=', TOK_A_XOR
)
2602 /* comments or operator */
2606 p
= parse_comment(p
);
2607 /* comments replaced by a blank */
2609 goto keep_tok_flags
;
2610 } else if (c
== '/') {
2611 p
= parse_line_comment(p
);
2613 goto keep_tok_flags
;
2614 } else if (c
== '=') {
2634 case '@': /* only used in assembler */
2640 tcc_error("unrecognized character \\x%02x", c
);
2646 #if defined(PARSE_DEBUG)
2647 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2651 /* return next token without macro substitution. Can read input from
2653 static void next_nomacro_spc(void)
2659 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2660 if (tok
== TOK_LINENUM
) {
2661 file
->line_num
= tokc
.i
;
2670 ST_FUNC
void next_nomacro(void)
2674 } while (tok
< 256 && (isidnum_table
[tok
- CH_EOF
] & IS_SPC
));
2678 static void macro_subst(
2679 TokenString
*tok_str
,
2681 const int *macro_str
,
2685 /* substitute arguments in replacement lists in macro_str by the values in
2686 args (field d) and return allocated string */
2687 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2699 TOK_GET(&t
, ¯o_str
, &cval
);
2704 TOK_GET(&t
, ¯o_str
, &cval
);
2707 s
= sym_find2(args
, t
);
2710 cstr_ccat(&cstr
, '\"');
2714 TOK_GET(&t
, &st
, &cval
);
2715 if (t
!= TOK_PLCHLDR
2717 && 0 == check_space(t
, &spc
)) {
2718 const char *s
= get_tok_str(t
, &cval
);
2720 if (t
== TOK_PPSTR
&& *s
!= '\'')
2721 add_char(&cstr
, *s
);
2723 cstr_ccat(&cstr
, *s
);
2729 cstr_ccat(&cstr
, '\"');
2730 cstr_ccat(&cstr
, '\0');
2732 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
2736 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
2737 cstr_free(cval
.cstr
);
2740 expect("macro parameter after '#'");
2742 } else if (t
>= TOK_IDENT
) {
2743 s
= sym_find2(args
, t
);
2747 /* if '##' is present before or after, no arg substitution */
2748 if (*macro_str
== TOK_TWOSHARPS
|| t1
== TOK_TWOSHARPS
) {
2749 /* special case for var arg macros : ## eats the ','
2750 if empty VA_ARGS variable. */
2751 if (t1
== TOK_TWOSHARPS
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
2753 /* suppress ',' '##' */
2756 /* suppress '##' and add variable */
2763 TOK_GET(&t1
, &st
, &cval
);
2766 tok_str_add2(&str
, t1
, &cval
);
2772 /* NOTE: the stream cannot be read when macro
2773 substituing an argument */
2774 macro_subst(&str
, nested_list
, st
, 0);
2776 if (str
.len
== l0
) /* exanded to empty string */
2777 tok_str_add(&str
, TOK_PLCHLDR
);
2779 tok_str_add(&str
, t
);
2782 tok_str_add2(&str
, t
, &cval
);
2786 tok_str_add(&str
, 0);
2790 static char const ab_month_name
[12][4] =
2792 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2793 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2796 /* peek or read [ws_str == NULL] next token from function macro call,
2797 walking up macro levels up to the file if necessary */
2798 static int next_argstream(Sym
**nested_list
, int can_read_stream
, TokenString
*ws_str
)
2806 p
= macro_ptr
, t
= *p
;
2808 while (is_space(t
) || TOK_LINEFEED
== t
)
2809 tok_str_add(ws_str
, t
), t
= *++p
;
2811 if (t
== 0 && can_read_stream
) {
2813 /* also, end of scope for nested defined symbol */
2815 while (sa
&& sa
->v
== -1)
2824 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
2827 uint8_t *p
= file
->buf_ptr
;
2830 p
= parse_comment(p
);
2831 file
->buf_ptr
= p
- 1;
2832 } else if (c
== '/') {
2833 p
= parse_line_comment(p
);
2834 file
->buf_ptr
= p
- 1;
2839 tok_str_add(ws_str
, ch
);
2853 /* do macro substitution of current token with macro 's' and add
2854 result to (tok_str,tok_len). 'nested_list' is the list of all
2855 macros we got inside to avoid recursing. Return non zero if no
2856 substitution needs to be done */
2857 static int macro_subst_tok(
2858 TokenString
*tok_str
,
2861 int can_read_stream
)
2863 Sym
*args
, *sa
, *sa1
;
2864 int parlevel
, *mstr
, t
, t1
, spc
;
2871 /* if symbol is a macro, prepare substitution */
2872 /* special macros */
2873 if (tok
== TOK___LINE__
) {
2874 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2878 } else if (tok
== TOK___FILE__
) {
2879 cstrval
= file
->filename
;
2881 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2886 tm
= localtime(&ti
);
2887 if (tok
== TOK___DATE__
) {
2888 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2889 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2891 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2892 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2899 cstr_cat(&cstr
, cstrval
);
2900 cstr_ccat(&cstr
, '\0');
2902 tok_str_add2(tok_str
, t1
, &cval
);
2905 int saved_parse_flags
= parse_flags
;
2908 if (s
->type
.t
== MACRO_FUNC
) {
2909 /* whitespace between macro name and argument list */
2911 tok_str_new(&ws_str
);
2914 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
2915 | PARSE_FLAG_ACCEPT_STRAYS
;
2917 /* get next token from argument stream */
2918 t
= next_argstream(nested_list
, can_read_stream
, &ws_str
);
2920 /* not a macro substitution after all, restore the
2921 * macro token plus all whitespace we've read.
2922 * whitespace is intentionally not merged to preserve
2924 parse_flags
= saved_parse_flags
;
2925 tok_str_add(tok_str
, tok
);
2926 if (parse_flags
& PARSE_FLAG_SPACES
) {
2928 for (i
= 0; i
< ws_str
.len
; i
++)
2929 tok_str_add(tok_str
, ws_str
.str
[i
]);
2931 tok_str_free(ws_str
.str
);
2934 tok_str_free(ws_str
.str
);
2936 next_nomacro(); /* eat '(' */
2938 /* argument macro */
2941 /* NOTE: empty args are allowed, except if no args */
2944 next_argstream(nested_list
, can_read_stream
, NULL
);
2945 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
2947 /* handle '()' case */
2948 if (!args
&& !sa
&& tok
== ')')
2951 tcc_error("macro '%s' used with too many args",
2952 get_tok_str(s
->v
, 0));
2955 /* NOTE: non zero sa->t indicates VA_ARGS */
2956 while ((parlevel
> 0 ||
2958 (tok
!= ',' || sa
->type
.t
)))) {
2959 if (tok
== TOK_EOF
|| tok
== 0)
2963 else if (tok
== ')')
2965 if (tok
== TOK_LINEFEED
)
2967 if (!check_space(tok
, &spc
))
2968 tok_str_add2(&str
, tok
, &tokc
);
2969 next_argstream(nested_list
, can_read_stream
, NULL
);
2974 tok_str_add(&str
, 0);
2975 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
2979 /* special case for gcc var args: add an empty
2980 var arg argument if it is omitted */
2981 if (sa
&& sa
->type
.t
&& gnu_ext
)
2989 tcc_error("macro '%s' used with too few args",
2990 get_tok_str(s
->v
, 0));
2993 parse_flags
= saved_parse_flags
;
2995 /* now subst each arg */
2996 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3001 tok_str_free(sa
->d
);
3007 sym_push2(nested_list
, s
->v
, 0, 0);
3008 parse_flags
= saved_parse_flags
;
3009 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
3011 /* pop nested defined symbol */
3013 *nested_list
= sa1
->prev
;
3021 int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3027 if (t1
!= TOK_PLCHLDR
)
3028 cstr_cat(&cstr
, get_tok_str(t1
, v1
));
3030 if (t2
!= TOK_PLCHLDR
)
3031 cstr_cat(&cstr
, get_tok_str(t2
, v2
));
3032 cstr_ccat(&cstr
, '\0');
3034 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3035 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3038 if (0 == *file
->buf_ptr
)
3042 tcc_warning("pasting <%.*s> and <%s> does not give a valid preprocessing token",
3043 n
, cstr
.data
, (char*)cstr
.data
+ n
);
3048 //printf("paste <%s>\n", (char*)cstr.data);
3053 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3054 return the resulting string (which must be freed). */
3055 static inline int *macro_twosharps(const int *ptr0
)
3059 TokenString macro_str1
;
3060 int start_of_nosubsts
= -1;
3063 /* we search the first '##' */
3064 for (ptr
= ptr0
;;) {
3065 TOK_GET(&t
, &ptr
, &cval
);
3066 if (t
== TOK_TWOSHARPS
)
3072 tok_str_new(¯o_str1
);
3074 //tok_print(" $$$", ptr0);
3075 for (ptr
= ptr0
;;) {
3076 TOK_GET(&t
, &ptr
, &cval
);
3079 if (t
== TOK_TWOSHARPS
)
3081 while (*ptr
== TOK_TWOSHARPS
) {
3083 /* given 'a##b', remove nosubsts preceding 'a' */
3084 if (start_of_nosubsts
>= 0)
3085 macro_str1
.len
= start_of_nosubsts
;
3086 /* given 'a##b', remove nosubsts preceding 'b' */
3087 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3089 if (t1
&& t1
!= TOK_TWOSHARPS
3090 && t1
!= ':') /* 'a##:' don't build a new token */
3092 TOK_GET(&t1
, &ptr
, &cv1
);
3093 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3094 paste_tokens(t
, &cval
, t1
, &cv1
);
3095 t
= tok
, cval
= tokc
;
3099 if (t
== TOK_NOSUBST
) {
3100 if (start_of_nosubsts
< 0)
3101 start_of_nosubsts
= macro_str1
.len
;
3103 start_of_nosubsts
= -1;
3105 tok_str_add2(¯o_str1
, t
, &cval
);
3107 tok_str_add(¯o_str1
, 0);
3108 //tok_print(" ###", macro_str1.str);
3109 return macro_str1
.str
;
3112 /* do macro substitution of macro_str and add result to
3113 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3114 inside to avoid recursing. */
3115 static void macro_subst(
3116 TokenString
*tok_str
,
3118 const int *macro_str
,
3124 int t
, spc
, nosubst
;
3126 int *macro_str1
= NULL
;
3128 /* first scan for '##' operator handling */
3132 /* first scan for '##' operator handling */
3133 if (can_read_stream
) {
3134 macro_str1
= macro_twosharps(ptr
);
3140 TOK_GET(&t
, &ptr
, &cval
);
3144 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3149 /* if nested substitution, do nothing */
3150 if (sym_find2(*nested_list
, t
)) {
3151 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3152 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3158 str
.str
= (int*)ptr
;
3159 begin_macro(&str
, 2);
3162 macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
3164 if (str
.alloc
== 3) {
3165 /* already finished by reading function macro arguments */
3173 spc
= tok_str
->len
&& is_space(tok_str
->str
[tok_str
->len
-1]);
3177 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3178 tcc_error("stray '\\' in program");
3181 if (!check_space(t
, &spc
))
3182 tok_str_add2(tok_str
, t
, &cval
);
3184 if (t
== TOK_NOSUBST
)
3189 tok_str_free(macro_str1
);
3193 /* return next token with macro substitution */
3194 ST_FUNC
void next(void)
3197 if (parse_flags
& PARSE_FLAG_SPACES
)
3203 if (tok
== TOK_NOSUBST
|| tok
== TOK_PLCHLDR
) {
3204 /* discard preprocessor markers */
3206 } else if (tok
== 0) {
3207 /* end of macro or unget token string */
3211 } else if (tok
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3213 /* if reading from file, try to substitute macros */
3214 s
= define_find(tok
);
3216 static TokenString str
; /* using static string for speed */
3217 Sym
*nested_list
= NULL
;
3220 macro_subst_tok(&str
, &nested_list
, s
, 1);
3221 tok_str_add(&str
, 0);
3222 begin_macro(&str
, 0);
3226 /* convert preprocessor tokens into C tokens */
3227 if (tok
== TOK_PPNUM
) {
3228 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3229 parse_number((char *)tokc
.cstr
->data
);
3230 } else if (tok
== TOK_PPSTR
) {
3231 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3232 parse_string((char *)tokc
.cstr
->data
, tokc
.cstr
->size
- 1);
3236 /* push back current token and set current token to 'last_tok'. Only
3237 identifier case handled for labels. */
3238 ST_INLN
void unget_tok(int last_tok
)
3240 TokenString
*str
= tcc_malloc(sizeof *str
);
3242 tok_str_add2(str
, tok
, &tokc
);
3243 tok_str_add(str
, 0);
3244 begin_macro(str
, 1);
3248 /* better than nothing, but needs extension to handle '-E' option
3250 ST_FUNC
void preprocess_init(TCCState
*s1
)
3252 s1
->include_stack_ptr
= s1
->include_stack
;
3253 /* XXX: move that before to avoid having to initialize
3254 file->ifdef_stack_ptr ? */
3255 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3256 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3258 pvtop
= vtop
= vstack
- 1;
3259 s1
->pack_stack
[0] = 0;
3260 s1
->pack_stack_ptr
= s1
->pack_stack
;
3262 isidnum_table
['$' - CH_EOF
] =
3263 tcc_state
->dollars_in_identifiers
? IS_ID
: 0;
3266 ST_FUNC
void preprocess_new(void)
3271 /* init isid table */
3272 for(i
= CH_EOF
; i
<256; i
++)
3273 isidnum_table
[i
- CH_EOF
]
3274 = is_space(i
) ? IS_SPC
3279 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3281 tok_ident
= TOK_IDENT
;
3290 tok_alloc(p
, r
- p
- 1);
3295 ST_FUNC
void preprocess_delete(void)
3299 /* free -D and compiler defines */
3302 /* cleanup from error/setjmp */
3308 n
= tok_ident
- TOK_IDENT
;
3309 for(i
= 0; i
< n
; i
++)
3310 tcc_free(table_ident
[i
]);
3311 tcc_free(table_ident
);
3315 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
3318 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
)
3320 if (level
== 0 && f
->line_ref
&& (d
= f
->line_num
- f
->line_ref
) < 8) {
3322 fputs("\n", s1
->ppfp
), --d
;
3323 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
3324 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
3326 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
3327 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
3329 f
->line_ref
= f
->line_num
;
3332 /* Preprocess the current file */
3333 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3336 BufferedFile
**iptr
;
3337 int token_seen
, spcs
, level
;
3339 preprocess_init(s1
);
3340 define_start
= define_stack
;
3341 ch
= file
->buf_ptr
[0];
3342 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3343 parse_flags
= PARSE_FLAG_PREPROCESS
3344 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3345 | PARSE_FLAG_LINEFEED
3347 | PARSE_FLAG_ACCEPT_STRAYS
3351 do next(); while (tok
!= TOK_EOF
); return 0;
3354 token_seen
= spcs
= 0;
3355 pp_line(s1
, file
, 0);
3358 iptr
= s1
->include_stack_ptr
;
3362 level
= s1
->include_stack_ptr
- iptr
;
3365 pp_line(s1
, *iptr
, 0);
3366 pp_line(s1
, file
, level
);
3369 if (0 == token_seen
) {
3374 if (tok
== TOK_LINEFEED
) {
3378 pp_line(s1
, file
, 0);
3380 fputs(" ", s1
->ppfp
), --spcs
;
3383 } else if (tok
== TOK_LINEFEED
) {
3388 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);
3391 free_defines(define_start
);