2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 /********************************************************/
24 /* global variables */
26 ST_DATA
int tok_flags
;
27 /* additional informations about token */
28 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
29 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
30 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
31 #define TOK_FLAG_EOF 0x0008 /* end of file */
33 ST_DATA
int parse_flags
;
34 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
35 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
36 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
37 token. line feed is also
39 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
40 #define PARSE_FLAG_SPACES 0x0010 /* next() returns space tokens (for -E) */
42 ST_DATA
struct BufferedFile
*file
;
45 ST_DATA
const int *macro_ptr
;
46 ST_DATA CString tokcstr
; /* current parsed string, if any */
48 /* display benchmark infos */
49 ST_DATA
int total_lines
;
50 ST_DATA
int total_bytes
;
51 ST_DATA
int tok_ident
;
52 ST_DATA TokenSym
**table_ident
;
54 /* ------------------------------------------------------------------------- */
56 static int *macro_ptr_allocated
;
57 static const int *unget_saved_macro_ptr
;
58 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
59 static int unget_buffer_enabled
;
60 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
61 static char token_buf
[STRING_MAX_SIZE
+ 1];
62 /* true if isid(c) || isnum(c) */
63 static unsigned char isidnum_table
[256-CH_EOF
];
65 static const char tcc_keywords
[] =
66 #define DEF(id, str) str "\0"
71 /* WARNING: the content of this string encodes token numbers */
72 static const unsigned char tok_two_chars
[] =
73 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
74 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
77 struct macro_level
*prev
;
81 static void next_nomacro_spc(void);
82 static void macro_subst(
86 struct macro_level
**can_read_stream
89 ST_FUNC
void skip(int c
)
92 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
96 ST_FUNC
void expect(const char *msg
)
98 tcc_error("%s expected", msg
);
101 /* ------------------------------------------------------------------------- */
102 /* CString handling */
103 static void cstr_realloc(CString
*cstr
, int new_size
)
108 size
= cstr
->size_allocated
;
110 size
= 8; /* no need to allocate a too small first string */
111 while (size
< new_size
)
113 data
= tcc_realloc(cstr
->data_allocated
, size
);
114 cstr
->data_allocated
= data
;
115 cstr
->size_allocated
= size
;
120 ST_FUNC
void cstr_ccat(CString
*cstr
, int ch
)
123 size
= cstr
->size
+ 1;
124 if (size
> cstr
->size_allocated
)
125 cstr_realloc(cstr
, size
);
126 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
130 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
)
142 /* add a wide char */
143 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
146 size
= cstr
->size
+ sizeof(nwchar_t
);
147 if (size
> cstr
->size_allocated
)
148 cstr_realloc(cstr
, size
);
149 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
153 ST_FUNC
void cstr_new(CString
*cstr
)
155 memset(cstr
, 0, sizeof(CString
));
158 /* free string and reset it to NULL */
159 ST_FUNC
void cstr_free(CString
*cstr
)
161 tcc_free(cstr
->data_allocated
);
165 /* reset string to empty */
166 ST_FUNC
void cstr_reset(CString
*cstr
)
172 static void add_char(CString
*cstr
, int c
)
174 if (c
== '\'' || c
== '\"' || c
== '\\') {
175 /* XXX: could be more precise if char or string */
176 cstr_ccat(cstr
, '\\');
178 if (c
>= 32 && c
<= 126) {
181 cstr_ccat(cstr
, '\\');
183 cstr_ccat(cstr
, 'n');
185 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
186 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
187 cstr_ccat(cstr
, '0' + (c
& 7));
192 /* ------------------------------------------------------------------------- */
193 /* allocate a new token */
194 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
196 TokenSym
*ts
, **ptable
;
199 if (tok_ident
>= SYM_FIRST_ANOM
)
200 tcc_error("memory full (symbols)");
202 /* expand token table if needed */
203 i
= tok_ident
- TOK_IDENT
;
204 if ((i
% TOK_ALLOC_INCR
) == 0) {
205 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
206 table_ident
= ptable
;
209 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
211 ts
->tok
= tok_ident
++;
212 ts
->sym_define
= NULL
;
213 ts
->sym_label
= NULL
;
214 ts
->sym_struct
= NULL
;
215 ts
->sym_identifier
= NULL
;
217 ts
->hash_next
= NULL
;
218 memcpy(ts
->str
, str
, len
);
224 #define TOK_HASH_INIT 1
225 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
227 /* find a token and add it if not found */
228 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
236 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
237 h
&= (TOK_HASH_SIZE
- 1);
239 pts
= &hash_ident
[h
];
244 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
246 pts
= &(ts
->hash_next
);
248 return tok_alloc_new(pts
, str
, len
);
251 /* XXX: buffer overflow */
252 /* XXX: float tokens */
253 ST_FUNC
char *get_tok_str(int v
, CValue
*cv
)
255 static char buf
[STRING_MAX_SIZE
+ 1];
256 static CString cstr_buf
;
261 /* NOTE: to go faster, we give a fixed buffer for small strings */
262 cstr_reset(&cstr_buf
);
264 cstr_buf
.size_allocated
= sizeof(buf
);
270 /* XXX: not quite exact, but only useful for testing */
271 sprintf(p
, "%u", cv
->ui
);
275 /* XXX: not quite exact, but only useful for testing */
277 sprintf(p
, "%u", (unsigned)cv
->ull
);
279 sprintf(p
, "%llu", cv
->ull
);
283 cstr_ccat(&cstr_buf
, 'L');
285 cstr_ccat(&cstr_buf
, '\'');
286 add_char(&cstr_buf
, cv
->i
);
287 cstr_ccat(&cstr_buf
, '\'');
288 cstr_ccat(&cstr_buf
, '\0');
292 len
= cstr
->size
- 1;
294 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
295 cstr_ccat(&cstr_buf
, '\0');
298 cstr_ccat(&cstr_buf
, 'L');
301 cstr_ccat(&cstr_buf
, '\"');
303 len
= cstr
->size
- 1;
305 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
307 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
309 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
311 cstr_ccat(&cstr_buf
, '\"');
312 cstr_ccat(&cstr_buf
, '\0');
321 return strcpy(p
, "...");
323 return strcpy(p
, "<<=");
325 return strcpy(p
, ">>=");
328 /* search in two bytes table */
329 const unsigned char *q
= tok_two_chars
;
342 } else if (v
< tok_ident
) {
343 return table_ident
[v
- TOK_IDENT
]->str
;
344 } else if (v
>= SYM_FIRST_ANOM
) {
345 /* special name for anonymous symbol */
346 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
348 /* should never happen */
353 return cstr_buf
.data
;
356 /* fill input buffer and peek next char */
357 static int tcc_peekc_slow(BufferedFile
*bf
)
360 /* only tries to read if really end of buffer */
361 if (bf
->buf_ptr
>= bf
->buf_end
) {
363 #if defined(PARSE_DEBUG)
368 len
= read(bf
->fd
, bf
->buffer
, len
);
375 bf
->buf_ptr
= bf
->buffer
;
376 bf
->buf_end
= bf
->buffer
+ len
;
377 *bf
->buf_end
= CH_EOB
;
379 if (bf
->buf_ptr
< bf
->buf_end
) {
380 return bf
->buf_ptr
[0];
382 bf
->buf_ptr
= bf
->buf_end
;
387 /* return the current character, handling end of block if necessary
389 ST_FUNC
int handle_eob(void)
391 return tcc_peekc_slow(file
);
394 /* read next char from current input file and handle end of input buffer */
395 ST_INLN
void inp(void)
397 ch
= *(++(file
->buf_ptr
));
398 /* end of buffer/file handling */
403 /* handle '\[\r]\n' */
404 static int handle_stray_noerror(void)
411 } else if (ch
== '\r') {
425 static void handle_stray(void)
427 if (handle_stray_noerror())
428 tcc_error("stray '\\' in program");
431 /* skip the stray and handle the \\n case. Output an error if
432 incorrect char after the stray */
433 static int handle_stray1(uint8_t *p
)
437 if (p
>= file
->buf_end
) {
454 /* handle just the EOB case, but not stray */
455 #define PEEKC_EOB(c, p)\
466 /* handle the complicated stray case */
472 c = handle_stray1(p);\
477 /* input with '\[\r]\n' handling. Note that this function cannot
478 handle other characters after '\', so you cannot call it inside
479 strings or comments */
480 ST_FUNC
void minp(void)
488 /* single line C++ comments */
489 static uint8_t *parse_line_comment(uint8_t *p
)
497 if (c
== '\n' || c
== CH_EOF
) {
499 } else if (c
== '\\') {
508 } else if (c
== '\r') {
526 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
535 if (c
== '\n' || c
== '*' || c
== '\\')
539 if (c
== '\n' || c
== '*' || c
== '\\')
543 /* now we can handle all the cases */
547 } else if (c
== '*') {
553 } else if (c
== '/') {
555 } else if (c
== '\\') {
560 /* skip '\[\r]\n', otherwise just skip the stray */
566 } else if (c
== '\r') {
583 /* stray, eob or eof */
588 tcc_error("unexpected end of file in comment");
589 } else if (c
== '\\') {
601 static inline void skip_spaces(void)
607 static inline int check_space(int t
, int *spc
)
618 /* parse a string without interpreting escapes */
619 static uint8_t *parse_pp_string(uint8_t *p
,
620 int sep
, CString
*str
)
628 } else if (c
== '\\') {
634 /* XXX: indicate line number of start of string */
635 tcc_error("missing terminating %c character", sep
);
636 } else if (c
== '\\') {
637 /* escape : just skip \[\r]\n */
642 } else if (c
== '\r') {
645 expect("'\n' after '\r'");
648 } else if (c
== CH_EOF
) {
649 goto unterminated_string
;
652 cstr_ccat(str
, '\\');
658 } else if (c
== '\n') {
661 } else if (c
== '\r') {
665 cstr_ccat(str
, '\r');
681 /* skip block of text until #else, #elif or #endif. skip also pairs of
683 static void preprocess_skip(void)
685 int a
, start_of_line
, c
, in_warn_or_error
;
692 in_warn_or_error
= 0;
713 } else if (c
== '\\') {
714 ch
= file
->buf_ptr
[0];
715 handle_stray_noerror();
722 if (in_warn_or_error
)
724 p
= parse_pp_string(p
, c
, NULL
);
728 if (in_warn_or_error
)
735 p
= parse_comment(p
);
736 } else if (ch
== '/') {
737 p
= parse_line_comment(p
);
747 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
749 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
751 else if (tok
== TOK_ENDIF
)
753 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
754 in_warn_or_error
= 1;
755 else if (tok
== TOK_LINEFEED
)
770 /* ParseState handling */
772 /* XXX: currently, no include file info is stored. Thus, we cannot display
773 accurate messages if the function or data definition spans multiple
776 /* save current parse state in 's' */
777 ST_FUNC
void save_parse_state(ParseState
*s
)
779 s
->line_num
= file
->line_num
;
780 s
->macro_ptr
= macro_ptr
;
785 /* restore parse state from 's' */
786 ST_FUNC
void restore_parse_state(ParseState
*s
)
788 file
->line_num
= s
->line_num
;
789 macro_ptr
= s
->macro_ptr
;
794 /* return the number of additional 'ints' necessary to store the
796 static inline int tok_ext_size(int t
)
810 tcc_error("unsupported token");
817 return LDOUBLE_SIZE
/ 4;
823 /* token string handling */
825 ST_INLN
void tok_str_new(TokenString
*s
)
829 s
->allocated_len
= 0;
830 s
->last_line_num
= -1;
833 ST_FUNC
void tok_str_free(int *str
)
838 static int *tok_str_realloc(TokenString
*s
)
842 if (s
->allocated_len
== 0) {
845 len
= s
->allocated_len
* 2;
847 str
= tcc_realloc(s
->str
, len
* sizeof(int));
848 s
->allocated_len
= len
;
853 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
859 if (len
>= s
->allocated_len
)
860 str
= tok_str_realloc(s
);
865 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
872 /* allocate space for worst case */
873 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
874 str
= tok_str_realloc(s
);
883 str
[len
++] = cv
->tab
[0];
892 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
893 while ((len
+ nb_words
) > s
->allocated_len
)
894 str
= tok_str_realloc(s
);
895 cstr
= (CString
*)(str
+ len
);
897 cstr
->size
= cv
->cstr
->size
;
898 cstr
->data_allocated
= NULL
;
899 cstr
->size_allocated
= cstr
->size
;
900 memcpy((char *)cstr
+ sizeof(CString
),
901 cv
->cstr
->data
, cstr
->size
);
908 #if LDOUBLE_SIZE == 8
911 str
[len
++] = cv
->tab
[0];
912 str
[len
++] = cv
->tab
[1];
914 #if LDOUBLE_SIZE == 12
916 str
[len
++] = cv
->tab
[0];
917 str
[len
++] = cv
->tab
[1];
918 str
[len
++] = cv
->tab
[2];
919 #elif LDOUBLE_SIZE == 16
921 str
[len
++] = cv
->tab
[0];
922 str
[len
++] = cv
->tab
[1];
923 str
[len
++] = cv
->tab
[2];
924 str
[len
++] = cv
->tab
[3];
925 #elif LDOUBLE_SIZE != 8
926 #error add long double size support
935 /* add the current parse token in token string 's' */
936 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
939 memset(&cval
, 0, sizeof(CValue
));
941 /* save line number info */
942 if (file
->line_num
!= s
->last_line_num
) {
943 s
->last_line_num
= file
->line_num
;
944 cval
.i
= s
->last_line_num
;
945 tok_str_add2(s
, TOK_LINENUM
, &cval
);
947 tok_str_add2(s
, tok
, &tokc
);
950 /* get a token from an integer array and increment pointer
951 accordingly. we code it as a macro to avoid pointer aliasing. */
952 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
970 cv
->cstr
= (CString
*)p
;
971 cv
->cstr
->data
= (char *)p
+ sizeof(CString
);
972 p
+= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
980 #if LDOUBLE_SIZE == 16
982 #elif LDOUBLE_SIZE == 12
984 #elif LDOUBLE_SIZE == 8
987 # error add long double size support
1000 static int macro_is_equal(const int *a
, const int *b
)
1002 char buf
[STRING_MAX_SIZE
+ 1];
1005 memset(&cv
, 0, sizeof(CValue
));
1007 TOK_GET(&t
, &a
, &cv
);
1008 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1009 TOK_GET(&t
, &b
, &cv
);
1010 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1016 /* defines handling */
1017 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1022 if (s
&& !macro_is_equal(s
->d
, str
))
1023 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1025 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1027 s
->next
= first_arg
;
1028 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1031 /* undefined a define symbol. Its name is just set to zero */
1032 ST_FUNC
void define_undef(Sym
*s
)
1036 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1037 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1041 ST_INLN Sym
*define_find(int v
)
1044 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1046 return table_ident
[v
]->sym_define
;
1049 /* free define stack until top reaches 'b' */
1050 ST_FUNC
void free_defines(Sym
*b
)
1058 /* do not free args or predefined defines */
1060 tok_str_free(top
->d
);
1062 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1063 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1071 ST_FUNC Sym
*label_find(int v
)
1074 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1076 return table_ident
[v
]->sym_label
;
1079 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1082 s
= sym_push2(ptop
, v
, 0, 0);
1084 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1085 if (ptop
== &global_label_stack
) {
1086 /* modify the top most local identifier, so that
1087 sym_identifier will point to 's' when popped */
1089 ps
= &(*ps
)->prev_tok
;
1096 /* pop labels until element last is reached. Look if any labels are
1097 undefined. Define symbols if '&&label' was used. */
1098 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1101 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1103 if (s
->r
== LABEL_DECLARED
) {
1104 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1105 } else if (s
->r
== LABEL_FORWARD
) {
1106 tcc_error("label '%s' used but not defined",
1107 get_tok_str(s
->v
, NULL
));
1110 /* define corresponding symbol. A size of
1112 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1116 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1122 /* eval an expression for #if/#elif */
1123 static int expr_preprocess(void)
1129 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1130 next(); /* do macro subst */
1131 if (tok
== TOK_DEFINED
) {
1136 c
= define_find(tok
) != 0;
1141 } else if (tok
>= TOK_IDENT
) {
1142 /* if undefined macro */
1146 tok_str_add_tok(&str
);
1148 tok_str_add(&str
, -1); /* simulate end of file */
1149 tok_str_add(&str
, 0);
1150 /* now evaluate C constant expression */
1151 macro_ptr
= str
.str
;
1155 tok_str_free(str
.str
);
1159 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1160 static void tok_print(int *str
)
1164 memset(&cval
, 0, sizeof(CValue
));
1168 TOK_GET(&t
, &str
, &cval
);
1171 printf("%s", get_tok_str(t
, &cval
));
1177 /* parse after #define */
1178 ST_FUNC
void parse_define(void)
1180 Sym
*s
, *first
, **ps
;
1181 int v
, t
, varg
, is_vaargs
, spc
;
1186 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1187 /* XXX: should check if same macro (ANSI) */
1190 /* '(' must be just after macro definition for MACRO_FUNC */
1195 while (tok
!= ')') {
1199 if (varg
== TOK_DOTS
) {
1200 varg
= TOK___VA_ARGS__
;
1202 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1206 if (varg
< TOK_IDENT
)
1207 tcc_error("badly punctuated parameter list");
1208 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1221 /* EOF testing necessary for '-D' handling */
1222 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1223 /* remove spaces around ## and after '#' */
1224 if (TOK_TWOSHARPS
== tok
) {
1228 } else if ('#' == tok
) {
1230 } else if (check_space(tok
, &spc
)) {
1233 tok_str_add2(&str
, tok
, &tokc
);
1238 --str
.len
; /* remove trailing space */
1239 tok_str_add(&str
, 0);
1241 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
1244 define_push(v
, t
, str
.str
, first
);
1247 static inline int hash_cached_include(const char *filename
)
1249 const unsigned char *s
;
1253 s
= (unsigned char *) filename
;
1255 h
= TOK_HASH_FUNC(h
, *s
);
1258 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1262 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1266 h
= hash_cached_include(filename
);
1267 i
= s1
->cached_includes_hash
[h
];
1271 e
= s1
->cached_includes
[i
- 1];
1272 if (0 == PATHCMP(e
->filename
, filename
))
1279 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1284 if (search_cached_include(s1
, filename
))
1287 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1289 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1290 strcpy(e
->filename
, filename
);
1291 e
->ifndef_macro
= ifndef_macro
;
1292 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1293 /* add in hash table */
1294 h
= hash_cached_include(filename
);
1295 e
->hash_next
= s1
->cached_includes_hash
[h
];
1296 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1299 static void pragma_parse(TCCState
*s1
)
1304 if (tok
== TOK_pack
) {
1307 #pragma pack(1) // set
1308 #pragma pack() // reset to default
1309 #pragma pack(push,1) // push & set
1310 #pragma pack(pop) // restore previous
1314 if (tok
== TOK_ASM_pop
) {
1316 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1318 tcc_error("out of pack stack");
1320 s1
->pack_stack_ptr
--;
1324 if (tok
== TOK_ASM_push
) {
1326 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1328 s1
->pack_stack_ptr
++;
1331 if (tok
!= TOK_CINT
) {
1333 tcc_error("invalid pack pragma");
1336 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1340 *s1
->pack_stack_ptr
= val
;
1346 /* is_bof is true if first non space token at beginning of file */
1347 ST_FUNC
void preprocess(int is_bof
)
1349 TCCState
*s1
= tcc_state
;
1350 int i
, c
, n
, saved_parse_flags
;
1354 saved_parse_flags
= parse_flags
;
1355 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
1356 PARSE_FLAG_LINEFEED
;
1366 s
= define_find(tok
);
1367 /* undefine symbol by putting an invalid name */
1372 case TOK_INCLUDE_NEXT
:
1373 ch
= file
->buf_ptr
[0];
1374 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1379 } else if (ch
== '\"') {
1384 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1385 if ((q
- buf
) < sizeof(buf
) - 1)
1388 if (handle_stray_noerror() == 0)
1396 /* eat all spaces and comments after include */
1397 /* XXX: slightly incorrect */
1398 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1402 /* computed #include : either we have only strings or
1403 we have anything enclosed in '<>' */
1406 if (tok
== TOK_STR
) {
1407 while (tok
!= TOK_LINEFEED
) {
1408 if (tok
!= TOK_STR
) {
1410 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1412 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1418 while (tok
!= TOK_LINEFEED
) {
1419 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1423 /* check syntax and remove '<>' */
1424 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1425 goto include_syntax
;
1426 memmove(buf
, buf
+ 1, len
- 2);
1427 buf
[len
- 2] = '\0';
1432 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1433 tcc_error("#include recursion too deep");
1434 /* store current file in stack, but increment stack later below */
1435 *s1
->include_stack_ptr
= file
;
1437 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1438 for (i
= -2; i
< n
; ++i
) {
1439 char buf1
[sizeof file
->filename
];
1445 /* check absolute include path */
1446 if (!IS_ABSPATH(buf
))
1449 i
= n
; /* force end loop */
1451 } else if (i
== -1) {
1452 /* search in current dir if "header.h" */
1455 path
= file
->filename
;
1456 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1459 /* search in all the include paths */
1460 if (i
< s1
->nb_include_paths
)
1461 path
= s1
->include_paths
[i
];
1463 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1464 pstrcpy(buf1
, sizeof(buf1
), path
);
1465 pstrcat(buf1
, sizeof(buf1
), "/");
1468 pstrcat(buf1
, sizeof(buf1
), buf
);
1470 if (tok
== TOK_INCLUDE_NEXT
)
1471 for (f
= s1
->include_stack_ptr
; f
>= s1
->include_stack
; --f
)
1472 if (0 == PATHCMP((*f
)->filename
, buf1
)) {
1474 printf("%s: #include_next skipping %s\n", file
->filename
, buf1
);
1476 goto include_trynext
;
1479 e
= search_cached_include(s1
, buf1
);
1480 if (e
&& define_find(e
->ifndef_macro
)) {
1481 /* no need to parse the include because the 'ifndef macro'
1484 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1489 if (tcc_open(s1
, buf1
) < 0)
1494 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1496 /* update target deps */
1497 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1499 /* push current file in stack */
1500 ++s1
->include_stack_ptr
;
1501 /* add include file debug info */
1503 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1504 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1505 ch
= file
->buf_ptr
[0];
1508 tcc_error("include file '%s' not found", buf
);
1515 c
= expr_preprocess();
1521 if (tok
< TOK_IDENT
)
1522 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1526 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1528 file
->ifndef_macro
= tok
;
1531 c
= (define_find(tok
) != 0) ^ c
;
1533 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1534 tcc_error("memory full (ifdef)");
1535 *s1
->ifdef_stack_ptr
++ = c
;
1538 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1539 tcc_error("#else without matching #if");
1540 if (s1
->ifdef_stack_ptr
[-1] & 2)
1541 tcc_error("#else after #else");
1542 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1545 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1546 tcc_error("#elif without matching #if");
1547 c
= s1
->ifdef_stack_ptr
[-1];
1549 tcc_error("#elif after #else");
1550 /* last #if/#elif expression was true: we skip */
1553 c
= expr_preprocess();
1554 s1
->ifdef_stack_ptr
[-1] = c
;
1556 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1557 file
->ifndef_macro
= 0;
1567 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1568 tcc_error("#endif without matching #if");
1569 s1
->ifdef_stack_ptr
--;
1570 /* '#ifndef macro' was at the start of file. Now we check if
1571 an '#endif' is exactly at the end of file */
1572 if (file
->ifndef_macro
&&
1573 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1574 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1575 /* need to set to zero to avoid false matches if another
1576 #ifndef at middle of file */
1577 file
->ifndef_macro
= 0;
1578 while (tok
!= TOK_LINEFEED
)
1580 tok_flags
|= TOK_FLAG_ENDIF
;
1586 if (tok
!= TOK_CINT
)
1588 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
1590 if (tok
!= TOK_LINEFEED
) {
1593 pstrcpy(file
->filename
, sizeof(file
->filename
),
1594 (char *)tokc
.cstr
->data
);
1600 ch
= file
->buf_ptr
[0];
1603 while (ch
!= '\n' && ch
!= CH_EOF
) {
1604 if ((q
- buf
) < sizeof(buf
) - 1)
1607 if (handle_stray_noerror() == 0)
1614 tcc_error("#error %s", buf
);
1616 tcc_warning("#warning %s", buf
);
1622 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_PPNUM
) {
1623 /* '!' is ignored to allow C scripts. numbers are ignored
1624 to emulate cpp behaviour */
1626 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
1627 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1629 /* this is a gas line comment in an 'S' file. */
1630 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1636 /* ignore other preprocess commands or #! for C scripts */
1637 while (tok
!= TOK_LINEFEED
)
1640 parse_flags
= saved_parse_flags
;
1643 /* evaluate escape codes in a string. */
1644 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1659 case '0': case '1': case '2': case '3':
1660 case '4': case '5': case '6': case '7':
1661 /* at most three octal digits */
1666 n
= n
* 8 + c
- '0';
1670 n
= n
* 8 + c
- '0';
1675 goto add_char_nonext
;
1683 if (c
>= 'a' && c
<= 'f')
1685 else if (c
>= 'A' && c
<= 'F')
1695 goto add_char_nonext
;
1719 goto invalid_escape
;
1729 if (c
>= '!' && c
<= '~')
1730 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1732 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1739 cstr_ccat(outstr
, c
);
1741 cstr_wccat(outstr
, c
);
1743 /* add a trailing '\0' */
1745 cstr_ccat(outstr
, '\0');
1747 cstr_wccat(outstr
, '\0');
1750 /* we use 64 bit numbers */
1753 /* bn = (bn << shift) | or_val */
1754 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
1758 for(i
=0;i
<BN_SIZE
;i
++) {
1760 bn
[i
] = (v
<< shift
) | or_val
;
1761 or_val
= v
>> (32 - shift
);
1765 static void bn_zero(unsigned int *bn
)
1768 for(i
=0;i
<BN_SIZE
;i
++) {
1773 /* parse number in null terminated string 'p' and return it in the
1775 static void parse_number(const char *p
)
1777 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
1779 unsigned int bn
[BN_SIZE
];
1790 goto float_frac_parse
;
1791 } else if (t
== '0') {
1792 if (ch
== 'x' || ch
== 'X') {
1796 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
1802 /* parse all digits. cannot check octal numbers at this stage
1803 because of floating point constants */
1805 if (ch
>= 'a' && ch
<= 'f')
1807 else if (ch
>= 'A' && ch
<= 'F')
1815 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
1817 tcc_error("number too long");
1823 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
1824 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
1826 /* NOTE: strtox should support that for hexa numbers, but
1827 non ISOC99 libcs do not support it, so we prefer to do
1829 /* hexadecimal or binary floats */
1830 /* XXX: handle overflows */
1842 } else if (t
>= 'a') {
1844 } else if (t
>= 'A') {
1849 bn_lshift(bn
, shift
, t
);
1856 if (t
>= 'a' && t
<= 'f') {
1858 } else if (t
>= 'A' && t
<= 'F') {
1860 } else if (t
>= '0' && t
<= '9') {
1866 tcc_error("invalid digit");
1867 bn_lshift(bn
, shift
, t
);
1872 if (ch
!= 'p' && ch
!= 'P')
1879 } else if (ch
== '-') {
1883 if (ch
< '0' || ch
> '9')
1884 expect("exponent digits");
1885 while (ch
>= '0' && ch
<= '9') {
1886 exp_val
= exp_val
* 10 + ch
- '0';
1889 exp_val
= exp_val
* s
;
1891 /* now we can generate the number */
1892 /* XXX: should patch directly float number */
1893 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
1894 d
= ldexp(d
, exp_val
- frac_bits
);
1899 /* float : should handle overflow */
1901 } else if (t
== 'L') {
1903 #ifdef TCC_TARGET_PE
1908 /* XXX: not large enough */
1909 tokc
.ld
= (long double)d
;
1916 /* decimal floats */
1918 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1923 while (ch
>= '0' && ch
<= '9') {
1924 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1930 if (ch
== 'e' || ch
== 'E') {
1931 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1935 if (ch
== '-' || ch
== '+') {
1936 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1941 if (ch
< '0' || ch
> '9')
1942 expect("exponent digits");
1943 while (ch
>= '0' && ch
<= '9') {
1944 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1956 tokc
.f
= strtof(token_buf
, NULL
);
1957 } else if (t
== 'L') {
1959 #ifdef TCC_TARGET_PE
1961 tokc
.d
= strtod(token_buf
, NULL
);
1964 tokc
.ld
= strtold(token_buf
, NULL
);
1968 tokc
.d
= strtod(token_buf
, NULL
);
1972 unsigned long long n
, n1
;
1975 /* integer number */
1978 if (b
== 10 && *q
== '0') {
1985 /* no need for checks except for base 10 / 8 errors */
1988 } else if (t
>= 'a') {
1990 } else if (t
>= 'A') {
1995 tcc_error("invalid digit");
1999 /* detect overflow */
2000 /* XXX: this test is not reliable */
2002 tcc_error("integer constant overflow");
2005 /* XXX: not exactly ANSI compliant */
2006 if ((n
& 0xffffffff00000000LL
) != 0) {
2011 } else if (n
> 0x7fffffff) {
2022 tcc_error("three 'l's in integer constant");
2024 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2027 if (tok
== TOK_CINT
)
2029 else if (tok
== TOK_CUINT
)
2031 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2035 } else if (t
== 'U') {
2037 tcc_error("two 'u's in integer constant");
2039 if (tok
== TOK_CINT
)
2041 else if (tok
== TOK_CLLONG
)
2048 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2054 tcc_error("invalid number\n");
2058 #define PARSE2(c1, tok1, c2, tok2) \
2069 /* return next token without macro substitution */
2070 static inline void next_nomacro1(void)
2085 goto keep_tok_flags
;
2092 /* first look if it is in fact an end of buffer */
2093 if (p
>= file
->buf_end
) {
2097 if (p
>= file
->buf_end
)
2110 TCCState
*s1
= tcc_state
;
2111 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2112 && !(tok_flags
& TOK_FLAG_EOF
)) {
2113 tok_flags
|= TOK_FLAG_EOF
;
2115 goto keep_tok_flags
;
2116 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2118 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2119 tcc_error("missing #endif");
2120 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2121 /* no include left : end of file. */
2124 tok_flags
&= ~TOK_FLAG_EOF
;
2125 /* pop include file */
2127 /* test if previous '#endif' was after a #ifdef at
2129 if (tok_flags
& TOK_FLAG_ENDIF
) {
2131 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2133 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2134 tok_flags
&= ~TOK_FLAG_ENDIF
;
2137 /* add end of include file debug info */
2138 if (tcc_state
->do_debug
) {
2139 put_stabd(N_EINCL
, 0, 0);
2141 /* pop include stack */
2143 s1
->include_stack_ptr
--;
2152 tok_flags
|= TOK_FLAG_BOL
;
2155 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2158 goto keep_tok_flags
;
2163 if ((tok_flags
& TOK_FLAG_BOL
) &&
2164 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2166 preprocess(tok_flags
& TOK_FLAG_BOF
);
2172 tok
= TOK_TWOSHARPS
;
2174 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
2175 p
= parse_line_comment(p
- 1);
2184 case 'a': case 'b': case 'c': case 'd':
2185 case 'e': case 'f': case 'g': case 'h':
2186 case 'i': case 'j': case 'k': case 'l':
2187 case 'm': case 'n': case 'o': case 'p':
2188 case 'q': case 'r': case 's': case 't':
2189 case 'u': case 'v': case 'w': case 'x':
2191 case 'A': case 'B': case 'C': case 'D':
2192 case 'E': case 'F': case 'G': case 'H':
2193 case 'I': case 'J': case 'K':
2194 case 'M': case 'N': case 'O': case 'P':
2195 case 'Q': case 'R': case 'S': case 'T':
2196 case 'U': case 'V': case 'W': case 'X':
2202 h
= TOK_HASH_FUNC(h
, c
);
2206 if (!isidnum_table
[c
-CH_EOF
])
2208 h
= TOK_HASH_FUNC(h
, c
);
2215 /* fast case : no stray found, so we have the full token
2216 and we have already hashed it */
2218 h
&= (TOK_HASH_SIZE
- 1);
2219 pts
= &hash_ident
[h
];
2224 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2226 pts
= &(ts
->hash_next
);
2228 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2232 cstr_reset(&tokcstr
);
2235 cstr_ccat(&tokcstr
, *p1
);
2241 while (isidnum_table
[c
-CH_EOF
]) {
2242 cstr_ccat(&tokcstr
, c
);
2245 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2251 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2253 goto parse_ident_fast
;
2256 if (c
== '\'' || c
== '\"') {
2260 cstr_reset(&tokcstr
);
2261 cstr_ccat(&tokcstr
, 'L');
2262 goto parse_ident_slow
;
2266 case '0': case '1': case '2': case '3':
2267 case '4': case '5': case '6': case '7':
2270 cstr_reset(&tokcstr
);
2271 /* after the first digit, accept digits, alpha, '.' or sign if
2272 prefixed by 'eEpP' */
2276 cstr_ccat(&tokcstr
, c
);
2278 if (!(isnum(c
) || isid(c
) || c
== '.' ||
2279 ((c
== '+' || c
== '-') &&
2280 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
2283 /* We add a trailing '\0' to ease parsing */
2284 cstr_ccat(&tokcstr
, '\0');
2285 tokc
.cstr
= &tokcstr
;
2289 /* special dot handling because it can also start a number */
2292 cstr_reset(&tokcstr
);
2293 cstr_ccat(&tokcstr
, '.');
2295 } else if (c
== '.') {
2315 /* parse the string */
2317 p
= parse_pp_string(p
, sep
, &str
);
2318 cstr_ccat(&str
, '\0');
2320 /* eval the escape (should be done as TOK_PPNUM) */
2321 cstr_reset(&tokcstr
);
2322 parse_escape_string(&tokcstr
, str
.data
, is_long
);
2327 /* XXX: make it portable */
2331 char_size
= sizeof(nwchar_t
);
2332 if (tokcstr
.size
<= char_size
)
2333 tcc_error("empty character constant");
2334 if (tokcstr
.size
> 2 * char_size
)
2335 tcc_warning("multi-character character constant");
2337 tokc
.i
= *(int8_t *)tokcstr
.data
;
2340 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2344 tokc
.cstr
= &tokcstr
;
2358 } else if (c
== '<') {
2376 } else if (c
== '>') {
2394 } else if (c
== '=') {
2407 } else if (c
== '=') {
2420 } else if (c
== '=') {
2433 } else if (c
== '=') {
2436 } else if (c
== '>') {
2444 PARSE2('!', '!', '=', TOK_NE
)
2445 PARSE2('=', '=', '=', TOK_EQ
)
2446 PARSE2('*', '*', '=', TOK_A_MUL
)
2447 PARSE2('%', '%', '=', TOK_A_MOD
)
2448 PARSE2('^', '^', '=', TOK_A_XOR
)
2450 /* comments or operator */
2454 p
= parse_comment(p
);
2455 /* comments replaced by a blank */
2457 goto keep_tok_flags
;
2458 } else if (c
== '/') {
2459 p
= parse_line_comment(p
);
2461 goto keep_tok_flags
;
2462 } else if (c
== '=') {
2482 case '$': /* only used in assembler */
2483 case '@': /* dito */
2488 tcc_error("unrecognized character \\x%02x", c
);
2494 #if defined(PARSE_DEBUG)
2495 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2499 /* return next token without macro substitution. Can read input from
2501 static void next_nomacro_spc(void)
2507 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2508 if (tok
== TOK_LINENUM
) {
2509 file
->line_num
= tokc
.i
;
2518 ST_FUNC
void next_nomacro(void)
2522 } while (is_space(tok
));
2525 /* substitute args in macro_str and return allocated string */
2526 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2528 int last_tok
, t
, spc
;
2534 memset(&cval
, 0, sizeof(CValue
));
2539 TOK_GET(&t
, ¯o_str
, &cval
);
2544 TOK_GET(&t
, ¯o_str
, &cval
);
2547 s
= sym_find2(args
, t
);
2553 TOK_GET(&t
, &st
, &cval
);
2554 if (!check_space(t
, &spc
))
2555 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2558 cstr_ccat(&cstr
, '\0');
2560 printf("stringize: %s\n", (char *)cstr
.data
);
2564 tok_str_add2(&str
, TOK_STR
, &cval
);
2567 tok_str_add2(&str
, t
, &cval
);
2569 } else if (t
>= TOK_IDENT
) {
2570 s
= sym_find2(args
, t
);
2573 /* if '##' is present before or after, no arg substitution */
2574 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
2575 /* special case for var arg macros : ## eats the
2576 ',' if empty VA_ARGS variable. */
2577 /* XXX: test of the ',' is not 100%
2578 reliable. should fix it to avoid security
2580 if (gnu_ext
&& s
->type
.t
&&
2581 last_tok
== TOK_TWOSHARPS
&&
2582 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
2584 /* suppress ',' '##' */
2587 /* suppress '##' and add variable */
2595 TOK_GET(&t1
, &st
, &cval
);
2598 tok_str_add2(&str
, t1
, &cval
);
2602 /* NOTE: the stream cannot be read when macro
2603 substituing an argument */
2604 macro_subst(&str
, nested_list
, st
, NULL
);
2607 tok_str_add(&str
, t
);
2610 tok_str_add2(&str
, t
, &cval
);
2614 tok_str_add(&str
, 0);
2618 static char const ab_month_name
[12][4] =
2620 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2621 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2624 /* do macro substitution of current token with macro 's' and add
2625 result to (tok_str,tok_len). 'nested_list' is the list of all
2626 macros we got inside to avoid recursing. Return non zero if no
2627 substitution needs to be done */
2628 static int macro_subst_tok(TokenString
*tok_str
,
2629 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
2631 Sym
*args
, *sa
, *sa1
;
2632 int mstr_allocated
, parlevel
, *mstr
, t
, t1
, spc
;
2639 memset(&cval
, 0, sizeof(CValue
));
2641 /* if symbol is a macro, prepare substitution */
2642 /* special macros */
2643 if (tok
== TOK___LINE__
) {
2644 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2648 } else if (tok
== TOK___FILE__
) {
2649 cstrval
= file
->filename
;
2651 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2656 tm
= localtime(&ti
);
2657 if (tok
== TOK___DATE__
) {
2658 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2659 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2661 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2662 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2669 cstr_cat(&cstr
, cstrval
);
2670 cstr_ccat(&cstr
, '\0');
2672 tok_str_add2(tok_str
, t1
, &cval
);
2677 if (s
->type
.t
== MACRO_FUNC
) {
2678 /* NOTE: we do not use next_nomacro to avoid eating the
2679 next token. XXX: find better solution */
2683 while (is_space(t
= *p
) || TOK_LINEFEED
== t
)
2685 if (t
== 0 && can_read_stream
) {
2686 /* end of macro stream: we must look at the token
2687 after in the file */
2688 struct macro_level
*ml
= *can_read_stream
;
2694 *can_read_stream
= ml
-> prev
;
2696 /* also, end of scope for nested defined symbol */
2697 (*nested_list
)->v
= -1;
2701 ch
= file
->buf_ptr
[0];
2702 while (is_space(ch
) || ch
== '\n' || ch
== '/')
2707 uint8_t *p
= file
->buf_ptr
;
2710 p
= parse_comment(p
);
2711 file
->buf_ptr
= p
- 1;
2712 } else if (c
== '/') {
2713 p
= parse_line_comment(p
);
2714 file
->buf_ptr
= p
- 1;
2722 if (t
!= '(') /* no macro subst */
2725 /* argument macro */
2730 /* NOTE: empty args are allowed, except if no args */
2732 /* handle '()' case */
2733 if (!args
&& !sa
&& tok
== ')')
2736 tcc_error("macro '%s' used with too many args",
2737 get_tok_str(s
->v
, 0));
2740 /* NOTE: non zero sa->t indicates VA_ARGS */
2741 while ((parlevel
> 0 ||
2743 (tok
!= ',' || sa
->type
.t
))) &&
2747 else if (tok
== ')')
2749 if (tok
== TOK_LINEFEED
)
2751 if (!check_space(tok
, &spc
))
2752 tok_str_add2(&str
, tok
, &tokc
);
2756 tok_str_add(&str
, 0);
2757 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
2761 /* special case for gcc var args: add an empty
2762 var arg argument if it is omitted */
2763 if (sa
&& sa
->type
.t
&& gnu_ext
)
2773 tcc_error("macro '%s' used with too few args",
2774 get_tok_str(s
->v
, 0));
2777 /* now subst each arg */
2778 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
2783 tok_str_free(sa
->d
);
2789 sym_push2(nested_list
, s
->v
, 0, 0);
2790 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
2791 /* pop nested defined symbol */
2793 *nested_list
= sa1
->prev
;
2801 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2802 return the resulting string (which must be freed). */
2803 static inline int *macro_twosharps(const int *macro_str
)
2807 TokenString macro_str1
;
2809 int n
, start_of_nosubsts
;
2811 /* we search the first '##' */
2812 for(ptr
= macro_str
;;) {
2814 memset(&cval
, 0, sizeof(CValue
));
2815 TOK_GET(&t
, &ptr
, &cval
);
2816 if (t
== TOK_TWOSHARPS
)
2818 /* nothing more to do if end of string */
2823 /* we saw '##', so we need more processing to handle it */
2824 start_of_nosubsts
= -1;
2825 tok_str_new(¯o_str1
);
2826 for(ptr
= macro_str
;;) {
2827 TOK_GET(&tok
, &ptr
, &tokc
);
2830 if (tok
== TOK_TWOSHARPS
)
2832 if (tok
== TOK_NOSUBST
&& start_of_nosubsts
< 0)
2833 start_of_nosubsts
= macro_str1
.len
;
2834 while (*ptr
== TOK_TWOSHARPS
) {
2835 /* given 'a##b', remove nosubsts preceding 'a' */
2836 if (start_of_nosubsts
>= 0)
2837 macro_str1
.len
= start_of_nosubsts
;
2838 /* given 'a##b', skip '##' */
2840 /* given 'a##b', remove nosubsts preceding 'b' */
2841 while (t
== TOK_NOSUBST
)
2843 if (t
&& t
!= TOK_TWOSHARPS
) {
2845 memset(&cval
, 0, sizeof(CValue
));
2846 TOK_GET(&t
, &ptr
, &cval
);
2847 /* We concatenate the two tokens */
2849 cstr_cat(&cstr
, get_tok_str(tok
, &tokc
));
2851 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2852 cstr_ccat(&cstr
, '\0');
2854 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
2855 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
2858 if (0 == *file
->buf_ptr
)
2860 tok_str_add2(¯o_str1
, tok
, &tokc
);
2861 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2862 n
, cstr
.data
, (char*)cstr
.data
+ n
);
2868 if (tok
!= TOK_NOSUBST
)
2869 start_of_nosubsts
= -1;
2870 tok_str_add2(¯o_str1
, tok
, &tokc
);
2872 tok_str_add(¯o_str1
, 0);
2873 return macro_str1
.str
;
2877 /* do macro substitution of macro_str and add result to
2878 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2879 inside to avoid recursing. */
2880 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
2881 const int *macro_str
, struct macro_level
** can_read_stream
)
2887 struct macro_level ml
;
2890 memset(&cval
, 0, sizeof(CValue
));
2892 /* first scan for '##' operator handling */
2894 macro_str1
= macro_twosharps(ptr
);
2902 /* NOTE: ptr == NULL can only happen if tokens are read from
2903 file stream due to a macro function call */
2906 TOK_GET(&t
, &ptr
, &cval
);
2909 if (t
== TOK_NOSUBST
) {
2910 /* following token has already been subst'd. just copy it on */
2911 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
2912 TOK_GET(&t
, &ptr
, &cval
);
2917 /* if nested substitution, do nothing */
2918 if (sym_find2(*nested_list
, t
)) {
2919 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
2920 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
2924 if (can_read_stream
)
2925 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
2926 macro_ptr
= (int *)ptr
;
2928 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
2929 ptr
= (int *)macro_ptr
;
2931 if (can_read_stream
&& *can_read_stream
== &ml
)
2932 *can_read_stream
= ml
.prev
;
2935 if (parse_flags
& PARSE_FLAG_SPACES
)
2940 tok_str_add(tok_str
, ' ');
2944 if (!check_space(t
, &spc
))
2945 tok_str_add2(tok_str
, t
, &cval
);
2949 tok_str_free(macro_str1
);
2952 /* return next token with macro substitution */
2953 ST_FUNC
void next(void)
2955 Sym
*nested_list
, *s
;
2957 struct macro_level
*ml
;
2960 if (parse_flags
& PARSE_FLAG_SPACES
)
2965 /* if not reading from macro substituted string, then try
2966 to substitute macros */
2967 if (tok
>= TOK_IDENT
&&
2968 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2969 s
= define_find(tok
);
2971 /* we have a macro: we try to substitute */
2975 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
2976 /* substitution done, NOTE: maybe empty */
2977 tok_str_add(&str
, 0);
2978 macro_ptr
= str
.str
;
2979 macro_ptr_allocated
= str
.str
;
2986 /* end of macro or end of unget buffer */
2987 if (unget_buffer_enabled
) {
2988 macro_ptr
= unget_saved_macro_ptr
;
2989 unget_buffer_enabled
= 0;
2991 /* end of macro string: free it */
2992 tok_str_free(macro_ptr_allocated
);
2993 macro_ptr_allocated
= NULL
;
2997 } else if (tok
== TOK_NOSUBST
) {
2998 /* discard preprocessor's nosubst markers */
3003 /* convert preprocessor tokens into C tokens */
3004 if (tok
== TOK_PPNUM
&&
3005 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
3006 parse_number((char *)tokc
.cstr
->data
);
3010 /* push back current token and set current token to 'last_tok'. Only
3011 identifier case handled for labels. */
3012 ST_INLN
void unget_tok(int last_tok
)
3016 if (unget_buffer_enabled
)
3018 /* assert(macro_ptr == unget_saved_buffer + 1);
3019 assert(*macro_ptr == 0); */
3023 unget_saved_macro_ptr
= macro_ptr
;
3024 unget_buffer_enabled
= 1;
3026 q
= unget_saved_buffer
;
3029 n
= tok_ext_size(tok
) - 1;
3032 *q
= 0; /* end of token string */
3037 /* better than nothing, but needs extension to handle '-E' option
3039 ST_FUNC
void preprocess_init(TCCState
*s1
)
3041 s1
->include_stack_ptr
= s1
->include_stack
;
3042 /* XXX: move that before to avoid having to initialize
3043 file->ifdef_stack_ptr ? */
3044 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3045 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3048 s1
->pack_stack
[0] = 0;
3049 s1
->pack_stack_ptr
= s1
->pack_stack
;
3052 ST_FUNC
void preprocess_new(void)
3057 /* init isid table */
3058 for(i
=CH_EOF
;i
<256;i
++)
3059 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
3061 /* add all tokens */
3063 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3065 tok_ident
= TOK_IDENT
;
3074 tok_alloc(p
, r
- p
- 1);
3079 /* Preprocess the current file */
3080 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3084 BufferedFile
*file_ref
, **iptr
, **iptr_new
;
3085 int token_seen
, line_ref
, d
;
3088 preprocess_init(s1
);
3089 define_start
= define_stack
;
3090 ch
= file
->buf_ptr
[0];
3091 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3092 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
3093 PARSE_FLAG_LINEFEED
| PARSE_FLAG_SPACES
;
3097 iptr
= s1
->include_stack_ptr
;
3101 if (tok
== TOK_EOF
) {
3103 } else if (file
!= file_ref
) {
3105 } else if (tok
== TOK_LINEFEED
) {
3110 } else if (!token_seen
) {
3111 d
= file
->line_num
- line_ref
;
3112 if (file
!= file_ref
|| d
< 0 || d
>= 8) {
3114 iptr_new
= s1
->include_stack_ptr
;
3115 s
= iptr_new
> iptr
? " 1"
3116 : iptr_new
< iptr
? " 2"
3117 : iptr_new
> s1
->include_stack
? " 3"
3121 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", file
->line_num
, file
->filename
, s
);
3124 fputs("\n", s1
->ppfp
), --d
;
3126 line_ref
= (file_ref
= file
)->line_num
;
3127 token_seen
= tok
!= TOK_LINEFEED
;
3131 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);
3133 free_defines(define_start
);