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
, "%Lu", 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
)
940 /* save line number info */
941 if (file
->line_num
!= s
->last_line_num
) {
942 s
->last_line_num
= file
->line_num
;
943 cval
.i
= s
->last_line_num
;
944 tok_str_add2(s
, TOK_LINENUM
, &cval
);
946 tok_str_add2(s
, tok
, &tokc
);
949 /* get a token from an integer array and increment pointer
950 accordingly. we code it as a macro to avoid pointer aliasing. */
951 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
969 cv
->cstr
= (CString
*)p
;
970 cv
->cstr
->data
= (char *)p
+ sizeof(CString
);
971 p
+= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
979 #if LDOUBLE_SIZE == 16
981 #elif LDOUBLE_SIZE == 12
983 #elif LDOUBLE_SIZE == 8
986 # error add long double size support
999 static int macro_is_equal(const int *a
, const int *b
)
1001 char buf
[STRING_MAX_SIZE
+ 1];
1005 TOK_GET(&t
, &a
, &cv
);
1006 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1007 TOK_GET(&t
, &b
, &cv
);
1008 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1014 /* defines handling */
1015 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1020 if (s
&& !macro_is_equal(s
->d
, str
))
1021 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1023 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1025 s
->next
= first_arg
;
1026 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1029 /* undefined a define symbol. Its name is just set to zero */
1030 ST_FUNC
void define_undef(Sym
*s
)
1034 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1035 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1039 ST_INLN Sym
*define_find(int v
)
1042 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1044 return table_ident
[v
]->sym_define
;
1047 /* free define stack until top reaches 'b' */
1048 ST_FUNC
void free_defines(Sym
*b
)
1056 /* do not free args or predefined defines */
1058 tok_str_free(top
->d
);
1060 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1061 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1069 ST_FUNC Sym
*label_find(int v
)
1072 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1074 return table_ident
[v
]->sym_label
;
1077 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1080 s
= sym_push2(ptop
, v
, 0, 0);
1082 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1083 if (ptop
== &global_label_stack
) {
1084 /* modify the top most local identifier, so that
1085 sym_identifier will point to 's' when popped */
1087 ps
= &(*ps
)->prev_tok
;
1094 /* pop labels until element last is reached. Look if any labels are
1095 undefined. Define symbols if '&&label' was used. */
1096 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1099 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1101 if (s
->r
== LABEL_DECLARED
) {
1102 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1103 } else if (s
->r
== LABEL_FORWARD
) {
1104 tcc_error("label '%s' used but not defined",
1105 get_tok_str(s
->v
, NULL
));
1108 /* define corresponding symbol. A size of
1110 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1114 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1120 /* eval an expression for #if/#elif */
1121 static int expr_preprocess(void)
1127 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1128 next(); /* do macro subst */
1129 if (tok
== TOK_DEFINED
) {
1134 c
= define_find(tok
) != 0;
1139 } else if (tok
>= TOK_IDENT
) {
1140 /* if undefined macro */
1144 tok_str_add_tok(&str
);
1146 tok_str_add(&str
, -1); /* simulate end of file */
1147 tok_str_add(&str
, 0);
1148 /* now evaluate C constant expression */
1149 macro_ptr
= str
.str
;
1153 tok_str_free(str
.str
);
1157 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1158 static void tok_print(int *str
)
1165 TOK_GET(&t
, &str
, &cval
);
1168 printf("%s", get_tok_str(t
, &cval
));
1174 /* parse after #define */
1175 ST_FUNC
void parse_define(void)
1177 Sym
*s
, *first
, **ps
;
1178 int v
, t
, varg
, is_vaargs
, spc
;
1183 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1184 /* XXX: should check if same macro (ANSI) */
1187 /* '(' must be just after macro definition for MACRO_FUNC */
1192 while (tok
!= ')') {
1196 if (varg
== TOK_DOTS
) {
1197 varg
= TOK___VA_ARGS__
;
1199 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1203 if (varg
< TOK_IDENT
)
1204 tcc_error("badly punctuated parameter list");
1205 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1218 /* EOF testing necessary for '-D' handling */
1219 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1220 /* remove spaces around ## and after '#' */
1221 if (TOK_TWOSHARPS
== tok
) {
1225 } else if ('#' == tok
) {
1227 } else if (check_space(tok
, &spc
)) {
1230 tok_str_add2(&str
, tok
, &tokc
);
1235 --str
.len
; /* remove trailing space */
1236 tok_str_add(&str
, 0);
1238 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
1241 define_push(v
, t
, str
.str
, first
);
1244 static inline int hash_cached_include(const char *filename
)
1246 const unsigned char *s
;
1252 h
= TOK_HASH_FUNC(h
, *s
);
1255 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1259 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1263 h
= hash_cached_include(filename
);
1264 i
= s1
->cached_includes_hash
[h
];
1268 e
= s1
->cached_includes
[i
- 1];
1269 if (0 == PATHCMP(e
->filename
, filename
))
1276 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1281 if (search_cached_include(s1
, filename
))
1284 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1286 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1287 strcpy(e
->filename
, filename
);
1288 e
->ifndef_macro
= ifndef_macro
;
1289 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1290 /* add in hash table */
1291 h
= hash_cached_include(filename
);
1292 e
->hash_next
= s1
->cached_includes_hash
[h
];
1293 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1296 static void pragma_parse(TCCState
*s1
)
1301 if (tok
== TOK_pack
) {
1304 #pragma pack(1) // set
1305 #pragma pack() // reset to default
1306 #pragma pack(push,1) // push & set
1307 #pragma pack(pop) // restore previous
1311 if (tok
== TOK_ASM_pop
) {
1313 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1315 tcc_error("out of pack stack");
1317 s1
->pack_stack_ptr
--;
1321 if (tok
== TOK_ASM_push
) {
1323 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1325 s1
->pack_stack_ptr
++;
1328 if (tok
!= TOK_CINT
) {
1330 tcc_error("invalid pack pragma");
1333 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1337 *s1
->pack_stack_ptr
= val
;
1343 /* is_bof is true if first non space token at beginning of file */
1344 ST_FUNC
void preprocess(int is_bof
)
1346 TCCState
*s1
= tcc_state
;
1347 int i
, c
, n
, saved_parse_flags
;
1351 saved_parse_flags
= parse_flags
;
1352 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
1353 PARSE_FLAG_LINEFEED
;
1363 s
= define_find(tok
);
1364 /* undefine symbol by putting an invalid name */
1369 case TOK_INCLUDE_NEXT
:
1370 ch
= file
->buf_ptr
[0];
1371 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1376 } else if (ch
== '\"') {
1381 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1382 if ((q
- buf
) < sizeof(buf
) - 1)
1385 if (handle_stray_noerror() == 0)
1393 /* eat all spaces and comments after include */
1394 /* XXX: slightly incorrect */
1395 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1399 /* computed #include : either we have only strings or
1400 we have anything enclosed in '<>' */
1403 if (tok
== TOK_STR
) {
1404 while (tok
!= TOK_LINEFEED
) {
1405 if (tok
!= TOK_STR
) {
1407 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1409 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1415 while (tok
!= TOK_LINEFEED
) {
1416 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1420 /* check syntax and remove '<>' */
1421 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1422 goto include_syntax
;
1423 memmove(buf
, buf
+ 1, len
- 2);
1424 buf
[len
- 2] = '\0';
1429 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1430 tcc_error("#include recursion too deep");
1431 /* store current file in stack, but increment stack later below */
1432 *s1
->include_stack_ptr
= file
;
1434 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1435 for (i
= -2; i
< n
; ++i
) {
1436 char buf1
[sizeof file
->filename
];
1442 /* check absolute include path */
1443 if (!IS_ABSPATH(buf
))
1446 i
= n
; /* force end loop */
1448 } else if (i
== -1) {
1449 /* search in current dir if "header.h" */
1452 path
= file
->filename
;
1453 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1456 /* search in all the include paths */
1457 if (i
< s1
->nb_include_paths
)
1458 path
= s1
->include_paths
[i
];
1460 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1461 pstrcpy(buf1
, sizeof(buf1
), path
);
1462 pstrcat(buf1
, sizeof(buf1
), "/");
1465 pstrcat(buf1
, sizeof(buf1
), buf
);
1467 if (tok
== TOK_INCLUDE_NEXT
)
1468 for (f
= s1
->include_stack_ptr
; f
>= s1
->include_stack
; --f
)
1469 if (0 == PATHCMP((*f
)->filename
, buf1
)) {
1471 printf("%s: #include_next skipping %s\n", file
->filename
, buf1
);
1473 goto include_trynext
;
1476 e
= search_cached_include(s1
, buf1
);
1477 if (e
&& define_find(e
->ifndef_macro
)) {
1478 /* no need to parse the include because the 'ifndef macro'
1481 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1486 if (tcc_open(s1
, buf1
) < 0)
1491 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1493 /* update target deps */
1494 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1496 /* push current file in stack */
1497 ++s1
->include_stack_ptr
;
1498 /* add include file debug info */
1500 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1501 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1502 ch
= file
->buf_ptr
[0];
1505 tcc_error("include file '%s' not found", buf
);
1512 c
= expr_preprocess();
1518 if (tok
< TOK_IDENT
)
1519 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1523 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1525 file
->ifndef_macro
= tok
;
1528 c
= (define_find(tok
) != 0) ^ c
;
1530 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1531 tcc_error("memory full (ifdef)");
1532 *s1
->ifdef_stack_ptr
++ = c
;
1535 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1536 tcc_error("#else without matching #if");
1537 if (s1
->ifdef_stack_ptr
[-1] & 2)
1538 tcc_error("#else after #else");
1539 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1542 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1543 tcc_error("#elif without matching #if");
1544 c
= s1
->ifdef_stack_ptr
[-1];
1546 tcc_error("#elif after #else");
1547 /* last #if/#elif expression was true: we skip */
1550 c
= expr_preprocess();
1551 s1
->ifdef_stack_ptr
[-1] = c
;
1553 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1554 file
->ifndef_macro
= 0;
1564 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1565 tcc_error("#endif without matching #if");
1566 s1
->ifdef_stack_ptr
--;
1567 /* '#ifndef macro' was at the start of file. Now we check if
1568 an '#endif' is exactly at the end of file */
1569 if (file
->ifndef_macro
&&
1570 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1571 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1572 /* need to set to zero to avoid false matches if another
1573 #ifndef at middle of file */
1574 file
->ifndef_macro
= 0;
1575 while (tok
!= TOK_LINEFEED
)
1577 tok_flags
|= TOK_FLAG_ENDIF
;
1583 if (tok
!= TOK_CINT
)
1585 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
1587 if (tok
!= TOK_LINEFEED
) {
1590 pstrcpy(file
->filename
, sizeof(file
->filename
),
1591 (char *)tokc
.cstr
->data
);
1597 ch
= file
->buf_ptr
[0];
1600 while (ch
!= '\n' && ch
!= CH_EOF
) {
1601 if ((q
- buf
) < sizeof(buf
) - 1)
1604 if (handle_stray_noerror() == 0)
1611 tcc_error("#error %s", buf
);
1613 tcc_warning("#warning %s", buf
);
1619 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_PPNUM
) {
1620 /* '!' is ignored to allow C scripts. numbers are ignored
1621 to emulate cpp behaviour */
1623 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
1624 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1626 /* this is a gas line comment in an 'S' file. */
1627 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1633 /* ignore other preprocess commands or #! for C scripts */
1634 while (tok
!= TOK_LINEFEED
)
1637 parse_flags
= saved_parse_flags
;
1640 /* evaluate escape codes in a string. */
1641 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1656 case '0': case '1': case '2': case '3':
1657 case '4': case '5': case '6': case '7':
1658 /* at most three octal digits */
1663 n
= n
* 8 + c
- '0';
1667 n
= n
* 8 + c
- '0';
1672 goto add_char_nonext
;
1680 if (c
>= 'a' && c
<= 'f')
1682 else if (c
>= 'A' && c
<= 'F')
1692 goto add_char_nonext
;
1716 goto invalid_escape
;
1726 if (c
>= '!' && c
<= '~')
1727 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1729 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1736 cstr_ccat(outstr
, c
);
1738 cstr_wccat(outstr
, c
);
1740 /* add a trailing '\0' */
1742 cstr_ccat(outstr
, '\0');
1744 cstr_wccat(outstr
, '\0');
1747 /* we use 64 bit numbers */
1750 /* bn = (bn << shift) | or_val */
1751 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
1755 for(i
=0;i
<BN_SIZE
;i
++) {
1757 bn
[i
] = (v
<< shift
) | or_val
;
1758 or_val
= v
>> (32 - shift
);
1762 static void bn_zero(unsigned int *bn
)
1765 for(i
=0;i
<BN_SIZE
;i
++) {
1770 /* parse number in null terminated string 'p' and return it in the
1772 static void parse_number(const char *p
)
1774 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
1776 unsigned int bn
[BN_SIZE
];
1787 goto float_frac_parse
;
1788 } else if (t
== '0') {
1789 if (ch
== 'x' || ch
== 'X') {
1793 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
1799 /* parse all digits. cannot check octal numbers at this stage
1800 because of floating point constants */
1802 if (ch
>= 'a' && ch
<= 'f')
1804 else if (ch
>= 'A' && ch
<= 'F')
1812 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
1814 tcc_error("number too long");
1820 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
1821 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
1823 /* NOTE: strtox should support that for hexa numbers, but
1824 non ISOC99 libcs do not support it, so we prefer to do
1826 /* hexadecimal or binary floats */
1827 /* XXX: handle overflows */
1839 } else if (t
>= 'a') {
1841 } else if (t
>= 'A') {
1846 bn_lshift(bn
, shift
, t
);
1853 if (t
>= 'a' && t
<= 'f') {
1855 } else if (t
>= 'A' && t
<= 'F') {
1857 } else if (t
>= '0' && t
<= '9') {
1863 tcc_error("invalid digit");
1864 bn_lshift(bn
, shift
, t
);
1869 if (ch
!= 'p' && ch
!= 'P')
1876 } else if (ch
== '-') {
1880 if (ch
< '0' || ch
> '9')
1881 expect("exponent digits");
1882 while (ch
>= '0' && ch
<= '9') {
1883 exp_val
= exp_val
* 10 + ch
- '0';
1886 exp_val
= exp_val
* s
;
1888 /* now we can generate the number */
1889 /* XXX: should patch directly float number */
1890 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
1891 d
= ldexp(d
, exp_val
- frac_bits
);
1896 /* float : should handle overflow */
1898 } else if (t
== 'L') {
1900 #ifdef TCC_TARGET_PE
1905 /* XXX: not large enough */
1906 tokc
.ld
= (long double)d
;
1913 /* decimal floats */
1915 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1920 while (ch
>= '0' && ch
<= '9') {
1921 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1927 if (ch
== 'e' || ch
== 'E') {
1928 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1932 if (ch
== '-' || ch
== '+') {
1933 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1938 if (ch
< '0' || ch
> '9')
1939 expect("exponent digits");
1940 while (ch
>= '0' && ch
<= '9') {
1941 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1953 tokc
.f
= strtof(token_buf
, NULL
);
1954 } else if (t
== 'L') {
1956 #ifdef TCC_TARGET_PE
1958 tokc
.d
= strtod(token_buf
, NULL
);
1961 tokc
.ld
= strtold(token_buf
, NULL
);
1965 tokc
.d
= strtod(token_buf
, NULL
);
1969 unsigned long long n
, n1
;
1972 /* integer number */
1975 if (b
== 10 && *q
== '0') {
1982 /* no need for checks except for base 10 / 8 errors */
1985 } else if (t
>= 'a') {
1987 } else if (t
>= 'A') {
1992 tcc_error("invalid digit");
1996 /* detect overflow */
1997 /* XXX: this test is not reliable */
1999 tcc_error("integer constant overflow");
2002 /* XXX: not exactly ANSI compliant */
2003 if ((n
& 0xffffffff00000000LL
) != 0) {
2008 } else if (n
> 0x7fffffff) {
2019 tcc_error("three 'l's in integer constant");
2021 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2024 if (tok
== TOK_CINT
)
2026 else if (tok
== TOK_CUINT
)
2028 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2032 } else if (t
== 'U') {
2034 tcc_error("two 'u's in integer constant");
2036 if (tok
== TOK_CINT
)
2038 else if (tok
== TOK_CLLONG
)
2045 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2051 tcc_error("invalid number\n");
2055 #define PARSE2(c1, tok1, c2, tok2) \
2066 /* return next token without macro substitution */
2067 static inline void next_nomacro1(void)
2082 goto keep_tok_flags
;
2089 /* first look if it is in fact an end of buffer */
2090 if (p
>= file
->buf_end
) {
2094 if (p
>= file
->buf_end
)
2107 TCCState
*s1
= tcc_state
;
2108 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2109 && !(tok_flags
& TOK_FLAG_EOF
)) {
2110 tok_flags
|= TOK_FLAG_EOF
;
2112 goto keep_tok_flags
;
2113 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2115 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2116 tcc_error("missing #endif");
2117 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2118 /* no include left : end of file. */
2121 tok_flags
&= ~TOK_FLAG_EOF
;
2122 /* pop include file */
2124 /* test if previous '#endif' was after a #ifdef at
2126 if (tok_flags
& TOK_FLAG_ENDIF
) {
2128 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2130 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2131 tok_flags
&= ~TOK_FLAG_ENDIF
;
2134 /* add end of include file debug info */
2135 if (tcc_state
->do_debug
) {
2136 put_stabd(N_EINCL
, 0, 0);
2138 /* pop include stack */
2140 s1
->include_stack_ptr
--;
2149 tok_flags
|= TOK_FLAG_BOL
;
2152 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2155 goto keep_tok_flags
;
2160 if ((tok_flags
& TOK_FLAG_BOL
) &&
2161 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2163 preprocess(tok_flags
& TOK_FLAG_BOF
);
2169 tok
= TOK_TWOSHARPS
;
2171 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
2172 p
= parse_line_comment(p
- 1);
2181 case 'a': case 'b': case 'c': case 'd':
2182 case 'e': case 'f': case 'g': case 'h':
2183 case 'i': case 'j': case 'k': case 'l':
2184 case 'm': case 'n': case 'o': case 'p':
2185 case 'q': case 'r': case 's': case 't':
2186 case 'u': case 'v': case 'w': case 'x':
2188 case 'A': case 'B': case 'C': case 'D':
2189 case 'E': case 'F': case 'G': case 'H':
2190 case 'I': case 'J': case 'K':
2191 case 'M': case 'N': case 'O': case 'P':
2192 case 'Q': case 'R': case 'S': case 'T':
2193 case 'U': case 'V': case 'W': case 'X':
2199 h
= TOK_HASH_FUNC(h
, c
);
2203 if (!isidnum_table
[c
-CH_EOF
])
2205 h
= TOK_HASH_FUNC(h
, c
);
2212 /* fast case : no stray found, so we have the full token
2213 and we have already hashed it */
2215 h
&= (TOK_HASH_SIZE
- 1);
2216 pts
= &hash_ident
[h
];
2221 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2223 pts
= &(ts
->hash_next
);
2225 ts
= tok_alloc_new(pts
, p1
, len
);
2229 cstr_reset(&tokcstr
);
2232 cstr_ccat(&tokcstr
, *p1
);
2238 while (isidnum_table
[c
-CH_EOF
]) {
2239 cstr_ccat(&tokcstr
, c
);
2242 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2248 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2250 goto parse_ident_fast
;
2253 if (c
== '\'' || c
== '\"') {
2257 cstr_reset(&tokcstr
);
2258 cstr_ccat(&tokcstr
, 'L');
2259 goto parse_ident_slow
;
2263 case '0': case '1': case '2': case '3':
2264 case '4': case '5': case '6': case '7':
2267 cstr_reset(&tokcstr
);
2268 /* after the first digit, accept digits, alpha, '.' or sign if
2269 prefixed by 'eEpP' */
2273 cstr_ccat(&tokcstr
, c
);
2275 if (!(isnum(c
) || isid(c
) || c
== '.' ||
2276 ((c
== '+' || c
== '-') &&
2277 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
2280 /* We add a trailing '\0' to ease parsing */
2281 cstr_ccat(&tokcstr
, '\0');
2282 tokc
.cstr
= &tokcstr
;
2286 /* special dot handling because it can also start a number */
2289 cstr_reset(&tokcstr
);
2290 cstr_ccat(&tokcstr
, '.');
2292 } else if (c
== '.') {
2312 /* parse the string */
2314 p
= parse_pp_string(p
, sep
, &str
);
2315 cstr_ccat(&str
, '\0');
2317 /* eval the escape (should be done as TOK_PPNUM) */
2318 cstr_reset(&tokcstr
);
2319 parse_escape_string(&tokcstr
, str
.data
, is_long
);
2324 /* XXX: make it portable */
2328 char_size
= sizeof(nwchar_t
);
2329 if (tokcstr
.size
<= char_size
)
2330 tcc_error("empty character constant");
2331 if (tokcstr
.size
> 2 * char_size
)
2332 tcc_warning("multi-character character constant");
2334 tokc
.i
= *(int8_t *)tokcstr
.data
;
2337 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2341 tokc
.cstr
= &tokcstr
;
2355 } else if (c
== '<') {
2373 } else if (c
== '>') {
2391 } else if (c
== '=') {
2404 } else if (c
== '=') {
2417 } else if (c
== '=') {
2430 } else if (c
== '=') {
2433 } else if (c
== '>') {
2441 PARSE2('!', '!', '=', TOK_NE
)
2442 PARSE2('=', '=', '=', TOK_EQ
)
2443 PARSE2('*', '*', '=', TOK_A_MUL
)
2444 PARSE2('%', '%', '=', TOK_A_MOD
)
2445 PARSE2('^', '^', '=', TOK_A_XOR
)
2447 /* comments or operator */
2451 p
= parse_comment(p
);
2452 /* comments replaced by a blank */
2454 goto keep_tok_flags
;
2455 } else if (c
== '/') {
2456 p
= parse_line_comment(p
);
2458 goto keep_tok_flags
;
2459 } else if (c
== '=') {
2479 case '$': /* only used in assembler */
2480 case '@': /* dito */
2485 tcc_error("unrecognized character \\x%02x", c
);
2491 #if defined(PARSE_DEBUG)
2492 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2496 /* return next token without macro substitution. Can read input from
2498 static void next_nomacro_spc(void)
2504 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2505 if (tok
== TOK_LINENUM
) {
2506 file
->line_num
= tokc
.i
;
2515 ST_FUNC
void next_nomacro(void)
2519 } while (is_space(tok
));
2522 /* substitute args in macro_str and return allocated string */
2523 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2525 int last_tok
, t
, spc
;
2535 TOK_GET(&t
, ¯o_str
, &cval
);
2540 TOK_GET(&t
, ¯o_str
, &cval
);
2543 s
= sym_find2(args
, t
);
2549 TOK_GET(&t
, &st
, &cval
);
2550 if (!check_space(t
, &spc
))
2551 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2554 cstr_ccat(&cstr
, '\0');
2556 printf("stringize: %s\n", (char *)cstr
.data
);
2560 tok_str_add2(&str
, TOK_STR
, &cval
);
2563 tok_str_add2(&str
, t
, &cval
);
2565 } else if (t
>= TOK_IDENT
) {
2566 s
= sym_find2(args
, t
);
2569 /* if '##' is present before or after, no arg substitution */
2570 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
2571 /* special case for var arg macros : ## eats the
2572 ',' if empty VA_ARGS variable. */
2573 /* XXX: test of the ',' is not 100%
2574 reliable. should fix it to avoid security
2576 if (gnu_ext
&& s
->type
.t
&&
2577 last_tok
== TOK_TWOSHARPS
&&
2578 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
2580 /* suppress ',' '##' */
2583 /* suppress '##' and add variable */
2591 TOK_GET(&t1
, &st
, &cval
);
2594 tok_str_add2(&str
, t1
, &cval
);
2598 /* NOTE: the stream cannot be read when macro
2599 substituing an argument */
2600 macro_subst(&str
, nested_list
, st
, NULL
);
2603 tok_str_add(&str
, t
);
2606 tok_str_add2(&str
, t
, &cval
);
2610 tok_str_add(&str
, 0);
2614 static char const ab_month_name
[12][4] =
2616 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2617 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2620 /* do macro substitution of current token with macro 's' and add
2621 result to (tok_str,tok_len). 'nested_list' is the list of all
2622 macros we got inside to avoid recursing. Return non zero if no
2623 substitution needs to be done */
2624 static int macro_subst_tok(TokenString
*tok_str
,
2625 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
2627 Sym
*args
, *sa
, *sa1
;
2628 int mstr_allocated
, parlevel
, *mstr
, t
, t1
, spc
;
2636 /* if symbol is a macro, prepare substitution */
2637 /* special macros */
2638 if (tok
== TOK___LINE__
) {
2639 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2643 } else if (tok
== TOK___FILE__
) {
2644 cstrval
= file
->filename
;
2646 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2651 tm
= localtime(&ti
);
2652 if (tok
== TOK___DATE__
) {
2653 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2654 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2656 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2657 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2664 cstr_cat(&cstr
, cstrval
);
2665 cstr_ccat(&cstr
, '\0');
2667 tok_str_add2(tok_str
, t1
, &cval
);
2672 if (s
->type
.t
== MACRO_FUNC
) {
2673 /* NOTE: we do not use next_nomacro to avoid eating the
2674 next token. XXX: find better solution */
2678 while (is_space(t
= *p
) || TOK_LINEFEED
== t
)
2680 if (t
== 0 && can_read_stream
) {
2681 /* end of macro stream: we must look at the token
2682 after in the file */
2683 struct macro_level
*ml
= *can_read_stream
;
2689 *can_read_stream
= ml
-> prev
;
2691 /* also, end of scope for nested defined symbol */
2692 (*nested_list
)->v
= -1;
2696 ch
= file
->buf_ptr
[0];
2697 while (is_space(ch
) || ch
== '\n' || ch
== '/')
2702 uint8_t *p
= file
->buf_ptr
;
2705 p
= parse_comment(p
);
2706 file
->buf_ptr
= p
- 1;
2707 } else if (c
== '/') {
2708 p
= parse_line_comment(p
);
2709 file
->buf_ptr
= p
- 1;
2717 if (t
!= '(') /* no macro subst */
2720 /* argument macro */
2725 /* NOTE: empty args are allowed, except if no args */
2727 /* handle '()' case */
2728 if (!args
&& !sa
&& tok
== ')')
2731 tcc_error("macro '%s' used with too many args",
2732 get_tok_str(s
->v
, 0));
2735 /* NOTE: non zero sa->t indicates VA_ARGS */
2736 while ((parlevel
> 0 ||
2738 (tok
!= ',' || sa
->type
.t
))) &&
2742 else if (tok
== ')')
2744 if (tok
== TOK_LINEFEED
)
2746 if (!check_space(tok
, &spc
))
2747 tok_str_add2(&str
, tok
, &tokc
);
2751 tok_str_add(&str
, 0);
2752 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
2756 /* special case for gcc var args: add an empty
2757 var arg argument if it is omitted */
2758 if (sa
&& sa
->type
.t
&& gnu_ext
)
2768 tcc_error("macro '%s' used with too few args",
2769 get_tok_str(s
->v
, 0));
2772 /* now subst each arg */
2773 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
2778 tok_str_free(sa
->d
);
2784 sym_push2(nested_list
, s
->v
, 0, 0);
2785 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
2786 /* pop nested defined symbol */
2788 *nested_list
= sa1
->prev
;
2796 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2797 return the resulting string (which must be freed). */
2798 static inline int *macro_twosharps(const int *macro_str
)
2802 TokenString macro_str1
;
2804 int n
, start_of_nosubsts
;
2806 /* we search the first '##' */
2807 for(ptr
= macro_str
;;) {
2809 TOK_GET(&t
, &ptr
, &cval
);
2810 if (t
== TOK_TWOSHARPS
)
2812 /* nothing more to do if end of string */
2817 /* we saw '##', so we need more processing to handle it */
2818 start_of_nosubsts
= -1;
2819 tok_str_new(¯o_str1
);
2820 for(ptr
= macro_str
;;) {
2821 TOK_GET(&tok
, &ptr
, &tokc
);
2824 if (tok
== TOK_TWOSHARPS
)
2826 if (tok
== TOK_NOSUBST
&& start_of_nosubsts
< 0)
2827 start_of_nosubsts
= macro_str1
.len
;
2828 while (*ptr
== TOK_TWOSHARPS
) {
2829 /* given 'a##b', remove nosubsts preceding 'a' */
2830 if (start_of_nosubsts
>= 0)
2831 macro_str1
.len
= start_of_nosubsts
;
2832 /* given 'a##b', skip '##' */
2834 /* given 'a##b', remove nosubsts preceding 'b' */
2835 while (t
== TOK_NOSUBST
)
2837 if (t
&& t
!= TOK_TWOSHARPS
) {
2839 TOK_GET(&t
, &ptr
, &cval
);
2840 /* We concatenate the two tokens */
2842 cstr_cat(&cstr
, get_tok_str(tok
, &tokc
));
2844 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2845 cstr_ccat(&cstr
, '\0');
2847 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
2848 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
2851 if (0 == *file
->buf_ptr
)
2853 tok_str_add2(¯o_str1
, tok
, &tokc
);
2854 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2855 n
, cstr
.data
, (char*)cstr
.data
+ n
);
2861 if (tok
!= TOK_NOSUBST
)
2862 start_of_nosubsts
= -1;
2863 tok_str_add2(¯o_str1
, tok
, &tokc
);
2865 tok_str_add(¯o_str1
, 0);
2866 return macro_str1
.str
;
2870 /* do macro substitution of macro_str and add result to
2871 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2872 inside to avoid recursing. */
2873 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
2874 const int *macro_str
, struct macro_level
** can_read_stream
)
2881 struct macro_level ml
;
2884 /* first scan for '##' operator handling */
2886 macro_str1
= macro_twosharps(ptr
);
2894 /* NOTE: ptr == NULL can only happen if tokens are read from
2895 file stream due to a macro function call */
2898 TOK_GET(&t
, &ptr
, &cval
);
2901 if (t
== TOK_NOSUBST
) {
2902 /* following token has already been subst'd. just copy it on */
2903 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
2904 TOK_GET(&t
, &ptr
, &cval
);
2909 /* if nested substitution, do nothing */
2910 if (sym_find2(*nested_list
, t
)) {
2911 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
2912 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
2916 if (can_read_stream
)
2917 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
2918 macro_ptr
= (int *)ptr
;
2920 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
2921 ptr
= (int *)macro_ptr
;
2923 if (can_read_stream
&& *can_read_stream
== &ml
)
2924 *can_read_stream
= ml
.prev
;
2927 if (parse_flags
& PARSE_FLAG_SPACES
)
2932 tok_str_add(tok_str
, ' ');
2936 if (!check_space(t
, &spc
))
2937 tok_str_add2(tok_str
, t
, &cval
);
2941 tok_str_free(macro_str1
);
2944 /* return next token with macro substitution */
2945 ST_FUNC
void next(void)
2947 Sym
*nested_list
, *s
;
2949 struct macro_level
*ml
;
2952 if (parse_flags
& PARSE_FLAG_SPACES
)
2957 /* if not reading from macro substituted string, then try
2958 to substitute macros */
2959 if (tok
>= TOK_IDENT
&&
2960 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2961 s
= define_find(tok
);
2963 /* we have a macro: we try to substitute */
2967 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
2968 /* substitution done, NOTE: maybe empty */
2969 tok_str_add(&str
, 0);
2970 macro_ptr
= str
.str
;
2971 macro_ptr_allocated
= str
.str
;
2978 /* end of macro or end of unget buffer */
2979 if (unget_buffer_enabled
) {
2980 macro_ptr
= unget_saved_macro_ptr
;
2981 unget_buffer_enabled
= 0;
2983 /* end of macro string: free it */
2984 tok_str_free(macro_ptr_allocated
);
2985 macro_ptr_allocated
= NULL
;
2989 } else if (tok
== TOK_NOSUBST
) {
2990 /* discard preprocessor's nosubst markers */
2995 /* convert preprocessor tokens into C tokens */
2996 if (tok
== TOK_PPNUM
&&
2997 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
2998 parse_number((char *)tokc
.cstr
->data
);
3002 /* push back current token and set current token to 'last_tok'. Only
3003 identifier case handled for labels. */
3004 ST_INLN
void unget_tok(int last_tok
)
3008 if (unget_buffer_enabled
)
3010 /* assert(macro_ptr == unget_saved_buffer + 1);
3011 assert(*macro_ptr == 0); */
3015 unget_saved_macro_ptr
= macro_ptr
;
3016 unget_buffer_enabled
= 1;
3018 q
= unget_saved_buffer
;
3021 n
= tok_ext_size(tok
) - 1;
3024 *q
= 0; /* end of token string */
3029 /* better than nothing, but needs extension to handle '-E' option
3031 ST_FUNC
void preprocess_init(TCCState
*s1
)
3033 s1
->include_stack_ptr
= s1
->include_stack
;
3034 /* XXX: move that before to avoid having to initialize
3035 file->ifdef_stack_ptr ? */
3036 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3037 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3040 s1
->pack_stack
[0] = 0;
3041 s1
->pack_stack_ptr
= s1
->pack_stack
;
3044 ST_FUNC
void preprocess_new(void)
3049 /* init isid table */
3050 for(i
=CH_EOF
;i
<256;i
++)
3051 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
3053 /* add all tokens */
3055 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3057 tok_ident
= TOK_IDENT
;
3066 tok_alloc(p
, r
- p
- 1);
3071 /* Preprocess the current file */
3072 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3076 BufferedFile
*file_ref
, **iptr
, **iptr_new
;
3077 int token_seen
, line_ref
, d
;
3080 preprocess_init(s1
);
3081 define_start
= define_stack
;
3082 ch
= file
->buf_ptr
[0];
3083 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3084 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
3085 PARSE_FLAG_LINEFEED
| PARSE_FLAG_SPACES
;
3089 iptr
= s1
->include_stack_ptr
;
3093 if (tok
== TOK_EOF
) {
3095 } else if (file
!= file_ref
) {
3097 } else if (tok
== TOK_LINEFEED
) {
3102 } else if (!token_seen
) {
3103 d
= file
->line_num
- line_ref
;
3104 if (file
!= file_ref
|| d
< 0 || d
>= 8) {
3106 iptr_new
= s1
->include_stack_ptr
;
3107 s
= iptr_new
> iptr
? " 1"
3108 : iptr_new
< iptr
? " 2"
3109 : iptr_new
> s1
->include_stack
? " 3"
3113 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", file
->line_num
, file
->filename
, s
);
3116 fputs("\n", s1
->ppfp
), --d
;
3118 line_ref
= (file_ref
= file
)->line_num
;
3119 token_seen
= tok
!= TOK_LINEFEED
;
3123 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);
3125 free_defines(define_start
);