2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
36 #include "lang_features.h"
38 #include "adt/bitfiddle.h"
39 #include "adt/error.h"
40 #include "adt/array.h"
42 /** if wchar_t is equal to unsigned short. */
43 bool opt_short_wchar_t =
50 //#define PRINT_TOKENS
51 #define MAX_LOOKAHEAD 2
54 declaration_t *old_declaration;
56 unsigned short namespc;
59 typedef struct argument_list_t argument_list_t;
60 struct argument_list_t {
62 argument_list_t *next;
65 typedef struct gnu_attribute_t gnu_attribute_t;
66 struct gnu_attribute_t {
67 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
68 gnu_attribute_t *next;
69 bool invalid; /**< Set if this attribute had argument errors, */
70 bool have_arguments; /**< True, if this attribute has arguments. */
74 atomic_type_kind_t akind;
75 long argument; /**< Single argument. */
76 argument_list_t *arguments; /**< List of argument expressions. */
80 typedef struct declaration_specifiers_t declaration_specifiers_t;
81 struct declaration_specifiers_t {
82 source_position_t source_position;
83 unsigned char declared_storage_class;
84 unsigned char alignment; /**< Alignment, 0 if not set. */
85 unsigned int is_inline : 1;
86 unsigned int deprecated : 1;
87 decl_modifiers_t modifiers; /**< declaration modifiers */
88 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
89 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
90 symbol_t *get_property_sym; /**< the name of the get property if set. */
91 symbol_t *put_property_sym; /**< the name of the put property if set. */
96 * An environment for parsing initializers (and compound literals).
98 typedef struct parse_initializer_env_t {
99 type_t *type; /**< the type of the initializer. In case of an
100 array type with unspecified size this gets
101 adjusted to the actual size. */
102 declaration_t *declaration; /**< the declaration that is initialized if any */
103 bool must_be_constant;
104 } parse_initializer_env_t;
106 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration, bool is_definition);
108 static token_t token;
109 static token_t lookahead_buffer[MAX_LOOKAHEAD];
110 static int lookahead_bufpos;
111 static stack_entry_t *environment_stack = NULL;
112 static stack_entry_t *label_stack = NULL;
113 static stack_entry_t *local_label_stack = NULL;
114 static scope_t *global_scope = NULL;
115 static scope_t *scope = NULL;
116 static declaration_t *last_declaration = NULL;
117 static declaration_t *current_function = NULL;
118 static declaration_t *current_init_decl = NULL;
119 static switch_statement_t *current_switch = NULL;
120 static statement_t *current_loop = NULL;
121 static statement_t *current_parent = NULL;
122 static ms_try_statement_t *current_try = NULL;
123 static goto_statement_t *goto_first = NULL;
124 static goto_statement_t *goto_last = NULL;
125 static label_statement_t *label_first = NULL;
126 static label_statement_t *label_last = NULL;
127 static translation_unit_t *unit = NULL;
128 static struct obstack temp_obst;
130 #define PUSH_PARENT(stmt) \
131 statement_t *const prev_parent = current_parent; \
132 current_parent = (stmt);
133 #define POP_PARENT ((void)(current_parent = prev_parent))
135 static source_position_t null_position = { NULL, 0 };
137 /** special symbol used for anonymous entities. */
138 static const symbol_t *sym_anonymous = NULL;
140 /* symbols for Microsoft extended-decl-modifier */
141 static const symbol_t *sym_align = NULL;
142 static const symbol_t *sym_allocate = NULL;
143 static const symbol_t *sym_dllimport = NULL;
144 static const symbol_t *sym_dllexport = NULL;
145 static const symbol_t *sym_naked = NULL;
146 static const symbol_t *sym_noinline = NULL;
147 static const symbol_t *sym_noreturn = NULL;
148 static const symbol_t *sym_nothrow = NULL;
149 static const symbol_t *sym_novtable = NULL;
150 static const symbol_t *sym_property = NULL;
151 static const symbol_t *sym_get = NULL;
152 static const symbol_t *sym_put = NULL;
153 static const symbol_t *sym_selectany = NULL;
154 static const symbol_t *sym_thread = NULL;
155 static const symbol_t *sym_uuid = NULL;
156 static const symbol_t *sym_deprecated = NULL;
157 static const symbol_t *sym_restrict = NULL;
158 static const symbol_t *sym_noalias = NULL;
160 /** The token anchor set */
161 static unsigned char token_anchor_set[T_LAST_TOKEN];
163 /** The current source position. */
164 #define HERE (&token.source_position)
166 static type_t *type_valist;
168 static statement_t *parse_compound_statement(bool inside_expression_statement);
169 static statement_t *parse_statement(void);
171 static expression_t *parse_sub_expression(unsigned precedence);
172 static expression_t *parse_expression(void);
173 static type_t *parse_typename(void);
175 static void parse_compound_type_entries(declaration_t *compound_declaration);
176 static declaration_t *parse_declarator(
177 const declaration_specifiers_t *specifiers, bool may_be_abstract);
178 static declaration_t *record_declaration(declaration_t *declaration, bool is_definition);
180 static void semantic_comparison(binary_expression_t *expression);
182 #define STORAGE_CLASSES \
190 #define TYPE_QUALIFIERS \
195 case T__forceinline: \
196 case T___attribute__:
198 #ifdef PROVIDE_COMPLEX
199 #define COMPLEX_SPECIFIERS \
201 #define IMAGINARY_SPECIFIERS \
204 #define COMPLEX_SPECIFIERS
205 #define IMAGINARY_SPECIFIERS
208 #define TYPE_SPECIFIERS \
223 case T___builtin_va_list: \
228 #define DECLARATION_START \
233 #define TYPENAME_START \
238 * Allocate an AST node with given size and
239 * initialize all fields with zero.
241 static void *allocate_ast_zero(size_t size)
243 void *res = allocate_ast(size);
244 memset(res, 0, size);
248 static declaration_t *allocate_declaration_zero(void)
250 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
251 declaration->type = type_error_type;
252 declaration->alignment = 0;
257 * Returns the size of a statement node.
259 * @param kind the statement kind
261 static size_t get_statement_struct_size(statement_kind_t kind)
263 static const size_t sizes[] = {
264 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
265 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
266 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
267 [STATEMENT_RETURN] = sizeof(return_statement_t),
268 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
269 [STATEMENT_IF] = sizeof(if_statement_t),
270 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
271 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
272 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
273 [STATEMENT_BREAK] = sizeof(statement_base_t),
274 [STATEMENT_GOTO] = sizeof(goto_statement_t),
275 [STATEMENT_LABEL] = sizeof(label_statement_t),
276 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
277 [STATEMENT_WHILE] = sizeof(while_statement_t),
278 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
279 [STATEMENT_FOR] = sizeof(for_statement_t),
280 [STATEMENT_ASM] = sizeof(asm_statement_t),
281 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
282 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
284 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
285 assert(sizes[kind] != 0);
290 * Returns the size of an expression node.
292 * @param kind the expression kind
294 static size_t get_expression_struct_size(expression_kind_t kind)
296 static const size_t sizes[] = {
297 [EXPR_INVALID] = sizeof(expression_base_t),
298 [EXPR_REFERENCE] = sizeof(reference_expression_t),
299 [EXPR_CONST] = sizeof(const_expression_t),
300 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
301 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
302 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
303 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
304 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
305 [EXPR_CALL] = sizeof(call_expression_t),
306 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
307 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
308 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
309 [EXPR_SELECT] = sizeof(select_expression_t),
310 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
311 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
312 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
313 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
314 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
315 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
316 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
317 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
318 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
319 [EXPR_VA_START] = sizeof(va_start_expression_t),
320 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
321 [EXPR_STATEMENT] = sizeof(statement_expression_t),
322 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
324 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
325 return sizes[EXPR_UNARY_FIRST];
327 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
328 return sizes[EXPR_BINARY_FIRST];
330 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
331 assert(sizes[kind] != 0);
336 * Allocate a statement node of given kind and initialize all
339 static statement_t *allocate_statement_zero(statement_kind_t kind)
341 size_t size = get_statement_struct_size(kind);
342 statement_t *res = allocate_ast_zero(size);
344 res->base.kind = kind;
345 res->base.parent = current_parent;
350 * Allocate an expression node of given kind and initialize all
353 static expression_t *allocate_expression_zero(expression_kind_t kind)
355 size_t size = get_expression_struct_size(kind);
356 expression_t *res = allocate_ast_zero(size);
358 res->base.kind = kind;
359 res->base.type = type_error_type;
364 * Creates a new invalid expression.
366 static expression_t *create_invalid_expression(void)
368 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
369 expression->base.source_position = token.source_position;
374 * Creates a new invalid statement.
376 static statement_t *create_invalid_statement(void)
378 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
379 statement->base.source_position = token.source_position;
384 * Allocate a new empty statement.
386 static statement_t *create_empty_statement(void)
388 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
389 statement->base.source_position = token.source_position;
394 * Returns the size of a type node.
396 * @param kind the type kind
398 static size_t get_type_struct_size(type_kind_t kind)
400 static const size_t sizes[] = {
401 [TYPE_ATOMIC] = sizeof(atomic_type_t),
402 [TYPE_COMPLEX] = sizeof(complex_type_t),
403 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
404 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
405 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
406 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
407 [TYPE_ENUM] = sizeof(enum_type_t),
408 [TYPE_FUNCTION] = sizeof(function_type_t),
409 [TYPE_POINTER] = sizeof(pointer_type_t),
410 [TYPE_ARRAY] = sizeof(array_type_t),
411 [TYPE_BUILTIN] = sizeof(builtin_type_t),
412 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
413 [TYPE_TYPEOF] = sizeof(typeof_type_t),
415 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
416 assert(kind <= TYPE_TYPEOF);
417 assert(sizes[kind] != 0);
422 * Allocate a type node of given kind and initialize all
425 * @param kind type kind to allocate
426 * @param source_position the source position of the type definition
428 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
430 size_t size = get_type_struct_size(kind);
431 type_t *res = obstack_alloc(type_obst, size);
432 memset(res, 0, size);
434 res->base.kind = kind;
435 res->base.source_position = *source_position;
440 * Returns the size of an initializer node.
442 * @param kind the initializer kind
444 static size_t get_initializer_size(initializer_kind_t kind)
446 static const size_t sizes[] = {
447 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
448 [INITIALIZER_STRING] = sizeof(initializer_string_t),
449 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
450 [INITIALIZER_LIST] = sizeof(initializer_list_t),
451 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
453 assert(kind < sizeof(sizes) / sizeof(*sizes));
454 assert(sizes[kind] != 0);
459 * Allocate an initializer node of given kind and initialize all
462 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
464 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
471 * Free a type from the type obstack.
473 static void free_type(void *type)
475 obstack_free(type_obst, type);
479 * Returns the index of the top element of the environment stack.
481 static size_t environment_top(void)
483 return ARR_LEN(environment_stack);
487 * Returns the index of the top element of the global label stack.
489 static size_t label_top(void)
491 return ARR_LEN(label_stack);
495 * Returns the index of the top element of the local label stack.
497 static size_t local_label_top(void)
499 return ARR_LEN(local_label_stack);
503 * Return the next token.
505 static inline void next_token(void)
507 token = lookahead_buffer[lookahead_bufpos];
508 lookahead_buffer[lookahead_bufpos] = lexer_token;
511 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
514 print_token(stderr, &token);
515 fprintf(stderr, "\n");
520 * Return the next token with a given lookahead.
522 static inline const token_t *look_ahead(int num)
524 assert(num > 0 && num <= MAX_LOOKAHEAD);
525 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
526 return &lookahead_buffer[pos];
530 * Adds a token to the token anchor set (a multi-set).
532 static void add_anchor_token(int token_type)
534 assert(0 <= token_type && token_type < T_LAST_TOKEN);
535 ++token_anchor_set[token_type];
538 static int save_and_reset_anchor_state(int token_type)
540 assert(0 <= token_type && token_type < T_LAST_TOKEN);
541 int count = token_anchor_set[token_type];
542 token_anchor_set[token_type] = 0;
546 static void restore_anchor_state(int token_type, int count)
548 assert(0 <= token_type && token_type < T_LAST_TOKEN);
549 token_anchor_set[token_type] = count;
553 * Remove a token from the token anchor set (a multi-set).
555 static void rem_anchor_token(int token_type)
557 assert(0 <= token_type && token_type < T_LAST_TOKEN);
558 assert(token_anchor_set[token_type] != 0);
559 --token_anchor_set[token_type];
562 static bool at_anchor(void)
566 return token_anchor_set[token.type];
570 * Eat tokens until a matching token is found.
572 static void eat_until_matching_token(int type)
576 case '(': end_token = ')'; break;
577 case '{': end_token = '}'; break;
578 case '[': end_token = ']'; break;
579 default: end_token = type; break;
582 unsigned parenthesis_count = 0;
583 unsigned brace_count = 0;
584 unsigned bracket_count = 0;
585 while (token.type != end_token ||
586 parenthesis_count != 0 ||
588 bracket_count != 0) {
589 switch (token.type) {
591 case '(': ++parenthesis_count; break;
592 case '{': ++brace_count; break;
593 case '[': ++bracket_count; break;
596 if (parenthesis_count > 0)
606 if (bracket_count > 0)
609 if (token.type == end_token &&
610 parenthesis_count == 0 &&
624 * Eat input tokens until an anchor is found.
626 static void eat_until_anchor(void)
628 if (token.type == T_EOF)
630 while (token_anchor_set[token.type] == 0) {
631 if (token.type == '(' || token.type == '{' || token.type == '[')
632 eat_until_matching_token(token.type);
633 if (token.type == T_EOF)
639 static void eat_block(void)
641 eat_until_matching_token('{');
642 if (token.type == '}')
647 * eat all token until a ';' is reached or a stop token is found.
649 static void eat_statement(void)
651 eat_until_matching_token(';');
652 if (token.type == ';')
656 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
659 * Report a parse error because an expected token was not found.
662 #if defined __GNUC__ && __GNUC__ >= 4
663 __attribute__((sentinel))
665 void parse_error_expected(const char *message, ...)
667 if (message != NULL) {
668 errorf(HERE, "%s", message);
671 va_start(ap, message);
672 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
677 * Report a type error.
679 static void type_error(const char *msg, const source_position_t *source_position,
682 errorf(source_position, "%s, but found type '%T'", msg, type);
686 * Report an incompatible type.
688 static void type_error_incompatible(const char *msg,
689 const source_position_t *source_position, type_t *type1, type_t *type2)
691 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
696 * Expect the the current token is the expected token.
697 * If not, generate an error, eat the current statement,
698 * and goto the end_error label.
700 #define expect(expected) \
702 if (UNLIKELY(token.type != (expected))) { \
703 parse_error_expected(NULL, (expected), NULL); \
704 add_anchor_token(expected); \
705 eat_until_anchor(); \
706 if (token.type == expected) \
708 rem_anchor_token(expected); \
714 static void set_scope(scope_t *new_scope)
717 scope->last_declaration = last_declaration;
721 last_declaration = new_scope->last_declaration;
725 * Search a symbol in a given namespace and returns its declaration or
726 * NULL if this symbol was not found.
728 static declaration_t *get_declaration(const symbol_t *const symbol,
729 const namespace_t namespc)
731 declaration_t *declaration = symbol->declaration;
732 for( ; declaration != NULL; declaration = declaration->symbol_next) {
733 if (declaration->namespc == namespc)
741 * pushs an environment_entry on the environment stack and links the
742 * corresponding symbol to the new entry
744 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
746 symbol_t *symbol = declaration->symbol;
747 namespace_t namespc = (namespace_t) declaration->namespc;
749 /* replace/add declaration into declaration list of the symbol */
750 declaration_t *iter = symbol->declaration;
752 symbol->declaration = declaration;
754 declaration_t *iter_last = NULL;
755 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
756 /* replace an entry? */
757 if (iter->namespc == namespc) {
758 if (iter_last == NULL) {
759 symbol->declaration = declaration;
761 iter_last->symbol_next = declaration;
763 declaration->symbol_next = iter->symbol_next;
768 assert(iter_last->symbol_next == NULL);
769 iter_last->symbol_next = declaration;
773 /* remember old declaration */
775 entry.symbol = symbol;
776 entry.old_declaration = iter;
777 entry.namespc = (unsigned short) namespc;
778 ARR_APP1(stack_entry_t, *stack_ptr, entry);
782 * Push a declaration on the environment stack.
784 * @param declaration the declaration
786 static void environment_push(declaration_t *declaration)
788 assert(declaration->source_position.input_name != NULL);
789 assert(declaration->parent_scope != NULL);
790 stack_push(&environment_stack, declaration);
794 * Push a declaration on the global label stack.
796 * @param declaration the declaration
798 static void label_push(declaration_t *declaration)
800 declaration->parent_scope = ¤t_function->scope;
801 stack_push(&label_stack, declaration);
805 * Push a declaration of the local label stack.
807 * @param declaration the declaration
809 static void local_label_push(declaration_t *declaration)
811 assert(declaration->parent_scope != NULL);
812 stack_push(&local_label_stack, declaration);
816 * pops symbols from the environment stack until @p new_top is the top element
818 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
820 stack_entry_t *stack = *stack_ptr;
821 size_t top = ARR_LEN(stack);
824 assert(new_top <= top);
828 for(i = top; i > new_top; --i) {
829 stack_entry_t *entry = &stack[i - 1];
831 declaration_t *old_declaration = entry->old_declaration;
832 symbol_t *symbol = entry->symbol;
833 namespace_t namespc = (namespace_t)entry->namespc;
835 /* replace/remove declaration */
836 declaration_t *declaration = symbol->declaration;
837 assert(declaration != NULL);
838 if (declaration->namespc == namespc) {
839 if (old_declaration == NULL) {
840 symbol->declaration = declaration->symbol_next;
842 symbol->declaration = old_declaration;
845 declaration_t *iter_last = declaration;
846 declaration_t *iter = declaration->symbol_next;
847 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
848 /* replace an entry? */
849 if (iter->namespc == namespc) {
850 assert(iter_last != NULL);
851 iter_last->symbol_next = old_declaration;
852 if (old_declaration != NULL) {
853 old_declaration->symbol_next = iter->symbol_next;
858 assert(iter != NULL);
862 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
866 * Pop all entries from the environment stack until the new_top
869 * @param new_top the new stack top
871 static void environment_pop_to(size_t new_top)
873 stack_pop_to(&environment_stack, new_top);
877 * Pop all entries from the global label stack until the new_top
880 * @param new_top the new stack top
882 static void label_pop_to(size_t new_top)
884 stack_pop_to(&label_stack, new_top);
888 * Pop all entries from the local label stack until the new_top
891 * @param new_top the new stack top
893 static void local_label_pop_to(size_t new_top)
895 stack_pop_to(&local_label_stack, new_top);
899 static int get_akind_rank(atomic_type_kind_t akind)
904 static int get_rank(const type_t *type)
906 assert(!is_typeref(type));
907 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
908 * and esp. footnote 108). However we can't fold constants (yet), so we
909 * can't decide whether unsigned int is possible, while int always works.
910 * (unsigned int would be preferable when possible... for stuff like
911 * struct { enum { ... } bla : 4; } ) */
912 if (type->kind == TYPE_ENUM)
913 return get_akind_rank(ATOMIC_TYPE_INT);
915 assert(type->kind == TYPE_ATOMIC);
916 return get_akind_rank(type->atomic.akind);
919 static type_t *promote_integer(type_t *type)
921 if (type->kind == TYPE_BITFIELD)
922 type = type->bitfield.base_type;
924 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
931 * Create a cast expression.
933 * @param expression the expression to cast
934 * @param dest_type the destination type
936 static expression_t *create_cast_expression(expression_t *expression,
939 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
941 cast->unary.value = expression;
942 cast->base.type = dest_type;
948 * Check if a given expression represents the 0 pointer constant.
950 static bool is_null_pointer_constant(const expression_t *expression)
952 /* skip void* cast */
953 if (expression->kind == EXPR_UNARY_CAST
954 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
955 expression = expression->unary.value;
958 /* TODO: not correct yet, should be any constant integer expression
959 * which evaluates to 0 */
960 if (expression->kind != EXPR_CONST)
963 type_t *const type = skip_typeref(expression->base.type);
964 if (!is_type_integer(type))
967 return expression->conste.v.int_value == 0;
971 * Create an implicit cast expression.
973 * @param expression the expression to cast
974 * @param dest_type the destination type
976 static expression_t *create_implicit_cast(expression_t *expression,
979 type_t *const source_type = expression->base.type;
981 if (source_type == dest_type)
984 return create_cast_expression(expression, dest_type);
987 typedef enum assign_error_t {
989 ASSIGN_ERROR_INCOMPATIBLE,
990 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
991 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
992 ASSIGN_WARNING_POINTER_FROM_INT,
993 ASSIGN_WARNING_INT_FROM_POINTER
996 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
997 const expression_t *const right,
999 const source_position_t *source_position)
1001 type_t *const orig_type_right = right->base.type;
1002 type_t *const type_left = skip_typeref(orig_type_left);
1003 type_t *const type_right = skip_typeref(orig_type_right);
1006 case ASSIGN_SUCCESS:
1008 case ASSIGN_ERROR_INCOMPATIBLE:
1009 errorf(source_position,
1010 "destination type '%T' in %s is incompatible with type '%T'",
1011 orig_type_left, context, orig_type_right);
1014 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1015 type_t *points_to_left
1016 = skip_typeref(type_left->pointer.points_to);
1017 type_t *points_to_right
1018 = skip_typeref(type_right->pointer.points_to);
1020 /* the left type has all qualifiers from the right type */
1021 unsigned missing_qualifiers
1022 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1023 warningf(source_position,
1024 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1025 orig_type_left, context, orig_type_right, missing_qualifiers);
1029 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1030 warningf(source_position,
1031 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1032 orig_type_left, context, right, orig_type_right);
1035 case ASSIGN_WARNING_POINTER_FROM_INT:
1036 warningf(source_position,
1037 "%s makes pointer '%T' from integer '%T' without a cast",
1038 context, orig_type_left, orig_type_right);
1041 case ASSIGN_WARNING_INT_FROM_POINTER:
1042 warningf(source_position,
1043 "%s makes integer '%T' from pointer '%T' without a cast",
1044 context, orig_type_left, orig_type_right);
1048 panic("invalid error value");
1052 /** Implements the rules from § 6.5.16.1 */
1053 static assign_error_t semantic_assign(type_t *orig_type_left,
1054 const expression_t *const right)
1056 type_t *const orig_type_right = right->base.type;
1057 type_t *const type_left = skip_typeref(orig_type_left);
1058 type_t *const type_right = skip_typeref(orig_type_right);
1060 if (is_type_pointer(type_left)) {
1061 if (is_null_pointer_constant(right)) {
1062 return ASSIGN_SUCCESS;
1063 } else if (is_type_pointer(type_right)) {
1064 type_t *points_to_left
1065 = skip_typeref(type_left->pointer.points_to);
1066 type_t *points_to_right
1067 = skip_typeref(type_right->pointer.points_to);
1068 assign_error_t res = ASSIGN_SUCCESS;
1070 /* the left type has all qualifiers from the right type */
1071 unsigned missing_qualifiers
1072 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1073 if (missing_qualifiers != 0) {
1074 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1077 points_to_left = get_unqualified_type(points_to_left);
1078 points_to_right = get_unqualified_type(points_to_right);
1080 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1081 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1085 if (!types_compatible(points_to_left, points_to_right)) {
1086 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1090 } else if (is_type_integer(type_right)) {
1091 return ASSIGN_WARNING_POINTER_FROM_INT;
1093 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1094 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1095 && is_type_pointer(type_right))) {
1096 return ASSIGN_SUCCESS;
1097 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1098 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1099 type_t *const unqual_type_left = get_unqualified_type(type_left);
1100 type_t *const unqual_type_right = get_unqualified_type(type_right);
1101 if (types_compatible(unqual_type_left, unqual_type_right)) {
1102 return ASSIGN_SUCCESS;
1104 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1105 return ASSIGN_WARNING_INT_FROM_POINTER;
1108 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1109 return ASSIGN_SUCCESS;
1111 return ASSIGN_ERROR_INCOMPATIBLE;
1114 static expression_t *parse_constant_expression(void)
1116 /* start parsing at precedence 7 (conditional expression) */
1117 expression_t *result = parse_sub_expression(7);
1119 if (!is_constant_expression(result)) {
1120 errorf(&result->base.source_position,
1121 "expression '%E' is not constant\n", result);
1127 static expression_t *parse_assignment_expression(void)
1129 /* start parsing at precedence 2 (assignment expression) */
1130 return parse_sub_expression(2);
1133 static type_t *make_global_typedef(const char *name, type_t *type)
1135 symbol_t *const symbol = symbol_table_insert(name);
1137 declaration_t *const declaration = allocate_declaration_zero();
1138 declaration->namespc = NAMESPACE_NORMAL;
1139 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1140 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1141 declaration->type = type;
1142 declaration->symbol = symbol;
1143 declaration->source_position = builtin_source_position;
1144 declaration->implicit = true;
1146 record_declaration(declaration, false);
1148 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1149 typedef_type->typedeft.declaration = declaration;
1151 return typedef_type;
1154 static string_t parse_string_literals(void)
1156 assert(token.type == T_STRING_LITERAL);
1157 string_t result = token.v.string;
1161 while (token.type == T_STRING_LITERAL) {
1162 result = concat_strings(&result, &token.v.string);
1169 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1170 [GNU_AK_CONST] = "const",
1171 [GNU_AK_VOLATILE] = "volatile",
1172 [GNU_AK_CDECL] = "cdecl",
1173 [GNU_AK_STDCALL] = "stdcall",
1174 [GNU_AK_FASTCALL] = "fastcall",
1175 [GNU_AK_DEPRECATED] = "deprecated",
1176 [GNU_AK_NOINLINE] = "noinline",
1177 [GNU_AK_NORETURN] = "noreturn",
1178 [GNU_AK_NAKED] = "naked",
1179 [GNU_AK_PURE] = "pure",
1180 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1181 [GNU_AK_MALLOC] = "malloc",
1182 [GNU_AK_WEAK] = "weak",
1183 [GNU_AK_CONSTRUCTOR] = "constructor",
1184 [GNU_AK_DESTRUCTOR] = "destructor",
1185 [GNU_AK_NOTHROW] = "nothrow",
1186 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1187 [GNU_AK_COMMON] = "common",
1188 [GNU_AK_NOCOMMON] = "nocommon",
1189 [GNU_AK_PACKED] = "packed",
1190 [GNU_AK_SHARED] = "shared",
1191 [GNU_AK_NOTSHARED] = "notshared",
1192 [GNU_AK_USED] = "used",
1193 [GNU_AK_UNUSED] = "unused",
1194 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1195 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1196 [GNU_AK_LONGCALL] = "longcall",
1197 [GNU_AK_SHORTCALL] = "shortcall",
1198 [GNU_AK_LONG_CALL] = "long_call",
1199 [GNU_AK_SHORT_CALL] = "short_call",
1200 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1201 [GNU_AK_INTERRUPT] = "interrupt",
1202 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1203 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1204 [GNU_AK_NESTING] = "nesting",
1205 [GNU_AK_NEAR] = "near",
1206 [GNU_AK_FAR] = "far",
1207 [GNU_AK_SIGNAL] = "signal",
1208 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1209 [GNU_AK_TINY_DATA] = "tiny_data",
1210 [GNU_AK_SAVEALL] = "saveall",
1211 [GNU_AK_FLATTEN] = "flatten",
1212 [GNU_AK_SSEREGPARM] = "sseregparm",
1213 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1214 [GNU_AK_RETURN_TWICE] = "return_twice",
1215 [GNU_AK_MAY_ALIAS] = "may_alias",
1216 [GNU_AK_MS_STRUCT] = "ms_struct",
1217 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1218 [GNU_AK_DLLIMPORT] = "dllimport",
1219 [GNU_AK_DLLEXPORT] = "dllexport",
1220 [GNU_AK_ALIGNED] = "aligned",
1221 [GNU_AK_ALIAS] = "alias",
1222 [GNU_AK_SECTION] = "section",
1223 [GNU_AK_FORMAT] = "format",
1224 [GNU_AK_FORMAT_ARG] = "format_arg",
1225 [GNU_AK_WEAKREF] = "weakref",
1226 [GNU_AK_NONNULL] = "nonnull",
1227 [GNU_AK_TLS_MODEL] = "tls_model",
1228 [GNU_AK_VISIBILITY] = "visibility",
1229 [GNU_AK_REGPARM] = "regparm",
1230 [GNU_AK_MODE] = "mode",
1231 [GNU_AK_MODEL] = "model",
1232 [GNU_AK_TRAP_EXIT] = "trap_exit",
1233 [GNU_AK_SP_SWITCH] = "sp_switch",
1234 [GNU_AK_SENTINEL] = "sentinel"
1238 * compare two string, ignoring double underscores on the second.
1240 static int strcmp_underscore(const char *s1, const char *s2)
1242 if (s2[0] == '_' && s2[1] == '_') {
1243 size_t len2 = strlen(s2);
1244 size_t len1 = strlen(s1);
1245 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1246 return strncmp(s1, s2+2, len2-4);
1250 return strcmp(s1, s2);
1254 * Allocate a new gnu temporal attribute.
1256 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1258 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1259 attribute->kind = kind;
1260 attribute->next = NULL;
1261 attribute->invalid = false;
1262 attribute->have_arguments = false;
1268 * parse one constant expression argument.
1270 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1272 expression_t *expression;
1273 add_anchor_token(')');
1274 expression = parse_constant_expression();
1275 rem_anchor_token(')');
1277 attribute->u.argument = fold_constant(expression);
1280 attribute->invalid = true;
1284 * parse a list of constant expressions arguments.
1286 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1288 argument_list_t **list = &attribute->u.arguments;
1289 argument_list_t *entry;
1290 expression_t *expression;
1291 add_anchor_token(')');
1292 add_anchor_token(',');
1294 expression = parse_constant_expression();
1295 entry = obstack_alloc(&temp_obst, sizeof(entry));
1296 entry->argument = fold_constant(expression);
1299 list = &entry->next;
1300 if (token.type != ',')
1304 rem_anchor_token(',');
1305 rem_anchor_token(')');
1309 attribute->invalid = true;
1313 * parse one string literal argument.
1315 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1318 add_anchor_token('(');
1319 if (token.type != T_STRING_LITERAL) {
1320 parse_error_expected("while parsing attribute directive",
1321 T_STRING_LITERAL, NULL);
1324 *string = parse_string_literals();
1325 rem_anchor_token('(');
1329 attribute->invalid = true;
1333 * parse one tls model.
1335 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1337 static const char *const tls_models[] = {
1343 string_t string = { NULL, 0 };
1344 parse_gnu_attribute_string_arg(attribute, &string);
1345 if (string.begin != NULL) {
1346 for(size_t i = 0; i < 4; ++i) {
1347 if (strcmp(tls_models[i], string.begin) == 0) {
1348 attribute->u.value = i;
1352 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1354 attribute->invalid = true;
1358 * parse one tls model.
1360 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1362 static const char *const visibilities[] = {
1368 string_t string = { NULL, 0 };
1369 parse_gnu_attribute_string_arg(attribute, &string);
1370 if (string.begin != NULL) {
1371 for(size_t i = 0; i < 4; ++i) {
1372 if (strcmp(visibilities[i], string.begin) == 0) {
1373 attribute->u.value = i;
1377 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1379 attribute->invalid = true;
1383 * parse one (code) model.
1385 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1387 static const char *const visibilities[] = {
1392 string_t string = { NULL, 0 };
1393 parse_gnu_attribute_string_arg(attribute, &string);
1394 if (string.begin != NULL) {
1395 for(int i = 0; i < 3; ++i) {
1396 if (strcmp(visibilities[i], string.begin) == 0) {
1397 attribute->u.value = i;
1401 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1403 attribute->invalid = true;
1406 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1408 /* TODO: find out what is allowed here... */
1410 /* at least: byte, word, pointer, list of machine modes
1411 * __XXX___ is interpreted as XXX */
1412 add_anchor_token(')');
1414 if (token.type != T_IDENTIFIER) {
1415 expect(T_IDENTIFIER);
1418 /* This isn't really correct, the backend should provide a list of machine
1419 * specific modes (according to gcc philosophy that is...) */
1420 const char *symbol_str = token.v.symbol->string;
1421 if (strcmp_underscore("QI", symbol_str) == 0 ||
1422 strcmp_underscore("byte", symbol_str) == 0) {
1423 attribute->u.akind = ATOMIC_TYPE_CHAR;
1424 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1425 attribute->u.akind = ATOMIC_TYPE_SHORT;
1426 } else if (strcmp_underscore("SI", symbol_str) == 0
1427 || strcmp_underscore("word", symbol_str) == 0
1428 || strcmp_underscore("pointer", symbol_str) == 0) {
1429 attribute->u.akind = ATOMIC_TYPE_INT;
1430 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1431 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1433 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1434 attribute->invalid = true;
1438 rem_anchor_token(')');
1442 attribute->invalid = true;
1446 * parse one interrupt argument.
1448 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1450 static const char *const interrupts[] = {
1457 string_t string = { NULL, 0 };
1458 parse_gnu_attribute_string_arg(attribute, &string);
1459 if (string.begin != NULL) {
1460 for(size_t i = 0; i < 5; ++i) {
1461 if (strcmp(interrupts[i], string.begin) == 0) {
1462 attribute->u.value = i;
1466 errorf(HERE, "'%s' is not an interrupt", string.begin);
1468 attribute->invalid = true;
1472 * parse ( identifier, const expression, const expression )
1474 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1476 static const char *const format_names[] = {
1484 if (token.type != T_IDENTIFIER) {
1485 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1488 const char *name = token.v.symbol->string;
1489 for(i = 0; i < 4; ++i) {
1490 if (strcmp_underscore(format_names[i], name) == 0)
1494 if (warning.attribute)
1495 warningf(HERE, "'%s' is an unrecognized format function type", name);
1500 add_anchor_token(')');
1501 add_anchor_token(',');
1502 parse_constant_expression();
1503 rem_anchor_token(',');
1504 rem_anchor_token(')');
1507 add_anchor_token(')');
1508 parse_constant_expression();
1509 rem_anchor_token(')');
1513 attribute->u.value = true;
1516 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1518 if (!attribute->have_arguments)
1521 /* should have no arguments */
1522 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1523 eat_until_matching_token('(');
1524 /* we have already consumed '(', so we stop before ')', eat it */
1526 attribute->invalid = true;
1530 * Parse one GNU attribute.
1532 * Note that attribute names can be specified WITH or WITHOUT
1533 * double underscores, ie const or __const__.
1535 * The following attributes are parsed without arguments
1560 * no_instrument_function
1561 * warn_unused_result
1578 * externally_visible
1586 * The following attributes are parsed with arguments
1587 * aligned( const expression )
1588 * alias( string literal )
1589 * section( string literal )
1590 * format( identifier, const expression, const expression )
1591 * format_arg( const expression )
1592 * tls_model( string literal )
1593 * visibility( string literal )
1594 * regparm( const expression )
1595 * model( string leteral )
1596 * trap_exit( const expression )
1597 * sp_switch( string literal )
1599 * The following attributes might have arguments
1600 * weak_ref( string literal )
1601 * non_null( const expression // ',' )
1602 * interrupt( string literal )
1603 * sentinel( constant expression )
1605 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1607 gnu_attribute_t *head = *attributes;
1608 gnu_attribute_t *last = *attributes;
1609 decl_modifiers_t modifiers = 0;
1610 gnu_attribute_t *attribute;
1612 eat(T___attribute__);
1616 if (token.type != ')') {
1617 /* find the end of the list */
1619 while (last->next != NULL)
1623 /* non-empty attribute list */
1626 if (token.type == T_const) {
1628 } else if (token.type == T_volatile) {
1630 } else if (token.type == T_cdecl) {
1631 /* __attribute__((cdecl)), WITH ms mode */
1633 } else if (token.type == T_IDENTIFIER) {
1634 const symbol_t *sym = token.v.symbol;
1637 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1644 for(i = 0; i < GNU_AK_LAST; ++i) {
1645 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1648 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1651 if (kind == GNU_AK_LAST) {
1652 if (warning.attribute)
1653 warningf(HERE, "'%s' attribute directive ignored", name);
1655 /* skip possible arguments */
1656 if (token.type == '(') {
1657 eat_until_matching_token(')');
1660 /* check for arguments */
1661 attribute = allocate_gnu_attribute(kind);
1662 if (token.type == '(') {
1664 if (token.type == ')') {
1665 /* empty args are allowed */
1668 attribute->have_arguments = true;
1673 case GNU_AK_VOLATILE:
1678 case GNU_AK_NOCOMMON:
1680 case GNU_AK_NOTSHARED:
1681 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1682 case GNU_AK_WARN_UNUSED_RESULT:
1683 case GNU_AK_LONGCALL:
1684 case GNU_AK_SHORTCALL:
1685 case GNU_AK_LONG_CALL:
1686 case GNU_AK_SHORT_CALL:
1687 case GNU_AK_FUNCTION_VECTOR:
1688 case GNU_AK_INTERRUPT_HANDLER:
1689 case GNU_AK_NMI_HANDLER:
1690 case GNU_AK_NESTING:
1694 case GNU_AK_EIGTHBIT_DATA:
1695 case GNU_AK_TINY_DATA:
1696 case GNU_AK_SAVEALL:
1697 case GNU_AK_FLATTEN:
1698 case GNU_AK_SSEREGPARM:
1699 case GNU_AK_EXTERNALLY_VISIBLE:
1700 case GNU_AK_RETURN_TWICE:
1701 case GNU_AK_MAY_ALIAS:
1702 case GNU_AK_MS_STRUCT:
1703 case GNU_AK_GCC_STRUCT:
1706 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1707 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1708 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1709 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1710 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1711 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1712 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1713 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1714 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1715 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1716 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1717 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1718 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1719 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1720 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1721 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1722 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1724 case GNU_AK_ALIGNED:
1725 /* __align__ may be used without an argument */
1726 if (attribute->have_arguments) {
1727 parse_gnu_attribute_const_arg(attribute);
1731 case GNU_AK_FORMAT_ARG:
1732 case GNU_AK_REGPARM:
1733 case GNU_AK_TRAP_EXIT:
1734 if (!attribute->have_arguments) {
1735 /* should have arguments */
1736 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1737 attribute->invalid = true;
1739 parse_gnu_attribute_const_arg(attribute);
1742 case GNU_AK_SECTION:
1743 case GNU_AK_SP_SWITCH:
1744 if (!attribute->have_arguments) {
1745 /* should have arguments */
1746 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1747 attribute->invalid = true;
1749 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1752 if (!attribute->have_arguments) {
1753 /* should have arguments */
1754 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1755 attribute->invalid = true;
1757 parse_gnu_attribute_format_args(attribute);
1759 case GNU_AK_WEAKREF:
1760 /* may have one string argument */
1761 if (attribute->have_arguments)
1762 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1764 case GNU_AK_NONNULL:
1765 if (attribute->have_arguments)
1766 parse_gnu_attribute_const_arg_list(attribute);
1768 case GNU_AK_TLS_MODEL:
1769 if (!attribute->have_arguments) {
1770 /* should have arguments */
1771 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1773 parse_gnu_attribute_tls_model_arg(attribute);
1775 case GNU_AK_VISIBILITY:
1776 if (!attribute->have_arguments) {
1777 /* should have arguments */
1778 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1780 parse_gnu_attribute_visibility_arg(attribute);
1783 if (!attribute->have_arguments) {
1784 /* should have arguments */
1785 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1787 parse_gnu_attribute_model_arg(attribute);
1791 if (!attribute->have_arguments) {
1792 /* should have arguments */
1793 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1795 parse_gnu_attribute_mode_arg(attribute);
1798 case GNU_AK_INTERRUPT:
1799 /* may have one string argument */
1800 if (attribute->have_arguments)
1801 parse_gnu_attribute_interrupt_arg(attribute);
1803 case GNU_AK_SENTINEL:
1804 /* may have one string argument */
1805 if (attribute->have_arguments)
1806 parse_gnu_attribute_const_arg(attribute);
1809 /* already handled */
1813 check_no_argument(attribute, name);
1816 if (attribute != NULL) {
1818 last->next = attribute;
1821 head = last = attribute;
1825 if (token.type != ',')
1839 * Parse GNU attributes.
1841 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1843 decl_modifiers_t modifiers = 0;
1846 switch(token.type) {
1847 case T___attribute__:
1848 modifiers |= parse_gnu_attribute(attributes);
1854 if (token.type != T_STRING_LITERAL) {
1855 parse_error_expected("while parsing assembler attribute",
1856 T_STRING_LITERAL, NULL);
1857 eat_until_matching_token('(');
1860 parse_string_literals();
1865 case T_cdecl: modifiers |= DM_CDECL; break;
1866 case T__fastcall: modifiers |= DM_FASTCALL; break;
1867 case T__stdcall: modifiers |= DM_STDCALL; break;
1870 /* TODO record modifier */
1871 warningf(HERE, "Ignoring declaration modifier %K", &token);
1875 default: return modifiers;
1882 static designator_t *parse_designation(void)
1884 designator_t *result = NULL;
1885 designator_t *last = NULL;
1888 designator_t *designator;
1889 switch(token.type) {
1891 designator = allocate_ast_zero(sizeof(designator[0]));
1892 designator->source_position = token.source_position;
1894 add_anchor_token(']');
1895 designator->array_index = parse_constant_expression();
1896 rem_anchor_token(']');
1900 designator = allocate_ast_zero(sizeof(designator[0]));
1901 designator->source_position = token.source_position;
1903 if (token.type != T_IDENTIFIER) {
1904 parse_error_expected("while parsing designator",
1905 T_IDENTIFIER, NULL);
1908 designator->symbol = token.v.symbol;
1916 assert(designator != NULL);
1918 last->next = designator;
1920 result = designator;
1928 static initializer_t *initializer_from_string(array_type_t *type,
1929 const string_t *const string)
1931 /* TODO: check len vs. size of array type */
1934 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1935 initializer->string.string = *string;
1940 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1941 wide_string_t *const string)
1943 /* TODO: check len vs. size of array type */
1946 initializer_t *const initializer =
1947 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1948 initializer->wide_string.string = *string;
1954 * Build an initializer from a given expression.
1956 static initializer_t *initializer_from_expression(type_t *orig_type,
1957 expression_t *expression)
1959 /* TODO check that expression is a constant expression */
1961 /* § 6.7.8.14/15 char array may be initialized by string literals */
1962 type_t *type = skip_typeref(orig_type);
1963 type_t *expr_type_orig = expression->base.type;
1964 type_t *expr_type = skip_typeref(expr_type_orig);
1965 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1966 array_type_t *const array_type = &type->array;
1967 type_t *const element_type = skip_typeref(array_type->element_type);
1969 if (element_type->kind == TYPE_ATOMIC) {
1970 atomic_type_kind_t akind = element_type->atomic.akind;
1971 switch (expression->kind) {
1972 case EXPR_STRING_LITERAL:
1973 if (akind == ATOMIC_TYPE_CHAR
1974 || akind == ATOMIC_TYPE_SCHAR
1975 || akind == ATOMIC_TYPE_UCHAR) {
1976 return initializer_from_string(array_type,
1977 &expression->string.value);
1980 case EXPR_WIDE_STRING_LITERAL: {
1981 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1982 if (get_unqualified_type(element_type) == bare_wchar_type) {
1983 return initializer_from_wide_string(array_type,
1984 &expression->wide_string.value);
1994 assign_error_t error = semantic_assign(type, expression);
1995 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1997 report_assign_error(error, type, expression, "initializer",
1998 &expression->base.source_position);
2000 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2001 result->value.value = create_implicit_cast(expression, type);
2007 * Checks if a given expression can be used as an constant initializer.
2009 static bool is_initializer_constant(const expression_t *expression)
2011 return is_constant_expression(expression)
2012 || is_address_constant(expression);
2016 * Parses an scalar initializer.
2018 * § 6.7.8.11; eat {} without warning
2020 static initializer_t *parse_scalar_initializer(type_t *type,
2021 bool must_be_constant)
2023 /* there might be extra {} hierarchies */
2025 if (token.type == '{') {
2026 warningf(HERE, "extra curly braces around scalar initializer");
2030 } while (token.type == '{');
2033 expression_t *expression = parse_assignment_expression();
2034 if (must_be_constant && !is_initializer_constant(expression)) {
2035 errorf(&expression->base.source_position,
2036 "Initialisation expression '%E' is not constant\n",
2040 initializer_t *initializer = initializer_from_expression(type, expression);
2042 if (initializer == NULL) {
2043 errorf(&expression->base.source_position,
2044 "expression '%E' (type '%T') doesn't match expected type '%T'",
2045 expression, expression->base.type, type);
2050 bool additional_warning_displayed = false;
2051 while (braces > 0) {
2052 if (token.type == ',') {
2055 if (token.type != '}') {
2056 if (!additional_warning_displayed) {
2057 warningf(HERE, "additional elements in scalar initializer");
2058 additional_warning_displayed = true;
2069 * An entry in the type path.
2071 typedef struct type_path_entry_t type_path_entry_t;
2072 struct type_path_entry_t {
2073 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2075 size_t index; /**< For array types: the current index. */
2076 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2081 * A type path expression a position inside compound or array types.
2083 typedef struct type_path_t type_path_t;
2084 struct type_path_t {
2085 type_path_entry_t *path; /**< An flexible array containing the current path. */
2086 type_t *top_type; /**< type of the element the path points */
2087 size_t max_index; /**< largest index in outermost array */
2091 * Prints a type path for debugging.
2093 static __attribute__((unused)) void debug_print_type_path(
2094 const type_path_t *path)
2096 size_t len = ARR_LEN(path->path);
2098 for(size_t i = 0; i < len; ++i) {
2099 const type_path_entry_t *entry = & path->path[i];
2101 type_t *type = skip_typeref(entry->type);
2102 if (is_type_compound(type)) {
2103 /* in gcc mode structs can have no members */
2104 if (entry->v.compound_entry == NULL) {
2108 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2109 } else if (is_type_array(type)) {
2110 fprintf(stderr, "[%zu]", entry->v.index);
2112 fprintf(stderr, "-INVALID-");
2115 if (path->top_type != NULL) {
2116 fprintf(stderr, " (");
2117 print_type(path->top_type);
2118 fprintf(stderr, ")");
2123 * Return the top type path entry, ie. in a path
2124 * (type).a.b returns the b.
2126 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2128 size_t len = ARR_LEN(path->path);
2130 return &path->path[len-1];
2134 * Enlarge the type path by an (empty) element.
2136 static type_path_entry_t *append_to_type_path(type_path_t *path)
2138 size_t len = ARR_LEN(path->path);
2139 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2141 type_path_entry_t *result = & path->path[len];
2142 memset(result, 0, sizeof(result[0]));
2147 * Descending into a sub-type. Enter the scope of the current
2150 static void descend_into_subtype(type_path_t *path)
2152 type_t *orig_top_type = path->top_type;
2153 type_t *top_type = skip_typeref(orig_top_type);
2155 type_path_entry_t *top = append_to_type_path(path);
2156 top->type = top_type;
2158 if (is_type_compound(top_type)) {
2159 declaration_t *declaration = top_type->compound.declaration;
2160 declaration_t *entry = declaration->scope.declarations;
2161 top->v.compound_entry = entry;
2163 if (entry != NULL) {
2164 path->top_type = entry->type;
2166 path->top_type = NULL;
2168 } else if (is_type_array(top_type)) {
2170 path->top_type = top_type->array.element_type;
2172 assert(!is_type_valid(top_type));
2177 * Pop an entry from the given type path, ie. returning from
2178 * (type).a.b to (type).a
2180 static void ascend_from_subtype(type_path_t *path)
2182 type_path_entry_t *top = get_type_path_top(path);
2184 path->top_type = top->type;
2186 size_t len = ARR_LEN(path->path);
2187 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2191 * Pop entries from the given type path until the given
2192 * path level is reached.
2194 static void ascend_to(type_path_t *path, size_t top_path_level)
2196 size_t len = ARR_LEN(path->path);
2198 while (len > top_path_level) {
2199 ascend_from_subtype(path);
2200 len = ARR_LEN(path->path);
2204 static bool walk_designator(type_path_t *path, const designator_t *designator,
2205 bool used_in_offsetof)
2207 for( ; designator != NULL; designator = designator->next) {
2208 type_path_entry_t *top = get_type_path_top(path);
2209 type_t *orig_type = top->type;
2211 type_t *type = skip_typeref(orig_type);
2213 if (designator->symbol != NULL) {
2214 symbol_t *symbol = designator->symbol;
2215 if (!is_type_compound(type)) {
2216 if (is_type_valid(type)) {
2217 errorf(&designator->source_position,
2218 "'.%Y' designator used for non-compound type '%T'",
2224 declaration_t *declaration = type->compound.declaration;
2225 declaration_t *iter = declaration->scope.declarations;
2226 for( ; iter != NULL; iter = iter->next) {
2227 if (iter->symbol == symbol) {
2232 errorf(&designator->source_position,
2233 "'%T' has no member named '%Y'", orig_type, symbol);
2236 if (used_in_offsetof) {
2237 type_t *real_type = skip_typeref(iter->type);
2238 if (real_type->kind == TYPE_BITFIELD) {
2239 errorf(&designator->source_position,
2240 "offsetof designator '%Y' may not specify bitfield",
2246 top->type = orig_type;
2247 top->v.compound_entry = iter;
2248 orig_type = iter->type;
2250 expression_t *array_index = designator->array_index;
2251 assert(designator->array_index != NULL);
2253 if (!is_type_array(type)) {
2254 if (is_type_valid(type)) {
2255 errorf(&designator->source_position,
2256 "[%E] designator used for non-array type '%T'",
2257 array_index, orig_type);
2261 if (!is_type_valid(array_index->base.type)) {
2265 long index = fold_constant(array_index);
2266 if (!used_in_offsetof) {
2268 errorf(&designator->source_position,
2269 "array index [%E] must be positive", array_index);
2272 if (type->array.size_constant == true) {
2273 long array_size = type->array.size;
2274 if (index >= array_size) {
2275 errorf(&designator->source_position,
2276 "designator [%E] (%d) exceeds array size %d",
2277 array_index, index, array_size);
2283 top->type = orig_type;
2284 top->v.index = (size_t) index;
2285 orig_type = type->array.element_type;
2287 path->top_type = orig_type;
2289 if (designator->next != NULL) {
2290 descend_into_subtype(path);
2299 static void advance_current_object(type_path_t *path, size_t top_path_level)
2301 type_path_entry_t *top = get_type_path_top(path);
2303 type_t *type = skip_typeref(top->type);
2304 if (is_type_union(type)) {
2305 /* in unions only the first element is initialized */
2306 top->v.compound_entry = NULL;
2307 } else if (is_type_struct(type)) {
2308 declaration_t *entry = top->v.compound_entry;
2310 entry = entry->next;
2311 top->v.compound_entry = entry;
2312 if (entry != NULL) {
2313 path->top_type = entry->type;
2317 assert(is_type_array(type));
2321 if (!type->array.size_constant || top->v.index < type->array.size) {
2326 /* we're past the last member of the current sub-aggregate, try if we
2327 * can ascend in the type hierarchy and continue with another subobject */
2328 size_t len = ARR_LEN(path->path);
2330 if (len > top_path_level) {
2331 ascend_from_subtype(path);
2332 advance_current_object(path, top_path_level);
2334 path->top_type = NULL;
2339 * skip until token is found.
2341 static void skip_until(int type)
2343 while (token.type != type) {
2344 if (token.type == T_EOF)
2351 * skip any {...} blocks until a closing bracket is reached.
2353 static void skip_initializers(void)
2355 if (token.type == '{')
2358 while (token.type != '}') {
2359 if (token.type == T_EOF)
2361 if (token.type == '{') {
2369 static initializer_t *create_empty_initializer(void)
2371 static initializer_t empty_initializer
2372 = { .list = { { INITIALIZER_LIST }, 0 } };
2373 return &empty_initializer;
2377 * Parse a part of an initialiser for a struct or union,
2379 static initializer_t *parse_sub_initializer(type_path_t *path,
2380 type_t *outer_type, size_t top_path_level,
2381 parse_initializer_env_t *env)
2383 if (token.type == '}') {
2384 /* empty initializer */
2385 return create_empty_initializer();
2388 type_t *orig_type = path->top_type;
2389 type_t *type = NULL;
2391 if (orig_type == NULL) {
2392 /* We are initializing an empty compound. */
2394 type = skip_typeref(orig_type);
2396 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2397 * initializers in this case. */
2398 if (!is_type_valid(type)) {
2399 skip_initializers();
2400 return create_empty_initializer();
2404 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2407 designator_t *designator = NULL;
2408 if (token.type == '.' || token.type == '[') {
2409 designator = parse_designation();
2410 goto finish_designator;
2411 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2412 /* GNU-style designator ("identifier: value") */
2413 designator = allocate_ast_zero(sizeof(designator[0]));
2414 designator->source_position = token.source_position;
2415 designator->symbol = token.v.symbol;
2420 /* reset path to toplevel, evaluate designator from there */
2421 ascend_to(path, top_path_level);
2422 if (!walk_designator(path, designator, false)) {
2423 /* can't continue after designation error */
2427 initializer_t *designator_initializer
2428 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2429 designator_initializer->designator.designator = designator;
2430 ARR_APP1(initializer_t*, initializers, designator_initializer);
2432 orig_type = path->top_type;
2433 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2438 if (token.type == '{') {
2439 if (type != NULL && is_type_scalar(type)) {
2440 sub = parse_scalar_initializer(type, env->must_be_constant);
2444 if (env->declaration != NULL) {
2445 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2446 env->declaration->symbol);
2448 errorf(HERE, "extra brace group at end of initializer");
2451 descend_into_subtype(path);
2453 add_anchor_token('}');
2454 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2456 rem_anchor_token('}');
2459 ascend_from_subtype(path);
2463 goto error_parse_next;
2467 /* must be an expression */
2468 expression_t *expression = parse_assignment_expression();
2470 if (env->must_be_constant && !is_initializer_constant(expression)) {
2471 errorf(&expression->base.source_position,
2472 "Initialisation expression '%E' is not constant\n",
2477 /* we are already outside, ... */
2478 if (is_type_compound(outer_type) &&
2479 !outer_type->compound.declaration->init.complete) {
2480 goto error_parse_next;
2485 /* handle { "string" } special case */
2486 if ((expression->kind == EXPR_STRING_LITERAL
2487 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2488 && outer_type != NULL) {
2489 sub = initializer_from_expression(outer_type, expression);
2491 if (token.type == ',') {
2494 if (token.type != '}') {
2495 warningf(HERE, "excessive elements in initializer for type '%T'",
2498 /* TODO: eat , ... */
2503 /* descend into subtypes until expression matches type */
2505 orig_type = path->top_type;
2506 type = skip_typeref(orig_type);
2508 sub = initializer_from_expression(orig_type, expression);
2512 if (!is_type_valid(type)) {
2515 if (is_type_scalar(type)) {
2516 errorf(&expression->base.source_position,
2517 "expression '%E' doesn't match expected type '%T'",
2518 expression, orig_type);
2522 descend_into_subtype(path);
2526 /* update largest index of top array */
2527 const type_path_entry_t *first = &path->path[0];
2528 type_t *first_type = first->type;
2529 first_type = skip_typeref(first_type);
2530 if (is_type_array(first_type)) {
2531 size_t index = first->v.index;
2532 if (index > path->max_index)
2533 path->max_index = index;
2537 /* append to initializers list */
2538 ARR_APP1(initializer_t*, initializers, sub);
2541 if (env->declaration != NULL)
2542 warningf(HERE, "excess elements in struct initializer for '%Y'",
2543 env->declaration->symbol);
2545 warningf(HERE, "excess elements in struct initializer");
2549 if (token.type == '}') {
2553 if (token.type == '}') {
2558 /* advance to the next declaration if we are not at the end */
2559 advance_current_object(path, top_path_level);
2560 orig_type = path->top_type;
2561 if (orig_type != NULL)
2562 type = skip_typeref(orig_type);
2568 size_t len = ARR_LEN(initializers);
2569 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2570 initializer_t *result = allocate_ast_zero(size);
2571 result->kind = INITIALIZER_LIST;
2572 result->list.len = len;
2573 memcpy(&result->list.initializers, initializers,
2574 len * sizeof(initializers[0]));
2576 DEL_ARR_F(initializers);
2577 ascend_to(path, top_path_level+1);
2582 skip_initializers();
2583 DEL_ARR_F(initializers);
2584 ascend_to(path, top_path_level+1);
2589 * Parses an initializer. Parsers either a compound literal
2590 * (env->declaration == NULL) or an initializer of a declaration.
2592 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2594 type_t *type = skip_typeref(env->type);
2595 initializer_t *result = NULL;
2598 if (is_type_scalar(type)) {
2599 result = parse_scalar_initializer(type, env->must_be_constant);
2600 } else if (token.type == '{') {
2604 memset(&path, 0, sizeof(path));
2605 path.top_type = env->type;
2606 path.path = NEW_ARR_F(type_path_entry_t, 0);
2608 descend_into_subtype(&path);
2610 add_anchor_token('}');
2611 result = parse_sub_initializer(&path, env->type, 1, env);
2612 rem_anchor_token('}');
2614 max_index = path.max_index;
2615 DEL_ARR_F(path.path);
2619 /* parse_scalar_initializer() also works in this case: we simply
2620 * have an expression without {} around it */
2621 result = parse_scalar_initializer(type, env->must_be_constant);
2624 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2625 * the array type size */
2626 if (is_type_array(type) && type->array.size_expression == NULL
2627 && result != NULL) {
2629 switch (result->kind) {
2630 case INITIALIZER_LIST:
2631 size = max_index + 1;
2634 case INITIALIZER_STRING:
2635 size = result->string.string.size;
2638 case INITIALIZER_WIDE_STRING:
2639 size = result->wide_string.string.size;
2642 case INITIALIZER_DESIGNATOR:
2643 case INITIALIZER_VALUE:
2644 /* can happen for parse errors */
2649 internal_errorf(HERE, "invalid initializer type");
2652 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2653 cnst->base.type = type_size_t;
2654 cnst->conste.v.int_value = size;
2656 type_t *new_type = duplicate_type(type);
2658 new_type->array.size_expression = cnst;
2659 new_type->array.size_constant = true;
2660 new_type->array.size = size;
2661 env->type = new_type;
2669 static declaration_t *append_declaration(declaration_t *declaration);
2671 static declaration_t *parse_compound_type_specifier(bool is_struct)
2673 gnu_attribute_t *attributes = NULL;
2674 decl_modifiers_t modifiers = 0;
2681 symbol_t *symbol = NULL;
2682 declaration_t *declaration = NULL;
2684 if (token.type == T___attribute__) {
2685 modifiers |= parse_attributes(&attributes);
2688 if (token.type == T_IDENTIFIER) {
2689 symbol = token.v.symbol;
2692 namespace_t const namespc =
2693 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2694 declaration = get_declaration(symbol, namespc);
2695 if (declaration != NULL) {
2696 if (declaration->parent_scope != scope &&
2697 (token.type == '{' || token.type == ';')) {
2699 } else if (declaration->init.complete &&
2700 token.type == '{') {
2701 assert(symbol != NULL);
2702 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2703 is_struct ? "struct" : "union", symbol,
2704 &declaration->source_position);
2705 declaration->scope.declarations = NULL;
2708 } else if (token.type != '{') {
2710 parse_error_expected("while parsing struct type specifier",
2711 T_IDENTIFIER, '{', NULL);
2713 parse_error_expected("while parsing union type specifier",
2714 T_IDENTIFIER, '{', NULL);
2720 if (declaration == NULL) {
2721 declaration = allocate_declaration_zero();
2722 declaration->namespc =
2723 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2724 declaration->source_position = token.source_position;
2725 declaration->symbol = symbol;
2726 declaration->parent_scope = scope;
2727 if (symbol != NULL) {
2728 environment_push(declaration);
2730 append_declaration(declaration);
2733 if (token.type == '{') {
2734 declaration->init.complete = true;
2736 parse_compound_type_entries(declaration);
2737 modifiers |= parse_attributes(&attributes);
2740 declaration->modifiers |= modifiers;
2744 static void parse_enum_entries(type_t *const enum_type)
2748 if (token.type == '}') {
2750 errorf(HERE, "empty enum not allowed");
2754 add_anchor_token('}');
2756 if (token.type != T_IDENTIFIER) {
2757 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2759 rem_anchor_token('}');
2763 declaration_t *const entry = allocate_declaration_zero();
2764 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2765 entry->type = enum_type;
2766 entry->symbol = token.v.symbol;
2767 entry->source_position = token.source_position;
2770 if (token.type == '=') {
2772 expression_t *value = parse_constant_expression();
2774 value = create_implicit_cast(value, enum_type);
2775 entry->init.enum_value = value;
2780 record_declaration(entry, false);
2782 if (token.type != ',')
2785 } while (token.type != '}');
2786 rem_anchor_token('}');
2794 static type_t *parse_enum_specifier(void)
2796 gnu_attribute_t *attributes = NULL;
2797 declaration_t *declaration;
2801 if (token.type == T_IDENTIFIER) {
2802 symbol = token.v.symbol;
2805 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2806 } else if (token.type != '{') {
2807 parse_error_expected("while parsing enum type specifier",
2808 T_IDENTIFIER, '{', NULL);
2815 if (declaration == NULL) {
2816 declaration = allocate_declaration_zero();
2817 declaration->namespc = NAMESPACE_ENUM;
2818 declaration->source_position = token.source_position;
2819 declaration->symbol = symbol;
2820 declaration->parent_scope = scope;
2823 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2824 type->enumt.declaration = declaration;
2826 if (token.type == '{') {
2827 if (declaration->init.complete) {
2828 errorf(HERE, "multiple definitions of enum %Y", symbol);
2830 if (symbol != NULL) {
2831 environment_push(declaration);
2833 append_declaration(declaration);
2834 declaration->init.complete = true;
2836 parse_enum_entries(type);
2837 parse_attributes(&attributes);
2844 * if a symbol is a typedef to another type, return true
2846 static bool is_typedef_symbol(symbol_t *symbol)
2848 const declaration_t *const declaration =
2849 get_declaration(symbol, NAMESPACE_NORMAL);
2851 declaration != NULL &&
2852 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2855 static type_t *parse_typeof(void)
2862 add_anchor_token(')');
2864 expression_t *expression = NULL;
2867 switch(token.type) {
2868 case T___extension__:
2869 /* This can be a prefix to a typename or an expression. We simply eat
2873 } while (token.type == T___extension__);
2877 if (is_typedef_symbol(token.v.symbol)) {
2878 type = parse_typename();
2880 expression = parse_expression();
2881 type = expression->base.type;
2886 type = parse_typename();
2890 expression = parse_expression();
2891 type = expression->base.type;
2895 rem_anchor_token(')');
2898 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2899 typeof_type->typeoft.expression = expression;
2900 typeof_type->typeoft.typeof_type = type;
2907 typedef enum specifiers_t {
2908 SPECIFIER_SIGNED = 1 << 0,
2909 SPECIFIER_UNSIGNED = 1 << 1,
2910 SPECIFIER_LONG = 1 << 2,
2911 SPECIFIER_INT = 1 << 3,
2912 SPECIFIER_DOUBLE = 1 << 4,
2913 SPECIFIER_CHAR = 1 << 5,
2914 SPECIFIER_SHORT = 1 << 6,
2915 SPECIFIER_LONG_LONG = 1 << 7,
2916 SPECIFIER_FLOAT = 1 << 8,
2917 SPECIFIER_BOOL = 1 << 9,
2918 SPECIFIER_VOID = 1 << 10,
2919 SPECIFIER_INT8 = 1 << 11,
2920 SPECIFIER_INT16 = 1 << 12,
2921 SPECIFIER_INT32 = 1 << 13,
2922 SPECIFIER_INT64 = 1 << 14,
2923 SPECIFIER_INT128 = 1 << 15,
2924 SPECIFIER_COMPLEX = 1 << 16,
2925 SPECIFIER_IMAGINARY = 1 << 17,
2928 static type_t *create_builtin_type(symbol_t *const symbol,
2929 type_t *const real_type)
2931 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2932 type->builtin.symbol = symbol;
2933 type->builtin.real_type = real_type;
2935 type_t *result = typehash_insert(type);
2936 if (type != result) {
2943 static type_t *get_typedef_type(symbol_t *symbol)
2945 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2946 if (declaration == NULL ||
2947 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2950 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2951 type->typedeft.declaration = declaration;
2957 * check for the allowed MS alignment values.
2959 static bool check_alignment_value(long long intvalue)
2961 if (intvalue < 1 || intvalue > 8192) {
2962 errorf(HERE, "illegal alignment value");
2965 unsigned v = (unsigned)intvalue;
2966 for(unsigned i = 1; i <= 8192; i += i) {
2970 errorf(HERE, "alignment must be power of two");
2974 #define DET_MOD(name, tag) do { \
2975 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2976 *modifiers |= tag; \
2979 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2981 decl_modifiers_t *modifiers = &specifiers->modifiers;
2984 if (token.type == T_restrict) {
2986 DET_MOD(restrict, DM_RESTRICT);
2988 } else if (token.type != T_IDENTIFIER)
2990 symbol_t *symbol = token.v.symbol;
2991 if (symbol == sym_align) {
2994 if (token.type != T_INTEGER)
2996 if (check_alignment_value(token.v.intvalue)) {
2997 if (specifiers->alignment != 0)
2998 warningf(HERE, "align used more than once");
2999 specifiers->alignment = (unsigned char)token.v.intvalue;
3003 } else if (symbol == sym_allocate) {
3006 if (token.type != T_IDENTIFIER)
3008 (void)token.v.symbol;
3010 } else if (symbol == sym_dllimport) {
3012 DET_MOD(dllimport, DM_DLLIMPORT);
3013 } else if (symbol == sym_dllexport) {
3015 DET_MOD(dllexport, DM_DLLEXPORT);
3016 } else if (symbol == sym_thread) {
3018 DET_MOD(thread, DM_THREAD);
3019 } else if (symbol == sym_naked) {
3021 DET_MOD(naked, DM_NAKED);
3022 } else if (symbol == sym_noinline) {
3024 DET_MOD(noinline, DM_NOINLINE);
3025 } else if (symbol == sym_noreturn) {
3027 DET_MOD(noreturn, DM_NORETURN);
3028 } else if (symbol == sym_nothrow) {
3030 DET_MOD(nothrow, DM_NOTHROW);
3031 } else if (symbol == sym_novtable) {
3033 DET_MOD(novtable, DM_NOVTABLE);
3034 } else if (symbol == sym_property) {
3038 bool is_get = false;
3039 if (token.type != T_IDENTIFIER)
3041 if (token.v.symbol == sym_get) {
3043 } else if (token.v.symbol == sym_put) {
3045 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3050 if (token.type != T_IDENTIFIER)
3053 if (specifiers->get_property_sym != NULL) {
3054 errorf(HERE, "get property name already specified");
3056 specifiers->get_property_sym = token.v.symbol;
3059 if (specifiers->put_property_sym != NULL) {
3060 errorf(HERE, "put property name already specified");
3062 specifiers->put_property_sym = token.v.symbol;
3066 if (token.type == ',') {
3073 } else if (symbol == sym_selectany) {
3075 DET_MOD(selectany, DM_SELECTANY);
3076 } else if (symbol == sym_uuid) {
3079 if (token.type != T_STRING_LITERAL)
3083 } else if (symbol == sym_deprecated) {
3085 if (specifiers->deprecated != 0)
3086 warningf(HERE, "deprecated used more than once");
3087 specifiers->deprecated = 1;
3088 if (token.type == '(') {
3090 if (token.type == T_STRING_LITERAL) {
3091 specifiers->deprecated_string = token.v.string.begin;
3094 errorf(HERE, "string literal expected");
3098 } else if (symbol == sym_noalias) {
3100 DET_MOD(noalias, DM_NOALIAS);
3102 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3104 if (token.type == '(')
3108 if (token.type == ',')
3115 static declaration_t *create_error_declaration(symbol_t *symbol, storage_class_tag_t storage_class)
3117 declaration_t *const decl = allocate_declaration_zero();
3118 decl->source_position = *HERE;
3119 decl->declared_storage_class = storage_class;
3120 decl->storage_class =
3121 storage_class != STORAGE_CLASS_NONE || scope == global_scope ?
3122 storage_class : STORAGE_CLASS_AUTO;
3123 decl->symbol = symbol;
3124 decl->implicit = true;
3125 record_declaration(decl, false);
3130 * Finish the construction of a struct type by calculating
3131 * its size, offsets, alignment.
3133 static void finish_struct_type(compound_type_t *type) {
3134 if (type->declaration == NULL)
3136 declaration_t *struct_decl = type->declaration;
3137 if (! struct_decl->init.complete)
3142 il_alignment_t alignment = 1;
3143 bool need_pad = false;
3145 declaration_t *entry = struct_decl->scope.declarations;
3146 for (; entry != NULL; entry = entry->next) {
3147 if (entry->namespc != NAMESPACE_NORMAL)
3150 type_t *m_type = skip_typeref(entry->type);
3151 if (! is_type_valid(m_type)) {
3152 /* simply ignore errors here */
3155 il_alignment_t m_alignment = m_type->base.alignment;
3156 if (m_alignment > alignment)
3157 alignment = m_alignment;
3159 offset = (size + m_alignment - 1) & -m_alignment;
3163 entry->offset = offset;
3164 size = offset + m_type->base.size;
3166 if (type->base.alignment != 0) {
3167 alignment = type->base.alignment;
3170 offset = (size + alignment - 1) & -alignment;
3174 if (warning.padded && need_pad) {
3175 warningf(&struct_decl->source_position,
3176 "'%#T' needs padding", type, struct_decl->symbol);
3178 if (warning.packed && !need_pad) {
3179 warningf(&struct_decl->source_position,
3180 "superfluous packed attribute on '%#T'",
3181 type, struct_decl->symbol);
3184 type->base.size = offset;
3185 type->base.alignment = alignment;
3189 * Finish the construction of an union type by calculating
3190 * its size and alignment.
3192 static void finish_union_type(compound_type_t *type) {
3193 if (type->declaration == NULL)
3195 declaration_t *union_decl = type->declaration;
3196 if (! union_decl->init.complete)
3200 il_alignment_t alignment = 1;
3202 declaration_t *entry = union_decl->scope.declarations;
3203 for (; entry != NULL; entry = entry->next) {
3204 if (entry->namespc != NAMESPACE_NORMAL)
3207 type_t *m_type = skip_typeref(entry->type);
3208 if (! is_type_valid(m_type))
3212 if (m_type->base.size > size)
3213 size = m_type->base.size;
3214 if (m_type->base.alignment > alignment)
3215 alignment = m_type->base.alignment;
3217 if (type->base.alignment != 0) {
3218 alignment = type->base.alignment;
3220 size = (size + alignment - 1) & -alignment;
3221 type->base.size = size;
3222 type->base.alignment = alignment;
3225 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3227 type_t *type = NULL;
3228 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3229 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3230 unsigned type_specifiers = 0;
3231 bool newtype = false;
3232 bool saw_error = false;
3234 specifiers->source_position = token.source_position;
3237 specifiers->modifiers
3238 |= parse_attributes(&specifiers->gnu_attributes);
3239 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3240 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3242 switch(token.type) {
3245 #define MATCH_STORAGE_CLASS(token, class) \
3247 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3248 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3250 specifiers->declared_storage_class = class; \
3254 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3255 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3256 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3257 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3258 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3263 add_anchor_token(')');
3264 parse_microsoft_extended_decl_modifier(specifiers);
3265 rem_anchor_token(')');
3270 switch (specifiers->declared_storage_class) {
3271 case STORAGE_CLASS_NONE:
3272 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3275 case STORAGE_CLASS_EXTERN:
3276 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3279 case STORAGE_CLASS_STATIC:
3280 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3284 errorf(HERE, "multiple storage classes in declaration specifiers");
3290 /* type qualifiers */
3291 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3293 qualifiers |= qualifier; \
3297 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3298 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3299 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3300 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3301 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3302 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3303 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3304 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3306 case T___extension__:
3311 /* type specifiers */
3312 #define MATCH_SPECIFIER(token, specifier, name) \
3315 if (type_specifiers & specifier) { \
3316 errorf(HERE, "multiple " name " type specifiers given"); \
3318 type_specifiers |= specifier; \
3322 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3323 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3324 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3325 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3326 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3327 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3328 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3329 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3330 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3331 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3332 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3333 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3334 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3335 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3336 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3337 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3339 case T__forceinline:
3340 /* only in microsoft mode */
3341 specifiers->modifiers |= DM_FORCEINLINE;
3346 specifiers->is_inline = true;
3351 if (type_specifiers & SPECIFIER_LONG_LONG) {
3352 errorf(HERE, "multiple type specifiers given");
3353 } else if (type_specifiers & SPECIFIER_LONG) {
3354 type_specifiers |= SPECIFIER_LONG_LONG;
3356 type_specifiers |= SPECIFIER_LONG;
3361 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3363 type->compound.declaration = parse_compound_type_specifier(true);
3364 finish_struct_type(&type->compound);
3368 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3369 type->compound.declaration = parse_compound_type_specifier(false);
3370 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3371 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3373 finish_union_type(&type->compound);
3376 type = parse_enum_specifier();
3379 type = parse_typeof();
3381 case T___builtin_va_list:
3382 type = duplicate_type(type_valist);
3386 case T_IDENTIFIER: {
3387 /* only parse identifier if we haven't found a type yet */
3388 if (type != NULL || type_specifiers != 0) {
3389 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3390 * declaration, so it doesn't generate errors about expecting '(' or
3392 switch (look_ahead(1)->type) {
3399 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3402 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3407 goto finish_specifiers;
3411 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3412 if (typedef_type == NULL) {
3413 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3414 * declaration, so it doesn't generate 'implicit int' followed by more
3415 * errors later on. */
3416 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3421 errorf(HERE, "%K does not name a type", &token);
3423 declaration_t *const decl =
3424 create_error_declaration(token.v.symbol, STORAGE_CLASS_TYPEDEF);
3426 type = allocate_type_zero(TYPE_TYPEDEF, HERE);
3427 type->typedeft.declaration = decl;
3431 if (la1_type == '*')
3432 goto finish_specifiers;
3437 goto finish_specifiers;
3442 type = typedef_type;
3446 /* function specifier */
3448 goto finish_specifiers;
3453 if (type == NULL || (saw_error && type_specifiers != 0)) {
3454 atomic_type_kind_t atomic_type;
3456 /* match valid basic types */
3457 switch(type_specifiers) {
3458 case SPECIFIER_VOID:
3459 atomic_type = ATOMIC_TYPE_VOID;
3461 case SPECIFIER_CHAR:
3462 atomic_type = ATOMIC_TYPE_CHAR;
3464 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3465 atomic_type = ATOMIC_TYPE_SCHAR;
3467 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3468 atomic_type = ATOMIC_TYPE_UCHAR;
3470 case SPECIFIER_SHORT:
3471 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3472 case SPECIFIER_SHORT | SPECIFIER_INT:
3473 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3474 atomic_type = ATOMIC_TYPE_SHORT;
3476 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3477 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3478 atomic_type = ATOMIC_TYPE_USHORT;
3481 case SPECIFIER_SIGNED:
3482 case SPECIFIER_SIGNED | SPECIFIER_INT:
3483 atomic_type = ATOMIC_TYPE_INT;
3485 case SPECIFIER_UNSIGNED:
3486 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3487 atomic_type = ATOMIC_TYPE_UINT;
3489 case SPECIFIER_LONG:
3490 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3491 case SPECIFIER_LONG | SPECIFIER_INT:
3492 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3493 atomic_type = ATOMIC_TYPE_LONG;
3495 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3496 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3497 atomic_type = ATOMIC_TYPE_ULONG;
3500 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3501 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3502 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3503 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3505 atomic_type = ATOMIC_TYPE_LONGLONG;
3506 goto warn_about_long_long;
3508 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3509 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3511 atomic_type = ATOMIC_TYPE_ULONGLONG;
3512 warn_about_long_long:
3513 if (warning.long_long) {
3514 warningf(&specifiers->source_position,
3515 "ISO C90 does not support 'long long'");
3519 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3520 atomic_type = unsigned_int8_type_kind;
3523 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3524 atomic_type = unsigned_int16_type_kind;
3527 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3528 atomic_type = unsigned_int32_type_kind;
3531 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3532 atomic_type = unsigned_int64_type_kind;
3535 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3536 atomic_type = unsigned_int128_type_kind;
3539 case SPECIFIER_INT8:
3540 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3541 atomic_type = int8_type_kind;
3544 case SPECIFIER_INT16:
3545 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3546 atomic_type = int16_type_kind;
3549 case SPECIFIER_INT32:
3550 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3551 atomic_type = int32_type_kind;
3554 case SPECIFIER_INT64:
3555 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3556 atomic_type = int64_type_kind;
3559 case SPECIFIER_INT128:
3560 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3561 atomic_type = int128_type_kind;
3564 case SPECIFIER_FLOAT:
3565 atomic_type = ATOMIC_TYPE_FLOAT;
3567 case SPECIFIER_DOUBLE:
3568 atomic_type = ATOMIC_TYPE_DOUBLE;
3570 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3571 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3573 case SPECIFIER_BOOL:
3574 atomic_type = ATOMIC_TYPE_BOOL;
3576 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3577 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3578 atomic_type = ATOMIC_TYPE_FLOAT;
3580 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3581 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3582 atomic_type = ATOMIC_TYPE_DOUBLE;
3584 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3585 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3586 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3589 /* invalid specifier combination, give an error message */
3590 if (type_specifiers == 0) {
3595 if (warning.implicit_int) {
3596 warningf(HERE, "no type specifiers in declaration, using 'int'");
3598 atomic_type = ATOMIC_TYPE_INT;
3601 errorf(HERE, "no type specifiers given in declaration");
3603 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3604 (type_specifiers & SPECIFIER_UNSIGNED)) {
3605 errorf(HERE, "signed and unsigned specifiers given");
3606 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3607 errorf(HERE, "only integer types can be signed or unsigned");
3609 errorf(HERE, "multiple datatypes in declaration");
3614 if (type_specifiers & SPECIFIER_COMPLEX) {
3615 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3616 type->complex.akind = atomic_type;
3617 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3618 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3619 type->imaginary.akind = atomic_type;
3621 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3622 type->atomic.akind = atomic_type;
3625 } else if (type_specifiers != 0) {
3626 errorf(HERE, "multiple datatypes in declaration");
3629 /* FIXME: check type qualifiers here */
3631 type->base.qualifiers = qualifiers;
3632 type->base.modifiers = modifiers;
3634 type_t *result = typehash_insert(type);
3635 if (newtype && result != type) {
3639 specifiers->type = result;
3643 specifiers->type = type_error_type;
3647 static type_qualifiers_t parse_type_qualifiers(void)
3649 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3652 switch(token.type) {
3653 /* type qualifiers */
3654 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3655 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3656 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3657 /* microsoft extended type modifiers */
3658 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3659 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3660 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3661 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3662 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3670 static declaration_t *parse_identifier_list(void)
3672 declaration_t *declarations = NULL;
3673 declaration_t *last_declaration = NULL;
3675 declaration_t *const declaration = allocate_declaration_zero();
3676 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3677 declaration->source_position = token.source_position;
3678 declaration->symbol = token.v.symbol;
3681 if (last_declaration != NULL) {
3682 last_declaration->next = declaration;
3684 declarations = declaration;
3686 last_declaration = declaration;
3688 if (token.type != ',') {
3692 } while (token.type == T_IDENTIFIER);
3694 return declarations;
3697 static type_t *automatic_type_conversion(type_t *orig_type);
3699 static void semantic_parameter(declaration_t *declaration)
3701 /* TODO: improve error messages */
3702 source_position_t const* const pos = &declaration->source_position;
3704 switch (declaration->declared_storage_class) {
3705 case STORAGE_CLASS_TYPEDEF:
3706 errorf(pos, "typedef not allowed in parameter list");
3709 /* Allowed storage classes */
3710 case STORAGE_CLASS_NONE:
3711 case STORAGE_CLASS_REGISTER:
3715 errorf(pos, "parameter may only have none or register storage class");
3719 type_t *const orig_type = declaration->type;
3720 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3721 * sugar. Turn it into a pointer.
3722 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3723 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3725 type_t *const type = automatic_type_conversion(orig_type);
3726 declaration->type = type;
3728 if (is_type_incomplete(skip_typeref(type))) {
3729 errorf(pos, "parameter '%#T' is of incomplete type",
3730 orig_type, declaration->symbol);
3734 static declaration_t *parse_parameter(void)
3736 declaration_specifiers_t specifiers;
3737 memset(&specifiers, 0, sizeof(specifiers));
3739 parse_declaration_specifiers(&specifiers);
3741 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3746 static declaration_t *parse_parameters(function_type_t *type)
3748 declaration_t *declarations = NULL;
3751 add_anchor_token(')');
3752 int saved_comma_state = save_and_reset_anchor_state(',');
3754 if (token.type == T_IDENTIFIER &&
3755 !is_typedef_symbol(token.v.symbol)) {
3756 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3757 if (la1_type == ',' || la1_type == ')') {
3758 type->kr_style_parameters = true;
3759 declarations = parse_identifier_list();
3760 goto parameters_finished;
3764 if (token.type == ')') {
3765 type->unspecified_parameters = 1;
3766 goto parameters_finished;
3769 declaration_t *declaration;
3770 declaration_t *last_declaration = NULL;
3771 function_parameter_t *parameter;
3772 function_parameter_t *last_parameter = NULL;
3775 switch(token.type) {
3779 goto parameters_finished;
3782 case T___extension__:
3784 declaration = parse_parameter();
3786 /* func(void) is not a parameter */
3787 if (last_parameter == NULL
3788 && token.type == ')'
3789 && declaration->symbol == NULL
3790 && skip_typeref(declaration->type) == type_void) {
3791 goto parameters_finished;
3793 semantic_parameter(declaration);
3795 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3796 memset(parameter, 0, sizeof(parameter[0]));
3797 parameter->type = declaration->type;
3799 if (last_parameter != NULL) {
3800 last_declaration->next = declaration;
3801 last_parameter->next = parameter;
3803 type->parameters = parameter;
3804 declarations = declaration;
3806 last_parameter = parameter;
3807 last_declaration = declaration;
3811 goto parameters_finished;
3813 if (token.type != ',') {
3814 goto parameters_finished;
3820 parameters_finished:
3821 rem_anchor_token(')');
3824 restore_anchor_state(',', saved_comma_state);
3825 return declarations;
3828 restore_anchor_state(',', saved_comma_state);
3832 typedef enum construct_type_kind_t {
3837 } construct_type_kind_t;
3839 typedef struct construct_type_t construct_type_t;
3840 struct construct_type_t {
3841 construct_type_kind_t kind;
3842 construct_type_t *next;
3845 typedef struct parsed_pointer_t parsed_pointer_t;
3846 struct parsed_pointer_t {
3847 construct_type_t construct_type;
3848 type_qualifiers_t type_qualifiers;
3851 typedef struct construct_function_type_t construct_function_type_t;
3852 struct construct_function_type_t {
3853 construct_type_t construct_type;
3854 type_t *function_type;
3857 typedef struct parsed_array_t parsed_array_t;
3858 struct parsed_array_t {
3859 construct_type_t construct_type;
3860 type_qualifiers_t type_qualifiers;
3866 typedef struct construct_base_type_t construct_base_type_t;
3867 struct construct_base_type_t {
3868 construct_type_t construct_type;
3872 static construct_type_t *parse_pointer_declarator(void)
3876 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3877 memset(pointer, 0, sizeof(pointer[0]));
3878 pointer->construct_type.kind = CONSTRUCT_POINTER;
3879 pointer->type_qualifiers = parse_type_qualifiers();
3881 return (construct_type_t*) pointer;
3884 static construct_type_t *parse_array_declarator(void)
3887 add_anchor_token(']');
3889 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3890 memset(array, 0, sizeof(array[0]));
3891 array->construct_type.kind = CONSTRUCT_ARRAY;
3893 if (token.type == T_static) {
3894 array->is_static = true;
3898 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3899 if (type_qualifiers != 0) {
3900 if (token.type == T_static) {
3901 array->is_static = true;
3905 array->type_qualifiers = type_qualifiers;
3907 if (token.type == '*' && look_ahead(1)->type == ']') {
3908 array->is_variable = true;
3910 } else if (token.type != ']') {
3911 array->size = parse_assignment_expression();
3914 rem_anchor_token(']');
3917 return (construct_type_t*) array;
3922 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3925 if (declaration != NULL) {
3926 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3928 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3930 if (mask & (mask-1)) {
3931 const char *first = NULL, *second = NULL;
3933 /* more than one calling convention set */
3934 if (declaration->modifiers & DM_CDECL) {
3935 if (first == NULL) first = "cdecl";
3936 else if (second == NULL) second = "cdecl";
3938 if (declaration->modifiers & DM_STDCALL) {
3939 if (first == NULL) first = "stdcall";
3940 else if (second == NULL) second = "stdcall";
3942 if (declaration->modifiers & DM_FASTCALL) {
3943 if (first == NULL) first = "fastcall";
3944 else if (second == NULL) second = "fastcall";
3946 if (declaration->modifiers & DM_THISCALL) {
3947 if (first == NULL) first = "thiscall";
3948 else if (second == NULL) second = "thiscall";
3950 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3953 if (declaration->modifiers & DM_CDECL)
3954 type->function.calling_convention = CC_CDECL;
3955 else if (declaration->modifiers & DM_STDCALL)
3956 type->function.calling_convention = CC_STDCALL;
3957 else if (declaration->modifiers & DM_FASTCALL)
3958 type->function.calling_convention = CC_FASTCALL;
3959 else if (declaration->modifiers & DM_THISCALL)
3960 type->function.calling_convention = CC_THISCALL;
3962 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3965 declaration_t *parameters = parse_parameters(&type->function);
3966 if (declaration != NULL) {
3967 declaration->scope.declarations = parameters;
3970 construct_function_type_t *construct_function_type =
3971 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3972 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3973 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3974 construct_function_type->function_type = type;
3976 return &construct_function_type->construct_type;
3979 static void fix_declaration_type(declaration_t *declaration)
3981 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3982 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3984 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3985 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3987 if (declaration->type->base.modifiers == type_modifiers)
3990 type_t *copy = duplicate_type(declaration->type);
3991 copy->base.modifiers = type_modifiers;
3993 type_t *result = typehash_insert(copy);
3994 if (result != copy) {
3995 obstack_free(type_obst, copy);
3998 declaration->type = result;
4001 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
4002 bool may_be_abstract)
4004 /* construct a single linked list of construct_type_t's which describe
4005 * how to construct the final declarator type */
4006 construct_type_t *first = NULL;
4007 construct_type_t *last = NULL;
4008 gnu_attribute_t *attributes = NULL;
4010 decl_modifiers_t modifiers = parse_attributes(&attributes);
4013 while (token.type == '*') {
4014 construct_type_t *type = parse_pointer_declarator();
4024 /* TODO: find out if this is correct */
4025 modifiers |= parse_attributes(&attributes);
4028 if (declaration != NULL)
4029 declaration->modifiers |= modifiers;
4031 construct_type_t *inner_types = NULL;
4033 switch(token.type) {
4035 if (declaration == NULL) {
4036 errorf(HERE, "no identifier expected in typename");
4038 declaration->symbol = token.v.symbol;
4039 declaration->source_position = token.source_position;
4045 add_anchor_token(')');
4046 inner_types = parse_inner_declarator(declaration, may_be_abstract);
4047 if (inner_types != NULL) {
4048 /* All later declarators only modify the return type, not declaration */
4051 rem_anchor_token(')');
4055 if (may_be_abstract)
4057 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4058 /* avoid a loop in the outermost scope, because eat_statement doesn't
4060 if (token.type == '}' && current_function == NULL) {
4068 construct_type_t *p = last;
4071 construct_type_t *type;
4072 switch(token.type) {
4074 type = parse_function_declarator(declaration);
4077 type = parse_array_declarator();
4080 goto declarator_finished;
4083 /* insert in the middle of the list (behind p) */
4085 type->next = p->next;
4096 declarator_finished:
4097 /* append inner_types at the end of the list, we don't to set last anymore
4098 * as it's not needed anymore */
4100 assert(first == NULL);
4101 first = inner_types;
4103 last->next = inner_types;
4111 static void parse_declaration_attributes(declaration_t *declaration)
4113 gnu_attribute_t *attributes = NULL;
4114 decl_modifiers_t modifiers = parse_attributes(&attributes);
4116 if (declaration == NULL)
4119 declaration->modifiers |= modifiers;
4120 /* check if we have these stupid mode attributes... */
4121 type_t *old_type = declaration->type;
4122 if (old_type == NULL)
4125 gnu_attribute_t *attribute = attributes;
4126 for ( ; attribute != NULL; attribute = attribute->next) {
4127 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4130 atomic_type_kind_t akind = attribute->u.akind;
4131 if (!is_type_signed(old_type)) {
4133 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4134 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4135 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4136 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4138 panic("invalid akind in mode attribute");
4142 = make_atomic_type(akind, old_type->base.qualifiers);
4146 static type_t *construct_declarator_type(construct_type_t *construct_list,
4149 construct_type_t *iter = construct_list;
4150 for( ; iter != NULL; iter = iter->next) {
4151 switch(iter->kind) {
4152 case CONSTRUCT_INVALID:
4153 internal_errorf(HERE, "invalid type construction found");
4154 case CONSTRUCT_FUNCTION: {
4155 construct_function_type_t *construct_function_type
4156 = (construct_function_type_t*) iter;
4158 type_t *function_type = construct_function_type->function_type;
4160 function_type->function.return_type = type;
4162 type_t *skipped_return_type = skip_typeref(type);
4163 if (is_type_function(skipped_return_type)) {
4164 errorf(HERE, "function returning function is not allowed");
4165 type = type_error_type;
4166 } else if (is_type_array(skipped_return_type)) {
4167 errorf(HERE, "function returning array is not allowed");
4168 type = type_error_type;
4170 type = function_type;
4175 case CONSTRUCT_POINTER: {
4176 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4177 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
4178 pointer_type->pointer.points_to = type;
4179 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
4181 type = pointer_type;
4185 case CONSTRUCT_ARRAY: {
4186 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4187 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4189 expression_t *size_expression = parsed_array->size;
4190 if (size_expression != NULL) {
4192 = create_implicit_cast(size_expression, type_size_t);
4195 array_type->base.qualifiers = parsed_array->type_qualifiers;
4196 array_type->array.element_type = type;
4197 array_type->array.is_static = parsed_array->is_static;
4198 array_type->array.is_variable = parsed_array->is_variable;
4199 array_type->array.size_expression = size_expression;
4201 if (size_expression != NULL) {
4202 if (is_constant_expression(size_expression)) {
4203 array_type->array.size_constant = true;
4204 array_type->array.size
4205 = fold_constant(size_expression);
4207 array_type->array.is_vla = true;
4211 type_t *skipped_type = skip_typeref(type);
4212 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
4213 errorf(HERE, "array of void is not allowed");
4214 type = type_error_type;
4222 type_t *hashed_type = typehash_insert(type);
4223 if (hashed_type != type) {
4224 /* the function type was constructed earlier freeing it here will
4225 * destroy other types... */
4226 if (iter->kind != CONSTRUCT_FUNCTION) {
4236 static declaration_t *parse_declarator(
4237 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4239 declaration_t *const declaration = allocate_declaration_zero();
4240 declaration->source_position = specifiers->source_position;
4241 declaration->declared_storage_class = specifiers->declared_storage_class;
4242 declaration->modifiers = specifiers->modifiers;
4243 declaration->deprecated_string = specifiers->deprecated_string;
4244 declaration->get_property_sym = specifiers->get_property_sym;
4245 declaration->put_property_sym = specifiers->put_property_sym;
4246 declaration->is_inline = specifiers->is_inline;
4248 declaration->storage_class = specifiers->declared_storage_class;
4249 if (declaration->storage_class == STORAGE_CLASS_NONE
4250 && scope != global_scope) {
4251 declaration->storage_class = STORAGE_CLASS_AUTO;
4254 if (specifiers->alignment != 0) {
4255 /* TODO: add checks here */
4256 declaration->alignment = specifiers->alignment;
4259 construct_type_t *construct_type
4260 = parse_inner_declarator(declaration, may_be_abstract);
4261 type_t *const type = specifiers->type;
4262 declaration->type = construct_declarator_type(construct_type, type);
4264 parse_declaration_attributes(declaration);
4266 fix_declaration_type(declaration);
4268 if (construct_type != NULL) {
4269 obstack_free(&temp_obst, construct_type);
4275 static type_t *parse_abstract_declarator(type_t *base_type)
4277 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4279 type_t *result = construct_declarator_type(construct_type, base_type);
4280 if (construct_type != NULL) {
4281 obstack_free(&temp_obst, construct_type);
4287 static declaration_t *append_declaration(declaration_t* const declaration)
4289 if (last_declaration != NULL) {
4290 last_declaration->next = declaration;
4292 scope->declarations = declaration;
4294 last_declaration = declaration;
4299 * Check if the declaration of main is suspicious. main should be a
4300 * function with external linkage, returning int, taking either zero
4301 * arguments, two, or three arguments of appropriate types, ie.
4303 * int main([ int argc, char **argv [, char **env ] ]).
4305 * @param decl the declaration to check
4306 * @param type the function type of the declaration
4308 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4310 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4311 warningf(&decl->source_position,
4312 "'main' is normally a non-static function");
4314 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4315 warningf(&decl->source_position,
4316 "return type of 'main' should be 'int', but is '%T'",
4317 func_type->return_type);
4319 const function_parameter_t *parm = func_type->parameters;
4321 type_t *const first_type = parm->type;
4322 if (!types_compatible(skip_typeref(first_type), type_int)) {
4323 warningf(&decl->source_position,
4324 "first argument of 'main' should be 'int', but is '%T'", first_type);
4328 type_t *const second_type = parm->type;
4329 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4330 warningf(&decl->source_position,
4331 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4335 type_t *const third_type = parm->type;
4336 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4337 warningf(&decl->source_position,
4338 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4342 goto warn_arg_count;
4346 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4352 * Check if a symbol is the equal to "main".
4354 static bool is_sym_main(const symbol_t *const sym)
4356 return strcmp(sym->string, "main") == 0;
4359 static declaration_t *record_declaration(
4360 declaration_t *const declaration,
4361 const bool is_definition)
4363 const symbol_t *const symbol = declaration->symbol;
4364 const namespace_t namespc = (namespace_t)declaration->namespc;
4366 assert(symbol != NULL);
4367 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4369 type_t *const orig_type = declaration->type;
4370 type_t *const type = skip_typeref(orig_type);
4371 if (is_type_function(type) &&
4372 type->function.unspecified_parameters &&
4373 warning.strict_prototypes &&
4374 previous_declaration == NULL) {
4375 warningf(&declaration->source_position,
4376 "function declaration '%#T' is not a prototype",
4377 orig_type, declaration->symbol);
4380 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4381 check_type_of_main(declaration, &type->function);
4384 if (warning.nested_externs &&
4385 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4386 scope != global_scope) {
4387 warningf(&declaration->source_position,
4388 "nested extern declaration of '%#T'", declaration->type, symbol);
4391 assert(declaration != previous_declaration);
4392 if (previous_declaration != NULL
4393 && previous_declaration->parent_scope == scope) {
4394 /* can happen for K&R style declarations */
4395 if (previous_declaration->type == NULL) {
4396 previous_declaration->type = declaration->type;
4399 const type_t *prev_type = skip_typeref(previous_declaration->type);
4400 if (!types_compatible(type, prev_type)) {
4401 errorf(&declaration->source_position,
4402 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4403 orig_type, symbol, previous_declaration->type, symbol,
4404 &previous_declaration->source_position);
4406 unsigned old_storage_class = previous_declaration->storage_class;
4407 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4408 errorf(&declaration->source_position,
4409 "redeclaration of enum entry '%Y' (declared %P)",
4410 symbol, &previous_declaration->source_position);
4411 return previous_declaration;
4414 if (warning.redundant_decls &&
4416 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4417 !(previous_declaration->modifiers & DM_USED) &&
4418 !previous_declaration->used) {
4419 warningf(&previous_declaration->source_position,
4420 "unnecessary static forward declaration for '%#T'",
4421 previous_declaration->type, symbol);
4424 unsigned new_storage_class = declaration->storage_class;
4426 if (is_type_incomplete(prev_type)) {
4427 previous_declaration->type = type;
4431 /* pretend no storage class means extern for function
4432 * declarations (except if the previous declaration is neither
4433 * none nor extern) */
4434 if (is_type_function(type)) {
4435 if (prev_type->function.unspecified_parameters) {
4436 previous_declaration->type = type;
4440 switch (old_storage_class) {
4441 case STORAGE_CLASS_NONE:
4442 old_storage_class = STORAGE_CLASS_EXTERN;
4445 case STORAGE_CLASS_EXTERN:
4446 if (is_definition) {
4447 if (warning.missing_prototypes &&
4448 prev_type->function.unspecified_parameters &&
4449 !is_sym_main(symbol)) {
4450 warningf(&declaration->source_position,
4451 "no previous prototype for '%#T'",
4454 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4455 new_storage_class = STORAGE_CLASS_EXTERN;
4464 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4465 new_storage_class == STORAGE_CLASS_EXTERN) {
4466 warn_redundant_declaration:
4467 if (!is_definition &&
4468 warning.redundant_decls &&
4469 is_type_valid(prev_type) &&
4470 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4471 warningf(&declaration->source_position,
4472 "redundant declaration for '%Y' (declared %P)",
4473 symbol, &previous_declaration->source_position);
4475 } else if (current_function == NULL) {
4476 if (old_storage_class != STORAGE_CLASS_STATIC &&
4477 new_storage_class == STORAGE_CLASS_STATIC) {
4478 errorf(&declaration->source_position,
4479 "static declaration of '%Y' follows non-static declaration (declared %P)",
4480 symbol, &previous_declaration->source_position);
4481 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4482 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4483 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4485 goto warn_redundant_declaration;
4487 } else if (is_type_valid(prev_type)) {
4488 if (old_storage_class == new_storage_class) {
4489 errorf(&declaration->source_position,
4490 "redeclaration of '%Y' (declared %P)",
4491 symbol, &previous_declaration->source_position);
4493 errorf(&declaration->source_position,
4494 "redeclaration of '%Y' with different linkage (declared %P)",
4495 symbol, &previous_declaration->source_position);
4500 previous_declaration->modifiers |= declaration->modifiers;
4501 previous_declaration->is_inline |= declaration->is_inline;
4502 return previous_declaration;
4503 } else if (is_type_function(type)) {
4504 if (is_definition &&
4505 declaration->storage_class != STORAGE_CLASS_STATIC) {
4506 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4507 warningf(&declaration->source_position,
4508 "no previous prototype for '%#T'", orig_type, symbol);
4509 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4510 warningf(&declaration->source_position,
4511 "no previous declaration for '%#T'", orig_type,
4516 if (warning.missing_declarations &&
4517 scope == global_scope && (
4518 declaration->storage_class == STORAGE_CLASS_NONE ||
4519 declaration->storage_class == STORAGE_CLASS_THREAD
4521 warningf(&declaration->source_position,
4522 "no previous declaration for '%#T'", orig_type, symbol);
4526 assert(declaration->parent_scope == NULL);
4527 assert(scope != NULL);
4529 declaration->parent_scope = scope;
4531 environment_push(declaration);
4532 return append_declaration(declaration);
4535 static void parser_error_multiple_definition(declaration_t *declaration,
4536 const source_position_t *source_position)
4538 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4539 declaration->symbol, &declaration->source_position);
4542 static bool is_declaration_specifier(const token_t *token,
4543 bool only_specifiers_qualifiers)
4545 switch(token->type) {
4550 return is_typedef_symbol(token->v.symbol);
4552 case T___extension__:
4554 return !only_specifiers_qualifiers;
4561 static void parse_init_declarator_rest(declaration_t *declaration)
4565 type_t *orig_type = declaration->type;
4566 type_t *type = skip_typeref(orig_type);
4568 if (declaration->init.initializer != NULL) {
4569 parser_error_multiple_definition(declaration, HERE);
4572 bool must_be_constant = false;
4573 if (declaration->storage_class == STORAGE_CLASS_STATIC
4574 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4575 || declaration->parent_scope == global_scope) {
4576 must_be_constant = true;
4579 if (is_type_function(type)) {
4580 errorf(&declaration->source_position,
4581 "function '%#T' is initialized like a variable",
4582 orig_type, declaration->symbol);
4583 orig_type = type_error_type;
4586 parse_initializer_env_t env;
4587 env.type = orig_type;
4588 env.must_be_constant = must_be_constant;
4589 env.declaration = current_init_decl = declaration;
4591 initializer_t *initializer = parse_initializer(&env);
4592 current_init_decl = NULL;
4594 if (!is_type_function(type)) {
4595 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
4596 * the array type size */
4597 declaration->type = env.type;
4598 declaration->init.initializer = initializer;
4602 /* parse rest of a declaration without any declarator */
4603 static void parse_anonymous_declaration_rest(
4604 const declaration_specifiers_t *specifiers)
4608 declaration_t *const declaration = allocate_declaration_zero();
4609 declaration->type = specifiers->type;
4610 declaration->declared_storage_class = specifiers->declared_storage_class;
4611 declaration->source_position = specifiers->source_position;
4612 declaration->modifiers = specifiers->modifiers;
4614 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4615 warningf(&declaration->source_position,
4616 "useless storage class in empty declaration");
4618 declaration->storage_class = STORAGE_CLASS_NONE;
4620 type_t *type = declaration->type;
4621 switch (type->kind) {
4622 case TYPE_COMPOUND_STRUCT:
4623 case TYPE_COMPOUND_UNION: {
4624 if (type->compound.declaration->symbol == NULL) {
4625 warningf(&declaration->source_position,
4626 "unnamed struct/union that defines no instances");
4635 warningf(&declaration->source_position, "empty declaration");
4639 append_declaration(declaration);
4642 static void parse_declaration_rest(declaration_t *ndeclaration,
4643 const declaration_specifiers_t *specifiers,
4644 parsed_declaration_func finished_declaration)
4646 add_anchor_token(';');
4647 add_anchor_token('=');
4648 add_anchor_token(',');
4650 declaration_t *declaration =
4651 finished_declaration(ndeclaration, token.type == '=');
4653 type_t *orig_type = declaration->type;
4654 type_t *type = skip_typeref(orig_type);
4656 if (type->kind != TYPE_FUNCTION &&
4657 declaration->is_inline &&
4658 is_type_valid(type)) {
4659 warningf(&declaration->source_position,
4660 "variable '%Y' declared 'inline'\n", declaration->symbol);
4663 if (token.type == '=') {
4664 parse_init_declarator_rest(declaration);
4667 if (token.type != ',')
4671 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4676 rem_anchor_token(';');
4677 rem_anchor_token('=');
4678 rem_anchor_token(',');
4681 static declaration_t *finished_kr_declaration(declaration_t *declaration, bool is_definition)
4683 symbol_t *symbol = declaration->symbol;
4684 if (symbol == NULL) {
4685 errorf(HERE, "anonymous declaration not valid as function parameter");
4688 namespace_t namespc = (namespace_t) declaration->namespc;
4689 if (namespc != NAMESPACE_NORMAL) {
4690 return record_declaration(declaration, false);
4693 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4694 if (previous_declaration == NULL ||
4695 previous_declaration->parent_scope != scope) {
4696 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4701 if (is_definition) {
4702 errorf(HERE, "parameter %Y is initialised", declaration->symbol);
4705 if (previous_declaration->type == NULL) {
4706 previous_declaration->type = declaration->type;
4707 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4708 previous_declaration->storage_class = declaration->storage_class;
4709 previous_declaration->parent_scope = scope;
4710 return previous_declaration;
4712 return record_declaration(declaration, false);
4716 static void parse_declaration(parsed_declaration_func finished_declaration)
4718 declaration_specifiers_t specifiers;
4719 memset(&specifiers, 0, sizeof(specifiers));
4720 parse_declaration_specifiers(&specifiers);
4722 if (token.type == ';') {
4723 parse_anonymous_declaration_rest(&specifiers);
4725 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4726 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4730 static type_t *get_default_promoted_type(type_t *orig_type)
4732 type_t *result = orig_type;
4734 type_t *type = skip_typeref(orig_type);
4735 if (is_type_integer(type)) {
4736 result = promote_integer(type);
4737 } else if (type == type_float) {
4738 result = type_double;
4744 static void parse_kr_declaration_list(declaration_t *declaration)
4746 type_t *type = skip_typeref(declaration->type);
4747 if (!is_type_function(type))
4750 if (!type->function.kr_style_parameters)
4753 /* push function parameters */
4754 int top = environment_top();
4755 scope_t *last_scope = scope;
4756 set_scope(&declaration->scope);
4758 declaration_t *parameter = declaration->scope.declarations;
4759 for ( ; parameter != NULL; parameter = parameter->next) {
4760 assert(parameter->parent_scope == NULL);
4761 parameter->parent_scope = scope;
4762 environment_push(parameter);
4765 /* parse declaration list */
4766 while (is_declaration_specifier(&token, false)) {
4767 parse_declaration(finished_kr_declaration);
4770 /* pop function parameters */
4771 assert(scope == &declaration->scope);
4772 set_scope(last_scope);
4773 environment_pop_to(top);
4775 /* update function type */
4776 type_t *new_type = duplicate_type(type);
4778 function_parameter_t *parameters = NULL;
4779 function_parameter_t *last_parameter = NULL;
4781 declaration_t *parameter_declaration = declaration->scope.declarations;
4782 for( ; parameter_declaration != NULL;
4783 parameter_declaration = parameter_declaration->next) {
4784 type_t *parameter_type = parameter_declaration->type;
4785 if (parameter_type == NULL) {
4787 errorf(HERE, "no type specified for function parameter '%Y'",
4788 parameter_declaration->symbol);
4790 if (warning.implicit_int) {
4791 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4792 parameter_declaration->symbol);
4794 parameter_type = type_int;
4795 parameter_declaration->type = parameter_type;
4799 semantic_parameter(parameter_declaration);
4800 parameter_type = parameter_declaration->type;
4803 * we need the default promoted types for the function type
4805 parameter_type = get_default_promoted_type(parameter_type);
4807 function_parameter_t *function_parameter
4808 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4809 memset(function_parameter, 0, sizeof(function_parameter[0]));
4811 function_parameter->type = parameter_type;
4812 if (last_parameter != NULL) {
4813 last_parameter->next = function_parameter;
4815 parameters = function_parameter;
4817 last_parameter = function_parameter;
4820 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4822 new_type->function.parameters = parameters;
4823 new_type->function.unspecified_parameters = true;
4825 type = typehash_insert(new_type);
4826 if (type != new_type) {
4827 obstack_free(type_obst, new_type);
4830 declaration->type = type;
4833 static bool first_err = true;
4836 * When called with first_err set, prints the name of the current function,
4839 static void print_in_function(void)
4843 diagnosticf("%s: In function '%Y':\n",
4844 current_function->source_position.input_name,
4845 current_function->symbol);
4850 * Check if all labels are defined in the current function.
4851 * Check if all labels are used in the current function.
4853 static void check_labels(void)
4855 for (const goto_statement_t *goto_statement = goto_first;
4856 goto_statement != NULL;
4857 goto_statement = goto_statement->next) {
4858 /* skip computed gotos */
4859 if (goto_statement->expression != NULL)
4862 declaration_t *label = goto_statement->label;
4865 if (label->source_position.input_name == NULL) {
4866 print_in_function();
4867 errorf(&goto_statement->base.source_position,
4868 "label '%Y' used but not defined", label->symbol);
4871 goto_first = goto_last = NULL;
4873 if (warning.unused_label) {
4874 for (const label_statement_t *label_statement = label_first;
4875 label_statement != NULL;
4876 label_statement = label_statement->next) {
4877 const declaration_t *label = label_statement->label;
4879 if (! label->used) {
4880 print_in_function();
4881 warningf(&label_statement->base.source_position,
4882 "label '%Y' defined but not used", label->symbol);
4886 label_first = label_last = NULL;
4890 * Check declarations of current_function for unused entities.
4892 static void check_declarations(void)
4894 if (warning.unused_parameter) {
4895 const scope_t *scope = ¤t_function->scope;
4897 if (is_sym_main(current_function->symbol)) {
4898 /* do not issue unused warnings for main */
4901 const declaration_t *parameter = scope->declarations;
4902 for (; parameter != NULL; parameter = parameter->next) {
4903 if (! parameter->used) {
4904 print_in_function();
4905 warningf(¶meter->source_position,
4906 "unused parameter '%Y'", parameter->symbol);
4910 if (warning.unused_variable) {
4914 static int determine_truth(expression_t const* const cond)
4917 !is_constant_expression(cond) ? 0 :
4918 fold_constant(cond) != 0 ? 1 :
4922 static bool noreturn_candidate;
4924 static void check_reachable(statement_t *const stmt)
4926 if (stmt->base.reachable)
4928 if (stmt->kind != STATEMENT_DO_WHILE)
4929 stmt->base.reachable = true;
4931 statement_t *last = stmt;
4933 switch (stmt->kind) {
4934 case STATEMENT_INVALID:
4935 case STATEMENT_EMPTY:
4936 case STATEMENT_DECLARATION:
4938 next = stmt->base.next;
4941 case STATEMENT_COMPOUND:
4942 next = stmt->compound.statements;
4945 case STATEMENT_RETURN:
4946 noreturn_candidate = false;
4949 case STATEMENT_IF: {
4950 if_statement_t const* const ifs = &stmt->ifs;
4951 int const val = determine_truth(ifs->condition);
4954 check_reachable(ifs->true_statement);
4959 if (ifs->false_statement != NULL) {
4960 check_reachable(ifs->false_statement);
4964 next = stmt->base.next;
4968 case STATEMENT_SWITCH: {
4969 switch_statement_t const *const switchs = &stmt->switchs;
4970 expression_t const *const expr = switchs->expression;
4972 if (is_constant_expression(expr)) {
4973 long const val = fold_constant(expr);
4974 case_label_statement_t * defaults = NULL;
4975 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4976 if (i->expression == NULL) {
4981 if (i->first_case <= val && val <= i->last_case) {
4982 check_reachable((statement_t*)i);
4987 if (defaults != NULL) {
4988 check_reachable((statement_t*)defaults);
4992 bool has_default = false;
4993 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4994 if (i->expression == NULL)
4997 check_reachable((statement_t*)i);
5004 next = stmt->base.next;
5008 case STATEMENT_EXPRESSION: {
5009 /* Check for noreturn function call */
5010 expression_t const *const expr = stmt->expression.expression;
5011 if (expr->kind == EXPR_CALL) {
5012 expression_t const *const func = expr->call.function;
5013 if (func->kind == EXPR_REFERENCE) {
5014 declaration_t const *const decl = func->reference.declaration;
5015 if (decl != NULL && decl->modifiers & DM_NORETURN) {
5021 next = stmt->base.next;
5025 case STATEMENT_CONTINUE: {
5026 statement_t *parent = stmt;
5028 parent = parent->base.parent;
5029 if (parent == NULL) /* continue not within loop */
5033 switch (parent->kind) {
5034 case STATEMENT_WHILE: goto continue_while;
5035 case STATEMENT_DO_WHILE: goto continue_do_while;
5036 case STATEMENT_FOR: goto continue_for;
5043 case STATEMENT_BREAK: {
5044 statement_t *parent = stmt;
5046 parent = parent->base.parent;
5047 if (parent == NULL) /* break not within loop/switch */
5050 switch (parent->kind) {
5051 case STATEMENT_SWITCH:
5052 case STATEMENT_WHILE:
5053 case STATEMENT_DO_WHILE:
5056 next = parent->base.next;
5057 goto found_break_parent;
5066 case STATEMENT_GOTO:
5067 if (stmt->gotos.expression) {
5068 statement_t *parent = stmt->base.parent;
5069 if (parent == NULL) /* top level goto */
5073 next = stmt->gotos.label->init.statement;
5074 if (next == NULL) /* missing label */
5079 case STATEMENT_LABEL:
5080 next = stmt->label.statement;
5083 case STATEMENT_CASE_LABEL:
5084 next = stmt->case_label.statement;
5087 case STATEMENT_WHILE: {
5088 while_statement_t const *const whiles = &stmt->whiles;
5089 int const val = determine_truth(whiles->condition);
5092 check_reachable(whiles->body);
5097 next = stmt->base.next;
5101 case STATEMENT_DO_WHILE:
5102 next = stmt->do_while.body;
5105 case STATEMENT_FOR: {
5106 for_statement_t *const fors = &stmt->fors;
5108 if (fors->condition_reachable)
5110 fors->condition_reachable = true;
5112 expression_t const *const cond = fors->condition;
5114 cond == NULL ? 1 : determine_truth(cond);
5117 check_reachable(fors->body);
5122 next = stmt->base.next;
5126 case STATEMENT_MS_TRY: {
5127 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5128 check_reachable(ms_try->try_statement);
5129 next = ms_try->final_statement;
5133 case STATEMENT_LEAVE: {
5134 statement_t *parent = stmt;
5136 parent = parent->base.parent;
5137 if (parent == NULL) /* __leave not within __try */
5140 if (parent->kind == STATEMENT_MS_TRY) {
5142 next = parent->ms_try.final_statement;
5150 while (next == NULL) {
5151 next = last->base.parent;
5153 noreturn_candidate = false;
5155 type_t *const type = current_function->type;
5156 assert(is_type_function(type));
5157 type_t *const ret = skip_typeref(type->function.return_type);
5158 if (warning.return_type &&
5159 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5160 is_type_valid(ret) &&
5161 !is_sym_main(current_function->symbol)) {
5162 warningf(&stmt->base.source_position,
5163 "control reaches end of non-void function");
5168 switch (next->kind) {
5169 case STATEMENT_INVALID:
5170 case STATEMENT_EMPTY:
5171 case STATEMENT_DECLARATION:
5172 case STATEMENT_EXPRESSION:
5174 case STATEMENT_RETURN:
5175 case STATEMENT_CONTINUE:
5176 case STATEMENT_BREAK:
5177 case STATEMENT_GOTO:
5178 case STATEMENT_LEAVE:
5179 panic("invalid control flow in function");
5181 case STATEMENT_COMPOUND:
5183 case STATEMENT_SWITCH:
5184 case STATEMENT_LABEL:
5185 case STATEMENT_CASE_LABEL:
5187 next = next->base.next;
5190 case STATEMENT_WHILE: {
5192 if (next->base.reachable)
5194 next->base.reachable = true;
5196 while_statement_t const *const whiles = &next->whiles;
5197 int const val = determine_truth(whiles->condition);
5200 check_reachable(whiles->body);
5206 next = next->base.next;
5210 case STATEMENT_DO_WHILE: {
5212 if (next->base.reachable)
5214 next->base.reachable = true;
5216 do_while_statement_t const *const dw = &next->do_while;
5217 int const val = determine_truth(dw->condition);
5220 check_reachable(dw->body);
5226 next = next->base.next;
5230 case STATEMENT_FOR: {
5232 for_statement_t *const fors = &next->fors;
5234 fors->step_reachable = true;
5236 if (fors->condition_reachable)
5238 fors->condition_reachable = true;
5240 expression_t const *const cond = fors->condition;
5242 cond == NULL ? 1 : determine_truth(cond);
5245 check_reachable(fors->body);
5251 next = next->base.next;
5255 case STATEMENT_MS_TRY:
5257 next = next->ms_try.final_statement;
5263 next = stmt->base.parent;
5265 warningf(&stmt->base.source_position,
5266 "control reaches end of non-void function");
5270 check_reachable(next);
5273 static void check_unreachable(statement_t const* const stmt)
5275 if (!stmt->base.reachable &&
5276 stmt->kind != STATEMENT_DO_WHILE &&
5277 stmt->kind != STATEMENT_FOR &&
5278 (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5279 warningf(&stmt->base.source_position, "statement is unreachable");
5282 switch (stmt->kind) {
5283 case STATEMENT_INVALID:
5284 case STATEMENT_EMPTY:
5285 case STATEMENT_RETURN:
5286 case STATEMENT_DECLARATION:
5287 case STATEMENT_EXPRESSION:
5288 case STATEMENT_CONTINUE:
5289 case STATEMENT_BREAK:
5290 case STATEMENT_GOTO:
5292 case STATEMENT_LEAVE:
5295 case STATEMENT_COMPOUND:
5296 if (stmt->compound.statements)
5297 check_unreachable(stmt->compound.statements);
5301 check_unreachable(stmt->ifs.true_statement);
5302 if (stmt->ifs.false_statement != NULL)
5303 check_unreachable(stmt->ifs.false_statement);
5306 case STATEMENT_SWITCH:
5307 check_unreachable(stmt->switchs.body);
5310 case STATEMENT_LABEL:
5311 check_unreachable(stmt->label.statement);
5314 case STATEMENT_CASE_LABEL:
5315 check_unreachable(stmt->case_label.statement);
5318 case STATEMENT_WHILE:
5319 check_unreachable(stmt->whiles.body);
5322 case STATEMENT_DO_WHILE:
5323 check_unreachable(stmt->do_while.body);
5324 if (!stmt->base.reachable) {
5325 expression_t const *const cond = stmt->do_while.condition;
5326 if (determine_truth(cond) >= 0) {
5327 warningf(&cond->base.source_position,
5328 "condition of do-while-loop is unreachable");
5333 case STATEMENT_FOR: {
5334 for_statement_t const* const fors = &stmt->fors;
5336 // if init and step are unreachable, cond is unreachable, too
5337 if (!stmt->base.reachable && !fors->step_reachable) {
5338 warningf(&stmt->base.source_position, "statement is unreachable");
5340 if (!stmt->base.reachable && fors->initialisation != NULL) {
5341 warningf(&fors->initialisation->base.source_position,
5342 "initialisation of for-statement is unreachable");
5345 if (!fors->condition_reachable && fors->condition != NULL) {
5346 warningf(&fors->condition->base.source_position,
5347 "condition of for-statement is unreachable");
5350 if (!fors->step_reachable && fors->step != NULL) {
5351 warningf(&fors->step->base.source_position,
5352 "step of for-statement is unreachable");
5356 check_unreachable(fors->body);
5360 case STATEMENT_MS_TRY: {
5361 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5362 check_unreachable(ms_try->try_statement);
5363 check_unreachable(ms_try->final_statement);
5367 if (stmt->base.next)
5368 check_unreachable(stmt->base.next);
5371 static void parse_external_declaration(void)
5373 /* function-definitions and declarations both start with declaration
5375 declaration_specifiers_t specifiers;
5376 memset(&specifiers, 0, sizeof(specifiers));
5378 add_anchor_token(';');
5379 parse_declaration_specifiers(&specifiers);
5380 rem_anchor_token(';');
5382 /* must be a declaration */
5383 if (token.type == ';') {
5384 parse_anonymous_declaration_rest(&specifiers);
5388 add_anchor_token(',');
5389 add_anchor_token('=');
5390 add_anchor_token(';');
5392 /* declarator is common to both function-definitions and declarations */
5393 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5395 rem_anchor_token(',');
5396 rem_anchor_token('=');
5397 rem_anchor_token(';');
5399 /* must be a declaration */
5400 switch (token.type) {
5404 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5408 /* must be a function definition */
5409 parse_kr_declaration_list(ndeclaration);
5411 if (token.type != '{') {
5412 parse_error_expected("while parsing function definition", '{', NULL);
5413 eat_until_matching_token(';');
5417 type_t *type = ndeclaration->type;
5419 /* note that we don't skip typerefs: the standard doesn't allow them here
5420 * (so we can't use is_type_function here) */
5421 if (type->kind != TYPE_FUNCTION) {
5422 if (is_type_valid(type)) {
5423 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5424 type, ndeclaration->symbol);
5430 if (warning.aggregate_return &&
5431 is_type_compound(skip_typeref(type->function.return_type))) {
5432 warningf(HERE, "function '%Y' returns an aggregate",
5433 ndeclaration->symbol);
5435 if (warning.traditional && !type->function.unspecified_parameters) {
5436 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5437 ndeclaration->symbol);
5439 if (warning.old_style_definition && type->function.unspecified_parameters) {
5440 warningf(HERE, "old-style function definition '%Y'",
5441 ndeclaration->symbol);
5444 /* § 6.7.5.3 (14) a function definition with () means no
5445 * parameters (and not unspecified parameters) */
5446 if (type->function.unspecified_parameters
5447 && type->function.parameters == NULL
5448 && !type->function.kr_style_parameters) {
5449 type_t *duplicate = duplicate_type(type);
5450 duplicate->function.unspecified_parameters = false;
5452 type = typehash_insert(duplicate);
5453 if (type != duplicate) {
5454 obstack_free(type_obst, duplicate);
5456 ndeclaration->type = type;
5459 declaration_t *const declaration = record_declaration(ndeclaration, true);
5460 if (ndeclaration != declaration) {
5461 declaration->scope = ndeclaration->scope;
5463 type = skip_typeref(declaration->type);
5465 /* push function parameters and switch scope */
5466 int top = environment_top();
5467 scope_t *last_scope = scope;
5468 set_scope(&declaration->scope);
5470 declaration_t *parameter = declaration->scope.declarations;
5471 for( ; parameter != NULL; parameter = parameter->next) {
5472 if (parameter->parent_scope == &ndeclaration->scope) {
5473 parameter->parent_scope = scope;
5475 assert(parameter->parent_scope == NULL
5476 || parameter->parent_scope == scope);
5477 parameter->parent_scope = scope;
5478 if (parameter->symbol == NULL) {
5479 errorf(¶meter->source_position, "parameter name omitted");
5482 environment_push(parameter);
5485 if (declaration->init.statement != NULL) {
5486 parser_error_multiple_definition(declaration, HERE);
5489 /* parse function body */
5490 int label_stack_top = label_top();
5491 declaration_t *old_current_function = current_function;
5492 current_function = declaration;
5493 current_parent = NULL;
5495 statement_t *const body = parse_compound_statement(false);
5496 declaration->init.statement = body;
5499 check_declarations();
5500 if (warning.return_type ||
5501 warning.unreachable_code ||
5502 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5503 noreturn_candidate = true;
5504 check_reachable(body);
5505 if (warning.unreachable_code)
5506 check_unreachable(body);
5507 if (warning.missing_noreturn &&
5508 noreturn_candidate &&
5509 !(declaration->modifiers & DM_NORETURN)) {
5510 warningf(&body->base.source_position,
5511 "function '%#T' is candidate for attribute 'noreturn'",
5512 type, declaration->symbol);
5516 assert(current_parent == NULL);
5517 assert(current_function == declaration);
5518 current_function = old_current_function;
5519 label_pop_to(label_stack_top);
5522 assert(scope == &declaration->scope);
5523 set_scope(last_scope);
5524 environment_pop_to(top);
5527 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5528 source_position_t *source_position,
5529 const symbol_t *symbol)
5531 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5533 type->bitfield.base_type = base_type;
5534 type->bitfield.size_expression = size;
5537 type_t *skipped_type = skip_typeref(base_type);
5538 if (!is_type_integer(skipped_type)) {
5539 errorf(HERE, "bitfield base type '%T' is not an integer type",
5543 bit_size = skipped_type->base.size * 8;
5546 if (is_constant_expression(size)) {
5547 long v = fold_constant(size);
5550 errorf(source_position, "negative width in bit-field '%Y'",
5552 } else if (v == 0) {
5553 errorf(source_position, "zero width for bit-field '%Y'",
5555 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5556 errorf(source_position, "width of '%Y' exceeds its type",
5559 type->bitfield.bit_size = v;
5566 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5569 declaration_t *iter = compound_declaration->scope.declarations;
5570 for( ; iter != NULL; iter = iter->next) {
5571 if (iter->namespc != NAMESPACE_NORMAL)
5574 if (iter->symbol == NULL) {
5575 type_t *type = skip_typeref(iter->type);
5576 if (is_type_compound(type)) {
5577 declaration_t *result
5578 = find_compound_entry(type->compound.declaration, symbol);
5585 if (iter->symbol == symbol) {
5593 static void parse_compound_declarators(declaration_t *struct_declaration,
5594 const declaration_specifiers_t *specifiers)
5596 declaration_t *last_declaration = struct_declaration->scope.declarations;
5597 if (last_declaration != NULL) {
5598 while (last_declaration->next != NULL) {
5599 last_declaration = last_declaration->next;
5604 declaration_t *declaration;
5606 if (token.type == ':') {
5607 source_position_t source_position = *HERE;
5610 type_t *base_type = specifiers->type;
5611 expression_t *size = parse_constant_expression();
5613 type_t *type = make_bitfield_type(base_type, size,
5614 &source_position, sym_anonymous);
5616 declaration = allocate_declaration_zero();
5617 declaration->namespc = NAMESPACE_NORMAL;
5618 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5619 declaration->storage_class = STORAGE_CLASS_NONE;
5620 declaration->source_position = source_position;
5621 declaration->modifiers = specifiers->modifiers;
5622 declaration->type = type;
5624 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5626 type_t *orig_type = declaration->type;
5627 type_t *type = skip_typeref(orig_type);
5629 if (token.type == ':') {
5630 source_position_t source_position = *HERE;
5632 expression_t *size = parse_constant_expression();
5634 type_t *bitfield_type = make_bitfield_type(orig_type, size,
5635 &source_position, declaration->symbol);
5636 declaration->type = bitfield_type;
5638 /* TODO we ignore arrays for now... what is missing is a check
5639 * that they're at the end of the struct */
5640 if (is_type_incomplete(type) && !is_type_array(type)) {
5642 "compound member '%Y' has incomplete type '%T'",
5643 declaration->symbol, orig_type);
5644 } else if (is_type_function(type)) {
5645 errorf(HERE, "compound member '%Y' must not have function type '%T'",
5646 declaration->symbol, orig_type);
5651 /* make sure we don't define a symbol multiple times */
5652 symbol_t *symbol = declaration->symbol;
5653 if (symbol != NULL) {
5654 declaration_t *prev_decl
5655 = find_compound_entry(struct_declaration, symbol);
5657 if (prev_decl != NULL) {
5658 assert(prev_decl->symbol == symbol);
5659 errorf(&declaration->source_position,
5660 "multiple declarations of symbol '%Y' (declared %P)",
5661 symbol, &prev_decl->source_position);
5665 /* append declaration */
5666 if (last_declaration != NULL) {
5667 last_declaration->next = declaration;
5669 struct_declaration->scope.declarations = declaration;
5671 last_declaration = declaration;
5673 if (token.type != ',')
5683 static void parse_compound_type_entries(declaration_t *compound_declaration)
5686 add_anchor_token('}');
5688 while (token.type != '}' && token.type != T_EOF) {
5689 declaration_specifiers_t specifiers;
5690 memset(&specifiers, 0, sizeof(specifiers));
5691 parse_declaration_specifiers(&specifiers);
5693 parse_compound_declarators(compound_declaration, &specifiers);
5695 rem_anchor_token('}');
5697 if (token.type == T_EOF) {
5698 errorf(HERE, "EOF while parsing struct");
5703 static type_t *parse_typename(void)
5705 declaration_specifiers_t specifiers;
5706 memset(&specifiers, 0, sizeof(specifiers));
5707 parse_declaration_specifiers(&specifiers);
5708 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5709 /* TODO: improve error message, user does probably not know what a
5710 * storage class is...
5712 errorf(HERE, "typename may not have a storage class");
5715 type_t *result = parse_abstract_declarator(specifiers.type);
5723 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5724 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5725 expression_t *left);
5727 typedef struct expression_parser_function_t expression_parser_function_t;
5728 struct expression_parser_function_t {
5729 unsigned precedence;
5730 parse_expression_function parser;
5731 unsigned infix_precedence;
5732 parse_expression_infix_function infix_parser;
5735 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5738 * Prints an error message if an expression was expected but not read
5740 static expression_t *expected_expression_error(void)
5742 /* skip the error message if the error token was read */
5743 if (token.type != T_ERROR) {
5744 errorf(HERE, "expected expression, got token '%K'", &token);
5748 return create_invalid_expression();
5752 * Parse a string constant.
5754 static expression_t *parse_string_const(void)
5757 if (token.type == T_STRING_LITERAL) {
5758 string_t res = token.v.string;
5760 while (token.type == T_STRING_LITERAL) {
5761 res = concat_strings(&res, &token.v.string);
5764 if (token.type != T_WIDE_STRING_LITERAL) {
5765 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5766 /* note: that we use type_char_ptr here, which is already the
5767 * automatic converted type. revert_automatic_type_conversion
5768 * will construct the array type */
5769 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5770 cnst->string.value = res;
5774 wres = concat_string_wide_string(&res, &token.v.wide_string);
5776 wres = token.v.wide_string;
5781 switch (token.type) {
5782 case T_WIDE_STRING_LITERAL:
5783 wres = concat_wide_strings(&wres, &token.v.wide_string);
5786 case T_STRING_LITERAL:
5787 wres = concat_wide_string_string(&wres, &token.v.string);
5791 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5792 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5793 cnst->wide_string.value = wres;
5802 * Parse an integer constant.
5804 static expression_t *parse_int_const(void)
5806 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5807 cnst->base.source_position = *HERE;
5808 cnst->base.type = token.datatype;
5809 cnst->conste.v.int_value = token.v.intvalue;
5817 * Parse a character constant.
5819 static expression_t *parse_character_constant(void)
5821 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5823 cnst->base.source_position = *HERE;
5824 cnst->base.type = token.datatype;
5825 cnst->conste.v.character = token.v.string;
5827 if (cnst->conste.v.character.size != 1) {
5828 if (warning.multichar && (c_mode & _GNUC)) {
5830 warningf(HERE, "multi-character character constant");
5832 errorf(HERE, "more than 1 characters in character constant");
5841 * Parse a wide character constant.
5843 static expression_t *parse_wide_character_constant(void)
5845 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5847 cnst->base.source_position = *HERE;
5848 cnst->base.type = token.datatype;
5849 cnst->conste.v.wide_character = token.v.wide_string;
5851 if (cnst->conste.v.wide_character.size != 1) {
5852 if (warning.multichar && (c_mode & _GNUC)) {
5854 warningf(HERE, "multi-character character constant");
5856 errorf(HERE, "more than 1 characters in character constant");
5865 * Parse a float constant.
5867 static expression_t *parse_float_const(void)
5869 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5870 cnst->base.type = token.datatype;
5871 cnst->conste.v.float_value = token.v.floatvalue;
5878 static declaration_t *create_implicit_function(symbol_t *symbol,
5879 const source_position_t *source_position)
5881 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5882 ntype->function.return_type = type_int;
5883 ntype->function.unspecified_parameters = true;
5885 type_t *type = typehash_insert(ntype);
5886 if (type != ntype) {
5890 declaration_t *const declaration = allocate_declaration_zero();
5891 declaration->storage_class = STORAGE_CLASS_EXTERN;
5892 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5893 declaration->type = type;
5894 declaration->symbol = symbol;
5895 declaration->source_position = *source_position;
5896 declaration->implicit = true;
5898 bool strict_prototypes_old = warning.strict_prototypes;
5899 warning.strict_prototypes = false;
5900 record_declaration(declaration, false);
5901 warning.strict_prototypes = strict_prototypes_old;
5907 * Creates a return_type (func)(argument_type) function type if not
5910 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5911 type_t *argument_type2)
5913 function_parameter_t *parameter2
5914 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5915 memset(parameter2, 0, sizeof(parameter2[0]));
5916 parameter2->type = argument_type2;
5918 function_parameter_t *parameter1
5919 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5920 memset(parameter1, 0, sizeof(parameter1[0]));
5921 parameter1->type = argument_type1;
5922 parameter1->next = parameter2;
5924 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5925 type->function.return_type = return_type;
5926 type->function.parameters = parameter1;
5928 type_t *result = typehash_insert(type);
5929 if (result != type) {
5937 * Creates a return_type (func)(argument_type) function type if not
5940 * @param return_type the return type
5941 * @param argument_type the argument type
5943 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5945 function_parameter_t *parameter
5946 = obstack_alloc(type_obst, sizeof(parameter[0]));
5947 memset(parameter, 0, sizeof(parameter[0]));
5948 parameter->type = argument_type;
5950 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5951 type->function.return_type = return_type;
5952 type->function.parameters = parameter;
5954 type_t *result = typehash_insert(type);
5955 if (result != type) {
5962 static type_t *make_function_0_type(type_t *return_type)
5964 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5965 type->function.return_type = return_type;
5966 type->function.parameters = NULL;
5968 type_t *result = typehash_insert(type);
5969 if (result != type) {
5977 * Creates a function type for some function like builtins.
5979 * @param symbol the symbol describing the builtin
5981 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5983 switch(symbol->ID) {
5984 case T___builtin_alloca:
5985 return make_function_1_type(type_void_ptr, type_size_t);
5986 case T___builtin_huge_val:
5987 return make_function_0_type(type_double);
5988 case T___builtin_nan:
5989 return make_function_1_type(type_double, type_char_ptr);
5990 case T___builtin_nanf:
5991 return make_function_1_type(type_float, type_char_ptr);
5992 case T___builtin_nand:
5993 return make_function_1_type(type_long_double, type_char_ptr);
5994 case T___builtin_va_end:
5995 return make_function_1_type(type_void, type_valist);
5996 case T___builtin_expect:
5997 return make_function_2_type(type_long, type_long, type_long);
5999 internal_errorf(HERE, "not implemented builtin symbol found");
6004 * Performs automatic type cast as described in § 6.3.2.1.
6006 * @param orig_type the original type
6008 static type_t *automatic_type_conversion(type_t *orig_type)
6010 type_t *type = skip_typeref(orig_type);
6011 if (is_type_array(type)) {
6012 array_type_t *array_type = &type->array;
6013 type_t *element_type = array_type->element_type;
6014 unsigned qualifiers = array_type->base.qualifiers;
6016 return make_pointer_type(element_type, qualifiers);
6019 if (is_type_function(type)) {
6020 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6027 * reverts the automatic casts of array to pointer types and function
6028 * to function-pointer types as defined § 6.3.2.1
6030 type_t *revert_automatic_type_conversion(const expression_t *expression)
6032 switch (expression->kind) {
6033 case EXPR_REFERENCE: return expression->reference.declaration->type;
6036 return get_qualified_type(expression->select.compound_entry->type,
6037 expression->base.type->base.qualifiers);
6039 case EXPR_UNARY_DEREFERENCE: {
6040 const expression_t *const value = expression->unary.value;
6041 type_t *const type = skip_typeref(value->base.type);
6042 assert(is_type_pointer(type));
6043 return type->pointer.points_to;
6046 case EXPR_BUILTIN_SYMBOL:
6047 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6049 case EXPR_ARRAY_ACCESS: {
6050 const expression_t *array_ref = expression->array_access.array_ref;
6051 type_t *type_left = skip_typeref(array_ref->base.type);
6052 if (!is_type_valid(type_left))
6054 assert(is_type_pointer(type_left));
6055 return type_left->pointer.points_to;
6058 case EXPR_STRING_LITERAL: {
6059 size_t size = expression->string.value.size;
6060 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6063 case EXPR_WIDE_STRING_LITERAL: {
6064 size_t size = expression->wide_string.value.size;
6065 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6068 case EXPR_COMPOUND_LITERAL:
6069 return expression->compound_literal.type;
6074 return expression->base.type;
6077 static expression_t *parse_reference(void)
6079 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
6081 reference_expression_t *ref = &expression->reference;
6082 symbol_t *const symbol = token.v.symbol;
6084 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
6086 if (declaration == NULL) {
6087 if (!strict_mode && look_ahead(1)->type == '(') {
6088 /* an implicitly declared function */
6089 if (warning.implicit_function_declaration) {
6090 warningf(HERE, "implicit declaration of function '%Y'",
6094 declaration = create_implicit_function(symbol, HERE);
6096 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6097 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6101 type_t *type = declaration->type;
6103 /* we always do the auto-type conversions; the & and sizeof parser contains
6104 * code to revert this! */
6105 type = automatic_type_conversion(type);
6107 ref->declaration = declaration;
6108 ref->base.type = type;
6110 /* this declaration is used */
6111 declaration->used = true;
6113 /* check for deprecated functions */
6114 if (warning.deprecated_declarations &&
6115 declaration->modifiers & DM_DEPRECATED) {
6116 char const *const prefix = is_type_function(declaration->type) ?
6117 "function" : "variable";
6119 if (declaration->deprecated_string != NULL) {
6120 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6121 prefix, declaration->symbol, &declaration->source_position,
6122 declaration->deprecated_string);
6124 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6125 declaration->symbol, &declaration->source_position);
6128 if (warning.init_self && declaration == current_init_decl) {
6129 current_init_decl = NULL;
6130 warningf(HERE, "variable '%#T' is initialized by itself",
6131 declaration->type, declaration->symbol);
6138 static bool semantic_cast(expression_t *cast)
6140 expression_t *expression = cast->unary.value;
6141 type_t *orig_dest_type = cast->base.type;
6142 type_t *orig_type_right = expression->base.type;
6143 type_t const *dst_type = skip_typeref(orig_dest_type);
6144 type_t const *src_type = skip_typeref(orig_type_right);
6145 source_position_t const *pos = &cast->base.source_position;
6147 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6148 if (dst_type == type_void)
6151 /* only integer and pointer can be casted to pointer */
6152 if (is_type_pointer(dst_type) &&
6153 !is_type_pointer(src_type) &&
6154 !is_type_integer(src_type) &&
6155 is_type_valid(src_type)) {
6156 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6160 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6161 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6165 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6166 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6170 if (warning.cast_qual &&
6171 is_type_pointer(src_type) &&
6172 is_type_pointer(dst_type)) {
6173 type_t *src = skip_typeref(src_type->pointer.points_to);
6174 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6175 unsigned missing_qualifiers =
6176 src->base.qualifiers & ~dst->base.qualifiers;
6177 if (missing_qualifiers != 0) {
6179 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6180 missing_qualifiers, orig_type_right);
6186 static expression_t *parse_compound_literal(type_t *type)
6188 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6190 parse_initializer_env_t env;
6192 env.declaration = NULL;
6193 env.must_be_constant = false;
6194 initializer_t *initializer = parse_initializer(&env);
6197 expression->compound_literal.initializer = initializer;
6198 expression->compound_literal.type = type;
6199 expression->base.type = automatic_type_conversion(type);
6205 * Parse a cast expression.
6207 static expression_t *parse_cast(void)
6209 add_anchor_token(')');
6211 source_position_t source_position = token.source_position;
6213 type_t *type = parse_typename();
6215 rem_anchor_token(')');
6218 if (token.type == '{') {
6219 return parse_compound_literal(type);
6222 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6223 cast->base.source_position = source_position;
6225 expression_t *value = parse_sub_expression(20);
6226 cast->base.type = type;
6227 cast->unary.value = value;
6229 if (! semantic_cast(cast)) {
6230 /* TODO: record the error in the AST. else it is impossible to detect it */
6235 return create_invalid_expression();
6239 * Parse a statement expression.
6241 static expression_t *parse_statement_expression(void)
6243 add_anchor_token(')');
6245 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6247 statement_t *statement = parse_compound_statement(true);
6248 expression->statement.statement = statement;
6249 expression->base.source_position = statement->base.source_position;
6251 /* find last statement and use its type */
6252 type_t *type = type_void;
6253 const statement_t *stmt = statement->compound.statements;
6255 while (stmt->base.next != NULL)
6256 stmt = stmt->base.next;
6258 if (stmt->kind == STATEMENT_EXPRESSION) {
6259 type = stmt->expression.expression->base.type;
6262 warningf(&expression->base.source_position, "empty statement expression ({})");
6264 expression->base.type = type;
6266 rem_anchor_token(')');
6274 * Parse a parenthesized expression.
6276 static expression_t *parse_parenthesized_expression(void)
6280 switch(token.type) {
6282 /* gcc extension: a statement expression */
6283 return parse_statement_expression();
6287 return parse_cast();
6289 if (is_typedef_symbol(token.v.symbol)) {
6290 return parse_cast();
6294 add_anchor_token(')');
6295 expression_t *result = parse_expression();
6296 rem_anchor_token(')');
6303 static expression_t *parse_function_keyword(void)
6308 if (current_function == NULL) {
6309 errorf(HERE, "'__func__' used outside of a function");
6312 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6313 expression->base.type = type_char_ptr;
6314 expression->funcname.kind = FUNCNAME_FUNCTION;
6319 static expression_t *parse_pretty_function_keyword(void)
6321 eat(T___PRETTY_FUNCTION__);
6323 if (current_function == NULL) {
6324 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6327 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6328 expression->base.type = type_char_ptr;
6329 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6334 static expression_t *parse_funcsig_keyword(void)
6338 if (current_function == NULL) {
6339 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6342 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6343 expression->base.type = type_char_ptr;
6344 expression->funcname.kind = FUNCNAME_FUNCSIG;
6349 static expression_t *parse_funcdname_keyword(void)
6351 eat(T___FUNCDNAME__);
6353 if (current_function == NULL) {
6354 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6357 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6358 expression->base.type = type_char_ptr;
6359 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6364 static designator_t *parse_designator(void)
6366 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6367 result->source_position = *HERE;
6369 if (token.type != T_IDENTIFIER) {
6370 parse_error_expected("while parsing member designator",
6371 T_IDENTIFIER, NULL);
6374 result->symbol = token.v.symbol;
6377 designator_t *last_designator = result;
6379 if (token.type == '.') {
6381 if (token.type != T_IDENTIFIER) {
6382 parse_error_expected("while parsing member designator",
6383 T_IDENTIFIER, NULL);
6386 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6387 designator->source_position = *HERE;
6388 designator->symbol = token.v.symbol;
6391 last_designator->next = designator;
6392 last_designator = designator;
6395 if (token.type == '[') {
6397 add_anchor_token(']');
6398 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6399 designator->source_position = *HERE;
6400 designator->array_index = parse_expression();
6401 rem_anchor_token(']');
6403 if (designator->array_index == NULL) {
6407 last_designator->next = designator;
6408 last_designator = designator;
6420 * Parse the __builtin_offsetof() expression.
6422 static expression_t *parse_offsetof(void)
6424 eat(T___builtin_offsetof);
6426 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6427 expression->base.type = type_size_t;
6430 add_anchor_token(',');
6431 type_t *type = parse_typename();
6432 rem_anchor_token(',');
6434 add_anchor_token(')');
6435 designator_t *designator = parse_designator();
6436 rem_anchor_token(')');
6439 expression->offsetofe.type = type;
6440 expression->offsetofe.designator = designator;
6443 memset(&path, 0, sizeof(path));
6444 path.top_type = type;
6445 path.path = NEW_ARR_F(type_path_entry_t, 0);
6447 descend_into_subtype(&path);
6449 if (!walk_designator(&path, designator, true)) {
6450 return create_invalid_expression();
6453 DEL_ARR_F(path.path);
6457 return create_invalid_expression();
6461 * Parses a _builtin_va_start() expression.
6463 static expression_t *parse_va_start(void)
6465 eat(T___builtin_va_start);
6467 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6470 add_anchor_token(',');
6471 expression->va_starte.ap = parse_assignment_expression();
6472 rem_anchor_token(',');
6474 expression_t *const expr = parse_assignment_expression();
6475 if (expr->kind == EXPR_REFERENCE) {
6476 declaration_t *const decl = expr->reference.declaration;
6477 if (decl->parent_scope != ¤t_function->scope || decl->next != NULL) {
6478 errorf(&expr->base.source_position,
6479 "second argument of 'va_start' must be last parameter of the current function");
6481 expression->va_starte.parameter = decl;
6487 return create_invalid_expression();
6491 * Parses a _builtin_va_arg() expression.
6493 static expression_t *parse_va_arg(void)
6495 eat(T___builtin_va_arg);
6497 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6500 expression->va_arge.ap = parse_assignment_expression();
6502 expression->base.type = parse_typename();
6507 return create_invalid_expression();
6510 static expression_t *parse_builtin_symbol(void)
6512 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6514 symbol_t *symbol = token.v.symbol;
6516 expression->builtin_symbol.symbol = symbol;
6519 type_t *type = get_builtin_symbol_type(symbol);
6520 type = automatic_type_conversion(type);
6522 expression->base.type = type;
6527 * Parses a __builtin_constant() expression.
6529 static expression_t *parse_builtin_constant(void)
6531 eat(T___builtin_constant_p);
6533 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6536 add_anchor_token(')');
6537 expression->builtin_constant.value = parse_assignment_expression();
6538 rem_anchor_token(')');
6540 expression->base.type = type_int;
6544 return create_invalid_expression();
6548 * Parses a __builtin_prefetch() expression.
6550 static expression_t *parse_builtin_prefetch(void)
6552 eat(T___builtin_prefetch);
6554 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6557 add_anchor_token(')');
6558 expression->builtin_prefetch.adr = parse_assignment_expression();
6559 if (token.type == ',') {
6561 expression->builtin_prefetch.rw = parse_assignment_expression();
6563 if (token.type == ',') {
6565 expression->builtin_prefetch.locality = parse_assignment_expression();
6567 rem_anchor_token(')');
6569 expression->base.type = type_void;
6573 return create_invalid_expression();
6577 * Parses a __builtin_is_*() compare expression.
6579 static expression_t *parse_compare_builtin(void)
6581 expression_t *expression;
6583 switch(token.type) {
6584 case T___builtin_isgreater:
6585 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6587 case T___builtin_isgreaterequal:
6588 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6590 case T___builtin_isless:
6591 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6593 case T___builtin_islessequal:
6594 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6596 case T___builtin_islessgreater:
6597 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6599 case T___builtin_isunordered:
6600 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6603 internal_errorf(HERE, "invalid compare builtin found");
6606 expression->base.source_position = *HERE;
6610 expression->binary.left = parse_assignment_expression();
6612 expression->binary.right = parse_assignment_expression();
6615 type_t *const orig_type_left = expression->binary.left->base.type;
6616 type_t *const orig_type_right = expression->binary.right->base.type;
6618 type_t *const type_left = skip_typeref(orig_type_left);
6619 type_t *const type_right = skip_typeref(orig_type_right);
6620 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6621 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6622 type_error_incompatible("invalid operands in comparison",
6623 &expression->base.source_position, orig_type_left, orig_type_right);
6626 semantic_comparison(&expression->binary);
6631 return create_invalid_expression();
6636 * Parses a __builtin_expect() expression.
6638 static expression_t *parse_builtin_expect(void)
6640 eat(T___builtin_expect);
6642 expression_t *expression
6643 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6646 expression->binary.left = parse_assignment_expression();
6648 expression->binary.right = parse_constant_expression();
6651 expression->base.type = expression->binary.left->base.type;
6655 return create_invalid_expression();
6660 * Parses a MS assume() expression.
6662 static expression_t *parse_assume(void)
6666 expression_t *expression
6667 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6670 add_anchor_token(')');
6671 expression->unary.value = parse_assignment_expression();
6672 rem_anchor_token(')');
6675 expression->base.type = type_void;
6678 return create_invalid_expression();
6682 * Return the declaration for a given label symbol or create a new one.
6684 * @param symbol the symbol of the label
6686 static declaration_t *get_label(symbol_t *symbol)
6688 declaration_t *candidate;
6689 assert(current_function != NULL);
6691 candidate = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
6692 /* if we found a local label, we already created the declaration */
6693 if (candidate != NULL) {
6694 assert(candidate->parent_scope == scope);
6698 candidate = get_declaration(symbol, NAMESPACE_LABEL);
6699 /* if we found a label in the same function, then we already created the
6701 if (candidate != NULL
6702 && candidate->parent_scope == ¤t_function->scope) {
6706 /* otherwise we need to create a new one */
6707 declaration_t *const declaration = allocate_declaration_zero();
6708 declaration->namespc = NAMESPACE_LABEL;
6709 declaration->symbol = symbol;
6711 label_push(declaration);
6717 * Parses a GNU && label address expression.
6719 static expression_t *parse_label_address(void)
6721 source_position_t source_position = token.source_position;
6723 if (token.type != T_IDENTIFIER) {
6724 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6727 symbol_t *symbol = token.v.symbol;
6730 declaration_t *label = get_label(symbol);
6733 label->address_taken = true;
6735 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6736 expression->base.source_position = source_position;
6738 /* label address is threaten as a void pointer */
6739 expression->base.type = type_void_ptr;
6740 expression->label_address.declaration = label;
6743 return create_invalid_expression();
6747 * Parse a microsoft __noop expression.
6749 static expression_t *parse_noop_expression(void)
6751 source_position_t source_position = *HERE;
6754 if (token.type == '(') {
6755 /* parse arguments */
6757 add_anchor_token(')');
6758 add_anchor_token(',');
6760 if (token.type != ')') {
6762 (void)parse_assignment_expression();
6763 if (token.type != ',')
6769 rem_anchor_token(',');
6770 rem_anchor_token(')');
6773 /* the result is a (int)0 */
6774 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6775 cnst->base.source_position = source_position;
6776 cnst->base.type = type_int;
6777 cnst->conste.v.int_value = 0;
6778 cnst->conste.is_ms_noop = true;
6783 return create_invalid_expression();
6787 * Parses a primary expression.
6789 static expression_t *parse_primary_expression(void)
6791 switch (token.type) {
6792 case T_INTEGER: return parse_int_const();
6793 case T_CHARACTER_CONSTANT: return parse_character_constant();
6794 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6795 case T_FLOATINGPOINT: return parse_float_const();
6796 case T_STRING_LITERAL:
6797 case T_WIDE_STRING_LITERAL: return parse_string_const();
6798 case T_IDENTIFIER: return parse_reference();
6799 case T___FUNCTION__:
6800 case T___func__: return parse_function_keyword();
6801 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6802 case T___FUNCSIG__: return parse_funcsig_keyword();
6803 case T___FUNCDNAME__: return parse_funcdname_keyword();
6804 case T___builtin_offsetof: return parse_offsetof();
6805 case T___builtin_va_start: return parse_va_start();
6806 case T___builtin_va_arg: return parse_va_arg();
6807 case T___builtin_expect:
6808 case T___builtin_alloca:
6809 case T___builtin_nan:
6810 case T___builtin_nand:
6811 case T___builtin_nanf:
6812 case T___builtin_huge_val:
6813 case T___builtin_va_end: return parse_builtin_symbol();
6814 case T___builtin_isgreater:
6815 case T___builtin_isgreaterequal:
6816 case T___builtin_isless:
6817 case T___builtin_islessequal:
6818 case T___builtin_islessgreater:
6819 case T___builtin_isunordered: return parse_compare_builtin();
6820 case T___builtin_constant_p: return parse_builtin_constant();
6821 case T___builtin_prefetch: return parse_builtin_prefetch();
6822 case T__assume: return parse_assume();
6825 return parse_label_address();
6828 case '(': return parse_parenthesized_expression();
6829 case T___noop: return parse_noop_expression();
6832 errorf(HERE, "unexpected token %K, expected an expression", &token);
6833 return create_invalid_expression();
6837 * Check if the expression has the character type and issue a warning then.
6839 static void check_for_char_index_type(const expression_t *expression)
6841 type_t *const type = expression->base.type;
6842 const type_t *const base_type = skip_typeref(type);
6844 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6845 warning.char_subscripts) {
6846 warningf(&expression->base.source_position,
6847 "array subscript has type '%T'", type);
6851 static expression_t *parse_array_expression(unsigned precedence,
6857 add_anchor_token(']');
6859 expression_t *inside = parse_expression();
6861 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6863 array_access_expression_t *array_access = &expression->array_access;
6865 type_t *const orig_type_left = left->base.type;
6866 type_t *const orig_type_inside = inside->base.type;
6868 type_t *const type_left = skip_typeref(orig_type_left);
6869 type_t *const type_inside = skip_typeref(orig_type_inside);
6871 type_t *return_type;
6872 if (is_type_pointer(type_left)) {
6873 return_type = type_left->pointer.points_to;
6874 array_access->array_ref = left;
6875 array_access->index = inside;
6876 check_for_char_index_type(inside);
6877 } else if (is_type_pointer(type_inside)) {
6878 return_type = type_inside->pointer.points_to;
6879 array_access->array_ref = inside;
6880 array_access->index = left;
6881 array_access->flipped = true;
6882 check_for_char_index_type(left);
6884 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6886 "array access on object with non-pointer types '%T', '%T'",
6887 orig_type_left, orig_type_inside);
6889 return_type = type_error_type;
6890 array_access->array_ref = left;
6891 array_access->index = inside;
6894 expression->base.type = automatic_type_conversion(return_type);
6896 rem_anchor_token(']');
6897 if (token.type == ']') {
6900 parse_error_expected("Problem while parsing array access", ']', NULL);
6905 static expression_t *parse_typeprop(expression_kind_t const kind,
6906 source_position_t const pos,
6907 unsigned const precedence)
6909 expression_t *tp_expression = allocate_expression_zero(kind);
6910 tp_expression->base.type = type_size_t;
6911 tp_expression->base.source_position = pos;
6913 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6915 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6917 add_anchor_token(')');
6918 type_t* const orig_type = parse_typename();
6919 tp_expression->typeprop.type = orig_type;
6921 type_t const* const type = skip_typeref(orig_type);
6922 char const* const wrong_type =
6923 is_type_incomplete(type) ? "incomplete" :
6924 type->kind == TYPE_FUNCTION ? "function designator" :
6925 type->kind == TYPE_BITFIELD ? "bitfield" :
6927 if (wrong_type != NULL) {
6928 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6929 what, wrong_type, type);
6932 rem_anchor_token(')');
6935 expression_t *expression = parse_sub_expression(precedence);
6937 type_t* const orig_type = revert_automatic_type_conversion(expression);
6938 expression->base.type = orig_type;
6940 type_t const* const type = skip_typeref(orig_type);
6941 char const* const wrong_type =
6942 is_type_incomplete(type) ? "incomplete" :
6943 type->kind == TYPE_FUNCTION ? "function designator" :
6944 type->kind == TYPE_BITFIELD ? "bitfield" :
6946 if (wrong_type != NULL) {
6947 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6950 tp_expression->typeprop.type = expression->base.type;
6951 tp_expression->typeprop.tp_expression = expression;
6955 return tp_expression;
6958 static expression_t *parse_sizeof(unsigned precedence)
6960 source_position_t pos = *HERE;
6962 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6965 static expression_t *parse_alignof(unsigned precedence)
6967 source_position_t pos = *HERE;
6969 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6972 static expression_t *parse_select_expression(unsigned precedence,
6973 expression_t *compound)
6976 assert(token.type == '.' || token.type == T_MINUSGREATER);
6978 bool is_pointer = (token.type == T_MINUSGREATER);
6981 expression_t *select = allocate_expression_zero(EXPR_SELECT);
6982 select->select.compound = compound;
6984 if (token.type != T_IDENTIFIER) {
6985 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6988 symbol_t *symbol = token.v.symbol;
6991 type_t *const orig_type = compound->base.type;
6992 type_t *const type = skip_typeref(orig_type);
6995 bool saw_error = false;
6996 if (is_type_pointer(type)) {
6999 "request for member '%Y' in something not a struct or union, but '%T'",
7003 type_left = skip_typeref(type->pointer.points_to);
7005 if (is_pointer && is_type_valid(type)) {
7006 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7012 declaration_t *entry;
7013 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7014 type_left->kind == TYPE_COMPOUND_UNION) {
7015 declaration_t *const declaration = type_left->compound.declaration;
7017 if (!declaration->init.complete) {
7018 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7020 goto create_error_entry;
7023 entry = find_compound_entry(declaration, symbol);
7024 if (entry == NULL) {
7025 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7026 goto create_error_entry;
7029 if (is_type_valid(type_left) && !saw_error) {
7031 "request for member '%Y' in something not a struct or union, but '%T'",
7035 entry = allocate_declaration_zero();
7036 entry->symbol = symbol;
7039 select->select.compound_entry = entry;
7041 type_t *const res_type =
7042 get_qualified_type(entry->type, type_left->base.qualifiers);
7044 /* we always do the auto-type conversions; the & and sizeof parser contains
7045 * code to revert this! */
7046 select->base.type = automatic_type_conversion(res_type);
7048 type_t *skipped = skip_typeref(res_type);
7049 if (skipped->kind == TYPE_BITFIELD) {
7050 select->base.type = skipped->bitfield.base_type;
7056 static void check_call_argument(const function_parameter_t *parameter,
7057 call_argument_t *argument, unsigned pos)
7059 type_t *expected_type = parameter->type;
7060 type_t *expected_type_skip = skip_typeref(expected_type);
7061 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7062 expression_t *arg_expr = argument->expression;
7063 type_t *arg_type = skip_typeref(arg_expr->base.type);
7065 /* handle transparent union gnu extension */
7066 if (is_type_union(expected_type_skip)
7067 && (expected_type_skip->base.modifiers
7068 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7069 declaration_t *union_decl = expected_type_skip->compound.declaration;
7071 declaration_t *declaration = union_decl->scope.declarations;
7072 type_t *best_type = NULL;
7073 for ( ; declaration != NULL; declaration = declaration->next) {
7074 type_t *decl_type = declaration->type;
7075 error = semantic_assign(decl_type, arg_expr);
7076 if (error == ASSIGN_ERROR_INCOMPATIBLE
7077 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7080 if (error == ASSIGN_SUCCESS) {
7081 best_type = decl_type;
7082 } else if (best_type == NULL) {
7083 best_type = decl_type;
7087 if (best_type != NULL) {
7088 expected_type = best_type;
7092 error = semantic_assign(expected_type, arg_expr);
7093 argument->expression = create_implicit_cast(argument->expression,
7096 if (error != ASSIGN_SUCCESS) {
7097 /* report exact scope in error messages (like "in argument 3") */
7099 snprintf(buf, sizeof(buf), "call argument %u", pos);
7100 report_assign_error(error, expected_type, arg_expr, buf,
7101 &arg_expr->base.source_position);
7102 } else if (warning.traditional || warning.conversion) {
7103 type_t *const promoted_type = get_default_promoted_type(arg_type);
7104 if (!types_compatible(expected_type_skip, promoted_type) &&
7105 !types_compatible(expected_type_skip, type_void_ptr) &&
7106 !types_compatible(type_void_ptr, promoted_type)) {
7107 /* Deliberately show the skipped types in this warning */
7108 warningf(&arg_expr->base.source_position,
7109 "passing call argument %u as '%T' rather than '%T' due to prototype",
7110 pos, expected_type_skip, promoted_type);
7116 * Parse a call expression, ie. expression '( ... )'.
7118 * @param expression the function address
7120 static expression_t *parse_call_expression(unsigned precedence,
7121 expression_t *expression)
7124 expression_t *result = allocate_expression_zero(EXPR_CALL);
7125 result->base.source_position = expression->base.source_position;
7127 call_expression_t *call = &result->call;
7128 call->function = expression;
7130 type_t *const orig_type = expression->base.type;
7131 type_t *const type = skip_typeref(orig_type);
7133 function_type_t *function_type = NULL;
7134 if (is_type_pointer(type)) {
7135 type_t *const to_type = skip_typeref(type->pointer.points_to);
7137 if (is_type_function(to_type)) {
7138 function_type = &to_type->function;
7139 call->base.type = function_type->return_type;
7143 if (function_type == NULL && is_type_valid(type)) {
7144 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7147 /* parse arguments */
7149 add_anchor_token(')');
7150 add_anchor_token(',');
7152 if (token.type != ')') {
7153 call_argument_t *last_argument = NULL;
7156 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7158 argument->expression = parse_assignment_expression();
7159 if (last_argument == NULL) {
7160 call->arguments = argument;
7162 last_argument->next = argument;
7164 last_argument = argument;
7166 if (token.type != ',')
7171 rem_anchor_token(',');
7172 rem_anchor_token(')');
7175 if (function_type == NULL)
7178 function_parameter_t *parameter = function_type->parameters;
7179 call_argument_t *argument = call->arguments;
7180 if (!function_type->unspecified_parameters) {
7181 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7182 parameter = parameter->next, argument = argument->next) {
7183 check_call_argument(parameter, argument, ++pos);
7186 if (parameter != NULL) {
7187 errorf(HERE, "too few arguments to function '%E'", expression);
7188 } else if (argument != NULL && !function_type->variadic) {
7189 errorf(HERE, "too many arguments to function '%E'", expression);
7193 /* do default promotion */
7194 for( ; argument != NULL; argument = argument->next) {
7195 type_t *type = argument->expression->base.type;
7197 type = get_default_promoted_type(type);
7199 argument->expression
7200 = create_implicit_cast(argument->expression, type);
7203 check_format(&result->call);
7205 if (warning.aggregate_return &&
7206 is_type_compound(skip_typeref(function_type->return_type))) {
7207 warningf(&result->base.source_position,
7208 "function call has aggregate value");
7215 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7217 static bool same_compound_type(const type_t *type1, const type_t *type2)
7220 is_type_compound(type1) &&
7221 type1->kind == type2->kind &&
7222 type1->compound.declaration == type2->compound.declaration;
7226 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7228 * @param expression the conditional expression
7230 static expression_t *parse_conditional_expression(unsigned precedence,
7231 expression_t *expression)
7233 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7235 conditional_expression_t *conditional = &result->conditional;
7236 conditional->base.source_position = *HERE;
7237 conditional->condition = expression;
7240 add_anchor_token(':');
7243 type_t *const condition_type_orig = expression->base.type;
7244 type_t *const condition_type = skip_typeref(condition_type_orig);
7245 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7246 type_error("expected a scalar type in conditional condition",
7247 &expression->base.source_position, condition_type_orig);
7250 expression_t *true_expression = expression;
7251 bool gnu_cond = false;
7252 if ((c_mode & _GNUC) && token.type == ':') {
7255 true_expression = parse_expression();
7256 rem_anchor_token(':');
7258 expression_t *false_expression = parse_sub_expression(precedence);
7260 type_t *const orig_true_type = true_expression->base.type;
7261 type_t *const orig_false_type = false_expression->base.type;
7262 type_t *const true_type = skip_typeref(orig_true_type);
7263 type_t *const false_type = skip_typeref(orig_false_type);
7266 type_t *result_type;
7267 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7268 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7269 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
7270 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7271 warningf(&conditional->base.source_position,
7272 "ISO C forbids conditional expression with only one void side");
7274 result_type = type_void;
7275 } else if (is_type_arithmetic(true_type)
7276 && is_type_arithmetic(false_type)) {
7277 result_type = semantic_arithmetic(true_type, false_type);
7279 true_expression = create_implicit_cast(true_expression, result_type);
7280 false_expression = create_implicit_cast(false_expression, result_type);
7282 conditional->true_expression = true_expression;
7283 conditional->false_expression = false_expression;
7284 conditional->base.type = result_type;
7285 } else if (same_compound_type(true_type, false_type)) {
7286 /* just take 1 of the 2 types */
7287 result_type = true_type;
7288 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7289 type_t *pointer_type;
7291 expression_t *other_expression;
7292 if (is_type_pointer(true_type) &&
7293 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7294 pointer_type = true_type;
7295 other_type = false_type;
7296 other_expression = false_expression;
7298 pointer_type = false_type;
7299 other_type = true_type;
7300 other_expression = true_expression;
7303 if (is_null_pointer_constant(other_expression)) {
7304 result_type = pointer_type;
7305 } else if (is_type_pointer(other_type)) {
7306 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7307 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7310 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7311 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7313 } else if (types_compatible(get_unqualified_type(to1),
7314 get_unqualified_type(to2))) {
7317 warningf(&conditional->base.source_position,
7318 "pointer types '%T' and '%T' in conditional expression are incompatible",
7319 true_type, false_type);
7323 type_t *const type =
7324 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7325 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7326 } else if (is_type_integer(other_type)) {
7327 warningf(&conditional->base.source_position,
7328 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7329 result_type = pointer_type;
7331 type_error_incompatible("while parsing conditional",
7332 &expression->base.source_position, true_type, false_type);
7333 result_type = type_error_type;
7336 /* TODO: one pointer to void*, other some pointer */
7338 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7339 type_error_incompatible("while parsing conditional",
7340 &conditional->base.source_position, true_type,
7343 result_type = type_error_type;
7346 conditional->true_expression
7347 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7348 conditional->false_expression
7349 = create_implicit_cast(false_expression, result_type);
7350 conditional->base.type = result_type;
7353 return create_invalid_expression();
7357 * Parse an extension expression.
7359 static expression_t *parse_extension(unsigned precedence)
7361 eat(T___extension__);
7363 /* TODO enable extensions */
7364 expression_t *expression = parse_sub_expression(precedence);
7365 /* TODO disable extensions */
7370 * Parse a __builtin_classify_type() expression.
7372 static expression_t *parse_builtin_classify_type(const unsigned precedence)
7374 eat(T___builtin_classify_type);
7376 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7377 result->base.type = type_int;
7380 add_anchor_token(')');
7381 expression_t *expression = parse_sub_expression(precedence);
7382 rem_anchor_token(')');
7384 result->classify_type.type_expression = expression;
7388 return create_invalid_expression();
7391 static bool check_pointer_arithmetic(const source_position_t *source_position,
7392 type_t *pointer_type,
7393 type_t *orig_pointer_type)
7395 type_t *points_to = pointer_type->pointer.points_to;
7396 points_to = skip_typeref(points_to);
7398 if (is_type_incomplete(points_to)) {
7399 if (!(c_mode & _GNUC) || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7400 errorf(source_position,
7401 "arithmetic with pointer to incomplete type '%T' not allowed",
7404 } else if (warning.pointer_arith) {
7405 warningf(source_position,
7406 "pointer of type '%T' used in arithmetic",
7409 } else if (is_type_function(points_to)) {
7410 if (!(c_mode && _GNUC)) {
7411 errorf(source_position,
7412 "arithmetic with pointer to function type '%T' not allowed",
7415 } else if (warning.pointer_arith) {
7416 warningf(source_position,
7417 "pointer to a function '%T' used in arithmetic",
7424 static bool is_lvalue(const expression_t *expression)
7426 switch (expression->kind) {
7427 case EXPR_REFERENCE:
7428 case EXPR_ARRAY_ACCESS:
7430 case EXPR_UNARY_DEREFERENCE:
7438 static void semantic_incdec(unary_expression_t *expression)
7440 type_t *const orig_type = expression->value->base.type;
7441 type_t *const type = skip_typeref(orig_type);
7442 if (is_type_pointer(type)) {
7443 if (!check_pointer_arithmetic(&expression->base.source_position,
7447 } else if (!is_type_real(type) && is_type_valid(type)) {
7448 /* TODO: improve error message */
7449 errorf(&expression->base.source_position,
7450 "operation needs an arithmetic or pointer type");
7453 if (!is_lvalue(expression->value)) {
7454 /* TODO: improve error message */
7455 errorf(&expression->base.source_position, "lvalue required as operand");
7457 expression->base.type = orig_type;
7460 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7462 type_t *const orig_type = expression->value->base.type;
7463 type_t *const type = skip_typeref(orig_type);
7464 if (!is_type_arithmetic(type)) {
7465 if (is_type_valid(type)) {
7466 /* TODO: improve error message */
7467 errorf(&expression->base.source_position,
7468 "operation needs an arithmetic type");
7473 expression->base.type = orig_type;
7476 static void semantic_unexpr_plus(unary_expression_t *expression)
7478 semantic_unexpr_arithmetic(expression);
7479 if (warning.traditional)
7480 warningf(&expression->base.source_position,
7481 "traditional C rejects the unary plus operator");
7484 static void semantic_not(unary_expression_t *expression)
7486 type_t *const orig_type = expression->value->base.type;
7487 type_t *const type = skip_typeref(orig_type);
7488 if (!is_type_scalar(type) && is_type_valid(type)) {
7489 errorf(&expression->base.source_position,
7490 "operand of ! must be of scalar type");
7493 expression->base.type = type_int;
7496 static void semantic_unexpr_integer(unary_expression_t *expression)
7498 type_t *const orig_type = expression->value->base.type;
7499 type_t *const type = skip_typeref(orig_type);
7500 if (!is_type_integer(type)) {
7501 if (is_type_valid(type)) {
7502 errorf(&expression->base.source_position,
7503 "operand of ~ must be of integer type");
7508 expression->base.type = orig_type;
7511 static void semantic_dereference(unary_expression_t *expression)
7513 type_t *const orig_type = expression->value->base.type;
7514 type_t *const type = skip_typeref(orig_type);
7515 if (!is_type_pointer(type)) {
7516 if (is_type_valid(type)) {
7517 errorf(&expression->base.source_position,
7518 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7523 type_t *result_type = type->pointer.points_to;
7524 result_type = automatic_type_conversion(result_type);
7525 expression->base.type = result_type;
7529 * Record that an address is taken (expression represents an lvalue).
7531 * @param expression the expression
7532 * @param may_be_register if true, the expression might be an register
7534 static void set_address_taken(expression_t *expression, bool may_be_register)
7536 if (expression->kind != EXPR_REFERENCE)
7539 declaration_t *const declaration = expression->reference.declaration;
7540 /* happens for parse errors */
7541 if (declaration == NULL)
7544 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7545 errorf(&expression->base.source_position,
7546 "address of register variable '%Y' requested",
7547 declaration->symbol);
7549 declaration->address_taken = 1;
7554 * Check the semantic of the address taken expression.
7556 static void semantic_take_addr(unary_expression_t *expression)
7558 expression_t *value = expression->value;
7559 value->base.type = revert_automatic_type_conversion(value);
7561 type_t *orig_type = value->base.type;
7562 if (!is_type_valid(orig_type))
7565 set_address_taken(value, false);
7567 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7570 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7571 static expression_t *parse_##unexpression_type(unsigned precedence) \
7573 expression_t *unary_expression \
7574 = allocate_expression_zero(unexpression_type); \
7575 unary_expression->base.source_position = *HERE; \
7577 unary_expression->unary.value = parse_sub_expression(precedence); \
7579 sfunc(&unary_expression->unary); \
7581 return unary_expression; \
7584 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7585 semantic_unexpr_arithmetic)
7586 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7587 semantic_unexpr_plus)
7588 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7590 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7591 semantic_dereference)
7592 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7594 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7595 semantic_unexpr_integer)
7596 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7598 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7601 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7603 static expression_t *parse_##unexpression_type(unsigned precedence, \
7604 expression_t *left) \
7606 (void) precedence; \
7608 expression_t *unary_expression \
7609 = allocate_expression_zero(unexpression_type); \
7610 unary_expression->base.source_position = *HERE; \
7612 unary_expression->unary.value = left; \
7614 sfunc(&unary_expression->unary); \
7616 return unary_expression; \
7619 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7620 EXPR_UNARY_POSTFIX_INCREMENT,
7622 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7623 EXPR_UNARY_POSTFIX_DECREMENT,
7626 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7628 /* TODO: handle complex + imaginary types */
7630 type_left = get_unqualified_type(type_left);
7631 type_right = get_unqualified_type(type_right);
7633 /* § 6.3.1.8 Usual arithmetic conversions */
7634 if (type_left == type_long_double || type_right == type_long_double) {
7635 return type_long_double;
7636 } else if (type_left == type_double || type_right == type_double) {
7638 } else if (type_left == type_float || type_right == type_float) {
7642 type_left = promote_integer(type_left);
7643 type_right = promote_integer(type_right);
7645 if (type_left == type_right)
7648 bool const signed_left = is_type_signed(type_left);
7649 bool const signed_right = is_type_signed(type_right);
7650 int const rank_left = get_rank(type_left);
7651 int const rank_right = get_rank(type_right);
7653 if (signed_left == signed_right)
7654 return rank_left >= rank_right ? type_left : type_right;
7663 u_rank = rank_right;
7664 u_type = type_right;
7666 s_rank = rank_right;
7667 s_type = type_right;
7672 if (u_rank >= s_rank)
7675 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7677 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7678 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7682 case ATOMIC_TYPE_INT: return type_unsigned_int;
7683 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7684 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7686 default: panic("invalid atomic type");
7691 * Check the semantic restrictions for a binary expression.
7693 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7695 expression_t *const left = expression->left;
7696 expression_t *const right = expression->right;
7697 type_t *const orig_type_left = left->base.type;
7698 type_t *const orig_type_right = right->base.type;
7699 type_t *const type_left = skip_typeref(orig_type_left);
7700 type_t *const type_right = skip_typeref(orig_type_right);
7702 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7703 /* TODO: improve error message */
7704 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7705 errorf(&expression->base.source_position,
7706 "operation needs arithmetic types");
7711 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7712 expression->left = create_implicit_cast(left, arithmetic_type);
7713 expression->right = create_implicit_cast(right, arithmetic_type);
7714 expression->base.type = arithmetic_type;
7717 static void warn_div_by_zero(binary_expression_t const *const expression)
7719 if (!warning.div_by_zero ||
7720 !is_type_integer(expression->base.type))
7723 expression_t const *const right = expression->right;
7724 /* The type of the right operand can be different for /= */
7725 if (is_type_integer(right->base.type) &&
7726 is_constant_expression(right) &&
7727 fold_constant(right) == 0) {
7728 warningf(&expression->base.source_position, "division by zero");
7733 * Check the semantic restrictions for a div/mod expression.
7735 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
7736 semantic_binexpr_arithmetic(expression);
7737 warn_div_by_zero(expression);
7740 static void semantic_shift_op(binary_expression_t *expression)
7742 expression_t *const left = expression->left;
7743 expression_t *const right = expression->right;
7744 type_t *const orig_type_left = left->base.type;
7745 type_t *const orig_type_right = right->base.type;
7746 type_t * type_left = skip_typeref(orig_type_left);
7747 type_t * type_right = skip_typeref(orig_type_right);
7749 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7750 /* TODO: improve error message */
7751 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7752 errorf(&expression->base.source_position,
7753 "operands of shift operation must have integer types");
7758 type_left = promote_integer(type_left);
7759 type_right = promote_integer(type_right);
7761 expression->left = create_implicit_cast(left, type_left);
7762 expression->right = create_implicit_cast(right, type_right);
7763 expression->base.type = type_left;
7766 static void semantic_add(binary_expression_t *expression)
7768 expression_t *const left = expression->left;
7769 expression_t *const right = expression->right;
7770 type_t *const orig_type_left = left->base.type;
7771 type_t *const orig_type_right = right->base.type;
7772 type_t *const type_left = skip_typeref(orig_type_left);
7773 type_t *const type_right = skip_typeref(orig_type_right);
7776 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7777 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7778 expression->left = create_implicit_cast(left, arithmetic_type);
7779 expression->right = create_implicit_cast(right, arithmetic_type);
7780 expression->base.type = arithmetic_type;
7782 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7783 check_pointer_arithmetic(&expression->base.source_position,
7784 type_left, orig_type_left);
7785 expression->base.type = type_left;
7786 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7787 check_pointer_arithmetic(&expression->base.source_position,
7788 type_right, orig_type_right);
7789 expression->base.type = type_right;
7790 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7791 errorf(&expression->base.source_position,
7792 "invalid operands to binary + ('%T', '%T')",
7793 orig_type_left, orig_type_right);
7797 static void semantic_sub(binary_expression_t *expression)
7799 expression_t *const left = expression->left;
7800 expression_t *const right = expression->right;
7801 type_t *const orig_type_left = left->base.type;
7802 type_t *const orig_type_right = right->base.type;
7803 type_t *const type_left = skip_typeref(orig_type_left);
7804 type_t *const type_right = skip_typeref(orig_type_right);
7805 source_position_t const *const pos = &expression->base.source_position;
7808 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7809 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7810 expression->left = create_implicit_cast(left, arithmetic_type);
7811 expression->right = create_implicit_cast(right, arithmetic_type);
7812 expression->base.type = arithmetic_type;
7814 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7815 check_pointer_arithmetic(&expression->base.source_position,
7816 type_left, orig_type_left);
7817 expression->base.type = type_left;
7818 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7819 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7820 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7821 if (!types_compatible(unqual_left, unqual_right)) {
7823 "subtracting pointers to incompatible types '%T' and '%T'",
7824 orig_type_left, orig_type_right);
7825 } else if (!is_type_object(unqual_left)) {
7826 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7827 warningf(pos, "subtracting pointers to void");
7829 errorf(pos, "subtracting pointers to non-object types '%T'",
7833 expression->base.type = type_ptrdiff_t;
7834 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7835 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7836 orig_type_left, orig_type_right);
7841 * Check the semantics of comparison expressions.
7843 * @param expression The expression to check.
7845 static void semantic_comparison(binary_expression_t *expression)
7847 expression_t *left = expression->left;
7848 expression_t *right = expression->right;
7849 type_t *orig_type_left = left->base.type;
7850 type_t *orig_type_right = right->base.type;
7852 type_t *type_left = skip_typeref(orig_type_left);
7853 type_t *type_right = skip_typeref(orig_type_right);
7855 /* TODO non-arithmetic types */
7856 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7857 /* test for signed vs unsigned compares */
7858 if (warning.sign_compare &&
7859 (expression->base.kind != EXPR_BINARY_EQUAL &&
7860 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7861 (is_type_signed(type_left) != is_type_signed(type_right))) {
7863 /* check if 1 of the operands is a constant, in this case we just
7864 * check wether we can safely represent the resulting constant in
7865 * the type of the other operand. */
7866 expression_t *const_expr = NULL;
7867 expression_t *other_expr = NULL;
7869 if (is_constant_expression(left)) {
7872 } else if (is_constant_expression(right)) {
7877 if (const_expr != NULL) {
7878 type_t *other_type = skip_typeref(other_expr->base.type);
7879 long val = fold_constant(const_expr);
7880 /* TODO: check if val can be represented by other_type */
7884 warningf(&expression->base.source_position,
7885 "comparison between signed and unsigned");
7887 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7888 expression->left = create_implicit_cast(left, arithmetic_type);
7889 expression->right = create_implicit_cast(right, arithmetic_type);
7890 expression->base.type = arithmetic_type;
7891 if (warning.float_equal &&
7892 (expression->base.kind == EXPR_BINARY_EQUAL ||
7893 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
7894 is_type_float(arithmetic_type)) {
7895 warningf(&expression->base.source_position,
7896 "comparing floating point with == or != is unsafe");
7898 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7899 /* TODO check compatibility */
7900 } else if (is_type_pointer(type_left)) {
7901 expression->right = create_implicit_cast(right, type_left);
7902 } else if (is_type_pointer(type_right)) {
7903 expression->left = create_implicit_cast(left, type_right);
7904 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7905 type_error_incompatible("invalid operands in comparison",
7906 &expression->base.source_position,
7907 type_left, type_right);
7909 expression->base.type = type_int;
7913 * Checks if a compound type has constant fields.
7915 static bool has_const_fields(const compound_type_t *type)
7917 const scope_t *scope = &type->declaration->scope;
7918 const declaration_t *declaration = scope->declarations;
7920 for (; declaration != NULL; declaration = declaration->next) {
7921 if (declaration->namespc != NAMESPACE_NORMAL)
7924 const type_t *decl_type = skip_typeref(declaration->type);
7925 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
7932 static bool is_valid_assignment_lhs(expression_t const* const left)
7934 type_t *const orig_type_left = revert_automatic_type_conversion(left);
7935 type_t *const type_left = skip_typeref(orig_type_left);
7937 if (!is_lvalue(left)) {
7938 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
7943 if (is_type_array(type_left)) {
7944 errorf(HERE, "cannot assign to arrays ('%E')", left);
7947 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
7948 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
7952 if (is_type_incomplete(type_left)) {
7953 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
7954 left, orig_type_left);
7957 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
7958 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
7959 left, orig_type_left);
7966 static void semantic_arithmetic_assign(binary_expression_t *expression)
7968 expression_t *left = expression->left;
7969 expression_t *right = expression->right;
7970 type_t *orig_type_left = left->base.type;
7971 type_t *orig_type_right = right->base.type;
7973 if (!is_valid_assignment_lhs(left))
7976 type_t *type_left = skip_typeref(orig_type_left);
7977 type_t *type_right = skip_typeref(orig_type_right);
7979 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7980 /* TODO: improve error message */
7981 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7982 errorf(&expression->base.source_position,
7983 "operation needs arithmetic types");
7988 /* combined instructions are tricky. We can't create an implicit cast on
7989 * the left side, because we need the uncasted form for the store.
7990 * The ast2firm pass has to know that left_type must be right_type
7991 * for the arithmetic operation and create a cast by itself */
7992 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7993 expression->right = create_implicit_cast(right, arithmetic_type);
7994 expression->base.type = type_left;
7997 static void semantic_divmod_assign(binary_expression_t *expression)
7999 semantic_arithmetic_assign(expression);
8000 warn_div_by_zero(expression);
8003 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8005 expression_t *const left = expression->left;
8006 expression_t *const right = expression->right;
8007 type_t *const orig_type_left = left->base.type;
8008 type_t *const orig_type_right = right->base.type;
8009 type_t *const type_left = skip_typeref(orig_type_left);
8010 type_t *const type_right = skip_typeref(orig_type_right);
8012 if (!is_valid_assignment_lhs(left))
8015 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8016 /* combined instructions are tricky. We can't create an implicit cast on
8017 * the left side, because we need the uncasted form for the store.
8018 * The ast2firm pass has to know that left_type must be right_type
8019 * for the arithmetic operation and create a cast by itself */
8020 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8021 expression->right = create_implicit_cast(right, arithmetic_type);
8022 expression->base.type = type_left;
8023 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8024 check_pointer_arithmetic(&expression->base.source_position,
8025 type_left, orig_type_left);
8026 expression->base.type = type_left;
8027 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8028 errorf(&expression->base.source_position,
8029 "incompatible types '%T' and '%T' in assignment",
8030 orig_type_left, orig_type_right);
8035 * Check the semantic restrictions of a logical expression.
8037 static void semantic_logical_op(binary_expression_t *expression)
8039 expression_t *const left = expression->left;
8040 expression_t *const right = expression->right;
8041 type_t *const orig_type_left = left->base.type;
8042 type_t *const orig_type_right = right->base.type;
8043 type_t *const type_left = skip_typeref(orig_type_left);
8044 type_t *const type_right = skip_typeref(orig_type_right);
8046 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8047 /* TODO: improve error message */
8048 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8049 errorf(&expression->base.source_position,
8050 "operation needs scalar types");
8055 expression->base.type = type_int;
8059 * Check the semantic restrictions of a binary assign expression.
8061 static void semantic_binexpr_assign(binary_expression_t *expression)
8063 expression_t *left = expression->left;
8064 type_t *orig_type_left = left->base.type;
8066 if (!is_valid_assignment_lhs(left))
8069 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8070 report_assign_error(error, orig_type_left, expression->right,
8071 "assignment", &left->base.source_position);
8072 expression->right = create_implicit_cast(expression->right, orig_type_left);
8073 expression->base.type = orig_type_left;
8077 * Determine if the outermost operation (or parts thereof) of the given
8078 * expression has no effect in order to generate a warning about this fact.
8079 * Therefore in some cases this only examines some of the operands of the
8080 * expression (see comments in the function and examples below).
8082 * f() + 23; // warning, because + has no effect
8083 * x || f(); // no warning, because x controls execution of f()
8084 * x ? y : f(); // warning, because y has no effect
8085 * (void)x; // no warning to be able to suppress the warning
8086 * This function can NOT be used for an "expression has definitely no effect"-
8088 static bool expression_has_effect(const expression_t *const expr)
8090 switch (expr->kind) {
8091 case EXPR_UNKNOWN: break;
8092 case EXPR_INVALID: return true; /* do NOT warn */
8093 case EXPR_REFERENCE: return false;
8094 /* suppress the warning for microsoft __noop operations */
8095 case EXPR_CONST: return expr->conste.is_ms_noop;
8096 case EXPR_CHARACTER_CONSTANT: return false;
8097 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8098 case EXPR_STRING_LITERAL: return false;
8099 case EXPR_WIDE_STRING_LITERAL: return false;
8100 case EXPR_LABEL_ADDRESS: return false;
8103 const call_expression_t *const call = &expr->call;
8104 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8107 switch (call->function->builtin_symbol.symbol->ID) {
8108 case T___builtin_va_end: return true;
8109 default: return false;
8113 /* Generate the warning if either the left or right hand side of a
8114 * conditional expression has no effect */
8115 case EXPR_CONDITIONAL: {
8116 const conditional_expression_t *const cond = &expr->conditional;
8118 expression_has_effect(cond->true_expression) &&
8119 expression_has_effect(cond->false_expression);
8122 case EXPR_SELECT: return false;
8123 case EXPR_ARRAY_ACCESS: return false;
8124 case EXPR_SIZEOF: return false;
8125 case EXPR_CLASSIFY_TYPE: return false;
8126 case EXPR_ALIGNOF: return false;
8128 case EXPR_FUNCNAME: return false;
8129 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8130 case EXPR_BUILTIN_CONSTANT_P: return false;
8131 case EXPR_BUILTIN_PREFETCH: return true;
8132 case EXPR_OFFSETOF: return false;
8133 case EXPR_VA_START: return true;
8134 case EXPR_VA_ARG: return true;
8135 case EXPR_STATEMENT: return true; // TODO
8136 case EXPR_COMPOUND_LITERAL: return false;
8138 case EXPR_UNARY_NEGATE: return false;
8139 case EXPR_UNARY_PLUS: return false;
8140 case EXPR_UNARY_BITWISE_NEGATE: return false;
8141 case EXPR_UNARY_NOT: return false;
8142 case EXPR_UNARY_DEREFERENCE: return false;
8143 case EXPR_UNARY_TAKE_ADDRESS: return false;
8144 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8145 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8146 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8147 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8149 /* Treat void casts as if they have an effect in order to being able to
8150 * suppress the warning */
8151 case EXPR_UNARY_CAST: {
8152 type_t *const type = skip_typeref(expr->base.type);
8153 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8156 case EXPR_UNARY_CAST_IMPLICIT: return true;
8157 case EXPR_UNARY_ASSUME: return true;
8159 case EXPR_BINARY_ADD: return false;
8160 case EXPR_BINARY_SUB: return false;
8161 case EXPR_BINARY_MUL: return false;
8162 case EXPR_BINARY_DIV: return false;
8163 case EXPR_BINARY_MOD: return false;
8164 case EXPR_BINARY_EQUAL: return false;
8165 case EXPR_BINARY_NOTEQUAL: return false;
8166 case EXPR_BINARY_LESS: return false;
8167 case EXPR_BINARY_LESSEQUAL: return false;
8168 case EXPR_BINARY_GREATER: return false;
8169 case EXPR_BINARY_GREATEREQUAL: return false;
8170 case EXPR_BINARY_BITWISE_AND: return false;
8171 case EXPR_BINARY_BITWISE_OR: return false;
8172 case EXPR_BINARY_BITWISE_XOR: return false;
8173 case EXPR_BINARY_SHIFTLEFT: return false;
8174 case EXPR_BINARY_SHIFTRIGHT: return false;
8175 case EXPR_BINARY_ASSIGN: return true;
8176 case EXPR_BINARY_MUL_ASSIGN: return true;
8177 case EXPR_BINARY_DIV_ASSIGN: return true;
8178 case EXPR_BINARY_MOD_ASSIGN: return true;
8179 case EXPR_BINARY_ADD_ASSIGN: return true;
8180 case EXPR_BINARY_SUB_ASSIGN: return true;
8181 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8182 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8183 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8184 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8185 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8187 /* Only examine the right hand side of && and ||, because the left hand
8188 * side already has the effect of controlling the execution of the right
8190 case EXPR_BINARY_LOGICAL_AND:
8191 case EXPR_BINARY_LOGICAL_OR:
8192 /* Only examine the right hand side of a comma expression, because the left
8193 * hand side has a separate warning */
8194 case EXPR_BINARY_COMMA:
8195 return expression_has_effect(expr->binary.right);
8197 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8198 case EXPR_BINARY_ISGREATER: return false;
8199 case EXPR_BINARY_ISGREATEREQUAL: return false;
8200 case EXPR_BINARY_ISLESS: return false;
8201 case EXPR_BINARY_ISLESSEQUAL: return false;
8202 case EXPR_BINARY_ISLESSGREATER: return false;
8203 case EXPR_BINARY_ISUNORDERED: return false;
8206 internal_errorf(HERE, "unexpected expression");
8209 static void semantic_comma(binary_expression_t *expression)
8211 if (warning.unused_value) {
8212 const expression_t *const left = expression->left;
8213 if (!expression_has_effect(left)) {
8214 warningf(&left->base.source_position,
8215 "left-hand operand of comma expression has no effect");
8218 expression->base.type = expression->right->base.type;
8221 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
8222 static expression_t *parse_##binexpression_type(unsigned precedence, \
8223 expression_t *left) \
8225 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8226 binexpr->base.source_position = *HERE; \
8227 binexpr->binary.left = left; \
8230 expression_t *right = parse_sub_expression(precedence + lr); \
8232 binexpr->binary.right = right; \
8233 sfunc(&binexpr->binary); \
8238 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
8239 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
8240 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_divmod_arithmetic, 1)
8241 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_divmod_arithmetic, 1)
8242 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
8243 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
8244 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
8245 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
8246 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
8248 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
8249 semantic_comparison, 1)
8250 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
8251 semantic_comparison, 1)
8252 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
8253 semantic_comparison, 1)
8254 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
8255 semantic_comparison, 1)
8257 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
8258 semantic_binexpr_arithmetic, 1)
8259 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
8260 semantic_binexpr_arithmetic, 1)
8261 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
8262 semantic_binexpr_arithmetic, 1)
8263 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
8264 semantic_logical_op, 1)
8265 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
8266 semantic_logical_op, 1)
8267 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
8268 semantic_shift_op, 1)
8269 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
8270 semantic_shift_op, 1)
8271 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
8272 semantic_arithmetic_addsubb_assign, 0)
8273 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
8274 semantic_arithmetic_addsubb_assign, 0)
8275 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
8276 semantic_arithmetic_assign, 0)
8277 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
8278 semantic_divmod_assign, 0)
8279 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
8280 semantic_divmod_assign, 0)
8281 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
8282 semantic_arithmetic_assign, 0)
8283 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8284 semantic_arithmetic_assign, 0)
8285 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
8286 semantic_arithmetic_assign, 0)
8287 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
8288 semantic_arithmetic_assign, 0)
8289 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
8290 semantic_arithmetic_assign, 0)
8292 static expression_t *parse_sub_expression(unsigned precedence)
8294 if (token.type < 0) {
8295 return expected_expression_error();
8298 expression_parser_function_t *parser
8299 = &expression_parsers[token.type];
8300 source_position_t source_position = token.source_position;
8303 if (parser->parser != NULL) {
8304 left = parser->parser(parser->precedence);
8306 left = parse_primary_expression();
8308 assert(left != NULL);
8309 left->base.source_position = source_position;
8312 if (token.type < 0) {
8313 return expected_expression_error();
8316 parser = &expression_parsers[token.type];
8317 if (parser->infix_parser == NULL)
8319 if (parser->infix_precedence < precedence)
8322 left = parser->infix_parser(parser->infix_precedence, left);
8324 assert(left != NULL);
8325 assert(left->kind != EXPR_UNKNOWN);
8326 left->base.source_position = source_position;
8333 * Parse an expression.
8335 static expression_t *parse_expression(void)
8337 return parse_sub_expression(1);
8341 * Register a parser for a prefix-like operator with given precedence.
8343 * @param parser the parser function
8344 * @param token_type the token type of the prefix token
8345 * @param precedence the precedence of the operator
8347 static void register_expression_parser(parse_expression_function parser,
8348 int token_type, unsigned precedence)
8350 expression_parser_function_t *entry = &expression_parsers[token_type];
8352 if (entry->parser != NULL) {
8353 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8354 panic("trying to register multiple expression parsers for a token");
8356 entry->parser = parser;
8357 entry->precedence = precedence;
8361 * Register a parser for an infix operator with given precedence.
8363 * @param parser the parser function
8364 * @param token_type the token type of the infix operator
8365 * @param precedence the precedence of the operator
8367 static void register_infix_parser(parse_expression_infix_function parser,
8368 int token_type, unsigned precedence)
8370 expression_parser_function_t *entry = &expression_parsers[token_type];
8372 if (entry->infix_parser != NULL) {
8373 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8374 panic("trying to register multiple infix expression parsers for a "
8377 entry->infix_parser = parser;
8378 entry->infix_precedence = precedence;
8382 * Initialize the expression parsers.
8384 static void init_expression_parsers(void)
8386 memset(&expression_parsers, 0, sizeof(expression_parsers));
8388 register_infix_parser(parse_array_expression, '[', 30);
8389 register_infix_parser(parse_call_expression, '(', 30);
8390 register_infix_parser(parse_select_expression, '.', 30);
8391 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
8392 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
8394 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
8397 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
8398 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
8399 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
8400 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
8401 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
8402 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
8403 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
8404 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
8405 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
8406 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
8407 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
8408 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
8409 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
8410 T_EXCLAMATIONMARKEQUAL, 13);
8411 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
8412 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
8413 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
8414 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
8415 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
8416 register_infix_parser(parse_conditional_expression, '?', 7);
8417 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
8418 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
8419 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
8420 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
8421 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
8422 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
8423 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
8424 T_LESSLESSEQUAL, 2);
8425 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8426 T_GREATERGREATEREQUAL, 2);
8427 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8429 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8431 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8434 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
8436 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8437 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8438 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8439 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8440 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8441 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8442 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8444 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8446 register_expression_parser(parse_sizeof, T_sizeof, 25);
8447 register_expression_parser(parse_alignof, T___alignof__, 25);
8448 register_expression_parser(parse_extension, T___extension__, 25);
8449 register_expression_parser(parse_builtin_classify_type,
8450 T___builtin_classify_type, 25);
8454 * Parse a asm statement arguments specification.
8456 static asm_argument_t *parse_asm_arguments(bool is_out)
8458 asm_argument_t *result = NULL;
8459 asm_argument_t *last = NULL;
8461 while (token.type == T_STRING_LITERAL || token.type == '[') {
8462 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8463 memset(argument, 0, sizeof(argument[0]));
8465 if (token.type == '[') {
8467 if (token.type != T_IDENTIFIER) {
8468 parse_error_expected("while parsing asm argument",
8469 T_IDENTIFIER, NULL);
8472 argument->symbol = token.v.symbol;
8477 argument->constraints = parse_string_literals();
8479 add_anchor_token(')');
8480 expression_t *expression = parse_expression();
8481 rem_anchor_token(')');
8483 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8484 * change size or type representation (e.g. int -> long is ok, but
8485 * int -> float is not) */
8486 if (expression->kind == EXPR_UNARY_CAST) {
8487 type_t *const type = expression->base.type;
8488 type_kind_t const kind = type->kind;
8489 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8492 if (kind == TYPE_ATOMIC) {
8493 atomic_type_kind_t const akind = type->atomic.akind;
8494 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8495 size = get_atomic_type_size(akind);
8497 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8498 size = get_atomic_type_size(get_intptr_kind());
8502 expression_t *const value = expression->unary.value;
8503 type_t *const value_type = value->base.type;
8504 type_kind_t const value_kind = value_type->kind;
8506 unsigned value_flags;
8507 unsigned value_size;
8508 if (value_kind == TYPE_ATOMIC) {
8509 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8510 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8511 value_size = get_atomic_type_size(value_akind);
8512 } else if (value_kind == TYPE_POINTER) {
8513 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8514 value_size = get_atomic_type_size(get_intptr_kind());
8519 if (value_flags != flags || value_size != size)
8523 } while (expression->kind == EXPR_UNARY_CAST);
8527 if (!is_lvalue(expression)) {
8528 errorf(&expression->base.source_position,
8529 "asm output argument is not an lvalue");
8532 argument->expression = expression;
8535 set_address_taken(expression, true);
8538 last->next = argument;
8544 if (token.type != ',')
8555 * Parse a asm statement clobber specification.
8557 static asm_clobber_t *parse_asm_clobbers(void)
8559 asm_clobber_t *result = NULL;
8560 asm_clobber_t *last = NULL;
8562 while(token.type == T_STRING_LITERAL) {
8563 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8564 clobber->clobber = parse_string_literals();
8567 last->next = clobber;
8573 if (token.type != ',')
8582 * Parse an asm statement.
8584 static statement_t *parse_asm_statement(void)
8588 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8589 statement->base.source_position = token.source_position;
8591 asm_statement_t *asm_statement = &statement->asms;
8593 if (token.type == T_volatile) {
8595 asm_statement->is_volatile = true;
8599 add_anchor_token(')');
8600 add_anchor_token(':');
8601 asm_statement->asm_text = parse_string_literals();
8603 if (token.type != ':') {
8604 rem_anchor_token(':');
8609 asm_statement->outputs = parse_asm_arguments(true);
8610 if (token.type != ':') {
8611 rem_anchor_token(':');
8616 asm_statement->inputs = parse_asm_arguments(false);
8617 if (token.type != ':') {
8618 rem_anchor_token(':');
8621 rem_anchor_token(':');
8624 asm_statement->clobbers = parse_asm_clobbers();
8627 rem_anchor_token(')');
8631 if (asm_statement->outputs == NULL) {
8632 /* GCC: An 'asm' instruction without any output operands will be treated
8633 * identically to a volatile 'asm' instruction. */
8634 asm_statement->is_volatile = true;
8639 return create_invalid_statement();
8643 * Parse a case statement.
8645 static statement_t *parse_case_statement(void)
8649 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8650 source_position_t *const pos = &statement->base.source_position;
8652 *pos = token.source_position;
8653 expression_t *const expression = parse_expression();
8654 statement->case_label.expression = expression;
8655 if (!is_constant_expression(expression)) {
8656 /* This check does not prevent the error message in all cases of an
8657 * prior error while parsing the expression. At least it catches the
8658 * common case of a mistyped enum entry. */
8659 if (is_type_valid(expression->base.type)) {
8660 errorf(pos, "case label does not reduce to an integer constant");
8662 statement->case_label.is_bad = true;
8664 long const val = fold_constant(expression);
8665 statement->case_label.first_case = val;
8666 statement->case_label.last_case = val;
8669 if (c_mode & _GNUC) {
8670 if (token.type == T_DOTDOTDOT) {
8672 expression_t *const end_range = parse_expression();
8673 statement->case_label.end_range = end_range;
8674 if (!is_constant_expression(end_range)) {
8675 /* This check does not prevent the error message in all cases of an
8676 * prior error while parsing the expression. At least it catches the
8677 * common case of a mistyped enum entry. */
8678 if (is_type_valid(end_range->base.type)) {
8679 errorf(pos, "case range does not reduce to an integer constant");
8681 statement->case_label.is_bad = true;
8683 long const val = fold_constant(end_range);
8684 statement->case_label.last_case = val;
8686 if (val < statement->case_label.first_case) {
8687 statement->case_label.is_empty_range = true;
8688 warningf(pos, "empty range specified");
8694 PUSH_PARENT(statement);
8698 if (current_switch != NULL) {
8699 if (! statement->case_label.is_bad) {
8700 /* Check for duplicate case values */
8701 case_label_statement_t *c = &statement->case_label;
8702 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8703 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8706 if (c->last_case < l->first_case || c->first_case > l->last_case)
8709 errorf(pos, "duplicate case value (previously used %P)",
8710 &l->base.source_position);
8714 /* link all cases into the switch statement */
8715 if (current_switch->last_case == NULL) {
8716 current_switch->first_case = &statement->case_label;
8718 current_switch->last_case->next = &statement->case_label;
8720 current_switch->last_case = &statement->case_label;
8722 errorf(pos, "case label not within a switch statement");
8725 statement_t *const inner_stmt = parse_statement();
8726 statement->case_label.statement = inner_stmt;
8727 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8728 errorf(&inner_stmt->base.source_position, "declaration after case label");
8735 return create_invalid_statement();
8739 * Parse a default statement.
8741 static statement_t *parse_default_statement(void)
8745 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8746 statement->base.source_position = token.source_position;
8748 PUSH_PARENT(statement);
8751 if (current_switch != NULL) {
8752 const case_label_statement_t *def_label = current_switch->default_label;
8753 if (def_label != NULL) {
8754 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8755 &def_label->base.source_position);
8757 current_switch->default_label = &statement->case_label;
8759 /* link all cases into the switch statement */
8760 if (current_switch->last_case == NULL) {
8761 current_switch->first_case = &statement->case_label;
8763 current_switch->last_case->next = &statement->case_label;
8765 current_switch->last_case = &statement->case_label;
8768 errorf(&statement->base.source_position,
8769 "'default' label not within a switch statement");
8772 statement_t *const inner_stmt = parse_statement();
8773 statement->case_label.statement = inner_stmt;
8774 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8775 errorf(&inner_stmt->base.source_position, "declaration after default label");
8782 return create_invalid_statement();
8786 * Parse a label statement.
8788 static statement_t *parse_label_statement(void)
8790 assert(token.type == T_IDENTIFIER);
8791 symbol_t *symbol = token.v.symbol;
8794 declaration_t *label = get_label(symbol);
8796 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8797 statement->base.source_position = token.source_position;
8798 statement->label.label = label;
8800 PUSH_PARENT(statement);
8802 /* if statement is already set then the label is defined twice,
8803 * otherwise it was just mentioned in a goto/local label declaration so far */
8804 if (label->init.statement != NULL) {
8805 errorf(HERE, "duplicate label '%Y' (declared %P)",
8806 symbol, &label->source_position);
8808 label->source_position = token.source_position;
8809 label->init.statement = statement;
8814 if (token.type == '}') {
8815 /* TODO only warn? */
8817 warningf(HERE, "label at end of compound statement");
8818 statement->label.statement = create_empty_statement();
8820 errorf(HERE, "label at end of compound statement");
8821 statement->label.statement = create_invalid_statement();
8823 } else if (token.type == ';') {
8824 /* Eat an empty statement here, to avoid the warning about an empty
8825 * statement after a label. label:; is commonly used to have a label
8826 * before a closing brace. */
8827 statement->label.statement = create_empty_statement();
8830 statement_t *const inner_stmt = parse_statement();
8831 statement->label.statement = inner_stmt;
8832 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8833 errorf(&inner_stmt->base.source_position, "declaration after label");
8837 /* remember the labels in a list for later checking */
8838 if (label_last == NULL) {
8839 label_first = &statement->label;
8841 label_last->next = &statement->label;
8843 label_last = &statement->label;
8850 * Parse an if statement.
8852 static statement_t *parse_if(void)
8856 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8857 statement->base.source_position = token.source_position;
8859 PUSH_PARENT(statement);
8862 add_anchor_token(')');
8863 statement->ifs.condition = parse_expression();
8864 rem_anchor_token(')');
8867 add_anchor_token(T_else);
8868 statement->ifs.true_statement = parse_statement();
8869 rem_anchor_token(T_else);
8871 if (token.type == T_else) {
8873 statement->ifs.false_statement = parse_statement();
8880 return create_invalid_statement();
8884 * Check that all enums are handled in a switch.
8886 * @param statement the switch statement to check
8888 static void check_enum_cases(const switch_statement_t *statement) {
8889 const type_t *type = skip_typeref(statement->expression->base.type);
8890 if (! is_type_enum(type))
8892 const enum_type_t *enumt = &type->enumt;
8894 /* if we have a default, no warnings */
8895 if (statement->default_label != NULL)
8898 /* FIXME: calculation of value should be done while parsing */
8899 const declaration_t *declaration;
8900 long last_value = -1;
8901 for (declaration = enumt->declaration->next;
8902 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
8903 declaration = declaration->next) {
8904 const expression_t *expression = declaration->init.enum_value;
8905 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
8907 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
8908 if (l->expression == NULL)
8910 if (l->first_case <= value && value <= l->last_case) {
8916 warningf(&statement->base.source_position,
8917 "enumeration value '%Y' not handled in switch", declaration->symbol);
8924 * Parse a switch statement.
8926 static statement_t *parse_switch(void)
8930 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
8931 statement->base.source_position = token.source_position;
8933 PUSH_PARENT(statement);
8936 add_anchor_token(')');
8937 expression_t *const expr = parse_expression();
8938 type_t * type = skip_typeref(expr->base.type);
8939 if (is_type_integer(type)) {
8940 type = promote_integer(type);
8941 if (warning.traditional) {
8942 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
8943 warningf(&expr->base.source_position,
8944 "'%T' switch expression not converted to '%T' in ISO C",
8948 } else if (is_type_valid(type)) {
8949 errorf(&expr->base.source_position,
8950 "switch quantity is not an integer, but '%T'", type);
8951 type = type_error_type;
8953 statement->switchs.expression = create_implicit_cast(expr, type);
8955 rem_anchor_token(')');
8957 switch_statement_t *rem = current_switch;
8958 current_switch = &statement->switchs;
8959 statement->switchs.body = parse_statement();
8960 current_switch = rem;
8962 if (warning.switch_default &&
8963 statement->switchs.default_label == NULL) {
8964 warningf(&statement->base.source_position, "switch has no default case");
8966 if (warning.switch_enum)
8967 check_enum_cases(&statement->switchs);
8973 return create_invalid_statement();
8976 static statement_t *parse_loop_body(statement_t *const loop)
8978 statement_t *const rem = current_loop;
8979 current_loop = loop;
8981 statement_t *const body = parse_statement();
8988 * Parse a while statement.
8990 static statement_t *parse_while(void)
8994 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
8995 statement->base.source_position = token.source_position;
8997 PUSH_PARENT(statement);
9000 add_anchor_token(')');
9001 statement->whiles.condition = parse_expression();
9002 rem_anchor_token(')');
9005 statement->whiles.body = parse_loop_body(statement);
9011 return create_invalid_statement();
9015 * Parse a do statement.
9017 static statement_t *parse_do(void)
9021 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9022 statement->base.source_position = token.source_position;
9024 PUSH_PARENT(statement)
9026 add_anchor_token(T_while);
9027 statement->do_while.body = parse_loop_body(statement);
9028 rem_anchor_token(T_while);
9032 add_anchor_token(')');
9033 statement->do_while.condition = parse_expression();
9034 rem_anchor_token(')');
9042 return create_invalid_statement();
9046 * Parse a for statement.
9048 static statement_t *parse_for(void)
9052 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9053 statement->base.source_position = token.source_position;
9055 PUSH_PARENT(statement);
9057 int top = environment_top();
9058 scope_t *last_scope = scope;
9059 set_scope(&statement->fors.scope);
9062 add_anchor_token(')');
9064 if (token.type != ';') {
9065 if (is_declaration_specifier(&token, false)) {
9066 parse_declaration(record_declaration);
9068 add_anchor_token(';');
9069 expression_t *const init = parse_expression();
9070 statement->fors.initialisation = init;
9071 if (warning.unused_value && !expression_has_effect(init)) {
9072 warningf(&init->base.source_position,
9073 "initialisation of 'for'-statement has no effect");
9075 rem_anchor_token(';');
9082 if (token.type != ';') {
9083 add_anchor_token(';');
9084 statement->fors.condition = parse_expression();
9085 rem_anchor_token(';');
9088 if (token.type != ')') {
9089 expression_t *const step = parse_expression();
9090 statement->fors.step = step;
9091 if (warning.unused_value && !expression_has_effect(step)) {
9092 warningf(&step->base.source_position,
9093 "step of 'for'-statement has no effect");
9096 rem_anchor_token(')');
9098 statement->fors.body = parse_loop_body(statement);
9100 assert(scope == &statement->fors.scope);
9101 set_scope(last_scope);
9102 environment_pop_to(top);
9109 rem_anchor_token(')');
9110 assert(scope == &statement->fors.scope);
9111 set_scope(last_scope);
9112 environment_pop_to(top);
9114 return create_invalid_statement();
9118 * Parse a goto statement.
9120 static statement_t *parse_goto(void)
9122 source_position_t source_position = token.source_position;
9125 statement_t *statement;
9126 if (c_mode & _GNUC && token.type == '*') {
9128 expression_t *expression = parse_expression();
9130 /* Argh: although documentation say the expression must be of type void *,
9131 * gcc excepts anything that can be casted into void * without error */
9132 type_t *type = expression->base.type;
9134 if (type != type_error_type) {
9135 if (!is_type_pointer(type) && !is_type_integer(type)) {
9136 errorf(&source_position, "cannot convert to a pointer type");
9137 } else if (type != type_void_ptr) {
9138 warningf(&source_position,
9139 "type of computed goto expression should be 'void*' not '%T'", type);
9141 expression = create_implicit_cast(expression, type_void_ptr);
9144 statement = allocate_statement_zero(STATEMENT_GOTO);
9145 statement->base.source_position = source_position;
9146 statement->gotos.expression = expression;
9148 if (token.type != T_IDENTIFIER) {
9150 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9152 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9156 symbol_t *symbol = token.v.symbol;
9159 statement = allocate_statement_zero(STATEMENT_GOTO);
9160 statement->base.source_position = source_position;
9161 statement->gotos.label = get_label(symbol);
9164 /* remember the goto's in a list for later checking */
9165 if (goto_last == NULL) {
9166 goto_first = &statement->gotos;
9168 goto_last->next = &statement->gotos;
9170 goto_last = &statement->gotos;
9176 return create_invalid_statement();
9180 * Parse a continue statement.
9182 static statement_t *parse_continue(void)
9184 if (current_loop == NULL) {
9185 errorf(HERE, "continue statement not within loop");
9188 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9189 statement->base.source_position = token.source_position;
9199 * Parse a break statement.
9201 static statement_t *parse_break(void)
9203 if (current_switch == NULL && current_loop == NULL) {
9204 errorf(HERE, "break statement not within loop or switch");
9207 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9208 statement->base.source_position = token.source_position;
9218 * Parse a __leave statement.
9220 static statement_t *parse_leave_statement(void)
9222 if (current_try == NULL) {
9223 errorf(HERE, "__leave statement not within __try");
9226 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9227 statement->base.source_position = token.source_position;
9237 * Check if a given declaration represents a local variable.
9239 static bool is_local_var_declaration(const declaration_t *declaration)
9241 switch ((storage_class_tag_t) declaration->storage_class) {
9242 case STORAGE_CLASS_AUTO:
9243 case STORAGE_CLASS_REGISTER: {
9244 const type_t *type = skip_typeref(declaration->type);
9245 if (is_type_function(type)) {
9257 * Check if a given declaration represents a variable.
9259 static bool is_var_declaration(const declaration_t *declaration)
9261 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9264 const type_t *type = skip_typeref(declaration->type);
9265 return !is_type_function(type);
9269 * Check if a given expression represents a local variable.
9271 static bool is_local_variable(const expression_t *expression)
9273 if (expression->base.kind != EXPR_REFERENCE) {
9276 const declaration_t *declaration = expression->reference.declaration;
9277 return is_local_var_declaration(declaration);
9281 * Check if a given expression represents a local variable and
9282 * return its declaration then, else return NULL.
9284 declaration_t *expr_is_variable(const expression_t *expression)
9286 if (expression->base.kind != EXPR_REFERENCE) {
9289 declaration_t *declaration = expression->reference.declaration;
9290 if (is_var_declaration(declaration))
9296 * Parse a return statement.
9298 static statement_t *parse_return(void)
9300 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9301 statement->base.source_position = token.source_position;
9305 expression_t *return_value = NULL;
9306 if (token.type != ';') {
9307 return_value = parse_expression();
9310 const type_t *const func_type = current_function->type;
9311 assert(is_type_function(func_type));
9312 type_t *const return_type = skip_typeref(func_type->function.return_type);
9314 if (return_value != NULL) {
9315 type_t *return_value_type = skip_typeref(return_value->base.type);
9317 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
9318 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9319 warningf(&statement->base.source_position,
9320 "'return' with a value, in function returning void");
9321 return_value = NULL;
9323 assign_error_t error = semantic_assign(return_type, return_value);
9324 report_assign_error(error, return_type, return_value, "'return'",
9325 &statement->base.source_position);
9326 return_value = create_implicit_cast(return_value, return_type);
9328 /* check for returning address of a local var */
9329 if (return_value != NULL &&
9330 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9331 const expression_t *expression = return_value->unary.value;
9332 if (is_local_variable(expression)) {
9333 warningf(&statement->base.source_position,
9334 "function returns address of local variable");
9338 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9339 warningf(&statement->base.source_position,
9340 "'return' without value, in function returning non-void");
9343 statement->returns.value = return_value;
9352 * Parse a declaration statement.
9354 static statement_t *parse_declaration_statement(void)
9356 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9358 statement->base.source_position = token.source_position;
9360 declaration_t *before = last_declaration;
9361 parse_declaration(record_declaration);
9363 if (before == NULL) {
9364 statement->declaration.declarations_begin = scope->declarations;
9366 statement->declaration.declarations_begin = before->next;
9368 statement->declaration.declarations_end = last_declaration;
9374 * Parse an expression statement, ie. expr ';'.
9376 static statement_t *parse_expression_statement(void)
9378 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9380 statement->base.source_position = token.source_position;
9381 expression_t *const expr = parse_expression();
9382 statement->expression.expression = expr;
9391 * Parse a microsoft __try { } __finally { } or
9392 * __try{ } __except() { }
9394 static statement_t *parse_ms_try_statment(void)
9396 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9397 statement->base.source_position = token.source_position;
9400 PUSH_PARENT(statement);
9402 ms_try_statement_t *rem = current_try;
9403 current_try = &statement->ms_try;
9404 statement->ms_try.try_statement = parse_compound_statement(false);
9409 if (token.type == T___except) {
9412 add_anchor_token(')');
9413 expression_t *const expr = parse_expression();
9414 type_t * type = skip_typeref(expr->base.type);
9415 if (is_type_integer(type)) {
9416 type = promote_integer(type);
9417 } else if (is_type_valid(type)) {
9418 errorf(&expr->base.source_position,
9419 "__expect expression is not an integer, but '%T'", type);
9420 type = type_error_type;
9422 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9423 rem_anchor_token(')');
9425 statement->ms_try.final_statement = parse_compound_statement(false);
9426 } else if (token.type == T__finally) {
9428 statement->ms_try.final_statement = parse_compound_statement(false);
9430 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9431 return create_invalid_statement();
9435 return create_invalid_statement();
9438 static statement_t *parse_empty_statement(void)
9440 if (warning.empty_statement) {
9441 warningf(HERE, "statement is empty");
9443 statement_t *const statement = create_empty_statement();
9448 static statement_t *parse_local_label_declaration(void) {
9449 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9450 statement->base.source_position = token.source_position;
9454 declaration_t *begin = NULL, *end = NULL;
9457 if (token.type != T_IDENTIFIER) {
9458 parse_error_expected("while parsing local label declaration",
9459 T_IDENTIFIER, NULL);
9462 symbol_t *symbol = token.v.symbol;
9463 declaration_t *declaration = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
9464 if (declaration != NULL) {
9465 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition at %P)",
9466 symbol, &declaration->source_position);
9468 declaration = allocate_declaration_zero();
9469 declaration->namespc = NAMESPACE_LOCAL_LABEL;
9470 declaration->source_position = token.source_position;
9471 declaration->symbol = symbol;
9472 declaration->parent_scope = scope;
9473 declaration->init.statement = NULL;
9476 end->next = declaration;
9479 begin = declaration;
9481 local_label_push(declaration);
9485 if (token.type != ',')
9491 statement->declaration.declarations_begin = begin;
9492 statement->declaration.declarations_end = end;
9497 * Parse a statement.
9498 * There's also parse_statement() which additionally checks for
9499 * "statement has no effect" warnings
9501 static statement_t *intern_parse_statement(void)
9503 statement_t *statement = NULL;
9505 /* declaration or statement */
9506 add_anchor_token(';');
9507 switch (token.type) {
9508 case T_IDENTIFIER: {
9509 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9510 if (la1_type == ':') {
9511 statement = parse_label_statement();
9512 } else if (is_typedef_symbol(token.v.symbol)) {
9513 statement = parse_declaration_statement();
9514 } else switch (la1_type) {
9516 if (get_declaration(token.v.symbol, NAMESPACE_NORMAL) != NULL)
9517 goto expression_statment;
9522 statement = parse_declaration_statement();
9526 expression_statment:
9527 statement = parse_expression_statement();
9533 case T___extension__:
9534 /* This can be a prefix to a declaration or an expression statement.
9535 * We simply eat it now and parse the rest with tail recursion. */
9538 } while (token.type == T___extension__);
9539 statement = parse_statement();
9543 statement = parse_declaration_statement();
9547 statement = parse_local_label_declaration();
9550 case ';': statement = parse_empty_statement(); break;
9551 case '{': statement = parse_compound_statement(false); break;
9552 case T___leave: statement = parse_leave_statement(); break;
9553 case T___try: statement = parse_ms_try_statment(); break;
9554 case T_asm: statement = parse_asm_statement(); break;
9555 case T_break: statement = parse_break(); break;
9556 case T_case: statement = parse_case_statement(); break;
9557 case T_continue: statement = parse_continue(); break;
9558 case T_default: statement = parse_default_statement(); break;
9559 case T_do: statement = parse_do(); break;
9560 case T_for: statement = parse_for(); break;
9561 case T_goto: statement = parse_goto(); break;
9562 case T_if: statement = parse_if (); break;
9563 case T_return: statement = parse_return(); break;
9564 case T_switch: statement = parse_switch(); break;
9565 case T_while: statement = parse_while(); break;
9575 case T_CHARACTER_CONSTANT:
9576 case T_FLOATINGPOINT:
9580 case T_STRING_LITERAL:
9581 case T_WIDE_CHARACTER_CONSTANT:
9582 case T_WIDE_STRING_LITERAL:
9583 case T___FUNCDNAME__:
9585 case T___FUNCTION__:
9586 case T___PRETTY_FUNCTION__:
9587 case T___builtin_alloca:
9588 case T___builtin_classify_type:
9589 case T___builtin_constant_p:
9590 case T___builtin_expect:
9591 case T___builtin_huge_val:
9592 case T___builtin_isgreater:
9593 case T___builtin_isgreaterequal:
9594 case T___builtin_isless:
9595 case T___builtin_islessequal:
9596 case T___builtin_islessgreater:
9597 case T___builtin_isunordered:
9598 case T___builtin_nan:
9599 case T___builtin_nand:
9600 case T___builtin_nanf:
9601 case T___builtin_offsetof:
9602 case T___builtin_prefetch:
9603 case T___builtin_va_arg:
9604 case T___builtin_va_end:
9605 case T___builtin_va_start:
9609 statement = parse_expression_statement();
9613 errorf(HERE, "unexpected token %K while parsing statement", &token);
9614 statement = create_invalid_statement();
9619 rem_anchor_token(';');
9621 assert(statement != NULL
9622 && statement->base.source_position.input_name != NULL);
9628 * parse a statement and emits "statement has no effect" warning if needed
9629 * (This is really a wrapper around intern_parse_statement with check for 1
9630 * single warning. It is needed, because for statement expressions we have
9631 * to avoid the warning on the last statement)
9633 static statement_t *parse_statement(void)
9635 statement_t *statement = intern_parse_statement();
9637 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9638 expression_t *expression = statement->expression.expression;
9639 if (!expression_has_effect(expression)) {
9640 warningf(&expression->base.source_position,
9641 "statement has no effect");
9649 * Parse a compound statement.
9651 static statement_t *parse_compound_statement(bool inside_expression_statement)
9653 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9654 statement->base.source_position = token.source_position;
9656 PUSH_PARENT(statement);
9659 add_anchor_token('}');
9661 int top = environment_top();
9662 int top_local = local_label_top();
9663 scope_t *last_scope = scope;
9664 set_scope(&statement->compound.scope);
9666 statement_t **anchor = &statement->compound.statements;
9667 bool only_decls_so_far = true;
9668 while (token.type != '}' && token.type != T_EOF) {
9669 statement_t *sub_statement = intern_parse_statement();
9670 if (is_invalid_statement(sub_statement)) {
9671 /* an error occurred. if we are at an anchor, return */
9677 if (warning.declaration_after_statement) {
9678 if (sub_statement->kind != STATEMENT_DECLARATION) {
9679 only_decls_so_far = false;
9680 } else if (!only_decls_so_far) {
9681 warningf(&sub_statement->base.source_position,
9682 "ISO C90 forbids mixed declarations and code");
9686 *anchor = sub_statement;
9688 while (sub_statement->base.next != NULL)
9689 sub_statement = sub_statement->base.next;
9691 anchor = &sub_statement->base.next;
9694 if (token.type == '}') {
9697 errorf(&statement->base.source_position,
9698 "end of file while looking for closing '}'");
9701 /* look over all statements again to produce no effect warnings */
9702 if (warning.unused_value) {
9703 statement_t *sub_statement = statement->compound.statements;
9704 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9705 if (sub_statement->kind != STATEMENT_EXPRESSION)
9707 /* don't emit a warning for the last expression in an expression
9708 * statement as it has always an effect */
9709 if (inside_expression_statement && sub_statement->base.next == NULL)
9712 expression_t *expression = sub_statement->expression.expression;
9713 if (!expression_has_effect(expression)) {
9714 warningf(&expression->base.source_position,
9715 "statement has no effect");
9721 rem_anchor_token('}');
9722 assert(scope == &statement->compound.scope);
9723 set_scope(last_scope);
9724 environment_pop_to(top);
9725 local_label_pop_to(top_local);
9732 * Initialize builtin types.
9734 static void initialize_builtin_types(void)
9736 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9737 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9738 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9739 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9740 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9741 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9742 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9743 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9745 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9746 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9747 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9748 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9750 /* const version of wchar_t */
9751 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9752 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9753 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9755 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9759 * Check for unused global static functions and variables
9761 static void check_unused_globals(void)
9763 if (!warning.unused_function && !warning.unused_variable)
9766 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9768 decl->modifiers & DM_UNUSED ||
9769 decl->modifiers & DM_USED ||
9770 decl->storage_class != STORAGE_CLASS_STATIC)
9773 type_t *const type = decl->type;
9775 if (is_type_function(skip_typeref(type))) {
9776 if (!warning.unused_function || decl->is_inline)
9779 s = (decl->init.statement != NULL ? "defined" : "declared");
9781 if (!warning.unused_variable)
9787 warningf(&decl->source_position, "'%#T' %s but not used",
9788 type, decl->symbol, s);
9792 static void parse_global_asm(void)
9797 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9798 statement->base.source_position = token.source_position;
9799 statement->asms.asm_text = parse_string_literals();
9800 statement->base.next = unit->global_asm;
9801 unit->global_asm = statement;
9810 * Parse a translation unit.
9812 static void parse_translation_unit(void)
9816 bool anchor_leak = false;
9817 for (token_type_t i = 0; i != T_LAST_TOKEN; ++i) {
9818 unsigned char count = token_anchor_set[i];
9820 errorf(HERE, "Leaked anchor token %k %d times", i, count);
9828 switch (token.type) {
9831 case T___extension__:
9832 parse_external_declaration();
9843 /* TODO error in strict mode */
9844 warningf(HERE, "stray ';' outside of function");
9849 errorf(HERE, "stray %K outside of function", &token);
9850 if (token.type == '(' || token.type == '{' || token.type == '[')
9851 eat_until_matching_token(token.type);
9861 * @return the translation unit or NULL if errors occurred.
9863 void start_parsing(void)
9865 environment_stack = NEW_ARR_F(stack_entry_t, 0);
9866 label_stack = NEW_ARR_F(stack_entry_t, 0);
9867 local_label_stack = NEW_ARR_F(stack_entry_t, 0);
9868 diagnostic_count = 0;
9872 type_set_output(stderr);
9873 ast_set_output(stderr);
9875 assert(unit == NULL);
9876 unit = allocate_ast_zero(sizeof(unit[0]));
9878 assert(global_scope == NULL);
9879 global_scope = &unit->scope;
9881 assert(scope == NULL);
9882 set_scope(&unit->scope);
9884 initialize_builtin_types();
9887 translation_unit_t *finish_parsing(void)
9889 assert(scope == &unit->scope);
9891 last_declaration = NULL;
9893 assert(global_scope == &unit->scope);
9894 check_unused_globals();
9895 global_scope = NULL;
9897 DEL_ARR_F(environment_stack);
9898 DEL_ARR_F(label_stack);
9899 DEL_ARR_F(local_label_stack);
9901 translation_unit_t *result = unit;
9908 lookahead_bufpos = 0;
9909 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
9912 parse_translation_unit();
9916 * Initialize the parser.
9918 void init_parser(void)
9920 sym_anonymous = symbol_table_insert("<anonymous>");
9923 /* add predefined symbols for extended-decl-modifier */
9924 sym_align = symbol_table_insert("align");
9925 sym_allocate = symbol_table_insert("allocate");
9926 sym_dllimport = symbol_table_insert("dllimport");
9927 sym_dllexport = symbol_table_insert("dllexport");
9928 sym_naked = symbol_table_insert("naked");
9929 sym_noinline = symbol_table_insert("noinline");
9930 sym_noreturn = symbol_table_insert("noreturn");
9931 sym_nothrow = symbol_table_insert("nothrow");
9932 sym_novtable = symbol_table_insert("novtable");
9933 sym_property = symbol_table_insert("property");
9934 sym_get = symbol_table_insert("get");
9935 sym_put = symbol_table_insert("put");
9936 sym_selectany = symbol_table_insert("selectany");
9937 sym_thread = symbol_table_insert("thread");
9938 sym_uuid = symbol_table_insert("uuid");
9939 sym_deprecated = symbol_table_insert("deprecated");
9940 sym_restrict = symbol_table_insert("restrict");
9941 sym_noalias = symbol_table_insert("noalias");
9943 memset(token_anchor_set, 0, sizeof(token_anchor_set));
9945 init_expression_parsers();
9946 obstack_init(&temp_obst);
9948 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
9949 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
9953 * Terminate the parser.
9955 void exit_parser(void)
9957 obstack_free(&temp_obst, NULL);