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 ST_DATA
int parse_flags
;
29 ST_DATA
struct BufferedFile
*file
;
32 ST_DATA
const int *macro_ptr
;
33 ST_DATA CString tokcstr
; /* current parsed string, if any */
35 /* display benchmark infos */
36 ST_DATA
int total_lines
;
37 ST_DATA
int total_bytes
;
38 ST_DATA
int tok_ident
;
39 ST_DATA TokenSym
**table_ident
;
41 /* ------------------------------------------------------------------------- */
43 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
44 static char token_buf
[STRING_MAX_SIZE
+ 1];
45 static unsigned char isidnum_table
[256 - CH_EOF
];
46 /* isidnum_table flags: */
51 static TokenString
*macro_stack
;
53 static const char tcc_keywords
[] =
54 #define DEF(id, str) str "\0"
59 /* WARNING: the content of this string encodes token numbers */
60 static const unsigned char tok_two_chars
[] =
62 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
63 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
84 '.','.', 0xa8, // C++ token ?
85 '#','#', TOK_TWOSHARPS
,
89 static void next_nomacro_spc(void);
91 ST_FUNC
void skip(int c
)
94 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
98 ST_FUNC
void expect(const char *msg
)
100 tcc_error("%s expected", msg
);
103 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
106 str
->prev
= macro_stack
;
107 str
->prev_ptr
= macro_ptr
;
108 macro_ptr
= str
->str
;
112 ST_FUNC
void end_macro(void)
114 TokenString
*str
= macro_stack
;
115 macro_stack
= str
->prev
;
116 macro_ptr
= str
->prev_ptr
;
117 if (str
->alloc
== 2) {
118 str
->alloc
= 3; /* just mark as finished */
120 tok_str_free(str
->str
);
126 /* ------------------------------------------------------------------------- */
127 /* CString handling */
128 static void cstr_realloc(CString
*cstr
, int new_size
)
133 size
= cstr
->size_allocated
;
135 size
= 8; /* no need to allocate a too small first string */
136 while (size
< new_size
)
138 data
= tcc_realloc(cstr
->data_allocated
, size
);
139 cstr
->data_allocated
= data
;
140 cstr
->size_allocated
= size
;
145 ST_FUNC
void cstr_ccat(CString
*cstr
, int ch
)
148 size
= cstr
->size
+ 1;
149 if (size
> cstr
->size_allocated
)
150 cstr_realloc(cstr
, size
);
151 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
155 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
)
167 /* add a wide char */
168 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
171 size
= cstr
->size
+ sizeof(nwchar_t
);
172 if (size
> cstr
->size_allocated
)
173 cstr_realloc(cstr
, size
);
174 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
178 ST_FUNC
void cstr_new(CString
*cstr
)
180 memset(cstr
, 0, sizeof(CString
));
183 /* free string and reset it to NULL */
184 ST_FUNC
void cstr_free(CString
*cstr
)
186 tcc_free(cstr
->data_allocated
);
190 /* reset string to empty */
191 ST_FUNC
void cstr_reset(CString
*cstr
)
197 static void add_char(CString
*cstr
, int c
)
199 if (c
== '\'' || c
== '\"' || c
== '\\') {
200 /* XXX: could be more precise if char or string */
201 cstr_ccat(cstr
, '\\');
203 if (c
>= 32 && c
<= 126) {
206 cstr_ccat(cstr
, '\\');
208 cstr_ccat(cstr
, 'n');
210 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
211 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
212 cstr_ccat(cstr
, '0' + (c
& 7));
217 /* ------------------------------------------------------------------------- */
218 /* allocate a new token */
219 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
221 TokenSym
*ts
, **ptable
;
224 if (tok_ident
>= SYM_FIRST_ANOM
)
225 tcc_error("memory full (symbols)");
227 /* expand token table if needed */
228 i
= tok_ident
- TOK_IDENT
;
229 if ((i
% TOK_ALLOC_INCR
) == 0) {
230 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
231 table_ident
= ptable
;
234 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
236 ts
->tok
= tok_ident
++;
237 ts
->sym_define
= NULL
;
238 ts
->sym_label
= NULL
;
239 ts
->sym_struct
= NULL
;
240 ts
->sym_identifier
= NULL
;
242 ts
->hash_next
= NULL
;
243 memcpy(ts
->str
, str
, len
);
249 #define TOK_HASH_INIT 1
250 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
252 /* find a token and add it if not found */
253 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
261 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
262 h
&= (TOK_HASH_SIZE
- 1);
264 pts
= &hash_ident
[h
];
269 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
271 pts
= &(ts
->hash_next
);
273 return tok_alloc_new(pts
, str
, len
);
276 /* XXX: buffer overflow */
277 /* XXX: float tokens */
278 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
280 static char buf
[STRING_MAX_SIZE
+ 1];
281 static CString cstr_buf
;
286 /* NOTE: to go faster, we give a fixed buffer for small strings */
287 cstr_reset(&cstr_buf
);
289 cstr_buf
.size_allocated
= sizeof(buf
);
295 /* XXX: not quite exact, but only useful for testing */
296 sprintf(p
, "%u", cv
->ui
);
300 /* XXX: not quite exact, but only useful for testing */
302 sprintf(p
, "%u", (unsigned)cv
->ull
);
304 sprintf(p
, "%llu", cv
->ull
);
308 cstr_ccat(&cstr_buf
, 'L');
310 cstr_ccat(&cstr_buf
, '\'');
311 add_char(&cstr_buf
, cv
->i
);
312 cstr_ccat(&cstr_buf
, '\'');
313 cstr_ccat(&cstr_buf
, '\0');
317 return (char*)cv
->cstr
->data
;
319 cstr_ccat(&cstr_buf
, 'L');
322 cstr_ccat(&cstr_buf
, '\"');
324 len
= cstr
->size
- 1;
326 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
328 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
330 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
332 cstr_ccat(&cstr_buf
, '\"');
333 cstr_ccat(&cstr_buf
, '\0');
340 return NULL
; /* should not happen */
342 /* above tokens have value, the ones below don't */
351 return strcpy(p
, "...");
353 return strcpy(p
, "<<=");
355 return strcpy(p
, ">>=");
358 /* search in two bytes table */
359 const unsigned char *q
= tok_two_chars
;
370 sprintf(buf
, "<%02x>", v
);
376 } else if (v
< tok_ident
) {
377 return table_ident
[v
- TOK_IDENT
]->str
;
378 } else if (v
>= SYM_FIRST_ANOM
) {
379 /* special name for anonymous symbol */
380 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
382 /* should never happen */
387 return cstr_buf
.data
;
390 /* return the current character, handling end of block if necessary
392 ST_FUNC
int handle_eob(void)
394 BufferedFile
*bf
= file
;
397 /* only tries to read if really end of buffer */
398 if (bf
->buf_ptr
>= bf
->buf_end
) {
400 #if defined(PARSE_DEBUG)
405 len
= read(bf
->fd
, bf
->buffer
, len
);
412 bf
->buf_ptr
= bf
->buffer
;
413 bf
->buf_end
= bf
->buffer
+ len
;
414 *bf
->buf_end
= CH_EOB
;
416 if (bf
->buf_ptr
< bf
->buf_end
) {
417 return bf
->buf_ptr
[0];
419 bf
->buf_ptr
= bf
->buf_end
;
424 /* read next char from current input file and handle end of input buffer */
425 ST_INLN
void inp(void)
427 ch
= *(++(file
->buf_ptr
));
428 /* end of buffer/file handling */
433 /* handle '\[\r]\n' */
434 static int handle_stray_noerror(void)
441 } else if (ch
== '\r') {
455 static void handle_stray(void)
457 if (handle_stray_noerror())
458 tcc_error("stray '\\' in program");
461 /* skip the stray and handle the \\n case. Output an error if
462 incorrect char after the stray */
463 static int handle_stray1(uint8_t *p
)
468 if (p
>= file
->buf_end
) {
475 if (handle_stray_noerror()) {
476 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
477 tcc_error("stray '\\' in program");
478 *--file
->buf_ptr
= '\\';
485 /* handle just the EOB case, but not stray */
486 #define PEEKC_EOB(c, p)\
497 /* handle the complicated stray case */
503 c = handle_stray1(p);\
508 /* input with '\[\r]\n' handling. Note that this function cannot
509 handle other characters after '\', so you cannot call it inside
510 strings or comments */
511 ST_FUNC
void minp(void)
519 /* single line C++ comments */
520 static uint8_t *parse_line_comment(uint8_t *p
)
528 if (c
== '\n' || c
== CH_EOF
) {
530 } else if (c
== '\\') {
539 } else if (c
== '\r') {
557 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
566 if (c
== '\n' || c
== '*' || c
== '\\')
570 if (c
== '\n' || c
== '*' || c
== '\\')
574 /* now we can handle all the cases */
578 } else if (c
== '*') {
584 } else if (c
== '/') {
586 } else if (c
== '\\') {
591 tcc_error("unexpected end of file in comment");
593 /* skip '\[\r]\n', otherwise just skip the stray */
599 } else if (c
== '\r') {
616 /* stray, eob or eof */
621 tcc_error("unexpected end of file in comment");
622 } else if (c
== '\\') {
634 static inline void skip_spaces(void)
636 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
640 static inline int check_space(int t
, int *spc
)
642 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
651 /* parse a string without interpreting escapes */
652 static uint8_t *parse_pp_string(uint8_t *p
,
653 int sep
, CString
*str
)
661 } else if (c
== '\\') {
667 /* XXX: indicate line number of start of string */
668 tcc_error("missing terminating %c character", sep
);
669 } else if (c
== '\\') {
670 /* escape : just skip \[\r]\n */
675 } else if (c
== '\r') {
678 expect("'\n' after '\r'");
681 } else if (c
== CH_EOF
) {
682 goto unterminated_string
;
685 cstr_ccat(str
, '\\');
691 } else if (c
== '\n') {
694 } else if (c
== '\r') {
698 cstr_ccat(str
, '\r');
714 /* skip block of text until #else, #elif or #endif. skip also pairs of
716 static void preprocess_skip(void)
718 int a
, start_of_line
, c
, in_warn_or_error
;
725 in_warn_or_error
= 0;
746 } else if (c
== '\\') {
747 ch
= file
->buf_ptr
[0];
748 handle_stray_noerror();
755 if (in_warn_or_error
)
757 p
= parse_pp_string(p
, c
, NULL
);
761 if (in_warn_or_error
)
768 p
= parse_comment(p
);
769 } else if (ch
== '/') {
770 p
= parse_line_comment(p
);
780 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
782 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
784 else if (tok
== TOK_ENDIF
)
786 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
787 in_warn_or_error
= 1;
788 else if (tok
== TOK_LINEFEED
)
790 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
791 p
= parse_line_comment(p
);
804 /* ParseState handling */
806 /* XXX: currently, no include file info is stored. Thus, we cannot display
807 accurate messages if the function or data definition spans multiple
810 /* save current parse state in 's' */
811 ST_FUNC
void save_parse_state(ParseState
*s
)
813 s
->line_num
= file
->line_num
;
814 s
->macro_ptr
= macro_ptr
;
819 /* restore parse state from 's' */
820 ST_FUNC
void restore_parse_state(ParseState
*s
)
822 file
->line_num
= s
->line_num
;
823 macro_ptr
= s
->macro_ptr
;
828 /* return the number of additional 'ints' necessary to store the
830 static inline int tok_size(const int *p
)
845 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
851 return 1 + LDOUBLE_SIZE
/ 4;
857 /* token string handling */
859 ST_INLN
void tok_str_new(TokenString
*s
)
863 s
->allocated_len
= 0;
864 s
->last_line_num
= -1;
867 ST_FUNC
void tok_str_free(int *str
)
872 static int *tok_str_realloc(TokenString
*s
)
876 if (s
->allocated_len
== 0) {
879 len
= s
->allocated_len
* 2;
881 str
= tcc_realloc(s
->str
, len
* sizeof(int));
882 s
->allocated_len
= len
;
887 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
893 if (len
>= s
->allocated_len
)
894 str
= tok_str_realloc(s
);
899 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
906 /* allocate space for worst case */
907 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
908 str
= tok_str_realloc(s
);
917 str
[len
++] = cv
->tab
[0];
927 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
928 while ((len
+ nb_words
) > s
->allocated_len
)
929 str
= tok_str_realloc(s
);
930 cstr
= (CString
*)(str
+ len
);
932 cstr
->size
= cv
->cstr
->size
;
933 cstr
->data_allocated
= NULL
;
934 cstr
->size_allocated
= cstr
->size
;
935 memcpy((char *)cstr
+ sizeof(CString
),
936 cv
->cstr
->data
, cstr
->size
);
943 #if LDOUBLE_SIZE == 8
946 str
[len
++] = cv
->tab
[0];
947 str
[len
++] = cv
->tab
[1];
949 #if LDOUBLE_SIZE == 12
951 str
[len
++] = cv
->tab
[0];
952 str
[len
++] = cv
->tab
[1];
953 str
[len
++] = cv
->tab
[2];
954 #elif LDOUBLE_SIZE == 16
956 str
[len
++] = cv
->tab
[0];
957 str
[len
++] = cv
->tab
[1];
958 str
[len
++] = cv
->tab
[2];
959 str
[len
++] = cv
->tab
[3];
960 #elif LDOUBLE_SIZE != 8
961 #error add long double size support
970 /* add the current parse token in token string 's' */
971 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
975 /* save line number info */
976 if (file
->line_num
!= s
->last_line_num
) {
977 s
->last_line_num
= file
->line_num
;
978 cval
.i
= s
->last_line_num
;
979 tok_str_add2(s
, TOK_LINENUM
, &cval
);
981 tok_str_add2(s
, tok
, &tokc
);
984 /* get a token from an integer array and increment pointer
985 accordingly. we code it as a macro to avoid pointer aliasing. */
986 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1005 cv
->cstr
= (CString
*)p
;
1006 cv
->cstr
->data
= (char *)p
+ sizeof(CString
);
1007 p
+= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
1015 #if LDOUBLE_SIZE == 16
1017 #elif LDOUBLE_SIZE == 12
1019 #elif LDOUBLE_SIZE == 8
1022 # error add long double size support
1035 static int macro_is_equal(const int *a
, const int *b
)
1037 char buf
[STRING_MAX_SIZE
+ 1];
1041 TOK_GET(&t
, &a
, &cv
);
1042 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1043 TOK_GET(&t
, &b
, &cv
);
1044 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1050 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
1052 int d
= f
->line_num
- f
->line_ref
;
1053 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
1054 || (level
== 0 && f
->line_ref
&& d
< 8))
1057 fputs("\n", s1
->ppfp
), --d
;
1060 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
1061 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
1064 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
1065 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
1067 f
->line_ref
= f
->line_num
;
1070 static void tok_print(const char *msg
, const int *str
)
1072 FILE *pr
= tcc_state
->ppfp
;
1076 fprintf(pr
, "%s ", msg
);
1078 TOK_GET(&t
, &str
, &cval
);
1081 fprintf(pr
,"%s", get_tok_str(t
, &cval
));
1086 static int define_print_prepared(Sym
*s
)
1088 if (!s
|| !tcc_state
->ppfp
|| tcc_state
->dflag
== 0)
1091 if (s
->v
< TOK_IDENT
|| s
->v
>= tok_ident
)
1096 pp_line(tcc_state
, file
, 0);
1097 file
->line_ref
= ++file
->line_num
;
1102 static void define_print(int v
)
1104 FILE *pr
= tcc_state
->ppfp
;
1108 if (define_print_prepared(s
) == 0)
1111 fprintf(pr
, "// #define %s", get_tok_str(v
, NULL
));
1112 if (s
->type
.t
== MACRO_FUNC
) {
1117 fprintf(pr
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
1124 tok_print("", s
->d
);
1127 static void undef_print(int v
)
1129 FILE *pr
= tcc_state
->ppfp
;
1133 if (define_print_prepared(s
) == 0)
1136 fprintf(pr
, "// #undef %s\n", get_tok_str(s
->v
, NULL
));
1139 ST_FUNC
void print_defines(void)
1141 Sym
*top
= define_stack
;
1143 define_print(top
->v
);
1148 /* defines handling */
1149 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1154 if (s
&& !macro_is_equal(s
->d
, str
))
1155 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1157 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1159 s
->next
= first_arg
;
1160 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1163 /* undefined a define symbol. Its name is just set to zero */
1164 ST_FUNC
void define_undef(Sym
*s
)
1168 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1169 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1172 ST_INLN Sym
*define_find(int v
)
1175 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1177 return table_ident
[v
]->sym_define
;
1180 /* free define stack until top reaches 'b' */
1181 ST_FUNC
void free_defines(Sym
*b
)
1189 /* do not free args or predefined defines */
1191 tok_str_free(top
->d
);
1193 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1194 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1202 ST_FUNC Sym
*label_find(int v
)
1205 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1207 return table_ident
[v
]->sym_label
;
1210 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1213 s
= sym_push2(ptop
, v
, 0, 0);
1215 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1216 if (ptop
== &global_label_stack
) {
1217 /* modify the top most local identifier, so that
1218 sym_identifier will point to 's' when popped */
1220 ps
= &(*ps
)->prev_tok
;
1227 /* pop labels until element last is reached. Look if any labels are
1228 undefined. Define symbols if '&&label' was used. */
1229 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1232 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1234 if (s
->r
== LABEL_DECLARED
) {
1235 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1236 } else if (s
->r
== LABEL_FORWARD
) {
1237 tcc_error("label '%s' used but not defined",
1238 get_tok_str(s
->v
, NULL
));
1241 /* define corresponding symbol. A size of
1243 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1247 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1253 /* eval an expression for #if/#elif */
1254 static int expr_preprocess(void)
1260 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1261 next(); /* do macro subst */
1262 if (tok
== TOK_DEFINED
) {
1267 c
= define_find(tok
) != 0;
1272 } else if (tok
>= TOK_IDENT
) {
1273 /* if undefined macro */
1277 tok_str_add_tok(&str
);
1279 tok_str_add(&str
, -1); /* simulate end of file */
1280 tok_str_add(&str
, 0);
1281 /* now evaluate C constant expression */
1282 begin_macro(&str
, 0);
1290 /* parse after #define */
1291 ST_FUNC
void parse_define(void)
1293 Sym
*s
, *first
, **ps
;
1294 int v
, t
, varg
, is_vaargs
, spc
;
1295 int saved_parse_flags
= parse_flags
;
1300 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1301 /* XXX: should check if same macro (ANSI) */
1304 /* '(' must be just after macro definition for MACRO_FUNC */
1305 parse_flags
|= PARSE_FLAG_SPACES
;
1310 if (tok
!= ')') for (;;) {
1314 if (varg
== TOK_DOTS
) {
1315 varg
= TOK___VA_ARGS__
;
1317 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1321 if (varg
< TOK_IDENT
)
1323 tcc_error("bad macro parameter list");
1324 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1329 if (tok
!= ',' || is_vaargs
)
1338 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1339 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1340 /* remove spaces around ## and after '#' */
1341 if (TOK_TWOSHARPS
== tok
) {
1347 } else if ('#' == tok
) {
1349 } else if (check_space(tok
, &spc
)) {
1352 tok_str_add2(&str
, tok
, &tokc
);
1357 parse_flags
= saved_parse_flags
;
1359 --str
.len
; /* remove trailing space */
1360 tok_str_add(&str
, 0);
1363 tcc_error("'##' cannot appear at either end of macro");
1364 define_push(v
, t
, str
.str
, first
);
1368 static inline int hash_cached_include(const char *filename
)
1370 const unsigned char *s
;
1374 s
= (unsigned char *) filename
;
1376 h
= TOK_HASH_FUNC(h
, *s
);
1379 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1383 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1387 h
= hash_cached_include(filename
);
1388 i
= s1
->cached_includes_hash
[h
];
1392 e
= s1
->cached_includes
[i
- 1];
1393 if (0 == PATHCMP(e
->filename
, filename
))
1400 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1405 if (search_cached_include(s1
, filename
))
1408 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1410 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1411 strcpy(e
->filename
, filename
);
1412 e
->ifndef_macro
= ifndef_macro
;
1413 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1414 /* add in hash table */
1415 h
= hash_cached_include(filename
);
1416 e
->hash_next
= s1
->cached_includes_hash
[h
];
1417 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1420 static void pragma_parse(TCCState
*s1
)
1423 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1427 if (next(), tok
!= '(')
1429 if (next(), tok
!= TOK_STR
)
1431 v
= tok_alloc(tokc
.cstr
->data
, tokc
.cstr
->size
- 1)->tok
;
1432 if (next(), tok
!= ')')
1434 if (t
== TOK_push_macro
) {
1435 while (NULL
== (s
= define_find(v
)))
1436 define_push(v
, 0, NULL
, NULL
);
1437 s
->type
.ref
= s
; /* set push boundary */
1439 for (s
= define_stack
; s
; s
= s
->prev
)
1440 if (s
->v
== v
&& s
->type
.ref
== s
) {
1446 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1448 tcc_warning("unbalanced #pragma pop_macro");
1450 } else if (tok
== TOK_once
) {
1451 add_cached_include(s1
, file
->filename
, TOK_once
);
1453 } else if (s1
->ppfp
) {
1454 /* tcc -E: keep pragmas below unchanged */
1456 unget_tok(TOK_PRAGMA
);
1458 unget_tok(TOK_LINEFEED
);
1460 } else if (tok
== TOK_pack
) {
1462 #pragma pack(1) // set
1463 #pragma pack() // reset to default
1464 #pragma pack(push,1) // push & set
1465 #pragma pack(pop) // restore previous */
1468 if (tok
== TOK_ASM_pop
) {
1470 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1472 tcc_error("out of pack stack");
1474 s1
->pack_stack_ptr
--;
1478 if (tok
== TOK_ASM_push
) {
1480 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1482 s1
->pack_stack_ptr
++;
1485 if (tok
!= TOK_CINT
)
1488 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1492 *s1
->pack_stack_ptr
= val
;
1497 } else if (tok
== TOK_comment
) {
1507 file
= tcc_strdup((char *)tokc
.cstr
->data
);
1508 dynarray_add((void ***)&s1
->pragma_libs
, &s1
->nb_pragma_libs
, file
);
1514 if (s1
->warn_unsupported
)
1515 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1520 tcc_error("malformed #pragma directive");
1524 /* is_bof is true if first non space token at beginning of file */
1525 ST_FUNC
void preprocess(int is_bof
)
1527 TCCState
*s1
= tcc_state
;
1528 int i
, c
, n
, saved_parse_flags
;
1533 saved_parse_flags
= parse_flags
;
1534 parse_flags
= PARSE_FLAG_PREPROCESS
1535 | PARSE_FLAG_TOK_NUM
1536 | PARSE_FLAG_TOK_STR
1537 | PARSE_FLAG_LINEFEED
1538 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1550 s
= define_find(tok
);
1551 /* undefine symbol by putting an invalid name */
1556 case TOK_INCLUDE_NEXT
:
1557 ch
= file
->buf_ptr
[0];
1558 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1563 } else if (ch
== '\"') {
1568 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1569 if ((q
- buf
) < sizeof(buf
) - 1)
1572 if (handle_stray_noerror() == 0)
1580 /* eat all spaces and comments after include */
1581 /* XXX: slightly incorrect */
1582 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1586 /* computed #include : either we have only strings or
1587 we have anything enclosed in '<>' */
1590 if (tok
== TOK_STR
) {
1591 while (tok
!= TOK_LINEFEED
) {
1592 if (tok
!= TOK_STR
) {
1594 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1596 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1602 while (tok
!= TOK_LINEFEED
) {
1603 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1607 /* check syntax and remove '<>' */
1608 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1609 goto include_syntax
;
1610 memmove(buf
, buf
+ 1, len
- 2);
1611 buf
[len
- 2] = '\0';
1616 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1617 tcc_error("#include recursion too deep");
1618 /* store current file in stack, but increment stack later below */
1619 *s1
->include_stack_ptr
= file
;
1622 if (tok
== TOK_INCLUDE_NEXT
)
1623 printf("%s (1) include_next file %s\n", file
->filename
, buf
);
1626 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1627 for (i
= -2; i
< n
; ++i
) {
1628 char buf1
[sizeof file
->filename
];
1634 /* check absolute include path */
1635 if (!IS_ABSPATH(buf
))
1638 i
= n
; /* force end loop */
1640 } else if (i
== -1) {
1641 /* search in current dir if "header.h" */
1644 path
= file
->filename
;
1645 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1648 /* search in all the include paths */
1649 if (i
< s1
->nb_include_paths
)
1650 path
= s1
->include_paths
[i
];
1652 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1653 pstrcpy(buf1
, sizeof(buf1
), path
);
1654 pstrcat(buf1
, sizeof(buf1
), "/");
1658 if (tok
== TOK_INCLUDE_NEXT
)
1659 printf("%s (2) include_next path <%s> name <%s>\n", file
->filename
, buf1
, buf
);
1662 pstrcat(buf1
, sizeof(buf1
), buf
);
1664 if (tok
== TOK_INCLUDE_NEXT
) {
1666 if ((p1
[0] == '.') && IS_DIRSEP(p1
[1])) p1
+= 2;
1669 if (0 == PATHCMP(p1
, p3
)) {
1671 printf("%s (3) include_next skipping <%s>\n", file
->filename
, p1
);
1673 goto include_trynext
;
1677 for (f
= s1
->include_stack_ptr
; f
>= s1
->include_stack
; --f
) {
1678 char *p2
= (*f
)->filename
;
1679 if ((p2
[0] == '.') && IS_DIRSEP(p2
[1])) p2
+= 2;
1680 if (0 == PATHCMP(p2
, p1
)) {
1686 printf("%s: (4) include_next skipping <%s> (p3=%p)\n", file
->filename
, buf1
, p3
);
1688 goto include_trynext
;
1691 printf("%s (5) include_next considering <%s>\n", file
->filename
, buf1
);
1695 e
= search_cached_include(s1
, buf1
);
1696 if (e
&& (define_find(e
->ifndef_macro
) || e
->ifndef_macro
== TOK_once
)) {
1697 /* no need to parse the include because the 'ifndef macro'
1701 printf("%s: skipping cached <%s>\n", file
->filename
, buf1
);
1706 if (tcc_open(s1
, buf1
) < 0) {
1708 printf("%s: include open failed <%s>\n", file
->filename
, buf1
);
1715 printf("%s: including <%s>\n", file
->prev
->filename
, file
->filename
);
1718 /* update target deps */
1719 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1721 /* push current file in stack */
1722 ++s1
->include_stack_ptr
;
1723 /* add include file debug info */
1725 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1726 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1727 ch
= file
->buf_ptr
[0];
1730 tcc_error("include file '%s' not found", buf
);
1737 c
= expr_preprocess();
1743 if (tok
< TOK_IDENT
)
1744 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1748 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1750 file
->ifndef_macro
= tok
;
1753 c
= (define_find(tok
) != 0) ^ c
;
1755 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1756 tcc_error("memory full (ifdef)");
1757 *s1
->ifdef_stack_ptr
++ = c
;
1760 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1761 tcc_error("#else without matching #if");
1762 if (s1
->ifdef_stack_ptr
[-1] & 2)
1763 tcc_error("#else after #else");
1764 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1767 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1768 tcc_error("#elif without matching #if");
1769 c
= s1
->ifdef_stack_ptr
[-1];
1771 tcc_error("#elif after #else");
1772 /* last #if/#elif expression was true: we skip */
1775 c
= expr_preprocess();
1776 s1
->ifdef_stack_ptr
[-1] = c
;
1778 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1779 file
->ifndef_macro
= 0;
1789 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1790 tcc_error("#endif without matching #if");
1791 s1
->ifdef_stack_ptr
--;
1792 /* '#ifndef macro' was at the start of file. Now we check if
1793 an '#endif' is exactly at the end of file */
1794 if (file
->ifndef_macro
&&
1795 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1796 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1797 /* need to set to zero to avoid false matches if another
1798 #ifndef at middle of file */
1799 file
->ifndef_macro
= 0;
1800 while (tok
!= TOK_LINEFEED
)
1802 tok_flags
|= TOK_FLAG_ENDIF
;
1807 n
= strtoul((char*)tokc
.cstr
->data
, &q
, 10);
1811 if (tok
!= TOK_CINT
)
1813 tcc_error("wrong #line format");
1817 if (tok
!= TOK_LINEFEED
) {
1819 pstrcpy(file
->filename
, sizeof(file
->filename
), (char *)tokc
.cstr
->data
);
1820 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1827 total_lines
+= file
->line_num
- n
;
1830 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1835 ch
= file
->buf_ptr
[0];
1838 while (ch
!= '\n' && ch
!= CH_EOF
) {
1839 if ((q
- buf
) < sizeof(buf
) - 1)
1842 if (handle_stray_noerror() == 0)
1849 tcc_error("#error %s", buf
);
1851 tcc_warning("#warning %s", buf
);
1859 /* ignore gas line comment in an 'S' file. */
1860 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
1862 if (tok
== '!' && is_bof
)
1863 /* '!' is ignored at beginning to allow C scripts. */
1865 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1867 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1870 /* ignore other preprocess commands or #! for C scripts */
1871 while (tok
!= TOK_LINEFEED
)
1874 parse_flags
= saved_parse_flags
;
1877 /* evaluate escape codes in a string. */
1878 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1893 case '0': case '1': case '2': case '3':
1894 case '4': case '5': case '6': case '7':
1895 /* at most three octal digits */
1900 n
= n
* 8 + c
- '0';
1904 n
= n
* 8 + c
- '0';
1909 goto add_char_nonext
;
1917 if (c
>= 'a' && c
<= 'f')
1919 else if (c
>= 'A' && c
<= 'F')
1929 goto add_char_nonext
;
1953 goto invalid_escape
;
1963 if (c
>= '!' && c
<= '~')
1964 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1966 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1973 cstr_ccat(outstr
, c
);
1975 cstr_wccat(outstr
, c
);
1977 /* add a trailing '\0' */
1979 cstr_ccat(outstr
, '\0');
1981 cstr_wccat(outstr
, '\0');
1984 void parse_string(const char *s
, int len
)
1986 uint8_t buf
[1000], *p
= buf
;
1989 if ((is_long
= *s
== 'L'))
1993 if (len
>= sizeof buf
)
1994 p
= tcc_malloc(len
+ 1);
1998 cstr_reset(&tokcstr
);
1999 parse_escape_string(&tokcstr
, p
, is_long
);
2005 /* XXX: make it portable */
2009 char_size
= sizeof(nwchar_t
);
2010 if (tokcstr
.size
<= char_size
)
2011 tcc_error("empty character constant");
2012 if (tokcstr
.size
> 2 * char_size
)
2013 tcc_warning("multi-character character constant");
2015 tokc
.i
= *(int8_t *)tokcstr
.data
;
2018 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2022 tokc
.cstr
= &tokcstr
;
2030 /* we use 64 bit numbers */
2033 /* bn = (bn << shift) | or_val */
2034 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2038 for(i
=0;i
<BN_SIZE
;i
++) {
2040 bn
[i
] = (v
<< shift
) | or_val
;
2041 or_val
= v
>> (32 - shift
);
2045 static void bn_zero(unsigned int *bn
)
2048 for(i
=0;i
<BN_SIZE
;i
++) {
2053 /* parse number in null terminated string 'p' and return it in the
2055 static void parse_number(const char *p
)
2057 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2059 unsigned int bn
[BN_SIZE
];
2070 goto float_frac_parse
;
2071 } else if (t
== '0') {
2072 if (ch
== 'x' || ch
== 'X') {
2076 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2082 /* parse all digits. cannot check octal numbers at this stage
2083 because of floating point constants */
2085 if (ch
>= 'a' && ch
<= 'f')
2087 else if (ch
>= 'A' && ch
<= 'F')
2095 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2097 tcc_error("number too long");
2103 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2104 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2106 /* NOTE: strtox should support that for hexa numbers, but
2107 non ISOC99 libcs do not support it, so we prefer to do
2109 /* hexadecimal or binary floats */
2110 /* XXX: handle overflows */
2122 } else if (t
>= 'a') {
2124 } else if (t
>= 'A') {
2129 bn_lshift(bn
, shift
, t
);
2136 if (t
>= 'a' && t
<= 'f') {
2138 } else if (t
>= 'A' && t
<= 'F') {
2140 } else if (t
>= '0' && t
<= '9') {
2146 tcc_error("invalid digit");
2147 bn_lshift(bn
, shift
, t
);
2152 if (ch
!= 'p' && ch
!= 'P')
2159 } else if (ch
== '-') {
2163 if (ch
< '0' || ch
> '9')
2164 expect("exponent digits");
2165 while (ch
>= '0' && ch
<= '9') {
2166 exp_val
= exp_val
* 10 + ch
- '0';
2169 exp_val
= exp_val
* s
;
2171 /* now we can generate the number */
2172 /* XXX: should patch directly float number */
2173 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2174 d
= ldexp(d
, exp_val
- frac_bits
);
2179 /* float : should handle overflow */
2181 } else if (t
== 'L') {
2183 #ifdef TCC_TARGET_PE
2188 /* XXX: not large enough */
2189 tokc
.ld
= (long double)d
;
2196 /* decimal floats */
2198 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2203 while (ch
>= '0' && ch
<= '9') {
2204 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2210 if (ch
== 'e' || ch
== 'E') {
2211 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2215 if (ch
== '-' || ch
== '+') {
2216 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2221 if (ch
< '0' || ch
> '9')
2222 expect("exponent digits");
2223 while (ch
>= '0' && ch
<= '9') {
2224 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2236 tokc
.f
= strtof(token_buf
, NULL
);
2237 } else if (t
== 'L') {
2239 #ifdef TCC_TARGET_PE
2241 tokc
.d
= strtod(token_buf
, NULL
);
2244 tokc
.ld
= strtold(token_buf
, NULL
);
2248 tokc
.d
= strtod(token_buf
, NULL
);
2252 unsigned long long n
, n1
;
2253 int lcount
, ucount
, must_64bit
;
2256 /* integer number */
2259 if (b
== 10 && *q
== '0') {
2266 /* no need for checks except for base 10 / 8 errors */
2276 tcc_error("invalid digit");
2279 /* detect overflow */
2280 /* XXX: this test is not reliable */
2282 tcc_error("integer constant overflow");
2285 /* Determine the characteristics (unsigned and/or 64bit) the type of
2286 the constant must have according to the constant suffix(es) */
2287 lcount
= ucount
= must_64bit
= 0;
2293 tcc_error("three 'l's in integer constant");
2294 if (lcount
&& *(p
- 1) != ch
)
2295 tcc_error("incorrect integer suffix: %s", p1
);
2297 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2302 } else if (t
== 'U') {
2304 tcc_error("two 'u's in integer constant");
2312 /* Whether 64 bits are needed to hold the constant's value */
2313 if (n
& 0xffffffff00000000LL
|| must_64bit
) {
2321 /* Whether type must be unsigned to hold the constant's value */
2322 if (ucount
|| ((n1
>> 31) && (b
!= 10))) {
2323 if (tok
== TOK_CLLONG
)
2327 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2328 } else if (n1
>> 31) {
2329 if (tok
== TOK_CINT
)
2332 tcc_error("integer constant overflow");
2335 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2341 tcc_error("invalid number\n");
2345 #define PARSE2(c1, tok1, c2, tok2) \
2356 /* return next token without macro substitution */
2357 static inline void next_nomacro1(void)
2372 if (parse_flags
& PARSE_FLAG_SPACES
)
2373 goto keep_tok_flags
;
2374 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2383 /* first look if it is in fact an end of buffer */
2384 c
= handle_stray1(p
);
2391 TCCState
*s1
= tcc_state
;
2392 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2393 && !(tok_flags
& TOK_FLAG_EOF
)) {
2394 tok_flags
|= TOK_FLAG_EOF
;
2396 goto keep_tok_flags
;
2397 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2399 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2400 tcc_error("missing #endif");
2401 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2402 /* no include left : end of file. */
2405 tok_flags
&= ~TOK_FLAG_EOF
;
2406 /* pop include file */
2408 /* test if previous '#endif' was after a #ifdef at
2410 if (tok_flags
& TOK_FLAG_ENDIF
) {
2412 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2414 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2415 tok_flags
&= ~TOK_FLAG_ENDIF
;
2418 /* add end of include file debug info */
2419 if (tcc_state
->do_debug
) {
2420 put_stabd(N_EINCL
, 0, 0);
2422 /* pop include stack */
2424 s1
->include_stack_ptr
--;
2433 tok_flags
|= TOK_FLAG_BOL
;
2436 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2439 goto keep_tok_flags
;
2444 if ((tok_flags
& TOK_FLAG_BOL
) &&
2445 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2447 preprocess(tok_flags
& TOK_FLAG_BOF
);
2453 tok
= TOK_TWOSHARPS
;
2455 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2456 p
= parse_line_comment(p
- 1);
2465 /* dollar is allowed to start identifiers when not parsing asm */
2467 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2468 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2471 case 'a': case 'b': case 'c': case 'd':
2472 case 'e': case 'f': case 'g': case 'h':
2473 case 'i': case 'j': case 'k': case 'l':
2474 case 'm': case 'n': case 'o': case 'p':
2475 case 'q': case 'r': case 's': case 't':
2476 case 'u': case 'v': case 'w': case 'x':
2478 case 'A': case 'B': case 'C': case 'D':
2479 case 'E': case 'F': case 'G': case 'H':
2480 case 'I': case 'J': case 'K':
2481 case 'M': case 'N': case 'O': case 'P':
2482 case 'Q': case 'R': case 'S': case 'T':
2483 case 'U': case 'V': case 'W': case 'X':
2489 h
= TOK_HASH_FUNC(h
, c
);
2490 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2491 h
= TOK_HASH_FUNC(h
, c
);
2496 /* fast case : no stray found, so we have the full token
2497 and we have already hashed it */
2499 h
&= (TOK_HASH_SIZE
- 1);
2500 pts
= &hash_ident
[h
];
2505 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2507 pts
= &(ts
->hash_next
);
2509 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2513 cstr_reset(&tokcstr
);
2516 cstr_ccat(&tokcstr
, *p1
);
2522 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
)) {
2523 cstr_ccat(&tokcstr
, c
);
2526 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2532 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2534 goto parse_ident_fast
;
2537 if (c
== '\'' || c
== '\"') {
2541 cstr_reset(&tokcstr
);
2542 cstr_ccat(&tokcstr
, 'L');
2543 goto parse_ident_slow
;
2548 case '0': case '1': case '2': case '3':
2549 case '4': case '5': case '6': case '7':
2551 cstr_reset(&tokcstr
);
2552 /* after the first digit, accept digits, alpha, '.' or sign if
2553 prefixed by 'eEpP' */
2557 cstr_ccat(&tokcstr
, c
);
2559 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2561 || ((c
== '+' || c
== '-')
2562 && (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P')
2566 /* We add a trailing '\0' to ease parsing */
2567 cstr_ccat(&tokcstr
, '\0');
2568 tokc
.cstr
= &tokcstr
;
2573 /* special dot handling because it can also start a number */
2576 cstr_reset(&tokcstr
);
2577 cstr_ccat(&tokcstr
, '.');
2579 } else if ((c
== '.') && (p
[1] == '.')){
2591 cstr_reset(&tokcstr
);
2593 cstr_ccat(&tokcstr
, 'L');
2594 cstr_ccat(&tokcstr
, c
);
2595 p
= parse_pp_string(p
, c
, &tokcstr
);
2596 cstr_ccat(&tokcstr
, c
);
2597 cstr_ccat(&tokcstr
, '\0');
2598 tokc
.cstr
= &tokcstr
;
2607 } else if (c
== '<') {
2624 } else if (c
== '>') {
2642 } else if (c
== '=') {
2655 } else if (c
== '=') {
2668 } else if (c
== '=') {
2681 } else if (c
== '=') {
2684 } else if (c
== '>') {
2692 PARSE2('!', '!', '=', TOK_NE
)
2693 PARSE2('=', '=', '=', TOK_EQ
)
2694 PARSE2('*', '*', '=', TOK_A_MUL
)
2695 PARSE2('%', '%', '=', TOK_A_MOD
)
2696 PARSE2('^', '^', '=', TOK_A_XOR
)
2698 /* comments or operator */
2702 p
= parse_comment(p
);
2703 /* comments replaced by a blank */
2705 goto keep_tok_flags
;
2706 } else if (c
== '/') {
2707 p
= parse_line_comment(p
);
2709 goto keep_tok_flags
;
2710 } else if (c
== '=') {
2730 case '@': /* only used in assembler */
2736 tcc_error("unrecognized character \\x%02x", c
);
2742 #if defined(PARSE_DEBUG)
2743 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2747 /* return next token without macro substitution. Can read input from
2749 static void next_nomacro_spc(void)
2755 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2756 if (tok
== TOK_LINENUM
) {
2757 file
->line_num
= tokc
.i
;
2766 ST_FUNC
void next_nomacro(void)
2770 } while (tok
< 256 && (isidnum_table
[tok
- CH_EOF
] & IS_SPC
));
2774 static void macro_subst(
2775 TokenString
*tok_str
,
2777 const int *macro_str
,
2781 /* substitute arguments in replacement lists in macro_str by the values in
2782 args (field d) and return allocated string */
2783 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2795 TOK_GET(&t
, ¯o_str
, &cval
);
2800 TOK_GET(&t
, ¯o_str
, &cval
);
2803 s
= sym_find2(args
, t
);
2806 cstr_ccat(&cstr
, '\"');
2810 TOK_GET(&t
, &st
, &cval
);
2811 if (t
!= TOK_PLCHLDR
2813 && 0 == check_space(t
, &spc
)) {
2814 const char *s
= get_tok_str(t
, &cval
);
2816 if (t
== TOK_PPSTR
&& *s
!= '\'')
2817 add_char(&cstr
, *s
);
2819 cstr_ccat(&cstr
, *s
);
2825 cstr_ccat(&cstr
, '\"');
2826 cstr_ccat(&cstr
, '\0');
2828 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
2832 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
2833 cstr_free(cval
.cstr
);
2836 expect("macro parameter after '#'");
2838 } else if (t
>= TOK_IDENT
) {
2839 s
= sym_find2(args
, t
);
2843 /* if '##' is present before or after, no arg substitution */
2844 if (*macro_str
== TOK_TWOSHARPS
|| t1
== TOK_TWOSHARPS
) {
2845 /* special case for var arg macros : ## eats the ','
2846 if empty VA_ARGS variable. */
2847 if (t1
== TOK_TWOSHARPS
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
2849 /* suppress ',' '##' */
2852 /* suppress '##' and add variable */
2859 TOK_GET(&t1
, &st
, &cval
);
2862 tok_str_add2(&str
, t1
, &cval
);
2868 /* NOTE: the stream cannot be read when macro
2869 substituing an argument */
2870 macro_subst(&str
, nested_list
, st
, 0);
2872 if (str
.len
== l0
) /* exanded to empty string */
2873 tok_str_add(&str
, TOK_PLCHLDR
);
2875 tok_str_add(&str
, t
);
2878 tok_str_add2(&str
, t
, &cval
);
2882 tok_str_add(&str
, 0);
2886 static char const ab_month_name
[12][4] =
2888 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2889 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2892 /* peek or read [ws_str == NULL] next token from function macro call,
2893 walking up macro levels up to the file if necessary */
2894 static int next_argstream(Sym
**nested_list
, int can_read_stream
, TokenString
*ws_str
)
2902 p
= macro_ptr
, t
= *p
;
2904 while (is_space(t
) || TOK_LINEFEED
== t
)
2905 tok_str_add(ws_str
, t
), t
= *++p
;
2907 if (t
== 0 && can_read_stream
) {
2909 /* also, end of scope for nested defined symbol */
2911 while (sa
&& sa
->v
== -1)
2920 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
2923 uint8_t *p
= file
->buf_ptr
;
2926 p
= parse_comment(p
);
2927 file
->buf_ptr
= p
- 1;
2928 } else if (c
== '/') {
2929 p
= parse_line_comment(p
);
2930 file
->buf_ptr
= p
- 1;
2935 tok_str_add(ws_str
, ch
);
2949 /* do macro substitution of current token with macro 's' and add
2950 result to (tok_str,tok_len). 'nested_list' is the list of all
2951 macros we got inside to avoid recursing. Return non zero if no
2952 substitution needs to be done */
2953 static int macro_subst_tok(
2954 TokenString
*tok_str
,
2957 int can_read_stream
)
2959 Sym
*args
, *sa
, *sa1
;
2960 int parlevel
, *mstr
, t
, t1
, spc
;
2967 /* if symbol is a macro, prepare substitution */
2968 /* special macros */
2969 if (tok
== TOK___LINE__
) {
2970 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2974 } else if (tok
== TOK___FILE__
) {
2975 cstrval
= file
->filename
;
2977 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2982 tm
= localtime(&ti
);
2983 if (tok
== TOK___DATE__
) {
2984 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2985 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2987 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2988 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2995 cstr_cat(&cstr
, cstrval
);
2996 cstr_ccat(&cstr
, '\0');
2998 tok_str_add2(tok_str
, t1
, &cval
);
3001 int saved_parse_flags
= parse_flags
;
3004 if (s
->type
.t
== MACRO_FUNC
) {
3005 /* whitespace between macro name and argument list */
3007 tok_str_new(&ws_str
);
3010 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3011 | PARSE_FLAG_ACCEPT_STRAYS
;
3013 /* get next token from argument stream */
3014 t
= next_argstream(nested_list
, can_read_stream
, &ws_str
);
3016 /* not a macro substitution after all, restore the
3017 * macro token plus all whitespace we've read.
3018 * whitespace is intentionally not merged to preserve
3020 parse_flags
= saved_parse_flags
;
3021 tok_str_add(tok_str
, tok
);
3022 if (parse_flags
& PARSE_FLAG_SPACES
) {
3024 for (i
= 0; i
< ws_str
.len
; i
++)
3025 tok_str_add(tok_str
, ws_str
.str
[i
]);
3027 tok_str_free(ws_str
.str
);
3030 tok_str_free(ws_str
.str
);
3032 next_nomacro(); /* eat '(' */
3034 /* argument macro */
3037 /* NOTE: empty args are allowed, except if no args */
3040 next_argstream(nested_list
, can_read_stream
, NULL
);
3041 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3043 /* handle '()' case */
3044 if (!args
&& !sa
&& tok
== ')')
3047 tcc_error("macro '%s' used with too many args",
3048 get_tok_str(s
->v
, 0));
3051 /* NOTE: non zero sa->t indicates VA_ARGS */
3052 while ((parlevel
> 0 ||
3054 (tok
!= ',' || sa
->type
.t
)))) {
3055 if (tok
== TOK_EOF
|| tok
== 0)
3059 else if (tok
== ')')
3061 if (tok
== TOK_LINEFEED
)
3063 if (!check_space(tok
, &spc
))
3064 tok_str_add2(&str
, tok
, &tokc
);
3065 next_argstream(nested_list
, can_read_stream
, NULL
);
3070 tok_str_add(&str
, 0);
3071 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3075 /* special case for gcc var args: add an empty
3076 var arg argument if it is omitted */
3077 if (sa
&& sa
->type
.t
&& gnu_ext
)
3085 tcc_error("macro '%s' used with too few args",
3086 get_tok_str(s
->v
, 0));
3089 parse_flags
= saved_parse_flags
;
3091 /* now subst each arg */
3092 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3097 tok_str_free(sa
->d
);
3103 sym_push2(nested_list
, s
->v
, 0, 0);
3104 parse_flags
= saved_parse_flags
;
3105 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
3107 /* pop nested defined symbol */
3109 *nested_list
= sa1
->prev
;
3117 int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3123 if (t1
!= TOK_PLCHLDR
)
3124 cstr_cat(&cstr
, get_tok_str(t1
, v1
));
3126 if (t2
!= TOK_PLCHLDR
)
3127 cstr_cat(&cstr
, get_tok_str(t2
, v2
));
3128 cstr_ccat(&cstr
, '\0');
3130 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3131 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3134 if (0 == *file
->buf_ptr
)
3138 tcc_warning("pasting <%.*s> and <%s> does not give a valid preprocessing token",
3139 n
, cstr
.data
, (char*)cstr
.data
+ n
);
3144 //printf("paste <%s>\n", (char*)cstr.data);
3149 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3150 return the resulting string (which must be freed). */
3151 static inline int *macro_twosharps(const int *ptr0
)
3155 TokenString macro_str1
;
3156 int start_of_nosubsts
= -1;
3159 /* we search the first '##' */
3160 for (ptr
= ptr0
;;) {
3161 TOK_GET(&t
, &ptr
, &cval
);
3162 if (t
== TOK_TWOSHARPS
)
3168 tok_str_new(¯o_str1
);
3170 //tok_print(" $$$", ptr0);
3171 for (ptr
= ptr0
;;) {
3172 TOK_GET(&t
, &ptr
, &cval
);
3175 if (t
== TOK_TWOSHARPS
)
3177 while (*ptr
== TOK_TWOSHARPS
) {
3179 /* given 'a##b', remove nosubsts preceding 'a' */
3180 if (start_of_nosubsts
>= 0)
3181 macro_str1
.len
= start_of_nosubsts
;
3182 /* given 'a##b', remove nosubsts preceding 'b' */
3183 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3185 if (t1
&& t1
!= TOK_TWOSHARPS
3186 && t1
!= ':') /* 'a##:' don't build a new token */
3188 TOK_GET(&t1
, &ptr
, &cv1
);
3189 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3190 paste_tokens(t
, &cval
, t1
, &cv1
);
3191 t
= tok
, cval
= tokc
;
3195 if (t
== TOK_NOSUBST
) {
3196 if (start_of_nosubsts
< 0)
3197 start_of_nosubsts
= macro_str1
.len
;
3199 start_of_nosubsts
= -1;
3201 tok_str_add2(¯o_str1
, t
, &cval
);
3203 tok_str_add(¯o_str1
, 0);
3204 //tok_print(" ###", macro_str1.str);
3205 return macro_str1
.str
;
3208 /* do macro substitution of macro_str and add result to
3209 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3210 inside to avoid recursing. */
3211 static void macro_subst(
3212 TokenString
*tok_str
,
3214 const int *macro_str
,
3220 int t
, spc
, nosubst
;
3222 int *macro_str1
= NULL
;
3224 /* first scan for '##' operator handling */
3228 /* first scan for '##' operator handling */
3229 if (can_read_stream
) {
3230 macro_str1
= macro_twosharps(ptr
);
3236 TOK_GET(&t
, &ptr
, &cval
);
3240 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3245 /* if nested substitution, do nothing */
3246 if (sym_find2(*nested_list
, t
)) {
3247 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3248 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3254 str
.str
= (int*)ptr
;
3255 begin_macro(&str
, 2);
3258 macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
3260 if (str
.alloc
== 3) {
3261 /* already finished by reading function macro arguments */
3269 spc
= tok_str
->len
&& is_space(tok_str
->str
[tok_str
->len
-1]);
3273 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3274 tcc_error("stray '\\' in program");
3277 if (!check_space(t
, &spc
))
3278 tok_str_add2(tok_str
, t
, &cval
);
3280 if (t
== TOK_NOSUBST
)
3285 tok_str_free(macro_str1
);
3289 /* return next token with macro substitution */
3290 ST_FUNC
void next(void)
3293 if (parse_flags
& PARSE_FLAG_SPACES
)
3299 if (tok
== TOK_NOSUBST
|| tok
== TOK_PLCHLDR
) {
3300 /* discard preprocessor markers */
3302 } else if (tok
== 0) {
3303 /* end of macro or unget token string */
3307 } else if (tok
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3309 /* if reading from file, try to substitute macros */
3310 s
= define_find(tok
);
3312 static TokenString str
; /* using static string for speed */
3313 Sym
*nested_list
= NULL
;
3316 macro_subst_tok(&str
, &nested_list
, s
, 1);
3317 tok_str_add(&str
, 0);
3318 begin_macro(&str
, 0);
3322 /* convert preprocessor tokens into C tokens */
3323 if (tok
== TOK_PPNUM
) {
3324 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3325 parse_number((char *)tokc
.cstr
->data
);
3326 } else if (tok
== TOK_PPSTR
) {
3327 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3328 parse_string((char *)tokc
.cstr
->data
, tokc
.cstr
->size
- 1);
3332 /* push back current token and set current token to 'last_tok'. Only
3333 identifier case handled for labels. */
3334 ST_INLN
void unget_tok(int last_tok
)
3336 TokenString
*str
= tcc_malloc(sizeof *str
);
3338 tok_str_add2(str
, tok
, &tokc
);
3339 tok_str_add(str
, 0);
3340 begin_macro(str
, 1);
3344 /* better than nothing, but needs extension to handle '-E' option
3346 ST_FUNC
void preprocess_init(TCCState
*s1
)
3348 s1
->include_stack_ptr
= s1
->include_stack
;
3349 /* XXX: move that before to avoid having to initialize
3350 file->ifdef_stack_ptr ? */
3351 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3352 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3354 pvtop
= vtop
= vstack
- 1;
3355 s1
->pack_stack
[0] = 0;
3356 s1
->pack_stack_ptr
= s1
->pack_stack
;
3358 isidnum_table
['$' - CH_EOF
] =
3359 tcc_state
->dollars_in_identifiers
? IS_ID
: 0;
3362 ST_FUNC
void preprocess_new(void)
3367 /* init isid table */
3368 for(i
= CH_EOF
; i
<256; i
++)
3369 isidnum_table
[i
- CH_EOF
]
3370 = is_space(i
) ? IS_SPC
3375 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3377 tok_ident
= TOK_IDENT
;
3386 tok_alloc(p
, r
- p
- 1);
3391 ST_FUNC
void preprocess_delete(void)
3395 /* free -D and compiler defines */
3398 /* cleanup from error/setjmp */
3404 n
= tok_ident
- TOK_IDENT
;
3405 for(i
= 0; i
< n
; i
++)
3406 tcc_free(table_ident
[i
]);
3407 tcc_free(table_ident
);
3411 /* Preprocess the current file */
3412 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3414 BufferedFile
**iptr
;
3415 int token_seen
, spcs
, level
;
3417 preprocess_init(s1
);
3418 ch
= file
->buf_ptr
[0];
3419 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3420 parse_flags
= PARSE_FLAG_PREPROCESS
3421 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3422 | PARSE_FLAG_LINEFEED
3424 | PARSE_FLAG_ACCEPT_STRAYS
3428 do next(); while (tok
!= TOK_EOF
); return 0;
3431 token_seen
= spcs
= 0;
3432 pp_line(s1
, file
, 0);
3435 iptr
= s1
->include_stack_ptr
;
3439 level
= s1
->include_stack_ptr
- iptr
;
3442 pp_line(s1
, *iptr
, 0);
3443 pp_line(s1
, file
, level
);
3446 if (0 == token_seen
) {
3451 if (tok
== TOK_LINEFEED
) {
3455 pp_line(s1
, file
, 0);
3457 fputs(" ", s1
->ppfp
), --spcs
;
3460 } else if (tok
== TOK_LINEFEED
) {
3465 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);