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
;
267 /* NOTE: to go faster, we give a fixed buffer for small strings */
268 cstr_reset(&cstr_buf
);
270 cstr_buf
.size_allocated
= sizeof(buf
);
276 /* XXX: not quite exact, but only useful for testing */
277 sprintf(p
, "%u", cv
->ui
);
281 /* XXX: not quite exact, but only useful for testing */
283 sprintf(p
, "%u", (unsigned)cv
->ull
);
285 sprintf(p
, "%llu", cv
->ull
);
289 cstr_ccat(&cstr_buf
, 'L');
291 cstr_ccat(&cstr_buf
, '\'');
292 add_char(&cstr_buf
, cv
->i
);
293 cstr_ccat(&cstr_buf
, '\'');
294 cstr_ccat(&cstr_buf
, '\0');
298 len
= cstr
->size
- 1;
300 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
301 cstr_ccat(&cstr_buf
, '\0');
304 cstr_ccat(&cstr_buf
, 'L');
307 cstr_ccat(&cstr_buf
, '\"');
309 len
= cstr
->size
- 1;
311 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
313 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
315 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
317 cstr_ccat(&cstr_buf
, '\"');
318 cstr_ccat(&cstr_buf
, '\0');
327 return strcpy(p
, "...");
329 return strcpy(p
, "<<=");
331 return strcpy(p
, ">>=");
334 /* search in two bytes table */
335 const unsigned char *q
= tok_two_chars
;
348 } else if (v
< tok_ident
) {
349 return table_ident
[v
- TOK_IDENT
]->str
;
350 } else if (v
>= SYM_FIRST_ANOM
) {
351 /* special name for anonymous symbol */
352 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
354 /* should never happen */
359 return cstr_buf
.data
;
362 /* fill input buffer and peek next char */
363 static int tcc_peekc_slow(BufferedFile
*bf
)
366 /* only tries to read if really end of buffer */
367 if (bf
->buf_ptr
>= bf
->buf_end
) {
369 #if defined(PARSE_DEBUG)
374 len
= read(bf
->fd
, bf
->buffer
, len
);
381 bf
->buf_ptr
= bf
->buffer
;
382 bf
->buf_end
= bf
->buffer
+ len
;
383 *bf
->buf_end
= CH_EOB
;
385 if (bf
->buf_ptr
< bf
->buf_end
) {
386 return bf
->buf_ptr
[0];
388 bf
->buf_ptr
= bf
->buf_end
;
393 /* return the current character, handling end of block if necessary
395 ST_FUNC
int handle_eob(void)
397 return tcc_peekc_slow(file
);
400 /* read next char from current input file and handle end of input buffer */
401 ST_INLN
void inp(void)
403 ch
= *(++(file
->buf_ptr
));
404 /* end of buffer/file handling */
409 /* handle '\[\r]\n' */
410 static int handle_stray_noerror(void)
417 } else if (ch
== '\r') {
431 static void handle_stray(void)
433 if (handle_stray_noerror())
434 tcc_error("stray '\\' in program");
437 /* skip the stray and handle the \\n case. Output an error if
438 incorrect char after the stray */
439 static int handle_stray1(uint8_t *p
)
443 if (p
>= file
->buf_end
) {
460 /* handle just the EOB case, but not stray */
461 #define PEEKC_EOB(c, p)\
472 /* handle the complicated stray case */
478 c = handle_stray1(p);\
483 /* input with '\[\r]\n' handling. Note that this function cannot
484 handle other characters after '\', so you cannot call it inside
485 strings or comments */
486 ST_FUNC
void minp(void)
494 /* single line C++ comments */
495 static uint8_t *parse_line_comment(uint8_t *p
)
503 if (c
== '\n' || c
== CH_EOF
) {
505 } else if (c
== '\\') {
514 } else if (c
== '\r') {
532 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
541 if (c
== '\n' || c
== '*' || c
== '\\')
545 if (c
== '\n' || c
== '*' || c
== '\\')
549 /* now we can handle all the cases */
553 } else if (c
== '*') {
559 } else if (c
== '/') {
561 } else if (c
== '\\') {
566 /* skip '\[\r]\n', otherwise just skip the stray */
572 } else if (c
== '\r') {
589 /* stray, eob or eof */
594 tcc_error("unexpected end of file in comment");
595 } else if (c
== '\\') {
607 static inline void skip_spaces(void)
613 static inline int check_space(int t
, int *spc
)
624 /* parse a string without interpreting escapes */
625 static uint8_t *parse_pp_string(uint8_t *p
,
626 int sep
, CString
*str
)
634 } else if (c
== '\\') {
640 /* XXX: indicate line number of start of string */
641 tcc_error("missing terminating %c character", sep
);
642 } else if (c
== '\\') {
643 /* escape : just skip \[\r]\n */
648 } else if (c
== '\r') {
651 expect("'\n' after '\r'");
654 } else if (c
== CH_EOF
) {
655 goto unterminated_string
;
658 cstr_ccat(str
, '\\');
664 } else if (c
== '\n') {
667 } else if (c
== '\r') {
671 cstr_ccat(str
, '\r');
687 /* skip block of text until #else, #elif or #endif. skip also pairs of
689 static void preprocess_skip(void)
691 int a
, start_of_line
, c
, in_warn_or_error
;
698 in_warn_or_error
= 0;
719 } else if (c
== '\\') {
720 ch
= file
->buf_ptr
[0];
721 handle_stray_noerror();
728 if (in_warn_or_error
)
730 p
= parse_pp_string(p
, c
, NULL
);
734 if (in_warn_or_error
)
741 p
= parse_comment(p
);
742 } else if (ch
== '/') {
743 p
= parse_line_comment(p
);
753 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
755 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
757 else if (tok
== TOK_ENDIF
)
759 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
760 in_warn_or_error
= 1;
761 else if (tok
== TOK_LINEFEED
)
776 /* ParseState handling */
778 /* XXX: currently, no include file info is stored. Thus, we cannot display
779 accurate messages if the function or data definition spans multiple
782 /* save current parse state in 's' */
783 ST_FUNC
void save_parse_state(ParseState
*s
)
785 s
->line_num
= file
->line_num
;
786 s
->macro_ptr
= macro_ptr
;
791 /* restore parse state from 's' */
792 ST_FUNC
void restore_parse_state(ParseState
*s
)
794 file
->line_num
= s
->line_num
;
795 macro_ptr
= s
->macro_ptr
;
800 /* return the number of additional 'ints' necessary to store the
802 static inline int tok_ext_size(int t
)
816 tcc_error("unsupported token");
823 return LDOUBLE_SIZE
/ 4;
829 /* token string handling */
831 ST_INLN
void tok_str_new(TokenString
*s
)
835 s
->allocated_len
= 0;
836 s
->last_line_num
= -1;
839 ST_FUNC
void tok_str_free(int *str
)
844 static int *tok_str_realloc(TokenString
*s
)
848 if (s
->allocated_len
== 0) {
851 len
= s
->allocated_len
* 2;
853 str
= tcc_realloc(s
->str
, len
* sizeof(int));
854 s
->allocated_len
= len
;
859 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
865 if (len
>= s
->allocated_len
)
866 str
= tok_str_realloc(s
);
871 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
878 /* allocate space for worst case */
879 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
880 str
= tok_str_realloc(s
);
889 str
[len
++] = cv
->tab
[0];
898 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
899 while ((len
+ nb_words
) > s
->allocated_len
)
900 str
= tok_str_realloc(s
);
901 cstr
= (CString
*)(str
+ len
);
903 cstr
->size
= cv
->cstr
->size
;
904 cstr
->data_allocated
= NULL
;
905 cstr
->size_allocated
= cstr
->size
;
906 memcpy((char *)cstr
+ sizeof(CString
),
907 cv
->cstr
->data
, cstr
->size
);
914 #if LDOUBLE_SIZE == 8
917 str
[len
++] = cv
->tab
[0];
918 str
[len
++] = cv
->tab
[1];
920 #if LDOUBLE_SIZE == 12
922 str
[len
++] = cv
->tab
[0];
923 str
[len
++] = cv
->tab
[1];
924 str
[len
++] = cv
->tab
[2];
925 #elif LDOUBLE_SIZE == 16
927 str
[len
++] = cv
->tab
[0];
928 str
[len
++] = cv
->tab
[1];
929 str
[len
++] = cv
->tab
[2];
930 str
[len
++] = cv
->tab
[3];
931 #elif LDOUBLE_SIZE != 8
932 #error add long double size support
941 /* add the current parse token in token string 's' */
942 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
945 memset(&cval
, 0, sizeof(CValue
));
947 /* save line number info */
948 if (file
->line_num
!= s
->last_line_num
) {
949 s
->last_line_num
= file
->line_num
;
950 cval
.i
= s
->last_line_num
;
951 tok_str_add2(s
, TOK_LINENUM
, &cval
);
953 tok_str_add2(s
, tok
, &tokc
);
956 /* get a token from an integer array and increment pointer
957 accordingly. we code it as a macro to avoid pointer aliasing. */
958 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
976 cv
->cstr
= (CString
*)p
;
977 cv
->cstr
->data
= (char *)p
+ sizeof(CString
);
978 p
+= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
986 #if LDOUBLE_SIZE == 16
988 #elif LDOUBLE_SIZE == 12
990 #elif LDOUBLE_SIZE == 8
993 # error add long double size support
1006 static int macro_is_equal(const int *a
, const int *b
)
1008 char buf
[STRING_MAX_SIZE
+ 1];
1011 memset(&cv
, 0, sizeof(CValue
));
1013 TOK_GET(&t
, &a
, &cv
);
1014 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1015 TOK_GET(&t
, &b
, &cv
);
1016 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1022 /* defines handling */
1023 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1028 if (s
&& !macro_is_equal(s
->d
, str
))
1029 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1031 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1033 s
->next
= first_arg
;
1034 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1037 /* undefined a define symbol. Its name is just set to zero */
1038 ST_FUNC
void define_undef(Sym
*s
)
1042 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1043 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1047 ST_INLN Sym
*define_find(int v
)
1050 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1052 return table_ident
[v
]->sym_define
;
1055 /* free define stack until top reaches 'b' */
1056 ST_FUNC
void free_defines(Sym
*b
)
1064 /* do not free args or predefined defines */
1066 tok_str_free(top
->d
);
1068 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1069 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1077 ST_FUNC Sym
*label_find(int v
)
1080 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1082 return table_ident
[v
]->sym_label
;
1085 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1088 s
= sym_push2(ptop
, v
, 0, 0);
1090 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1091 if (ptop
== &global_label_stack
) {
1092 /* modify the top most local identifier, so that
1093 sym_identifier will point to 's' when popped */
1095 ps
= &(*ps
)->prev_tok
;
1102 /* pop labels until element last is reached. Look if any labels are
1103 undefined. Define symbols if '&&label' was used. */
1104 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1107 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1109 if (s
->r
== LABEL_DECLARED
) {
1110 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1111 } else if (s
->r
== LABEL_FORWARD
) {
1112 tcc_error("label '%s' used but not defined",
1113 get_tok_str(s
->v
, NULL
));
1116 /* define corresponding symbol. A size of
1118 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1122 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1128 /* eval an expression for #if/#elif */
1129 static int expr_preprocess(void)
1135 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1136 next(); /* do macro subst */
1137 if (tok
== TOK_DEFINED
) {
1142 c
= define_find(tok
) != 0;
1147 } else if (tok
>= TOK_IDENT
) {
1148 /* if undefined macro */
1152 tok_str_add_tok(&str
);
1154 tok_str_add(&str
, -1); /* simulate end of file */
1155 tok_str_add(&str
, 0);
1156 /* now evaluate C constant expression */
1157 macro_ptr
= str
.str
;
1161 tok_str_free(str
.str
);
1165 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
1166 static void tok_print(int *str
)
1170 memset(&cval
, 0, sizeof(CValue
));
1174 TOK_GET(&t
, &str
, &cval
);
1177 printf("%s", get_tok_str(t
, &cval
));
1183 /* parse after #define */
1184 ST_FUNC
void parse_define(void)
1186 Sym
*s
, *first
, **ps
;
1187 int v
, t
, varg
, is_vaargs
, spc
;
1192 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1193 /* XXX: should check if same macro (ANSI) */
1196 /* '(' must be just after macro definition for MACRO_FUNC */
1201 while (tok
!= ')') {
1205 if (varg
== TOK_DOTS
) {
1206 varg
= TOK___VA_ARGS__
;
1208 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1212 if (varg
< TOK_IDENT
)
1213 tcc_error("badly punctuated parameter list");
1214 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1227 /* EOF testing necessary for '-D' handling */
1228 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1229 /* remove spaces around ## and after '#' */
1230 if (TOK_TWOSHARPS
== tok
) {
1234 } else if ('#' == tok
) {
1236 } else if (check_space(tok
, &spc
)) {
1239 tok_str_add2(&str
, tok
, &tokc
);
1244 --str
.len
; /* remove trailing space */
1245 tok_str_add(&str
, 0);
1247 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
1250 define_push(v
, t
, str
.str
, first
);
1253 static inline int hash_cached_include(const char *filename
)
1255 const unsigned char *s
;
1259 s
= (unsigned char *) filename
;
1261 h
= TOK_HASH_FUNC(h
, *s
);
1264 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1268 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1272 h
= hash_cached_include(filename
);
1273 i
= s1
->cached_includes_hash
[h
];
1277 e
= s1
->cached_includes
[i
- 1];
1278 if (0 == PATHCMP(e
->filename
, filename
))
1285 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1290 if (search_cached_include(s1
, filename
))
1293 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1295 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1296 strcpy(e
->filename
, filename
);
1297 e
->ifndef_macro
= ifndef_macro
;
1298 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1299 /* add in hash table */
1300 h
= hash_cached_include(filename
);
1301 e
->hash_next
= s1
->cached_includes_hash
[h
];
1302 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1305 static void pragma_parse(TCCState
*s1
)
1310 if (tok
== TOK_pack
) {
1313 #pragma pack(1) // set
1314 #pragma pack() // reset to default
1315 #pragma pack(push,1) // push & set
1316 #pragma pack(pop) // restore previous
1320 if (tok
== TOK_ASM_pop
) {
1322 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1324 tcc_error("out of pack stack");
1326 s1
->pack_stack_ptr
--;
1330 if (tok
== TOK_ASM_push
) {
1332 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1334 s1
->pack_stack_ptr
++;
1337 if (tok
!= TOK_CINT
) {
1339 tcc_error("invalid pack pragma");
1342 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1346 *s1
->pack_stack_ptr
= val
;
1352 /* is_bof is true if first non space token at beginning of file */
1353 ST_FUNC
void preprocess(int is_bof
)
1355 TCCState
*s1
= tcc_state
;
1356 int i
, c
, n
, saved_parse_flags
;
1360 saved_parse_flags
= parse_flags
;
1361 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
1362 PARSE_FLAG_LINEFEED
;
1372 s
= define_find(tok
);
1373 /* undefine symbol by putting an invalid name */
1378 case TOK_INCLUDE_NEXT
:
1379 ch
= file
->buf_ptr
[0];
1380 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1385 } else if (ch
== '\"') {
1390 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1391 if ((q
- buf
) < sizeof(buf
) - 1)
1394 if (handle_stray_noerror() == 0)
1402 /* eat all spaces and comments after include */
1403 /* XXX: slightly incorrect */
1404 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1408 /* computed #include : either we have only strings or
1409 we have anything enclosed in '<>' */
1412 if (tok
== TOK_STR
) {
1413 while (tok
!= TOK_LINEFEED
) {
1414 if (tok
!= TOK_STR
) {
1416 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1418 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1424 while (tok
!= TOK_LINEFEED
) {
1425 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1429 /* check syntax and remove '<>' */
1430 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1431 goto include_syntax
;
1432 memmove(buf
, buf
+ 1, len
- 2);
1433 buf
[len
- 2] = '\0';
1438 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1439 tcc_error("#include recursion too deep");
1440 /* store current file in stack, but increment stack later below */
1441 *s1
->include_stack_ptr
= file
;
1443 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1444 for (i
= -2; i
< n
; ++i
) {
1445 char buf1
[sizeof file
->filename
];
1451 /* check absolute include path */
1452 if (!IS_ABSPATH(buf
))
1455 i
= n
; /* force end loop */
1457 } else if (i
== -1) {
1458 /* search in current dir if "header.h" */
1461 path
= file
->filename
;
1462 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1465 /* search in all the include paths */
1466 if (i
< s1
->nb_include_paths
)
1467 path
= s1
->include_paths
[i
];
1469 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1470 pstrcpy(buf1
, sizeof(buf1
), path
);
1471 pstrcat(buf1
, sizeof(buf1
), "/");
1474 pstrcat(buf1
, sizeof(buf1
), buf
);
1476 if (tok
== TOK_INCLUDE_NEXT
)
1477 for (f
= s1
->include_stack_ptr
; f
>= s1
->include_stack
; --f
)
1478 if (0 == PATHCMP((*f
)->filename
, buf1
)) {
1480 printf("%s: #include_next skipping %s\n", file
->filename
, buf1
);
1482 goto include_trynext
;
1485 e
= search_cached_include(s1
, buf1
);
1486 if (e
&& define_find(e
->ifndef_macro
)) {
1487 /* no need to parse the include because the 'ifndef macro'
1490 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1495 if (tcc_open(s1
, buf1
) < 0)
1500 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1502 /* update target deps */
1503 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1505 /* push current file in stack */
1506 ++s1
->include_stack_ptr
;
1507 /* add include file debug info */
1509 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1510 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1511 ch
= file
->buf_ptr
[0];
1514 tcc_error("include file '%s' not found", buf
);
1521 c
= expr_preprocess();
1527 if (tok
< TOK_IDENT
)
1528 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1532 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1534 file
->ifndef_macro
= tok
;
1537 c
= (define_find(tok
) != 0) ^ c
;
1539 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1540 tcc_error("memory full (ifdef)");
1541 *s1
->ifdef_stack_ptr
++ = c
;
1544 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1545 tcc_error("#else without matching #if");
1546 if (s1
->ifdef_stack_ptr
[-1] & 2)
1547 tcc_error("#else after #else");
1548 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1551 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1552 tcc_error("#elif without matching #if");
1553 c
= s1
->ifdef_stack_ptr
[-1];
1555 tcc_error("#elif after #else");
1556 /* last #if/#elif expression was true: we skip */
1559 c
= expr_preprocess();
1560 s1
->ifdef_stack_ptr
[-1] = c
;
1562 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1563 file
->ifndef_macro
= 0;
1573 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1574 tcc_error("#endif without matching #if");
1575 s1
->ifdef_stack_ptr
--;
1576 /* '#ifndef macro' was at the start of file. Now we check if
1577 an '#endif' is exactly at the end of file */
1578 if (file
->ifndef_macro
&&
1579 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1580 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1581 /* need to set to zero to avoid false matches if another
1582 #ifndef at middle of file */
1583 file
->ifndef_macro
= 0;
1584 while (tok
!= TOK_LINEFEED
)
1586 tok_flags
|= TOK_FLAG_ENDIF
;
1592 if (tok
!= TOK_CINT
)
1594 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
1596 if (tok
!= TOK_LINEFEED
) {
1599 pstrcpy(file
->filename
, sizeof(file
->filename
),
1600 (char *)tokc
.cstr
->data
);
1606 ch
= file
->buf_ptr
[0];
1609 while (ch
!= '\n' && ch
!= CH_EOF
) {
1610 if ((q
- buf
) < sizeof(buf
) - 1)
1613 if (handle_stray_noerror() == 0)
1620 tcc_error("#error %s", buf
);
1622 tcc_warning("#warning %s", buf
);
1628 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_PPNUM
) {
1629 /* '!' is ignored to allow C scripts. numbers are ignored
1630 to emulate cpp behaviour */
1632 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
1633 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1635 /* this is a gas line comment in an 'S' file. */
1636 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1642 /* ignore other preprocess commands or #! for C scripts */
1643 while (tok
!= TOK_LINEFEED
)
1646 parse_flags
= saved_parse_flags
;
1649 /* evaluate escape codes in a string. */
1650 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1665 case '0': case '1': case '2': case '3':
1666 case '4': case '5': case '6': case '7':
1667 /* at most three octal digits */
1672 n
= n
* 8 + c
- '0';
1676 n
= n
* 8 + c
- '0';
1681 goto add_char_nonext
;
1689 if (c
>= 'a' && c
<= 'f')
1691 else if (c
>= 'A' && c
<= 'F')
1701 goto add_char_nonext
;
1725 goto invalid_escape
;
1735 if (c
>= '!' && c
<= '~')
1736 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1738 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1745 cstr_ccat(outstr
, c
);
1747 cstr_wccat(outstr
, c
);
1749 /* add a trailing '\0' */
1751 cstr_ccat(outstr
, '\0');
1753 cstr_wccat(outstr
, '\0');
1756 /* we use 64 bit numbers */
1759 /* bn = (bn << shift) | or_val */
1760 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
1764 for(i
=0;i
<BN_SIZE
;i
++) {
1766 bn
[i
] = (v
<< shift
) | or_val
;
1767 or_val
= v
>> (32 - shift
);
1771 static void bn_zero(unsigned int *bn
)
1774 for(i
=0;i
<BN_SIZE
;i
++) {
1779 /* parse number in null terminated string 'p' and return it in the
1781 static void parse_number(const char *p
)
1783 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
1785 unsigned int bn
[BN_SIZE
];
1796 goto float_frac_parse
;
1797 } else if (t
== '0') {
1798 if (ch
== 'x' || ch
== 'X') {
1802 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
1808 /* parse all digits. cannot check octal numbers at this stage
1809 because of floating point constants */
1811 if (ch
>= 'a' && ch
<= 'f')
1813 else if (ch
>= 'A' && ch
<= 'F')
1821 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
1823 tcc_error("number too long");
1829 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
1830 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
1832 /* NOTE: strtox should support that for hexa numbers, but
1833 non ISOC99 libcs do not support it, so we prefer to do
1835 /* hexadecimal or binary floats */
1836 /* XXX: handle overflows */
1848 } else if (t
>= 'a') {
1850 } else if (t
>= 'A') {
1855 bn_lshift(bn
, shift
, t
);
1862 if (t
>= 'a' && t
<= 'f') {
1864 } else if (t
>= 'A' && t
<= 'F') {
1866 } else if (t
>= '0' && t
<= '9') {
1872 tcc_error("invalid digit");
1873 bn_lshift(bn
, shift
, t
);
1878 if (ch
!= 'p' && ch
!= 'P')
1885 } else if (ch
== '-') {
1889 if (ch
< '0' || ch
> '9')
1890 expect("exponent digits");
1891 while (ch
>= '0' && ch
<= '9') {
1892 exp_val
= exp_val
* 10 + ch
- '0';
1895 exp_val
= exp_val
* s
;
1897 /* now we can generate the number */
1898 /* XXX: should patch directly float number */
1899 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
1900 d
= ldexp(d
, exp_val
- frac_bits
);
1905 /* float : should handle overflow */
1907 } else if (t
== 'L') {
1909 #ifdef TCC_TARGET_PE
1914 /* XXX: not large enough */
1915 tokc
.ld
= (long double)d
;
1922 /* decimal floats */
1924 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1929 while (ch
>= '0' && ch
<= '9') {
1930 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1936 if (ch
== 'e' || ch
== 'E') {
1937 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1941 if (ch
== '-' || ch
== '+') {
1942 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1947 if (ch
< '0' || ch
> '9')
1948 expect("exponent digits");
1949 while (ch
>= '0' && ch
<= '9') {
1950 if (q
>= token_buf
+ STRING_MAX_SIZE
)
1962 tokc
.f
= strtof(token_buf
, NULL
);
1963 } else if (t
== 'L') {
1965 #ifdef TCC_TARGET_PE
1967 tokc
.d
= strtod(token_buf
, NULL
);
1970 tokc
.ld
= strtold(token_buf
, NULL
);
1974 tokc
.d
= strtod(token_buf
, NULL
);
1978 unsigned long long n
, n1
;
1981 /* integer number */
1984 if (b
== 10 && *q
== '0') {
1991 /* no need for checks except for base 10 / 8 errors */
1994 } else if (t
>= 'a') {
1996 } else if (t
>= 'A') {
2001 tcc_error("invalid digit");
2005 /* detect overflow */
2006 /* XXX: this test is not reliable */
2008 tcc_error("integer constant overflow");
2011 /* XXX: not exactly ANSI compliant */
2012 if ((n
& 0xffffffff00000000LL
) != 0) {
2017 } else if (n
> 0x7fffffff) {
2028 tcc_error("three 'l's in integer constant");
2030 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2033 if (tok
== TOK_CINT
)
2035 else if (tok
== TOK_CUINT
)
2037 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2041 } else if (t
== 'U') {
2043 tcc_error("two 'u's in integer constant");
2045 if (tok
== TOK_CINT
)
2047 else if (tok
== TOK_CLLONG
)
2054 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2060 tcc_error("invalid number\n");
2064 #define PARSE2(c1, tok1, c2, tok2) \
2075 /* return next token without macro substitution */
2076 static inline void next_nomacro1(void)
2091 goto keep_tok_flags
;
2098 /* first look if it is in fact an end of buffer */
2099 if (p
>= file
->buf_end
) {
2103 if (p
>= file
->buf_end
)
2116 TCCState
*s1
= tcc_state
;
2117 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2118 && !(tok_flags
& TOK_FLAG_EOF
)) {
2119 tok_flags
|= TOK_FLAG_EOF
;
2121 goto keep_tok_flags
;
2122 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2124 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2125 tcc_error("missing #endif");
2126 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2127 /* no include left : end of file. */
2130 tok_flags
&= ~TOK_FLAG_EOF
;
2131 /* pop include file */
2133 /* test if previous '#endif' was after a #ifdef at
2135 if (tok_flags
& TOK_FLAG_ENDIF
) {
2137 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2139 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2140 tok_flags
&= ~TOK_FLAG_ENDIF
;
2143 /* add end of include file debug info */
2144 if (tcc_state
->do_debug
) {
2145 put_stabd(N_EINCL
, 0, 0);
2147 /* pop include stack */
2149 s1
->include_stack_ptr
--;
2158 tok_flags
|= TOK_FLAG_BOL
;
2161 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2164 goto keep_tok_flags
;
2169 if ((tok_flags
& TOK_FLAG_BOL
) &&
2170 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2172 preprocess(tok_flags
& TOK_FLAG_BOF
);
2178 tok
= TOK_TWOSHARPS
;
2180 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
2181 p
= parse_line_comment(p
- 1);
2190 case 'a': case 'b': case 'c': case 'd':
2191 case 'e': case 'f': case 'g': case 'h':
2192 case 'i': case 'j': case 'k': case 'l':
2193 case 'm': case 'n': case 'o': case 'p':
2194 case 'q': case 'r': case 's': case 't':
2195 case 'u': case 'v': case 'w': case 'x':
2197 case 'A': case 'B': case 'C': case 'D':
2198 case 'E': case 'F': case 'G': case 'H':
2199 case 'I': case 'J': case 'K':
2200 case 'M': case 'N': case 'O': case 'P':
2201 case 'Q': case 'R': case 'S': case 'T':
2202 case 'U': case 'V': case 'W': case 'X':
2208 h
= TOK_HASH_FUNC(h
, c
);
2212 if (!isidnum_table
[c
-CH_EOF
])
2214 h
= TOK_HASH_FUNC(h
, c
);
2221 /* fast case : no stray found, so we have the full token
2222 and we have already hashed it */
2224 h
&= (TOK_HASH_SIZE
- 1);
2225 pts
= &hash_ident
[h
];
2230 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2232 pts
= &(ts
->hash_next
);
2234 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2238 cstr_reset(&tokcstr
);
2241 cstr_ccat(&tokcstr
, *p1
);
2247 while (isidnum_table
[c
-CH_EOF
]) {
2248 cstr_ccat(&tokcstr
, c
);
2251 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2257 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2259 goto parse_ident_fast
;
2262 if (c
== '\'' || c
== '\"') {
2266 cstr_reset(&tokcstr
);
2267 cstr_ccat(&tokcstr
, 'L');
2268 goto parse_ident_slow
;
2272 case '0': case '1': case '2': case '3':
2273 case '4': case '5': case '6': case '7':
2276 cstr_reset(&tokcstr
);
2277 /* after the first digit, accept digits, alpha, '.' or sign if
2278 prefixed by 'eEpP' */
2282 cstr_ccat(&tokcstr
, c
);
2284 if (!(isnum(c
) || isid(c
) || c
== '.' ||
2285 ((c
== '+' || c
== '-') &&
2286 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
2289 /* We add a trailing '\0' to ease parsing */
2290 cstr_ccat(&tokcstr
, '\0');
2291 tokc
.cstr
= &tokcstr
;
2295 /* special dot handling because it can also start a number */
2298 cstr_reset(&tokcstr
);
2299 cstr_ccat(&tokcstr
, '.');
2301 } else if (c
== '.') {
2321 /* parse the string */
2323 p
= parse_pp_string(p
, sep
, &str
);
2324 cstr_ccat(&str
, '\0');
2326 /* eval the escape (should be done as TOK_PPNUM) */
2327 cstr_reset(&tokcstr
);
2328 parse_escape_string(&tokcstr
, str
.data
, is_long
);
2333 /* XXX: make it portable */
2337 char_size
= sizeof(nwchar_t
);
2338 if (tokcstr
.size
<= char_size
)
2339 tcc_error("empty character constant");
2340 if (tokcstr
.size
> 2 * char_size
)
2341 tcc_warning("multi-character character constant");
2343 tokc
.i
= *(int8_t *)tokcstr
.data
;
2346 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2350 tokc
.cstr
= &tokcstr
;
2364 } else if (c
== '<') {
2382 } else if (c
== '>') {
2400 } else if (c
== '=') {
2413 } else if (c
== '=') {
2426 } else if (c
== '=') {
2439 } else if (c
== '=') {
2442 } else if (c
== '>') {
2450 PARSE2('!', '!', '=', TOK_NE
)
2451 PARSE2('=', '=', '=', TOK_EQ
)
2452 PARSE2('*', '*', '=', TOK_A_MUL
)
2453 PARSE2('%', '%', '=', TOK_A_MOD
)
2454 PARSE2('^', '^', '=', TOK_A_XOR
)
2456 /* comments or operator */
2460 p
= parse_comment(p
);
2461 /* comments replaced by a blank */
2463 goto keep_tok_flags
;
2464 } else if (c
== '/') {
2465 p
= parse_line_comment(p
);
2467 goto keep_tok_flags
;
2468 } else if (c
== '=') {
2488 case '$': /* only used in assembler */
2489 case '@': /* dito */
2494 tcc_error("unrecognized character \\x%02x", c
);
2500 #if defined(PARSE_DEBUG)
2501 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2505 /* return next token without macro substitution. Can read input from
2507 static void next_nomacro_spc(void)
2513 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2514 if (tok
== TOK_LINENUM
) {
2515 file
->line_num
= tokc
.i
;
2524 ST_FUNC
void next_nomacro(void)
2528 } while (is_space(tok
));
2531 /* substitute args in macro_str and return allocated string */
2532 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2534 int last_tok
, t
, spc
;
2540 memset(&cval
, 0, sizeof(CValue
));
2545 TOK_GET(&t
, ¯o_str
, &cval
);
2550 TOK_GET(&t
, ¯o_str
, &cval
);
2553 s
= sym_find2(args
, t
);
2559 TOK_GET(&t
, &st
, &cval
);
2560 if (!check_space(t
, &spc
))
2561 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2564 cstr_ccat(&cstr
, '\0');
2566 printf("stringize: %s\n", (char *)cstr
.data
);
2570 tok_str_add2(&str
, TOK_STR
, &cval
);
2573 tok_str_add2(&str
, t
, &cval
);
2575 } else if (t
>= TOK_IDENT
) {
2576 s
= sym_find2(args
, t
);
2579 /* if '##' is present before or after, no arg substitution */
2580 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
2581 /* special case for var arg macros : ## eats the
2582 ',' if empty VA_ARGS variable. */
2583 /* XXX: test of the ',' is not 100%
2584 reliable. should fix it to avoid security
2586 if (gnu_ext
&& s
->type
.t
&&
2587 last_tok
== TOK_TWOSHARPS
&&
2588 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
2590 /* suppress ',' '##' */
2593 /* suppress '##' and add variable */
2601 TOK_GET(&t1
, &st
, &cval
);
2604 tok_str_add2(&str
, t1
, &cval
);
2608 /* NOTE: the stream cannot be read when macro
2609 substituing an argument */
2610 macro_subst(&str
, nested_list
, st
, NULL
);
2613 tok_str_add(&str
, t
);
2616 tok_str_add2(&str
, t
, &cval
);
2620 tok_str_add(&str
, 0);
2624 static char const ab_month_name
[12][4] =
2626 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2627 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2630 /* do macro substitution of current token with macro 's' and add
2631 result to (tok_str,tok_len). 'nested_list' is the list of all
2632 macros we got inside to avoid recursing. Return non zero if no
2633 substitution needs to be done */
2634 static int macro_subst_tok(TokenString
*tok_str
,
2635 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
2637 Sym
*args
, *sa
, *sa1
;
2638 int mstr_allocated
, parlevel
, *mstr
, t
, t1
, spc
;
2645 memset(&cval
, 0, sizeof(CValue
));
2647 /* if symbol is a macro, prepare substitution */
2648 /* special macros */
2649 if (tok
== TOK___LINE__
) {
2650 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2654 } else if (tok
== TOK___FILE__
) {
2655 cstrval
= file
->filename
;
2657 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2662 tm
= localtime(&ti
);
2663 if (tok
== TOK___DATE__
) {
2664 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2665 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2667 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2668 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2675 cstr_cat(&cstr
, cstrval
);
2676 cstr_ccat(&cstr
, '\0');
2678 tok_str_add2(tok_str
, t1
, &cval
);
2683 if (s
->type
.t
== MACRO_FUNC
) {
2684 /* NOTE: we do not use next_nomacro to avoid eating the
2685 next token. XXX: find better solution */
2689 while (is_space(t
= *p
) || TOK_LINEFEED
== t
)
2691 if (t
== 0 && can_read_stream
) {
2692 /* end of macro stream: we must look at the token
2693 after in the file */
2694 struct macro_level
*ml
= *can_read_stream
;
2700 *can_read_stream
= ml
-> prev
;
2702 /* also, end of scope for nested defined symbol */
2703 (*nested_list
)->v
= -1;
2707 ch
= file
->buf_ptr
[0];
2708 while (is_space(ch
) || ch
== '\n' || ch
== '/')
2713 uint8_t *p
= file
->buf_ptr
;
2716 p
= parse_comment(p
);
2717 file
->buf_ptr
= p
- 1;
2718 } else if (c
== '/') {
2719 p
= parse_line_comment(p
);
2720 file
->buf_ptr
= p
- 1;
2728 if (t
!= '(') /* no macro subst */
2731 /* argument macro */
2736 /* NOTE: empty args are allowed, except if no args */
2738 /* handle '()' case */
2739 if (!args
&& !sa
&& tok
== ')')
2742 tcc_error("macro '%s' used with too many args",
2743 get_tok_str(s
->v
, 0));
2746 /* NOTE: non zero sa->t indicates VA_ARGS */
2747 while ((parlevel
> 0 ||
2749 (tok
!= ',' || sa
->type
.t
))) &&
2753 else if (tok
== ')')
2755 if (tok
== TOK_LINEFEED
)
2757 if (!check_space(tok
, &spc
))
2758 tok_str_add2(&str
, tok
, &tokc
);
2762 tok_str_add(&str
, 0);
2763 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
2767 /* special case for gcc var args: add an empty
2768 var arg argument if it is omitted */
2769 if (sa
&& sa
->type
.t
&& gnu_ext
)
2779 tcc_error("macro '%s' used with too few args",
2780 get_tok_str(s
->v
, 0));
2783 /* now subst each arg */
2784 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
2789 tok_str_free(sa
->d
);
2795 sym_push2(nested_list
, s
->v
, 0, 0);
2796 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
2797 /* pop nested defined symbol */
2799 *nested_list
= sa1
->prev
;
2807 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
2808 return the resulting string (which must be freed). */
2809 static inline int *macro_twosharps(const int *macro_str
)
2813 TokenString macro_str1
;
2815 int n
, start_of_nosubsts
;
2817 /* we search the first '##' */
2818 for(ptr
= macro_str
;;) {
2820 memset(&cval
, 0, sizeof(CValue
));
2821 TOK_GET(&t
, &ptr
, &cval
);
2822 if (t
== TOK_TWOSHARPS
)
2824 /* nothing more to do if end of string */
2829 /* we saw '##', so we need more processing to handle it */
2830 start_of_nosubsts
= -1;
2831 tok_str_new(¯o_str1
);
2832 for(ptr
= macro_str
;;) {
2833 TOK_GET(&tok
, &ptr
, &tokc
);
2836 if (tok
== TOK_TWOSHARPS
)
2838 if (tok
== TOK_NOSUBST
&& start_of_nosubsts
< 0)
2839 start_of_nosubsts
= macro_str1
.len
;
2840 while (*ptr
== TOK_TWOSHARPS
) {
2841 /* given 'a##b', remove nosubsts preceding 'a' */
2842 if (start_of_nosubsts
>= 0)
2843 macro_str1
.len
= start_of_nosubsts
;
2844 /* given 'a##b', skip '##' */
2846 /* given 'a##b', remove nosubsts preceding 'b' */
2847 while (t
== TOK_NOSUBST
)
2849 if (t
&& t
!= TOK_TWOSHARPS
) {
2851 memset(&cval
, 0, sizeof(CValue
));
2852 TOK_GET(&t
, &ptr
, &cval
);
2853 /* We concatenate the two tokens */
2855 cstr_cat(&cstr
, get_tok_str(tok
, &tokc
));
2857 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2858 cstr_ccat(&cstr
, '\0');
2860 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
2861 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
2864 if (0 == *file
->buf_ptr
)
2866 tok_str_add2(¯o_str1
, tok
, &tokc
);
2867 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
2868 n
, cstr
.data
, (char*)cstr
.data
+ n
);
2874 if (tok
!= TOK_NOSUBST
)
2875 start_of_nosubsts
= -1;
2876 tok_str_add2(¯o_str1
, tok
, &tokc
);
2878 tok_str_add(¯o_str1
, 0);
2879 return macro_str1
.str
;
2883 /* do macro substitution of macro_str and add result to
2884 (tok_str,tok_len). 'nested_list' is the list of all macros we got
2885 inside to avoid recursing. */
2886 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
2887 const int *macro_str
, struct macro_level
** can_read_stream
)
2893 struct macro_level ml
;
2896 memset(&cval
, 0, sizeof(CValue
));
2898 /* first scan for '##' operator handling */
2900 macro_str1
= macro_twosharps(ptr
);
2908 /* NOTE: ptr == NULL can only happen if tokens are read from
2909 file stream due to a macro function call */
2912 TOK_GET(&t
, &ptr
, &cval
);
2915 if (t
== TOK_NOSUBST
) {
2916 /* following token has already been subst'd. just copy it on */
2917 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
2918 TOK_GET(&t
, &ptr
, &cval
);
2923 /* if nested substitution, do nothing */
2924 if (sym_find2(*nested_list
, t
)) {
2925 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
2926 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
2930 if (can_read_stream
)
2931 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
2932 macro_ptr
= (int *)ptr
;
2934 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
2935 ptr
= (int *)macro_ptr
;
2937 if (can_read_stream
&& *can_read_stream
== &ml
)
2938 *can_read_stream
= ml
.prev
;
2941 if (parse_flags
& PARSE_FLAG_SPACES
)
2946 tok_str_add(tok_str
, ' ');
2950 if (!check_space(t
, &spc
))
2951 tok_str_add2(tok_str
, t
, &cval
);
2955 tok_str_free(macro_str1
);
2958 /* return next token with macro substitution */
2959 ST_FUNC
void next(void)
2961 Sym
*nested_list
, *s
;
2963 struct macro_level
*ml
;
2966 if (parse_flags
& PARSE_FLAG_SPACES
)
2971 /* if not reading from macro substituted string, then try
2972 to substitute macros */
2973 if (tok
>= TOK_IDENT
&&
2974 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2975 s
= define_find(tok
);
2977 /* we have a macro: we try to substitute */
2981 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
2982 /* substitution done, NOTE: maybe empty */
2983 tok_str_add(&str
, 0);
2984 macro_ptr
= str
.str
;
2985 macro_ptr_allocated
= str
.str
;
2992 /* end of macro or end of unget buffer */
2993 if (unget_buffer_enabled
) {
2994 macro_ptr
= unget_saved_macro_ptr
;
2995 unget_buffer_enabled
= 0;
2997 /* end of macro string: free it */
2998 tok_str_free(macro_ptr_allocated
);
2999 macro_ptr_allocated
= NULL
;
3003 } else if (tok
== TOK_NOSUBST
) {
3004 /* discard preprocessor's nosubst markers */
3009 /* convert preprocessor tokens into C tokens */
3010 if (tok
== TOK_PPNUM
&&
3011 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
3012 parse_number((char *)tokc
.cstr
->data
);
3016 /* push back current token and set current token to 'last_tok'. Only
3017 identifier case handled for labels. */
3018 ST_INLN
void unget_tok(int last_tok
)
3022 if (unget_buffer_enabled
)
3024 /* assert(macro_ptr == unget_saved_buffer + 1);
3025 assert(*macro_ptr == 0); */
3029 unget_saved_macro_ptr
= macro_ptr
;
3030 unget_buffer_enabled
= 1;
3032 q
= unget_saved_buffer
;
3035 n
= tok_ext_size(tok
) - 1;
3038 *q
= 0; /* end of token string */
3043 /* better than nothing, but needs extension to handle '-E' option
3045 ST_FUNC
void preprocess_init(TCCState
*s1
)
3047 s1
->include_stack_ptr
= s1
->include_stack
;
3048 /* XXX: move that before to avoid having to initialize
3049 file->ifdef_stack_ptr ? */
3050 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3051 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3054 s1
->pack_stack
[0] = 0;
3055 s1
->pack_stack_ptr
= s1
->pack_stack
;
3058 ST_FUNC
void preprocess_new(void)
3063 /* init isid table */
3064 for(i
=CH_EOF
;i
<256;i
++)
3065 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
3067 /* add all tokens */
3069 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3071 tok_ident
= TOK_IDENT
;
3080 tok_alloc(p
, r
- p
- 1);
3085 /* Preprocess the current file */
3086 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3090 BufferedFile
*file_ref
, **iptr
, **iptr_new
;
3091 int token_seen
, line_ref
, d
;
3094 preprocess_init(s1
);
3095 define_start
= define_stack
;
3096 ch
= file
->buf_ptr
[0];
3097 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3098 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
3099 PARSE_FLAG_LINEFEED
| PARSE_FLAG_SPACES
;
3103 iptr
= s1
->include_stack_ptr
;
3107 if (tok
== TOK_EOF
) {
3109 } else if (file
!= file_ref
) {
3111 } else if (tok
== TOK_LINEFEED
) {
3116 } else if (!token_seen
) {
3117 d
= file
->line_num
- line_ref
;
3118 if (file
!= file_ref
|| d
< 0 || d
>= 8) {
3120 iptr_new
= s1
->include_stack_ptr
;
3121 s
= iptr_new
> iptr
? " 1"
3122 : iptr_new
< iptr
? " 2"
3123 : iptr_new
> s1
->include_stack
? " 3"
3127 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", file
->line_num
, file
->filename
, s
);
3130 fputs("\n", s1
->ppfp
), --d
;
3132 line_ref
= (file_ref
= file
)->line_num
;
3133 token_seen
= tok
!= TOK_LINEFEED
;
3137 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);
3139 free_defines(define_start
);