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 int *macro_ptr_allocated
;
44 static const int *unget_saved_macro_ptr
;
45 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
46 static int unget_buffer_enabled
;
47 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
48 static char token_buf
[STRING_MAX_SIZE
+ 1];
49 /* true if isid(c) || isnum(c) */
50 static unsigned char isidnum_table
[256-CH_EOF
];
52 static const char tcc_keywords
[] =
53 #define DEF(id, str) str "\0"
58 /* WARNING: the content of this string encodes token numbers */
59 static const unsigned char tok_two_chars
[] =
61 "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253"
62 "-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
83 '.','.', 0xa8, // C++ token ?
84 '#','#', TOK_TWOSHARPS
,
89 struct macro_level
*prev
;
93 static void next_nomacro_spc(void);
94 static void macro_subst(
98 struct macro_level
**can_read_stream
101 ST_FUNC
void skip(int c
)
104 tcc_error("'%c' expected (got \"%s\")", c
, get_tok_str(tok
, &tokc
));
108 ST_FUNC
void expect(const char *msg
)
110 tcc_error("%s expected", msg
);
113 /* ------------------------------------------------------------------------- */
114 /* CString handling */
115 static void cstr_realloc(CString
*cstr
, int new_size
)
120 size
= cstr
->size_allocated
;
122 size
= 8; /* no need to allocate a too small first string */
123 while (size
< new_size
)
125 data
= tcc_realloc(cstr
->data_allocated
, size
);
126 cstr
->data_allocated
= data
;
127 cstr
->size_allocated
= size
;
132 ST_FUNC
void cstr_ccat(CString
*cstr
, int ch
)
135 size
= cstr
->size
+ 1;
136 if (size
> cstr
->size_allocated
)
137 cstr_realloc(cstr
, size
);
138 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
142 ST_FUNC
void cstr_cat(CString
*cstr
, const char *str
)
154 /* add a wide char */
155 ST_FUNC
void cstr_wccat(CString
*cstr
, int ch
)
158 size
= cstr
->size
+ sizeof(nwchar_t
);
159 if (size
> cstr
->size_allocated
)
160 cstr_realloc(cstr
, size
);
161 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
165 ST_FUNC
void cstr_new(CString
*cstr
)
167 memset(cstr
, 0, sizeof(CString
));
170 /* free string and reset it to NULL */
171 ST_FUNC
void cstr_free(CString
*cstr
)
173 tcc_free(cstr
->data_allocated
);
177 /* reset string to empty */
178 ST_FUNC
void cstr_reset(CString
*cstr
)
184 static void add_char(CString
*cstr
, int c
)
186 if (c
== '\'' || c
== '\"' || c
== '\\') {
187 /* XXX: could be more precise if char or string */
188 cstr_ccat(cstr
, '\\');
190 if (c
>= 32 && c
<= 126) {
193 cstr_ccat(cstr
, '\\');
195 cstr_ccat(cstr
, 'n');
197 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
198 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
199 cstr_ccat(cstr
, '0' + (c
& 7));
204 /* ------------------------------------------------------------------------- */
205 /* allocate a new token */
206 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
208 TokenSym
*ts
, **ptable
;
211 if (tok_ident
>= SYM_FIRST_ANOM
)
212 tcc_error("memory full (symbols)");
214 /* expand token table if needed */
215 i
= tok_ident
- TOK_IDENT
;
216 if ((i
% TOK_ALLOC_INCR
) == 0) {
217 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
218 table_ident
= ptable
;
221 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
223 ts
->tok
= tok_ident
++;
224 ts
->sym_define
= NULL
;
225 ts
->sym_label
= NULL
;
226 ts
->sym_struct
= NULL
;
227 ts
->sym_identifier
= NULL
;
229 ts
->hash_next
= NULL
;
230 memcpy(ts
->str
, str
, len
);
236 #define TOK_HASH_INIT 1
237 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
239 /* find a token and add it if not found */
240 ST_FUNC TokenSym
*tok_alloc(const char *str
, int len
)
248 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
249 h
&= (TOK_HASH_SIZE
- 1);
251 pts
= &hash_ident
[h
];
256 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
258 pts
= &(ts
->hash_next
);
260 return tok_alloc_new(pts
, str
, len
);
263 /* XXX: buffer overflow */
264 /* XXX: float tokens */
265 ST_FUNC
char *get_tok_str(int v
, CValue
*cv
)
267 static char buf
[STRING_MAX_SIZE
+ 1];
268 static CString cstr_buf
;
273 /* NOTE: to go faster, we give a fixed buffer for small strings */
274 cstr_reset(&cstr_buf
);
276 cstr_buf
.size_allocated
= sizeof(buf
);
279 /* just an explanation, should never happen:
280 if (v <= TOK_LINENUM && v >= TOK_CINT && cv == NULL)
281 tcc_error("internal error: get_tok_str"); */
286 /* XXX: not quite exact, but only useful for testing */
287 sprintf(p
, "%u", cv
->ui
);
291 /* XXX: not quite exact, but only useful for testing */
293 sprintf(p
, "%u", (unsigned)cv
->ull
);
295 sprintf(p
, "%llu", cv
->ull
);
299 cstr_ccat(&cstr_buf
, 'L');
301 cstr_ccat(&cstr_buf
, '\'');
302 add_char(&cstr_buf
, cv
->i
);
303 cstr_ccat(&cstr_buf
, '\'');
304 cstr_ccat(&cstr_buf
, '\0');
308 len
= cstr
->size
- 1;
310 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
311 cstr_ccat(&cstr_buf
, '\0');
314 cstr_ccat(&cstr_buf
, 'L');
317 cstr_ccat(&cstr_buf
, '\"');
319 len
= cstr
->size
- 1;
321 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
323 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
325 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
327 cstr_ccat(&cstr_buf
, '\"');
328 cstr_ccat(&cstr_buf
, '\0');
335 return NULL
; /* should not happen */
337 /* above tokens have value, the ones below don't */
346 return strcpy(p
, "...");
348 return strcpy(p
, "<<=");
350 return strcpy(p
, ">>=");
353 /* search in two bytes table */
354 const unsigned char *q
= tok_two_chars
;
367 } else if (v
< tok_ident
) {
368 return table_ident
[v
- TOK_IDENT
]->str
;
369 } else if (v
>= SYM_FIRST_ANOM
) {
370 /* special name for anonymous symbol */
371 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
373 /* should never happen */
378 return cstr_buf
.data
;
381 /* fill input buffer and peek next char */
382 static int tcc_peekc_slow(BufferedFile
*bf
)
385 /* only tries to read if really end of buffer */
386 if (bf
->buf_ptr
>= bf
->buf_end
) {
388 #if defined(PARSE_DEBUG)
393 len
= read(bf
->fd
, bf
->buffer
, len
);
400 bf
->buf_ptr
= bf
->buffer
;
401 bf
->buf_end
= bf
->buffer
+ len
;
402 *bf
->buf_end
= CH_EOB
;
404 if (bf
->buf_ptr
< bf
->buf_end
) {
405 return bf
->buf_ptr
[0];
407 bf
->buf_ptr
= bf
->buf_end
;
412 /* return the current character, handling end of block if necessary
414 ST_FUNC
int handle_eob(void)
416 return tcc_peekc_slow(file
);
419 /* read next char from current input file and handle end of input buffer */
420 ST_INLN
void inp(void)
422 ch
= *(++(file
->buf_ptr
));
423 /* end of buffer/file handling */
428 /* handle '\[\r]\n' */
429 static int handle_stray_noerror(void)
436 } else if (ch
== '\r') {
450 static void handle_stray(void)
452 if (handle_stray_noerror())
453 tcc_error("stray '\\' in program");
456 /* skip the stray and handle the \\n case. Output an error if
457 incorrect char after the stray */
458 static int handle_stray1(uint8_t *p
)
462 if (p
>= file
->buf_end
) {
479 /* handle just the EOB case, but not stray */
480 #define PEEKC_EOB(c, p)\
491 /* handle the complicated stray case */
497 c = handle_stray1(p);\
502 /* input with '\[\r]\n' handling. Note that this function cannot
503 handle other characters after '\', so you cannot call it inside
504 strings or comments */
505 ST_FUNC
void minp(void)
513 /* single line C++ comments */
514 static uint8_t *parse_line_comment(uint8_t *p
)
522 if (c
== '\n' || c
== CH_EOF
) {
524 } else if (c
== '\\') {
533 } else if (c
== '\r') {
551 ST_FUNC
uint8_t *parse_comment(uint8_t *p
)
560 if (c
== '\n' || c
== '*' || c
== '\\')
564 if (c
== '\n' || c
== '*' || c
== '\\')
568 /* now we can handle all the cases */
572 } else if (c
== '*') {
578 } else if (c
== '/') {
580 } else if (c
== '\\') {
585 /* skip '\[\r]\n', otherwise just skip the stray */
591 } else if (c
== '\r') {
608 /* stray, eob or eof */
613 tcc_error("unexpected end of file in comment");
614 } else if (c
== '\\') {
626 static inline void skip_spaces(void)
632 static inline int check_space(int t
, int *spc
)
643 /* parse a string without interpreting escapes */
644 static uint8_t *parse_pp_string(uint8_t *p
,
645 int sep
, CString
*str
)
653 } else if (c
== '\\') {
659 /* XXX: indicate line number of start of string */
660 tcc_error("missing terminating %c character", sep
);
661 } else if (c
== '\\') {
662 /* escape : just skip \[\r]\n */
667 } else if (c
== '\r') {
670 expect("'\n' after '\r'");
673 } else if (c
== CH_EOF
) {
674 goto unterminated_string
;
677 cstr_ccat(str
, '\\');
683 } else if (c
== '\n') {
686 } else if (c
== '\r') {
690 cstr_ccat(str
, '\r');
706 /* skip block of text until #else, #elif or #endif. skip also pairs of
708 static void preprocess_skip(void)
710 int a
, start_of_line
, c
, in_warn_or_error
;
717 in_warn_or_error
= 0;
738 } else if (c
== '\\') {
739 ch
= file
->buf_ptr
[0];
740 handle_stray_noerror();
747 if (in_warn_or_error
)
749 p
= parse_pp_string(p
, c
, NULL
);
753 if (in_warn_or_error
)
760 p
= parse_comment(p
);
761 } else if (ch
== '/') {
762 p
= parse_line_comment(p
);
772 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
774 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
776 else if (tok
== TOK_ENDIF
)
778 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
779 in_warn_or_error
= 1;
780 else if (tok
== TOK_LINEFEED
)
782 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
783 p
= parse_line_comment(p
);
785 else if (parse_flags
& PARSE_FLAG_ASM_FILE
)
786 p
= parse_line_comment(p
);
799 /* ParseState handling */
801 /* XXX: currently, no include file info is stored. Thus, we cannot display
802 accurate messages if the function or data definition spans multiple
805 /* save current parse state in 's' */
806 ST_FUNC
void save_parse_state(ParseState
*s
)
808 s
->line_num
= file
->line_num
;
809 s
->macro_ptr
= macro_ptr
;
814 /* restore parse state from 's' */
815 ST_FUNC
void restore_parse_state(ParseState
*s
)
817 file
->line_num
= s
->line_num
;
818 macro_ptr
= s
->macro_ptr
;
823 /* return the number of additional 'ints' necessary to store the
825 static inline int tok_ext_size(int t
)
839 tcc_error("unsupported token");
846 return LDOUBLE_SIZE
/ 4;
852 /* token string handling */
854 ST_INLN
void tok_str_new(TokenString
*s
)
858 s
->allocated_len
= 0;
859 s
->last_line_num
= -1;
862 ST_FUNC
void tok_str_free(int *str
)
867 static int *tok_str_realloc(TokenString
*s
)
871 if (s
->allocated_len
== 0) {
874 len
= s
->allocated_len
* 2;
876 str
= tcc_realloc(s
->str
, len
* sizeof(int));
877 s
->allocated_len
= len
;
882 ST_FUNC
void tok_str_add(TokenString
*s
, int t
)
888 if (len
>= s
->allocated_len
)
889 str
= tok_str_realloc(s
);
894 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
901 /* allocate space for worst case */
902 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
903 str
= tok_str_realloc(s
);
912 str
[len
++] = cv
->tab
[0];
921 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
922 while ((len
+ nb_words
) > s
->allocated_len
)
923 str
= tok_str_realloc(s
);
924 cstr
= (CString
*)(str
+ len
);
926 cstr
->size
= cv
->cstr
->size
;
927 cstr
->data_allocated
= NULL
;
928 cstr
->size_allocated
= cstr
->size
;
929 memcpy((char *)cstr
+ sizeof(CString
),
930 cv
->cstr
->data
, cstr
->size
);
937 #if LDOUBLE_SIZE == 8
940 str
[len
++] = cv
->tab
[0];
941 str
[len
++] = cv
->tab
[1];
943 #if LDOUBLE_SIZE == 12
945 str
[len
++] = cv
->tab
[0];
946 str
[len
++] = cv
->tab
[1];
947 str
[len
++] = cv
->tab
[2];
948 #elif LDOUBLE_SIZE == 16
950 str
[len
++] = cv
->tab
[0];
951 str
[len
++] = cv
->tab
[1];
952 str
[len
++] = cv
->tab
[2];
953 str
[len
++] = cv
->tab
[3];
954 #elif LDOUBLE_SIZE != 8
955 #error add long double size support
964 /* add the current parse token in token string 's' */
965 ST_FUNC
void tok_str_add_tok(TokenString
*s
)
969 /* save line number info */
970 if (file
->line_num
!= s
->last_line_num
) {
971 s
->last_line_num
= file
->line_num
;
972 cval
.i
= s
->last_line_num
;
973 tok_str_add2(s
, TOK_LINENUM
, &cval
);
975 tok_str_add2(s
, tok
, &tokc
);
978 /* get a token from an integer array and increment pointer
979 accordingly. we code it as a macro to avoid pointer aliasing. */
980 static inline void TOK_GET(int *t
, const int **pp
, CValue
*cv
)
998 cv
->cstr
= (CString
*)p
;
999 cv
->cstr
->data
= (char *)p
+ sizeof(CString
);
1000 p
+= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
1008 #if LDOUBLE_SIZE == 16
1010 #elif LDOUBLE_SIZE == 12
1012 #elif LDOUBLE_SIZE == 8
1015 # error add long double size support
1028 static int macro_is_equal(const int *a
, const int *b
)
1030 char buf
[STRING_MAX_SIZE
+ 1];
1034 TOK_GET(&t
, &a
, &cv
);
1035 pstrcpy(buf
, sizeof buf
, get_tok_str(t
, &cv
));
1036 TOK_GET(&t
, &b
, &cv
);
1037 if (strcmp(buf
, get_tok_str(t
, &cv
)))
1043 static void define_print(Sym
*s
, int is_undef
)
1050 if (tcc_state
->dflag
== 0 || !s
|| !tcc_state
->ppfp
)
1054 c
= file
->line_num
- file
->line_ref
- 1;
1057 fputs("\n", tcc_state
->ppfp
);
1058 file
->line_ref
= file
->line_num
;
1063 fprintf(tcc_state
->ppfp
, "// #undef %s", get_tok_str(s
->v
, NULL
));
1067 fprintf(tcc_state
->ppfp
, "// #define %s", get_tok_str(s
->v
, NULL
));
1072 fprintf(tcc_state
->ppfp
, "%s%s", sep
, get_tok_str(arg
->v
& ~SYM_FIELD
, NULL
));
1076 fprintf(tcc_state
->ppfp
, ")");
1081 fprintf(tcc_state
->ppfp
, " ");
1084 TOK_GET(&t
, &str
, &cval
);
1087 fprintf(tcc_state
->ppfp
, "%s", get_tok_str(t
, &cval
));
1091 /* defines handling */
1092 ST_INLN
void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
1097 if (s
&& !macro_is_equal(s
->d
, str
))
1098 tcc_warning("%s redefined", get_tok_str(v
, NULL
));
1100 s
= sym_push2(&define_stack
, v
, macro_type
, 0);
1102 s
->next
= first_arg
;
1103 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
1107 /* undefined a define symbol. Its name is just set to zero */
1108 ST_FUNC
void define_undef(Sym
*s
)
1112 if (v
>= TOK_IDENT
&& v
< tok_ident
) {
1114 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1118 ST_INLN Sym
*define_find(int v
)
1121 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1123 return table_ident
[v
]->sym_define
;
1126 /* free define stack until top reaches 'b' */
1127 ST_FUNC
void free_defines(Sym
*b
)
1135 /* do not free args or predefined defines */
1137 tok_str_free(top
->d
);
1139 if (v
>= TOK_IDENT
&& v
< tok_ident
)
1140 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
1147 ST_FUNC
void print_defines(void)
1155 if (v
>= TOK_IDENT
&& v
< tok_ident
) {
1156 s
= table_ident
[v
- TOK_IDENT
]->sym_define
;
1164 ST_FUNC Sym
*label_find(int v
)
1167 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1169 return table_ident
[v
]->sym_label
;
1172 ST_FUNC Sym
*label_push(Sym
**ptop
, int v
, int flags
)
1175 s
= sym_push2(ptop
, v
, 0, 0);
1177 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
1178 if (ptop
== &global_label_stack
) {
1179 /* modify the top most local identifier, so that
1180 sym_identifier will point to 's' when popped */
1182 ps
= &(*ps
)->prev_tok
;
1189 /* pop labels until element last is reached. Look if any labels are
1190 undefined. Define symbols if '&&label' was used. */
1191 ST_FUNC
void label_pop(Sym
**ptop
, Sym
*slast
)
1194 for(s
= *ptop
; s
!= slast
; s
= s1
) {
1196 if (s
->r
== LABEL_DECLARED
) {
1197 tcc_warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
1198 } else if (s
->r
== LABEL_FORWARD
) {
1199 tcc_error("label '%s' used but not defined",
1200 get_tok_str(s
->v
, NULL
));
1203 /* define corresponding symbol. A size of
1205 put_extern_sym(s
, cur_text_section
, s
->jnext
, 1);
1209 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
1215 /* eval an expression for #if/#elif */
1216 static int expr_preprocess(void)
1222 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1223 next(); /* do macro subst */
1224 if (tok
== TOK_DEFINED
) {
1229 c
= define_find(tok
) != 0;
1234 } else if (tok
>= TOK_IDENT
) {
1235 /* if undefined macro */
1239 tok_str_add_tok(&str
);
1241 tok_str_add(&str
, -1); /* simulate end of file */
1242 tok_str_add(&str
, 0);
1243 /* now evaluate C constant expression */
1244 macro_ptr
= str
.str
;
1248 tok_str_free(str
.str
);
1252 /* parse after #define */
1253 ST_FUNC
void parse_define(void)
1255 Sym
*s
, *first
, **ps
;
1256 int v
, t
, varg
, is_vaargs
, spc
, ptok
, macro_list_start
;
1257 int saved_parse_flags
;
1262 tcc_error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
1263 /* XXX: should check if same macro (ANSI) */
1266 /* '(' must be just after macro definition for MACRO_FUNC */
1271 while (tok
!= ')') {
1275 if (varg
== TOK_DOTS
) {
1276 varg
= TOK___VA_ARGS__
;
1278 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1282 if (varg
< TOK_IDENT
)
1283 tcc_error( "\'%s\' may not appear in parameter list", get_tok_str(varg
, NULL
));
1284 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1296 /* EOF testing necessary for '-D' handling */
1298 macro_list_start
= 1;
1299 saved_parse_flags
= parse_flags
;
1300 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
1301 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1302 if (macro_list_start
&& spc
== 2 && tok
== TOK_TWOSHARPS
)
1303 tcc_error("'##' invalid at start of macro");
1305 /* remove spaces around ## and after '#' */
1306 if (TOK_TWOSHARPS
== tok
) {
1310 } else if ('#' == tok
) {
1312 } else if (check_space(tok
, &spc
)) {
1315 tok_str_add2(&str
, tok
, &tokc
);
1316 macro_list_start
= 0;
1320 parse_flags
= saved_parse_flags
;
1321 if (ptok
== TOK_TWOSHARPS
)
1322 tcc_error("'##' invalid at end of macro");
1324 --str
.len
; /* remove trailing space */
1325 tok_str_add(&str
, 0);
1326 define_push(v
, t
, str
.str
, first
);
1329 static inline int hash_cached_include(const char *filename
)
1331 const unsigned char *s
;
1335 s
= (unsigned char *) filename
;
1337 h
= TOK_HASH_FUNC(h
, *s
);
1340 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
1344 static CachedInclude
*search_cached_include(TCCState
*s1
, const char *filename
)
1348 h
= hash_cached_include(filename
);
1349 i
= s1
->cached_includes_hash
[h
];
1353 e
= s1
->cached_includes
[i
- 1];
1354 if (0 == PATHCMP(e
->filename
, filename
))
1361 static inline void add_cached_include(TCCState
*s1
, const char *filename
, int ifndef_macro
)
1366 if (search_cached_include(s1
, filename
))
1369 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
1371 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
1372 strcpy(e
->filename
, filename
);
1373 e
->ifndef_macro
= ifndef_macro
;
1374 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
1375 /* add in hash table */
1376 h
= hash_cached_include(filename
);
1377 e
->hash_next
= s1
->cached_includes_hash
[h
];
1378 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
1381 static void pragma_parse(TCCState
*s1
)
1384 if (tok
== TOK_pack
) {
1387 #pragma pack(1) // set
1388 #pragma pack() // reset to default
1389 #pragma pack(push,1) // push & set
1390 #pragma pack(pop) // restore previous
1394 if (tok
== TOK_ASM_pop
) {
1396 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
1398 tcc_error("out of pack stack");
1400 s1
->pack_stack_ptr
--;
1404 if (tok
== TOK_ASM_push
) {
1406 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
1408 s1
->pack_stack_ptr
++;
1411 if (tok
!= TOK_CINT
)
1414 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
1418 *s1
->pack_stack_ptr
= val
;
1422 } else if (tok
== TOK_comment
) {
1423 if (s1
->ms_extensions
) {
1426 if (tok
== TOK_lib
) {
1429 if (tok
!= TOK_STR
) {
1430 tcc_error("invalid library specification");
1432 int len
= strlen((char *)tokc
.cstr
->data
);
1433 char *file
= tcc_malloc(len
+ 4); /* filetype, "-l", and \0 at the end */
1434 file
[0] = TCC_FILETYPE_BINARY
;
1437 strcpy(&file
[3],(char *)tokc
.cstr
->data
);
1438 dynarray_add((void ***)&s1
->files
, &s1
->nb_files
, file
);
1443 tcc_warning("unknown specifier '%s' in #pragma comment", get_tok_str(tok
, &tokc
));
1446 tcc_warning("#pragma comment(lib) is ignored");
1448 } else if (tok
== TOK_push_macro
|| tok
== TOK_pop_macro
) {
1452 if (next_nomacro(), tok
!= '(')
1454 if (next_nomacro(), tok
!= TOK_STR
)
1456 v
= tok_alloc(tokc
.cstr
->data
, tokc
.cstr
->size
- 1)->tok
;
1457 if (next_nomacro(), tok
!= ')')
1459 if (t
== TOK_push_macro
) {
1460 while (NULL
== (s
= define_find(v
)))
1461 define_push(v
, 0, NULL
, NULL
);
1462 s
->type
.ref
= s
; /* set push boundary */
1464 for (s
= define_stack
; s
; s
= s
->prev
)
1465 if (s
->v
== v
&& s
->type
.ref
== s
) {
1471 table_ident
[v
- TOK_IDENT
]->sym_define
= s
->d
? s
: NULL
;
1473 tcc_warning("unbalanced #pragma pop_macro");
1475 /* print info when tcc is called with "-E -dD" switches */
1476 if (s1
->dflag
&& s1
->ppfp
) {
1478 int c
= file
->line_num
- file
->line_ref
- 1;
1481 fputs("\n", tcc_state
->ppfp
);
1482 file
->line_ref
= file
->line_num
;
1485 fprintf(s1
->ppfp
, "// #pragma %s_macro(\"%s\")",
1486 (t
== TOK_push_macro
) ? "push" : "pop",
1487 get_tok_str(v
, NULL
));
1489 } else if (tok
== TOK_once
) {
1490 add_cached_include(s1
, file
->filename
, TOK_once
);
1492 tcc_warning("unknown #pragma %s", get_tok_str(tok
, &tokc
));
1496 tcc_error("malformed #pragma directive");
1499 /* is_bof is true if first non space token at beginning of file */
1500 ST_FUNC
void preprocess(int is_bof
)
1502 TCCState
*s1
= tcc_state
;
1503 int i
, c
, n
, saved_parse_flags
;
1507 saved_parse_flags
= parse_flags
;
1508 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
1509 PARSE_FLAG_LINEFEED
;
1510 parse_flags
|= (saved_parse_flags
& PARSE_FLAG_ASM_FILE
);
1520 s
= define_find(tok
);
1521 /* undefine symbol by putting an invalid name */
1526 case TOK_INCLUDE_NEXT
:
1527 ch
= file
->buf_ptr
[0];
1528 /* XXX: incorrect if comments : use next_nomacro with a special mode */
1533 } else if (ch
== '\"') {
1538 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1539 if ((q
- buf
) < sizeof(buf
) - 1)
1542 if (handle_stray_noerror() == 0)
1550 /* eat all spaces and comments after include */
1551 /* XXX: slightly incorrect */
1552 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1556 /* computed #include : either we have only strings or
1557 we have anything enclosed in '<>' */
1560 if (tok
== TOK_STR
) {
1561 while (tok
!= TOK_LINEFEED
) {
1562 if (tok
!= TOK_STR
) {
1564 tcc_error("'#include' expects \"FILENAME\" or <FILENAME>");
1566 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1572 while (tok
!= TOK_LINEFEED
) {
1573 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1577 /* check syntax and remove '<>' */
1578 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1579 goto include_syntax
;
1580 memmove(buf
, buf
+ 1, len
- 2);
1581 buf
[len
- 2] = '\0';
1586 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
1587 tcc_error("#include recursion too deep");
1588 /* store current file in stack, but increment stack later below */
1589 *s1
->include_stack_ptr
= file
;
1591 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
1592 for (i
= -2; i
< n
; ++i
) {
1593 char buf1
[sizeof file
->filename
];
1599 /* check absolute include path */
1600 if (!IS_ABSPATH(buf
))
1603 i
= n
; /* force end loop */
1605 } else if (i
== -1) {
1606 /* search in current dir if "header.h" */
1609 path
= file
->filename
;
1610 pstrncpy(buf1
, path
, tcc_basename(path
) - path
);
1613 /* search in all the include paths */
1614 if (i
< s1
->nb_include_paths
)
1615 path
= s1
->include_paths
[i
];
1617 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
1618 pstrcpy(buf1
, sizeof(buf1
), path
);
1619 pstrcat(buf1
, sizeof(buf1
), "/");
1622 pstrcat(buf1
, sizeof(buf1
), buf
);
1624 if (tok
== TOK_INCLUDE_NEXT
)
1625 for (f
= s1
->include_stack_ptr
; f
>= s1
->include_stack
; --f
)
1626 if (0 == PATHCMP((*f
)->filename
, buf1
)) {
1628 printf("%s: #include_next skipping %s\n", file
->filename
, buf1
);
1630 goto include_trynext
;
1633 e
= search_cached_include(s1
, buf1
);
1634 if (e
&& (define_find(e
->ifndef_macro
) || e
->ifndef_macro
== TOK_once
)) {
1635 /* no need to parse the include because the 'ifndef macro'
1638 printf("%s: skipping cached %s\n", file
->filename
, buf1
);
1643 if (tcc_open(s1
, buf1
) < 0)
1648 printf("%s: including %s\n", file
->prev
->filename
, file
->filename
);
1650 /* update target deps */
1651 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1653 /* push current file in stack */
1654 ++s1
->include_stack_ptr
;
1655 /* add include file debug info */
1657 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1658 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
1659 ch
= file
->buf_ptr
[0];
1662 tcc_error("include file '%s' not found", buf
);
1669 c
= expr_preprocess();
1675 if (tok
< TOK_IDENT
)
1676 tcc_error("invalid argument for '#if%sdef'", c
? "n" : "");
1680 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
1682 file
->ifndef_macro
= tok
;
1685 c
= (define_find(tok
) != 0) ^ c
;
1687 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
1688 tcc_error("memory full (ifdef)");
1689 *s1
->ifdef_stack_ptr
++ = c
;
1692 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1693 tcc_error("#else without matching #if");
1694 if (s1
->ifdef_stack_ptr
[-1] & 2)
1695 tcc_error("#else after #else");
1696 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
1699 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
1700 tcc_error("#elif without matching #if");
1701 c
= s1
->ifdef_stack_ptr
[-1];
1703 tcc_error("#elif after #else");
1704 /* last #if/#elif expression was true: we skip */
1707 c
= expr_preprocess();
1708 s1
->ifdef_stack_ptr
[-1] = c
;
1710 if (s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
+ 1)
1711 file
->ifndef_macro
= 0;
1721 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
1722 tcc_error("#endif without matching #if");
1723 s1
->ifdef_stack_ptr
--;
1724 /* '#ifndef macro' was at the start of file. Now we check if
1725 an '#endif' is exactly at the end of file */
1726 if (file
->ifndef_macro
&&
1727 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
1728 file
->ifndef_macro_saved
= file
->ifndef_macro
;
1729 /* need to set to zero to avoid false matches if another
1730 #ifndef at middle of file */
1731 file
->ifndef_macro
= 0;
1732 while (tok
!= TOK_LINEFEED
)
1734 tok_flags
|= TOK_FLAG_ENDIF
;
1740 if (tok
!= TOK_CINT
)
1741 tcc_error("A #line format is wrong");
1743 if (tok
!= TOK_CINT
) {
1744 char *p
= tokc
.cstr
->data
;
1745 tokc
.i
= strtoul(p
, (char **)&p
, 10);
1748 file
->line_num
= tokc
.i
- 1;
1750 if (tok
!= TOK_LINEFEED
) {
1751 if (tok
!= TOK_STR
) {
1752 if ((parse_flags
& PARSE_FLAG_ASM_FILE
) == 0) {
1754 tcc_error("#line format is wrong");
1758 pstrcpy(file
->filename
, sizeof(file
->filename
),
1759 (char *)tokc
.cstr
->data
);
1762 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1767 ch
= file
->buf_ptr
[0];
1770 while (ch
!= '\n' && ch
!= CH_EOF
) {
1771 if ((q
- buf
) < sizeof(buf
) - 1)
1774 if (handle_stray_noerror() == 0)
1781 tcc_error("#error %s", buf
);
1783 tcc_warning("#warning %s", buf
);
1789 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_PPNUM
) {
1790 /* '!' is ignored to allow C scripts. numbers are ignored
1791 to emulate cpp behaviour */
1793 if (!(parse_flags
& PARSE_FLAG_ASM_FILE
))
1794 tcc_warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
1796 /* this is a gas line comment in an 'S' file. */
1797 file
->buf_ptr
= parse_line_comment(file
->buf_ptr
);
1803 /* ignore other preprocess commands or #! for C scripts */
1804 while (tok
!= TOK_LINEFEED
)
1807 parse_flags
= saved_parse_flags
;
1810 /* evaluate escape codes in a string. */
1811 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
1826 case '0': case '1': case '2': case '3':
1827 case '4': case '5': case '6': case '7':
1828 /* at most three octal digits */
1833 n
= n
* 8 + c
- '0';
1837 n
= n
* 8 + c
- '0';
1842 goto add_char_nonext
;
1850 if (c
>= 'a' && c
<= 'f')
1852 else if (c
>= 'A' && c
<= 'F')
1862 goto add_char_nonext
;
1886 goto invalid_escape
;
1896 if (c
>= '!' && c
<= '~')
1897 tcc_warning("unknown escape sequence: \'\\%c\'", c
);
1899 tcc_warning("unknown escape sequence: \'\\x%x\'", c
);
1906 cstr_ccat(outstr
, c
);
1908 cstr_wccat(outstr
, c
);
1910 /* add a trailing '\0' */
1912 cstr_ccat(outstr
, '\0');
1914 cstr_wccat(outstr
, '\0');
1917 /* we use 64 bit numbers */
1920 /* bn = (bn << shift) | or_val */
1921 static void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
1925 for(i
=0;i
<BN_SIZE
;i
++) {
1927 bn
[i
] = (v
<< shift
) | or_val
;
1928 or_val
= v
>> (32 - shift
);
1932 static void bn_zero(unsigned int *bn
)
1935 for(i
=0;i
<BN_SIZE
;i
++) {
1940 /* parse number in null terminated string 'p' and return it in the
1942 static void parse_number(const char *p
)
1944 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
1946 unsigned int bn
[BN_SIZE
];
1957 goto float_frac_parse
;
1958 } else if (t
== '0') {
1959 if (ch
== 'x' || ch
== 'X') {
1963 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
1969 /* parse all digits. cannot check octal numbers at this stage
1970 because of floating point constants */
1972 if (ch
>= 'a' && ch
<= 'f')
1974 else if (ch
>= 'A' && ch
<= 'F')
1982 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
1984 tcc_error("number too long");
1990 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
1991 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
1993 /* NOTE: strtox should support that for hexa numbers, but
1994 non ISOC99 libcs do not support it, so we prefer to do
1996 /* hexadecimal or binary floats */
1997 /* XXX: handle overflows */
2009 } else if (t
>= 'a') {
2011 } else if (t
>= 'A') {
2016 bn_lshift(bn
, shift
, t
);
2023 if (t
>= 'a' && t
<= 'f') {
2025 } else if (t
>= 'A' && t
<= 'F') {
2027 } else if (t
>= '0' && t
<= '9') {
2033 tcc_error("invalid digit");
2034 bn_lshift(bn
, shift
, t
);
2039 if (ch
!= 'p' && ch
!= 'P')
2046 } else if (ch
== '-') {
2050 if (ch
< '0' || ch
> '9')
2051 expect("exponent digits");
2052 while (ch
>= '0' && ch
<= '9') {
2053 exp_val
= exp_val
* 10 + ch
- '0';
2056 exp_val
= exp_val
* s
;
2058 /* now we can generate the number */
2059 /* XXX: should patch directly float number */
2060 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2061 d
= ldexp(d
, exp_val
- frac_bits
);
2066 /* float : should handle overflow */
2068 } else if (t
== 'L') {
2070 #ifdef TCC_TARGET_PE
2075 /* XXX: not large enough */
2076 tokc
.ld
= (long double)d
;
2083 /* decimal floats */
2085 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2090 while (ch
>= '0' && ch
<= '9') {
2091 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2097 if (ch
== 'e' || ch
== 'E') {
2098 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2102 if (ch
== '-' || ch
== '+') {
2103 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2108 if (ch
< '0' || ch
> '9')
2109 expect("exponent digits");
2110 while (ch
>= '0' && ch
<= '9') {
2111 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2123 tokc
.f
= strtof(token_buf
, NULL
);
2124 } else if (t
== 'L') {
2126 #ifdef TCC_TARGET_PE
2128 tokc
.d
= strtod(token_buf
, NULL
);
2131 tokc
.ld
= strtold(token_buf
, NULL
);
2135 tokc
.d
= strtod(token_buf
, NULL
);
2139 unsigned long long n
, n1
;
2140 int lcount
, ucount
, must_64bit
;
2143 /* integer number */
2146 if (b
== 10 && *q
== '0') {
2153 /* no need for checks except for base 10 / 8 errors */
2163 tcc_error("invalid digit");
2166 /* detect overflow */
2167 /* XXX: this test is not reliable */
2169 tcc_error("integer constant overflow");
2172 /* Determine the characteristics (unsigned and/or 64bit) the type of
2173 the constant must have according to the constant suffix(es) */
2174 lcount
= ucount
= must_64bit
= 0;
2180 tcc_error("three 'l's in integer constant");
2181 if (lcount
&& *(p
- 1) != ch
)
2182 tcc_error("incorrect integer suffix: %s", p1
);
2184 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
2189 } else if (t
== 'U') {
2191 tcc_error("two 'u's in integer constant");
2199 /* Whether 64 bits are needed to hold the constant's value */
2200 if (n
& 0xffffffff00000000LL
|| must_64bit
) {
2208 /* Whether type must be unsigned to hold the constant's value */
2209 if (ucount
|| ((n1
>> 31) && (b
!= 10))) {
2210 if (tok
== TOK_CLLONG
)
2214 /* If decimal and no unsigned suffix, bump to 64 bits or throw error */
2215 } else if (n1
>> 31) {
2216 if (tok
== TOK_CINT
)
2219 tcc_error("integer constant overflow");
2222 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2228 tcc_error("invalid number\n");
2232 #define PARSE2(c1, tok1, c2, tok2) \
2243 /* return next token without macro substitution */
2244 static inline void next_nomacro1(void)
2259 goto keep_tok_flags
;
2266 /* first look if it is in fact an end of buffer */
2267 if (p
>= file
->buf_end
) {
2271 if (p
>= file
->buf_end
)
2278 if (parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
) {
2279 if (handle_stray_noerror() != 0) {
2290 TCCState
*s1
= tcc_state
;
2291 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
2292 && !(tok_flags
& TOK_FLAG_EOF
)) {
2293 tok_flags
|= TOK_FLAG_EOF
;
2295 goto keep_tok_flags
;
2296 } else if (!(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2298 } else if (s1
->ifdef_stack_ptr
!= file
->ifdef_stack_ptr
) {
2299 tcc_error("missing #endif");
2300 } else if (s1
->include_stack_ptr
== s1
->include_stack
) {
2301 /* no include left : end of file. */
2304 tok_flags
&= ~TOK_FLAG_EOF
;
2305 /* pop include file */
2307 /* test if previous '#endif' was after a #ifdef at
2309 if (tok_flags
& TOK_FLAG_ENDIF
) {
2311 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
2313 add_cached_include(s1
, file
->filename
, file
->ifndef_macro_saved
);
2314 tok_flags
&= ~TOK_FLAG_ENDIF
;
2317 /* add end of include file debug info */
2318 if (tcc_state
->do_debug
) {
2319 put_stabd(N_EINCL
, 0, 0);
2321 /* pop include stack */
2323 s1
->include_stack_ptr
--;
2332 tok_flags
|= TOK_FLAG_BOL
;
2335 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
2338 goto keep_tok_flags
;
2343 if (is_space(c
) && (parse_flags
& PARSE_FLAG_ASM_FILE
)) {
2344 p
= parse_line_comment(p
);
2348 if ((tok_flags
& TOK_FLAG_BOL
) &&
2349 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
2351 preprocess(tok_flags
& TOK_FLAG_BOF
);
2357 tok
= TOK_TWOSHARPS
;
2359 if (parse_flags
& PARSE_FLAG_ASM_FILE
) {
2360 p
= parse_line_comment(p
- 1);
2369 /* dollar is allowed to start identifiers when not parsing asm */
2371 if (!tcc_state
->dollars_in_identifiers
2372 || (parse_flags
& PARSE_FLAG_ASM_FILE
)) goto parse_simple
;
2374 case 'a': case 'b': case 'c': case 'd':
2375 case 'e': case 'f': case 'g': case 'h':
2376 case 'i': case 'j': case 'k': case 'l':
2377 case 'm': case 'n': case 'o': case 'p':
2378 case 'q': case 'r': case 's': case 't':
2379 case 'u': case 'v': case 'w': case 'x':
2381 case 'A': case 'B': case 'C': case 'D':
2382 case 'E': case 'F': case 'G': case 'H':
2383 case 'I': case 'J': case 'K':
2384 case 'M': case 'N': case 'O': case 'P':
2385 case 'Q': case 'R': case 'S': case 'T':
2386 case 'U': case 'V': case 'W': case 'X':
2392 h
= TOK_HASH_FUNC(h
, c
);
2396 if (!isidnum_table
[c
-CH_EOF
]
2397 && (tcc_state
->dollars_in_identifiers
? (c
!= '$') : 1))
2399 h
= TOK_HASH_FUNC(h
, c
);
2406 /* fast case : no stray found, so we have the full token
2407 and we have already hashed it */
2409 h
&= (TOK_HASH_SIZE
- 1);
2410 pts
= &hash_ident
[h
];
2415 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
2417 pts
= &(ts
->hash_next
);
2419 ts
= tok_alloc_new(pts
, (char *) p1
, len
);
2423 cstr_reset(&tokcstr
);
2426 cstr_ccat(&tokcstr
, *p1
);
2432 while (isidnum_table
[c
-CH_EOF
]
2433 || (tcc_state
->dollars_in_identifiers
? (c
== '$') : 0)) {
2434 cstr_ccat(&tokcstr
, c
);
2437 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
2443 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
2445 goto parse_ident_fast
;
2448 if (c
== '\'' || c
== '\"') {
2452 cstr_reset(&tokcstr
);
2453 cstr_ccat(&tokcstr
, 'L');
2454 goto parse_ident_slow
;
2458 case '0': case '1': case '2': case '3':
2459 case '4': case '5': case '6': case '7':
2462 cstr_reset(&tokcstr
);
2463 /* after the first digit, accept digits, alpha, '.' or sign if
2464 prefixed by 'eEpP' */
2468 cstr_ccat(&tokcstr
, c
);
2470 if (!(isnum(c
) || isid(c
) || c
== '.' ||
2471 ((c
== '+' || c
== '-') &&
2472 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
2475 /* We add a trailing '\0' to ease parsing */
2476 cstr_ccat(&tokcstr
, '\0');
2477 tokc
.cstr
= &tokcstr
;
2481 /* special dot handling because it can also start a number */
2484 cstr_reset(&tokcstr
);
2485 cstr_ccat(&tokcstr
, '.');
2487 } else if (c
== '.') {
2490 if ((parse_flags
& PARSE_FLAG_ASM_FILE
) == 0)
2511 /* parse the string */
2513 p
= parse_pp_string(p
, sep
, &str
);
2514 cstr_ccat(&str
, '\0');
2516 /* eval the escape (should be done as TOK_PPNUM) */
2517 cstr_reset(&tokcstr
);
2518 parse_escape_string(&tokcstr
, str
.data
, is_long
);
2523 /* XXX: make it portable */
2527 char_size
= sizeof(nwchar_t
);
2528 if (tokcstr
.size
<= char_size
)
2529 tcc_error("empty character constant");
2530 if (tokcstr
.size
> 2 * char_size
)
2531 tcc_warning("multi-character character constant");
2533 tokc
.i
= *(int8_t *)tokcstr
.data
;
2536 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
2540 tokc
.cstr
= &tokcstr
;
2554 } else if (c
== '<') {
2572 } else if (c
== '>') {
2590 } else if (c
== '=') {
2603 } else if (c
== '=') {
2616 } else if (c
== '=') {
2629 } else if (c
== '=') {
2632 } else if (c
== '>') {
2640 PARSE2('!', '!', '=', TOK_NE
)
2641 PARSE2('=', '=', '=', TOK_EQ
)
2642 PARSE2('*', '*', '=', TOK_A_MUL
)
2643 PARSE2('%', '%', '=', TOK_A_MOD
)
2644 PARSE2('^', '^', '=', TOK_A_XOR
)
2646 /* comments or operator */
2650 p
= parse_comment(p
);
2651 /* comments replaced by a blank */
2653 goto keep_tok_flags
;
2654 } else if (c
== '/') {
2655 p
= parse_line_comment(p
);
2657 goto keep_tok_flags
;
2658 } else if (c
== '=') {
2678 case '@': /* only used in assembler */
2684 if ((parse_flags
& PARSE_FLAG_ASM_FILE
) == 0)
2685 tcc_error("unrecognized character \\x%02x", c
);
2695 #if defined(PARSE_DEBUG)
2696 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2700 /* return next token without macro substitution. Can read input from
2702 static void next_nomacro_spc(void)
2708 TOK_GET(&tok
, ¯o_ptr
, &tokc
);
2709 if (tok
== TOK_LINENUM
) {
2710 file
->line_num
= tokc
.i
;
2719 ST_FUNC
void next_nomacro(void)
2723 } while (is_space(tok
));
2726 /* substitute arguments in replacement lists in macro_str by the values in
2727 args (field d) and return allocated string */
2728 static int *macro_arg_subst(Sym
**nested_list
, const int *macro_str
, Sym
*args
)
2730 int last_tok
, t
, spc
;
2741 TOK_GET(&t
, ¯o_str
, &cval
);
2746 TOK_GET(&t
, ¯o_str
, &cval
);
2749 s
= sym_find2(args
, t
);
2755 TOK_GET(&t
, &st
, &cval
);
2756 if (t
!= TOK_PLCHLDR
&& !check_space(t
, &spc
))
2757 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2760 cstr_ccat(&cstr
, '\0');
2762 printf("stringize: %s\n", (char *)cstr
.data
);
2766 /* emulate GCC behaviour and parse escapes in the token string */
2767 parse_escape_string(&cstr2
, cstr
.data
, 0);
2770 tok_str_add2(&str
, TOK_STR
, &cval
);
2771 cstr_free(cval
.cstr
);
2773 tok_str_add2(&str
, t
, &cval
);
2775 } else if (t
>= TOK_IDENT
) {
2776 s
= sym_find2(args
, t
);
2779 /* if '##' is present before or after, no arg substitution */
2780 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
2781 /* special case for var arg macros : ## eats the
2782 ',' if empty VA_ARGS variable. */
2783 /* XXX: test of the ',' is not 100%
2784 reliable. should fix it to avoid security
2786 if (gnu_ext
&& s
->type
.t
&&
2787 last_tok
== TOK_TWOSHARPS
&&
2788 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
2789 if (*st
== TOK_PLCHLDR
) {
2790 /* suppress ',' '##' */
2793 /* suppress '##' and add variable */
2801 TOK_GET(&t1
, &st
, &cval
);
2804 tok_str_add2(&str
, t1
, &cval
);
2807 } else if (*st
!= TOK_PLCHLDR
) {
2808 /* NOTE: the stream cannot be read when macro
2809 substituing an argument */
2810 macro_subst(&str
, nested_list
, st
, NULL
);
2813 tok_str_add(&str
, t
);
2816 tok_str_add2(&str
, t
, &cval
);
2820 tok_str_add(&str
, 0);
2824 static char const ab_month_name
[12][4] =
2826 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2827 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2830 /* do macro substitution of current token with macro 's' and add
2831 result to (tok_str,tok_len). 'nested_list' is the list of all
2832 macros we got inside to avoid recursing. Return non zero if no
2833 substitution needs to be done */
2834 static int macro_subst_tok(TokenString
*tok_str
,
2835 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
2837 Sym
*args
, *sa
, *sa1
;
2838 int mstr_allocated
, parlevel
, *mstr
, t
, t1
, spc
;
2846 /* if symbol is a macro, prepare substitution */
2847 /* special macros */
2848 if (tok
== TOK___LINE__
) {
2849 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
2853 } else if (tok
== TOK___FILE__
) {
2854 cstrval
= file
->filename
;
2856 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
2861 tm
= localtime(&ti
);
2862 if (tok
== TOK___DATE__
) {
2863 snprintf(buf
, sizeof(buf
), "%s %2d %d",
2864 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
2866 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
2867 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
2874 cstr_cat(&cstr
, cstrval
);
2875 cstr_ccat(&cstr
, '\0');
2877 tok_str_add2(tok_str
, t1
, &cval
);
2880 int saved_parse_flags
= parse_flags
;
2881 parse_flags
|= PARSE_FLAG_ACCEPT_STRAYS
| PARSE_FLAG_SPACES
| PARSE_FLAG_LINEFEED
;
2885 if (s
->type
.t
== MACRO_FUNC
) {
2886 /* NOTE: we do not use next_nomacro to avoid eating the
2887 next token. XXX: find better solution */
2891 while (is_space(t
= *p
) || TOK_LINEFEED
== t
)
2893 if (t
== 0 && can_read_stream
) {
2894 /* end of macro stream: we must look at the token
2895 after in the file */
2896 struct macro_level
*ml
= *can_read_stream
;
2902 *can_read_stream
= ml
-> prev
;
2904 /* also, end of scope for nested defined symbol */
2905 (*nested_list
)->v
= -1;
2909 ch
= tcc_peekc_slow(file
);
2910 while (is_space(ch
) || ch
== '\n' || ch
== '/')
2915 uint8_t *p
= file
->buf_ptr
;
2918 p
= parse_comment(p
);
2919 file
->buf_ptr
= p
- 1;
2920 } else if (c
== '/') {
2921 p
= parse_line_comment(p
);
2922 file
->buf_ptr
= p
- 1;
2931 /* no macro subst */
2932 parse_flags
= saved_parse_flags
;
2936 /* argument macro */
2941 /* NOTE: empty args are allowed, except if no args */
2943 /* handle '()' case */
2944 if (!args
&& !sa
&& tok
== ')')
2947 tcc_error("macro '%s' used with too many args",
2948 get_tok_str(s
->v
, 0));
2951 /* NOTE: non zero sa->t indicates VA_ARGS */
2952 while ((parlevel
> 0 ||
2954 (tok
!= ',' || sa
->type
.t
)))) {
2955 if (tok
== TOK_EOF
|| tok
== 0)
2959 else if (tok
== ')')
2961 if (tok
== TOK_LINEFEED
)
2963 if (!check_space(tok
, &spc
))
2964 tok_str_add2(&str
, tok
, &tokc
);
2968 tok_str_add(&str
, TOK_PLCHLDR
);
2970 tok_str_add(&str
, 0);
2971 sa1
= sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, 0);
2975 /* special case for gcc var args: add an empty
2976 var arg argument if it is omitted */
2977 if (sa
&& sa
->type
.t
&& gnu_ext
)
2987 tcc_error("macro '%s' used with too few args",
2988 get_tok_str(s
->v
, 0));
2991 /* now subst each arg */
2992 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
2997 tok_str_free(sa
->d
);
3003 sym_push2(nested_list
, s
->v
, 0, 0);
3004 parse_flags
= saved_parse_flags
;
3005 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
3006 /* pop nested defined symbol */
3008 *nested_list
= sa1
->prev
;
3016 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3017 return the resulting string (which must be freed). */
3018 static inline int *macro_twosharps(const int *macro_str
)
3022 TokenString macro_str1
;
3024 int n
, start_of_nosubsts
;
3026 /* we search the first '##' */
3027 for(ptr
= macro_str
;;) {
3029 TOK_GET(&t
, &ptr
, &cval
);
3030 if (t
== TOK_TWOSHARPS
)
3032 /* nothing more to do if end of string */
3037 /* we saw '##', so we need more processing to handle it */
3038 start_of_nosubsts
= -1;
3039 tok_str_new(¯o_str1
);
3040 for(ptr
= macro_str
;;) {
3041 TOK_GET(&tok
, &ptr
, &tokc
);
3044 if (tok
== TOK_TWOSHARPS
)
3046 if (tok
== TOK_NOSUBST
&& start_of_nosubsts
< 0)
3047 start_of_nosubsts
= macro_str1
.len
;
3048 while (*ptr
== TOK_TWOSHARPS
) {
3049 /* given 'a##b', remove nosubsts preceding 'a' */
3050 if (start_of_nosubsts
>= 0)
3051 macro_str1
.len
= start_of_nosubsts
;
3052 /* given 'a##b', skip '##' */
3054 /* given 'a##b', remove nosubsts preceding 'b' */
3055 while (t
== TOK_NOSUBST
)
3057 if (t
&& t
!= TOK_TWOSHARPS
) {
3059 TOK_GET(&t
, &ptr
, &cval
);
3060 /* We concatenate the two tokens */
3062 if (tok
!= TOK_PLCHLDR
)
3063 cstr_cat(&cstr
, get_tok_str(tok
, &tokc
));
3065 if (t
!= TOK_PLCHLDR
|| tok
== TOK_PLCHLDR
)
3066 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3067 cstr_ccat(&cstr
, '\0');
3069 tcc_open_bf(tcc_state
, ":paste:", cstr
.size
);
3070 memcpy(file
->buffer
, cstr
.data
, cstr
.size
);
3073 if (0 == *file
->buf_ptr
)
3075 tok_str_add2(¯o_str1
, tok
, &tokc
);
3076 tcc_warning("pasting \"%.*s\" and \"%s\" does not give a valid preprocessing token",
3077 n
, cstr
.data
, (char*)cstr
.data
+ n
);
3083 if (tok
!= TOK_NOSUBST
) {
3084 tok_str_add2(¯o_str1
, tok
, &tokc
);
3086 start_of_nosubsts
= -1;
3088 tok_str_add2(¯o_str1
, tok
, &tokc
);
3090 tok_str_add(¯o_str1
, 0);
3091 return macro_str1
.str
;
3095 /* do macro substitution of macro_str and add result to
3096 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3097 inside to avoid recursing. */
3098 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
3099 const int *macro_str
, struct macro_level
** can_read_stream
)
3106 struct macro_level ml
;
3109 /* first scan for '##' operator handling */
3111 macro_str1
= macro_twosharps(ptr
);
3119 /* NOTE: ptr == NULL can only happen if tokens are read from
3120 file stream due to a macro function call */
3123 TOK_GET(&t
, &ptr
, &cval
);
3126 if (t
== '\\' && !(parse_flags
& PARSE_FLAG_ACCEPT_STRAYS
)) {
3127 tcc_error("stray '\\' in program");
3129 if (t
== TOK_NOSUBST
) {
3130 /* following token has already been subst'd. just copy it on */
3131 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3132 TOK_GET(&t
, &ptr
, &cval
);
3137 /* if nested substitution, do nothing */
3138 if (sym_find2(*nested_list
, t
)) {
3139 /* and mark it as TOK_NOSUBST, so it doesn't get subst'd again */
3140 tok_str_add2(tok_str
, TOK_NOSUBST
, NULL
);
3144 if (can_read_stream
)
3145 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
3146 macro_ptr
= (int *)ptr
;
3148 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
3149 spc
= tok_str
->len
&& is_space(tok_str
->str
[tok_str
->len
-1]);
3150 ptr
= (int *)macro_ptr
;
3152 if (can_read_stream
&& *can_read_stream
== &ml
)
3153 *can_read_stream
= ml
.prev
;
3156 if (parse_flags
& PARSE_FLAG_SPACES
)
3161 tok_str_add(tok_str
, ' ');
3165 if (!check_space(t
, &spc
))
3166 tok_str_add2(tok_str
, t
, &cval
);
3170 tok_str_free(macro_str1
);
3173 /* return next token with macro substitution */
3174 ST_FUNC
void next(void)
3176 Sym
*nested_list
, *s
;
3178 struct macro_level
*ml
;
3181 if (parse_flags
& PARSE_FLAG_SPACES
)
3186 /* if not reading from macro substituted string, then try
3187 to substitute macros */
3188 if (tok
>= TOK_IDENT
&&
3189 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3190 s
= define_find(tok
);
3192 /* we have a macro: we try to substitute */
3196 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
3197 /* substitution done, NOTE: maybe empty */
3198 tok_str_add(&str
, 0);
3199 macro_ptr
= str
.str
;
3200 macro_ptr_allocated
= str
.str
;
3207 /* end of macro or end of unget buffer */
3208 if (unget_buffer_enabled
) {
3209 macro_ptr
= unget_saved_macro_ptr
;
3210 unget_buffer_enabled
= 0;
3212 /* end of macro string: free it */
3213 tok_str_free(macro_ptr_allocated
);
3214 macro_ptr_allocated
= NULL
;
3218 } else if (tok
== TOK_NOSUBST
) {
3219 /* discard preprocessor's nosubst markers */
3224 /* convert preprocessor tokens into C tokens */
3225 if (tok
== TOK_PPNUM
&&
3226 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
3227 parse_number((char *)tokc
.cstr
->data
);
3231 /* push back current token and set current token to 'last_tok'. Only
3232 identifier case handled for labels. */
3233 ST_INLN
void unget_tok(int last_tok
)
3237 if (unget_buffer_enabled
)
3239 /* assert(macro_ptr == unget_saved_buffer + 1);
3240 assert(*macro_ptr == 0); */
3244 unget_saved_macro_ptr
= macro_ptr
;
3245 unget_buffer_enabled
= 1;
3247 q
= unget_saved_buffer
;
3250 n
= tok_ext_size(tok
) - 1;
3253 *q
= 0; /* end of token string */
3258 /* better than nothing, but needs extension to handle '-E' option
3260 ST_FUNC
void preprocess_init(TCCState
*s1
)
3262 s1
->include_stack_ptr
= s1
->include_stack
;
3263 /* XXX: move that before to avoid having to initialize
3264 file->ifdef_stack_ptr ? */
3265 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
3266 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
3269 s1
->pack_stack
[0] = 0;
3270 s1
->pack_stack_ptr
= s1
->pack_stack
;
3273 ST_FUNC
void preprocess_new(void)
3278 /* init isid table */
3280 for(i
=CH_EOF
;i
<256;i
++)
3281 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
3283 /* add all tokens */
3285 tcc_free (table_ident
);
3288 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
3290 tok_ident
= TOK_IDENT
;
3299 tok_alloc(p
, r
- p
- 1);
3304 static void line_macro_output(BufferedFile
*f
, const char *s
, TCCState
*s1
)
3306 switch (s1
->Pflag
) {
3307 case LINE_MACRO_OUTPUT_FORMAT_STD
:
3308 /* "tcc -E -P1" case */
3309 fprintf(s1
->ppfp
, "# line %d \"%s\"\n", f
->line_num
, f
->filename
);
3312 case LINE_MACRO_OUTPUT_FORMAT_NONE
:
3313 /* "tcc -E -P" case: don't output a line directive */
3316 case LINE_MACRO_OUTPUT_FORMAT_GCC
:
3318 /* "tcc -E" case: a gcc standard by default */
3319 fprintf(s1
->ppfp
, "# %d \"%s\"%s\n", f
->line_num
, f
->filename
, s
);
3324 /* Preprocess the current file */
3325 ST_FUNC
int tcc_preprocess(TCCState
*s1
)
3327 BufferedFile
*file_ref
, **iptr
, **iptr_new
;
3331 preprocess_init(s1
);
3332 ch
= file
->buf_ptr
[0];
3333 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
3334 parse_flags
&= PARSE_FLAG_ASM_FILE
;
3335 parse_flags
|= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_LINEFEED
| PARSE_FLAG_SPACES
| PARSE_FLAG_ACCEPT_STRAYS
;
3339 iptr
= s1
->include_stack_ptr
;
3343 if (tok
== TOK_EOF
) {
3345 } else if (file
!= file_ref
) {
3347 line_macro_output(file_ref
, "", s1
);
3349 } else if (tok
== TOK_LINEFEED
) {
3354 } else if (!token_seen
) {
3355 d
= file
->line_num
- file
->line_ref
;
3356 if (file
!= file_ref
|| d
>= 8) {
3359 if (tcc_state
->Pflag
== LINE_MACRO_OUTPUT_FORMAT_GCC
) {
3360 iptr_new
= s1
->include_stack_ptr
;
3361 s
= iptr_new
> iptr
? " 1"
3362 : iptr_new
< iptr
? " 2"
3363 : iptr_new
> s1
->include_stack
? " 3"
3367 line_macro_output(file
, s
, s1
);
3370 fputs("\n", s1
->ppfp
), --d
;
3372 file
->line_ref
= (file_ref
= file
)->line_num
;
3373 token_seen
= tok
!= TOK_LINEFEED
;
3377 fputs(get_tok_str(tok
, &tokc
), s1
->ppfp
);