buf_size: big ugly sync with released sources
[smatch.git] / parse.c
blob3e801134b0913b36fd86bce55cb7066043eac088
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);
78 typedef struct token *attr_t(struct token *, struct symbol *,
79 struct decl_state *);
81 static attr_t
82 attribute_packed, attribute_aligned, attribute_cleanup,
83 attribute_modifier,
84 attribute_function,
85 attribute_bitwise,
86 attribute_address_space, attribute_context,
87 attribute_designated_init,
88 attribute_transparent_union, ignore_attribute,
89 attribute_mode, attribute_force;
91 typedef struct symbol *to_mode_t(struct symbol *);
93 static to_mode_t
94 to_QI_mode, to_HI_mode, to_SI_mode, to_DI_mode, to_TI_mode;
95 static to_mode_t to_pointer_mode, to_word_mode;
97 enum {
98 Set_T = 1,
99 Set_S = 2,
100 Set_Char = 4,
101 Set_Int = 8,
102 Set_Double = 16,
103 Set_Float = 32,
104 Set_Signed = 64,
105 Set_Unsigned = 128,
106 Set_Short = 256,
107 Set_Long = 512,
108 Set_Vlong = 1024,
109 Set_Int128 = 2048,
110 Set_Any = Set_T | Set_Short | Set_Long | Set_Signed | Set_Unsigned
113 enum {
114 CInt = 0, CSInt, CUInt, CReal,
117 static void asm_modifier(struct token *token, unsigned long *mods, unsigned long mod)
119 if (*mods & mod)
120 warning(token->pos, "duplicated asm modifier");
121 *mods |= mod;
124 static struct symbol_op typedef_op = {
125 .type = KW_MODIFIER,
126 .declarator = storage_specifier,
129 static struct symbol_op inline_op = {
130 .type = KW_MODIFIER,
131 .declarator = generic_qualifier,
132 .asm_modifier = asm_modifier,
135 static struct symbol_op noreturn_op = {
136 .type = KW_MODIFIER,
137 .declarator = generic_qualifier,
140 static declarator_t alignas_specifier;
141 static struct symbol_op alignas_op = {
142 .type = KW_MODIFIER,
143 .declarator = alignas_specifier,
146 static struct symbol_op auto_op = {
147 .type = KW_MODIFIER,
148 .declarator = storage_specifier,
151 static struct symbol_op register_op = {
152 .type = KW_MODIFIER,
153 .declarator = storage_specifier,
156 static struct symbol_op static_op = {
157 .type = KW_MODIFIER|KW_STATIC,
158 .declarator = storage_specifier,
161 static struct symbol_op extern_op = {
162 .type = KW_MODIFIER,
163 .declarator = storage_specifier,
166 static struct symbol_op thread_op = {
167 .type = KW_MODIFIER,
168 .declarator = thread_specifier,
171 static struct symbol_op const_op = {
172 .type = KW_QUALIFIER,
173 .declarator = generic_qualifier,
176 static struct symbol_op volatile_op = {
177 .type = KW_QUALIFIER,
178 .declarator = generic_qualifier,
179 .asm_modifier = asm_modifier,
182 static struct symbol_op restrict_op = {
183 .type = KW_QUALIFIER,
184 .declarator = generic_qualifier,
187 static struct symbol_op atomic_op = {
188 .type = KW_QUALIFIER,
189 .declarator = generic_qualifier,
192 static struct symbol_op typeof_op = {
193 .type = KW_SPECIFIER,
194 .declarator = typeof_specifier,
195 .test = Set_Any,
196 .set = Set_S|Set_T,
199 static struct symbol_op autotype_op = {
200 .type = KW_SPECIFIER,
201 .declarator = autotype_specifier,
202 .test = Set_Any,
203 .set = Set_S|Set_T,
206 static struct symbol_op attribute_op = {
207 .type = KW_ATTRIBUTE,
208 .declarator = attribute_specifier,
211 static struct symbol_op struct_op = {
212 .type = KW_SPECIFIER,
213 .declarator = struct_specifier,
214 .test = Set_Any,
215 .set = Set_S|Set_T,
218 static struct symbol_op union_op = {
219 .type = KW_SPECIFIER,
220 .declarator = union_specifier,
221 .test = Set_Any,
222 .set = Set_S|Set_T,
225 static struct symbol_op enum_op = {
226 .type = KW_SPECIFIER,
227 .declarator = enum_specifier,
228 .test = Set_Any,
229 .set = Set_S|Set_T,
232 static struct symbol_op spec_op = {
233 .type = KW_SPECIFIER | KW_EXACT,
234 .test = Set_Any,
235 .set = Set_S|Set_T,
238 static struct symbol_op char_op = {
239 .type = KW_SPECIFIER,
240 .test = Set_T|Set_Long|Set_Short,
241 .set = Set_T|Set_Char,
242 .class = CInt,
245 static struct symbol_op int_op = {
246 .type = KW_SPECIFIER,
247 .test = Set_T,
248 .set = Set_T|Set_Int,
251 static struct symbol_op double_op = {
252 .type = KW_SPECIFIER,
253 .test = Set_T|Set_Signed|Set_Unsigned|Set_Short|Set_Vlong,
254 .set = Set_T|Set_Double,
255 .class = CReal,
258 static struct symbol_op float_op = {
259 .type = KW_SPECIFIER,
260 .test = Set_T|Set_Signed|Set_Unsigned|Set_Short|Set_Long,
261 .set = Set_T|Set_Float,
262 .class = CReal,
265 static struct symbol_op short_op = {
266 .type = KW_SPECIFIER,
267 .test = Set_S|Set_Char|Set_Float|Set_Double|Set_Long|Set_Short,
268 .set = Set_Short,
271 static struct symbol_op signed_op = {
272 .type = KW_SPECIFIER,
273 .test = Set_S|Set_Float|Set_Double|Set_Signed|Set_Unsigned,
274 .set = Set_Signed,
275 .class = CSInt,
278 static struct symbol_op unsigned_op = {
279 .type = KW_SPECIFIER,
280 .test = Set_S|Set_Float|Set_Double|Set_Signed|Set_Unsigned,
281 .set = Set_Unsigned,
282 .class = CUInt,
285 static struct symbol_op long_op = {
286 .type = KW_SPECIFIER,
287 .test = Set_S|Set_Char|Set_Float|Set_Short|Set_Vlong,
288 .set = Set_Long,
291 static struct symbol_op int128_op = {
292 .type = KW_SPECIFIER,
293 .test = Set_S|Set_T|Set_Char|Set_Short|Set_Int|Set_Float|Set_Double|Set_Long|Set_Vlong|Set_Int128,
294 .set = Set_T|Set_Int128|Set_Vlong,
295 .class = CInt,
298 static struct symbol_op if_op = {
299 .statement = parse_if_statement,
302 static struct symbol_op return_op = {
303 .statement = parse_return_statement,
306 static struct symbol_op loop_iter_op = {
307 .statement = parse_loop_iterator,
310 static struct symbol_op default_op = {
311 .statement = parse_default_statement,
314 static struct symbol_op case_op = {
315 .statement = parse_case_statement,
318 static struct symbol_op switch_op = {
319 .statement = parse_switch_statement,
322 static struct symbol_op for_op = {
323 .statement = parse_for_statement,
326 static struct symbol_op while_op = {
327 .statement = parse_while_statement,
330 static struct symbol_op do_op = {
331 .statement = parse_do_statement,
334 static struct symbol_op goto_op = {
335 .statement = parse_goto_statement,
338 static struct symbol_op __context___op = {
339 .statement = parse_context_statement,
340 .attribute = attribute_context,
343 static struct symbol_op range_op = {
344 .statement = parse_range_statement,
347 static struct symbol_op asm_op = {
348 .type = KW_ASM,
349 .statement = parse_asm_statement,
350 .toplevel = toplevel_asm_declaration,
353 static struct symbol_op static_assert_op = {
354 .toplevel = parse_static_assert,
357 static struct symbol_op packed_op = {
358 .attribute = attribute_packed,
361 static struct symbol_op aligned_op = {
362 .attribute = attribute_aligned,
365 static struct symbol_op cleanup_op = {
366 .attribute = attribute_cleanup,
369 static struct symbol_op attr_mod_op = {
370 .attribute = attribute_modifier,
373 static struct symbol_op attr_fun_op = {
374 .attribute = attribute_function,
377 static struct symbol_op attr_bitwise_op = {
378 .attribute = attribute_bitwise,
381 static struct symbol_op attr_force_op = {
382 .attribute = attribute_force,
385 static struct symbol_op address_space_op = {
386 .attribute = attribute_address_space,
389 static struct symbol_op mode_op = {
390 .attribute = attribute_mode,
393 static struct symbol_op context_op = {
394 .attribute = attribute_context,
397 static struct symbol_op designated_init_op = {
398 .attribute = attribute_designated_init,
401 static struct symbol_op transparent_union_op = {
402 .attribute = attribute_transparent_union,
405 static struct symbol_op ignore_attr_op = {
406 .attribute = ignore_attribute,
409 static struct symbol_op mode_QI_op = {
410 .type = KW_MODE,
411 .to_mode = to_QI_mode
414 static struct symbol_op mode_HI_op = {
415 .type = KW_MODE,
416 .to_mode = to_HI_mode
419 static struct symbol_op mode_SI_op = {
420 .type = KW_MODE,
421 .to_mode = to_SI_mode
424 static struct symbol_op mode_DI_op = {
425 .type = KW_MODE,
426 .to_mode = to_DI_mode
429 static struct symbol_op mode_TI_op = {
430 .type = KW_MODE,
431 .to_mode = to_TI_mode
434 static struct symbol_op mode_pointer_op = {
435 .type = KW_MODE,
436 .to_mode = to_pointer_mode
439 static struct symbol_op mode_word_op = {
440 .type = KW_MODE,
441 .to_mode = to_word_mode
445 * Define the keyword and their effects.
446 * The entries in the 'typedef' and put in NS_TYPEDEF and
447 * are automatically set as reserved keyword while the ones
448 * in the 'keyword' table are just put in NS_KEYWORD.
450 * The entries are added via the 3 macros:
451 * N() for entries with "name" only,
452 * D() for entries with "name" & "__name__",
453 * A() for entries with "name", "__name" & "__name__",
454 * U() for entries with "__name" & "__name__".
456 static struct init_keyword {
457 const char *name;
458 struct symbol_op *op;
459 struct symbol *type;
460 unsigned long mods;
461 } typedefs[] = {
462 #define N(I, O,...) { I, O,##__VA_ARGS__ }
463 #define D(I, O,...) N(I,O,##__VA_ARGS__ ), \
464 N("__" I "__",O,##__VA_ARGS__)
465 #define A(I, O,...) N(I,O,##__VA_ARGS__ ), \
466 N("__" I,O,##__VA_ARGS__), \
467 N("__" I "__",O,##__VA_ARGS__)
468 #define U(I, O,...) N("__" I,O,##__VA_ARGS__), \
469 N("__" I "__",O,##__VA_ARGS__)
470 /* Storage classes */
471 N("auto", &auto_op, .mods = MOD_AUTO),
472 N("register", &register_op, .mods = MOD_REGISTER),
473 N("static", &static_op, .mods = MOD_STATIC),
474 N("extern", &extern_op, .mods = MOD_EXTERN),
475 N("__thread", &thread_op),
476 N("_Thread_local", &thread_op),
478 A("inline", &inline_op, .mods = MOD_INLINE),
480 /* Typedef ... */
481 N("typedef", &typedef_op, .mods = MOD_USERTYPE),
482 A("typeof", &typeof_op),
483 N("__auto_type", &autotype_op),
485 /* Type qualifiers */
486 A("const", &const_op, .mods = MOD_CONST),
487 A("volatile", &volatile_op, .mods = MOD_VOLATILE),
488 A("restrict", &restrict_op, .mods = MOD_RESTRICT),
490 N("_Atomic", &atomic_op, .mods = MOD_ATOMIC),
491 N("_Noreturn", &noreturn_op, .mods = MOD_NORETURN),
492 N("_Alignas", &alignas_op),
494 U("attribute", &attribute_op),
496 /* Type specifiers */
497 N("struct", &struct_op),
498 N("union", &union_op),
499 N("enum", &enum_op),
501 N("void", &spec_op, .type = &void_ctype),
502 N("char", &char_op),
503 N("short", &short_op),
504 N("int", &int_op),
505 N("long", &long_op),
506 N("float", &float_op),
507 N("double", &double_op),
508 A("signed", &signed_op),
509 N("unsigned", &unsigned_op),
510 N("__int128", &int128_op),
511 N("_Bool", &spec_op, .type = &bool_ctype),
513 /* Predeclared types */
514 N("__builtin_va_list", &spec_op, .type = &ptr_ctype),
515 N("__builtin_ms_va_list",&spec_op, .type = &ptr_ctype),
516 N("__int128_t", &spec_op, .type = &sint128_ctype),
517 N("__uint128_t", &spec_op, .type = &uint128_ctype),
518 N("_Float32", &spec_op, .type = &float32_ctype),
519 N("_Float32x", &spec_op, .type = &float32x_ctype),
520 N("_Float64", &spec_op, .type = &float64_ctype),
521 N("_Float64x", &spec_op, .type = &float64x_ctype),
522 N("_Float128", &spec_op, .type = &float128_ctype),
523 N("__float128", &spec_op, .type = &float128_ctype),
524 }, keywords[] = {
525 /* Statements */
526 N("if", &if_op),
527 N("return", &return_op),
528 N("break", &loop_iter_op),
529 N("continue", &loop_iter_op),
530 N("default", &default_op),
531 N("case", &case_op),
532 N("switch", &switch_op),
533 N("for", &for_op),
534 N("while", &while_op),
535 N("do", &do_op),
536 N("goto", &goto_op),
537 A("asm", &asm_op),
538 N("context", &context_op),
539 N("__context__", &__context___op),
540 N("__range__", &range_op),
541 N("_Static_assert", &static_assert_op),
543 /* Attributes */
544 D("packed", &packed_op),
545 D("aligned", &aligned_op),
546 D("__cleanup__", &cleanup_op),
547 D("nocast", &attr_mod_op, .mods = MOD_NOCAST),
548 D("noderef", &attr_mod_op, .mods = MOD_NODEREF),
549 D("safe", &attr_mod_op, .mods = MOD_SAFE),
550 D("unused", &attr_mod_op, .mods = MOD_UNUSED),
551 D("externally_visible", &attr_mod_op, .mods = MOD_EXT_VISIBLE),
552 D("force", &attr_force_op),
553 D("bitwise", &attr_bitwise_op, .mods = MOD_BITWISE),
554 D("address_space", &address_space_op),
555 D("designated_init", &designated_init_op),
556 D("transparent_union", &transparent_union_op),
557 D("noreturn", &attr_fun_op, .mods = MOD_NORETURN),
558 D("pure", &attr_fun_op, .mods = MOD_PURE),
559 A("const", &attr_fun_op, .mods = MOD_PURE),
560 D("gnu_inline", &attr_fun_op, .mods = MOD_GNU_INLINE),
562 /* Modes */
563 D("mode", &mode_op),
564 D("QI", &mode_QI_op),
565 D("HI", &mode_HI_op),
566 D("SI", &mode_SI_op),
567 D("DI", &mode_DI_op),
568 D("TI", &mode_TI_op),
569 D("byte", &mode_QI_op),
570 D("pointer", &mode_pointer_op),
571 D("word", &mode_word_op),
575 static const char *ignored_attributes[] = {
577 #define GCC_ATTR(x) \
578 STRINGIFY(x), \
579 STRINGIFY(__##x##__),
581 #include "gcc-attr-list.h"
583 #undef GCC_ATTR
585 "bounded",
586 "__bounded__",
587 "__noclone",
588 "__nonnull",
589 "__nothrow",
593 static void init_keyword(int stream, struct init_keyword *kw, enum namespace ns)
595 struct symbol *sym = create_symbol(stream, kw->name, SYM_KEYWORD, ns);
596 sym->ident->keyword = 1;
597 sym->ident->reserved |= (ns == NS_TYPEDEF);
598 sym->ctype.modifiers = kw->mods;
599 sym->ctype.base_type = kw->type;
600 sym->op = kw->op;
603 void init_parser(int stream)
605 int i;
607 for (i = 0; i < ARRAY_SIZE(typedefs); i++)
608 init_keyword(stream, &typedefs[i], NS_TYPEDEF);
609 for (i = 0; i < ARRAY_SIZE(keywords); i++)
610 init_keyword(stream, &keywords[i], NS_KEYWORD);
612 for (i = 0; i < ARRAY_SIZE(ignored_attributes); i++) {
613 const char * name = ignored_attributes[i];
614 struct symbol *sym = create_symbol(stream, name, SYM_KEYWORD,
615 NS_KEYWORD);
616 if (!sym->op) {
617 sym->ident->keyword = 1;
618 sym->op = &ignore_attr_op;
624 static struct token *skip_to(struct token *token, int op)
626 while (!match_op(token, op) && !eof_token(token))
627 token = token->next;
628 return token;
631 static struct token bad_token = { .pos.type = TOKEN_BAD };
632 struct token *expect(struct token *token, int op, const char *where)
634 if (!match_op(token, op)) {
635 if (token != &bad_token) {
636 bad_token.next = token;
637 sparse_error(token->pos, "Expected %s %s", show_special(op), where);
638 sparse_error(token->pos, "got %s", show_token(token));
640 if (op == ';')
641 return skip_to(token, op);
642 return &bad_token;
644 return token->next;
648 // issue an error message on new parsing errors
649 // @token: the current token
650 // @errmsg: the error message
651 // If the current token is from a previous error, an error message
652 // has already been issued, so nothing more is done.
653 // Otherwise, @errmsg is displayed followed by the current token.
654 static void unexpected(struct token *token, const char *errmsg)
656 if (token == &bad_token)
657 return;
658 sparse_error(token->pos, "%s", errmsg);
659 sparse_error(token->pos, "got %s", show_token(token));
662 // Add a symbol to the list of function-local symbols
663 static void fn_local_symbol(struct symbol *sym)
665 if (function_symbol_list)
666 add_symbol(function_symbol_list, sym);
669 struct statement *alloc_statement(struct position pos, int type)
671 struct statement *stmt = __alloc_statement(0);
672 stmt->type = type;
673 stmt->pos = pos;
674 return stmt;
677 static struct token *struct_declaration_list(struct token *token, struct symbol_list **list);
679 static void apply_ctype(struct position pos, struct ctype *dst, struct ctype *src);
681 static void apply_modifiers(struct position pos, struct decl_state *ctx)
683 struct symbol *ctype;
684 if (!ctx->mode)
685 return;
686 ctype = ctx->mode->to_mode(ctx->ctype.base_type);
687 if (!ctype)
688 sparse_error(pos, "don't know how to apply mode to %s",
689 show_typename(ctx->ctype.base_type));
690 else
691 ctx->ctype.base_type = ctype;
695 static struct symbol * alloc_indirect_symbol(struct position pos, struct ctype *ctype, int type)
697 struct symbol *sym = alloc_symbol(pos, type);
699 sym->ctype.base_type = ctype->base_type;
700 sym->ctype.modifiers = ctype->modifiers;
702 ctype->base_type = sym;
703 ctype->modifiers = 0;
704 return sym;
708 * NOTE! NS_LABEL is not just a different namespace,
709 * it also ends up using function scope instead of the
710 * regular symbol scope.
712 struct symbol *label_symbol(struct token *token, int used)
714 struct symbol *sym = lookup_symbol(token->ident, NS_LABEL);
715 if (!sym) {
716 sym = alloc_symbol(token->pos, SYM_LABEL);
717 bind_symbol(sym, token->ident, NS_LABEL);
718 if (used)
719 sym->used = 1;
720 fn_local_symbol(sym);
722 return sym;
725 static struct token *struct_union_enum_specifier(enum type type,
726 struct token *token, struct decl_state *ctx,
727 struct token *(*parse)(struct token *, struct symbol *))
729 struct decl_state attr = { };
730 struct symbol *sym;
731 struct position *repos;
733 token = handle_attributes(token, &attr);
734 if (token_type(token) == TOKEN_IDENT) {
735 sym = lookup_symbol(token->ident, NS_STRUCT);
736 if (!sym ||
737 (is_outer_scope(sym->scope) &&
738 (match_op(token->next,';') || match_op(token->next,'{')))) {
739 // Either a new symbol, or else an out-of-scope
740 // symbol being redefined.
741 sym = alloc_symbol(token->pos, type);
742 bind_symbol(sym, token->ident, NS_STRUCT);
744 if (sym->type != type)
745 error_die(token->pos, "invalid tag applied to %s", show_typename (sym));
746 ctx->ctype.base_type = sym;
747 repos = &token->pos;
748 token = token->next;
749 if (!match_op(token, '{'))
750 return token;
752 // The following test is actually wrong for empty
753 // structs, but (1) they are not C99, (2) gcc does
754 // the same thing, and (3) it's easier.
755 if (sym->symbol_list)
756 error_die(token->pos, "redefinition of %s", show_typename (sym));
757 sym->pos = *repos;
759 // Mark the structure as needing re-examination
760 sym->examined = 0;
761 } else if (match_op(token, '{')) {
762 // private struct/union/enum type
763 sym = alloc_symbol(token->pos, type);
764 set_current_scope(sym); // used by dissect
765 ctx->ctype.base_type = sym;
766 } else {
767 sparse_error(token->pos, "expected declaration");
768 ctx->ctype.base_type = &bad_ctype;
769 return token;
772 token = parse(token->next, sym);
773 token = expect(token, '}', "at end of specifier");
774 attr.ctype.base_type = sym;
775 token = handle_attributes(token, &attr);
776 apply_ctype(token->pos, &sym->ctype, &attr.ctype);
777 sym->packed = attr.packed;
779 sym->endpos = token->pos;
781 return token;
784 static struct token *parse_struct_declaration(struct token *token, struct symbol *sym)
786 struct symbol *field, *last = NULL;
787 struct token *res;
788 res = struct_declaration_list(token, &sym->symbol_list);
789 FOR_EACH_PTR(sym->symbol_list, field) {
790 if (!field->ident) {
791 struct symbol *base = field->ctype.base_type;
792 if (base && base->type == SYM_BITFIELD)
793 continue;
795 if (last)
796 last->next_subobject = field;
797 last = field;
798 } END_FOR_EACH_PTR(field);
799 return res;
802 static struct token *parse_union_declaration(struct token *token, struct symbol *sym)
804 return struct_declaration_list(token, &sym->symbol_list);
807 static struct token *struct_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
809 return struct_union_enum_specifier(SYM_STRUCT, token, ctx, parse_struct_declaration);
812 static struct token *union_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
814 return struct_union_enum_specifier(SYM_UNION, token, ctx, parse_union_declaration);
818 // safe right shift
820 // This allow to use a shift amount as big (or bigger)
821 // than the width of the value to be shifted, in which case
822 // the result is, of course, 0.
823 static unsigned long long rshift(unsigned long long val, unsigned int n)
825 if (n >= (sizeof(val) * 8))
826 return 0;
827 return val >> n;
830 struct range {
831 long long neg;
832 unsigned long long pos;
835 static void update_range(struct range *range, unsigned long long uval, struct symbol *vtype)
837 long long sval = uval;
839 if (is_signed_type(vtype) && (sval < 0)) {
840 if (sval < range->neg)
841 range->neg = sval;
842 } else {
843 if (uval > range->pos)
844 range->pos = uval;
848 static int type_is_ok(struct symbol *type, struct range range)
850 int shift = type->bit_size;
851 int is_unsigned = type->ctype.modifiers & MOD_UNSIGNED;
853 if (!is_unsigned)
854 shift--;
855 if (rshift(range.pos, shift))
856 return 0;
857 if (range.neg == 0)
858 return 1;
859 if (is_unsigned)
860 return 0;
861 if (rshift(~range.neg, shift))
862 return 0;
863 return 1;
866 static struct range type_range(struct symbol *type)
868 struct range range;
869 unsigned int size = type->bit_size;
870 unsigned long long max;
871 long long min;
873 if (is_signed_type(type)) {
874 min = sign_bit(size);
875 max = min - 1;
876 } else {
877 min = 0;
878 max = bits_mask(size);
881 range.pos = max;
882 range.neg = min;
883 return range;
886 static int val_in_range(struct range *range, long long sval, struct symbol *vtype)
888 unsigned long long uval = sval;
890 if (is_signed_type(vtype) && (sval < 0))
891 return range->neg <= sval;
892 else
893 return uval <= range->pos;
896 static void cast_enum_list(struct symbol_list *list, struct symbol *base_type)
898 struct range irange = type_range(&int_ctype);
899 struct symbol *sym;
901 FOR_EACH_PTR(list, sym) {
902 struct expression *expr = sym->initializer;
903 struct symbol *ctype;
904 long long val;
905 if (expr->type != EXPR_VALUE)
906 continue;
907 ctype = expr->ctype;
908 val = get_expression_value(expr);
909 if (is_int_type(ctype) && val_in_range(&irange, val, ctype)) {
910 expr->ctype = &int_ctype;
911 continue;
913 cast_value(expr, base_type, expr);
914 } END_FOR_EACH_PTR(sym);
917 static struct token *parse_enum_declaration(struct token *token, struct symbol *parent)
919 unsigned long long lastval = 0;
920 struct symbol *ctype = NULL, *base_type = NULL;
921 struct range range = { };
922 int mix_bitwise = 0;
924 parent->examined = 1;
925 parent->ctype.base_type = &int_ctype;
926 while (token_type(token) == TOKEN_IDENT) {
927 struct expression *expr = NULL;
928 struct token *next = token->next;
929 struct decl_state ctx = { };
930 struct symbol *sym;
932 // FIXME: only 'deprecated' should be accepted
933 next = handle_attributes(next, &ctx);
935 if (match_op(next, '=')) {
936 next = constant_expression(next->next, &expr);
937 lastval = get_expression_value(expr);
938 ctype = &void_ctype;
939 if (expr && expr->ctype)
940 ctype = expr->ctype;
941 } else if (!ctype) {
942 ctype = &int_ctype;
943 } else if (is_int_type(ctype)) {
944 lastval++;
945 } else {
946 error_die(token->pos, "can't increment the last enum member");
949 if (!expr) {
950 expr = alloc_expression(token->pos, EXPR_VALUE);
951 expr->value = lastval;
952 expr->ctype = ctype;
955 sym = alloc_symbol(token->pos, SYM_NODE);
956 bind_symbol(sym, token->ident, NS_SYMBOL);
957 sym->ctype.modifiers &= ~MOD_ADDRESSABLE;
958 sym->initializer = expr;
959 sym->enum_member = 1;
960 sym->ctype.base_type = parent;
961 add_ptr_list(&parent->symbol_list, sym);
963 if (base_type != &bad_ctype) {
964 if (ctype->type == SYM_NODE)
965 ctype = ctype->ctype.base_type;
966 if (ctype->type == SYM_ENUM) {
967 if (ctype == parent)
968 ctype = base_type;
969 else
970 ctype = ctype->ctype.base_type;
973 * base_type rules:
974 * - if all enums are of the same type, then
975 * the base_type is that type (two first
976 * cases)
977 * - if enums are of different types, they
978 * all have to be integer types, and the
979 * base type is at least "int_ctype".
980 * - otherwise the base_type is "bad_ctype".
982 if (!base_type || ctype == &bad_ctype) {
983 base_type = ctype;
984 } else if (ctype == base_type) {
985 /* nothing */
986 } else if (is_int_type(base_type) && is_int_type(ctype)) {
987 base_type = &int_ctype;
988 } else if (is_restricted_type(base_type) != is_restricted_type(ctype)) {
989 if (!mix_bitwise++) {
990 warning(expr->pos, "mixed bitwiseness");
992 } else if (is_restricted_type(base_type) && base_type != ctype) {
993 sparse_error(expr->pos, "incompatible restricted type");
994 info(expr->pos, " expected: %s", show_typename(base_type));
995 info(expr->pos, " got: %s", show_typename(ctype));
996 base_type = &bad_ctype;
997 } else if (base_type != &bad_ctype) {
998 sparse_error(token->pos, "bad enum definition");
999 base_type = &bad_ctype;
1001 parent->ctype.base_type = base_type;
1003 if (is_int_type(base_type)) {
1004 update_range(&range, lastval, ctype);
1006 token = next;
1008 sym->endpos = token->pos;
1010 if (!match_op(token, ','))
1011 break;
1012 token = token->next;
1014 if (!base_type) {
1015 sparse_error(token->pos, "empty enum definition");
1016 base_type = &bad_ctype;
1018 else if (!is_int_type(base_type))
1020 else if (type_is_ok(&uint_ctype, range))
1021 base_type = &uint_ctype;
1022 else if (type_is_ok(&int_ctype, range))
1023 base_type = &int_ctype;
1024 else if (type_is_ok(&ulong_ctype, range))
1025 base_type = &ulong_ctype;
1026 else if (type_is_ok(&long_ctype, range))
1027 base_type = &long_ctype;
1028 else if (type_is_ok(&ullong_ctype, range))
1029 base_type = &ullong_ctype;
1030 else if (type_is_ok(&llong_ctype, range))
1031 base_type = &llong_ctype;
1032 else
1033 base_type = &bad_ctype;
1034 parent->ctype.base_type = base_type;
1035 parent->ctype.modifiers |= (base_type->ctype.modifiers & MOD_UNSIGNED);
1036 parent->examined = 0;
1038 if (mix_bitwise)
1039 return token;
1040 cast_enum_list(parent->symbol_list, base_type);
1042 return token;
1045 static struct token *enum_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
1047 struct token *ret = struct_union_enum_specifier(SYM_ENUM, token, ctx, parse_enum_declaration);
1048 struct ctype *ctype = &ctx->ctype.base_type->ctype;
1050 if (!ctype->base_type)
1051 ctype->base_type = &incomplete_ctype;
1053 return ret;
1056 static struct token *typeof_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
1059 if (!match_op(token, '(')) {
1060 sparse_error(token->pos, "expected '(' after typeof");
1061 return token;
1063 if (lookup_type(token->next)) {
1064 struct symbol *sym;
1065 token = typename(token->next, &sym, NULL);
1066 ctx->ctype.base_type = sym->ctype.base_type;
1067 apply_ctype(token->pos, &ctx->ctype, &sym->ctype);
1068 } else {
1069 struct symbol *typeof_sym = alloc_symbol(token->pos, SYM_TYPEOF);
1070 token = parse_expression(token->next, &typeof_sym->initializer);
1072 typeof_sym->endpos = token->pos;
1073 if (!typeof_sym->initializer) {
1074 sparse_error(token->pos, "expected expression after the '(' token");
1075 typeof_sym = &bad_ctype;
1077 ctx->ctype.base_type = typeof_sym;
1079 return expect(token, ')', "after typeof");
1082 static struct token *autotype_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
1084 ctx->ctype.base_type = &autotype_ctype;
1085 ctx->autotype = 1;
1086 return token;
1089 static struct token *ignore_attribute(struct token *token, struct symbol *attr, struct decl_state *ctx)
1091 struct expression *expr = NULL;
1092 if (match_op(token, '('))
1093 token = parens_expression(token, &expr, "in attribute");
1094 return token;
1097 static struct token *attribute_packed(struct token *token, struct symbol *attr, struct decl_state *ctx)
1099 if (!ctx->ctype.alignment) {
1100 ctx->ctype.alignment = 1;
1101 ctx->packed = 1;
1103 return token;
1106 static struct token *attribute_aligned(struct token *token, struct symbol *attr, struct decl_state *ctx)
1108 int alignment = max_alignment;
1109 struct expression *expr = NULL;
1111 if (match_op(token, '(')) {
1112 token = parens_expression(token, &expr, "in attribute");
1113 if (expr)
1114 alignment = const_expression_value(expr);
1116 if (alignment & (alignment-1)) {
1117 warning(token->pos, "I don't like non-power-of-2 alignments");
1118 return token;
1119 } else if (alignment > ctx->ctype.alignment)
1120 ctx->ctype.alignment = alignment;
1121 return token;
1124 static struct token *attribute_cleanup(struct token *token, struct symbol *attr, struct decl_state *ctx)
1126 struct expression *expr = NULL;
1128 if (match_op(token, '(')) {
1129 token = parens_expression(token, &expr, "in attribute");
1130 if (expr && expr->type == EXPR_SYMBOL)
1131 ctx->cleanup = expr;
1133 return token;
1136 static void apply_mod(struct position *pos, unsigned long *mods, unsigned long mod)
1138 if (*mods & mod & ~MOD_DUP_OK)
1139 warning(*pos, "duplicate %s", modifier_name(mod));
1140 *mods |= mod;
1143 static void apply_qualifier(struct position *pos, struct ctype *ctx, unsigned long qual)
1145 apply_mod(pos, &ctx->modifiers, qual);
1148 static struct token *attribute_modifier(struct token *token, struct symbol *attr, struct decl_state *ctx)
1150 apply_mod(&token->pos, &ctx->ctype.modifiers, attr->ctype.modifiers);
1151 return token;
1154 static struct token *attribute_function(struct token *token, struct symbol *attr, struct decl_state *ctx)
1156 apply_mod(&token->pos, &ctx->f_modifiers, attr->ctype.modifiers);
1157 return token;
1160 static struct token *attribute_bitwise(struct token *token, struct symbol *attr, struct decl_state *ctx)
1162 if (Wbitwise)
1163 attribute_modifier(token, attr, ctx);
1164 return token;
1167 static struct ident *numerical_address_space(int asn)
1169 char buff[32];
1171 if (!asn)
1172 return NULL;
1173 sprintf(buff, "<asn:%d>", asn);
1174 return built_in_ident(buff);
1177 static struct token *attribute_address_space(struct token *token, struct symbol *attr, struct decl_state *ctx)
1179 struct expression *expr = NULL;
1180 struct ident *as = NULL;
1181 struct token *next;
1183 token = expect(token, '(', "after address_space attribute");
1184 switch (token_type(token)) {
1185 case TOKEN_NUMBER:
1186 next = primary_expression(token, &expr);
1187 if (expr->type != EXPR_VALUE)
1188 goto invalid;
1189 as = numerical_address_space(expr->value);
1190 break;
1191 case TOKEN_IDENT:
1192 next = token->next;
1193 as = token->ident;
1194 break;
1195 default:
1196 next = token->next;
1197 invalid:
1198 as = NULL;
1199 warning(token->pos, "invalid address space name");
1202 if (Waddress_space && as) {
1203 if (ctx->ctype.as)
1204 sparse_error(token->pos,
1205 "multiple address spaces given: %s & %s",
1206 show_as(ctx->ctype.as), show_as(as));
1207 ctx->ctype.as = as;
1209 token = expect(next, ')', "after address_space attribute");
1210 return token;
1213 static struct symbol *to_QI_mode(struct symbol *ctype)
1215 if (ctype->ctype.base_type != &int_type)
1216 return NULL;
1217 if (ctype == &char_ctype)
1218 return ctype;
1219 return ctype->ctype.modifiers & MOD_UNSIGNED ? &uchar_ctype
1220 : &schar_ctype;
1223 static struct symbol *to_HI_mode(struct symbol *ctype)
1225 if (ctype->ctype.base_type != &int_type)
1226 return NULL;
1227 return ctype->ctype.modifiers & MOD_UNSIGNED ? &ushort_ctype
1228 : &sshort_ctype;
1231 static struct symbol *to_SI_mode(struct symbol *ctype)
1233 if (ctype->ctype.base_type != &int_type)
1234 return NULL;
1235 return ctype->ctype.modifiers & MOD_UNSIGNED ? &uint_ctype
1236 : &sint_ctype;
1239 static struct symbol *to_DI_mode(struct symbol *ctype)
1241 if (ctype->ctype.base_type != &int_type)
1242 return NULL;
1243 return ctype->ctype.modifiers & MOD_UNSIGNED ? &ullong_ctype
1244 : &sllong_ctype;
1247 static struct symbol *to_TI_mode(struct symbol *ctype)
1249 if (ctype->ctype.base_type != &int_type)
1250 return NULL;
1251 return ctype->ctype.modifiers & MOD_UNSIGNED ? &uint128_ctype
1252 : &sint128_ctype;
1255 static struct symbol *to_pointer_mode(struct symbol *ctype)
1257 if (ctype->ctype.base_type != &int_type)
1258 return NULL;
1259 return ctype->ctype.modifiers & MOD_UNSIGNED ? uintptr_ctype
1260 : intptr_ctype;
1263 static struct symbol *to_word_mode(struct symbol *ctype)
1265 if (ctype->ctype.base_type != &int_type)
1266 return NULL;
1267 return ctype->ctype.modifiers & MOD_UNSIGNED ? &ulong_ctype
1268 : &slong_ctype;
1271 static struct token *attribute_mode(struct token *token, struct symbol *attr, struct decl_state *ctx)
1273 token = expect(token, '(', "after mode attribute");
1274 if (token_type(token) == TOKEN_IDENT) {
1275 struct symbol *mode = lookup_keyword(token->ident, NS_KEYWORD);
1276 if (mode && mode->op->type & KW_MODE)
1277 ctx->mode = mode->op;
1278 else
1279 sparse_error(token->pos, "unknown mode attribute %s", show_ident(token->ident));
1280 token = token->next;
1281 } else
1282 sparse_error(token->pos, "expect attribute mode symbol\n");
1283 token = expect(token, ')', "after mode attribute");
1284 return token;
1287 static struct token *attribute_context(struct token *token, struct symbol *attr, struct decl_state *ctx)
1289 struct context *context = alloc_context();
1290 struct expression *args[3];
1291 int idx = 0;
1293 token = expect(token, '(', "after context attribute");
1294 token = conditional_expression(token, &args[0]);
1295 token = expect(token, ',', "after context 1st argument");
1296 token = conditional_expression(token, &args[1]);
1297 if (match_op(token, ',')) {
1298 token = token->next;
1299 token = conditional_expression(token, &args[2]);
1300 token = expect(token, ')', "after context 3rd argument");
1301 context->context = args[0];
1302 idx++;
1303 } else {
1304 token = expect(token, ')', "after context 2nd argument");
1306 context->in = get_expression_value(args[idx++]);
1307 context->out = get_expression_value(args[idx++]);
1308 add_ptr_list(&ctx->ctype.contexts, context);
1309 return token;
1312 static struct token *attribute_designated_init(struct token *token, struct symbol *attr, struct decl_state *ctx)
1314 if (ctx->ctype.base_type && ctx->ctype.base_type->type == SYM_STRUCT)
1315 ctx->ctype.base_type->designated_init = 1;
1316 else
1317 warning(token->pos, "attribute designated_init applied to non-structure type");
1318 return token;
1321 static struct token *attribute_transparent_union(struct token *token, struct symbol *attr, struct decl_state *ctx)
1323 if (Wtransparent_union)
1324 warning(token->pos, "attribute __transparent_union__");
1326 if (ctx->ctype.base_type && ctx->ctype.base_type->type == SYM_UNION)
1327 ctx->ctype.base_type->transparent_union = 1;
1328 else
1329 warning(token->pos, "attribute __transparent_union__ applied to non-union type");
1330 return token;
1333 static struct token *recover_unknown_attribute(struct token *token)
1335 struct expression *expr = NULL;
1337 if (Wunknown_attribute)
1338 warning(token->pos, "unknown attribute '%s'", show_ident(token->ident));
1339 token = token->next;
1340 if (match_op(token, '('))
1341 token = parens_expression(token, &expr, "in attribute");
1342 return token;
1345 static struct token *attribute_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
1347 token = expect(token, '(', "after attribute");
1348 token = expect(token, '(', "after attribute");
1350 while (token_type(token) == TOKEN_IDENT) {
1351 struct symbol *attr = lookup_keyword(token->ident, NS_KEYWORD);
1352 if (attr && attr->op->attribute)
1353 token = attr->op->attribute(token->next, attr, ctx);
1354 else
1355 token = recover_unknown_attribute(token);
1357 if (!match_op(token, ','))
1358 break;
1359 token = token->next;
1362 token = expect(token, ')', "after attribute");
1363 token = expect(token, ')', "after attribute");
1364 return token;
1367 static unsigned long decl_modifiers(struct decl_state *ctx)
1369 unsigned long mods = ctx->ctype.modifiers & MOD_DECLARE;
1370 ctx->ctype.modifiers &= ~MOD_DECLARE;
1371 return ctx->storage_class | mods;
1374 static struct token *storage_specifier(struct token *next, struct symbol *sym, struct decl_state *ctx)
1376 int is_tls = ctx->ctype.modifiers & MOD_TLS;
1377 unsigned long class = sym->ctype.modifiers;
1378 const char *storage = modifier_name(class);
1380 /* __thread can be used alone, or with extern or static */
1381 if (is_tls && (class & ~(MOD_STATIC|MOD_EXTERN)))
1382 sparse_error(next->pos, "__thread cannot be used with '%s'", storage);
1383 else if (!ctx->storage_class)
1384 ctx->storage_class = class;
1385 else if (ctx->storage_class == class)
1386 sparse_error(next->pos, "duplicate %s", storage);
1387 else
1388 sparse_error(next->pos, "multiple storage classes");
1389 return next;
1392 static struct token *thread_specifier(struct token *next, struct symbol *sym, struct decl_state *ctx)
1394 /* This GCC extension can be used alone, or with extern or static */
1395 if (!(ctx->storage_class & ~(MOD_STATIC|MOD_EXTERN))) {
1396 apply_qualifier(&next->pos, &ctx->ctype, MOD_TLS);
1397 } else {
1398 sparse_error(next->pos, "__thread cannot be used with '%s'",
1399 modifier_name(ctx->storage_class));
1402 return next;
1405 static struct token *attribute_force(struct token *token, struct symbol *attr, struct decl_state *ctx)
1407 ctx->forced = 1;
1408 return token;
1411 static struct token *alignas_specifier(struct token *token, struct symbol *sym, struct decl_state *ctx)
1413 int alignment = 0;
1415 if (!match_op(token, '(')) {
1416 sparse_error(token->pos, "expected '(' after _Alignas");
1417 return token;
1419 if (lookup_type(token->next)) {
1420 struct symbol *sym = NULL;
1421 token = typename(token->next, &sym, NULL);
1422 sym = examine_symbol_type(sym);
1423 alignment = sym->ctype.alignment;
1424 token = expect(token, ')', "after _Alignas(...");
1425 } else {
1426 struct expression *expr = NULL;
1427 token = parens_expression(token, &expr, "after _Alignas");
1428 if (!expr)
1429 return token;
1430 alignment = const_expression_value(expr);
1433 if (alignment < 0) {
1434 warning(token->pos, "non-positive alignment");
1435 return token;
1437 if (alignment & (alignment-1)) {
1438 warning(token->pos, "non-power-of-2 alignment");
1439 return token;
1441 if (alignment > ctx->ctype.alignment)
1442 ctx->ctype.alignment = alignment;
1443 return token;
1446 static struct token *generic_qualifier(struct token *next, struct symbol *sym, struct decl_state *ctx)
1448 apply_qualifier(&next->pos, &ctx->ctype, sym->ctype.modifiers);
1449 return next;
1452 static void apply_ctype(struct position pos, struct ctype *dst, struct ctype *src)
1454 unsigned long mod = src->modifiers;
1456 if (mod)
1457 apply_qualifier(&pos, dst, mod);
1459 /* Context */
1460 concat_ptr_list((struct ptr_list *)src->contexts,
1461 (struct ptr_list **)&dst->contexts);
1463 /* Alignment */
1464 if (src->alignment > dst->alignment)
1465 dst->alignment = src->alignment;
1467 /* Address space */
1468 if (src->as)
1469 dst->as = src->as;
1472 static void specifier_conflict(struct position pos, int what, struct ident *new)
1474 const char *old;
1475 if (what & (Set_S | Set_T))
1476 goto Catch_all;
1477 if (what & Set_Char)
1478 old = "char";
1479 else if (what & Set_Double)
1480 old = "double";
1481 else if (what & Set_Float)
1482 old = "float";
1483 else if (what & Set_Signed)
1484 old = "signed";
1485 else if (what & Set_Unsigned)
1486 old = "unsigned";
1487 else if (what & Set_Short)
1488 old = "short";
1489 else if (what & Set_Long)
1490 old = "long";
1491 else
1492 old = "long long";
1493 sparse_error(pos, "impossible combination of type specifiers: %s %s",
1494 old, show_ident(new));
1495 return;
1497 Catch_all:
1498 sparse_error(pos, "two or more data types in declaration specifiers");
1501 static struct symbol * const int_types[] =
1502 {&char_ctype, &short_ctype, &int_ctype, &long_ctype, &llong_ctype, &int128_ctype};
1503 static struct symbol * const signed_types[] =
1504 {&schar_ctype, &sshort_ctype, &sint_ctype, &slong_ctype, &sllong_ctype,
1505 &sint128_ctype};
1506 static struct symbol * const unsigned_types[] =
1507 {&uchar_ctype, &ushort_ctype, &uint_ctype, &ulong_ctype, &ullong_ctype,
1508 &uint128_ctype};
1509 static struct symbol * const real_types[] =
1510 {&float_ctype, &double_ctype, &ldouble_ctype};
1511 static struct symbol * const * const types[] = {
1512 [CInt] = int_types + 2,
1513 [CSInt] = signed_types + 2,
1514 [CUInt] = unsigned_types + 2,
1515 [CReal] = real_types + 1,
1518 struct symbol *ctype_integer(int size, int want_unsigned)
1520 return types[want_unsigned ? CUInt : CInt][size];
1523 static struct token *handle_qualifiers(struct token *t, struct decl_state *ctx)
1525 while (token_type(t) == TOKEN_IDENT) {
1526 struct symbol *s = lookup_keyword(t->ident, NS_TYPEDEF);
1527 if (!s)
1528 break;
1529 if (!(s->op->type & (KW_ATTRIBUTE | KW_QUALIFIER)))
1530 break;
1531 t = t->next;
1532 if (s->op->declarator)
1533 t = s->op->declarator(t, s, ctx);
1535 return t;
1538 static struct token *declaration_specifiers(struct token *token, struct decl_state *ctx)
1540 int seen = 0;
1541 int class = CInt;
1542 int rank = 0;
1544 while (token_type(token) == TOKEN_IDENT) {
1545 struct symbol *s = lookup_symbol(token->ident,
1546 NS_TYPEDEF | NS_SYMBOL);
1547 if (!s || !(s->namespace & NS_TYPEDEF))
1548 break;
1549 if (s->type != SYM_KEYWORD) {
1550 if (seen & Set_Any)
1551 break;
1552 seen |= Set_S | Set_T;
1553 ctx->ctype.base_type = s->ctype.base_type;
1554 apply_ctype(token->pos, &ctx->ctype, &s->ctype);
1555 token = token->next;
1556 continue;
1558 if (s->op->type & KW_SPECIFIER) {
1559 if (seen & s->op->test) {
1560 specifier_conflict(token->pos,
1561 seen & s->op->test,
1562 token->ident);
1563 break;
1565 seen |= s->op->set;
1566 class += s->op->class;
1567 if (s->op->set & Set_Int128)
1568 rank = 3;
1569 else if (s->op->set & Set_Char)
1570 rank = -2;
1571 if (s->op->set & (Set_Short|Set_Float)) {
1572 rank = -1;
1573 } else if (s->op->set & Set_Long && rank++) {
1574 if (class == CReal) {
1575 specifier_conflict(token->pos,
1576 Set_Vlong,
1577 &double_ident);
1578 break;
1580 seen |= Set_Vlong;
1583 token = token->next;
1584 if (s->op->declarator) // Note: this eats attributes
1585 token = s->op->declarator(token, s, ctx);
1586 if (s->op->type & KW_EXACT) {
1587 ctx->ctype.base_type = s->ctype.base_type;
1588 ctx->ctype.modifiers |= s->ctype.modifiers;
1592 if (!(seen & Set_S)) { /* not set explicitly? */
1593 struct symbol *base = &incomplete_ctype;
1594 if (seen & Set_Any)
1595 base = types[class][rank];
1596 ctx->ctype.base_type = base;
1599 if (ctx->ctype.modifiers & MOD_BITWISE) {
1600 struct symbol *type;
1601 ctx->ctype.modifiers &= ~MOD_BITWISE;
1602 if (!is_int_type(ctx->ctype.base_type)) {
1603 sparse_error(token->pos, "invalid modifier");
1604 return token;
1606 type = alloc_symbol(token->pos, SYM_BASETYPE);
1607 *type = *ctx->ctype.base_type;
1608 type->ctype.modifiers &= ~MOD_SPECIFIER;
1609 type->ctype.base_type = ctx->ctype.base_type;
1610 type->type = SYM_RESTRICT;
1611 ctx->ctype.base_type = type;
1612 create_fouled(type);
1614 return token;
1617 static struct token *abstract_array_declarator(struct token *token, struct symbol *sym)
1619 struct expression *expr = NULL;
1620 int has_static = 0;
1622 while (token_type(token) == TOKEN_IDENT) {
1623 struct symbol *sym = lookup_keyword(token->ident, NS_TYPEDEF);
1624 if (!sym || !(sym->op->type & (KW_STATIC|KW_QUALIFIER)))
1625 break;
1626 if (has_static && (sym->op->type & KW_STATIC))
1627 sparse_error(token->pos, "duplicate array static declarator");
1628 has_static |= (sym->op->type & KW_STATIC);
1629 token = token->next;
1631 if (match_op(token, '*') && match_op(token->next, ']')) {
1632 // FIXME: '[*]' is treated like '[]'
1633 token = token->next;
1634 } else {
1635 token = assignment_expression(token, &expr);
1637 sym->array_size = expr;
1638 return token;
1641 static struct token *parameter_type_list(struct token *, struct symbol *);
1642 static struct token *identifier_list(struct token *, struct symbol *);
1643 static struct token *declarator(struct token *token, struct decl_state *ctx);
1645 static struct token *handle_asm_name(struct token *token, struct decl_state *ctx)
1647 struct expression *expr;
1648 struct symbol *keyword;
1650 if (token_type(token) != TOKEN_IDENT)
1651 return token;
1652 keyword = lookup_keyword(token->ident, NS_KEYWORD);
1653 if (!keyword)
1654 return token;
1655 if (!(keyword->op->type & KW_ASM))
1656 return token;
1658 token = token->next;
1659 token = expect(token, '(', "after asm");
1660 token = string_expression(token, &expr, "asm name");
1661 token = expect(token, ')', "after asm");
1662 return token;
1666 // test if @token is '__attribute__' (or one of its variant)
1667 static bool match_attribute(struct token *token)
1669 struct symbol *sym;
1671 if (token_type(token) != TOKEN_IDENT)
1672 return false;
1673 sym = lookup_keyword(token->ident, NS_TYPEDEF);
1674 if (!sym || !sym->op)
1675 return false;
1676 return sym->op->type & KW_ATTRIBUTE;
1679 static struct token *skip_attribute(struct token *token)
1681 token = token->next;
1682 if (match_op(token, '(')) {
1683 int depth = 1;
1684 token = token->next;
1685 while (depth && !eof_token(token)) {
1686 if (token_type(token) == TOKEN_SPECIAL) {
1687 if (token->special == '(')
1688 depth++;
1689 else if (token->special == ')')
1690 depth--;
1692 token = token->next;
1695 return token;
1698 static struct token *skip_attributes(struct token *token)
1700 while (match_attribute(token)) {
1701 token = expect(token->next, '(', "after attribute");
1702 token = expect(token, '(', "after attribute");
1703 while (token_type(token) == TOKEN_IDENT) {
1704 token = skip_attribute(token);
1705 if (!match_op(token, ','))
1706 break;
1707 token = token->next;
1709 token = expect(token, ')', "after attribute");
1710 token = expect(token, ')', "after attribute");
1712 return token;
1715 static struct token *handle_attributes(struct token *token, struct decl_state *ctx)
1717 while (match_attribute(token))
1718 token = attribute_specifier(token->next, NULL, ctx);
1719 return token;
1722 static int is_nested(struct token *token, struct token **p,
1723 int prefer_abstract)
1726 * This can be either a parameter list or a grouping.
1727 * For the direct (non-abstract) case, we know if must be
1728 * a parameter list if we already saw the identifier.
1729 * For the abstract case, we know if must be a parameter
1730 * list if it is empty or starts with a type.
1732 struct token *next = token->next;
1734 *p = next = skip_attributes(next);
1736 if (token_type(next) == TOKEN_IDENT) {
1737 if (lookup_type(next))
1738 return !prefer_abstract;
1739 return 1;
1742 if (match_op(next, ')') || match_op(next, SPECIAL_ELLIPSIS))
1743 return 0;
1745 return 1;
1748 enum kind {
1749 Empty, K_R, Proto, Bad_Func,
1752 static enum kind which_func(struct token *token,
1753 struct ident **n,
1754 int prefer_abstract)
1756 struct token *next = token->next;
1758 if (token_type(next) == TOKEN_IDENT) {
1759 if (lookup_type(next))
1760 return Proto;
1761 /* identifier list not in definition; complain */
1762 if (prefer_abstract)
1763 warning(token->pos,
1764 "identifier list not in definition");
1765 return K_R;
1768 if (token_type(next) != TOKEN_SPECIAL)
1769 return Bad_Func;
1771 if (next->special == ')') {
1772 /* don't complain about those */
1773 if (!n || match_op(next->next, ';') || match_op(next->next, ','))
1774 return Empty;
1775 if (Wstrict_prototypes)
1776 warning(next->pos,
1777 "non-ANSI function declaration of function '%s'",
1778 show_ident(*n));
1779 return Empty;
1782 if (next->special == SPECIAL_ELLIPSIS) {
1783 warning(next->pos,
1784 "variadic functions must have one named argument");
1785 return Proto;
1788 return Bad_Func;
1791 static struct token *direct_declarator(struct token *token, struct decl_state *ctx)
1793 struct ctype *ctype = &ctx->ctype;
1794 struct token *next;
1795 struct ident **p = ctx->ident;
1797 if (ctx->ident && token_type(token) == TOKEN_IDENT) {
1798 *ctx->ident = token->ident;
1799 token = token->next;
1800 } else if (match_op(token, '(') &&
1801 is_nested(token, &next, ctx->prefer_abstract)) {
1802 struct symbol *base_type = ctype->base_type;
1803 if (token->next != next)
1804 next = handle_attributes(token->next, ctx);
1805 token = declarator(next, ctx);
1806 token = expect(token, ')', "in nested declarator");
1807 while (ctype->base_type != base_type)
1808 ctype = &ctype->base_type->ctype;
1809 p = NULL;
1812 if (match_op(token, '(')) {
1813 enum kind kind = which_func(token, p, ctx->prefer_abstract);
1814 struct symbol *fn;
1815 fn = alloc_indirect_symbol(token->pos, ctype, SYM_FN);
1816 ctype->modifiers |= ctx->f_modifiers;
1817 token = token->next;
1818 if (kind == K_R)
1819 token = identifier_list(token, fn);
1820 else if (kind == Proto)
1821 token = parameter_type_list(token, fn);
1822 token = expect(token, ')', "in function declarator");
1823 fn->endpos = token->pos;
1824 return token;
1827 while (match_op(token, '[')) {
1828 struct symbol *array;
1829 array = alloc_indirect_symbol(token->pos, ctype, SYM_ARRAY);
1830 token = abstract_array_declarator(token->next, array);
1831 token = expect(token, ']', "in abstract_array_declarator");
1832 array->endpos = token->pos;
1833 ctype = &array->ctype;
1835 return token;
1838 static struct token *pointer(struct token *token, struct decl_state *ctx)
1840 while (match_op(token,'*')) {
1841 struct symbol *ptr = alloc_symbol(token->pos, SYM_PTR);
1842 ptr->ctype.modifiers = ctx->ctype.modifiers;
1843 ptr->ctype.base_type = ctx->ctype.base_type;
1844 ptr->ctype.as = ctx->ctype.as;
1845 ptr->ctype.contexts = ctx->ctype.contexts;
1846 ctx->ctype.modifiers = 0;
1847 ctx->ctype.base_type = ptr;
1848 ctx->ctype.as = NULL;
1849 ctx->ctype.contexts = NULL;
1850 ctx->ctype.alignment = 0;
1852 token = handle_qualifiers(token->next, ctx);
1853 ctx->ctype.base_type->endpos = token->pos;
1855 return token;
1858 static struct token *declarator(struct token *token, struct decl_state *ctx)
1860 token = pointer(token, ctx);
1861 return direct_declarator(token, ctx);
1864 static struct token *handle_bitfield(struct token *token, struct decl_state *ctx)
1866 struct ctype *ctype = &ctx->ctype;
1867 struct expression *expr;
1868 struct symbol *bitfield;
1869 long long width;
1871 if (ctype->base_type != &int_type && !is_int_type(ctype->base_type)) {
1872 sparse_error(token->pos, "invalid bitfield specifier for type %s.",
1873 show_typename(ctype->base_type));
1874 // Parse this to recover gracefully.
1875 return conditional_expression(token->next, &expr);
1878 bitfield = alloc_indirect_symbol(token->pos, ctype, SYM_BITFIELD);
1879 token = conditional_expression(token->next, &expr);
1880 width = const_expression_value(expr);
1881 bitfield->bit_size = width;
1883 if (width < 0 || width > INT_MAX || (*ctx->ident && width == 0)) {
1884 sparse_error(token->pos, "bitfield '%s' has invalid width (%lld)",
1885 show_ident(*ctx->ident), width);
1886 width = -1;
1887 } else if (*ctx->ident) {
1888 struct symbol *base_type = bitfield->ctype.base_type;
1889 struct symbol *bitfield_type = base_type == &int_type ? bitfield : base_type;
1890 int is_signed = !(bitfield_type->ctype.modifiers & MOD_UNSIGNED);
1891 if (Wone_bit_signed_bitfield && width == 1 && is_signed) {
1892 // Valid values are either {-1;0} or {0}, depending on integer
1893 // representation. The latter makes for very efficient code...
1894 sparse_error(token->pos, "dubious one-bit signed bitfield");
1896 if (Wdefault_bitfield_sign &&
1897 bitfield_type->type != SYM_ENUM &&
1898 !(bitfield_type->ctype.modifiers & MOD_EXPLICITLY_SIGNED) &&
1899 is_signed) {
1900 // The sign of bitfields is unspecified by default.
1901 warning(token->pos, "dubious bitfield without explicit `signed' or `unsigned'");
1904 bitfield->bit_size = width;
1905 bitfield->endpos = token->pos;
1906 bitfield->ident = *ctx->ident;
1907 return token;
1910 static struct token *declaration_list(struct token *token, struct symbol_list **list)
1912 struct decl_state ctx = {.prefer_abstract = 0};
1913 struct ctype saved;
1914 unsigned long mod;
1916 token = declaration_specifiers(token, &ctx);
1917 mod = decl_modifiers(&ctx);
1918 saved = ctx.ctype;
1919 for (;;) {
1920 struct symbol *decl = alloc_symbol(token->pos, SYM_NODE);
1921 ctx.ident = &decl->ident;
1923 token = declarator(token, &ctx);
1924 if (match_op(token, ':'))
1925 token = handle_bitfield(token, &ctx);
1927 token = handle_attributes(token, &ctx);
1928 apply_modifiers(token->pos, &ctx);
1930 decl->ctype = ctx.ctype;
1931 decl->ctype.modifiers |= mod;
1932 decl->cleanup = ctx.cleanup;
1933 decl->endpos = token->pos;
1934 add_symbol(list, decl);
1935 if (!match_op(token, ','))
1936 break;
1937 token = token->next;
1938 ctx.ctype = saved;
1940 return token;
1943 static struct token *struct_declaration_list(struct token *token, struct symbol_list **list)
1945 while (!match_op(token, '}')) {
1946 if (match_ident(token, &_Static_assert_ident)) {
1947 token = parse_static_assert(token, NULL);
1948 continue;
1950 if (!match_op(token, ';'))
1951 token = declaration_list(token, list);
1952 if (!match_op(token, ';')) {
1953 sparse_error(token->pos, "expected ; at end of declaration");
1954 break;
1956 token = token->next;
1958 return token;
1961 static struct token *parameter_declaration(struct token *token, struct symbol *sym)
1963 struct decl_state ctx = {.prefer_abstract = 1};
1965 token = declaration_specifiers(token, &ctx);
1966 ctx.ident = &sym->ident;
1967 token = declarator(token, &ctx);
1968 token = handle_attributes(token, &ctx);
1969 apply_modifiers(token->pos, &ctx);
1970 sym->ctype = ctx.ctype;
1971 sym->ctype.modifiers |= decl_modifiers(&ctx);
1972 sym->endpos = token->pos;
1973 sym->forced_arg = ctx.forced;
1974 return token;
1977 struct token *typename(struct token *token, struct symbol **p, int *forced)
1979 struct decl_state ctx = {.prefer_abstract = 1};
1980 unsigned long class;
1981 struct symbol *sym = alloc_symbol(token->pos, SYM_NODE);
1982 *p = sym;
1983 token = declaration_specifiers(token, &ctx);
1984 token = declarator(token, &ctx);
1985 apply_modifiers(token->pos, &ctx);
1986 sym->ctype = ctx.ctype;
1987 sym->cleanup = ctx.cleanup;
1988 sym->endpos = token->pos;
1989 class = ctx.storage_class;
1990 if (forced)
1991 *forced = ctx.forced;
1992 if (class)
1993 warning(sym->pos, "storage class in typename (%s%s)",
1994 modifier_string(class), show_typename(sym));
1995 return token;
1998 static struct token *parse_underscore_Pragma(struct token *token)
2000 struct token *next;
2002 next = token->next;
2003 if (!match_op(next, '('))
2004 return next;
2005 next = next->next;
2006 if (next->pos.type != TOKEN_STRING)
2007 return next;
2008 next = next->next;
2009 if (!match_op(next, ')'))
2010 return next;
2011 return next->next;
2014 static struct token *expression_statement(struct token *token, struct expression **tree)
2016 if (match_ident(token, &_Pragma_ident))
2017 return parse_underscore_Pragma(token);
2019 token = parse_expression(token, tree);
2020 return expect(token, ';', "at end of statement");
2023 static struct token *parse_asm_operands(struct token *token, struct statement *stmt,
2024 struct asm_operand_list **inout)
2026 /* Allow empty operands */
2027 if (match_op(token->next, ':') || match_op(token->next, ')'))
2028 return token->next;
2029 do {
2030 struct asm_operand *op = __alloc_asm_operand(0);
2031 if (match_op(token->next, '[') &&
2032 token_type(token->next->next) == TOKEN_IDENT &&
2033 match_op(token->next->next->next, ']')) {
2034 op->name = token->next->next->ident;
2035 token = token->next->next->next;
2037 token = token->next;
2038 token = string_expression(token, &op->constraint, "asm constraint");
2039 token = parens_expression(token, &op->expr, "in asm parameter");
2040 add_ptr_list(inout, op);
2041 } while (match_op(token, ','));
2042 return token;
2045 static struct token *parse_asm_clobbers(struct token *token, struct statement *stmt,
2046 struct expression_list **clobbers)
2048 struct expression *expr;
2050 do {
2051 token = primary_expression(token->next, &expr);
2052 if (expr)
2053 add_expression(clobbers, expr);
2054 } while (match_op(token, ','));
2055 return token;
2058 static struct token *parse_asm_labels(struct token *token, struct statement *stmt,
2059 struct symbol_list **labels)
2061 struct symbol *label;
2063 do {
2064 token = token->next; /* skip ':' and ',' */
2065 if (token_type(token) != TOKEN_IDENT)
2066 return token;
2067 label = label_symbol(token, 1);
2068 add_symbol(labels, label);
2069 token = token->next;
2070 } while (match_op(token, ','));
2071 return token;
2074 static struct token *parse_asm_statement(struct token *token, struct statement *stmt)
2076 unsigned long mods = 0;
2078 token = token->next;
2079 stmt->type = STMT_ASM;
2080 while (token_type(token) == TOKEN_IDENT) {
2081 struct symbol *s = lookup_keyword(token->ident, NS_TYPEDEF);
2082 if (s && s->op->asm_modifier)
2083 s->op->asm_modifier(token, &mods, s->ctype.modifiers);
2084 else if (token->ident == &goto_ident)
2085 asm_modifier(token, &mods, MOD_ASM_GOTO);
2086 token = token->next;
2088 token = expect(token, '(', "after asm");
2089 token = string_expression(token, &stmt->asm_string, "inline asm");
2090 if (match_op(token, ':'))
2091 token = parse_asm_operands(token, stmt, &stmt->asm_outputs);
2092 if (match_op(token, ':'))
2093 token = parse_asm_operands(token, stmt, &stmt->asm_inputs);
2094 if (match_op(token, ':'))
2095 token = parse_asm_clobbers(token, stmt, &stmt->asm_clobbers);
2096 if (match_op(token, ':') && (mods & MOD_ASM_GOTO))
2097 token = parse_asm_labels(token, stmt, &stmt->asm_labels);
2098 token = expect(token, ')', "after asm");
2099 return expect(token, ';', "at end of asm-statement");
2102 static struct token *parse_static_assert(struct token *token, struct symbol_list **unused)
2104 struct expression *cond = NULL, *message = NULL;
2106 token = expect(token->next, '(', "after _Static_assert");
2107 token = constant_expression(token, &cond);
2108 if (!cond)
2109 sparse_error(token->pos, "Expected constant expression");
2110 if (match_op(token, ',')) {
2111 token = token->next;
2112 token = string_expression(token, &message, "_Static_assert()");
2113 if (!message)
2114 cond = NULL;
2116 token = expect(token, ')', "after diagnostic message in _Static_assert");
2117 token = expect(token, ';', "after _Static_assert()");
2119 if (cond && !const_expression_value(cond) && cond->type == EXPR_VALUE) {
2120 const char *sep = "", *msg = "";
2122 if (message) {
2123 sep = ": ";
2124 msg = show_string(message->string);
2126 sparse_error(cond->pos, "static assertion failed%s%s", sep, msg);
2129 return token;
2132 /* Make a statement out of an expression */
2133 static struct statement *make_statement(struct expression *expr)
2135 struct statement *stmt;
2137 if (!expr)
2138 return NULL;
2139 stmt = alloc_statement(expr->pos, STMT_EXPRESSION);
2140 stmt->expression = expr;
2141 return stmt;
2145 * All iterators have two symbols associated with them:
2146 * the "continue" and "break" symbols, which are targets
2147 * for continue and break statements respectively.
2149 * They are in a special name-space, but they follow
2150 * all the normal visibility rules, so nested iterators
2151 * automatically work right.
2153 static void start_iterator(struct statement *stmt)
2155 struct symbol *cont, *brk;
2157 start_block_scope(stmt->pos);
2158 cont = alloc_symbol(stmt->pos, SYM_NODE);
2159 bind_symbol(cont, &continue_ident, NS_ITERATOR);
2160 brk = alloc_symbol(stmt->pos, SYM_NODE);
2161 bind_symbol(brk, &break_ident, NS_ITERATOR);
2163 stmt->type = STMT_ITERATOR;
2164 stmt->iterator_break = brk;
2165 stmt->iterator_continue = cont;
2166 fn_local_symbol(brk);
2167 fn_local_symbol(cont);
2170 static void end_iterator(struct statement *stmt)
2172 end_block_scope();
2175 static struct statement *start_function(struct symbol *sym)
2177 struct symbol *ret;
2178 struct statement *stmt = alloc_statement(sym->pos, STMT_COMPOUND);
2180 start_function_scope(sym->pos);
2181 ret = alloc_symbol(sym->pos, SYM_NODE);
2182 ret->ctype = sym->ctype.base_type->ctype;
2183 ret->ctype.modifiers &= ~(MOD_STORAGE | MOD_QUALIFIER | MOD_TLS | MOD_ACCESS | MOD_NOCAST | MOD_NODEREF);
2184 ret->ctype.modifiers |= (MOD_AUTO | MOD_REGISTER);
2185 bind_symbol(ret, &return_ident, NS_ITERATOR);
2186 stmt->ret = ret;
2187 fn_local_symbol(ret);
2189 // Currently parsed symbol for __func__/__FUNCTION__/__PRETTY_FUNCTION__
2190 current_fn = sym;
2192 return stmt;
2195 static void end_function(struct symbol *sym)
2197 current_fn = NULL;
2198 end_function_scope();
2202 * A "switch()" statement, like an iterator, has a
2203 * the "break" symbol associated with it. It works
2204 * exactly like the iterator break - it's the target
2205 * for any break-statements in scope, and means that
2206 * "break" handling doesn't even need to know whether
2207 * it's breaking out of an iterator or a switch.
2209 * In addition, the "case" symbol is a marker for the
2210 * case/default statements to find the switch statement
2211 * that they are associated with.
2213 static void start_switch(struct statement *stmt)
2215 struct symbol *brk, *switch_case;
2217 start_block_scope(stmt->pos);
2218 brk = alloc_symbol(stmt->pos, SYM_NODE);
2219 bind_symbol(brk, &break_ident, NS_ITERATOR);
2221 switch_case = alloc_symbol(stmt->pos, SYM_NODE);
2222 bind_symbol(switch_case, &case_ident, NS_ITERATOR);
2223 switch_case->stmt = stmt;
2225 stmt->type = STMT_SWITCH;
2226 stmt->switch_break = brk;
2227 stmt->switch_case = switch_case;
2229 fn_local_symbol(brk);
2230 fn_local_symbol(switch_case);
2233 static void end_switch(struct statement *stmt)
2235 if (!stmt->switch_case->symbol_list)
2236 warning(stmt->pos, "switch with no cases");
2237 end_block_scope();
2240 static void add_case_statement(struct statement *stmt)
2242 struct symbol *target = lookup_symbol(&case_ident, NS_ITERATOR);
2243 struct symbol *sym;
2245 if (!target) {
2246 sparse_error(stmt->pos, "not in switch scope");
2247 stmt->type = STMT_NONE;
2248 return;
2250 sym = alloc_symbol(stmt->pos, SYM_NODE);
2251 add_symbol(&target->symbol_list, sym);
2252 sym->stmt = stmt;
2253 stmt->case_label = sym;
2254 fn_local_symbol(sym);
2257 static struct token *parse_return_statement(struct token *token, struct statement *stmt)
2259 struct symbol *target = lookup_symbol(&return_ident, NS_ITERATOR);
2261 if (!target)
2262 error_die(token->pos, "internal error: return without a function target");
2263 stmt->type = STMT_RETURN;
2264 stmt->ret_target = target;
2265 return expression_statement(token->next, &stmt->ret_value);
2268 static void validate_for_loop_decl(struct symbol *sym)
2270 unsigned long storage = sym->ctype.modifiers & MOD_STORAGE;
2272 if (storage & ~(MOD_AUTO | MOD_REGISTER)) {
2273 const char *name = show_ident(sym->ident);
2274 sparse_error(sym->pos, "non-local var '%s' in for-loop initializer", name);
2275 sym->ctype.modifiers &= ~MOD_STORAGE;
2279 static struct token *parse_for_statement(struct token *token, struct statement *stmt)
2281 struct symbol_list *syms;
2282 struct expression *e1, *e2, *e3;
2283 struct statement *iterator;
2285 start_iterator(stmt);
2286 token = expect(token->next, '(', "after 'for'");
2288 syms = NULL;
2289 e1 = NULL;
2290 /* C99 variable declaration? */
2291 if (lookup_type(token)) {
2292 token = external_declaration(token, &syms, validate_for_loop_decl);
2293 } else {
2294 token = parse_expression(token, &e1);
2295 token = expect(token, ';', "in 'for'");
2297 token = parse_expression(token, &e2);
2298 token = expect(token, ';', "in 'for'");
2299 token = parse_expression(token, &e3);
2300 token = expect(token, ')', "in 'for'");
2301 token = statement(token, &iterator);
2303 stmt->iterator_syms = syms;
2304 stmt->iterator_pre_statement = make_statement(e1);
2305 stmt->iterator_pre_condition = e2;
2306 stmt->iterator_post_statement = make_statement(e3);
2307 stmt->iterator_post_condition = NULL;
2308 stmt->iterator_statement = iterator;
2309 end_iterator(stmt);
2311 return token;
2314 static struct token *parse_while_statement(struct token *token, struct statement *stmt)
2316 struct expression *expr;
2317 struct statement *iterator;
2319 start_iterator(stmt);
2320 token = parens_expression(token->next, &expr, "after 'while'");
2321 token = statement(token, &iterator);
2323 stmt->iterator_pre_condition = expr;
2324 stmt->iterator_post_condition = NULL;
2325 stmt->iterator_statement = iterator;
2326 end_iterator(stmt);
2328 return token;
2331 static struct token *parse_do_statement(struct token *token, struct statement *stmt)
2333 struct expression *expr;
2334 struct statement *iterator;
2336 start_iterator(stmt);
2337 token = statement(token->next, &iterator);
2338 if (token_type(token) == TOKEN_IDENT && token->ident == &while_ident)
2339 token = token->next;
2340 else
2341 sparse_error(token->pos, "expected 'while' after 'do'");
2342 token = parens_expression(token, &expr, "after 'do-while'");
2344 stmt->iterator_post_condition = expr;
2345 stmt->iterator_statement = iterator;
2346 end_iterator(stmt);
2348 if (iterator && iterator->type != STMT_COMPOUND && Wdo_while)
2349 warning(iterator->pos, "do-while statement is not a compound statement");
2351 return expect(token, ';', "after statement");
2354 static struct token *parse_if_statement(struct token *token, struct statement *stmt)
2356 stmt->type = STMT_IF;
2357 token = parens_expression(token->next, &stmt->if_conditional, "after if");
2358 token = statement(token, &stmt->if_true);
2359 if (token_type(token) != TOKEN_IDENT)
2360 return token;
2361 if (token->ident != &else_ident)
2362 return token;
2363 return statement(token->next, &stmt->if_false);
2366 static inline struct token *case_statement(struct token *token, struct statement *stmt)
2368 stmt->type = STMT_CASE;
2369 token = expect(token, ':', "after default/case");
2370 add_case_statement(stmt);
2371 if (match_op(token, '}')) {
2372 warning(token->pos, "statement expected after case label");
2373 stmt->case_statement = alloc_statement(token->pos, STMT_NONE);
2374 return token;
2376 return statement(token, &stmt->case_statement);
2379 static struct token *parse_case_statement(struct token *token, struct statement *stmt)
2381 token = parse_expression(token->next, &stmt->case_expression);
2382 if (match_op(token, SPECIAL_ELLIPSIS))
2383 token = parse_expression(token->next, &stmt->case_to);
2384 return case_statement(token, stmt);
2387 static struct token *parse_default_statement(struct token *token, struct statement *stmt)
2389 return case_statement(token->next, stmt);
2392 static struct token *parse_loop_iterator(struct token *token, struct statement *stmt)
2394 struct symbol *target = lookup_symbol(token->ident, NS_ITERATOR);
2395 stmt->type = STMT_GOTO;
2396 stmt->goto_label = target;
2397 if (!target)
2398 sparse_error(stmt->pos, "break/continue not in iterator scope");
2399 return expect(token->next, ';', "at end of statement");
2402 static struct token *parse_switch_statement(struct token *token, struct statement *stmt)
2404 stmt->type = STMT_SWITCH;
2405 start_switch(stmt);
2406 token = parens_expression(token->next, &stmt->switch_expression, "after 'switch'");
2407 token = statement(token, &stmt->switch_statement);
2408 end_switch(stmt);
2409 return token;
2412 static void warn_label_usage(struct position def, struct position use, struct ident *ident)
2414 const char *id = show_ident(ident);
2415 sparse_error(use, "label '%s' used outside statement expression", id);
2416 info(def, " label '%s' defined here", id);
2417 current_fn->bogus_linear = 1;
2420 void check_label_usage(struct symbol *label, struct position use_pos)
2422 struct statement *def = label->stmt;
2424 if (def) {
2425 if (!is_in_scope(def->label_scope, label_scope))
2426 warn_label_usage(def->pos, use_pos, label->ident);
2427 } else if (!label->label_scope) {
2428 label->label_scope = label_scope;
2429 label->label_pos = use_pos;
2433 static struct token *parse_goto_statement(struct token *token, struct statement *stmt)
2435 stmt->type = STMT_GOTO;
2436 token = token->next;
2437 if (match_op(token, '*')) {
2438 token = parse_expression(token->next, &stmt->goto_expression);
2439 add_statement(&function_computed_goto_list, stmt);
2440 } else if (token_type(token) == TOKEN_IDENT) {
2441 struct symbol *label = label_symbol(token, 1);
2442 stmt->goto_label = label;
2443 check_label_usage(label, stmt->pos);
2444 token = token->next;
2445 } else {
2446 sparse_error(token->pos, "Expected identifier or goto expression");
2448 return expect(token, ';', "at end of statement");
2451 static struct token *parse_context_statement(struct token *token, struct statement *stmt)
2453 stmt->type = STMT_CONTEXT;
2454 token = token->next;
2455 token = expect(token, '(', "after __context__ statement");
2456 token = assignment_expression(token, &stmt->expression);
2457 if (!stmt->expression)
2458 unexpected(token, "expression expected after '('");
2459 if (match_op(token, ',')) {
2460 token = token->next;
2461 stmt->context = stmt->expression;
2462 token = assignment_expression(token, &stmt->expression);
2463 if (!stmt->expression)
2464 unexpected(token, "expression expected after ','");
2466 token = expect(token, ')', "at end of __context__ statement");
2467 return expect(token, ';', "at end of statement");
2470 static struct token *parse_range_statement(struct token *token, struct statement *stmt)
2472 stmt->type = STMT_RANGE;
2473 token = token->next;
2474 token = expect(token, '(', "after __range__ statement");
2475 token = assignment_expression(token, &stmt->range_expression);
2476 token = expect(token, ',', "after range expression");
2477 token = assignment_expression(token, &stmt->range_low);
2478 token = expect(token, ',', "after low range");
2479 token = assignment_expression(token, &stmt->range_high);
2480 token = expect(token, ')', "after range statement");
2481 return expect(token, ';', "after range statement");
2484 static struct token *handle_label_attributes(struct token *token, struct symbol *label)
2486 struct decl_state ctx = { };
2488 token = handle_attributes(token, &ctx);
2489 label->label_modifiers = ctx.ctype.modifiers;
2490 return token;
2493 static struct token *statement(struct token *token, struct statement **tree)
2495 struct statement *stmt = alloc_statement(token->pos, STMT_NONE);
2497 *tree = stmt;
2498 if (token_type(token) == TOKEN_IDENT) {
2499 struct symbol *s = lookup_keyword(token->ident, NS_KEYWORD);
2500 if (s && s->op->statement)
2501 return s->op->statement(token, stmt);
2503 if (match_op(token->next, ':')) {
2504 struct symbol *s = label_symbol(token, 0);
2505 token = handle_label_attributes(token->next->next, s);
2506 if (s->stmt) {
2507 sparse_error(stmt->pos, "label '%s' redefined", show_ident(s->ident));
2508 // skip the label to avoid multiple definitions
2509 return statement(token, tree);
2511 stmt->type = STMT_LABEL;
2512 stmt->label_identifier = s;
2513 stmt->label_scope = label_scope;
2514 if (s->label_scope) {
2515 if (!is_in_scope(label_scope, s->label_scope))
2516 warn_label_usage(stmt->pos, s->label_pos, s->ident);
2518 s->stmt = stmt;
2519 if (match_op(token, '}')) {
2520 warning(token->pos, "statement expected after label");
2521 stmt->label_statement = alloc_statement(token->pos, STMT_NONE);
2522 return token;
2524 return statement(token, &stmt->label_statement);
2528 if (match_op(token, '{')) {
2529 token = compound_statement(token->next, stmt);
2530 return expect(token, '}', "at end of compound statement");
2533 stmt->type = STMT_EXPRESSION;
2534 return expression_statement(token, &stmt->expression);
2537 /* gcc extension - __label__ ident-list; in the beginning of compound stmt */
2538 static struct token *label_statement(struct token *token)
2540 while (token_type(token) == TOKEN_IDENT) {
2541 struct symbol *sym = alloc_symbol(token->pos, SYM_LABEL);
2542 /* it's block-scope, but we want label namespace */
2543 bind_symbol_with_scope(sym, token->ident, NS_LABEL, block_scope);
2544 fn_local_symbol(sym);
2545 token = token->next;
2546 if (!match_op(token, ','))
2547 break;
2548 token = token->next;
2550 return expect(token, ';', "at end of label declaration");
2553 static struct token * statement_list(struct token *token, struct statement_list **list)
2555 int seen_statement = 0;
2556 while (token_type(token) == TOKEN_IDENT &&
2557 token->ident == &__label___ident)
2558 token = label_statement(token->next);
2559 for (;;) {
2560 struct statement * stmt;
2561 if (eof_token(token))
2562 break;
2563 if (match_op(token, '}'))
2564 break;
2565 if (match_ident(token, &_Static_assert_ident)) {
2566 token = parse_static_assert(token, NULL);
2567 continue;
2569 if (lookup_type(token)) {
2570 if (seen_statement) {
2571 warning(token->pos, "mixing declarations and code");
2572 seen_statement = 0;
2574 stmt = alloc_statement(token->pos, STMT_DECLARATION);
2575 token = external_declaration(token, &stmt->declaration, NULL);
2576 } else {
2577 seen_statement = Wdeclarationafterstatement;
2578 token = statement(token, &stmt);
2580 add_statement(list, stmt);
2582 return token;
2585 static struct token *identifier_list(struct token *token, struct symbol *fn)
2587 struct symbol_list **list = &fn->arguments;
2588 for (;;) {
2589 struct symbol *sym = alloc_symbol(token->pos, SYM_NODE);
2590 sym->ident = token->ident;
2591 token = token->next;
2592 sym->endpos = token->pos;
2593 sym->ctype.base_type = &incomplete_ctype;
2594 add_symbol(list, sym);
2595 if (!match_op(token, ',') ||
2596 token_type(token->next) != TOKEN_IDENT ||
2597 lookup_type(token->next))
2598 break;
2599 token = token->next;
2601 return token;
2604 static struct token *parameter_type_list(struct token *token, struct symbol *fn)
2606 struct symbol_list **list = &fn->arguments;
2608 for (;;) {
2609 struct symbol *sym;
2611 if (match_op(token, SPECIAL_ELLIPSIS)) {
2612 fn->variadic = 1;
2613 token = token->next;
2614 break;
2617 sym = alloc_symbol(token->pos, SYM_NODE);
2618 token = parameter_declaration(token, sym);
2619 if (sym->ctype.base_type == &void_ctype) {
2620 /* Special case: (void) */
2621 if (!*list && !sym->ident)
2622 break;
2623 warning(token->pos, "void parameter");
2625 add_symbol(list, sym);
2626 if (!match_op(token, ','))
2627 break;
2628 token = token->next;
2630 return token;
2633 struct token *compound_statement(struct token *token, struct statement *stmt)
2635 stmt->type = STMT_COMPOUND;
2636 start_block_scope(token->pos);
2637 token = statement_list(token, &stmt->stmts);
2638 end_block_scope();
2639 return token;
2642 static struct expression *identifier_expression(struct token *token)
2644 struct expression *expr = alloc_expression(token->pos, EXPR_IDENTIFIER);
2645 expr->expr_ident = token->ident;
2646 return expr;
2649 static struct expression *index_expression(struct expression *from, struct expression *to)
2651 int idx_from, idx_to;
2652 struct expression *expr = alloc_expression(from->pos, EXPR_INDEX);
2654 idx_from = const_expression_value(from);
2655 idx_to = idx_from;
2656 if (to) {
2657 idx_to = const_expression_value(to);
2658 if (idx_to < idx_from || idx_from < 0)
2659 warning(from->pos, "nonsense array initializer index range");
2661 expr->idx_from = idx_from;
2662 expr->idx_to = idx_to;
2663 return expr;
2666 static struct token *single_initializer(struct expression **ep, struct token *token)
2668 int expect_equal = 0;
2669 struct token *next = token->next;
2670 struct expression **tail = ep;
2671 int nested;
2673 *ep = NULL;
2675 if ((token_type(token) == TOKEN_IDENT) && match_op(next, ':')) {
2676 struct expression *expr = identifier_expression(token);
2677 if (Wold_initializer)
2678 warning(token->pos, "obsolete struct initializer, use C99 syntax");
2679 token = initializer(&expr->ident_expression, next->next);
2680 if (expr->ident_expression)
2681 *ep = expr;
2682 return token;
2685 for (tail = ep, nested = 0; ; nested++, next = token->next) {
2686 if (match_op(token, '.') && (token_type(next) == TOKEN_IDENT)) {
2687 struct expression *expr = identifier_expression(next);
2688 *tail = expr;
2689 tail = &expr->ident_expression;
2690 expect_equal = 1;
2691 token = next->next;
2692 } else if (match_op(token, '[')) {
2693 struct expression *from = NULL, *to = NULL, *expr;
2694 token = constant_expression(token->next, &from);
2695 if (!from) {
2696 sparse_error(token->pos, "Expected constant expression");
2697 break;
2699 if (match_op(token, SPECIAL_ELLIPSIS))
2700 token = constant_expression(token->next, &to);
2701 expr = index_expression(from, to);
2702 *tail = expr;
2703 tail = &expr->idx_expression;
2704 token = expect(token, ']', "at end of initializer index");
2705 if (nested)
2706 expect_equal = 1;
2707 } else {
2708 break;
2711 if (nested && !expect_equal) {
2712 if (!match_op(token, '='))
2713 warning(token->pos, "obsolete array initializer, use C99 syntax");
2714 else
2715 expect_equal = 1;
2717 if (expect_equal)
2718 token = expect(token, '=', "at end of initializer index");
2720 token = initializer(tail, token);
2721 if (!*tail)
2722 *ep = NULL;
2723 return token;
2726 static struct token *initializer_list(struct expression_list **list, struct token *token)
2728 struct expression *expr;
2730 for (;;) {
2731 token = single_initializer(&expr, token);
2732 if (!expr)
2733 break;
2734 add_expression(list, expr);
2735 if (!match_op(token, ','))
2736 break;
2737 token = token->next;
2739 return token;
2742 struct token *initializer(struct expression **tree, struct token *token)
2744 if (match_op(token, '{')) {
2745 struct expression *expr = alloc_expression(token->pos, EXPR_INITIALIZER);
2746 *tree = expr;
2747 if (!Wuniversal_initializer) {
2748 struct token *next = token->next;
2749 // '{ 0 }' is equivalent to '{ }' except for some
2750 // warnings, like using 0 to initialize a null-pointer.
2751 if (match_token_zero(next)) {
2752 if (match_op(next->next, '}'))
2753 expr->zero_init = 1;
2757 token = initializer_list(&expr->expr_list, token->next);
2758 return expect(token, '}', "at end of initializer");
2760 return assignment_expression(token, tree);
2763 static void declare_argument(struct symbol *sym, struct symbol *fn)
2765 if (!sym->ident) {
2766 sparse_error(sym->pos, "no identifier for function argument");
2767 return;
2769 if (sym->ctype.base_type == &incomplete_ctype) {
2770 sym->ctype.base_type = &int_ctype;
2772 if (Wimplicit_int) {
2773 sparse_error(sym->pos, "missing type declaration for parameter '%s'",
2774 show_ident(sym->ident));
2777 bind_symbol(sym, sym->ident, NS_SYMBOL);
2780 static int is_syscall(struct symbol *sym)
2782 char *macro;
2783 char *name;
2784 int is_syscall = 0;
2786 macro = get_macro_name(sym->pos);
2787 if (macro &&
2788 (strncmp("SYSCALL_DEFINE", macro, strlen("SYSCALL_DEFINE")) == 0 ||
2789 strncmp("COMPAT_SYSCALL_DEFINE", macro, strlen("COMPAT_SYSCALL_DEFINE")) == 0))
2790 is_syscall = 1;
2792 name = sym->ident->name;
2794 if (name && strncmp(name, "sys_", 4) ==0)
2795 is_syscall = 1;
2797 if (name && strncmp(name, "compat_sys_", 11) == 0)
2798 is_syscall = 1;
2800 return is_syscall;
2804 static struct token *parse_function_body(struct token *token, struct symbol *decl,
2805 struct symbol_list **list)
2807 struct symbol_list **old_symbol_list;
2808 struct symbol *base_type = decl->ctype.base_type;
2809 struct statement *stmt, **p;
2810 struct symbol *prev;
2811 struct symbol *arg;
2813 old_symbol_list = function_symbol_list;
2814 if (decl->ctype.modifiers & MOD_INLINE) {
2815 function_symbol_list = &decl->inline_symbol_list;
2816 p = &base_type->inline_stmt;
2817 } else {
2818 function_symbol_list = &decl->symbol_list;
2819 p = &base_type->stmt;
2821 function_computed_target_list = NULL;
2822 function_computed_goto_list = NULL;
2824 if ((decl->ctype.modifiers & (MOD_EXTERN|MOD_INLINE)) == MOD_EXTERN) {
2825 if (Wexternal_function_has_definition)
2826 warning(decl->pos, "function '%s' with external linkage has definition", show_ident(decl->ident));
2828 if (!(decl->ctype.modifiers & MOD_STATIC))
2829 decl->ctype.modifiers |= MOD_EXTERN;
2831 stmt = start_function(decl);
2832 *p = stmt;
2834 FOR_EACH_PTR (base_type->arguments, arg) {
2835 declare_argument(arg, base_type);
2836 } END_FOR_EACH_PTR(arg);
2838 token = statement_list(token->next, &stmt->stmts);
2839 end_function(decl);
2841 if (!(decl->ctype.modifiers & MOD_INLINE))
2842 add_symbol(list, decl);
2843 else if (is_syscall(decl)) {
2844 add_symbol(list, decl);
2846 printf("parse.c decl: %s\n", decl->ident->name);
2847 char *macro = get_macro_name(decl->pos);
2848 printf("decl macro: %s\n", macro);
2851 check_declaration(decl);
2852 decl->definition = decl;
2853 prev = decl->same_symbol;
2854 if (prev && prev->definition) {
2855 warning(decl->pos, "multiple definitions for function '%s'",
2856 show_ident(decl->ident));
2857 info(prev->definition->pos, " the previous one is here");
2858 } else {
2859 while (prev) {
2860 rebind_scope(prev, decl->scope);
2861 prev->definition = decl;
2862 prev = prev->same_symbol;
2865 function_symbol_list = old_symbol_list;
2866 if (function_computed_goto_list) {
2867 if (!function_computed_target_list)
2868 warning(decl->pos, "function '%s' has computed goto but no targets?", show_ident(decl->ident));
2869 else {
2870 FOR_EACH_PTR(function_computed_goto_list, stmt) {
2871 stmt->target_list = function_computed_target_list;
2872 } END_FOR_EACH_PTR(stmt);
2875 return expect(token, '}', "at end of function");
2878 static void promote_k_r_types(struct symbol *arg)
2880 struct symbol *base = arg->ctype.base_type;
2881 if (base && base->ctype.base_type == &int_type && base->rank < 0) {
2882 arg->ctype.base_type = &int_ctype;
2886 static void apply_k_r_types(struct symbol_list *argtypes, struct symbol *fn)
2888 struct symbol_list *real_args = fn->ctype.base_type->arguments;
2889 struct symbol *arg;
2891 FOR_EACH_PTR(real_args, arg) {
2892 struct symbol *type;
2894 /* This is quadratic in the number of arguments. We _really_ don't care */
2895 FOR_EACH_PTR(argtypes, type) {
2896 if (type->ident == arg->ident)
2897 goto match;
2898 } END_FOR_EACH_PTR(type);
2899 if (Wimplicit_int) {
2900 warning(arg->pos, "missing type declaration for parameter '%s'",
2901 show_ident(arg->ident));
2903 type = alloc_symbol(arg->pos, SYM_NODE);
2904 type->ident = arg->ident;
2905 type->ctype.base_type = &int_ctype;
2906 match:
2907 type->used = 1;
2908 /* "char" and "short" promote to "int" */
2909 promote_k_r_types(type);
2911 arg->ctype = type->ctype;
2912 } END_FOR_EACH_PTR(arg);
2914 FOR_EACH_PTR(argtypes, arg) {
2915 if (!arg->used)
2916 warning(arg->pos, "nonsensical parameter declaration '%s'", show_ident(arg->ident));
2917 } END_FOR_EACH_PTR(arg);
2921 static struct token *parse_k_r_arguments(struct token *token, struct symbol *decl,
2922 struct symbol_list **list)
2924 struct symbol_list *args = NULL;
2926 if (Wold_style_definition)
2927 warning(token->pos, "non-ANSI definition of function '%s'", show_ident(decl->ident));
2929 do {
2930 token = declaration_list(token, &args);
2931 if (!match_op(token, ';')) {
2932 sparse_error(token->pos, "expected ';' at end of parameter declaration");
2933 break;
2935 token = token->next;
2936 } while (lookup_type(token));
2938 apply_k_r_types(args, decl);
2940 if (!match_op(token, '{')) {
2941 sparse_error(token->pos, "expected function body");
2942 return token;
2944 return parse_function_body(token, decl, list);
2947 static struct token *toplevel_asm_declaration(struct token *token, struct symbol_list **list)
2949 struct symbol *anon = alloc_symbol(token->pos, SYM_NODE);
2950 struct symbol *fn = alloc_symbol(token->pos, SYM_FN);
2951 struct statement *stmt;
2953 anon->ctype.base_type = fn;
2954 stmt = alloc_statement(token->pos, STMT_NONE);
2955 fn->stmt = stmt;
2957 token = parse_asm_statement(token, stmt);
2959 // FIXME: add_symbol(list, anon);
2960 return token;
2963 struct token *external_declaration(struct token *token, struct symbol_list **list,
2964 validate_decl_t validate_decl)
2966 struct ident *ident = NULL;
2967 struct symbol *decl;
2968 struct decl_state ctx = { .ident = &ident };
2969 struct ctype saved;
2970 struct symbol *base_type;
2971 unsigned long mod;
2972 int is_typedef;
2974 if (match_ident(token, &_Pragma_ident))
2975 return parse_underscore_Pragma(token);
2977 /* Top-level inline asm or static assertion? */
2978 if (token_type(token) == TOKEN_IDENT) {
2979 struct symbol *s = lookup_keyword(token->ident, NS_KEYWORD);
2980 if (s && s->op->toplevel)
2981 return s->op->toplevel(token, list);
2984 /* Parse declaration-specifiers, if any */
2985 token = declaration_specifiers(token, &ctx);
2986 mod = decl_modifiers(&ctx);
2987 decl = alloc_symbol(token->pos, SYM_NODE);
2988 /* Just a type declaration? */
2989 if (match_op(token, ';')) {
2990 apply_modifiers(token->pos, &ctx);
2991 return token->next;
2994 saved = ctx.ctype;
2995 token = declarator(token, &ctx);
2996 token = handle_asm_name(token, &ctx);
2997 token = handle_attributes(token, &ctx);
2998 apply_modifiers(token->pos, &ctx);
3000 decl->ctype = ctx.ctype;
3001 decl->ctype.modifiers |= mod;
3002 decl->cleanup = ctx.cleanup;
3003 decl->endpos = token->pos;
3005 /* Just a type declaration? */
3006 if (!ident) {
3007 warning(token->pos, "missing identifier in declaration");
3008 return expect(token, ';', "at the end of type declaration");
3011 /* type define declaration? */
3012 is_typedef = ctx.storage_class == MOD_USERTYPE;
3014 /* Typedefs don't have meaningful storage */
3015 if (is_typedef)
3016 decl->ctype.modifiers |= MOD_USERTYPE;
3018 bind_symbol(decl, ident, is_typedef ? NS_TYPEDEF: NS_SYMBOL);
3020 base_type = decl->ctype.base_type;
3022 if (is_typedef) {
3023 if (base_type && !base_type->ident) {
3024 switch (base_type->type) {
3025 case SYM_STRUCT:
3026 case SYM_UNION:
3027 case SYM_ENUM:
3028 case SYM_RESTRICT:
3029 base_type->ident = ident;
3030 break;
3031 default:
3032 break;
3035 } else if (base_type && base_type->type == SYM_FN) {
3036 if (base_type->ctype.base_type == &autotype_ctype) {
3037 sparse_error(decl->pos, "'%s()' has __auto_type return type",
3038 show_ident(decl->ident));
3039 base_type->ctype.base_type = &int_ctype;
3041 if (base_type->ctype.base_type == &incomplete_ctype) {
3042 warning(decl->pos, "'%s()' has implicit return type",
3043 show_ident(decl->ident));
3044 base_type->ctype.base_type = &int_ctype;
3046 /* apply attributes placed after the declarator */
3047 decl->ctype.modifiers |= ctx.f_modifiers;
3049 /* K&R argument declaration? */
3050 if (lookup_type(token))
3051 return parse_k_r_arguments(token, decl, list);
3052 if (match_op(token, '{'))
3053 return parse_function_body(token, decl, list);
3055 if (!(decl->ctype.modifiers & MOD_STATIC))
3056 decl->ctype.modifiers |= MOD_EXTERN;
3057 } else if (base_type == &void_ctype && !(decl->ctype.modifiers & MOD_EXTERN)) {
3058 sparse_error(token->pos, "void declaration");
3060 if (base_type == &incomplete_ctype) {
3061 warning(decl->pos, "'%s' has implicit type", show_ident(decl->ident));
3062 decl->ctype.base_type = &int_ctype;;
3065 for (;;) {
3066 if (!is_typedef && match_op(token, '=')) {
3067 struct token *next = token->next;
3068 token = initializer(&decl->initializer, next);
3069 if (token == next)
3070 sparse_error(token->pos, "expression expected before '%s'", show_token(token));
3072 if (!is_typedef) {
3073 if (validate_decl)
3074 validate_decl(decl);
3076 if (decl->initializer && decl->ctype.modifiers & MOD_EXTERN) {
3077 warning(decl->pos, "symbol with external linkage has initializer");
3078 decl->ctype.modifiers &= ~MOD_EXTERN;
3081 if (!(decl->ctype.modifiers & (MOD_EXTERN | MOD_INLINE))) {
3082 add_symbol(list, decl);
3083 fn_local_symbol(decl);
3086 check_declaration(decl);
3087 if (decl->same_symbol) {
3088 decl->definition = decl->same_symbol->definition;
3089 decl->op = decl->same_symbol->op;
3090 if (is_typedef) {
3091 // TODO: handle -std=c89 --pedantic
3092 check_duplicates(decl);
3096 if (ctx.autotype) {
3097 const char *msg = NULL;
3098 if (decl->ctype.base_type != &autotype_ctype)
3099 msg = "on non-identifier";
3100 else if (match_op(token, ','))
3101 msg = "on declaration list";
3102 else if (!decl->initializer)
3103 msg = "without initializer";
3104 else if (decl->initializer->type == EXPR_SYMBOL &&
3105 decl->initializer->symbol == decl)
3106 msg = "on self-init var";
3107 if (msg) {
3108 sparse_error(decl->pos, "__auto_type %s", msg);
3109 decl->ctype.base_type = &bad_ctype;
3113 if (!match_op(token, ','))
3114 break;
3116 token = token->next;
3117 ident = NULL;
3118 decl = alloc_symbol(token->pos, SYM_NODE);
3119 ctx.ctype = saved;
3120 token = handle_attributes(token, &ctx);
3121 token = declarator(token, &ctx);
3122 token = handle_asm_name(token, &ctx);
3123 token = handle_attributes(token, &ctx);
3124 apply_modifiers(token->pos, &ctx);
3125 decl->ctype = ctx.ctype;
3126 decl->ctype.modifiers |= mod;
3127 decl->cleanup = ctx.cleanup;
3128 decl->endpos = token->pos;
3129 if (!ident) {
3130 sparse_error(token->pos, "expected identifier name in type definition");
3131 return token;
3134 if (is_typedef)
3135 decl->ctype.modifiers |= MOD_USERTYPE;
3137 bind_symbol(decl, ident, is_typedef ? NS_TYPEDEF: NS_SYMBOL);
3139 /* Function declarations are automatically extern unless specifically static */
3140 base_type = decl->ctype.base_type;
3141 if (!is_typedef && base_type && base_type->type == SYM_FN) {
3142 if (!(decl->ctype.modifiers & MOD_STATIC))
3143 decl->ctype.modifiers |= MOD_EXTERN;
3146 return expect(token, ';', "at end of declaration");