2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 /********************************************************/
24 /* global variables */
26 ST_DATA
int tok_flags
;
27 ST_DATA
int parse_flags
;
29 ST_DATA
struct BufferedFile
*file
;
32 ST_DATA
const int *macro_ptr
;
33 ST_DATA CString tokcstr
; /* current parsed string, if any */
35 /* display benchmark infos */
36 ST_DATA
int total_lines
;
37 ST_DATA
int total_bytes
;
38 ST_DATA
int tok_ident
;
39 ST_DATA TokenSym
**table_ident
;
41 /* ------------------------------------------------------------------------- */
43 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
44 static char token_buf
[STRING_MAX_SIZE
+ 1];
45 static unsigned char isidnum_table
[256 - CH_EOF
];
46 /* isidnum_table flags: */
51 static TokenString
*macro_stack
;
53 static const char tcc_keywords
[] =
54 #define DEF(id, str) str "\0"
59 /* WARNING: the content of this string encodes token numbers */
60 static const unsigned char tok_two_chars
[] =
62 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
63 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
84 '.','.', 0xa8, // C++ token ?
85 '#','#', TOK_TWOSHARPS
,
89 static void next_nomacro_spc(void);
91 ST_FUNC
void skip(int c
)
94 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
98 ST_FUNC
void expect(const char *msg
)
100 tcc_error("%s expected", msg
);
103 ST_FUNC
void begin_macro(TokenString
*str
, int alloc
)
106 str
->prev
= macro_stack
;
107 str
->prev_ptr
= macro_ptr
;
108 macro_ptr
= str
->str
;
112 ST_FUNC
void end_macro(void)
114 TokenString
*str
= macro_stack
;
115 macro_stack
= str
->prev
;
116 macro_ptr
= str
->prev_ptr
;
117 if (str
->alloc
== 2) {
118 str
->alloc
= 3; /* just mark as finished */
120 tok_str_free(str
->str
);
126 /* ------------------------------------------------------------------------- */
127 /* CString handling */
128 static void cstr_realloc(CString
*cstr
, int new_size
)
133 size
= cstr
->size_allocated
;
135 size
= 8; /* no need to allocate a too small first string */
136 while (size
< new_size
)
138 data
= tcc_realloc(cstr
->data_allocated
, size
);
139 cstr
->data_allocated
= data
;
140 cstr
->size_allocated
= size
;
145 ST_FUNC
void cstr_ccat(CString
*cstr
, int ch
)
148 size
= cstr
->size
+ 1;
149 if (size
> cstr
->size_allocated
)
150 cstr_realloc(cstr
, size
);
151 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
155 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
)
167 /* add a wide char */
168 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
171 size
= cstr
->size
+ sizeof(nwchar_t
);
172 if (size
> cstr
->size_allocated
)
173 cstr_realloc(cstr
, size
);
174 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
178 ST_FUNC
void cstr_new(CString
*cstr
)
180 memset(cstr
, 0, sizeof(CString
));
183 /* free string and reset it to NULL */
184 ST_FUNC
void cstr_free(CString
*cstr
)
186 tcc_free(cstr
->data_allocated
);
190 /* reset string to empty */
191 ST_FUNC
void cstr_reset(CString
*cstr
)
197 static void add_char(CString
*cstr
, int c
)
199 if (c
== '\'' || c
== '\"' || c
== '\\') {
200 /* XXX: could be more precise if char or string */
201 cstr_ccat(cstr
, '\\');
203 if (c
>= 32 && c
<= 126) {
206 cstr_ccat(cstr
, '\\');
208 cstr_ccat(cstr
, 'n');
210 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
211 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
212 cstr_ccat(cstr
, '0' + (c
& 7));
217 /* ------------------------------------------------------------------------- */
218 /* allocate a new token */
219 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
221 TokenSym
*ts
, **ptable
;
224 if (tok_ident
>= SYM_FIRST_ANOM
)
225 tcc_error("memory full (symbols)");
227 /* expand token table if needed */
228 i
= tok_ident
- TOK_IDENT
;
229 if ((i
% TOK_ALLOC_INCR
) == 0) {
230 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
231 table_ident
= ptable
;
234 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
236 ts
->tok
= tok_ident
++;
237 ts
->sym_define
= NULL
;
238 ts
->sym_label
= NULL
;
239 ts
->sym_struct
= NULL
;
240 ts
->sym_identifier
= NULL
;
242 ts
->hash_next
= NULL
;
243 memcpy(ts
->str
, str
, len
);
249 #define TOK_HASH_INIT 1
250 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
252 /* find a token and add it if not found */
253 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
261 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
262 h
&= (TOK_HASH_SIZE
- 1);
264 pts
= &hash_ident
[h
];
269 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
271 pts
= &(ts
->hash_next
);
273 return tok_alloc_new(pts
, str
, len
);
276 /* XXX: buffer overflow */
277 /* XXX: float tokens */
278 ST_FUNC
const char *get_tok_str(int v
, CValue
*cv
)
280 static char buf
[STRING_MAX_SIZE
+ 1];
281 static CString cstr_buf
;
285 /* NOTE: to go faster, we give a fixed buffer for small strings */
286 cstr_reset(&cstr_buf
);
288 cstr_buf
.size_allocated
= sizeof(buf
);
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>");
338 cstr_cat(&cstr_buf
, "<double>");
341 cstr_cat(&cstr_buf
, "<long double>");
344 cstr_cat(&cstr_buf
, "<linenumber>");
346 //return NULL; /* should not happen */
348 /* above tokens have value, the ones below don't */
357 return strcpy(p
, "...");
359 return strcpy(p
, "<<=");
361 return strcpy(p
, ">>=");
364 /* search in two bytes table */
365 const unsigned char *q
= tok_two_chars
;
376 sprintf(buf
, "<%02x>", v
);
382 } else if (v
< tok_ident
) {
383 return table_ident
[v
- TOK_IDENT
]->str
;
384 } else if (v
>= SYM_FIRST_ANOM
) {
385 /* special name for anonymous symbol */
386 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
388 /* should never happen */
393 return cstr_buf
.data
;
396 /* return the current character, handling end of block if necessary
398 ST_FUNC
int handle_eob(void)
400 BufferedFile
*bf
= file
;
403 /* only tries to read if really end of buffer */
404 if (bf
->buf_ptr
>= bf
->buf_end
) {
406 #if defined(PARSE_DEBUG)
411 len
= read(bf
->fd
, bf
->buffer
, len
);
418 bf
->buf_ptr
= bf
->buffer
;
419 bf
->buf_end
= bf
->buffer
+ len
;
420 *bf
->buf_end
= CH_EOB
;
422 if (bf
->buf_ptr
< bf
->buf_end
) {
423 return bf
->buf_ptr
[0];
425 bf
->buf_ptr
= bf
->buf_end
;
430 /* read next char from current input file and handle end of input buffer */
431 ST_INLN
void inp(void)
433 ch
= *(++(file
->buf_ptr
));
434 /* end of buffer/file handling */
439 /* handle '\[\r]\n' */
440 static int handle_stray_noerror(void)
447 } else if (ch
== '\r') {
461 static void handle_stray(void)
463 if (handle_stray_noerror())
464 tcc_error("stray '\\' in program");
467 /* skip the stray and handle the \\n case. Output an error if
468 incorrect char after the stray */
469 static int handle_stray1(uint8_t *p
)
474 if (p
>= file
->buf_end
) {
481 if (handle_stray_noerror()) {
482 if (!(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
483 tcc_error("stray '\\' in program");
484 *--file
->buf_ptr
= '\\';
491 /* handle just the EOB case, but not stray */
492 #define PEEKC_EOB(c, p)\
503 /* handle the complicated stray case */
509 c = handle_stray1(p);\
514 /* input with '\[\r]\n' handling. Note that this function cannot
515 handle other characters after '\', so you cannot call it inside
516 strings or comments */
517 ST_FUNC
void minp(void)
525 /* single line C++ comments */
526 static uint8_t *parse_line_comment(uint8_t *p
)
534 if (c
== '\n' || c
== CH_EOF
) {
536 } else if (c
== '\\') {
545 } else if (c
== '\r') {
563 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
572 if (c
== '\n' || c
== '*' || c
== '\\')
576 if (c
== '\n' || c
== '*' || c
== '\\')
580 /* now we can handle all the cases */
584 } else if (c
== '*') {
590 } else if (c
== '/') {
592 } else if (c
== '\\') {
597 tcc_error("unexpected end of file in comment");
599 /* skip '\[\r]\n', otherwise just skip the stray */
605 } else if (c
== '\r') {
622 /* stray, eob or eof */
627 tcc_error("unexpected end of file in comment");
628 } else if (c
== '\\') {
640 static inline void skip_spaces(void)
642 while (isidnum_table
[ch
- CH_EOF
] & IS_SPC
)
646 static inline int check_space(int t
, int *spc
)
648 if (t
< 256 && (isidnum_table
[t
- CH_EOF
] & IS_SPC
)) {
657 /* parse a string without interpreting escapes */
658 static uint8_t *parse_pp_string(uint8_t *p
,
659 int sep
, CString
*str
)
667 } else if (c
== '\\') {
673 /* XXX: indicate line number of start of string */
674 tcc_error("missing terminating %c character", sep
);
675 } else if (c
== '\\') {
676 /* escape : just skip \[\r]\n */
681 } else if (c
== '\r') {
684 expect("'\n' after '\r'");
687 } else if (c
== CH_EOF
) {
688 goto unterminated_string
;
691 cstr_ccat(str
, '\\');
697 } else if (c
== '\n') {
700 } else if (c
== '\r') {
704 cstr_ccat(str
, '\r');
720 /* skip block of text until #else, #elif or #endif. skip also pairs of
722 static void preprocess_skip(void)
724 int a
, start_of_line
, c
, in_warn_or_error
;
731 in_warn_or_error
= 0;
752 } else if (c
== '\\') {
753 ch
= file
->buf_ptr
[0];
754 handle_stray_noerror();
761 if (in_warn_or_error
)
763 p
= parse_pp_string(p
, c
, NULL
);
767 if (in_warn_or_error
)
774 p
= parse_comment(p
);
775 } else if (ch
== '/') {
776 p
= parse_line_comment(p
);
786 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
788 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
790 else if (tok
== TOK_ENDIF
)
792 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
793 in_warn_or_error
= 1;
794 else if (tok
== TOK_LINEFEED
)
796 } else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
797 p
= parse_line_comment(p
);
810 /* ParseState handling */
812 /* XXX: currently, no include file info is stored. Thus, we cannot display
813 accurate messages if the function or data definition spans multiple
816 /* save current parse state in 's' */
817 ST_FUNC
void save_parse_state(ParseState
*s
)
819 s
->line_num
= file
->line_num
;
820 s
->macro_ptr
= macro_ptr
;
825 /* restore parse state from 's' */
826 ST_FUNC
void restore_parse_state(ParseState
*s
)
828 file
->line_num
= s
->line_num
;
829 macro_ptr
= s
->macro_ptr
;
834 /* return the number of additional 'ints' necessary to store the
836 static inline int tok_size(const int *p
)
851 return 1 + ((sizeof(CString
) + ((CString
*)(p
+1))->size
+ 3) >> 2);
857 return 1 + LDOUBLE_SIZE
/ 4;
863 /* token string handling */
865 ST_INLN
void tok_str_new(TokenString
*s
)
869 s
->allocated_len
= 0;
870 s
->last_line_num
= -1;
873 ST_FUNC
void tok_str_free(int *str
)
878 static int *tok_str_realloc(TokenString
*s
)
882 if (s
->allocated_len
== 0) {
885 len
= s
->allocated_len
* 2;
887 str
= tcc_realloc(s
->str
, len
* sizeof(int));
888 s
->allocated_len
= len
;
893 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
899 if (len
>= s
->allocated_len
)
900 str
= tok_str_realloc(s
);
905 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
912 /* allocate space for worst case */
913 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
914 str
= tok_str_realloc(s
);
923 str
[len
++] = cv
->tab
[0];
930 /* Insert the string into the int array. */
932 1 + (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
933 while ((len
+ nb_words
) > s
->allocated_len
)
934 str
= tok_str_realloc(s
);
935 str
[len
] = cv
->str
.size
;
936 memcpy(&str
[len
+ 1], cv
->str
.data
, cv
->str
.size
);
943 #if LDOUBLE_SIZE == 8
946 str
[len
++] = cv
->tab
[0];
947 str
[len
++] = cv
->tab
[1];
949 #if LDOUBLE_SIZE == 12
951 str
[len
++] = cv
->tab
[0];
952 str
[len
++] = cv
->tab
[1];
953 str
[len
++] = cv
->tab
[2];
954 #elif LDOUBLE_SIZE == 16
956 str
[len
++] = cv
->tab
[0];
957 str
[len
++] = cv
->tab
[1];
958 str
[len
++] = cv
->tab
[2];
959 str
[len
++] = cv
->tab
[3];
960 #elif LDOUBLE_SIZE != 8
961 #error add long double size support
970 /* add the current parse token in token string 's' */
971 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
975 /* save line number info */
976 if (file
->line_num
!= s
->last_line_num
) {
977 s
->last_line_num
= file
->line_num
;
978 cval
.i
= s
->last_line_num
;
979 tok_str_add2(s
, TOK_LINENUM
, &cval
);
981 tok_str_add2(s
, tok
, &tokc
);
984 /* get a token from an integer array and increment pointer
985 accordingly. we code it as a macro to avoid pointer aliasing. */
986 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
1005 cv
->str
.size
= *p
++;
1007 cv
->str
.data_allocated
= 0;
1008 p
+= (cv
->str
.size
+ sizeof(int) - 1) / sizeof(int);
1016 #if LDOUBLE_SIZE == 16
1018 #elif LDOUBLE_SIZE == 12
1020 #elif LDOUBLE_SIZE == 8
1023 # error add long double size support
1036 /* Calling this function is expensive, but it is not possible
1037 to read a token string backwards. */
1038 static int tok_last(const int *str0
, const int *str1
)
1040 const int *str
= str0
;
1045 TOK_GET(&tok
, &str
, &cval
);
1049 static int macro_is_equal(const int *a
, const int *b
)
1051 char buf
[STRING_MAX_SIZE
+ 1];
1055 TOK_GET(&t
, &a
, &cv
);
1056 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1057 TOK_GET(&t
, &b
, &cv
);
1058 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1064 static void pp_line(TCCState
*s1
, BufferedFile
*f
, int level
)
1066 int d
= f
->line_num
- f
->line_ref
;
1067 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_NONE
1068 || (level
== 0 && f
->line_ref
&& d
< 8))
1071 fputs("\n", s1
->ppfp
), --d
;
1074 if (s1
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_STD
) {
1075 fprintf(s1
->ppfp
, "#line %d \"%s\"\n", f
->line_num
, f
->filename
);
1078 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
,
1079 level
> 0 ? " 1" : level
< 0 ? " 2" : "");
1081 f
->line_ref
= f
->line_num
;
1084 static void tok_print(const char *msg
, const int *str
)
1086 FILE *pr
= tcc_state
->ppfp
;
1090 fprintf(pr
, "%s ", msg
);
1092 TOK_GET(&t
, &str
, &cval
);
1095 fprintf(pr
,"%s", get_tok_str(t
, &cval
));
1100 static int define_print_prepared(Sym
*s
)
1102 if (!s
|| !tcc_state
->ppfp
|| tcc_state
->dflag
== 0)
1105 if (s
->v
< TOK_IDENT
|| s
->v
>= tok_ident
)
1110 pp_line(tcc_state
, file
, 0);
1111 file
->line_ref
= ++file
->line_num
;
1116 static void define_print(int v
)
1118 FILE *pr
= tcc_state
->ppfp
;
1122 if (define_print_prepared(s
) == 0)
1125 fprintf(pr
, "// #define %s", get_tok_str(v
, NULL
));
1126 if (s
->type
.t
== MACRO_FUNC
) {
1131 fprintf(pr
,"%s", get_tok_str(a
->v
& ~SYM_FIELD
, NULL
));
1138 tok_print("", s
->d
);
1141 static void undef_print(int v
)
1143 FILE *pr
= tcc_state
->ppfp
;
1147 if (define_print_prepared(s
) == 0)
1150 fprintf(pr
, "// #undef %s\n", get_tok_str(s
->v
, NULL
));
1153 ST_FUNC
void print_defines(void)
1155 Sym
*top
= define_stack
;
1157 define_print(top
->v
);
1162 /* defines handling */
1163 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1168 if (s
&& !macro_is_equal(s
->d
, str
))
1169 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1171 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1173 s
->next
= first_arg
;
1174 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1177 /* undefined a define symbol. Its name is just set to zero */
1178 ST_FUNC
void define_undef(Sym
*s
)
1182 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1183 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1186 ST_INLN Sym
*define_find(int v
)
1189 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1191 return table_ident
[v
]->sym_define
;
1194 /* free define stack until top reaches 'b' */
1195 ST_FUNC
void free_defines(Sym
*b
)
1203 /* do not free args or predefined defines */
1205 tok_str_free(top
->d
);
1207 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1208 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1216 ST_FUNC Sym
*label_find(int v
)
1219 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1221 return table_ident
[v
]->sym_label
;
1224 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1227 s
= sym_push2(ptop
, v
, 0, 0);
1229 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1230 if (ptop
== &global_label_stack
) {
1231 /* modify the top most local identifier, so that
1232 sym_identifier will point to 's' when popped */
1234 ps
= &(*ps
)->prev_tok
;
1241 /* pop labels until element last is reached. Look if any labels are
1242 undefined. Define symbols if '&&label' was used. */
1243 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1246 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1248 if (s
->r
== LABEL_DECLARED
) {
1249 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1250 } else if (s
->r
== LABEL_FORWARD
) {
1251 tcc_error("label '%s' used but not defined",
1252 get_tok_str(s
->v
, NULL
));
1255 /* define corresponding symbol. A size of
1257 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1261 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1267 /* eval an expression for #if/#elif */
1268 static int expr_preprocess(void)
1274 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1275 next(); /* do macro subst */
1276 if (tok
== TOK_DEFINED
) {
1281 c
= define_find(tok
) != 0;
1286 } else if (tok
>= TOK_IDENT
) {
1287 /* if undefined macro */
1291 tok_str_add_tok(&str
);
1293 tok_str_add(&str
, -1); /* simulate end of file */
1294 tok_str_add(&str
, 0);
1295 /* now evaluate C constant expression */
1296 begin_macro(&str
, 0);
1304 /* parse after #define */
1305 ST_FUNC
void parse_define(void)
1307 Sym
*s
, *first
, **ps
;
1308 int v
, t
, varg
, is_vaargs
, spc
;
1309 int saved_parse_flags
= parse_flags
;
1314 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1315 /* XXX: should check if same macro (ANSI) */
1318 /* '(' must be just after macro definition for MACRO_FUNC */
1319 parse_flags
|= PARSE_FLAG_SPACES
;
1324 if (tok
!= ')') for (;;) {
1328 if (varg
== TOK_DOTS
) {
1329 varg
= TOK___VA_ARGS__
;
1331 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1335 if (varg
< TOK_IDENT
)
1337 tcc_error("bad macro parameter list");
1338 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1343 if (tok
!= ',' || is_vaargs
)
1352 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1353 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1354 /* remove spaces around ## and after '#' */
1355 if (TOK_TWOSHARPS
== tok
) {
1361 } else if ('#' == tok
) {
1363 } else if (check_space(tok
, &spc
)) {
1366 tok_str_add2(&str
, tok
, &tokc
);
1371 parse_flags
= saved_parse_flags
;
1373 --str
.len
; /* remove trailing space */
1374 tok_str_add(&str
, 0);
1377 tcc_error("'##' cannot appear at either end of macro");
1378 define_push(v
, t
, str
.str
, first
);
1382 static inline int hash_cached_include(const char *filename
)
1384 const unsigned char *s
;
1388 s
= (unsigned char *) filename
;
1390 h
= TOK_HASH_FUNC(h
, *s
);
1393 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1397 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1401 h
= hash_cached_include(filename
);
1402 i
= s1
->cached_includes_hash
[h
];
1406 e
= s1
->cached_includes
[i
- 1];
1407 if (0 == PATHCMP(e
->filename
, filename
))
1414 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1419 if (search_cached_include(s1
, filename
))
1422 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1424 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1425 strcpy(e
->filename
, filename
);
1426 e
->ifndef_macro
= ifndef_macro
;
1427 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1428 /* add in hash table */
1429 h
= hash_cached_include(filename
);
1430 e
->hash_next
= s1
->cached_includes_hash
[h
];
1431 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1434 static void pragma_parse(TCCState
*s1
)
1437 if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1441 if (next(), tok
!= '(')
1443 if (next(), tok
!= TOK_STR
)
1445 v
= tok_alloc(tokc
.str
.data
, tokc
.str
.size
- 1)->tok
;
1446 if (next(), tok
!= ')')
1448 if (t
== TOK_push_macro
) {
1449 while (NULL
== (s
= define_find(v
)))
1450 define_push(v
, 0, NULL
, NULL
);
1451 s
->type
.ref
= s
; /* set push boundary */
1453 for (s
= define_stack
; s
; s
= s
->prev
)
1454 if (s
->v
== v
&& s
->type
.ref
== s
) {
1460 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1462 tcc_warning("unbalanced #pragma pop_macro");
1464 } else if (tok
== TOK_once
) {
1465 add_cached_include(s1
, file
->filename
, TOK_once
);
1467 } else if (s1
->ppfp
) {
1468 /* tcc -E: keep pragmas below unchanged */
1470 unget_tok(TOK_PRAGMA
);
1472 unget_tok(TOK_LINEFEED
);
1474 } else if (tok
== TOK_pack
) {
1476 #pragma pack(1) // set
1477 #pragma pack() // reset to default
1478 #pragma pack(push,1) // push & set
1479 #pragma pack(pop) // restore previous */
1482 if (tok
== TOK_ASM_pop
) {
1484 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1486 tcc_error("out of pack stack");
1488 s1
->pack_stack_ptr
--;
1492 if (tok
== TOK_ASM_push
) {
1494 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1496 s1
->pack_stack_ptr
++;
1499 if (tok
!= TOK_CINT
)
1502 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1506 *s1
->pack_stack_ptr
= val
;
1511 } else if (tok
== TOK_comment
) {
1521 file
= tcc_strdup((char *)tokc
.str
.data
);
1522 dynarray_add((void ***)&s1
->pragma_libs
, &s1
->nb_pragma_libs
, file
);
1528 if (s1
->warn_unsupported
)
1529 tcc_warning("#pragma %s is ignored", get_tok_str(tok
, &tokc
));
1534 tcc_error("malformed #pragma directive");
1538 /* is_bof is true if first non space token at beginning of file */
1539 ST_FUNC
void preprocess(int is_bof
)
1541 TCCState
*s1
= tcc_state
;
1542 int i
, c
, n
, saved_parse_flags
;
1546 saved_parse_flags
= parse_flags
;
1547 parse_flags
= PARSE_FLAG_PREPROCESS
1548 | PARSE_FLAG_TOK_NUM
1549 | PARSE_FLAG_TOK_STR
1550 | PARSE_FLAG_LINEFEED
1551 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
1563 s
= define_find(tok
);
1564 /* undefine symbol by putting an invalid name */
1569 case TOK_INCLUDE_NEXT
:
1570 ch
= file
->buf_ptr
[0];
1571 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1576 } else if (ch
== '\"') {
1581 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1582 if ((q
- buf
) < sizeof(buf
) - 1)
1585 if (handle_stray_noerror() == 0)
1593 /* eat all spaces and comments after include */
1594 /* XXX: slightly incorrect */
1595 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1599 /* computed #include : either we have only strings or
1600 we have anything enclosed in '<>' */
1603 if (tok
== TOK_STR
) {
1604 while (tok
!= TOK_LINEFEED
) {
1605 if (tok
!= TOK_STR
) {
1607 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1609 pstrcat(buf
, sizeof(buf
), (char *)tokc
.str
.data
);
1615 while (tok
!= TOK_LINEFEED
) {
1616 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1620 /* check syntax and remove '<>' */
1621 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1622 goto include_syntax
;
1623 memmove(buf
, buf
+ 1, len
- 2);
1624 buf
[len
- 2] = '\0';
1629 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1630 tcc_error("#include recursion too deep");
1631 /* store current file in stack, but increment stack later below */
1632 *s1
->include_stack_ptr
= file
;
1633 i
= tok
== TOK_INCLUDE_NEXT
? file
->include_next_index
: 0;
1634 n
= 2 + s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1635 for (; i
< n
; ++i
) {
1636 char buf1
[sizeof file
->filename
];
1641 /* check absolute include path */
1642 if (!IS_ABSPATH(buf
))
1646 } else if (i
== 1) {
1647 /* search in current dir if "header.h" */
1650 path
= file
->filename
;
1651 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1654 /* search in all the include paths */
1655 int j
= i
- 2, k
= j
- s1
->nb_include_paths
;
1656 path
= k
< 0 ? s1
->include_paths
[j
] : s1
->sysinclude_paths
[k
];
1657 pstrcpy(buf1
, sizeof(buf1
), path
);
1658 pstrcat(buf1
, sizeof(buf1
), "/");
1661 pstrcat(buf1
, sizeof(buf1
), buf
);
1662 e
= search_cached_include(s1
, buf1
);
1663 if (e
&& (define_find(e
->ifndef_macro
) || e
->ifndef_macro
== TOK_once
)) {
1664 /* no need to parse the include because the 'ifndef macro'
1667 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1672 if (tcc_open(s1
, buf1
) < 0)
1675 file
->include_next_index
= i
+ 1;
1677 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1679 /* update target deps */
1680 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1682 /* push current file in stack */
1683 ++s1
->include_stack_ptr
;
1684 /* add include file debug info */
1686 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1687 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1688 ch
= file
->buf_ptr
[0];
1691 tcc_error("include file '%s' not found", buf
);
1698 c
= expr_preprocess();
1704 if (tok
< TOK_IDENT
)
1705 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1709 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1711 file
->ifndef_macro
= tok
;
1714 c
= (define_find(tok
) != 0) ^ c
;
1716 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1717 tcc_error("memory full (ifdef)");
1718 *s1
->ifdef_stack_ptr
++ = c
;
1721 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1722 tcc_error("#else without matching #if");
1723 if (s1
->ifdef_stack_ptr
[-1] & 2)
1724 tcc_error("#else after #else");
1725 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1728 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1729 tcc_error("#elif without matching #if");
1730 c
= s1
->ifdef_stack_ptr
[-1];
1732 tcc_error("#elif after #else");
1733 /* last #if/#elif expression was true: we skip */
1736 c
= expr_preprocess();
1737 s1
->ifdef_stack_ptr
[-1] = c
;
1739 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1740 file
->ifndef_macro
= 0;
1750 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1751 tcc_error("#endif without matching #if");
1752 s1
->ifdef_stack_ptr
--;
1753 /* '#ifndef macro' was at the start of file. Now we check if
1754 an '#endif' is exactly at the end of file */
1755 if (file
->ifndef_macro
&&
1756 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1757 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1758 /* need to set to zero to avoid false matches if another
1759 #ifndef at middle of file */
1760 file
->ifndef_macro
= 0;
1761 while (tok
!= TOK_LINEFEED
)
1763 tok_flags
|= TOK_FLAG_ENDIF
;
1768 n
= strtoul((char*)tokc
.str
.data
, &q
, 10);
1772 if (tok
!= TOK_CINT
)
1774 tcc_error("wrong #line format");
1778 if (tok
!= TOK_LINEFEED
) {
1780 pstrcpy(file
->filename
, sizeof(file
->filename
), (char *)tokc
.str
.data
);
1781 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
1788 total_lines
+= file
->line_num
- n
;
1791 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1796 ch
= file
->buf_ptr
[0];
1799 while (ch
!= '\n' && ch
!= CH_EOF
) {
1800 if ((q
- buf
) < sizeof(buf
) - 1)
1803 if (handle_stray_noerror() == 0)
1810 tcc_error("#error %s", buf
);
1812 tcc_warning("#warning %s", buf
);
1820 /* ignore gas line comment in an 'S' file. */
1821 if (saved_parse_flags
& PARSE_FLAG_ASM_FILE
)
1823 if (tok
== '!' && is_bof
)
1824 /* '!' is ignored at beginning to allow C scripts. */
1826 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1828 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1831 /* ignore other preprocess commands or #! for C scripts */
1832 while (tok
!= TOK_LINEFEED
)
1835 parse_flags
= saved_parse_flags
;
1838 /* evaluate escape codes in a string. */
1839 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1854 case '0': case '1': case '2': case '3':
1855 case '4': case '5': case '6': case '7':
1856 /* at most three octal digits */
1861 n
= n
* 8 + c
- '0';
1865 n
= n
* 8 + c
- '0';
1870 goto add_char_nonext
;
1878 if (c
>= 'a' && c
<= 'f')
1880 else if (c
>= 'A' && c
<= 'F')
1890 goto add_char_nonext
;
1914 goto invalid_escape
;
1924 if (c
>= '!' && c
<= '~')
1925 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1927 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1934 cstr_ccat(outstr
, c
);
1936 cstr_wccat(outstr
, c
);
1938 /* add a trailing '\0' */
1940 cstr_ccat(outstr
, '\0');
1942 cstr_wccat(outstr
, '\0');
1945 void parse_string(const char *s
, int len
)
1947 uint8_t buf
[1000], *p
= buf
;
1950 if ((is_long
= *s
== 'L'))
1954 if (len
>= sizeof buf
)
1955 p
= tcc_malloc(len
+ 1);
1959 cstr_reset(&tokcstr
);
1960 parse_escape_string(&tokcstr
, p
, is_long
);
1966 /* XXX: make it portable */
1970 char_size
= sizeof(nwchar_t
);
1971 if (tokcstr
.size
<= char_size
)
1972 tcc_error("empty character constant");
1973 if (tokcstr
.size
> 2 * char_size
)
1974 tcc_warning("multi-character character constant");
1976 tokc
.i
= *(int8_t *)tokcstr
.data
;
1979 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
1983 tokc
.str
.size
= tokcstr
.size
;
1984 tokc
.str
.data
= tokcstr
.data
;
1985 tokc
.str
.data_allocated
= tokcstr
.data_allocated
;
1993 /* we use 64 bit numbers */
1996 /* bn = (bn << shift) | or_val */
1997 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2001 for(i
=0;i
<BN_SIZE
;i
++) {
2003 bn
[i
] = (v
<< shift
) | or_val
;
2004 or_val
= v
>> (32 - shift
);
2008 static void bn_zero(unsigned int *bn
)
2011 for(i
=0;i
<BN_SIZE
;i
++) {
2016 /* parse number in null terminated string 'p' and return it in the
2018 static void parse_number(const char *p
)
2020 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2022 unsigned int bn
[BN_SIZE
];
2033 goto float_frac_parse
;
2034 } else if (t
== '0') {
2035 if (ch
== 'x' || ch
== 'X') {
2039 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2045 /* parse all digits. cannot check octal numbers at this stage
2046 because of floating point constants */
2048 if (ch
>= 'a' && ch
<= 'f')
2050 else if (ch
>= 'A' && ch
<= 'F')
2058 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2060 tcc_error("number too long");
2066 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2067 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2069 /* NOTE: strtox should support that for hexa numbers, but
2070 non ISOC99 libcs do not support it, so we prefer to do
2072 /* hexadecimal or binary floats */
2073 /* XXX: handle overflows */
2085 } else if (t
>= 'a') {
2087 } else if (t
>= 'A') {
2092 bn_lshift(bn
, shift
, t
);
2099 if (t
>= 'a' && t
<= 'f') {
2101 } else if (t
>= 'A' && t
<= 'F') {
2103 } else if (t
>= '0' && t
<= '9') {
2109 tcc_error("invalid digit");
2110 bn_lshift(bn
, shift
, t
);
2115 if (ch
!= 'p' && ch
!= 'P')
2122 } else if (ch
== '-') {
2126 if (ch
< '0' || ch
> '9')
2127 expect("exponent digits");
2128 while (ch
>= '0' && ch
<= '9') {
2129 exp_val
= exp_val
* 10 + ch
- '0';
2132 exp_val
= exp_val
* s
;
2134 /* now we can generate the number */
2135 /* XXX: should patch directly float number */
2136 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2137 d
= ldexp(d
, exp_val
- frac_bits
);
2142 /* float : should handle overflow */
2144 } else if (t
== 'L') {
2146 #ifdef TCC_TARGET_PE
2151 /* XXX: not large enough */
2152 tokc
.ld
= (long double)d
;
2159 /* decimal floats */
2161 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2166 while (ch
>= '0' && ch
<= '9') {
2167 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2173 if (ch
== 'e' || ch
== 'E') {
2174 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2178 if (ch
== '-' || ch
== '+') {
2179 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2184 if (ch
< '0' || ch
> '9')
2185 expect("exponent digits");
2186 while (ch
>= '0' && ch
<= '9') {
2187 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2199 tokc
.f
= strtof(token_buf
, NULL
);
2200 } else if (t
== 'L') {
2202 #ifdef TCC_TARGET_PE
2204 tokc
.d
= strtod(token_buf
, NULL
);
2207 tokc
.ld
= strtold(token_buf
, NULL
);
2211 tokc
.d
= strtod(token_buf
, NULL
);
2215 unsigned long long n
, n1
;
2216 int lcount
, ucount
, must_64bit
;
2219 /* integer number */
2222 if (b
== 10 && *q
== '0') {
2229 /* no need for checks except for base 10 / 8 errors */
2239 tcc_error("invalid digit");
2242 /* detect overflow */
2243 /* XXX: this test is not reliable */
2245 tcc_error("integer constant overflow");
2248 /* Determine the characteristics (unsigned and/or 64bit) the type of
2249 the constant must have according to the constant suffix(es) */
2250 lcount
= ucount
= must_64bit
= 0;
2256 tcc_error("three 'l's in integer constant");
2257 if (lcount
&& *(p
- 1) != ch
)
2258 tcc_error("incorrect integer suffix: %s", p1
);
2260 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2265 } else if (t
== 'U') {
2267 tcc_error("two 'u's in integer constant");
2275 /* Whether 64 bits are needed to hold the constant's value */
2276 if (n
& 0xffffffff00000000LL
|| must_64bit
) {
2284 /* Whether type must be unsigned to hold the constant's value */
2285 if (ucount
|| ((n1
>> 31) && (b
!= 10))) {
2286 if (tok
== TOK_CLLONG
)
2290 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2291 } else if (n1
>> 31) {
2292 if (tok
== TOK_CINT
)
2295 tcc_error("integer constant overflow");
2298 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2304 tcc_error("invalid number\n");
2308 #define PARSE2(c1, tok1, c2, tok2) \
2319 /* return next token without macro substitution */
2320 static inline void next_nomacro1(void)
2335 if (parse_flags
& PARSE_FLAG_SPACES
)
2336 goto keep_tok_flags
;
2337 while (isidnum_table
[*p
- CH_EOF
] & IS_SPC
)
2346 /* first look if it is in fact an end of buffer */
2347 c
= handle_stray1(p
);
2354 TCCState
*s1
= tcc_state
;
2355 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2356 && !(tok_flags
& TOK_FLAG_EOF
)) {
2357 tok_flags
|= TOK_FLAG_EOF
;
2359 goto keep_tok_flags
;
2360 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2362 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2363 tcc_error("missing #endif");
2364 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2365 /* no include left : end of file. */
2368 tok_flags
&= ~TOK_FLAG_EOF
;
2369 /* pop include file */
2371 /* test if previous '#endif' was after a #ifdef at
2373 if (tok_flags
& TOK_FLAG_ENDIF
) {
2375 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2377 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2378 tok_flags
&= ~TOK_FLAG_ENDIF
;
2381 /* add end of include file debug info */
2382 if (tcc_state
->do_debug
) {
2383 put_stabd(N_EINCL
, 0, 0);
2385 /* pop include stack */
2387 s1
->include_stack_ptr
--;
2396 tok_flags
|= TOK_FLAG_BOL
;
2399 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2402 goto keep_tok_flags
;
2407 if ((tok_flags
& TOK_FLAG_BOL
) &&
2408 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2410 preprocess(tok_flags
& TOK_FLAG_BOF
);
2416 tok
= TOK_TWOSHARPS
;
2418 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2419 p
= parse_line_comment(p
- 1);
2428 /* dollar is allowed to start identifiers when not parsing asm */
2430 if (!(isidnum_table
[c
- CH_EOF
] & IS_ID
)
2431 || (parse_flags
& PARSE_FLAG_ASM_FILE
))
2434 case 'a': case 'b': case 'c': case 'd':
2435 case 'e': case 'f': case 'g': case 'h':
2436 case 'i': case 'j': case 'k': case 'l':
2437 case 'm': case 'n': case 'o': case 'p':
2438 case 'q': case 'r': case 's': case 't':
2439 case 'u': case 'v': case 'w': case 'x':
2441 case 'A': case 'B': case 'C': case 'D':
2442 case 'E': case 'F': case 'G': case 'H':
2443 case 'I': case 'J': case 'K':
2444 case 'M': case 'N': case 'O': case 'P':
2445 case 'Q': case 'R': case 'S': case 'T':
2446 case 'U': case 'V': case 'W': case 'X':
2452 h
= TOK_HASH_FUNC(h
, c
);
2453 while (c
= *++p
, isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2454 h
= TOK_HASH_FUNC(h
, c
);
2459 /* fast case : no stray found, so we have the full token
2460 and we have already hashed it */
2462 h
&= (TOK_HASH_SIZE
- 1);
2463 pts
= &hash_ident
[h
];
2468 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2470 pts
= &(ts
->hash_next
);
2472 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2476 cstr_reset(&tokcstr
);
2479 cstr_ccat(&tokcstr
, *p1
);
2485 while (isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
)) {
2486 cstr_ccat(&tokcstr
, c
);
2489 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2495 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2497 goto parse_ident_fast
;
2500 if (c
== '\'' || c
== '\"') {
2504 cstr_reset(&tokcstr
);
2505 cstr_ccat(&tokcstr
, 'L');
2506 goto parse_ident_slow
;
2511 case '0': case '1': case '2': case '3':
2512 case '4': case '5': case '6': case '7':
2514 cstr_reset(&tokcstr
);
2515 /* after the first digit, accept digits, alpha, '.' or sign if
2516 prefixed by 'eEpP' */
2520 cstr_ccat(&tokcstr
, c
);
2522 if (!((isidnum_table
[c
- CH_EOF
] & (IS_ID
|IS_NUM
))
2524 || ((c
== '+' || c
== '-')
2525 && (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P')
2529 /* We add a trailing '\0' to ease parsing */
2530 cstr_ccat(&tokcstr
, '\0');
2531 tokc
.str
.size
= tokcstr
.size
;
2532 tokc
.str
.data
= tokcstr
.data
;
2533 tokc
.str
.data_allocated
= tokcstr
.data_allocated
;
2538 /* special dot handling because it can also start a number */
2541 cstr_reset(&tokcstr
);
2542 cstr_ccat(&tokcstr
, '.');
2544 } else if (c
== '.') {
2550 *--p
= '.'; /* may underflow into file->unget[] */
2561 cstr_reset(&tokcstr
);
2563 cstr_ccat(&tokcstr
, 'L');
2564 cstr_ccat(&tokcstr
, c
);
2565 p
= parse_pp_string(p
, c
, &tokcstr
);
2566 cstr_ccat(&tokcstr
, c
);
2567 cstr_ccat(&tokcstr
, '\0');
2568 tokc
.str
.size
= tokcstr
.size
;
2569 tokc
.str
.data
= tokcstr
.data
;
2570 tokc
.str
.data_allocated
= tokcstr
.data_allocated
;
2579 } else if (c
== '<') {
2596 } else if (c
== '>') {
2614 } else if (c
== '=') {
2627 } else if (c
== '=') {
2640 } else if (c
== '=') {
2653 } else if (c
== '=') {
2656 } else if (c
== '>') {
2664 PARSE2('!', '!', '=', TOK_NE
)
2665 PARSE2('=', '=', '=', TOK_EQ
)
2666 PARSE2('*', '*', '=', TOK_A_MUL
)
2667 PARSE2('%', '%', '=', TOK_A_MOD
)
2668 PARSE2('^', '^', '=', TOK_A_XOR
)
2670 /* comments or operator */
2674 p
= parse_comment(p
);
2675 /* comments replaced by a blank */
2677 goto keep_tok_flags
;
2678 } else if (c
== '/') {
2679 p
= parse_line_comment(p
);
2681 goto keep_tok_flags
;
2682 } else if (c
== '=') {
2702 case '@': /* only used in assembler */
2708 tcc_error("unrecognized character \\x%02x", c
);
2714 #if defined(PARSE_DEBUG)
2715 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2719 /* return next token without macro substitution. Can read input from
2721 static void next_nomacro_spc(void)
2727 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2728 if (tok
== TOK_LINENUM
) {
2729 file
->line_num
= tokc
.i
;
2738 ST_FUNC
void next_nomacro(void)
2742 } while (tok
< 256 && (isidnum_table
[tok
- CH_EOF
] & IS_SPC
));
2746 static void macro_subst(
2747 TokenString
*tok_str
,
2749 const int *macro_str
,
2753 /* substitute arguments in replacement lists in macro_str by the values in
2754 args (field d) and return allocated string */
2755 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2767 TOK_GET(&t
, ¯o_str
, &cval
);
2772 TOK_GET(&t
, ¯o_str
, &cval
);
2775 s
= sym_find2(args
, t
);
2778 cstr_ccat(&cstr
, '\"');
2782 TOK_GET(&t
, &st
, &cval
);
2783 if (t
!= TOK_PLCHLDR
2785 && 0 == check_space(t
, &spc
)) {
2786 const char *s
= get_tok_str(t
, &cval
);
2788 if (t
== TOK_PPSTR
&& *s
!= '\'')
2789 add_char(&cstr
, *s
);
2791 cstr_ccat(&cstr
, *s
);
2797 cstr_ccat(&cstr
, '\"');
2798 cstr_ccat(&cstr
, '\0');
2800 printf("\nstringize: <%s>\n", (char *)cstr
.data
);
2803 cval
.str
.size
= cstr
.size
;
2804 cval
.str
.data
= cstr
.data
;
2805 cval
.str
.data_allocated
= cstr
.data_allocated
;
2806 tok_str_add2(&str
, TOK_PPSTR
, &cval
);
2807 tcc_free(cval
.str
.data_allocated
);
2810 expect("macro parameter after '#'");
2812 } else if (t
>= TOK_IDENT
) {
2813 s
= sym_find2(args
, t
);
2817 /* if '##' is present before or after, no arg substitution */
2818 if (*macro_str
== TOK_TWOSHARPS
|| t1
== TOK_TWOSHARPS
) {
2819 /* special case for var arg macros : ## eats the ','
2820 if empty VA_ARGS variable. */
2821 if (t1
== TOK_TWOSHARPS
&& t0
== ',' && gnu_ext
&& s
->type
.t
) {
2823 /* suppress ',' '##' */
2826 /* suppress '##' and add variable */
2833 TOK_GET(&t1
, &st
, &cval
);
2836 tok_str_add2(&str
, t1
, &cval
);
2842 /* NOTE: the stream cannot be read when macro
2843 substituing an argument */
2844 macro_subst(&str
, nested_list
, st
, 0);
2846 if (str
.len
== l0
) /* exanded to empty string */
2847 tok_str_add(&str
, TOK_PLCHLDR
);
2849 tok_str_add(&str
, t
);
2852 tok_str_add2(&str
, t
, &cval
);
2856 tok_str_add(&str
, 0);
2860 static char const ab_month_name
[12][4] =
2862 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2863 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2866 /* peek or read [ws_str == NULL] next token from function macro call,
2867 walking up macro levels up to the file if necessary */
2868 static int next_argstream(Sym
**nested_list
, int can_read_stream
, TokenString
*ws_str
)
2876 p
= macro_ptr
, t
= *p
;
2878 while (is_space(t
) || TOK_LINEFEED
== t
)
2879 tok_str_add(ws_str
, t
), t
= *++p
;
2881 if (t
== 0 && can_read_stream
) {
2883 /* also, end of scope for nested defined symbol */
2885 while (sa
&& sa
->v
== -1)
2894 while (is_space(ch
) || ch
== '\n' || ch
== '/') {
2897 uint8_t *p
= file
->buf_ptr
;
2900 p
= parse_comment(p
);
2901 file
->buf_ptr
= p
- 1;
2902 } else if (c
== '/') {
2903 p
= parse_line_comment(p
);
2904 file
->buf_ptr
= p
- 1;
2909 tok_str_add(ws_str
, ch
);
2923 /* do macro substitution of current token with macro 's' and add
2924 result to (tok_str,tok_len). 'nested_list' is the list of all
2925 macros we got inside to avoid recursing. Return non zero if no
2926 substitution needs to be done */
2927 static int macro_subst_tok(
2928 TokenString
*tok_str
,
2931 int can_read_stream
)
2933 Sym
*args
, *sa
, *sa1
;
2934 int parlevel
, *mstr
, t
, t1
, spc
;
2941 /* if symbol is a macro, prepare substitution */
2942 /* special macros */
2943 if (tok
== TOK___LINE__
) {
2944 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2948 } else if (tok
== TOK___FILE__
) {
2949 cstrval
= file
->filename
;
2951 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2956 tm
= localtime(&ti
);
2957 if (tok
== TOK___DATE__
) {
2958 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2959 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2961 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2962 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2969 cstr_cat(&cstr
, cstrval
);
2970 cstr_ccat(&cstr
, '\0');
2971 cval
.str
.size
= cstr
.size
;
2972 cval
.str
.data
= cstr
.data
;
2973 cval
.str
.data_allocated
= cstr
.data_allocated
;
2974 tok_str_add2(tok_str
, t1
, &cval
);
2977 int saved_parse_flags
= parse_flags
;
2980 if (s
->type
.t
== MACRO_FUNC
) {
2981 /* whitespace between macro name and argument list */
2983 tok_str_new(&ws_str
);
2986 parse_flags
|= PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
2987 | PARSE_FLAG_ACCEPT_STRAYS
;
2989 /* get next token from argument stream */
2990 t
= next_argstream(nested_list
, can_read_stream
, &ws_str
);
2992 /* not a macro substitution after all, restore the
2993 * macro token plus all whitespace we've read.
2994 * whitespace is intentionally not merged to preserve
2996 parse_flags
= saved_parse_flags
;
2997 tok_str_add(tok_str
, tok
);
2998 if (parse_flags
& PARSE_FLAG_SPACES
) {
3000 for (i
= 0; i
< ws_str
.len
; i
++)
3001 tok_str_add(tok_str
, ws_str
.str
[i
]);
3003 tok_str_free(ws_str
.str
);
3006 tok_str_free(ws_str
.str
);
3008 next_nomacro(); /* eat '(' */
3010 /* argument macro */
3013 /* NOTE: empty args are allowed, except if no args */
3016 next_argstream(nested_list
, can_read_stream
, NULL
);
3017 } while (is_space(tok
) || TOK_LINEFEED
== tok
);
3019 /* handle '()' case */
3020 if (!args
&& !sa
&& tok
== ')')
3023 tcc_error("macro '%s' used with too many args",
3024 get_tok_str(s
->v
, 0));
3027 /* NOTE: non zero sa->t indicates VA_ARGS */
3028 while ((parlevel
> 0 ||
3030 (tok
!= ',' || sa
->type
.t
)))) {
3031 if (tok
== TOK_EOF
|| tok
== 0)
3035 else if (tok
== ')')
3037 if (tok
== TOK_LINEFEED
)
3039 if (!check_space(tok
, &spc
))
3040 tok_str_add2(&str
, tok
, &tokc
);
3041 next_argstream(nested_list
, can_read_stream
, NULL
);
3046 tok_str_add(&str
, 0);
3047 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
3051 /* special case for gcc var args: add an empty
3052 var arg argument if it is omitted */
3053 if (sa
&& sa
->type
.t
&& gnu_ext
)
3061 tcc_error("macro '%s' used with too few args",
3062 get_tok_str(s
->v
, 0));
3065 parse_flags
= saved_parse_flags
;
3067 /* now subst each arg */
3068 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3073 tok_str_free(sa
->d
);
3079 sym_push2(nested_list
, s
->v
, 0, 0);
3080 parse_flags
= saved_parse_flags
;
3081 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
3083 /* pop nested defined symbol */
3085 *nested_list
= sa1
->prev
;
3093 int paste_tokens(int t1
, CValue
*v1
, int t2
, CValue
*v2
)
3099 if (t1
!= TOK_PLCHLDR
)
3100 cstr_cat(&cstr
, get_tok_str(t1
, v1
));
3102 if (t2
!= TOK_PLCHLDR
)
3103 cstr_cat(&cstr
, get_tok_str(t2
, v2
));
3104 cstr_ccat(&cstr
, '\0');
3106 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3107 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3110 if (0 == *file
->buf_ptr
)
3114 tcc_warning("pasting <%.*s> and <%s> does not give a valid preprocessing token",
3115 n
, cstr
.data
, (char*)cstr
.data
+ n
);
3120 //printf("paste <%s>\n", (char*)cstr.data);
3125 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3126 return the resulting string (which must be freed). */
3127 static inline int *macro_twosharps(const int *ptr0
)
3131 TokenString macro_str1
;
3132 int start_of_nosubsts
= -1;
3135 /* we search the first '##' */
3136 for (ptr
= ptr0
;;) {
3137 TOK_GET(&t
, &ptr
, &cval
);
3138 if (t
== TOK_TWOSHARPS
)
3144 tok_str_new(¯o_str1
);
3146 //tok_print(" $$$", ptr0);
3147 for (ptr
= ptr0
;;) {
3148 TOK_GET(&t
, &ptr
, &cval
);
3151 if (t
== TOK_TWOSHARPS
)
3153 while (*ptr
== TOK_TWOSHARPS
) {
3155 /* given 'a##b', remove nosubsts preceding 'a' */
3156 if (start_of_nosubsts
>= 0)
3157 macro_str1
.len
= start_of_nosubsts
;
3158 /* given 'a##b', remove nosubsts preceding 'b' */
3159 while ((t1
= *++ptr
) == TOK_NOSUBST
)
3161 if (t1
&& t1
!= TOK_TWOSHARPS
3162 && t1
!= ':') /* 'a##:' don't build a new token */
3164 TOK_GET(&t1
, &ptr
, &cv1
);
3165 if (t
!= TOK_PLCHLDR
|| t1
!= TOK_PLCHLDR
) {
3166 paste_tokens(t
, &cval
, t1
, &cv1
);
3167 t
= tok
, cval
= tokc
;
3171 if (t
== TOK_NOSUBST
) {
3172 if (start_of_nosubsts
< 0)
3173 start_of_nosubsts
= macro_str1
.len
;
3175 start_of_nosubsts
= -1;
3177 tok_str_add2(¯o_str1
, t
, &cval
);
3179 tok_str_add(¯o_str1
, 0);
3180 //tok_print(" ###", macro_str1.str);
3181 return macro_str1
.str
;
3184 /* do macro substitution of macro_str and add result to
3185 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3186 inside to avoid recursing. */
3187 static void macro_subst(
3188 TokenString
*tok_str
,
3190 const int *macro_str
,
3196 int t
, spc
, nosubst
;
3198 int *macro_str1
= NULL
;
3200 /* first scan for '##' operator handling */
3204 /* first scan for '##' operator handling */
3205 if (can_read_stream
) {
3206 macro_str1
= macro_twosharps(ptr
);
3212 TOK_GET(&t
, &ptr
, &cval
);
3216 if (t
>= TOK_IDENT
&& 0 == nosubst
) {
3221 /* if nested substitution, do nothing */
3222 if (sym_find2(*nested_list
, t
)) {
3223 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3224 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3230 str
.str
= (int*)ptr
;
3231 begin_macro(&str
, 2);
3234 macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
3236 if (str
.alloc
== 3) {
3237 /* already finished by reading function macro arguments */
3245 spc
= (tok_str
->len
&&
3246 is_space(tok_last(tok_str
->str
,
3247 tok_str
->str
+ tok_str
->len
)));
3251 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
))
3252 tcc_error("stray '\\' in program");
3255 if (!check_space(t
, &spc
))
3256 tok_str_add2(tok_str
, t
, &cval
);
3258 if (t
== TOK_NOSUBST
)
3263 tok_str_free(macro_str1
);
3267 /* return next token with macro substitution */
3268 ST_FUNC
void next(void)
3271 if (parse_flags
& PARSE_FLAG_SPACES
)
3277 if (tok
== TOK_NOSUBST
|| tok
== TOK_PLCHLDR
) {
3278 /* discard preprocessor markers */
3280 } else if (tok
== 0) {
3281 /* end of macro or unget token string */
3285 } else if (tok
>= TOK_IDENT
&& (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3287 /* if reading from file, try to substitute macros */
3288 s
= define_find(tok
);
3290 static TokenString str
; /* using static string for speed */
3291 Sym
*nested_list
= NULL
;
3294 macro_subst_tok(&str
, &nested_list
, s
, 1);
3295 tok_str_add(&str
, 0);
3296 begin_macro(&str
, 0);
3300 /* convert preprocessor tokens into C tokens */
3301 if (tok
== TOK_PPNUM
) {
3302 if (parse_flags
& PARSE_FLAG_TOK_NUM
)
3303 parse_number((char *)tokc
.str
.data
);
3304 } else if (tok
== TOK_PPSTR
) {
3305 if (parse_flags
& PARSE_FLAG_TOK_STR
)
3306 parse_string((char *)tokc
.str
.data
, tokc
.str
.size
- 1);
3310 /* push back current token and set current token to 'last_tok'. Only
3311 identifier case handled for labels. */
3312 ST_INLN
void unget_tok(int last_tok
)
3314 TokenString
*str
= tcc_malloc(sizeof *str
);
3316 tok_str_add2(str
, tok
, &tokc
);
3317 tok_str_add(str
, 0);
3318 begin_macro(str
, 1);
3322 /* better than nothing, but needs extension to handle '-E' option
3324 ST_FUNC
void preprocess_init(TCCState
*s1
)
3326 s1
->include_stack_ptr
= s1
->include_stack
;
3327 /* XXX: move that before to avoid having to initialize
3328 file->ifdef_stack_ptr ? */
3329 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3330 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3332 pvtop
= vtop
= vstack
- 1;
3333 s1
->pack_stack
[0] = 0;
3334 s1
->pack_stack_ptr
= s1
->pack_stack
;
3336 isidnum_table
['$' - CH_EOF
] =
3337 tcc_state
->dollars_in_identifiers
? IS_ID
: 0;
3340 ST_FUNC
void preprocess_new(void)
3345 /* init isid table */
3346 for(i
= CH_EOF
; i
<256; i
++)
3347 isidnum_table
[i
- CH_EOF
]
3348 = is_space(i
) ? IS_SPC
3353 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3355 tok_ident
= TOK_IDENT
;
3364 tok_alloc(p
, r
- p
- 1);
3369 ST_FUNC
void preprocess_delete(void)
3373 /* free -D and compiler defines */
3376 /* cleanup from error/setjmp */
3382 n
= tok_ident
- TOK_IDENT
;
3383 for(i
= 0; i
< n
; i
++)
3384 tcc_free(table_ident
[i
]);
3385 tcc_free(table_ident
);
3389 /* Preprocess the current file */
3390 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3392 BufferedFile
**iptr
;
3393 int token_seen
, spcs
, level
;
3395 preprocess_init(s1
);
3396 ch
= file
->buf_ptr
[0];
3397 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3398 parse_flags
= PARSE_FLAG_PREPROCESS
3399 | (parse_flags
& PARSE_FLAG_ASM_FILE
)
3400 | PARSE_FLAG_LINEFEED
3402 | PARSE_FLAG_ACCEPT_STRAYS
3406 do next(); while (tok
!= TOK_EOF
); return 0;
3409 token_seen
= spcs
= 0;
3410 pp_line(s1
, file
, 0);
3413 iptr
= s1
->include_stack_ptr
;
3417 level
= s1
->include_stack_ptr
- iptr
;
3420 pp_line(s1
, *iptr
, 0);
3421 pp_line(s1
, file
, level
);
3424 if (0 == token_seen
) {
3429 if (tok
== TOK_LINEFEED
) {
3433 pp_line(s1
, file
, 0);
3435 fputs(" ", s1
->ppfp
), --spcs
;
3438 } else if (tok
== TOK_LINEFEED
) {
3443 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);