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 ST_FUNC
void next_nomacro(void);
82 static void next_nomacro_spc(void);
83 static void macro_subst(
87 struct macro_level
**can_read_stream
90 ST_FUNC
void skip(int c
)
93 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
97 ST_FUNC
void expect(const char *msg
)
99 tcc_error("%s expected", msg
);
102 /* ------------------------------------------------------------------------- */
103 /* CString handling */
104 static void cstr_realloc(CString
*cstr
, int new_size
)
109 size
= cstr
->size_allocated
;
111 size
= 8; /* no need to allocate a too small first string */
112 while (size
< new_size
)
114 data
= tcc_realloc(cstr
->data_allocated
, size
);
115 cstr
->data_allocated
= data
;
116 cstr
->size_allocated
= size
;
121 ST_FUNC
void cstr_ccat(CString
*cstr
, int ch
)
124 size
= cstr
->size
+ 1;
125 if (size
> cstr
->size_allocated
)
126 cstr_realloc(cstr
, size
);
127 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
131 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
)
143 /* add a wide char */
144 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
147 size
= cstr
->size
+ sizeof(nwchar_t
);
148 if (size
> cstr
->size_allocated
)
149 cstr_realloc(cstr
, size
);
150 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
154 ST_FUNC
void cstr_new(CString
*cstr
)
156 memset(cstr
, 0, sizeof(CString
));
159 /* free string and reset it to NULL */
160 ST_FUNC
void cstr_free(CString
*cstr
)
162 tcc_free(cstr
->data_allocated
);
166 /* reset string to empty */
167 ST_FUNC
void cstr_reset(CString
*cstr
)
173 static void add_char(CString
*cstr
, int c
)
175 if (c
== '\'' || c
== '\"' || c
== '\\') {
176 /* XXX: could be more precise if char or string */
177 cstr_ccat(cstr
, '\\');
179 if (c
>= 32 && c
<= 126) {
182 cstr_ccat(cstr
, '\\');
184 cstr_ccat(cstr
, 'n');
186 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
187 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
188 cstr_ccat(cstr
, '0' + (c
& 7));
193 /* ------------------------------------------------------------------------- */
194 /* allocate a new token */
195 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
197 TokenSym
*ts
, **ptable
;
200 if (tok_ident
>= SYM_FIRST_ANOM
)
201 tcc_error("memory full");
203 /* expand token table if needed */
204 i
= tok_ident
- TOK_IDENT
;
205 if ((i
% TOK_ALLOC_INCR
) == 0) {
206 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
207 table_ident
= ptable
;
210 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
212 ts
->tok
= tok_ident
++;
213 ts
->sym_define
= NULL
;
214 ts
->sym_label
= NULL
;
215 ts
->sym_struct
= NULL
;
216 ts
->sym_identifier
= NULL
;
218 ts
->hash_next
= NULL
;
219 memcpy(ts
->str
, str
, len
);
225 #define TOK_HASH_INIT 1
226 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
228 /* find a token and add it if not found */
229 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
237 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
238 h
&= (TOK_HASH_SIZE
- 1);
240 pts
= &hash_ident
[h
];
245 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
247 pts
= &(ts
->hash_next
);
249 return tok_alloc_new(pts
, str
, len
);
252 /* XXX: buffer overflow */
253 /* XXX: float tokens */
254 ST_FUNC
char *get_tok_str(int v
, CValue
*cv
)
256 static char buf
[STRING_MAX_SIZE
+ 1];
257 static CString cstr_buf
;
262 /* NOTE: to go faster, we give a fixed buffer for small strings */
263 cstr_reset(&cstr_buf
);
265 cstr_buf
.size_allocated
= sizeof(buf
);
271 /* XXX: not quite exact, but only useful for testing */
272 sprintf(p
, "%u", cv
->ui
);
276 /* XXX: not quite exact, but only useful for testing */
278 sprintf(p
, "%u", (unsigned)cv
->ull
);
280 sprintf(p
, "%Lu", cv
->ull
);
284 cstr_ccat(&cstr_buf
, 'L');
286 cstr_ccat(&cstr_buf
, '\'');
287 add_char(&cstr_buf
, cv
->i
);
288 cstr_ccat(&cstr_buf
, '\'');
289 cstr_ccat(&cstr_buf
, '\0');
293 len
= cstr
->size
- 1;
295 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
296 cstr_ccat(&cstr_buf
, '\0');
299 cstr_ccat(&cstr_buf
, 'L');
302 cstr_ccat(&cstr_buf
, '\"');
304 len
= cstr
->size
- 1;
306 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
308 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
310 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
312 cstr_ccat(&cstr_buf
, '\"');
313 cstr_ccat(&cstr_buf
, '\0');
322 return strcpy(p
, "...");
324 return strcpy(p
, "<<=");
326 return strcpy(p
, ">>=");
329 /* search in two bytes table */
330 const unsigned char *q
= tok_two_chars
;
343 } else if (v
< tok_ident
) {
344 return table_ident
[v
- TOK_IDENT
]->str
;
345 } else if (v
>= SYM_FIRST_ANOM
) {
346 /* special name for anonymous symbol */
347 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
349 /* should never happen */
354 return cstr_buf
.data
;
357 /* fill input buffer and peek next char */
358 static int tcc_peekc_slow(BufferedFile
*bf
)
361 /* only tries to read if really end of buffer */
362 if (bf
->buf_ptr
>= bf
->buf_end
) {
364 #if defined(PARSE_DEBUG)
369 len
= read(bf
->fd
, bf
->buffer
, len
);
376 bf
->buf_ptr
= bf
->buffer
;
377 bf
->buf_end
= bf
->buffer
+ len
;
378 *bf
->buf_end
= CH_EOB
;
380 if (bf
->buf_ptr
< bf
->buf_end
) {
381 return bf
->buf_ptr
[0];
383 bf
->buf_ptr
= bf
->buf_end
;
388 /* return the current character, handling end of block if necessary
390 ST_FUNC
int handle_eob(void)
392 return tcc_peekc_slow(file
);
395 /* read next char from current input file and handle end of input buffer */
396 ST_INLN
void inp(void)
398 ch
= *(++(file
->buf_ptr
));
399 /* end of buffer/file handling */
404 /* handle '\[\r]\n' */
405 static int handle_stray_noerror(void)
412 } else if (ch
== '\r') {
426 static void handle_stray(void)
428 if (handle_stray_noerror())
429 tcc_error("stray '\\' in program");
432 /* skip the stray and handle the \\n case. Output an error if
433 incorrect char after the stray */
434 static int handle_stray1(uint8_t *p
)
438 if (p
>= file
->buf_end
) {
455 /* handle just the EOB case, but not stray */
456 #define PEEKC_EOB(c, p)\
467 /* handle the complicated stray case */
473 c = handle_stray1(p);\
478 /* input with '\[\r]\n' handling. Note that this function cannot
479 handle other characters after '\', so you cannot call it inside
480 strings or comments */
481 ST_FUNC
void minp(void)
489 /* single line C++ comments */
490 static uint8_t *parse_line_comment(uint8_t *p
)
498 if (c
== '\n' || c
== CH_EOF
) {
500 } else if (c
== '\\') {
509 } else if (c
== '\r') {
527 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
536 if (c
== '\n' || c
== '*' || c
== '\\')
540 if (c
== '\n' || c
== '*' || c
== '\\')
544 /* now we can handle all the cases */
548 } else if (c
== '*') {
554 } else if (c
== '/') {
556 } else if (c
== '\\') {
561 /* skip '\[\r]\n', otherwise just skip the stray */
567 } else if (c
== '\r') {
584 /* stray, eob or eof */
589 tcc_error("unexpected end of file in comment");
590 } else if (c
== '\\') {
602 static inline void skip_spaces(void)
608 static inline int check_space(int t
, int *spc
)
619 /* parse a string without interpreting escapes */
620 static uint8_t *parse_pp_string(uint8_t *p
,
621 int sep
, CString
*str
)
629 } else if (c
== '\\') {
635 /* XXX: indicate line number of start of string */
636 tcc_error("missing terminating %c character", sep
);
637 } else if (c
== '\\') {
638 /* escape : just skip \[\r]\n */
643 } else if (c
== '\r') {
646 expect("'\n' after '\r'");
649 } else if (c
== CH_EOF
) {
650 goto unterminated_string
;
653 cstr_ccat(str
, '\\');
659 } else if (c
== '\n') {
662 } else if (c
== '\r') {
666 cstr_ccat(str
, '\r');
682 /* skip block of text until #else, #elif or #endif. skip also pairs of
684 static void preprocess_skip(void)
686 int a
, start_of_line
, c
, in_warn_or_error
;
693 in_warn_or_error
= 0;
714 } else if (c
== '\\') {
715 ch
= file
->buf_ptr
[0];
716 handle_stray_noerror();
723 if (in_warn_or_error
)
725 p
= parse_pp_string(p
, c
, NULL
);
729 if (in_warn_or_error
)
736 p
= parse_comment(p
);
737 } else if (ch
== '/') {
738 p
= parse_line_comment(p
);
748 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
750 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
752 else if (tok
== TOK_ENDIF
)
754 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
755 in_warn_or_error
= 1;
756 else if (tok
== TOK_LINEFEED
)
771 /* ParseState handling */
773 /* XXX: currently, no include file info is stored. Thus, we cannot display
774 accurate messages if the function or data definition spans multiple
777 /* save current parse state in 's' */
778 ST_FUNC
void save_parse_state(ParseState
*s
)
780 s
->line_num
= file
->line_num
;
781 s
->macro_ptr
= macro_ptr
;
786 /* restore parse state from 's' */
787 ST_FUNC
void restore_parse_state(ParseState
*s
)
789 file
->line_num
= s
->line_num
;
790 macro_ptr
= s
->macro_ptr
;
795 /* return the number of additional 'ints' necessary to store the
797 static inline int tok_ext_size(int t
)
811 tcc_error("unsupported token");
818 return LDOUBLE_SIZE
/ 4;
824 /* token string handling */
826 ST_INLN
void tok_str_new(TokenString
*s
)
830 s
->allocated_len
= 0;
831 s
->last_line_num
= -1;
834 ST_FUNC
void tok_str_free(int *str
)
839 static int *tok_str_realloc(TokenString
*s
)
843 if (s
->allocated_len
== 0) {
846 len
= s
->allocated_len
* 2;
848 str
= tcc_realloc(s
->str
, len
* sizeof(int));
849 s
->allocated_len
= len
;
854 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
860 if (len
>= s
->allocated_len
)
861 str
= tok_str_realloc(s
);
866 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
873 /* allocate space for worst case */
874 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
875 str
= tok_str_realloc(s
);
884 str
[len
++] = cv
->tab
[0];
893 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
894 while ((len
+ nb_words
) > s
->allocated_len
)
895 str
= tok_str_realloc(s
);
896 cstr
= (CString
*)(str
+ len
);
898 cstr
->size
= cv
->cstr
->size
;
899 cstr
->data_allocated
= NULL
;
900 cstr
->size_allocated
= cstr
->size
;
901 memcpy((char *)cstr
+ sizeof(CString
),
902 cv
->cstr
->data
, cstr
->size
);
909 #if LDOUBLE_SIZE == 8
912 str
[len
++] = cv
->tab
[0];
913 str
[len
++] = cv
->tab
[1];
915 #if LDOUBLE_SIZE == 12
917 str
[len
++] = cv
->tab
[0];
918 str
[len
++] = cv
->tab
[1];
919 str
[len
++] = cv
->tab
[2];
920 #elif LDOUBLE_SIZE == 16
922 str
[len
++] = cv
->tab
[0];
923 str
[len
++] = cv
->tab
[1];
924 str
[len
++] = cv
->tab
[2];
925 str
[len
++] = cv
->tab
[3];
926 #elif LDOUBLE_SIZE != 8
927 #error add long double size support
936 /* add the current parse token in token string 's' */
937 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
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];
1006 TOK_GET(&t
, &a
, &cv
);
1007 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1008 TOK_GET(&t
, &b
, &cv
);
1009 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1015 /* defines handling */
1016 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1021 if (s
&& !macro_is_equal(s
->d
, str
))
1022 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1024 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1026 s
->next
= first_arg
;
1027 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1030 /* undefined a define symbol. Its name is just set to zero */
1031 ST_FUNC
void define_undef(Sym
*s
)
1035 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1036 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1040 ST_INLN Sym
*define_find(int v
)
1043 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1045 return table_ident
[v
]->sym_define
;
1048 /* free define stack until top reaches 'b' */
1049 ST_FUNC
void free_defines(Sym
*b
)
1057 /* do not free args or predefined defines */
1059 tok_str_free(top
->d
);
1061 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1062 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1070 ST_FUNC Sym
*label_find(int v
)
1073 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1075 return table_ident
[v
]->sym_label
;
1078 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1081 s
= sym_push2(ptop
, v
, 0, 0);
1083 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1084 if (ptop
== &global_label_stack
) {
1085 /* modify the top most local identifier, so that
1086 sym_identifier will point to 's' when popped */
1088 ps
= &(*ps
)->prev_tok
;
1095 /* pop labels until element last is reached. Look if any labels are
1096 undefined. Define symbols if '&&label' was used. */
1097 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1100 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1102 if (s
->r
== LABEL_DECLARED
) {
1103 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1104 } else if (s
->r
== LABEL_FORWARD
) {
1105 tcc_error("label '%s' used but not defined",
1106 get_tok_str(s
->v
, NULL
));
1109 /* define corresponding symbol. A size of
1111 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1115 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1121 /* eval an expression for #if/#elif */
1122 static int expr_preprocess(void)
1128 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1129 next(); /* do macro subst */
1130 if (tok
== TOK_DEFINED
) {
1135 c
= define_find(tok
) != 0;
1140 } else if (tok
>= TOK_IDENT
) {
1141 /* if undefined macro */
1145 tok_str_add_tok(&str
);
1147 tok_str_add(&str
, -1); /* simulate end of file */
1148 tok_str_add(&str
, 0);
1149 /* now evaluate C constant expression */
1150 macro_ptr
= str
.str
;
1154 tok_str_free(str
.str
);
1158 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1159 static void tok_print(int *str
)
1166 TOK_GET(&t
, &str
, &cval
);
1169 printf("%s", get_tok_str(t
, &cval
));
1175 /* parse after #define */
1176 ST_FUNC
void parse_define(void)
1178 Sym
*s
, *first
, **ps
;
1179 int v
, t
, varg
, is_vaargs
, spc
;
1184 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1185 /* XXX: should check if same macro (ANSI) */
1188 /* '(' must be just after macro definition for MACRO_FUNC */
1193 while (tok
!= ')') {
1197 if (varg
== TOK_DOTS
) {
1198 varg
= TOK___VA_ARGS__
;
1200 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1204 if (varg
< TOK_IDENT
)
1205 tcc_error("badly punctuated parameter list");
1206 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1219 /* EOF testing necessary for '-D' handling */
1220 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1221 /* remove spaces around ## and after '#' */
1222 if (TOK_TWOSHARPS
== tok
) {
1226 } else if ('#' == tok
) {
1228 } else if (check_space(tok
, &spc
)) {
1231 tok_str_add2(&str
, tok
, &tokc
);
1236 --str
.len
; /* remove trailing space */
1237 tok_str_add(&str
, 0);
1239 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
1242 define_push(v
, t
, str
.str
, first
);
1245 static inline int hash_cached_include(const char *filename
)
1247 const unsigned char *s
;
1253 h
= TOK_HASH_FUNC(h
, *s
);
1256 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1260 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1264 h
= hash_cached_include(filename
);
1265 i
= s1
->cached_includes_hash
[h
];
1269 e
= s1
->cached_includes
[i
- 1];
1270 if (0 == PATHCMP(e
->filename
, filename
))
1277 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1282 if (search_cached_include(s1
, filename
))
1285 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1287 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1288 strcpy(e
->filename
, filename
);
1289 e
->ifndef_macro
= ifndef_macro
;
1290 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1291 /* add in hash table */
1292 h
= hash_cached_include(filename
);
1293 e
->hash_next
= s1
->cached_includes_hash
[h
];
1294 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1297 static void pragma_parse(TCCState
*s1
)
1302 if (tok
== TOK_pack
) {
1305 #pragma pack(1) // set
1306 #pragma pack() // reset to default
1307 #pragma pack(push,1) // push & set
1308 #pragma pack(pop) // restore previous
1312 if (tok
== TOK_ASM_pop
) {
1314 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1316 tcc_error("out of pack stack");
1318 s1
->pack_stack_ptr
--;
1322 if (tok
== TOK_ASM_push
) {
1324 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1326 s1
->pack_stack_ptr
++;
1329 if (tok
!= TOK_CINT
) {
1331 tcc_error("invalid pack pragma");
1334 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1338 *s1
->pack_stack_ptr
= val
;
1344 /* is_bof is true if first non space token at beginning of file */
1345 ST_FUNC
void preprocess(int is_bof
)
1347 TCCState
*s1
= tcc_state
;
1348 int i
, c
, n
, saved_parse_flags
;
1352 saved_parse_flags
= parse_flags
;
1353 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
1354 PARSE_FLAG_LINEFEED
;
1364 s
= define_find(tok
);
1365 /* undefine symbol by putting an invalid name */
1370 case TOK_INCLUDE_NEXT
:
1371 ch
= file
->buf_ptr
[0];
1372 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1377 } else if (ch
== '\"') {
1382 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1383 if ((q
- buf
) < sizeof(buf
) - 1)
1386 if (handle_stray_noerror() == 0)
1394 /* eat all spaces and comments after include */
1395 /* XXX: slightly incorrect */
1396 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1400 /* computed #include : either we have only strings or
1401 we have anything enclosed in '<>' */
1404 if (tok
== TOK_STR
) {
1405 while (tok
!= TOK_LINEFEED
) {
1406 if (tok
!= TOK_STR
) {
1408 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1410 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1416 while (tok
!= TOK_LINEFEED
) {
1417 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1421 /* check syntax and remove '<>' */
1422 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1423 goto include_syntax
;
1424 memmove(buf
, buf
+ 1, len
- 2);
1425 buf
[len
- 2] = '\0';
1430 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1431 tcc_error("#include recursion too deep");
1432 /* store current file in stack, but increment stack later below */
1433 *s1
->include_stack_ptr
= file
;
1435 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1436 for (i
= -2; i
< n
; ++i
) {
1437 char buf1
[sizeof file
->filename
];
1443 /* check absolute include path */
1444 if (!IS_ABSPATH(buf
))
1447 i
= n
; /* force end loop */
1449 } else if (i
== -1) {
1450 /* search in current dir if "header.h" */
1453 path
= file
->filename
;
1454 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1457 /* search in all the include paths */
1458 if (i
< s1
->nb_include_paths
)
1459 path
= s1
->include_paths
[i
];
1461 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1462 pstrcpy(buf1
, sizeof(buf1
), path
);
1463 pstrcat(buf1
, sizeof(buf1
), "/");
1466 pstrcat(buf1
, sizeof(buf1
), buf
);
1468 if (tok
== TOK_INCLUDE_NEXT
)
1469 for (f
= s1
->include_stack_ptr
; f
>= s1
->include_stack
; --f
)
1470 if (0 == PATHCMP((*f
)->filename
, buf1
)) {
1472 printf("%s: #include_next skipping %s\n", file
->filename
, buf1
);
1474 goto include_trynext
;
1477 e
= search_cached_include(s1
, buf1
);
1478 if (e
&& define_find(e
->ifndef_macro
)) {
1479 /* no need to parse the include because the 'ifndef macro'
1482 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1487 if (tcc_open(s1
, buf1
) < 0)
1492 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1494 /* update target deps */
1495 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1497 /* push current file in stack */
1498 ++s1
->include_stack_ptr
;
1499 /* add include file debug info */
1501 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1502 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1503 ch
= file
->buf_ptr
[0];
1506 tcc_error("include file '%s' not found", buf
);
1513 c
= expr_preprocess();
1519 if (tok
< TOK_IDENT
)
1520 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1524 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1526 file
->ifndef_macro
= tok
;
1529 c
= (define_find(tok
) != 0) ^ c
;
1531 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1532 tcc_error("memory full");
1533 *s1
->ifdef_stack_ptr
++ = c
;
1536 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1537 tcc_error("#else without matching #if");
1538 if (s1
->ifdef_stack_ptr
[-1] & 2)
1539 tcc_error("#else after #else");
1540 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1543 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1544 tcc_error("#elif without matching #if");
1545 c
= s1
->ifdef_stack_ptr
[-1];
1547 tcc_error("#elif after #else");
1548 /* last #if/#elif expression was true: we skip */
1551 c
= expr_preprocess();
1552 s1
->ifdef_stack_ptr
[-1] = c
;
1554 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1555 file
->ifndef_macro
= 0;
1565 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1566 tcc_error("#endif without matching #if");
1567 s1
->ifdef_stack_ptr
--;
1568 /* '#ifndef macro' was at the start of file. Now we check if
1569 an '#endif' is exactly at the end of file */
1570 if (file
->ifndef_macro
&&
1571 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1572 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1573 /* need to set to zero to avoid false matches if another
1574 #ifndef at middle of file */
1575 file
->ifndef_macro
= 0;
1576 while (tok
!= TOK_LINEFEED
)
1578 tok_flags
|= TOK_FLAG_ENDIF
;
1584 if (tok
!= TOK_CINT
)
1586 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
1588 if (tok
!= TOK_LINEFEED
) {
1591 pstrcpy(file
->filename
, sizeof(file
->filename
),
1592 (char *)tokc
.cstr
->data
);
1598 ch
= file
->buf_ptr
[0];
1601 while (ch
!= '\n' && ch
!= CH_EOF
) {
1602 if ((q
- buf
) < sizeof(buf
) - 1)
1605 if (handle_stray_noerror() == 0)
1612 tcc_error("#error %s", buf
);
1614 tcc_warning("#warning %s", buf
);
1620 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_PPNUM
) {
1621 /* '!' is ignored to allow C scripts. numbers are ignored
1622 to emulate cpp behaviour */
1624 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
1625 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1627 /* this is a gas line comment in an 'S' file. */
1628 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1634 /* ignore other preprocess commands or #! for C scripts */
1635 while (tok
!= TOK_LINEFEED
)
1638 parse_flags
= saved_parse_flags
;
1641 /* evaluate escape codes in a string. */
1642 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1657 case '0': case '1': case '2': case '3':
1658 case '4': case '5': case '6': case '7':
1659 /* at most three octal digits */
1664 n
= n
* 8 + c
- '0';
1668 n
= n
* 8 + c
- '0';
1673 goto add_char_nonext
;
1681 if (c
>= 'a' && c
<= 'f')
1683 else if (c
>= 'A' && c
<= 'F')
1693 goto add_char_nonext
;
1717 goto invalid_escape
;
1727 if (c
>= '!' && c
<= '~')
1728 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1730 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1737 cstr_ccat(outstr
, c
);
1739 cstr_wccat(outstr
, c
);
1741 /* add a trailing '\0' */
1743 cstr_ccat(outstr
, '\0');
1745 cstr_wccat(outstr
, '\0');
1748 /* we use 64 bit numbers */
1751 /* bn = (bn << shift) | or_val */
1752 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
1756 for(i
=0;i
<BN_SIZE
;i
++) {
1758 bn
[i
] = (v
<< shift
) | or_val
;
1759 or_val
= v
>> (32 - shift
);
1763 static void bn_zero(unsigned int *bn
)
1766 for(i
=0;i
<BN_SIZE
;i
++) {
1771 /* parse number in null terminated string 'p' and return it in the
1773 static void parse_number(const char *p
)
1775 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
1777 unsigned int bn
[BN_SIZE
];
1788 goto float_frac_parse
;
1789 } else if (t
== '0') {
1790 if (ch
== 'x' || ch
== 'X') {
1794 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
1800 /* parse all digits. cannot check octal numbers at this stage
1801 because of floating point constants */
1803 if (ch
>= 'a' && ch
<= 'f')
1805 else if (ch
>= 'A' && ch
<= 'F')
1813 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
1815 tcc_error("number too long");
1821 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
1822 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
1824 /* NOTE: strtox should support that for hexa numbers, but
1825 non ISOC99 libcs do not support it, so we prefer to do
1827 /* hexadecimal or binary floats */
1828 /* XXX: handle overflows */
1840 } else if (t
>= 'a') {
1842 } else if (t
>= 'A') {
1847 bn_lshift(bn
, shift
, t
);
1854 if (t
>= 'a' && t
<= 'f') {
1856 } else if (t
>= 'A' && t
<= 'F') {
1858 } else if (t
>= '0' && t
<= '9') {
1864 tcc_error("invalid digit");
1865 bn_lshift(bn
, shift
, t
);
1870 if (ch
!= 'p' && ch
!= 'P')
1877 } else if (ch
== '-') {
1881 if (ch
< '0' || ch
> '9')
1882 expect("exponent digits");
1883 while (ch
>= '0' && ch
<= '9') {
1884 exp_val
= exp_val
* 10 + ch
- '0';
1887 exp_val
= exp_val
* s
;
1889 /* now we can generate the number */
1890 /* XXX: should patch directly float number */
1891 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
1892 d
= ldexp(d
, exp_val
- frac_bits
);
1897 /* float : should handle overflow */
1899 } else if (t
== 'L') {
1901 #ifdef TCC_TARGET_PE
1906 /* XXX: not large enough */
1907 tokc
.ld
= (long double)d
;
1914 /* decimal floats */
1916 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1921 while (ch
>= '0' && ch
<= '9') {
1922 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1928 if (ch
== 'e' || ch
== 'E') {
1929 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1933 if (ch
== '-' || ch
== '+') {
1934 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1939 if (ch
< '0' || ch
> '9')
1940 expect("exponent digits");
1941 while (ch
>= '0' && ch
<= '9') {
1942 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1954 tokc
.f
= strtof(token_buf
, NULL
);
1955 } else if (t
== 'L') {
1957 #ifdef TCC_TARGET_PE
1959 tokc
.d
= strtod(token_buf
, NULL
);
1962 tokc
.ld
= strtold(token_buf
, NULL
);
1966 tokc
.d
= strtod(token_buf
, NULL
);
1970 unsigned long long n
, n1
;
1973 /* integer number */
1976 if (b
== 10 && *q
== '0') {
1983 /* no need for checks except for base 10 / 8 errors */
1986 } else if (t
>= 'a') {
1988 } else if (t
>= 'A') {
1993 tcc_error("invalid digit");
1997 /* detect overflow */
1998 /* XXX: this test is not reliable */
2000 tcc_error("integer constant overflow");
2003 /* XXX: not exactly ANSI compliant */
2004 if ((n
& 0xffffffff00000000LL
) != 0) {
2009 } else if (n
> 0x7fffffff) {
2020 tcc_error("three 'l's in integer constant");
2022 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2025 if (tok
== TOK_CINT
)
2027 else if (tok
== TOK_CUINT
)
2029 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2033 } else if (t
== 'U') {
2035 tcc_error("two 'u's in integer constant");
2037 if (tok
== TOK_CINT
)
2039 else if (tok
== TOK_CLLONG
)
2046 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2052 tcc_error("invalid number\n");
2056 #define PARSE2(c1, tok1, c2, tok2) \
2067 /* return next token without macro substitution */
2068 static inline void next_nomacro1(void)
2083 goto keep_tok_flags
;
2090 /* first look if it is in fact an end of buffer */
2091 if (p
>= file
->buf_end
) {
2095 if (p
>= file
->buf_end
)
2108 TCCState
*s1
= tcc_state
;
2109 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2110 && !(tok_flags
& TOK_FLAG_EOF
)) {
2111 tok_flags
|= TOK_FLAG_EOF
;
2113 goto keep_tok_flags
;
2114 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2116 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2117 tcc_error("missing #endif");
2118 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2119 /* no include left : end of file. */
2122 tok_flags
&= ~TOK_FLAG_EOF
;
2123 /* pop include file */
2125 /* test if previous '#endif' was after a #ifdef at
2127 if (tok_flags
& TOK_FLAG_ENDIF
) {
2129 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2131 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2132 tok_flags
&= ~TOK_FLAG_ENDIF
;
2135 /* add end of include file debug info */
2136 if (tcc_state
->do_debug
) {
2137 put_stabd(N_EINCL
, 0, 0);
2139 /* pop include stack */
2141 s1
->include_stack_ptr
--;
2150 tok_flags
|= TOK_FLAG_BOL
;
2153 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2156 goto keep_tok_flags
;
2161 if ((tok_flags
& TOK_FLAG_BOL
) &&
2162 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2164 preprocess(tok_flags
& TOK_FLAG_BOF
);
2170 tok
= TOK_TWOSHARPS
;
2172 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
2173 p
= parse_line_comment(p
- 1);
2182 case 'a': case 'b': case 'c': case 'd':
2183 case 'e': case 'f': case 'g': case 'h':
2184 case 'i': case 'j': case 'k': case 'l':
2185 case 'm': case 'n': case 'o': case 'p':
2186 case 'q': case 'r': case 's': case 't':
2187 case 'u': case 'v': case 'w': case 'x':
2189 case 'A': case 'B': case 'C': case 'D':
2190 case 'E': case 'F': case 'G': case 'H':
2191 case 'I': case 'J': case 'K':
2192 case 'M': case 'N': case 'O': case 'P':
2193 case 'Q': case 'R': case 'S': case 'T':
2194 case 'U': case 'V': case 'W': case 'X':
2200 h
= TOK_HASH_FUNC(h
, c
);
2204 if (!isidnum_table
[c
-CH_EOF
])
2206 h
= TOK_HASH_FUNC(h
, c
);
2213 /* fast case : no stray found, so we have the full token
2214 and we have already hashed it */
2216 h
&= (TOK_HASH_SIZE
- 1);
2217 pts
= &hash_ident
[h
];
2222 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2224 pts
= &(ts
->hash_next
);
2226 ts
= tok_alloc_new(pts
, p1
, len
);
2230 cstr_reset(&tokcstr
);
2233 cstr_ccat(&tokcstr
, *p1
);
2239 while (isidnum_table
[c
-CH_EOF
]) {
2240 cstr_ccat(&tokcstr
, c
);
2243 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2249 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2251 goto parse_ident_fast
;
2254 if (c
== '\'' || c
== '\"') {
2258 cstr_reset(&tokcstr
);
2259 cstr_ccat(&tokcstr
, 'L');
2260 goto parse_ident_slow
;
2264 case '0': case '1': case '2': case '3':
2265 case '4': case '5': case '6': case '7':
2268 cstr_reset(&tokcstr
);
2269 /* after the first digit, accept digits, alpha, '.' or sign if
2270 prefixed by 'eEpP' */
2274 cstr_ccat(&tokcstr
, c
);
2276 if (!(isnum(c
) || isid(c
) || c
== '.' ||
2277 ((c
== '+' || c
== '-') &&
2278 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
2281 /* We add a trailing '\0' to ease parsing */
2282 cstr_ccat(&tokcstr
, '\0');
2283 tokc
.cstr
= &tokcstr
;
2287 /* special dot handling because it can also start a number */
2290 cstr_reset(&tokcstr
);
2291 cstr_ccat(&tokcstr
, '.');
2293 } else if (c
== '.') {
2313 /* parse the string */
2315 p
= parse_pp_string(p
, sep
, &str
);
2316 cstr_ccat(&str
, '\0');
2318 /* eval the escape (should be done as TOK_PPNUM) */
2319 cstr_reset(&tokcstr
);
2320 parse_escape_string(&tokcstr
, str
.data
, is_long
);
2325 /* XXX: make it portable */
2329 char_size
= sizeof(nwchar_t
);
2330 if (tokcstr
.size
<= char_size
)
2331 tcc_error("empty character constant");
2332 if (tokcstr
.size
> 2 * char_size
)
2333 tcc_warning("multi-character character constant");
2335 tokc
.i
= *(int8_t *)tokcstr
.data
;
2338 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2342 tokc
.cstr
= &tokcstr
;
2356 } else if (c
== '<') {
2374 } else if (c
== '>') {
2392 } else if (c
== '=') {
2405 } else if (c
== '=') {
2418 } else if (c
== '=') {
2431 } else if (c
== '=') {
2434 } else if (c
== '>') {
2442 PARSE2('!', '!', '=', TOK_NE
)
2443 PARSE2('=', '=', '=', TOK_EQ
)
2444 PARSE2('*', '*', '=', TOK_A_MUL
)
2445 PARSE2('%', '%', '=', TOK_A_MOD
)
2446 PARSE2('^', '^', '=', TOK_A_XOR
)
2448 /* comments or operator */
2452 p
= parse_comment(p
);
2453 /* comments replaced by a blank */
2455 goto keep_tok_flags
;
2456 } else if (c
== '/') {
2457 p
= parse_line_comment(p
);
2459 goto keep_tok_flags
;
2460 } else if (c
== '=') {
2480 case '$': /* only used in assembler */
2481 case '@': /* dito */
2486 tcc_error("unrecognized character \\x%02x", c
);
2492 #if defined(PARSE_DEBUG)
2493 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2497 /* return next token without macro substitution. Can read input from
2499 static void next_nomacro_spc(void)
2505 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2506 if (tok
== TOK_LINENUM
) {
2507 file
->line_num
= tokc
.i
;
2516 ST_FUNC
void next_nomacro(void)
2520 } while (is_space(tok
));
2523 /* substitute args in macro_str and return allocated string */
2524 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2526 int last_tok
, t
, spc
;
2536 TOK_GET(&t
, ¯o_str
, &cval
);
2541 TOK_GET(&t
, ¯o_str
, &cval
);
2544 s
= sym_find2(args
, t
);
2550 TOK_GET(&t
, &st
, &cval
);
2551 if (!check_space(t
, &spc
))
2552 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2555 cstr_ccat(&cstr
, '\0');
2557 printf("stringize: %s\n", (char *)cstr
.data
);
2561 tok_str_add2(&str
, TOK_STR
, &cval
);
2564 tok_str_add2(&str
, t
, &cval
);
2566 } else if (t
>= TOK_IDENT
) {
2567 s
= sym_find2(args
, t
);
2570 /* if '##' is present before or after, no arg substitution */
2571 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
2572 /* special case for var arg macros : ## eats the
2573 ',' if empty VA_ARGS variable. */
2574 /* XXX: test of the ',' is not 100%
2575 reliable. should fix it to avoid security
2577 if (gnu_ext
&& s
->type
.t
&&
2578 last_tok
== TOK_TWOSHARPS
&&
2579 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
2581 /* suppress ',' '##' */
2584 /* suppress '##' and add variable */
2592 TOK_GET(&t1
, &st
, &cval
);
2595 tok_str_add2(&str
, t1
, &cval
);
2599 /* NOTE: the stream cannot be read when macro
2600 substituing an argument */
2601 macro_subst(&str
, nested_list
, st
, NULL
);
2604 tok_str_add(&str
, t
);
2607 tok_str_add2(&str
, t
, &cval
);
2611 tok_str_add(&str
, 0);
2615 static char const ab_month_name
[12][4] =
2617 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2618 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2621 /* do macro substitution of current token with macro 's' and add
2622 result to (tok_str,tok_len). 'nested_list' is the list of all
2623 macros we got inside to avoid recursing. Return non zero if no
2624 substitution needs to be done */
2625 static int macro_subst_tok(TokenString
*tok_str
,
2626 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
2628 Sym
*args
, *sa
, *sa1
;
2629 int mstr_allocated
, parlevel
, *mstr
, t
, t1
, spc
;
2637 /* if symbol is a macro, prepare substitution */
2638 /* special macros */
2639 if (tok
== TOK___LINE__
) {
2640 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2644 } else if (tok
== TOK___FILE__
) {
2645 cstrval
= file
->filename
;
2647 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2652 tm
= localtime(&ti
);
2653 if (tok
== TOK___DATE__
) {
2654 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2655 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2657 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2658 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2665 cstr_cat(&cstr
, cstrval
);
2666 cstr_ccat(&cstr
, '\0');
2668 tok_str_add2(tok_str
, t1
, &cval
);
2673 if (s
->type
.t
== MACRO_FUNC
) {
2674 /* NOTE: we do not use next_nomacro to avoid eating the
2675 next token. XXX: find better solution */
2679 while (is_space(t
= *p
) || TOK_LINEFEED
== t
)
2681 if (t
== 0 && can_read_stream
) {
2682 /* end of macro stream: we must look at the token
2683 after in the file */
2684 struct macro_level
*ml
= *can_read_stream
;
2690 *can_read_stream
= ml
-> prev
;
2692 /* also, end of scope for nested defined symbol */
2693 (*nested_list
)->v
= -1;
2697 ch
= file
->buf_ptr
[0];
2698 while (is_space(ch
) || ch
== '\n' || ch
== '/')
2703 uint8_t *p
= file
->buf_ptr
;
2706 p
= parse_comment(p
);
2707 file
->buf_ptr
= p
- 1;
2708 } else if (c
== '/') {
2709 p
= parse_line_comment(p
);
2710 file
->buf_ptr
= p
- 1;
2718 if (t
!= '(') /* no macro subst */
2721 /* argument macro */
2726 /* NOTE: empty args are allowed, except if no args */
2728 /* handle '()' case */
2729 if (!args
&& !sa
&& tok
== ')')
2732 tcc_error("macro '%s' used with too many args",
2733 get_tok_str(s
->v
, 0));
2736 /* NOTE: non zero sa->t indicates VA_ARGS */
2737 while ((parlevel
> 0 ||
2739 (tok
!= ',' || sa
->type
.t
))) &&
2743 else if (tok
== ')')
2745 if (tok
== TOK_LINEFEED
)
2747 if (!check_space(tok
, &spc
))
2748 tok_str_add2(&str
, tok
, &tokc
);
2752 tok_str_add(&str
, 0);
2753 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
2757 /* special case for gcc var args: add an empty
2758 var arg argument if it is omitted */
2759 if (sa
&& sa
->type
.t
&& gnu_ext
)
2769 tcc_error("macro '%s' used with too few args",
2770 get_tok_str(s
->v
, 0));
2773 /* now subst each arg */
2774 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
2779 tok_str_free(sa
->d
);
2785 sym_push2(nested_list
, s
->v
, 0, 0);
2786 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
2787 /* pop nested defined symbol */
2789 *nested_list
= sa1
->prev
;
2797 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2798 return the resulting string (which must be freed). */
2799 static inline int *macro_twosharps(const int *macro_str
)
2803 TokenString macro_str1
;
2805 int n
, start_of_nosubsts
;
2807 /* we search the first '##' */
2808 for(ptr
= macro_str
;;) {
2810 TOK_GET(&t
, &ptr
, &cval
);
2811 if (t
== TOK_TWOSHARPS
)
2813 /* nothing more to do if end of string */
2818 /* we saw '##', so we need more processing to handle it */
2819 start_of_nosubsts
= -1;
2820 tok_str_new(¯o_str1
);
2821 for(ptr
= macro_str
;;) {
2822 TOK_GET(&tok
, &ptr
, &tokc
);
2825 if (tok
== TOK_TWOSHARPS
)
2827 if (tok
== TOK_NOSUBST
&& start_of_nosubsts
< 0)
2828 start_of_nosubsts
= macro_str1
.len
;
2829 while (*ptr
== TOK_TWOSHARPS
) {
2830 /* given 'a##b', remove nosubsts preceding 'a' */
2831 if (start_of_nosubsts
>= 0)
2832 macro_str1
.len
= start_of_nosubsts
;
2833 /* given 'a##b', skip '##' */
2835 /* given 'a##b', remove nosubsts preceding 'b' */
2836 while (t
== TOK_NOSUBST
)
2838 if (t
&& t
!= TOK_TWOSHARPS
) {
2840 TOK_GET(&t
, &ptr
, &cval
);
2841 /* We concatenate the two tokens */
2843 cstr_cat(&cstr
, get_tok_str(tok
, &tokc
));
2845 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2846 cstr_ccat(&cstr
, '\0');
2848 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
2849 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
2852 if (0 == *file
->buf_ptr
)
2854 tok_str_add2(¯o_str1
, tok
, &tokc
);
2855 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2856 n
, cstr
.data
, (char*)cstr
.data
+ n
);
2862 if (tok
!= TOK_NOSUBST
)
2863 start_of_nosubsts
= -1;
2864 tok_str_add2(¯o_str1
, tok
, &tokc
);
2866 tok_str_add(¯o_str1
, 0);
2867 return macro_str1
.str
;
2871 /* do macro substitution of macro_str and add result to
2872 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2873 inside to avoid recursing. */
2874 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
2875 const int *macro_str
, struct macro_level
** can_read_stream
)
2882 struct macro_level ml
;
2885 /* first scan for '##' operator handling */
2887 macro_str1
= macro_twosharps(ptr
);
2895 /* NOTE: ptr == NULL can only happen if tokens are read from
2896 file stream due to a macro function call */
2899 TOK_GET(&t
, &ptr
, &cval
);
2902 if (t
== TOK_NOSUBST
) {
2903 /* following token has already been subst'd. just copy it on */
2904 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
2905 TOK_GET(&t
, &ptr
, &cval
);
2910 /* if nested substitution, do nothing */
2911 if (sym_find2(*nested_list
, t
)) {
2912 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
2913 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
2917 if (can_read_stream
)
2918 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
2919 macro_ptr
= (int *)ptr
;
2921 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
2922 ptr
= (int *)macro_ptr
;
2924 if (can_read_stream
&& *can_read_stream
== &ml
)
2925 *can_read_stream
= ml
.prev
;
2928 if (parse_flags
& PARSE_FLAG_SPACES
)
2933 tok_str_add(tok_str
, ' ');
2937 if (!check_space(t
, &spc
))
2938 tok_str_add2(tok_str
, t
, &cval
);
2942 tok_str_free(macro_str1
);
2945 /* return next token with macro substitution */
2946 ST_FUNC
void next(void)
2948 Sym
*nested_list
, *s
;
2950 struct macro_level
*ml
;
2953 if (parse_flags
& PARSE_FLAG_SPACES
)
2958 /* if not reading from macro substituted string, then try
2959 to substitute macros */
2960 if (tok
>= TOK_IDENT
&&
2961 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2962 s
= define_find(tok
);
2964 /* we have a macro: we try to substitute */
2968 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
2969 /* substitution done, NOTE: maybe empty */
2970 tok_str_add(&str
, 0);
2971 macro_ptr
= str
.str
;
2972 macro_ptr_allocated
= str
.str
;
2979 /* end of macro or end of unget buffer */
2980 if (unget_buffer_enabled
) {
2981 macro_ptr
= unget_saved_macro_ptr
;
2982 unget_buffer_enabled
= 0;
2984 /* end of macro string: free it */
2985 tok_str_free(macro_ptr_allocated
);
2986 macro_ptr_allocated
= NULL
;
2990 } else if (tok
== TOK_NOSUBST
) {
2991 /* discard preprocessor's nosubst markers */
2996 /* convert preprocessor tokens into C tokens */
2997 if (tok
== TOK_PPNUM
&&
2998 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
2999 parse_number((char *)tokc
.cstr
->data
);
3003 /* push back current token and set current token to 'last_tok'. Only
3004 identifier case handled for labels. */
3005 ST_INLN
void unget_tok(int last_tok
)
3009 if (unget_buffer_enabled
)
3011 /* assert(macro_ptr == unget_saved_buffer + 1);
3012 assert(*macro_ptr == 0); */
3016 unget_saved_macro_ptr
= macro_ptr
;
3017 unget_buffer_enabled
= 1;
3019 q
= unget_saved_buffer
;
3022 n
= tok_ext_size(tok
) - 1;
3025 *q
= 0; /* end of token string */
3030 /* better than nothing, but needs extension to handle '-E' option
3032 ST_FUNC
void preprocess_init(TCCState
*s1
)
3034 s1
->include_stack_ptr
= s1
->include_stack
;
3035 /* XXX: move that before to avoid having to initialize
3036 file->ifdef_stack_ptr ? */
3037 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3038 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3041 s1
->pack_stack
[0] = 0;
3042 s1
->pack_stack_ptr
= s1
->pack_stack
;
3045 ST_FUNC
void preprocess_new()
3050 /* init isid table */
3051 for(i
=CH_EOF
;i
<256;i
++)
3052 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
3054 /* add all tokens */
3056 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3058 tok_ident
= TOK_IDENT
;
3067 tok_alloc(p
, r
- p
- 1);
3072 /* Preprocess the current file */
3073 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3077 BufferedFile
*file_ref
, **iptr
, **iptr_new
;
3078 int token_seen
, line_ref
, d
;
3081 preprocess_init(s1
);
3082 define_start
= define_stack
;
3083 ch
= file
->buf_ptr
[0];
3084 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3085 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
3086 PARSE_FLAG_LINEFEED
| PARSE_FLAG_SPACES
;
3090 iptr
= s1
->include_stack_ptr
;
3094 if (tok
== TOK_EOF
) {
3096 } else if (file
!= file_ref
) {
3098 } else if (tok
== TOK_LINEFEED
) {
3103 } else if (!token_seen
) {
3104 d
= file
->line_num
- line_ref
;
3105 if (file
!= file_ref
|| d
< 0 || d
>= 8) {
3107 iptr_new
= s1
->include_stack_ptr
;
3108 s
= iptr_new
> iptr
? " 1"
3109 : iptr_new
< iptr
? " 2"
3110 : iptr_new
> s1
->include_stack
? " 3"
3114 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", file
->line_num
, file
->filename
, s
);
3117 fputs("\n", s1
->ppfp
), --d
;
3119 line_ref
= (file_ref
= file
)->line_num
;
3120 token_seen
= tok
!= TOK_LINEFEED
;
3124 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);
3126 free_defines(define_start
);