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
->dffp
;
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
->dffp
|| tcc_state
->dflag
== 0)
1114 if (s
->v
< TOK_IDENT
|| s
->v
>= tok_ident
)
1117 if (file
&& tcc_state
->dflag
== 'D') {
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
->dffp
;
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
->dffp
;
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
;
1331 /* must be able to parse TOK_DOTS (in asm mode '.' can be part of identifier) */
1332 parse_flags
&= ~PARSE_FLAG_ASM_FILE
;
1333 isidnum_table
['.' - CH_EOF
] = 0;
1336 if (tok
!= ')') for (;;) {
1340 if (varg
== TOK_DOTS
) {
1341 varg
= TOK___VA_ARGS__
;
1343 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1347 if (varg
< TOK_IDENT
)
1349 tcc_error("bad macro parameter list");
1350 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1355 if (tok
!= ',' || is_vaargs
)
1361 parse_flags
|= (saved_parse_flags
& PARSE_FLAG_ASM_FILE
);
1362 isidnum_table
['.' - CH_EOF
] =
1363 (parse_flags
& PARSE_FLAG_ASM_FILE
) ? IS_ID
: 0;
1367 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1368 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1369 /* remove spaces around ## and after '#' */
1370 if (TOK_TWOSHARPS
== tok
) {
1376 } else if ('#' == tok
) {
1378 } else if (check_space(tok
, &spc
)) {
1381 tok_str_add2(&str
, tok
, &tokc
);
1386 parse_flags
= saved_parse_flags
;
1388 --str
.len
; /* remove trailing space */
1389 tok_str_add(&str
, 0);
1392 tcc_error("'##' cannot appear at either end of macro");
1393 define_push(v
, t
, str
.str
, first
);
1397 static inline int hash_cached_include(const char *filename
)
1399 const unsigned char *s
;
1403 s
= (unsigned char *) filename
;
1405 h
= TOK_HASH_FUNC(h
, *s
);
1408 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1412 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1416 h
= hash_cached_include(filename
);
1417 i
= s1
->cached_includes_hash
[h
];
1421 e
= s1
->cached_includes
[i
- 1];
1422 if (0 == PATHCMP(e
->filename
, filename
))
1429 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1434 if (search_cached_include(s1
, filename
))
1437 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1439 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1440 strcpy(e
->filename
, filename
);
1441 e
->ifndef_macro
= ifndef_macro
;
1442 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1443 /* add in hash table */
1444 h
= hash_cached_include(filename
);
1445 e
->hash_next
= s1
->cached_includes_hash
[h
];
1446 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1449 static void pragma_parse(TCCState
*s1
)
1452 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1456 if (next(), tok
!= '(')
1458 if (next(), tok
!= TOK_STR
)
1460 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1461 if (next(), tok
!= ')')
1463 if (t
== TOK_push_macro
) {
1464 while (NULL
== (s
= define_find(v
)))
1465 define_push(v
, 0, NULL
, NULL
);
1466 s
->type
.ref
= s
; /* set push boundary */
1468 for (s
= define_stack
; s
; s
= s
->prev
)
1469 if (s
->v
== v
&& s
->type
.ref
== s
) {
1475 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1477 tcc_warning("unbalanced #pragma pop_macro");
1479 } else if (tok
== TOK_once
) {
1480 add_cached_include(s1
, file
->filename
, TOK_once
);
1482 } else if (s1
->ppfp
) {
1483 /* tcc -E: keep pragmas below unchanged */
1485 unget_tok(TOK_PRAGMA
);
1487 unget_tok(TOK_LINEFEED
);
1489 } else if (tok
== TOK_pack
) {
1491 #pragma pack(1) // set
1492 #pragma pack() // reset to default
1493 #pragma pack(push,1) // push & set
1494 #pragma pack(pop) // restore previous */
1497 if (tok
== TOK_ASM_pop
) {
1499 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1501 tcc_error("out of pack stack");
1503 s1
->pack_stack_ptr
--;
1507 if (tok
== TOK_ASM_push
) {
1509 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1511 s1
->pack_stack_ptr
++;
1514 if (tok
!= TOK_CINT
)
1517 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1521 *s1
->pack_stack_ptr
= val
;
1526 } else if (tok
== TOK_comment
) {
1536 file
= tcc_strdup((char *)tokc
.str
.data
);
1537 dynarray_add((void ***)&s1
->pragma_libs
, &s1
->nb_pragma_libs
, file
);
1543 if (s1
->warn_unsupported
)
1544 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1549 tcc_error("malformed #pragma directive");
1553 /* is_bof is true if first non space token at beginning of file */
1554 ST_FUNC
void preprocess(int is_bof
)
1556 TCCState
*s1
= tcc_state
;
1557 int i
, c
, n
, saved_parse_flags
;
1561 saved_parse_flags
= parse_flags
;
1562 parse_flags
= PARSE_FLAG_PREPROCESS
1563 | PARSE_FLAG_TOK_NUM
1564 | PARSE_FLAG_TOK_STR
1565 | PARSE_FLAG_LINEFEED
1566 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1578 s
= define_find(tok
);
1579 /* undefine symbol by putting an invalid name */
1584 case TOK_INCLUDE_NEXT
:
1585 ch
= file
->buf_ptr
[0];
1586 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1591 } else if (ch
== '\"') {
1596 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1597 if ((q
- buf
) < sizeof(buf
) - 1)
1600 if (handle_stray_noerror() == 0)
1608 /* eat all spaces and comments after include */
1609 /* XXX: slightly incorrect */
1610 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1614 /* computed #include : either we have only strings or
1615 we have anything enclosed in '<>' */
1618 if (tok
== TOK_STR
) {
1619 while (tok
!= TOK_LINEFEED
) {
1620 if (tok
!= TOK_STR
) {
1622 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1624 pstrcat(buf
, sizeof(buf
), (char *)tokc
.str
.data
);
1630 while (tok
!= TOK_LINEFEED
) {
1631 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1635 /* check syntax and remove '<>' */
1636 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1637 goto include_syntax
;
1638 memmove(buf
, buf
+ 1, len
- 2);
1639 buf
[len
- 2] = '\0';
1644 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1645 tcc_error("#include recursion too deep");
1646 /* store current file in stack, but increment stack later below */
1647 *s1
->include_stack_ptr
= file
;
1648 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
: 0;
1649 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1650 for (; i
< n
; ++i
) {
1651 char buf1
[sizeof file
->filename
];
1656 /* check absolute include path */
1657 if (!IS_ABSPATH(buf
))
1661 } else if (i
== 1) {
1662 /* search in current dir if "header.h" */
1665 path
= file
->filename
;
1666 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1669 /* search in all the include paths */
1670 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1671 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1672 if (path
== 0) continue;
1673 pstrcpy(buf1
, sizeof(buf1
), path
);
1674 pstrcat(buf1
, sizeof(buf1
), "/");
1677 pstrcat(buf1
, sizeof(buf1
), buf
);
1678 e
= search_cached_include(s1
, buf1
);
1679 if (e
&& (define_find(e
->ifndef_macro
) || e
->ifndef_macro
== TOK_once
)) {
1680 /* no need to parse the include because the 'ifndef macro'
1683 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1688 if (tcc_open(s1
, buf1
) < 0)
1691 file
->include_next_index
= i
+ 1;
1693 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1695 /* update target deps */
1696 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1698 /* push current file in stack */
1699 ++s1
->include_stack_ptr
;
1700 /* add include file debug info */
1702 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1703 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1704 ch
= file
->buf_ptr
[0];
1707 tcc_error("include file '%s' not found", buf
);
1714 c
= expr_preprocess();
1720 if (tok
< TOK_IDENT
)
1721 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1725 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1727 file
->ifndef_macro
= tok
;
1730 c
= (define_find(tok
) != 0) ^ c
;
1732 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1733 tcc_error("memory full (ifdef)");
1734 *s1
->ifdef_stack_ptr
++ = c
;
1737 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1738 tcc_error("#else without matching #if");
1739 if (s1
->ifdef_stack_ptr
[-1] & 2)
1740 tcc_error("#else after #else");
1741 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1744 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1745 tcc_error("#elif without matching #if");
1746 c
= s1
->ifdef_stack_ptr
[-1];
1748 tcc_error("#elif after #else");
1749 /* last #if/#elif expression was true: we skip */
1752 c
= expr_preprocess();
1753 s1
->ifdef_stack_ptr
[-1] = c
;
1755 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1756 file
->ifndef_macro
= 0;
1766 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1767 tcc_error("#endif without matching #if");
1768 s1
->ifdef_stack_ptr
--;
1769 /* '#ifndef macro' was at the start of file. Now we check if
1770 an '#endif' is exactly at the end of file */
1771 if (file
->ifndef_macro
&&
1772 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1773 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1774 /* need to set to zero to avoid false matches if another
1775 #ifndef at middle of file */
1776 file
->ifndef_macro
= 0;
1777 while (tok
!= TOK_LINEFEED
)
1779 tok_flags
|= TOK_FLAG_ENDIF
;
1784 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1788 if (tok
!= TOK_CINT
)
1790 tcc_error("wrong #line format");
1794 if (tok
!= TOK_LINEFEED
) {
1796 pstrcpy(file
->filename
, sizeof(file
->filename
), (char *)tokc
.str
.data
);
1797 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1804 total_lines
+= file
->line_num
- n
;
1807 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1812 ch
= file
->buf_ptr
[0];
1815 while (ch
!= '\n' && ch
!= CH_EOF
) {
1816 if ((q
- buf
) < sizeof(buf
) - 1)
1819 if (handle_stray_noerror() == 0)
1826 tcc_error("#error %s", buf
);
1828 tcc_warning("#warning %s", buf
);
1836 /* ignore gas line comment in an 'S' file. */
1837 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
1839 if (tok
== '!' && is_bof
)
1840 /* '!' is ignored at beginning to allow C scripts. */
1842 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1844 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1847 /* ignore other preprocess commands or #! for C scripts */
1848 while (tok
!= TOK_LINEFEED
)
1851 parse_flags
= saved_parse_flags
;
1854 /* evaluate escape codes in a string. */
1855 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1870 case '0': case '1': case '2': case '3':
1871 case '4': case '5': case '6': case '7':
1872 /* at most three octal digits */
1877 n
= n
* 8 + c
- '0';
1881 n
= n
* 8 + c
- '0';
1886 goto add_char_nonext
;
1894 if (c
>= 'a' && c
<= 'f')
1896 else if (c
>= 'A' && c
<= 'F')
1906 goto add_char_nonext
;
1930 goto invalid_escape
;
1940 if (c
>= '!' && c
<= '~')
1941 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1943 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1950 cstr_ccat(outstr
, c
);
1952 cstr_wccat(outstr
, c
);
1954 /* add a trailing '\0' */
1956 cstr_ccat(outstr
, '\0');
1958 cstr_wccat(outstr
, '\0');
1961 void parse_string(const char *s
, int len
)
1963 uint8_t buf
[1000], *p
= buf
;
1966 if ((is_long
= *s
== 'L'))
1970 if (len
>= sizeof buf
)
1971 p
= tcc_malloc(len
+ 1);
1975 cstr_reset(&tokcstr
);
1976 parse_escape_string(&tokcstr
, p
, is_long
);
1982 /* XXX: make it portable */
1986 char_size
= sizeof(nwchar_t
);
1987 if (tokcstr
.size
<= char_size
)
1988 tcc_error("empty character constant");
1989 if (tokcstr
.size
> 2 * char_size
)
1990 tcc_warning("multi-character character constant");
1992 tokc
.i
= *(int8_t *)tokcstr
.data
;
1995 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
1999 tokc
.str
.size
= tokcstr
.size
;
2000 tokc
.str
.data
= tokcstr
.data
;
2001 tokc
.str
.data_allocated
= tokcstr
.data_allocated
;
2009 /* we use 64 bit numbers */
2012 /* bn = (bn << shift) | or_val */
2013 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2017 for(i
=0;i
<BN_SIZE
;i
++) {
2019 bn
[i
] = (v
<< shift
) | or_val
;
2020 or_val
= v
>> (32 - shift
);
2024 static void bn_zero(unsigned int *bn
)
2027 for(i
=0;i
<BN_SIZE
;i
++) {
2032 /* parse number in null terminated string 'p' and return it in the
2034 static void parse_number(const char *p
)
2036 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2038 unsigned int bn
[BN_SIZE
];
2049 goto float_frac_parse
;
2050 } else if (t
== '0') {
2051 if (ch
== 'x' || ch
== 'X') {
2055 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2061 /* parse all digits. cannot check octal numbers at this stage
2062 because of floating point constants */
2064 if (ch
>= 'a' && ch
<= 'f')
2066 else if (ch
>= 'A' && ch
<= 'F')
2074 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2076 tcc_error("number too long");
2082 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2083 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2085 /* NOTE: strtox should support that for hexa numbers, but
2086 non ISOC99 libcs do not support it, so we prefer to do
2088 /* hexadecimal or binary floats */
2089 /* XXX: handle overflows */
2101 } else if (t
>= 'a') {
2103 } else if (t
>= 'A') {
2108 bn_lshift(bn
, shift
, t
);
2115 if (t
>= 'a' && t
<= 'f') {
2117 } else if (t
>= 'A' && t
<= 'F') {
2119 } else if (t
>= '0' && t
<= '9') {
2125 tcc_error("invalid digit");
2126 bn_lshift(bn
, shift
, t
);
2131 if (ch
!= 'p' && ch
!= 'P')
2138 } else if (ch
== '-') {
2142 if (ch
< '0' || ch
> '9')
2143 expect("exponent digits");
2144 while (ch
>= '0' && ch
<= '9') {
2145 exp_val
= exp_val
* 10 + ch
- '0';
2148 exp_val
= exp_val
* s
;
2150 /* now we can generate the number */
2151 /* XXX: should patch directly float number */
2152 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2153 d
= ldexp(d
, exp_val
- frac_bits
);
2158 /* float : should handle overflow */
2160 } else if (t
== 'L') {
2162 #ifdef TCC_TARGET_PE
2167 /* XXX: not large enough */
2168 tokc
.ld
= (long double)d
;
2175 /* decimal floats */
2177 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2182 while (ch
>= '0' && ch
<= '9') {
2183 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2189 if (ch
== 'e' || ch
== 'E') {
2190 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2194 if (ch
== '-' || ch
== '+') {
2195 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2200 if (ch
< '0' || ch
> '9')
2201 expect("exponent digits");
2202 while (ch
>= '0' && ch
<= '9') {
2203 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2215 tokc
.f
= strtof(token_buf
, NULL
);
2216 } else if (t
== 'L') {
2218 #ifdef TCC_TARGET_PE
2220 tokc
.d
= strtod(token_buf
, NULL
);
2223 tokc
.ld
= strtold(token_buf
, NULL
);
2227 tokc
.d
= strtod(token_buf
, NULL
);
2231 unsigned long long n
, n1
;
2232 int lcount
, ucount
, must_64bit
;
2235 /* integer number */
2238 if (b
== 10 && *q
== '0') {
2245 /* no need for checks except for base 10 / 8 errors */
2255 tcc_error("invalid digit");
2258 /* detect overflow */
2259 /* XXX: this test is not reliable */
2261 tcc_error("integer constant overflow");
2264 /* Determine the characteristics (unsigned and/or 64bit) the type of
2265 the constant must have according to the constant suffix(es) */
2266 lcount
= ucount
= must_64bit
= 0;
2272 tcc_error("three 'l's in integer constant");
2273 if (lcount
&& *(p
- 1) != ch
)
2274 tcc_error("incorrect integer suffix: %s", p1
);
2276 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2281 } else if (t
== 'U') {
2283 tcc_error("two 'u's in integer constant");
2291 /* Whether 64 bits are needed to hold the constant's value */
2292 if (n
& 0xffffffff00000000LL
|| must_64bit
) {
2300 /* Whether type must be unsigned to hold the constant's value */
2301 if (ucount
|| ((n1
>> 31) && (b
!= 10))) {
2302 if (tok
== TOK_CLLONG
)
2306 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2307 } else if (n1
>> 31) {
2308 if (tok
== TOK_CINT
)
2311 tcc_error("integer constant overflow");
2314 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2320 tcc_error("invalid number\n");
2324 #define PARSE2(c1, tok1, c2, tok2) \
2335 /* return next token without macro substitution */
2336 static inline void next_nomacro1(void)
2346 #if (__TINYC__ || __GNUC__)
2349 goto parse_ident_fast
;
2356 if (parse_flags
& PARSE_FLAG_SPACES
)
2357 goto keep_tok_flags
;
2358 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2367 /* first look if it is in fact an end of buffer */
2368 c
= handle_stray1(p
);
2375 TCCState
*s1
= tcc_state
;
2376 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2377 && !(tok_flags
& TOK_FLAG_EOF
)) {
2378 tok_flags
|= TOK_FLAG_EOF
;
2380 goto keep_tok_flags
;
2381 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2383 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2384 tcc_error("missing #endif");
2385 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2386 /* no include left : end of file. */
2389 tok_flags
&= ~TOK_FLAG_EOF
;
2390 /* pop include file */
2392 /* test if previous '#endif' was after a #ifdef at
2394 if (tok_flags
& TOK_FLAG_ENDIF
) {
2396 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2398 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2399 tok_flags
&= ~TOK_FLAG_ENDIF
;
2402 /* add end of include file debug info */
2403 if (tcc_state
->do_debug
) {
2404 put_stabd(N_EINCL
, 0, 0);
2406 /* pop include stack */
2408 s1
->include_stack_ptr
--;
2417 tok_flags
|= TOK_FLAG_BOL
;
2420 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2423 goto keep_tok_flags
;
2428 if ((tok_flags
& TOK_FLAG_BOL
) &&
2429 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2431 preprocess(tok_flags
& TOK_FLAG_BOF
);
2437 tok
= TOK_TWOSHARPS
;
2439 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2440 p
= parse_line_comment(p
- 1);
2449 /* dollar is allowed to start identifiers when not parsing asm */
2451 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2452 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2455 #if (__TINYC__ || __GNUC__)
2462 case 'a': case 'b': case 'c': case 'd':
2463 case 'e': case 'f': case 'g': case 'h':
2464 case 'i': case 'j': case 'k': case 'l':
2465 case 'm': case 'n': case 'o': case 'p':
2466 case 'q': case 'r': case 's': case 't':
2467 case 'u': case 'v': case 'w': case 'x':
2469 case 'A': case 'B': case 'C': case 'D':
2470 case 'E': case 'F': case 'G': case 'H':
2471 case 'I': case 'J': case 'K':
2472 case 'M': case 'N': case 'O': case 'P':
2473 case 'Q': case 'R': case 'S': case 'T':
2474 case 'U': case 'V': case 'W': case 'X':
2481 h
= TOK_HASH_FUNC(h
, c
);
2482 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2483 h
= TOK_HASH_FUNC(h
, c
);
2488 /* fast case : no stray found, so we have the full token
2489 and we have already hashed it */
2491 h
&= (TOK_HASH_SIZE
- 1);
2492 pts
= &hash_ident
[h
];
2497 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2499 pts
= &(ts
->hash_next
);
2501 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2505 cstr_reset(&tokcstr
);
2508 cstr_ccat(&tokcstr
, *p1
);
2514 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2516 cstr_ccat(&tokcstr
, c
);
2519 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2525 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2527 goto parse_ident_fast
;
2530 if (c
== '\'' || c
== '\"') {
2534 cstr_reset(&tokcstr
);
2535 cstr_ccat(&tokcstr
, 'L');
2536 goto parse_ident_slow
;
2541 case '0': case '1': case '2': case '3':
2542 case '4': case '5': case '6': case '7':
2544 cstr_reset(&tokcstr
);
2545 /* after the first digit, accept digits, alpha, '.' or sign if
2546 prefixed by 'eEpP' */
2550 cstr_ccat(&tokcstr
, c
);
2552 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2554 || ((c
== '+' || c
== '-')
2555 && (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P')
2559 /* We add a trailing '\0' to ease parsing */
2560 cstr_ccat(&tokcstr
, '\0');
2561 tokc
.str
.size
= tokcstr
.size
;
2562 tokc
.str
.data
= tokcstr
.data
;
2563 tokc
.str
.data_allocated
= tokcstr
.data_allocated
;
2568 /* special dot handling because it can also start a number */
2571 cstr_reset(&tokcstr
);
2572 cstr_ccat(&tokcstr
, '.');
2574 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2576 goto parse_ident_fast
;
2577 } else if (c
== '.') {
2583 *--p
= '.'; /* may underflow into file->unget[] */
2594 cstr_reset(&tokcstr
);
2596 cstr_ccat(&tokcstr
, 'L');
2597 cstr_ccat(&tokcstr
, c
);
2598 p
= parse_pp_string(p
, c
, &tokcstr
);
2599 cstr_ccat(&tokcstr
, c
);
2600 cstr_ccat(&tokcstr
, '\0');
2601 tokc
.str
.size
= tokcstr
.size
;
2602 tokc
.str
.data
= tokcstr
.data
;
2603 tokc
.str
.data_allocated
= tokcstr
.data_allocated
;
2612 } else if (c
== '<') {
2629 } else if (c
== '>') {
2647 } else if (c
== '=') {
2660 } else if (c
== '=') {
2673 } else if (c
== '=') {
2686 } else if (c
== '=') {
2689 } else if (c
== '>') {
2697 PARSE2('!', '!', '=', TOK_NE
)
2698 PARSE2('=', '=', '=', TOK_EQ
)
2699 PARSE2('*', '*', '=', TOK_A_MUL
)
2700 PARSE2('%', '%', '=', TOK_A_MOD
)
2701 PARSE2('^', '^', '=', TOK_A_XOR
)
2703 /* comments or operator */
2707 p
= parse_comment(p
);
2708 /* comments replaced by a blank */
2710 goto keep_tok_flags
;
2711 } else if (c
== '/') {
2712 p
= parse_line_comment(p
);
2714 goto keep_tok_flags
;
2715 } else if (c
== '=') {
2735 case '@': /* only used in assembler */
2741 tcc_error("unrecognized character \\x%02x", c
);
2747 #if defined(PARSE_DEBUG)
2748 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2752 /* return next token without macro substitution. Can read input from
2754 static void next_nomacro_spc(void)
2760 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2761 if (tok
== TOK_LINENUM
) {
2762 file
->line_num
= tokc
.i
;
2771 ST_FUNC
void next_nomacro(void)
2775 } while (tok
< 256 && (isidnum_table
[tok
- CH_EOF
] & IS_SPC
));
2779 static void macro_subst(
2780 TokenString
*tok_str
,
2782 const int *macro_str
,
2786 /* substitute arguments in replacement lists in macro_str by the values in
2787 args (field d) and return allocated string */
2788 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2800 TOK_GET(&t
, ¯o_str
, &cval
);
2805 TOK_GET(&t
, ¯o_str
, &cval
);
2808 s
= sym_find2(args
, t
);
2811 cstr_ccat(&cstr
, '\"');
2815 TOK_GET(&t
, &st
, &cval
);
2816 if (t
!= TOK_PLCHLDR
2818 && 0 == check_space(t
, &spc
)) {
2819 const char *s
= get_tok_str(t
, &cval
);
2821 if (t
== TOK_PPSTR
&& *s
!= '\'')
2822 add_char(&cstr
, *s
);
2824 cstr_ccat(&cstr
, *s
);
2830 cstr_ccat(&cstr
, '\"');
2831 cstr_ccat(&cstr
, '\0');
2833 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
2836 cval
.str
.size
= cstr
.size
;
2837 cval
.str
.data
= cstr
.data
;
2838 cval
.str
.data_allocated
= cstr
.data_allocated
;
2839 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
2840 tcc_free(cval
.str
.data_allocated
);
2843 expect("macro parameter after '#'");
2845 } else if (t
>= TOK_IDENT
) {
2846 s
= sym_find2(args
, t
);
2850 /* if '##' is present before or after, no arg substitution */
2851 if (*macro_str
== TOK_TWOSHARPS
|| t1
== TOK_TWOSHARPS
) {
2852 /* special case for var arg macros : ## eats the ','
2853 if empty VA_ARGS variable. */
2854 if (t1
== TOK_TWOSHARPS
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
2856 /* suppress ',' '##' */
2859 /* suppress '##' and add variable */
2866 TOK_GET(&t1
, &st
, &cval
);
2869 tok_str_add2(&str
, t1
, &cval
);
2875 /* NOTE: the stream cannot be read when macro
2876 substituing an argument */
2877 macro_subst(&str
, nested_list
, st
, 0);
2879 if (str
.len
== l0
) /* exanded to empty string */
2880 tok_str_add(&str
, TOK_PLCHLDR
);
2882 tok_str_add(&str
, t
);
2885 tok_str_add2(&str
, t
, &cval
);
2889 tok_str_add(&str
, 0);
2893 static char const ab_month_name
[12][4] =
2895 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2896 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2899 /* peek or read [ws_str == NULL] next token from function macro call,
2900 walking up macro levels up to the file if necessary */
2901 static int next_argstream(Sym
**nested_list
, int can_read_stream
, TokenString
*ws_str
)
2909 p
= macro_ptr
, t
= *p
;
2911 while (is_space(t
) || TOK_LINEFEED
== t
)
2912 tok_str_add(ws_str
, t
), t
= *++p
;
2914 if (t
== 0 && can_read_stream
) {
2916 /* also, end of scope for nested defined symbol */
2918 while (sa
&& sa
->v
== -1)
2927 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
2930 uint8_t *p
= file
->buf_ptr
;
2933 p
= parse_comment(p
);
2934 file
->buf_ptr
= p
- 1;
2935 } else if (c
== '/') {
2936 p
= parse_line_comment(p
);
2937 file
->buf_ptr
= p
- 1;
2942 tok_str_add(ws_str
, ch
);
2956 /* do macro substitution of current token with macro 's' and add
2957 result to (tok_str,tok_len). 'nested_list' is the list of all
2958 macros we got inside to avoid recursing. Return non zero if no
2959 substitution needs to be done */
2960 static int macro_subst_tok(
2961 TokenString
*tok_str
,
2964 int can_read_stream
)
2966 Sym
*args
, *sa
, *sa1
;
2967 int parlevel
, *mstr
, t
, t1
, spc
;
2974 /* if symbol is a macro, prepare substitution */
2975 /* special macros */
2976 if (tok
== TOK___LINE__
) {
2977 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2981 } else if (tok
== TOK___FILE__
) {
2982 cstrval
= file
->filename
;
2984 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2989 tm
= localtime(&ti
);
2990 if (tok
== TOK___DATE__
) {
2991 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2992 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2994 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2995 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3002 cstr_cat(&cstr
, cstrval
);
3003 cstr_ccat(&cstr
, '\0');
3004 cval
.str
.size
= cstr
.size
;
3005 cval
.str
.data
= cstr
.data
;
3006 cval
.str
.data_allocated
= cstr
.data_allocated
;
3007 tok_str_add2(tok_str
, t1
, &cval
);
3010 int saved_parse_flags
= parse_flags
;
3013 if (s
->type
.t
== MACRO_FUNC
) {
3014 /* whitespace between macro name and argument list */
3016 tok_str_new(&ws_str
);
3019 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3020 | PARSE_FLAG_ACCEPT_STRAYS
;
3022 /* get next token from argument stream */
3023 t
= next_argstream(nested_list
, can_read_stream
, &ws_str
);
3025 /* not a macro substitution after all, restore the
3026 * macro token plus all whitespace we've read.
3027 * whitespace is intentionally not merged to preserve
3029 parse_flags
= saved_parse_flags
;
3030 tok_str_add(tok_str
, tok
);
3031 if (parse_flags
& PARSE_FLAG_SPACES
) {
3033 for (i
= 0; i
< ws_str
.len
; i
++)
3034 tok_str_add(tok_str
, ws_str
.str
[i
]);
3036 tok_str_free(ws_str
.str
);
3039 tok_str_free(ws_str
.str
);
3041 next_nomacro(); /* eat '(' */
3043 /* argument macro */
3046 /* NOTE: empty args are allowed, except if no args */
3049 next_argstream(nested_list
, can_read_stream
, NULL
);
3050 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3052 /* handle '()' case */
3053 if (!args
&& !sa
&& tok
== ')')
3056 tcc_error("macro '%s' used with too many args",
3057 get_tok_str(s
->v
, 0));
3060 /* NOTE: non zero sa->t indicates VA_ARGS */
3061 while ((parlevel
> 0 ||
3063 (tok
!= ',' || sa
->type
.t
)))) {
3064 if (tok
== TOK_EOF
|| tok
== 0)
3068 else if (tok
== ')')
3070 if (tok
== TOK_LINEFEED
)
3072 if (!check_space(tok
, &spc
))
3073 tok_str_add2(&str
, tok
, &tokc
);
3074 next_argstream(nested_list
, can_read_stream
, NULL
);
3079 tok_str_add(&str
, 0);
3080 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3084 /* special case for gcc var args: add an empty
3085 var arg argument if it is omitted */
3086 if (sa
&& sa
->type
.t
&& gnu_ext
)
3094 tcc_error("macro '%s' used with too few args",
3095 get_tok_str(s
->v
, 0));
3098 parse_flags
= saved_parse_flags
;
3100 /* now subst each arg */
3101 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3106 tok_str_free(sa
->d
);
3112 sym_push2(nested_list
, s
->v
, 0, 0);
3113 parse_flags
= saved_parse_flags
;
3114 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
3116 /* pop nested defined symbol */
3118 *nested_list
= sa1
->prev
;
3126 int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3132 if (t1
!= TOK_PLCHLDR
)
3133 cstr_cat(&cstr
, get_tok_str(t1
, v1
));
3135 if (t2
!= TOK_PLCHLDR
)
3136 cstr_cat(&cstr
, get_tok_str(t2
, v2
));
3137 cstr_ccat(&cstr
, '\0');
3139 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3140 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3143 if (0 == *file
->buf_ptr
)
3147 tcc_warning("pasting <%.*s> and <%s> does not give a valid preprocessing token",
3148 n
, cstr
.data
, (char*)cstr
.data
+ n
);
3153 //printf("paste <%s>\n", (char*)cstr.data);
3158 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3159 return the resulting string (which must be freed). */
3160 static inline int *macro_twosharps(const int *ptr0
)
3164 TokenString macro_str1
;
3165 int start_of_nosubsts
= -1;
3168 /* we search the first '##' */
3169 for (ptr
= ptr0
;;) {
3170 TOK_GET(&t
, &ptr
, &cval
);
3171 if (t
== TOK_TWOSHARPS
)
3177 tok_str_new(¯o_str1
);
3179 //tok_print(" $$$", ptr0);
3180 for (ptr
= ptr0
;;) {
3181 TOK_GET(&t
, &ptr
, &cval
);
3184 if (t
== TOK_TWOSHARPS
)
3186 while (*ptr
== TOK_TWOSHARPS
) {
3188 /* given 'a##b', remove nosubsts preceding 'a' */
3189 if (start_of_nosubsts
>= 0)
3190 macro_str1
.len
= start_of_nosubsts
;
3191 /* given 'a##b', remove nosubsts preceding 'b' */
3192 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3194 if (t1
&& t1
!= TOK_TWOSHARPS
3195 && t1
!= ':') /* 'a##:' don't build a new token */
3197 TOK_GET(&t1
, &ptr
, &cv1
);
3198 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3199 paste_tokens(t
, &cval
, t1
, &cv1
);
3200 t
= tok
, cval
= tokc
;
3204 if (t
== TOK_NOSUBST
) {
3205 if (start_of_nosubsts
< 0)
3206 start_of_nosubsts
= macro_str1
.len
;
3208 start_of_nosubsts
= -1;
3210 tok_str_add2(¯o_str1
, t
, &cval
);
3212 tok_str_add(¯o_str1
, 0);
3213 //tok_print(" ###", macro_str1.str);
3214 return macro_str1
.str
;
3217 /* do macro substitution of macro_str and add result to
3218 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3219 inside to avoid recursing. */
3220 static void macro_subst(
3221 TokenString
*tok_str
,
3223 const int *macro_str
,
3229 int t
, spc
, nosubst
;
3231 int *macro_str1
= NULL
;
3233 /* first scan for '##' operator handling */
3237 /* first scan for '##' operator handling */
3238 if (can_read_stream
) {
3239 macro_str1
= macro_twosharps(ptr
);
3245 TOK_GET(&t
, &ptr
, &cval
);
3249 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3254 /* if nested substitution, do nothing */
3255 if (sym_find2(*nested_list
, t
)) {
3256 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3257 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3263 str
.str
= (int*)ptr
;
3264 begin_macro(&str
, 2);
3267 macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
3269 if (str
.alloc
== 3) {
3270 /* already finished by reading function macro arguments */
3278 spc
= (tok_str
->len
&&
3279 is_space(tok_last(tok_str
->str
,
3280 tok_str
->str
+ tok_str
->len
)));
3284 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3285 tcc_error("stray '\\' in program");
3288 if (!check_space(t
, &spc
))
3289 tok_str_add2(tok_str
, t
, &cval
);
3291 if (t
== TOK_NOSUBST
)
3296 tok_str_free(macro_str1
);
3300 /* return next token with macro substitution */
3301 ST_FUNC
void next(void)
3304 if (parse_flags
& PARSE_FLAG_SPACES
)
3310 if (tok
== TOK_NOSUBST
|| tok
== TOK_PLCHLDR
) {
3311 /* discard preprocessor markers */
3313 } else if (tok
== 0) {
3314 /* end of macro or unget token string */
3318 } else if (tok
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3320 /* if reading from file, try to substitute macros */
3321 s
= define_find(tok
);
3323 static TokenString str
; /* using static string for speed */
3324 Sym
*nested_list
= NULL
;
3327 macro_subst_tok(&str
, &nested_list
, s
, 1);
3328 tok_str_add(&str
, 0);
3329 begin_macro(&str
, 0);
3333 /* convert preprocessor tokens into C tokens */
3334 if (tok
== TOK_PPNUM
) {
3335 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3336 parse_number((char *)tokc
.str
.data
);
3337 } else if (tok
== TOK_PPSTR
) {
3338 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3339 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3343 /* push back current token and set current token to 'last_tok'. Only
3344 identifier case handled for labels. */
3345 ST_INLN
void unget_tok(int last_tok
)
3347 TokenString
*str
= tcc_malloc(sizeof *str
);
3349 tok_str_add2(str
, tok
, &tokc
);
3350 tok_str_add(str
, 0);
3351 begin_macro(str
, 1);
3355 /* better than nothing, but needs extension to handle '-E' option
3357 ST_FUNC
void preprocess_init(TCCState
*s1
)
3359 s1
->include_stack_ptr
= s1
->include_stack
;
3360 /* XXX: move that before to avoid having to initialize
3361 file->ifdef_stack_ptr ? */
3362 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3363 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3365 pvtop
= vtop
= vstack
- 1;
3366 s1
->pack_stack
[0] = 0;
3367 s1
->pack_stack_ptr
= s1
->pack_stack
;
3369 isidnum_table
['$' - CH_EOF
] =
3370 tcc_state
->dollars_in_identifiers
? IS_ID
: 0;
3372 isidnum_table
['.' - CH_EOF
] =
3373 (parse_flags
& PARSE_FLAG_ASM_FILE
) ? IS_ID
: 0;
3376 ST_FUNC
void preprocess_new(void)
3381 /* init isid table */
3382 for(i
= CH_EOF
; i
<128; i
++)
3383 isidnum_table
[i
- CH_EOF
]
3384 = is_space(i
) ? IS_SPC
3389 for(i
= 128; i
<256; i
++)
3390 isidnum_table
[i
- CH_EOF
] = IS_ID
;
3392 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3394 tok_ident
= TOK_IDENT
;
3403 tok_alloc(p
, r
- p
- 1);
3408 ST_FUNC
void preprocess_delete(void)
3412 /* free -D and compiler defines */
3415 /* cleanup from error/setjmp */
3421 n
= tok_ident
- TOK_IDENT
;
3422 for(i
= 0; i
< n
; i
++)
3423 tcc_free(table_ident
[i
]);
3424 tcc_free(table_ident
);
3428 /* Preprocess the current file */
3429 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3431 BufferedFile
**iptr
;
3432 int token_seen
, spcs
, level
;
3434 preprocess_init(s1
);
3435 ch
= file
->buf_ptr
[0];
3436 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3437 parse_flags
= PARSE_FLAG_PREPROCESS
3438 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3439 | PARSE_FLAG_LINEFEED
3441 | PARSE_FLAG_ACCEPT_STRAYS
3445 do next(); while (tok
!= TOK_EOF
); return 0;
3448 token_seen
= spcs
= 0;
3449 pp_line(s1
, file
, 0);
3452 iptr
= s1
->include_stack_ptr
;
3456 level
= s1
->include_stack_ptr
- iptr
;
3459 pp_line(s1
, *iptr
, 0);
3460 pp_line(s1
, file
, level
);
3463 if (0 == token_seen
) {
3468 if (tok
== TOK_LINEFEED
) {
3472 pp_line(s1
, file
, 0);
3474 fputs(" ", s1
->ppfp
), --spcs
;
3477 } else if (tok
== TOK_LINEFEED
) {
3482 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);