fix crash in rewrite_branch()
[smatch.git] / parse.c
blob02a55a7454580107fdb5aa9e64db54f1a9edb892
1 /*
2 * Stupid C parser, version 1e-6.
4 * Let's see how hard this is to do.
6 * Copyright (C) 2003 Transmeta Corp.
7 * 2003-2004 Linus Torvalds
8 * Copyright (C) 2004 Christopher Li
10 * Permission is hereby granted, free of charge, to any person obtaining a copy
11 * of this software and associated documentation files (the "Software"), to deal
12 * in the Software without restriction, including without limitation the rights
13 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the Software is
15 * furnished to do so, subject to the following conditions:
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 * THE SOFTWARE.
29 #include <stdarg.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <limits.h>
38 #include "lib.h"
39 #include "allocate.h"
40 #include "token.h"
41 #include "parse.h"
42 #include "symbol.h"
43 #include "scope.h"
44 #include "expression.h"
45 #include "target.h"
47 static struct symbol_list **function_symbol_list;
48 struct symbol_list *function_computed_target_list;
49 struct statement_list *function_computed_goto_list;
51 static struct token *statement(struct token *token, struct statement **tree);
52 static struct token *handle_attributes(struct token *token, struct decl_state *ctx, unsigned int keywords);
54 typedef struct token *declarator_t(struct token *, struct decl_state *);
55 static declarator_t
56 struct_specifier, union_specifier, enum_specifier,
57 attribute_specifier, typeof_specifier, parse_asm_declarator,
58 typedef_specifier, inline_specifier, auto_specifier,
59 register_specifier, static_specifier, extern_specifier,
60 thread_specifier, const_qualifier, volatile_qualifier;
62 static struct token *parse_if_statement(struct token *token, struct statement *stmt);
63 static struct token *parse_return_statement(struct token *token, struct statement *stmt);
64 static struct token *parse_loop_iterator(struct token *token, struct statement *stmt);
65 static struct token *parse_default_statement(struct token *token, struct statement *stmt);
66 static struct token *parse_case_statement(struct token *token, struct statement *stmt);
67 static struct token *parse_switch_statement(struct token *token, struct statement *stmt);
68 static struct token *parse_for_statement(struct token *token, struct statement *stmt);
69 static struct token *parse_while_statement(struct token *token, struct statement *stmt);
70 static struct token *parse_do_statement(struct token *token, struct statement *stmt);
71 static struct token *parse_goto_statement(struct token *token, struct statement *stmt);
72 static struct token *parse_context_statement(struct token *token, struct statement *stmt);
73 static struct token *parse_range_statement(struct token *token, struct statement *stmt);
74 static struct token *parse_asm_statement(struct token *token, struct statement *stmt);
75 static struct token *toplevel_asm_declaration(struct token *token, struct symbol_list **list);
76 static struct token *parse_static_assert(struct token *token, struct symbol_list **unused);
78 typedef struct token *attr_t(struct token *, struct symbol *,
79 struct decl_state *);
81 static attr_t
82 attribute_packed, attribute_aligned, attribute_modifier,
83 attribute_bitwise,
84 attribute_address_space, attribute_context,
85 attribute_designated_init,
86 attribute_transparent_union, ignore_attribute,
87 attribute_mode, attribute_force;
89 typedef struct symbol *to_mode_t(struct symbol *);
91 static to_mode_t
92 to_QI_mode, to_HI_mode, to_SI_mode, to_DI_mode, to_TI_mode, to_word_mode;
94 enum {
95 Set_T = 1,
96 Set_S = 2,
97 Set_Char = 4,
98 Set_Int = 8,
99 Set_Double = 16,
100 Set_Float = 32,
101 Set_Signed = 64,
102 Set_Unsigned = 128,
103 Set_Short = 256,
104 Set_Long = 512,
105 Set_Vlong = 1024,
106 Set_Int128 = 2048,
107 Set_Any = Set_T | Set_Short | Set_Long | Set_Signed | Set_Unsigned
110 enum {
111 CInt = 0, CSInt, CUInt, CReal, CChar, CSChar, CUChar,
114 enum {
115 SNone = 0, STypedef, SAuto, SRegister, SExtern, SStatic, SForced, SMax,
118 static struct symbol_op typedef_op = {
119 .type = KW_MODIFIER,
120 .declarator = typedef_specifier,
123 static struct symbol_op inline_op = {
124 .type = KW_MODIFIER,
125 .declarator = inline_specifier,
128 static declarator_t noreturn_specifier;
129 static struct symbol_op noreturn_op = {
130 .type = KW_MODIFIER,
131 .declarator = noreturn_specifier,
134 static declarator_t alignas_specifier;
135 static struct symbol_op alignas_op = {
136 .type = KW_MODIFIER,
137 .declarator = alignas_specifier,
140 static struct symbol_op auto_op = {
141 .type = KW_MODIFIER,
142 .declarator = auto_specifier,
145 static struct symbol_op register_op = {
146 .type = KW_MODIFIER,
147 .declarator = register_specifier,
150 static struct symbol_op static_op = {
151 .type = KW_MODIFIER,
152 .declarator = static_specifier,
155 static struct symbol_op extern_op = {
156 .type = KW_MODIFIER,
157 .declarator = extern_specifier,
160 static struct symbol_op thread_op = {
161 .type = KW_MODIFIER,
162 .declarator = thread_specifier,
165 static struct symbol_op const_op = {
166 .type = KW_QUALIFIER,
167 .declarator = const_qualifier,
170 static struct symbol_op volatile_op = {
171 .type = KW_QUALIFIER,
172 .declarator = volatile_qualifier,
175 static struct symbol_op restrict_op = {
176 .type = KW_QUALIFIER,
179 static struct symbol_op typeof_op = {
180 .type = KW_SPECIFIER,
181 .declarator = typeof_specifier,
182 .test = Set_Any,
183 .set = Set_S|Set_T,
186 static struct symbol_op attribute_op = {
187 .type = KW_ATTRIBUTE,
188 .declarator = attribute_specifier,
191 static struct symbol_op struct_op = {
192 .type = KW_SPECIFIER,
193 .declarator = struct_specifier,
194 .test = Set_Any,
195 .set = Set_S|Set_T,
198 static struct symbol_op union_op = {
199 .type = KW_SPECIFIER,
200 .declarator = union_specifier,
201 .test = Set_Any,
202 .set = Set_S|Set_T,
205 static struct symbol_op enum_op = {
206 .type = KW_SPECIFIER,
207 .declarator = enum_specifier,
208 .test = Set_Any,
209 .set = Set_S|Set_T,
212 static struct symbol_op spec_op = {
213 .type = KW_SPECIFIER | KW_EXACT,
214 .test = Set_Any,
215 .set = Set_S|Set_T,
218 static struct symbol_op char_op = {
219 .type = KW_SPECIFIER,
220 .test = Set_T|Set_Long|Set_Short,
221 .set = Set_T|Set_Char,
222 .class = CChar,
225 static struct symbol_op int_op = {
226 .type = KW_SPECIFIER,
227 .test = Set_T,
228 .set = Set_T|Set_Int,
231 static struct symbol_op double_op = {
232 .type = KW_SPECIFIER,
233 .test = Set_T|Set_Signed|Set_Unsigned|Set_Short|Set_Vlong,
234 .set = Set_T|Set_Double,
235 .class = CReal,
238 static struct symbol_op float_op = {
239 .type = KW_SPECIFIER | KW_SHORT,
240 .test = Set_T|Set_Signed|Set_Unsigned|Set_Short|Set_Long,
241 .set = Set_T|Set_Float,
242 .class = CReal,
245 static struct symbol_op short_op = {
246 .type = KW_SPECIFIER | KW_SHORT,
247 .test = Set_S|Set_Char|Set_Float|Set_Double|Set_Long|Set_Short,
248 .set = Set_Short,
251 static struct symbol_op signed_op = {
252 .type = KW_SPECIFIER,
253 .test = Set_S|Set_Float|Set_Double|Set_Signed|Set_Unsigned,
254 .set = Set_Signed,
255 .class = CSInt,
258 static struct symbol_op unsigned_op = {
259 .type = KW_SPECIFIER,
260 .test = Set_S|Set_Float|Set_Double|Set_Signed|Set_Unsigned,
261 .set = Set_Unsigned,
262 .class = CUInt,
265 static struct symbol_op long_op = {
266 .type = KW_SPECIFIER | KW_LONG,
267 .test = Set_S|Set_Char|Set_Float|Set_Short|Set_Vlong,
268 .set = Set_Long,
271 static struct symbol_op int128_op = {
272 .type = KW_SPECIFIER | KW_LONG,
273 .test = Set_S|Set_T|Set_Char|Set_Short|Set_Int|Set_Float|Set_Double|Set_Long|Set_Vlong|Set_Int128,
274 .set = Set_T|Set_Int128,
277 static struct symbol_op if_op = {
278 .statement = parse_if_statement,
281 static struct symbol_op return_op = {
282 .statement = parse_return_statement,
285 static struct symbol_op loop_iter_op = {
286 .statement = parse_loop_iterator,
289 static struct symbol_op default_op = {
290 .statement = parse_default_statement,
293 static struct symbol_op case_op = {
294 .statement = parse_case_statement,
297 static struct symbol_op switch_op = {
298 .statement = parse_switch_statement,
301 static struct symbol_op for_op = {
302 .statement = parse_for_statement,
305 static struct symbol_op while_op = {
306 .statement = parse_while_statement,
309 static struct symbol_op do_op = {
310 .statement = parse_do_statement,
313 static struct symbol_op goto_op = {
314 .statement = parse_goto_statement,
317 static struct symbol_op __context___op = {
318 .statement = parse_context_statement,
321 static struct symbol_op range_op = {
322 .statement = parse_range_statement,
325 static struct symbol_op asm_op = {
326 .type = KW_ASM,
327 .declarator = parse_asm_declarator,
328 .statement = parse_asm_statement,
329 .toplevel = toplevel_asm_declaration,
332 static struct symbol_op static_assert_op = {
333 .toplevel = parse_static_assert,
336 static struct symbol_op packed_op = {
337 .attribute = attribute_packed,
340 static struct symbol_op aligned_op = {
341 .attribute = attribute_aligned,
344 static struct symbol_op attr_mod_op = {
345 .attribute = attribute_modifier,
348 static struct symbol_op attr_bitwise_op = {
349 .attribute = attribute_bitwise,
352 static struct symbol_op attr_force_op = {
353 .attribute = attribute_force,
356 static struct symbol_op address_space_op = {
357 .attribute = attribute_address_space,
360 static struct symbol_op mode_op = {
361 .attribute = attribute_mode,
364 static struct symbol_op context_op = {
365 .attribute = attribute_context,
368 static struct symbol_op designated_init_op = {
369 .attribute = attribute_designated_init,
372 static struct symbol_op transparent_union_op = {
373 .attribute = attribute_transparent_union,
376 static struct symbol_op ignore_attr_op = {
377 .attribute = ignore_attribute,
380 static struct symbol_op mode_QI_op = {
381 .type = KW_MODE,
382 .to_mode = to_QI_mode
385 static struct symbol_op mode_HI_op = {
386 .type = KW_MODE,
387 .to_mode = to_HI_mode
390 static struct symbol_op mode_SI_op = {
391 .type = KW_MODE,
392 .to_mode = to_SI_mode
395 static struct symbol_op mode_DI_op = {
396 .type = KW_MODE,
397 .to_mode = to_DI_mode
400 static struct symbol_op mode_TI_op = {
401 .type = KW_MODE,
402 .to_mode = to_TI_mode
405 static struct symbol_op mode_word_op = {
406 .type = KW_MODE,
407 .to_mode = to_word_mode
410 /* Using NS_TYPEDEF will also make the keyword a reserved one */
411 static struct init_keyword {
412 const char *name;
413 enum namespace ns;
414 unsigned long modifiers;
415 struct symbol_op *op;
416 struct symbol *type;
417 } keyword_table[] = {
418 /* Type qualifiers */
419 { "const", NS_TYPEDEF, .op = &const_op },
420 { "__const", NS_TYPEDEF, .op = &const_op },
421 { "__const__", NS_TYPEDEF, .op = &const_op },
422 { "volatile", NS_TYPEDEF, .op = &volatile_op },
423 { "__volatile", NS_TYPEDEF, .op = &volatile_op },
424 { "__volatile__", NS_TYPEDEF, .op = &volatile_op },
426 /* Typedef.. */
427 { "typedef", NS_TYPEDEF, .op = &typedef_op },
429 /* Type specifiers */
430 { "void", NS_TYPEDEF, .type = &void_ctype, .op = &spec_op},
431 { "char", NS_TYPEDEF, .op = &char_op },
432 { "short", NS_TYPEDEF, .op = &short_op },
433 { "int", NS_TYPEDEF, .op = &int_op },
434 { "long", NS_TYPEDEF, .op = &long_op },
435 { "float", NS_TYPEDEF, .op = &float_op },
436 { "double", NS_TYPEDEF, .op = &double_op },
437 { "signed", NS_TYPEDEF, .op = &signed_op },
438 { "__signed", NS_TYPEDEF, .op = &signed_op },
439 { "__signed__", NS_TYPEDEF, .op = &signed_op },
440 { "unsigned", NS_TYPEDEF, .op = &unsigned_op },
441 { "__int128", NS_TYPEDEF, .op = &int128_op },
442 { "_Bool", NS_TYPEDEF, .type = &bool_ctype, .op = &spec_op },
444 /* Predeclared types */
445 { "__builtin_va_list", NS_TYPEDEF, .type = &ptr_ctype, .op = &spec_op },
446 { "__builtin_ms_va_list", NS_TYPEDEF, .type = &ptr_ctype, .op = &spec_op },
447 { "__int128_t", NS_TYPEDEF, .type = &lllong_ctype, .op = &spec_op },
448 { "__uint128_t",NS_TYPEDEF, .type = &ulllong_ctype, .op = &spec_op },
450 /* Extended types */
451 { "typeof", NS_TYPEDEF, .op = &typeof_op },
452 { "__typeof", NS_TYPEDEF, .op = &typeof_op },
453 { "__typeof__", NS_TYPEDEF, .op = &typeof_op },
455 { "__attribute", NS_TYPEDEF, .op = &attribute_op },
456 { "__attribute__", NS_TYPEDEF, .op = &attribute_op },
458 { "struct", NS_TYPEDEF, .op = &struct_op },
459 { "union", NS_TYPEDEF, .op = &union_op },
460 { "enum", NS_TYPEDEF, .op = &enum_op },
462 { "inline", NS_TYPEDEF, .op = &inline_op },
463 { "__inline", NS_TYPEDEF, .op = &inline_op },
464 { "__inline__", NS_TYPEDEF, .op = &inline_op },
466 { "_Noreturn", NS_TYPEDEF, .op = &noreturn_op },
468 { "_Alignas", NS_TYPEDEF, .op = &alignas_op },
470 /* Ignored for now.. */
471 { "restrict", NS_TYPEDEF, .op = &restrict_op},
472 { "__restrict", NS_TYPEDEF, .op = &restrict_op},
473 { "__restrict__", NS_TYPEDEF, .op = &restrict_op},
475 /* Static assertion */
476 { "_Static_assert", NS_KEYWORD, .op = &static_assert_op },
478 /* Storage class */
479 { "auto", NS_TYPEDEF, .op = &auto_op },
480 { "register", NS_TYPEDEF, .op = &register_op },
481 { "static", NS_TYPEDEF, .op = &static_op },
482 { "extern", NS_TYPEDEF, .op = &extern_op },
483 { "__thread", NS_TYPEDEF, .op = &thread_op },
484 { "_Thread_local", NS_TYPEDEF, .op = &thread_op },
486 /* Statement */
487 { "if", NS_KEYWORD, .op = &if_op },
488 { "return", NS_KEYWORD, .op = &return_op },
489 { "break", NS_KEYWORD, .op = &loop_iter_op },
490 { "continue", NS_KEYWORD, .op = &loop_iter_op },
491 { "default", NS_KEYWORD, .op = &default_op },
492 { "case", NS_KEYWORD, .op = &case_op },
493 { "switch", NS_KEYWORD, .op = &switch_op },
494 { "for", NS_KEYWORD, .op = &for_op },
495 { "while", NS_KEYWORD, .op = &while_op },
496 { "do", NS_KEYWORD, .op = &do_op },
497 { "goto", NS_KEYWORD, .op = &goto_op },
498 { "__context__",NS_KEYWORD, .op = &__context___op },
499 { "__range__", NS_KEYWORD, .op = &range_op },
500 { "asm", NS_KEYWORD, .op = &asm_op },
501 { "__asm", NS_KEYWORD, .op = &asm_op },
502 { "__asm__", NS_KEYWORD, .op = &asm_op },
504 /* Attribute */
505 { "packed", NS_KEYWORD, .op = &packed_op },
506 { "__packed__", NS_KEYWORD, .op = &packed_op },
507 { "aligned", NS_KEYWORD, .op = &aligned_op },
508 { "__aligned__",NS_KEYWORD, .op = &aligned_op },
509 { "nocast", NS_KEYWORD, MOD_NOCAST, .op = &attr_mod_op },
510 { "noderef", NS_KEYWORD, MOD_NODEREF, .op = &attr_mod_op },
511 { "safe", NS_KEYWORD, MOD_SAFE, .op = &attr_mod_op },
512 { "force", NS_KEYWORD, .op = &attr_force_op },
513 { "bitwise", NS_KEYWORD, MOD_BITWISE, .op = &attr_bitwise_op },
514 { "__bitwise__",NS_KEYWORD, MOD_BITWISE, .op = &attr_bitwise_op },
515 { "address_space",NS_KEYWORD, .op = &address_space_op },
516 { "mode", NS_KEYWORD, .op = &mode_op },
517 { "context", NS_KEYWORD, .op = &context_op },
518 { "designated_init", NS_KEYWORD, .op = &designated_init_op },
519 { "__transparent_union__", NS_KEYWORD, .op = &transparent_union_op },
520 { "noreturn", NS_KEYWORD, MOD_NORETURN, .op = &attr_mod_op },
521 { "__noreturn__", NS_KEYWORD, MOD_NORETURN, .op = &attr_mod_op },
522 { "pure", NS_KEYWORD, MOD_PURE, .op = &attr_mod_op },
523 {"__pure__", NS_KEYWORD, MOD_PURE, .op = &attr_mod_op },
524 {"const", NS_KEYWORD, MOD_PURE, .op = &attr_mod_op },
525 {"__const", NS_KEYWORD, MOD_PURE, .op = &attr_mod_op },
526 {"__const__", NS_KEYWORD, MOD_PURE, .op = &attr_mod_op },
528 { "__mode__", NS_KEYWORD, .op = &mode_op },
529 { "QI", NS_KEYWORD, MOD_CHAR, .op = &mode_QI_op },
530 { "__QI__", NS_KEYWORD, MOD_CHAR, .op = &mode_QI_op },
531 { "HI", NS_KEYWORD, MOD_SHORT, .op = &mode_HI_op },
532 { "__HI__", NS_KEYWORD, MOD_SHORT, .op = &mode_HI_op },
533 { "SI", NS_KEYWORD, .op = &mode_SI_op },
534 { "__SI__", NS_KEYWORD, .op = &mode_SI_op },
535 { "DI", NS_KEYWORD, MOD_LONGLONG, .op = &mode_DI_op },
536 { "__DI__", NS_KEYWORD, MOD_LONGLONG, .op = &mode_DI_op },
537 { "TI", NS_KEYWORD, MOD_LONGLONGLONG, .op = &mode_TI_op },
538 { "__TI__", NS_KEYWORD, MOD_LONGLONGLONG, .op = &mode_TI_op },
539 { "word", NS_KEYWORD, MOD_LONG, .op = &mode_word_op },
540 { "__word__", NS_KEYWORD, MOD_LONG, .op = &mode_word_op },
544 static const char *ignored_attributes[] = {
546 #define GCC_ATTR(x) \
547 STRINGIFY(x), \
548 STRINGIFY(__##x##__),
550 #include "gcc-attr-list.h"
552 #undef GCC_ATTR
554 "bounded",
555 "__bounded__",
556 "__noclone",
557 "__nonnull",
558 "__nothrow",
562 void init_parser(int stream)
564 int i;
565 for (i = 0; i < ARRAY_SIZE(keyword_table); i++) {
566 struct init_keyword *ptr = keyword_table + i;
567 struct symbol *sym = create_symbol(stream, ptr->name, SYM_KEYWORD, ptr->ns);
568 sym->ident->keyword = 1;
569 if (ptr->ns == NS_TYPEDEF)
570 sym->ident->reserved = 1;
571 sym->ctype.modifiers = ptr->modifiers;
572 sym->ctype.base_type = ptr->type;
573 sym->op = ptr->op;
576 for (i = 0; i < ARRAY_SIZE(ignored_attributes); i++) {
577 const char * name = ignored_attributes[i];
578 struct symbol *sym = create_symbol(stream, name, SYM_KEYWORD,
579 NS_KEYWORD);
580 if (!sym->op) {
581 sym->ident->keyword = 1;
582 sym->op = &ignore_attr_op;
588 // Add a symbol to the list of function-local symbols
589 static void fn_local_symbol(struct symbol *sym)
591 if (function_symbol_list)
592 add_symbol(function_symbol_list, sym);
595 static int SENTINEL_ATTR match_idents(struct token *token, ...)
597 va_list args;
598 struct ident * next;
600 if (token_type(token) != TOKEN_IDENT)
601 return 0;
603 va_start(args, token);
604 do {
605 next = va_arg(args, struct ident *);
606 } while (next && token->ident != next);
607 va_end(args);
609 return next && token->ident == next;
613 struct statement *alloc_statement(struct position pos, int type)
615 struct statement *stmt = __alloc_statement(0);
616 stmt->type = type;
617 stmt->pos = pos;
618 return stmt;
621 static struct token *struct_declaration_list(struct token *token, struct symbol_list **list);
623 static void apply_modifiers(struct position pos, struct decl_state *ctx)
625 struct symbol *ctype;
626 if (!ctx->mode)
627 return;
628 ctype = ctx->mode->to_mode(ctx->ctype.base_type);
629 if (!ctype)
630 sparse_error(pos, "don't know how to apply mode to %s",
631 show_typename(ctx->ctype.base_type));
632 else
633 ctx->ctype.base_type = ctype;
637 static struct symbol * alloc_indirect_symbol(struct position pos, struct ctype *ctype, int type)
639 struct symbol *sym = alloc_symbol(pos, type);
641 sym->ctype.base_type = ctype->base_type;
642 sym->ctype.modifiers = ctype->modifiers;
644 ctype->base_type = sym;
645 ctype->modifiers = 0;
646 return sym;
650 * NOTE! NS_LABEL is not just a different namespace,
651 * it also ends up using function scope instead of the
652 * regular symbol scope.
654 struct symbol *label_symbol(struct token *token)
656 struct symbol *sym = lookup_symbol(token->ident, NS_LABEL);
657 if (!sym) {
658 sym = alloc_symbol(token->pos, SYM_LABEL);
659 bind_symbol(sym, token->ident, NS_LABEL);
660 fn_local_symbol(sym);
662 return sym;
665 static struct token *struct_union_enum_specifier(enum type type,
666 struct token *token, struct decl_state *ctx,
667 struct token *(*parse)(struct token *, struct symbol *))
669 struct symbol *sym;
670 struct position *repos;
672 token = handle_attributes(token, ctx, KW_ATTRIBUTE);
673 if (token_type(token) == TOKEN_IDENT) {
674 sym = lookup_symbol(token->ident, NS_STRUCT);
675 if (!sym ||
676 (is_outer_scope(sym->scope) &&
677 (match_op(token->next,';') || match_op(token->next,'{')))) {
678 // Either a new symbol, or else an out-of-scope
679 // symbol being redefined.
680 sym = alloc_symbol(token->pos, type);
681 bind_symbol(sym, token->ident, NS_STRUCT);
683 if (sym->type != type)
684 error_die(token->pos, "invalid tag applied to %s", show_typename (sym));
685 ctx->ctype.base_type = sym;
686 repos = &token->pos;
687 token = token->next;
688 if (match_op(token, '{')) {
689 // The following test is actually wrong for empty
690 // structs, but (1) they are not C99, (2) gcc does
691 // the same thing, and (3) it's easier.
692 if (sym->symbol_list)
693 error_die(token->pos, "redefinition of %s", show_typename (sym));
694 sym->pos = *repos;
695 token = parse(token->next, sym);
696 token = expect(token, '}', "at end of struct-union-enum-specifier");
698 // Mark the structure as needing re-examination
699 sym->examined = 0;
700 sym->endpos = token->pos;
702 return token;
705 // private struct/union/enum type
706 if (!match_op(token, '{')) {
707 sparse_error(token->pos, "expected declaration");
708 ctx->ctype.base_type = &bad_ctype;
709 return token;
712 sym = alloc_symbol(token->pos, type);
713 token = parse(token->next, sym);
714 ctx->ctype.base_type = sym;
715 token = expect(token, '}', "at end of specifier");
716 sym->endpos = token->pos;
718 return token;
721 static struct token *parse_struct_declaration(struct token *token, struct symbol *sym)
723 struct symbol *field, *last = NULL;
724 struct token *res;
725 res = struct_declaration_list(token, &sym->symbol_list);
726 FOR_EACH_PTR(sym->symbol_list, field) {
727 if (!field->ident) {
728 struct symbol *base = field->ctype.base_type;
729 if (base && base->type == SYM_BITFIELD)
730 continue;
732 if (last)
733 last->next_subobject = field;
734 last = field;
735 } END_FOR_EACH_PTR(field);
736 return res;
739 static struct token *parse_union_declaration(struct token *token, struct symbol *sym)
741 return struct_declaration_list(token, &sym->symbol_list);
744 static struct token *struct_specifier(struct token *token, struct decl_state *ctx)
746 return struct_union_enum_specifier(SYM_STRUCT, token, ctx, parse_struct_declaration);
749 static struct token *union_specifier(struct token *token, struct decl_state *ctx)
751 return struct_union_enum_specifier(SYM_UNION, token, ctx, parse_union_declaration);
755 typedef struct {
756 int x;
757 unsigned long long y;
758 } Num;
760 static void upper_boundary(Num *n, Num *v)
762 if (n->x > v->x)
763 return;
764 if (n->x < v->x) {
765 *n = *v;
766 return;
768 if (n->y < v->y)
769 n->y = v->y;
772 static void lower_boundary(Num *n, Num *v)
774 if (n->x < v->x)
775 return;
776 if (n->x > v->x) {
777 *n = *v;
778 return;
780 if (n->y > v->y)
781 n->y = v->y;
784 static int type_is_ok(struct symbol *type, Num *upper, Num *lower)
786 int shift = type->bit_size;
787 int is_unsigned = type->ctype.modifiers & MOD_UNSIGNED;
789 if (!is_unsigned)
790 shift--;
791 if (upper->x == 0 && upper->y >> shift)
792 return 0;
793 if (lower->x == 0 || (!is_unsigned && (~lower->y >> shift) == 0))
794 return 1;
795 return 0;
798 static struct symbol *bigger_enum_type(struct symbol *s1, struct symbol *s2)
800 if (s1->bit_size < s2->bit_size) {
801 s1 = s2;
802 } else if (s1->bit_size == s2->bit_size) {
803 if (s2->ctype.modifiers & MOD_UNSIGNED)
804 s1 = s2;
806 if (s1->bit_size < bits_in_int)
807 return &int_ctype;
808 return s1;
811 static void cast_enum_list(struct symbol_list *list, struct symbol *base_type)
813 struct symbol *sym;
815 FOR_EACH_PTR(list, sym) {
816 struct expression *expr = sym->initializer;
817 struct symbol *ctype;
818 if (expr->type != EXPR_VALUE)
819 continue;
820 ctype = expr->ctype;
821 if (ctype->bit_size == base_type->bit_size)
822 continue;
823 cast_value(expr, base_type, expr, ctype);
824 } END_FOR_EACH_PTR(sym);
827 static struct token *parse_enum_declaration(struct token *token, struct symbol *parent)
829 unsigned long long lastval = 0;
830 struct symbol *ctype = NULL, *base_type = NULL;
831 Num upper = {-1, 0}, lower = {1, 0};
833 parent->examined = 1;
834 parent->ctype.base_type = &int_ctype;
835 while (token_type(token) == TOKEN_IDENT) {
836 struct expression *expr = NULL;
837 struct token *next = token->next;
838 struct symbol *sym;
840 if (match_op(next, '=')) {
841 next = constant_expression(next->next, &expr);
842 lastval = get_expression_value(expr);
843 ctype = &void_ctype;
844 if (expr && expr->ctype)
845 ctype = expr->ctype;
846 } else if (!ctype) {
847 ctype = &int_ctype;
848 } else if (is_int_type(ctype)) {
849 lastval++;
850 } else {
851 error_die(token->pos, "can't increment the last enum member");
854 if (!expr) {
855 expr = alloc_expression(token->pos, EXPR_VALUE);
856 expr->value = lastval;
857 expr->ctype = ctype;
860 sym = alloc_symbol(token->pos, SYM_NODE);
861 bind_symbol(sym, token->ident, NS_SYMBOL);
862 sym->ctype.modifiers &= ~MOD_ADDRESSABLE;
863 sym->initializer = expr;
864 sym->enum_member = 1;
865 sym->ctype.base_type = parent;
866 add_ptr_list(&parent->symbol_list, sym);
868 if (base_type != &bad_ctype) {
869 if (ctype->type == SYM_NODE)
870 ctype = ctype->ctype.base_type;
871 if (ctype->type == SYM_ENUM) {
872 if (ctype == parent)
873 ctype = base_type;
874 else
875 ctype = ctype->ctype.base_type;
878 * base_type rules:
879 * - if all enums are of the same type, then
880 * the base_type is that type (two first
881 * cases)
882 * - if enums are of different types, they
883 * all have to be integer types, and the
884 * base type is at least "int_ctype".
885 * - otherwise the base_type is "bad_ctype".
887 if (!base_type) {
888 base_type = ctype;
889 } else if (ctype == base_type) {
890 /* nothing */
891 } else if (is_int_type(base_type) && is_int_type(ctype)) {
892 base_type = bigger_enum_type(base_type, ctype);
893 } else
894 base_type = &bad_ctype;
895 parent->ctype.base_type = base_type;
897 if (is_int_type(base_type)) {
898 Num v = {.y = lastval};
899 if (ctype->ctype.modifiers & MOD_UNSIGNED)
900 v.x = 0;
901 else if ((long long)lastval >= 0)
902 v.x = 0;
903 else
904 v.x = -1;
905 upper_boundary(&upper, &v);
906 lower_boundary(&lower, &v);
908 token = next;
910 sym->endpos = token->pos;
912 if (!match_op(token, ','))
913 break;
914 token = token->next;
916 if (!base_type) {
917 sparse_error(token->pos, "bad enum definition");
918 base_type = &bad_ctype;
920 else if (!is_int_type(base_type))
921 base_type = base_type;
922 else if (type_is_ok(base_type, &upper, &lower))
923 base_type = base_type;
924 else if (type_is_ok(&int_ctype, &upper, &lower))
925 base_type = &int_ctype;
926 else if (type_is_ok(&uint_ctype, &upper, &lower))
927 base_type = &uint_ctype;
928 else if (type_is_ok(&long_ctype, &upper, &lower))
929 base_type = &long_ctype;
930 else if (type_is_ok(&ulong_ctype, &upper, &lower))
931 base_type = &ulong_ctype;
932 else if (type_is_ok(&llong_ctype, &upper, &lower))
933 base_type = &llong_ctype;
934 else if (type_is_ok(&ullong_ctype, &upper, &lower))
935 base_type = &ullong_ctype;
936 else
937 base_type = &bad_ctype;
938 parent->ctype.base_type = base_type;
939 parent->ctype.modifiers |= (base_type->ctype.modifiers & MOD_UNSIGNED);
940 parent->examined = 0;
942 cast_enum_list(parent->symbol_list, base_type);
944 return token;
947 static struct token *enum_specifier(struct token *token, struct decl_state *ctx)
949 struct token *ret = struct_union_enum_specifier(SYM_ENUM, token, ctx, parse_enum_declaration);
950 struct ctype *ctype = &ctx->ctype.base_type->ctype;
952 if (!ctype->base_type)
953 ctype->base_type = &incomplete_ctype;
955 return ret;
958 static void apply_ctype(struct position pos, struct ctype *thistype, struct ctype *ctype);
960 static struct token *typeof_specifier(struct token *token, struct decl_state *ctx)
962 struct symbol *sym;
964 if (!match_op(token, '(')) {
965 sparse_error(token->pos, "expected '(' after typeof");
966 return token;
968 if (lookup_type(token->next)) {
969 token = typename(token->next, &sym, NULL);
970 ctx->ctype.base_type = sym->ctype.base_type;
971 apply_ctype(token->pos, &sym->ctype, &ctx->ctype);
972 } else {
973 struct symbol *typeof_sym = alloc_symbol(token->pos, SYM_TYPEOF);
974 token = parse_expression(token->next, &typeof_sym->initializer);
976 typeof_sym->endpos = token->pos;
977 if (!typeof_sym->initializer) {
978 sparse_error(token->pos, "expected expression after the '(' token");
979 typeof_sym = &bad_ctype;
981 ctx->ctype.base_type = typeof_sym;
983 return expect(token, ')', "after typeof");
986 static struct token *ignore_attribute(struct token *token, struct symbol *attr, struct decl_state *ctx)
988 struct expression *expr = NULL;
989 if (match_op(token, '('))
990 token = parens_expression(token, &expr, "in attribute");
991 return token;
994 static struct token *attribute_packed(struct token *token, struct symbol *attr, struct decl_state *ctx)
996 if (!ctx->ctype.alignment)
997 ctx->ctype.alignment = 1;
998 return token;
1001 static struct token *attribute_aligned(struct token *token, struct symbol *attr, struct decl_state *ctx)
1003 int alignment = max_alignment;
1004 struct expression *expr = NULL;
1006 if (match_op(token, '(')) {
1007 token = parens_expression(token, &expr, "in attribute");
1008 if (expr)
1009 alignment = const_expression_value(expr);
1011 if (alignment & (alignment-1)) {
1012 warning(token->pos, "I don't like non-power-of-2 alignments");
1013 return token;
1014 } else if (alignment > ctx->ctype.alignment)
1015 ctx->ctype.alignment = alignment;
1016 return token;
1019 static void apply_qualifier(struct position *pos, struct ctype *ctx, unsigned long qual)
1021 if (ctx->modifiers & qual)
1022 warning(*pos, "duplicate %s", modifier_string(qual));
1023 ctx->modifiers |= qual;
1026 static struct token *attribute_modifier(struct token *token, struct symbol *attr, struct decl_state *ctx)
1028 apply_qualifier(&token->pos, &ctx->ctype, attr->ctype.modifiers);
1029 return token;
1032 static struct token *attribute_bitwise(struct token *token, struct symbol *attr, struct decl_state *ctx)
1034 if (Wbitwise)
1035 attribute_modifier(token, attr, ctx);
1036 return token;
1039 static struct token *attribute_address_space(struct token *token, struct symbol *attr, struct decl_state *ctx)
1041 struct expression *expr = NULL;
1042 int as;
1043 token = expect(token, '(', "after address_space attribute");
1044 token = conditional_expression(token, &expr);
1045 if (expr) {
1046 as = const_expression_value(expr);
1047 if (Waddress_space && as)
1048 ctx->ctype.as = as;
1050 token = expect(token, ')', "after address_space attribute");
1051 return token;
1054 static struct symbol *to_QI_mode(struct symbol *ctype)
1056 if (ctype->ctype.base_type != &int_type)
1057 return NULL;
1058 if (ctype == &char_ctype)
1059 return ctype;
1060 return ctype->ctype.modifiers & MOD_UNSIGNED ? &uchar_ctype
1061 : &schar_ctype;
1064 static struct symbol *to_HI_mode(struct symbol *ctype)
1066 if (ctype->ctype.base_type != &int_type)
1067 return NULL;
1068 return ctype->ctype.modifiers & MOD_UNSIGNED ? &ushort_ctype
1069 : &sshort_ctype;
1072 static struct symbol *to_SI_mode(struct symbol *ctype)
1074 if (ctype->ctype.base_type != &int_type)
1075 return NULL;
1076 return ctype->ctype.modifiers & MOD_UNSIGNED ? &uint_ctype
1077 : &sint_ctype;
1080 static struct symbol *to_DI_mode(struct symbol *ctype)
1082 if (ctype->ctype.base_type != &int_type)
1083 return NULL;
1084 return ctype->ctype.modifiers & MOD_UNSIGNED ? &ullong_ctype
1085 : &sllong_ctype;
1088 static struct symbol *to_TI_mode(struct symbol *ctype)
1090 if (ctype->ctype.base_type != &int_type)
1091 return NULL;
1092 return ctype->ctype.modifiers & MOD_UNSIGNED ? &ulllong_ctype
1093 : &slllong_ctype;
1096 static struct symbol *to_word_mode(struct symbol *ctype)
1098 if (ctype->ctype.base_type != &int_type)
1099 return NULL;
1100 return ctype->ctype.modifiers & MOD_UNSIGNED ? &ulong_ctype
1101 : &slong_ctype;
1104 static struct token *attribute_mode(struct token *token, struct symbol *attr, struct decl_state *ctx)
1106 token = expect(token, '(', "after mode attribute");
1107 if (token_type(token) == TOKEN_IDENT) {
1108 struct symbol *mode = lookup_keyword(token->ident, NS_KEYWORD);
1109 if (mode && mode->op->type == KW_MODE)
1110 ctx->mode = mode->op;
1111 else
1112 sparse_error(token->pos, "unknown mode attribute %s\n", show_ident(token->ident));
1113 token = token->next;
1114 } else
1115 sparse_error(token->pos, "expect attribute mode symbol\n");
1116 token = expect(token, ')', "after mode attribute");
1117 return token;
1120 static struct token *attribute_context(struct token *token, struct symbol *attr, struct decl_state *ctx)
1122 struct context *context = alloc_context();
1123 struct expression *args[3];
1124 int argc = 0;
1126 token = expect(token, '(', "after context attribute");
1127 while (!match_op(token, ')')) {
1128 struct expression *expr = NULL;
1129 token = conditional_expression(token, &expr);
1130 if (!expr)
1131 break;
1132 if (argc < 3)
1133 args[argc++] = expr;
1134 if (!match_op(token, ','))
1135 break;
1136 token = token->next;
1139 switch(argc) {
1140 case 0:
1141 sparse_error(token->pos, "expected context input/output values");
1142 break;
1143 case 1:
1144 context->in = get_expression_value(args[0]);
1145 break;
1146 case 2:
1147 context->in = get_expression_value(args[0]);
1148 context->out = get_expression_value(args[1]);
1149 break;
1150 case 3:
1151 context->context = args[0];
1152 context->in = get_expression_value(args[1]);
1153 context->out = get_expression_value(args[2]);
1154 break;
1157 if (argc)
1158 add_ptr_list(&ctx->ctype.contexts, context);
1160 token = expect(token, ')', "after context attribute");
1161 return token;
1164 static struct token *attribute_designated_init(struct token *token, struct symbol *attr, struct decl_state *ctx)
1166 if (ctx->ctype.base_type && ctx->ctype.base_type->type == SYM_STRUCT)
1167 ctx->ctype.base_type->designated_init = 1;
1168 else
1169 warning(token->pos, "attribute designated_init applied to non-structure type");
1170 return token;
1173 static struct token *attribute_transparent_union(struct token *token, struct symbol *attr, struct decl_state *ctx)
1175 if (Wtransparent_union)
1176 warning(token->pos, "attribute __transparent_union__");
1178 if (ctx->ctype.base_type && ctx->ctype.base_type->type == SYM_UNION)
1179 ctx->ctype.base_type->transparent_union = 1;
1180 else
1181 warning(token->pos, "attribute __transparent_union__ applied to non-union type");
1182 return token;
1185 static struct token *recover_unknown_attribute(struct token *token)
1187 struct expression *expr = NULL;
1189 if (Wunknown_attribute)
1190 warning(token->pos, "attribute '%s': unknown attribute", show_ident(token->ident));
1191 token = token->next;
1192 if (match_op(token, '('))
1193 token = parens_expression(token, &expr, "in attribute");
1194 return token;
1197 static struct token *attribute_specifier(struct token *token, struct decl_state *ctx)
1199 token = expect(token, '(', "after attribute");
1200 token = expect(token, '(', "after attribute");
1202 for (;;) {
1203 struct ident *attribute_name;
1204 struct symbol *attr;
1206 if (eof_token(token))
1207 break;
1208 if (match_op(token, ';'))
1209 break;
1210 if (token_type(token) != TOKEN_IDENT)
1211 break;
1212 attribute_name = token->ident;
1213 attr = lookup_keyword(attribute_name, NS_KEYWORD);
1214 if (attr && attr->op->attribute)
1215 token = attr->op->attribute(token->next, attr, ctx);
1216 else
1217 token = recover_unknown_attribute(token);
1219 if (!match_op(token, ','))
1220 break;
1221 token = token->next;
1224 token = expect(token, ')', "after attribute");
1225 token = expect(token, ')', "after attribute");
1226 return token;
1229 static const char *storage_class[] =
1231 [STypedef] = "typedef",
1232 [SAuto] = "auto",
1233 [SExtern] = "extern",
1234 [SStatic] = "static",
1235 [SRegister] = "register",
1236 [SForced] = "[force]"
1239 static unsigned long storage_modifiers(struct decl_state *ctx)
1241 static unsigned long mod[SMax] =
1243 [SAuto] = MOD_AUTO,
1244 [SExtern] = MOD_EXTERN,
1245 [SStatic] = MOD_STATIC,
1246 [SRegister] = MOD_REGISTER
1248 return mod[ctx->storage_class] | (ctx->is_inline ? MOD_INLINE : 0)
1249 | (ctx->is_tls ? MOD_TLS : 0);
1252 static void set_storage_class(struct position *pos, struct decl_state *ctx, int class)
1254 /* __thread can be used alone, or with extern or static */
1255 if (ctx->is_tls && (class != SStatic && class != SExtern)) {
1256 sparse_error(*pos, "__thread can only be used alone, or with "
1257 "extern or static");
1258 return;
1261 if (!ctx->storage_class) {
1262 ctx->storage_class = class;
1263 return;
1265 if (ctx->storage_class == class)
1266 sparse_error(*pos, "duplicate %s", storage_class[class]);
1267 else
1268 sparse_error(*pos, "multiple storage classes");
1271 static struct token *typedef_specifier(struct token *next, struct decl_state *ctx)
1273 set_storage_class(&next->pos, ctx, STypedef);
1274 return next;
1277 static struct token *auto_specifier(struct token *next, struct decl_state *ctx)
1279 set_storage_class(&next->pos, ctx, SAuto);
1280 return next;
1283 static struct token *register_specifier(struct token *next, struct decl_state *ctx)
1285 set_storage_class(&next->pos, ctx, SRegister);
1286 return next;
1289 static struct token *static_specifier(struct token *next, struct decl_state *ctx)
1291 set_storage_class(&next->pos, ctx, SStatic);
1292 return next;
1295 static struct token *extern_specifier(struct token *next, struct decl_state *ctx)
1297 set_storage_class(&next->pos, ctx, SExtern);
1298 return next;
1301 static struct token *thread_specifier(struct token *next, struct decl_state *ctx)
1303 /* This GCC extension can be used alone, or with extern or static */
1304 if (!ctx->storage_class || ctx->storage_class == SStatic
1305 || ctx->storage_class == SExtern) {
1306 ctx->is_tls = 1;
1307 } else {
1308 sparse_error(next->pos, "__thread can only be used alone, or "
1309 "with extern or static");
1312 return next;
1315 static struct token *attribute_force(struct token *token, struct symbol *attr, struct decl_state *ctx)
1317 set_storage_class(&token->pos, ctx, SForced);
1318 return token;
1321 static struct token *inline_specifier(struct token *next, struct decl_state *ctx)
1323 ctx->is_inline = 1;
1324 return next;
1327 static struct token *noreturn_specifier(struct token *next, struct decl_state *ctx)
1329 apply_qualifier(&next->pos, &ctx->ctype, MOD_NORETURN);
1330 return next;
1333 static struct token *alignas_specifier(struct token *token, struct decl_state *ctx)
1335 int alignment = 0;
1337 if (!match_op(token, '(')) {
1338 sparse_error(token->pos, "expected '(' after _Alignas");
1339 return token;
1341 if (lookup_type(token->next)) {
1342 struct symbol *sym = NULL;
1343 token = typename(token->next, &sym, NULL);
1344 sym = examine_symbol_type(sym);
1345 alignment = sym->ctype.alignment;
1346 token = expect(token, ')', "after _Alignas(...");
1347 } else {
1348 struct expression *expr = NULL;
1349 token = parens_expression(token, &expr, "after _Alignas");
1350 if (!expr)
1351 return token;
1352 alignment = const_expression_value(expr);
1355 if (alignment < 0) {
1356 warning(token->pos, "non-positive alignment");
1357 return token;
1359 if (alignment & (alignment-1)) {
1360 warning(token->pos, "non-power-of-2 alignment");
1361 return token;
1363 if (alignment > ctx->ctype.alignment)
1364 ctx->ctype.alignment = alignment;
1365 return token;
1368 static struct token *const_qualifier(struct token *next, struct decl_state *ctx)
1370 apply_qualifier(&next->pos, &ctx->ctype, MOD_CONST);
1371 return next;
1374 static struct token *volatile_qualifier(struct token *next, struct decl_state *ctx)
1376 apply_qualifier(&next->pos, &ctx->ctype, MOD_VOLATILE);
1377 return next;
1380 static void apply_ctype(struct position pos, struct ctype *thistype, struct ctype *ctype)
1382 unsigned long mod = thistype->modifiers;
1384 if (mod)
1385 apply_qualifier(&pos, ctype, mod);
1387 /* Context */
1388 concat_ptr_list((struct ptr_list *)thistype->contexts,
1389 (struct ptr_list **)&ctype->contexts);
1391 /* Alignment */
1392 if (thistype->alignment > ctype->alignment)
1393 ctype->alignment = thistype->alignment;
1395 /* Address space */
1396 if (thistype->as)
1397 ctype->as = thistype->as;
1400 static void specifier_conflict(struct position pos, int what, struct ident *new)
1402 const char *old;
1403 if (what & (Set_S | Set_T))
1404 goto Catch_all;
1405 if (what & Set_Char)
1406 old = "char";
1407 else if (what & Set_Double)
1408 old = "double";
1409 else if (what & Set_Float)
1410 old = "float";
1411 else if (what & Set_Signed)
1412 old = "signed";
1413 else if (what & Set_Unsigned)
1414 old = "unsigned";
1415 else if (what & Set_Short)
1416 old = "short";
1417 else if (what & Set_Long)
1418 old = "long";
1419 else
1420 old = "long long";
1421 sparse_error(pos, "impossible combination of type specifiers: %s %s",
1422 old, show_ident(new));
1423 return;
1425 Catch_all:
1426 sparse_error(pos, "two or more data types in declaration specifiers");
1429 static struct symbol * const int_types[] =
1430 {&short_ctype, &int_ctype, &long_ctype, &llong_ctype, &lllong_ctype};
1431 static struct symbol * const signed_types[] =
1432 {&sshort_ctype, &sint_ctype, &slong_ctype, &sllong_ctype,
1433 &slllong_ctype};
1434 static struct symbol * const unsigned_types[] =
1435 {&ushort_ctype, &uint_ctype, &ulong_ctype, &ullong_ctype,
1436 &ulllong_ctype};
1437 static struct symbol * const real_types[] =
1438 {&float_ctype, &double_ctype, &ldouble_ctype};
1439 static struct symbol * const char_types[] =
1440 {&char_ctype, &schar_ctype, &uchar_ctype};
1441 static struct symbol * const * const types[] = {
1442 int_types + 1, signed_types + 1, unsigned_types + 1,
1443 real_types + 1, char_types, char_types + 1, char_types + 2
1446 struct symbol *ctype_integer(int size, int want_unsigned)
1448 return types[want_unsigned ? CUInt : CInt][size];
1451 static struct token *handle_qualifiers(struct token *t, struct decl_state *ctx)
1453 while (token_type(t) == TOKEN_IDENT) {
1454 struct symbol *s = lookup_symbol(t->ident, NS_TYPEDEF);
1455 if (!s)
1456 break;
1457 if (s->type != SYM_KEYWORD)
1458 break;
1459 if (!(s->op->type & (KW_ATTRIBUTE | KW_QUALIFIER)))
1460 break;
1461 t = t->next;
1462 if (s->op->declarator)
1463 t = s->op->declarator(t, ctx);
1465 return t;
1468 static struct token *declaration_specifiers(struct token *token, struct decl_state *ctx)
1470 int seen = 0;
1471 int class = CInt;
1472 int size = 0;
1474 while (token_type(token) == TOKEN_IDENT) {
1475 struct symbol *s = lookup_symbol(token->ident,
1476 NS_TYPEDEF | NS_SYMBOL);
1477 if (!s || !(s->namespace & NS_TYPEDEF))
1478 break;
1479 if (s->type != SYM_KEYWORD) {
1480 if (seen & Set_Any)
1481 break;
1482 seen |= Set_S | Set_T;
1483 ctx->ctype.base_type = s->ctype.base_type;
1484 apply_ctype(token->pos, &s->ctype, &ctx->ctype);
1485 token = token->next;
1486 continue;
1488 if (s->op->type & KW_SPECIFIER) {
1489 if (seen & s->op->test) {
1490 specifier_conflict(token->pos,
1491 seen & s->op->test,
1492 token->ident);
1493 break;
1495 seen |= s->op->set;
1496 class += s->op->class;
1497 if (s->op->set & Set_Int128)
1498 size = 2;
1499 if (s->op->type & KW_SHORT) {
1500 size = -1;
1501 } else if (s->op->type & KW_LONG && size++) {
1502 if (class == CReal) {
1503 specifier_conflict(token->pos,
1504 Set_Vlong,
1505 &double_ident);
1506 break;
1508 seen |= Set_Vlong;
1511 token = token->next;
1512 if (s->op->declarator)
1513 token = s->op->declarator(token, ctx);
1514 if (s->op->type & KW_EXACT) {
1515 ctx->ctype.base_type = s->ctype.base_type;
1516 ctx->ctype.modifiers |= s->ctype.modifiers;
1520 if (!(seen & Set_S)) { /* not set explicitly? */
1521 struct symbol *base = &incomplete_ctype;
1522 if (seen & Set_Any)
1523 base = types[class][size];
1524 ctx->ctype.base_type = base;
1527 if (ctx->ctype.modifiers & MOD_BITWISE) {
1528 struct symbol *type;
1529 ctx->ctype.modifiers &= ~MOD_BITWISE;
1530 if (!is_int_type(ctx->ctype.base_type)) {
1531 sparse_error(token->pos, "invalid modifier");
1532 return token;
1534 type = alloc_symbol(token->pos, SYM_BASETYPE);
1535 *type = *ctx->ctype.base_type;
1536 type->ctype.modifiers &= ~MOD_SPECIFIER;
1537 type->ctype.base_type = ctx->ctype.base_type;
1538 type->type = SYM_RESTRICT;
1539 ctx->ctype.base_type = type;
1540 create_fouled(type);
1542 return token;
1545 static struct token *abstract_array_static_declarator(struct token *token, int *has_static)
1547 while (token->ident == &static_ident) {
1548 if (*has_static)
1549 sparse_error(token->pos, "duplicate array static declarator");
1551 *has_static = 1;
1552 token = token->next;
1554 return token;
1558 static struct token *abstract_array_declarator(struct token *token, struct symbol *sym)
1560 struct expression *expr = NULL;
1561 int has_static = 0;
1563 token = abstract_array_static_declarator(token, &has_static);
1565 if (match_idents(token, &restrict_ident, &__restrict_ident, &__restrict___ident, NULL))
1566 token = abstract_array_static_declarator(token->next, &has_static);
1567 token = parse_expression(token, &expr);
1568 sym->array_size = expr;
1569 return token;
1572 static struct token *parameter_type_list(struct token *, struct symbol *);
1573 static struct token *identifier_list(struct token *, struct symbol *);
1574 static struct token *declarator(struct token *token, struct decl_state *ctx);
1576 static struct token *skip_attribute(struct token *token)
1578 token = token->next;
1579 if (match_op(token, '(')) {
1580 int depth = 1;
1581 token = token->next;
1582 while (depth && !eof_token(token)) {
1583 if (token_type(token) == TOKEN_SPECIAL) {
1584 if (token->special == '(')
1585 depth++;
1586 else if (token->special == ')')
1587 depth--;
1589 token = token->next;
1592 return token;
1595 static struct token *skip_attributes(struct token *token)
1597 struct symbol *keyword;
1598 for (;;) {
1599 if (token_type(token) != TOKEN_IDENT)
1600 break;
1601 keyword = lookup_keyword(token->ident, NS_KEYWORD | NS_TYPEDEF);
1602 if (!keyword || keyword->type != SYM_KEYWORD)
1603 break;
1604 if (!(keyword->op->type & KW_ATTRIBUTE))
1605 break;
1606 token = expect(token->next, '(', "after attribute");
1607 token = expect(token, '(', "after attribute");
1608 for (;;) {
1609 if (eof_token(token))
1610 break;
1611 if (match_op(token, ';'))
1612 break;
1613 if (token_type(token) != TOKEN_IDENT)
1614 break;
1615 token = skip_attribute(token);
1616 if (!match_op(token, ','))
1617 break;
1618 token = token->next;
1620 token = expect(token, ')', "after attribute");
1621 token = expect(token, ')', "after attribute");
1623 return token;
1626 static struct token *handle_attributes(struct token *token, struct decl_state *ctx, unsigned int keywords)
1628 struct symbol *keyword;
1629 for (;;) {
1630 if (token_type(token) != TOKEN_IDENT)
1631 break;
1632 keyword = lookup_keyword(token->ident, NS_KEYWORD | NS_TYPEDEF);
1633 if (!keyword || keyword->type != SYM_KEYWORD)
1634 break;
1635 if (!(keyword->op->type & keywords))
1636 break;
1637 token = keyword->op->declarator(token->next, ctx);
1638 keywords &= KW_ATTRIBUTE;
1640 return token;
1643 static int is_nested(struct token *token, struct token **p,
1644 int prefer_abstract)
1647 * This can be either a parameter list or a grouping.
1648 * For the direct (non-abstract) case, we know if must be
1649 * a parameter list if we already saw the identifier.
1650 * For the abstract case, we know if must be a parameter
1651 * list if it is empty or starts with a type.
1653 struct token *next = token->next;
1655 *p = next = skip_attributes(next);
1657 if (token_type(next) == TOKEN_IDENT) {
1658 if (lookup_type(next))
1659 return !prefer_abstract;
1660 return 1;
1663 if (match_op(next, ')') || match_op(next, SPECIAL_ELLIPSIS))
1664 return 0;
1666 return 1;
1669 enum kind {
1670 Empty, K_R, Proto, Bad_Func,
1673 static enum kind which_func(struct token *token,
1674 struct ident **n,
1675 int prefer_abstract)
1677 struct token *next = token->next;
1679 if (token_type(next) == TOKEN_IDENT) {
1680 if (lookup_type(next))
1681 return Proto;
1682 /* identifier list not in definition; complain */
1683 if (prefer_abstract)
1684 warning(token->pos,
1685 "identifier list not in definition");
1686 return K_R;
1689 if (token_type(next) != TOKEN_SPECIAL)
1690 return Bad_Func;
1692 if (next->special == ')') {
1693 /* don't complain about those */
1694 if (!n || match_op(next->next, ';'))
1695 return Empty;
1696 warning(next->pos,
1697 "non-ANSI function declaration of function '%s'",
1698 show_ident(*n));
1699 return Empty;
1702 if (next->special == SPECIAL_ELLIPSIS) {
1703 warning(next->pos,
1704 "variadic functions must have one named argument");
1705 return Proto;
1708 return Bad_Func;
1711 static struct token *direct_declarator(struct token *token, struct decl_state *ctx)
1713 struct ctype *ctype = &ctx->ctype;
1714 struct token *next;
1715 struct ident **p = ctx->ident;
1717 if (ctx->ident && token_type(token) == TOKEN_IDENT) {
1718 *ctx->ident = token->ident;
1719 token = token->next;
1720 } else if (match_op(token, '(') &&
1721 is_nested(token, &next, ctx->prefer_abstract)) {
1722 struct symbol *base_type = ctype->base_type;
1723 if (token->next != next)
1724 next = handle_attributes(token->next, ctx,
1725 KW_ATTRIBUTE);
1726 token = declarator(next, ctx);
1727 token = expect(token, ')', "in nested declarator");
1728 while (ctype->base_type != base_type)
1729 ctype = &ctype->base_type->ctype;
1730 p = NULL;
1733 if (match_op(token, '(')) {
1734 enum kind kind = which_func(token, p, ctx->prefer_abstract);
1735 struct symbol *fn;
1736 fn = alloc_indirect_symbol(token->pos, ctype, SYM_FN);
1737 token = token->next;
1738 if (kind == K_R)
1739 token = identifier_list(token, fn);
1740 else if (kind == Proto)
1741 token = parameter_type_list(token, fn);
1742 token = expect(token, ')', "in function declarator");
1743 fn->endpos = token->pos;
1744 return token;
1747 while (match_op(token, '[')) {
1748 struct symbol *array;
1749 array = alloc_indirect_symbol(token->pos, ctype, SYM_ARRAY);
1750 token = abstract_array_declarator(token->next, array);
1751 token = expect(token, ']', "in abstract_array_declarator");
1752 array->endpos = token->pos;
1753 ctype = &array->ctype;
1755 return token;
1758 static struct token *pointer(struct token *token, struct decl_state *ctx)
1760 while (match_op(token,'*')) {
1761 struct symbol *ptr = alloc_symbol(token->pos, SYM_PTR);
1762 ptr->ctype.modifiers = ctx->ctype.modifiers;
1763 ptr->ctype.base_type = ctx->ctype.base_type;
1764 ptr->ctype.as = ctx->ctype.as;
1765 ptr->ctype.contexts = ctx->ctype.contexts;
1766 ctx->ctype.modifiers = 0;
1767 ctx->ctype.base_type = ptr;
1768 ctx->ctype.as = 0;
1769 ctx->ctype.contexts = NULL;
1770 ctx->ctype.alignment = 0;
1772 token = handle_qualifiers(token->next, ctx);
1773 ctx->ctype.base_type->endpos = token->pos;
1775 return token;
1778 static struct token *declarator(struct token *token, struct decl_state *ctx)
1780 token = pointer(token, ctx);
1781 return direct_declarator(token, ctx);
1784 static struct token *handle_bitfield(struct token *token, struct decl_state *ctx)
1786 struct ctype *ctype = &ctx->ctype;
1787 struct expression *expr;
1788 struct symbol *bitfield;
1789 long long width;
1791 if (ctype->base_type != &int_type && !is_int_type(ctype->base_type)) {
1792 sparse_error(token->pos, "invalid bitfield specifier for type %s.",
1793 show_typename(ctype->base_type));
1794 // Parse this to recover gracefully.
1795 return conditional_expression(token->next, &expr);
1798 bitfield = alloc_indirect_symbol(token->pos, ctype, SYM_BITFIELD);
1799 token = conditional_expression(token->next, &expr);
1800 width = const_expression_value(expr);
1801 bitfield->bit_size = width;
1803 if (width < 0 || width > INT_MAX) {
1804 sparse_error(token->pos, "invalid bitfield width, %lld.", width);
1805 width = -1;
1806 } else if (*ctx->ident && width == 0) {
1807 sparse_error(token->pos, "invalid named zero-width bitfield `%s'",
1808 show_ident(*ctx->ident));
1809 width = -1;
1810 } else if (*ctx->ident) {
1811 struct symbol *base_type = bitfield->ctype.base_type;
1812 struct symbol *bitfield_type = base_type == &int_type ? bitfield : base_type;
1813 int is_signed = !(bitfield_type->ctype.modifiers & MOD_UNSIGNED);
1814 if (Wone_bit_signed_bitfield && width == 1 && is_signed) {
1815 // Valid values are either {-1;0} or {0}, depending on integer
1816 // representation. The latter makes for very efficient code...
1817 sparse_error(token->pos, "dubious one-bit signed bitfield");
1819 if (Wdefault_bitfield_sign &&
1820 bitfield_type->type != SYM_ENUM &&
1821 !(bitfield_type->ctype.modifiers & MOD_EXPLICITLY_SIGNED) &&
1822 is_signed) {
1823 // The sign of bitfields is unspecified by default.
1824 warning(token->pos, "dubious bitfield without explicit `signed' or `unsigned'");
1827 bitfield->bit_size = width;
1828 bitfield->endpos = token->pos;
1829 return token;
1832 static struct token *declaration_list(struct token *token, struct symbol_list **list)
1834 struct decl_state ctx = {.prefer_abstract = 0};
1835 struct ctype saved;
1836 unsigned long mod;
1838 token = declaration_specifiers(token, &ctx);
1839 mod = storage_modifiers(&ctx);
1840 saved = ctx.ctype;
1841 for (;;) {
1842 struct symbol *decl = alloc_symbol(token->pos, SYM_NODE);
1843 ctx.ident = &decl->ident;
1845 token = declarator(token, &ctx);
1846 if (match_op(token, ':'))
1847 token = handle_bitfield(token, &ctx);
1849 token = handle_attributes(token, &ctx, KW_ATTRIBUTE);
1850 apply_modifiers(token->pos, &ctx);
1852 decl->ctype = ctx.ctype;
1853 decl->ctype.modifiers |= mod;
1854 decl->endpos = token->pos;
1855 add_symbol(list, decl);
1856 if (!match_op(token, ','))
1857 break;
1858 token = token->next;
1859 ctx.ctype = saved;
1861 return token;
1864 static struct token *struct_declaration_list(struct token *token, struct symbol_list **list)
1866 while (!match_op(token, '}')) {
1867 if (match_ident(token, &_Static_assert_ident)) {
1868 token = parse_static_assert(token, NULL);
1869 continue;
1871 if (!match_op(token, ';'))
1872 token = declaration_list(token, list);
1873 if (!match_op(token, ';')) {
1874 sparse_error(token->pos, "expected ; at end of declaration");
1875 break;
1877 token = token->next;
1879 return token;
1882 static struct token *parameter_declaration(struct token *token, struct symbol *sym)
1884 struct decl_state ctx = {.prefer_abstract = 1};
1886 token = declaration_specifiers(token, &ctx);
1887 ctx.ident = &sym->ident;
1888 token = declarator(token, &ctx);
1889 token = handle_attributes(token, &ctx, KW_ATTRIBUTE);
1890 apply_modifiers(token->pos, &ctx);
1891 sym->ctype = ctx.ctype;
1892 sym->ctype.modifiers |= storage_modifiers(&ctx);
1893 sym->endpos = token->pos;
1894 sym->forced_arg = ctx.storage_class == SForced;
1895 return token;
1898 struct token *typename(struct token *token, struct symbol **p, int *forced)
1900 struct decl_state ctx = {.prefer_abstract = 1};
1901 int class;
1902 struct symbol *sym = alloc_symbol(token->pos, SYM_NODE);
1903 *p = sym;
1904 token = declaration_specifiers(token, &ctx);
1905 token = declarator(token, &ctx);
1906 apply_modifiers(token->pos, &ctx);
1907 sym->ctype = ctx.ctype;
1908 sym->endpos = token->pos;
1909 class = ctx.storage_class;
1910 if (forced) {
1911 *forced = 0;
1912 if (class == SForced) {
1913 *forced = 1;
1914 class = 0;
1917 if (class)
1918 warning(sym->pos, "storage class in typename (%s %s)",
1919 storage_class[class], show_typename(sym));
1920 return token;
1923 static struct token *expression_statement(struct token *token, struct expression **tree)
1925 token = parse_expression(token, tree);
1926 return expect(token, ';', "at end of statement");
1929 static struct token *parse_asm_operands(struct token *token, struct statement *stmt,
1930 struct expression_list **inout)
1932 struct expression *expr;
1934 /* Allow empty operands */
1935 if (match_op(token->next, ':') || match_op(token->next, ')'))
1936 return token->next;
1937 do {
1938 struct ident *ident = NULL;
1939 if (match_op(token->next, '[') &&
1940 token_type(token->next->next) == TOKEN_IDENT &&
1941 match_op(token->next->next->next, ']')) {
1942 ident = token->next->next->ident;
1943 token = token->next->next->next;
1945 add_expression(inout, (struct expression *)ident); /* UGGLEE!!! */
1946 token = primary_expression(token->next, &expr);
1947 add_expression(inout, expr);
1948 token = parens_expression(token, &expr, "in asm parameter");
1949 add_expression(inout, expr);
1950 } while (match_op(token, ','));
1951 return token;
1954 static struct token *parse_asm_clobbers(struct token *token, struct statement *stmt,
1955 struct expression_list **clobbers)
1957 struct expression *expr;
1959 do {
1960 token = primary_expression(token->next, &expr);
1961 if (expr)
1962 add_expression(clobbers, expr);
1963 } while (match_op(token, ','));
1964 return token;
1967 static struct token *parse_asm_labels(struct token *token, struct statement *stmt,
1968 struct symbol_list **labels)
1970 struct symbol *label;
1972 do {
1973 token = token->next; /* skip ':' and ',' */
1974 if (token_type(token) != TOKEN_IDENT)
1975 return token;
1976 label = label_symbol(token);
1977 add_symbol(labels, label);
1978 token = token->next;
1979 } while (match_op(token, ','));
1980 return token;
1983 static struct token *parse_asm_statement(struct token *token, struct statement *stmt)
1985 int is_goto = 0;
1987 token = token->next;
1988 stmt->type = STMT_ASM;
1989 if (match_idents(token, &__volatile___ident, &__volatile_ident, &volatile_ident, NULL)) {
1990 token = token->next;
1992 if (token_type(token) == TOKEN_IDENT && token->ident == &goto_ident) {
1993 is_goto = 1;
1994 token = token->next;
1996 token = expect(token, '(', "after asm");
1997 token = parse_expression(token, &stmt->asm_string);
1998 if (match_op(token, ':'))
1999 token = parse_asm_operands(token, stmt, &stmt->asm_outputs);
2000 if (match_op(token, ':'))
2001 token = parse_asm_operands(token, stmt, &stmt->asm_inputs);
2002 if (match_op(token, ':'))
2003 token = parse_asm_clobbers(token, stmt, &stmt->asm_clobbers);
2004 if (is_goto && match_op(token, ':'))
2005 token = parse_asm_labels(token, stmt, &stmt->asm_labels);
2006 token = expect(token, ')', "after asm");
2007 return expect(token, ';', "at end of asm-statement");
2010 static struct token *parse_asm_declarator(struct token *token, struct decl_state *ctx)
2012 struct expression *expr;
2013 token = expect(token, '(', "after asm");
2014 token = parse_expression(token->next, &expr);
2015 token = expect(token, ')', "after asm");
2016 return token;
2019 static struct token *parse_static_assert(struct token *token, struct symbol_list **unused)
2021 struct expression *cond = NULL, *message = NULL;
2023 token = expect(token->next, '(', "after _Static_assert");
2024 token = constant_expression(token, &cond);
2025 if (!cond)
2026 sparse_error(token->pos, "Expected constant expression");
2027 token = expect(token, ',', "after conditional expression in _Static_assert");
2028 token = parse_expression(token, &message);
2029 if (!message || message->type != EXPR_STRING) {
2030 struct position pos;
2032 pos = message ? message->pos : token->pos;
2033 sparse_error(pos, "bad or missing string literal");
2034 cond = NULL;
2036 token = expect(token, ')', "after diagnostic message in _Static_assert");
2038 token = expect(token, ';', "after _Static_assert()");
2040 if (cond && !const_expression_value(cond) && cond->type == EXPR_VALUE)
2041 sparse_error(cond->pos, "static assertion failed: %s",
2042 show_string(message->string));
2043 return token;
2046 /* Make a statement out of an expression */
2047 static struct statement *make_statement(struct expression *expr)
2049 struct statement *stmt;
2051 if (!expr)
2052 return NULL;
2053 stmt = alloc_statement(expr->pos, STMT_EXPRESSION);
2054 stmt->expression = expr;
2055 return stmt;
2059 * All iterators have two symbols associated with them:
2060 * the "continue" and "break" symbols, which are targets
2061 * for continue and break statements respectively.
2063 * They are in a special name-space, but they follow
2064 * all the normal visibility rules, so nested iterators
2065 * automatically work right.
2067 static void start_iterator(struct statement *stmt)
2069 struct symbol *cont, *brk;
2071 start_symbol_scope();
2072 cont = alloc_symbol(stmt->pos, SYM_NODE);
2073 bind_symbol(cont, &continue_ident, NS_ITERATOR);
2074 brk = alloc_symbol(stmt->pos, SYM_NODE);
2075 bind_symbol(brk, &break_ident, NS_ITERATOR);
2077 stmt->type = STMT_ITERATOR;
2078 stmt->iterator_break = brk;
2079 stmt->iterator_continue = cont;
2080 fn_local_symbol(brk);
2081 fn_local_symbol(cont);
2084 static void end_iterator(struct statement *stmt)
2086 end_symbol_scope();
2089 static struct statement *start_function(struct symbol *sym)
2091 struct symbol *ret;
2092 struct statement *stmt = alloc_statement(sym->pos, STMT_COMPOUND);
2094 start_function_scope();
2095 ret = alloc_symbol(sym->pos, SYM_NODE);
2096 ret->ctype = sym->ctype.base_type->ctype;
2097 ret->ctype.modifiers &= ~(MOD_STORAGE | MOD_CONST | MOD_VOLATILE | MOD_TLS | MOD_INLINE | MOD_ADDRESSABLE | MOD_NOCAST | MOD_NODEREF | MOD_ACCESSED | MOD_TOPLEVEL);
2098 ret->ctype.modifiers |= (MOD_AUTO | MOD_REGISTER);
2099 bind_symbol(ret, &return_ident, NS_ITERATOR);
2100 stmt->ret = ret;
2101 fn_local_symbol(ret);
2103 // Currently parsed symbol for __func__/__FUNCTION__/__PRETTY_FUNCTION__
2104 current_fn = sym;
2106 return stmt;
2109 static void end_function(struct symbol *sym)
2111 current_fn = NULL;
2112 end_function_scope();
2116 * A "switch()" statement, like an iterator, has a
2117 * the "break" symbol associated with it. It works
2118 * exactly like the iterator break - it's the target
2119 * for any break-statements in scope, and means that
2120 * "break" handling doesn't even need to know whether
2121 * it's breaking out of an iterator or a switch.
2123 * In addition, the "case" symbol is a marker for the
2124 * case/default statements to find the switch statement
2125 * that they are associated with.
2127 static void start_switch(struct statement *stmt)
2129 struct symbol *brk, *switch_case;
2131 start_symbol_scope();
2132 brk = alloc_symbol(stmt->pos, SYM_NODE);
2133 bind_symbol(brk, &break_ident, NS_ITERATOR);
2135 switch_case = alloc_symbol(stmt->pos, SYM_NODE);
2136 bind_symbol(switch_case, &case_ident, NS_ITERATOR);
2137 switch_case->stmt = stmt;
2139 stmt->type = STMT_SWITCH;
2140 stmt->switch_break = brk;
2141 stmt->switch_case = switch_case;
2143 fn_local_symbol(brk);
2144 fn_local_symbol(switch_case);
2147 static void end_switch(struct statement *stmt)
2149 if (!stmt->switch_case->symbol_list)
2150 warning(stmt->pos, "switch with no cases");
2151 end_symbol_scope();
2154 static void add_case_statement(struct statement *stmt)
2156 struct symbol *target = lookup_symbol(&case_ident, NS_ITERATOR);
2157 struct symbol *sym;
2159 if (!target) {
2160 sparse_error(stmt->pos, "not in switch scope");
2161 stmt->type = STMT_NONE;
2162 return;
2164 sym = alloc_symbol(stmt->pos, SYM_NODE);
2165 add_symbol(&target->symbol_list, sym);
2166 sym->stmt = stmt;
2167 stmt->case_label = sym;
2168 fn_local_symbol(sym);
2171 static struct token *parse_return_statement(struct token *token, struct statement *stmt)
2173 struct symbol *target = lookup_symbol(&return_ident, NS_ITERATOR);
2175 if (!target)
2176 error_die(token->pos, "internal error: return without a function target");
2177 stmt->type = STMT_RETURN;
2178 stmt->ret_target = target;
2179 return expression_statement(token->next, &stmt->ret_value);
2182 static void validate_for_loop_decl(struct symbol *sym)
2184 unsigned long storage = sym->ctype.modifiers & MOD_STORAGE;
2186 if (storage & ~(MOD_AUTO | MOD_REGISTER)) {
2187 const char *name = show_ident(sym->ident);
2188 sparse_error(sym->pos, "non-local var '%s' in for-loop initializer", name);
2189 sym->ctype.modifiers &= ~MOD_STORAGE;
2193 static struct token *parse_for_statement(struct token *token, struct statement *stmt)
2195 struct symbol_list *syms;
2196 struct expression *e1, *e2, *e3;
2197 struct statement *iterator;
2199 start_iterator(stmt);
2200 token = expect(token->next, '(', "after 'for'");
2202 syms = NULL;
2203 e1 = NULL;
2204 /* C99 variable declaration? */
2205 if (lookup_type(token)) {
2206 token = external_declaration(token, &syms, validate_for_loop_decl);
2207 } else {
2208 token = parse_expression(token, &e1);
2209 token = expect(token, ';', "in 'for'");
2211 token = parse_expression(token, &e2);
2212 token = expect(token, ';', "in 'for'");
2213 token = parse_expression(token, &e3);
2214 token = expect(token, ')', "in 'for'");
2215 token = statement(token, &iterator);
2217 stmt->iterator_syms = syms;
2218 stmt->iterator_pre_statement = make_statement(e1);
2219 stmt->iterator_pre_condition = e2;
2220 stmt->iterator_post_statement = make_statement(e3);
2221 stmt->iterator_post_condition = NULL;
2222 stmt->iterator_statement = iterator;
2223 end_iterator(stmt);
2225 return token;
2228 static struct token *parse_while_statement(struct token *token, struct statement *stmt)
2230 struct expression *expr;
2231 struct statement *iterator;
2233 start_iterator(stmt);
2234 token = parens_expression(token->next, &expr, "after 'while'");
2235 token = statement(token, &iterator);
2237 stmt->iterator_pre_condition = expr;
2238 stmt->iterator_post_condition = NULL;
2239 stmt->iterator_statement = iterator;
2240 end_iterator(stmt);
2242 return token;
2245 static struct token *parse_do_statement(struct token *token, struct statement *stmt)
2247 struct expression *expr;
2248 struct statement *iterator;
2250 start_iterator(stmt);
2251 token = statement(token->next, &iterator);
2252 if (token_type(token) == TOKEN_IDENT && token->ident == &while_ident)
2253 token = token->next;
2254 else
2255 sparse_error(token->pos, "expected 'while' after 'do'");
2256 token = parens_expression(token, &expr, "after 'do-while'");
2258 stmt->iterator_post_condition = expr;
2259 stmt->iterator_statement = iterator;
2260 end_iterator(stmt);
2262 if (iterator && iterator->type != STMT_COMPOUND && Wdo_while)
2263 warning(iterator->pos, "do-while statement is not a compound statement");
2265 return expect(token, ';', "after statement");
2268 static struct token *parse_if_statement(struct token *token, struct statement *stmt)
2270 stmt->type = STMT_IF;
2271 token = parens_expression(token->next, &stmt->if_conditional, "after if");
2272 token = statement(token, &stmt->if_true);
2273 if (token_type(token) != TOKEN_IDENT)
2274 return token;
2275 if (token->ident != &else_ident)
2276 return token;
2277 return statement(token->next, &stmt->if_false);
2280 static inline struct token *case_statement(struct token *token, struct statement *stmt)
2282 stmt->type = STMT_CASE;
2283 token = expect(token, ':', "after default/case");
2284 add_case_statement(stmt);
2285 return statement(token, &stmt->case_statement);
2288 static struct token *parse_case_statement(struct token *token, struct statement *stmt)
2290 token = parse_expression(token->next, &stmt->case_expression);
2291 if (match_op(token, SPECIAL_ELLIPSIS))
2292 token = parse_expression(token->next, &stmt->case_to);
2293 return case_statement(token, stmt);
2296 static struct token *parse_default_statement(struct token *token, struct statement *stmt)
2298 return case_statement(token->next, stmt);
2301 static struct token *parse_loop_iterator(struct token *token, struct statement *stmt)
2303 struct symbol *target = lookup_symbol(token->ident, NS_ITERATOR);
2304 stmt->type = STMT_GOTO;
2305 stmt->goto_label = target;
2306 if (!target)
2307 sparse_error(stmt->pos, "break/continue not in iterator scope");
2308 return expect(token->next, ';', "at end of statement");
2311 static struct token *parse_switch_statement(struct token *token, struct statement *stmt)
2313 stmt->type = STMT_SWITCH;
2314 start_switch(stmt);
2315 token = parens_expression(token->next, &stmt->switch_expression, "after 'switch'");
2316 token = statement(token, &stmt->switch_statement);
2317 end_switch(stmt);
2318 return token;
2321 static struct token *parse_goto_statement(struct token *token, struct statement *stmt)
2323 stmt->type = STMT_GOTO;
2324 token = token->next;
2325 if (match_op(token, '*')) {
2326 token = parse_expression(token->next, &stmt->goto_expression);
2327 add_statement(&function_computed_goto_list, stmt);
2328 } else if (token_type(token) == TOKEN_IDENT) {
2329 stmt->goto_label = label_symbol(token);
2330 token = token->next;
2331 } else {
2332 sparse_error(token->pos, "Expected identifier or goto expression");
2334 return expect(token, ';', "at end of statement");
2337 static struct token *parse_context_statement(struct token *token, struct statement *stmt)
2339 stmt->type = STMT_CONTEXT;
2340 token = parse_expression(token->next, &stmt->expression);
2341 if (stmt->expression->type == EXPR_PREOP
2342 && stmt->expression->op == '('
2343 && stmt->expression->unop->type == EXPR_COMMA) {
2344 struct expression *expr;
2345 expr = stmt->expression->unop;
2346 stmt->context = expr->left;
2347 stmt->expression = expr->right;
2349 return expect(token, ';', "at end of statement");
2352 static struct token *parse_range_statement(struct token *token, struct statement *stmt)
2354 stmt->type = STMT_RANGE;
2355 token = assignment_expression(token->next, &stmt->range_expression);
2356 token = expect(token, ',', "after range expression");
2357 token = assignment_expression(token, &stmt->range_low);
2358 token = expect(token, ',', "after low range");
2359 token = assignment_expression(token, &stmt->range_high);
2360 return expect(token, ';', "after range statement");
2363 static struct token *statement(struct token *token, struct statement **tree)
2365 struct statement *stmt = alloc_statement(token->pos, STMT_NONE);
2367 *tree = stmt;
2368 if (token_type(token) == TOKEN_IDENT) {
2369 struct symbol *s = lookup_keyword(token->ident, NS_KEYWORD);
2370 if (s && s->op->statement)
2371 return s->op->statement(token, stmt);
2373 if (match_op(token->next, ':')) {
2374 struct symbol *s = label_symbol(token);
2375 stmt->type = STMT_LABEL;
2376 stmt->label_identifier = s;
2377 if (s->stmt)
2378 sparse_error(stmt->pos, "label '%s' redefined", show_ident(token->ident));
2379 s->stmt = stmt;
2380 token = skip_attributes(token->next->next);
2381 return statement(token, &stmt->label_statement);
2385 if (match_op(token, '{')) {
2386 stmt->type = STMT_COMPOUND;
2387 start_symbol_scope();
2388 token = compound_statement(token->next, stmt);
2389 end_symbol_scope();
2391 return expect(token, '}', "at end of compound statement");
2394 stmt->type = STMT_EXPRESSION;
2395 return expression_statement(token, &stmt->expression);
2398 /* gcc extension - __label__ ident-list; in the beginning of compound stmt */
2399 static struct token *label_statement(struct token *token)
2401 while (token_type(token) == TOKEN_IDENT) {
2402 struct symbol *sym = alloc_symbol(token->pos, SYM_LABEL);
2403 /* it's block-scope, but we want label namespace */
2404 bind_symbol(sym, token->ident, NS_SYMBOL);
2405 sym->namespace = NS_LABEL;
2406 fn_local_symbol(sym);
2407 token = token->next;
2408 if (!match_op(token, ','))
2409 break;
2410 token = token->next;
2412 return expect(token, ';', "at end of label declaration");
2415 static struct token * statement_list(struct token *token, struct statement_list **list)
2417 int seen_statement = 0;
2418 while (token_type(token) == TOKEN_IDENT &&
2419 token->ident == &__label___ident)
2420 token = label_statement(token->next);
2421 for (;;) {
2422 struct statement * stmt;
2423 if (eof_token(token))
2424 break;
2425 if (match_op(token, '}'))
2426 break;
2427 if (match_ident(token, &_Static_assert_ident)) {
2428 token = parse_static_assert(token, NULL);
2429 continue;
2431 if (lookup_type(token)) {
2432 if (seen_statement) {
2433 warning(token->pos, "mixing declarations and code");
2434 seen_statement = 0;
2436 stmt = alloc_statement(token->pos, STMT_DECLARATION);
2437 token = external_declaration(token, &stmt->declaration, NULL);
2438 } else {
2439 seen_statement = Wdeclarationafterstatement;
2440 token = statement(token, &stmt);
2442 add_statement(list, stmt);
2444 return token;
2447 static struct token *identifier_list(struct token *token, struct symbol *fn)
2449 struct symbol_list **list = &fn->arguments;
2450 for (;;) {
2451 struct symbol *sym = alloc_symbol(token->pos, SYM_NODE);
2452 sym->ident = token->ident;
2453 token = token->next;
2454 sym->endpos = token->pos;
2455 sym->ctype.base_type = &incomplete_ctype;
2456 add_symbol(list, sym);
2457 if (!match_op(token, ',') ||
2458 token_type(token->next) != TOKEN_IDENT ||
2459 lookup_type(token->next))
2460 break;
2461 token = token->next;
2463 return token;
2466 static struct token *parameter_type_list(struct token *token, struct symbol *fn)
2468 struct symbol_list **list = &fn->arguments;
2470 for (;;) {
2471 struct symbol *sym;
2473 if (match_op(token, SPECIAL_ELLIPSIS)) {
2474 fn->variadic = 1;
2475 token = token->next;
2476 break;
2479 sym = alloc_symbol(token->pos, SYM_NODE);
2480 token = parameter_declaration(token, sym);
2481 if (sym->ctype.base_type == &void_ctype) {
2482 /* Special case: (void) */
2483 if (!*list && !sym->ident)
2484 break;
2485 warning(token->pos, "void parameter");
2487 add_symbol(list, sym);
2488 if (!match_op(token, ','))
2489 break;
2490 token = token->next;
2492 return token;
2495 struct token *compound_statement(struct token *token, struct statement *stmt)
2497 token = statement_list(token, &stmt->stmts);
2498 return token;
2501 static struct expression *identifier_expression(struct token *token)
2503 struct expression *expr = alloc_expression(token->pos, EXPR_IDENTIFIER);
2504 expr->expr_ident = token->ident;
2505 return expr;
2508 static struct expression *index_expression(struct expression *from, struct expression *to)
2510 int idx_from, idx_to;
2511 struct expression *expr = alloc_expression(from->pos, EXPR_INDEX);
2513 idx_from = const_expression_value(from);
2514 idx_to = idx_from;
2515 if (to) {
2516 idx_to = const_expression_value(to);
2517 if (idx_to < idx_from || idx_from < 0)
2518 warning(from->pos, "nonsense array initializer index range");
2520 expr->idx_from = idx_from;
2521 expr->idx_to = idx_to;
2522 return expr;
2525 static struct token *single_initializer(struct expression **ep, struct token *token)
2527 int expect_equal = 0;
2528 struct token *next = token->next;
2529 struct expression **tail = ep;
2530 int nested;
2532 *ep = NULL;
2534 if ((token_type(token) == TOKEN_IDENT) && match_op(next, ':')) {
2535 struct expression *expr = identifier_expression(token);
2536 if (Wold_initializer)
2537 warning(token->pos, "obsolete struct initializer, use C99 syntax");
2538 token = initializer(&expr->ident_expression, next->next);
2539 if (expr->ident_expression)
2540 *ep = expr;
2541 return token;
2544 for (tail = ep, nested = 0; ; nested++, next = token->next) {
2545 if (match_op(token, '.') && (token_type(next) == TOKEN_IDENT)) {
2546 struct expression *expr = identifier_expression(next);
2547 *tail = expr;
2548 tail = &expr->ident_expression;
2549 expect_equal = 1;
2550 token = next->next;
2551 } else if (match_op(token, '[')) {
2552 struct expression *from = NULL, *to = NULL, *expr;
2553 token = constant_expression(token->next, &from);
2554 if (!from) {
2555 sparse_error(token->pos, "Expected constant expression");
2556 break;
2558 if (match_op(token, SPECIAL_ELLIPSIS))
2559 token = constant_expression(token->next, &to);
2560 expr = index_expression(from, to);
2561 *tail = expr;
2562 tail = &expr->idx_expression;
2563 token = expect(token, ']', "at end of initializer index");
2564 if (nested)
2565 expect_equal = 1;
2566 } else {
2567 break;
2570 if (nested && !expect_equal) {
2571 if (!match_op(token, '='))
2572 warning(token->pos, "obsolete array initializer, use C99 syntax");
2573 else
2574 expect_equal = 1;
2576 if (expect_equal)
2577 token = expect(token, '=', "at end of initializer index");
2579 token = initializer(tail, token);
2580 if (!*tail)
2581 *ep = NULL;
2582 return token;
2585 static struct token *initializer_list(struct expression_list **list, struct token *token)
2587 struct expression *expr;
2589 for (;;) {
2590 token = single_initializer(&expr, token);
2591 if (!expr)
2592 break;
2593 add_expression(list, expr);
2594 if (!match_op(token, ','))
2595 break;
2596 token = token->next;
2598 return token;
2601 struct token *initializer(struct expression **tree, struct token *token)
2603 if (match_op(token, '{')) {
2604 struct expression *expr = alloc_expression(token->pos, EXPR_INITIALIZER);
2605 *tree = expr;
2606 token = initializer_list(&expr->expr_list, token->next);
2607 return expect(token, '}', "at end of initializer");
2609 return assignment_expression(token, tree);
2612 static void declare_argument(struct symbol *sym, struct symbol *fn)
2614 if (!sym->ident) {
2615 sparse_error(sym->pos, "no identifier for function argument");
2616 return;
2618 bind_symbol(sym, sym->ident, NS_SYMBOL);
2621 static struct token *parse_function_body(struct token *token, struct symbol *decl,
2622 struct symbol_list **list)
2624 struct symbol_list **old_symbol_list;
2625 struct symbol *base_type = decl->ctype.base_type;
2626 struct statement *stmt, **p;
2627 struct symbol *prev;
2628 struct symbol *arg;
2630 old_symbol_list = function_symbol_list;
2631 if (decl->ctype.modifiers & MOD_INLINE) {
2632 function_symbol_list = &decl->inline_symbol_list;
2633 p = &base_type->inline_stmt;
2634 } else {
2635 function_symbol_list = &decl->symbol_list;
2636 p = &base_type->stmt;
2638 function_computed_target_list = NULL;
2639 function_computed_goto_list = NULL;
2641 if (decl->ctype.modifiers & MOD_EXTERN) {
2642 if (!(decl->ctype.modifiers & MOD_INLINE))
2643 warning(decl->pos, "function '%s' with external linkage has definition", show_ident(decl->ident));
2645 if (!(decl->ctype.modifiers & MOD_STATIC))
2646 decl->ctype.modifiers |= MOD_EXTERN;
2648 stmt = start_function(decl);
2650 *p = stmt;
2651 FOR_EACH_PTR (base_type->arguments, arg) {
2652 declare_argument(arg, base_type);
2653 } END_FOR_EACH_PTR(arg);
2655 token = compound_statement(token->next, stmt);
2657 end_function(decl);
2658 if (!(decl->ctype.modifiers & MOD_INLINE))
2659 add_symbol(list, decl);
2660 check_declaration(decl);
2661 decl->definition = decl;
2662 prev = decl->same_symbol;
2663 if (prev && prev->definition) {
2664 warning(decl->pos, "multiple definitions for function '%s'",
2665 show_ident(decl->ident));
2666 info(prev->definition->pos, " the previous one is here");
2667 } else {
2668 while (prev) {
2669 rebind_scope(prev, decl->scope);
2670 prev->definition = decl;
2671 prev = prev->same_symbol;
2674 function_symbol_list = old_symbol_list;
2675 if (function_computed_goto_list) {
2676 if (!function_computed_target_list)
2677 warning(decl->pos, "function '%s' has computed goto but no targets?", show_ident(decl->ident));
2678 else {
2679 FOR_EACH_PTR(function_computed_goto_list, stmt) {
2680 stmt->target_list = function_computed_target_list;
2681 } END_FOR_EACH_PTR(stmt);
2684 return expect(token, '}', "at end of function");
2687 static void promote_k_r_types(struct symbol *arg)
2689 struct symbol *base = arg->ctype.base_type;
2690 if (base && base->ctype.base_type == &int_type && (base->ctype.modifiers & (MOD_CHAR | MOD_SHORT))) {
2691 arg->ctype.base_type = &int_ctype;
2695 static void apply_k_r_types(struct symbol_list *argtypes, struct symbol *fn)
2697 struct symbol_list *real_args = fn->ctype.base_type->arguments;
2698 struct symbol *arg;
2700 FOR_EACH_PTR(real_args, arg) {
2701 struct symbol *type;
2703 /* This is quadratic in the number of arguments. We _really_ don't care */
2704 FOR_EACH_PTR(argtypes, type) {
2705 if (type->ident == arg->ident)
2706 goto match;
2707 } END_FOR_EACH_PTR(type);
2708 sparse_error(arg->pos, "missing type declaration for parameter '%s'", show_ident(arg->ident));
2709 continue;
2710 match:
2711 type->used = 1;
2712 /* "char" and "short" promote to "int" */
2713 promote_k_r_types(type);
2715 arg->ctype = type->ctype;
2716 } END_FOR_EACH_PTR(arg);
2718 FOR_EACH_PTR(argtypes, arg) {
2719 if (!arg->used)
2720 warning(arg->pos, "nonsensical parameter declaration '%s'", show_ident(arg->ident));
2721 } END_FOR_EACH_PTR(arg);
2725 static struct token *parse_k_r_arguments(struct token *token, struct symbol *decl,
2726 struct symbol_list **list)
2728 struct symbol_list *args = NULL;
2730 warning(token->pos, "non-ANSI definition of function '%s'", show_ident(decl->ident));
2731 do {
2732 token = declaration_list(token, &args);
2733 if (!match_op(token, ';')) {
2734 sparse_error(token->pos, "expected ';' at end of parameter declaration");
2735 break;
2737 token = token->next;
2738 } while (lookup_type(token));
2740 apply_k_r_types(args, decl);
2742 if (!match_op(token, '{')) {
2743 sparse_error(token->pos, "expected function body");
2744 return token;
2746 return parse_function_body(token, decl, list);
2749 static struct token *toplevel_asm_declaration(struct token *token, struct symbol_list **list)
2751 struct symbol *anon = alloc_symbol(token->pos, SYM_NODE);
2752 struct symbol *fn = alloc_symbol(token->pos, SYM_FN);
2753 struct statement *stmt;
2755 anon->ctype.base_type = fn;
2756 stmt = alloc_statement(token->pos, STMT_NONE);
2757 fn->stmt = stmt;
2759 token = parse_asm_statement(token, stmt);
2761 add_symbol(list, anon);
2762 return token;
2765 struct token *external_declaration(struct token *token, struct symbol_list **list,
2766 validate_decl_t validate_decl)
2768 struct ident *ident = NULL;
2769 struct symbol *decl;
2770 struct decl_state ctx = { .ident = &ident };
2771 struct ctype saved;
2772 struct symbol *base_type;
2773 unsigned long mod;
2774 int is_typedef;
2776 /* Top-level inline asm or static assertion? */
2777 if (token_type(token) == TOKEN_IDENT) {
2778 struct symbol *s = lookup_keyword(token->ident, NS_KEYWORD);
2779 if (s && s->op->toplevel)
2780 return s->op->toplevel(token, list);
2783 /* Parse declaration-specifiers, if any */
2784 token = declaration_specifiers(token, &ctx);
2785 mod = storage_modifiers(&ctx);
2786 decl = alloc_symbol(token->pos, SYM_NODE);
2787 /* Just a type declaration? */
2788 if (match_op(token, ';')) {
2789 apply_modifiers(token->pos, &ctx);
2790 return token->next;
2793 saved = ctx.ctype;
2794 token = declarator(token, &ctx);
2795 token = handle_attributes(token, &ctx, KW_ATTRIBUTE | KW_ASM);
2796 apply_modifiers(token->pos, &ctx);
2798 decl->ctype = ctx.ctype;
2799 decl->ctype.modifiers |= mod;
2800 decl->endpos = token->pos;
2802 /* Just a type declaration? */
2803 if (!ident) {
2804 warning(token->pos, "missing identifier in declaration");
2805 return expect(token, ';', "at the end of type declaration");
2808 /* type define declaration? */
2809 is_typedef = ctx.storage_class == STypedef;
2811 /* Typedefs don't have meaningful storage */
2812 if (is_typedef)
2813 decl->ctype.modifiers |= MOD_USERTYPE;
2815 bind_symbol(decl, ident, is_typedef ? NS_TYPEDEF: NS_SYMBOL);
2817 base_type = decl->ctype.base_type;
2819 if (is_typedef) {
2820 if (base_type && !base_type->ident) {
2821 switch (base_type->type) {
2822 case SYM_STRUCT:
2823 case SYM_UNION:
2824 case SYM_ENUM:
2825 case SYM_RESTRICT:
2826 base_type->ident = ident;
2827 break;
2828 default:
2829 break;
2832 } else if (base_type && base_type->type == SYM_FN) {
2833 if (base_type->ctype.base_type == &incomplete_ctype) {
2834 warning(decl->pos, "'%s()' has implicit return type",
2835 show_ident(decl->ident));
2836 base_type->ctype.base_type = &int_ctype;
2838 /* K&R argument declaration? */
2839 if (lookup_type(token))
2840 return parse_k_r_arguments(token, decl, list);
2841 if (match_op(token, '{'))
2842 return parse_function_body(token, decl, list);
2844 if (!(decl->ctype.modifiers & MOD_STATIC))
2845 decl->ctype.modifiers |= MOD_EXTERN;
2846 } else if (base_type == &void_ctype && !(decl->ctype.modifiers & MOD_EXTERN)) {
2847 sparse_error(token->pos, "void declaration");
2849 if (base_type == &incomplete_ctype) {
2850 warning(decl->pos, "'%s' has implicit type", show_ident(decl->ident));
2851 decl->ctype.base_type = &int_ctype;;
2854 for (;;) {
2855 if (!is_typedef && match_op(token, '=')) {
2856 token = initializer(&decl->initializer, token->next);
2858 if (!is_typedef) {
2859 if (validate_decl)
2860 validate_decl(decl);
2862 if (decl->initializer && decl->ctype.modifiers & MOD_EXTERN) {
2863 warning(decl->pos, "symbol with external linkage has initializer");
2864 decl->ctype.modifiers &= ~MOD_EXTERN;
2867 if (!(decl->ctype.modifiers & (MOD_EXTERN | MOD_INLINE))) {
2868 add_symbol(list, decl);
2869 fn_local_symbol(decl);
2872 check_declaration(decl);
2873 if (decl->same_symbol) {
2874 decl->definition = decl->same_symbol->definition;
2875 decl->op = decl->same_symbol->op;
2878 if (!match_op(token, ','))
2879 break;
2881 token = token->next;
2882 ident = NULL;
2883 decl = alloc_symbol(token->pos, SYM_NODE);
2884 ctx.ctype = saved;
2885 token = handle_attributes(token, &ctx, KW_ATTRIBUTE);
2886 token = declarator(token, &ctx);
2887 token = handle_attributes(token, &ctx, KW_ATTRIBUTE | KW_ASM);
2888 apply_modifiers(token->pos, &ctx);
2889 decl->ctype = ctx.ctype;
2890 decl->ctype.modifiers |= mod;
2891 decl->endpos = token->pos;
2892 if (!ident) {
2893 sparse_error(token->pos, "expected identifier name in type definition");
2894 return token;
2897 if (is_typedef)
2898 decl->ctype.modifiers |= MOD_USERTYPE;
2900 bind_symbol(decl, ident, is_typedef ? NS_TYPEDEF: NS_SYMBOL);
2902 /* Function declarations are automatically extern unless specifically static */
2903 base_type = decl->ctype.base_type;
2904 if (!is_typedef && base_type && base_type->type == SYM_FN) {
2905 if (!(decl->ctype.modifiers & MOD_STATIC))
2906 decl->ctype.modifiers |= MOD_EXTERN;
2909 return expect(token, ';', "at end of declaration");