units: anything can be saved to a register
[smatch.git] / parse.c
blob2ddc29acbd3399ebc1df4a96b25bca42ae066292
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);
54 typedef struct token *declarator_t(struct token *, struct symbol *, struct decl_state *);
55 static declarator_t
56 struct_specifier, union_specifier, enum_specifier,
57 attribute_specifier, typeof_specifier,
58 storage_specifier, thread_specifier;
59 static declarator_t generic_qualifier;
60 static declarator_t autotype_specifier;
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);
77 static struct token *ignore_seg_gs(struct token *token, struct symbol_list **unused);
79 typedef struct token *attr_t(struct token *, struct symbol *,
80 struct decl_state *);
82 static attr_t
83 attribute_packed, attribute_aligned, attribute_cleanup,
84 attribute_modifier,
85 attribute_function,
86 attribute_bitwise,
87 attribute_address_space, attribute_context,
88 attribute_designated_init,
89 attribute_transparent_union, ignore_attribute,
90 attribute_mode, attribute_force;
92 typedef struct symbol *to_mode_t(struct symbol *);
94 static to_mode_t
95 to_QI_mode, to_HI_mode, to_SI_mode, to_DI_mode, to_TI_mode;
96 static to_mode_t to_pointer_mode, to_word_mode;
98 enum {
99 Set_T = 1,
100 Set_S = 2,
101 Set_Char = 4,
102 Set_Int = 8,
103 Set_Double = 16,
104 Set_Float = 32,
105 Set_Signed = 64,
106 Set_Unsigned = 128,
107 Set_Short = 256,
108 Set_Long = 512,
109 Set_Vlong = 1024,
110 Set_Int128 = 2048,
111 Set_Any = Set_T | Set_Short | Set_Long | Set_Signed | Set_Unsigned
114 enum {
115 CInt = 0, CSInt, CUInt, CReal,
118 static void asm_modifier(struct token *token, unsigned long *mods, unsigned long mod)
120 if (*mods & mod)
121 warning(token->pos, "duplicated asm modifier");
122 *mods |= mod;
125 static struct symbol_op typedef_op = {
126 .type = KW_MODIFIER,
127 .declarator = storage_specifier,
130 static struct symbol_op inline_op = {
131 .type = KW_MODIFIER,
132 .declarator = generic_qualifier,
133 .asm_modifier = asm_modifier,
136 static struct symbol_op noreturn_op = {
137 .type = KW_MODIFIER,
138 .declarator = generic_qualifier,
141 static declarator_t alignas_specifier;
142 static struct symbol_op alignas_op = {
143 .type = KW_MODIFIER,
144 .declarator = alignas_specifier,
147 static struct symbol_op auto_op = {
148 .type = KW_MODIFIER,
149 .declarator = storage_specifier,
152 static struct symbol_op register_op = {
153 .type = KW_MODIFIER,
154 .declarator = storage_specifier,
157 static struct symbol_op static_op = {
158 .type = KW_MODIFIER|KW_STATIC,
159 .declarator = storage_specifier,
162 static struct symbol_op extern_op = {
163 .type = KW_MODIFIER,
164 .declarator = storage_specifier,
167 static struct symbol_op thread_op = {
168 .type = KW_MODIFIER,
169 .declarator = thread_specifier,
172 static struct symbol_op const_op = {
173 .type = KW_QUALIFIER,
174 .declarator = generic_qualifier,
177 static struct symbol_op volatile_op = {
178 .type = KW_QUALIFIER,
179 .declarator = generic_qualifier,
180 .asm_modifier = asm_modifier,
183 static struct symbol_op restrict_op = {
184 .type = KW_QUALIFIER,
185 .declarator = generic_qualifier,
188 static struct symbol_op atomic_op = {
189 .type = KW_QUALIFIER,
190 .declarator = generic_qualifier,
193 static struct symbol_op typeof_op = {
194 .type = KW_SPECIFIER,
195 .declarator = typeof_specifier,
196 .test = Set_Any,
197 .set = Set_S|Set_T,
200 static struct symbol_op autotype_op = {
201 .type = KW_SPECIFIER,
202 .declarator = autotype_specifier,
203 .test = Set_Any,
204 .set = Set_S|Set_T,
207 static struct symbol_op attribute_op = {
208 .type = KW_ATTRIBUTE,
209 .declarator = attribute_specifier,
212 static struct symbol_op struct_op = {
213 .type = KW_SPECIFIER,
214 .declarator = struct_specifier,
215 .test = Set_Any,
216 .set = Set_S|Set_T,
219 static struct symbol_op union_op = {
220 .type = KW_SPECIFIER,
221 .declarator = union_specifier,
222 .test = Set_Any,
223 .set = Set_S|Set_T,
226 static struct symbol_op enum_op = {
227 .type = KW_SPECIFIER,
228 .declarator = enum_specifier,
229 .test = Set_Any,
230 .set = Set_S|Set_T,
233 static struct symbol_op spec_op = {
234 .type = KW_SPECIFIER | KW_EXACT,
235 .test = Set_Any,
236 .set = Set_S|Set_T,
239 static struct symbol_op char_op = {
240 .type = KW_SPECIFIER,
241 .test = Set_T|Set_Long|Set_Short,
242 .set = Set_T|Set_Char,
243 .class = CInt,
246 static struct symbol_op int_op = {
247 .type = KW_SPECIFIER,
248 .test = Set_T,
249 .set = Set_T|Set_Int,
252 static struct symbol_op double_op = {
253 .type = KW_SPECIFIER,
254 .test = Set_T|Set_Signed|Set_Unsigned|Set_Short|Set_Vlong,
255 .set = Set_T|Set_Double,
256 .class = CReal,
259 static struct symbol_op float_op = {
260 .type = KW_SPECIFIER,
261 .test = Set_T|Set_Signed|Set_Unsigned|Set_Short|Set_Long,
262 .set = Set_T|Set_Float,
263 .class = CReal,
266 static struct symbol_op short_op = {
267 .type = KW_SPECIFIER,
268 .test = Set_S|Set_Char|Set_Float|Set_Double|Set_Long|Set_Short,
269 .set = Set_Short,
272 static struct symbol_op signed_op = {
273 .type = KW_SPECIFIER,
274 .test = Set_S|Set_Float|Set_Double|Set_Signed|Set_Unsigned,
275 .set = Set_Signed,
276 .class = CSInt,
279 static struct symbol_op unsigned_op = {
280 .type = KW_SPECIFIER,
281 .test = Set_S|Set_Float|Set_Double|Set_Signed|Set_Unsigned,
282 .set = Set_Unsigned,
283 .class = CUInt,
286 static struct symbol_op long_op = {
287 .type = KW_SPECIFIER,
288 .test = Set_S|Set_Char|Set_Float|Set_Short|Set_Vlong,
289 .set = Set_Long,
292 static struct symbol_op int128_op = {
293 .type = KW_SPECIFIER,
294 .test = Set_S|Set_T|Set_Char|Set_Short|Set_Int|Set_Float|Set_Double|Set_Long|Set_Vlong|Set_Int128,
295 .set = Set_T|Set_Int128|Set_Vlong,
296 .class = CInt,
299 static struct symbol_op if_op = {
300 .statement = parse_if_statement,
303 static struct symbol_op return_op = {
304 .statement = parse_return_statement,
307 static struct symbol_op loop_iter_op = {
308 .statement = parse_loop_iterator,
311 static struct symbol_op default_op = {
312 .statement = parse_default_statement,
315 static struct symbol_op case_op = {
316 .statement = parse_case_statement,
319 static struct symbol_op switch_op = {
320 .statement = parse_switch_statement,
323 static struct symbol_op for_op = {
324 .statement = parse_for_statement,
327 static struct symbol_op while_op = {
328 .statement = parse_while_statement,
331 static struct symbol_op do_op = {
332 .statement = parse_do_statement,
335 static struct symbol_op goto_op = {
336 .statement = parse_goto_statement,
339 static struct symbol_op __context___op = {
340 .statement = parse_context_statement,
341 .attribute = attribute_context,
344 static struct symbol_op range_op = {
345 .statement = parse_range_statement,
348 static struct symbol_op asm_op = {
349 .type = KW_ASM,
350 .statement = parse_asm_statement,
351 .toplevel = toplevel_asm_declaration,
354 static struct symbol_op static_assert_op = {
355 .toplevel = parse_static_assert,
358 static struct symbol_op seg_gs = {
359 .toplevel = ignore_seg_gs,
362 static struct symbol_op packed_op = {
363 .attribute = attribute_packed,
366 static struct symbol_op aligned_op = {
367 .attribute = attribute_aligned,
370 static struct symbol_op cleanup_op = {
371 .attribute = attribute_cleanup,
374 static struct symbol_op attr_mod_op = {
375 .attribute = attribute_modifier,
378 static struct symbol_op attr_fun_op = {
379 .attribute = attribute_function,
382 static struct symbol_op attr_bitwise_op = {
383 .attribute = attribute_bitwise,
386 static struct symbol_op attr_force_op = {
387 .attribute = attribute_force,
390 static struct symbol_op address_space_op = {
391 .attribute = attribute_address_space,
394 static struct symbol_op mode_op = {
395 .attribute = attribute_mode,
398 static struct symbol_op context_op = {
399 .attribute = attribute_context,
402 static struct symbol_op designated_init_op = {
403 .attribute = attribute_designated_init,
406 static struct symbol_op transparent_union_op = {
407 .attribute = attribute_transparent_union,
410 static struct symbol_op ignore_attr_op = {
411 .attribute = ignore_attribute,
414 static struct symbol_op mode_QI_op = {
415 .type = KW_MODE,
416 .to_mode = to_QI_mode
419 static struct symbol_op mode_HI_op = {
420 .type = KW_MODE,
421 .to_mode = to_HI_mode
424 static struct symbol_op mode_SI_op = {
425 .type = KW_MODE,
426 .to_mode = to_SI_mode
429 static struct symbol_op mode_DI_op = {
430 .type = KW_MODE,
431 .to_mode = to_DI_mode
434 static struct symbol_op mode_TI_op = {
435 .type = KW_MODE,
436 .to_mode = to_TI_mode
439 static struct symbol_op mode_pointer_op = {
440 .type = KW_MODE,
441 .to_mode = to_pointer_mode
444 static struct symbol_op mode_word_op = {
445 .type = KW_MODE,
446 .to_mode = to_word_mode
450 * Define the keyword and their effects.
451 * The entries in the 'typedef' and put in NS_TYPEDEF and
452 * are automatically set as reserved keyword while the ones
453 * in the 'keyword' table are just put in NS_KEYWORD.
455 * The entries are added via the 3 macros:
456 * N() for entries with "name" only,
457 * D() for entries with "name" & "__name__",
458 * A() for entries with "name", "__name" & "__name__",
459 * U() for entries with "__name" & "__name__".
461 static struct init_keyword {
462 const char *name;
463 struct symbol_op *op;
464 struct symbol *type;
465 unsigned long mods;
466 } typedefs[] = {
467 #define N(I, O,...) { I, O,##__VA_ARGS__ }
468 #define D(I, O,...) N(I,O,##__VA_ARGS__ ), \
469 N("__" I "__",O,##__VA_ARGS__)
470 #define A(I, O,...) N(I,O,##__VA_ARGS__ ), \
471 N("__" I,O,##__VA_ARGS__), \
472 N("__" I "__",O,##__VA_ARGS__)
473 #define U(I, O,...) N("__" I,O,##__VA_ARGS__), \
474 N("__" I "__",O,##__VA_ARGS__)
475 /* Storage classes */
476 N("auto", &auto_op, .mods = MOD_AUTO),
477 N("register", &register_op, .mods = MOD_REGISTER),
478 N("static", &static_op, .mods = MOD_STATIC),
479 N("extern", &extern_op, .mods = MOD_EXTERN),
480 N("__thread", &thread_op),
481 N("_Thread_local", &thread_op),
483 A("inline", &inline_op, .mods = MOD_INLINE),
485 /* Typedef ... */
486 N("typedef", &typedef_op, .mods = MOD_USERTYPE),
487 A("typeof", &typeof_op),
488 N("__auto_type", &autotype_op),
490 /* Type qualifiers */
491 A("const", &const_op, .mods = MOD_CONST),
492 A("volatile", &volatile_op, .mods = MOD_VOLATILE),
493 A("restrict", &restrict_op, .mods = MOD_RESTRICT),
495 N("_Atomic", &atomic_op, .mods = MOD_ATOMIC),
496 N("_Noreturn", &noreturn_op, .mods = MOD_NORETURN),
497 N("_Alignas", &alignas_op),
499 U("attribute", &attribute_op),
501 /* Type specifiers */
502 N("struct", &struct_op),
503 N("union", &union_op),
504 N("enum", &enum_op),
506 N("void", &spec_op, .type = &void_ctype),
507 N("char", &char_op),
508 N("short", &short_op),
509 N("int", &int_op),
510 N("long", &long_op),
511 N("float", &float_op),
512 N("double", &double_op),
513 A("signed", &signed_op),
514 N("unsigned", &unsigned_op),
515 N("__int128", &int128_op),
516 N("_Bool", &spec_op, .type = &bool_ctype),
518 /* Predeclared types */
519 N("__builtin_va_list", &spec_op, .type = &ptr_ctype),
520 N("__builtin_ms_va_list",&spec_op, .type = &ptr_ctype),
521 N("__int128_t", &spec_op, .type = &sint128_ctype),
522 N("__uint128_t", &spec_op, .type = &uint128_ctype),
523 N("_Float32", &spec_op, .type = &float32_ctype),
524 N("_Float32x", &spec_op, .type = &float32x_ctype),
525 N("_Float64", &spec_op, .type = &float64_ctype),
526 N("_Float64x", &spec_op, .type = &float64x_ctype),
527 N("_Float128", &spec_op, .type = &float128_ctype),
528 N("__float128", &spec_op, .type = &float128_ctype),
530 N("__seg_gs", &seg_gs),
532 }, keywords[] = {
533 /* Statements */
534 N("if", &if_op),
535 N("return", &return_op),
536 N("break", &loop_iter_op),
537 N("continue", &loop_iter_op),
538 N("default", &default_op),
539 N("case", &case_op),
540 N("switch", &switch_op),
541 N("for", &for_op),
542 N("while", &while_op),
543 N("do", &do_op),
544 N("goto", &goto_op),
545 A("asm", &asm_op),
546 N("context", &context_op),
547 N("__context__", &__context___op),
548 N("__range__", &range_op),
549 N("_Static_assert", &static_assert_op),
551 /* Attributes */
552 D("packed", &packed_op),
553 D("aligned", &aligned_op),
554 D("__cleanup__", &cleanup_op),
555 D("nocast", &attr_mod_op, .mods = MOD_NOCAST),
556 D("noderef", &attr_mod_op, .mods = MOD_NODEREF),
557 D("safe", &attr_mod_op, .mods = MOD_SAFE),
558 D("unused", &attr_mod_op, .mods = MOD_UNUSED),
559 D("externally_visible", &attr_mod_op, .mods = MOD_EXT_VISIBLE),
560 D("force", &attr_force_op),
561 D("bitwise", &attr_bitwise_op, .mods = MOD_BITWISE),
562 D("address_space", &address_space_op),
563 D("designated_init", &designated_init_op),
564 D("transparent_union", &transparent_union_op),
565 D("noreturn", &attr_fun_op, .mods = MOD_NORETURN),
566 D("pure", &attr_fun_op, .mods = MOD_PURE),
567 A("const", &attr_fun_op, .mods = MOD_PURE),
568 D("gnu_inline", &attr_fun_op, .mods = MOD_GNU_INLINE),
570 /* Modes */
571 D("mode", &mode_op),
572 D("QI", &mode_QI_op),
573 D("HI", &mode_HI_op),
574 D("SI", &mode_SI_op),
575 D("DI", &mode_DI_op),
576 D("TI", &mode_TI_op),
577 D("byte", &mode_QI_op),
578 D("pointer", &mode_pointer_op),
579 D("word", &mode_word_op),
583 static const char *ignored_attributes[] = {
585 #define GCC_ATTR(x) \
586 STRINGIFY(x), \
587 STRINGIFY(__##x##__),
589 #include "gcc-attr-list.h"
591 #undef GCC_ATTR
593 "bounded",
594 "__bounded__",
595 "__noclone",
596 "__nonnull",
597 "__nothrow",
601 static void init_keyword(int stream, struct init_keyword *kw, enum namespace ns)
603 struct symbol *sym = create_symbol(stream, kw->name, SYM_KEYWORD, ns);
604 sym->ident->keyword = 1;
605 sym->ident->reserved |= (ns == NS_TYPEDEF);
606 sym->ctype.modifiers = kw->mods;
607 sym->ctype.base_type = kw->type;
608 sym->op = kw->op;
611 void init_parser(int stream)
613 int i;
615 for (i = 0; i < ARRAY_SIZE(typedefs); i++)
616 init_keyword(stream, &typedefs[i], NS_TYPEDEF);
617 for (i = 0; i < ARRAY_SIZE(keywords); i++)
618 init_keyword(stream, &keywords[i], NS_KEYWORD);
620 for (i = 0; i < ARRAY_SIZE(ignored_attributes); i++) {
621 const char * name = ignored_attributes[i];
622 struct symbol *sym = create_symbol(stream, name, SYM_KEYWORD,
623 NS_KEYWORD);
624 if (!sym->op) {
625 sym->ident->keyword = 1;
626 sym->op = &ignore_attr_op;
632 static struct token *skip_to(struct token *token, int op)
634 while (!match_op(token, op) && !eof_token(token))
635 token = token->next;
636 return token;
639 static struct token bad_token = { .pos.type = TOKEN_BAD };
640 struct token *expect(struct token *token, int op, const char *where)
642 if (!match_op(token, op)) {
643 if (token != &bad_token) {
644 bad_token.next = token;
645 sparse_error(token->pos, "Expected %s %s", show_special(op), where);
646 sparse_error(token->pos, "got %s", show_token(token));
648 if (op == ';')
649 return skip_to(token, op);
650 return &bad_token;
652 return token->next;
656 // issue an error message on new parsing errors
657 // @token: the current token
658 // @errmsg: the error message
659 // If the current token is from a previous error, an error message
660 // has already been issued, so nothing more is done.
661 // Otherwise, @errmsg is displayed followed by the current token.
662 static void unexpected(struct token *token, const char *errmsg)
664 if (token == &bad_token)
665 return;
666 sparse_error(token->pos, "%s", errmsg);
667 sparse_error(token->pos, "got %s", show_token(token));
670 // Add a symbol to the list of function-local symbols
671 static void fn_local_symbol(struct symbol *sym)
673 if (function_symbol_list)
674 add_symbol(function_symbol_list, sym);
677 struct statement *alloc_statement(struct position pos, int type)
679 struct statement *stmt = __alloc_statement(0);
680 stmt->type = type;
681 stmt->pos = pos;
682 return stmt;
685 static struct token *struct_declaration_list(struct token *token, struct symbol_list **list);
687 static void apply_ctype(struct position pos, struct ctype *dst, struct ctype *src);
689 static void apply_modifiers(struct position pos, struct decl_state *ctx)
691 struct symbol *ctype;
692 if (!ctx->mode)
693 return;
694 ctype = ctx->mode->to_mode(ctx->ctype.base_type);
695 if (!ctype)
696 sparse_error(pos, "don't know how to apply mode to %s",
697 show_typename(ctx->ctype.base_type));
698 else
699 ctx->ctype.base_type = ctype;
703 static struct symbol * alloc_indirect_symbol(struct position pos, struct ctype *ctype, int type)
705 struct symbol *sym = alloc_symbol(pos, type);
707 sym->ctype.base_type = ctype->base_type;
708 sym->ctype.modifiers = ctype->modifiers;
710 ctype->base_type = sym;
711 ctype->modifiers = 0;
712 return sym;
716 * NOTE! NS_LABEL is not just a different namespace,
717 * it also ends up using function scope instead of the
718 * regular symbol scope.
720 struct symbol *label_symbol(struct token *token, int used)
722 struct symbol *sym = lookup_symbol(token->ident, NS_LABEL);
723 if (!sym) {
724 sym = alloc_symbol(token->pos, SYM_LABEL);
725 bind_symbol(sym, token->ident, NS_LABEL);
726 if (used)
727 sym->used = 1;
728 fn_local_symbol(sym);
730 return sym;
733 static struct token *struct_union_enum_specifier(enum type type,
734 struct token *token, struct decl_state *ctx,
735 struct token *(*parse)(struct token *, struct symbol *))
737 struct decl_state attr = { };
738 struct symbol *sym;
739 struct position *repos;
741 token = handle_attributes(token, &attr);
742 if (token_type(token) == TOKEN_IDENT) {
743 sym = lookup_symbol(token->ident, NS_STRUCT);
744 if (!sym ||
745 (is_outer_scope(sym->scope) &&
746 (match_op(token->next,';') || match_op(token->next,'{')))) {
747 // Either a new symbol, or else an out-of-scope
748 // symbol being redefined.
749 sym = alloc_symbol(token->pos, type);
750 bind_symbol(sym, token->ident, NS_STRUCT);
752 if (sym->type != type)
753 error_die(token->pos, "invalid tag applied to %s", show_typename (sym));
754 ctx->ctype.base_type = sym;
755 repos = &token->pos;
756 token = token->next;
757 if (!match_op(token, '{'))
758 return token;
760 // The following test is actually wrong for empty
761 // structs, but (1) they are not C99, (2) gcc does
762 // the same thing, and (3) it's easier.
763 if (sym->symbol_list)
764 error_die(token->pos, "redefinition of %s", show_typename (sym));
765 sym->pos = *repos;
767 // Mark the structure as needing re-examination
768 sym->examined = 0;
769 } else if (match_op(token, '{')) {
770 // private struct/union/enum type
771 sym = alloc_symbol(token->pos, type);
772 set_current_scope(sym); // used by dissect
773 ctx->ctype.base_type = sym;
774 } else {
775 sparse_error(token->pos, "expected declaration");
776 ctx->ctype.base_type = &bad_ctype;
777 return token;
780 token = parse(token->next, sym);
781 token = expect(token, '}', "at end of specifier");
782 attr.ctype.base_type = sym;
783 token = handle_attributes(token, &attr);
784 apply_ctype(token->pos, &sym->ctype, &attr.ctype);
785 sym->packed = attr.packed;
787 sym->endpos = token->pos;
789 return token;
792 static struct token *parse_struct_declaration(struct token *token, struct symbol *sym)
794 struct symbol *field, *last = NULL;
795 struct token *res;
796 res = struct_declaration_list(token, &sym->symbol_list);
797 FOR_EACH_PTR(sym->symbol_list, field) {
798 if (!field->ident) {
799 struct symbol *base = field->ctype.base_type;
800 if (base && base->type == SYM_BITFIELD)
801 continue;
803 if (last)
804 last->next_subobject = field;
805 last = field;
806 } END_FOR_EACH_PTR(field);
807 return res;
810 static struct token *parse_union_declaration(struct token *token, struct symbol *sym)
812 return struct_declaration_list(token, &sym->symbol_list);
815 static struct token *struct_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
817 return struct_union_enum_specifier(SYM_STRUCT, token, ctx, parse_struct_declaration);
820 static struct token *union_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
822 return struct_union_enum_specifier(SYM_UNION, token, ctx, parse_union_declaration);
826 // safe right shift
828 // This allow to use a shift amount as big (or bigger)
829 // than the width of the value to be shifted, in which case
830 // the result is, of course, 0.
831 static unsigned long long rshift(unsigned long long val, unsigned int n)
833 if (n >= (sizeof(val) * 8))
834 return 0;
835 return val >> n;
838 struct range {
839 long long neg;
840 unsigned long long pos;
843 static void update_range(struct range *range, unsigned long long uval, struct symbol *vtype)
845 long long sval = uval;
847 if (is_signed_type(vtype) && (sval < 0)) {
848 if (sval < range->neg)
849 range->neg = sval;
850 } else {
851 if (uval > range->pos)
852 range->pos = uval;
856 static int type_is_ok(struct symbol *type, struct range range)
858 int shift = type->bit_size;
859 int is_unsigned = type->ctype.modifiers & MOD_UNSIGNED;
861 if (!is_unsigned)
862 shift--;
863 if (rshift(range.pos, shift))
864 return 0;
865 if (range.neg == 0)
866 return 1;
867 if (is_unsigned)
868 return 0;
869 if (rshift(~range.neg, shift))
870 return 0;
871 return 1;
874 static struct range type_range(struct symbol *type)
876 struct range range;
877 unsigned int size = type->bit_size;
878 unsigned long long max;
879 long long min;
881 if (is_signed_type(type)) {
882 min = sign_bit(size);
883 max = min - 1;
884 } else {
885 min = 0;
886 max = bits_mask(size);
889 range.pos = max;
890 range.neg = min;
891 return range;
894 static int val_in_range(struct range *range, long long sval, struct symbol *vtype)
896 unsigned long long uval = sval;
898 if (is_signed_type(vtype) && (sval < 0))
899 return range->neg <= sval;
900 else
901 return uval <= range->pos;
904 static void cast_enum_list(struct symbol_list *list, struct symbol *base_type)
906 struct range irange = type_range(&int_ctype);
907 struct symbol *sym;
909 FOR_EACH_PTR(list, sym) {
910 struct expression *expr = sym->initializer;
911 struct symbol *ctype;
912 long long val;
913 if (expr->type != EXPR_VALUE)
914 continue;
915 ctype = expr->ctype;
916 val = get_expression_value(expr);
917 if (is_int_type(ctype) && val_in_range(&irange, val, ctype)) {
918 expr->ctype = &int_ctype;
919 continue;
921 cast_value(expr, base_type, expr);
922 } END_FOR_EACH_PTR(sym);
925 static struct token *parse_enum_declaration(struct token *token, struct symbol *parent)
927 unsigned long long lastval = 0;
928 struct symbol *ctype = NULL, *base_type = NULL;
929 struct range range = { };
930 int mix_bitwise = 0;
932 parent->examined = 1;
933 parent->ctype.base_type = &int_ctype;
934 while (token_type(token) == TOKEN_IDENT) {
935 struct expression *expr = NULL;
936 struct token *next = token->next;
937 struct decl_state ctx = { };
938 struct symbol *sym;
940 // FIXME: only 'deprecated' should be accepted
941 next = handle_attributes(next, &ctx);
943 if (match_op(next, '=')) {
944 next = constant_expression(next->next, &expr);
945 lastval = get_expression_value(expr);
946 ctype = &void_ctype;
947 if (expr && expr->ctype)
948 ctype = expr->ctype;
949 } else if (!ctype) {
950 ctype = &int_ctype;
951 } else if (is_int_type(ctype)) {
952 lastval++;
953 } else {
954 error_die(token->pos, "can't increment the last enum member");
957 if (!expr) {
958 expr = alloc_expression(token->pos, EXPR_VALUE);
959 expr->value = lastval;
960 expr->ctype = ctype;
963 sym = alloc_symbol(token->pos, SYM_NODE);
964 bind_symbol(sym, token->ident, NS_SYMBOL);
965 sym->ctype.modifiers &= ~MOD_ADDRESSABLE;
966 sym->initializer = expr;
967 sym->enum_member = 1;
968 sym->ctype.base_type = parent;
969 add_ptr_list(&parent->symbol_list, sym);
971 if (base_type != &bad_ctype) {
972 if (ctype->type == SYM_NODE)
973 ctype = ctype->ctype.base_type;
974 if (ctype->type == SYM_ENUM) {
975 if (ctype == parent)
976 ctype = base_type;
977 else
978 ctype = ctype->ctype.base_type;
981 * base_type rules:
982 * - if all enums are of the same type, then
983 * the base_type is that type (two first
984 * cases)
985 * - if enums are of different types, they
986 * all have to be integer types, and the
987 * base type is at least "int_ctype".
988 * - otherwise the base_type is "bad_ctype".
990 if (!base_type || ctype == &bad_ctype) {
991 base_type = ctype;
992 } else if (ctype == base_type) {
993 /* nothing */
994 } else if (is_int_type(base_type) && is_int_type(ctype)) {
995 base_type = &int_ctype;
996 } else if (is_restricted_type(base_type) != is_restricted_type(ctype)) {
997 if (!mix_bitwise++) {
998 warning(expr->pos, "mixed bitwiseness");
1000 } else if (is_restricted_type(base_type) && base_type != ctype) {
1001 sparse_error(expr->pos, "incompatible restricted type");
1002 info(expr->pos, " expected: %s", show_typename(base_type));
1003 info(expr->pos, " got: %s", show_typename(ctype));
1004 base_type = &bad_ctype;
1005 } else if (base_type != &bad_ctype) {
1006 sparse_error(token->pos, "bad enum definition");
1007 base_type = &bad_ctype;
1009 parent->ctype.base_type = base_type;
1011 if (is_int_type(base_type)) {
1012 update_range(&range, lastval, ctype);
1014 token = next;
1016 sym->endpos = token->pos;
1018 if (!match_op(token, ','))
1019 break;
1020 token = token->next;
1022 if (!base_type) {
1023 sparse_error(token->pos, "empty enum definition");
1024 base_type = &bad_ctype;
1026 else if (!is_int_type(base_type))
1028 else if (type_is_ok(&uint_ctype, range))
1029 base_type = &uint_ctype;
1030 else if (type_is_ok(&int_ctype, range))
1031 base_type = &int_ctype;
1032 else if (type_is_ok(&ulong_ctype, range))
1033 base_type = &ulong_ctype;
1034 else if (type_is_ok(&long_ctype, range))
1035 base_type = &long_ctype;
1036 else if (type_is_ok(&ullong_ctype, range))
1037 base_type = &ullong_ctype;
1038 else if (type_is_ok(&llong_ctype, range))
1039 base_type = &llong_ctype;
1040 else
1041 base_type = &bad_ctype;
1042 parent->ctype.base_type = base_type;
1043 parent->ctype.modifiers |= (base_type->ctype.modifiers & MOD_UNSIGNED);
1044 parent->examined = 0;
1046 if (mix_bitwise)
1047 return token;
1048 cast_enum_list(parent->symbol_list, base_type);
1050 return token;
1053 static struct token *enum_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
1055 struct token *ret = struct_union_enum_specifier(SYM_ENUM, token, ctx, parse_enum_declaration);
1056 struct ctype *ctype = &ctx->ctype.base_type->ctype;
1058 if (!ctype->base_type)
1059 ctype->base_type = &incomplete_ctype;
1061 return ret;
1064 static struct token *typeof_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
1067 if (!match_op(token, '(')) {
1068 sparse_error(token->pos, "expected '(' after typeof");
1069 return token;
1071 if (lookup_type(token->next)) {
1072 struct symbol *sym;
1073 token = typename(token->next, &sym, NULL);
1074 ctx->ctype.base_type = sym->ctype.base_type;
1075 apply_ctype(token->pos, &ctx->ctype, &sym->ctype);
1076 } else {
1077 struct symbol *typeof_sym = alloc_symbol(token->pos, SYM_TYPEOF);
1078 token = parse_expression(token->next, &typeof_sym->initializer);
1080 typeof_sym->endpos = token->pos;
1081 if (!typeof_sym->initializer) {
1082 sparse_error(token->pos, "expected expression after the '(' token");
1083 typeof_sym = &bad_ctype;
1085 ctx->ctype.base_type = typeof_sym;
1087 return expect(token, ')', "after typeof");
1090 static struct token *autotype_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
1092 ctx->ctype.base_type = &autotype_ctype;
1093 ctx->autotype = 1;
1094 return token;
1097 static struct token *ignore_attribute(struct token *token, struct symbol *attr, struct decl_state *ctx)
1099 struct expression *expr = NULL;
1100 if (match_op(token, '('))
1101 token = parens_expression(token, &expr, "in attribute");
1102 return token;
1105 static struct token *attribute_packed(struct token *token, struct symbol *attr, struct decl_state *ctx)
1107 if (!ctx->ctype.alignment) {
1108 ctx->ctype.alignment = 1;
1109 ctx->packed = 1;
1111 return token;
1114 static struct token *attribute_aligned(struct token *token, struct symbol *attr, struct decl_state *ctx)
1116 int alignment = max_alignment;
1117 struct expression *expr = NULL;
1119 if (match_op(token, '(')) {
1120 token = parens_expression(token, &expr, "in attribute");
1121 if (expr)
1122 alignment = const_expression_value(expr);
1124 if (alignment & (alignment-1)) {
1125 warning(token->pos, "I don't like non-power-of-2 alignments");
1126 return token;
1127 } else if (alignment > ctx->ctype.alignment)
1128 ctx->ctype.alignment = alignment;
1129 return token;
1132 static struct token *attribute_cleanup(struct token *token, struct symbol *attr, struct decl_state *ctx)
1134 struct expression *expr = NULL;
1136 if (match_op(token, '(')) {
1137 token = parens_expression(token, &expr, "in attribute");
1138 if (expr && expr->type == EXPR_SYMBOL)
1139 ctx->cleanup = expr;
1141 return token;
1144 static void apply_mod(struct position *pos, unsigned long *mods, unsigned long mod)
1146 if (*mods & mod & ~MOD_DUP_OK)
1147 warning(*pos, "duplicate %s", modifier_name(mod));
1148 *mods |= mod;
1151 static void apply_qualifier(struct position *pos, struct ctype *ctx, unsigned long qual)
1153 apply_mod(pos, &ctx->modifiers, qual);
1156 static struct token *attribute_modifier(struct token *token, struct symbol *attr, struct decl_state *ctx)
1158 apply_mod(&token->pos, &ctx->ctype.modifiers, attr->ctype.modifiers);
1159 return token;
1162 static struct token *attribute_function(struct token *token, struct symbol *attr, struct decl_state *ctx)
1164 apply_mod(&token->pos, &ctx->f_modifiers, attr->ctype.modifiers);
1165 return token;
1168 static struct token *attribute_bitwise(struct token *token, struct symbol *attr, struct decl_state *ctx)
1170 if (Wbitwise)
1171 attribute_modifier(token, attr, ctx);
1172 return token;
1175 static struct ident *numerical_address_space(int asn)
1177 char buff[32];
1179 if (!asn)
1180 return NULL;
1181 sprintf(buff, "<asn:%d>", asn);
1182 return built_in_ident(buff);
1185 static struct token *attribute_address_space(struct token *token, struct symbol *attr, struct decl_state *ctx)
1187 struct expression *expr = NULL;
1188 struct ident *as = NULL;
1189 struct token *next;
1191 token = expect(token, '(', "after address_space attribute");
1192 switch (token_type(token)) {
1193 case TOKEN_NUMBER:
1194 next = primary_expression(token, &expr);
1195 if (expr->type != EXPR_VALUE)
1196 goto invalid;
1197 as = numerical_address_space(expr->value);
1198 break;
1199 case TOKEN_IDENT:
1200 next = token->next;
1201 as = token->ident;
1202 break;
1203 default:
1204 next = token->next;
1205 invalid:
1206 as = NULL;
1207 warning(token->pos, "invalid address space name");
1210 if (Waddress_space && as) {
1211 if (ctx->ctype.as)
1212 sparse_error(token->pos,
1213 "multiple address spaces given: %s & %s",
1214 show_as(ctx->ctype.as), show_as(as));
1215 ctx->ctype.as = as;
1217 token = expect(next, ')', "after address_space attribute");
1218 return token;
1221 static struct symbol *to_QI_mode(struct symbol *ctype)
1223 if (ctype->ctype.base_type != &int_type)
1224 return NULL;
1225 if (ctype == &char_ctype)
1226 return ctype;
1227 return ctype->ctype.modifiers & MOD_UNSIGNED ? &uchar_ctype
1228 : &schar_ctype;
1231 static struct symbol *to_HI_mode(struct symbol *ctype)
1233 if (ctype->ctype.base_type != &int_type)
1234 return NULL;
1235 return ctype->ctype.modifiers & MOD_UNSIGNED ? &ushort_ctype
1236 : &sshort_ctype;
1239 static struct symbol *to_SI_mode(struct symbol *ctype)
1241 if (ctype->ctype.base_type != &int_type)
1242 return NULL;
1243 return ctype->ctype.modifiers & MOD_UNSIGNED ? &uint_ctype
1244 : &sint_ctype;
1247 static struct symbol *to_DI_mode(struct symbol *ctype)
1249 if (ctype->ctype.base_type != &int_type)
1250 return NULL;
1251 return ctype->ctype.modifiers & MOD_UNSIGNED ? &ullong_ctype
1252 : &sllong_ctype;
1255 static struct symbol *to_TI_mode(struct symbol *ctype)
1257 if (ctype->ctype.base_type != &int_type)
1258 return NULL;
1259 return ctype->ctype.modifiers & MOD_UNSIGNED ? &uint128_ctype
1260 : &sint128_ctype;
1263 static struct symbol *to_pointer_mode(struct symbol *ctype)
1265 if (ctype->ctype.base_type != &int_type)
1266 return NULL;
1267 return ctype->ctype.modifiers & MOD_UNSIGNED ? uintptr_ctype
1268 : intptr_ctype;
1271 static struct symbol *to_word_mode(struct symbol *ctype)
1273 if (ctype->ctype.base_type != &int_type)
1274 return NULL;
1275 return ctype->ctype.modifiers & MOD_UNSIGNED ? &ulong_ctype
1276 : &slong_ctype;
1279 static struct token *attribute_mode(struct token *token, struct symbol *attr, struct decl_state *ctx)
1281 token = expect(token, '(', "after mode attribute");
1282 if (token_type(token) == TOKEN_IDENT) {
1283 struct symbol *mode = lookup_keyword(token->ident, NS_KEYWORD);
1284 if (mode && mode->op->type & KW_MODE)
1285 ctx->mode = mode->op;
1286 else
1287 sparse_error(token->pos, "unknown mode attribute %s", show_ident(token->ident));
1288 token = token->next;
1289 } else
1290 sparse_error(token->pos, "expect attribute mode symbol\n");
1291 token = expect(token, ')', "after mode attribute");
1292 return token;
1295 static struct token *attribute_context(struct token *token, struct symbol *attr, struct decl_state *ctx)
1297 struct context *context = alloc_context();
1298 struct expression *args[3];
1299 int idx = 0;
1301 token = expect(token, '(', "after context attribute");
1302 token = conditional_expression(token, &args[0]);
1303 token = expect(token, ',', "after context 1st argument");
1304 token = conditional_expression(token, &args[1]);
1305 if (match_op(token, ',')) {
1306 token = token->next;
1307 token = conditional_expression(token, &args[2]);
1308 token = expect(token, ')', "after context 3rd argument");
1309 context->context = args[0];
1310 idx++;
1311 } else {
1312 token = expect(token, ')', "after context 2nd argument");
1314 context->in = get_expression_value(args[idx++]);
1315 context->out = get_expression_value(args[idx++]);
1316 add_ptr_list(&ctx->ctype.contexts, context);
1317 return token;
1320 static struct token *attribute_designated_init(struct token *token, struct symbol *attr, struct decl_state *ctx)
1322 if (ctx->ctype.base_type && ctx->ctype.base_type->type == SYM_STRUCT)
1323 ctx->ctype.base_type->designated_init = 1;
1324 else
1325 warning(token->pos, "attribute designated_init applied to non-structure type");
1326 return token;
1329 static struct token *attribute_transparent_union(struct token *token, struct symbol *attr, struct decl_state *ctx)
1331 if (Wtransparent_union)
1332 warning(token->pos, "attribute __transparent_union__");
1334 if (ctx->ctype.base_type && ctx->ctype.base_type->type == SYM_UNION)
1335 ctx->ctype.base_type->transparent_union = 1;
1336 else
1337 warning(token->pos, "attribute __transparent_union__ applied to non-union type");
1338 return token;
1341 static struct token *recover_unknown_attribute(struct token *token)
1343 struct expression *expr = NULL;
1345 if (Wunknown_attribute)
1346 warning(token->pos, "unknown attribute '%s'", show_ident(token->ident));
1347 token = token->next;
1348 if (match_op(token, '('))
1349 token = parens_expression(token, &expr, "in attribute");
1350 return token;
1353 static struct token *attribute_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
1355 token = expect(token, '(', "after attribute");
1356 token = expect(token, '(', "after attribute");
1358 while (token_type(token) == TOKEN_IDENT) {
1359 struct symbol *attr = lookup_keyword(token->ident, NS_KEYWORD);
1360 if (attr && attr->op->attribute)
1361 token = attr->op->attribute(token->next, attr, ctx);
1362 else
1363 token = recover_unknown_attribute(token);
1365 if (!match_op(token, ','))
1366 break;
1367 token = token->next;
1370 token = expect(token, ')', "after attribute");
1371 token = expect(token, ')', "after attribute");
1372 return token;
1375 static unsigned long decl_modifiers(struct decl_state *ctx)
1377 unsigned long mods = ctx->ctype.modifiers & MOD_DECLARE;
1378 ctx->ctype.modifiers &= ~MOD_DECLARE;
1379 return ctx->storage_class | mods;
1382 static struct token *storage_specifier(struct token *next, struct symbol *sym, struct decl_state *ctx)
1384 int is_tls = ctx->ctype.modifiers & MOD_TLS;
1385 unsigned long class = sym->ctype.modifiers;
1386 const char *storage = modifier_name(class);
1388 /* __thread can be used alone, or with extern or static */
1389 if (is_tls && (class & ~(MOD_STATIC|MOD_EXTERN)))
1390 sparse_error(next->pos, "__thread cannot be used with '%s'", storage);
1391 else if (!ctx->storage_class)
1392 ctx->storage_class = class;
1393 else if (ctx->storage_class == class)
1394 sparse_error(next->pos, "duplicate %s", storage);
1395 else
1396 sparse_error(next->pos, "multiple storage classes");
1397 return next;
1400 static struct token *thread_specifier(struct token *next, struct symbol *sym, struct decl_state *ctx)
1402 /* This GCC extension can be used alone, or with extern or static */
1403 if (!(ctx->storage_class & ~(MOD_STATIC|MOD_EXTERN))) {
1404 apply_qualifier(&next->pos, &ctx->ctype, MOD_TLS);
1405 } else {
1406 sparse_error(next->pos, "__thread cannot be used with '%s'",
1407 modifier_name(ctx->storage_class));
1410 return next;
1413 static struct token *attribute_force(struct token *token, struct symbol *attr, struct decl_state *ctx)
1415 ctx->forced = 1;
1416 return token;
1419 static struct token *alignas_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
1421 int alignment = 0;
1423 if (!match_op(token, '(')) {
1424 sparse_error(token->pos, "expected '(' after _Alignas");
1425 return token;
1427 if (lookup_type(token->next)) {
1428 struct symbol *sym = NULL;
1429 token = typename(token->next, &sym, NULL);
1430 sym = examine_symbol_type(sym);
1431 alignment = sym->ctype.alignment;
1432 token = expect(token, ')', "after _Alignas(...");
1433 } else {
1434 struct expression *expr = NULL;
1435 token = parens_expression(token, &expr, "after _Alignas");
1436 if (!expr)
1437 return token;
1438 alignment = const_expression_value(expr);
1441 if (alignment < 0) {
1442 warning(token->pos, "non-positive alignment");
1443 return token;
1445 if (alignment & (alignment-1)) {
1446 warning(token->pos, "non-power-of-2 alignment");
1447 return token;
1449 if (alignment > ctx->ctype.alignment)
1450 ctx->ctype.alignment = alignment;
1451 return token;
1454 static struct token *generic_qualifier(struct token *next, struct symbol *sym, struct decl_state *ctx)
1456 apply_qualifier(&next->pos, &ctx->ctype, sym->ctype.modifiers);
1457 return next;
1460 static void apply_ctype(struct position pos, struct ctype *dst, struct ctype *src)
1462 unsigned long mod = src->modifiers;
1464 if (mod)
1465 apply_qualifier(&pos, dst, mod);
1467 /* Context */
1468 concat_ptr_list((struct ptr_list *)src->contexts,
1469 (struct ptr_list **)&dst->contexts);
1471 /* Alignment */
1472 if (src->alignment > dst->alignment)
1473 dst->alignment = src->alignment;
1475 /* Address space */
1476 if (src->as)
1477 dst->as = src->as;
1480 static void specifier_conflict(struct position pos, int what, struct ident *new)
1482 const char *old;
1483 if (what & (Set_S | Set_T))
1484 goto Catch_all;
1485 if (what & Set_Char)
1486 old = "char";
1487 else if (what & Set_Double)
1488 old = "double";
1489 else if (what & Set_Float)
1490 old = "float";
1491 else if (what & Set_Signed)
1492 old = "signed";
1493 else if (what & Set_Unsigned)
1494 old = "unsigned";
1495 else if (what & Set_Short)
1496 old = "short";
1497 else if (what & Set_Long)
1498 old = "long";
1499 else
1500 old = "long long";
1501 sparse_error(pos, "impossible combination of type specifiers: %s %s",
1502 old, show_ident(new));
1503 return;
1505 Catch_all:
1506 sparse_error(pos, "two or more data types in declaration specifiers");
1509 static struct symbol * const int_types[] =
1510 {&char_ctype, &short_ctype, &int_ctype, &long_ctype, &llong_ctype, &int128_ctype};
1511 static struct symbol * const signed_types[] =
1512 {&schar_ctype, &sshort_ctype, &sint_ctype, &slong_ctype, &sllong_ctype,
1513 &sint128_ctype};
1514 static struct symbol * const unsigned_types[] =
1515 {&uchar_ctype, &ushort_ctype, &uint_ctype, &ulong_ctype, &ullong_ctype,
1516 &uint128_ctype};
1517 static struct symbol * const real_types[] =
1518 {&float_ctype, &double_ctype, &ldouble_ctype};
1519 static struct symbol * const * const types[] = {
1520 [CInt] = int_types + 2,
1521 [CSInt] = signed_types + 2,
1522 [CUInt] = unsigned_types + 2,
1523 [CReal] = real_types + 1,
1526 struct symbol *ctype_integer(int size, int want_unsigned)
1528 return types[want_unsigned ? CUInt : CInt][size];
1531 static struct token *handle_qualifiers(struct token *t, struct decl_state *ctx)
1533 while (token_type(t) == TOKEN_IDENT) {
1534 struct symbol *s = lookup_keyword(t->ident, NS_TYPEDEF);
1535 if (!s)
1536 break;
1537 if (!(s->op->type & (KW_ATTRIBUTE | KW_QUALIFIER)))
1538 break;
1539 t = t->next;
1540 if (s->op->declarator)
1541 t = s->op->declarator(t, s, ctx);
1543 return t;
1546 static struct token *declaration_specifiers(struct token *token, struct decl_state *ctx)
1548 int seen = 0;
1549 int class = CInt;
1550 int rank = 0;
1552 while (token_type(token) == TOKEN_IDENT) {
1553 struct symbol *s = lookup_symbol(token->ident,
1554 NS_TYPEDEF | NS_SYMBOL);
1555 if (!s || !(s->namespace & NS_TYPEDEF))
1556 break;
1557 if (s->type != SYM_KEYWORD) {
1558 if (seen & Set_Any)
1559 break;
1560 seen |= Set_S | Set_T;
1561 ctx->ctype.base_type = s->ctype.base_type;
1562 apply_ctype(token->pos, &ctx->ctype, &s->ctype);
1563 token = token->next;
1564 continue;
1566 if (s->op->type & KW_SPECIFIER) {
1567 if (seen & s->op->test) {
1568 specifier_conflict(token->pos,
1569 seen & s->op->test,
1570 token->ident);
1571 break;
1573 seen |= s->op->set;
1574 class += s->op->class;
1575 if (s->op->set & Set_Int128)
1576 rank = 3;
1577 else if (s->op->set & Set_Char)
1578 rank = -2;
1579 if (s->op->set & (Set_Short|Set_Float)) {
1580 rank = -1;
1581 } else if (s->op->set & Set_Long && rank++) {
1582 if (class == CReal) {
1583 specifier_conflict(token->pos,
1584 Set_Vlong,
1585 &double_ident);
1586 break;
1588 seen |= Set_Vlong;
1591 token = token->next;
1592 if (s->op->declarator) // Note: this eats attributes
1593 token = s->op->declarator(token, s, ctx);
1594 if (s->op->type & KW_EXACT) {
1595 ctx->ctype.base_type = s->ctype.base_type;
1596 ctx->ctype.modifiers |= s->ctype.modifiers;
1600 if (!(seen & Set_S)) { /* not set explicitly? */
1601 struct symbol *base = &incomplete_ctype;
1602 if (seen & Set_Any)
1603 base = types[class][rank];
1604 ctx->ctype.base_type = base;
1607 if (ctx->ctype.modifiers & MOD_BITWISE) {
1608 struct symbol *type;
1609 ctx->ctype.modifiers &= ~MOD_BITWISE;
1610 if (!is_int_type(ctx->ctype.base_type)) {
1611 sparse_error(token->pos, "invalid modifier");
1612 return token;
1614 type = alloc_symbol(token->pos, SYM_BASETYPE);
1615 *type = *ctx->ctype.base_type;
1616 type->ctype.modifiers &= ~MOD_SPECIFIER;
1617 type->ctype.base_type = ctx->ctype.base_type;
1618 type->type = SYM_RESTRICT;
1619 ctx->ctype.base_type = type;
1620 create_fouled(type);
1622 return token;
1625 static struct token *abstract_array_declarator(struct token *token, struct symbol *sym)
1627 struct expression *expr = NULL;
1628 int has_static = 0;
1630 while (token_type(token) == TOKEN_IDENT) {
1631 struct symbol *sym = lookup_keyword(token->ident, NS_TYPEDEF);
1632 if (!sym || !(sym->op->type & (KW_STATIC|KW_QUALIFIER)))
1633 break;
1634 if (has_static && (sym->op->type & KW_STATIC))
1635 sparse_error(token->pos, "duplicate array static declarator");
1636 has_static |= (sym->op->type & KW_STATIC);
1637 token = token->next;
1639 if (match_op(token, '*') && match_op(token->next, ']')) {
1640 // FIXME: '[*]' is treated like '[]'
1641 token = token->next;
1642 } else {
1643 token = assignment_expression(token, &expr);
1645 sym->array_size = expr;
1646 return token;
1649 static struct token *parameter_type_list(struct token *, struct symbol *);
1650 static struct token *identifier_list(struct token *, struct symbol *);
1651 static struct token *declarator(struct token *token, struct decl_state *ctx);
1653 static struct token *handle_asm_name(struct token *token, struct decl_state *ctx)
1655 struct expression *expr;
1656 struct symbol *keyword;
1658 if (token_type(token) != TOKEN_IDENT)
1659 return token;
1660 keyword = lookup_keyword(token->ident, NS_KEYWORD);
1661 if (!keyword)
1662 return token;
1663 if (!(keyword->op->type & KW_ASM))
1664 return token;
1666 token = token->next;
1667 token = expect(token, '(', "after asm");
1668 token = string_expression(token, &expr, "asm name");
1669 token = expect(token, ')', "after asm");
1670 return token;
1674 // test if @token is '__attribute__' (or one of its variant)
1675 static bool match_attribute(struct token *token)
1677 struct symbol *sym;
1679 if (token_type(token) != TOKEN_IDENT)
1680 return false;
1681 sym = lookup_keyword(token->ident, NS_TYPEDEF);
1682 if (!sym || !sym->op)
1683 return false;
1684 return sym->op->type & KW_ATTRIBUTE;
1687 static struct token *skip_attribute(struct token *token)
1689 token = token->next;
1690 if (match_op(token, '(')) {
1691 int depth = 1;
1692 token = token->next;
1693 while (depth && !eof_token(token)) {
1694 if (token_type(token) == TOKEN_SPECIAL) {
1695 if (token->special == '(')
1696 depth++;
1697 else if (token->special == ')')
1698 depth--;
1700 token = token->next;
1703 return token;
1706 static struct token *skip_attributes(struct token *token)
1708 while (match_attribute(token)) {
1709 token = expect(token->next, '(', "after attribute");
1710 token = expect(token, '(', "after attribute");
1711 while (token_type(token) == TOKEN_IDENT) {
1712 token = skip_attribute(token);
1713 if (!match_op(token, ','))
1714 break;
1715 token = token->next;
1717 token = expect(token, ')', "after attribute");
1718 token = expect(token, ')', "after attribute");
1720 return token;
1723 static struct token *handle_attributes(struct token *token, struct decl_state *ctx)
1725 while (match_attribute(token))
1726 token = attribute_specifier(token->next, NULL, ctx);
1727 return token;
1730 static int is_nested(struct token *token, struct token **p,
1731 int prefer_abstract)
1734 * This can be either a parameter list or a grouping.
1735 * For the direct (non-abstract) case, we know if must be
1736 * a parameter list if we already saw the identifier.
1737 * For the abstract case, we know if must be a parameter
1738 * list if it is empty or starts with a type.
1740 struct token *next = token->next;
1742 *p = next = skip_attributes(next);
1744 if (token_type(next) == TOKEN_IDENT) {
1745 if (lookup_type(next))
1746 return !prefer_abstract;
1747 return 1;
1750 if (match_op(next, ')') || match_op(next, SPECIAL_ELLIPSIS))
1751 return 0;
1753 return 1;
1756 enum kind {
1757 Empty, K_R, Proto, Bad_Func,
1760 static enum kind which_func(struct token *token,
1761 struct ident **n,
1762 int prefer_abstract)
1764 struct token *next = token->next;
1766 if (token_type(next) == TOKEN_IDENT) {
1767 if (lookup_type(next))
1768 return Proto;
1769 /* identifier list not in definition; complain */
1770 if (prefer_abstract)
1771 warning(token->pos,
1772 "identifier list not in definition");
1773 return K_R;
1776 if (token_type(next) != TOKEN_SPECIAL)
1777 return Bad_Func;
1779 if (next->special == ')') {
1780 /* don't complain about those */
1781 if (!n || match_op(next->next, ';') || match_op(next->next, ','))
1782 return Empty;
1783 if (Wstrict_prototypes)
1784 warning(next->pos,
1785 "non-ANSI function declaration of function '%s'",
1786 show_ident(*n));
1787 return Empty;
1790 if (next->special == SPECIAL_ELLIPSIS) {
1791 warning(next->pos,
1792 "variadic functions must have one named argument");
1793 return Proto;
1796 return Bad_Func;
1799 static struct token *direct_declarator(struct token *token, struct decl_state *ctx)
1801 struct ctype *ctype = &ctx->ctype;
1802 struct token *next;
1803 struct ident **p = ctx->ident;
1805 if (ctx->ident && token_type(token) == TOKEN_IDENT) {
1806 *ctx->ident = token->ident;
1807 token = token->next;
1808 } else if (match_op(token, '(') &&
1809 is_nested(token, &next, ctx->prefer_abstract)) {
1810 struct symbol *base_type = ctype->base_type;
1811 if (token->next != next)
1812 next = handle_attributes(token->next, ctx);
1813 token = declarator(next, ctx);
1814 token = expect(token, ')', "in nested declarator");
1815 while (ctype->base_type != base_type)
1816 ctype = &ctype->base_type->ctype;
1817 p = NULL;
1820 if (match_op(token, '(')) {
1821 enum kind kind = which_func(token, p, ctx->prefer_abstract);
1822 struct symbol *fn;
1823 fn = alloc_indirect_symbol(token->pos, ctype, SYM_FN);
1824 ctype->modifiers |= ctx->f_modifiers;
1825 token = token->next;
1826 if (kind == K_R)
1827 token = identifier_list(token, fn);
1828 else if (kind == Proto)
1829 token = parameter_type_list(token, fn);
1830 token = expect(token, ')', "in function declarator");
1831 fn->endpos = token->pos;
1832 return token;
1835 while (match_op(token, '[')) {
1836 struct symbol *array;
1837 array = alloc_indirect_symbol(token->pos, ctype, SYM_ARRAY);
1838 token = abstract_array_declarator(token->next, array);
1839 token = expect(token, ']', "in abstract_array_declarator");
1840 array->endpos = token->pos;
1841 ctype = &array->ctype;
1843 return token;
1846 static struct token *pointer(struct token *token, struct decl_state *ctx)
1848 while (match_op(token,'*')) {
1849 struct symbol *ptr = alloc_symbol(token->pos, SYM_PTR);
1850 ptr->ctype.modifiers = ctx->ctype.modifiers;
1851 ptr->ctype.base_type = ctx->ctype.base_type;
1852 ptr->ctype.as = ctx->ctype.as;
1853 ptr->ctype.contexts = ctx->ctype.contexts;
1854 ctx->ctype.modifiers = 0;
1855 ctx->ctype.base_type = ptr;
1856 ctx->ctype.as = NULL;
1857 ctx->ctype.contexts = NULL;
1858 ctx->ctype.alignment = 0;
1860 token = handle_qualifiers(token->next, ctx);
1861 ctx->ctype.base_type->endpos = token->pos;
1863 return token;
1866 static struct token *declarator(struct token *token, struct decl_state *ctx)
1868 token = pointer(token, ctx);
1869 return direct_declarator(token, ctx);
1872 static struct token *handle_bitfield(struct token *token, struct decl_state *ctx)
1874 struct ctype *ctype = &ctx->ctype;
1875 struct expression *expr;
1876 struct symbol *bitfield;
1877 long long width;
1879 if (ctype->base_type != &int_type && !is_int_type(ctype->base_type)) {
1880 sparse_error(token->pos, "invalid bitfield specifier for type %s.",
1881 show_typename(ctype->base_type));
1882 // Parse this to recover gracefully.
1883 return conditional_expression(token->next, &expr);
1886 bitfield = alloc_indirect_symbol(token->pos, ctype, SYM_BITFIELD);
1887 token = conditional_expression(token->next, &expr);
1888 width = const_expression_value(expr);
1889 bitfield->bit_size = width;
1891 if (width < 0 || width > INT_MAX || (*ctx->ident && width == 0)) {
1892 sparse_error(token->pos, "bitfield '%s' has invalid width (%lld)",
1893 show_ident(*ctx->ident), width);
1894 width = -1;
1895 } else if (*ctx->ident) {
1896 struct symbol *base_type = bitfield->ctype.base_type;
1897 struct symbol *bitfield_type = base_type == &int_type ? bitfield : base_type;
1898 int is_signed = !(bitfield_type->ctype.modifiers & MOD_UNSIGNED);
1899 if (Wone_bit_signed_bitfield && width == 1 && is_signed) {
1900 // Valid values are either {-1;0} or {0}, depending on integer
1901 // representation. The latter makes for very efficient code...
1902 sparse_error(token->pos, "dubious one-bit signed bitfield");
1904 if (Wdefault_bitfield_sign &&
1905 bitfield_type->type != SYM_ENUM &&
1906 !(bitfield_type->ctype.modifiers & MOD_EXPLICITLY_SIGNED) &&
1907 is_signed) {
1908 // The sign of bitfields is unspecified by default.
1909 warning(token->pos, "dubious bitfield without explicit `signed' or `unsigned'");
1912 bitfield->bit_size = width;
1913 bitfield->endpos = token->pos;
1914 bitfield->ident = *ctx->ident;
1915 return token;
1918 static struct token *declaration_list(struct token *token, struct symbol_list **list)
1920 struct decl_state ctx = {.prefer_abstract = 0};
1921 struct ctype saved;
1922 unsigned long mod;
1924 token = declaration_specifiers(token, &ctx);
1925 mod = decl_modifiers(&ctx);
1926 saved = ctx.ctype;
1927 for (;;) {
1928 struct symbol *decl = alloc_symbol(token->pos, SYM_NODE);
1929 ctx.cleanup = NULL;
1930 ctx.ident = &decl->ident;
1932 token = declarator(token, &ctx);
1933 if (match_op(token, ':'))
1934 token = handle_bitfield(token, &ctx);
1936 token = handle_attributes(token, &ctx);
1937 apply_modifiers(token->pos, &ctx);
1939 decl->ctype = ctx.ctype;
1940 decl->ctype.modifiers |= mod;
1941 decl->cleanup = ctx.cleanup;
1942 decl->endpos = token->pos;
1943 add_symbol(list, decl);
1944 if (!match_op(token, ','))
1945 break;
1946 token = token->next;
1947 ctx.ctype = saved;
1949 return token;
1952 static struct token *struct_declaration_list(struct token *token, struct symbol_list **list)
1954 while (!match_op(token, '}')) {
1955 if (match_ident(token, &_Static_assert_ident)) {
1956 token = parse_static_assert(token, NULL);
1957 continue;
1959 if (!match_op(token, ';'))
1960 token = declaration_list(token, list);
1961 if (!match_op(token, ';')) {
1962 sparse_error(token->pos, "expected ; at end of declaration");
1963 break;
1965 token = token->next;
1967 return token;
1970 static struct token *parameter_declaration(struct token *token, struct symbol *sym)
1972 struct decl_state ctx = {.prefer_abstract = 1};
1974 token = declaration_specifiers(token, &ctx);
1975 ctx.ident = &sym->ident;
1976 token = declarator(token, &ctx);
1977 token = handle_attributes(token, &ctx);
1978 apply_modifiers(token->pos, &ctx);
1979 sym->ctype = ctx.ctype;
1980 sym->ctype.modifiers |= decl_modifiers(&ctx);
1981 sym->endpos = token->pos;
1982 sym->forced_arg = ctx.forced;
1983 return token;
1986 struct token *typename(struct token *token, struct symbol **p, int *forced)
1988 struct decl_state ctx = {.prefer_abstract = 1};
1989 unsigned long class;
1990 struct symbol *sym = alloc_symbol(token->pos, SYM_NODE);
1991 *p = sym;
1992 token = declaration_specifiers(token, &ctx);
1993 token = declarator(token, &ctx);
1994 apply_modifiers(token->pos, &ctx);
1995 sym->ctype = ctx.ctype;
1996 sym->cleanup = ctx.cleanup;
1997 sym->endpos = token->pos;
1998 class = ctx.storage_class;
1999 if (forced)
2000 *forced = ctx.forced;
2001 if (class)
2002 warning(sym->pos, "storage class in typename (%s%s)",
2003 modifier_string(class), show_typename(sym));
2004 return token;
2007 static struct token *parse_underscore_Pragma(struct token *token)
2009 struct token *next;
2011 next = token->next;
2012 if (!match_op(next, '('))
2013 return next;
2014 next = next->next;
2015 if (next->pos.type != TOKEN_STRING)
2016 return next;
2017 next = next->next;
2018 if (!match_op(next, ')'))
2019 return next;
2020 return next->next;
2023 static struct token *expression_statement(struct token *token, struct expression **tree)
2025 if (match_ident(token, &_Pragma_ident))
2026 return parse_underscore_Pragma(token);
2028 token = parse_expression(token, tree);
2029 return expect(token, ';', "at end of statement");
2032 static struct token *parse_asm_operands(struct token *token, struct statement *stmt,
2033 struct asm_operand_list **inout)
2035 /* Allow empty operands */
2036 if (match_op(token->next, ':') || match_op(token->next, ')'))
2037 return token->next;
2038 do {
2039 struct asm_operand *op = __alloc_asm_operand(0);
2040 if (match_op(token->next, '[') &&
2041 token_type(token->next->next) == TOKEN_IDENT &&
2042 match_op(token->next->next->next, ']')) {
2043 op->name = token->next->next->ident;
2044 token = token->next->next->next;
2046 token = token->next;
2047 token = string_expression(token, &op->constraint, "asm constraint");
2048 token = parens_expression(token, &op->expr, "in asm parameter");
2049 add_ptr_list(inout, op);
2050 } while (match_op(token, ','));
2051 return token;
2054 static struct token *parse_asm_clobbers(struct token *token, struct statement *stmt,
2055 struct expression_list **clobbers)
2057 struct expression *expr;
2059 do {
2060 token = primary_expression(token->next, &expr);
2061 if (expr)
2062 add_expression(clobbers, expr);
2063 } while (match_op(token, ','));
2064 return token;
2067 static struct token *parse_asm_labels(struct token *token, struct statement *stmt,
2068 struct symbol_list **labels)
2070 struct symbol *label;
2072 do {
2073 token = token->next; /* skip ':' and ',' */
2074 if (token_type(token) != TOKEN_IDENT)
2075 return token;
2076 label = label_symbol(token, 1);
2077 add_symbol(labels, label);
2078 token = token->next;
2079 } while (match_op(token, ','));
2080 return token;
2083 static struct token *parse_asm_statement(struct token *token, struct statement *stmt)
2085 unsigned long mods = 0;
2087 token = token->next;
2088 stmt->type = STMT_ASM;
2089 while (token_type(token) == TOKEN_IDENT) {
2090 struct symbol *s = lookup_keyword(token->ident, NS_TYPEDEF);
2091 if (s && s->op->asm_modifier)
2092 s->op->asm_modifier(token, &mods, s->ctype.modifiers);
2093 else if (token->ident == &goto_ident)
2094 asm_modifier(token, &mods, MOD_ASM_GOTO);
2095 token = token->next;
2097 token = expect(token, '(', "after asm");
2098 token = string_expression(token, &stmt->asm_string, "inline asm");
2099 if (match_op(token, ':'))
2100 token = parse_asm_operands(token, stmt, &stmt->asm_outputs);
2101 if (match_op(token, ':'))
2102 token = parse_asm_operands(token, stmt, &stmt->asm_inputs);
2103 if (match_op(token, ':'))
2104 token = parse_asm_clobbers(token, stmt, &stmt->asm_clobbers);
2105 if (match_op(token, ':') && (mods & MOD_ASM_GOTO))
2106 token = parse_asm_labels(token, stmt, &stmt->asm_labels);
2107 token = expect(token, ')', "after asm");
2108 return expect(token, ';', "at end of asm-statement");
2111 static struct token *parse_static_assert(struct token *token, struct symbol_list **unused)
2113 struct expression *cond = NULL, *message = NULL;
2115 token = expect(token->next, '(', "after _Static_assert");
2116 token = constant_expression(token, &cond);
2117 if (!cond)
2118 sparse_error(token->pos, "Expected constant expression");
2119 if (match_op(token, ',')) {
2120 token = token->next;
2121 token = string_expression(token, &message, "_Static_assert()");
2122 if (!message)
2123 cond = NULL;
2125 token = expect(token, ')', "after diagnostic message in _Static_assert");
2126 token = expect(token, ';', "after _Static_assert()");
2128 if (cond && !const_expression_value(cond) && cond->type == EXPR_VALUE) {
2129 const char *sep = "", *msg = "";
2131 if (message) {
2132 sep = ": ";
2133 msg = show_string(message->string);
2135 sparse_error(cond->pos, "static assertion failed%s%s", sep, msg);
2138 return token;
2141 static struct token *ignore_seg_gs(struct token *token, struct symbol_list **unused)
2143 return token->next;
2146 /* Make a statement out of an expression */
2147 static struct statement *make_statement(struct expression *expr)
2149 struct statement *stmt;
2151 if (!expr)
2152 return NULL;
2153 stmt = alloc_statement(expr->pos, STMT_EXPRESSION);
2154 stmt->expression = expr;
2155 return stmt;
2159 * All iterators have two symbols associated with them:
2160 * the "continue" and "break" symbols, which are targets
2161 * for continue and break statements respectively.
2163 * They are in a special name-space, but they follow
2164 * all the normal visibility rules, so nested iterators
2165 * automatically work right.
2167 static void start_iterator(struct statement *stmt)
2169 struct symbol *cont, *brk;
2171 start_block_scope(stmt->pos);
2172 cont = alloc_symbol(stmt->pos, SYM_NODE);
2173 bind_symbol(cont, &continue_ident, NS_ITERATOR);
2174 brk = alloc_symbol(stmt->pos, SYM_NODE);
2175 bind_symbol(brk, &break_ident, NS_ITERATOR);
2177 stmt->type = STMT_ITERATOR;
2178 stmt->iterator_break = brk;
2179 stmt->iterator_continue = cont;
2180 fn_local_symbol(brk);
2181 fn_local_symbol(cont);
2184 static void end_iterator(struct statement *stmt)
2186 end_block_scope();
2189 static struct statement *start_function(struct symbol *sym)
2191 struct symbol *ret;
2192 struct statement *stmt = alloc_statement(sym->pos, STMT_COMPOUND);
2194 start_function_scope(sym->pos);
2195 ret = alloc_symbol(sym->pos, SYM_NODE);
2196 ret->ctype = sym->ctype.base_type->ctype;
2197 ret->ctype.modifiers &= ~(MOD_STORAGE | MOD_QUALIFIER | MOD_TLS | MOD_ACCESS | MOD_NOCAST | MOD_NODEREF);
2198 ret->ctype.modifiers |= (MOD_AUTO | MOD_REGISTER);
2199 bind_symbol(ret, &return_ident, NS_ITERATOR);
2200 stmt->ret = ret;
2201 fn_local_symbol(ret);
2203 // Currently parsed symbol for __func__/__FUNCTION__/__PRETTY_FUNCTION__
2204 current_fn = sym;
2206 return stmt;
2209 static void end_function(struct symbol *sym)
2211 current_fn = NULL;
2212 end_function_scope();
2216 * A "switch()" statement, like an iterator, has a
2217 * the "break" symbol associated with it. It works
2218 * exactly like the iterator break - it's the target
2219 * for any break-statements in scope, and means that
2220 * "break" handling doesn't even need to know whether
2221 * it's breaking out of an iterator or a switch.
2223 * In addition, the "case" symbol is a marker for the
2224 * case/default statements to find the switch statement
2225 * that they are associated with.
2227 static void start_switch(struct statement *stmt)
2229 struct symbol *brk, *switch_case;
2231 start_block_scope(stmt->pos);
2232 brk = alloc_symbol(stmt->pos, SYM_NODE);
2233 bind_symbol(brk, &break_ident, NS_ITERATOR);
2235 switch_case = alloc_symbol(stmt->pos, SYM_NODE);
2236 bind_symbol(switch_case, &case_ident, NS_ITERATOR);
2237 switch_case->stmt = stmt;
2239 stmt->type = STMT_SWITCH;
2240 stmt->switch_break = brk;
2241 stmt->switch_case = switch_case;
2243 fn_local_symbol(brk);
2244 fn_local_symbol(switch_case);
2247 static void end_switch(struct statement *stmt)
2249 if (!stmt->switch_case->symbol_list)
2250 warning(stmt->pos, "switch with no cases");
2251 end_block_scope();
2254 static void add_case_statement(struct statement *stmt)
2256 struct symbol *target = lookup_symbol(&case_ident, NS_ITERATOR);
2257 struct symbol *sym;
2259 if (!target) {
2260 sparse_error(stmt->pos, "not in switch scope");
2261 stmt->type = STMT_NONE;
2262 return;
2264 sym = alloc_symbol(stmt->pos, SYM_NODE);
2265 add_symbol(&target->symbol_list, sym);
2266 sym->stmt = stmt;
2267 stmt->case_label = sym;
2268 fn_local_symbol(sym);
2271 static struct token *parse_return_statement(struct token *token, struct statement *stmt)
2273 struct symbol *target = lookup_symbol(&return_ident, NS_ITERATOR);
2275 if (!target)
2276 error_die(token->pos, "internal error: return without a function target");
2277 stmt->type = STMT_RETURN;
2278 stmt->ret_target = target;
2279 return expression_statement(token->next, &stmt->ret_value);
2282 static void validate_for_loop_decl(struct symbol *sym)
2284 unsigned long storage = sym->ctype.modifiers & MOD_STORAGE;
2286 if (storage & ~(MOD_AUTO | MOD_REGISTER)) {
2287 const char *name = show_ident(sym->ident);
2288 sparse_error(sym->pos, "non-local var '%s' in for-loop initializer", name);
2289 sym->ctype.modifiers &= ~MOD_STORAGE;
2293 static struct token *parse_for_statement(struct token *token, struct statement *stmt)
2295 struct symbol_list *syms;
2296 struct expression *e1, *e2, *e3;
2297 struct statement *iterator;
2299 start_iterator(stmt);
2300 token = expect(token->next, '(', "after 'for'");
2302 syms = NULL;
2303 e1 = NULL;
2304 /* C99 variable declaration? */
2305 if (lookup_type(token)) {
2306 token = external_declaration(token, &syms, validate_for_loop_decl);
2307 } else {
2308 token = parse_expression(token, &e1);
2309 token = expect(token, ';', "in 'for'");
2311 token = parse_expression(token, &e2);
2312 token = expect(token, ';', "in 'for'");
2313 token = parse_expression(token, &e3);
2314 token = expect(token, ')', "in 'for'");
2315 token = statement(token, &iterator);
2317 stmt->iterator_syms = syms;
2318 stmt->iterator_pre_statement = make_statement(e1);
2319 stmt->iterator_pre_condition = e2;
2320 stmt->iterator_post_statement = make_statement(e3);
2321 stmt->iterator_post_condition = NULL;
2322 stmt->iterator_statement = iterator;
2323 end_iterator(stmt);
2325 return token;
2328 static struct token *parse_while_statement(struct token *token, struct statement *stmt)
2330 struct expression *expr;
2331 struct statement *iterator;
2333 start_iterator(stmt);
2334 token = parens_expression(token->next, &expr, "after 'while'");
2335 token = statement(token, &iterator);
2337 stmt->iterator_pre_condition = expr;
2338 stmt->iterator_post_condition = NULL;
2339 stmt->iterator_statement = iterator;
2340 end_iterator(stmt);
2342 return token;
2345 static struct token *parse_do_statement(struct token *token, struct statement *stmt)
2347 struct expression *expr;
2348 struct statement *iterator;
2350 start_iterator(stmt);
2351 token = statement(token->next, &iterator);
2352 if (token_type(token) == TOKEN_IDENT && token->ident == &while_ident)
2353 token = token->next;
2354 else
2355 sparse_error(token->pos, "expected 'while' after 'do'");
2356 token = parens_expression(token, &expr, "after 'do-while'");
2358 stmt->iterator_post_condition = expr;
2359 stmt->iterator_statement = iterator;
2360 end_iterator(stmt);
2362 if (iterator && iterator->type != STMT_COMPOUND && Wdo_while)
2363 warning(iterator->pos, "do-while statement is not a compound statement");
2365 return expect(token, ';', "after statement");
2368 static struct token *parse_if_statement(struct token *token, struct statement *stmt)
2370 stmt->type = STMT_IF;
2371 token = parens_expression(token->next, &stmt->if_conditional, "after if");
2372 token = statement(token, &stmt->if_true);
2373 if (token_type(token) != TOKEN_IDENT)
2374 return token;
2375 if (token->ident != &else_ident)
2376 return token;
2377 return statement(token->next, &stmt->if_false);
2380 static inline struct token *case_statement(struct token *token, struct statement *stmt)
2382 stmt->type = STMT_CASE;
2383 token = expect(token, ':', "after default/case");
2384 add_case_statement(stmt);
2385 if (match_op(token, '}')) {
2386 warning(token->pos, "statement expected after case label");
2387 stmt->case_statement = alloc_statement(token->pos, STMT_NONE);
2388 return token;
2390 return statement(token, &stmt->case_statement);
2393 static struct token *parse_case_statement(struct token *token, struct statement *stmt)
2395 token = parse_expression(token->next, &stmt->case_expression);
2396 if (match_op(token, SPECIAL_ELLIPSIS))
2397 token = parse_expression(token->next, &stmt->case_to);
2398 return case_statement(token, stmt);
2401 static struct token *parse_default_statement(struct token *token, struct statement *stmt)
2403 return case_statement(token->next, stmt);
2406 static struct token *parse_loop_iterator(struct token *token, struct statement *stmt)
2408 struct symbol *target = lookup_symbol(token->ident, NS_ITERATOR);
2409 stmt->type = STMT_GOTO;
2410 stmt->goto_label = target;
2411 if (!target)
2412 sparse_error(stmt->pos, "break/continue not in iterator scope");
2413 return expect(token->next, ';', "at end of statement");
2416 static struct token *parse_switch_statement(struct token *token, struct statement *stmt)
2418 stmt->type = STMT_SWITCH;
2419 start_switch(stmt);
2420 token = parens_expression(token->next, &stmt->switch_expression, "after 'switch'");
2421 token = statement(token, &stmt->switch_statement);
2422 end_switch(stmt);
2423 return token;
2426 static void warn_label_usage(struct position def, struct position use, struct ident *ident)
2428 const char *id = show_ident(ident);
2429 sparse_error(use, "label '%s' used outside statement expression", id);
2430 info(def, " label '%s' defined here", id);
2431 current_fn->bogus_linear = 1;
2434 void check_label_usage(struct symbol *label, struct position use_pos)
2436 struct statement *def = label->stmt;
2438 if (def) {
2439 if (!is_in_scope(def->label_scope, label_scope))
2440 warn_label_usage(def->pos, use_pos, label->ident);
2441 } else if (!label->label_scope) {
2442 label->label_scope = label_scope;
2443 label->label_pos = use_pos;
2447 static struct token *parse_goto_statement(struct token *token, struct statement *stmt)
2449 stmt->type = STMT_GOTO;
2450 token = token->next;
2451 if (match_op(token, '*')) {
2452 token = parse_expression(token->next, &stmt->goto_expression);
2453 add_statement(&function_computed_goto_list, stmt);
2454 } else if (token_type(token) == TOKEN_IDENT) {
2455 struct symbol *label = label_symbol(token, 1);
2456 stmt->goto_label = label;
2457 check_label_usage(label, stmt->pos);
2458 token = token->next;
2459 } else {
2460 sparse_error(token->pos, "Expected identifier or goto expression");
2462 return expect(token, ';', "at end of statement");
2465 static struct token *parse_context_statement(struct token *token, struct statement *stmt)
2467 stmt->type = STMT_CONTEXT;
2468 token = token->next;
2469 token = expect(token, '(', "after __context__ statement");
2470 token = assignment_expression(token, &stmt->expression);
2471 if (!stmt->expression)
2472 unexpected(token, "expression expected after '('");
2473 if (match_op(token, ',')) {
2474 token = token->next;
2475 stmt->context = stmt->expression;
2476 token = assignment_expression(token, &stmt->expression);
2477 if (!stmt->expression)
2478 unexpected(token, "expression expected after ','");
2480 token = expect(token, ')', "at end of __context__ statement");
2481 return expect(token, ';', "at end of statement");
2484 static struct token *parse_range_statement(struct token *token, struct statement *stmt)
2486 stmt->type = STMT_RANGE;
2487 token = token->next;
2488 token = expect(token, '(', "after __range__ statement");
2489 token = assignment_expression(token, &stmt->range_expression);
2490 token = expect(token, ',', "after range expression");
2491 token = assignment_expression(token, &stmt->range_low);
2492 token = expect(token, ',', "after low range");
2493 token = assignment_expression(token, &stmt->range_high);
2494 token = expect(token, ')', "after range statement");
2495 return expect(token, ';', "after range statement");
2498 static struct token *handle_label_attributes(struct token *token, struct symbol *label)
2500 struct decl_state ctx = { };
2502 token = handle_attributes(token, &ctx);
2503 label->label_modifiers = ctx.ctype.modifiers;
2504 return token;
2507 static struct token *statement(struct token *token, struct statement **tree)
2509 struct statement *stmt = alloc_statement(token->pos, STMT_NONE);
2511 *tree = stmt;
2512 if (token_type(token) == TOKEN_IDENT) {
2513 struct symbol *s = lookup_keyword(token->ident, NS_KEYWORD);
2514 if (s && s->op->statement)
2515 return s->op->statement(token, stmt);
2517 if (match_op(token->next, ':')) {
2518 struct symbol *s = label_symbol(token, 0);
2519 token = handle_label_attributes(token->next->next, s);
2520 if (s->stmt) {
2521 sparse_error(stmt->pos, "label '%s' redefined", show_ident(s->ident));
2522 // skip the label to avoid multiple definitions
2523 return statement(token, tree);
2525 stmt->type = STMT_LABEL;
2526 stmt->label_identifier = s;
2527 stmt->label_scope = label_scope;
2528 if (s->label_scope) {
2529 if (!is_in_scope(label_scope, s->label_scope))
2530 warn_label_usage(stmt->pos, s->label_pos, s->ident);
2532 s->stmt = stmt;
2533 if (match_op(token, '}')) {
2534 warning(token->pos, "statement expected after label");
2535 stmt->label_statement = alloc_statement(token->pos, STMT_NONE);
2536 return token;
2538 return statement(token, &stmt->label_statement);
2542 if (match_op(token, '{')) {
2543 token = compound_statement(token->next, stmt);
2544 return expect(token, '}', "at end of compound statement");
2547 stmt->type = STMT_EXPRESSION;
2548 return expression_statement(token, &stmt->expression);
2551 /* gcc extension - __label__ ident-list; in the beginning of compound stmt */
2552 static struct token *label_statement(struct token *token)
2554 while (token_type(token) == TOKEN_IDENT) {
2555 struct symbol *sym = alloc_symbol(token->pos, SYM_LABEL);
2556 /* it's block-scope, but we want label namespace */
2557 bind_symbol_with_scope(sym, token->ident, NS_LABEL, block_scope);
2558 fn_local_symbol(sym);
2559 token = token->next;
2560 if (!match_op(token, ','))
2561 break;
2562 token = token->next;
2564 return expect(token, ';', "at end of label declaration");
2567 static struct token * statement_list(struct token *token, struct statement_list **list)
2569 int seen_statement = 0;
2570 while (token_type(token) == TOKEN_IDENT &&
2571 token->ident == &__label___ident)
2572 token = label_statement(token->next);
2573 for (;;) {
2574 struct statement * stmt;
2575 if (eof_token(token))
2576 break;
2577 if (match_op(token, '}'))
2578 break;
2579 if (match_ident(token, &_Static_assert_ident)) {
2580 token = parse_static_assert(token, NULL);
2581 continue;
2583 if (lookup_type(token)) {
2584 if (seen_statement) {
2585 warning(token->pos, "mixing declarations and code");
2586 seen_statement = 0;
2588 stmt = alloc_statement(token->pos, STMT_DECLARATION);
2589 token = external_declaration(token, &stmt->declaration, NULL);
2590 } else {
2591 seen_statement = Wdeclarationafterstatement;
2592 token = statement(token, &stmt);
2594 add_statement(list, stmt);
2596 return token;
2599 static struct token *identifier_list(struct token *token, struct symbol *fn)
2601 struct symbol_list **list = &fn->arguments;
2602 for (;;) {
2603 struct symbol *sym = alloc_symbol(token->pos, SYM_NODE);
2604 sym->ident = token->ident;
2605 token = token->next;
2606 sym->endpos = token->pos;
2607 sym->ctype.base_type = &incomplete_ctype;
2608 add_symbol(list, sym);
2609 if (!match_op(token, ',') ||
2610 token_type(token->next) != TOKEN_IDENT ||
2611 lookup_type(token->next))
2612 break;
2613 token = token->next;
2615 return token;
2618 static struct token *parameter_type_list(struct token *token, struct symbol *fn)
2620 struct symbol_list **list = &fn->arguments;
2622 for (;;) {
2623 struct symbol *sym;
2625 if (match_op(token, SPECIAL_ELLIPSIS)) {
2626 fn->variadic = 1;
2627 token = token->next;
2628 break;
2631 sym = alloc_symbol(token->pos, SYM_NODE);
2632 token = parameter_declaration(token, sym);
2633 if (sym->ctype.base_type == &void_ctype) {
2634 /* Special case: (void) */
2635 if (!*list && !sym->ident)
2636 break;
2637 warning(token->pos, "void parameter");
2639 add_symbol(list, sym);
2640 if (!match_op(token, ','))
2641 break;
2642 token = token->next;
2644 return token;
2647 struct token *compound_statement(struct token *token, struct statement *stmt)
2649 stmt->type = STMT_COMPOUND;
2650 start_block_scope(token->pos);
2651 token = statement_list(token, &stmt->stmts);
2652 end_block_scope();
2653 return token;
2656 static struct expression *identifier_expression(struct token *token)
2658 struct expression *expr = alloc_expression(token->pos, EXPR_IDENTIFIER);
2659 expr->expr_ident = token->ident;
2660 return expr;
2663 static struct expression *index_expression(struct expression *from, struct expression *to)
2665 int idx_from, idx_to;
2666 struct expression *expr = alloc_expression(from->pos, EXPR_INDEX);
2668 idx_from = const_expression_value(from);
2669 idx_to = idx_from;
2670 if (to) {
2671 idx_to = const_expression_value(to);
2672 if (idx_to < idx_from || idx_from < 0)
2673 warning(from->pos, "nonsense array initializer index range");
2675 expr->idx_from = idx_from;
2676 expr->idx_to = idx_to;
2677 return expr;
2680 static struct token *single_initializer(struct expression **ep, struct token *token)
2682 int expect_equal = 0;
2683 struct token *next = token->next;
2684 struct expression **tail = ep;
2685 int nested;
2687 *ep = NULL;
2689 if ((token_type(token) == TOKEN_IDENT) && match_op(next, ':')) {
2690 struct expression *expr = identifier_expression(token);
2691 if (Wold_initializer)
2692 warning(token->pos, "obsolete struct initializer, use C99 syntax");
2693 token = initializer(&expr->ident_expression, next->next);
2694 if (expr->ident_expression)
2695 *ep = expr;
2696 return token;
2699 for (tail = ep, nested = 0; ; nested++, next = token->next) {
2700 if (match_op(token, '.') && (token_type(next) == TOKEN_IDENT)) {
2701 struct expression *expr = identifier_expression(next);
2702 *tail = expr;
2703 tail = &expr->ident_expression;
2704 expect_equal = 1;
2705 token = next->next;
2706 } else if (match_op(token, '[')) {
2707 struct expression *from = NULL, *to = NULL, *expr;
2708 token = constant_expression(token->next, &from);
2709 if (!from) {
2710 sparse_error(token->pos, "Expected constant expression");
2711 break;
2713 if (match_op(token, SPECIAL_ELLIPSIS))
2714 token = constant_expression(token->next, &to);
2715 expr = index_expression(from, to);
2716 *tail = expr;
2717 tail = &expr->idx_expression;
2718 token = expect(token, ']', "at end of initializer index");
2719 if (nested)
2720 expect_equal = 1;
2721 } else {
2722 break;
2725 if (nested && !expect_equal) {
2726 if (!match_op(token, '='))
2727 warning(token->pos, "obsolete array initializer, use C99 syntax");
2728 else
2729 expect_equal = 1;
2731 if (expect_equal)
2732 token = expect(token, '=', "at end of initializer index");
2734 token = initializer(tail, token);
2735 if (!*tail)
2736 *ep = NULL;
2737 return token;
2740 static struct token *initializer_list(struct expression_list **list, struct token *token)
2742 struct expression *expr;
2744 for (;;) {
2745 token = single_initializer(&expr, token);
2746 if (!expr)
2747 break;
2748 add_expression(list, expr);
2749 if (!match_op(token, ','))
2750 break;
2751 token = token->next;
2753 return token;
2756 struct token *initializer(struct expression **tree, struct token *token)
2758 if (match_op(token, '{')) {
2759 struct expression *expr = alloc_expression(token->pos, EXPR_INITIALIZER);
2760 *tree = expr;
2761 if (!Wuniversal_initializer) {
2762 struct token *next = token->next;
2763 // '{ 0 }' is equivalent to '{ }' except for some
2764 // warnings, like using 0 to initialize a null-pointer.
2765 if (match_token_zero(next)) {
2766 if (match_op(next->next, '}'))
2767 expr->zero_init = 1;
2771 token = initializer_list(&expr->expr_list, token->next);
2772 return expect(token, '}', "at end of initializer");
2774 return assignment_expression(token, tree);
2777 static void declare_argument(struct symbol *sym, struct symbol *fn)
2779 if (!sym->ident) {
2780 sparse_error(sym->pos, "no identifier for function argument");
2781 return;
2783 if (sym->ctype.base_type == &incomplete_ctype) {
2784 sym->ctype.base_type = &int_ctype;
2786 if (Wimplicit_int) {
2787 sparse_error(sym->pos, "missing type declaration for parameter '%s'",
2788 show_ident(sym->ident));
2791 bind_symbol(sym, sym->ident, NS_SYMBOL);
2794 static int is_syscall(struct symbol *sym)
2796 char *macro;
2797 char *name;
2798 int is_syscall = 0;
2800 macro = get_macro_name(sym->pos);
2801 if (macro &&
2802 (strncmp("SYSCALL_DEFINE", macro, strlen("SYSCALL_DEFINE")) == 0 ||
2803 strncmp("COMPAT_SYSCALL_DEFINE", macro, strlen("COMPAT_SYSCALL_DEFINE")) == 0))
2804 is_syscall = 1;
2806 name = sym->ident->name;
2808 if (name && strncmp(name, "sys_", 4) ==0)
2809 is_syscall = 1;
2811 if (name && strncmp(name, "compat_sys_", 11) == 0)
2812 is_syscall = 1;
2814 return is_syscall;
2818 static struct token *parse_function_body(struct token *token, struct symbol *decl,
2819 struct symbol_list **list)
2821 struct symbol_list **old_symbol_list;
2822 struct symbol *base_type = decl->ctype.base_type;
2823 struct statement *stmt, **p;
2824 struct symbol *prev;
2825 struct symbol *arg;
2827 old_symbol_list = function_symbol_list;
2828 if (decl->ctype.modifiers & MOD_INLINE) {
2829 function_symbol_list = &decl->inline_symbol_list;
2830 p = &base_type->inline_stmt;
2831 } else {
2832 function_symbol_list = &decl->symbol_list;
2833 p = &base_type->stmt;
2835 function_computed_target_list = NULL;
2836 function_computed_goto_list = NULL;
2838 if ((decl->ctype.modifiers & (MOD_EXTERN|MOD_INLINE)) == MOD_EXTERN) {
2839 if (Wexternal_function_has_definition)
2840 warning(decl->pos, "function '%s' with external linkage has definition", show_ident(decl->ident));
2842 if (!(decl->ctype.modifiers & MOD_STATIC))
2843 decl->ctype.modifiers |= MOD_EXTERN;
2845 stmt = start_function(decl);
2846 *p = stmt;
2848 FOR_EACH_PTR (base_type->arguments, arg) {
2849 declare_argument(arg, base_type);
2850 } END_FOR_EACH_PTR(arg);
2852 token = statement_list(token->next, &stmt->stmts);
2853 end_function(decl);
2855 if (!(decl->ctype.modifiers & MOD_INLINE))
2856 add_symbol(list, decl);
2857 else if (is_syscall(decl)) {
2858 add_symbol(list, decl);
2860 printf("parse.c decl: %s\n", decl->ident->name);
2861 char *macro = get_macro_name(decl->pos);
2862 printf("decl macro: %s\n", macro);
2865 check_declaration(decl);
2866 decl->definition = decl;
2867 prev = decl->same_symbol;
2868 if (prev && prev->definition) {
2869 warning(decl->pos, "multiple definitions for function '%s'",
2870 show_ident(decl->ident));
2871 info(prev->definition->pos, " the previous one is here");
2872 } else {
2873 while (prev) {
2874 rebind_scope(prev, decl->scope);
2875 prev->definition = decl;
2876 prev = prev->same_symbol;
2879 function_symbol_list = old_symbol_list;
2880 if (function_computed_goto_list) {
2881 if (!function_computed_target_list)
2882 warning(decl->pos, "function '%s' has computed goto but no targets?", show_ident(decl->ident));
2883 else {
2884 FOR_EACH_PTR(function_computed_goto_list, stmt) {
2885 stmt->target_list = function_computed_target_list;
2886 } END_FOR_EACH_PTR(stmt);
2889 return expect(token, '}', "at end of function");
2892 static void promote_k_r_types(struct symbol *arg)
2894 struct symbol *base = arg->ctype.base_type;
2895 if (base && base->ctype.base_type == &int_type && base->rank < 0) {
2896 arg->ctype.base_type = &int_ctype;
2900 static void apply_k_r_types(struct symbol_list *argtypes, struct symbol *fn)
2902 struct symbol_list *real_args = fn->ctype.base_type->arguments;
2903 struct symbol *arg;
2905 FOR_EACH_PTR(real_args, arg) {
2906 struct symbol *type;
2908 /* This is quadratic in the number of arguments. We _really_ don't care */
2909 FOR_EACH_PTR(argtypes, type) {
2910 if (type->ident == arg->ident)
2911 goto match;
2912 } END_FOR_EACH_PTR(type);
2913 if (Wimplicit_int) {
2914 warning(arg->pos, "missing type declaration for parameter '%s'",
2915 show_ident(arg->ident));
2917 type = alloc_symbol(arg->pos, SYM_NODE);
2918 type->ident = arg->ident;
2919 type->ctype.base_type = &int_ctype;
2920 match:
2921 type->used = 1;
2922 /* "char" and "short" promote to "int" */
2923 promote_k_r_types(type);
2925 arg->ctype = type->ctype;
2926 } END_FOR_EACH_PTR(arg);
2928 FOR_EACH_PTR(argtypes, arg) {
2929 if (!arg->used)
2930 warning(arg->pos, "nonsensical parameter declaration '%s'", show_ident(arg->ident));
2931 } END_FOR_EACH_PTR(arg);
2935 static struct token *parse_k_r_arguments(struct token *token, struct symbol *decl,
2936 struct symbol_list **list)
2938 struct symbol_list *args = NULL;
2940 if (Wold_style_definition)
2941 warning(token->pos, "non-ANSI definition of function '%s'", show_ident(decl->ident));
2943 do {
2944 token = declaration_list(token, &args);
2945 if (!match_op(token, ';')) {
2946 sparse_error(token->pos, "expected ';' at end of parameter declaration");
2947 break;
2949 token = token->next;
2950 } while (lookup_type(token));
2952 apply_k_r_types(args, decl);
2954 if (!match_op(token, '{')) {
2955 sparse_error(token->pos, "expected function body");
2956 return token;
2958 return parse_function_body(token, decl, list);
2961 static struct token *toplevel_asm_declaration(struct token *token, struct symbol_list **list)
2963 struct symbol *anon = alloc_symbol(token->pos, SYM_NODE);
2964 struct symbol *fn = alloc_symbol(token->pos, SYM_FN);
2965 struct statement *stmt;
2967 anon->ctype.base_type = fn;
2968 stmt = alloc_statement(token->pos, STMT_NONE);
2969 fn->stmt = stmt;
2971 token = parse_asm_statement(token, stmt);
2973 // FIXME: add_symbol(list, anon);
2974 return token;
2977 struct token *external_declaration(struct token *token, struct symbol_list **list,
2978 validate_decl_t validate_decl)
2980 struct ident *ident = NULL;
2981 struct symbol *decl;
2982 struct decl_state ctx = { .ident = &ident };
2983 struct ctype saved;
2984 struct symbol *base_type;
2985 unsigned long mod;
2986 int is_typedef;
2988 if (match_ident(token, &_Pragma_ident))
2989 return parse_underscore_Pragma(token);
2991 /* Top-level inline asm or static assertion? */
2992 if (token_type(token) == TOKEN_IDENT) {
2993 struct symbol *s = lookup_keyword(token->ident, NS_KEYWORD);
2994 if (s && s->op->toplevel)
2995 return s->op->toplevel(token, list);
2998 /* Parse declaration-specifiers, if any */
2999 token = declaration_specifiers(token, &ctx);
3000 mod = decl_modifiers(&ctx);
3001 decl = alloc_symbol(token->pos, SYM_NODE);
3002 /* Just a type declaration? */
3003 if (match_op(token, ';')) {
3004 apply_modifiers(token->pos, &ctx);
3005 return token->next;
3008 saved = ctx.ctype;
3009 token = declarator(token, &ctx);
3010 token = handle_asm_name(token, &ctx);
3011 token = handle_attributes(token, &ctx);
3012 apply_modifiers(token->pos, &ctx);
3014 decl->ctype = ctx.ctype;
3015 decl->ctype.modifiers |= mod;
3016 decl->cleanup = ctx.cleanup;
3017 decl->endpos = token->pos;
3019 /* Just a type declaration? */
3020 if (!ident) {
3021 warning(token->pos, "missing identifier in declaration");
3022 return expect(token, ';', "at the end of type declaration");
3025 /* type define declaration? */
3026 is_typedef = ctx.storage_class == MOD_USERTYPE;
3028 /* Typedefs don't have meaningful storage */
3029 if (is_typedef)
3030 decl->ctype.modifiers |= MOD_USERTYPE;
3032 bind_symbol(decl, ident, is_typedef ? NS_TYPEDEF: NS_SYMBOL);
3034 base_type = decl->ctype.base_type;
3036 if (is_typedef) {
3037 if (base_type && !base_type->ident) {
3038 switch (base_type->type) {
3039 case SYM_STRUCT:
3040 case SYM_UNION:
3041 case SYM_ENUM:
3042 case SYM_RESTRICT:
3043 base_type->ident = ident;
3044 break;
3045 default:
3046 break;
3049 } else if (base_type && base_type->type == SYM_FN) {
3050 if (base_type->ctype.base_type == &autotype_ctype) {
3051 sparse_error(decl->pos, "'%s()' has __auto_type return type",
3052 show_ident(decl->ident));
3053 base_type->ctype.base_type = &int_ctype;
3055 if (base_type->ctype.base_type == &incomplete_ctype) {
3056 warning(decl->pos, "'%s()' has implicit return type",
3057 show_ident(decl->ident));
3058 base_type->ctype.base_type = &int_ctype;
3060 /* apply attributes placed after the declarator */
3061 decl->ctype.modifiers |= ctx.f_modifiers;
3063 /* K&R argument declaration? */
3064 if (lookup_type(token))
3065 return parse_k_r_arguments(token, decl, list);
3066 if (match_op(token, '{'))
3067 return parse_function_body(token, decl, list);
3069 if (!(decl->ctype.modifiers & MOD_STATIC))
3070 decl->ctype.modifiers |= MOD_EXTERN;
3071 } else if (base_type == &void_ctype && !(decl->ctype.modifiers & MOD_EXTERN)) {
3072 sparse_error(token->pos, "void declaration");
3074 if (base_type == &incomplete_ctype) {
3075 warning(decl->pos, "'%s' has implicit type", show_ident(decl->ident));
3076 decl->ctype.base_type = &int_ctype;;
3079 for (;;) {
3080 if (!is_typedef && match_op(token, '=')) {
3081 struct token *next = token->next;
3082 token = initializer(&decl->initializer, next);
3083 if (token == next)
3084 sparse_error(token->pos, "expression expected before '%s'", show_token(token));
3086 if (!is_typedef) {
3087 if (validate_decl)
3088 validate_decl(decl);
3090 if (decl->initializer && decl->ctype.modifiers & MOD_EXTERN) {
3091 warning(decl->pos, "symbol with external linkage has initializer");
3092 decl->ctype.modifiers &= ~MOD_EXTERN;
3095 if (!(decl->ctype.modifiers & (MOD_EXTERN | MOD_INLINE))) {
3096 add_symbol(list, decl);
3097 fn_local_symbol(decl);
3100 check_declaration(decl);
3101 if (decl->same_symbol) {
3102 decl->definition = decl->same_symbol->definition;
3103 decl->op = decl->same_symbol->op;
3104 if (is_typedef) {
3105 // TODO: handle -std=c89 --pedantic
3106 check_duplicates(decl);
3110 if (ctx.autotype) {
3111 const char *msg = NULL;
3112 if (decl->ctype.base_type != &autotype_ctype)
3113 msg = "on non-identifier";
3114 else if (match_op(token, ','))
3115 msg = "on declaration list";
3116 else if (!decl->initializer)
3117 msg = "without initializer";
3118 else if (decl->initializer->type == EXPR_SYMBOL &&
3119 decl->initializer->symbol == decl)
3120 msg = "on self-init var";
3121 if (msg) {
3122 sparse_error(decl->pos, "__auto_type %s", msg);
3123 decl->ctype.base_type = &bad_ctype;
3127 if (!match_op(token, ','))
3128 break;
3130 token = token->next;
3131 ident = NULL;
3132 decl = alloc_symbol(token->pos, SYM_NODE);
3133 ctx.ctype = saved;
3134 ctx.cleanup = NULL;
3135 token = handle_attributes(token, &ctx);
3136 token = declarator(token, &ctx);
3137 token = handle_asm_name(token, &ctx);
3138 token = handle_attributes(token, &ctx);
3139 apply_modifiers(token->pos, &ctx);
3140 decl->ctype = ctx.ctype;
3141 decl->ctype.modifiers |= mod;
3142 decl->cleanup = ctx.cleanup;
3143 decl->endpos = token->pos;
3144 if (!ident) {
3145 sparse_error(token->pos, "expected identifier name in type definition");
3146 return token;
3149 if (is_typedef)
3150 decl->ctype.modifiers |= MOD_USERTYPE;
3152 bind_symbol(decl, ident, is_typedef ? NS_TYPEDEF: NS_SYMBOL);
3154 /* Function declarations are automatically extern unless specifically static */
3155 base_type = decl->ctype.base_type;
3156 if (!is_typedef && base_type && base_type->type == SYM_FN) {
3157 if (!(decl->ctype.modifiers & MOD_STATIC))
3158 decl->ctype.modifiers |= MOD_EXTERN;
3161 return expect(token, ';', "at end of declaration");