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 CString cstr_buf
;
284 /* first time preallocate static cstr_buf, next time only reset position to start */
285 if (!cstr_buf
.data_allocated
)
286 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
294 /* XXX: not quite exact, but only useful for testing */
295 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
299 /* XXX: not quite exact, but only useful for testing */
301 sprintf(p
, "%u", (unsigned)cv
->i
);
303 sprintf(p
, "%llu", (unsigned long long)cv
->i
);
307 cstr_ccat(&cstr_buf
, 'L');
309 cstr_ccat(&cstr_buf
, '\'');
310 add_char(&cstr_buf
, cv
->i
);
311 cstr_ccat(&cstr_buf
, '\'');
312 cstr_ccat(&cstr_buf
, '\0');
316 return (char*)cv
->str
.data
;
318 cstr_ccat(&cstr_buf
, 'L');
320 cstr_ccat(&cstr_buf
, '\"');
322 len
= cv
->str
.size
- 1;
324 add_char(&cstr_buf
, ((unsigned char *)cv
->str
.data
)[i
]);
326 len
= (cv
->str
.size
/ sizeof(nwchar_t
)) - 1;
328 add_char(&cstr_buf
, ((nwchar_t
*)cv
->str
.data
)[i
]);
330 cstr_ccat(&cstr_buf
, '\"');
331 cstr_ccat(&cstr_buf
, '\0');
335 cstr_cat(&cstr_buf
, "<float>");
336 cstr_ccat(&cstr_buf
, '\0');
339 cstr_cat(&cstr_buf
, "<double>");
340 cstr_ccat(&cstr_buf
, '\0');
343 cstr_cat(&cstr_buf
, "<long double>");
344 cstr_ccat(&cstr_buf
, '\0');
347 cstr_cat(&cstr_buf
, "<linenumber>");
348 cstr_ccat(&cstr_buf
, '\0');
351 /* above tokens have value, the ones below don't */
360 return strcpy(p
, "...");
362 return strcpy(p
, "<<=");
364 return strcpy(p
, ">>=");
367 /* search in two bytes table */
368 const unsigned char *q
= tok_two_chars
;
374 return cstr_buf
.data
;
379 sprintf(cstr_buf
.data
, "<%02x>", v
);
380 return cstr_buf
.data
;
385 } else if (v
< tok_ident
) {
386 return table_ident
[v
- TOK_IDENT
]->str
;
387 } else if (v
>= SYM_FIRST_ANOM
) {
388 /* special name for anonymous symbol */
389 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
391 /* should never happen */
396 return cstr_buf
.data
;
399 /* return the current character, handling end of block if necessary
401 ST_FUNC
int handle_eob(void)
403 BufferedFile
*bf
= file
;
406 /* only tries to read if really end of buffer */
407 if (bf
->buf_ptr
>= bf
->buf_end
) {
409 #if defined(PARSE_DEBUG)
414 len
= read(bf
->fd
, bf
->buffer
, len
);
421 bf
->buf_ptr
= bf
->buffer
;
422 bf
->buf_end
= bf
->buffer
+ len
;
423 *bf
->buf_end
= CH_EOB
;
425 if (bf
->buf_ptr
< bf
->buf_end
) {
426 return bf
->buf_ptr
[0];
428 bf
->buf_ptr
= bf
->buf_end
;
433 /* read next char from current input file and handle end of input buffer */
434 ST_INLN
void inp(void)
436 ch
= *(++(file
->buf_ptr
));
437 /* end of buffer/file handling */
442 /* handle '\[\r]\n' */
443 static int handle_stray_noerror(void)
450 } else if (ch
== '\r') {
464 static void handle_stray(void)
466 if (handle_stray_noerror())
467 tcc_error("stray '\\' in program");
470 /* skip the stray and handle the \\n case. Output an error if
471 incorrect char after the stray */
472 static int handle_stray1(uint8_t *p
)
477 if (p
>= file
->buf_end
) {
484 if (handle_stray_noerror()) {
485 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
486 tcc_error("stray '\\' in program");
487 *--file
->buf_ptr
= '\\';
494 /* handle just the EOB case, but not stray */
495 #define PEEKC_EOB(c, p)\
506 /* handle the complicated stray case */
512 c = handle_stray1(p);\
517 /* input with '\[\r]\n' handling. Note that this function cannot
518 handle other characters after '\', so you cannot call it inside
519 strings or comments */
520 ST_FUNC
void minp(void)
528 /* single line C++ comments */
529 static uint8_t *parse_line_comment(uint8_t *p
)
537 if (c
== '\n' || c
== CH_EOF
) {
539 } else if (c
== '\\') {
548 } else if (c
== '\r') {
566 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
575 if (c
== '\n' || c
== '*' || c
== '\\')
579 if (c
== '\n' || c
== '*' || c
== '\\')
583 /* now we can handle all the cases */
587 } else if (c
== '*') {
593 } else if (c
== '/') {
595 } else if (c
== '\\') {
600 tcc_error("unexpected end of file in comment");
602 /* skip '\[\r]\n', otherwise just skip the stray */
608 } else if (c
== '\r') {
625 /* stray, eob or eof */
630 tcc_error("unexpected end of file in comment");
631 } else if (c
== '\\') {
643 static inline void skip_spaces(void)
645 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
649 static inline int check_space(int t
, int *spc
)
651 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
660 /* parse a string without interpreting escapes */
661 static uint8_t *parse_pp_string(uint8_t *p
,
662 int sep
, CString
*str
)
670 } else if (c
== '\\') {
676 /* XXX: indicate line number of start of string */
677 tcc_error("missing terminating %c character", sep
);
678 } else if (c
== '\\') {
679 /* escape : just skip \[\r]\n */
684 } else if (c
== '\r') {
687 expect("'\n' after '\r'");
690 } else if (c
== CH_EOF
) {
691 goto unterminated_string
;
694 cstr_ccat(str
, '\\');
700 } else if (c
== '\n') {
703 } else if (c
== '\r') {
707 cstr_ccat(str
, '\r');
723 /* skip block of text until #else, #elif or #endif. skip also pairs of
725 static void preprocess_skip(void)
727 int a
, start_of_line
, c
, in_warn_or_error
;
734 in_warn_or_error
= 0;
755 } else if (c
== '\\') {
756 ch
= file
->buf_ptr
[0];
757 handle_stray_noerror();
764 if (in_warn_or_error
)
766 p
= parse_pp_string(p
, c
, NULL
);
770 if (in_warn_or_error
)
777 p
= parse_comment(p
);
778 } else if (ch
== '/') {
779 p
= parse_line_comment(p
);
789 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
791 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
793 else if (tok
== TOK_ENDIF
)
795 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
796 in_warn_or_error
= 1;
797 else if (tok
== TOK_LINEFEED
)
799 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
800 p
= parse_line_comment(p
);
813 /* ParseState handling */
815 /* XXX: currently, no include file info is stored. Thus, we cannot display
816 accurate messages if the function or data definition spans multiple
819 /* save current parse state in 's' */
820 ST_FUNC
void save_parse_state(ParseState
*s
)
822 s
->line_num
= file
->line_num
;
823 s
->macro_ptr
= macro_ptr
;
828 /* restore parse state from 's' */
829 ST_FUNC
void restore_parse_state(ParseState
*s
)
831 file
->line_num
= s
->line_num
;
832 macro_ptr
= s
->macro_ptr
;
837 /* return the number of additional 'ints' necessary to store the
839 static inline int tok_size(const int *p
)
854 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
860 return 1 + LDOUBLE_SIZE
/ 4;
866 /* token string handling */
868 ST_INLN
void tok_str_new(TokenString
*s
)
872 s
->allocated_len
= 0;
873 s
->last_line_num
= -1;
876 ST_FUNC
void tok_str_free(int *str
)
881 static int *tok_str_realloc(TokenString
*s
)
885 if (s
->allocated_len
== 0) {
888 len
= s
->allocated_len
* 2;
890 str
= tcc_realloc(s
->str
, len
* sizeof(int));
891 s
->allocated_len
= len
;
896 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
902 if (len
>= s
->allocated_len
)
903 str
= tok_str_realloc(s
);
908 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
915 /* allocate space for worst case */
916 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
917 str
= tok_str_realloc(s
);
926 str
[len
++] = cv
->tab
[0];
933 /* Insert the string into the int array. */
935 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
936 while ((len
+ nb_words
) > s
->allocated_len
)
937 str
= tok_str_realloc(s
);
938 str
[len
] = cv
->str
.size
;
939 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
946 #if LDOUBLE_SIZE == 8
949 str
[len
++] = cv
->tab
[0];
950 str
[len
++] = cv
->tab
[1];
952 #if LDOUBLE_SIZE == 12
954 str
[len
++] = cv
->tab
[0];
955 str
[len
++] = cv
->tab
[1];
956 str
[len
++] = cv
->tab
[2];
957 #elif LDOUBLE_SIZE == 16
959 str
[len
++] = cv
->tab
[0];
960 str
[len
++] = cv
->tab
[1];
961 str
[len
++] = cv
->tab
[2];
962 str
[len
++] = cv
->tab
[3];
963 #elif LDOUBLE_SIZE != 8
964 #error add long double size support
973 /* add the current parse token in token string 's' */
974 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
978 /* save line number info */
979 if (file
->line_num
!= s
->last_line_num
) {
980 s
->last_line_num
= file
->line_num
;
981 cval
.i
= s
->last_line_num
;
982 tok_str_add2(s
, TOK_LINENUM
, &cval
);
984 tok_str_add2(s
, tok
, &tokc
);
987 /* get a token from an integer array and increment pointer
988 accordingly. we code it as a macro to avoid pointer aliasing. */
989 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1008 cv
->str
.size
= *p
++;
1010 cv
->str
.data_allocated
= 0;
1011 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1019 #if LDOUBLE_SIZE == 16
1021 #elif LDOUBLE_SIZE == 12
1023 #elif LDOUBLE_SIZE == 8
1026 # error add long double size support
1039 /* Calling this function is expensive, but it is not possible
1040 to read a token string backwards. */
1041 static int tok_last(const int *str0
, const int *str1
)
1043 const int *str
= str0
;
1048 TOK_GET(&tok
, &str
, &cval
);
1052 static int macro_is_equal(const int *a
, const int *b
)
1054 static CString cstr_buf
;
1058 /* first time preallocate static cstr_buf, next time only reset position to start */
1059 if (!cstr_buf
.data_allocated
)
1060 cstr_realloc(&cstr_buf
, STRING_MAX_SIZE
);
1063 TOK_GET(&t
, &a
, &cv
);
1064 cstr_cat(&cstr_buf
, get_tok_str(t
, &cv
));
1065 cstr_ccat(&cstr_buf
, '\0');
1066 TOK_GET(&t
, &b
, &cv
);
1067 if (strcmp(cstr_buf
.data
, get_tok_str(t
, &cv
)))
1073 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
1075 int d
= f
->line_num
- f
->line_ref
;
1076 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
1077 || (level
== 0 && f
->line_ref
&& d
< 8))
1080 fputs("\n", s1
->ppfp
), --d
;
1083 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
1084 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
1087 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
1088 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
1090 f
->line_ref
= f
->line_num
;
1093 static void tok_print(const char *msg
, const int *str
)
1095 FILE *pr
= tcc_state
->ppfp
;
1099 fprintf(pr
, "%s ", msg
);
1101 TOK_GET(&t
, &str
, &cval
);
1104 fprintf(pr
,"%s", get_tok_str(t
, &cval
));
1109 static int define_print_prepared(Sym
*s
)
1111 if (!s
|| !tcc_state
->ppfp
|| tcc_state
->dflag
== 0)
1114 if (s
->v
< TOK_IDENT
|| s
->v
>= tok_ident
)
1119 pp_line(tcc_state
, file
, 0);
1120 file
->line_ref
= ++file
->line_num
;
1125 static void define_print(int v
)
1127 FILE *pr
= tcc_state
->ppfp
;
1131 if (define_print_prepared(s
) == 0)
1134 fprintf(pr
, "// #define %s", get_tok_str(v
, NULL
));
1135 if (s
->type
.t
== MACRO_FUNC
) {
1140 fprintf(pr
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
1147 tok_print("", s
->d
);
1150 static void undef_print(int v
)
1152 FILE *pr
= tcc_state
->ppfp
;
1156 if (define_print_prepared(s
) == 0)
1159 fprintf(pr
, "// #undef %s\n", get_tok_str(s
->v
, NULL
));
1162 ST_FUNC
void print_defines(void)
1164 Sym
*top
= define_stack
;
1166 define_print(top
->v
);
1171 /* defines handling */
1172 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1177 if (s
&& !macro_is_equal(s
->d
, str
))
1178 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1180 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1182 s
->next
= first_arg
;
1183 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1186 /* undefined a define symbol. Its name is just set to zero */
1187 ST_FUNC
void define_undef(Sym
*s
)
1191 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1192 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1195 ST_INLN Sym
*define_find(int v
)
1198 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1200 return table_ident
[v
]->sym_define
;
1203 /* free define stack until top reaches 'b' */
1204 ST_FUNC
void free_defines(Sym
*b
)
1212 /* do not free args or predefined defines */
1214 tok_str_free(top
->d
);
1216 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1217 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1225 ST_FUNC Sym
*label_find(int v
)
1228 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1230 return table_ident
[v
]->sym_label
;
1233 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1236 s
= sym_push2(ptop
, v
, 0, 0);
1238 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1239 if (ptop
== &global_label_stack
) {
1240 /* modify the top most local identifier, so that
1241 sym_identifier will point to 's' when popped */
1243 ps
= &(*ps
)->prev_tok
;
1250 /* pop labels until element last is reached. Look if any labels are
1251 undefined. Define symbols if '&&label' was used. */
1252 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1255 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1257 if (s
->r
== LABEL_DECLARED
) {
1258 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1259 } else if (s
->r
== LABEL_FORWARD
) {
1260 tcc_error("label '%s' used but not defined",
1261 get_tok_str(s
->v
, NULL
));
1264 /* define corresponding symbol. A size of
1266 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1270 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1276 /* eval an expression for #if/#elif */
1277 static int expr_preprocess(void)
1283 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1284 next(); /* do macro subst */
1285 if (tok
== TOK_DEFINED
) {
1290 c
= define_find(tok
) != 0;
1295 } else if (tok
>= TOK_IDENT
) {
1296 /* if undefined macro */
1300 tok_str_add_tok(&str
);
1302 tok_str_add(&str
, -1); /* simulate end of file */
1303 tok_str_add(&str
, 0);
1304 /* now evaluate C constant expression */
1305 begin_macro(&str
, 0);
1313 /* parse after #define */
1314 ST_FUNC
void parse_define(void)
1316 Sym
*s
, *first
, **ps
;
1317 int v
, t
, varg
, is_vaargs
, spc
;
1318 int saved_parse_flags
= parse_flags
;
1323 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1324 /* XXX: should check if same macro (ANSI) */
1327 /* '(' must be just after macro definition for MACRO_FUNC */
1328 parse_flags
|= PARSE_FLAG_SPACES
;
1333 if (tok
!= ')') for (;;) {
1337 if (varg
== TOK_DOTS
) {
1338 varg
= TOK___VA_ARGS__
;
1340 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1344 if (varg
< TOK_IDENT
)
1346 tcc_error("bad macro parameter list");
1347 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1352 if (tok
!= ',' || is_vaargs
)
1361 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1362 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1363 /* remove spaces around ## and after '#' */
1364 if (TOK_TWOSHARPS
== tok
) {
1370 } else if ('#' == tok
) {
1372 } else if (check_space(tok
, &spc
)) {
1375 tok_str_add2(&str
, tok
, &tokc
);
1380 parse_flags
= saved_parse_flags
;
1382 --str
.len
; /* remove trailing space */
1383 tok_str_add(&str
, 0);
1386 tcc_error("'##' cannot appear at either end of macro");
1387 define_push(v
, t
, str
.str
, first
);
1391 static inline int hash_cached_include(const char *filename
)
1393 const unsigned char *s
;
1397 s
= (unsigned char *) filename
;
1399 h
= TOK_HASH_FUNC(h
, *s
);
1402 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1406 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1410 h
= hash_cached_include(filename
);
1411 i
= s1
->cached_includes_hash
[h
];
1415 e
= s1
->cached_includes
[i
- 1];
1416 if (0 == PATHCMP(e
->filename
, filename
))
1423 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1428 if (search_cached_include(s1
, filename
))
1431 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1433 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1434 strcpy(e
->filename
, filename
);
1435 e
->ifndef_macro
= ifndef_macro
;
1436 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1437 /* add in hash table */
1438 h
= hash_cached_include(filename
);
1439 e
->hash_next
= s1
->cached_includes_hash
[h
];
1440 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1443 static void pragma_parse(TCCState
*s1
)
1446 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1450 if (next(), tok
!= '(')
1452 if (next(), tok
!= TOK_STR
)
1454 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1455 if (next(), tok
!= ')')
1457 if (t
== TOK_push_macro
) {
1458 while (NULL
== (s
= define_find(v
)))
1459 define_push(v
, 0, NULL
, NULL
);
1460 s
->type
.ref
= s
; /* set push boundary */
1462 for (s
= define_stack
; s
; s
= s
->prev
)
1463 if (s
->v
== v
&& s
->type
.ref
== s
) {
1469 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1471 tcc_warning("unbalanced #pragma pop_macro");
1473 } else if (tok
== TOK_once
) {
1474 add_cached_include(s1
, file
->filename
, TOK_once
);
1476 } else if (s1
->ppfp
) {
1477 /* tcc -E: keep pragmas below unchanged */
1479 unget_tok(TOK_PRAGMA
);
1481 unget_tok(TOK_LINEFEED
);
1483 } else if (tok
== TOK_pack
) {
1485 #pragma pack(1) // set
1486 #pragma pack() // reset to default
1487 #pragma pack(push,1) // push & set
1488 #pragma pack(pop) // restore previous */
1491 if (tok
== TOK_ASM_pop
) {
1493 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1495 tcc_error("out of pack stack");
1497 s1
->pack_stack_ptr
--;
1501 if (tok
== TOK_ASM_push
) {
1503 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1505 s1
->pack_stack_ptr
++;
1508 if (tok
!= TOK_CINT
)
1511 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1515 *s1
->pack_stack_ptr
= val
;
1520 } else if (tok
== TOK_comment
) {
1530 file
= tcc_strdup((char *)tokc
.str
.data
);
1531 dynarray_add((void ***)&s1
->pragma_libs
, &s1
->nb_pragma_libs
, file
);
1537 if (s1
->warn_unsupported
)
1538 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1543 tcc_error("malformed #pragma directive");
1547 /* is_bof is true if first non space token at beginning of file */
1548 ST_FUNC
void preprocess(int is_bof
)
1550 TCCState
*s1
= tcc_state
;
1551 int i
, c
, n
, saved_parse_flags
;
1555 saved_parse_flags
= parse_flags
;
1556 parse_flags
= PARSE_FLAG_PREPROCESS
1557 | PARSE_FLAG_TOK_NUM
1558 | PARSE_FLAG_TOK_STR
1559 | PARSE_FLAG_LINEFEED
1560 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1572 s
= define_find(tok
);
1573 /* undefine symbol by putting an invalid name */
1578 case TOK_INCLUDE_NEXT
:
1579 ch
= file
->buf_ptr
[0];
1580 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1585 } else if (ch
== '\"') {
1590 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1591 if ((q
- buf
) < sizeof(buf
) - 1)
1594 if (handle_stray_noerror() == 0)
1602 /* eat all spaces and comments after include */
1603 /* XXX: slightly incorrect */
1604 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1608 /* computed #include : either we have only strings or
1609 we have anything enclosed in '<>' */
1612 if (tok
== TOK_STR
) {
1613 while (tok
!= TOK_LINEFEED
) {
1614 if (tok
!= TOK_STR
) {
1616 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1618 pstrcat(buf
, sizeof(buf
), (char *)tokc
.str
.data
);
1624 while (tok
!= TOK_LINEFEED
) {
1625 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1629 /* check syntax and remove '<>' */
1630 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1631 goto include_syntax
;
1632 memmove(buf
, buf
+ 1, len
- 2);
1633 buf
[len
- 2] = '\0';
1638 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1639 tcc_error("#include recursion too deep");
1640 /* store current file in stack, but increment stack later below */
1641 *s1
->include_stack_ptr
= file
;
1642 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
: 0;
1643 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1644 for (; i
< n
; ++i
) {
1645 char buf1
[sizeof file
->filename
];
1650 /* check absolute include path */
1651 if (!IS_ABSPATH(buf
))
1655 } else if (i
== 1) {
1656 /* search in current dir if "header.h" */
1659 path
= file
->filename
;
1660 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1663 /* search in all the include paths */
1664 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1665 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1666 pstrcpy(buf1
, sizeof(buf1
), path
);
1667 pstrcat(buf1
, sizeof(buf1
), "/");
1670 pstrcat(buf1
, sizeof(buf1
), buf
);
1671 e
= search_cached_include(s1
, buf1
);
1672 if (e
&& (define_find(e
->ifndef_macro
) || e
->ifndef_macro
== TOK_once
)) {
1673 /* no need to parse the include because the 'ifndef macro'
1676 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1681 if (tcc_open(s1
, buf1
) < 0)
1684 file
->include_next_index
= i
+ 1;
1686 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1688 /* update target deps */
1689 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1691 /* push current file in stack */
1692 ++s1
->include_stack_ptr
;
1693 /* add include file debug info */
1695 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1696 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1697 ch
= file
->buf_ptr
[0];
1700 tcc_error("include file '%s' not found", buf
);
1707 c
= expr_preprocess();
1713 if (tok
< TOK_IDENT
)
1714 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1718 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1720 file
->ifndef_macro
= tok
;
1723 c
= (define_find(tok
) != 0) ^ c
;
1725 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1726 tcc_error("memory full (ifdef)");
1727 *s1
->ifdef_stack_ptr
++ = c
;
1730 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1731 tcc_error("#else without matching #if");
1732 if (s1
->ifdef_stack_ptr
[-1] & 2)
1733 tcc_error("#else after #else");
1734 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1737 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1738 tcc_error("#elif without matching #if");
1739 c
= s1
->ifdef_stack_ptr
[-1];
1741 tcc_error("#elif after #else");
1742 /* last #if/#elif expression was true: we skip */
1745 c
= expr_preprocess();
1746 s1
->ifdef_stack_ptr
[-1] = c
;
1748 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1749 file
->ifndef_macro
= 0;
1759 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1760 tcc_error("#endif without matching #if");
1761 s1
->ifdef_stack_ptr
--;
1762 /* '#ifndef macro' was at the start of file. Now we check if
1763 an '#endif' is exactly at the end of file */
1764 if (file
->ifndef_macro
&&
1765 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1766 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1767 /* need to set to zero to avoid false matches if another
1768 #ifndef at middle of file */
1769 file
->ifndef_macro
= 0;
1770 while (tok
!= TOK_LINEFEED
)
1772 tok_flags
|= TOK_FLAG_ENDIF
;
1777 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1781 if (tok
!= TOK_CINT
)
1783 tcc_error("wrong #line format");
1787 if (tok
!= TOK_LINEFEED
) {
1789 pstrcpy(file
->filename
, sizeof(file
->filename
), (char *)tokc
.str
.data
);
1790 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1797 total_lines
+= file
->line_num
- n
;
1800 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1805 ch
= file
->buf_ptr
[0];
1808 while (ch
!= '\n' && ch
!= CH_EOF
) {
1809 if ((q
- buf
) < sizeof(buf
) - 1)
1812 if (handle_stray_noerror() == 0)
1819 tcc_error("#error %s", buf
);
1821 tcc_warning("#warning %s", buf
);
1829 /* ignore gas line comment in an 'S' file. */
1830 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
1832 if (tok
== '!' && is_bof
)
1833 /* '!' is ignored at beginning to allow C scripts. */
1835 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1837 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1840 /* ignore other preprocess commands or #! for C scripts */
1841 while (tok
!= TOK_LINEFEED
)
1844 parse_flags
= saved_parse_flags
;
1847 /* evaluate escape codes in a string. */
1848 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1863 case '0': case '1': case '2': case '3':
1864 case '4': case '5': case '6': case '7':
1865 /* at most three octal digits */
1870 n
= n
* 8 + c
- '0';
1874 n
= n
* 8 + c
- '0';
1879 goto add_char_nonext
;
1887 if (c
>= 'a' && c
<= 'f')
1889 else if (c
>= 'A' && c
<= 'F')
1899 goto add_char_nonext
;
1923 goto invalid_escape
;
1933 if (c
>= '!' && c
<= '~')
1934 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1936 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1943 cstr_ccat(outstr
, c
);
1945 cstr_wccat(outstr
, c
);
1947 /* add a trailing '\0' */
1949 cstr_ccat(outstr
, '\0');
1951 cstr_wccat(outstr
, '\0');
1954 void parse_string(const char *s
, int len
)
1956 uint8_t buf
[1000], *p
= buf
;
1959 if ((is_long
= *s
== 'L'))
1963 if (len
>= sizeof buf
)
1964 p
= tcc_malloc(len
+ 1);
1968 cstr_reset(&tokcstr
);
1969 parse_escape_string(&tokcstr
, p
, is_long
);
1975 /* XXX: make it portable */
1979 char_size
= sizeof(nwchar_t
);
1980 if (tokcstr
.size
<= char_size
)
1981 tcc_error("empty character constant");
1982 if (tokcstr
.size
> 2 * char_size
)
1983 tcc_warning("multi-character character constant");
1985 tokc
.i
= *(int8_t *)tokcstr
.data
;
1988 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
1992 tokc
.str
.size
= tokcstr
.size
;
1993 tokc
.str
.data
= tokcstr
.data
;
1994 tokc
.str
.data_allocated
= tokcstr
.data_allocated
;
2002 /* we use 64 bit numbers */
2005 /* bn = (bn << shift) | or_val */
2006 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2010 for(i
=0;i
<BN_SIZE
;i
++) {
2012 bn
[i
] = (v
<< shift
) | or_val
;
2013 or_val
= v
>> (32 - shift
);
2017 static void bn_zero(unsigned int *bn
)
2020 for(i
=0;i
<BN_SIZE
;i
++) {
2025 /* parse number in null terminated string 'p' and return it in the
2027 static void parse_number(const char *p
)
2029 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2031 unsigned int bn
[BN_SIZE
];
2042 goto float_frac_parse
;
2043 } else if (t
== '0') {
2044 if (ch
== 'x' || ch
== 'X') {
2048 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2054 /* parse all digits. cannot check octal numbers at this stage
2055 because of floating point constants */
2057 if (ch
>= 'a' && ch
<= 'f')
2059 else if (ch
>= 'A' && ch
<= 'F')
2067 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2069 tcc_error("number too long");
2075 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2076 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2078 /* NOTE: strtox should support that for hexa numbers, but
2079 non ISOC99 libcs do not support it, so we prefer to do
2081 /* hexadecimal or binary floats */
2082 /* XXX: handle overflows */
2094 } else if (t
>= 'a') {
2096 } else if (t
>= 'A') {
2101 bn_lshift(bn
, shift
, t
);
2108 if (t
>= 'a' && t
<= 'f') {
2110 } else if (t
>= 'A' && t
<= 'F') {
2112 } else if (t
>= '0' && t
<= '9') {
2118 tcc_error("invalid digit");
2119 bn_lshift(bn
, shift
, t
);
2124 if (ch
!= 'p' && ch
!= 'P')
2131 } else if (ch
== '-') {
2135 if (ch
< '0' || ch
> '9')
2136 expect("exponent digits");
2137 while (ch
>= '0' && ch
<= '9') {
2138 exp_val
= exp_val
* 10 + ch
- '0';
2141 exp_val
= exp_val
* s
;
2143 /* now we can generate the number */
2144 /* XXX: should patch directly float number */
2145 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2146 d
= ldexp(d
, exp_val
- frac_bits
);
2151 /* float : should handle overflow */
2153 } else if (t
== 'L') {
2155 #ifdef TCC_TARGET_PE
2160 /* XXX: not large enough */
2161 tokc
.ld
= (long double)d
;
2168 /* decimal floats */
2170 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2175 while (ch
>= '0' && ch
<= '9') {
2176 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2182 if (ch
== 'e' || ch
== 'E') {
2183 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2187 if (ch
== '-' || ch
== '+') {
2188 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2193 if (ch
< '0' || ch
> '9')
2194 expect("exponent digits");
2195 while (ch
>= '0' && ch
<= '9') {
2196 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2208 tokc
.f
= strtof(token_buf
, NULL
);
2209 } else if (t
== 'L') {
2211 #ifdef TCC_TARGET_PE
2213 tokc
.d
= strtod(token_buf
, NULL
);
2216 tokc
.ld
= strtold(token_buf
, NULL
);
2220 tokc
.d
= strtod(token_buf
, NULL
);
2224 unsigned long long n
, n1
;
2225 int lcount
, ucount
, must_64bit
;
2228 /* integer number */
2231 if (b
== 10 && *q
== '0') {
2238 /* no need for checks except for base 10 / 8 errors */
2248 tcc_error("invalid digit");
2251 /* detect overflow */
2252 /* XXX: this test is not reliable */
2254 tcc_error("integer constant overflow");
2257 /* Determine the characteristics (unsigned and/or 64bit) the type of
2258 the constant must have according to the constant suffix(es) */
2259 lcount
= ucount
= must_64bit
= 0;
2265 tcc_error("three 'l's in integer constant");
2266 if (lcount
&& *(p
- 1) != ch
)
2267 tcc_error("incorrect integer suffix: %s", p1
);
2269 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2274 } else if (t
== 'U') {
2276 tcc_error("two 'u's in integer constant");
2284 /* Whether 64 bits are needed to hold the constant's value */
2285 if (n
& 0xffffffff00000000LL
|| must_64bit
) {
2293 /* Whether type must be unsigned to hold the constant's value */
2294 if (ucount
|| ((n1
>> 31) && (b
!= 10))) {
2295 if (tok
== TOK_CLLONG
)
2299 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2300 } else if (n1
>> 31) {
2301 if (tok
== TOK_CINT
)
2304 tcc_error("integer constant overflow");
2307 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2313 tcc_error("invalid number\n");
2317 #define PARSE2(c1, tok1, c2, tok2) \
2328 /* return next token without macro substitution */
2329 static inline void next_nomacro1(void)
2344 if (parse_flags
& PARSE_FLAG_SPACES
)
2345 goto keep_tok_flags
;
2346 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2355 /* first look if it is in fact an end of buffer */
2356 c
= handle_stray1(p
);
2363 TCCState
*s1
= tcc_state
;
2364 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2365 && !(tok_flags
& TOK_FLAG_EOF
)) {
2366 tok_flags
|= TOK_FLAG_EOF
;
2368 goto keep_tok_flags
;
2369 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2371 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2372 tcc_error("missing #endif");
2373 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2374 /* no include left : end of file. */
2377 tok_flags
&= ~TOK_FLAG_EOF
;
2378 /* pop include file */
2380 /* test if previous '#endif' was after a #ifdef at
2382 if (tok_flags
& TOK_FLAG_ENDIF
) {
2384 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2386 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2387 tok_flags
&= ~TOK_FLAG_ENDIF
;
2390 /* add end of include file debug info */
2391 if (tcc_state
->do_debug
) {
2392 put_stabd(N_EINCL
, 0, 0);
2394 /* pop include stack */
2396 s1
->include_stack_ptr
--;
2405 tok_flags
|= TOK_FLAG_BOL
;
2408 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2411 goto keep_tok_flags
;
2416 if ((tok_flags
& TOK_FLAG_BOL
) &&
2417 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2419 preprocess(tok_flags
& TOK_FLAG_BOF
);
2425 tok
= TOK_TWOSHARPS
;
2427 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2428 p
= parse_line_comment(p
- 1);
2437 /* dollar is allowed to start identifiers when not parsing asm */
2439 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2440 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2443 case 'a': case 'b': case 'c': case 'd':
2444 case 'e': case 'f': case 'g': case 'h':
2445 case 'i': case 'j': case 'k': case 'l':
2446 case 'm': case 'n': case 'o': case 'p':
2447 case 'q': case 'r': case 's': case 't':
2448 case 'u': case 'v': case 'w': case 'x':
2450 case 'A': case 'B': case 'C': case 'D':
2451 case 'E': case 'F': case 'G': case 'H':
2452 case 'I': case 'J': case 'K':
2453 case 'M': case 'N': case 'O': case 'P':
2454 case 'Q': case 'R': case 'S': case 'T':
2455 case 'U': case 'V': case 'W': case 'X':
2461 h
= TOK_HASH_FUNC(h
, c
);
2462 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2463 h
= TOK_HASH_FUNC(h
, c
);
2468 /* fast case : no stray found, so we have the full token
2469 and we have already hashed it */
2471 h
&= (TOK_HASH_SIZE
- 1);
2472 pts
= &hash_ident
[h
];
2477 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2479 pts
= &(ts
->hash_next
);
2481 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2485 cstr_reset(&tokcstr
);
2488 cstr_ccat(&tokcstr
, *p1
);
2494 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
)) {
2495 cstr_ccat(&tokcstr
, c
);
2498 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2504 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2506 goto parse_ident_fast
;
2509 if (c
== '\'' || c
== '\"') {
2513 cstr_reset(&tokcstr
);
2514 cstr_ccat(&tokcstr
, 'L');
2515 goto parse_ident_slow
;
2520 case '0': case '1': case '2': case '3':
2521 case '4': case '5': case '6': case '7':
2523 cstr_reset(&tokcstr
);
2524 /* after the first digit, accept digits, alpha, '.' or sign if
2525 prefixed by 'eEpP' */
2529 cstr_ccat(&tokcstr
, c
);
2531 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2533 || ((c
== '+' || c
== '-')
2534 && (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P')
2538 /* We add a trailing '\0' to ease parsing */
2539 cstr_ccat(&tokcstr
, '\0');
2540 tokc
.str
.size
= tokcstr
.size
;
2541 tokc
.str
.data
= tokcstr
.data
;
2542 tokc
.str
.data_allocated
= tokcstr
.data_allocated
;
2547 /* special dot handling because it can also start a number */
2550 cstr_reset(&tokcstr
);
2551 cstr_ccat(&tokcstr
, '.');
2553 } else if (c
== '.') {
2559 *--p
= '.'; /* may underflow into file->unget[] */
2570 cstr_reset(&tokcstr
);
2572 cstr_ccat(&tokcstr
, 'L');
2573 cstr_ccat(&tokcstr
, c
);
2574 p
= parse_pp_string(p
, c
, &tokcstr
);
2575 cstr_ccat(&tokcstr
, c
);
2576 cstr_ccat(&tokcstr
, '\0');
2577 tokc
.str
.size
= tokcstr
.size
;
2578 tokc
.str
.data
= tokcstr
.data
;
2579 tokc
.str
.data_allocated
= tokcstr
.data_allocated
;
2588 } else if (c
== '<') {
2605 } else if (c
== '>') {
2623 } else if (c
== '=') {
2636 } else if (c
== '=') {
2649 } else if (c
== '=') {
2662 } else if (c
== '=') {
2665 } else if (c
== '>') {
2673 PARSE2('!', '!', '=', TOK_NE
)
2674 PARSE2('=', '=', '=', TOK_EQ
)
2675 PARSE2('*', '*', '=', TOK_A_MUL
)
2676 PARSE2('%', '%', '=', TOK_A_MOD
)
2677 PARSE2('^', '^', '=', TOK_A_XOR
)
2679 /* comments or operator */
2683 p
= parse_comment(p
);
2684 /* comments replaced by a blank */
2686 goto keep_tok_flags
;
2687 } else if (c
== '/') {
2688 p
= parse_line_comment(p
);
2690 goto keep_tok_flags
;
2691 } else if (c
== '=') {
2711 case '@': /* only used in assembler */
2717 tcc_error("unrecognized character \\x%02x", c
);
2723 #if defined(PARSE_DEBUG)
2724 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2728 /* return next token without macro substitution. Can read input from
2730 static void next_nomacro_spc(void)
2736 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2737 if (tok
== TOK_LINENUM
) {
2738 file
->line_num
= tokc
.i
;
2747 ST_FUNC
void next_nomacro(void)
2751 } while (tok
< 256 && (isidnum_table
[tok
- CH_EOF
] & IS_SPC
));
2755 static void macro_subst(
2756 TokenString
*tok_str
,
2758 const int *macro_str
,
2762 /* substitute arguments in replacement lists in macro_str by the values in
2763 args (field d) and return allocated string */
2764 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2776 TOK_GET(&t
, ¯o_str
, &cval
);
2781 TOK_GET(&t
, ¯o_str
, &cval
);
2784 s
= sym_find2(args
, t
);
2787 cstr_ccat(&cstr
, '\"');
2791 TOK_GET(&t
, &st
, &cval
);
2792 if (t
!= TOK_PLCHLDR
2794 && 0 == check_space(t
, &spc
)) {
2795 const char *s
= get_tok_str(t
, &cval
);
2797 if (/*t == TOK_PPSTR &&*/ *s
!= '\'')
2798 add_char(&cstr
, *s
);
2800 cstr_ccat(&cstr
, *s
);
2806 cstr_ccat(&cstr
, '\"');
2807 cstr_ccat(&cstr
, '\0');
2809 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
2812 cval
.str
.size
= cstr
.size
;
2813 cval
.str
.data
= cstr
.data
;
2814 cval
.str
.data_allocated
= cstr
.data_allocated
;
2815 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
2816 tcc_free(cval
.str
.data_allocated
);
2819 expect("macro parameter after '#'");
2821 } else if (t
>= TOK_IDENT
) {
2822 s
= sym_find2(args
, t
);
2826 /* if '##' is present before or after, no arg substitution */
2827 if (*macro_str
== TOK_TWOSHARPS
|| t1
== TOK_TWOSHARPS
) {
2828 /* special case for var arg macros : ## eats the ','
2829 if empty VA_ARGS variable. */
2830 if (t1
== TOK_TWOSHARPS
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
2832 /* suppress ',' '##' */
2835 /* suppress '##' and add variable */
2842 TOK_GET(&t1
, &st
, &cval
);
2845 tok_str_add2(&str
, t1
, &cval
);
2851 /* NOTE: the stream cannot be read when macro
2852 substituing an argument */
2853 macro_subst(&str
, nested_list
, st
, 0);
2855 if (str
.len
== l0
) /* exanded to empty string */
2856 tok_str_add(&str
, TOK_PLCHLDR
);
2858 tok_str_add(&str
, t
);
2861 tok_str_add2(&str
, t
, &cval
);
2865 tok_str_add(&str
, 0);
2869 static char const ab_month_name
[12][4] =
2871 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2872 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2875 /* peek or read [ws_str == NULL] next token from function macro call,
2876 walking up macro levels up to the file if necessary */
2877 static int next_argstream(Sym
**nested_list
, int can_read_stream
, TokenString
*ws_str
)
2885 p
= macro_ptr
, t
= *p
;
2887 while (is_space(t
) || TOK_LINEFEED
== t
)
2888 tok_str_add(ws_str
, t
), t
= *++p
;
2890 if (t
== 0 && can_read_stream
) {
2892 /* also, end of scope for nested defined symbol */
2894 while (sa
&& sa
->v
== -1)
2903 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
2906 uint8_t *p
= file
->buf_ptr
;
2909 p
= parse_comment(p
);
2910 file
->buf_ptr
= p
- 1;
2911 } else if (c
== '/') {
2912 p
= parse_line_comment(p
);
2913 file
->buf_ptr
= p
- 1;
2918 tok_str_add(ws_str
, ch
);
2932 /* do macro substitution of current token with macro 's' and add
2933 result to (tok_str,tok_len). 'nested_list' is the list of all
2934 macros we got inside to avoid recursing. Return non zero if no
2935 substitution needs to be done */
2936 static int macro_subst_tok(
2937 TokenString
*tok_str
,
2940 int can_read_stream
)
2942 Sym
*args
, *sa
, *sa1
;
2943 int parlevel
, *mstr
, t
, t1
, spc
;
2950 /* if symbol is a macro, prepare substitution */
2951 /* special macros */
2952 if (tok
== TOK___LINE__
) {
2953 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2957 } else if (tok
== TOK___FILE__
) {
2958 cstrval
= file
->filename
;
2960 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2965 tm
= localtime(&ti
);
2966 if (tok
== TOK___DATE__
) {
2967 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2968 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2970 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2971 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2978 cstr_cat(&cstr
, cstrval
);
2979 cstr_ccat(&cstr
, '\0');
2980 cval
.str
.size
= cstr
.size
;
2981 cval
.str
.data
= cstr
.data
;
2982 cval
.str
.data_allocated
= cstr
.data_allocated
;
2983 tok_str_add2(tok_str
, t1
, &cval
);
2986 int saved_parse_flags
= parse_flags
;
2989 if (s
->type
.t
== MACRO_FUNC
) {
2990 /* whitespace between macro name and argument list */
2992 tok_str_new(&ws_str
);
2995 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
2996 | PARSE_FLAG_ACCEPT_STRAYS
;
2998 /* get next token from argument stream */
2999 t
= next_argstream(nested_list
, can_read_stream
, &ws_str
);
3001 /* not a macro substitution after all, restore the
3002 * macro token plus all whitespace we've read.
3003 * whitespace is intentionally not merged to preserve
3005 parse_flags
= saved_parse_flags
;
3006 tok_str_add(tok_str
, tok
);
3007 if (parse_flags
& PARSE_FLAG_SPACES
) {
3009 for (i
= 0; i
< ws_str
.len
; i
++)
3010 tok_str_add(tok_str
, ws_str
.str
[i
]);
3012 tok_str_free(ws_str
.str
);
3015 tok_str_free(ws_str
.str
);
3017 next_nomacro(); /* eat '(' */
3019 /* argument macro */
3022 /* NOTE: empty args are allowed, except if no args */
3025 next_argstream(nested_list
, can_read_stream
, NULL
);
3026 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3028 /* handle '()' case */
3029 if (!args
&& !sa
&& tok
== ')')
3032 tcc_error("macro '%s' used with too many args",
3033 get_tok_str(s
->v
, 0));
3036 /* NOTE: non zero sa->t indicates VA_ARGS */
3037 while ((parlevel
> 0 ||
3039 (tok
!= ',' || sa
->type
.t
)))) {
3040 if (tok
== TOK_EOF
|| tok
== 0)
3044 else if (tok
== ')')
3046 if (tok
== TOK_LINEFEED
)
3048 if (!check_space(tok
, &spc
))
3049 tok_str_add2(&str
, tok
, &tokc
);
3050 next_argstream(nested_list
, can_read_stream
, NULL
);
3055 tok_str_add(&str
, 0);
3056 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3060 /* special case for gcc var args: add an empty
3061 var arg argument if it is omitted */
3062 if (sa
&& sa
->type
.t
&& gnu_ext
)
3070 tcc_error("macro '%s' used with too few args",
3071 get_tok_str(s
->v
, 0));
3074 parse_flags
= saved_parse_flags
;
3076 /* now subst each arg */
3077 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3082 tok_str_free(sa
->d
);
3088 sym_push2(nested_list
, s
->v
, 0, 0);
3089 parse_flags
= saved_parse_flags
;
3090 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
3092 /* pop nested defined symbol */
3094 *nested_list
= sa1
->prev
;
3102 int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3108 if (t1
!= TOK_PLCHLDR
)
3109 cstr_cat(&cstr
, get_tok_str(t1
, v1
));
3111 if (t2
!= TOK_PLCHLDR
)
3112 cstr_cat(&cstr
, get_tok_str(t2
, v2
));
3113 cstr_ccat(&cstr
, '\0');
3115 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3116 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3119 if (0 == *file
->buf_ptr
)
3123 tcc_warning("pasting <%.*s> and <%s> does not give a valid preprocessing token",
3124 n
, cstr
.data
, (char*)cstr
.data
+ n
);
3129 //printf("paste <%s>\n", (char*)cstr.data);
3134 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3135 return the resulting string (which must be freed). */
3136 static inline int *macro_twosharps(const int *ptr0
)
3140 TokenString macro_str1
;
3141 int start_of_nosubsts
= -1;
3144 /* we search the first '##' */
3145 for (ptr
= ptr0
;;) {
3146 TOK_GET(&t
, &ptr
, &cval
);
3147 if (t
== TOK_TWOSHARPS
)
3153 tok_str_new(¯o_str1
);
3155 //tok_print(" $$$", ptr0);
3156 for (ptr
= ptr0
;;) {
3157 TOK_GET(&t
, &ptr
, &cval
);
3160 if (t
== TOK_TWOSHARPS
)
3162 while (*ptr
== TOK_TWOSHARPS
) {
3164 /* given 'a##b', remove nosubsts preceding 'a' */
3165 if (start_of_nosubsts
>= 0)
3166 macro_str1
.len
= start_of_nosubsts
;
3167 /* given 'a##b', remove nosubsts preceding 'b' */
3168 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3170 if (t1
&& t1
!= TOK_TWOSHARPS
3171 && t1
!= ':') /* 'a##:' don't build a new token */
3173 TOK_GET(&t1
, &ptr
, &cv1
);
3174 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3175 paste_tokens(t
, &cval
, t1
, &cv1
);
3176 t
= tok
, cval
= tokc
;
3180 if (t
== TOK_NOSUBST
) {
3181 if (start_of_nosubsts
< 0)
3182 start_of_nosubsts
= macro_str1
.len
;
3184 start_of_nosubsts
= -1;
3186 tok_str_add2(¯o_str1
, t
, &cval
);
3188 tok_str_add(¯o_str1
, 0);
3189 //tok_print(" ###", macro_str1.str);
3190 return macro_str1
.str
;
3193 /* do macro substitution of macro_str and add result to
3194 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3195 inside to avoid recursing. */
3196 static void macro_subst(
3197 TokenString
*tok_str
,
3199 const int *macro_str
,
3205 int t
, spc
, nosubst
;
3207 int *macro_str1
= NULL
;
3209 /* first scan for '##' operator handling */
3213 /* first scan for '##' operator handling */
3214 if (can_read_stream
) {
3215 macro_str1
= macro_twosharps(ptr
);
3221 TOK_GET(&t
, &ptr
, &cval
);
3225 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3230 /* if nested substitution, do nothing */
3231 if (sym_find2(*nested_list
, t
)) {
3232 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3233 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3239 str
.str
= (int*)ptr
;
3240 begin_macro(&str
, 2);
3243 macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
3245 if (str
.alloc
== 3) {
3246 /* already finished by reading function macro arguments */
3254 spc
= (tok_str
->len
&&
3255 is_space(tok_last(tok_str
->str
,
3256 tok_str
->str
+ tok_str
->len
)));
3260 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3261 tcc_error("stray '\\' in program");
3264 if (!check_space(t
, &spc
))
3265 tok_str_add2(tok_str
, t
, &cval
);
3267 if (t
== TOK_NOSUBST
)
3272 tok_str_free(macro_str1
);
3276 /* return next token with macro substitution */
3277 ST_FUNC
void next(void)
3280 if (parse_flags
& PARSE_FLAG_SPACES
)
3286 if (tok
== TOK_NOSUBST
|| tok
== TOK_PLCHLDR
) {
3287 /* discard preprocessor markers */
3289 } else if (tok
== 0) {
3290 /* end of macro or unget token string */
3294 } else if (tok
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3296 /* if reading from file, try to substitute macros */
3297 s
= define_find(tok
);
3299 static TokenString str
; /* using static string for speed */
3300 Sym
*nested_list
= NULL
;
3303 macro_subst_tok(&str
, &nested_list
, s
, 1);
3304 tok_str_add(&str
, 0);
3305 begin_macro(&str
, 0);
3309 /* convert preprocessor tokens into C tokens */
3310 if (tok
== TOK_PPNUM
) {
3311 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3312 parse_number((char *)tokc
.str
.data
);
3313 } else if (tok
== TOK_PPSTR
) {
3314 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3315 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3319 /* push back current token and set current token to 'last_tok'. Only
3320 identifier case handled for labels. */
3321 ST_INLN
void unget_tok(int last_tok
)
3323 TokenString
*str
= tcc_malloc(sizeof *str
);
3325 tok_str_add2(str
, tok
, &tokc
);
3326 tok_str_add(str
, 0);
3327 begin_macro(str
, 1);
3331 /* better than nothing, but needs extension to handle '-E' option
3333 ST_FUNC
void preprocess_init(TCCState
*s1
)
3335 s1
->include_stack_ptr
= s1
->include_stack
;
3336 /* XXX: move that before to avoid having to initialize
3337 file->ifdef_stack_ptr ? */
3338 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3339 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3341 pvtop
= vtop
= vstack
- 1;
3342 s1
->pack_stack
[0] = 0;
3343 s1
->pack_stack_ptr
= s1
->pack_stack
;
3345 isidnum_table
['$' - CH_EOF
] =
3346 tcc_state
->dollars_in_identifiers
? IS_ID
: 0;
3349 ST_FUNC
void preprocess_new(void)
3354 /* init isid table */
3355 for(i
= CH_EOF
; i
<256; i
++)
3356 isidnum_table
[i
- CH_EOF
]
3357 = is_space(i
) ? IS_SPC
3362 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3364 tok_ident
= TOK_IDENT
;
3373 tok_alloc(p
, r
- p
- 1);
3378 ST_FUNC
void preprocess_delete(void)
3382 /* free -D and compiler defines */
3385 /* cleanup from error/setjmp */
3391 n
= tok_ident
- TOK_IDENT
;
3392 for(i
= 0; i
< n
; i
++)
3393 tcc_free(table_ident
[i
]);
3394 tcc_free(table_ident
);
3398 /* Preprocess the current file */
3399 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3401 BufferedFile
**iptr
;
3402 int token_seen
, spcs
, level
;
3404 preprocess_init(s1
);
3405 ch
= file
->buf_ptr
[0];
3406 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3407 parse_flags
= PARSE_FLAG_PREPROCESS
3408 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3409 | PARSE_FLAG_LINEFEED
3411 | PARSE_FLAG_ACCEPT_STRAYS
3415 do next(); while (tok
!= TOK_EOF
); return 0;
3418 token_seen
= spcs
= 0;
3419 pp_line(s1
, file
, 0);
3422 iptr
= s1
->include_stack_ptr
;
3426 level
= s1
->include_stack_ptr
- iptr
;
3429 pp_line(s1
, *iptr
, 0);
3430 pp_line(s1
, file
, level
);
3433 if (0 == token_seen
) {
3438 if (tok
== TOK_LINEFEED
) {
3442 pp_line(s1
, file
, 0);
3444 fputs(" ", s1
->ppfp
), --spcs
;
3447 } else if (tok
== TOK_LINEFEED
) {
3452 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);