2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 /********************************************************/
24 /* global variables */
26 ST_DATA
int tok_flags
;
27 /* additional informations about token */
28 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
29 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
30 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
31 #define TOK_FLAG_EOF 0x0008 /* end of file */
33 ST_DATA
int parse_flags
;
34 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
35 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
36 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
37 token. line feed is also
39 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
40 #define PARSE_FLAG_SPACES 0x0010 /* next() returns space tokens (for -E) */
42 ST_DATA
struct BufferedFile
*file
;
45 ST_DATA
const int *macro_ptr
;
46 ST_DATA CString tokcstr
; /* current parsed string, if any */
48 /* display benchmark infos */
49 ST_DATA
int total_lines
;
50 ST_DATA
int total_bytes
;
51 ST_DATA
int tok_ident
;
52 ST_DATA TokenSym
**table_ident
;
54 /* ------------------------------------------------------------------------- */
56 static int *macro_ptr_allocated
;
57 static const int *unget_saved_macro_ptr
;
58 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
59 static int unget_buffer_enabled
;
60 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
61 /* true if isid(c) || isnum(c) */
62 static unsigned char isidnum_table
[256-CH_EOF
];
64 static const char tcc_keywords
[] =
65 #define DEF(id, str) str "\0"
70 /* WARNING: the content of this string encodes token numbers */
71 static const unsigned char tok_two_chars
[] =
73 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
74 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
95 '.','.', 0xa8, // C++ token ?
96 '#','#', TOK_TWOSHARPS
,
101 struct macro_level
*prev
;
105 static void next_nomacro_spc(void);
106 static void macro_subst(
107 TokenString
*tok_str
,
109 const int *macro_str
,
110 struct macro_level
**can_read_stream
113 ST_FUNC
void skip(int c
)
116 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
120 ST_FUNC
void expect(const char *msg
)
122 tcc_error("%s expected", msg
);
125 /* ------------------------------------------------------------------------- */
126 /* CString handling */
127 static void cstr_realloc(CString
*cstr
, int new_size
)
132 size
= cstr
->size_allocated
;
134 size
= 8; /* no need to allocate a too small first string */
135 while (size
< new_size
)
137 data
= tcc_realloc(cstr
->data_allocated
, size
);
138 cstr
->data_allocated
= data
;
139 cstr
->size_allocated
= size
;
144 ST_FUNC
void cstr_ccat(CString
*cstr
, int ch
)
147 size
= cstr
->size
+ 1;
148 if (size
> cstr
->size_allocated
)
149 cstr_realloc(cstr
, size
);
150 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
154 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
)
166 /* add a wide char */
167 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
170 size
= cstr
->size
+ sizeof(nwchar_t
);
171 if (size
> cstr
->size_allocated
)
172 cstr_realloc(cstr
, size
);
173 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
177 ST_FUNC
void cstr_new(CString
*cstr
)
179 memset(cstr
, 0, sizeof(CString
));
182 /* free string and reset it to NULL */
183 ST_FUNC
void cstr_free(CString
*cstr
)
185 tcc_free(cstr
->data_allocated
);
189 /* reset string to empty */
190 ST_FUNC
void cstr_reset(CString
*cstr
)
196 static void add_char(CString
*cstr
, int c
)
198 if (c
== '\'' || c
== '\"' || c
== '\\') {
199 /* XXX: could be more precise if char or string */
200 cstr_ccat(cstr
, '\\');
202 if (c
>= 32 && c
<= 126) {
205 cstr_ccat(cstr
, '\\');
207 cstr_ccat(cstr
, 'n');
209 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
210 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
211 cstr_ccat(cstr
, '0' + (c
& 7));
216 /* ------------------------------------------------------------------------- */
217 /* allocate a new token */
218 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
220 TokenSym
*ts
, **ptable
;
223 if (tok_ident
>= SYM_FIRST_ANOM
)
224 tcc_error("memory full (symbols)");
226 /* expand token table if needed */
227 i
= tok_ident
- TOK_IDENT
;
228 if ((i
% TOK_ALLOC_INCR
) == 0) {
229 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
230 table_ident
= ptable
;
233 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
235 ts
->tok
= tok_ident
++;
236 ts
->sym_define
.data
= tcc_malloc(sizeof(Sym
**));
237 ts
->sym_define
.off
= 0;
238 ts
->sym_define
.data
[0] = NULL
;
239 ts
->sym_define
.size
= 1;
240 ts
->sym_label
= NULL
;
241 ts
->sym_struct
= NULL
;
242 ts
->sym_identifier
= NULL
;
244 ts
->hash_next
= NULL
;
245 memcpy(ts
->str
, str
, len
);
251 #define TOK_HASH_INIT 1
252 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
254 /* find a token and add it if not found */
255 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
263 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
264 h
&= (TOK_HASH_SIZE
- 1);
266 pts
= &hash_ident
[h
];
271 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
273 pts
= &(ts
->hash_next
);
275 return tok_alloc_new(pts
, str
, len
);
278 /* XXX: buffer overflow */
279 /* XXX: float tokens */
280 ST_FUNC
char *get_tok_str(int v
, CValue
*cv
)
282 static char buf
[STRING_MAX_SIZE
+ 1];
283 static CString cstr_buf
;
288 /* NOTE: to go faster, we give a fixed buffer for small strings */
289 cstr_reset(&cstr_buf
);
291 cstr_buf
.size_allocated
= sizeof(buf
);
294 /* just an explanation, should never happen:
295 if (v <= TOK_LINENUM && v >= TOK_CINT && cv == NULL)
296 tcc_error("internal error: get_tok_str"); */
301 /* XXX: not quite exact, but only useful for testing */
302 sprintf(p
, "%u", cv
->ui
);
306 /* XXX: not quite exact, but only useful for testing */
308 sprintf(p
, "%u", (unsigned)cv
->ull
);
310 sprintf(p
, "%llu", cv
->ull
);
314 cstr_ccat(&cstr_buf
, 'L');
316 cstr_ccat(&cstr_buf
, '\'');
317 add_char(&cstr_buf
, cv
->i
);
318 cstr_ccat(&cstr_buf
, '\'');
319 cstr_ccat(&cstr_buf
, '\0');
323 len
= cstr
->size
- 1;
325 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
326 cstr_ccat(&cstr_buf
, '\0');
329 cstr_ccat(&cstr_buf
, 'L');
332 cstr_ccat(&cstr_buf
, '\"');
334 len
= cstr
->size
- 1;
336 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
338 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
340 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
342 cstr_ccat(&cstr_buf
, '\"');
343 cstr_ccat(&cstr_buf
, '\0');
350 return NULL
; /* should not happen */
352 /* above tokens have value, the ones below don't */
361 return strcpy(p
, "...");
363 return strcpy(p
, "<<=");
365 return strcpy(p
, ">>=");
368 /* search in two bytes table */
369 const unsigned char *q
= tok_two_chars
;
382 } else if (v
< tok_ident
) {
383 return table_ident
[v
- TOK_IDENT
]->str
;
384 } else if (v
>= SYM_FIRST_ANOM
) {
385 /* special name for anonymous symbol */
386 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
388 /* should never happen */
393 return cstr_buf
.data
;
396 /* fill input buffer and peek next char */
397 static int tcc_peekc_slow(BufferedFile
*bf
)
400 /* only tries to read if really end of buffer */
401 if (bf
->buf_ptr
>= bf
->buf_end
) {
403 #if defined(PARSE_DEBUG)
408 len
= read(bf
->fd
, bf
->buffer
, len
);
415 bf
->buf_ptr
= bf
->buffer
;
416 bf
->buf_end
= bf
->buffer
+ len
;
417 *bf
->buf_end
= CH_EOB
;
419 if (bf
->buf_ptr
< bf
->buf_end
) {
420 return bf
->buf_ptr
[0];
422 bf
->buf_ptr
= bf
->buf_end
;
427 /* return the current character, handling end of block if necessary
429 ST_FUNC
int handle_eob(void)
431 return tcc_peekc_slow(file
);
434 /* read next char from current input file and handle end of input buffer */
435 ST_INLN
void inp(void)
437 ch
= *(++(file
->buf_ptr
));
438 /* end of buffer/file handling */
443 /* handle '\[\r]\n' */
444 static int handle_stray_noerror(void)
451 } else if (ch
== '\r') {
465 static void handle_stray(void)
467 if (handle_stray_noerror())
468 tcc_error("stray '\\' in program");
471 /* skip the stray and handle the \\n case. Output an error if
472 incorrect char after the stray */
473 static int handle_stray1(uint8_t *p
)
477 if (p
>= file
->buf_end
) {
494 /* handle just the EOB case, but not stray */
495 #define PEEKC_EOB(c, p)\
506 /* handle the complicated stray case */
512 c = handle_stray1(p);\
517 /* input with '\[\r]\n' handling. Note that this function cannot
518 handle other characters after '\', so you cannot call it inside
519 strings or comments */
520 ST_FUNC
void minp(void)
528 /* single line C++ comments */
529 static uint8_t *parse_line_comment(uint8_t *p
)
537 if (c
== '\n' || c
== CH_EOF
) {
539 } else if (c
== '\\') {
548 } else if (c
== '\r') {
566 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
575 if (c
== '\n' || c
== '*' || c
== '\\')
579 if (c
== '\n' || c
== '*' || c
== '\\')
583 /* now we can handle all the cases */
587 } else if (c
== '*') {
593 } else if (c
== '/') {
595 } else if (c
== '\\') {
600 /* skip '\[\r]\n', otherwise just skip the stray */
606 } else if (c
== '\r') {
623 /* stray, eob or eof */
628 tcc_error("unexpected end of file in comment");
629 } else if (c
== '\\') {
641 static inline void skip_spaces(void)
647 static inline int check_space(int t
, int *spc
)
658 /* parse a string without interpreting escapes */
659 static uint8_t *parse_pp_string(uint8_t *p
,
660 int sep
, CString
*str
)
668 } else if (c
== '\\') {
674 /* XXX: indicate line number of start of string */
675 tcc_error("missing terminating %c character", sep
);
676 } else if (c
== '\\') {
677 /* escape : just skip \[\r]\n */
682 } else if (c
== '\r') {
685 expect("'\n' after '\r'");
688 } else if (c
== CH_EOF
) {
689 goto unterminated_string
;
692 cstr_ccat(str
, '\\');
698 } else if (c
== '\n') {
701 } else if (c
== '\r') {
705 cstr_ccat(str
, '\r');
721 /* skip block of text until #else, #elif or #endif. skip also pairs of
723 static void preprocess_skip(void)
725 int a
, start_of_line
, c
, in_warn_or_error
;
732 in_warn_or_error
= 0;
753 } else if (c
== '\\') {
754 ch
= file
->buf_ptr
[0];
755 handle_stray_noerror();
762 if (in_warn_or_error
)
764 p
= parse_pp_string(p
, c
, NULL
);
768 if (in_warn_or_error
)
775 p
= parse_comment(p
);
776 } else if (ch
== '/') {
777 p
= parse_line_comment(p
);
787 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
789 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
791 else if (tok
== TOK_ENDIF
)
793 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
794 in_warn_or_error
= 1;
795 else if (tok
== TOK_LINEFEED
)
810 /* ParseState handling */
812 /* XXX: currently, no include file info is stored. Thus, we cannot display
813 accurate messages if the function or data definition spans multiple
816 /* save current parse state in 's' */
817 ST_FUNC
void save_parse_state(ParseState
*s
)
819 s
->line_num
= file
->line_num
;
820 s
->macro_ptr
= macro_ptr
;
825 /* restore parse state from 's' */
826 ST_FUNC
void restore_parse_state(ParseState
*s
)
828 file
->line_num
= s
->line_num
;
829 macro_ptr
= s
->macro_ptr
;
834 /* return the number of additional 'ints' necessary to store the
836 static inline int tok_ext_size(int t
)
850 tcc_error("unsupported token");
857 return LDOUBLE_SIZE
/ 4;
863 /* token string handling */
865 ST_INLN
void tok_str_new(TokenString
*s
)
869 s
->allocated_len
= 0;
870 s
->last_line_num
= -1;
873 ST_FUNC
void tok_str_free(int *str
)
878 static int *tok_str_realloc(TokenString
*s
)
882 if (s
->allocated_len
== 0) {
885 len
= s
->allocated_len
* 2;
887 str
= tcc_realloc(s
->str
, len
* sizeof(int));
888 s
->allocated_len
= len
;
893 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
899 if (len
>= s
->allocated_len
)
900 str
= tok_str_realloc(s
);
905 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
912 /* allocate space for worst case */
913 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
914 str
= tok_str_realloc(s
);
923 str
[len
++] = cv
->tab
[0];
932 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
933 while ((len
+ nb_words
) > s
->allocated_len
)
934 str
= tok_str_realloc(s
);
935 cstr
= (CString
*)(str
+ len
);
937 cstr
->size
= cv
->cstr
->size
;
938 cstr
->data_allocated
= NULL
;
939 cstr
->size_allocated
= cstr
->size
;
940 memcpy((char *)cstr
+ sizeof(CString
),
941 cv
->cstr
->data
, cstr
->size
);
948 #if LDOUBLE_SIZE == 8
951 str
[len
++] = cv
->tab
[0];
952 str
[len
++] = cv
->tab
[1];
954 #if LDOUBLE_SIZE == 12
956 str
[len
++] = cv
->tab
[0];
957 str
[len
++] = cv
->tab
[1];
958 str
[len
++] = cv
->tab
[2];
959 #elif LDOUBLE_SIZE == 16
961 str
[len
++] = cv
->tab
[0];
962 str
[len
++] = cv
->tab
[1];
963 str
[len
++] = cv
->tab
[2];
964 str
[len
++] = cv
->tab
[3];
965 #elif LDOUBLE_SIZE != 8
966 #error add long double size support
975 /* add the current parse token in token string 's' */
976 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
980 /* save line number info */
981 if (file
->line_num
!= s
->last_line_num
) {
982 s
->last_line_num
= file
->line_num
;
983 cval
.i
= s
->last_line_num
;
984 tok_str_add2(s
, TOK_LINENUM
, &cval
);
986 tok_str_add2(s
, tok
, &tokc
);
989 /* get a token from an integer array and increment pointer
990 accordingly. we code it as a macro to avoid pointer aliasing. */
991 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1009 cv
->cstr
= (CString
*)p
;
1010 cv
->cstr
->data
= (char *)p
+ sizeof(CString
);
1011 p
+= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
1019 #if LDOUBLE_SIZE == 16
1021 #elif LDOUBLE_SIZE == 12
1023 #elif LDOUBLE_SIZE == 8
1026 # error add long double size support
1039 static int macro_is_equal(const int *a
, const int *b
)
1041 char buf
[STRING_MAX_SIZE
+ 1];
1045 TOK_GET(&t
, &a
, &cv
);
1046 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1047 TOK_GET(&t
, &b
, &cv
);
1048 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1054 /* defines handling */
1055 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1060 if (s
&& !macro_is_equal(s
->d
, str
))
1061 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1062 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1064 s
->next
= first_arg
;
1065 def
= &table_ident
[v
- TOK_IDENT
]->sym_define
;
1066 def
->data
[def
->off
] = s
;
1069 /* undefined a define symbol. Its name is just set to zero */
1070 ST_FUNC
void define_undef(Sym
*s
)
1074 v
= s
->v
- TOK_IDENT
;
1075 if ((unsigned)v
< (unsigned)(tok_ident
- TOK_IDENT
)){
1076 def
= &table_ident
[v
]->sym_define
;
1077 def
->data
[def
->off
] = NULL
;
1081 ST_INLN Sym
*define_find(int v
)
1085 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1087 def
= &table_ident
[v
]->sym_define
;
1088 return def
->data
[def
->off
];
1091 /* free define stack until top reaches 'b' */
1092 ST_FUNC
void free_defines(Sym
*b
)
1101 /* do not free args or predefined defines */
1103 tok_str_free(top
->d
);
1104 v
= top
->v
- TOK_IDENT
;
1105 if ((unsigned)v
< (unsigned)(tok_ident
- TOK_IDENT
)){
1106 def
= &table_ident
[v
]->sym_define
;
1110 def
->data
[0] = NULL
;
1119 ST_FUNC Sym
*label_find(int v
)
1122 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1124 return table_ident
[v
]->sym_label
;
1127 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1130 s
= sym_push2(ptop
, v
, 0, 0);
1132 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1133 if (ptop
== &global_label_stack
) {
1134 /* modify the top most local identifier, so that
1135 sym_identifier will point to 's' when popped */
1137 ps
= &(*ps
)->prev_tok
;
1144 /* pop labels until element last is reached. Look if any labels are
1145 undefined. Define symbols if '&&label' was used. */
1146 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1149 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1151 if (s
->r
== LABEL_DECLARED
) {
1152 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1153 } else if (s
->r
== LABEL_FORWARD
) {
1154 tcc_error("label '%s' used but not defined",
1155 get_tok_str(s
->v
, NULL
));
1158 /* define corresponding symbol. A size of
1160 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1164 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1170 /* eval an expression for #if/#elif */
1171 static int expr_preprocess(void)
1177 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1178 next(); /* do macro subst */
1179 if (tok
== TOK_DEFINED
) {
1184 c
= define_find(tok
) != 0;
1189 } else if (tok
>= TOK_IDENT
) {
1190 /* if undefined macro */
1194 tok_str_add_tok(&str
);
1196 tok_str_add(&str
, -1); /* simulate end of file */
1197 tok_str_add(&str
, 0);
1198 /* now evaluate C constant expression */
1199 macro_ptr
= str
.str
;
1203 tok_str_free(str
.str
);
1207 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1208 static void tok_print(int *str
)
1215 TOK_GET(&t
, &str
, &cval
);
1218 printf("%s", get_tok_str(t
, &cval
));
1224 /* parse after #define */
1225 ST_FUNC
void parse_define(void)
1227 Sym
*s
, *first
, **ps
;
1228 int v
, t
, varg
, is_vaargs
, spc
, ptok
, macro_list_start
;
1233 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1234 /* XXX: should check if same macro (ANSI) */
1237 /* '(' must be just after macro definition for MACRO_FUNC */
1242 while (tok
!= ')') {
1246 if (varg
== TOK_DOTS
) {
1247 varg
= TOK___VA_ARGS__
;
1249 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1253 if (varg
< TOK_IDENT
)
1254 tcc_error("badly punctuated parameter list");
1255 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1268 /* EOF testing necessary for '-D' handling */
1270 macro_list_start
= 1;
1271 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1272 if (!macro_list_start
&& spc
== 2 && tok
== TOK_TWOSHARPS
)
1273 tcc_error("'##' invalid at start of macro");
1275 /* remove spaces around ## and after '#' */
1276 if (TOK_TWOSHARPS
== tok
) {
1280 } else if ('#' == tok
) {
1282 } else if (check_space(tok
, &spc
)) {
1285 tok_str_add2(&str
, tok
, &tokc
);
1288 macro_list_start
= 0;
1290 if (ptok
== TOK_TWOSHARPS
)
1291 tcc_error("'##' invalid at end of macro");
1293 --str
.len
; /* remove trailing space */
1294 tok_str_add(&str
, 0);
1296 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
1299 define_push(v
, t
, str
.str
, first
);
1302 static inline int hash_cached_include(const char *filename
)
1304 const unsigned char *s
;
1308 s
= (unsigned char *) filename
;
1310 h
= TOK_HASH_FUNC(h
, *s
);
1313 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1317 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1321 h
= hash_cached_include(filename
);
1322 i
= s1
->cached_includes_hash
[h
];
1326 e
= s1
->cached_includes
[i
- 1];
1327 if (0 == PATHCMP(e
->filename
, filename
))
1334 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1339 if (search_cached_include(s1
, filename
))
1342 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1344 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1345 strcpy(e
->filename
, filename
);
1346 e
->ifndef_macro
= ifndef_macro
;
1347 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1348 /* add in hash table */
1349 h
= hash_cached_include(filename
);
1350 e
->hash_next
= s1
->cached_includes_hash
[h
];
1351 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1354 /* is_bof is true if first non space token at beginning of file */
1355 ST_FUNC
void preprocess(int is_bof
)
1357 TCCState
*s1
= tcc_state
;
1358 int i
, c
, n
, saved_parse_flags
;
1359 uint8_t buf
[1024], *p
;
1362 saved_parse_flags
= parse_flags
;
1363 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
| PARSE_FLAG_LINEFEED
;
1373 s
= define_find(tok
);
1374 /* undefine symbol by putting an invalid name */
1379 case TOK_INCLUDE_NEXT
:
1380 ch
= file
->buf_ptr
[0];
1381 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1386 } else if (ch
== '\"') {
1391 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1392 if ((p
- buf
) < sizeof(buf
) - 1)
1395 if (handle_stray_noerror() == 0)
1401 goto include_syntax
;
1405 /* eat all spaces and comments after include */
1406 /* XXX: slightly incorrect */
1407 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1411 /* computed #include : either we have only strings or
1412 we have anything enclosed in '<>' */
1415 if (tok
== TOK_STR
) {
1416 while (tok
!= TOK_LINEFEED
) {
1417 if (tok
!= TOK_STR
) {
1419 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1421 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1427 while (tok
!= TOK_LINEFEED
) {
1428 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1432 /* check syntax and remove '<>' */
1433 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1434 goto include_syntax
;
1435 memmove(buf
, buf
+ 1, len
- 2);
1436 buf
[len
- 2] = '\0';
1441 tcc_error(" empty filename in #include");
1443 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1444 tcc_error("#include recursion too deep");
1445 /* store current file in stack, but increment stack later below */
1446 *s1
->include_stack_ptr
= file
;
1448 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1449 for (i
= -2; i
< n
; ++i
) {
1450 char buf1
[sizeof file
->filename
];
1456 /* check absolute include path */
1457 if (!IS_ABSPATH(buf
))
1460 i
= n
; /* force end loop */
1462 } else if (i
== -1) {
1463 /* search in current dir if "header.h" */
1466 path
= file
->filename
;
1467 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1470 /* search in all the include paths */
1471 if (i
< s1
->nb_include_paths
)
1472 path
= s1
->include_paths
[i
];
1474 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1475 pstrcpy(buf1
, sizeof(buf1
), path
);
1476 pstrcat(buf1
, sizeof(buf1
), "/");
1479 pstrcat(buf1
, sizeof(buf1
), buf
);
1481 if (tok
== TOK_INCLUDE_NEXT
)
1482 for (f
= s1
->include_stack_ptr
; f
>= s1
->include_stack
; --f
)
1483 if (0 == PATHCMP((*f
)->filename
, buf1
)) {
1485 printf("%s: #include_next skipping %s\n", file
->filename
, buf1
);
1487 goto include_trynext
;
1490 e
= search_cached_include(s1
, buf1
);
1491 if (e
&& define_find(e
->ifndef_macro
)) {
1492 /* no need to parse the include because the 'ifndef macro'
1495 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1500 if (tcc_open(s1
, buf1
) < 0)
1505 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1507 /* update target deps */
1508 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
, tcc_strdup(buf1
));
1509 /* push current file in stack */
1510 ++s1
->include_stack_ptr
;
1511 /* add include file debug info */
1513 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1514 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1515 ch
= file
->buf_ptr
[0];
1518 tcc_error("include file '%s' not found", buf
);
1525 c
= expr_preprocess();
1531 if (tok
< TOK_IDENT
)
1532 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1536 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1538 file
->ifndef_macro
= tok
;
1541 c
= !!define_find(tok
) ^ c
;
1543 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1544 tcc_error("memory full (ifdef)");
1545 *s1
->ifdef_stack_ptr
++ = c
;
1548 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1549 tcc_error("#else without matching #if");
1550 if (s1
->ifdef_stack_ptr
[-1] & 2)
1551 tcc_error("#else after #else");
1552 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1555 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1556 tcc_error("#elif without matching #if");
1557 c
= s1
->ifdef_stack_ptr
[-1];
1559 tcc_error("#elif after #else");
1560 /* last #if/#elif expression was true: we skip */
1563 c
= expr_preprocess();
1564 s1
->ifdef_stack_ptr
[-1] = c
;
1566 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1567 file
->ifndef_macro
= 0;
1577 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1578 tcc_error("#endif without matching #if");
1579 s1
->ifdef_stack_ptr
--;
1580 /* '#ifndef macro' was at the start of file. Now we check if
1581 an '#endif' is exactly at the end of file */
1582 if (file
->ifndef_macro
&&
1583 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1584 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1585 /* need to set to zero to avoid false matches if another
1586 #ifndef at middle of file */
1587 file
->ifndef_macro
= 0;
1588 tok_flags
|= TOK_FLAG_ENDIF
;
1591 if (tok
!= TOK_LINEFEED
)
1592 tcc_warning("Ignoring: %s", get_tok_str(tok
, &tokc
));
1596 if (tok
!= TOK_CINT
)
1598 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
1600 if (tok
!= TOK_LINEFEED
) {
1603 pstrcpy(file
->filename
, sizeof(file
->filename
), (char *)tokc
.cstr
->data
);
1609 ch
= file
->buf_ptr
[0];
1612 while (ch
!= '\n' && ch
!= CH_EOF
) {
1613 if ((p
- buf
) < sizeof(buf
) - 1)
1616 if (handle_stray_noerror() == 0)
1623 tcc_error("#error %s", buf
);
1625 tcc_warning("#warning %s", buf
);
1629 if (tok
== TOK_pack
&& parse_flags
& PARSE_FLAG_PACK
) {
1632 #pragma pack(1) // set
1633 #pragma pack() // reset to default
1634 #pragma pack(push,1) // push & set
1635 #pragma pack(pop) // restore previous
1639 if (tok
== TOK_ASM_pop
) {
1641 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1643 tcc_error("out of pack stack");
1645 s1
->pack_stack_ptr
--;
1649 if (tok
== TOK_ASM_push
) {
1651 s1
->pack_stack_ptr
++;
1652 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
)
1656 if (tok
!= TOK_CINT
) {
1658 tcc_error("invalid pack pragma");
1661 if (val
< 1 || val
> 16)
1663 if (val
< 1 || val
> 16)
1664 tcc_error("Value must be greater than 1 is less than or equal to 16");
1665 if ((val
& (val
- 1)) != 0)
1666 tcc_error("Value must be a power of 2 curtain");
1669 *s1
->pack_stack_ptr
= val
;
1672 }else if (tok
== TOK_PUSH_MACRO
|| tok
== TOK_POP_MACRO
) {
1678 ch
= file
->buf_ptr
[0];
1681 goto macro_xxx_syntax
;
1682 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1688 while (ch
!= '\"' && ch
!= '\n' && ch
!= CH_EOF
) {
1689 if ((p
- buf
) < sizeof(buf
) - 1)
1698 goto macro_xxx_syntax
;
1703 /* computed #pragma macro_xxx for #define xxx */
1706 while (tok
!= ')') {
1707 if (tok
!= TOK_STR
) {
1709 tcc_error("'macro_xxx' expects (\"NAME\")");
1711 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1717 tcc_error(" empty string in #pragma");
1720 while (is_space(*p
))
1724 if (!isidnum_table
[p
[0] - CH_EOF
])
1729 while (is_space(*p
))
1732 tcc_error("unrecognized string: %s", buf
);
1733 ts
= tok_alloc(p1
, len
);
1735 def
= &ts
->sym_define
;
1736 if(t
== TOK_PUSH_MACRO
){
1737 void *tmp
= def
->data
[def
->off
];
1740 if(def
->off
>= def
->size
){
1741 int size
= def
->size
;
1743 if (size
>= MACRO_STACK_SIZE
)
1744 tcc_error("stack full");
1745 def
->data
= tcc_realloc(def
->data
, size
*sizeof(Sym
**));
1748 def
->data
[def
->off
] = tmp
;
1754 tcc_warning("stack empty");
1759 fputs("#pragma ", s1
->ppfp
);
1760 while (tok
!= TOK_LINEFEED
){
1761 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);
1768 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_PPNUM
) {
1769 /* '!' is ignored to allow C scripts. numbers are ignored
1770 to emulate cpp behaviour */
1772 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
1773 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1775 /* this is a gas line comment in an 'S' file. */
1776 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1782 /* ignore other preprocess commands or #! for C scripts */
1783 while (tok
!= TOK_LINEFEED
)
1786 parse_flags
= saved_parse_flags
;
1789 /* evaluate escape codes in a string. */
1790 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1805 case '0': case '1': case '2': case '3':
1806 case '4': case '5': case '6': case '7':
1807 /* at most three octal digits */
1812 n
= n
* 8 + c
- '0';
1816 n
= n
* 8 + c
- '0';
1821 goto add_char_nonext
;
1829 if (c
>= 'a' && c
<= 'f')
1831 else if (c
>= 'A' && c
<= 'F')
1841 goto add_char_nonext
;
1865 goto invalid_escape
;
1875 if (c
>= '!' && c
<= '~')
1876 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1878 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1885 cstr_ccat(outstr
, c
);
1887 cstr_wccat(outstr
, c
);
1889 /* add a trailing '\0' */
1891 cstr_ccat(outstr
, '\0');
1893 cstr_wccat(outstr
, '\0');
1896 /* parse number in null terminated string 'p' and return it in the
1898 static void parse_number(const char *p
)
1907 goto float_frac_parse
;
1910 if (t
== 'x' || t
== 'X') {
1913 } else if (tcc_ext
&& (t
== 'b' || t
== 'B')) {
1921 if(strchr(p
, '.') || (b
== 10 && (strchr(p
,'e') || strchr(p
,'E'))) ||
1922 ((b
== 2 || b
== 16)&& (strchr(p
,'p') || strchr(p
,'P')))){
1923 long double ld
, sh
, fb
;
1925 /* NOTE: strtox should support that for hexa numbers, but
1926 non ISOC99 libcs do not support it, so we prefer to do
1928 /* hexadecimal or binary floats */
1929 /* XXX: handle overflows */
1938 if (c
>= 'a' && c
<= 'f')
1940 else if (c
>= 'A' && c
<= 'F')
1947 tcc_error("invalid digit");
1957 if (c
>= 'a' && c
<= 'f')
1959 else if (c
>= 'A' && c
<= 'F')
1966 if(b
== 10 && (c
== 'e' || c
== 'E' || c
== 'f' || c
== 'F'))
1968 tcc_error("invalid digit");
1975 if ((b
== 16 || b
== 2) && c
!= 'p' && c
!= 'P')
1977 if(((c
== 'e' || c
== 'E') && b
== 10) ||
1978 ((c
== 'p' || c
== 'P') && (b
== 16 || b
== 2))){
1980 if(c
== '+' || c
== '-'){
1987 expect("exponent digits");
1990 exp
= exp
* 10 + c
- '0';
2005 } else if (t
== 'L') {
2007 #ifdef TCC_TARGET_PE
2009 tokc
.d
= (double)ld
;
2016 tokc
.d
= (double)ld
;
2022 if (b
== 10 && c
== '0') {
2028 if (c
>= 'a' && c
<= 'f')
2030 else if (c
>= 'A' && c
<= 'F')
2037 tcc_error("invalid digit");
2040 if (n
< n1
&& warn
){
2041 tcc_warning("integer constant overflow");
2046 /* XXX: not exactly ANSI compliant */
2047 if ((n
& 0xffffffff00000000LL
) != 0) {
2052 } else if (n
> 0x7fffffff) {
2063 tcc_error("three 'l's in integer constant");
2065 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2068 if (tok
== TOK_CINT
)
2070 else if (tok
== TOK_CUINT
)
2072 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2076 } else if (t
== 'U') {
2078 tcc_error("two 'u's in integer constant");
2080 if (tok
== TOK_CINT
)
2082 else if (tok
== TOK_CLLONG
)
2089 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2095 tcc_error("invalid number\n");
2099 #define PARSE2(c1, tok1, c2, tok2) \
2110 /* return next token without macro substitution */
2111 static inline void next_nomacro1(void)
2126 goto keep_tok_flags
;
2133 /* first look if it is in fact an end of buffer */
2134 if (p
>= file
->buf_end
) {
2138 if (p
>= file
->buf_end
)
2151 TCCState
*s1
= tcc_state
;
2152 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2153 && !(tok_flags
& TOK_FLAG_EOF
)) {
2154 tok_flags
|= TOK_FLAG_EOF
;
2156 goto keep_tok_flags
;
2157 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2159 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2160 tcc_error("missing #endif");
2161 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2162 /* no include left : end of file. */
2165 tok_flags
&= ~TOK_FLAG_EOF
;
2166 /* pop include file */
2168 /* test if previous '#endif' was after a #ifdef at
2170 if (tok_flags
& TOK_FLAG_ENDIF
) {
2172 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2174 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2175 tok_flags
&= ~TOK_FLAG_ENDIF
;
2178 /* add end of include file debug info */
2179 if (tcc_state
->do_debug
) {
2180 put_stabd(N_EINCL
, 0, 0);
2182 /* pop include stack */
2184 s1
->include_stack_ptr
--;
2193 tok_flags
|= TOK_FLAG_BOL
;
2196 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2199 goto keep_tok_flags
;
2204 if ((tok_flags
& TOK_FLAG_BOL
) &&
2205 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2207 preprocess(tok_flags
& TOK_FLAG_BOF
);
2213 tok
= TOK_TWOSHARPS
;
2215 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
2216 p
= parse_line_comment(p
- 1);
2225 case 'a': case 'b': case 'c': case 'd':
2226 case 'e': case 'f': case 'g': case 'h':
2227 case 'i': case 'j': case 'k': case 'l':
2228 case 'm': case 'n': case 'o': case 'p':
2229 case 'q': case 'r': case 's': case 't':
2230 case 'u': case 'v': case 'w': case 'x':
2232 case 'A': case 'B': case 'C': case 'D':
2233 case 'E': case 'F': case 'G': case 'H':
2234 case 'I': case 'J': case 'K':
2235 case 'M': case 'N': case 'O': case 'P':
2236 case 'Q': case 'R': case 'S': case 'T':
2237 case 'U': case 'V': case 'W': case 'X':
2243 h
= TOK_HASH_FUNC(h
, c
);
2247 if (!isidnum_table
[c
-CH_EOF
])
2249 h
= TOK_HASH_FUNC(h
, c
);
2256 /* fast case : no stray found, so we have the full token
2257 and we have already hashed it */
2259 h
&= (TOK_HASH_SIZE
- 1);
2260 pts
= &hash_ident
[h
];
2265 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2267 pts
= &(ts
->hash_next
);
2269 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2273 cstr_reset(&tokcstr
);
2276 cstr_ccat(&tokcstr
, *p1
);
2282 while (isidnum_table
[c
-CH_EOF
]) {
2283 cstr_ccat(&tokcstr
, c
);
2286 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2292 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2294 goto parse_ident_fast
;
2297 if (c
== '\'' || c
== '\"') {
2301 cstr_reset(&tokcstr
);
2302 cstr_ccat(&tokcstr
, 'L');
2303 goto parse_ident_slow
;
2307 case '0': case '1': case '2': case '3':
2308 case '4': case '5': case '6': case '7':
2311 cstr_reset(&tokcstr
);
2312 /* after the first digit, accept digits, alpha, '.' or sign if
2313 prefixed by 'eEpP' */
2317 cstr_ccat(&tokcstr
, c
);
2319 if (!(isnum(c
) || isid(c
) || c
== '.' ||
2320 ((c
== '+' || c
== '-') &&
2321 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
2324 /* We add a trailing '\0' to ease parsing */
2325 cstr_ccat(&tokcstr
, '\0');
2326 tokc
.cstr
= &tokcstr
;
2330 /* special dot handling because it can also start a number */
2333 cstr_reset(&tokcstr
);
2334 cstr_ccat(&tokcstr
, '.');
2336 } else if (c
== '.') {
2356 /* parse the string */
2358 p
= parse_pp_string(p
, sep
, &str
);
2359 cstr_ccat(&str
, '\0');
2361 /* eval the escape (should be done as TOK_PPNUM) */
2362 cstr_reset(&tokcstr
);
2363 parse_escape_string(&tokcstr
, str
.data
, is_long
);
2368 /* XXX: make it portable */
2372 char_size
= sizeof(nwchar_t
);
2373 if (tokcstr
.size
<= char_size
)
2374 tcc_error("empty character constant");
2375 if (tokcstr
.size
> 2 * char_size
)
2376 tcc_warning("multi-character character constant");
2378 tokc
.i
= *(int8_t *)tokcstr
.data
;
2381 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2385 tokc
.cstr
= &tokcstr
;
2399 } else if (c
== '<') {
2417 } else if (c
== '>') {
2435 } else if (c
== '=') {
2448 } else if (c
== '=') {
2461 } else if (c
== '=') {
2474 } else if (c
== '=') {
2477 } else if (c
== '>') {
2485 PARSE2('!', '!', '=', TOK_NE
)
2486 PARSE2('=', '=', '=', TOK_EQ
)
2487 PARSE2('*', '*', '=', TOK_A_MUL
)
2488 PARSE2('%', '%', '=', TOK_A_MOD
)
2489 PARSE2('^', '^', '=', TOK_A_XOR
)
2491 /* comments or operator */
2495 p
= parse_comment(p
);
2496 /* comments replaced by a blank */
2498 goto keep_tok_flags
;
2499 } else if (c
== '/') {
2500 p
= parse_line_comment(p
);
2502 goto keep_tok_flags
;
2503 } else if (c
== '=') {
2523 case '$': /* only used in assembler */
2524 case '@': /* dito */
2529 tcc_error("unrecognized character \\x%02x", c
);
2535 #if defined(PARSE_DEBUG)
2536 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2540 /* return next token without macro substitution. Can read input from
2542 static void next_nomacro_spc(void)
2548 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2549 if (tok
== TOK_LINENUM
) {
2550 file
->line_num
= tokc
.i
;
2559 ST_FUNC
void next_nomacro(void)
2563 } while (is_space(tok
));
2566 /* substitute arguments in replacement lists in macro_str by the values in
2567 args (field d) and return allocated string */
2568 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2570 int last_tok
, t
, spc
;
2580 TOK_GET(&t
, ¯o_str
, &cval
);
2585 TOK_GET(&t
, ¯o_str
, &cval
);
2588 s
= sym_find2(args
, t
);
2594 TOK_GET(&t
, &st
, &cval
);
2595 if (!check_space(t
, &spc
))
2596 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2599 cstr_ccat(&cstr
, '\0');
2601 printf("stringize: %s\n", (char *)cstr
.data
);
2605 tok_str_add2(&str
, TOK_STR
, &cval
);
2608 tok_str_add2(&str
, t
, &cval
);
2610 } else if (t
>= TOK_IDENT
) {
2611 s
= sym_find2(args
, t
);
2614 /* if '##' is present before or after, no arg substitution */
2615 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
2616 /* special case for var arg macros : ## eats the
2617 ',' if empty VA_ARGS variable. */
2618 /* XXX: test of the ',' is not 100%
2619 reliable. should fix it to avoid security
2621 if (gnu_ext
&& s
->type
.t
&&
2622 last_tok
== TOK_TWOSHARPS
&&
2623 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
2624 if (*st
== TOK_PLCHLDR
) {
2625 /* suppress ',' '##' */
2628 /* suppress '##' and add variable */
2636 TOK_GET(&t1
, &st
, &cval
);
2639 tok_str_add2(&str
, t1
, &cval
);
2643 /* NOTE: the stream cannot be read when macro
2644 substituing an argument */
2645 macro_subst(&str
, nested_list
, st
, NULL
);
2648 tok_str_add(&str
, t
);
2651 tok_str_add2(&str
, t
, &cval
);
2655 tok_str_add(&str
, 0);
2659 static char const ab_month_name
[12][4] =
2661 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2662 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2665 /* do macro substitution of current token with macro 's' and add
2666 result to (tok_str,tok_len). 'nested_list' is the list of all
2667 macros we got inside to avoid recursing. Return non zero if no
2668 substitution needs to be done */
2669 static int macro_subst_tok(TokenString
*tok_str
,
2670 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
2672 Sym
*args
, *sa
, *sa1
;
2673 int mstr_allocated
, parlevel
, *mstr
, t
, t1
, spc
;
2681 /* if symbol is a macro, prepare substitution */
2682 /* special macros */
2683 if (tok
== TOK___LINE__
) {
2684 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2688 } else if (tok
== TOK___FILE__
) {
2689 cstrval
= file
->filename
;
2691 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2696 tm
= localtime(&ti
);
2697 if (tok
== TOK___DATE__
) {
2698 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2699 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2701 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2702 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2709 cstr_cat(&cstr
, cstrval
);
2710 cstr_ccat(&cstr
, '\0');
2712 tok_str_add2(tok_str
, t1
, &cval
);
2717 if (s
->type
.t
== MACRO_FUNC
) {
2718 /* NOTE: we do not use next_nomacro to avoid eating the
2719 next token. XXX: find better solution */
2723 while (is_space(t
= *p
) || TOK_LINEFEED
== t
)
2725 if (t
== 0 && can_read_stream
) {
2726 /* end of macro stream: we must look at the token
2727 after in the file */
2728 struct macro_level
*ml
= *can_read_stream
;
2734 *can_read_stream
= ml
-> prev
;
2736 /* also, end of scope for nested defined symbol */
2737 (*nested_list
)->v
= -1;
2741 ch
= file
->buf_ptr
[0];
2742 while (is_space(ch
) || ch
== '\n' || ch
== '/')
2747 uint8_t *p
= file
->buf_ptr
;
2750 p
= parse_comment(p
);
2751 file
->buf_ptr
= p
- 1;
2752 } else if (c
== '/') {
2753 p
= parse_line_comment(p
);
2754 file
->buf_ptr
= p
- 1;
2762 if (t
!= '(') /* no macro subst */
2765 /* argument macro */
2770 /* NOTE: empty args are allowed, except if no args */
2772 /* handle '()' case */
2773 if (!args
&& !sa
&& tok
== ')')
2776 tcc_error("macro '%s' used with too many args",
2777 get_tok_str(s
->v
, 0));
2780 /* NOTE: non zero sa->t indicates VA_ARGS */
2781 while ((parlevel
> 0 ||
2783 (tok
!= ',' || sa
->type
.t
))) &&
2787 else if (tok
== ')')
2789 if (tok
== TOK_LINEFEED
)
2791 if (!check_space(tok
, &spc
))
2792 tok_str_add2(&str
, tok
, &tokc
);
2796 tok_str_add(&str
, TOK_PLCHLDR
);
2798 tok_str_add(&str
, 0);
2799 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
2803 /* special case for gcc var args: add an empty
2804 var arg argument if it is omitted */
2805 if (sa
&& sa
->type
.t
&& gnu_ext
)
2815 tcc_error("macro '%s' used with too few args",
2816 get_tok_str(s
->v
, 0));
2819 /* now subst each arg */
2820 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
2825 tok_str_free(sa
->d
);
2831 sym_push2(nested_list
, s
->v
, 0, 0);
2832 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
2833 /* pop nested defined symbol */
2835 *nested_list
= sa1
->prev
;
2843 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2844 return the resulting string (which must be freed). */
2845 static inline int *macro_twosharps(const int *macro_str
)
2849 TokenString macro_str1
;
2851 int n
, start_of_nosubsts
;
2853 /* we search the first '##' */
2854 for(ptr
= macro_str
;;) {
2856 TOK_GET(&t
, &ptr
, &cval
);
2857 if (t
== TOK_TWOSHARPS
)
2859 /* nothing more to do if end of string */
2864 /* we saw '##', so we need more processing to handle it */
2865 start_of_nosubsts
= -1;
2866 tok_str_new(¯o_str1
);
2867 for(ptr
= macro_str
;;) {
2868 TOK_GET(&tok
, &ptr
, &tokc
);
2871 if (tok
== TOK_TWOSHARPS
)
2873 if (tok
== TOK_NOSUBST
&& start_of_nosubsts
< 0)
2874 start_of_nosubsts
= macro_str1
.len
;
2875 while (*ptr
== TOK_TWOSHARPS
) {
2876 /* given 'a##b', remove nosubsts preceding 'a' */
2877 if (start_of_nosubsts
>= 0)
2878 macro_str1
.len
= start_of_nosubsts
;
2879 /* given 'a##b', skip '##' */
2881 /* given 'a##b', remove nosubsts preceding 'b' */
2882 while (t
== TOK_NOSUBST
)
2884 if (t
&& t
!= TOK_TWOSHARPS
) {
2886 TOK_GET(&t
, &ptr
, &cval
);
2887 /* We concatenate the two tokens */
2889 if (tok
!= TOK_PLCHLDR
)
2890 cstr_cat(&cstr
, get_tok_str(tok
, &tokc
));
2892 if (t
!= TOK_PLCHLDR
|| tok
== TOK_PLCHLDR
)
2893 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2894 cstr_ccat(&cstr
, '\0');
2896 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
2897 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
2900 if (0 == *file
->buf_ptr
)
2902 tok_str_add2(¯o_str1
, tok
, &tokc
);
2903 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2904 n
, cstr
.data
, (char*)cstr
.data
+ n
);
2910 if (tok
!= TOK_NOSUBST
) {
2911 tok_str_add2(¯o_str1
, tok
, &tokc
);
2913 start_of_nosubsts
= -1;
2915 tok_str_add2(¯o_str1
, tok
, &tokc
);
2917 tok_str_add(¯o_str1
, 0);
2918 return macro_str1
.str
;
2922 /* do macro substitution of macro_str and add result to
2923 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2924 inside to avoid recursing. */
2925 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
2926 const int *macro_str
, struct macro_level
** can_read_stream
)
2933 struct macro_level ml
;
2936 /* first scan for '##' operator handling */
2938 macro_str1
= macro_twosharps(ptr
);
2946 /* NOTE: ptr == NULL can only happen if tokens are read from
2947 file stream due to a macro function call */
2950 TOK_GET(&t
, &ptr
, &cval
);
2953 if (t
== TOK_NOSUBST
) {
2954 /* following token has already been subst'd. just copy it on */
2955 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
2956 TOK_GET(&t
, &ptr
, &cval
);
2961 /* if nested substitution, do nothing */
2962 if (sym_find2(*nested_list
, t
)) {
2963 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
2964 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
2968 if (can_read_stream
)
2969 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
2970 macro_ptr
= (int *)ptr
;
2972 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
2973 ptr
= (int *)macro_ptr
;
2975 if (can_read_stream
&& *can_read_stream
== &ml
)
2976 *can_read_stream
= ml
.prev
;
2979 if (parse_flags
& PARSE_FLAG_SPACES
)
2984 tok_str_add(tok_str
, ' ');
2988 if (!check_space(t
, &spc
))
2989 tok_str_add2(tok_str
, t
, &cval
);
2993 tok_str_free(macro_str1
);
2996 /* return next token with macro substitution */
2997 ST_FUNC
void next(void)
2999 Sym
*nested_list
, *s
;
3001 struct macro_level
*ml
;
3004 if (parse_flags
& PARSE_FLAG_SPACES
)
3009 /* if not reading from macro substituted string, then try
3010 to substitute macros */
3011 if (tok
>= TOK_IDENT
&&
3012 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3013 s
= define_find(tok
);
3015 /* we have a macro: we try to substitute */
3019 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
3020 /* substitution done, NOTE: maybe empty */
3021 tok_str_add(&str
, 0);
3022 macro_ptr
= str
.str
;
3023 macro_ptr_allocated
= str
.str
;
3030 /* end of macro or end of unget buffer */
3031 if (unget_buffer_enabled
) {
3032 macro_ptr
= unget_saved_macro_ptr
;
3033 unget_buffer_enabled
= 0;
3035 /* end of macro string: free it */
3036 tok_str_free(macro_ptr_allocated
);
3037 macro_ptr_allocated
= NULL
;
3041 } else if (tok
== TOK_NOSUBST
) {
3042 /* discard preprocessor's nosubst markers */
3047 /* convert preprocessor tokens into C tokens */
3048 if (tok
== TOK_PPNUM
&&
3049 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
3050 parse_number((char *)tokc
.cstr
->data
);
3054 /* push back current token and set current token to 'last_tok'. Only
3055 identifier case handled for labels. */
3056 ST_INLN
void unget_tok(int last_tok
)
3060 if (unget_buffer_enabled
)
3062 /* assert(macro_ptr == unget_saved_buffer + 1);
3063 assert(*macro_ptr == 0); */
3067 unget_saved_macro_ptr
= macro_ptr
;
3068 unget_buffer_enabled
= 1;
3070 q
= unget_saved_buffer
;
3073 n
= tok_ext_size(tok
) - 1;
3076 *q
= 0; /* end of token string */
3081 /* better than nothing, but needs extension to handle '-E' option
3083 ST_FUNC
void preprocess_init(TCCState
*s1
)
3085 s1
->include_stack_ptr
= s1
->include_stack
;
3086 /* XXX: move that before to avoid having to initialize
3087 file->ifdef_stack_ptr ? */
3088 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3089 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3092 s1
->pack_stack
[0] = 0;
3093 s1
->pack_stack_ptr
= s1
->pack_stack
;
3096 ST_FUNC
void preprocess_new(void)
3101 /* init isid table */
3102 for(i
=CH_EOF
;i
<256;i
++)
3103 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
3105 /* add all tokens */
3107 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3109 tok_ident
= TOK_IDENT
;
3118 tok_alloc(p
, r
- p
- 1);
3123 /* Preprocess the current file */
3124 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3128 BufferedFile
*file_ref
, **iptr
, **iptr_new
;
3129 int token_seen
, line_ref
, d
;
3132 preprocess_init(s1
);
3133 define_start
= define_stack
;
3134 ch
= file
->buf_ptr
[0];
3135 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3136 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
3137 PARSE_FLAG_LINEFEED
| PARSE_FLAG_SPACES
;
3141 iptr
= s1
->include_stack_ptr
;
3142 tok
= TOK_LINEFEED
; /* print line */
3146 if (tok
== TOK_EOF
) {
3148 } else if (file
!= file_ref
) {
3150 } else if (tok
== TOK_LINEFEED
) {
3155 } else if (token_seen
) {
3156 d
= file
->line_num
- line_ref
;
3157 if (file
!= file_ref
|| d
< 0 || d
>= 8) {
3159 iptr_new
= s1
->include_stack_ptr
;
3160 s
= iptr_new
> iptr
? " 1"
3161 : iptr_new
< iptr
? " 2"
3162 : iptr_new
> s1
->include_stack
? " 3"
3165 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", file
->line_num
, file
->filename
, s
);
3168 fputs("\n", s1
->ppfp
), --d
;
3170 line_ref
= (file_ref
= file
)->line_num
;
3171 token_seen
= tok
== TOK_LINEFEED
;
3175 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);
3177 free_defines(define_start
);