2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 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 "adt/strutil.h"
29 #include "diagnostic.h"
30 #include "format_check.h"
31 #include "preprocessor.h"
36 #include "type_hash.h"
39 #include "attribute_t.h"
40 #include "lang_features.h"
44 #include "adt/bitfiddle.h"
45 #include "adt/error.h"
46 #include "adt/array.h"
48 //#define PRINT_TOKENS
49 #define MAX_LOOKAHEAD 1
54 entity_namespace_t namespc;
57 typedef struct declaration_specifiers_t declaration_specifiers_t;
58 struct declaration_specifiers_t {
59 source_position_t source_position;
60 storage_class_t storage_class;
61 unsigned char alignment; /**< Alignment, 0 if not set. */
63 bool thread_local : 1; /**< GCC __thread */
64 attribute_t *attributes; /**< list of attributes */
69 * An environment for parsing initializers (and compound literals).
71 typedef struct parse_initializer_env_t {
72 type_t *type; /**< the type of the initializer. In case of an
73 array type with unspecified size this gets
74 adjusted to the actual size. */
75 entity_t *entity; /**< the variable that is initialized if any */
76 bool must_be_constant;
77 } parse_initializer_env_t;
79 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
81 /** The current token. */
83 /** The lookahead ring-buffer. */
84 static token_t lookahead_buffer[MAX_LOOKAHEAD];
85 /** Position of the next token in the lookahead buffer. */
86 static size_t lookahead_bufpos;
87 static stack_entry_t *environment_stack = NULL;
88 static stack_entry_t *label_stack = NULL;
89 static scope_t *file_scope = NULL;
90 static scope_t *current_scope = NULL;
91 /** Point to the current function declaration if inside a function. */
92 static function_t *current_function = NULL;
93 static entity_t *current_entity = NULL;
94 static switch_statement_t *current_switch = NULL;
95 static statement_t *current_loop = NULL;
96 static statement_t *current_parent = NULL;
97 static ms_try_statement_t *current_try = NULL;
98 static linkage_kind_t current_linkage;
99 static goto_statement_t *goto_first = NULL;
100 static goto_statement_t **goto_anchor = NULL;
101 static label_statement_t *label_first = NULL;
102 static label_statement_t **label_anchor = NULL;
103 /** current translation unit. */
104 static translation_unit_t *unit = NULL;
105 /** true if we are in an __extension__ context. */
106 static bool in_gcc_extension = false;
107 static struct obstack temp_obst;
108 static entity_t *anonymous_entity;
109 static declaration_t **incomplete_arrays;
110 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
113 #define PUSH_CURRENT_ENTITY(entity) \
114 entity_t *const new_current_entity = (entity); \
115 entity_t *const old_current_entity = current_entity; \
116 ((void)(current_entity = new_current_entity))
117 #define POP_CURRENT_ENTITY() (assert(current_entity == new_current_entity), (void)(current_entity = old_current_entity))
119 #define PUSH_PARENT(stmt) \
120 statement_t *const new_parent = (stmt); \
121 statement_t *const old_parent = current_parent; \
122 ((void)(current_parent = new_parent))
123 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
125 #define PUSH_SCOPE(scope) \
126 size_t const top = environment_top(); \
127 scope_t *const new_scope = (scope); \
128 scope_t *const old_scope = (new_scope ? scope_push(new_scope) : NULL)
129 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
130 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
132 #define PUSH_EXTENSION() \
134 bool const old_gcc_extension = in_gcc_extension; \
135 while (next_if(T___extension__)) { \
136 in_gcc_extension = true; \
139 #define POP_EXTENSION() \
140 ((void)(in_gcc_extension = old_gcc_extension))
142 /** The token anchor set */
143 static unsigned short token_anchor_set[T_LAST_TOKEN];
145 /** The current source position. */
146 #define HERE (&token.base.source_position)
148 /** true if we are in GCC mode. */
149 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
151 static statement_t *parse_compound_statement(bool inside_expression_statement);
152 static statement_t *parse_statement(void);
154 static expression_t *parse_subexpression(precedence_t);
155 static expression_t *parse_expression(void);
156 static type_t *parse_typename(void);
157 static void parse_externals(void);
158 static void parse_external(void);
160 static void parse_compound_type_entries(compound_t *compound_declaration);
162 static void check_call_argument(type_t *expected_type,
163 call_argument_t *argument, unsigned pos);
165 typedef enum declarator_flags_t {
167 DECL_MAY_BE_ABSTRACT = 1U << 0,
168 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
169 DECL_IS_PARAMETER = 1U << 2
170 } declarator_flags_t;
172 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
173 declarator_flags_t flags);
175 static void semantic_comparison(binary_expression_t *expression);
177 #define STORAGE_CLASSES \
178 STORAGE_CLASSES_NO_EXTERN \
181 #define STORAGE_CLASSES_NO_EXTERN \
188 #define TYPE_QUALIFIERS \
193 case T__forceinline: \
194 case T___attribute__:
196 #define COMPLEX_SPECIFIERS \
198 #define IMAGINARY_SPECIFIERS \
201 #define TYPE_SPECIFIERS \
203 case T___builtin_va_list: \
228 #define DECLARATION_START \
233 #define DECLARATION_START_NO_EXTERN \
234 STORAGE_CLASSES_NO_EXTERN \
238 #define EXPRESSION_START \
247 case T_CHARACTER_CONSTANT: \
251 case T_STRING_LITERAL: \
252 case T___FUNCDNAME__: \
253 case T___FUNCSIG__: \
254 case T___PRETTY_FUNCTION__: \
255 case T___alignof__: \
256 case T___builtin_classify_type: \
257 case T___builtin_constant_p: \
258 case T___builtin_isgreater: \
259 case T___builtin_isgreaterequal: \
260 case T___builtin_isless: \
261 case T___builtin_islessequal: \
262 case T___builtin_islessgreater: \
263 case T___builtin_isunordered: \
264 case T___builtin_offsetof: \
265 case T___builtin_va_arg: \
266 case T___builtin_va_copy: \
267 case T___builtin_va_start: \
278 * Returns the size of a statement node.
280 * @param kind the statement kind
282 static size_t get_statement_struct_size(statement_kind_t kind)
284 static const size_t sizes[] = {
285 [STATEMENT_ERROR] = sizeof(statement_base_t),
286 [STATEMENT_EMPTY] = sizeof(statement_base_t),
287 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
288 [STATEMENT_RETURN] = sizeof(return_statement_t),
289 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
290 [STATEMENT_IF] = sizeof(if_statement_t),
291 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
292 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
293 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
294 [STATEMENT_BREAK] = sizeof(statement_base_t),
295 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
296 [STATEMENT_GOTO] = sizeof(goto_statement_t),
297 [STATEMENT_LABEL] = sizeof(label_statement_t),
298 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
299 [STATEMENT_WHILE] = sizeof(while_statement_t),
300 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
301 [STATEMENT_FOR] = sizeof(for_statement_t),
302 [STATEMENT_ASM] = sizeof(asm_statement_t),
303 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
304 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
306 assert((size_t)kind < lengthof(sizes));
307 assert(sizes[kind] != 0);
312 * Returns the size of an expression node.
314 * @param kind the expression kind
316 static size_t get_expression_struct_size(expression_kind_t kind)
318 static const size_t sizes[] = {
319 [EXPR_ERROR] = sizeof(expression_base_t),
320 [EXPR_REFERENCE] = sizeof(reference_expression_t),
321 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
322 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
323 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
324 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
325 [EXPR_LITERAL_CHARACTER] = sizeof(string_literal_expression_t),
326 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
327 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
328 [EXPR_CALL] = sizeof(call_expression_t),
329 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
330 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
331 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
332 [EXPR_SELECT] = sizeof(select_expression_t),
333 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
334 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
335 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
336 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
337 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
338 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
339 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
340 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
341 [EXPR_VA_START] = sizeof(va_start_expression_t),
342 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
343 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
344 [EXPR_STATEMENT] = sizeof(statement_expression_t),
345 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
347 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
348 return sizes[EXPR_UNARY_FIRST];
350 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
351 return sizes[EXPR_BINARY_FIRST];
353 assert((size_t)kind < lengthof(sizes));
354 assert(sizes[kind] != 0);
359 * Allocate a statement node of given kind and initialize all
360 * fields with zero. Sets its source position to the position
361 * of the current token.
363 static statement_t *allocate_statement_zero(statement_kind_t kind)
365 size_t size = get_statement_struct_size(kind);
366 statement_t *res = allocate_ast_zero(size);
368 res->base.kind = kind;
369 res->base.parent = current_parent;
370 res->base.source_position = *HERE;
375 * Allocate an expression node of given kind and initialize all
378 * @param kind the kind of the expression to allocate
380 static expression_t *allocate_expression_zero(expression_kind_t kind)
382 size_t size = get_expression_struct_size(kind);
383 expression_t *res = allocate_ast_zero(size);
385 res->base.kind = kind;
386 res->base.type = type_error_type;
387 res->base.source_position = *HERE;
392 * Creates a new invalid expression at the source position
393 * of the current token.
395 static expression_t *create_error_expression(void)
397 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
398 expression->base.type = type_error_type;
403 * Creates a new invalid statement.
405 static statement_t *create_error_statement(void)
407 return allocate_statement_zero(STATEMENT_ERROR);
411 * Allocate a new empty statement.
413 static statement_t *create_empty_statement(void)
415 return allocate_statement_zero(STATEMENT_EMPTY);
419 * Returns the size of an initializer node.
421 * @param kind the initializer kind
423 static size_t get_initializer_size(initializer_kind_t kind)
425 static const size_t sizes[] = {
426 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
427 [INITIALIZER_STRING] = sizeof(initializer_value_t),
428 [INITIALIZER_LIST] = sizeof(initializer_list_t),
429 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
431 assert((size_t)kind < lengthof(sizes));
432 assert(sizes[kind] != 0);
437 * Allocate an initializer node of given kind and initialize all
440 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
442 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
449 * Returns the index of the top element of the environment stack.
451 static size_t environment_top(void)
453 return ARR_LEN(environment_stack);
457 * Returns the index of the top element of the global label stack.
459 static size_t label_top(void)
461 return ARR_LEN(label_stack);
465 * Return the next token.
467 static inline void next_token(void)
469 token = lookahead_buffer[lookahead_bufpos];
470 lookahead_buffer[lookahead_bufpos] = pp_token;
471 next_preprocessing_token();
473 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
476 print_token(stderr, &token);
477 fprintf(stderr, "\n");
481 static inline void eat(token_kind_t const kind)
483 assert(token.kind == kind);
488 static inline bool next_if(token_kind_t const kind)
490 if (token.kind == kind) {
499 * Return the next token with a given lookahead.
501 static inline const token_t *look_ahead(size_t num)
503 assert(0 < num && num <= MAX_LOOKAHEAD);
504 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
505 return &lookahead_buffer[pos];
509 * Adds a token type to the token type anchor set (a multi-set).
511 static void add_anchor_token(token_kind_t const token_kind)
513 assert(token_kind < T_LAST_TOKEN);
514 ++token_anchor_set[token_kind];
518 * Remove a token type from the token type anchor set (a multi-set).
520 static void rem_anchor_token(token_kind_t const token_kind)
522 assert(token_kind < T_LAST_TOKEN);
523 assert(token_anchor_set[token_kind] != 0);
524 --token_anchor_set[token_kind];
528 * Eat tokens until a matching token type is found.
530 static void eat_until_matching_token(token_kind_t const type)
532 token_kind_t end_token;
534 case '(': end_token = ')'; break;
535 case '{': end_token = '}'; break;
536 case '[': end_token = ']'; break;
537 default: end_token = type; break;
540 unsigned parenthesis_count = 0;
541 unsigned brace_count = 0;
542 unsigned bracket_count = 0;
543 while (token.kind != end_token ||
544 parenthesis_count != 0 ||
546 bracket_count != 0) {
547 switch (token.kind) {
549 case '(': ++parenthesis_count; break;
550 case '{': ++brace_count; break;
551 case '[': ++bracket_count; break;
554 if (parenthesis_count > 0)
564 if (bracket_count > 0)
567 if (token.kind == end_token &&
568 parenthesis_count == 0 &&
582 * Eat input tokens until an anchor is found.
584 static void eat_until_anchor(void)
586 while (token_anchor_set[token.kind] == 0) {
587 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
588 eat_until_matching_token(token.kind);
594 * Eat a whole block from input tokens.
596 static void eat_block(void)
598 eat_until_matching_token('{');
603 * Report a parse error because an expected token was not found.
606 #if defined __GNUC__ && __GNUC__ >= 4
607 __attribute__((sentinel))
609 void parse_error_expected(const char *message, ...)
611 if (message != NULL) {
612 errorf(HERE, "%s", message);
615 va_start(ap, message);
616 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
621 * Report an incompatible type.
623 static void type_error_incompatible(const char *msg,
624 const source_position_t *source_position, type_t *type1, type_t *type2)
626 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
630 static bool skip_till(token_kind_t const expected, char const *const context)
632 if (UNLIKELY(token.kind != expected)) {
633 parse_error_expected(context, expected, NULL);
634 add_anchor_token(expected);
636 rem_anchor_token(expected);
637 if (token.kind != expected)
644 * Expect the current token is the expected token.
645 * If not, generate an error and skip until the next anchor.
647 static void expect(token_kind_t const expected)
649 if (skip_till(expected, NULL))
653 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
655 if (!skip_till(T_IDENTIFIER, context))
657 symbol_t *const sym = token.base.symbol;
665 * Push a given scope on the scope stack and make it the
668 static scope_t *scope_push(scope_t *new_scope)
670 if (current_scope != NULL) {
671 new_scope->depth = current_scope->depth + 1;
674 scope_t *old_scope = current_scope;
675 current_scope = new_scope;
680 * Pop the current scope from the scope stack.
682 static void scope_pop(scope_t *old_scope)
684 current_scope = old_scope;
688 * Search an entity by its symbol in a given namespace.
690 static entity_t *get_entity(const symbol_t *const symbol,
691 namespace_tag_t namespc)
693 entity_t *entity = symbol->entity;
694 for (; entity != NULL; entity = entity->base.symbol_next) {
695 if ((namespace_tag_t)entity->base.namespc == namespc)
702 /* §6.2.3:1 24) There is only one name space for tags even though three are
704 static entity_t *get_tag(symbol_t const *const symbol,
705 entity_kind_tag_t const kind)
707 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
708 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
710 "'%Y' defined as wrong kind of tag (previous definition %P)",
711 symbol, &entity->base.source_position);
718 * pushs an entity on the environment stack and links the corresponding symbol
721 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
723 symbol_t *symbol = entity->base.symbol;
724 entity_namespace_t namespc = entity->base.namespc;
725 assert(namespc != 0);
727 /* replace/add entity into entity list of the symbol */
730 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
735 /* replace an entry? */
736 if (iter->base.namespc == namespc) {
737 entity->base.symbol_next = iter->base.symbol_next;
743 /* remember old declaration */
745 entry.symbol = symbol;
746 entry.old_entity = iter;
747 entry.namespc = namespc;
748 ARR_APP1(stack_entry_t, *stack_ptr, entry);
752 * Push an entity on the environment stack.
754 static void environment_push(entity_t *entity)
756 assert(entity->base.source_position.input_name != NULL);
757 assert(entity->base.parent_scope != NULL);
758 stack_push(&environment_stack, entity);
762 * Push a declaration on the global label stack.
764 * @param declaration the declaration
766 static void label_push(entity_t *label)
768 /* we abuse the parameters scope as parent for the labels */
769 label->base.parent_scope = ¤t_function->parameters;
770 stack_push(&label_stack, label);
774 * pops symbols from the environment stack until @p new_top is the top element
776 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
778 stack_entry_t *stack = *stack_ptr;
779 size_t top = ARR_LEN(stack);
782 assert(new_top <= top);
786 for (i = top; i > new_top; --i) {
787 stack_entry_t *entry = &stack[i - 1];
789 entity_t *old_entity = entry->old_entity;
790 symbol_t *symbol = entry->symbol;
791 entity_namespace_t namespc = entry->namespc;
793 /* replace with old_entity/remove */
796 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
798 assert(iter != NULL);
799 /* replace an entry? */
800 if (iter->base.namespc == namespc)
804 /* restore definition from outer scopes (if there was one) */
805 if (old_entity != NULL) {
806 old_entity->base.symbol_next = iter->base.symbol_next;
807 *anchor = old_entity;
809 /* remove entry from list */
810 *anchor = iter->base.symbol_next;
814 ARR_SHRINKLEN(*stack_ptr, new_top);
818 * Pop all entries from the environment stack until the new_top
821 * @param new_top the new stack top
823 static void environment_pop_to(size_t new_top)
825 stack_pop_to(&environment_stack, new_top);
829 * Pop all entries from the global label stack until the new_top
832 * @param new_top the new stack top
834 static void label_pop_to(size_t new_top)
836 stack_pop_to(&label_stack, new_top);
839 static atomic_type_kind_t get_akind(const type_t *type)
841 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
842 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
843 return type->atomic.akind;
847 * §6.3.1.1:2 Do integer promotion for a given type.
849 * @param type the type to promote
850 * @return the promoted type
852 static type_t *promote_integer(type_t *type)
854 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
861 * Check if a given expression represents a null pointer constant.
863 * @param expression the expression to check
865 static bool is_null_pointer_constant(const expression_t *expression)
867 /* skip void* cast */
868 if (expression->kind == EXPR_UNARY_CAST) {
869 type_t *const type = skip_typeref(expression->base.type);
870 if (types_compatible(type, type_void_ptr))
871 expression = expression->unary.value;
874 type_t *const type = skip_typeref(expression->base.type);
875 if (!is_type_integer(type))
877 switch (is_constant_expression(expression)) {
878 case EXPR_CLASS_ERROR: return true;
879 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
880 default: return false;
885 * Create an implicit cast expression.
887 * @param expression the expression to cast
888 * @param dest_type the destination type
890 static expression_t *create_implicit_cast(expression_t *expression,
893 type_t *const source_type = expression->base.type;
895 if (source_type == dest_type)
898 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
899 cast->unary.value = expression;
900 cast->base.type = dest_type;
901 cast->base.implicit = true;
906 typedef enum assign_error_t {
908 ASSIGN_ERROR_INCOMPATIBLE,
909 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
910 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
911 ASSIGN_WARNING_POINTER_FROM_INT,
912 ASSIGN_WARNING_INT_FROM_POINTER
915 static void report_assign_error(assign_error_t error, type_t *orig_type_left, expression_t const *const right, char const *const context, source_position_t const *const pos)
917 type_t *const orig_type_right = right->base.type;
918 type_t *const type_left = skip_typeref(orig_type_left);
919 type_t *const type_right = skip_typeref(orig_type_right);
924 case ASSIGN_ERROR_INCOMPATIBLE:
925 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
928 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
929 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
930 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
932 /* the left type has all qualifiers from the right type */
933 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
934 warningf(WARN_OTHER, pos, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type", orig_type_left, context, orig_type_right, missing_qualifiers);
938 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
939 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
942 case ASSIGN_WARNING_POINTER_FROM_INT:
943 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
946 case ASSIGN_WARNING_INT_FROM_POINTER:
947 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
951 panic("invalid error value");
955 /** Implements the rules from §6.5.16.1 */
956 static assign_error_t semantic_assign(type_t *orig_type_left,
957 const expression_t *const right)
959 type_t *const orig_type_right = right->base.type;
960 type_t *const type_left = skip_typeref(orig_type_left);
961 type_t *const type_right = skip_typeref(orig_type_right);
963 if (is_type_pointer(type_left)) {
964 if (is_null_pointer_constant(right)) {
965 return ASSIGN_SUCCESS;
966 } else if (is_type_pointer(type_right)) {
967 type_t *points_to_left
968 = skip_typeref(type_left->pointer.points_to);
969 type_t *points_to_right
970 = skip_typeref(type_right->pointer.points_to);
971 assign_error_t res = ASSIGN_SUCCESS;
973 /* the left type has all qualifiers from the right type */
974 unsigned missing_qualifiers
975 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
976 if (missing_qualifiers != 0) {
977 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
980 points_to_left = get_unqualified_type(points_to_left);
981 points_to_right = get_unqualified_type(points_to_right);
983 if (is_type_void(points_to_left))
986 if (is_type_void(points_to_right)) {
987 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
988 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
991 if (!types_compatible(points_to_left, points_to_right)) {
992 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
996 } else if (is_type_integer(type_right)) {
997 return ASSIGN_WARNING_POINTER_FROM_INT;
999 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1000 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1001 && is_type_pointer(type_right))) {
1002 return ASSIGN_SUCCESS;
1003 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1004 type_t *const unqual_type_left = get_unqualified_type(type_left);
1005 type_t *const unqual_type_right = get_unqualified_type(type_right);
1006 if (types_compatible(unqual_type_left, unqual_type_right)) {
1007 return ASSIGN_SUCCESS;
1009 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1010 return ASSIGN_WARNING_INT_FROM_POINTER;
1013 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1014 return ASSIGN_SUCCESS;
1016 return ASSIGN_ERROR_INCOMPATIBLE;
1019 static expression_t *parse_constant_expression(void)
1021 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1023 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1024 errorf(&result->base.source_position,
1025 "expression '%E' is not constant", result);
1031 static expression_t *parse_assignment_expression(void)
1033 return parse_subexpression(PREC_ASSIGNMENT);
1036 static void append_string(string_t const *const s)
1038 /* FIXME Using the ast_obstack is a hack. Using the symbol_obstack is not
1039 * possible, because other tokens are grown there alongside. */
1040 obstack_grow(&ast_obstack, s->begin, s->size);
1043 static string_t finish_string(string_encoding_t const enc)
1045 obstack_1grow(&ast_obstack, '\0');
1046 size_t const size = obstack_object_size(&ast_obstack) - 1;
1047 char const *const string = obstack_finish(&ast_obstack);
1048 return (string_t){ string, size, enc };
1051 static string_t concat_string_literals(void)
1053 assert(token.kind == T_STRING_LITERAL);
1056 if (look_ahead(1)->kind == T_STRING_LITERAL) {
1057 append_string(&token.literal.string);
1058 eat(T_STRING_LITERAL);
1059 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects string constant concatenation");
1060 string_encoding_t enc = token.literal.string.encoding;
1062 if (token.literal.string.encoding != STRING_ENCODING_CHAR) {
1063 enc = token.literal.string.encoding;
1065 append_string(&token.literal.string);
1066 eat(T_STRING_LITERAL);
1067 } while (token.kind == T_STRING_LITERAL);
1068 result = finish_string(enc);
1070 result = token.literal.string;
1071 eat(T_STRING_LITERAL);
1077 static string_t parse_string_literals(char const *const context)
1079 if (!skip_till(T_STRING_LITERAL, context))
1080 return (string_t){ "", 0, STRING_ENCODING_CHAR };
1082 source_position_t const pos = *HERE;
1083 string_t const res = concat_string_literals();
1085 if (res.encoding != STRING_ENCODING_CHAR) {
1086 errorf(&pos, "expected plain string literal, got wide string literal");
1092 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1094 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1095 attribute->kind = kind;
1096 attribute->source_position = *HERE;
1101 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1104 * __attribute__ ( ( attribute-list ) )
1108 * attribute_list , attrib
1113 * any-word ( identifier )
1114 * any-word ( identifier , nonempty-expr-list )
1115 * any-word ( expr-list )
1117 * where the "identifier" must not be declared as a type, and
1118 * "any-word" may be any identifier (including one declared as a
1119 * type), a reserved word storage class specifier, type specifier or
1120 * type qualifier. ??? This still leaves out most reserved keywords
1121 * (following the old parser), shouldn't we include them, and why not
1122 * allow identifiers declared as types to start the arguments?
1124 * Matze: this all looks confusing and little systematic, so we're even less
1125 * strict and parse any list of things which are identifiers or
1126 * (assignment-)expressions.
1128 static attribute_argument_t *parse_attribute_arguments(void)
1130 attribute_argument_t *first = NULL;
1131 attribute_argument_t **anchor = &first;
1132 if (token.kind != ')') do {
1133 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1135 /* is it an identifier */
1136 if (token.kind == T_IDENTIFIER
1137 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1138 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1139 argument->v.symbol = token.base.symbol;
1142 /* must be an expression */
1143 expression_t *expression = parse_assignment_expression();
1145 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1146 argument->v.expression = expression;
1149 /* append argument */
1151 anchor = &argument->next;
1152 } while (next_if(','));
1157 static attribute_t *parse_attribute_asm(void)
1159 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1162 attribute->a.arguments = parse_attribute_arguments();
1166 static attribute_t *parse_attribute_gnu_single(void)
1168 /* parse "any-word" */
1169 symbol_t *const symbol = token.base.symbol;
1170 if (symbol == NULL) {
1171 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1175 attribute_kind_t kind;
1176 char const *const name = symbol->string;
1177 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1178 if (kind > ATTRIBUTE_GNU_LAST) {
1179 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1180 /* TODO: we should still save the attribute in the list... */
1181 kind = ATTRIBUTE_UNKNOWN;
1185 const char *attribute_name = get_attribute_name(kind);
1186 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1190 attribute_t *attribute = allocate_attribute_zero(kind);
1193 /* parse arguments */
1195 attribute->a.arguments = parse_attribute_arguments();
1200 static attribute_t *parse_attribute_gnu(void)
1202 attribute_t *first = NULL;
1203 attribute_t **anchor = &first;
1205 eat(T___attribute__);
1206 add_anchor_token(')');
1207 add_anchor_token(',');
1211 if (token.kind != ')') do {
1212 attribute_t *attribute = parse_attribute_gnu_single();
1214 *anchor = attribute;
1215 anchor = &attribute->next;
1217 } while (next_if(','));
1218 rem_anchor_token(',');
1219 rem_anchor_token(')');
1226 /** Parse attributes. */
1227 static attribute_t *parse_attributes(attribute_t *first)
1229 attribute_t **anchor = &first;
1231 while (*anchor != NULL)
1232 anchor = &(*anchor)->next;
1234 attribute_t *attribute;
1235 switch (token.kind) {
1236 case T___attribute__:
1237 attribute = parse_attribute_gnu();
1238 if (attribute == NULL)
1243 attribute = parse_attribute_asm();
1247 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1252 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1256 case T__forceinline:
1257 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1258 eat(T__forceinline);
1262 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1267 /* TODO record modifier */
1268 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1269 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1277 *anchor = attribute;
1278 anchor = &attribute->next;
1282 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1284 static entity_t *determine_lhs_ent(expression_t *const expr,
1287 switch (expr->kind) {
1288 case EXPR_REFERENCE: {
1289 entity_t *const entity = expr->reference.entity;
1290 /* we should only find variables as lvalues... */
1291 if (entity->base.kind != ENTITY_VARIABLE
1292 && entity->base.kind != ENTITY_PARAMETER)
1298 case EXPR_ARRAY_ACCESS: {
1299 expression_t *const ref = expr->array_access.array_ref;
1300 entity_t * ent = NULL;
1301 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1302 ent = determine_lhs_ent(ref, lhs_ent);
1305 mark_vars_read(ref, lhs_ent);
1307 mark_vars_read(expr->array_access.index, lhs_ent);
1312 mark_vars_read(expr->select.compound, lhs_ent);
1313 if (is_type_compound(skip_typeref(expr->base.type)))
1314 return determine_lhs_ent(expr->select.compound, lhs_ent);
1318 case EXPR_UNARY_DEREFERENCE: {
1319 expression_t *const val = expr->unary.value;
1320 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1322 return determine_lhs_ent(val->unary.value, lhs_ent);
1324 mark_vars_read(val, NULL);
1330 mark_vars_read(expr, NULL);
1335 #define ENT_ANY ((entity_t*)-1)
1338 * Mark declarations, which are read. This is used to detect variables, which
1342 * x is not marked as "read", because it is only read to calculate its own new
1346 * x and y are not detected as "not read", because multiple variables are
1349 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1351 switch (expr->kind) {
1352 case EXPR_REFERENCE: {
1353 entity_t *const entity = expr->reference.entity;
1354 if (entity->kind != ENTITY_VARIABLE
1355 && entity->kind != ENTITY_PARAMETER)
1358 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1359 entity->variable.read = true;
1365 // TODO respect pure/const
1366 mark_vars_read(expr->call.function, NULL);
1367 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1368 mark_vars_read(arg->expression, NULL);
1372 case EXPR_CONDITIONAL:
1373 // TODO lhs_decl should depend on whether true/false have an effect
1374 mark_vars_read(expr->conditional.condition, NULL);
1375 if (expr->conditional.true_expression != NULL)
1376 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1377 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1381 if (lhs_ent == ENT_ANY
1382 && !is_type_compound(skip_typeref(expr->base.type)))
1384 mark_vars_read(expr->select.compound, lhs_ent);
1387 case EXPR_ARRAY_ACCESS: {
1388 mark_vars_read(expr->array_access.index, lhs_ent);
1389 expression_t *const ref = expr->array_access.array_ref;
1390 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1391 if (lhs_ent == ENT_ANY)
1394 mark_vars_read(ref, lhs_ent);
1399 mark_vars_read(expr->va_arge.ap, lhs_ent);
1403 mark_vars_read(expr->va_copye.src, lhs_ent);
1406 case EXPR_UNARY_CAST:
1407 /* Special case: Use void cast to mark a variable as "read" */
1408 if (is_type_void(skip_typeref(expr->base.type)))
1413 case EXPR_UNARY_THROW:
1414 if (expr->unary.value == NULL)
1417 case EXPR_UNARY_DEREFERENCE:
1418 case EXPR_UNARY_DELETE:
1419 case EXPR_UNARY_DELETE_ARRAY:
1420 if (lhs_ent == ENT_ANY)
1424 case EXPR_UNARY_NEGATE:
1425 case EXPR_UNARY_PLUS:
1426 case EXPR_UNARY_BITWISE_NEGATE:
1427 case EXPR_UNARY_NOT:
1428 case EXPR_UNARY_TAKE_ADDRESS:
1429 case EXPR_UNARY_POSTFIX_INCREMENT:
1430 case EXPR_UNARY_POSTFIX_DECREMENT:
1431 case EXPR_UNARY_PREFIX_INCREMENT:
1432 case EXPR_UNARY_PREFIX_DECREMENT:
1433 case EXPR_UNARY_ASSUME:
1435 mark_vars_read(expr->unary.value, lhs_ent);
1438 case EXPR_BINARY_ADD:
1439 case EXPR_BINARY_SUB:
1440 case EXPR_BINARY_MUL:
1441 case EXPR_BINARY_DIV:
1442 case EXPR_BINARY_MOD:
1443 case EXPR_BINARY_EQUAL:
1444 case EXPR_BINARY_NOTEQUAL:
1445 case EXPR_BINARY_LESS:
1446 case EXPR_BINARY_LESSEQUAL:
1447 case EXPR_BINARY_GREATER:
1448 case EXPR_BINARY_GREATEREQUAL:
1449 case EXPR_BINARY_BITWISE_AND:
1450 case EXPR_BINARY_BITWISE_OR:
1451 case EXPR_BINARY_BITWISE_XOR:
1452 case EXPR_BINARY_LOGICAL_AND:
1453 case EXPR_BINARY_LOGICAL_OR:
1454 case EXPR_BINARY_SHIFTLEFT:
1455 case EXPR_BINARY_SHIFTRIGHT:
1456 case EXPR_BINARY_COMMA:
1457 case EXPR_BINARY_ISGREATER:
1458 case EXPR_BINARY_ISGREATEREQUAL:
1459 case EXPR_BINARY_ISLESS:
1460 case EXPR_BINARY_ISLESSEQUAL:
1461 case EXPR_BINARY_ISLESSGREATER:
1462 case EXPR_BINARY_ISUNORDERED:
1463 mark_vars_read(expr->binary.left, lhs_ent);
1464 mark_vars_read(expr->binary.right, lhs_ent);
1467 case EXPR_BINARY_ASSIGN:
1468 case EXPR_BINARY_MUL_ASSIGN:
1469 case EXPR_BINARY_DIV_ASSIGN:
1470 case EXPR_BINARY_MOD_ASSIGN:
1471 case EXPR_BINARY_ADD_ASSIGN:
1472 case EXPR_BINARY_SUB_ASSIGN:
1473 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1474 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1475 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1476 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1477 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1478 if (lhs_ent == ENT_ANY)
1480 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1481 mark_vars_read(expr->binary.right, lhs_ent);
1486 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1489 case EXPR_LITERAL_CASES:
1490 case EXPR_LITERAL_CHARACTER:
1492 case EXPR_STRING_LITERAL:
1493 case EXPR_COMPOUND_LITERAL: // TODO init?
1495 case EXPR_CLASSIFY_TYPE:
1498 case EXPR_BUILTIN_CONSTANT_P:
1499 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1501 case EXPR_STATEMENT: // TODO
1502 case EXPR_LABEL_ADDRESS:
1503 case EXPR_ENUM_CONSTANT:
1507 panic("unhandled expression");
1510 static designator_t *parse_designation(void)
1512 designator_t *result = NULL;
1513 designator_t **anchor = &result;
1516 designator_t *designator;
1517 switch (token.kind) {
1519 designator = allocate_ast_zero(sizeof(designator[0]));
1520 designator->source_position = *HERE;
1522 add_anchor_token(']');
1523 designator->array_index = parse_constant_expression();
1524 rem_anchor_token(']');
1528 designator = allocate_ast_zero(sizeof(designator[0]));
1529 designator->source_position = *HERE;
1531 designator->symbol = expect_identifier("while parsing designator", NULL);
1532 if (!designator->symbol)
1540 assert(designator != NULL);
1541 *anchor = designator;
1542 anchor = &designator->next;
1547 * Build an initializer from a given expression.
1549 static initializer_t *initializer_from_expression(type_t *orig_type,
1550 expression_t *expression)
1552 /* TODO check that expression is a constant expression */
1554 type_t *const type = skip_typeref(orig_type);
1556 /* §6.7.8.14/15 char array may be initialized by string literals */
1557 if (expression->kind == EXPR_STRING_LITERAL && is_type_array(type)) {
1558 array_type_t *const array_type = &type->array;
1559 type_t *const element_type = skip_typeref(array_type->element_type);
1560 switch (expression->string_literal.value.encoding) {
1561 case STRING_ENCODING_CHAR: {
1562 if (is_type_atomic(element_type, ATOMIC_TYPE_CHAR) ||
1563 is_type_atomic(element_type, ATOMIC_TYPE_SCHAR) ||
1564 is_type_atomic(element_type, ATOMIC_TYPE_UCHAR)) {
1565 goto make_string_init;
1570 case STRING_ENCODING_WIDE: {
1571 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1572 if (get_unqualified_type(element_type) == bare_wchar_type) {
1574 initializer_t *const init = allocate_initializer_zero(INITIALIZER_STRING);
1575 init->value.value = expression;
1583 assign_error_t error = semantic_assign(type, expression);
1584 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1586 report_assign_error(error, type, expression, "initializer",
1587 &expression->base.source_position);
1589 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1590 result->value.value = create_implicit_cast(expression, type);
1596 * Parses an scalar initializer.
1598 * §6.7.8.11; eat {} without warning
1600 static initializer_t *parse_scalar_initializer(type_t *type,
1601 bool must_be_constant)
1603 /* there might be extra {} hierarchies */
1605 if (token.kind == '{') {
1606 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1610 } while (token.kind == '{');
1613 expression_t *expression = parse_assignment_expression();
1614 mark_vars_read(expression, NULL);
1615 if (must_be_constant && !is_linker_constant(expression)) {
1616 errorf(&expression->base.source_position,
1617 "initialisation expression '%E' is not constant",
1621 initializer_t *initializer = initializer_from_expression(type, expression);
1623 if (initializer == NULL) {
1624 errorf(&expression->base.source_position,
1625 "expression '%E' (type '%T') doesn't match expected type '%T'",
1626 expression, expression->base.type, type);
1631 bool additional_warning_displayed = false;
1632 while (braces > 0) {
1634 if (token.kind != '}') {
1635 if (!additional_warning_displayed) {
1636 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1637 additional_warning_displayed = true;
1648 * An entry in the type path.
1650 typedef struct type_path_entry_t type_path_entry_t;
1651 struct type_path_entry_t {
1652 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1654 size_t index; /**< For array types: the current index. */
1655 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1660 * A type path expression a position inside compound or array types.
1662 typedef struct type_path_t type_path_t;
1663 struct type_path_t {
1664 type_path_entry_t *path; /**< An flexible array containing the current path. */
1665 type_t *top_type; /**< type of the element the path points */
1666 size_t max_index; /**< largest index in outermost array */
1670 * Prints a type path for debugging.
1672 static __attribute__((unused)) void debug_print_type_path(
1673 const type_path_t *path)
1675 size_t len = ARR_LEN(path->path);
1677 for (size_t i = 0; i < len; ++i) {
1678 const type_path_entry_t *entry = & path->path[i];
1680 type_t *type = skip_typeref(entry->type);
1681 if (is_type_compound(type)) {
1682 /* in gcc mode structs can have no members */
1683 if (entry->v.compound_entry == NULL) {
1687 fprintf(stderr, ".%s",
1688 entry->v.compound_entry->base.symbol->string);
1689 } else if (is_type_array(type)) {
1690 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1692 fprintf(stderr, "-INVALID-");
1695 if (path->top_type != NULL) {
1696 fprintf(stderr, " (");
1697 print_type(path->top_type);
1698 fprintf(stderr, ")");
1703 * Return the top type path entry, ie. in a path
1704 * (type).a.b returns the b.
1706 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1708 size_t len = ARR_LEN(path->path);
1710 return &path->path[len-1];
1714 * Enlarge the type path by an (empty) element.
1716 static type_path_entry_t *append_to_type_path(type_path_t *path)
1718 size_t len = ARR_LEN(path->path);
1719 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1721 type_path_entry_t *result = & path->path[len];
1722 memset(result, 0, sizeof(result[0]));
1727 * Descending into a sub-type. Enter the scope of the current top_type.
1729 static void descend_into_subtype(type_path_t *path)
1731 type_t *orig_top_type = path->top_type;
1732 type_t *top_type = skip_typeref(orig_top_type);
1734 type_path_entry_t *top = append_to_type_path(path);
1735 top->type = top_type;
1737 if (is_type_compound(top_type)) {
1738 compound_t *const compound = top_type->compound.compound;
1739 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1741 if (entry != NULL) {
1742 top->v.compound_entry = &entry->declaration;
1743 path->top_type = entry->declaration.type;
1745 path->top_type = NULL;
1747 } else if (is_type_array(top_type)) {
1749 path->top_type = top_type->array.element_type;
1751 assert(!is_type_valid(top_type));
1756 * Pop an entry from the given type path, ie. returning from
1757 * (type).a.b to (type).a
1759 static void ascend_from_subtype(type_path_t *path)
1761 type_path_entry_t *top = get_type_path_top(path);
1763 path->top_type = top->type;
1765 size_t len = ARR_LEN(path->path);
1766 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1770 * Pop entries from the given type path until the given
1771 * path level is reached.
1773 static void ascend_to(type_path_t *path, size_t top_path_level)
1775 size_t len = ARR_LEN(path->path);
1777 while (len > top_path_level) {
1778 ascend_from_subtype(path);
1779 len = ARR_LEN(path->path);
1783 static bool walk_designator(type_path_t *path, const designator_t *designator,
1784 bool used_in_offsetof)
1786 for (; designator != NULL; designator = designator->next) {
1787 type_path_entry_t *top = get_type_path_top(path);
1788 type_t *orig_type = top->type;
1790 type_t *type = skip_typeref(orig_type);
1792 if (designator->symbol != NULL) {
1793 symbol_t *symbol = designator->symbol;
1794 if (!is_type_compound(type)) {
1795 if (is_type_valid(type)) {
1796 errorf(&designator->source_position,
1797 "'.%Y' designator used for non-compound type '%T'",
1801 top->type = type_error_type;
1802 top->v.compound_entry = NULL;
1803 orig_type = type_error_type;
1805 compound_t *compound = type->compound.compound;
1806 entity_t *iter = compound->members.entities;
1807 for (; iter != NULL; iter = iter->base.next) {
1808 if (iter->base.symbol == symbol) {
1813 errorf(&designator->source_position,
1814 "'%T' has no member named '%Y'", orig_type, symbol);
1817 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1818 if (used_in_offsetof && iter->compound_member.bitfield) {
1819 errorf(&designator->source_position,
1820 "offsetof designator '%Y' must not specify bitfield",
1825 top->type = orig_type;
1826 top->v.compound_entry = &iter->declaration;
1827 orig_type = iter->declaration.type;
1830 expression_t *array_index = designator->array_index;
1831 if (is_constant_expression(array_index) != EXPR_CLASS_CONSTANT)
1834 if (!is_type_array(type)) {
1835 if (is_type_valid(type)) {
1836 errorf(&designator->source_position,
1837 "[%E] designator used for non-array type '%T'",
1838 array_index, orig_type);
1843 long index = fold_constant_to_int(array_index);
1844 if (!used_in_offsetof) {
1846 errorf(&designator->source_position,
1847 "array index [%E] must be positive", array_index);
1848 } else if (type->array.size_constant) {
1849 long array_size = type->array.size;
1850 if (index >= array_size) {
1851 errorf(&designator->source_position,
1852 "designator [%E] (%d) exceeds array size %d",
1853 array_index, index, array_size);
1858 top->type = orig_type;
1859 top->v.index = (size_t) index;
1860 orig_type = type->array.element_type;
1862 path->top_type = orig_type;
1864 if (designator->next != NULL) {
1865 descend_into_subtype(path);
1871 static void advance_current_object(type_path_t *path, size_t top_path_level)
1873 type_path_entry_t *top = get_type_path_top(path);
1875 type_t *type = skip_typeref(top->type);
1876 if (is_type_union(type)) {
1877 /* in unions only the first element is initialized */
1878 top->v.compound_entry = NULL;
1879 } else if (is_type_struct(type)) {
1880 declaration_t *entry = top->v.compound_entry;
1882 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1883 if (next_entity != NULL) {
1884 assert(is_declaration(next_entity));
1885 entry = &next_entity->declaration;
1890 top->v.compound_entry = entry;
1891 if (entry != NULL) {
1892 path->top_type = entry->type;
1895 } else if (is_type_array(type)) {
1896 assert(is_type_array(type));
1900 if (!type->array.size_constant || top->v.index < type->array.size) {
1904 assert(!is_type_valid(type));
1908 /* we're past the last member of the current sub-aggregate, try if we
1909 * can ascend in the type hierarchy and continue with another subobject */
1910 size_t len = ARR_LEN(path->path);
1912 if (len > top_path_level) {
1913 ascend_from_subtype(path);
1914 advance_current_object(path, top_path_level);
1916 path->top_type = NULL;
1921 * skip any {...} blocks until a closing bracket is reached.
1923 static void skip_initializers(void)
1927 while (token.kind != '}') {
1928 if (token.kind == T_EOF)
1930 if (token.kind == '{') {
1938 static initializer_t *create_empty_initializer(void)
1940 static initializer_t empty_initializer
1941 = { .list = { { INITIALIZER_LIST }, 0 } };
1942 return &empty_initializer;
1946 * Parse a part of an initialiser for a struct or union,
1948 static initializer_t *parse_sub_initializer(type_path_t *path,
1949 type_t *outer_type, size_t top_path_level,
1950 parse_initializer_env_t *env)
1952 if (token.kind == '}') {
1953 /* empty initializer */
1954 return create_empty_initializer();
1957 initializer_t *result = NULL;
1959 type_t *orig_type = path->top_type;
1960 type_t *type = NULL;
1962 if (orig_type == NULL) {
1963 /* We are initializing an empty compound. */
1965 type = skip_typeref(orig_type);
1968 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1971 designator_t *designator = NULL;
1972 if (token.kind == '.' || token.kind == '[') {
1973 designator = parse_designation();
1974 goto finish_designator;
1975 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
1976 /* GNU-style designator ("identifier: value") */
1977 designator = allocate_ast_zero(sizeof(designator[0]));
1978 designator->source_position = *HERE;
1979 designator->symbol = token.base.symbol;
1984 /* reset path to toplevel, evaluate designator from there */
1985 ascend_to(path, top_path_level);
1986 if (!walk_designator(path, designator, false)) {
1987 /* can't continue after designation error */
1991 initializer_t *designator_initializer
1992 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1993 designator_initializer->designator.designator = designator;
1994 ARR_APP1(initializer_t*, initializers, designator_initializer);
1996 orig_type = path->top_type;
1997 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2002 if (token.kind == '{') {
2003 if (type != NULL && is_type_scalar(type)) {
2004 sub = parse_scalar_initializer(type, env->must_be_constant);
2007 if (env->entity != NULL) {
2008 errorf(HERE, "extra brace group at end of initializer for '%N'", env->entity);
2010 errorf(HERE, "extra brace group at end of initializer");
2015 descend_into_subtype(path);
2018 add_anchor_token('}');
2019 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2021 rem_anchor_token('}');
2026 goto error_parse_next;
2028 ascend_from_subtype(path);
2031 /* must be an expression */
2032 expression_t *expression = parse_assignment_expression();
2033 mark_vars_read(expression, NULL);
2035 if (env->must_be_constant && !is_linker_constant(expression)) {
2036 errorf(&expression->base.source_position,
2037 "Initialisation expression '%E' is not constant",
2042 /* we are already outside, ... */
2043 if (outer_type == NULL)
2044 goto error_parse_next;
2045 type_t *const outer_type_skip = skip_typeref(outer_type);
2046 if (is_type_compound(outer_type_skip) &&
2047 !outer_type_skip->compound.compound->complete) {
2048 goto error_parse_next;
2051 source_position_t const* const pos = &expression->base.source_position;
2052 if (env->entity != NULL) {
2053 warningf(WARN_OTHER, pos, "excess elements in initializer for '%N'", env->entity);
2055 warningf(WARN_OTHER, pos, "excess elements in initializer");
2057 goto error_parse_next;
2060 /* handle { "string" } special case */
2061 if (expression->kind == EXPR_STRING_LITERAL && outer_type != NULL) {
2062 result = initializer_from_expression(outer_type, expression);
2063 if (result != NULL) {
2065 if (token.kind != '}') {
2066 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", outer_type);
2068 /* TODO: eat , ... */
2073 /* descend into subtypes until expression matches type */
2075 orig_type = path->top_type;
2076 type = skip_typeref(orig_type);
2078 sub = initializer_from_expression(orig_type, expression);
2082 if (!is_type_valid(type)) {
2085 if (is_type_scalar(type)) {
2086 errorf(&expression->base.source_position,
2087 "expression '%E' doesn't match expected type '%T'",
2088 expression, orig_type);
2092 descend_into_subtype(path);
2096 /* update largest index of top array */
2097 const type_path_entry_t *first = &path->path[0];
2098 type_t *first_type = first->type;
2099 first_type = skip_typeref(first_type);
2100 if (is_type_array(first_type)) {
2101 size_t index = first->v.index;
2102 if (index > path->max_index)
2103 path->max_index = index;
2106 /* append to initializers list */
2107 ARR_APP1(initializer_t*, initializers, sub);
2112 if (token.kind == '}') {
2117 /* advance to the next declaration if we are not at the end */
2118 advance_current_object(path, top_path_level);
2119 orig_type = path->top_type;
2120 if (orig_type != NULL)
2121 type = skip_typeref(orig_type);
2127 size_t len = ARR_LEN(initializers);
2128 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2129 result = allocate_ast_zero(size);
2130 result->kind = INITIALIZER_LIST;
2131 result->list.len = len;
2132 memcpy(&result->list.initializers, initializers,
2133 len * sizeof(initializers[0]));
2137 skip_initializers();
2139 DEL_ARR_F(initializers);
2140 ascend_to(path, top_path_level+1);
2144 static expression_t *make_size_literal(size_t value)
2146 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2147 literal->base.type = type_size_t;
2150 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2151 literal->literal.value = make_string(buf);
2157 * Parses an initializer. Parsers either a compound literal
2158 * (env->declaration == NULL) or an initializer of a declaration.
2160 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2162 type_t *type = skip_typeref(env->type);
2163 size_t max_index = 0;
2164 initializer_t *result;
2166 if (is_type_scalar(type)) {
2167 result = parse_scalar_initializer(type, env->must_be_constant);
2168 } else if (token.kind == '{') {
2172 memset(&path, 0, sizeof(path));
2173 path.top_type = env->type;
2174 path.path = NEW_ARR_F(type_path_entry_t, 0);
2176 descend_into_subtype(&path);
2178 add_anchor_token('}');
2179 result = parse_sub_initializer(&path, env->type, 1, env);
2180 rem_anchor_token('}');
2182 max_index = path.max_index;
2183 DEL_ARR_F(path.path);
2187 /* parse_scalar_initializer() also works in this case: we simply
2188 * have an expression without {} around it */
2189 result = parse_scalar_initializer(type, env->must_be_constant);
2192 /* §6.7.8:22 array initializers for arrays with unknown size determine
2193 * the array type size */
2194 if (is_type_array(type) && type->array.size_expression == NULL
2195 && result != NULL) {
2197 switch (result->kind) {
2198 case INITIALIZER_LIST:
2199 assert(max_index != 0xdeadbeaf);
2200 size = max_index + 1;
2203 case INITIALIZER_STRING: {
2204 size = get_string_len(&get_init_string(result)->value) + 1;
2208 case INITIALIZER_DESIGNATOR:
2209 case INITIALIZER_VALUE:
2210 /* can happen for parse errors */
2215 internal_errorf(HERE, "invalid initializer type");
2218 type_t *new_type = duplicate_type(type);
2220 new_type->array.size_expression = make_size_literal(size);
2221 new_type->array.size_constant = true;
2222 new_type->array.has_implicit_size = true;
2223 new_type->array.size = size;
2224 env->type = new_type;
2230 static void append_entity(scope_t *scope, entity_t *entity)
2232 if (scope->last_entity != NULL) {
2233 scope->last_entity->base.next = entity;
2235 scope->entities = entity;
2237 entity->base.parent_entity = current_entity;
2238 scope->last_entity = entity;
2242 static compound_t *parse_compound_type_specifier(bool is_struct)
2244 source_position_t const pos = *HERE;
2245 eat(is_struct ? T_struct : T_union);
2247 symbol_t *symbol = NULL;
2248 entity_t *entity = NULL;
2249 attribute_t *attributes = NULL;
2251 if (token.kind == T___attribute__) {
2252 attributes = parse_attributes(NULL);
2255 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2256 if (token.kind == T_IDENTIFIER) {
2257 /* the compound has a name, check if we have seen it already */
2258 symbol = token.base.symbol;
2259 entity = get_tag(symbol, kind);
2262 if (entity != NULL) {
2263 if (entity->base.parent_scope != current_scope &&
2264 (token.kind == '{' || token.kind == ';')) {
2265 /* we're in an inner scope and have a definition. Shadow
2266 * existing definition in outer scope */
2268 } else if (entity->compound.complete && token.kind == '{') {
2269 source_position_t const *const ppos = &entity->base.source_position;
2270 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2271 /* clear members in the hope to avoid further errors */
2272 entity->compound.members.entities = NULL;
2275 } else if (token.kind != '{') {
2276 char const *const msg =
2277 is_struct ? "while parsing struct type specifier" :
2278 "while parsing union type specifier";
2279 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2284 if (entity == NULL) {
2285 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2286 entity->compound.alignment = 1;
2287 entity->base.parent_scope = current_scope;
2288 if (symbol != NULL) {
2289 environment_push(entity);
2291 append_entity(current_scope, entity);
2294 if (token.kind == '{') {
2295 parse_compound_type_entries(&entity->compound);
2297 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2298 if (symbol == NULL) {
2299 assert(anonymous_entity == NULL);
2300 anonymous_entity = entity;
2304 if (attributes != NULL) {
2305 handle_entity_attributes(attributes, entity);
2308 return &entity->compound;
2311 static void parse_enum_entries(type_t *const enum_type)
2315 if (token.kind == '}') {
2316 errorf(HERE, "empty enum not allowed");
2321 add_anchor_token('}');
2322 add_anchor_token(',');
2324 add_anchor_token('=');
2325 source_position_t pos;
2326 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2327 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2328 entity->enum_value.enum_type = enum_type;
2329 rem_anchor_token('=');
2332 expression_t *value = parse_constant_expression();
2334 value = create_implicit_cast(value, enum_type);
2335 entity->enum_value.value = value;
2340 record_entity(entity, false);
2341 } while (next_if(',') && token.kind != '}');
2342 rem_anchor_token(',');
2343 rem_anchor_token('}');
2348 static type_t *parse_enum_specifier(void)
2350 source_position_t const pos = *HERE;
2355 switch (token.kind) {
2357 symbol = token.base.symbol;
2358 entity = get_tag(symbol, ENTITY_ENUM);
2361 if (entity != NULL) {
2362 if (entity->base.parent_scope != current_scope &&
2363 (token.kind == '{' || token.kind == ';')) {
2364 /* we're in an inner scope and have a definition. Shadow
2365 * existing definition in outer scope */
2367 } else if (entity->enume.complete && token.kind == '{') {
2368 source_position_t const *const ppos = &entity->base.source_position;
2369 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2380 parse_error_expected("while parsing enum type specifier",
2381 T_IDENTIFIER, '{', NULL);
2385 if (entity == NULL) {
2386 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2387 entity->base.parent_scope = current_scope;
2390 type_t *const type = allocate_type_zero(TYPE_ENUM);
2391 type->enumt.enume = &entity->enume;
2392 type->enumt.base.akind = ATOMIC_TYPE_INT;
2394 if (token.kind == '{') {
2395 if (symbol != NULL) {
2396 environment_push(entity);
2398 append_entity(current_scope, entity);
2399 entity->enume.complete = true;
2401 parse_enum_entries(type);
2402 parse_attributes(NULL);
2404 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2405 if (symbol == NULL) {
2406 assert(anonymous_entity == NULL);
2407 anonymous_entity = entity;
2409 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2410 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2417 * if a symbol is a typedef to another type, return true
2419 static bool is_typedef_symbol(symbol_t *symbol)
2421 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2422 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2425 static type_t *parse_typeof(void)
2431 add_anchor_token(')');
2434 expression_t *expression = NULL;
2436 switch (token.kind) {
2438 if (is_typedef_symbol(token.base.symbol)) {
2440 type = parse_typename();
2443 expression = parse_expression();
2444 type = revert_automatic_type_conversion(expression);
2449 rem_anchor_token(')');
2452 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2453 typeof_type->typeoft.expression = expression;
2454 typeof_type->typeoft.typeof_type = type;
2459 typedef enum specifiers_t {
2461 SPECIFIER_SIGNED = 1 << 0,
2462 SPECIFIER_UNSIGNED = 1 << 1,
2463 SPECIFIER_LONG = 1 << 2,
2464 SPECIFIER_INT = 1 << 3,
2465 SPECIFIER_DOUBLE = 1 << 4,
2466 SPECIFIER_CHAR = 1 << 5,
2467 SPECIFIER_WCHAR_T = 1 << 6,
2468 SPECIFIER_SHORT = 1 << 7,
2469 SPECIFIER_LONG_LONG = 1 << 8,
2470 SPECIFIER_FLOAT = 1 << 9,
2471 SPECIFIER_BOOL = 1 << 10,
2472 SPECIFIER_VOID = 1 << 11,
2473 SPECIFIER_INT8 = 1 << 12,
2474 SPECIFIER_INT16 = 1 << 13,
2475 SPECIFIER_INT32 = 1 << 14,
2476 SPECIFIER_INT64 = 1 << 15,
2477 SPECIFIER_INT128 = 1 << 16,
2478 SPECIFIER_COMPLEX = 1 << 17,
2479 SPECIFIER_IMAGINARY = 1 << 18,
2482 static type_t *get_typedef_type(symbol_t *symbol)
2484 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2485 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2488 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2489 type->typedeft.typedefe = &entity->typedefe;
2494 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2496 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2498 add_anchor_token(')');
2499 add_anchor_token(',');
2503 add_anchor_token('=');
2504 source_position_t pos;
2505 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2506 rem_anchor_token('=');
2508 symbol_t **prop = NULL;
2510 if (streq(prop_sym->string, "put")) {
2511 prop = &property->put_symbol;
2512 } else if (streq(prop_sym->string, "get")) {
2513 prop = &property->get_symbol;
2515 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2519 add_anchor_token(T_IDENTIFIER);
2521 rem_anchor_token(T_IDENTIFIER);
2523 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2525 *prop = sym ? sym : sym_anonymous;
2526 } while (next_if(','));
2527 rem_anchor_token(',');
2528 rem_anchor_token(')');
2530 attribute->a.property = property;
2536 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2538 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2539 if (next_if(T_restrict)) {
2540 kind = ATTRIBUTE_MS_RESTRICT;
2541 } else if (token.kind == T_IDENTIFIER) {
2542 char const *const name = token.base.symbol->string;
2543 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2545 const char *attribute_name = get_attribute_name(k);
2546 if (attribute_name != NULL && streq(attribute_name, name)) {
2552 if (kind == ATTRIBUTE_UNKNOWN) {
2553 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2556 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2560 attribute_t *attribute = allocate_attribute_zero(kind);
2563 if (kind == ATTRIBUTE_MS_PROPERTY) {
2564 return parse_attribute_ms_property(attribute);
2567 /* parse arguments */
2569 attribute->a.arguments = parse_attribute_arguments();
2574 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2578 add_anchor_token(')');
2580 if (token.kind != ')') {
2581 attribute_t **anchor = &first;
2583 while (*anchor != NULL)
2584 anchor = &(*anchor)->next;
2586 attribute_t *attribute
2587 = parse_microsoft_extended_decl_modifier_single();
2588 if (attribute == NULL)
2591 *anchor = attribute;
2592 anchor = &attribute->next;
2593 } while (next_if(','));
2595 rem_anchor_token(')');
2600 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2602 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2603 if (is_declaration(entity)) {
2604 entity->declaration.type = type_error_type;
2605 entity->declaration.implicit = true;
2606 } else if (kind == ENTITY_TYPEDEF) {
2607 entity->typedefe.type = type_error_type;
2608 entity->typedefe.builtin = true;
2610 if (kind != ENTITY_COMPOUND_MEMBER)
2611 record_entity(entity, false);
2615 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2617 type_t *type = NULL;
2618 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2619 unsigned type_specifiers = 0;
2620 bool newtype = false;
2621 bool saw_error = false;
2623 memset(specifiers, 0, sizeof(*specifiers));
2624 specifiers->source_position = *HERE;
2627 specifiers->attributes = parse_attributes(specifiers->attributes);
2629 switch (token.kind) {
2631 #define MATCH_STORAGE_CLASS(token, class) \
2633 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2634 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2636 specifiers->storage_class = class; \
2637 if (specifiers->thread_local) \
2638 goto check_thread_storage_class; \
2642 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2643 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2644 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2645 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2646 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2649 specifiers->attributes
2650 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2654 if (specifiers->thread_local) {
2655 errorf(HERE, "duplicate '__thread'");
2657 specifiers->thread_local = true;
2658 check_thread_storage_class:
2659 switch (specifiers->storage_class) {
2660 case STORAGE_CLASS_EXTERN:
2661 case STORAGE_CLASS_NONE:
2662 case STORAGE_CLASS_STATIC:
2666 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2667 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2668 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2669 wrong_thread_storage_class:
2670 errorf(HERE, "'__thread' used with '%s'", wrong);
2677 /* type qualifiers */
2678 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2680 qualifiers |= qualifier; \
2684 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2685 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2686 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2687 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2688 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2689 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2690 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2691 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2693 /* type specifiers */
2694 #define MATCH_SPECIFIER(token, specifier, name) \
2696 if (type_specifiers & specifier) { \
2697 errorf(HERE, "multiple " name " type specifiers given"); \
2699 type_specifiers |= specifier; \
2704 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2705 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2706 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2707 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2708 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2709 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2710 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2711 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2712 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2713 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2714 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2715 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2716 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2717 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2718 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2719 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2720 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2721 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2725 specifiers->is_inline = true;
2729 case T__forceinline:
2730 eat(T__forceinline);
2731 specifiers->modifiers |= DM_FORCEINLINE;
2736 if (type_specifiers & SPECIFIER_LONG_LONG) {
2737 errorf(HERE, "too many long type specifiers given");
2738 } else if (type_specifiers & SPECIFIER_LONG) {
2739 type_specifiers |= SPECIFIER_LONG_LONG;
2741 type_specifiers |= SPECIFIER_LONG;
2746 #define CHECK_DOUBLE_TYPE() \
2747 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2750 CHECK_DOUBLE_TYPE();
2751 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2753 type->compound.compound = parse_compound_type_specifier(true);
2756 CHECK_DOUBLE_TYPE();
2757 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2758 type->compound.compound = parse_compound_type_specifier(false);
2761 CHECK_DOUBLE_TYPE();
2762 type = parse_enum_specifier();
2765 CHECK_DOUBLE_TYPE();
2766 type = parse_typeof();
2768 case T___builtin_va_list:
2769 CHECK_DOUBLE_TYPE();
2770 type = duplicate_type(type_valist);
2771 eat(T___builtin_va_list);
2774 case T_IDENTIFIER: {
2775 /* only parse identifier if we haven't found a type yet */
2776 if (type != NULL || type_specifiers != 0) {
2777 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2778 * declaration, so it doesn't generate errors about expecting '(' or
2780 switch (look_ahead(1)->kind) {
2787 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2791 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2796 goto finish_specifiers;
2800 type_t *const typedef_type = get_typedef_type(token.base.symbol);
2801 if (typedef_type == NULL) {
2802 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2803 * declaration, so it doesn't generate 'implicit int' followed by more
2804 * errors later on. */
2805 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2811 errorf(HERE, "%K does not name a type", &token);
2813 entity_t *const entity = create_error_entity(token.base.symbol, ENTITY_TYPEDEF);
2815 type = allocate_type_zero(TYPE_TYPEDEF);
2816 type->typedeft.typedefe = &entity->typedefe;
2824 goto finish_specifiers;
2829 type = typedef_type;
2833 /* function specifier */
2835 goto finish_specifiers;
2840 specifiers->attributes = parse_attributes(specifiers->attributes);
2842 if (type == NULL || (saw_error && type_specifiers != 0)) {
2843 atomic_type_kind_t atomic_type;
2845 /* match valid basic types */
2846 switch (type_specifiers) {
2847 case SPECIFIER_VOID:
2848 atomic_type = ATOMIC_TYPE_VOID;
2850 case SPECIFIER_WCHAR_T:
2851 atomic_type = ATOMIC_TYPE_WCHAR_T;
2853 case SPECIFIER_CHAR:
2854 atomic_type = ATOMIC_TYPE_CHAR;
2856 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2857 atomic_type = ATOMIC_TYPE_SCHAR;
2859 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2860 atomic_type = ATOMIC_TYPE_UCHAR;
2862 case SPECIFIER_SHORT:
2863 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2864 case SPECIFIER_SHORT | SPECIFIER_INT:
2865 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2866 atomic_type = ATOMIC_TYPE_SHORT;
2868 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2869 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2870 atomic_type = ATOMIC_TYPE_USHORT;
2873 case SPECIFIER_SIGNED:
2874 case SPECIFIER_SIGNED | SPECIFIER_INT:
2875 atomic_type = ATOMIC_TYPE_INT;
2877 case SPECIFIER_UNSIGNED:
2878 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2879 atomic_type = ATOMIC_TYPE_UINT;
2881 case SPECIFIER_LONG:
2882 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2883 case SPECIFIER_LONG | SPECIFIER_INT:
2884 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2885 atomic_type = ATOMIC_TYPE_LONG;
2887 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2888 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2889 atomic_type = ATOMIC_TYPE_ULONG;
2892 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2893 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2894 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2895 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2897 atomic_type = ATOMIC_TYPE_LONGLONG;
2898 goto warn_about_long_long;
2900 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2901 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2903 atomic_type = ATOMIC_TYPE_ULONGLONG;
2904 warn_about_long_long:
2905 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2908 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2909 atomic_type = unsigned_int8_type_kind;
2912 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2913 atomic_type = unsigned_int16_type_kind;
2916 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2917 atomic_type = unsigned_int32_type_kind;
2920 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2921 atomic_type = unsigned_int64_type_kind;
2924 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2925 atomic_type = unsigned_int128_type_kind;
2928 case SPECIFIER_INT8:
2929 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2930 atomic_type = int8_type_kind;
2933 case SPECIFIER_INT16:
2934 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2935 atomic_type = int16_type_kind;
2938 case SPECIFIER_INT32:
2939 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2940 atomic_type = int32_type_kind;
2943 case SPECIFIER_INT64:
2944 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2945 atomic_type = int64_type_kind;
2948 case SPECIFIER_INT128:
2949 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2950 atomic_type = int128_type_kind;
2953 case SPECIFIER_FLOAT:
2954 atomic_type = ATOMIC_TYPE_FLOAT;
2956 case SPECIFIER_DOUBLE:
2957 atomic_type = ATOMIC_TYPE_DOUBLE;
2959 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2960 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2962 case SPECIFIER_BOOL:
2963 atomic_type = ATOMIC_TYPE_BOOL;
2965 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2966 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2967 atomic_type = ATOMIC_TYPE_FLOAT;
2969 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2970 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2971 atomic_type = ATOMIC_TYPE_DOUBLE;
2973 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2974 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2975 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2978 /* invalid specifier combination, give an error message */
2979 source_position_t const* const pos = &specifiers->source_position;
2980 if (type_specifiers == 0) {
2982 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
2983 if (!(c_mode & _CXX) && !strict_mode) {
2984 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
2985 atomic_type = ATOMIC_TYPE_INT;
2988 errorf(pos, "no type specifiers given in declaration");
2991 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
2992 (type_specifiers & SPECIFIER_UNSIGNED)) {
2993 errorf(pos, "signed and unsigned specifiers given");
2994 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2995 errorf(pos, "only integer types can be signed or unsigned");
2997 errorf(pos, "multiple datatypes in declaration");
2999 specifiers->type = type_error_type;
3004 if (type_specifiers & SPECIFIER_COMPLEX) {
3005 type = allocate_type_zero(TYPE_COMPLEX);
3006 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3007 type = allocate_type_zero(TYPE_IMAGINARY);
3009 type = allocate_type_zero(TYPE_ATOMIC);
3011 type->atomic.akind = atomic_type;
3013 } else if (type_specifiers != 0) {
3014 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3017 /* FIXME: check type qualifiers here */
3018 type->base.qualifiers = qualifiers;
3021 type = identify_new_type(type);
3023 type = typehash_insert(type);
3026 if (specifiers->attributes != NULL)
3027 type = handle_type_attributes(specifiers->attributes, type);
3028 specifiers->type = type;
3031 static type_qualifiers_t parse_type_qualifiers(void)
3033 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3036 switch (token.kind) {
3037 /* type qualifiers */
3038 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3039 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3040 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3041 /* microsoft extended type modifiers */
3042 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3043 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3044 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3045 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3046 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3055 * Parses an K&R identifier list
3057 static void parse_identifier_list(scope_t *scope)
3059 assert(token.kind == T_IDENTIFIER);
3061 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.base.symbol, HERE);
3062 /* a K&R parameter has no type, yet */
3066 append_entity(scope, entity);
3067 } while (next_if(',') && token.kind == T_IDENTIFIER);
3070 static entity_t *parse_parameter(void)
3072 declaration_specifiers_t specifiers;
3073 parse_declaration_specifiers(&specifiers);
3075 entity_t *entity = parse_declarator(&specifiers,
3076 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3077 anonymous_entity = NULL;
3081 static void semantic_parameter_incomplete(const entity_t *entity)
3083 assert(entity->kind == ENTITY_PARAMETER);
3085 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3086 * list in a function declarator that is part of a
3087 * definition of that function shall not have
3088 * incomplete type. */
3089 type_t *type = skip_typeref(entity->declaration.type);
3090 if (is_type_incomplete(type)) {
3091 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3095 static bool has_parameters(void)
3097 /* func(void) is not a parameter */
3098 if (look_ahead(1)->kind != ')')
3100 if (token.kind == T_IDENTIFIER) {
3101 entity_t const *const entity = get_entity(token.base.symbol, NAMESPACE_NORMAL);
3104 if (entity->kind != ENTITY_TYPEDEF)
3106 type_t const *const type = skip_typeref(entity->typedefe.type);
3107 if (!is_type_void(type))
3109 if (c_mode & _CXX) {
3110 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3111 * is not allowed. */
3112 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3113 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3114 /* §6.7.5.3:10 Qualification is not allowed here. */
3115 errorf(HERE, "'void' as parameter must not have type qualifiers");
3117 } else if (token.kind != T_void) {
3125 * Parses function type parameters (and optionally creates variable_t entities
3126 * for them in a scope)
3128 static void parse_parameters(function_type_t *type, scope_t *scope)
3130 add_anchor_token(')');
3133 if (token.kind == T_IDENTIFIER &&
3134 !is_typedef_symbol(token.base.symbol) &&
3135 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3136 type->kr_style_parameters = true;
3137 parse_identifier_list(scope);
3138 } else if (token.kind == ')') {
3139 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3140 if (!(c_mode & _CXX))
3141 type->unspecified_parameters = true;
3142 } else if (has_parameters()) {
3143 function_parameter_t **anchor = &type->parameters;
3144 add_anchor_token(',');
3146 switch (token.kind) {
3149 type->variadic = true;
3150 goto parameters_finished;
3155 entity_t *entity = parse_parameter();
3156 if (entity->kind == ENTITY_TYPEDEF) {
3157 errorf(&entity->base.source_position,
3158 "typedef not allowed as function parameter");
3161 assert(is_declaration(entity));
3163 semantic_parameter_incomplete(entity);
3165 function_parameter_t *const parameter =
3166 allocate_parameter(entity->declaration.type);
3168 if (scope != NULL) {
3169 append_entity(scope, entity);
3172 *anchor = parameter;
3173 anchor = ¶meter->next;
3178 goto parameters_finished;
3180 } while (next_if(','));
3181 parameters_finished:
3182 rem_anchor_token(',');
3185 rem_anchor_token(')');
3189 typedef enum construct_type_kind_t {
3190 CONSTRUCT_POINTER = 1,
3191 CONSTRUCT_REFERENCE,
3194 } construct_type_kind_t;
3196 typedef union construct_type_t construct_type_t;
3198 typedef struct construct_type_base_t {
3199 construct_type_kind_t kind;
3200 source_position_t pos;
3201 construct_type_t *next;
3202 } construct_type_base_t;
3204 typedef struct parsed_pointer_t {
3205 construct_type_base_t base;
3206 type_qualifiers_t type_qualifiers;
3207 variable_t *base_variable; /**< MS __based extension. */
3210 typedef struct parsed_reference_t {
3211 construct_type_base_t base;
3212 } parsed_reference_t;
3214 typedef struct construct_function_type_t {
3215 construct_type_base_t base;
3216 type_t *function_type;
3217 } construct_function_type_t;
3219 typedef struct parsed_array_t {
3220 construct_type_base_t base;
3221 type_qualifiers_t type_qualifiers;
3227 union construct_type_t {
3228 construct_type_kind_t kind;
3229 construct_type_base_t base;
3230 parsed_pointer_t pointer;
3231 parsed_reference_t reference;
3232 construct_function_type_t function;
3233 parsed_array_t array;
3236 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3238 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3239 memset(cons, 0, size);
3241 cons->base.pos = *HERE;
3246 static construct_type_t *parse_pointer_declarator(void)
3248 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3250 cons->pointer.type_qualifiers = parse_type_qualifiers();
3251 //cons->pointer.base_variable = base_variable;
3256 /* ISO/IEC 14882:1998(E) §8.3.2 */
3257 static construct_type_t *parse_reference_declarator(void)
3259 if (!(c_mode & _CXX))
3260 errorf(HERE, "references are only available for C++");
3262 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3269 static construct_type_t *parse_array_declarator(void)
3271 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3272 parsed_array_t *const array = &cons->array;
3275 add_anchor_token(']');
3277 bool is_static = next_if(T_static);
3279 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3282 is_static = next_if(T_static);
3284 array->type_qualifiers = type_qualifiers;
3285 array->is_static = is_static;
3287 expression_t *size = NULL;
3288 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3289 array->is_variable = true;
3291 } else if (token.kind != ']') {
3292 size = parse_assignment_expression();
3294 /* §6.7.5.2:1 Array size must have integer type */
3295 type_t *const orig_type = size->base.type;
3296 type_t *const type = skip_typeref(orig_type);
3297 if (!is_type_integer(type) && is_type_valid(type)) {
3298 errorf(&size->base.source_position,
3299 "array size '%E' must have integer type but has type '%T'",
3304 mark_vars_read(size, NULL);
3307 if (is_static && size == NULL)
3308 errorf(&array->base.pos, "static array parameters require a size");
3310 rem_anchor_token(']');
3316 static construct_type_t *parse_function_declarator(scope_t *scope)
3318 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3320 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3321 function_type_t *ftype = &type->function;
3323 ftype->linkage = current_linkage;
3324 ftype->calling_convention = CC_DEFAULT;
3326 parse_parameters(ftype, scope);
3328 cons->function.function_type = type;
3333 typedef struct parse_declarator_env_t {
3334 bool may_be_abstract : 1;
3335 bool must_be_abstract : 1;
3336 decl_modifiers_t modifiers;
3338 source_position_t source_position;
3340 attribute_t *attributes;
3341 } parse_declarator_env_t;
3344 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3346 /* construct a single linked list of construct_type_t's which describe
3347 * how to construct the final declarator type */
3348 construct_type_t *first = NULL;
3349 construct_type_t **anchor = &first;
3351 env->attributes = parse_attributes(env->attributes);
3354 construct_type_t *type;
3355 //variable_t *based = NULL; /* MS __based extension */
3356 switch (token.kind) {
3358 type = parse_reference_declarator();
3362 panic("based not supported anymore");
3367 type = parse_pointer_declarator();
3371 goto ptr_operator_end;
3375 anchor = &type->base.next;
3377 /* TODO: find out if this is correct */
3378 env->attributes = parse_attributes(env->attributes);
3382 construct_type_t *inner_types = NULL;
3384 switch (token.kind) {
3386 if (env->must_be_abstract) {
3387 errorf(HERE, "no identifier expected in typename");
3389 env->symbol = token.base.symbol;
3390 env->source_position = *HERE;
3396 /* Parenthesized declarator or function declarator? */
3397 token_t const *const la1 = look_ahead(1);
3398 switch (la1->kind) {
3400 if (is_typedef_symbol(la1->base.symbol)) {
3402 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3403 * interpreted as ``function with no parameter specification'', rather
3404 * than redundant parentheses around the omitted identifier. */
3406 /* Function declarator. */
3407 if (!env->may_be_abstract) {
3408 errorf(HERE, "function declarator must have a name");
3415 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3416 /* Paranthesized declarator. */
3418 add_anchor_token(')');
3419 inner_types = parse_inner_declarator(env);
3420 if (inner_types != NULL) {
3421 /* All later declarators only modify the return type */
3422 env->must_be_abstract = true;
3424 rem_anchor_token(')');
3433 if (env->may_be_abstract)
3435 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3440 construct_type_t **const p = anchor;
3443 construct_type_t *type;
3444 switch (token.kind) {
3446 scope_t *scope = NULL;
3447 if (!env->must_be_abstract) {
3448 scope = &env->parameters;
3451 type = parse_function_declarator(scope);
3455 type = parse_array_declarator();
3458 goto declarator_finished;
3461 /* insert in the middle of the list (at p) */
3462 type->base.next = *p;
3465 anchor = &type->base.next;
3468 declarator_finished:
3469 /* append inner_types at the end of the list, we don't to set anchor anymore
3470 * as it's not needed anymore */
3471 *anchor = inner_types;
3476 static type_t *construct_declarator_type(construct_type_t *construct_list,
3479 construct_type_t *iter = construct_list;
3480 for (; iter != NULL; iter = iter->base.next) {
3481 source_position_t const* const pos = &iter->base.pos;
3482 switch (iter->kind) {
3483 case CONSTRUCT_FUNCTION: {
3484 construct_function_type_t *function = &iter->function;
3485 type_t *function_type = function->function_type;
3487 function_type->function.return_type = type;
3489 type_t *skipped_return_type = skip_typeref(type);
3491 if (is_type_function(skipped_return_type)) {
3492 errorf(pos, "function returning function is not allowed");
3493 } else if (is_type_array(skipped_return_type)) {
3494 errorf(pos, "function returning array is not allowed");
3496 if (skipped_return_type->base.qualifiers != 0) {
3497 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3501 /* The function type was constructed earlier. Freeing it here will
3502 * destroy other types. */
3503 type = typehash_insert(function_type);
3507 case CONSTRUCT_POINTER: {
3508 if (is_type_reference(skip_typeref(type)))
3509 errorf(pos, "cannot declare a pointer to reference");
3511 parsed_pointer_t *pointer = &iter->pointer;
3512 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3516 case CONSTRUCT_REFERENCE:
3517 if (is_type_reference(skip_typeref(type)))
3518 errorf(pos, "cannot declare a reference to reference");
3520 type = make_reference_type(type);
3523 case CONSTRUCT_ARRAY: {
3524 if (is_type_reference(skip_typeref(type)))
3525 errorf(pos, "cannot declare an array of references");
3527 parsed_array_t *array = &iter->array;
3528 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3530 expression_t *size_expression = array->size;
3531 if (size_expression != NULL) {
3533 = create_implicit_cast(size_expression, type_size_t);
3536 array_type->base.qualifiers = array->type_qualifiers;
3537 array_type->array.element_type = type;
3538 array_type->array.is_static = array->is_static;
3539 array_type->array.is_variable = array->is_variable;
3540 array_type->array.size_expression = size_expression;
3542 if (size_expression != NULL) {
3543 switch (is_constant_expression(size_expression)) {
3544 case EXPR_CLASS_CONSTANT: {
3545 long const size = fold_constant_to_int(size_expression);
3546 array_type->array.size = size;
3547 array_type->array.size_constant = true;
3548 /* §6.7.5.2:1 If the expression is a constant expression,
3549 * it shall have a value greater than zero. */
3551 errorf(&size_expression->base.source_position,
3552 "size of array must be greater than zero");
3553 } else if (size == 0 && !GNU_MODE) {
3554 errorf(&size_expression->base.source_position,
3555 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3560 case EXPR_CLASS_VARIABLE:
3561 array_type->array.is_vla = true;
3564 case EXPR_CLASS_ERROR:
3569 type_t *skipped_type = skip_typeref(type);
3571 if (is_type_incomplete(skipped_type)) {
3572 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3573 } else if (is_type_function(skipped_type)) {
3574 errorf(pos, "array of functions is not allowed");
3576 type = identify_new_type(array_type);
3580 internal_errorf(pos, "invalid type construction found");
3586 static type_t *automatic_type_conversion(type_t *orig_type);
3588 static type_t *semantic_parameter(const source_position_t *pos,
3590 const declaration_specifiers_t *specifiers,
3591 entity_t const *const param)
3593 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3594 * shall be adjusted to ``qualified pointer to type'',
3596 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3597 * type'' shall be adjusted to ``pointer to function
3598 * returning type'', as in 6.3.2.1. */
3599 type = automatic_type_conversion(type);
3601 if (specifiers->is_inline && is_type_valid(type)) {
3602 errorf(pos, "'%N' declared 'inline'", param);
3605 /* §6.9.1:6 The declarations in the declaration list shall contain
3606 * no storage-class specifier other than register and no
3607 * initializations. */
3608 if (specifiers->thread_local || (
3609 specifiers->storage_class != STORAGE_CLASS_NONE &&
3610 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3612 errorf(pos, "invalid storage class for '%N'", param);
3615 /* delay test for incomplete type, because we might have (void)
3616 * which is legal but incomplete... */
3621 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3622 declarator_flags_t flags)
3624 parse_declarator_env_t env;
3625 memset(&env, 0, sizeof(env));
3626 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3628 construct_type_t *construct_type = parse_inner_declarator(&env);
3630 construct_declarator_type(construct_type, specifiers->type);
3631 type_t *type = skip_typeref(orig_type);
3633 if (construct_type != NULL) {
3634 obstack_free(&temp_obst, construct_type);
3637 attribute_t *attributes = parse_attributes(env.attributes);
3638 /* append (shared) specifier attribute behind attributes of this
3640 attribute_t **anchor = &attributes;
3641 while (*anchor != NULL)
3642 anchor = &(*anchor)->next;
3643 *anchor = specifiers->attributes;
3646 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3647 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3648 entity->typedefe.type = orig_type;
3650 if (anonymous_entity != NULL) {
3651 if (is_type_compound(type)) {
3652 assert(anonymous_entity->compound.alias == NULL);
3653 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3654 anonymous_entity->kind == ENTITY_UNION);
3655 anonymous_entity->compound.alias = entity;
3656 anonymous_entity = NULL;
3657 } else if (is_type_enum(type)) {
3658 assert(anonymous_entity->enume.alias == NULL);
3659 assert(anonymous_entity->kind == ENTITY_ENUM);
3660 anonymous_entity->enume.alias = entity;
3661 anonymous_entity = NULL;
3665 /* create a declaration type entity */
3666 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3667 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3668 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3670 if (env.symbol != NULL) {
3671 if (specifiers->is_inline && is_type_valid(type)) {
3672 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3675 if (specifiers->thread_local ||
3676 specifiers->storage_class != STORAGE_CLASS_NONE) {
3677 errorf(&env.source_position, "'%N' must have no storage class", entity);
3680 } else if (flags & DECL_IS_PARAMETER) {
3681 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3682 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3683 } else if (is_type_function(type)) {
3684 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3685 entity->function.is_inline = specifiers->is_inline;
3686 entity->function.elf_visibility = default_visibility;
3687 entity->function.parameters = env.parameters;
3689 if (env.symbol != NULL) {
3690 /* this needs fixes for C++ */
3691 bool in_function_scope = current_function != NULL;
3693 if (specifiers->thread_local || (
3694 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3695 specifiers->storage_class != STORAGE_CLASS_NONE &&
3696 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3698 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3702 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3703 entity->variable.elf_visibility = default_visibility;
3704 entity->variable.thread_local = specifiers->thread_local;
3706 if (env.symbol != NULL) {
3707 if (specifiers->is_inline && is_type_valid(type)) {
3708 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3711 bool invalid_storage_class = false;
3712 if (current_scope == file_scope) {
3713 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3714 specifiers->storage_class != STORAGE_CLASS_NONE &&
3715 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3716 invalid_storage_class = true;
3719 if (specifiers->thread_local &&
3720 specifiers->storage_class == STORAGE_CLASS_NONE) {
3721 invalid_storage_class = true;
3724 if (invalid_storage_class) {
3725 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3730 entity->declaration.type = orig_type;
3731 entity->declaration.alignment = get_type_alignment(orig_type);
3732 entity->declaration.modifiers = env.modifiers;
3733 entity->declaration.attributes = attributes;
3735 storage_class_t storage_class = specifiers->storage_class;
3736 entity->declaration.declared_storage_class = storage_class;
3738 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3739 storage_class = STORAGE_CLASS_AUTO;
3740 entity->declaration.storage_class = storage_class;
3743 if (attributes != NULL) {
3744 handle_entity_attributes(attributes, entity);
3747 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3748 adapt_special_functions(&entity->function);
3754 static type_t *parse_abstract_declarator(type_t *base_type)
3756 parse_declarator_env_t env;
3757 memset(&env, 0, sizeof(env));
3758 env.may_be_abstract = true;
3759 env.must_be_abstract = true;
3761 construct_type_t *construct_type = parse_inner_declarator(&env);
3763 type_t *result = construct_declarator_type(construct_type, base_type);
3764 if (construct_type != NULL) {
3765 obstack_free(&temp_obst, construct_type);
3767 result = handle_type_attributes(env.attributes, result);
3773 * Check if the declaration of main is suspicious. main should be a
3774 * function with external linkage, returning int, taking either zero
3775 * arguments, two, or three arguments of appropriate types, ie.
3777 * int main([ int argc, char **argv [, char **env ] ]).
3779 * @param decl the declaration to check
3780 * @param type the function type of the declaration
3782 static void check_main(const entity_t *entity)
3784 const source_position_t *pos = &entity->base.source_position;
3785 if (entity->kind != ENTITY_FUNCTION) {
3786 warningf(WARN_MAIN, pos, "'main' is not a function");
3790 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3791 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3794 type_t *type = skip_typeref(entity->declaration.type);
3795 assert(is_type_function(type));
3797 function_type_t const *const func_type = &type->function;
3798 type_t *const ret_type = func_type->return_type;
3799 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3800 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3802 const function_parameter_t *parm = func_type->parameters;
3804 type_t *const first_type = skip_typeref(parm->type);
3805 type_t *const first_type_unqual = get_unqualified_type(first_type);
3806 if (!types_compatible(first_type_unqual, type_int)) {
3807 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3811 type_t *const second_type = skip_typeref(parm->type);
3812 type_t *const second_type_unqual
3813 = get_unqualified_type(second_type);
3814 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3815 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3819 type_t *const third_type = skip_typeref(parm->type);
3820 type_t *const third_type_unqual
3821 = get_unqualified_type(third_type);
3822 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3823 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3827 goto warn_arg_count;
3831 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3836 static void error_redefined_as_different_kind(const source_position_t *pos,
3837 const entity_t *old, entity_kind_t new_kind)
3839 char const *const what = get_entity_kind_name(new_kind);
3840 source_position_t const *const ppos = &old->base.source_position;
3841 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3844 static bool is_entity_valid(entity_t *const ent)
3846 if (is_declaration(ent)) {
3847 return is_type_valid(skip_typeref(ent->declaration.type));
3848 } else if (ent->kind == ENTITY_TYPEDEF) {
3849 return is_type_valid(skip_typeref(ent->typedefe.type));
3854 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3856 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3857 if (attributes_equal(tattr, attr))
3864 * test wether new_list contains any attributes not included in old_list
3866 static bool has_new_attributes(const attribute_t *old_list,
3867 const attribute_t *new_list)
3869 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3870 if (!contains_attribute(old_list, attr))
3877 * Merge in attributes from an attribute list (probably from a previous
3878 * declaration with the same name). Warning: destroys the old structure
3879 * of the attribute list - don't reuse attributes after this call.
3881 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3884 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3886 if (contains_attribute(decl->attributes, attr))
3889 /* move attribute to new declarations attributes list */
3890 attr->next = decl->attributes;
3891 decl->attributes = attr;
3895 static bool is_main(entity_t*);
3898 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3899 * for various problems that occur for multiple definitions
3901 entity_t *record_entity(entity_t *entity, const bool is_definition)
3903 const symbol_t *const symbol = entity->base.symbol;
3904 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3905 const source_position_t *pos = &entity->base.source_position;
3907 /* can happen in error cases */
3911 assert(!entity->base.parent_scope);
3912 assert(current_scope);
3913 entity->base.parent_scope = current_scope;
3915 entity_t *const previous_entity = get_entity(symbol, namespc);
3916 /* pushing the same entity twice will break the stack structure */
3917 assert(previous_entity != entity);
3919 if (entity->kind == ENTITY_FUNCTION) {
3920 type_t *const orig_type = entity->declaration.type;
3921 type_t *const type = skip_typeref(orig_type);
3923 assert(is_type_function(type));
3924 if (type->function.unspecified_parameters &&
3925 previous_entity == NULL &&
3926 !entity->declaration.implicit) {
3927 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3930 if (is_main(entity)) {
3935 if (is_declaration(entity) &&
3936 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3937 current_scope != file_scope &&
3938 !entity->declaration.implicit) {
3939 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3942 if (previous_entity != NULL) {
3943 source_position_t const *const ppos = &previous_entity->base.source_position;
3945 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3946 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3947 assert(previous_entity->kind == ENTITY_PARAMETER);
3948 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3952 if (previous_entity->base.parent_scope == current_scope) {
3953 if (previous_entity->kind != entity->kind) {
3954 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
3955 error_redefined_as_different_kind(pos, previous_entity,
3960 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
3961 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
3964 if (previous_entity->kind == ENTITY_TYPEDEF) {
3965 type_t *const type = skip_typeref(entity->typedefe.type);
3966 type_t *const prev_type
3967 = skip_typeref(previous_entity->typedefe.type);
3968 if (c_mode & _CXX) {
3969 /* C++ allows double typedef if they are identical
3970 * (after skipping typedefs) */
3971 if (type == prev_type)
3974 /* GCC extension: redef in system headers is allowed */
3975 if ((pos->is_system_header || ppos->is_system_header) &&
3976 types_compatible(type, prev_type))
3979 errorf(pos, "redefinition of '%N' (declared %P)",
3984 /* at this point we should have only VARIABLES or FUNCTIONS */
3985 assert(is_declaration(previous_entity) && is_declaration(entity));
3987 declaration_t *const prev_decl = &previous_entity->declaration;
3988 declaration_t *const decl = &entity->declaration;
3990 /* can happen for K&R style declarations */
3991 if (prev_decl->type == NULL &&
3992 previous_entity->kind == ENTITY_PARAMETER &&
3993 entity->kind == ENTITY_PARAMETER) {
3994 prev_decl->type = decl->type;
3995 prev_decl->storage_class = decl->storage_class;
3996 prev_decl->declared_storage_class = decl->declared_storage_class;
3997 prev_decl->modifiers = decl->modifiers;
3998 return previous_entity;
4001 type_t *const type = skip_typeref(decl->type);
4002 type_t *const prev_type = skip_typeref(prev_decl->type);
4004 if (!types_compatible(type, prev_type)) {
4005 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4007 unsigned old_storage_class = prev_decl->storage_class;
4009 if (is_definition &&
4011 !(prev_decl->modifiers & DM_USED) &&
4012 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4013 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4016 storage_class_t new_storage_class = decl->storage_class;
4018 /* pretend no storage class means extern for function
4019 * declarations (except if the previous declaration is neither
4020 * none nor extern) */
4021 if (entity->kind == ENTITY_FUNCTION) {
4022 /* the previous declaration could have unspecified parameters or
4023 * be a typedef, so use the new type */
4024 if (prev_type->function.unspecified_parameters || is_definition)
4025 prev_decl->type = type;
4027 switch (old_storage_class) {
4028 case STORAGE_CLASS_NONE:
4029 old_storage_class = STORAGE_CLASS_EXTERN;
4032 case STORAGE_CLASS_EXTERN:
4033 if (is_definition) {
4034 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4035 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4037 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4038 new_storage_class = STORAGE_CLASS_EXTERN;
4045 } else if (is_type_incomplete(prev_type)) {
4046 prev_decl->type = type;
4049 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4050 new_storage_class == STORAGE_CLASS_EXTERN) {
4052 warn_redundant_declaration: ;
4054 = has_new_attributes(prev_decl->attributes,
4056 if (has_new_attrs) {
4057 merge_in_attributes(decl, prev_decl->attributes);
4058 } else if (!is_definition &&
4059 is_type_valid(prev_type) &&
4060 !pos->is_system_header) {
4061 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%N' (declared %P)", entity, ppos);
4063 } else if (current_function == NULL) {
4064 if (old_storage_class != STORAGE_CLASS_STATIC &&
4065 new_storage_class == STORAGE_CLASS_STATIC) {
4066 errorf(pos, "static declaration of '%N' follows non-static declaration (declared %P)", entity, ppos);
4067 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4068 prev_decl->storage_class = STORAGE_CLASS_NONE;
4069 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4071 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4073 goto error_redeclaration;
4074 goto warn_redundant_declaration;
4076 } else if (is_type_valid(prev_type)) {
4077 if (old_storage_class == new_storage_class) {
4078 error_redeclaration:
4079 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4081 errorf(pos, "redeclaration of '%N' with different linkage (declared %P)", entity, ppos);
4086 prev_decl->modifiers |= decl->modifiers;
4087 if (entity->kind == ENTITY_FUNCTION) {
4088 previous_entity->function.is_inline |= entity->function.is_inline;
4090 return previous_entity;
4094 if (is_warn_on(why = WARN_SHADOW) ||
4095 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4096 char const *const what = get_entity_kind_name(previous_entity->kind);
4097 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4101 if (entity->kind == ENTITY_FUNCTION) {
4102 if (is_definition &&
4103 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4105 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4106 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4108 goto warn_missing_declaration;
4111 } else if (entity->kind == ENTITY_VARIABLE) {
4112 if (current_scope == file_scope &&
4113 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4114 !entity->declaration.implicit) {
4115 warn_missing_declaration:
4116 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4121 environment_push(entity);
4122 append_entity(current_scope, entity);
4127 static void parser_error_multiple_definition(entity_t *entity,
4128 const source_position_t *source_position)
4130 errorf(source_position, "redefinition of '%N' (declared %P)", entity, &entity->base.source_position);
4133 static bool is_declaration_specifier(const token_t *token)
4135 switch (token->kind) {
4139 return is_typedef_symbol(token->base.symbol);
4146 static void parse_init_declarator_rest(entity_t *entity)
4148 type_t *orig_type = type_error_type;
4150 if (entity->base.kind == ENTITY_TYPEDEF) {
4151 source_position_t const *const pos = &entity->base.source_position;
4152 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4154 assert(is_declaration(entity));
4155 orig_type = entity->declaration.type;
4158 type_t *type = skip_typeref(orig_type);
4160 if (entity->kind == ENTITY_VARIABLE
4161 && entity->variable.initializer != NULL) {
4162 parser_error_multiple_definition(entity, HERE);
4166 declaration_t *const declaration = &entity->declaration;
4167 bool must_be_constant = false;
4168 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4169 entity->base.parent_scope == file_scope) {
4170 must_be_constant = true;
4173 if (is_type_function(type)) {
4174 source_position_t const *const pos = &entity->base.source_position;
4175 errorf(pos, "'%N' is initialized like a variable", entity);
4176 orig_type = type_error_type;
4179 parse_initializer_env_t env;
4180 env.type = orig_type;
4181 env.must_be_constant = must_be_constant;
4182 env.entity = entity;
4184 initializer_t *initializer = parse_initializer(&env);
4186 if (entity->kind == ENTITY_VARIABLE) {
4187 /* §6.7.5:22 array initializers for arrays with unknown size
4188 * determine the array type size */
4189 declaration->type = env.type;
4190 entity->variable.initializer = initializer;
4194 /* parse rest of a declaration without any declarator */
4195 static void parse_anonymous_declaration_rest(
4196 const declaration_specifiers_t *specifiers)
4199 anonymous_entity = NULL;
4201 source_position_t const *const pos = &specifiers->source_position;
4202 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4203 specifiers->thread_local) {
4204 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4207 type_t *type = specifiers->type;
4208 switch (type->kind) {
4209 case TYPE_COMPOUND_STRUCT:
4210 case TYPE_COMPOUND_UNION: {
4211 if (type->compound.compound->base.symbol == NULL) {
4212 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4221 warningf(WARN_OTHER, pos, "empty declaration");
4226 static void check_variable_type_complete(entity_t *ent)
4228 if (ent->kind != ENTITY_VARIABLE)
4231 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4232 * type for the object shall be complete [...] */
4233 declaration_t *decl = &ent->declaration;
4234 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4235 decl->storage_class == STORAGE_CLASS_STATIC)
4238 type_t *const type = skip_typeref(decl->type);
4239 if (!is_type_incomplete(type))
4242 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4243 * are given length one. */
4244 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4245 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4249 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4253 static void parse_declaration_rest(entity_t *ndeclaration,
4254 const declaration_specifiers_t *specifiers,
4255 parsed_declaration_func finished_declaration,
4256 declarator_flags_t flags)
4258 add_anchor_token(';');
4259 add_anchor_token(',');
4261 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4263 if (token.kind == '=') {
4264 parse_init_declarator_rest(entity);
4265 } else if (entity->kind == ENTITY_VARIABLE) {
4266 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4267 * [...] where the extern specifier is explicitly used. */
4268 declaration_t *decl = &entity->declaration;
4269 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4270 is_type_reference(skip_typeref(decl->type))) {
4271 source_position_t const *const pos = &entity->base.source_position;
4272 errorf(pos, "reference '%#N' must be initialized", entity);
4276 check_variable_type_complete(entity);
4281 add_anchor_token('=');
4282 ndeclaration = parse_declarator(specifiers, flags);
4283 rem_anchor_token('=');
4285 rem_anchor_token(',');
4286 rem_anchor_token(';');
4289 anonymous_entity = NULL;
4292 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4294 symbol_t *symbol = entity->base.symbol;
4298 assert(entity->base.namespc == NAMESPACE_NORMAL);
4299 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4300 if (previous_entity == NULL
4301 || previous_entity->base.parent_scope != current_scope) {
4302 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4307 if (is_definition) {
4308 errorf(HERE, "'%N' is initialised", entity);
4311 return record_entity(entity, false);
4314 static void parse_declaration(parsed_declaration_func finished_declaration,
4315 declarator_flags_t flags)
4317 add_anchor_token(';');
4318 declaration_specifiers_t specifiers;
4319 parse_declaration_specifiers(&specifiers);
4320 rem_anchor_token(';');
4322 if (token.kind == ';') {
4323 parse_anonymous_declaration_rest(&specifiers);
4325 entity_t *entity = parse_declarator(&specifiers, flags);
4326 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4331 static type_t *get_default_promoted_type(type_t *orig_type)
4333 type_t *result = orig_type;
4335 type_t *type = skip_typeref(orig_type);
4336 if (is_type_integer(type)) {
4337 result = promote_integer(type);
4338 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4339 result = type_double;
4345 static void parse_kr_declaration_list(entity_t *entity)
4347 if (entity->kind != ENTITY_FUNCTION)
4350 type_t *type = skip_typeref(entity->declaration.type);
4351 assert(is_type_function(type));
4352 if (!type->function.kr_style_parameters)
4355 add_anchor_token('{');
4357 PUSH_SCOPE(&entity->function.parameters);
4359 entity_t *parameter = entity->function.parameters.entities;
4360 for ( ; parameter != NULL; parameter = parameter->base.next) {
4361 assert(parameter->base.parent_scope == NULL);
4362 parameter->base.parent_scope = current_scope;
4363 environment_push(parameter);
4366 /* parse declaration list */
4368 switch (token.kind) {
4370 /* This covers symbols, which are no type, too, and results in
4371 * better error messages. The typical cases are misspelled type
4372 * names and missing includes. */
4374 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4384 /* update function type */
4385 type_t *new_type = duplicate_type(type);
4387 function_parameter_t *parameters = NULL;
4388 function_parameter_t **anchor = ¶meters;
4390 /* did we have an earlier prototype? */
4391 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4392 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4395 function_parameter_t *proto_parameter = NULL;
4396 if (proto_type != NULL) {
4397 type_t *proto_type_type = proto_type->declaration.type;
4398 proto_parameter = proto_type_type->function.parameters;
4399 /* If a K&R function definition has a variadic prototype earlier, then
4400 * make the function definition variadic, too. This should conform to
4401 * §6.7.5.3:15 and §6.9.1:8. */
4402 new_type->function.variadic = proto_type_type->function.variadic;
4404 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4406 new_type->function.unspecified_parameters = true;
4409 bool need_incompatible_warning = false;
4410 parameter = entity->function.parameters.entities;
4411 for (; parameter != NULL; parameter = parameter->base.next,
4413 proto_parameter == NULL ? NULL : proto_parameter->next) {
4414 if (parameter->kind != ENTITY_PARAMETER)
4417 type_t *parameter_type = parameter->declaration.type;
4418 if (parameter_type == NULL) {
4419 source_position_t const* const pos = ¶meter->base.source_position;
4421 errorf(pos, "no type specified for function '%N'", parameter);
4422 parameter_type = type_error_type;
4424 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4425 parameter_type = type_int;
4427 parameter->declaration.type = parameter_type;
4430 semantic_parameter_incomplete(parameter);
4432 /* we need the default promoted types for the function type */
4433 type_t *not_promoted = parameter_type;
4434 parameter_type = get_default_promoted_type(parameter_type);
4436 /* gcc special: if the type of the prototype matches the unpromoted
4437 * type don't promote */
4438 if (!strict_mode && proto_parameter != NULL) {
4439 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4440 type_t *promo_skip = skip_typeref(parameter_type);
4441 type_t *param_skip = skip_typeref(not_promoted);
4442 if (!types_compatible(proto_p_type, promo_skip)
4443 && types_compatible(proto_p_type, param_skip)) {
4445 need_incompatible_warning = true;
4446 parameter_type = not_promoted;
4449 function_parameter_t *const function_parameter
4450 = allocate_parameter(parameter_type);
4452 *anchor = function_parameter;
4453 anchor = &function_parameter->next;
4456 new_type->function.parameters = parameters;
4457 new_type = identify_new_type(new_type);
4459 if (need_incompatible_warning) {
4460 symbol_t const *const sym = entity->base.symbol;
4461 source_position_t const *const pos = &entity->base.source_position;
4462 source_position_t const *const ppos = &proto_type->base.source_position;
4463 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4465 entity->declaration.type = new_type;
4467 rem_anchor_token('{');
4470 static bool first_err = true;
4473 * When called with first_err set, prints the name of the current function,
4476 static void print_in_function(void)
4480 char const *const file = current_function->base.base.source_position.input_name;
4481 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4486 * Check if all labels are defined in the current function.
4487 * Check if all labels are used in the current function.
4489 static void check_labels(void)
4491 for (const goto_statement_t *goto_statement = goto_first;
4492 goto_statement != NULL;
4493 goto_statement = goto_statement->next) {
4494 label_t *label = goto_statement->label;
4495 if (label->base.source_position.input_name == NULL) {
4496 print_in_function();
4497 source_position_t const *const pos = &goto_statement->base.source_position;
4498 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4502 if (is_warn_on(WARN_UNUSED_LABEL)) {
4503 for (const label_statement_t *label_statement = label_first;
4504 label_statement != NULL;
4505 label_statement = label_statement->next) {
4506 label_t *label = label_statement->label;
4508 if (! label->used) {
4509 print_in_function();
4510 source_position_t const *const pos = &label_statement->base.source_position;
4511 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4517 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4519 entity_t const *const end = last != NULL ? last->base.next : NULL;
4520 for (; entity != end; entity = entity->base.next) {
4521 if (!is_declaration(entity))
4524 declaration_t *declaration = &entity->declaration;
4525 if (declaration->implicit)
4528 if (!declaration->used) {
4529 print_in_function();
4530 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4531 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4532 print_in_function();
4533 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4538 static void check_unused_variables(statement_t *const stmt, void *const env)
4542 switch (stmt->kind) {
4543 case STATEMENT_DECLARATION: {
4544 declaration_statement_t const *const decls = &stmt->declaration;
4545 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4550 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4559 * Check declarations of current_function for unused entities.
4561 static void check_declarations(void)
4563 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4564 const scope_t *scope = ¤t_function->parameters;
4565 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4567 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4568 walk_statements(current_function->statement, check_unused_variables,
4573 static int determine_truth(expression_t const* const cond)
4576 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4577 fold_constant_to_bool(cond) ? 1 :
4581 static void check_reachable(statement_t *);
4582 static bool reaches_end;
4584 static bool expression_returns(expression_t const *const expr)
4586 switch (expr->kind) {
4588 expression_t const *const func = expr->call.function;
4589 type_t const *const type = skip_typeref(func->base.type);
4590 if (type->kind == TYPE_POINTER) {
4591 type_t const *const points_to
4592 = skip_typeref(type->pointer.points_to);
4593 if (points_to->kind == TYPE_FUNCTION
4594 && points_to->function.modifiers & DM_NORETURN)
4598 if (!expression_returns(func))
4601 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4602 if (!expression_returns(arg->expression))
4609 case EXPR_REFERENCE:
4610 case EXPR_ENUM_CONSTANT:
4611 case EXPR_LITERAL_CASES:
4612 case EXPR_LITERAL_CHARACTER:
4613 case EXPR_STRING_LITERAL:
4614 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4615 case EXPR_LABEL_ADDRESS:
4616 case EXPR_CLASSIFY_TYPE:
4617 case EXPR_SIZEOF: // TODO handle obscure VLA case
4620 case EXPR_BUILTIN_CONSTANT_P:
4621 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4626 case EXPR_STATEMENT: {
4627 bool old_reaches_end = reaches_end;
4628 reaches_end = false;
4629 check_reachable(expr->statement.statement);
4630 bool returns = reaches_end;
4631 reaches_end = old_reaches_end;
4635 case EXPR_CONDITIONAL:
4636 // TODO handle constant expression
4638 if (!expression_returns(expr->conditional.condition))
4641 if (expr->conditional.true_expression != NULL
4642 && expression_returns(expr->conditional.true_expression))
4645 return expression_returns(expr->conditional.false_expression);
4648 return expression_returns(expr->select.compound);
4650 case EXPR_ARRAY_ACCESS:
4652 expression_returns(expr->array_access.array_ref) &&
4653 expression_returns(expr->array_access.index);
4656 return expression_returns(expr->va_starte.ap);
4659 return expression_returns(expr->va_arge.ap);
4662 return expression_returns(expr->va_copye.src);
4664 case EXPR_UNARY_CASES_MANDATORY:
4665 return expression_returns(expr->unary.value);
4667 case EXPR_UNARY_THROW:
4670 case EXPR_BINARY_CASES:
4671 // TODO handle constant lhs of && and ||
4673 expression_returns(expr->binary.left) &&
4674 expression_returns(expr->binary.right);
4677 panic("unhandled expression");
4680 static bool initializer_returns(initializer_t const *const init)
4682 switch (init->kind) {
4683 case INITIALIZER_VALUE:
4684 return expression_returns(init->value.value);
4686 case INITIALIZER_LIST: {
4687 initializer_t * const* i = init->list.initializers;
4688 initializer_t * const* const end = i + init->list.len;
4689 bool returns = true;
4690 for (; i != end; ++i) {
4691 if (!initializer_returns(*i))
4697 case INITIALIZER_STRING:
4698 case INITIALIZER_DESIGNATOR: // designators have no payload
4701 panic("unhandled initializer");
4704 static bool noreturn_candidate;
4706 static void check_reachable(statement_t *const stmt)
4708 if (stmt->base.reachable)
4710 if (stmt->kind != STATEMENT_DO_WHILE)
4711 stmt->base.reachable = true;
4713 statement_t *last = stmt;
4715 switch (stmt->kind) {
4716 case STATEMENT_ERROR:
4717 case STATEMENT_EMPTY:
4719 next = stmt->base.next;
4722 case STATEMENT_DECLARATION: {
4723 declaration_statement_t const *const decl = &stmt->declaration;
4724 entity_t const * ent = decl->declarations_begin;
4725 entity_t const *const last_decl = decl->declarations_end;
4727 for (;; ent = ent->base.next) {
4728 if (ent->kind == ENTITY_VARIABLE &&
4729 ent->variable.initializer != NULL &&
4730 !initializer_returns(ent->variable.initializer)) {
4733 if (ent == last_decl)
4737 next = stmt->base.next;
4741 case STATEMENT_COMPOUND:
4742 next = stmt->compound.statements;
4744 next = stmt->base.next;
4747 case STATEMENT_RETURN: {
4748 expression_t const *const val = stmt->returns.value;
4749 if (val == NULL || expression_returns(val))
4750 noreturn_candidate = false;
4754 case STATEMENT_IF: {
4755 if_statement_t const *const ifs = &stmt->ifs;
4756 expression_t const *const cond = ifs->condition;
4758 if (!expression_returns(cond))
4761 int const val = determine_truth(cond);
4764 check_reachable(ifs->true_statement);
4769 if (ifs->false_statement != NULL) {
4770 check_reachable(ifs->false_statement);
4774 next = stmt->base.next;
4778 case STATEMENT_SWITCH: {
4779 switch_statement_t const *const switchs = &stmt->switchs;
4780 expression_t const *const expr = switchs->expression;
4782 if (!expression_returns(expr))
4785 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4786 long const val = fold_constant_to_int(expr);
4787 case_label_statement_t * defaults = NULL;
4788 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4789 if (i->expression == NULL) {
4794 if (i->first_case <= val && val <= i->last_case) {
4795 check_reachable((statement_t*)i);
4800 if (defaults != NULL) {
4801 check_reachable((statement_t*)defaults);
4805 bool has_default = false;
4806 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4807 if (i->expression == NULL)
4810 check_reachable((statement_t*)i);
4817 next = stmt->base.next;
4821 case STATEMENT_EXPRESSION: {
4822 /* Check for noreturn function call */
4823 expression_t const *const expr = stmt->expression.expression;
4824 if (!expression_returns(expr))
4827 next = stmt->base.next;
4831 case STATEMENT_CONTINUE:
4832 for (statement_t *parent = stmt;;) {
4833 parent = parent->base.parent;
4834 if (parent == NULL) /* continue not within loop */
4838 switch (parent->kind) {
4839 case STATEMENT_WHILE: goto continue_while;
4840 case STATEMENT_DO_WHILE: goto continue_do_while;
4841 case STATEMENT_FOR: goto continue_for;
4847 case STATEMENT_BREAK:
4848 for (statement_t *parent = stmt;;) {
4849 parent = parent->base.parent;
4850 if (parent == NULL) /* break not within loop/switch */
4853 switch (parent->kind) {
4854 case STATEMENT_SWITCH:
4855 case STATEMENT_WHILE:
4856 case STATEMENT_DO_WHILE:
4859 next = parent->base.next;
4860 goto found_break_parent;
4868 case STATEMENT_COMPUTED_GOTO: {
4869 if (!expression_returns(stmt->computed_goto.expression))
4872 statement_t *parent = stmt->base.parent;
4873 if (parent == NULL) /* top level goto */
4879 case STATEMENT_GOTO:
4880 next = stmt->gotos.label->statement;
4881 if (next == NULL) /* missing label */
4885 case STATEMENT_LABEL:
4886 next = stmt->label.statement;
4889 case STATEMENT_CASE_LABEL:
4890 next = stmt->case_label.statement;
4893 case STATEMENT_WHILE: {
4894 while_statement_t const *const whiles = &stmt->whiles;
4895 expression_t const *const cond = whiles->condition;
4897 if (!expression_returns(cond))
4900 int const val = determine_truth(cond);
4903 check_reachable(whiles->body);
4908 next = stmt->base.next;
4912 case STATEMENT_DO_WHILE:
4913 next = stmt->do_while.body;
4916 case STATEMENT_FOR: {
4917 for_statement_t *const fors = &stmt->fors;
4919 if (fors->condition_reachable)
4921 fors->condition_reachable = true;
4923 expression_t const *const cond = fors->condition;
4928 } else if (expression_returns(cond)) {
4929 val = determine_truth(cond);
4935 check_reachable(fors->body);
4940 next = stmt->base.next;
4944 case STATEMENT_MS_TRY: {
4945 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4946 check_reachable(ms_try->try_statement);
4947 next = ms_try->final_statement;
4951 case STATEMENT_LEAVE: {
4952 statement_t *parent = stmt;
4954 parent = parent->base.parent;
4955 if (parent == NULL) /* __leave not within __try */
4958 if (parent->kind == STATEMENT_MS_TRY) {
4960 next = parent->ms_try.final_statement;
4968 panic("invalid statement kind");
4971 while (next == NULL) {
4972 next = last->base.parent;
4974 noreturn_candidate = false;
4976 type_t *const type = skip_typeref(current_function->base.type);
4977 assert(is_type_function(type));
4978 type_t *const ret = skip_typeref(type->function.return_type);
4979 if (!is_type_void(ret) &&
4980 is_type_valid(ret) &&
4981 !is_main(current_entity)) {
4982 source_position_t const *const pos = &stmt->base.source_position;
4983 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
4988 switch (next->kind) {
4989 case STATEMENT_ERROR:
4990 case STATEMENT_EMPTY:
4991 case STATEMENT_DECLARATION:
4992 case STATEMENT_EXPRESSION:
4994 case STATEMENT_RETURN:
4995 case STATEMENT_CONTINUE:
4996 case STATEMENT_BREAK:
4997 case STATEMENT_COMPUTED_GOTO:
4998 case STATEMENT_GOTO:
4999 case STATEMENT_LEAVE:
5000 panic("invalid control flow in function");
5002 case STATEMENT_COMPOUND:
5003 if (next->compound.stmt_expr) {
5009 case STATEMENT_SWITCH:
5010 case STATEMENT_LABEL:
5011 case STATEMENT_CASE_LABEL:
5013 next = next->base.next;
5016 case STATEMENT_WHILE: {
5018 if (next->base.reachable)
5020 next->base.reachable = true;
5022 while_statement_t const *const whiles = &next->whiles;
5023 expression_t const *const cond = whiles->condition;
5025 if (!expression_returns(cond))
5028 int const val = determine_truth(cond);
5031 check_reachable(whiles->body);
5037 next = next->base.next;
5041 case STATEMENT_DO_WHILE: {
5043 if (next->base.reachable)
5045 next->base.reachable = true;
5047 do_while_statement_t const *const dw = &next->do_while;
5048 expression_t const *const cond = dw->condition;
5050 if (!expression_returns(cond))
5053 int const val = determine_truth(cond);
5056 check_reachable(dw->body);
5062 next = next->base.next;
5066 case STATEMENT_FOR: {
5068 for_statement_t *const fors = &next->fors;
5070 fors->step_reachable = true;
5072 if (fors->condition_reachable)
5074 fors->condition_reachable = true;
5076 expression_t const *const cond = fors->condition;
5081 } else if (expression_returns(cond)) {
5082 val = determine_truth(cond);
5088 check_reachable(fors->body);
5094 next = next->base.next;
5098 case STATEMENT_MS_TRY:
5100 next = next->ms_try.final_statement;
5105 check_reachable(next);
5108 static void check_unreachable(statement_t* const stmt, void *const env)
5112 switch (stmt->kind) {
5113 case STATEMENT_DO_WHILE:
5114 if (!stmt->base.reachable) {
5115 expression_t const *const cond = stmt->do_while.condition;
5116 if (determine_truth(cond) >= 0) {
5117 source_position_t const *const pos = &cond->base.source_position;
5118 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5123 case STATEMENT_FOR: {
5124 for_statement_t const* const fors = &stmt->fors;
5126 // if init and step are unreachable, cond is unreachable, too
5127 if (!stmt->base.reachable && !fors->step_reachable) {
5128 goto warn_unreachable;
5130 if (!stmt->base.reachable && fors->initialisation != NULL) {
5131 source_position_t const *const pos = &fors->initialisation->base.source_position;
5132 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5135 if (!fors->condition_reachable && fors->condition != NULL) {
5136 source_position_t const *const pos = &fors->condition->base.source_position;
5137 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5140 if (!fors->step_reachable && fors->step != NULL) {
5141 source_position_t const *const pos = &fors->step->base.source_position;
5142 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5148 case STATEMENT_COMPOUND:
5149 if (stmt->compound.statements != NULL)
5151 goto warn_unreachable;
5153 case STATEMENT_DECLARATION: {
5154 /* Only warn if there is at least one declarator with an initializer.
5155 * This typically occurs in switch statements. */
5156 declaration_statement_t const *const decl = &stmt->declaration;
5157 entity_t const * ent = decl->declarations_begin;
5158 entity_t const *const last = decl->declarations_end;
5160 for (;; ent = ent->base.next) {
5161 if (ent->kind == ENTITY_VARIABLE &&
5162 ent->variable.initializer != NULL) {
5163 goto warn_unreachable;
5173 if (!stmt->base.reachable) {
5174 source_position_t const *const pos = &stmt->base.source_position;
5175 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5181 static bool is_main(entity_t *entity)
5183 static symbol_t *sym_main = NULL;
5184 if (sym_main == NULL) {
5185 sym_main = symbol_table_insert("main");
5188 if (entity->base.symbol != sym_main)
5190 /* must be in outermost scope */
5191 if (entity->base.parent_scope != file_scope)
5197 static void prepare_main_collect2(entity_t*);
5199 static void parse_external_declaration(void)
5201 /* function-definitions and declarations both start with declaration
5203 add_anchor_token(';');
5204 declaration_specifiers_t specifiers;
5205 parse_declaration_specifiers(&specifiers);
5206 rem_anchor_token(';');
5208 /* must be a declaration */
5209 if (token.kind == ';') {
5210 parse_anonymous_declaration_rest(&specifiers);
5214 add_anchor_token(',');
5215 add_anchor_token('=');
5216 add_anchor_token(';');
5217 add_anchor_token('{');
5219 /* declarator is common to both function-definitions and declarations */
5220 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5222 rem_anchor_token('{');
5223 rem_anchor_token(';');
5224 rem_anchor_token('=');
5225 rem_anchor_token(',');
5227 /* must be a declaration */
5228 switch (token.kind) {
5232 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5237 /* must be a function definition */
5238 parse_kr_declaration_list(ndeclaration);
5240 if (token.kind != '{') {
5241 parse_error_expected("while parsing function definition", '{', NULL);
5242 eat_until_matching_token(';');
5246 assert(is_declaration(ndeclaration));
5247 type_t *const orig_type = ndeclaration->declaration.type;
5248 type_t * type = skip_typeref(orig_type);
5250 if (!is_type_function(type)) {
5251 if (is_type_valid(type)) {
5252 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5258 source_position_t const *const pos = &ndeclaration->base.source_position;
5259 if (is_typeref(orig_type)) {
5261 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5264 if (is_type_compound(skip_typeref(type->function.return_type))) {
5265 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5267 if (type->function.unspecified_parameters) {
5268 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5270 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5273 /* §6.7.5.3:14 a function definition with () means no
5274 * parameters (and not unspecified parameters) */
5275 if (type->function.unspecified_parameters &&
5276 type->function.parameters == NULL) {
5277 type_t *copy = duplicate_type(type);
5278 copy->function.unspecified_parameters = false;
5279 type = identify_new_type(copy);
5281 ndeclaration->declaration.type = type;
5284 entity_t *const entity = record_entity(ndeclaration, true);
5285 assert(entity->kind == ENTITY_FUNCTION);
5286 assert(ndeclaration->kind == ENTITY_FUNCTION);
5288 function_t *const function = &entity->function;
5289 if (ndeclaration != entity) {
5290 function->parameters = ndeclaration->function.parameters;
5293 PUSH_SCOPE(&function->parameters);
5295 entity_t *parameter = function->parameters.entities;
5296 for (; parameter != NULL; parameter = parameter->base.next) {
5297 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5298 parameter->base.parent_scope = current_scope;
5300 assert(parameter->base.parent_scope == NULL
5301 || parameter->base.parent_scope == current_scope);
5302 parameter->base.parent_scope = current_scope;
5303 if (parameter->base.symbol == NULL) {
5304 errorf(¶meter->base.source_position, "parameter name omitted");
5307 environment_push(parameter);
5310 if (function->statement != NULL) {
5311 parser_error_multiple_definition(entity, HERE);
5314 /* parse function body */
5315 int label_stack_top = label_top();
5316 function_t *old_current_function = current_function;
5317 current_function = function;
5318 PUSH_CURRENT_ENTITY(entity);
5322 goto_anchor = &goto_first;
5324 label_anchor = &label_first;
5326 statement_t *const body = parse_compound_statement(false);
5327 function->statement = body;
5330 check_declarations();
5331 if (is_warn_on(WARN_RETURN_TYPE) ||
5332 is_warn_on(WARN_UNREACHABLE_CODE) ||
5333 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5334 noreturn_candidate = true;
5335 check_reachable(body);
5336 if (is_warn_on(WARN_UNREACHABLE_CODE))
5337 walk_statements(body, check_unreachable, NULL);
5338 if (noreturn_candidate &&
5339 !(function->base.modifiers & DM_NORETURN)) {
5340 source_position_t const *const pos = &body->base.source_position;
5341 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5345 if (is_main(entity)) {
5346 /* Force main to C linkage. */
5347 type_t *const type = entity->declaration.type;
5348 assert(is_type_function(type));
5349 if (type->function.linkage != LINKAGE_C) {
5350 type_t *new_type = duplicate_type(type);
5351 new_type->function.linkage = LINKAGE_C;
5352 entity->declaration.type = identify_new_type(new_type);
5355 if (enable_main_collect2_hack)
5356 prepare_main_collect2(entity);
5359 POP_CURRENT_ENTITY();
5361 assert(current_function == function);
5362 current_function = old_current_function;
5363 label_pop_to(label_stack_top);
5369 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5371 entity_t *iter = compound->members.entities;
5372 for (; iter != NULL; iter = iter->base.next) {
5373 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5376 if (iter->base.symbol == symbol) {
5378 } else if (iter->base.symbol == NULL) {
5379 /* search in anonymous structs and unions */
5380 type_t *type = skip_typeref(iter->declaration.type);
5381 if (is_type_compound(type)) {
5382 if (find_compound_entry(type->compound.compound, symbol)
5393 static void check_deprecated(const source_position_t *source_position,
5394 const entity_t *entity)
5396 if (!is_declaration(entity))
5398 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5401 source_position_t const *const epos = &entity->base.source_position;
5402 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5404 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5406 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5411 static expression_t *create_select(const source_position_t *pos,
5413 type_qualifiers_t qualifiers,
5416 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5418 check_deprecated(pos, entry);
5420 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5421 select->select.compound = addr;
5422 select->select.compound_entry = entry;
5424 type_t *entry_type = entry->declaration.type;
5425 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5427 /* bitfields need special treatment */
5428 if (entry->compound_member.bitfield) {
5429 unsigned bit_size = entry->compound_member.bit_size;
5430 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5431 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5432 res_type = type_int;
5436 /* we always do the auto-type conversions; the & and sizeof parser contains
5437 * code to revert this! */
5438 select->base.type = automatic_type_conversion(res_type);
5445 * Find entry with symbol in compound. Search anonymous structs and unions and
5446 * creates implicit select expressions for them.
5447 * Returns the adress for the innermost compound.
5449 static expression_t *find_create_select(const source_position_t *pos,
5451 type_qualifiers_t qualifiers,
5452 compound_t *compound, symbol_t *symbol)
5454 entity_t *iter = compound->members.entities;
5455 for (; iter != NULL; iter = iter->base.next) {
5456 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5459 symbol_t *iter_symbol = iter->base.symbol;
5460 if (iter_symbol == NULL) {
5461 type_t *type = iter->declaration.type;
5462 if (!is_type_compound(type))
5465 compound_t *sub_compound = type->compound.compound;
5467 if (find_compound_entry(sub_compound, symbol) == NULL)
5470 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5471 sub_addr->base.source_position = *pos;
5472 sub_addr->base.implicit = true;
5473 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5477 if (iter_symbol == symbol) {
5478 return create_select(pos, addr, qualifiers, iter);
5485 static void parse_bitfield_member(entity_t *entity)
5489 expression_t *size = parse_constant_expression();
5492 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5493 type_t *type = entity->declaration.type;
5494 if (!is_type_integer(skip_typeref(type))) {
5495 errorf(HERE, "bitfield base type '%T' is not an integer type",
5499 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5500 /* error already reported by parse_constant_expression */
5501 size_long = get_type_size(type) * 8;
5503 size_long = fold_constant_to_int(size);
5505 const symbol_t *symbol = entity->base.symbol;
5506 const symbol_t *user_symbol
5507 = symbol == NULL ? sym_anonymous : symbol;
5508 unsigned bit_size = get_type_size(type) * 8;
5509 if (size_long < 0) {
5510 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5511 } else if (size_long == 0 && symbol != NULL) {
5512 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5513 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5514 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5517 /* hope that people don't invent crazy types with more bits
5518 * than our struct can hold */
5520 (1 << sizeof(entity->compound_member.bit_size)*8));
5524 entity->compound_member.bitfield = true;
5525 entity->compound_member.bit_size = (unsigned char)size_long;
5528 static void parse_compound_declarators(compound_t *compound,
5529 const declaration_specifiers_t *specifiers)
5531 add_anchor_token(';');
5532 add_anchor_token(',');
5536 if (token.kind == ':') {
5537 /* anonymous bitfield */
5538 type_t *type = specifiers->type;
5539 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5540 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5541 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5542 entity->declaration.type = type;
5544 parse_bitfield_member(entity);
5546 attribute_t *attributes = parse_attributes(NULL);
5547 attribute_t **anchor = &attributes;
5548 while (*anchor != NULL)
5549 anchor = &(*anchor)->next;
5550 *anchor = specifiers->attributes;
5551 if (attributes != NULL) {
5552 handle_entity_attributes(attributes, entity);
5554 entity->declaration.attributes = attributes;
5556 append_entity(&compound->members, entity);
5558 entity = parse_declarator(specifiers,
5559 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5560 source_position_t const *const pos = &entity->base.source_position;
5561 if (entity->kind == ENTITY_TYPEDEF) {
5562 errorf(pos, "typedef not allowed as compound member");
5564 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5566 /* make sure we don't define a symbol multiple times */
5567 symbol_t *symbol = entity->base.symbol;
5568 if (symbol != NULL) {
5569 entity_t *prev = find_compound_entry(compound, symbol);
5571 source_position_t const *const ppos = &prev->base.source_position;
5572 errorf(pos, "multiple declarations of '%N' (declared %P)", entity, ppos);
5576 if (token.kind == ':') {
5577 parse_bitfield_member(entity);
5579 attribute_t *attributes = parse_attributes(NULL);
5580 handle_entity_attributes(attributes, entity);
5582 type_t *orig_type = entity->declaration.type;
5583 type_t *type = skip_typeref(orig_type);
5584 if (is_type_function(type)) {
5585 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5586 } else if (is_type_incomplete(type)) {
5587 /* §6.7.2.1:16 flexible array member */
5588 if (!is_type_array(type) ||
5589 token.kind != ';' ||
5590 look_ahead(1)->kind != '}') {
5591 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5592 } else if (compound->members.entities == NULL) {
5593 errorf(pos, "flexible array member in otherwise empty struct");
5598 append_entity(&compound->members, entity);
5601 } while (next_if(','));
5602 rem_anchor_token(',');
5603 rem_anchor_token(';');
5606 anonymous_entity = NULL;
5609 static void parse_compound_type_entries(compound_t *compound)
5612 add_anchor_token('}');
5615 switch (token.kind) {
5617 case T___extension__:
5618 case T_IDENTIFIER: {
5620 declaration_specifiers_t specifiers;
5621 parse_declaration_specifiers(&specifiers);
5622 parse_compound_declarators(compound, &specifiers);
5628 rem_anchor_token('}');
5631 compound->complete = true;
5637 static type_t *parse_typename(void)
5639 declaration_specifiers_t specifiers;
5640 parse_declaration_specifiers(&specifiers);
5641 if (specifiers.storage_class != STORAGE_CLASS_NONE
5642 || specifiers.thread_local) {
5643 /* TODO: improve error message, user does probably not know what a
5644 * storage class is...
5646 errorf(&specifiers.source_position, "typename must not have a storage class");
5649 type_t *result = parse_abstract_declarator(specifiers.type);
5657 typedef expression_t* (*parse_expression_function)(void);
5658 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5660 typedef struct expression_parser_function_t expression_parser_function_t;
5661 struct expression_parser_function_t {
5662 parse_expression_function parser;
5663 precedence_t infix_precedence;
5664 parse_expression_infix_function infix_parser;
5667 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5669 static type_t *get_string_type(string_encoding_t const enc)
5671 bool const warn = is_warn_on(WARN_WRITE_STRINGS);
5673 case STRING_ENCODING_CHAR: return warn ? type_const_char_ptr : type_char_ptr;
5674 case STRING_ENCODING_WIDE: return warn ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5676 panic("invalid string encoding");
5680 * Parse a string constant.
5682 static expression_t *parse_string_literal(void)
5684 expression_t *const expr = allocate_expression_zero(EXPR_STRING_LITERAL);
5685 expr->string_literal.value = concat_string_literals();
5686 expr->base.type = get_string_type(expr->string_literal.value.encoding);
5691 * Parse a boolean constant.
5693 static expression_t *parse_boolean_literal(bool value)
5695 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5696 literal->base.type = type_bool;
5697 literal->literal.value.begin = value ? "true" : "false";
5698 literal->literal.value.size = value ? 4 : 5;
5700 eat(value ? T_true : T_false);
5704 static void warn_traditional_suffix(char const *const suffix)
5706 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%s' suffix", suffix);
5709 static void check_integer_suffix(expression_t *const expr, char const *const suffix)
5711 unsigned spec = SPECIFIER_NONE;
5712 char const *c = suffix;
5715 if (*c == 'L' || *c == 'l') {
5716 add = SPECIFIER_LONG;
5718 add |= SPECIFIER_LONG_LONG;
5721 } else if (*c == 'U' || *c == 'u') {
5722 add = SPECIFIER_UNSIGNED;
5735 case SPECIFIER_NONE: type = type_int; break;
5736 case SPECIFIER_LONG: type = type_long; break;
5737 case SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_long_long; break;
5738 case SPECIFIER_UNSIGNED: type = type_unsigned_int; break;
5739 case SPECIFIER_UNSIGNED | SPECIFIER_LONG: type = type_unsigned_long; break;
5740 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_unsigned_long_long; break;
5741 default: panic("inconsistent suffix");
5743 if (spec != SPECIFIER_NONE && spec != SPECIFIER_LONG) {
5744 warn_traditional_suffix(suffix);
5746 expr->base.type = type;
5747 /* Integer type depends on the size of the number and the size
5748 * representable by the types. The backend/codegeneration has to
5749 * determine that. */
5750 determine_literal_type(&expr->literal);
5753 errorf(HERE, "invalid suffix '%s' on integer constant", suffix);
5757 static void check_floatingpoint_suffix(expression_t *const expr, char const *const suffix)
5760 char const *c = suffix;
5763 case 'f': type = type_float; ++c; break;
5765 case 'l': type = type_long_double; ++c; break;
5766 default: type = type_double; break;
5770 expr->base.type = type;
5771 if (suffix[0] != '\0') {
5772 warn_traditional_suffix(suffix);
5775 errorf(HERE, "invalid suffix '%s' on floatingpoint constant", suffix);
5779 static expression_t *parse_number_literal(void)
5781 string_t const *const str = &token.literal.string;
5782 char const * i = str->begin;
5783 unsigned digits = 0;
5784 bool is_float = false;
5786 /* Parse base prefix. */
5790 case 'B': case 'b': base = 2; ++i; break;
5791 case 'X': case 'x': base = 16; ++i; break;
5792 default: base = 8; digits |= 1U << 0; break;
5798 /* Parse mantissa. */
5804 errorf(HERE, "multiple decimal points in %K", &token);
5813 case '0': digit = 0; break;
5814 case '1': digit = 1; break;
5815 case '2': digit = 2; break;
5816 case '3': digit = 3; break;
5817 case '4': digit = 4; break;
5818 case '5': digit = 5; break;
5819 case '6': digit = 6; break;
5820 case '7': digit = 7; break;
5821 case '8': digit = 8; break;
5822 case '9': digit = 9; break;
5823 case 'A': case 'a': digit = 10; break;
5824 case 'B': case 'b': digit = 11; break;
5825 case 'C': case 'c': digit = 12; break;
5826 case 'D': case 'd': digit = 13; break;
5827 case 'E': case 'e': digit = 14; break;
5828 case 'F': case 'f': digit = 15; break;
5830 default: goto done_mantissa;
5833 if (digit >= 10 && base != 16)
5836 digits |= 1U << digit;
5840 /* Parse exponent. */
5844 errorf(HERE, "binary floating %K not allowed", &token);
5849 if (*i == 'E' || *i == 'e') {
5851 goto parse_exponent;
5856 if (*i == 'P' || *i == 'p') {
5861 if (*i == '-' || *i == '+')
5867 } while (isdigit(*i));
5869 errorf(HERE, "exponent of %K has no digits", &token);
5871 } else if (is_float) {
5872 errorf(HERE, "hexadecimal floating %K requires an exponent", &token);
5878 panic("invalid base");
5882 expression_t *const expr = allocate_expression_zero(is_float ? EXPR_LITERAL_FLOATINGPOINT : EXPR_LITERAL_INTEGER);
5883 expr->literal.value = *str;
5887 errorf(HERE, "%K has no digits", &token);
5888 } else if (digits & ~((1U << base) - 1)) {
5889 errorf(HERE, "invalid digit in %K", &token);
5891 expr->literal.suffix = i;
5893 check_floatingpoint_suffix(expr, i);
5895 check_integer_suffix(expr, i);
5905 * Parse a character constant.
5907 static expression_t *parse_character_constant(void)
5909 expression_t *const literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5910 literal->string_literal.value = token.literal.string;
5912 size_t const size = get_string_len(&token.literal.string);
5913 switch (token.literal.string.encoding) {
5914 case STRING_ENCODING_CHAR:
5915 literal->base.type = c_mode & _CXX ? type_char : type_int;
5917 if (!GNU_MODE && !(c_mode & _C99)) {
5918 errorf(HERE, "more than 1 character in character constant");
5920 literal->base.type = type_int;
5921 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5926 case STRING_ENCODING_WIDE:
5927 literal->base.type = type_int;
5929 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5934 eat(T_CHARACTER_CONSTANT);
5938 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5940 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5941 ntype->function.return_type = type_int;
5942 ntype->function.unspecified_parameters = true;
5943 ntype->function.linkage = LINKAGE_C;
5944 type_t *type = identify_new_type(ntype);
5946 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5947 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5948 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5949 entity->declaration.type = type;
5950 entity->declaration.implicit = true;
5952 if (current_scope != NULL)
5953 record_entity(entity, false);
5959 * Performs automatic type cast as described in §6.3.2.1.
5961 * @param orig_type the original type
5963 static type_t *automatic_type_conversion(type_t *orig_type)
5965 type_t *type = skip_typeref(orig_type);
5966 if (is_type_array(type)) {
5967 array_type_t *array_type = &type->array;
5968 type_t *element_type = array_type->element_type;
5969 unsigned qualifiers = array_type->base.qualifiers;
5971 return make_pointer_type(element_type, qualifiers);
5974 if (is_type_function(type)) {
5975 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5982 * reverts the automatic casts of array to pointer types and function
5983 * to function-pointer types as defined §6.3.2.1
5985 type_t *revert_automatic_type_conversion(const expression_t *expression)
5987 switch (expression->kind) {
5988 case EXPR_REFERENCE: {
5989 entity_t *entity = expression->reference.entity;
5990 if (is_declaration(entity)) {
5991 return entity->declaration.type;
5992 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5993 return entity->enum_value.enum_type;
5995 panic("no declaration or enum in reference");
6000 entity_t *entity = expression->select.compound_entry;
6001 assert(is_declaration(entity));
6002 type_t *type = entity->declaration.type;
6003 return get_qualified_type(type, expression->base.type->base.qualifiers);
6006 case EXPR_UNARY_DEREFERENCE: {
6007 const expression_t *const value = expression->unary.value;
6008 type_t *const type = skip_typeref(value->base.type);
6009 if (!is_type_pointer(type))
6010 return type_error_type;
6011 return type->pointer.points_to;
6014 case EXPR_ARRAY_ACCESS: {
6015 const expression_t *array_ref = expression->array_access.array_ref;
6016 type_t *type_left = skip_typeref(array_ref->base.type);
6017 if (!is_type_pointer(type_left))
6018 return type_error_type;
6019 return type_left->pointer.points_to;
6022 case EXPR_STRING_LITERAL: {
6023 size_t const size = get_string_len(&expression->string_literal.value) + 1;
6024 type_t *const elem = get_unqualified_type(expression->base.type->pointer.points_to);
6025 return make_array_type(elem, size, TYPE_QUALIFIER_NONE);
6028 case EXPR_COMPOUND_LITERAL:
6029 return expression->compound_literal.type;
6034 return expression->base.type;
6038 * Find an entity matching a symbol in a scope.
6039 * Uses current scope if scope is NULL
6041 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6042 namespace_tag_t namespc)
6044 if (scope == NULL) {
6045 return get_entity(symbol, namespc);
6048 /* we should optimize here, if scope grows above a certain size we should
6049 construct a hashmap here... */
6050 entity_t *entity = scope->entities;
6051 for ( ; entity != NULL; entity = entity->base.next) {
6052 if (entity->base.symbol == symbol
6053 && (namespace_tag_t)entity->base.namespc == namespc)
6060 static entity_t *parse_qualified_identifier(void)
6062 /* namespace containing the symbol */
6064 source_position_t pos;
6065 const scope_t *lookup_scope = NULL;
6067 if (next_if(T_COLONCOLON))
6068 lookup_scope = &unit->scope;
6072 symbol = expect_identifier("while parsing identifier", &pos);
6074 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6077 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6079 if (!next_if(T_COLONCOLON))
6082 switch (entity->kind) {
6083 case ENTITY_NAMESPACE:
6084 lookup_scope = &entity->namespacee.members;
6089 lookup_scope = &entity->compound.members;
6092 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6093 symbol, get_entity_kind_name(entity->kind));
6095 /* skip further qualifications */
6096 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6098 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6102 if (entity == NULL) {
6103 if (!strict_mode && token.kind == '(') {
6104 /* an implicitly declared function */
6105 entity = create_implicit_function(symbol, &pos);
6106 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of '%N'", entity);
6108 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6109 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6116 static expression_t *parse_reference(void)
6118 source_position_t const pos = *HERE;
6119 entity_t *const entity = parse_qualified_identifier();
6122 if (is_declaration(entity)) {
6123 orig_type = entity->declaration.type;
6124 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6125 orig_type = entity->enum_value.enum_type;
6127 panic("expected declaration or enum value in reference");
6130 /* we always do the auto-type conversions; the & and sizeof parser contains
6131 * code to revert this! */
6132 type_t *type = automatic_type_conversion(orig_type);
6134 expression_kind_t kind = EXPR_REFERENCE;
6135 if (entity->kind == ENTITY_ENUM_VALUE)
6136 kind = EXPR_ENUM_CONSTANT;
6138 expression_t *expression = allocate_expression_zero(kind);
6139 expression->base.source_position = pos;
6140 expression->base.type = type;
6141 expression->reference.entity = entity;
6143 /* this declaration is used */
6144 if (is_declaration(entity)) {
6145 entity->declaration.used = true;
6148 if (entity->base.parent_scope != file_scope
6149 && (current_function != NULL
6150 && entity->base.parent_scope->depth < current_function->parameters.depth)
6151 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6152 /* access of a variable from an outer function */
6153 entity->variable.address_taken = true;
6154 current_function->need_closure = true;
6157 check_deprecated(&pos, entity);
6162 static bool semantic_cast(expression_t *cast)
6164 expression_t *expression = cast->unary.value;
6165 type_t *orig_dest_type = cast->base.type;
6166 type_t *orig_type_right = expression->base.type;
6167 type_t const *dst_type = skip_typeref(orig_dest_type);
6168 type_t const *src_type = skip_typeref(orig_type_right);
6169 source_position_t const *pos = &cast->base.source_position;
6171 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6172 if (is_type_void(dst_type))
6175 /* only integer and pointer can be casted to pointer */
6176 if (is_type_pointer(dst_type) &&
6177 !is_type_pointer(src_type) &&
6178 !is_type_integer(src_type) &&
6179 is_type_valid(src_type)) {
6180 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6184 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6185 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6189 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6190 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6194 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6195 type_t *src = skip_typeref(src_type->pointer.points_to);
6196 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6197 unsigned missing_qualifiers =
6198 src->base.qualifiers & ~dst->base.qualifiers;
6199 if (missing_qualifiers != 0) {
6200 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6206 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6208 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6209 expression->base.source_position = *pos;
6211 parse_initializer_env_t env;
6214 env.must_be_constant = false;
6215 initializer_t *initializer = parse_initializer(&env);
6218 expression->compound_literal.initializer = initializer;
6219 expression->compound_literal.type = type;
6220 expression->base.type = automatic_type_conversion(type);
6226 * Parse a cast expression.
6228 static expression_t *parse_cast(void)
6230 source_position_t const pos = *HERE;
6233 add_anchor_token(')');
6235 type_t *type = parse_typename();
6237 rem_anchor_token(')');
6240 if (token.kind == '{') {
6241 return parse_compound_literal(&pos, type);
6244 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6245 cast->base.source_position = pos;
6247 expression_t *value = parse_subexpression(PREC_CAST);
6248 cast->base.type = type;
6249 cast->unary.value = value;
6251 if (! semantic_cast(cast)) {
6252 /* TODO: record the error in the AST. else it is impossible to detect it */
6259 * Parse a statement expression.
6261 static expression_t *parse_statement_expression(void)
6263 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6266 add_anchor_token(')');
6268 statement_t *statement = parse_compound_statement(true);
6269 statement->compound.stmt_expr = true;
6270 expression->statement.statement = statement;
6272 /* find last statement and use its type */
6273 type_t *type = type_void;
6274 const statement_t *stmt = statement->compound.statements;
6276 while (stmt->base.next != NULL)
6277 stmt = stmt->base.next;
6279 if (stmt->kind == STATEMENT_EXPRESSION) {
6280 type = stmt->expression.expression->base.type;
6283 source_position_t const *const pos = &expression->base.source_position;
6284 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6286 expression->base.type = type;
6288 rem_anchor_token(')');
6294 * Parse a parenthesized expression.
6296 static expression_t *parse_parenthesized_expression(void)
6298 token_t const* const la1 = look_ahead(1);
6299 switch (la1->kind) {
6301 /* gcc extension: a statement expression */
6302 return parse_statement_expression();
6305 if (is_typedef_symbol(la1->base.symbol)) {
6307 return parse_cast();
6312 add_anchor_token(')');
6313 expression_t *result = parse_expression();
6314 result->base.parenthesized = true;
6315 rem_anchor_token(')');
6321 static expression_t *parse_function_keyword(funcname_kind_t const kind)
6323 if (current_function == NULL) {
6324 errorf(HERE, "'%K' used outside of a function", &token);
6327 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6328 expression->base.type = type_char_ptr;
6329 expression->funcname.kind = kind;
6336 static designator_t *parse_designator(void)
6338 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6339 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6340 if (!result->symbol)
6343 designator_t *last_designator = result;
6346 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6347 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6348 if (!designator->symbol)
6351 last_designator->next = designator;
6352 last_designator = designator;
6356 add_anchor_token(']');
6357 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6358 designator->source_position = *HERE;
6359 designator->array_index = parse_expression();
6360 rem_anchor_token(']');
6362 if (designator->array_index == NULL) {
6366 last_designator->next = designator;
6367 last_designator = designator;
6377 * Parse the __builtin_offsetof() expression.
6379 static expression_t *parse_offsetof(void)
6381 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6382 expression->base.type = type_size_t;
6384 eat(T___builtin_offsetof);
6386 add_anchor_token(')');
6387 add_anchor_token(',');
6389 type_t *type = parse_typename();
6390 rem_anchor_token(',');
6392 designator_t *designator = parse_designator();
6393 rem_anchor_token(')');
6396 expression->offsetofe.type = type;
6397 expression->offsetofe.designator = designator;
6400 memset(&path, 0, sizeof(path));
6401 path.top_type = type;
6402 path.path = NEW_ARR_F(type_path_entry_t, 0);
6404 descend_into_subtype(&path);
6406 if (!walk_designator(&path, designator, true)) {
6407 return create_error_expression();
6410 DEL_ARR_F(path.path);
6415 static bool is_last_parameter(expression_t *const param)
6417 if (param->kind == EXPR_REFERENCE) {
6418 entity_t *const entity = param->reference.entity;
6419 if (entity->kind == ENTITY_PARAMETER &&
6420 !entity->base.next &&
6421 entity->base.parent_scope == ¤t_function->parameters) {
6426 if (!is_type_valid(skip_typeref(param->base.type)))
6433 * Parses a __builtin_va_start() expression.
6435 static expression_t *parse_va_start(void)
6437 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6439 eat(T___builtin_va_start);
6441 add_anchor_token(')');
6442 add_anchor_token(',');
6444 expression->va_starte.ap = parse_assignment_expression();
6445 rem_anchor_token(',');
6447 expression_t *const param = parse_assignment_expression();
6448 expression->va_starte.parameter = param;
6449 rem_anchor_token(')');
6452 if (!current_function) {
6453 errorf(&expression->base.source_position, "'va_start' used outside of function");
6454 } else if (!current_function->base.type->function.variadic) {
6455 errorf(&expression->base.source_position, "'va_start' used in non-variadic function");
6456 } else if (!is_last_parameter(param)) {
6457 errorf(¶m->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
6464 * Parses a __builtin_va_arg() expression.
6466 static expression_t *parse_va_arg(void)
6468 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6470 eat(T___builtin_va_arg);
6472 add_anchor_token(')');
6473 add_anchor_token(',');
6476 ap.expression = parse_assignment_expression();
6477 expression->va_arge.ap = ap.expression;
6478 check_call_argument(type_valist, &ap, 1);
6480 rem_anchor_token(',');
6482 expression->base.type = parse_typename();
6483 rem_anchor_token(')');
6490 * Parses a __builtin_va_copy() expression.
6492 static expression_t *parse_va_copy(void)
6494 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6496 eat(T___builtin_va_copy);
6498 add_anchor_token(')');
6499 add_anchor_token(',');
6501 expression_t *dst = parse_assignment_expression();
6502 assign_error_t error = semantic_assign(type_valist, dst);
6503 report_assign_error(error, type_valist, dst, "call argument 1",
6504 &dst->base.source_position);
6505 expression->va_copye.dst = dst;
6507 rem_anchor_token(',');
6510 call_argument_t src;
6511 src.expression = parse_assignment_expression();
6512 check_call_argument(type_valist, &src, 2);
6513 expression->va_copye.src = src.expression;
6514 rem_anchor_token(')');
6521 * Parses a __builtin_constant_p() expression.
6523 static expression_t *parse_builtin_constant(void)
6525 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6527 eat(T___builtin_constant_p);
6529 add_anchor_token(')');
6531 expression->builtin_constant.value = parse_assignment_expression();
6532 rem_anchor_token(')');
6534 expression->base.type = type_int;
6540 * Parses a __builtin_types_compatible_p() expression.
6542 static expression_t *parse_builtin_types_compatible(void)
6544 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6546 eat(T___builtin_types_compatible_p);
6548 add_anchor_token(')');
6549 add_anchor_token(',');
6551 expression->builtin_types_compatible.left = parse_typename();
6552 rem_anchor_token(',');
6554 expression->builtin_types_compatible.right = parse_typename();
6555 rem_anchor_token(')');
6557 expression->base.type = type_int;
6563 * Parses a __builtin_is_*() compare expression.
6565 static expression_t *parse_compare_builtin(void)
6567 expression_kind_t kind;
6568 switch (token.kind) {
6569 case T___builtin_isgreater: kind = EXPR_BINARY_ISGREATER; break;
6570 case T___builtin_isgreaterequal: kind = EXPR_BINARY_ISGREATEREQUAL; break;
6571 case T___builtin_isless: kind = EXPR_BINARY_ISLESS; break;
6572 case T___builtin_islessequal: kind = EXPR_BINARY_ISLESSEQUAL; break;
6573 case T___builtin_islessgreater: kind = EXPR_BINARY_ISLESSGREATER; break;
6574 case T___builtin_isunordered: kind = EXPR_BINARY_ISUNORDERED; break;
6575 default: internal_errorf(HERE, "invalid compare builtin found");
6577 expression_t *const expression = allocate_expression_zero(kind);
6580 add_anchor_token(')');
6581 add_anchor_token(',');
6583 expression->binary.left = parse_assignment_expression();
6584 rem_anchor_token(',');
6586 expression->binary.right = parse_assignment_expression();
6587 rem_anchor_token(')');
6590 type_t *const orig_type_left = expression->binary.left->base.type;
6591 type_t *const orig_type_right = expression->binary.right->base.type;
6593 type_t *const type_left = skip_typeref(orig_type_left);
6594 type_t *const type_right = skip_typeref(orig_type_right);
6595 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6596 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6597 type_error_incompatible("invalid operands in comparison",
6598 &expression->base.source_position, orig_type_left, orig_type_right);
6601 semantic_comparison(&expression->binary);
6608 * Parses a MS assume() expression.
6610 static expression_t *parse_assume(void)
6612 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6616 add_anchor_token(')');
6618 expression->unary.value = parse_assignment_expression();
6619 rem_anchor_token(')');
6622 expression->base.type = type_void;
6627 * Return the label for the current symbol or create a new one.
6629 static label_t *get_label(char const *const context)
6631 assert(current_function != NULL);
6633 symbol_t *const sym = expect_identifier(context, NULL);
6637 entity_t *label = get_entity(sym, NAMESPACE_LABEL);
6638 /* If we find a local label, we already created the declaration. */
6639 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6640 if (label->base.parent_scope != current_scope) {
6641 assert(label->base.parent_scope->depth < current_scope->depth);
6642 current_function->goto_to_outer = true;
6644 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6645 /* There is no matching label in the same function, so create a new one. */
6646 source_position_t const nowhere = { NULL, 0, 0, false };
6647 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym, &nowhere);
6651 return &label->label;
6655 * Parses a GNU && label address expression.
6657 static expression_t *parse_label_address(void)
6659 source_position_t const source_position = *HERE;
6662 label_t *const label = get_label("while parsing label address");
6664 return create_error_expression();
6667 label->address_taken = true;
6669 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6670 expression->base.source_position = source_position;
6672 /* label address is treated as a void pointer */
6673 expression->base.type = type_void_ptr;
6674 expression->label_address.label = label;
6679 * Parse a microsoft __noop expression.
6681 static expression_t *parse_noop_expression(void)
6683 /* the result is a (int)0 */
6684 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6685 literal->base.type = type_int;
6686 literal->literal.value.begin = "__noop";
6687 literal->literal.value.size = 6;
6691 if (token.kind == '(') {
6692 /* parse arguments */
6694 add_anchor_token(')');
6695 add_anchor_token(',');
6697 if (token.kind != ')') do {
6698 (void)parse_assignment_expression();
6699 } while (next_if(','));
6701 rem_anchor_token(',');
6702 rem_anchor_token(')');
6710 * Parses a primary expression.
6712 static expression_t *parse_primary_expression(void)
6714 switch (token.kind) {
6715 case T_false: return parse_boolean_literal(false);
6716 case T_true: return parse_boolean_literal(true);
6717 case T_NUMBER: return parse_number_literal();
6718 case T_CHARACTER_CONSTANT: return parse_character_constant();
6719 case T_STRING_LITERAL: return parse_string_literal();
6720 case T___func__: return parse_function_keyword(FUNCNAME_FUNCTION);
6721 case T___PRETTY_FUNCTION__: return parse_function_keyword(FUNCNAME_PRETTY_FUNCTION);
6722 case T___FUNCSIG__: return parse_function_keyword(FUNCNAME_FUNCSIG);
6723 case T___FUNCDNAME__: return parse_function_keyword(FUNCNAME_FUNCDNAME);
6724 case T___builtin_offsetof: return parse_offsetof();
6725 case T___builtin_va_start: return parse_va_start();
6726 case T___builtin_va_arg: return parse_va_arg();
6727 case T___builtin_va_copy: return parse_va_copy();
6728 case T___builtin_isgreater:
6729 case T___builtin_isgreaterequal:
6730 case T___builtin_isless:
6731 case T___builtin_islessequal:
6732 case T___builtin_islessgreater:
6733 case T___builtin_isunordered: return parse_compare_builtin();
6734 case T___builtin_constant_p: return parse_builtin_constant();
6735 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6736 case T__assume: return parse_assume();
6739 return parse_label_address();
6742 case '(': return parse_parenthesized_expression();
6743 case T___noop: return parse_noop_expression();
6745 /* Gracefully handle type names while parsing expressions. */
6747 return parse_reference();
6749 if (!is_typedef_symbol(token.base.symbol)) {
6750 return parse_reference();
6754 source_position_t const pos = *HERE;
6755 declaration_specifiers_t specifiers;
6756 parse_declaration_specifiers(&specifiers);
6757 type_t const *const type = parse_abstract_declarator(specifiers.type);
6758 errorf(&pos, "encountered type '%T' while parsing expression", type);
6759 return create_error_expression();
6763 errorf(HERE, "unexpected token %K, expected an expression", &token);
6765 return create_error_expression();
6768 static expression_t *parse_array_expression(expression_t *left)
6770 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6771 array_access_expression_t *const arr = &expr->array_access;
6774 add_anchor_token(']');
6776 expression_t *const inside = parse_expression();
6778 type_t *const orig_type_left = left->base.type;
6779 type_t *const orig_type_inside = inside->base.type;
6781 type_t *const type_left = skip_typeref(orig_type_left);
6782 type_t *const type_inside = skip_typeref(orig_type_inside);
6788 if (is_type_pointer(type_left)) {
6791 idx_type = type_inside;
6792 res_type = type_left->pointer.points_to;
6794 } else if (is_type_pointer(type_inside)) {
6795 arr->flipped = true;
6798 idx_type = type_left;
6799 res_type = type_inside->pointer.points_to;
6801 res_type = automatic_type_conversion(res_type);
6802 if (!is_type_integer(idx_type)) {
6803 errorf(&idx->base.source_position, "array subscript must have integer type");
6804 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6805 source_position_t const *const pos = &idx->base.source_position;
6806 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6809 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6810 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6812 res_type = type_error_type;
6817 arr->array_ref = ref;
6819 arr->base.type = res_type;
6821 rem_anchor_token(']');
6826 static bool is_bitfield(const expression_t *expression)
6828 return expression->kind == EXPR_SELECT
6829 && expression->select.compound_entry->compound_member.bitfield;
6832 static expression_t *parse_typeprop(expression_kind_t const kind)
6834 expression_t *tp_expression = allocate_expression_zero(kind);
6835 tp_expression->base.type = type_size_t;
6837 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6840 expression_t *expression;
6841 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6842 source_position_t const pos = *HERE;
6844 add_anchor_token(')');
6845 orig_type = parse_typename();
6846 rem_anchor_token(')');
6849 if (token.kind == '{') {
6850 /* It was not sizeof(type) after all. It is sizeof of an expression
6851 * starting with a compound literal */
6852 expression = parse_compound_literal(&pos, orig_type);
6853 goto typeprop_expression;
6856 expression = parse_subexpression(PREC_UNARY);
6858 typeprop_expression:
6859 if (is_bitfield(expression)) {
6860 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6861 errorf(&tp_expression->base.source_position,
6862 "operand of %s expression must not be a bitfield", what);
6865 tp_expression->typeprop.tp_expression = expression;
6867 orig_type = revert_automatic_type_conversion(expression);
6868 expression->base.type = orig_type;
6871 tp_expression->typeprop.type = orig_type;
6872 type_t const* const type = skip_typeref(orig_type);
6873 char const* wrong_type = NULL;
6874 if (is_type_incomplete(type)) {
6875 if (!is_type_void(type) || !GNU_MODE)
6876 wrong_type = "incomplete";
6877 } else if (type->kind == TYPE_FUNCTION) {
6879 /* function types are allowed (and return 1) */
6880 source_position_t const *const pos = &tp_expression->base.source_position;
6881 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6882 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6884 wrong_type = "function";
6888 if (wrong_type != NULL) {
6889 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6890 errorf(&tp_expression->base.source_position,
6891 "operand of %s expression must not be of %s type '%T'",
6892 what, wrong_type, orig_type);
6895 return tp_expression;
6898 static expression_t *parse_sizeof(void)
6900 return parse_typeprop(EXPR_SIZEOF);
6903 static expression_t *parse_alignof(void)
6905 return parse_typeprop(EXPR_ALIGNOF);
6908 static expression_t *parse_select_expression(expression_t *addr)
6910 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6911 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6912 source_position_t const pos = *HERE;
6915 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6917 return create_error_expression();
6919 type_t *const orig_type = addr->base.type;
6920 type_t *const type = skip_typeref(orig_type);
6923 bool saw_error = false;
6924 if (is_type_pointer(type)) {
6925 if (!select_left_arrow) {
6927 "request for member '%Y' in something not a struct or union, but '%T'",
6931 type_left = skip_typeref(type->pointer.points_to);
6933 if (select_left_arrow && is_type_valid(type)) {
6934 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6940 if (!is_type_compound(type_left)) {
6941 if (is_type_valid(type_left) && !saw_error) {
6943 "request for member '%Y' in something not a struct or union, but '%T'",
6946 return create_error_expression();
6949 compound_t *compound = type_left->compound.compound;
6950 if (!compound->complete) {
6951 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
6953 return create_error_expression();
6956 type_qualifiers_t qualifiers = type_left->base.qualifiers;
6957 expression_t *result =
6958 find_create_select(&pos, addr, qualifiers, compound, symbol);
6960 if (result == NULL) {
6961 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
6962 return create_error_expression();
6968 static void check_call_argument(type_t *expected_type,
6969 call_argument_t *argument, unsigned pos)
6971 type_t *expected_type_skip = skip_typeref(expected_type);
6972 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6973 expression_t *arg_expr = argument->expression;
6974 type_t *arg_type = skip_typeref(arg_expr->base.type);
6976 /* handle transparent union gnu extension */
6977 if (is_type_union(expected_type_skip)
6978 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
6979 compound_t *union_decl = expected_type_skip->compound.compound;
6980 type_t *best_type = NULL;
6981 entity_t *entry = union_decl->members.entities;
6982 for ( ; entry != NULL; entry = entry->base.next) {
6983 assert(is_declaration(entry));
6984 type_t *decl_type = entry->declaration.type;
6985 error = semantic_assign(decl_type, arg_expr);
6986 if (error == ASSIGN_ERROR_INCOMPATIBLE
6987 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6990 if (error == ASSIGN_SUCCESS) {
6991 best_type = decl_type;
6992 } else if (best_type == NULL) {
6993 best_type = decl_type;
6997 if (best_type != NULL) {
6998 expected_type = best_type;
7002 error = semantic_assign(expected_type, arg_expr);
7003 argument->expression = create_implicit_cast(arg_expr, expected_type);
7005 if (error != ASSIGN_SUCCESS) {
7006 /* report exact scope in error messages (like "in argument 3") */
7008 snprintf(buf, sizeof(buf), "call argument %u", pos);
7009 report_assign_error(error, expected_type, arg_expr, buf,
7010 &arg_expr->base.source_position);
7012 type_t *const promoted_type = get_default_promoted_type(arg_type);
7013 if (!types_compatible(expected_type_skip, promoted_type) &&
7014 !types_compatible(expected_type_skip, type_void_ptr) &&
7015 !types_compatible(type_void_ptr, promoted_type)) {
7016 /* Deliberately show the skipped types in this warning */
7017 source_position_t const *const apos = &arg_expr->base.source_position;
7018 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7024 * Handle the semantic restrictions of builtin calls
7026 static void handle_builtin_argument_restrictions(call_expression_t *call)
7028 entity_t *entity = call->function->reference.entity;
7029 switch (entity->function.btk) {
7031 switch (entity->function.b.firm_builtin_kind) {
7032 case ir_bk_return_address:
7033 case ir_bk_frame_address: {
7034 /* argument must be constant */
7035 call_argument_t *argument = call->arguments;
7037 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7038 errorf(&call->base.source_position,
7039 "argument of '%Y' must be a constant expression",
7040 call->function->reference.entity->base.symbol);
7044 case ir_bk_prefetch:
7045 /* second and third argument must be constant if existent */
7046 if (call->arguments == NULL)
7048 call_argument_t *rw = call->arguments->next;
7049 call_argument_t *locality = NULL;
7052 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7053 errorf(&call->base.source_position,
7054 "second argument of '%Y' must be a constant expression",
7055 call->function->reference.entity->base.symbol);
7057 locality = rw->next;
7059 if (locality != NULL) {
7060 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7061 errorf(&call->base.source_position,
7062 "third argument of '%Y' must be a constant expression",
7063 call->function->reference.entity->base.symbol);
7065 locality = rw->next;
7072 case BUILTIN_OBJECT_SIZE:
7073 if (call->arguments == NULL)
7076 call_argument_t *arg = call->arguments->next;
7077 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7078 errorf(&call->base.source_position,
7079 "second argument of '%Y' must be a constant expression",
7080 call->function->reference.entity->base.symbol);
7089 * Parse a call expression, ie. expression '( ... )'.
7091 * @param expression the function address
7093 static expression_t *parse_call_expression(expression_t *expression)
7095 expression_t *result = allocate_expression_zero(EXPR_CALL);
7096 call_expression_t *call = &result->call;
7097 call->function = expression;
7099 type_t *const orig_type = expression->base.type;
7100 type_t *const type = skip_typeref(orig_type);
7102 function_type_t *function_type = NULL;
7103 if (is_type_pointer(type)) {
7104 type_t *const to_type = skip_typeref(type->pointer.points_to);
7106 if (is_type_function(to_type)) {
7107 function_type = &to_type->function;
7108 call->base.type = function_type->return_type;
7112 if (function_type == NULL && is_type_valid(type)) {
7114 "called object '%E' (type '%T') is not a pointer to a function",
7115 expression, orig_type);
7118 /* parse arguments */
7120 add_anchor_token(')');
7121 add_anchor_token(',');
7123 if (token.kind != ')') {
7124 call_argument_t **anchor = &call->arguments;
7126 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7127 argument->expression = parse_assignment_expression();
7130 anchor = &argument->next;
7131 } while (next_if(','));
7133 rem_anchor_token(',');
7134 rem_anchor_token(')');
7137 if (function_type == NULL)
7140 /* check type and count of call arguments */
7141 function_parameter_t *parameter = function_type->parameters;
7142 call_argument_t *argument = call->arguments;
7143 if (!function_type->unspecified_parameters) {
7144 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7145 parameter = parameter->next, argument = argument->next) {
7146 check_call_argument(parameter->type, argument, ++pos);
7149 if (parameter != NULL) {
7150 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7151 } else if (argument != NULL && !function_type->variadic) {
7152 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7156 /* do default promotion for other arguments */
7157 for (; argument != NULL; argument = argument->next) {
7158 type_t *argument_type = argument->expression->base.type;
7159 if (!is_type_object(skip_typeref(argument_type))) {
7160 errorf(&argument->expression->base.source_position,
7161 "call argument '%E' must not be void", argument->expression);
7164 argument_type = get_default_promoted_type(argument_type);
7166 argument->expression
7167 = create_implicit_cast(argument->expression, argument_type);
7172 if (is_type_compound(skip_typeref(function_type->return_type))) {
7173 source_position_t const *const pos = &expression->base.source_position;
7174 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7177 if (expression->kind == EXPR_REFERENCE) {
7178 reference_expression_t *reference = &expression->reference;
7179 if (reference->entity->kind == ENTITY_FUNCTION &&
7180 reference->entity->function.btk != BUILTIN_NONE)
7181 handle_builtin_argument_restrictions(call);
7187 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7189 static bool same_compound_type(const type_t *type1, const type_t *type2)
7192 is_type_compound(type1) &&
7193 type1->kind == type2->kind &&
7194 type1->compound.compound == type2->compound.compound;
7197 static expression_t const *get_reference_address(expression_t const *expr)
7199 bool regular_take_address = true;
7201 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7202 expr = expr->unary.value;
7204 regular_take_address = false;
7207 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7210 expr = expr->unary.value;
7213 if (expr->kind != EXPR_REFERENCE)
7216 /* special case for functions which are automatically converted to a
7217 * pointer to function without an extra TAKE_ADDRESS operation */
7218 if (!regular_take_address &&
7219 expr->reference.entity->kind != ENTITY_FUNCTION) {
7226 static void warn_reference_address_as_bool(expression_t const* expr)
7228 expr = get_reference_address(expr);
7230 source_position_t const *const pos = &expr->base.source_position;
7231 entity_t const *const ent = expr->reference.entity;
7232 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7236 static void warn_assignment_in_condition(const expression_t *const expr)
7238 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7240 if (expr->base.parenthesized)
7242 source_position_t const *const pos = &expr->base.source_position;
7243 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7246 static void semantic_condition(expression_t const *const expr,
7247 char const *const context)
7249 type_t *const type = skip_typeref(expr->base.type);
7250 if (is_type_scalar(type)) {
7251 warn_reference_address_as_bool(expr);
7252 warn_assignment_in_condition(expr);
7253 } else if (is_type_valid(type)) {
7254 errorf(&expr->base.source_position,
7255 "%s must have scalar type", context);
7260 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7262 * @param expression the conditional expression
7264 static expression_t *parse_conditional_expression(expression_t *expression)
7266 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7268 conditional_expression_t *conditional = &result->conditional;
7269 conditional->condition = expression;
7272 add_anchor_token(':');
7274 /* §6.5.15:2 The first operand shall have scalar type. */
7275 semantic_condition(expression, "condition of conditional operator");
7277 expression_t *true_expression = expression;
7278 bool gnu_cond = false;
7279 if (GNU_MODE && token.kind == ':') {
7282 true_expression = parse_expression();
7284 rem_anchor_token(':');
7286 expression_t *false_expression =
7287 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7289 type_t *const orig_true_type = true_expression->base.type;
7290 type_t *const orig_false_type = false_expression->base.type;
7291 type_t *const true_type = skip_typeref(orig_true_type);
7292 type_t *const false_type = skip_typeref(orig_false_type);
7295 source_position_t const *const pos = &conditional->base.source_position;
7296 type_t *result_type;
7297 if (is_type_void(true_type) || is_type_void(false_type)) {
7298 /* ISO/IEC 14882:1998(E) §5.16:2 */
7299 if (true_expression->kind == EXPR_UNARY_THROW) {
7300 result_type = false_type;
7301 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7302 result_type = true_type;
7304 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7305 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7307 result_type = type_void;
7309 } else if (is_type_arithmetic(true_type)
7310 && is_type_arithmetic(false_type)) {
7311 result_type = semantic_arithmetic(true_type, false_type);
7312 } else if (same_compound_type(true_type, false_type)) {
7313 /* just take 1 of the 2 types */
7314 result_type = true_type;
7315 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7316 type_t *pointer_type;
7318 expression_t *other_expression;
7319 if (is_type_pointer(true_type) &&
7320 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7321 pointer_type = true_type;
7322 other_type = false_type;
7323 other_expression = false_expression;
7325 pointer_type = false_type;
7326 other_type = true_type;
7327 other_expression = true_expression;
7330 if (is_null_pointer_constant(other_expression)) {
7331 result_type = pointer_type;
7332 } else if (is_type_pointer(other_type)) {
7333 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7334 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7337 if (is_type_void(to1) || is_type_void(to2)) {
7339 } else if (types_compatible(get_unqualified_type(to1),
7340 get_unqualified_type(to2))) {
7343 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7347 type_t *const type =
7348 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7349 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7350 } else if (is_type_integer(other_type)) {
7351 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7352 result_type = pointer_type;
7354 goto types_incompatible;
7358 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7359 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7361 result_type = type_error_type;
7364 conditional->true_expression
7365 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7366 conditional->false_expression
7367 = create_implicit_cast(false_expression, result_type);
7368 conditional->base.type = result_type;
7373 * Parse an extension expression.
7375 static expression_t *parse_extension(void)
7378 expression_t *expression = parse_subexpression(PREC_UNARY);
7384 * Parse a __builtin_classify_type() expression.
7386 static expression_t *parse_builtin_classify_type(void)
7388 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7389 result->base.type = type_int;
7391 eat(T___builtin_classify_type);
7393 add_anchor_token(')');
7395 expression_t *expression = parse_expression();
7396 rem_anchor_token(')');
7398 result->classify_type.type_expression = expression;
7404 * Parse a delete expression
7405 * ISO/IEC 14882:1998(E) §5.3.5
7407 static expression_t *parse_delete(void)
7409 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7410 result->base.type = type_void;
7415 result->kind = EXPR_UNARY_DELETE_ARRAY;
7419 expression_t *const value = parse_subexpression(PREC_CAST);
7420 result->unary.value = value;
7422 type_t *const type = skip_typeref(value->base.type);
7423 if (!is_type_pointer(type)) {
7424 if (is_type_valid(type)) {
7425 errorf(&value->base.source_position,
7426 "operand of delete must have pointer type");
7428 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7429 source_position_t const *const pos = &value->base.source_position;
7430 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7437 * Parse a throw expression
7438 * ISO/IEC 14882:1998(E) §15:1
7440 static expression_t *parse_throw(void)
7442 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7443 result->base.type = type_void;
7447 expression_t *value = NULL;
7448 switch (token.kind) {
7450 value = parse_assignment_expression();
7451 /* ISO/IEC 14882:1998(E) §15.1:3 */
7452 type_t *const orig_type = value->base.type;
7453 type_t *const type = skip_typeref(orig_type);
7454 if (is_type_incomplete(type)) {
7455 errorf(&value->base.source_position,
7456 "cannot throw object of incomplete type '%T'", orig_type);
7457 } else if (is_type_pointer(type)) {
7458 type_t *const points_to = skip_typeref(type->pointer.points_to);
7459 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7460 errorf(&value->base.source_position,
7461 "cannot throw pointer to incomplete type '%T'", orig_type);
7469 result->unary.value = value;
7474 static bool check_pointer_arithmetic(const source_position_t *source_position,
7475 type_t *pointer_type,
7476 type_t *orig_pointer_type)
7478 type_t *points_to = pointer_type->pointer.points_to;
7479 points_to = skip_typeref(points_to);
7481 if (is_type_incomplete(points_to)) {
7482 if (!GNU_MODE || !is_type_void(points_to)) {
7483 errorf(source_position,
7484 "arithmetic with pointer to incomplete type '%T' not allowed",
7488 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7490 } else if (is_type_function(points_to)) {
7492 errorf(source_position,
7493 "arithmetic with pointer to function type '%T' not allowed",
7497 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7503 static bool is_lvalue(const expression_t *expression)
7505 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7506 switch (expression->kind) {
7507 case EXPR_ARRAY_ACCESS:
7508 case EXPR_COMPOUND_LITERAL:
7509 case EXPR_REFERENCE:
7511 case EXPR_UNARY_DEREFERENCE:
7515 type_t *type = skip_typeref(expression->base.type);
7517 /* ISO/IEC 14882:1998(E) §3.10:3 */
7518 is_type_reference(type) ||
7519 /* Claim it is an lvalue, if the type is invalid. There was a parse
7520 * error before, which maybe prevented properly recognizing it as
7522 !is_type_valid(type);
7527 static void semantic_incdec(unary_expression_t *expression)
7529 type_t *const orig_type = expression->value->base.type;
7530 type_t *const type = skip_typeref(orig_type);
7531 if (is_type_pointer(type)) {
7532 if (!check_pointer_arithmetic(&expression->base.source_position,
7536 } else if (!is_type_real(type) && is_type_valid(type)) {
7537 /* TODO: improve error message */
7538 errorf(&expression->base.source_position,
7539 "operation needs an arithmetic or pointer type");
7542 if (!is_lvalue(expression->value)) {
7543 /* TODO: improve error message */
7544 errorf(&expression->base.source_position, "lvalue required as operand");
7546 expression->base.type = orig_type;
7549 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7551 type_t *const res_type = promote_integer(type);
7552 expr->base.type = res_type;
7553 expr->value = create_implicit_cast(expr->value, res_type);
7556 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7558 type_t *const orig_type = expression->value->base.type;
7559 type_t *const type = skip_typeref(orig_type);
7560 if (!is_type_arithmetic(type)) {
7561 if (is_type_valid(type)) {
7562 /* TODO: improve error message */
7563 errorf(&expression->base.source_position,
7564 "operation needs an arithmetic type");
7567 } else if (is_type_integer(type)) {
7568 promote_unary_int_expr(expression, type);
7570 expression->base.type = orig_type;
7574 static void semantic_unexpr_plus(unary_expression_t *expression)
7576 semantic_unexpr_arithmetic(expression);
7577 source_position_t const *const pos = &expression->base.source_position;
7578 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7581 static void semantic_not(unary_expression_t *expression)
7583 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7584 semantic_condition(expression->value, "operand of !");
7585 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7588 static void semantic_unexpr_integer(unary_expression_t *expression)
7590 type_t *const orig_type = expression->value->base.type;
7591 type_t *const type = skip_typeref(orig_type);
7592 if (!is_type_integer(type)) {
7593 if (is_type_valid(type)) {
7594 errorf(&expression->base.source_position,
7595 "operand of ~ must be of integer type");
7600 promote_unary_int_expr(expression, type);
7603 static void semantic_dereference(unary_expression_t *expression)
7605 type_t *const orig_type = expression->value->base.type;
7606 type_t *const type = skip_typeref(orig_type);
7607 if (!is_type_pointer(type)) {
7608 if (is_type_valid(type)) {
7609 errorf(&expression->base.source_position,
7610 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7615 type_t *result_type = type->pointer.points_to;
7616 result_type = automatic_type_conversion(result_type);
7617 expression->base.type = result_type;
7621 * Record that an address is taken (expression represents an lvalue).
7623 * @param expression the expression
7624 * @param may_be_register if true, the expression might be an register
7626 static void set_address_taken(expression_t *expression, bool may_be_register)
7628 if (expression->kind != EXPR_REFERENCE)
7631 entity_t *const entity = expression->reference.entity;
7633 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7636 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7637 && !may_be_register) {
7638 source_position_t const *const pos = &expression->base.source_position;
7639 errorf(pos, "address of register '%N' requested", entity);
7642 entity->variable.address_taken = true;
7646 * Check the semantic of the address taken expression.
7648 static void semantic_take_addr(unary_expression_t *expression)
7650 expression_t *value = expression->value;
7651 value->base.type = revert_automatic_type_conversion(value);
7653 type_t *orig_type = value->base.type;
7654 type_t *type = skip_typeref(orig_type);
7655 if (!is_type_valid(type))
7659 if (!is_lvalue(value)) {
7660 errorf(&expression->base.source_position, "'&' requires an lvalue");
7662 if (is_bitfield(value)) {
7663 errorf(&expression->base.source_position,
7664 "'&' not allowed on bitfield");
7667 set_address_taken(value, false);
7669 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7672 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7673 static expression_t *parse_##unexpression_type(void) \
7675 expression_t *unary_expression \
7676 = allocate_expression_zero(unexpression_type); \
7678 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7680 sfunc(&unary_expression->unary); \
7682 return unary_expression; \
7685 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7686 semantic_unexpr_arithmetic)
7687 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7688 semantic_unexpr_plus)
7689 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7691 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7692 semantic_dereference)
7693 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7695 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7696 semantic_unexpr_integer)
7697 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7699 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7702 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7704 static expression_t *parse_##unexpression_type(expression_t *left) \
7706 expression_t *unary_expression \
7707 = allocate_expression_zero(unexpression_type); \
7709 unary_expression->unary.value = left; \
7711 sfunc(&unary_expression->unary); \
7713 return unary_expression; \
7716 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7717 EXPR_UNARY_POSTFIX_INCREMENT,
7719 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7720 EXPR_UNARY_POSTFIX_DECREMENT,
7723 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7725 /* TODO: handle complex + imaginary types */
7727 type_left = get_unqualified_type(type_left);
7728 type_right = get_unqualified_type(type_right);
7730 /* §6.3.1.8 Usual arithmetic conversions */
7731 if (type_left == type_long_double || type_right == type_long_double) {
7732 return type_long_double;
7733 } else if (type_left == type_double || type_right == type_double) {
7735 } else if (type_left == type_float || type_right == type_float) {
7739 type_left = promote_integer(type_left);
7740 type_right = promote_integer(type_right);
7742 if (type_left == type_right)
7745 bool const signed_left = is_type_signed(type_left);
7746 bool const signed_right = is_type_signed(type_right);
7747 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7748 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7750 if (signed_left == signed_right)
7751 return rank_left >= rank_right ? type_left : type_right;
7755 atomic_type_kind_t s_akind;
7756 atomic_type_kind_t u_akind;
7761 u_type = type_right;
7763 s_type = type_right;
7766 s_akind = get_akind(s_type);
7767 u_akind = get_akind(u_type);
7768 s_rank = get_akind_rank(s_akind);
7769 u_rank = get_akind_rank(u_akind);
7771 if (u_rank >= s_rank)
7774 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7778 case ATOMIC_TYPE_INT: return type_unsigned_int;
7779 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7780 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7782 default: panic("invalid atomic type");
7787 * Check the semantic restrictions for a binary expression.
7789 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7791 expression_t *const left = expression->left;
7792 expression_t *const right = expression->right;
7793 type_t *const orig_type_left = left->base.type;
7794 type_t *const orig_type_right = right->base.type;
7795 type_t *const type_left = skip_typeref(orig_type_left);
7796 type_t *const type_right = skip_typeref(orig_type_right);
7798 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7799 /* TODO: improve error message */
7800 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7801 errorf(&expression->base.source_position,
7802 "operation needs arithmetic types");
7807 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7808 expression->left = create_implicit_cast(left, arithmetic_type);
7809 expression->right = create_implicit_cast(right, arithmetic_type);
7810 expression->base.type = arithmetic_type;
7813 static void semantic_binexpr_integer(binary_expression_t *const expression)
7815 expression_t *const left = expression->left;
7816 expression_t *const right = expression->right;
7817 type_t *const orig_type_left = left->base.type;
7818 type_t *const orig_type_right = right->base.type;
7819 type_t *const type_left = skip_typeref(orig_type_left);
7820 type_t *const type_right = skip_typeref(orig_type_right);
7822 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7823 /* TODO: improve error message */
7824 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7825 errorf(&expression->base.source_position,
7826 "operation needs integer types");
7831 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7832 expression->left = create_implicit_cast(left, result_type);
7833 expression->right = create_implicit_cast(right, result_type);
7834 expression->base.type = result_type;
7837 static void warn_div_by_zero(binary_expression_t const *const expression)
7839 if (!is_type_integer(expression->base.type))
7842 expression_t const *const right = expression->right;
7843 /* The type of the right operand can be different for /= */
7844 if (is_type_integer(right->base.type) &&
7845 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7846 !fold_constant_to_bool(right)) {
7847 source_position_t const *const pos = &expression->base.source_position;
7848 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7853 * Check the semantic restrictions for a div/mod expression.
7855 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7857 semantic_binexpr_arithmetic(expression);
7858 warn_div_by_zero(expression);
7861 static void warn_addsub_in_shift(const expression_t *const expr)
7863 if (expr->base.parenthesized)
7867 switch (expr->kind) {
7868 case EXPR_BINARY_ADD: op = '+'; break;
7869 case EXPR_BINARY_SUB: op = '-'; break;
7873 source_position_t const *const pos = &expr->base.source_position;
7874 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7877 static bool semantic_shift(binary_expression_t *expression)
7879 expression_t *const left = expression->left;
7880 expression_t *const right = expression->right;
7881 type_t *const orig_type_left = left->base.type;
7882 type_t *const orig_type_right = right->base.type;
7883 type_t * type_left = skip_typeref(orig_type_left);
7884 type_t * type_right = skip_typeref(orig_type_right);
7886 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7887 /* TODO: improve error message */
7888 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7889 errorf(&expression->base.source_position,
7890 "operands of shift operation must have integer types");
7895 type_left = promote_integer(type_left);
7897 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7898 source_position_t const *const pos = &right->base.source_position;
7899 long const count = fold_constant_to_int(right);
7901 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7902 } else if ((unsigned long)count >=
7903 get_atomic_type_size(type_left->atomic.akind) * 8) {
7904 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7908 type_right = promote_integer(type_right);
7909 expression->right = create_implicit_cast(right, type_right);
7914 static void semantic_shift_op(binary_expression_t *expression)
7916 expression_t *const left = expression->left;
7917 expression_t *const right = expression->right;
7919 if (!semantic_shift(expression))
7922 warn_addsub_in_shift(left);
7923 warn_addsub_in_shift(right);
7925 type_t *const orig_type_left = left->base.type;
7926 type_t * type_left = skip_typeref(orig_type_left);
7928 type_left = promote_integer(type_left);
7929 expression->left = create_implicit_cast(left, type_left);
7930 expression->base.type = type_left;
7933 static void semantic_add(binary_expression_t *expression)
7935 expression_t *const left = expression->left;
7936 expression_t *const right = expression->right;
7937 type_t *const orig_type_left = left->base.type;
7938 type_t *const orig_type_right = right->base.type;
7939 type_t *const type_left = skip_typeref(orig_type_left);
7940 type_t *const type_right = skip_typeref(orig_type_right);
7943 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7944 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7945 expression->left = create_implicit_cast(left, arithmetic_type);
7946 expression->right = create_implicit_cast(right, arithmetic_type);
7947 expression->base.type = arithmetic_type;
7948 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7949 check_pointer_arithmetic(&expression->base.source_position,
7950 type_left, orig_type_left);
7951 expression->base.type = type_left;
7952 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7953 check_pointer_arithmetic(&expression->base.source_position,
7954 type_right, orig_type_right);
7955 expression->base.type = type_right;
7956 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7957 errorf(&expression->base.source_position,
7958 "invalid operands to binary + ('%T', '%T')",
7959 orig_type_left, orig_type_right);
7963 static void semantic_sub(binary_expression_t *expression)
7965 expression_t *const left = expression->left;
7966 expression_t *const right = expression->right;
7967 type_t *const orig_type_left = left->base.type;
7968 type_t *const orig_type_right = right->base.type;
7969 type_t *const type_left = skip_typeref(orig_type_left);
7970 type_t *const type_right = skip_typeref(orig_type_right);
7971 source_position_t const *const pos = &expression->base.source_position;
7974 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7975 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7976 expression->left = create_implicit_cast(left, arithmetic_type);
7977 expression->right = create_implicit_cast(right, arithmetic_type);
7978 expression->base.type = arithmetic_type;
7979 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7980 check_pointer_arithmetic(&expression->base.source_position,
7981 type_left, orig_type_left);
7982 expression->base.type = type_left;
7983 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7984 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7985 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7986 if (!types_compatible(unqual_left, unqual_right)) {
7988 "subtracting pointers to incompatible types '%T' and '%T'",
7989 orig_type_left, orig_type_right);
7990 } else if (!is_type_object(unqual_left)) {
7991 if (!is_type_void(unqual_left)) {
7992 errorf(pos, "subtracting pointers to non-object types '%T'",
7995 warningf(WARN_OTHER, pos, "subtracting pointers to void");
7998 expression->base.type = type_ptrdiff_t;
7999 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8000 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8001 orig_type_left, orig_type_right);
8005 static void warn_string_literal_address(expression_t const* expr)
8007 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8008 expr = expr->unary.value;
8009 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8011 expr = expr->unary.value;
8014 if (expr->kind == EXPR_STRING_LITERAL) {
8015 source_position_t const *const pos = &expr->base.source_position;
8016 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8020 static bool maybe_negative(expression_t const *const expr)
8022 switch (is_constant_expression(expr)) {
8023 case EXPR_CLASS_ERROR: return false;
8024 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8025 default: return true;
8029 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8031 warn_string_literal_address(expr);
8033 expression_t const* const ref = get_reference_address(expr);
8034 if (ref != NULL && is_null_pointer_constant(other)) {
8035 entity_t const *const ent = ref->reference.entity;
8036 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8039 if (!expr->base.parenthesized) {
8040 switch (expr->base.kind) {
8041 case EXPR_BINARY_LESS:
8042 case EXPR_BINARY_GREATER:
8043 case EXPR_BINARY_LESSEQUAL:
8044 case EXPR_BINARY_GREATEREQUAL:
8045 case EXPR_BINARY_NOTEQUAL:
8046 case EXPR_BINARY_EQUAL:
8047 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8056 * Check the semantics of comparison expressions.
8058 * @param expression The expression to check.
8060 static void semantic_comparison(binary_expression_t *expression)
8062 source_position_t const *const pos = &expression->base.source_position;
8063 expression_t *const left = expression->left;
8064 expression_t *const right = expression->right;
8066 warn_comparison(pos, left, right);
8067 warn_comparison(pos, right, left);
8069 type_t *orig_type_left = left->base.type;
8070 type_t *orig_type_right = right->base.type;
8071 type_t *type_left = skip_typeref(orig_type_left);
8072 type_t *type_right = skip_typeref(orig_type_right);
8074 /* TODO non-arithmetic types */
8075 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8076 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8078 /* test for signed vs unsigned compares */
8079 if (is_type_integer(arithmetic_type)) {
8080 bool const signed_left = is_type_signed(type_left);
8081 bool const signed_right = is_type_signed(type_right);
8082 if (signed_left != signed_right) {
8083 /* FIXME long long needs better const folding magic */
8084 /* TODO check whether constant value can be represented by other type */
8085 if ((signed_left && maybe_negative(left)) ||
8086 (signed_right && maybe_negative(right))) {
8087 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8092 expression->left = create_implicit_cast(left, arithmetic_type);
8093 expression->right = create_implicit_cast(right, arithmetic_type);
8094 expression->base.type = arithmetic_type;
8095 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8096 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8097 is_type_float(arithmetic_type)) {
8098 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8100 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8101 /* TODO check compatibility */
8102 } else if (is_type_pointer(type_left)) {
8103 expression->right = create_implicit_cast(right, type_left);
8104 } else if (is_type_pointer(type_right)) {
8105 expression->left = create_implicit_cast(left, type_right);
8106 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8107 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8109 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8113 * Checks if a compound type has constant fields.
8115 static bool has_const_fields(const compound_type_t *type)
8117 compound_t *compound = type->compound;
8118 entity_t *entry = compound->members.entities;
8120 for (; entry != NULL; entry = entry->base.next) {
8121 if (!is_declaration(entry))
8124 const type_t *decl_type = skip_typeref(entry->declaration.type);
8125 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8132 static bool is_valid_assignment_lhs(expression_t const* const left)
8134 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8135 type_t *const type_left = skip_typeref(orig_type_left);
8137 if (!is_lvalue(left)) {
8138 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8143 if (left->kind == EXPR_REFERENCE
8144 && left->reference.entity->kind == ENTITY_FUNCTION) {
8145 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8149 if (is_type_array(type_left)) {
8150 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8153 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8154 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8158 if (is_type_incomplete(type_left)) {
8159 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8160 left, orig_type_left);
8163 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8164 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8165 left, orig_type_left);
8172 static void semantic_arithmetic_assign(binary_expression_t *expression)
8174 expression_t *left = expression->left;
8175 expression_t *right = expression->right;
8176 type_t *orig_type_left = left->base.type;
8177 type_t *orig_type_right = right->base.type;
8179 if (!is_valid_assignment_lhs(left))
8182 type_t *type_left = skip_typeref(orig_type_left);
8183 type_t *type_right = skip_typeref(orig_type_right);
8185 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8186 /* TODO: improve error message */
8187 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8188 errorf(&expression->base.source_position,
8189 "operation needs arithmetic types");
8194 /* combined instructions are tricky. We can't create an implicit cast on
8195 * the left side, because we need the uncasted form for the store.
8196 * The ast2firm pass has to know that left_type must be right_type
8197 * for the arithmetic operation and create a cast by itself */
8198 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8199 expression->right = create_implicit_cast(right, arithmetic_type);
8200 expression->base.type = type_left;
8203 static void semantic_divmod_assign(binary_expression_t *expression)
8205 semantic_arithmetic_assign(expression);
8206 warn_div_by_zero(expression);
8209 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8211 expression_t *const left = expression->left;
8212 expression_t *const right = expression->right;
8213 type_t *const orig_type_left = left->base.type;
8214 type_t *const orig_type_right = right->base.type;
8215 type_t *const type_left = skip_typeref(orig_type_left);
8216 type_t *const type_right = skip_typeref(orig_type_right);
8218 if (!is_valid_assignment_lhs(left))
8221 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8222 /* combined instructions are tricky. We can't create an implicit cast on
8223 * the left side, because we need the uncasted form for the store.
8224 * The ast2firm pass has to know that left_type must be right_type
8225 * for the arithmetic operation and create a cast by itself */
8226 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8227 expression->right = create_implicit_cast(right, arithmetic_type);
8228 expression->base.type = type_left;
8229 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8230 check_pointer_arithmetic(&expression->base.source_position,
8231 type_left, orig_type_left);
8232 expression->base.type = type_left;
8233 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8234 errorf(&expression->base.source_position,
8235 "incompatible types '%T' and '%T' in assignment",
8236 orig_type_left, orig_type_right);
8240 static void semantic_integer_assign(binary_expression_t *expression)
8242 expression_t *left = expression->left;
8243 expression_t *right = expression->right;
8244 type_t *orig_type_left = left->base.type;
8245 type_t *orig_type_right = right->base.type;
8247 if (!is_valid_assignment_lhs(left))
8250 type_t *type_left = skip_typeref(orig_type_left);
8251 type_t *type_right = skip_typeref(orig_type_right);
8253 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8254 /* TODO: improve error message */
8255 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8256 errorf(&expression->base.source_position,
8257 "operation needs integer types");
8262 /* combined instructions are tricky. We can't create an implicit cast on
8263 * the left side, because we need the uncasted form for the store.
8264 * The ast2firm pass has to know that left_type must be right_type
8265 * for the arithmetic operation and create a cast by itself */
8266 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8267 expression->right = create_implicit_cast(right, arithmetic_type);
8268 expression->base.type = type_left;
8271 static void semantic_shift_assign(binary_expression_t *expression)
8273 expression_t *left = expression->left;
8275 if (!is_valid_assignment_lhs(left))
8278 if (!semantic_shift(expression))
8281 expression->base.type = skip_typeref(left->base.type);
8284 static void warn_logical_and_within_or(const expression_t *const expr)
8286 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8288 if (expr->base.parenthesized)
8290 source_position_t const *const pos = &expr->base.source_position;
8291 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8295 * Check the semantic restrictions of a logical expression.
8297 static void semantic_logical_op(binary_expression_t *expression)
8299 /* §6.5.13:2 Each of the operands shall have scalar type.
8300 * §6.5.14:2 Each of the operands shall have scalar type. */
8301 semantic_condition(expression->left, "left operand of logical operator");
8302 semantic_condition(expression->right, "right operand of logical operator");
8303 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8304 warn_logical_and_within_or(expression->left);
8305 warn_logical_and_within_or(expression->right);
8307 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8311 * Check the semantic restrictions of a binary assign expression.
8313 static void semantic_binexpr_assign(binary_expression_t *expression)
8315 expression_t *left = expression->left;
8316 type_t *orig_type_left = left->base.type;
8318 if (!is_valid_assignment_lhs(left))
8321 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8322 report_assign_error(error, orig_type_left, expression->right,
8323 "assignment", &left->base.source_position);
8324 expression->right = create_implicit_cast(expression->right, orig_type_left);
8325 expression->base.type = orig_type_left;
8329 * Determine if the outermost operation (or parts thereof) of the given
8330 * expression has no effect in order to generate a warning about this fact.
8331 * Therefore in some cases this only examines some of the operands of the
8332 * expression (see comments in the function and examples below).
8334 * f() + 23; // warning, because + has no effect
8335 * x || f(); // no warning, because x controls execution of f()
8336 * x ? y : f(); // warning, because y has no effect
8337 * (void)x; // no warning to be able to suppress the warning
8338 * This function can NOT be used for an "expression has definitely no effect"-
8340 static bool expression_has_effect(const expression_t *const expr)
8342 switch (expr->kind) {
8343 case EXPR_ERROR: return true; /* do NOT warn */
8344 case EXPR_REFERENCE: return false;
8345 case EXPR_ENUM_CONSTANT: return false;
8346 case EXPR_LABEL_ADDRESS: return false;
8348 /* suppress the warning for microsoft __noop operations */
8349 case EXPR_LITERAL_MS_NOOP: return true;
8350 case EXPR_LITERAL_BOOLEAN:
8351 case EXPR_LITERAL_CHARACTER:
8352 case EXPR_LITERAL_INTEGER:
8353 case EXPR_LITERAL_FLOATINGPOINT:
8354 case EXPR_STRING_LITERAL: return false;
8357 const call_expression_t *const call = &expr->call;
8358 if (call->function->kind != EXPR_REFERENCE)
8361 switch (call->function->reference.entity->function.btk) {
8362 /* FIXME: which builtins have no effect? */
8363 default: return true;
8367 /* Generate the warning if either the left or right hand side of a
8368 * conditional expression has no effect */
8369 case EXPR_CONDITIONAL: {
8370 conditional_expression_t const *const cond = &expr->conditional;
8371 expression_t const *const t = cond->true_expression;
8373 (t == NULL || expression_has_effect(t)) &&
8374 expression_has_effect(cond->false_expression);
8377 case EXPR_SELECT: return false;
8378 case EXPR_ARRAY_ACCESS: return false;
8379 case EXPR_SIZEOF: return false;
8380 case EXPR_CLASSIFY_TYPE: return false;
8381 case EXPR_ALIGNOF: return false;
8383 case EXPR_FUNCNAME: return false;
8384 case EXPR_BUILTIN_CONSTANT_P: return false;
8385 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8386 case EXPR_OFFSETOF: return false;
8387 case EXPR_VA_START: return true;
8388 case EXPR_VA_ARG: return true;
8389 case EXPR_VA_COPY: return true;
8390 case EXPR_STATEMENT: return true; // TODO
8391 case EXPR_COMPOUND_LITERAL: return false;
8393 case EXPR_UNARY_NEGATE: return false;
8394 case EXPR_UNARY_PLUS: return false;
8395 case EXPR_UNARY_BITWISE_NEGATE: return false;
8396 case EXPR_UNARY_NOT: return false;
8397 case EXPR_UNARY_DEREFERENCE: return false;
8398 case EXPR_UNARY_TAKE_ADDRESS: return false;
8399 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8400 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8401 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8402 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8404 /* Treat void casts as if they have an effect in order to being able to
8405 * suppress the warning */
8406 case EXPR_UNARY_CAST: {
8407 type_t *const type = skip_typeref(expr->base.type);
8408 return is_type_void(type);
8411 case EXPR_UNARY_ASSUME: return true;
8412 case EXPR_UNARY_DELETE: return true;
8413 case EXPR_UNARY_DELETE_ARRAY: return true;
8414 case EXPR_UNARY_THROW: return true;
8416 case EXPR_BINARY_ADD: return false;
8417 case EXPR_BINARY_SUB: return false;
8418 case EXPR_BINARY_MUL: return false;
8419 case EXPR_BINARY_DIV: return false;
8420 case EXPR_BINARY_MOD: return false;
8421 case EXPR_BINARY_EQUAL: return false;
8422 case EXPR_BINARY_NOTEQUAL: return false;
8423 case EXPR_BINARY_LESS: return false;
8424 case EXPR_BINARY_LESSEQUAL: return false;
8425 case EXPR_BINARY_GREATER: return false;
8426 case EXPR_BINARY_GREATEREQUAL: return false;
8427 case EXPR_BINARY_BITWISE_AND: return false;
8428 case EXPR_BINARY_BITWISE_OR: return false;
8429 case EXPR_BINARY_BITWISE_XOR: return false;
8430 case EXPR_BINARY_SHIFTLEFT: return false;
8431 case EXPR_BINARY_SHIFTRIGHT: return false;
8432 case EXPR_BINARY_ASSIGN: return true;
8433 case EXPR_BINARY_MUL_ASSIGN: return true;
8434 case EXPR_BINARY_DIV_ASSIGN: return true;
8435 case EXPR_BINARY_MOD_ASSIGN: return true;
8436 case EXPR_BINARY_ADD_ASSIGN: return true;
8437 case EXPR_BINARY_SUB_ASSIGN: return true;
8438 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8439 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8440 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8441 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8442 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8444 /* Only examine the right hand side of && and ||, because the left hand
8445 * side already has the effect of controlling the execution of the right
8447 case EXPR_BINARY_LOGICAL_AND:
8448 case EXPR_BINARY_LOGICAL_OR:
8449 /* Only examine the right hand side of a comma expression, because the left
8450 * hand side has a separate warning */
8451 case EXPR_BINARY_COMMA:
8452 return expression_has_effect(expr->binary.right);
8454 case EXPR_BINARY_ISGREATER: return false;
8455 case EXPR_BINARY_ISGREATEREQUAL: return false;
8456 case EXPR_BINARY_ISLESS: return false;
8457 case EXPR_BINARY_ISLESSEQUAL: return false;
8458 case EXPR_BINARY_ISLESSGREATER: return false;
8459 case EXPR_BINARY_ISUNORDERED: return false;
8462 internal_errorf(HERE, "unexpected expression");
8465 static void semantic_comma(binary_expression_t *expression)
8467 const expression_t *const left = expression->left;
8468 if (!expression_has_effect(left)) {
8469 source_position_t const *const pos = &left->base.source_position;
8470 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8472 expression->base.type = expression->right->base.type;
8476 * @param prec_r precedence of the right operand
8478 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8479 static expression_t *parse_##binexpression_type(expression_t *left) \
8481 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8482 binexpr->binary.left = left; \
8485 expression_t *right = parse_subexpression(prec_r); \
8487 binexpr->binary.right = right; \
8488 sfunc(&binexpr->binary); \
8493 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8494 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8495 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8496 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8497 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8498 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8499 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8500 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8501 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8502 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8503 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8504 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8505 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8506 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8507 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8508 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8509 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8510 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8511 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8512 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8513 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8514 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8515 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8516 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8517 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8518 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8519 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8520 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8521 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8522 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8525 static expression_t *parse_subexpression(precedence_t precedence)
8527 expression_parser_function_t *parser
8528 = &expression_parsers[token.kind];
8531 if (parser->parser != NULL) {
8532 left = parser->parser();
8534 left = parse_primary_expression();
8536 assert(left != NULL);
8539 parser = &expression_parsers[token.kind];
8540 if (parser->infix_parser == NULL)
8542 if (parser->infix_precedence < precedence)
8545 left = parser->infix_parser(left);
8547 assert(left != NULL);
8554 * Parse an expression.
8556 static expression_t *parse_expression(void)
8558 return parse_subexpression(PREC_EXPRESSION);
8562 * Register a parser for a prefix-like operator.
8564 * @param parser the parser function
8565 * @param token_kind the token type of the prefix token
8567 static void register_expression_parser(parse_expression_function parser,
8570 expression_parser_function_t *entry = &expression_parsers[token_kind];
8572 assert(!entry->parser);
8573 entry->parser = parser;
8577 * Register a parser for an infix operator with given precedence.
8579 * @param parser the parser function
8580 * @param token_kind the token type of the infix operator
8581 * @param precedence the precedence of the operator
8583 static void register_infix_parser(parse_expression_infix_function parser,
8584 int token_kind, precedence_t precedence)
8586 expression_parser_function_t *entry = &expression_parsers[token_kind];
8588 assert(!entry->infix_parser);
8589 entry->infix_parser = parser;
8590 entry->infix_precedence = precedence;
8594 * Initialize the expression parsers.
8596 static void init_expression_parsers(void)
8598 memset(&expression_parsers, 0, sizeof(expression_parsers));
8600 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8601 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8602 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8603 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8604 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8605 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8606 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8607 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8608 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8609 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8610 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8611 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8612 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8613 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8614 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8615 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8616 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8617 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8618 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8619 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8620 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8621 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8622 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8623 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8624 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8625 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8626 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8627 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8628 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8629 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8630 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8631 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8632 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8633 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8634 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8635 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8636 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8638 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8639 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8640 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8641 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8642 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8643 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8644 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8645 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8646 register_expression_parser(parse_sizeof, T_sizeof);
8647 register_expression_parser(parse_alignof, T___alignof__);
8648 register_expression_parser(parse_extension, T___extension__);
8649 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8650 register_expression_parser(parse_delete, T_delete);
8651 register_expression_parser(parse_throw, T_throw);
8655 * Parse a asm statement arguments specification.
8657 static asm_argument_t *parse_asm_arguments(bool is_out)
8659 asm_argument_t *result = NULL;
8660 asm_argument_t **anchor = &result;
8662 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8663 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8666 add_anchor_token(']');
8667 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8668 rem_anchor_token(']');
8670 if (!argument->symbol)
8674 argument->constraints = parse_string_literals("asm argument");
8675 add_anchor_token(')');
8677 expression_t *expression = parse_expression();
8678 rem_anchor_token(')');
8680 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8681 * change size or type representation (e.g. int -> long is ok, but
8682 * int -> float is not) */
8683 if (expression->kind == EXPR_UNARY_CAST) {
8684 type_t *const type = expression->base.type;
8685 type_kind_t const kind = type->kind;
8686 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8689 if (kind == TYPE_ATOMIC) {
8690 atomic_type_kind_t const akind = type->atomic.akind;
8691 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8692 size = get_atomic_type_size(akind);
8694 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8695 size = get_type_size(type_void_ptr);
8699 expression_t *const value = expression->unary.value;
8700 type_t *const value_type = value->base.type;
8701 type_kind_t const value_kind = value_type->kind;
8703 unsigned value_flags;
8704 unsigned value_size;
8705 if (value_kind == TYPE_ATOMIC) {
8706 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8707 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8708 value_size = get_atomic_type_size(value_akind);
8709 } else if (value_kind == TYPE_POINTER) {
8710 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8711 value_size = get_type_size(type_void_ptr);
8716 if (value_flags != flags || value_size != size)
8720 } while (expression->kind == EXPR_UNARY_CAST);
8724 if (!is_lvalue(expression)) {
8725 errorf(&expression->base.source_position,
8726 "asm output argument is not an lvalue");
8729 if (argument->constraints.begin[0] == '=')
8730 determine_lhs_ent(expression, NULL);
8732 mark_vars_read(expression, NULL);
8734 mark_vars_read(expression, NULL);
8736 argument->expression = expression;
8739 set_address_taken(expression, true);
8742 anchor = &argument->next;
8752 * Parse a asm statement clobber specification.
8754 static asm_clobber_t *parse_asm_clobbers(void)
8756 asm_clobber_t *result = NULL;
8757 asm_clobber_t **anchor = &result;
8759 while (token.kind == T_STRING_LITERAL) {
8760 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8761 clobber->clobber = parse_string_literals(NULL);
8764 anchor = &clobber->next;
8774 * Parse an asm statement.
8776 static statement_t *parse_asm_statement(void)
8778 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8779 asm_statement_t *asm_statement = &statement->asms;
8782 add_anchor_token(')');
8783 add_anchor_token(':');
8784 add_anchor_token(T_STRING_LITERAL);
8786 if (next_if(T_volatile))
8787 asm_statement->is_volatile = true;
8790 rem_anchor_token(T_STRING_LITERAL);
8791 asm_statement->asm_text = parse_string_literals("asm statement");
8794 asm_statement->outputs = parse_asm_arguments(true);
8797 asm_statement->inputs = parse_asm_arguments(false);
8799 rem_anchor_token(':');
8801 asm_statement->clobbers = parse_asm_clobbers();
8803 rem_anchor_token(')');
8807 if (asm_statement->outputs == NULL) {
8808 /* GCC: An 'asm' instruction without any output operands will be treated
8809 * identically to a volatile 'asm' instruction. */
8810 asm_statement->is_volatile = true;
8816 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8818 statement_t *inner_stmt;
8819 switch (token.kind) {
8821 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8822 inner_stmt = create_error_statement();
8826 if (label->kind == STATEMENT_LABEL) {
8827 /* Eat an empty statement here, to avoid the warning about an empty
8828 * statement after a label. label:; is commonly used to have a label
8829 * before a closing brace. */
8830 inner_stmt = create_empty_statement();
8837 inner_stmt = parse_statement();
8838 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8839 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8840 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8841 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8849 * Parse a case statement.
8851 static statement_t *parse_case_statement(void)
8853 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8854 source_position_t *const pos = &statement->base.source_position;
8857 add_anchor_token(':');
8859 expression_t *expression = parse_expression();
8860 type_t *expression_type = expression->base.type;
8861 type_t *skipped = skip_typeref(expression_type);
8862 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8863 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8864 expression, expression_type);
8867 type_t *type = expression_type;
8868 if (current_switch != NULL) {
8869 type_t *switch_type = current_switch->expression->base.type;
8870 if (is_type_valid(switch_type)) {
8871 expression = create_implicit_cast(expression, switch_type);
8875 statement->case_label.expression = expression;
8876 expression_classification_t const expr_class = is_constant_expression(expression);
8877 if (expr_class != EXPR_CLASS_CONSTANT) {
8878 if (expr_class != EXPR_CLASS_ERROR) {
8879 errorf(pos, "case label does not reduce to an integer constant");
8881 statement->case_label.is_bad = true;
8883 long const val = fold_constant_to_int(expression);
8884 statement->case_label.first_case = val;
8885 statement->case_label.last_case = val;
8889 if (next_if(T_DOTDOTDOT)) {
8890 expression_t *end_range = parse_expression();
8891 expression_type = expression->base.type;
8892 skipped = skip_typeref(expression_type);
8893 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8894 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8895 expression, expression_type);
8898 end_range = create_implicit_cast(end_range, type);
8899 statement->case_label.end_range = end_range;
8900 expression_classification_t const end_class = is_constant_expression(end_range);
8901 if (end_class != EXPR_CLASS_CONSTANT) {
8902 if (end_class != EXPR_CLASS_ERROR) {
8903 errorf(pos, "case range does not reduce to an integer constant");
8905 statement->case_label.is_bad = true;
8907 long const val = fold_constant_to_int(end_range);
8908 statement->case_label.last_case = val;
8910 if (val < statement->case_label.first_case) {
8911 statement->case_label.is_empty_range = true;
8912 warningf(WARN_OTHER, pos, "empty range specified");
8918 PUSH_PARENT(statement);
8920 rem_anchor_token(':');
8923 if (current_switch != NULL) {
8924 if (! statement->case_label.is_bad) {
8925 /* Check for duplicate case values */
8926 case_label_statement_t *c = &statement->case_label;
8927 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8928 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8931 if (c->last_case < l->first_case || c->first_case > l->last_case)
8934 errorf(pos, "duplicate case value (previously used %P)",
8935 &l->base.source_position);
8939 /* link all cases into the switch statement */
8940 if (current_switch->last_case == NULL) {
8941 current_switch->first_case = &statement->case_label;
8943 current_switch->last_case->next = &statement->case_label;
8945 current_switch->last_case = &statement->case_label;
8947 errorf(pos, "case label not within a switch statement");
8950 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
8957 * Parse a default statement.
8959 static statement_t *parse_default_statement(void)
8961 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8965 PUSH_PARENT(statement);
8969 if (current_switch != NULL) {
8970 const case_label_statement_t *def_label = current_switch->default_label;
8971 if (def_label != NULL) {
8972 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
8974 current_switch->default_label = &statement->case_label;
8976 /* link all cases into the switch statement */
8977 if (current_switch->last_case == NULL) {
8978 current_switch->first_case = &statement->case_label;
8980 current_switch->last_case->next = &statement->case_label;
8982 current_switch->last_case = &statement->case_label;
8985 errorf(&statement->base.source_position,
8986 "'default' label not within a switch statement");
8989 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
8996 * Parse a label statement.
8998 static statement_t *parse_label_statement(void)
9000 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9001 label_t *const label = get_label(NULL /* Cannot fail, token is T_IDENTIFIER. */);
9002 statement->label.label = label;
9004 PUSH_PARENT(statement);
9006 /* if statement is already set then the label is defined twice,
9007 * otherwise it was just mentioned in a goto/local label declaration so far
9009 source_position_t const* const pos = &statement->base.source_position;
9010 if (label->statement != NULL) {
9011 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9013 label->base.source_position = *pos;
9014 label->statement = statement;
9019 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9020 parse_attributes(NULL); // TODO process attributes
9023 statement->label.statement = parse_label_inner_statement(statement, "label");
9025 /* remember the labels in a list for later checking */
9026 *label_anchor = &statement->label;
9027 label_anchor = &statement->label.next;
9033 static statement_t *parse_inner_statement(void)
9035 statement_t *const stmt = parse_statement();
9036 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9037 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9038 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9039 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9045 * Parse an expression in parentheses and mark its variables as read.
9047 static expression_t *parse_condition(void)
9049 add_anchor_token(')');
9051 expression_t *const expr = parse_expression();
9052 mark_vars_read(expr, NULL);
9053 rem_anchor_token(')');
9059 * Parse an if statement.
9061 static statement_t *parse_if(void)
9063 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9067 PUSH_PARENT(statement);
9068 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9070 add_anchor_token(T_else);
9072 expression_t *const expr = parse_condition();
9073 statement->ifs.condition = expr;
9074 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9076 semantic_condition(expr, "condition of 'if'-statment");
9078 statement_t *const true_stmt = parse_inner_statement();
9079 statement->ifs.true_statement = true_stmt;
9080 rem_anchor_token(T_else);
9082 if (true_stmt->kind == STATEMENT_EMPTY) {
9083 warningf(WARN_EMPTY_BODY, HERE,
9084 "suggest braces around empty body in an ‘if’ statement");
9087 if (next_if(T_else)) {
9088 statement->ifs.false_statement = parse_inner_statement();
9090 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9091 warningf(WARN_EMPTY_BODY, HERE,
9092 "suggest braces around empty body in an ‘if’ statement");
9094 } else if (true_stmt->kind == STATEMENT_IF &&
9095 true_stmt->ifs.false_statement != NULL) {
9096 source_position_t const *const pos = &true_stmt->base.source_position;
9097 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9106 * Check that all enums are handled in a switch.
9108 * @param statement the switch statement to check
9110 static void check_enum_cases(const switch_statement_t *statement)
9112 if (!is_warn_on(WARN_SWITCH_ENUM))
9114 const type_t *type = skip_typeref(statement->expression->base.type);
9115 if (! is_type_enum(type))
9117 const enum_type_t *enumt = &type->enumt;
9119 /* if we have a default, no warnings */
9120 if (statement->default_label != NULL)
9123 /* FIXME: calculation of value should be done while parsing */
9124 /* TODO: quadratic algorithm here. Change to an n log n one */
9125 long last_value = -1;
9126 const entity_t *entry = enumt->enume->base.next;
9127 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9128 entry = entry->base.next) {
9129 const expression_t *expression = entry->enum_value.value;
9130 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9132 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9133 if (l->expression == NULL)
9135 if (l->first_case <= value && value <= l->last_case) {
9141 source_position_t const *const pos = &statement->base.source_position;
9142 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9149 * Parse a switch statement.
9151 static statement_t *parse_switch(void)
9153 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9157 PUSH_PARENT(statement);
9158 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9160 expression_t *const expr = parse_condition();
9161 type_t * type = skip_typeref(expr->base.type);
9162 if (is_type_integer(type)) {
9163 type = promote_integer(type);
9164 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9165 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9167 } else if (is_type_valid(type)) {
9168 errorf(&expr->base.source_position,
9169 "switch quantity is not an integer, but '%T'", type);
9170 type = type_error_type;
9172 statement->switchs.expression = create_implicit_cast(expr, type);
9174 switch_statement_t *rem = current_switch;
9175 current_switch = &statement->switchs;
9176 statement->switchs.body = parse_inner_statement();
9177 current_switch = rem;
9179 if (statement->switchs.default_label == NULL) {
9180 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9182 check_enum_cases(&statement->switchs);
9189 static statement_t *parse_loop_body(statement_t *const loop)
9191 statement_t *const rem = current_loop;
9192 current_loop = loop;
9194 statement_t *const body = parse_inner_statement();
9201 * Parse a while statement.
9203 static statement_t *parse_while(void)
9205 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9209 PUSH_PARENT(statement);
9210 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9212 expression_t *const cond = parse_condition();
9213 statement->whiles.condition = cond;
9214 /* §6.8.5:2 The controlling expression of an iteration statement shall
9215 * have scalar type. */
9216 semantic_condition(cond, "condition of 'while'-statement");
9218 statement->whiles.body = parse_loop_body(statement);
9226 * Parse a do statement.
9228 static statement_t *parse_do(void)
9230 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9234 PUSH_PARENT(statement);
9235 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9237 add_anchor_token(T_while);
9238 statement->do_while.body = parse_loop_body(statement);
9239 rem_anchor_token(T_while);
9242 expression_t *const cond = parse_condition();
9243 statement->do_while.condition = cond;
9244 /* §6.8.5:2 The controlling expression of an iteration statement shall
9245 * have scalar type. */
9246 semantic_condition(cond, "condition of 'do-while'-statement");
9255 * Parse a for statement.
9257 static statement_t *parse_for(void)
9259 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9263 PUSH_PARENT(statement);
9264 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9266 add_anchor_token(')');
9272 } else if (is_declaration_specifier(&token)) {
9273 parse_declaration(record_entity, DECL_FLAGS_NONE);
9275 add_anchor_token(';');
9276 expression_t *const init = parse_expression();
9277 statement->fors.initialisation = init;
9278 mark_vars_read(init, ENT_ANY);
9279 if (!expression_has_effect(init)) {
9280 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9282 rem_anchor_token(';');
9288 if (token.kind != ';') {
9289 add_anchor_token(';');
9290 expression_t *const cond = parse_expression();
9291 statement->fors.condition = cond;
9292 /* §6.8.5:2 The controlling expression of an iteration statement
9293 * shall have scalar type. */
9294 semantic_condition(cond, "condition of 'for'-statement");
9295 mark_vars_read(cond, NULL);
9296 rem_anchor_token(';');
9299 if (token.kind != ')') {
9300 expression_t *const step = parse_expression();
9301 statement->fors.step = step;
9302 mark_vars_read(step, ENT_ANY);
9303 if (!expression_has_effect(step)) {
9304 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9307 rem_anchor_token(')');
9309 statement->fors.body = parse_loop_body(statement);
9317 * Parse a goto statement.
9319 static statement_t *parse_goto(void)
9321 statement_t *statement;
9322 if (GNU_MODE && look_ahead(1)->kind == '*') {
9323 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9327 expression_t *expression = parse_expression();
9328 mark_vars_read(expression, NULL);
9330 /* Argh: although documentation says the expression must be of type void*,
9331 * gcc accepts anything that can be casted into void* without error */
9332 type_t *type = expression->base.type;
9334 if (type != type_error_type) {
9335 if (!is_type_pointer(type) && !is_type_integer(type)) {
9336 errorf(&expression->base.source_position,
9337 "cannot convert to a pointer type");
9338 } else if (type != type_void_ptr) {
9339 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9341 expression = create_implicit_cast(expression, type_void_ptr);
9344 statement->computed_goto.expression = expression;
9346 statement = allocate_statement_zero(STATEMENT_GOTO);
9349 label_t *const label = get_label("while parsing goto");
9352 statement->gotos.label = label;
9354 /* remember the goto's in a list for later checking */
9355 *goto_anchor = &statement->gotos;
9356 goto_anchor = &statement->gotos.next;
9358 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9367 * Parse a continue statement.
9369 static statement_t *parse_continue(void)
9371 if (current_loop == NULL) {
9372 errorf(HERE, "continue statement not within loop");
9375 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9383 * Parse a break statement.
9385 static statement_t *parse_break(void)
9387 if (current_switch == NULL && current_loop == NULL) {
9388 errorf(HERE, "break statement not within loop or switch");
9391 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9399 * Parse a __leave statement.
9401 static statement_t *parse_leave_statement(void)
9403 if (current_try == NULL) {
9404 errorf(HERE, "__leave statement not within __try");
9407 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9415 * Check if a given entity represents a local variable.
9417 static bool is_local_variable(const entity_t *entity)
9419 if (entity->kind != ENTITY_VARIABLE)
9422 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9423 case STORAGE_CLASS_AUTO:
9424 case STORAGE_CLASS_REGISTER: {
9425 const type_t *type = skip_typeref(entity->declaration.type);
9426 if (is_type_function(type)) {
9438 * Check if a given expression represents a local variable.
9440 static bool expression_is_local_variable(const expression_t *expression)
9442 if (expression->base.kind != EXPR_REFERENCE) {
9445 const entity_t *entity = expression->reference.entity;
9446 return is_local_variable(entity);
9449 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9451 if (c_mode & _CXX || strict_mode) {
9454 warningf(WARN_OTHER, pos, msg);
9459 * Parse a return statement.
9461 static statement_t *parse_return(void)
9463 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9466 expression_t *return_value = NULL;
9467 if (token.kind != ';') {
9468 return_value = parse_expression();
9469 mark_vars_read(return_value, NULL);
9472 const type_t *const func_type = skip_typeref(current_function->base.type);
9473 assert(is_type_function(func_type));
9474 type_t *const return_type = skip_typeref(func_type->function.return_type);
9476 source_position_t const *const pos = &statement->base.source_position;
9477 if (return_value != NULL) {
9478 type_t *return_value_type = skip_typeref(return_value->base.type);
9480 if (is_type_void(return_type)) {
9481 if (!is_type_void(return_value_type)) {
9482 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9483 /* Only warn in C mode, because GCC does the same */
9484 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9485 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9486 /* Only warn in C mode, because GCC does the same */
9487 err_or_warn(pos, "'return' with expression in function returning 'void'");
9490 assign_error_t error = semantic_assign(return_type, return_value);
9491 report_assign_error(error, return_type, return_value, "'return'",
9494 return_value = create_implicit_cast(return_value, return_type);
9495 /* check for returning address of a local var */
9496 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9497 const expression_t *expression = return_value->unary.value;
9498 if (expression_is_local_variable(expression)) {
9499 warningf(WARN_OTHER, pos, "function returns address of local variable");
9502 } else if (!is_type_void(return_type)) {
9503 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9504 err_or_warn(pos, "'return' without value, in function returning non-void");
9506 statement->returns.value = return_value;
9513 * Parse a declaration statement.
9515 static statement_t *parse_declaration_statement(void)
9517 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9519 entity_t *before = current_scope->last_entity;
9521 parse_external_declaration();
9523 parse_declaration(record_entity, DECL_FLAGS_NONE);
9526 declaration_statement_t *const decl = &statement->declaration;
9527 entity_t *const begin =
9528 before != NULL ? before->base.next : current_scope->entities;
9529 decl->declarations_begin = begin;
9530 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9536 * Parse an expression statement, ie. expr ';'.
9538 static statement_t *parse_expression_statement(void)
9540 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9542 expression_t *const expr = parse_expression();
9543 statement->expression.expression = expr;
9544 mark_vars_read(expr, ENT_ANY);
9551 * Parse a microsoft __try { } __finally { } or
9552 * __try{ } __except() { }
9554 static statement_t *parse_ms_try_statment(void)
9556 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9559 PUSH_PARENT(statement);
9561 ms_try_statement_t *rem = current_try;
9562 current_try = &statement->ms_try;
9563 statement->ms_try.try_statement = parse_compound_statement(false);
9568 if (next_if(T___except)) {
9569 expression_t *const expr = parse_condition();
9570 type_t * type = skip_typeref(expr->base.type);
9571 if (is_type_integer(type)) {
9572 type = promote_integer(type);
9573 } else if (is_type_valid(type)) {
9574 errorf(&expr->base.source_position,
9575 "__expect expression is not an integer, but '%T'", type);
9576 type = type_error_type;
9578 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9579 } else if (!next_if(T__finally)) {
9580 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9582 statement->ms_try.final_statement = parse_compound_statement(false);
9586 static statement_t *parse_empty_statement(void)
9588 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9589 statement_t *const statement = create_empty_statement();
9594 static statement_t *parse_local_label_declaration(void)
9596 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9600 entity_t *begin = NULL;
9601 entity_t *end = NULL;
9602 entity_t **anchor = &begin;
9603 add_anchor_token(';');
9604 add_anchor_token(',');
9606 source_position_t pos;
9607 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9609 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9610 if (entity != NULL && entity->base.parent_scope == current_scope) {
9611 source_position_t const *const ppos = &entity->base.source_position;
9612 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9614 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9615 entity->base.parent_scope = current_scope;
9618 anchor = &entity->base.next;
9621 environment_push(entity);
9624 } while (next_if(','));
9625 rem_anchor_token(',');
9626 rem_anchor_token(';');
9628 statement->declaration.declarations_begin = begin;
9629 statement->declaration.declarations_end = end;
9633 static void parse_namespace_definition(void)
9637 entity_t *entity = NULL;
9638 symbol_t *symbol = NULL;
9640 if (token.kind == T_IDENTIFIER) {
9641 symbol = token.base.symbol;
9642 entity = get_entity(symbol, NAMESPACE_NORMAL);
9643 if (entity && entity->kind != ENTITY_NAMESPACE) {
9645 if (entity->base.parent_scope == current_scope && is_entity_valid(entity)) {
9646 error_redefined_as_different_kind(HERE, entity, ENTITY_NAMESPACE);
9652 if (entity == NULL) {
9653 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9654 entity->base.parent_scope = current_scope;
9657 if (token.kind == '=') {
9658 /* TODO: parse namespace alias */
9659 panic("namespace alias definition not supported yet");
9662 environment_push(entity);
9663 append_entity(current_scope, entity);
9665 PUSH_SCOPE(&entity->namespacee.members);
9666 PUSH_CURRENT_ENTITY(entity);
9668 add_anchor_token('}');
9671 rem_anchor_token('}');
9674 POP_CURRENT_ENTITY();
9679 * Parse a statement.
9680 * There's also parse_statement() which additionally checks for
9681 * "statement has no effect" warnings
9683 static statement_t *intern_parse_statement(void)
9685 /* declaration or statement */
9686 statement_t *statement;
9687 switch (token.kind) {
9688 case T_IDENTIFIER: {
9689 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9690 if (la1_type == ':') {
9691 statement = parse_label_statement();
9692 } else if (is_typedef_symbol(token.base.symbol)) {
9693 statement = parse_declaration_statement();
9695 /* it's an identifier, the grammar says this must be an
9696 * expression statement. However it is common that users mistype
9697 * declaration types, so we guess a bit here to improve robustness
9698 * for incorrect programs */
9702 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9704 statement = parse_expression_statement();
9708 statement = parse_declaration_statement();
9716 case T___extension__: {
9717 /* This can be a prefix to a declaration or an expression statement.
9718 * We simply eat it now and parse the rest with tail recursion. */
9720 statement = intern_parse_statement();
9726 statement = parse_declaration_statement();
9730 statement = parse_local_label_declaration();
9733 case ';': statement = parse_empty_statement(); break;
9734 case '{': statement = parse_compound_statement(false); break;
9735 case T___leave: statement = parse_leave_statement(); break;
9736 case T___try: statement = parse_ms_try_statment(); break;
9737 case T_asm: statement = parse_asm_statement(); break;
9738 case T_break: statement = parse_break(); break;
9739 case T_case: statement = parse_case_statement(); break;
9740 case T_continue: statement = parse_continue(); break;
9741 case T_default: statement = parse_default_statement(); break;
9742 case T_do: statement = parse_do(); break;
9743 case T_for: statement = parse_for(); break;
9744 case T_goto: statement = parse_goto(); break;
9745 case T_if: statement = parse_if(); break;
9746 case T_return: statement = parse_return(); break;
9747 case T_switch: statement = parse_switch(); break;
9748 case T_while: statement = parse_while(); break;
9751 statement = parse_expression_statement();
9755 errorf(HERE, "unexpected token %K while parsing statement", &token);
9756 statement = create_error_statement();
9765 * parse a statement and emits "statement has no effect" warning if needed
9766 * (This is really a wrapper around intern_parse_statement with check for 1
9767 * single warning. It is needed, because for statement expressions we have
9768 * to avoid the warning on the last statement)
9770 static statement_t *parse_statement(void)
9772 statement_t *statement = intern_parse_statement();
9774 if (statement->kind == STATEMENT_EXPRESSION) {
9775 expression_t *expression = statement->expression.expression;
9776 if (!expression_has_effect(expression)) {
9777 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9785 * Parse a compound statement.
9787 static statement_t *parse_compound_statement(bool inside_expression_statement)
9789 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9791 PUSH_PARENT(statement);
9792 PUSH_SCOPE(&statement->compound.scope);
9795 add_anchor_token('}');
9796 /* tokens, which can start a statement */
9797 /* TODO MS, __builtin_FOO */
9798 add_anchor_token('!');
9799 add_anchor_token('&');
9800 add_anchor_token('(');
9801 add_anchor_token('*');
9802 add_anchor_token('+');
9803 add_anchor_token('-');
9804 add_anchor_token(';');
9805 add_anchor_token('{');
9806 add_anchor_token('~');
9807 add_anchor_token(T_CHARACTER_CONSTANT);
9808 add_anchor_token(T_COLONCOLON);
9809 add_anchor_token(T_IDENTIFIER);
9810 add_anchor_token(T_MINUSMINUS);
9811 add_anchor_token(T_NUMBER);
9812 add_anchor_token(T_PLUSPLUS);
9813 add_anchor_token(T_STRING_LITERAL);
9814 add_anchor_token(T__Bool);
9815 add_anchor_token(T__Complex);
9816 add_anchor_token(T__Imaginary);
9817 add_anchor_token(T___PRETTY_FUNCTION__);
9818 add_anchor_token(T___alignof__);
9819 add_anchor_token(T___attribute__);
9820 add_anchor_token(T___builtin_va_start);
9821 add_anchor_token(T___extension__);
9822 add_anchor_token(T___func__);
9823 add_anchor_token(T___imag__);
9824 add_anchor_token(T___label__);
9825 add_anchor_token(T___real__);
9826 add_anchor_token(T___thread);
9827 add_anchor_token(T_asm);
9828 add_anchor_token(T_auto);
9829 add_anchor_token(T_bool);
9830 add_anchor_token(T_break);
9831 add_anchor_token(T_case);
9832 add_anchor_token(T_char);
9833 add_anchor_token(T_class);
9834 add_anchor_token(T_const);
9835 add_anchor_token(T_const_cast);
9836 add_anchor_token(T_continue);
9837 add_anchor_token(T_default);
9838 add_anchor_token(T_delete);
9839 add_anchor_token(T_double);
9840 add_anchor_token(T_do);
9841 add_anchor_token(T_dynamic_cast);
9842 add_anchor_token(T_enum);
9843 add_anchor_token(T_extern);
9844 add_anchor_token(T_false);
9845 add_anchor_token(T_float);
9846 add_anchor_token(T_for);
9847 add_anchor_token(T_goto);
9848 add_anchor_token(T_if);
9849 add_anchor_token(T_inline);
9850 add_anchor_token(T_int);
9851 add_anchor_token(T_long);
9852 add_anchor_token(T_new);
9853 add_anchor_token(T_operator);
9854 add_anchor_token(T_register);
9855 add_anchor_token(T_reinterpret_cast);
9856 add_anchor_token(T_restrict);
9857 add_anchor_token(T_return);
9858 add_anchor_token(T_short);
9859 add_anchor_token(T_signed);
9860 add_anchor_token(T_sizeof);
9861 add_anchor_token(T_static);
9862 add_anchor_token(T_static_cast);
9863 add_anchor_token(T_struct);
9864 add_anchor_token(T_switch);
9865 add_anchor_token(T_template);
9866 add_anchor_token(T_this);
9867 add_anchor_token(T_throw);
9868 add_anchor_token(T_true);
9869 add_anchor_token(T_try);
9870 add_anchor_token(T_typedef);
9871 add_anchor_token(T_typeid);
9872 add_anchor_token(T_typename);
9873 add_anchor_token(T_typeof);
9874 add_anchor_token(T_union);
9875 add_anchor_token(T_unsigned);
9876 add_anchor_token(T_using);
9877 add_anchor_token(T_void);
9878 add_anchor_token(T_volatile);
9879 add_anchor_token(T_wchar_t);
9880 add_anchor_token(T_while);
9882 statement_t **anchor = &statement->compound.statements;
9883 bool only_decls_so_far = true;
9884 while (token.kind != '}' && token.kind != T_EOF) {
9885 statement_t *sub_statement = intern_parse_statement();
9886 if (sub_statement->kind == STATEMENT_ERROR) {
9890 if (sub_statement->kind != STATEMENT_DECLARATION) {
9891 only_decls_so_far = false;
9892 } else if (!only_decls_so_far) {
9893 source_position_t const *const pos = &sub_statement->base.source_position;
9894 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
9897 *anchor = sub_statement;
9898 anchor = &sub_statement->base.next;
9902 /* look over all statements again to produce no effect warnings */
9903 if (is_warn_on(WARN_UNUSED_VALUE)) {
9904 statement_t *sub_statement = statement->compound.statements;
9905 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9906 if (sub_statement->kind != STATEMENT_EXPRESSION)
9908 /* don't emit a warning for the last expression in an expression
9909 * statement as it has always an effect */
9910 if (inside_expression_statement && sub_statement->base.next == NULL)
9913 expression_t *expression = sub_statement->expression.expression;
9914 if (!expression_has_effect(expression)) {
9915 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9920 rem_anchor_token(T_while);
9921 rem_anchor_token(T_wchar_t);
9922 rem_anchor_token(T_volatile);
9923 rem_anchor_token(T_void);
9924 rem_anchor_token(T_using);
9925 rem_anchor_token(T_unsigned);
9926 rem_anchor_token(T_union);
9927 rem_anchor_token(T_typeof);
9928 rem_anchor_token(T_typename);
9929 rem_anchor_token(T_typeid);
9930 rem_anchor_token(T_typedef);
9931 rem_anchor_token(T_try);
9932 rem_anchor_token(T_true);
9933 rem_anchor_token(T_throw);
9934 rem_anchor_token(T_this);
9935 rem_anchor_token(T_template);
9936 rem_anchor_token(T_switch);
9937 rem_anchor_token(T_struct);
9938 rem_anchor_token(T_static_cast);
9939 rem_anchor_token(T_static);
9940 rem_anchor_token(T_sizeof);
9941 rem_anchor_token(T_signed);
9942 rem_anchor_token(T_short);
9943 rem_anchor_token(T_return);
9944 rem_anchor_token(T_restrict);
9945 rem_anchor_token(T_reinterpret_cast);
9946 rem_anchor_token(T_register);
9947 rem_anchor_token(T_operator);
9948 rem_anchor_token(T_new);
9949 rem_anchor_token(T_long);
9950 rem_anchor_token(T_int);
9951 rem_anchor_token(T_inline);
9952 rem_anchor_token(T_if);
9953 rem_anchor_token(T_goto);
9954 rem_anchor_token(T_for);
9955 rem_anchor_token(T_float);
9956 rem_anchor_token(T_false);
9957 rem_anchor_token(T_extern);
9958 rem_anchor_token(T_enum);
9959 rem_anchor_token(T_dynamic_cast);
9960 rem_anchor_token(T_do);
9961 rem_anchor_token(T_double);
9962 rem_anchor_token(T_delete);
9963 rem_anchor_token(T_default);
9964 rem_anchor_token(T_continue);
9965 rem_anchor_token(T_const_cast);
9966 rem_anchor_token(T_const);
9967 rem_anchor_token(T_class);
9968 rem_anchor_token(T_char);
9969 rem_anchor_token(T_case);
9970 rem_anchor_token(T_break);
9971 rem_anchor_token(T_bool);
9972 rem_anchor_token(T_auto);
9973 rem_anchor_token(T_asm);
9974 rem_anchor_token(T___thread);
9975 rem_anchor_token(T___real__);
9976 rem_anchor_token(T___label__);
9977 rem_anchor_token(T___imag__);
9978 rem_anchor_token(T___func__);
9979 rem_anchor_token(T___extension__);
9980 rem_anchor_token(T___builtin_va_start);
9981 rem_anchor_token(T___attribute__);
9982 rem_anchor_token(T___alignof__);
9983 rem_anchor_token(T___PRETTY_FUNCTION__);
9984 rem_anchor_token(T__Imaginary);
9985 rem_anchor_token(T__Complex);
9986 rem_anchor_token(T__Bool);
9987 rem_anchor_token(T_STRING_LITERAL);
9988 rem_anchor_token(T_PLUSPLUS);
9989 rem_anchor_token(T_NUMBER);
9990 rem_anchor_token(T_MINUSMINUS);
9991 rem_anchor_token(T_IDENTIFIER);
9992 rem_anchor_token(T_COLONCOLON);
9993 rem_anchor_token(T_CHARACTER_CONSTANT);
9994 rem_anchor_token('~');
9995 rem_anchor_token('{');
9996 rem_anchor_token(';');
9997 rem_anchor_token('-');
9998 rem_anchor_token('+');
9999 rem_anchor_token('*');
10000 rem_anchor_token('(');
10001 rem_anchor_token('&');
10002 rem_anchor_token('!');
10003 rem_anchor_token('}');
10011 * Check for unused global static functions and variables
10013 static void check_unused_globals(void)
10015 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10018 for (const entity_t *entity = file_scope->entities; entity != NULL;
10019 entity = entity->base.next) {
10020 if (!is_declaration(entity))
10023 const declaration_t *declaration = &entity->declaration;
10024 if (declaration->used ||
10025 declaration->modifiers & DM_UNUSED ||
10026 declaration->modifiers & DM_USED ||
10027 declaration->storage_class != STORAGE_CLASS_STATIC)
10032 if (entity->kind == ENTITY_FUNCTION) {
10033 /* inhibit warning for static inline functions */
10034 if (entity->function.is_inline)
10037 why = WARN_UNUSED_FUNCTION;
10038 s = entity->function.statement != NULL ? "defined" : "declared";
10040 why = WARN_UNUSED_VARIABLE;
10044 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10048 static void parse_global_asm(void)
10050 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10053 add_anchor_token(';');
10054 add_anchor_token(')');
10055 add_anchor_token(T_STRING_LITERAL);
10058 rem_anchor_token(T_STRING_LITERAL);
10059 statement->asms.asm_text = parse_string_literals("global asm");
10060 statement->base.next = unit->global_asm;
10061 unit->global_asm = statement;
10063 rem_anchor_token(')');
10065 rem_anchor_token(';');
10069 static void parse_linkage_specification(void)
10073 source_position_t const pos = *HERE;
10074 char const *const linkage = parse_string_literals(NULL).begin;
10076 linkage_kind_t old_linkage = current_linkage;
10077 linkage_kind_t new_linkage;
10078 if (streq(linkage, "C")) {
10079 new_linkage = LINKAGE_C;
10080 } else if (streq(linkage, "C++")) {
10081 new_linkage = LINKAGE_CXX;
10083 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10084 new_linkage = LINKAGE_C;
10086 current_linkage = new_linkage;
10088 if (next_if('{')) {
10095 assert(current_linkage == new_linkage);
10096 current_linkage = old_linkage;
10099 static void parse_external(void)
10101 switch (token.kind) {
10103 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10104 parse_linkage_specification();
10106 DECLARATION_START_NO_EXTERN
10108 case T___extension__:
10109 /* tokens below are for implicit int */
10110 case '&': /* & x; -> int& x; (and error later, because C++ has no
10112 case '*': /* * x; -> int* x; */
10113 case '(': /* (x); -> int (x); */
10115 parse_external_declaration();
10121 parse_global_asm();
10125 parse_namespace_definition();
10129 if (!strict_mode) {
10130 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10137 errorf(HERE, "stray %K outside of function", &token);
10138 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10139 eat_until_matching_token(token.kind);
10145 static void parse_externals(void)
10147 add_anchor_token('}');
10148 add_anchor_token(T_EOF);
10151 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10152 unsigned short token_anchor_copy[T_LAST_TOKEN];
10153 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10156 while (token.kind != T_EOF && token.kind != '}') {
10158 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10159 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10161 /* the anchor set and its copy differs */
10162 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10165 if (in_gcc_extension) {
10166 /* an gcc extension scope was not closed */
10167 internal_errorf(HERE, "Leaked __extension__");
10174 rem_anchor_token(T_EOF);
10175 rem_anchor_token('}');
10179 * Parse a translation unit.
10181 static void parse_translation_unit(void)
10183 add_anchor_token(T_EOF);
10188 if (token.kind == T_EOF)
10191 errorf(HERE, "stray %K outside of function", &token);
10192 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10193 eat_until_matching_token(token.kind);
10198 void set_default_visibility(elf_visibility_tag_t visibility)
10200 default_visibility = visibility;
10206 * @return the translation unit or NULL if errors occurred.
10208 void start_parsing(void)
10210 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10211 label_stack = NEW_ARR_F(stack_entry_t, 0);
10213 print_to_file(stderr);
10215 assert(unit == NULL);
10216 unit = allocate_ast_zero(sizeof(unit[0]));
10218 assert(file_scope == NULL);
10219 file_scope = &unit->scope;
10221 assert(current_scope == NULL);
10222 scope_push(&unit->scope);
10224 create_gnu_builtins();
10226 create_microsoft_intrinsics();
10229 translation_unit_t *finish_parsing(void)
10231 assert(current_scope == &unit->scope);
10234 assert(file_scope == &unit->scope);
10235 check_unused_globals();
10238 DEL_ARR_F(environment_stack);
10239 DEL_ARR_F(label_stack);
10241 translation_unit_t *result = unit;
10246 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10247 * are given length one. */
10248 static void complete_incomplete_arrays(void)
10250 size_t n = ARR_LEN(incomplete_arrays);
10251 for (size_t i = 0; i != n; ++i) {
10252 declaration_t *const decl = incomplete_arrays[i];
10253 type_t *const type = skip_typeref(decl->type);
10255 if (!is_type_incomplete(type))
10258 source_position_t const *const pos = &decl->base.source_position;
10259 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10261 type_t *const new_type = duplicate_type(type);
10262 new_type->array.size_constant = true;
10263 new_type->array.has_implicit_size = true;
10264 new_type->array.size = 1;
10266 type_t *const result = identify_new_type(new_type);
10268 decl->type = result;
10272 static void prepare_main_collect2(entity_t *const entity)
10274 PUSH_SCOPE(&entity->function.statement->compound.scope);
10276 // create call to __main
10277 symbol_t *symbol = symbol_table_insert("__main");
10278 entity_t *subsubmain_ent
10279 = create_implicit_function(symbol, &builtin_source_position);
10281 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10282 type_t *ftype = subsubmain_ent->declaration.type;
10283 ref->base.source_position = builtin_source_position;
10284 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10285 ref->reference.entity = subsubmain_ent;
10287 expression_t *call = allocate_expression_zero(EXPR_CALL);
10288 call->base.source_position = builtin_source_position;
10289 call->base.type = type_void;
10290 call->call.function = ref;
10292 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10293 expr_statement->base.source_position = builtin_source_position;
10294 expr_statement->expression.expression = call;
10296 statement_t *statement = entity->function.statement;
10297 assert(statement->kind == STATEMENT_COMPOUND);
10298 compound_statement_t *compounds = &statement->compound;
10300 expr_statement->base.next = compounds->statements;
10301 compounds->statements = expr_statement;
10308 lookahead_bufpos = 0;
10309 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10312 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10313 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10314 parse_translation_unit();
10315 complete_incomplete_arrays();
10316 DEL_ARR_F(incomplete_arrays);
10317 incomplete_arrays = NULL;
10321 * Initialize the parser.
10323 void init_parser(void)
10325 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10327 init_expression_parsers();
10328 obstack_init(&temp_obst);
10332 * Terminate the parser.
10334 void exit_parser(void)
10336 obstack_free(&temp_obst, NULL);