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
)
1076 int d
= f
->line_num
- f
->line_ref
;
1077 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
1078 || (level
== 0 && f
->line_ref
&& d
< 8)) {
1080 fputs("\n", s1
->ppfp
), --d
;
1081 } else if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
1082 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
1084 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
1085 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
1088 f
->line_ref
= f
->line_num
;
1091 static void tok_print(const char *msg
, const int *str
)
1093 FILE *pr
= tcc_state
->dffp
;
1097 fprintf(pr
, "%s ", msg
);
1099 TOK_GET(&t
, &str
, &cval
);
1102 fprintf(pr
,"%s", get_tok_str(t
, &cval
));
1107 static int define_print_prepared(Sym
*s
)
1109 if (!s
|| !tcc_state
->dffp
|| tcc_state
->dflag
== 0)
1112 if (s
->v
< TOK_IDENT
|| s
->v
>= tok_ident
)
1115 if (file
&& tcc_state
->dflag
== 'D') {
1117 pp_line(tcc_state
, file
, 0);
1118 file
->line_ref
= ++file
->line_num
;
1123 static void define_print(int v
)
1125 FILE *pr
= tcc_state
->dffp
;
1129 if (define_print_prepared(s
) == 0)
1132 fprintf(pr
, "// #define %s", get_tok_str(v
, NULL
));
1133 if (s
->type
.t
== MACRO_FUNC
) {
1138 fprintf(pr
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
1145 tok_print("", s
->d
);
1148 static void undef_print(int v
)
1150 FILE *pr
= tcc_state
->dffp
;
1154 if (define_print_prepared(s
) == 0)
1157 fprintf(pr
, "// #undef %s\n", get_tok_str(s
->v
, NULL
));
1160 ST_FUNC
void print_defines(void)
1162 Sym
*top
= define_stack
;
1164 define_print(top
->v
);
1169 /* defines handling */
1170 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1175 if (s
&& !macro_is_equal(s
->d
, str
))
1176 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1178 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1180 s
->next
= first_arg
;
1181 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1184 /* undefined a define symbol. Its name is just set to zero */
1185 ST_FUNC
void define_undef(Sym
*s
)
1189 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1190 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1193 ST_INLN Sym
*define_find(int v
)
1196 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1198 return table_ident
[v
]->sym_define
;
1201 /* free define stack until top reaches 'b' */
1202 ST_FUNC
void free_defines(Sym
*b
)
1210 /* do not free args or predefined defines */
1212 tok_str_free(top
->d
);
1214 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1215 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1223 ST_FUNC Sym
*label_find(int v
)
1226 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1228 return table_ident
[v
]->sym_label
;
1231 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1234 s
= sym_push2(ptop
, v
, 0, 0);
1236 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1237 if (ptop
== &global_label_stack
) {
1238 /* modify the top most local identifier, so that
1239 sym_identifier will point to 's' when popped */
1241 ps
= &(*ps
)->prev_tok
;
1248 /* pop labels until element last is reached. Look if any labels are
1249 undefined. Define symbols if '&&label' was used. */
1250 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1253 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1255 if (s
->r
== LABEL_DECLARED
) {
1256 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1257 } else if (s
->r
== LABEL_FORWARD
) {
1258 tcc_error("label '%s' used but not defined",
1259 get_tok_str(s
->v
, NULL
));
1262 /* define corresponding symbol. A size of
1264 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1268 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1274 /* eval an expression for #if/#elif */
1275 static int expr_preprocess(void)
1281 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1282 next(); /* do macro subst */
1283 if (tok
== TOK_DEFINED
) {
1288 c
= define_find(tok
) != 0;
1293 } else if (tok
>= TOK_IDENT
) {
1294 /* if undefined macro */
1298 tok_str_add_tok(&str
);
1300 tok_str_add(&str
, -1); /* simulate end of file */
1301 tok_str_add(&str
, 0);
1302 /* now evaluate C constant expression */
1303 begin_macro(&str
, 0);
1311 /* parse after #define */
1312 ST_FUNC
void parse_define(void)
1314 Sym
*s
, *first
, **ps
;
1315 int v
, t
, varg
, is_vaargs
, spc
;
1316 int saved_parse_flags
= parse_flags
;
1321 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1322 /* XXX: should check if same macro (ANSI) */
1325 /* '(' must be just after macro definition for MACRO_FUNC */
1326 parse_flags
|= PARSE_FLAG_SPACES
;
1329 /* must be able to parse TOK_DOTS (in asm mode '.' can be part of identifier) */
1330 parse_flags
&= ~PARSE_FLAG_ASM_FILE
;
1331 isidnum_table
['.' - CH_EOF
] = 0;
1334 if (tok
!= ')') for (;;) {
1338 if (varg
== TOK_DOTS
) {
1339 varg
= TOK___VA_ARGS__
;
1341 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1345 if (varg
< TOK_IDENT
)
1347 tcc_error("bad macro parameter list");
1348 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1353 if (tok
!= ',' || is_vaargs
)
1359 parse_flags
|= (saved_parse_flags
& PARSE_FLAG_ASM_FILE
);
1360 isidnum_table
['.' - CH_EOF
] =
1361 (parse_flags
& PARSE_FLAG_ASM_FILE
) ? IS_ID
: 0;
1365 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1366 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1367 /* remove spaces around ## and after '#' */
1368 if (TOK_TWOSHARPS
== tok
) {
1374 } else if ('#' == tok
) {
1376 } else if (check_space(tok
, &spc
)) {
1379 tok_str_add2(&str
, tok
, &tokc
);
1384 parse_flags
= saved_parse_flags
;
1386 --str
.len
; /* remove trailing space */
1387 tok_str_add(&str
, 0);
1390 tcc_error("'##' cannot appear at either end of macro");
1391 define_push(v
, t
, str
.str
, first
);
1395 static inline int hash_cached_include(const char *filename
)
1397 const unsigned char *s
;
1401 s
= (unsigned char *) filename
;
1403 h
= TOK_HASH_FUNC(h
, *s
);
1406 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1410 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1414 h
= hash_cached_include(filename
);
1415 i
= s1
->cached_includes_hash
[h
];
1419 e
= s1
->cached_includes
[i
- 1];
1420 if (0 == PATHCMP(e
->filename
, filename
))
1427 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1432 if (search_cached_include(s1
, filename
))
1435 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1437 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1438 strcpy(e
->filename
, filename
);
1439 e
->ifndef_macro
= ifndef_macro
;
1440 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1441 /* add in hash table */
1442 h
= hash_cached_include(filename
);
1443 e
->hash_next
= s1
->cached_includes_hash
[h
];
1444 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1447 #define ONCE_PREFIX "#ONCE#"
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 char buf1
[sizeof(file
->filename
) + sizeof(ONCE_PREFIX
)];
1481 strcpy(buf1
, ONCE_PREFIX
);
1482 strcat(buf1
, file
->filename
);
1483 #if PATHCMP==stricmp
1486 add_cached_include(s1
, file
->filename
, tok_alloc(buf1
, strlen(buf1
))->tok
);
1487 } else if (s1
->ppfp
) {
1488 /* tcc -E: keep pragmas below unchanged */
1490 unget_tok(TOK_PRAGMA
);
1492 unget_tok(TOK_LINEFEED
);
1494 } else if (tok
== TOK_pack
) {
1496 #pragma pack(1) // set
1497 #pragma pack() // reset to default
1498 #pragma pack(push,1) // push & set
1499 #pragma pack(pop) // restore previous */
1502 if (tok
== TOK_ASM_pop
) {
1504 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1506 tcc_error("out of pack stack");
1508 s1
->pack_stack_ptr
--;
1512 if (tok
== TOK_ASM_push
) {
1514 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1516 s1
->pack_stack_ptr
++;
1519 if (tok
!= TOK_CINT
)
1522 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1526 *s1
->pack_stack_ptr
= val
;
1531 } else if (tok
== TOK_comment
) {
1541 file
= tcc_strdup((char *)tokc
.str
.data
);
1542 dynarray_add((void ***)&s1
->pragma_libs
, &s1
->nb_pragma_libs
, file
);
1548 if (s1
->warn_unsupported
)
1549 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1554 tcc_error("malformed #pragma directive");
1558 /* is_bof is true if first non space token at beginning of file */
1559 ST_FUNC
void preprocess(int is_bof
)
1561 TCCState
*s1
= tcc_state
;
1562 int i
, c
, n
, saved_parse_flags
;
1566 saved_parse_flags
= parse_flags
;
1567 parse_flags
= PARSE_FLAG_PREPROCESS
1568 | PARSE_FLAG_TOK_NUM
1569 | PARSE_FLAG_TOK_STR
1570 | PARSE_FLAG_LINEFEED
1571 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1583 s
= define_find(tok
);
1584 /* undefine symbol by putting an invalid name */
1589 case TOK_INCLUDE_NEXT
:
1590 ch
= file
->buf_ptr
[0];
1591 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1596 } else if (ch
== '\"') {
1601 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1602 if ((q
- buf
) < sizeof(buf
) - 1)
1605 if (handle_stray_noerror() == 0)
1613 /* eat all spaces and comments after include */
1614 /* XXX: slightly incorrect */
1615 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1619 /* computed #include : either we have only strings or
1620 we have anything enclosed in '<>' */
1623 if (tok
== TOK_STR
) {
1624 while (tok
!= TOK_LINEFEED
) {
1625 if (tok
!= TOK_STR
) {
1627 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1629 pstrcat(buf
, sizeof(buf
), (char *)tokc
.str
.data
);
1635 while (tok
!= TOK_LINEFEED
) {
1636 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1640 /* check syntax and remove '<>' */
1641 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1642 goto include_syntax
;
1643 memmove(buf
, buf
+ 1, len
- 2);
1644 buf
[len
- 2] = '\0';
1649 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1650 tcc_error("#include recursion too deep");
1651 /* store current file in stack, but increment stack later below */
1652 *s1
->include_stack_ptr
= file
;
1653 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
: 0;
1654 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1655 for (; i
< n
; ++i
) {
1656 char buf1
[sizeof file
->filename
];
1661 /* check absolute include path */
1662 if (!IS_ABSPATH(buf
))
1666 } else if (i
== 1) {
1667 /* search in current dir if "header.h" */
1670 path
= file
->filename
;
1671 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1674 /* search in all the include paths */
1675 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1676 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1677 if (path
== 0) continue;
1678 pstrcpy(buf1
, sizeof(buf1
), path
);
1679 pstrcat(buf1
, sizeof(buf1
), "/");
1682 pstrcat(buf1
, sizeof(buf1
), buf
);
1683 e
= search_cached_include(s1
, buf1
);
1684 if (e
&& define_find(e
->ifndef_macro
)) {
1685 /* no need to parse the include because the 'ifndef macro'
1688 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1693 if (tcc_open(s1
, buf1
) < 0)
1696 file
->include_next_index
= i
+ 1;
1698 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1700 /* update target deps */
1701 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1703 /* push current file in stack */
1704 ++s1
->include_stack_ptr
;
1705 /* add include file debug info */
1707 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1708 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1709 ch
= file
->buf_ptr
[0];
1712 tcc_error("include file '%s' not found", buf
);
1719 c
= expr_preprocess();
1725 if (tok
< TOK_IDENT
)
1726 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1730 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1732 file
->ifndef_macro
= tok
;
1735 c
= (define_find(tok
) != 0) ^ c
;
1737 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1738 tcc_error("memory full (ifdef)");
1739 *s1
->ifdef_stack_ptr
++ = c
;
1742 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1743 tcc_error("#else without matching #if");
1744 if (s1
->ifdef_stack_ptr
[-1] & 2)
1745 tcc_error("#else after #else");
1746 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1749 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1750 tcc_error("#elif without matching #if");
1751 c
= s1
->ifdef_stack_ptr
[-1];
1753 tcc_error("#elif after #else");
1754 /* last #if/#elif expression was true: we skip */
1757 c
= expr_preprocess();
1758 s1
->ifdef_stack_ptr
[-1] = c
;
1760 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1761 file
->ifndef_macro
= 0;
1771 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1772 tcc_error("#endif without matching #if");
1773 s1
->ifdef_stack_ptr
--;
1774 /* '#ifndef macro' was at the start of file. Now we check if
1775 an '#endif' is exactly at the end of file */
1776 if (file
->ifndef_macro
&&
1777 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1778 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1779 /* need to set to zero to avoid false matches if another
1780 #ifndef at middle of file */
1781 file
->ifndef_macro
= 0;
1782 while (tok
!= TOK_LINEFEED
)
1784 tok_flags
|= TOK_FLAG_ENDIF
;
1789 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1793 if (tok
!= TOK_CINT
)
1795 tcc_error("wrong #line format");
1799 if (tok
!= TOK_LINEFEED
) {
1801 pstrcpy(file
->filename
, sizeof(file
->filename
), (char *)tokc
.str
.data
);
1802 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1809 total_lines
+= file
->line_num
- n
;
1812 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1817 ch
= file
->buf_ptr
[0];
1820 while (ch
!= '\n' && ch
!= CH_EOF
) {
1821 if ((q
- buf
) < sizeof(buf
) - 1)
1824 if (handle_stray_noerror() == 0)
1831 tcc_error("#error %s", buf
);
1833 tcc_warning("#warning %s", buf
);
1841 /* ignore gas line comment in an 'S' file. */
1842 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
1844 if (tok
== '!' && is_bof
)
1845 /* '!' is ignored at beginning to allow C scripts. */
1847 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1849 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1852 /* ignore other preprocess commands or #! for C scripts */
1853 while (tok
!= TOK_LINEFEED
)
1856 parse_flags
= saved_parse_flags
;
1859 /* evaluate escape codes in a string. */
1860 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1875 case '0': case '1': case '2': case '3':
1876 case '4': case '5': case '6': case '7':
1877 /* at most three octal digits */
1882 n
= n
* 8 + c
- '0';
1886 n
= n
* 8 + c
- '0';
1891 goto add_char_nonext
;
1899 if (c
>= 'a' && c
<= 'f')
1901 else if (c
>= 'A' && c
<= 'F')
1911 goto add_char_nonext
;
1935 goto invalid_escape
;
1945 if (c
>= '!' && c
<= '~')
1946 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1948 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1955 cstr_ccat(outstr
, c
);
1957 cstr_wccat(outstr
, c
);
1959 /* add a trailing '\0' */
1961 cstr_ccat(outstr
, '\0');
1963 cstr_wccat(outstr
, '\0');
1966 void parse_string(const char *s
, int len
)
1968 uint8_t buf
[1000], *p
= buf
;
1971 if ((is_long
= *s
== 'L'))
1975 if (len
>= sizeof buf
)
1976 p
= tcc_malloc(len
+ 1);
1980 cstr_reset(&tokcstr
);
1981 parse_escape_string(&tokcstr
, p
, is_long
);
1987 /* XXX: make it portable */
1991 char_size
= sizeof(nwchar_t
);
1992 if (tokcstr
.size
<= char_size
)
1993 tcc_error("empty character constant");
1994 if (tokcstr
.size
> 2 * char_size
)
1995 tcc_warning("multi-character character constant");
1997 tokc
.i
= *(int8_t *)tokcstr
.data
;
2000 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2004 tokc
.str
.size
= tokcstr
.size
;
2005 tokc
.str
.data
= tokcstr
.data
;
2006 tokc
.str
.data_allocated
= tokcstr
.data_allocated
;
2014 /* we use 64 bit numbers */
2017 /* bn = (bn << shift) | or_val */
2018 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2022 for(i
=0;i
<BN_SIZE
;i
++) {
2024 bn
[i
] = (v
<< shift
) | or_val
;
2025 or_val
= v
>> (32 - shift
);
2029 static void bn_zero(unsigned int *bn
)
2032 for(i
=0;i
<BN_SIZE
;i
++) {
2037 /* parse number in null terminated string 'p' and return it in the
2039 static void parse_number(const char *p
)
2041 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2043 unsigned int bn
[BN_SIZE
];
2054 goto float_frac_parse
;
2055 } else if (t
== '0') {
2056 if (ch
== 'x' || ch
== 'X') {
2060 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2066 /* parse all digits. cannot check octal numbers at this stage
2067 because of floating point constants */
2069 if (ch
>= 'a' && ch
<= 'f')
2071 else if (ch
>= 'A' && ch
<= 'F')
2079 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2081 tcc_error("number too long");
2087 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2088 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2090 /* NOTE: strtox should support that for hexa numbers, but
2091 non ISOC99 libcs do not support it, so we prefer to do
2093 /* hexadecimal or binary floats */
2094 /* XXX: handle overflows */
2106 } else if (t
>= 'a') {
2108 } else if (t
>= 'A') {
2113 bn_lshift(bn
, shift
, t
);
2120 if (t
>= 'a' && t
<= 'f') {
2122 } else if (t
>= 'A' && t
<= 'F') {
2124 } else if (t
>= '0' && t
<= '9') {
2130 tcc_error("invalid digit");
2131 bn_lshift(bn
, shift
, t
);
2136 if (ch
!= 'p' && ch
!= 'P')
2143 } else if (ch
== '-') {
2147 if (ch
< '0' || ch
> '9')
2148 expect("exponent digits");
2149 while (ch
>= '0' && ch
<= '9') {
2150 exp_val
= exp_val
* 10 + ch
- '0';
2153 exp_val
= exp_val
* s
;
2155 /* now we can generate the number */
2156 /* XXX: should patch directly float number */
2157 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2158 d
= ldexp(d
, exp_val
- frac_bits
);
2163 /* float : should handle overflow */
2165 } else if (t
== 'L') {
2167 #ifdef TCC_TARGET_PE
2172 /* XXX: not large enough */
2173 tokc
.ld
= (long double)d
;
2180 /* decimal floats */
2182 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2187 while (ch
>= '0' && ch
<= '9') {
2188 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2194 if (ch
== 'e' || ch
== 'E') {
2195 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2199 if (ch
== '-' || ch
== '+') {
2200 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2205 if (ch
< '0' || ch
> '9')
2206 expect("exponent digits");
2207 while (ch
>= '0' && ch
<= '9') {
2208 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2220 tokc
.f
= strtof(token_buf
, NULL
);
2221 } else if (t
== 'L') {
2223 #ifdef TCC_TARGET_PE
2225 tokc
.d
= strtod(token_buf
, NULL
);
2228 tokc
.ld
= strtold(token_buf
, NULL
);
2232 tokc
.d
= strtod(token_buf
, NULL
);
2236 unsigned long long n
, n1
;
2237 int lcount
, ucount
, must_64bit
;
2240 /* integer number */
2243 if (b
== 10 && *q
== '0') {
2250 /* no need for checks except for base 10 / 8 errors */
2260 tcc_error("invalid digit");
2263 /* detect overflow */
2264 /* XXX: this test is not reliable */
2266 tcc_error("integer constant overflow");
2269 /* Determine the characteristics (unsigned and/or 64bit) the type of
2270 the constant must have according to the constant suffix(es) */
2271 lcount
= ucount
= must_64bit
= 0;
2277 tcc_error("three 'l's in integer constant");
2278 if (lcount
&& *(p
- 1) != ch
)
2279 tcc_error("incorrect integer suffix: %s", p1
);
2281 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2286 } else if (t
== 'U') {
2288 tcc_error("two 'u's in integer constant");
2296 /* Whether 64 bits are needed to hold the constant's value */
2297 if (n
& 0xffffffff00000000LL
|| must_64bit
) {
2305 /* Whether type must be unsigned to hold the constant's value */
2306 if (ucount
|| ((n1
>> 31) && (b
!= 10))) {
2307 if (tok
== TOK_CLLONG
)
2311 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2312 } else if (n1
>> 31) {
2313 if (tok
== TOK_CINT
)
2316 tcc_error("integer constant overflow");
2319 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2325 tcc_error("invalid number\n");
2329 #define PARSE2(c1, tok1, c2, tok2) \
2340 /* return next token without macro substitution */
2341 static inline void next_nomacro1(void)
2351 #if (__TINYC__ || __GNUC__)
2354 goto parse_ident_fast
;
2361 if (parse_flags
& PARSE_FLAG_SPACES
)
2362 goto keep_tok_flags
;
2363 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2372 /* first look if it is in fact an end of buffer */
2373 c
= handle_stray1(p
);
2380 TCCState
*s1
= tcc_state
;
2381 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2382 && !(tok_flags
& TOK_FLAG_EOF
)) {
2383 tok_flags
|= TOK_FLAG_EOF
;
2385 goto keep_tok_flags
;
2386 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2388 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2389 tcc_error("missing #endif");
2390 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2391 /* no include left : end of file. */
2394 tok_flags
&= ~TOK_FLAG_EOF
;
2395 /* pop include file */
2397 /* test if previous '#endif' was after a #ifdef at
2399 if (tok_flags
& TOK_FLAG_ENDIF
) {
2401 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2403 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2404 tok_flags
&= ~TOK_FLAG_ENDIF
;
2407 /* add end of include file debug info */
2408 if (tcc_state
->do_debug
) {
2409 put_stabd(N_EINCL
, 0, 0);
2411 /* pop include stack */
2413 s1
->include_stack_ptr
--;
2422 tok_flags
|= TOK_FLAG_BOL
;
2425 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2428 goto keep_tok_flags
;
2433 if ((tok_flags
& TOK_FLAG_BOL
) &&
2434 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2436 preprocess(tok_flags
& TOK_FLAG_BOF
);
2442 tok
= TOK_TWOSHARPS
;
2444 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2445 p
= parse_line_comment(p
- 1);
2454 /* dollar is allowed to start identifiers when not parsing asm */
2456 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2457 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2460 #if (__TINYC__ || __GNUC__)
2467 case 'a': case 'b': case 'c': case 'd':
2468 case 'e': case 'f': case 'g': case 'h':
2469 case 'i': case 'j': case 'k': case 'l':
2470 case 'm': case 'n': case 'o': case 'p':
2471 case 'q': case 'r': case 's': case 't':
2472 case 'u': case 'v': case 'w': case 'x':
2474 case 'A': case 'B': case 'C': case 'D':
2475 case 'E': case 'F': case 'G': case 'H':
2476 case 'I': case 'J': case 'K':
2477 case 'M': case 'N': case 'O': case 'P':
2478 case 'Q': case 'R': case 'S': case 'T':
2479 case 'U': case 'V': case 'W': case 'X':
2486 h
= TOK_HASH_FUNC(h
, c
);
2487 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2488 h
= TOK_HASH_FUNC(h
, c
);
2493 /* fast case : no stray found, so we have the full token
2494 and we have already hashed it */
2496 h
&= (TOK_HASH_SIZE
- 1);
2497 pts
= &hash_ident
[h
];
2502 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2504 pts
= &(ts
->hash_next
);
2506 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2510 cstr_reset(&tokcstr
);
2513 cstr_ccat(&tokcstr
, *p1
);
2519 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2521 cstr_ccat(&tokcstr
, c
);
2524 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2530 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2532 goto parse_ident_fast
;
2535 if (c
== '\'' || c
== '\"') {
2539 cstr_reset(&tokcstr
);
2540 cstr_ccat(&tokcstr
, 'L');
2541 goto parse_ident_slow
;
2546 case '0': case '1': case '2': case '3':
2547 case '4': case '5': case '6': case '7':
2549 cstr_reset(&tokcstr
);
2550 /* after the first digit, accept digits, alpha, '.' or sign if
2551 prefixed by 'eEpP' */
2555 cstr_ccat(&tokcstr
, c
);
2557 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2559 || ((c
== '+' || c
== '-')
2560 && (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P')
2564 /* We add a trailing '\0' to ease parsing */
2565 cstr_ccat(&tokcstr
, '\0');
2566 tokc
.str
.size
= tokcstr
.size
;
2567 tokc
.str
.data
= tokcstr
.data
;
2568 tokc
.str
.data_allocated
= tokcstr
.data_allocated
;
2573 /* special dot handling because it can also start a number */
2576 cstr_reset(&tokcstr
);
2577 cstr_ccat(&tokcstr
, '.');
2579 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2581 goto parse_ident_fast
;
2582 } else if (c
== '.') {
2588 *--p
= '.'; /* may underflow into file->unget[] */
2599 cstr_reset(&tokcstr
);
2601 cstr_ccat(&tokcstr
, 'L');
2602 cstr_ccat(&tokcstr
, c
);
2603 p
= parse_pp_string(p
, c
, &tokcstr
);
2604 cstr_ccat(&tokcstr
, c
);
2605 cstr_ccat(&tokcstr
, '\0');
2606 tokc
.str
.size
= tokcstr
.size
;
2607 tokc
.str
.data
= tokcstr
.data
;
2608 tokc
.str
.data_allocated
= tokcstr
.data_allocated
;
2617 } else if (c
== '<') {
2634 } else if (c
== '>') {
2652 } else if (c
== '=') {
2665 } else if (c
== '=') {
2678 } else if (c
== '=') {
2691 } else if (c
== '=') {
2694 } else if (c
== '>') {
2702 PARSE2('!', '!', '=', TOK_NE
)
2703 PARSE2('=', '=', '=', TOK_EQ
)
2704 PARSE2('*', '*', '=', TOK_A_MUL
)
2705 PARSE2('%', '%', '=', TOK_A_MOD
)
2706 PARSE2('^', '^', '=', TOK_A_XOR
)
2708 /* comments or operator */
2712 p
= parse_comment(p
);
2713 /* comments replaced by a blank */
2715 goto keep_tok_flags
;
2716 } else if (c
== '/') {
2717 p
= parse_line_comment(p
);
2719 goto keep_tok_flags
;
2720 } else if (c
== '=') {
2740 case '@': /* only used in assembler */
2746 tcc_error("unrecognized character \\x%02x", c
);
2752 #if defined(PARSE_DEBUG)
2753 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2757 /* return next token without macro substitution. Can read input from
2759 static void next_nomacro_spc(void)
2765 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2766 if (tok
== TOK_LINENUM
) {
2767 file
->line_num
= tokc
.i
;
2776 ST_FUNC
void next_nomacro(void)
2780 } while (tok
< 256 && (isidnum_table
[tok
- CH_EOF
] & IS_SPC
));
2784 static void macro_subst(
2785 TokenString
*tok_str
,
2787 const int *macro_str
,
2791 /* substitute arguments in replacement lists in macro_str by the values in
2792 args (field d) and return allocated string */
2793 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2805 TOK_GET(&t
, ¯o_str
, &cval
);
2810 TOK_GET(&t
, ¯o_str
, &cval
);
2813 s
= sym_find2(args
, t
);
2816 cstr_ccat(&cstr
, '\"');
2820 TOK_GET(&t
, &st
, &cval
);
2821 if (t
!= TOK_PLCHLDR
2823 && 0 == check_space(t
, &spc
)) {
2824 const char *s
= get_tok_str(t
, &cval
);
2826 if (t
== TOK_PPSTR
&& *s
!= '\'')
2827 add_char(&cstr
, *s
);
2829 cstr_ccat(&cstr
, *s
);
2835 cstr_ccat(&cstr
, '\"');
2836 cstr_ccat(&cstr
, '\0');
2838 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
2841 cval
.str
.size
= cstr
.size
;
2842 cval
.str
.data
= cstr
.data
;
2843 cval
.str
.data_allocated
= cstr
.data_allocated
;
2844 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
2845 tcc_free(cval
.str
.data_allocated
);
2848 expect("macro parameter after '#'");
2850 } else if (t
>= TOK_IDENT
) {
2851 s
= sym_find2(args
, t
);
2855 /* if '##' is present before or after, no arg substitution */
2856 if (*macro_str
== TOK_TWOSHARPS
|| t1
== TOK_TWOSHARPS
) {
2857 /* special case for var arg macros : ## eats the ','
2858 if empty VA_ARGS variable. */
2859 if (t1
== TOK_TWOSHARPS
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
2861 /* suppress ',' '##' */
2864 /* suppress '##' and add variable */
2871 TOK_GET(&t1
, &st
, &cval
);
2874 tok_str_add2(&str
, t1
, &cval
);
2880 /* NOTE: the stream cannot be read when macro
2881 substituing an argument */
2882 macro_subst(&str
, nested_list
, st
, 0);
2884 if (str
.len
== l0
) /* exanded to empty string */
2885 tok_str_add(&str
, TOK_PLCHLDR
);
2887 tok_str_add(&str
, t
);
2890 tok_str_add2(&str
, t
, &cval
);
2894 tok_str_add(&str
, 0);
2898 static char const ab_month_name
[12][4] =
2900 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2901 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2904 /* peek or read [ws_str == NULL] next token from function macro call,
2905 walking up macro levels up to the file if necessary */
2906 static int next_argstream(Sym
**nested_list
, int can_read_stream
, TokenString
*ws_str
)
2914 p
= macro_ptr
, t
= *p
;
2916 while (is_space(t
) || TOK_LINEFEED
== t
)
2917 tok_str_add(ws_str
, t
), t
= *++p
;
2919 if (t
== 0 && can_read_stream
) {
2921 /* also, end of scope for nested defined symbol */
2923 while (sa
&& sa
->v
== -1)
2932 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
2935 uint8_t *p
= file
->buf_ptr
;
2938 p
= parse_comment(p
);
2939 file
->buf_ptr
= p
- 1;
2940 } else if (c
== '/') {
2941 p
= parse_line_comment(p
);
2942 file
->buf_ptr
= p
- 1;
2947 tok_str_add(ws_str
, ch
);
2961 /* do macro substitution of current token with macro 's' and add
2962 result to (tok_str,tok_len). 'nested_list' is the list of all
2963 macros we got inside to avoid recursing. Return non zero if no
2964 substitution needs to be done */
2965 static int macro_subst_tok(
2966 TokenString
*tok_str
,
2969 int can_read_stream
)
2971 Sym
*args
, *sa
, *sa1
;
2972 int parlevel
, *mstr
, t
, t1
, spc
;
2979 /* if symbol is a macro, prepare substitution */
2980 /* special macros */
2981 if (tok
== TOK___LINE__
) {
2982 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2986 } else if (tok
== TOK___FILE__
) {
2987 cstrval
= file
->filename
;
2989 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2994 tm
= localtime(&ti
);
2995 if (tok
== TOK___DATE__
) {
2996 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2997 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2999 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3000 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3007 cstr_cat(&cstr
, cstrval
);
3008 cstr_ccat(&cstr
, '\0');
3009 cval
.str
.size
= cstr
.size
;
3010 cval
.str
.data
= cstr
.data
;
3011 cval
.str
.data_allocated
= cstr
.data_allocated
;
3012 tok_str_add2(tok_str
, t1
, &cval
);
3015 int saved_parse_flags
= parse_flags
;
3018 if (s
->type
.t
== MACRO_FUNC
) {
3019 /* whitespace between macro name and argument list */
3021 tok_str_new(&ws_str
);
3024 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
3025 | PARSE_FLAG_ACCEPT_STRAYS
;
3027 /* get next token from argument stream */
3028 t
= next_argstream(nested_list
, can_read_stream
, &ws_str
);
3030 /* not a macro substitution after all, restore the
3031 * macro token plus all whitespace we've read.
3032 * whitespace is intentionally not merged to preserve
3034 parse_flags
= saved_parse_flags
;
3035 tok_str_add(tok_str
, tok
);
3036 if (parse_flags
& PARSE_FLAG_SPACES
) {
3038 for (i
= 0; i
< ws_str
.len
; i
++)
3039 tok_str_add(tok_str
, ws_str
.str
[i
]);
3041 tok_str_free(ws_str
.str
);
3044 tok_str_free(ws_str
.str
);
3046 next_nomacro(); /* eat '(' */
3048 /* argument macro */
3051 /* NOTE: empty args are allowed, except if no args */
3054 next_argstream(nested_list
, can_read_stream
, NULL
);
3055 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3057 /* handle '()' case */
3058 if (!args
&& !sa
&& tok
== ')')
3061 tcc_error("macro '%s' used with too many args",
3062 get_tok_str(s
->v
, 0));
3065 /* NOTE: non zero sa->t indicates VA_ARGS */
3066 while ((parlevel
> 0 ||
3068 (tok
!= ',' || sa
->type
.t
)))) {
3069 if (tok
== TOK_EOF
|| tok
== 0)
3073 else if (tok
== ')')
3075 if (tok
== TOK_LINEFEED
)
3077 if (!check_space(tok
, &spc
))
3078 tok_str_add2(&str
, tok
, &tokc
);
3079 next_argstream(nested_list
, can_read_stream
, NULL
);
3084 tok_str_add(&str
, 0);
3085 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3089 /* special case for gcc var args: add an empty
3090 var arg argument if it is omitted */
3091 if (sa
&& sa
->type
.t
&& gnu_ext
)
3099 tcc_error("macro '%s' used with too few args",
3100 get_tok_str(s
->v
, 0));
3103 parse_flags
= saved_parse_flags
;
3105 /* now subst each arg */
3106 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3111 tok_str_free(sa
->d
);
3117 sym_push2(nested_list
, s
->v
, 0, 0);
3118 parse_flags
= saved_parse_flags
;
3119 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
3121 /* pop nested defined symbol */
3123 *nested_list
= sa1
->prev
;
3131 int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3137 if (t1
!= TOK_PLCHLDR
)
3138 cstr_cat(&cstr
, get_tok_str(t1
, v1
));
3140 if (t2
!= TOK_PLCHLDR
)
3141 cstr_cat(&cstr
, get_tok_str(t2
, v2
));
3142 cstr_ccat(&cstr
, '\0');
3144 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3145 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3148 if (0 == *file
->buf_ptr
)
3152 tcc_warning("pasting <%.*s> and <%s> does not give a valid preprocessing token",
3153 n
, cstr
.data
, (char*)cstr
.data
+ n
);
3158 //printf("paste <%s>\n", (char*)cstr.data);
3163 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3164 return the resulting string (which must be freed). */
3165 static inline int *macro_twosharps(const int *ptr0
)
3169 TokenString macro_str1
;
3170 int start_of_nosubsts
= -1;
3173 /* we search the first '##' */
3174 for (ptr
= ptr0
;;) {
3175 TOK_GET(&t
, &ptr
, &cval
);
3176 if (t
== TOK_TWOSHARPS
)
3182 tok_str_new(¯o_str1
);
3184 //tok_print(" $$$", ptr0);
3185 for (ptr
= ptr0
;;) {
3186 TOK_GET(&t
, &ptr
, &cval
);
3189 if (t
== TOK_TWOSHARPS
)
3191 while (*ptr
== TOK_TWOSHARPS
) {
3193 /* given 'a##b', remove nosubsts preceding 'a' */
3194 if (start_of_nosubsts
>= 0)
3195 macro_str1
.len
= start_of_nosubsts
;
3196 /* given 'a##b', remove nosubsts preceding 'b' */
3197 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3199 if (t1
&& t1
!= TOK_TWOSHARPS
3200 && t1
!= ':') /* 'a##:' don't build a new token */
3202 TOK_GET(&t1
, &ptr
, &cv1
);
3203 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3204 paste_tokens(t
, &cval
, t1
, &cv1
);
3205 t
= tok
, cval
= tokc
;
3209 if (t
== TOK_NOSUBST
) {
3210 if (start_of_nosubsts
< 0)
3211 start_of_nosubsts
= macro_str1
.len
;
3213 start_of_nosubsts
= -1;
3215 tok_str_add2(¯o_str1
, t
, &cval
);
3217 tok_str_add(¯o_str1
, 0);
3218 //tok_print(" ###", macro_str1.str);
3219 return macro_str1
.str
;
3222 /* do macro substitution of macro_str and add result to
3223 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3224 inside to avoid recursing. */
3225 static void macro_subst(
3226 TokenString
*tok_str
,
3228 const int *macro_str
,
3234 int t
, spc
, nosubst
;
3236 int *macro_str1
= NULL
;
3238 /* first scan for '##' operator handling */
3242 /* first scan for '##' operator handling */
3243 if (can_read_stream
) {
3244 macro_str1
= macro_twosharps(ptr
);
3250 TOK_GET(&t
, &ptr
, &cval
);
3254 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3259 /* if nested substitution, do nothing */
3260 if (sym_find2(*nested_list
, t
)) {
3261 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3262 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3268 str
.str
= (int*)ptr
;
3269 begin_macro(&str
, 2);
3272 macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
3274 if (str
.alloc
== 3) {
3275 /* already finished by reading function macro arguments */
3283 spc
= (tok_str
->len
&&
3284 is_space(tok_last(tok_str
->str
,
3285 tok_str
->str
+ tok_str
->len
)));
3289 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3290 tcc_error("stray '\\' in program");
3293 if (!check_space(t
, &spc
))
3294 tok_str_add2(tok_str
, t
, &cval
);
3296 if (t
== TOK_NOSUBST
)
3301 tok_str_free(macro_str1
);
3305 /* return next token with macro substitution */
3306 ST_FUNC
void next(void)
3309 if (parse_flags
& PARSE_FLAG_SPACES
)
3315 if (tok
== TOK_NOSUBST
|| tok
== TOK_PLCHLDR
) {
3316 /* discard preprocessor markers */
3318 } else if (tok
== 0) {
3319 /* end of macro or unget token string */
3323 } else if (tok
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3325 /* if reading from file, try to substitute macros */
3326 s
= define_find(tok
);
3328 static TokenString str
; /* using static string for speed */
3329 Sym
*nested_list
= NULL
;
3332 macro_subst_tok(&str
, &nested_list
, s
, 1);
3333 tok_str_add(&str
, 0);
3334 begin_macro(&str
, 0);
3338 /* convert preprocessor tokens into C tokens */
3339 if (tok
== TOK_PPNUM
) {
3340 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3341 parse_number((char *)tokc
.str
.data
);
3342 } else if (tok
== TOK_PPSTR
) {
3343 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3344 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3348 /* push back current token and set current token to 'last_tok'. Only
3349 identifier case handled for labels. */
3350 ST_INLN
void unget_tok(int last_tok
)
3352 TokenString
*str
= tcc_malloc(sizeof *str
);
3354 tok_str_add2(str
, tok
, &tokc
);
3355 tok_str_add(str
, 0);
3356 begin_macro(str
, 1);
3360 /* better than nothing, but needs extension to handle '-E' option
3362 ST_FUNC
void preprocess_init(TCCState
*s1
)
3364 s1
->include_stack_ptr
= s1
->include_stack
;
3365 /* XXX: move that before to avoid having to initialize
3366 file->ifdef_stack_ptr ? */
3367 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3368 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3370 pvtop
= vtop
= vstack
- 1;
3371 s1
->pack_stack
[0] = 0;
3372 s1
->pack_stack_ptr
= s1
->pack_stack
;
3374 isidnum_table
['$' - CH_EOF
] =
3375 tcc_state
->dollars_in_identifiers
? IS_ID
: 0;
3377 isidnum_table
['.' - CH_EOF
] =
3378 (parse_flags
& PARSE_FLAG_ASM_FILE
) ? IS_ID
: 0;
3381 ST_FUNC
void preprocess_new(void)
3386 /* init isid table */
3387 for(i
= CH_EOF
; i
<128; i
++)
3388 isidnum_table
[i
- CH_EOF
]
3389 = is_space(i
) ? IS_SPC
3394 for(i
= 128; i
<256; i
++)
3395 isidnum_table
[i
- CH_EOF
] = IS_ID
;
3397 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3399 tok_ident
= TOK_IDENT
;
3408 tok_alloc(p
, r
- p
- 1);
3413 ST_FUNC
void preprocess_delete(void)
3417 /* free -D and compiler defines */
3420 /* cleanup from error/setjmp */
3426 n
= tok_ident
- TOK_IDENT
;
3427 for(i
= 0; i
< n
; i
++)
3428 tcc_free(table_ident
[i
]);
3429 tcc_free(table_ident
);
3433 /* Preprocess the current file */
3434 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3436 BufferedFile
**iptr
;
3437 int token_seen
, spcs
, level
;
3439 preprocess_init(s1
);
3440 ch
= file
->buf_ptr
[0];
3441 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3442 parse_flags
= PARSE_FLAG_PREPROCESS
3443 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3444 | PARSE_FLAG_LINEFEED
3446 | PARSE_FLAG_ACCEPT_STRAYS
3450 do next(); while (tok
!= TOK_EOF
); return 0;
3453 token_seen
= spcs
= 0;
3454 pp_line(s1
, file
, 0);
3457 iptr
= s1
->include_stack_ptr
;
3461 level
= s1
->include_stack_ptr
- iptr
;
3464 pp_line(s1
, *iptr
, 0);
3465 pp_line(s1
, file
, level
);
3468 if (0 == token_seen
) {
3473 if (tok
== TOK_LINEFEED
) {
3477 pp_line(s1
, file
, 0);
3478 while (s1
->ppfp
&& spcs
> 0)
3479 fputs(" ", s1
->ppfp
), --spcs
;
3483 } else if (tok
== TOK_LINEFEED
) {
3488 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);
3494 ST_FUNC
char *trimfront(char *p
)
3496 while (*p
&& (unsigned char)*p
<= ' ')
3501 ST_FUNC
char *trimback(char *a
, char *e
)
3503 while (e
> a
&& (unsigned char)e
[-1] <= ' ')