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);
2110 if (token.kind == '}') {
2113 add_anchor_token('}');
2115 rem_anchor_token('}');
2116 if (token.kind == '}') {
2121 /* advance to the next declaration if we are not at the end */
2122 advance_current_object(path, top_path_level);
2123 orig_type = path->top_type;
2124 if (orig_type != NULL)
2125 type = skip_typeref(orig_type);
2131 size_t len = ARR_LEN(initializers);
2132 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2133 result = allocate_ast_zero(size);
2134 result->kind = INITIALIZER_LIST;
2135 result->list.len = len;
2136 memcpy(&result->list.initializers, initializers,
2137 len * sizeof(initializers[0]));
2141 skip_initializers();
2143 DEL_ARR_F(initializers);
2144 ascend_to(path, top_path_level+1);
2148 static expression_t *make_size_literal(size_t value)
2150 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2151 literal->base.type = type_size_t;
2154 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2155 literal->literal.value = make_string(buf);
2161 * Parses an initializer. Parsers either a compound literal
2162 * (env->declaration == NULL) or an initializer of a declaration.
2164 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2166 type_t *type = skip_typeref(env->type);
2167 size_t max_index = 0;
2168 initializer_t *result;
2170 if (is_type_scalar(type)) {
2171 result = parse_scalar_initializer(type, env->must_be_constant);
2172 } else if (token.kind == '{') {
2176 memset(&path, 0, sizeof(path));
2177 path.top_type = env->type;
2178 path.path = NEW_ARR_F(type_path_entry_t, 0);
2180 descend_into_subtype(&path);
2182 add_anchor_token('}');
2183 result = parse_sub_initializer(&path, env->type, 1, env);
2184 rem_anchor_token('}');
2186 max_index = path.max_index;
2187 DEL_ARR_F(path.path);
2191 /* parse_scalar_initializer() also works in this case: we simply
2192 * have an expression without {} around it */
2193 result = parse_scalar_initializer(type, env->must_be_constant);
2196 /* §6.7.8:22 array initializers for arrays with unknown size determine
2197 * the array type size */
2198 if (is_type_array(type) && type->array.size_expression == NULL
2199 && result != NULL) {
2201 switch (result->kind) {
2202 case INITIALIZER_LIST:
2203 assert(max_index != 0xdeadbeaf);
2204 size = max_index + 1;
2207 case INITIALIZER_STRING: {
2208 size = get_string_len(&get_init_string(result)->value) + 1;
2212 case INITIALIZER_DESIGNATOR:
2213 case INITIALIZER_VALUE:
2214 /* can happen for parse errors */
2219 internal_errorf(HERE, "invalid initializer type");
2222 type_t *new_type = duplicate_type(type);
2224 new_type->array.size_expression = make_size_literal(size);
2225 new_type->array.size_constant = true;
2226 new_type->array.has_implicit_size = true;
2227 new_type->array.size = size;
2228 env->type = new_type;
2234 static void append_entity(scope_t *scope, entity_t *entity)
2236 if (scope->last_entity != NULL) {
2237 scope->last_entity->base.next = entity;
2239 scope->entities = entity;
2241 entity->base.parent_entity = current_entity;
2242 scope->last_entity = entity;
2246 static compound_t *parse_compound_type_specifier(bool is_struct)
2248 source_position_t const pos = *HERE;
2249 eat(is_struct ? T_struct : T_union);
2251 symbol_t *symbol = NULL;
2252 entity_t *entity = NULL;
2253 attribute_t *attributes = NULL;
2255 if (token.kind == T___attribute__) {
2256 attributes = parse_attributes(NULL);
2259 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2260 if (token.kind == T_IDENTIFIER) {
2261 /* the compound has a name, check if we have seen it already */
2262 symbol = token.base.symbol;
2263 entity = get_tag(symbol, kind);
2266 if (entity != NULL) {
2267 if (entity->base.parent_scope != current_scope &&
2268 (token.kind == '{' || token.kind == ';')) {
2269 /* we're in an inner scope and have a definition. Shadow
2270 * existing definition in outer scope */
2272 } else if (entity->compound.complete && token.kind == '{') {
2273 source_position_t const *const ppos = &entity->base.source_position;
2274 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2275 /* clear members in the hope to avoid further errors */
2276 entity->compound.members.entities = NULL;
2279 } else if (token.kind != '{') {
2280 char const *const msg =
2281 is_struct ? "while parsing struct type specifier" :
2282 "while parsing union type specifier";
2283 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2288 if (entity == NULL) {
2289 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2290 entity->compound.alignment = 1;
2291 entity->base.parent_scope = current_scope;
2292 if (symbol != NULL) {
2293 environment_push(entity);
2295 append_entity(current_scope, entity);
2298 if (token.kind == '{') {
2299 parse_compound_type_entries(&entity->compound);
2301 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2302 if (symbol == NULL) {
2303 assert(anonymous_entity == NULL);
2304 anonymous_entity = entity;
2308 if (attributes != NULL) {
2309 handle_entity_attributes(attributes, entity);
2312 return &entity->compound;
2315 static void parse_enum_entries(type_t *const enum_type)
2319 if (token.kind == '}') {
2320 errorf(HERE, "empty enum not allowed");
2325 add_anchor_token('}');
2326 add_anchor_token(',');
2328 add_anchor_token('=');
2329 source_position_t pos;
2330 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2331 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2332 entity->enum_value.enum_type = enum_type;
2333 rem_anchor_token('=');
2336 expression_t *value = parse_constant_expression();
2338 value = create_implicit_cast(value, enum_type);
2339 entity->enum_value.value = value;
2344 record_entity(entity, false);
2345 } while (next_if(',') && token.kind != '}');
2346 rem_anchor_token(',');
2347 rem_anchor_token('}');
2352 static type_t *parse_enum_specifier(void)
2354 source_position_t const pos = *HERE;
2359 switch (token.kind) {
2361 symbol = token.base.symbol;
2362 entity = get_tag(symbol, ENTITY_ENUM);
2365 if (entity != NULL) {
2366 if (entity->base.parent_scope != current_scope &&
2367 (token.kind == '{' || token.kind == ';')) {
2368 /* we're in an inner scope and have a definition. Shadow
2369 * existing definition in outer scope */
2371 } else if (entity->enume.complete && token.kind == '{') {
2372 source_position_t const *const ppos = &entity->base.source_position;
2373 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2384 parse_error_expected("while parsing enum type specifier",
2385 T_IDENTIFIER, '{', NULL);
2389 if (entity == NULL) {
2390 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2391 entity->base.parent_scope = current_scope;
2394 type_t *const type = allocate_type_zero(TYPE_ENUM);
2395 type->enumt.enume = &entity->enume;
2396 type->enumt.base.akind = ATOMIC_TYPE_INT;
2398 if (token.kind == '{') {
2399 if (symbol != NULL) {
2400 environment_push(entity);
2402 append_entity(current_scope, entity);
2403 entity->enume.complete = true;
2405 parse_enum_entries(type);
2406 parse_attributes(NULL);
2408 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2409 if (symbol == NULL) {
2410 assert(anonymous_entity == NULL);
2411 anonymous_entity = entity;
2413 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2414 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2421 * if a symbol is a typedef to another type, return true
2423 static bool is_typedef_symbol(symbol_t *symbol)
2425 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2426 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2429 static type_t *parse_typeof(void)
2435 add_anchor_token(')');
2438 expression_t *expression = NULL;
2440 switch (token.kind) {
2442 if (is_typedef_symbol(token.base.symbol)) {
2444 type = parse_typename();
2447 expression = parse_expression();
2448 type = revert_automatic_type_conversion(expression);
2453 rem_anchor_token(')');
2456 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2457 typeof_type->typeoft.expression = expression;
2458 typeof_type->typeoft.typeof_type = type;
2463 typedef enum specifiers_t {
2465 SPECIFIER_SIGNED = 1 << 0,
2466 SPECIFIER_UNSIGNED = 1 << 1,
2467 SPECIFIER_LONG = 1 << 2,
2468 SPECIFIER_INT = 1 << 3,
2469 SPECIFIER_DOUBLE = 1 << 4,
2470 SPECIFIER_CHAR = 1 << 5,
2471 SPECIFIER_WCHAR_T = 1 << 6,
2472 SPECIFIER_SHORT = 1 << 7,
2473 SPECIFIER_LONG_LONG = 1 << 8,
2474 SPECIFIER_FLOAT = 1 << 9,
2475 SPECIFIER_BOOL = 1 << 10,
2476 SPECIFIER_VOID = 1 << 11,
2477 SPECIFIER_INT8 = 1 << 12,
2478 SPECIFIER_INT16 = 1 << 13,
2479 SPECIFIER_INT32 = 1 << 14,
2480 SPECIFIER_INT64 = 1 << 15,
2481 SPECIFIER_INT128 = 1 << 16,
2482 SPECIFIER_COMPLEX = 1 << 17,
2483 SPECIFIER_IMAGINARY = 1 << 18,
2486 static type_t *get_typedef_type(symbol_t *symbol)
2488 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2489 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2492 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2493 type->typedeft.typedefe = &entity->typedefe;
2498 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2500 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2502 add_anchor_token(')');
2503 add_anchor_token(',');
2507 add_anchor_token('=');
2508 source_position_t pos;
2509 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2510 rem_anchor_token('=');
2512 symbol_t **prop = NULL;
2514 if (streq(prop_sym->string, "put")) {
2515 prop = &property->put_symbol;
2516 } else if (streq(prop_sym->string, "get")) {
2517 prop = &property->get_symbol;
2519 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2523 add_anchor_token(T_IDENTIFIER);
2525 rem_anchor_token(T_IDENTIFIER);
2527 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2529 *prop = sym ? sym : sym_anonymous;
2530 } while (next_if(','));
2531 rem_anchor_token(',');
2532 rem_anchor_token(')');
2534 attribute->a.property = property;
2540 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2542 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2543 if (next_if(T_restrict)) {
2544 kind = ATTRIBUTE_MS_RESTRICT;
2545 } else if (token.kind == T_IDENTIFIER) {
2546 char const *const name = token.base.symbol->string;
2547 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2549 const char *attribute_name = get_attribute_name(k);
2550 if (attribute_name != NULL && streq(attribute_name, name)) {
2556 if (kind == ATTRIBUTE_UNKNOWN) {
2557 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2560 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2564 attribute_t *attribute = allocate_attribute_zero(kind);
2567 if (kind == ATTRIBUTE_MS_PROPERTY) {
2568 return parse_attribute_ms_property(attribute);
2571 /* parse arguments */
2573 attribute->a.arguments = parse_attribute_arguments();
2578 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2582 add_anchor_token(')');
2584 if (token.kind != ')') {
2585 attribute_t **anchor = &first;
2587 while (*anchor != NULL)
2588 anchor = &(*anchor)->next;
2590 attribute_t *attribute
2591 = parse_microsoft_extended_decl_modifier_single();
2592 if (attribute == NULL)
2595 *anchor = attribute;
2596 anchor = &attribute->next;
2597 } while (next_if(','));
2599 rem_anchor_token(')');
2604 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2606 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2607 if (is_declaration(entity)) {
2608 entity->declaration.type = type_error_type;
2609 entity->declaration.implicit = true;
2610 } else if (kind == ENTITY_TYPEDEF) {
2611 entity->typedefe.type = type_error_type;
2612 entity->typedefe.builtin = true;
2614 if (kind != ENTITY_COMPOUND_MEMBER)
2615 record_entity(entity, false);
2619 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2621 type_t *type = NULL;
2622 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2623 unsigned type_specifiers = 0;
2624 bool newtype = false;
2625 bool saw_error = false;
2627 memset(specifiers, 0, sizeof(*specifiers));
2628 specifiers->source_position = *HERE;
2631 specifiers->attributes = parse_attributes(specifiers->attributes);
2633 switch (token.kind) {
2635 #define MATCH_STORAGE_CLASS(token, class) \
2637 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2638 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2640 specifiers->storage_class = class; \
2641 if (specifiers->thread_local) \
2642 goto check_thread_storage_class; \
2646 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2647 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2648 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2649 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2650 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2653 specifiers->attributes
2654 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2658 if (specifiers->thread_local) {
2659 errorf(HERE, "duplicate '__thread'");
2661 specifiers->thread_local = true;
2662 check_thread_storage_class:
2663 switch (specifiers->storage_class) {
2664 case STORAGE_CLASS_EXTERN:
2665 case STORAGE_CLASS_NONE:
2666 case STORAGE_CLASS_STATIC:
2670 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2671 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2672 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2673 wrong_thread_storage_class:
2674 errorf(HERE, "'__thread' used with '%s'", wrong);
2681 /* type qualifiers */
2682 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2684 qualifiers |= qualifier; \
2688 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2689 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2690 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2691 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2692 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2693 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2694 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2695 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2697 /* type specifiers */
2698 #define MATCH_SPECIFIER(token, specifier, name) \
2700 if (type_specifiers & specifier) { \
2701 errorf(HERE, "multiple " name " type specifiers given"); \
2703 type_specifiers |= specifier; \
2708 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2709 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2710 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2711 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2712 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2713 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2714 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2715 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2716 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2717 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2718 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2719 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2720 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2721 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2722 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2723 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2724 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2725 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2729 specifiers->is_inline = true;
2733 case T__forceinline:
2734 eat(T__forceinline);
2735 specifiers->modifiers |= DM_FORCEINLINE;
2740 if (type_specifiers & SPECIFIER_LONG_LONG) {
2741 errorf(HERE, "too many long type specifiers given");
2742 } else if (type_specifiers & SPECIFIER_LONG) {
2743 type_specifiers |= SPECIFIER_LONG_LONG;
2745 type_specifiers |= SPECIFIER_LONG;
2750 #define CHECK_DOUBLE_TYPE() \
2751 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2754 CHECK_DOUBLE_TYPE();
2755 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2757 type->compound.compound = parse_compound_type_specifier(true);
2760 CHECK_DOUBLE_TYPE();
2761 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2762 type->compound.compound = parse_compound_type_specifier(false);
2765 CHECK_DOUBLE_TYPE();
2766 type = parse_enum_specifier();
2769 CHECK_DOUBLE_TYPE();
2770 type = parse_typeof();
2772 case T___builtin_va_list:
2773 CHECK_DOUBLE_TYPE();
2774 type = duplicate_type(type_valist);
2775 eat(T___builtin_va_list);
2778 case T_IDENTIFIER: {
2779 /* only parse identifier if we haven't found a type yet */
2780 if (type != NULL || type_specifiers != 0) {
2781 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2782 * declaration, so it doesn't generate errors about expecting '(' or
2784 switch (look_ahead(1)->kind) {
2791 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2795 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2800 goto finish_specifiers;
2804 type_t *const typedef_type = get_typedef_type(token.base.symbol);
2805 if (typedef_type == NULL) {
2806 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2807 * declaration, so it doesn't generate 'implicit int' followed by more
2808 * errors later on. */
2809 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2815 errorf(HERE, "%K does not name a type", &token);
2817 entity_t *const entity = create_error_entity(token.base.symbol, ENTITY_TYPEDEF);
2819 type = allocate_type_zero(TYPE_TYPEDEF);
2820 type->typedeft.typedefe = &entity->typedefe;
2828 goto finish_specifiers;
2833 type = typedef_type;
2837 /* function specifier */
2839 goto finish_specifiers;
2844 specifiers->attributes = parse_attributes(specifiers->attributes);
2846 if (type == NULL || (saw_error && type_specifiers != 0)) {
2847 atomic_type_kind_t atomic_type;
2849 /* match valid basic types */
2850 switch (type_specifiers) {
2851 case SPECIFIER_VOID:
2852 atomic_type = ATOMIC_TYPE_VOID;
2854 case SPECIFIER_WCHAR_T:
2855 atomic_type = ATOMIC_TYPE_WCHAR_T;
2857 case SPECIFIER_CHAR:
2858 atomic_type = ATOMIC_TYPE_CHAR;
2860 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2861 atomic_type = ATOMIC_TYPE_SCHAR;
2863 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2864 atomic_type = ATOMIC_TYPE_UCHAR;
2866 case SPECIFIER_SHORT:
2867 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2868 case SPECIFIER_SHORT | SPECIFIER_INT:
2869 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2870 atomic_type = ATOMIC_TYPE_SHORT;
2872 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2873 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2874 atomic_type = ATOMIC_TYPE_USHORT;
2877 case SPECIFIER_SIGNED:
2878 case SPECIFIER_SIGNED | SPECIFIER_INT:
2879 atomic_type = ATOMIC_TYPE_INT;
2881 case SPECIFIER_UNSIGNED:
2882 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2883 atomic_type = ATOMIC_TYPE_UINT;
2885 case SPECIFIER_LONG:
2886 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2887 case SPECIFIER_LONG | SPECIFIER_INT:
2888 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2889 atomic_type = ATOMIC_TYPE_LONG;
2891 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2892 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2893 atomic_type = ATOMIC_TYPE_ULONG;
2896 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2897 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2898 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2899 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2901 atomic_type = ATOMIC_TYPE_LONGLONG;
2902 goto warn_about_long_long;
2904 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2905 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2907 atomic_type = ATOMIC_TYPE_ULONGLONG;
2908 warn_about_long_long:
2909 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2912 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2913 atomic_type = unsigned_int8_type_kind;
2916 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2917 atomic_type = unsigned_int16_type_kind;
2920 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2921 atomic_type = unsigned_int32_type_kind;
2924 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2925 atomic_type = unsigned_int64_type_kind;
2928 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2929 atomic_type = unsigned_int128_type_kind;
2932 case SPECIFIER_INT8:
2933 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2934 atomic_type = int8_type_kind;
2937 case SPECIFIER_INT16:
2938 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2939 atomic_type = int16_type_kind;
2942 case SPECIFIER_INT32:
2943 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2944 atomic_type = int32_type_kind;
2947 case SPECIFIER_INT64:
2948 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2949 atomic_type = int64_type_kind;
2952 case SPECIFIER_INT128:
2953 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2954 atomic_type = int128_type_kind;
2957 case SPECIFIER_FLOAT:
2958 atomic_type = ATOMIC_TYPE_FLOAT;
2960 case SPECIFIER_DOUBLE:
2961 atomic_type = ATOMIC_TYPE_DOUBLE;
2963 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2964 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2966 case SPECIFIER_BOOL:
2967 atomic_type = ATOMIC_TYPE_BOOL;
2969 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2970 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2971 atomic_type = ATOMIC_TYPE_FLOAT;
2973 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2974 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2975 atomic_type = ATOMIC_TYPE_DOUBLE;
2977 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2978 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2979 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2982 /* invalid specifier combination, give an error message */
2983 source_position_t const* const pos = &specifiers->source_position;
2984 if (type_specifiers == 0) {
2986 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
2987 if (!(c_mode & _CXX) && !strict_mode) {
2988 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
2989 atomic_type = ATOMIC_TYPE_INT;
2992 errorf(pos, "no type specifiers given in declaration");
2995 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
2996 (type_specifiers & SPECIFIER_UNSIGNED)) {
2997 errorf(pos, "signed and unsigned specifiers given");
2998 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2999 errorf(pos, "only integer types can be signed or unsigned");
3001 errorf(pos, "multiple datatypes in declaration");
3003 specifiers->type = type_error_type;
3008 if (type_specifiers & SPECIFIER_COMPLEX) {
3009 type = allocate_type_zero(TYPE_COMPLEX);
3010 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3011 type = allocate_type_zero(TYPE_IMAGINARY);
3013 type = allocate_type_zero(TYPE_ATOMIC);
3015 type->atomic.akind = atomic_type;
3017 } else if (type_specifiers != 0) {
3018 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3021 /* FIXME: check type qualifiers here */
3022 type->base.qualifiers = qualifiers;
3025 type = identify_new_type(type);
3027 type = typehash_insert(type);
3030 if (specifiers->attributes != NULL)
3031 type = handle_type_attributes(specifiers->attributes, type);
3032 specifiers->type = type;
3035 static type_qualifiers_t parse_type_qualifiers(void)
3037 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3040 switch (token.kind) {
3041 /* type qualifiers */
3042 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3043 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3044 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3045 /* microsoft extended type modifiers */
3046 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3047 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3048 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3049 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3050 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3059 * Parses an K&R identifier list
3061 static void parse_identifier_list(scope_t *scope)
3063 assert(token.kind == T_IDENTIFIER);
3065 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.base.symbol, HERE);
3066 /* a K&R parameter has no type, yet */
3070 append_entity(scope, entity);
3071 } while (next_if(',') && token.kind == T_IDENTIFIER);
3074 static entity_t *parse_parameter(void)
3076 declaration_specifiers_t specifiers;
3077 parse_declaration_specifiers(&specifiers);
3079 entity_t *entity = parse_declarator(&specifiers,
3080 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3081 anonymous_entity = NULL;
3085 static void semantic_parameter_incomplete(const entity_t *entity)
3087 assert(entity->kind == ENTITY_PARAMETER);
3089 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3090 * list in a function declarator that is part of a
3091 * definition of that function shall not have
3092 * incomplete type. */
3093 type_t *type = skip_typeref(entity->declaration.type);
3094 if (is_type_incomplete(type)) {
3095 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3099 static bool has_parameters(void)
3101 /* func(void) is not a parameter */
3102 if (look_ahead(1)->kind != ')')
3104 if (token.kind == T_IDENTIFIER) {
3105 entity_t const *const entity = get_entity(token.base.symbol, NAMESPACE_NORMAL);
3108 if (entity->kind != ENTITY_TYPEDEF)
3110 type_t const *const type = skip_typeref(entity->typedefe.type);
3111 if (!is_type_void(type))
3113 if (c_mode & _CXX) {
3114 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3115 * is not allowed. */
3116 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3117 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3118 /* §6.7.5.3:10 Qualification is not allowed here. */
3119 errorf(HERE, "'void' as parameter must not have type qualifiers");
3121 } else if (token.kind != T_void) {
3129 * Parses function type parameters (and optionally creates variable_t entities
3130 * for them in a scope)
3132 static void parse_parameters(function_type_t *type, scope_t *scope)
3134 add_anchor_token(')');
3137 if (token.kind == T_IDENTIFIER &&
3138 !is_typedef_symbol(token.base.symbol) &&
3139 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3140 type->kr_style_parameters = true;
3141 parse_identifier_list(scope);
3142 } else if (token.kind == ')') {
3143 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3144 if (!(c_mode & _CXX))
3145 type->unspecified_parameters = true;
3146 } else if (has_parameters()) {
3147 function_parameter_t **anchor = &type->parameters;
3148 add_anchor_token(',');
3150 switch (token.kind) {
3153 type->variadic = true;
3154 goto parameters_finished;
3159 entity_t *entity = parse_parameter();
3160 if (entity->kind == ENTITY_TYPEDEF) {
3161 errorf(&entity->base.source_position,
3162 "typedef not allowed as function parameter");
3165 assert(is_declaration(entity));
3167 semantic_parameter_incomplete(entity);
3169 function_parameter_t *const parameter =
3170 allocate_parameter(entity->declaration.type);
3172 if (scope != NULL) {
3173 append_entity(scope, entity);
3176 *anchor = parameter;
3177 anchor = ¶meter->next;
3182 goto parameters_finished;
3184 } while (next_if(','));
3185 parameters_finished:
3186 rem_anchor_token(',');
3189 rem_anchor_token(')');
3193 typedef enum construct_type_kind_t {
3194 CONSTRUCT_POINTER = 1,
3195 CONSTRUCT_REFERENCE,
3198 } construct_type_kind_t;
3200 typedef union construct_type_t construct_type_t;
3202 typedef struct construct_type_base_t {
3203 construct_type_kind_t kind;
3204 source_position_t pos;
3205 construct_type_t *next;
3206 } construct_type_base_t;
3208 typedef struct parsed_pointer_t {
3209 construct_type_base_t base;
3210 type_qualifiers_t type_qualifiers;
3211 variable_t *base_variable; /**< MS __based extension. */
3214 typedef struct parsed_reference_t {
3215 construct_type_base_t base;
3216 } parsed_reference_t;
3218 typedef struct construct_function_type_t {
3219 construct_type_base_t base;
3220 type_t *function_type;
3221 } construct_function_type_t;
3223 typedef struct parsed_array_t {
3224 construct_type_base_t base;
3225 type_qualifiers_t type_qualifiers;
3231 union construct_type_t {
3232 construct_type_kind_t kind;
3233 construct_type_base_t base;
3234 parsed_pointer_t pointer;
3235 parsed_reference_t reference;
3236 construct_function_type_t function;
3237 parsed_array_t array;
3240 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3242 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3243 memset(cons, 0, size);
3245 cons->base.pos = *HERE;
3250 static construct_type_t *parse_pointer_declarator(void)
3252 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3254 cons->pointer.type_qualifiers = parse_type_qualifiers();
3255 //cons->pointer.base_variable = base_variable;
3260 /* ISO/IEC 14882:1998(E) §8.3.2 */
3261 static construct_type_t *parse_reference_declarator(void)
3263 if (!(c_mode & _CXX))
3264 errorf(HERE, "references are only available for C++");
3266 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3273 static construct_type_t *parse_array_declarator(void)
3275 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3276 parsed_array_t *const array = &cons->array;
3279 add_anchor_token(']');
3281 bool is_static = next_if(T_static);
3283 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3286 is_static = next_if(T_static);
3288 array->type_qualifiers = type_qualifiers;
3289 array->is_static = is_static;
3291 expression_t *size = NULL;
3292 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3293 array->is_variable = true;
3295 } else if (token.kind != ']') {
3296 size = parse_assignment_expression();
3298 /* §6.7.5.2:1 Array size must have integer type */
3299 type_t *const orig_type = size->base.type;
3300 type_t *const type = skip_typeref(orig_type);
3301 if (!is_type_integer(type) && is_type_valid(type)) {
3302 errorf(&size->base.source_position,
3303 "array size '%E' must have integer type but has type '%T'",
3308 mark_vars_read(size, NULL);
3311 if (is_static && size == NULL)
3312 errorf(&array->base.pos, "static array parameters require a size");
3314 rem_anchor_token(']');
3320 static construct_type_t *parse_function_declarator(scope_t *scope)
3322 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3324 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3325 function_type_t *ftype = &type->function;
3327 ftype->linkage = current_linkage;
3328 ftype->calling_convention = CC_DEFAULT;
3330 parse_parameters(ftype, scope);
3332 cons->function.function_type = type;
3337 typedef struct parse_declarator_env_t {
3338 bool may_be_abstract : 1;
3339 bool must_be_abstract : 1;
3340 decl_modifiers_t modifiers;
3342 source_position_t source_position;
3344 attribute_t *attributes;
3345 } parse_declarator_env_t;
3348 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3350 /* construct a single linked list of construct_type_t's which describe
3351 * how to construct the final declarator type */
3352 construct_type_t *first = NULL;
3353 construct_type_t **anchor = &first;
3355 env->attributes = parse_attributes(env->attributes);
3358 construct_type_t *type;
3359 //variable_t *based = NULL; /* MS __based extension */
3360 switch (token.kind) {
3362 type = parse_reference_declarator();
3366 panic("based not supported anymore");
3371 type = parse_pointer_declarator();
3375 goto ptr_operator_end;
3379 anchor = &type->base.next;
3381 /* TODO: find out if this is correct */
3382 env->attributes = parse_attributes(env->attributes);
3386 construct_type_t *inner_types = NULL;
3388 switch (token.kind) {
3390 if (env->must_be_abstract) {
3391 errorf(HERE, "no identifier expected in typename");
3393 env->symbol = token.base.symbol;
3394 env->source_position = *HERE;
3400 /* Parenthesized declarator or function declarator? */
3401 token_t const *const la1 = look_ahead(1);
3402 switch (la1->kind) {
3404 if (is_typedef_symbol(la1->base.symbol)) {
3406 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3407 * interpreted as ``function with no parameter specification'', rather
3408 * than redundant parentheses around the omitted identifier. */
3410 /* Function declarator. */
3411 if (!env->may_be_abstract) {
3412 errorf(HERE, "function declarator must have a name");
3419 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3420 /* Paranthesized declarator. */
3422 add_anchor_token(')');
3423 inner_types = parse_inner_declarator(env);
3424 if (inner_types != NULL) {
3425 /* All later declarators only modify the return type */
3426 env->must_be_abstract = true;
3428 rem_anchor_token(')');
3437 if (env->may_be_abstract)
3439 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3444 construct_type_t **const p = anchor;
3447 construct_type_t *type;
3448 switch (token.kind) {
3450 scope_t *scope = NULL;
3451 if (!env->must_be_abstract) {
3452 scope = &env->parameters;
3455 type = parse_function_declarator(scope);
3459 type = parse_array_declarator();
3462 goto declarator_finished;
3465 /* insert in the middle of the list (at p) */
3466 type->base.next = *p;
3469 anchor = &type->base.next;
3472 declarator_finished:
3473 /* append inner_types at the end of the list, we don't to set anchor anymore
3474 * as it's not needed anymore */
3475 *anchor = inner_types;
3480 static type_t *construct_declarator_type(construct_type_t *construct_list,
3483 construct_type_t *iter = construct_list;
3484 for (; iter != NULL; iter = iter->base.next) {
3485 source_position_t const* const pos = &iter->base.pos;
3486 switch (iter->kind) {
3487 case CONSTRUCT_FUNCTION: {
3488 construct_function_type_t *function = &iter->function;
3489 type_t *function_type = function->function_type;
3491 function_type->function.return_type = type;
3493 type_t *skipped_return_type = skip_typeref(type);
3495 if (is_type_function(skipped_return_type)) {
3496 errorf(pos, "function returning function is not allowed");
3497 } else if (is_type_array(skipped_return_type)) {
3498 errorf(pos, "function returning array is not allowed");
3500 if (skipped_return_type->base.qualifiers != 0) {
3501 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3505 /* The function type was constructed earlier. Freeing it here will
3506 * destroy other types. */
3507 type = typehash_insert(function_type);
3511 case CONSTRUCT_POINTER: {
3512 if (is_type_reference(skip_typeref(type)))
3513 errorf(pos, "cannot declare a pointer to reference");
3515 parsed_pointer_t *pointer = &iter->pointer;
3516 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3520 case CONSTRUCT_REFERENCE:
3521 if (is_type_reference(skip_typeref(type)))
3522 errorf(pos, "cannot declare a reference to reference");
3524 type = make_reference_type(type);
3527 case CONSTRUCT_ARRAY: {
3528 if (is_type_reference(skip_typeref(type)))
3529 errorf(pos, "cannot declare an array of references");
3531 parsed_array_t *array = &iter->array;
3532 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3534 expression_t *size_expression = array->size;
3535 if (size_expression != NULL) {
3537 = create_implicit_cast(size_expression, type_size_t);
3540 array_type->base.qualifiers = array->type_qualifiers;
3541 array_type->array.element_type = type;
3542 array_type->array.is_static = array->is_static;
3543 array_type->array.is_variable = array->is_variable;
3544 array_type->array.size_expression = size_expression;
3546 if (size_expression != NULL) {
3547 switch (is_constant_expression(size_expression)) {
3548 case EXPR_CLASS_CONSTANT: {
3549 long const size = fold_constant_to_int(size_expression);
3550 array_type->array.size = size;
3551 array_type->array.size_constant = true;
3552 /* §6.7.5.2:1 If the expression is a constant expression,
3553 * it shall have a value greater than zero. */
3555 errorf(&size_expression->base.source_position,
3556 "size of array must be greater than zero");
3557 } else if (size == 0 && !GNU_MODE) {
3558 errorf(&size_expression->base.source_position,
3559 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3564 case EXPR_CLASS_VARIABLE:
3565 array_type->array.is_vla = true;
3568 case EXPR_CLASS_ERROR:
3573 type_t *skipped_type = skip_typeref(type);
3575 if (is_type_incomplete(skipped_type)) {
3576 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3577 } else if (is_type_function(skipped_type)) {
3578 errorf(pos, "array of functions is not allowed");
3580 type = identify_new_type(array_type);
3584 internal_errorf(pos, "invalid type construction found");
3590 static type_t *automatic_type_conversion(type_t *orig_type);
3592 static type_t *semantic_parameter(const source_position_t *pos,
3594 const declaration_specifiers_t *specifiers,
3595 entity_t const *const param)
3597 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3598 * shall be adjusted to ``qualified pointer to type'',
3600 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3601 * type'' shall be adjusted to ``pointer to function
3602 * returning type'', as in 6.3.2.1. */
3603 type = automatic_type_conversion(type);
3605 if (specifiers->is_inline && is_type_valid(type)) {
3606 errorf(pos, "'%N' declared 'inline'", param);
3609 /* §6.9.1:6 The declarations in the declaration list shall contain
3610 * no storage-class specifier other than register and no
3611 * initializations. */
3612 if (specifiers->thread_local || (
3613 specifiers->storage_class != STORAGE_CLASS_NONE &&
3614 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3616 errorf(pos, "invalid storage class for '%N'", param);
3619 /* delay test for incomplete type, because we might have (void)
3620 * which is legal but incomplete... */
3625 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3626 declarator_flags_t flags)
3628 parse_declarator_env_t env;
3629 memset(&env, 0, sizeof(env));
3630 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3632 construct_type_t *construct_type = parse_inner_declarator(&env);
3634 construct_declarator_type(construct_type, specifiers->type);
3635 type_t *type = skip_typeref(orig_type);
3637 if (construct_type != NULL) {
3638 obstack_free(&temp_obst, construct_type);
3641 attribute_t *attributes = parse_attributes(env.attributes);
3642 /* append (shared) specifier attribute behind attributes of this
3644 attribute_t **anchor = &attributes;
3645 while (*anchor != NULL)
3646 anchor = &(*anchor)->next;
3647 *anchor = specifiers->attributes;
3650 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3651 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3652 entity->typedefe.type = orig_type;
3654 if (anonymous_entity != NULL) {
3655 if (is_type_compound(type)) {
3656 assert(anonymous_entity->compound.alias == NULL);
3657 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3658 anonymous_entity->kind == ENTITY_UNION);
3659 anonymous_entity->compound.alias = entity;
3660 anonymous_entity = NULL;
3661 } else if (is_type_enum(type)) {
3662 assert(anonymous_entity->enume.alias == NULL);
3663 assert(anonymous_entity->kind == ENTITY_ENUM);
3664 anonymous_entity->enume.alias = entity;
3665 anonymous_entity = NULL;
3669 /* create a declaration type entity */
3670 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3671 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3672 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3674 if (env.symbol != NULL) {
3675 if (specifiers->is_inline && is_type_valid(type)) {
3676 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3679 if (specifiers->thread_local ||
3680 specifiers->storage_class != STORAGE_CLASS_NONE) {
3681 errorf(&env.source_position, "'%N' must have no storage class", entity);
3684 } else if (flags & DECL_IS_PARAMETER) {
3685 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3686 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3687 } else if (is_type_function(type)) {
3688 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3689 entity->function.is_inline = specifiers->is_inline;
3690 entity->function.elf_visibility = default_visibility;
3691 entity->function.parameters = env.parameters;
3693 if (env.symbol != NULL) {
3694 /* this needs fixes for C++ */
3695 bool in_function_scope = current_function != NULL;
3697 if (specifiers->thread_local || (
3698 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3699 specifiers->storage_class != STORAGE_CLASS_NONE &&
3700 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3702 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3706 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3707 entity->variable.elf_visibility = default_visibility;
3708 entity->variable.thread_local = specifiers->thread_local;
3710 if (env.symbol != NULL) {
3711 if (specifiers->is_inline && is_type_valid(type)) {
3712 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3715 bool invalid_storage_class = false;
3716 if (current_scope == file_scope) {
3717 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3718 specifiers->storage_class != STORAGE_CLASS_NONE &&
3719 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3720 invalid_storage_class = true;
3723 if (specifiers->thread_local &&
3724 specifiers->storage_class == STORAGE_CLASS_NONE) {
3725 invalid_storage_class = true;
3728 if (invalid_storage_class) {
3729 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3734 entity->declaration.type = orig_type;
3735 entity->declaration.alignment = get_type_alignment(orig_type);
3736 entity->declaration.modifiers = env.modifiers;
3737 entity->declaration.attributes = attributes;
3739 storage_class_t storage_class = specifiers->storage_class;
3740 entity->declaration.declared_storage_class = storage_class;
3742 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3743 storage_class = STORAGE_CLASS_AUTO;
3744 entity->declaration.storage_class = storage_class;
3747 if (attributes != NULL) {
3748 handle_entity_attributes(attributes, entity);
3751 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3752 adapt_special_functions(&entity->function);
3758 static type_t *parse_abstract_declarator(type_t *base_type)
3760 parse_declarator_env_t env;
3761 memset(&env, 0, sizeof(env));
3762 env.may_be_abstract = true;
3763 env.must_be_abstract = true;
3765 construct_type_t *construct_type = parse_inner_declarator(&env);
3767 type_t *result = construct_declarator_type(construct_type, base_type);
3768 if (construct_type != NULL) {
3769 obstack_free(&temp_obst, construct_type);
3771 result = handle_type_attributes(env.attributes, result);
3777 * Check if the declaration of main is suspicious. main should be a
3778 * function with external linkage, returning int, taking either zero
3779 * arguments, two, or three arguments of appropriate types, ie.
3781 * int main([ int argc, char **argv [, char **env ] ]).
3783 * @param decl the declaration to check
3784 * @param type the function type of the declaration
3786 static void check_main(const entity_t *entity)
3788 const source_position_t *pos = &entity->base.source_position;
3789 if (entity->kind != ENTITY_FUNCTION) {
3790 warningf(WARN_MAIN, pos, "'main' is not a function");
3794 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3795 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3798 type_t *type = skip_typeref(entity->declaration.type);
3799 assert(is_type_function(type));
3801 function_type_t const *const func_type = &type->function;
3802 type_t *const ret_type = func_type->return_type;
3803 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3804 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3806 const function_parameter_t *parm = func_type->parameters;
3808 type_t *const first_type = skip_typeref(parm->type);
3809 type_t *const first_type_unqual = get_unqualified_type(first_type);
3810 if (!types_compatible(first_type_unqual, type_int)) {
3811 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3815 type_t *const second_type = skip_typeref(parm->type);
3816 type_t *const second_type_unqual
3817 = get_unqualified_type(second_type);
3818 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3819 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3823 type_t *const third_type = skip_typeref(parm->type);
3824 type_t *const third_type_unqual
3825 = get_unqualified_type(third_type);
3826 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3827 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3831 goto warn_arg_count;
3835 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3840 static void error_redefined_as_different_kind(const source_position_t *pos,
3841 const entity_t *old, entity_kind_t new_kind)
3843 char const *const what = get_entity_kind_name(new_kind);
3844 source_position_t const *const ppos = &old->base.source_position;
3845 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3848 static bool is_entity_valid(entity_t *const ent)
3850 if (is_declaration(ent)) {
3851 return is_type_valid(skip_typeref(ent->declaration.type));
3852 } else if (ent->kind == ENTITY_TYPEDEF) {
3853 return is_type_valid(skip_typeref(ent->typedefe.type));
3858 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3860 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3861 if (attributes_equal(tattr, attr))
3868 * test wether new_list contains any attributes not included in old_list
3870 static bool has_new_attributes(const attribute_t *old_list,
3871 const attribute_t *new_list)
3873 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3874 if (!contains_attribute(old_list, attr))
3881 * Merge in attributes from an attribute list (probably from a previous
3882 * declaration with the same name). Warning: destroys the old structure
3883 * of the attribute list - don't reuse attributes after this call.
3885 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3888 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3890 if (contains_attribute(decl->attributes, attr))
3893 /* move attribute to new declarations attributes list */
3894 attr->next = decl->attributes;
3895 decl->attributes = attr;
3899 static bool is_main(entity_t*);
3902 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3903 * for various problems that occur for multiple definitions
3905 entity_t *record_entity(entity_t *entity, const bool is_definition)
3907 const symbol_t *const symbol = entity->base.symbol;
3908 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3909 const source_position_t *pos = &entity->base.source_position;
3911 /* can happen in error cases */
3915 assert(!entity->base.parent_scope);
3916 assert(current_scope);
3917 entity->base.parent_scope = current_scope;
3919 entity_t *const previous_entity = get_entity(symbol, namespc);
3920 /* pushing the same entity twice will break the stack structure */
3921 assert(previous_entity != entity);
3923 if (entity->kind == ENTITY_FUNCTION) {
3924 type_t *const orig_type = entity->declaration.type;
3925 type_t *const type = skip_typeref(orig_type);
3927 assert(is_type_function(type));
3928 if (type->function.unspecified_parameters &&
3929 previous_entity == NULL &&
3930 !entity->declaration.implicit) {
3931 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3934 if (is_main(entity)) {
3939 if (is_declaration(entity) &&
3940 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3941 current_scope != file_scope &&
3942 !entity->declaration.implicit) {
3943 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3946 if (previous_entity != NULL) {
3947 source_position_t const *const ppos = &previous_entity->base.source_position;
3949 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3950 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3951 assert(previous_entity->kind == ENTITY_PARAMETER);
3952 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3956 if (previous_entity->base.parent_scope == current_scope) {
3957 if (previous_entity->kind != entity->kind) {
3958 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
3959 error_redefined_as_different_kind(pos, previous_entity,
3964 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
3965 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
3968 if (previous_entity->kind == ENTITY_TYPEDEF) {
3969 type_t *const type = skip_typeref(entity->typedefe.type);
3970 type_t *const prev_type
3971 = skip_typeref(previous_entity->typedefe.type);
3972 if (c_mode & _CXX) {
3973 /* C++ allows double typedef if they are identical
3974 * (after skipping typedefs) */
3975 if (type == prev_type)
3978 /* GCC extension: redef in system headers is allowed */
3979 if ((pos->is_system_header || ppos->is_system_header) &&
3980 types_compatible(type, prev_type))
3983 errorf(pos, "redefinition of '%N' (declared %P)",
3988 /* at this point we should have only VARIABLES or FUNCTIONS */
3989 assert(is_declaration(previous_entity) && is_declaration(entity));
3991 declaration_t *const prev_decl = &previous_entity->declaration;
3992 declaration_t *const decl = &entity->declaration;
3994 /* can happen for K&R style declarations */
3995 if (prev_decl->type == NULL &&
3996 previous_entity->kind == ENTITY_PARAMETER &&
3997 entity->kind == ENTITY_PARAMETER) {
3998 prev_decl->type = decl->type;
3999 prev_decl->storage_class = decl->storage_class;
4000 prev_decl->declared_storage_class = decl->declared_storage_class;
4001 prev_decl->modifiers = decl->modifiers;
4002 return previous_entity;
4005 type_t *const type = skip_typeref(decl->type);
4006 type_t *const prev_type = skip_typeref(prev_decl->type);
4008 if (!types_compatible(type, prev_type)) {
4009 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4011 unsigned old_storage_class = prev_decl->storage_class;
4013 if (is_definition &&
4015 !(prev_decl->modifiers & DM_USED) &&
4016 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4017 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4020 storage_class_t new_storage_class = decl->storage_class;
4022 /* pretend no storage class means extern for function
4023 * declarations (except if the previous declaration is neither
4024 * none nor extern) */
4025 if (entity->kind == ENTITY_FUNCTION) {
4026 /* the previous declaration could have unspecified parameters or
4027 * be a typedef, so use the new type */
4028 if (prev_type->function.unspecified_parameters || is_definition)
4029 prev_decl->type = type;
4031 switch (old_storage_class) {
4032 case STORAGE_CLASS_NONE:
4033 old_storage_class = STORAGE_CLASS_EXTERN;
4036 case STORAGE_CLASS_EXTERN:
4037 if (is_definition) {
4038 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4039 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4041 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4042 new_storage_class = STORAGE_CLASS_EXTERN;
4049 } else if (is_type_incomplete(prev_type)) {
4050 prev_decl->type = type;
4053 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4054 new_storage_class == STORAGE_CLASS_EXTERN) {
4056 warn_redundant_declaration: ;
4058 = has_new_attributes(prev_decl->attributes,
4060 if (has_new_attrs) {
4061 merge_in_attributes(decl, prev_decl->attributes);
4062 } else if (!is_definition &&
4063 is_type_valid(prev_type) &&
4064 !pos->is_system_header) {
4065 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%N' (declared %P)", entity, ppos);
4067 } else if (current_function == NULL) {
4068 if (old_storage_class != STORAGE_CLASS_STATIC &&
4069 new_storage_class == STORAGE_CLASS_STATIC) {
4070 errorf(pos, "static declaration of '%N' follows non-static declaration (declared %P)", entity, ppos);
4071 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4072 prev_decl->storage_class = STORAGE_CLASS_NONE;
4073 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4075 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4077 goto error_redeclaration;
4078 goto warn_redundant_declaration;
4080 } else if (is_type_valid(prev_type)) {
4081 if (old_storage_class == new_storage_class) {
4082 error_redeclaration:
4083 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4085 errorf(pos, "redeclaration of '%N' with different linkage (declared %P)", entity, ppos);
4090 prev_decl->modifiers |= decl->modifiers;
4091 if (entity->kind == ENTITY_FUNCTION) {
4092 previous_entity->function.is_inline |= entity->function.is_inline;
4094 return previous_entity;
4098 if (is_warn_on(why = WARN_SHADOW) ||
4099 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4100 char const *const what = get_entity_kind_name(previous_entity->kind);
4101 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4105 if (entity->kind == ENTITY_FUNCTION) {
4106 if (is_definition &&
4107 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4109 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4110 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4112 goto warn_missing_declaration;
4115 } else if (entity->kind == ENTITY_VARIABLE) {
4116 if (current_scope == file_scope &&
4117 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4118 !entity->declaration.implicit) {
4119 warn_missing_declaration:
4120 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4125 environment_push(entity);
4126 append_entity(current_scope, entity);
4131 static void parser_error_multiple_definition(entity_t *entity,
4132 const source_position_t *source_position)
4134 errorf(source_position, "redefinition of '%N' (declared %P)", entity, &entity->base.source_position);
4137 static bool is_declaration_specifier(const token_t *token)
4139 switch (token->kind) {
4143 return is_typedef_symbol(token->base.symbol);
4150 static void parse_init_declarator_rest(entity_t *entity)
4152 type_t *orig_type = type_error_type;
4154 if (entity->base.kind == ENTITY_TYPEDEF) {
4155 source_position_t const *const pos = &entity->base.source_position;
4156 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4158 assert(is_declaration(entity));
4159 orig_type = entity->declaration.type;
4162 type_t *type = skip_typeref(orig_type);
4164 if (entity->kind == ENTITY_VARIABLE
4165 && entity->variable.initializer != NULL) {
4166 parser_error_multiple_definition(entity, HERE);
4170 declaration_t *const declaration = &entity->declaration;
4171 bool must_be_constant = false;
4172 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4173 entity->base.parent_scope == file_scope) {
4174 must_be_constant = true;
4177 if (is_type_function(type)) {
4178 source_position_t const *const pos = &entity->base.source_position;
4179 errorf(pos, "'%N' is initialized like a variable", entity);
4180 orig_type = type_error_type;
4183 parse_initializer_env_t env;
4184 env.type = orig_type;
4185 env.must_be_constant = must_be_constant;
4186 env.entity = entity;
4188 initializer_t *initializer = parse_initializer(&env);
4190 if (entity->kind == ENTITY_VARIABLE) {
4191 /* §6.7.5:22 array initializers for arrays with unknown size
4192 * determine the array type size */
4193 declaration->type = env.type;
4194 entity->variable.initializer = initializer;
4198 /* parse rest of a declaration without any declarator */
4199 static void parse_anonymous_declaration_rest(
4200 const declaration_specifiers_t *specifiers)
4203 anonymous_entity = NULL;
4205 source_position_t const *const pos = &specifiers->source_position;
4206 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4207 specifiers->thread_local) {
4208 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4211 type_t *type = specifiers->type;
4212 switch (type->kind) {
4213 case TYPE_COMPOUND_STRUCT:
4214 case TYPE_COMPOUND_UNION: {
4215 if (type->compound.compound->base.symbol == NULL) {
4216 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4225 warningf(WARN_OTHER, pos, "empty declaration");
4230 static void check_variable_type_complete(entity_t *ent)
4232 if (ent->kind != ENTITY_VARIABLE)
4235 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4236 * type for the object shall be complete [...] */
4237 declaration_t *decl = &ent->declaration;
4238 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4239 decl->storage_class == STORAGE_CLASS_STATIC)
4242 type_t *const type = skip_typeref(decl->type);
4243 if (!is_type_incomplete(type))
4246 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4247 * are given length one. */
4248 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4249 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4253 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4257 static void parse_declaration_rest(entity_t *ndeclaration,
4258 const declaration_specifiers_t *specifiers,
4259 parsed_declaration_func finished_declaration,
4260 declarator_flags_t flags)
4262 add_anchor_token(';');
4263 add_anchor_token(',');
4265 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4267 if (token.kind == '=') {
4268 parse_init_declarator_rest(entity);
4269 } else if (entity->kind == ENTITY_VARIABLE) {
4270 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4271 * [...] where the extern specifier is explicitly used. */
4272 declaration_t *decl = &entity->declaration;
4273 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4274 is_type_reference(skip_typeref(decl->type))) {
4275 source_position_t const *const pos = &entity->base.source_position;
4276 errorf(pos, "reference '%#N' must be initialized", entity);
4280 check_variable_type_complete(entity);
4285 add_anchor_token('=');
4286 ndeclaration = parse_declarator(specifiers, flags);
4287 rem_anchor_token('=');
4289 rem_anchor_token(',');
4290 rem_anchor_token(';');
4293 anonymous_entity = NULL;
4296 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4298 symbol_t *symbol = entity->base.symbol;
4302 assert(entity->base.namespc == NAMESPACE_NORMAL);
4303 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4304 if (previous_entity == NULL
4305 || previous_entity->base.parent_scope != current_scope) {
4306 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4311 if (is_definition) {
4312 errorf(HERE, "'%N' is initialised", entity);
4315 return record_entity(entity, false);
4318 static void parse_declaration(parsed_declaration_func finished_declaration,
4319 declarator_flags_t flags)
4321 add_anchor_token(';');
4322 declaration_specifiers_t specifiers;
4323 parse_declaration_specifiers(&specifiers);
4324 rem_anchor_token(';');
4326 if (token.kind == ';') {
4327 parse_anonymous_declaration_rest(&specifiers);
4329 entity_t *entity = parse_declarator(&specifiers, flags);
4330 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4335 static type_t *get_default_promoted_type(type_t *orig_type)
4337 type_t *result = orig_type;
4339 type_t *type = skip_typeref(orig_type);
4340 if (is_type_integer(type)) {
4341 result = promote_integer(type);
4342 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4343 result = type_double;
4349 static void parse_kr_declaration_list(entity_t *entity)
4351 if (entity->kind != ENTITY_FUNCTION)
4354 type_t *type = skip_typeref(entity->declaration.type);
4355 assert(is_type_function(type));
4356 if (!type->function.kr_style_parameters)
4359 add_anchor_token('{');
4361 PUSH_SCOPE(&entity->function.parameters);
4363 entity_t *parameter = entity->function.parameters.entities;
4364 for ( ; parameter != NULL; parameter = parameter->base.next) {
4365 assert(parameter->base.parent_scope == NULL);
4366 parameter->base.parent_scope = current_scope;
4367 environment_push(parameter);
4370 /* parse declaration list */
4372 switch (token.kind) {
4374 /* This covers symbols, which are no type, too, and results in
4375 * better error messages. The typical cases are misspelled type
4376 * names and missing includes. */
4378 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4388 /* update function type */
4389 type_t *new_type = duplicate_type(type);
4391 function_parameter_t *parameters = NULL;
4392 function_parameter_t **anchor = ¶meters;
4394 /* did we have an earlier prototype? */
4395 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4396 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4399 function_parameter_t *proto_parameter = NULL;
4400 if (proto_type != NULL) {
4401 type_t *proto_type_type = proto_type->declaration.type;
4402 proto_parameter = proto_type_type->function.parameters;
4403 /* If a K&R function definition has a variadic prototype earlier, then
4404 * make the function definition variadic, too. This should conform to
4405 * §6.7.5.3:15 and §6.9.1:8. */
4406 new_type->function.variadic = proto_type_type->function.variadic;
4408 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4410 new_type->function.unspecified_parameters = true;
4413 bool need_incompatible_warning = false;
4414 parameter = entity->function.parameters.entities;
4415 for (; parameter != NULL; parameter = parameter->base.next,
4417 proto_parameter == NULL ? NULL : proto_parameter->next) {
4418 if (parameter->kind != ENTITY_PARAMETER)
4421 type_t *parameter_type = parameter->declaration.type;
4422 if (parameter_type == NULL) {
4423 source_position_t const* const pos = ¶meter->base.source_position;
4425 errorf(pos, "no type specified for function '%N'", parameter);
4426 parameter_type = type_error_type;
4428 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4429 parameter_type = type_int;
4431 parameter->declaration.type = parameter_type;
4434 semantic_parameter_incomplete(parameter);
4436 /* we need the default promoted types for the function type */
4437 type_t *not_promoted = parameter_type;
4438 parameter_type = get_default_promoted_type(parameter_type);
4440 /* gcc special: if the type of the prototype matches the unpromoted
4441 * type don't promote */
4442 if (!strict_mode && proto_parameter != NULL) {
4443 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4444 type_t *promo_skip = skip_typeref(parameter_type);
4445 type_t *param_skip = skip_typeref(not_promoted);
4446 if (!types_compatible(proto_p_type, promo_skip)
4447 && types_compatible(proto_p_type, param_skip)) {
4449 need_incompatible_warning = true;
4450 parameter_type = not_promoted;
4453 function_parameter_t *const function_parameter
4454 = allocate_parameter(parameter_type);
4456 *anchor = function_parameter;
4457 anchor = &function_parameter->next;
4460 new_type->function.parameters = parameters;
4461 new_type = identify_new_type(new_type);
4463 if (need_incompatible_warning) {
4464 symbol_t const *const sym = entity->base.symbol;
4465 source_position_t const *const pos = &entity->base.source_position;
4466 source_position_t const *const ppos = &proto_type->base.source_position;
4467 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4469 entity->declaration.type = new_type;
4471 rem_anchor_token('{');
4474 static bool first_err = true;
4477 * When called with first_err set, prints the name of the current function,
4480 static void print_in_function(void)
4484 char const *const file = current_function->base.base.source_position.input_name;
4485 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4490 * Check if all labels are defined in the current function.
4491 * Check if all labels are used in the current function.
4493 static void check_labels(void)
4495 for (const goto_statement_t *goto_statement = goto_first;
4496 goto_statement != NULL;
4497 goto_statement = goto_statement->next) {
4498 label_t *label = goto_statement->label;
4499 if (label->base.source_position.input_name == NULL) {
4500 print_in_function();
4501 source_position_t const *const pos = &goto_statement->base.source_position;
4502 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4506 if (is_warn_on(WARN_UNUSED_LABEL)) {
4507 for (const label_statement_t *label_statement = label_first;
4508 label_statement != NULL;
4509 label_statement = label_statement->next) {
4510 label_t *label = label_statement->label;
4512 if (! label->used) {
4513 print_in_function();
4514 source_position_t const *const pos = &label_statement->base.source_position;
4515 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4521 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4523 entity_t const *const end = last != NULL ? last->base.next : NULL;
4524 for (; entity != end; entity = entity->base.next) {
4525 if (!is_declaration(entity))
4528 declaration_t *declaration = &entity->declaration;
4529 if (declaration->implicit)
4532 if (!declaration->used) {
4533 print_in_function();
4534 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4535 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4536 print_in_function();
4537 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4542 static void check_unused_variables(statement_t *const stmt, void *const env)
4546 switch (stmt->kind) {
4547 case STATEMENT_DECLARATION: {
4548 declaration_statement_t const *const decls = &stmt->declaration;
4549 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4554 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4563 * Check declarations of current_function for unused entities.
4565 static void check_declarations(void)
4567 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4568 const scope_t *scope = ¤t_function->parameters;
4569 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4571 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4572 walk_statements(current_function->statement, check_unused_variables,
4577 static int determine_truth(expression_t const* const cond)
4580 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4581 fold_constant_to_bool(cond) ? 1 :
4585 static void check_reachable(statement_t *);
4586 static bool reaches_end;
4588 static bool expression_returns(expression_t const *const expr)
4590 switch (expr->kind) {
4592 expression_t const *const func = expr->call.function;
4593 type_t const *const type = skip_typeref(func->base.type);
4594 if (type->kind == TYPE_POINTER) {
4595 type_t const *const points_to
4596 = skip_typeref(type->pointer.points_to);
4597 if (points_to->kind == TYPE_FUNCTION
4598 && points_to->function.modifiers & DM_NORETURN)
4602 if (!expression_returns(func))
4605 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4606 if (!expression_returns(arg->expression))
4613 case EXPR_REFERENCE:
4614 case EXPR_ENUM_CONSTANT:
4615 case EXPR_LITERAL_CASES:
4616 case EXPR_LITERAL_CHARACTER:
4617 case EXPR_STRING_LITERAL:
4618 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4619 case EXPR_LABEL_ADDRESS:
4620 case EXPR_CLASSIFY_TYPE:
4621 case EXPR_SIZEOF: // TODO handle obscure VLA case
4624 case EXPR_BUILTIN_CONSTANT_P:
4625 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4630 case EXPR_STATEMENT: {
4631 bool old_reaches_end = reaches_end;
4632 reaches_end = false;
4633 check_reachable(expr->statement.statement);
4634 bool returns = reaches_end;
4635 reaches_end = old_reaches_end;
4639 case EXPR_CONDITIONAL:
4640 // TODO handle constant expression
4642 if (!expression_returns(expr->conditional.condition))
4645 if (expr->conditional.true_expression != NULL
4646 && expression_returns(expr->conditional.true_expression))
4649 return expression_returns(expr->conditional.false_expression);
4652 return expression_returns(expr->select.compound);
4654 case EXPR_ARRAY_ACCESS:
4656 expression_returns(expr->array_access.array_ref) &&
4657 expression_returns(expr->array_access.index);
4660 return expression_returns(expr->va_starte.ap);
4663 return expression_returns(expr->va_arge.ap);
4666 return expression_returns(expr->va_copye.src);
4668 case EXPR_UNARY_CASES_MANDATORY:
4669 return expression_returns(expr->unary.value);
4671 case EXPR_UNARY_THROW:
4674 case EXPR_BINARY_CASES:
4675 // TODO handle constant lhs of && and ||
4677 expression_returns(expr->binary.left) &&
4678 expression_returns(expr->binary.right);
4681 panic("unhandled expression");
4684 static bool initializer_returns(initializer_t const *const init)
4686 switch (init->kind) {
4687 case INITIALIZER_VALUE:
4688 return expression_returns(init->value.value);
4690 case INITIALIZER_LIST: {
4691 initializer_t * const* i = init->list.initializers;
4692 initializer_t * const* const end = i + init->list.len;
4693 bool returns = true;
4694 for (; i != end; ++i) {
4695 if (!initializer_returns(*i))
4701 case INITIALIZER_STRING:
4702 case INITIALIZER_DESIGNATOR: // designators have no payload
4705 panic("unhandled initializer");
4708 static bool noreturn_candidate;
4710 static void check_reachable(statement_t *const stmt)
4712 if (stmt->base.reachable)
4714 if (stmt->kind != STATEMENT_DO_WHILE)
4715 stmt->base.reachable = true;
4717 statement_t *last = stmt;
4719 switch (stmt->kind) {
4720 case STATEMENT_ERROR:
4721 case STATEMENT_EMPTY:
4723 next = stmt->base.next;
4726 case STATEMENT_DECLARATION: {
4727 declaration_statement_t const *const decl = &stmt->declaration;
4728 entity_t const * ent = decl->declarations_begin;
4729 entity_t const *const last_decl = decl->declarations_end;
4731 for (;; ent = ent->base.next) {
4732 if (ent->kind == ENTITY_VARIABLE &&
4733 ent->variable.initializer != NULL &&
4734 !initializer_returns(ent->variable.initializer)) {
4737 if (ent == last_decl)
4741 next = stmt->base.next;
4745 case STATEMENT_COMPOUND:
4746 next = stmt->compound.statements;
4748 next = stmt->base.next;
4751 case STATEMENT_RETURN: {
4752 expression_t const *const val = stmt->returns.value;
4753 if (val == NULL || expression_returns(val))
4754 noreturn_candidate = false;
4758 case STATEMENT_IF: {
4759 if_statement_t const *const ifs = &stmt->ifs;
4760 expression_t const *const cond = ifs->condition;
4762 if (!expression_returns(cond))
4765 int const val = determine_truth(cond);
4768 check_reachable(ifs->true_statement);
4773 if (ifs->false_statement != NULL) {
4774 check_reachable(ifs->false_statement);
4778 next = stmt->base.next;
4782 case STATEMENT_SWITCH: {
4783 switch_statement_t const *const switchs = &stmt->switchs;
4784 expression_t const *const expr = switchs->expression;
4786 if (!expression_returns(expr))
4789 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4790 long const val = fold_constant_to_int(expr);
4791 case_label_statement_t * defaults = NULL;
4792 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4793 if (i->expression == NULL) {
4798 if (i->first_case <= val && val <= i->last_case) {
4799 check_reachable((statement_t*)i);
4804 if (defaults != NULL) {
4805 check_reachable((statement_t*)defaults);
4809 bool has_default = false;
4810 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4811 if (i->expression == NULL)
4814 check_reachable((statement_t*)i);
4821 next = stmt->base.next;
4825 case STATEMENT_EXPRESSION: {
4826 /* Check for noreturn function call */
4827 expression_t const *const expr = stmt->expression.expression;
4828 if (!expression_returns(expr))
4831 next = stmt->base.next;
4835 case STATEMENT_CONTINUE:
4836 for (statement_t *parent = stmt;;) {
4837 parent = parent->base.parent;
4838 if (parent == NULL) /* continue not within loop */
4842 switch (parent->kind) {
4843 case STATEMENT_WHILE: goto continue_while;
4844 case STATEMENT_DO_WHILE: goto continue_do_while;
4845 case STATEMENT_FOR: goto continue_for;
4851 case STATEMENT_BREAK:
4852 for (statement_t *parent = stmt;;) {
4853 parent = parent->base.parent;
4854 if (parent == NULL) /* break not within loop/switch */
4857 switch (parent->kind) {
4858 case STATEMENT_SWITCH:
4859 case STATEMENT_WHILE:
4860 case STATEMENT_DO_WHILE:
4863 next = parent->base.next;
4864 goto found_break_parent;
4872 case STATEMENT_COMPUTED_GOTO: {
4873 if (!expression_returns(stmt->computed_goto.expression))
4876 statement_t *parent = stmt->base.parent;
4877 if (parent == NULL) /* top level goto */
4883 case STATEMENT_GOTO:
4884 next = stmt->gotos.label->statement;
4885 if (next == NULL) /* missing label */
4889 case STATEMENT_LABEL:
4890 next = stmt->label.statement;
4893 case STATEMENT_CASE_LABEL:
4894 next = stmt->case_label.statement;
4897 case STATEMENT_WHILE: {
4898 while_statement_t const *const whiles = &stmt->whiles;
4899 expression_t const *const cond = whiles->condition;
4901 if (!expression_returns(cond))
4904 int const val = determine_truth(cond);
4907 check_reachable(whiles->body);
4912 next = stmt->base.next;
4916 case STATEMENT_DO_WHILE:
4917 next = stmt->do_while.body;
4920 case STATEMENT_FOR: {
4921 for_statement_t *const fors = &stmt->fors;
4923 if (fors->condition_reachable)
4925 fors->condition_reachable = true;
4927 expression_t const *const cond = fors->condition;
4932 } else if (expression_returns(cond)) {
4933 val = determine_truth(cond);
4939 check_reachable(fors->body);
4944 next = stmt->base.next;
4948 case STATEMENT_MS_TRY: {
4949 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4950 check_reachable(ms_try->try_statement);
4951 next = ms_try->final_statement;
4955 case STATEMENT_LEAVE: {
4956 statement_t *parent = stmt;
4958 parent = parent->base.parent;
4959 if (parent == NULL) /* __leave not within __try */
4962 if (parent->kind == STATEMENT_MS_TRY) {
4964 next = parent->ms_try.final_statement;
4972 panic("invalid statement kind");
4975 while (next == NULL) {
4976 next = last->base.parent;
4978 noreturn_candidate = false;
4980 type_t *const type = skip_typeref(current_function->base.type);
4981 assert(is_type_function(type));
4982 type_t *const ret = skip_typeref(type->function.return_type);
4983 if (!is_type_void(ret) &&
4984 is_type_valid(ret) &&
4985 !is_main(current_entity)) {
4986 source_position_t const *const pos = &stmt->base.source_position;
4987 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
4992 switch (next->kind) {
4993 case STATEMENT_ERROR:
4994 case STATEMENT_EMPTY:
4995 case STATEMENT_DECLARATION:
4996 case STATEMENT_EXPRESSION:
4998 case STATEMENT_RETURN:
4999 case STATEMENT_CONTINUE:
5000 case STATEMENT_BREAK:
5001 case STATEMENT_COMPUTED_GOTO:
5002 case STATEMENT_GOTO:
5003 case STATEMENT_LEAVE:
5004 panic("invalid control flow in function");
5006 case STATEMENT_COMPOUND:
5007 if (next->compound.stmt_expr) {
5013 case STATEMENT_SWITCH:
5014 case STATEMENT_LABEL:
5015 case STATEMENT_CASE_LABEL:
5017 next = next->base.next;
5020 case STATEMENT_WHILE: {
5022 if (next->base.reachable)
5024 next->base.reachable = true;
5026 while_statement_t const *const whiles = &next->whiles;
5027 expression_t const *const cond = whiles->condition;
5029 if (!expression_returns(cond))
5032 int const val = determine_truth(cond);
5035 check_reachable(whiles->body);
5041 next = next->base.next;
5045 case STATEMENT_DO_WHILE: {
5047 if (next->base.reachable)
5049 next->base.reachable = true;
5051 do_while_statement_t const *const dw = &next->do_while;
5052 expression_t const *const cond = dw->condition;
5054 if (!expression_returns(cond))
5057 int const val = determine_truth(cond);
5060 check_reachable(dw->body);
5066 next = next->base.next;
5070 case STATEMENT_FOR: {
5072 for_statement_t *const fors = &next->fors;
5074 fors->step_reachable = true;
5076 if (fors->condition_reachable)
5078 fors->condition_reachable = true;
5080 expression_t const *const cond = fors->condition;
5085 } else if (expression_returns(cond)) {
5086 val = determine_truth(cond);
5092 check_reachable(fors->body);
5098 next = next->base.next;
5102 case STATEMENT_MS_TRY:
5104 next = next->ms_try.final_statement;
5109 check_reachable(next);
5112 static void check_unreachable(statement_t* const stmt, void *const env)
5116 switch (stmt->kind) {
5117 case STATEMENT_DO_WHILE:
5118 if (!stmt->base.reachable) {
5119 expression_t const *const cond = stmt->do_while.condition;
5120 if (determine_truth(cond) >= 0) {
5121 source_position_t const *const pos = &cond->base.source_position;
5122 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5127 case STATEMENT_FOR: {
5128 for_statement_t const* const fors = &stmt->fors;
5130 // if init and step are unreachable, cond is unreachable, too
5131 if (!stmt->base.reachable && !fors->step_reachable) {
5132 goto warn_unreachable;
5134 if (!stmt->base.reachable && fors->initialisation != NULL) {
5135 source_position_t const *const pos = &fors->initialisation->base.source_position;
5136 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5139 if (!fors->condition_reachable && fors->condition != NULL) {
5140 source_position_t const *const pos = &fors->condition->base.source_position;
5141 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5144 if (!fors->step_reachable && fors->step != NULL) {
5145 source_position_t const *const pos = &fors->step->base.source_position;
5146 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5152 case STATEMENT_COMPOUND:
5153 if (stmt->compound.statements != NULL)
5155 goto warn_unreachable;
5157 case STATEMENT_DECLARATION: {
5158 /* Only warn if there is at least one declarator with an initializer.
5159 * This typically occurs in switch statements. */
5160 declaration_statement_t const *const decl = &stmt->declaration;
5161 entity_t const * ent = decl->declarations_begin;
5162 entity_t const *const last = decl->declarations_end;
5164 for (;; ent = ent->base.next) {
5165 if (ent->kind == ENTITY_VARIABLE &&
5166 ent->variable.initializer != NULL) {
5167 goto warn_unreachable;
5177 if (!stmt->base.reachable) {
5178 source_position_t const *const pos = &stmt->base.source_position;
5179 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5185 static bool is_main(entity_t *entity)
5187 static symbol_t *sym_main = NULL;
5188 if (sym_main == NULL) {
5189 sym_main = symbol_table_insert("main");
5192 if (entity->base.symbol != sym_main)
5194 /* must be in outermost scope */
5195 if (entity->base.parent_scope != file_scope)
5201 static void prepare_main_collect2(entity_t*);
5203 static void parse_external_declaration(void)
5205 /* function-definitions and declarations both start with declaration
5207 add_anchor_token(';');
5208 declaration_specifiers_t specifiers;
5209 parse_declaration_specifiers(&specifiers);
5210 rem_anchor_token(';');
5212 /* must be a declaration */
5213 if (token.kind == ';') {
5214 parse_anonymous_declaration_rest(&specifiers);
5218 add_anchor_token(',');
5219 add_anchor_token('=');
5220 add_anchor_token(';');
5221 add_anchor_token('{');
5223 /* declarator is common to both function-definitions and declarations */
5224 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5226 rem_anchor_token('{');
5227 rem_anchor_token(';');
5228 rem_anchor_token('=');
5229 rem_anchor_token(',');
5231 /* must be a declaration */
5232 switch (token.kind) {
5236 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5241 /* must be a function definition */
5242 parse_kr_declaration_list(ndeclaration);
5244 if (token.kind != '{') {
5245 parse_error_expected("while parsing function definition", '{', NULL);
5246 eat_until_matching_token(';');
5250 assert(is_declaration(ndeclaration));
5251 type_t *const orig_type = ndeclaration->declaration.type;
5252 type_t * type = skip_typeref(orig_type);
5254 if (!is_type_function(type)) {
5255 if (is_type_valid(type)) {
5256 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5262 source_position_t const *const pos = &ndeclaration->base.source_position;
5263 if (is_typeref(orig_type)) {
5265 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5268 if (is_type_compound(skip_typeref(type->function.return_type))) {
5269 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5271 if (type->function.unspecified_parameters) {
5272 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5274 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5277 /* §6.7.5.3:14 a function definition with () means no
5278 * parameters (and not unspecified parameters) */
5279 if (type->function.unspecified_parameters &&
5280 type->function.parameters == NULL) {
5281 type_t *copy = duplicate_type(type);
5282 copy->function.unspecified_parameters = false;
5283 type = identify_new_type(copy);
5285 ndeclaration->declaration.type = type;
5288 entity_t *const entity = record_entity(ndeclaration, true);
5289 assert(entity->kind == ENTITY_FUNCTION);
5290 assert(ndeclaration->kind == ENTITY_FUNCTION);
5292 function_t *const function = &entity->function;
5293 if (ndeclaration != entity) {
5294 function->parameters = ndeclaration->function.parameters;
5297 PUSH_SCOPE(&function->parameters);
5299 entity_t *parameter = function->parameters.entities;
5300 for (; parameter != NULL; parameter = parameter->base.next) {
5301 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5302 parameter->base.parent_scope = current_scope;
5304 assert(parameter->base.parent_scope == NULL
5305 || parameter->base.parent_scope == current_scope);
5306 parameter->base.parent_scope = current_scope;
5307 if (parameter->base.symbol == NULL) {
5308 errorf(¶meter->base.source_position, "parameter name omitted");
5311 environment_push(parameter);
5314 if (function->statement != NULL) {
5315 parser_error_multiple_definition(entity, HERE);
5318 /* parse function body */
5319 int label_stack_top = label_top();
5320 function_t *old_current_function = current_function;
5321 current_function = function;
5322 PUSH_CURRENT_ENTITY(entity);
5326 goto_anchor = &goto_first;
5328 label_anchor = &label_first;
5330 statement_t *const body = parse_compound_statement(false);
5331 function->statement = body;
5334 check_declarations();
5335 if (is_warn_on(WARN_RETURN_TYPE) ||
5336 is_warn_on(WARN_UNREACHABLE_CODE) ||
5337 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5338 noreturn_candidate = true;
5339 check_reachable(body);
5340 if (is_warn_on(WARN_UNREACHABLE_CODE))
5341 walk_statements(body, check_unreachable, NULL);
5342 if (noreturn_candidate &&
5343 !(function->base.modifiers & DM_NORETURN)) {
5344 source_position_t const *const pos = &body->base.source_position;
5345 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5349 if (is_main(entity)) {
5350 /* Force main to C linkage. */
5351 type_t *const type = entity->declaration.type;
5352 assert(is_type_function(type));
5353 if (type->function.linkage != LINKAGE_C) {
5354 type_t *new_type = duplicate_type(type);
5355 new_type->function.linkage = LINKAGE_C;
5356 entity->declaration.type = identify_new_type(new_type);
5359 if (enable_main_collect2_hack)
5360 prepare_main_collect2(entity);
5363 POP_CURRENT_ENTITY();
5365 assert(current_function == function);
5366 current_function = old_current_function;
5367 label_pop_to(label_stack_top);
5373 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5375 entity_t *iter = compound->members.entities;
5376 for (; iter != NULL; iter = iter->base.next) {
5377 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5380 if (iter->base.symbol == symbol) {
5382 } else if (iter->base.symbol == NULL) {
5383 /* search in anonymous structs and unions */
5384 type_t *type = skip_typeref(iter->declaration.type);
5385 if (is_type_compound(type)) {
5386 if (find_compound_entry(type->compound.compound, symbol)
5397 static void check_deprecated(const source_position_t *source_position,
5398 const entity_t *entity)
5400 if (!is_declaration(entity))
5402 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5405 source_position_t const *const epos = &entity->base.source_position;
5406 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5408 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5410 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5415 static expression_t *create_select(const source_position_t *pos,
5417 type_qualifiers_t qualifiers,
5420 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5422 check_deprecated(pos, entry);
5424 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5425 select->select.compound = addr;
5426 select->select.compound_entry = entry;
5428 type_t *entry_type = entry->declaration.type;
5429 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5431 /* bitfields need special treatment */
5432 if (entry->compound_member.bitfield) {
5433 unsigned bit_size = entry->compound_member.bit_size;
5434 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5435 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5436 res_type = type_int;
5440 /* we always do the auto-type conversions; the & and sizeof parser contains
5441 * code to revert this! */
5442 select->base.type = automatic_type_conversion(res_type);
5449 * Find entry with symbol in compound. Search anonymous structs and unions and
5450 * creates implicit select expressions for them.
5451 * Returns the adress for the innermost compound.
5453 static expression_t *find_create_select(const source_position_t *pos,
5455 type_qualifiers_t qualifiers,
5456 compound_t *compound, symbol_t *symbol)
5458 entity_t *iter = compound->members.entities;
5459 for (; iter != NULL; iter = iter->base.next) {
5460 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5463 symbol_t *iter_symbol = iter->base.symbol;
5464 if (iter_symbol == NULL) {
5465 type_t *type = iter->declaration.type;
5466 if (!is_type_compound(type))
5469 compound_t *sub_compound = type->compound.compound;
5471 if (find_compound_entry(sub_compound, symbol) == NULL)
5474 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5475 sub_addr->base.source_position = *pos;
5476 sub_addr->base.implicit = true;
5477 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5481 if (iter_symbol == symbol) {
5482 return create_select(pos, addr, qualifiers, iter);
5489 static void parse_bitfield_member(entity_t *entity)
5493 expression_t *size = parse_constant_expression();
5496 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5497 type_t *type = entity->declaration.type;
5498 if (!is_type_integer(skip_typeref(type))) {
5499 errorf(HERE, "bitfield base type '%T' is not an integer type",
5503 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5504 /* error already reported by parse_constant_expression */
5505 size_long = get_type_size(type) * 8;
5507 size_long = fold_constant_to_int(size);
5509 const symbol_t *symbol = entity->base.symbol;
5510 const symbol_t *user_symbol
5511 = symbol == NULL ? sym_anonymous : symbol;
5512 unsigned bit_size = get_type_size(type) * 8;
5513 if (size_long < 0) {
5514 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5515 } else if (size_long == 0 && symbol != NULL) {
5516 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5517 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5518 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5521 /* hope that people don't invent crazy types with more bits
5522 * than our struct can hold */
5524 (1 << sizeof(entity->compound_member.bit_size)*8));
5528 entity->compound_member.bitfield = true;
5529 entity->compound_member.bit_size = (unsigned char)size_long;
5532 static void parse_compound_declarators(compound_t *compound,
5533 const declaration_specifiers_t *specifiers)
5535 add_anchor_token(';');
5536 add_anchor_token(',');
5540 if (token.kind == ':') {
5541 /* anonymous bitfield */
5542 type_t *type = specifiers->type;
5543 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5544 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5545 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5546 entity->declaration.type = type;
5548 parse_bitfield_member(entity);
5550 attribute_t *attributes = parse_attributes(NULL);
5551 attribute_t **anchor = &attributes;
5552 while (*anchor != NULL)
5553 anchor = &(*anchor)->next;
5554 *anchor = specifiers->attributes;
5555 if (attributes != NULL) {
5556 handle_entity_attributes(attributes, entity);
5558 entity->declaration.attributes = attributes;
5560 append_entity(&compound->members, entity);
5562 entity = parse_declarator(specifiers,
5563 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5564 source_position_t const *const pos = &entity->base.source_position;
5565 if (entity->kind == ENTITY_TYPEDEF) {
5566 errorf(pos, "typedef not allowed as compound member");
5568 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5570 /* make sure we don't define a symbol multiple times */
5571 symbol_t *symbol = entity->base.symbol;
5572 if (symbol != NULL) {
5573 entity_t *prev = find_compound_entry(compound, symbol);
5575 source_position_t const *const ppos = &prev->base.source_position;
5576 errorf(pos, "multiple declarations of '%N' (declared %P)", entity, ppos);
5580 if (token.kind == ':') {
5581 parse_bitfield_member(entity);
5583 attribute_t *attributes = parse_attributes(NULL);
5584 handle_entity_attributes(attributes, entity);
5586 type_t *orig_type = entity->declaration.type;
5587 type_t *type = skip_typeref(orig_type);
5588 if (is_type_function(type)) {
5589 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5590 } else if (is_type_incomplete(type)) {
5591 /* §6.7.2.1:16 flexible array member */
5592 if (!is_type_array(type) ||
5593 token.kind != ';' ||
5594 look_ahead(1)->kind != '}') {
5595 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5596 } else if (compound->members.entities == NULL) {
5597 errorf(pos, "flexible array member in otherwise empty struct");
5602 append_entity(&compound->members, entity);
5605 } while (next_if(','));
5606 rem_anchor_token(',');
5607 rem_anchor_token(';');
5610 anonymous_entity = NULL;
5613 static void parse_compound_type_entries(compound_t *compound)
5616 add_anchor_token('}');
5619 switch (token.kind) {
5621 case T___extension__:
5622 case T_IDENTIFIER: {
5624 declaration_specifiers_t specifiers;
5625 parse_declaration_specifiers(&specifiers);
5626 parse_compound_declarators(compound, &specifiers);
5632 rem_anchor_token('}');
5635 compound->complete = true;
5641 static type_t *parse_typename(void)
5643 declaration_specifiers_t specifiers;
5644 parse_declaration_specifiers(&specifiers);
5645 if (specifiers.storage_class != STORAGE_CLASS_NONE
5646 || specifiers.thread_local) {
5647 /* TODO: improve error message, user does probably not know what a
5648 * storage class is...
5650 errorf(&specifiers.source_position, "typename must not have a storage class");
5653 type_t *result = parse_abstract_declarator(specifiers.type);
5661 typedef expression_t* (*parse_expression_function)(void);
5662 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5664 typedef struct expression_parser_function_t expression_parser_function_t;
5665 struct expression_parser_function_t {
5666 parse_expression_function parser;
5667 precedence_t infix_precedence;
5668 parse_expression_infix_function infix_parser;
5671 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5673 static type_t *get_string_type(string_encoding_t const enc)
5675 bool const warn = is_warn_on(WARN_WRITE_STRINGS);
5677 case STRING_ENCODING_CHAR: return warn ? type_const_char_ptr : type_char_ptr;
5678 case STRING_ENCODING_WIDE: return warn ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5680 panic("invalid string encoding");
5684 * Parse a string constant.
5686 static expression_t *parse_string_literal(void)
5688 expression_t *const expr = allocate_expression_zero(EXPR_STRING_LITERAL);
5689 expr->string_literal.value = concat_string_literals();
5690 expr->base.type = get_string_type(expr->string_literal.value.encoding);
5695 * Parse a boolean constant.
5697 static expression_t *parse_boolean_literal(bool value)
5699 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5700 literal->base.type = type_bool;
5701 literal->literal.value.begin = value ? "true" : "false";
5702 literal->literal.value.size = value ? 4 : 5;
5704 eat(value ? T_true : T_false);
5708 static void warn_traditional_suffix(char const *const suffix)
5710 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%s' suffix", suffix);
5713 static void check_integer_suffix(expression_t *const expr, char const *const suffix)
5715 unsigned spec = SPECIFIER_NONE;
5716 char const *c = suffix;
5719 if (*c == 'L' || *c == 'l') {
5720 add = SPECIFIER_LONG;
5722 add |= SPECIFIER_LONG_LONG;
5725 } else if (*c == 'U' || *c == 'u') {
5726 add = SPECIFIER_UNSIGNED;
5739 case SPECIFIER_NONE: type = type_int; break;
5740 case SPECIFIER_LONG: type = type_long; break;
5741 case SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_long_long; break;
5742 case SPECIFIER_UNSIGNED: type = type_unsigned_int; break;
5743 case SPECIFIER_UNSIGNED | SPECIFIER_LONG: type = type_unsigned_long; break;
5744 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_unsigned_long_long; break;
5745 default: panic("inconsistent suffix");
5747 if (spec != SPECIFIER_NONE && spec != SPECIFIER_LONG) {
5748 warn_traditional_suffix(suffix);
5750 expr->base.type = type;
5751 /* Integer type depends on the size of the number and the size
5752 * representable by the types. The backend/codegeneration has to
5753 * determine that. */
5754 determine_literal_type(&expr->literal);
5757 errorf(HERE, "invalid suffix '%s' on integer constant", suffix);
5761 static void check_floatingpoint_suffix(expression_t *const expr, char const *const suffix)
5764 char const *c = suffix;
5767 case 'f': type = type_float; ++c; break;
5769 case 'l': type = type_long_double; ++c; break;
5770 default: type = type_double; break;
5774 expr->base.type = type;
5775 if (suffix[0] != '\0') {
5776 warn_traditional_suffix(suffix);
5779 errorf(HERE, "invalid suffix '%s' on floatingpoint constant", suffix);
5783 static expression_t *parse_number_literal(void)
5785 string_t const *const str = &token.literal.string;
5786 char const * i = str->begin;
5787 unsigned digits = 0;
5788 bool is_float = false;
5790 /* Parse base prefix. */
5794 case 'B': case 'b': base = 2; ++i; break;
5795 case 'X': case 'x': base = 16; ++i; break;
5796 default: base = 8; digits |= 1U << 0; break;
5802 /* Parse mantissa. */
5808 errorf(HERE, "multiple decimal points in %K", &token);
5817 case '0': digit = 0; break;
5818 case '1': digit = 1; break;
5819 case '2': digit = 2; break;
5820 case '3': digit = 3; break;
5821 case '4': digit = 4; break;
5822 case '5': digit = 5; break;
5823 case '6': digit = 6; break;
5824 case '7': digit = 7; break;
5825 case '8': digit = 8; break;
5826 case '9': digit = 9; break;
5827 case 'A': case 'a': digit = 10; break;
5828 case 'B': case 'b': digit = 11; break;
5829 case 'C': case 'c': digit = 12; break;
5830 case 'D': case 'd': digit = 13; break;
5831 case 'E': case 'e': digit = 14; break;
5832 case 'F': case 'f': digit = 15; break;
5834 default: goto done_mantissa;
5837 if (digit >= 10 && base != 16)
5840 digits |= 1U << digit;
5844 /* Parse exponent. */
5848 errorf(HERE, "binary floating %K not allowed", &token);
5853 if (*i == 'E' || *i == 'e') {
5855 goto parse_exponent;
5860 if (*i == 'P' || *i == 'p') {
5865 if (*i == '-' || *i == '+')
5871 } while (isdigit(*i));
5873 errorf(HERE, "exponent of %K has no digits", &token);
5875 } else if (is_float) {
5876 errorf(HERE, "hexadecimal floating %K requires an exponent", &token);
5882 panic("invalid base");
5886 expression_t *const expr = allocate_expression_zero(is_float ? EXPR_LITERAL_FLOATINGPOINT : EXPR_LITERAL_INTEGER);
5887 expr->literal.value = *str;
5891 errorf(HERE, "%K has no digits", &token);
5892 } else if (digits & ~((1U << base) - 1)) {
5893 errorf(HERE, "invalid digit in %K", &token);
5895 expr->literal.suffix = i;
5897 check_floatingpoint_suffix(expr, i);
5899 check_integer_suffix(expr, i);
5909 * Parse a character constant.
5911 static expression_t *parse_character_constant(void)
5913 expression_t *const literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5914 literal->string_literal.value = token.literal.string;
5916 size_t const size = get_string_len(&token.literal.string);
5917 switch (token.literal.string.encoding) {
5918 case STRING_ENCODING_CHAR:
5919 literal->base.type = c_mode & _CXX ? type_char : type_int;
5921 if (!GNU_MODE && !(c_mode & _C99)) {
5922 errorf(HERE, "more than 1 character in character constant");
5924 literal->base.type = type_int;
5925 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5930 case STRING_ENCODING_WIDE:
5931 literal->base.type = type_int;
5933 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5938 eat(T_CHARACTER_CONSTANT);
5942 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5944 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5945 ntype->function.return_type = type_int;
5946 ntype->function.unspecified_parameters = true;
5947 ntype->function.linkage = LINKAGE_C;
5948 type_t *type = identify_new_type(ntype);
5950 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5951 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5952 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5953 entity->declaration.type = type;
5954 entity->declaration.implicit = true;
5956 if (current_scope != NULL)
5957 record_entity(entity, false);
5963 * Performs automatic type cast as described in §6.3.2.1.
5965 * @param orig_type the original type
5967 static type_t *automatic_type_conversion(type_t *orig_type)
5969 type_t *type = skip_typeref(orig_type);
5970 if (is_type_array(type)) {
5971 array_type_t *array_type = &type->array;
5972 type_t *element_type = array_type->element_type;
5973 unsigned qualifiers = array_type->base.qualifiers;
5975 return make_pointer_type(element_type, qualifiers);
5978 if (is_type_function(type)) {
5979 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5986 * reverts the automatic casts of array to pointer types and function
5987 * to function-pointer types as defined §6.3.2.1
5989 type_t *revert_automatic_type_conversion(const expression_t *expression)
5991 switch (expression->kind) {
5992 case EXPR_REFERENCE: {
5993 entity_t *entity = expression->reference.entity;
5994 if (is_declaration(entity)) {
5995 return entity->declaration.type;
5996 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5997 return entity->enum_value.enum_type;
5999 panic("no declaration or enum in reference");
6004 entity_t *entity = expression->select.compound_entry;
6005 assert(is_declaration(entity));
6006 type_t *type = entity->declaration.type;
6007 return get_qualified_type(type, expression->base.type->base.qualifiers);
6010 case EXPR_UNARY_DEREFERENCE: {
6011 const expression_t *const value = expression->unary.value;
6012 type_t *const type = skip_typeref(value->base.type);
6013 if (!is_type_pointer(type))
6014 return type_error_type;
6015 return type->pointer.points_to;
6018 case EXPR_ARRAY_ACCESS: {
6019 const expression_t *array_ref = expression->array_access.array_ref;
6020 type_t *type_left = skip_typeref(array_ref->base.type);
6021 if (!is_type_pointer(type_left))
6022 return type_error_type;
6023 return type_left->pointer.points_to;
6026 case EXPR_STRING_LITERAL: {
6027 size_t const size = get_string_len(&expression->string_literal.value) + 1;
6028 type_t *const elem = get_unqualified_type(expression->base.type->pointer.points_to);
6029 return make_array_type(elem, size, TYPE_QUALIFIER_NONE);
6032 case EXPR_COMPOUND_LITERAL:
6033 return expression->compound_literal.type;
6038 return expression->base.type;
6042 * Find an entity matching a symbol in a scope.
6043 * Uses current scope if scope is NULL
6045 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6046 namespace_tag_t namespc)
6048 if (scope == NULL) {
6049 return get_entity(symbol, namespc);
6052 /* we should optimize here, if scope grows above a certain size we should
6053 construct a hashmap here... */
6054 entity_t *entity = scope->entities;
6055 for ( ; entity != NULL; entity = entity->base.next) {
6056 if (entity->base.symbol == symbol
6057 && (namespace_tag_t)entity->base.namespc == namespc)
6064 static entity_t *parse_qualified_identifier(void)
6066 /* namespace containing the symbol */
6068 source_position_t pos;
6069 const scope_t *lookup_scope = NULL;
6071 if (next_if(T_COLONCOLON))
6072 lookup_scope = &unit->scope;
6076 symbol = expect_identifier("while parsing identifier", &pos);
6078 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6081 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6083 if (!next_if(T_COLONCOLON))
6086 switch (entity->kind) {
6087 case ENTITY_NAMESPACE:
6088 lookup_scope = &entity->namespacee.members;
6093 lookup_scope = &entity->compound.members;
6096 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6097 symbol, get_entity_kind_name(entity->kind));
6099 /* skip further qualifications */
6100 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6102 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6106 if (entity == NULL) {
6107 if (!strict_mode && token.kind == '(') {
6108 /* an implicitly declared function */
6109 entity = create_implicit_function(symbol, &pos);
6110 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of '%N'", entity);
6112 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6113 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6120 static expression_t *parse_reference(void)
6122 source_position_t const pos = *HERE;
6123 entity_t *const entity = parse_qualified_identifier();
6126 if (is_declaration(entity)) {
6127 orig_type = entity->declaration.type;
6128 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6129 orig_type = entity->enum_value.enum_type;
6131 panic("expected declaration or enum value in reference");
6134 /* we always do the auto-type conversions; the & and sizeof parser contains
6135 * code to revert this! */
6136 type_t *type = automatic_type_conversion(orig_type);
6138 expression_kind_t kind = EXPR_REFERENCE;
6139 if (entity->kind == ENTITY_ENUM_VALUE)
6140 kind = EXPR_ENUM_CONSTANT;
6142 expression_t *expression = allocate_expression_zero(kind);
6143 expression->base.source_position = pos;
6144 expression->base.type = type;
6145 expression->reference.entity = entity;
6147 /* this declaration is used */
6148 if (is_declaration(entity)) {
6149 entity->declaration.used = true;
6152 if (entity->base.parent_scope != file_scope
6153 && (current_function != NULL
6154 && entity->base.parent_scope->depth < current_function->parameters.depth)
6155 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6156 /* access of a variable from an outer function */
6157 entity->variable.address_taken = true;
6158 current_function->need_closure = true;
6161 check_deprecated(&pos, entity);
6166 static bool semantic_cast(expression_t *cast)
6168 expression_t *expression = cast->unary.value;
6169 type_t *orig_dest_type = cast->base.type;
6170 type_t *orig_type_right = expression->base.type;
6171 type_t const *dst_type = skip_typeref(orig_dest_type);
6172 type_t const *src_type = skip_typeref(orig_type_right);
6173 source_position_t const *pos = &cast->base.source_position;
6175 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6176 if (is_type_void(dst_type))
6179 /* only integer and pointer can be casted to pointer */
6180 if (is_type_pointer(dst_type) &&
6181 !is_type_pointer(src_type) &&
6182 !is_type_integer(src_type) &&
6183 is_type_valid(src_type)) {
6184 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6188 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6189 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6193 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6194 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6198 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6199 type_t *src = skip_typeref(src_type->pointer.points_to);
6200 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6201 unsigned missing_qualifiers =
6202 src->base.qualifiers & ~dst->base.qualifiers;
6203 if (missing_qualifiers != 0) {
6204 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6210 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6212 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6213 expression->base.source_position = *pos;
6215 parse_initializer_env_t env;
6218 env.must_be_constant = false;
6219 initializer_t *initializer = parse_initializer(&env);
6222 expression->compound_literal.initializer = initializer;
6223 expression->compound_literal.type = type;
6224 expression->base.type = automatic_type_conversion(type);
6230 * Parse a cast expression.
6232 static expression_t *parse_cast(void)
6234 source_position_t const pos = *HERE;
6237 add_anchor_token(')');
6239 type_t *type = parse_typename();
6241 rem_anchor_token(')');
6244 if (token.kind == '{') {
6245 return parse_compound_literal(&pos, type);
6248 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6249 cast->base.source_position = pos;
6251 expression_t *value = parse_subexpression(PREC_CAST);
6252 cast->base.type = type;
6253 cast->unary.value = value;
6255 if (! semantic_cast(cast)) {
6256 /* TODO: record the error in the AST. else it is impossible to detect it */
6263 * Parse a statement expression.
6265 static expression_t *parse_statement_expression(void)
6267 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6270 add_anchor_token(')');
6272 statement_t *statement = parse_compound_statement(true);
6273 statement->compound.stmt_expr = true;
6274 expression->statement.statement = statement;
6276 /* find last statement and use its type */
6277 type_t *type = type_void;
6278 const statement_t *stmt = statement->compound.statements;
6280 while (stmt->base.next != NULL)
6281 stmt = stmt->base.next;
6283 if (stmt->kind == STATEMENT_EXPRESSION) {
6284 type = stmt->expression.expression->base.type;
6287 source_position_t const *const pos = &expression->base.source_position;
6288 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6290 expression->base.type = type;
6292 rem_anchor_token(')');
6298 * Parse a parenthesized expression.
6300 static expression_t *parse_parenthesized_expression(void)
6302 token_t const* const la1 = look_ahead(1);
6303 switch (la1->kind) {
6305 /* gcc extension: a statement expression */
6306 return parse_statement_expression();
6309 if (is_typedef_symbol(la1->base.symbol)) {
6311 return parse_cast();
6316 add_anchor_token(')');
6317 expression_t *result = parse_expression();
6318 result->base.parenthesized = true;
6319 rem_anchor_token(')');
6325 static expression_t *parse_function_keyword(funcname_kind_t const kind)
6327 if (current_function == NULL) {
6328 errorf(HERE, "'%K' used outside of a function", &token);
6331 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6332 expression->base.type = type_char_ptr;
6333 expression->funcname.kind = kind;
6340 static designator_t *parse_designator(void)
6342 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6343 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6344 if (!result->symbol)
6347 designator_t *last_designator = result;
6350 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6351 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6352 if (!designator->symbol)
6355 last_designator->next = designator;
6356 last_designator = designator;
6360 add_anchor_token(']');
6361 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6362 designator->source_position = *HERE;
6363 designator->array_index = parse_expression();
6364 rem_anchor_token(']');
6366 if (designator->array_index == NULL) {
6370 last_designator->next = designator;
6371 last_designator = designator;
6381 * Parse the __builtin_offsetof() expression.
6383 static expression_t *parse_offsetof(void)
6385 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6386 expression->base.type = type_size_t;
6388 eat(T___builtin_offsetof);
6390 add_anchor_token(')');
6391 add_anchor_token(',');
6393 type_t *type = parse_typename();
6394 rem_anchor_token(',');
6396 designator_t *designator = parse_designator();
6397 rem_anchor_token(')');
6400 expression->offsetofe.type = type;
6401 expression->offsetofe.designator = designator;
6404 memset(&path, 0, sizeof(path));
6405 path.top_type = type;
6406 path.path = NEW_ARR_F(type_path_entry_t, 0);
6408 descend_into_subtype(&path);
6410 if (!walk_designator(&path, designator, true)) {
6411 return create_error_expression();
6414 DEL_ARR_F(path.path);
6419 static bool is_last_parameter(expression_t *const param)
6421 if (param->kind == EXPR_REFERENCE) {
6422 entity_t *const entity = param->reference.entity;
6423 if (entity->kind == ENTITY_PARAMETER &&
6424 !entity->base.next &&
6425 entity->base.parent_scope == ¤t_function->parameters) {
6430 if (!is_type_valid(skip_typeref(param->base.type)))
6437 * Parses a __builtin_va_start() expression.
6439 static expression_t *parse_va_start(void)
6441 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6443 eat(T___builtin_va_start);
6445 add_anchor_token(')');
6446 add_anchor_token(',');
6448 expression->va_starte.ap = parse_assignment_expression();
6449 rem_anchor_token(',');
6451 expression_t *const param = parse_assignment_expression();
6452 expression->va_starte.parameter = param;
6453 rem_anchor_token(')');
6456 if (!current_function) {
6457 errorf(&expression->base.source_position, "'va_start' used outside of function");
6458 } else if (!current_function->base.type->function.variadic) {
6459 errorf(&expression->base.source_position, "'va_start' used in non-variadic function");
6460 } else if (!is_last_parameter(param)) {
6461 errorf(¶m->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
6468 * Parses a __builtin_va_arg() expression.
6470 static expression_t *parse_va_arg(void)
6472 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6474 eat(T___builtin_va_arg);
6476 add_anchor_token(')');
6477 add_anchor_token(',');
6480 ap.expression = parse_assignment_expression();
6481 expression->va_arge.ap = ap.expression;
6482 check_call_argument(type_valist, &ap, 1);
6484 rem_anchor_token(',');
6486 expression->base.type = parse_typename();
6487 rem_anchor_token(')');
6494 * Parses a __builtin_va_copy() expression.
6496 static expression_t *parse_va_copy(void)
6498 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6500 eat(T___builtin_va_copy);
6502 add_anchor_token(')');
6503 add_anchor_token(',');
6505 expression_t *dst = parse_assignment_expression();
6506 assign_error_t error = semantic_assign(type_valist, dst);
6507 report_assign_error(error, type_valist, dst, "call argument 1",
6508 &dst->base.source_position);
6509 expression->va_copye.dst = dst;
6511 rem_anchor_token(',');
6514 call_argument_t src;
6515 src.expression = parse_assignment_expression();
6516 check_call_argument(type_valist, &src, 2);
6517 expression->va_copye.src = src.expression;
6518 rem_anchor_token(')');
6525 * Parses a __builtin_constant_p() expression.
6527 static expression_t *parse_builtin_constant(void)
6529 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6531 eat(T___builtin_constant_p);
6533 add_anchor_token(')');
6535 expression->builtin_constant.value = parse_assignment_expression();
6536 rem_anchor_token(')');
6538 expression->base.type = type_int;
6544 * Parses a __builtin_types_compatible_p() expression.
6546 static expression_t *parse_builtin_types_compatible(void)
6548 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6550 eat(T___builtin_types_compatible_p);
6552 add_anchor_token(')');
6553 add_anchor_token(',');
6555 expression->builtin_types_compatible.left = parse_typename();
6556 rem_anchor_token(',');
6558 expression->builtin_types_compatible.right = parse_typename();
6559 rem_anchor_token(')');
6561 expression->base.type = type_int;
6567 * Parses a __builtin_is_*() compare expression.
6569 static expression_t *parse_compare_builtin(void)
6571 expression_kind_t kind;
6572 switch (token.kind) {
6573 case T___builtin_isgreater: kind = EXPR_BINARY_ISGREATER; break;
6574 case T___builtin_isgreaterequal: kind = EXPR_BINARY_ISGREATEREQUAL; break;
6575 case T___builtin_isless: kind = EXPR_BINARY_ISLESS; break;
6576 case T___builtin_islessequal: kind = EXPR_BINARY_ISLESSEQUAL; break;
6577 case T___builtin_islessgreater: kind = EXPR_BINARY_ISLESSGREATER; break;
6578 case T___builtin_isunordered: kind = EXPR_BINARY_ISUNORDERED; break;
6579 default: internal_errorf(HERE, "invalid compare builtin found");
6581 expression_t *const expression = allocate_expression_zero(kind);
6584 add_anchor_token(')');
6585 add_anchor_token(',');
6587 expression->binary.left = parse_assignment_expression();
6588 rem_anchor_token(',');
6590 expression->binary.right = parse_assignment_expression();
6591 rem_anchor_token(')');
6594 type_t *const orig_type_left = expression->binary.left->base.type;
6595 type_t *const orig_type_right = expression->binary.right->base.type;
6597 type_t *const type_left = skip_typeref(orig_type_left);
6598 type_t *const type_right = skip_typeref(orig_type_right);
6599 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6600 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6601 type_error_incompatible("invalid operands in comparison",
6602 &expression->base.source_position, orig_type_left, orig_type_right);
6605 semantic_comparison(&expression->binary);
6612 * Parses a MS assume() expression.
6614 static expression_t *parse_assume(void)
6616 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6620 add_anchor_token(')');
6622 expression->unary.value = parse_assignment_expression();
6623 rem_anchor_token(')');
6626 expression->base.type = type_void;
6631 * Return the label for the current symbol or create a new one.
6633 static label_t *get_label(char const *const context)
6635 assert(current_function != NULL);
6637 symbol_t *const sym = expect_identifier(context, NULL);
6641 entity_t *label = get_entity(sym, NAMESPACE_LABEL);
6642 /* If we find a local label, we already created the declaration. */
6643 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6644 if (label->base.parent_scope != current_scope) {
6645 assert(label->base.parent_scope->depth < current_scope->depth);
6646 current_function->goto_to_outer = true;
6648 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6649 /* There is no matching label in the same function, so create a new one. */
6650 source_position_t const nowhere = { NULL, 0, 0, false };
6651 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym, &nowhere);
6655 return &label->label;
6659 * Parses a GNU && label address expression.
6661 static expression_t *parse_label_address(void)
6663 source_position_t const source_position = *HERE;
6666 label_t *const label = get_label("while parsing label address");
6668 return create_error_expression();
6671 label->address_taken = true;
6673 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6674 expression->base.source_position = source_position;
6676 /* label address is treated as a void pointer */
6677 expression->base.type = type_void_ptr;
6678 expression->label_address.label = label;
6683 * Parse a microsoft __noop expression.
6685 static expression_t *parse_noop_expression(void)
6687 /* the result is a (int)0 */
6688 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6689 literal->base.type = type_int;
6690 literal->literal.value.begin = "__noop";
6691 literal->literal.value.size = 6;
6695 if (token.kind == '(') {
6696 /* parse arguments */
6698 add_anchor_token(')');
6699 add_anchor_token(',');
6701 if (token.kind != ')') do {
6702 (void)parse_assignment_expression();
6703 } while (next_if(','));
6705 rem_anchor_token(',');
6706 rem_anchor_token(')');
6714 * Parses a primary expression.
6716 static expression_t *parse_primary_expression(void)
6718 switch (token.kind) {
6719 case T_false: return parse_boolean_literal(false);
6720 case T_true: return parse_boolean_literal(true);
6721 case T_NUMBER: return parse_number_literal();
6722 case T_CHARACTER_CONSTANT: return parse_character_constant();
6723 case T_STRING_LITERAL: return parse_string_literal();
6724 case T___func__: return parse_function_keyword(FUNCNAME_FUNCTION);
6725 case T___PRETTY_FUNCTION__: return parse_function_keyword(FUNCNAME_PRETTY_FUNCTION);
6726 case T___FUNCSIG__: return parse_function_keyword(FUNCNAME_FUNCSIG);
6727 case T___FUNCDNAME__: return parse_function_keyword(FUNCNAME_FUNCDNAME);
6728 case T___builtin_offsetof: return parse_offsetof();
6729 case T___builtin_va_start: return parse_va_start();
6730 case T___builtin_va_arg: return parse_va_arg();
6731 case T___builtin_va_copy: return parse_va_copy();
6732 case T___builtin_isgreater:
6733 case T___builtin_isgreaterequal:
6734 case T___builtin_isless:
6735 case T___builtin_islessequal:
6736 case T___builtin_islessgreater:
6737 case T___builtin_isunordered: return parse_compare_builtin();
6738 case T___builtin_constant_p: return parse_builtin_constant();
6739 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6740 case T__assume: return parse_assume();
6743 return parse_label_address();
6746 case '(': return parse_parenthesized_expression();
6747 case T___noop: return parse_noop_expression();
6749 /* Gracefully handle type names while parsing expressions. */
6751 return parse_reference();
6753 if (!is_typedef_symbol(token.base.symbol)) {
6754 return parse_reference();
6758 source_position_t const pos = *HERE;
6759 declaration_specifiers_t specifiers;
6760 parse_declaration_specifiers(&specifiers);
6761 type_t const *const type = parse_abstract_declarator(specifiers.type);
6762 errorf(&pos, "encountered type '%T' while parsing expression", type);
6763 return create_error_expression();
6767 errorf(HERE, "unexpected token %K, expected an expression", &token);
6769 return create_error_expression();
6772 static expression_t *parse_array_expression(expression_t *left)
6774 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6775 array_access_expression_t *const arr = &expr->array_access;
6778 add_anchor_token(']');
6780 expression_t *const inside = parse_expression();
6782 type_t *const orig_type_left = left->base.type;
6783 type_t *const orig_type_inside = inside->base.type;
6785 type_t *const type_left = skip_typeref(orig_type_left);
6786 type_t *const type_inside = skip_typeref(orig_type_inside);
6792 if (is_type_pointer(type_left)) {
6795 idx_type = type_inside;
6796 res_type = type_left->pointer.points_to;
6798 } else if (is_type_pointer(type_inside)) {
6799 arr->flipped = true;
6802 idx_type = type_left;
6803 res_type = type_inside->pointer.points_to;
6805 res_type = automatic_type_conversion(res_type);
6806 if (!is_type_integer(idx_type)) {
6807 errorf(&idx->base.source_position, "array subscript must have integer type");
6808 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6809 source_position_t const *const pos = &idx->base.source_position;
6810 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6813 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6814 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6816 res_type = type_error_type;
6821 arr->array_ref = ref;
6823 arr->base.type = res_type;
6825 rem_anchor_token(']');
6830 static bool is_bitfield(const expression_t *expression)
6832 return expression->kind == EXPR_SELECT
6833 && expression->select.compound_entry->compound_member.bitfield;
6836 static expression_t *parse_typeprop(expression_kind_t const kind)
6838 expression_t *tp_expression = allocate_expression_zero(kind);
6839 tp_expression->base.type = type_size_t;
6841 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6844 expression_t *expression;
6845 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6846 source_position_t const pos = *HERE;
6848 add_anchor_token(')');
6849 orig_type = parse_typename();
6850 rem_anchor_token(')');
6853 if (token.kind == '{') {
6854 /* It was not sizeof(type) after all. It is sizeof of an expression
6855 * starting with a compound literal */
6856 expression = parse_compound_literal(&pos, orig_type);
6857 goto typeprop_expression;
6860 expression = parse_subexpression(PREC_UNARY);
6862 typeprop_expression:
6863 if (is_bitfield(expression)) {
6864 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6865 errorf(&tp_expression->base.source_position,
6866 "operand of %s expression must not be a bitfield", what);
6869 tp_expression->typeprop.tp_expression = expression;
6871 orig_type = revert_automatic_type_conversion(expression);
6872 expression->base.type = orig_type;
6875 tp_expression->typeprop.type = orig_type;
6876 type_t const* const type = skip_typeref(orig_type);
6877 char const* wrong_type = NULL;
6878 if (is_type_incomplete(type)) {
6879 if (!is_type_void(type) || !GNU_MODE)
6880 wrong_type = "incomplete";
6881 } else if (type->kind == TYPE_FUNCTION) {
6883 /* function types are allowed (and return 1) */
6884 source_position_t const *const pos = &tp_expression->base.source_position;
6885 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6886 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6888 wrong_type = "function";
6892 if (wrong_type != NULL) {
6893 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6894 errorf(&tp_expression->base.source_position,
6895 "operand of %s expression must not be of %s type '%T'",
6896 what, wrong_type, orig_type);
6899 return tp_expression;
6902 static expression_t *parse_sizeof(void)
6904 return parse_typeprop(EXPR_SIZEOF);
6907 static expression_t *parse_alignof(void)
6909 return parse_typeprop(EXPR_ALIGNOF);
6912 static expression_t *parse_select_expression(expression_t *addr)
6914 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6915 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6916 source_position_t const pos = *HERE;
6919 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6921 return create_error_expression();
6923 type_t *const orig_type = addr->base.type;
6924 type_t *const type = skip_typeref(orig_type);
6927 bool saw_error = false;
6928 if (is_type_pointer(type)) {
6929 if (!select_left_arrow) {
6931 "request for member '%Y' in something not a struct or union, but '%T'",
6935 type_left = skip_typeref(type->pointer.points_to);
6937 if (select_left_arrow && is_type_valid(type)) {
6938 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6944 if (!is_type_compound(type_left)) {
6945 if (is_type_valid(type_left) && !saw_error) {
6947 "request for member '%Y' in something not a struct or union, but '%T'",
6950 return create_error_expression();
6953 compound_t *compound = type_left->compound.compound;
6954 if (!compound->complete) {
6955 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
6957 return create_error_expression();
6960 type_qualifiers_t qualifiers = type_left->base.qualifiers;
6961 expression_t *result =
6962 find_create_select(&pos, addr, qualifiers, compound, symbol);
6964 if (result == NULL) {
6965 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
6966 return create_error_expression();
6972 static void check_call_argument(type_t *expected_type,
6973 call_argument_t *argument, unsigned pos)
6975 type_t *expected_type_skip = skip_typeref(expected_type);
6976 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6977 expression_t *arg_expr = argument->expression;
6978 type_t *arg_type = skip_typeref(arg_expr->base.type);
6980 /* handle transparent union gnu extension */
6981 if (is_type_union(expected_type_skip)
6982 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
6983 compound_t *union_decl = expected_type_skip->compound.compound;
6984 type_t *best_type = NULL;
6985 entity_t *entry = union_decl->members.entities;
6986 for ( ; entry != NULL; entry = entry->base.next) {
6987 assert(is_declaration(entry));
6988 type_t *decl_type = entry->declaration.type;
6989 error = semantic_assign(decl_type, arg_expr);
6990 if (error == ASSIGN_ERROR_INCOMPATIBLE
6991 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6994 if (error == ASSIGN_SUCCESS) {
6995 best_type = decl_type;
6996 } else if (best_type == NULL) {
6997 best_type = decl_type;
7001 if (best_type != NULL) {
7002 expected_type = best_type;
7006 error = semantic_assign(expected_type, arg_expr);
7007 argument->expression = create_implicit_cast(arg_expr, expected_type);
7009 if (error != ASSIGN_SUCCESS) {
7010 /* report exact scope in error messages (like "in argument 3") */
7012 snprintf(buf, sizeof(buf), "call argument %u", pos);
7013 report_assign_error(error, expected_type, arg_expr, buf,
7014 &arg_expr->base.source_position);
7016 type_t *const promoted_type = get_default_promoted_type(arg_type);
7017 if (!types_compatible(expected_type_skip, promoted_type) &&
7018 !types_compatible(expected_type_skip, type_void_ptr) &&
7019 !types_compatible(type_void_ptr, promoted_type)) {
7020 /* Deliberately show the skipped types in this warning */
7021 source_position_t const *const apos = &arg_expr->base.source_position;
7022 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7028 * Handle the semantic restrictions of builtin calls
7030 static void handle_builtin_argument_restrictions(call_expression_t *call)
7032 entity_t *entity = call->function->reference.entity;
7033 switch (entity->function.btk) {
7035 switch (entity->function.b.firm_builtin_kind) {
7036 case ir_bk_return_address:
7037 case ir_bk_frame_address: {
7038 /* argument must be constant */
7039 call_argument_t *argument = call->arguments;
7041 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7042 errorf(&call->base.source_position,
7043 "argument of '%Y' must be a constant expression",
7044 call->function->reference.entity->base.symbol);
7048 case ir_bk_prefetch:
7049 /* second and third argument must be constant if existent */
7050 if (call->arguments == NULL)
7052 call_argument_t *rw = call->arguments->next;
7053 call_argument_t *locality = NULL;
7056 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7057 errorf(&call->base.source_position,
7058 "second argument of '%Y' must be a constant expression",
7059 call->function->reference.entity->base.symbol);
7061 locality = rw->next;
7063 if (locality != NULL) {
7064 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7065 errorf(&call->base.source_position,
7066 "third argument of '%Y' must be a constant expression",
7067 call->function->reference.entity->base.symbol);
7069 locality = rw->next;
7076 case BUILTIN_OBJECT_SIZE:
7077 if (call->arguments == NULL)
7080 call_argument_t *arg = call->arguments->next;
7081 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7082 errorf(&call->base.source_position,
7083 "second argument of '%Y' must be a constant expression",
7084 call->function->reference.entity->base.symbol);
7093 * Parse a call expression, ie. expression '( ... )'.
7095 * @param expression the function address
7097 static expression_t *parse_call_expression(expression_t *expression)
7099 expression_t *result = allocate_expression_zero(EXPR_CALL);
7100 call_expression_t *call = &result->call;
7101 call->function = expression;
7103 type_t *const orig_type = expression->base.type;
7104 type_t *const type = skip_typeref(orig_type);
7106 function_type_t *function_type = NULL;
7107 if (is_type_pointer(type)) {
7108 type_t *const to_type = skip_typeref(type->pointer.points_to);
7110 if (is_type_function(to_type)) {
7111 function_type = &to_type->function;
7112 call->base.type = function_type->return_type;
7116 if (function_type == NULL && is_type_valid(type)) {
7118 "called object '%E' (type '%T') is not a pointer to a function",
7119 expression, orig_type);
7122 /* parse arguments */
7124 add_anchor_token(')');
7125 add_anchor_token(',');
7127 if (token.kind != ')') {
7128 call_argument_t **anchor = &call->arguments;
7130 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7131 argument->expression = parse_assignment_expression();
7134 anchor = &argument->next;
7135 } while (next_if(','));
7137 rem_anchor_token(',');
7138 rem_anchor_token(')');
7141 if (function_type == NULL)
7144 /* check type and count of call arguments */
7145 function_parameter_t *parameter = function_type->parameters;
7146 call_argument_t *argument = call->arguments;
7147 if (!function_type->unspecified_parameters) {
7148 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7149 parameter = parameter->next, argument = argument->next) {
7150 check_call_argument(parameter->type, argument, ++pos);
7153 if (parameter != NULL) {
7154 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7155 } else if (argument != NULL && !function_type->variadic) {
7156 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7160 /* do default promotion for other arguments */
7161 for (; argument != NULL; argument = argument->next) {
7162 type_t *argument_type = argument->expression->base.type;
7163 if (!is_type_object(skip_typeref(argument_type))) {
7164 errorf(&argument->expression->base.source_position,
7165 "call argument '%E' must not be void", argument->expression);
7168 argument_type = get_default_promoted_type(argument_type);
7170 argument->expression
7171 = create_implicit_cast(argument->expression, argument_type);
7176 if (is_type_compound(skip_typeref(function_type->return_type))) {
7177 source_position_t const *const pos = &expression->base.source_position;
7178 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7181 if (expression->kind == EXPR_REFERENCE) {
7182 reference_expression_t *reference = &expression->reference;
7183 if (reference->entity->kind == ENTITY_FUNCTION &&
7184 reference->entity->function.btk != BUILTIN_NONE)
7185 handle_builtin_argument_restrictions(call);
7191 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7193 static bool same_compound_type(const type_t *type1, const type_t *type2)
7196 is_type_compound(type1) &&
7197 type1->kind == type2->kind &&
7198 type1->compound.compound == type2->compound.compound;
7201 static expression_t const *get_reference_address(expression_t const *expr)
7203 bool regular_take_address = true;
7205 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7206 expr = expr->unary.value;
7208 regular_take_address = false;
7211 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7214 expr = expr->unary.value;
7217 if (expr->kind != EXPR_REFERENCE)
7220 /* special case for functions which are automatically converted to a
7221 * pointer to function without an extra TAKE_ADDRESS operation */
7222 if (!regular_take_address &&
7223 expr->reference.entity->kind != ENTITY_FUNCTION) {
7230 static void warn_reference_address_as_bool(expression_t const* expr)
7232 expr = get_reference_address(expr);
7234 source_position_t const *const pos = &expr->base.source_position;
7235 entity_t const *const ent = expr->reference.entity;
7236 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7240 static void warn_assignment_in_condition(const expression_t *const expr)
7242 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7244 if (expr->base.parenthesized)
7246 source_position_t const *const pos = &expr->base.source_position;
7247 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7250 static void semantic_condition(expression_t const *const expr,
7251 char const *const context)
7253 type_t *const type = skip_typeref(expr->base.type);
7254 if (is_type_scalar(type)) {
7255 warn_reference_address_as_bool(expr);
7256 warn_assignment_in_condition(expr);
7257 } else if (is_type_valid(type)) {
7258 errorf(&expr->base.source_position,
7259 "%s must have scalar type", context);
7264 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7266 * @param expression the conditional expression
7268 static expression_t *parse_conditional_expression(expression_t *expression)
7270 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7272 conditional_expression_t *conditional = &result->conditional;
7273 conditional->condition = expression;
7276 add_anchor_token(':');
7278 /* §6.5.15:2 The first operand shall have scalar type. */
7279 semantic_condition(expression, "condition of conditional operator");
7281 expression_t *true_expression = expression;
7282 bool gnu_cond = false;
7283 if (GNU_MODE && token.kind == ':') {
7286 true_expression = parse_expression();
7288 rem_anchor_token(':');
7290 expression_t *false_expression =
7291 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7293 type_t *const orig_true_type = true_expression->base.type;
7294 type_t *const orig_false_type = false_expression->base.type;
7295 type_t *const true_type = skip_typeref(orig_true_type);
7296 type_t *const false_type = skip_typeref(orig_false_type);
7299 source_position_t const *const pos = &conditional->base.source_position;
7300 type_t *result_type;
7301 if (is_type_void(true_type) || is_type_void(false_type)) {
7302 /* ISO/IEC 14882:1998(E) §5.16:2 */
7303 if (true_expression->kind == EXPR_UNARY_THROW) {
7304 result_type = false_type;
7305 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7306 result_type = true_type;
7308 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7309 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7311 result_type = type_void;
7313 } else if (is_type_arithmetic(true_type)
7314 && is_type_arithmetic(false_type)) {
7315 result_type = semantic_arithmetic(true_type, false_type);
7316 } else if (same_compound_type(true_type, false_type)) {
7317 /* just take 1 of the 2 types */
7318 result_type = true_type;
7319 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7320 type_t *pointer_type;
7322 expression_t *other_expression;
7323 if (is_type_pointer(true_type) &&
7324 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7325 pointer_type = true_type;
7326 other_type = false_type;
7327 other_expression = false_expression;
7329 pointer_type = false_type;
7330 other_type = true_type;
7331 other_expression = true_expression;
7334 if (is_null_pointer_constant(other_expression)) {
7335 result_type = pointer_type;
7336 } else if (is_type_pointer(other_type)) {
7337 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7338 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7341 if (is_type_void(to1) || is_type_void(to2)) {
7343 } else if (types_compatible(get_unqualified_type(to1),
7344 get_unqualified_type(to2))) {
7347 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7351 type_t *const type =
7352 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7353 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7354 } else if (is_type_integer(other_type)) {
7355 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7356 result_type = pointer_type;
7358 goto types_incompatible;
7362 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7363 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7365 result_type = type_error_type;
7368 conditional->true_expression
7369 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7370 conditional->false_expression
7371 = create_implicit_cast(false_expression, result_type);
7372 conditional->base.type = result_type;
7377 * Parse an extension expression.
7379 static expression_t *parse_extension(void)
7382 expression_t *expression = parse_subexpression(PREC_UNARY);
7388 * Parse a __builtin_classify_type() expression.
7390 static expression_t *parse_builtin_classify_type(void)
7392 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7393 result->base.type = type_int;
7395 eat(T___builtin_classify_type);
7397 add_anchor_token(')');
7399 expression_t *expression = parse_expression();
7400 rem_anchor_token(')');
7402 result->classify_type.type_expression = expression;
7408 * Parse a delete expression
7409 * ISO/IEC 14882:1998(E) §5.3.5
7411 static expression_t *parse_delete(void)
7413 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7414 result->base.type = type_void;
7419 result->kind = EXPR_UNARY_DELETE_ARRAY;
7423 expression_t *const value = parse_subexpression(PREC_CAST);
7424 result->unary.value = value;
7426 type_t *const type = skip_typeref(value->base.type);
7427 if (!is_type_pointer(type)) {
7428 if (is_type_valid(type)) {
7429 errorf(&value->base.source_position,
7430 "operand of delete must have pointer type");
7432 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7433 source_position_t const *const pos = &value->base.source_position;
7434 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7441 * Parse a throw expression
7442 * ISO/IEC 14882:1998(E) §15:1
7444 static expression_t *parse_throw(void)
7446 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7447 result->base.type = type_void;
7451 expression_t *value = NULL;
7452 switch (token.kind) {
7454 value = parse_assignment_expression();
7455 /* ISO/IEC 14882:1998(E) §15.1:3 */
7456 type_t *const orig_type = value->base.type;
7457 type_t *const type = skip_typeref(orig_type);
7458 if (is_type_incomplete(type)) {
7459 errorf(&value->base.source_position,
7460 "cannot throw object of incomplete type '%T'", orig_type);
7461 } else if (is_type_pointer(type)) {
7462 type_t *const points_to = skip_typeref(type->pointer.points_to);
7463 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7464 errorf(&value->base.source_position,
7465 "cannot throw pointer to incomplete type '%T'", orig_type);
7473 result->unary.value = value;
7478 static bool check_pointer_arithmetic(const source_position_t *source_position,
7479 type_t *pointer_type,
7480 type_t *orig_pointer_type)
7482 type_t *points_to = pointer_type->pointer.points_to;
7483 points_to = skip_typeref(points_to);
7485 if (is_type_incomplete(points_to)) {
7486 if (!GNU_MODE || !is_type_void(points_to)) {
7487 errorf(source_position,
7488 "arithmetic with pointer to incomplete type '%T' not allowed",
7492 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7494 } else if (is_type_function(points_to)) {
7496 errorf(source_position,
7497 "arithmetic with pointer to function type '%T' not allowed",
7501 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7507 static bool is_lvalue(const expression_t *expression)
7509 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7510 switch (expression->kind) {
7511 case EXPR_ARRAY_ACCESS:
7512 case EXPR_COMPOUND_LITERAL:
7513 case EXPR_REFERENCE:
7515 case EXPR_UNARY_DEREFERENCE:
7519 type_t *type = skip_typeref(expression->base.type);
7521 /* ISO/IEC 14882:1998(E) §3.10:3 */
7522 is_type_reference(type) ||
7523 /* Claim it is an lvalue, if the type is invalid. There was a parse
7524 * error before, which maybe prevented properly recognizing it as
7526 !is_type_valid(type);
7531 static void semantic_incdec(unary_expression_t *expression)
7533 type_t *const orig_type = expression->value->base.type;
7534 type_t *const type = skip_typeref(orig_type);
7535 if (is_type_pointer(type)) {
7536 if (!check_pointer_arithmetic(&expression->base.source_position,
7540 } else if (!is_type_real(type) && is_type_valid(type)) {
7541 /* TODO: improve error message */
7542 errorf(&expression->base.source_position,
7543 "operation needs an arithmetic or pointer type");
7546 if (!is_lvalue(expression->value)) {
7547 /* TODO: improve error message */
7548 errorf(&expression->base.source_position, "lvalue required as operand");
7550 expression->base.type = orig_type;
7553 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7555 type_t *const res_type = promote_integer(type);
7556 expr->base.type = res_type;
7557 expr->value = create_implicit_cast(expr->value, res_type);
7560 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7562 type_t *const orig_type = expression->value->base.type;
7563 type_t *const type = skip_typeref(orig_type);
7564 if (!is_type_arithmetic(type)) {
7565 if (is_type_valid(type)) {
7566 /* TODO: improve error message */
7567 errorf(&expression->base.source_position,
7568 "operation needs an arithmetic type");
7571 } else if (is_type_integer(type)) {
7572 promote_unary_int_expr(expression, type);
7574 expression->base.type = orig_type;
7578 static void semantic_unexpr_plus(unary_expression_t *expression)
7580 semantic_unexpr_arithmetic(expression);
7581 source_position_t const *const pos = &expression->base.source_position;
7582 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7585 static void semantic_not(unary_expression_t *expression)
7587 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7588 semantic_condition(expression->value, "operand of !");
7589 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7592 static void semantic_unexpr_integer(unary_expression_t *expression)
7594 type_t *const orig_type = expression->value->base.type;
7595 type_t *const type = skip_typeref(orig_type);
7596 if (!is_type_integer(type)) {
7597 if (is_type_valid(type)) {
7598 errorf(&expression->base.source_position,
7599 "operand of ~ must be of integer type");
7604 promote_unary_int_expr(expression, type);
7607 static void semantic_dereference(unary_expression_t *expression)
7609 type_t *const orig_type = expression->value->base.type;
7610 type_t *const type = skip_typeref(orig_type);
7611 if (!is_type_pointer(type)) {
7612 if (is_type_valid(type)) {
7613 errorf(&expression->base.source_position,
7614 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7619 type_t *result_type = type->pointer.points_to;
7620 result_type = automatic_type_conversion(result_type);
7621 expression->base.type = result_type;
7625 * Record that an address is taken (expression represents an lvalue).
7627 * @param expression the expression
7628 * @param may_be_register if true, the expression might be an register
7630 static void set_address_taken(expression_t *expression, bool may_be_register)
7632 if (expression->kind != EXPR_REFERENCE)
7635 entity_t *const entity = expression->reference.entity;
7637 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7640 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7641 && !may_be_register) {
7642 source_position_t const *const pos = &expression->base.source_position;
7643 errorf(pos, "address of register '%N' requested", entity);
7646 entity->variable.address_taken = true;
7650 * Check the semantic of the address taken expression.
7652 static void semantic_take_addr(unary_expression_t *expression)
7654 expression_t *value = expression->value;
7655 value->base.type = revert_automatic_type_conversion(value);
7657 type_t *orig_type = value->base.type;
7658 type_t *type = skip_typeref(orig_type);
7659 if (!is_type_valid(type))
7663 if (!is_lvalue(value)) {
7664 errorf(&expression->base.source_position, "'&' requires an lvalue");
7666 if (is_bitfield(value)) {
7667 errorf(&expression->base.source_position,
7668 "'&' not allowed on bitfield");
7671 set_address_taken(value, false);
7673 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7676 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7677 static expression_t *parse_##unexpression_type(void) \
7679 expression_t *unary_expression \
7680 = allocate_expression_zero(unexpression_type); \
7682 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7684 sfunc(&unary_expression->unary); \
7686 return unary_expression; \
7689 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7690 semantic_unexpr_arithmetic)
7691 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7692 semantic_unexpr_plus)
7693 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7695 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7696 semantic_dereference)
7697 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7699 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7700 semantic_unexpr_integer)
7701 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7703 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7706 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7708 static expression_t *parse_##unexpression_type(expression_t *left) \
7710 expression_t *unary_expression \
7711 = allocate_expression_zero(unexpression_type); \
7713 unary_expression->unary.value = left; \
7715 sfunc(&unary_expression->unary); \
7717 return unary_expression; \
7720 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7721 EXPR_UNARY_POSTFIX_INCREMENT,
7723 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7724 EXPR_UNARY_POSTFIX_DECREMENT,
7727 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7729 /* TODO: handle complex + imaginary types */
7731 type_left = get_unqualified_type(type_left);
7732 type_right = get_unqualified_type(type_right);
7734 /* §6.3.1.8 Usual arithmetic conversions */
7735 if (type_left == type_long_double || type_right == type_long_double) {
7736 return type_long_double;
7737 } else if (type_left == type_double || type_right == type_double) {
7739 } else if (type_left == type_float || type_right == type_float) {
7743 type_left = promote_integer(type_left);
7744 type_right = promote_integer(type_right);
7746 if (type_left == type_right)
7749 bool const signed_left = is_type_signed(type_left);
7750 bool const signed_right = is_type_signed(type_right);
7751 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7752 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7754 if (signed_left == signed_right)
7755 return rank_left >= rank_right ? type_left : type_right;
7759 atomic_type_kind_t s_akind;
7760 atomic_type_kind_t u_akind;
7765 u_type = type_right;
7767 s_type = type_right;
7770 s_akind = get_akind(s_type);
7771 u_akind = get_akind(u_type);
7772 s_rank = get_akind_rank(s_akind);
7773 u_rank = get_akind_rank(u_akind);
7775 if (u_rank >= s_rank)
7778 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7782 case ATOMIC_TYPE_INT: return type_unsigned_int;
7783 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7784 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7786 default: panic("invalid atomic type");
7791 * Check the semantic restrictions for a binary expression.
7793 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7795 expression_t *const left = expression->left;
7796 expression_t *const right = expression->right;
7797 type_t *const orig_type_left = left->base.type;
7798 type_t *const orig_type_right = right->base.type;
7799 type_t *const type_left = skip_typeref(orig_type_left);
7800 type_t *const type_right = skip_typeref(orig_type_right);
7802 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7803 /* TODO: improve error message */
7804 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7805 errorf(&expression->base.source_position,
7806 "operation needs arithmetic types");
7811 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7812 expression->left = create_implicit_cast(left, arithmetic_type);
7813 expression->right = create_implicit_cast(right, arithmetic_type);
7814 expression->base.type = arithmetic_type;
7817 static void semantic_binexpr_integer(binary_expression_t *const expression)
7819 expression_t *const left = expression->left;
7820 expression_t *const right = expression->right;
7821 type_t *const orig_type_left = left->base.type;
7822 type_t *const orig_type_right = right->base.type;
7823 type_t *const type_left = skip_typeref(orig_type_left);
7824 type_t *const type_right = skip_typeref(orig_type_right);
7826 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7827 /* TODO: improve error message */
7828 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7829 errorf(&expression->base.source_position,
7830 "operation needs integer types");
7835 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7836 expression->left = create_implicit_cast(left, result_type);
7837 expression->right = create_implicit_cast(right, result_type);
7838 expression->base.type = result_type;
7841 static void warn_div_by_zero(binary_expression_t const *const expression)
7843 if (!is_type_integer(expression->base.type))
7846 expression_t const *const right = expression->right;
7847 /* The type of the right operand can be different for /= */
7848 if (is_type_integer(right->base.type) &&
7849 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7850 !fold_constant_to_bool(right)) {
7851 source_position_t const *const pos = &expression->base.source_position;
7852 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7857 * Check the semantic restrictions for a div/mod expression.
7859 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7861 semantic_binexpr_arithmetic(expression);
7862 warn_div_by_zero(expression);
7865 static void warn_addsub_in_shift(const expression_t *const expr)
7867 if (expr->base.parenthesized)
7871 switch (expr->kind) {
7872 case EXPR_BINARY_ADD: op = '+'; break;
7873 case EXPR_BINARY_SUB: op = '-'; break;
7877 source_position_t const *const pos = &expr->base.source_position;
7878 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7881 static bool semantic_shift(binary_expression_t *expression)
7883 expression_t *const left = expression->left;
7884 expression_t *const right = expression->right;
7885 type_t *const orig_type_left = left->base.type;
7886 type_t *const orig_type_right = right->base.type;
7887 type_t * type_left = skip_typeref(orig_type_left);
7888 type_t * type_right = skip_typeref(orig_type_right);
7890 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7891 /* TODO: improve error message */
7892 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7893 errorf(&expression->base.source_position,
7894 "operands of shift operation must have integer types");
7899 type_left = promote_integer(type_left);
7901 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7902 source_position_t const *const pos = &right->base.source_position;
7903 long const count = fold_constant_to_int(right);
7905 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7906 } else if ((unsigned long)count >=
7907 get_atomic_type_size(type_left->atomic.akind) * 8) {
7908 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7912 type_right = promote_integer(type_right);
7913 expression->right = create_implicit_cast(right, type_right);
7918 static void semantic_shift_op(binary_expression_t *expression)
7920 expression_t *const left = expression->left;
7921 expression_t *const right = expression->right;
7923 if (!semantic_shift(expression))
7926 warn_addsub_in_shift(left);
7927 warn_addsub_in_shift(right);
7929 type_t *const orig_type_left = left->base.type;
7930 type_t * type_left = skip_typeref(orig_type_left);
7932 type_left = promote_integer(type_left);
7933 expression->left = create_implicit_cast(left, type_left);
7934 expression->base.type = type_left;
7937 static void semantic_add(binary_expression_t *expression)
7939 expression_t *const left = expression->left;
7940 expression_t *const right = expression->right;
7941 type_t *const orig_type_left = left->base.type;
7942 type_t *const orig_type_right = right->base.type;
7943 type_t *const type_left = skip_typeref(orig_type_left);
7944 type_t *const type_right = skip_typeref(orig_type_right);
7947 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7948 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7949 expression->left = create_implicit_cast(left, arithmetic_type);
7950 expression->right = create_implicit_cast(right, arithmetic_type);
7951 expression->base.type = arithmetic_type;
7952 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7953 check_pointer_arithmetic(&expression->base.source_position,
7954 type_left, orig_type_left);
7955 expression->base.type = type_left;
7956 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7957 check_pointer_arithmetic(&expression->base.source_position,
7958 type_right, orig_type_right);
7959 expression->base.type = type_right;
7960 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7961 errorf(&expression->base.source_position,
7962 "invalid operands to binary + ('%T', '%T')",
7963 orig_type_left, orig_type_right);
7967 static void semantic_sub(binary_expression_t *expression)
7969 expression_t *const left = expression->left;
7970 expression_t *const right = expression->right;
7971 type_t *const orig_type_left = left->base.type;
7972 type_t *const orig_type_right = right->base.type;
7973 type_t *const type_left = skip_typeref(orig_type_left);
7974 type_t *const type_right = skip_typeref(orig_type_right);
7975 source_position_t const *const pos = &expression->base.source_position;
7978 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7979 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7980 expression->left = create_implicit_cast(left, arithmetic_type);
7981 expression->right = create_implicit_cast(right, arithmetic_type);
7982 expression->base.type = arithmetic_type;
7983 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7984 check_pointer_arithmetic(&expression->base.source_position,
7985 type_left, orig_type_left);
7986 expression->base.type = type_left;
7987 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7988 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7989 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7990 if (!types_compatible(unqual_left, unqual_right)) {
7992 "subtracting pointers to incompatible types '%T' and '%T'",
7993 orig_type_left, orig_type_right);
7994 } else if (!is_type_object(unqual_left)) {
7995 if (!is_type_void(unqual_left)) {
7996 errorf(pos, "subtracting pointers to non-object types '%T'",
7999 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8002 expression->base.type = type_ptrdiff_t;
8003 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8004 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8005 orig_type_left, orig_type_right);
8009 static void warn_string_literal_address(expression_t const* expr)
8011 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8012 expr = expr->unary.value;
8013 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8015 expr = expr->unary.value;
8018 if (expr->kind == EXPR_STRING_LITERAL) {
8019 source_position_t const *const pos = &expr->base.source_position;
8020 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8024 static bool maybe_negative(expression_t const *const expr)
8026 switch (is_constant_expression(expr)) {
8027 case EXPR_CLASS_ERROR: return false;
8028 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8029 default: return true;
8033 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8035 warn_string_literal_address(expr);
8037 expression_t const* const ref = get_reference_address(expr);
8038 if (ref != NULL && is_null_pointer_constant(other)) {
8039 entity_t const *const ent = ref->reference.entity;
8040 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8043 if (!expr->base.parenthesized) {
8044 switch (expr->base.kind) {
8045 case EXPR_BINARY_LESS:
8046 case EXPR_BINARY_GREATER:
8047 case EXPR_BINARY_LESSEQUAL:
8048 case EXPR_BINARY_GREATEREQUAL:
8049 case EXPR_BINARY_NOTEQUAL:
8050 case EXPR_BINARY_EQUAL:
8051 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8060 * Check the semantics of comparison expressions.
8062 * @param expression The expression to check.
8064 static void semantic_comparison(binary_expression_t *expression)
8066 source_position_t const *const pos = &expression->base.source_position;
8067 expression_t *const left = expression->left;
8068 expression_t *const right = expression->right;
8070 warn_comparison(pos, left, right);
8071 warn_comparison(pos, right, left);
8073 type_t *orig_type_left = left->base.type;
8074 type_t *orig_type_right = right->base.type;
8075 type_t *type_left = skip_typeref(orig_type_left);
8076 type_t *type_right = skip_typeref(orig_type_right);
8078 /* TODO non-arithmetic types */
8079 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8080 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8082 /* test for signed vs unsigned compares */
8083 if (is_type_integer(arithmetic_type)) {
8084 bool const signed_left = is_type_signed(type_left);
8085 bool const signed_right = is_type_signed(type_right);
8086 if (signed_left != signed_right) {
8087 /* FIXME long long needs better const folding magic */
8088 /* TODO check whether constant value can be represented by other type */
8089 if ((signed_left && maybe_negative(left)) ||
8090 (signed_right && maybe_negative(right))) {
8091 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8096 expression->left = create_implicit_cast(left, arithmetic_type);
8097 expression->right = create_implicit_cast(right, arithmetic_type);
8098 expression->base.type = arithmetic_type;
8099 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8100 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8101 is_type_float(arithmetic_type)) {
8102 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8104 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8105 /* TODO check compatibility */
8106 } else if (is_type_pointer(type_left)) {
8107 expression->right = create_implicit_cast(right, type_left);
8108 } else if (is_type_pointer(type_right)) {
8109 expression->left = create_implicit_cast(left, type_right);
8110 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8111 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8113 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8117 * Checks if a compound type has constant fields.
8119 static bool has_const_fields(const compound_type_t *type)
8121 compound_t *compound = type->compound;
8122 entity_t *entry = compound->members.entities;
8124 for (; entry != NULL; entry = entry->base.next) {
8125 if (!is_declaration(entry))
8128 const type_t *decl_type = skip_typeref(entry->declaration.type);
8129 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8136 static bool is_valid_assignment_lhs(expression_t const* const left)
8138 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8139 type_t *const type_left = skip_typeref(orig_type_left);
8141 if (!is_lvalue(left)) {
8142 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8147 if (left->kind == EXPR_REFERENCE
8148 && left->reference.entity->kind == ENTITY_FUNCTION) {
8149 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8153 if (is_type_array(type_left)) {
8154 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8157 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8158 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8162 if (is_type_incomplete(type_left)) {
8163 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8164 left, orig_type_left);
8167 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8168 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8169 left, orig_type_left);
8176 static void semantic_arithmetic_assign(binary_expression_t *expression)
8178 expression_t *left = expression->left;
8179 expression_t *right = expression->right;
8180 type_t *orig_type_left = left->base.type;
8181 type_t *orig_type_right = right->base.type;
8183 if (!is_valid_assignment_lhs(left))
8186 type_t *type_left = skip_typeref(orig_type_left);
8187 type_t *type_right = skip_typeref(orig_type_right);
8189 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8190 /* TODO: improve error message */
8191 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8192 errorf(&expression->base.source_position,
8193 "operation needs arithmetic types");
8198 /* combined instructions are tricky. We can't create an implicit cast on
8199 * the left side, because we need the uncasted form for the store.
8200 * The ast2firm pass has to know that left_type must be right_type
8201 * for the arithmetic operation and create a cast by itself */
8202 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8203 expression->right = create_implicit_cast(right, arithmetic_type);
8204 expression->base.type = type_left;
8207 static void semantic_divmod_assign(binary_expression_t *expression)
8209 semantic_arithmetic_assign(expression);
8210 warn_div_by_zero(expression);
8213 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8215 expression_t *const left = expression->left;
8216 expression_t *const right = expression->right;
8217 type_t *const orig_type_left = left->base.type;
8218 type_t *const orig_type_right = right->base.type;
8219 type_t *const type_left = skip_typeref(orig_type_left);
8220 type_t *const type_right = skip_typeref(orig_type_right);
8222 if (!is_valid_assignment_lhs(left))
8225 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8226 /* combined instructions are tricky. We can't create an implicit cast on
8227 * the left side, because we need the uncasted form for the store.
8228 * The ast2firm pass has to know that left_type must be right_type
8229 * for the arithmetic operation and create a cast by itself */
8230 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8231 expression->right = create_implicit_cast(right, arithmetic_type);
8232 expression->base.type = type_left;
8233 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8234 check_pointer_arithmetic(&expression->base.source_position,
8235 type_left, orig_type_left);
8236 expression->base.type = type_left;
8237 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8238 errorf(&expression->base.source_position,
8239 "incompatible types '%T' and '%T' in assignment",
8240 orig_type_left, orig_type_right);
8244 static void semantic_integer_assign(binary_expression_t *expression)
8246 expression_t *left = expression->left;
8247 expression_t *right = expression->right;
8248 type_t *orig_type_left = left->base.type;
8249 type_t *orig_type_right = right->base.type;
8251 if (!is_valid_assignment_lhs(left))
8254 type_t *type_left = skip_typeref(orig_type_left);
8255 type_t *type_right = skip_typeref(orig_type_right);
8257 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8258 /* TODO: improve error message */
8259 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8260 errorf(&expression->base.source_position,
8261 "operation needs integer types");
8266 /* combined instructions are tricky. We can't create an implicit cast on
8267 * the left side, because we need the uncasted form for the store.
8268 * The ast2firm pass has to know that left_type must be right_type
8269 * for the arithmetic operation and create a cast by itself */
8270 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8271 expression->right = create_implicit_cast(right, arithmetic_type);
8272 expression->base.type = type_left;
8275 static void semantic_shift_assign(binary_expression_t *expression)
8277 expression_t *left = expression->left;
8279 if (!is_valid_assignment_lhs(left))
8282 if (!semantic_shift(expression))
8285 expression->base.type = skip_typeref(left->base.type);
8288 static void warn_logical_and_within_or(const expression_t *const expr)
8290 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8292 if (expr->base.parenthesized)
8294 source_position_t const *const pos = &expr->base.source_position;
8295 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8299 * Check the semantic restrictions of a logical expression.
8301 static void semantic_logical_op(binary_expression_t *expression)
8303 /* §6.5.13:2 Each of the operands shall have scalar type.
8304 * §6.5.14:2 Each of the operands shall have scalar type. */
8305 semantic_condition(expression->left, "left operand of logical operator");
8306 semantic_condition(expression->right, "right operand of logical operator");
8307 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8308 warn_logical_and_within_or(expression->left);
8309 warn_logical_and_within_or(expression->right);
8311 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8315 * Check the semantic restrictions of a binary assign expression.
8317 static void semantic_binexpr_assign(binary_expression_t *expression)
8319 expression_t *left = expression->left;
8320 type_t *orig_type_left = left->base.type;
8322 if (!is_valid_assignment_lhs(left))
8325 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8326 report_assign_error(error, orig_type_left, expression->right,
8327 "assignment", &left->base.source_position);
8328 expression->right = create_implicit_cast(expression->right, orig_type_left);
8329 expression->base.type = orig_type_left;
8333 * Determine if the outermost operation (or parts thereof) of the given
8334 * expression has no effect in order to generate a warning about this fact.
8335 * Therefore in some cases this only examines some of the operands of the
8336 * expression (see comments in the function and examples below).
8338 * f() + 23; // warning, because + has no effect
8339 * x || f(); // no warning, because x controls execution of f()
8340 * x ? y : f(); // warning, because y has no effect
8341 * (void)x; // no warning to be able to suppress the warning
8342 * This function can NOT be used for an "expression has definitely no effect"-
8344 static bool expression_has_effect(const expression_t *const expr)
8346 switch (expr->kind) {
8347 case EXPR_ERROR: return true; /* do NOT warn */
8348 case EXPR_REFERENCE: return false;
8349 case EXPR_ENUM_CONSTANT: return false;
8350 case EXPR_LABEL_ADDRESS: return false;
8352 /* suppress the warning for microsoft __noop operations */
8353 case EXPR_LITERAL_MS_NOOP: return true;
8354 case EXPR_LITERAL_BOOLEAN:
8355 case EXPR_LITERAL_CHARACTER:
8356 case EXPR_LITERAL_INTEGER:
8357 case EXPR_LITERAL_FLOATINGPOINT:
8358 case EXPR_STRING_LITERAL: return false;
8361 const call_expression_t *const call = &expr->call;
8362 if (call->function->kind != EXPR_REFERENCE)
8365 switch (call->function->reference.entity->function.btk) {
8366 /* FIXME: which builtins have no effect? */
8367 default: return true;
8371 /* Generate the warning if either the left or right hand side of a
8372 * conditional expression has no effect */
8373 case EXPR_CONDITIONAL: {
8374 conditional_expression_t const *const cond = &expr->conditional;
8375 expression_t const *const t = cond->true_expression;
8377 (t == NULL || expression_has_effect(t)) &&
8378 expression_has_effect(cond->false_expression);
8381 case EXPR_SELECT: return false;
8382 case EXPR_ARRAY_ACCESS: return false;
8383 case EXPR_SIZEOF: return false;
8384 case EXPR_CLASSIFY_TYPE: return false;
8385 case EXPR_ALIGNOF: return false;
8387 case EXPR_FUNCNAME: return false;
8388 case EXPR_BUILTIN_CONSTANT_P: return false;
8389 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8390 case EXPR_OFFSETOF: return false;
8391 case EXPR_VA_START: return true;
8392 case EXPR_VA_ARG: return true;
8393 case EXPR_VA_COPY: return true;
8394 case EXPR_STATEMENT: return true; // TODO
8395 case EXPR_COMPOUND_LITERAL: return false;
8397 case EXPR_UNARY_NEGATE: return false;
8398 case EXPR_UNARY_PLUS: return false;
8399 case EXPR_UNARY_BITWISE_NEGATE: return false;
8400 case EXPR_UNARY_NOT: return false;
8401 case EXPR_UNARY_DEREFERENCE: return false;
8402 case EXPR_UNARY_TAKE_ADDRESS: return false;
8403 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8404 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8405 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8406 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8408 /* Treat void casts as if they have an effect in order to being able to
8409 * suppress the warning */
8410 case EXPR_UNARY_CAST: {
8411 type_t *const type = skip_typeref(expr->base.type);
8412 return is_type_void(type);
8415 case EXPR_UNARY_ASSUME: return true;
8416 case EXPR_UNARY_DELETE: return true;
8417 case EXPR_UNARY_DELETE_ARRAY: return true;
8418 case EXPR_UNARY_THROW: return true;
8420 case EXPR_BINARY_ADD: return false;
8421 case EXPR_BINARY_SUB: return false;
8422 case EXPR_BINARY_MUL: return false;
8423 case EXPR_BINARY_DIV: return false;
8424 case EXPR_BINARY_MOD: return false;
8425 case EXPR_BINARY_EQUAL: return false;
8426 case EXPR_BINARY_NOTEQUAL: return false;
8427 case EXPR_BINARY_LESS: return false;
8428 case EXPR_BINARY_LESSEQUAL: return false;
8429 case EXPR_BINARY_GREATER: return false;
8430 case EXPR_BINARY_GREATEREQUAL: return false;
8431 case EXPR_BINARY_BITWISE_AND: return false;
8432 case EXPR_BINARY_BITWISE_OR: return false;
8433 case EXPR_BINARY_BITWISE_XOR: return false;
8434 case EXPR_BINARY_SHIFTLEFT: return false;
8435 case EXPR_BINARY_SHIFTRIGHT: return false;
8436 case EXPR_BINARY_ASSIGN: return true;
8437 case EXPR_BINARY_MUL_ASSIGN: return true;
8438 case EXPR_BINARY_DIV_ASSIGN: return true;
8439 case EXPR_BINARY_MOD_ASSIGN: return true;
8440 case EXPR_BINARY_ADD_ASSIGN: return true;
8441 case EXPR_BINARY_SUB_ASSIGN: return true;
8442 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8443 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8444 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8445 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8446 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8448 /* Only examine the right hand side of && and ||, because the left hand
8449 * side already has the effect of controlling the execution of the right
8451 case EXPR_BINARY_LOGICAL_AND:
8452 case EXPR_BINARY_LOGICAL_OR:
8453 /* Only examine the right hand side of a comma expression, because the left
8454 * hand side has a separate warning */
8455 case EXPR_BINARY_COMMA:
8456 return expression_has_effect(expr->binary.right);
8458 case EXPR_BINARY_ISGREATER: return false;
8459 case EXPR_BINARY_ISGREATEREQUAL: return false;
8460 case EXPR_BINARY_ISLESS: return false;
8461 case EXPR_BINARY_ISLESSEQUAL: return false;
8462 case EXPR_BINARY_ISLESSGREATER: return false;
8463 case EXPR_BINARY_ISUNORDERED: return false;
8466 internal_errorf(HERE, "unexpected expression");
8469 static void semantic_comma(binary_expression_t *expression)
8471 const expression_t *const left = expression->left;
8472 if (!expression_has_effect(left)) {
8473 source_position_t const *const pos = &left->base.source_position;
8474 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8476 expression->base.type = expression->right->base.type;
8480 * @param prec_r precedence of the right operand
8482 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8483 static expression_t *parse_##binexpression_type(expression_t *left) \
8485 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8486 binexpr->binary.left = left; \
8489 expression_t *right = parse_subexpression(prec_r); \
8491 binexpr->binary.right = right; \
8492 sfunc(&binexpr->binary); \
8497 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8498 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8499 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8500 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8501 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8502 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8503 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8504 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8505 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8506 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8507 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8508 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8509 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8510 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8511 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8512 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8513 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8514 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8515 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8516 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8517 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8518 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8519 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8520 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8521 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8522 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8523 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8524 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8525 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8526 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8529 static expression_t *parse_subexpression(precedence_t precedence)
8531 expression_parser_function_t *parser
8532 = &expression_parsers[token.kind];
8535 if (parser->parser != NULL) {
8536 left = parser->parser();
8538 left = parse_primary_expression();
8540 assert(left != NULL);
8543 parser = &expression_parsers[token.kind];
8544 if (parser->infix_parser == NULL)
8546 if (parser->infix_precedence < precedence)
8549 left = parser->infix_parser(left);
8551 assert(left != NULL);
8558 * Parse an expression.
8560 static expression_t *parse_expression(void)
8562 return parse_subexpression(PREC_EXPRESSION);
8566 * Register a parser for a prefix-like operator.
8568 * @param parser the parser function
8569 * @param token_kind the token type of the prefix token
8571 static void register_expression_parser(parse_expression_function parser,
8574 expression_parser_function_t *entry = &expression_parsers[token_kind];
8576 assert(!entry->parser);
8577 entry->parser = parser;
8581 * Register a parser for an infix operator with given precedence.
8583 * @param parser the parser function
8584 * @param token_kind the token type of the infix operator
8585 * @param precedence the precedence of the operator
8587 static void register_infix_parser(parse_expression_infix_function parser,
8588 int token_kind, precedence_t precedence)
8590 expression_parser_function_t *entry = &expression_parsers[token_kind];
8592 assert(!entry->infix_parser);
8593 entry->infix_parser = parser;
8594 entry->infix_precedence = precedence;
8598 * Initialize the expression parsers.
8600 static void init_expression_parsers(void)
8602 memset(&expression_parsers, 0, sizeof(expression_parsers));
8604 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8605 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8606 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8607 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8608 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8609 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8610 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8611 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8612 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8613 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8614 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8615 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8616 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8617 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8618 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8619 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8620 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8621 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8622 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8623 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8624 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8625 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8626 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8627 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8628 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8629 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8630 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8631 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8632 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8633 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8634 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8635 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8636 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8637 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8638 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8639 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8640 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8642 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8643 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8644 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8645 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8646 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8647 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8648 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8649 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8650 register_expression_parser(parse_sizeof, T_sizeof);
8651 register_expression_parser(parse_alignof, T___alignof__);
8652 register_expression_parser(parse_extension, T___extension__);
8653 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8654 register_expression_parser(parse_delete, T_delete);
8655 register_expression_parser(parse_throw, T_throw);
8659 * Parse a asm statement arguments specification.
8661 static asm_argument_t *parse_asm_arguments(bool is_out)
8663 asm_argument_t *result = NULL;
8664 asm_argument_t **anchor = &result;
8666 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8667 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8670 add_anchor_token(']');
8671 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8672 rem_anchor_token(']');
8674 if (!argument->symbol)
8678 argument->constraints = parse_string_literals("asm argument");
8679 add_anchor_token(')');
8681 expression_t *expression = parse_expression();
8682 rem_anchor_token(')');
8684 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8685 * change size or type representation (e.g. int -> long is ok, but
8686 * int -> float is not) */
8687 if (expression->kind == EXPR_UNARY_CAST) {
8688 type_t *const type = expression->base.type;
8689 type_kind_t const kind = type->kind;
8690 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8693 if (kind == TYPE_ATOMIC) {
8694 atomic_type_kind_t const akind = type->atomic.akind;
8695 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8696 size = get_atomic_type_size(akind);
8698 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8699 size = get_type_size(type_void_ptr);
8703 expression_t *const value = expression->unary.value;
8704 type_t *const value_type = value->base.type;
8705 type_kind_t const value_kind = value_type->kind;
8707 unsigned value_flags;
8708 unsigned value_size;
8709 if (value_kind == TYPE_ATOMIC) {
8710 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8711 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8712 value_size = get_atomic_type_size(value_akind);
8713 } else if (value_kind == TYPE_POINTER) {
8714 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8715 value_size = get_type_size(type_void_ptr);
8720 if (value_flags != flags || value_size != size)
8724 } while (expression->kind == EXPR_UNARY_CAST);
8728 if (!is_lvalue(expression)) {
8729 errorf(&expression->base.source_position,
8730 "asm output argument is not an lvalue");
8733 if (argument->constraints.begin[0] == '=')
8734 determine_lhs_ent(expression, NULL);
8736 mark_vars_read(expression, NULL);
8738 mark_vars_read(expression, NULL);
8740 argument->expression = expression;
8743 set_address_taken(expression, true);
8746 anchor = &argument->next;
8756 * Parse a asm statement clobber specification.
8758 static asm_clobber_t *parse_asm_clobbers(void)
8760 asm_clobber_t *result = NULL;
8761 asm_clobber_t **anchor = &result;
8763 while (token.kind == T_STRING_LITERAL) {
8764 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8765 clobber->clobber = parse_string_literals(NULL);
8768 anchor = &clobber->next;
8778 * Parse an asm statement.
8780 static statement_t *parse_asm_statement(void)
8782 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8783 asm_statement_t *asm_statement = &statement->asms;
8786 add_anchor_token(')');
8787 add_anchor_token(':');
8788 add_anchor_token(T_STRING_LITERAL);
8790 if (next_if(T_volatile))
8791 asm_statement->is_volatile = true;
8794 rem_anchor_token(T_STRING_LITERAL);
8795 asm_statement->asm_text = parse_string_literals("asm statement");
8798 asm_statement->outputs = parse_asm_arguments(true);
8801 asm_statement->inputs = parse_asm_arguments(false);
8803 rem_anchor_token(':');
8805 asm_statement->clobbers = parse_asm_clobbers();
8807 rem_anchor_token(')');
8811 if (asm_statement->outputs == NULL) {
8812 /* GCC: An 'asm' instruction without any output operands will be treated
8813 * identically to a volatile 'asm' instruction. */
8814 asm_statement->is_volatile = true;
8820 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8822 statement_t *inner_stmt;
8823 switch (token.kind) {
8825 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8826 inner_stmt = create_error_statement();
8830 if (label->kind == STATEMENT_LABEL) {
8831 /* Eat an empty statement here, to avoid the warning about an empty
8832 * statement after a label. label:; is commonly used to have a label
8833 * before a closing brace. */
8834 inner_stmt = create_empty_statement();
8841 inner_stmt = parse_statement();
8842 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8843 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8844 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8845 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8853 * Parse a case statement.
8855 static statement_t *parse_case_statement(void)
8857 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8858 source_position_t *const pos = &statement->base.source_position;
8861 add_anchor_token(':');
8863 expression_t *expression = parse_expression();
8864 type_t *expression_type = expression->base.type;
8865 type_t *skipped = skip_typeref(expression_type);
8866 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8867 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8868 expression, expression_type);
8871 type_t *type = expression_type;
8872 if (current_switch != NULL) {
8873 type_t *switch_type = current_switch->expression->base.type;
8874 if (is_type_valid(switch_type)) {
8875 expression = create_implicit_cast(expression, switch_type);
8879 statement->case_label.expression = expression;
8880 expression_classification_t const expr_class = is_constant_expression(expression);
8881 if (expr_class != EXPR_CLASS_CONSTANT) {
8882 if (expr_class != EXPR_CLASS_ERROR) {
8883 errorf(pos, "case label does not reduce to an integer constant");
8885 statement->case_label.is_bad = true;
8887 long const val = fold_constant_to_int(expression);
8888 statement->case_label.first_case = val;
8889 statement->case_label.last_case = val;
8893 if (next_if(T_DOTDOTDOT)) {
8894 expression_t *end_range = parse_expression();
8895 expression_type = expression->base.type;
8896 skipped = skip_typeref(expression_type);
8897 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8898 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8899 expression, expression_type);
8902 end_range = create_implicit_cast(end_range, type);
8903 statement->case_label.end_range = end_range;
8904 expression_classification_t const end_class = is_constant_expression(end_range);
8905 if (end_class != EXPR_CLASS_CONSTANT) {
8906 if (end_class != EXPR_CLASS_ERROR) {
8907 errorf(pos, "case range does not reduce to an integer constant");
8909 statement->case_label.is_bad = true;
8911 long const val = fold_constant_to_int(end_range);
8912 statement->case_label.last_case = val;
8914 if (val < statement->case_label.first_case) {
8915 statement->case_label.is_empty_range = true;
8916 warningf(WARN_OTHER, pos, "empty range specified");
8922 PUSH_PARENT(statement);
8924 rem_anchor_token(':');
8927 if (current_switch != NULL) {
8928 if (! statement->case_label.is_bad) {
8929 /* Check for duplicate case values */
8930 case_label_statement_t *c = &statement->case_label;
8931 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8932 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8935 if (c->last_case < l->first_case || c->first_case > l->last_case)
8938 errorf(pos, "duplicate case value (previously used %P)",
8939 &l->base.source_position);
8943 /* link all cases into the switch statement */
8944 if (current_switch->last_case == NULL) {
8945 current_switch->first_case = &statement->case_label;
8947 current_switch->last_case->next = &statement->case_label;
8949 current_switch->last_case = &statement->case_label;
8951 errorf(pos, "case label not within a switch statement");
8954 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
8961 * Parse a default statement.
8963 static statement_t *parse_default_statement(void)
8965 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8969 PUSH_PARENT(statement);
8973 if (current_switch != NULL) {
8974 const case_label_statement_t *def_label = current_switch->default_label;
8975 if (def_label != NULL) {
8976 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
8978 current_switch->default_label = &statement->case_label;
8980 /* link all cases into the switch statement */
8981 if (current_switch->last_case == NULL) {
8982 current_switch->first_case = &statement->case_label;
8984 current_switch->last_case->next = &statement->case_label;
8986 current_switch->last_case = &statement->case_label;
8989 errorf(&statement->base.source_position,
8990 "'default' label not within a switch statement");
8993 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9000 * Parse a label statement.
9002 static statement_t *parse_label_statement(void)
9004 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9005 label_t *const label = get_label(NULL /* Cannot fail, token is T_IDENTIFIER. */);
9006 statement->label.label = label;
9008 PUSH_PARENT(statement);
9010 /* if statement is already set then the label is defined twice,
9011 * otherwise it was just mentioned in a goto/local label declaration so far
9013 source_position_t const* const pos = &statement->base.source_position;
9014 if (label->statement != NULL) {
9015 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9017 label->base.source_position = *pos;
9018 label->statement = statement;
9023 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9024 parse_attributes(NULL); // TODO process attributes
9027 statement->label.statement = parse_label_inner_statement(statement, "label");
9029 /* remember the labels in a list for later checking */
9030 *label_anchor = &statement->label;
9031 label_anchor = &statement->label.next;
9037 static statement_t *parse_inner_statement(void)
9039 statement_t *const stmt = parse_statement();
9040 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9041 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9042 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9043 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9049 * Parse an expression in parentheses and mark its variables as read.
9051 static expression_t *parse_condition(void)
9053 add_anchor_token(')');
9055 expression_t *const expr = parse_expression();
9056 mark_vars_read(expr, NULL);
9057 rem_anchor_token(')');
9063 * Parse an if statement.
9065 static statement_t *parse_if(void)
9067 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9071 PUSH_PARENT(statement);
9072 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9074 add_anchor_token(T_else);
9076 expression_t *const expr = parse_condition();
9077 statement->ifs.condition = expr;
9078 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9080 semantic_condition(expr, "condition of 'if'-statment");
9082 statement_t *const true_stmt = parse_inner_statement();
9083 statement->ifs.true_statement = true_stmt;
9084 rem_anchor_token(T_else);
9086 if (true_stmt->kind == STATEMENT_EMPTY) {
9087 warningf(WARN_EMPTY_BODY, HERE,
9088 "suggest braces around empty body in an ‘if’ statement");
9091 if (next_if(T_else)) {
9092 statement->ifs.false_statement = parse_inner_statement();
9094 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9095 warningf(WARN_EMPTY_BODY, HERE,
9096 "suggest braces around empty body in an ‘if’ statement");
9098 } else if (true_stmt->kind == STATEMENT_IF &&
9099 true_stmt->ifs.false_statement != NULL) {
9100 source_position_t const *const pos = &true_stmt->base.source_position;
9101 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9110 * Check that all enums are handled in a switch.
9112 * @param statement the switch statement to check
9114 static void check_enum_cases(const switch_statement_t *statement)
9116 if (!is_warn_on(WARN_SWITCH_ENUM))
9118 const type_t *type = skip_typeref(statement->expression->base.type);
9119 if (! is_type_enum(type))
9121 const enum_type_t *enumt = &type->enumt;
9123 /* if we have a default, no warnings */
9124 if (statement->default_label != NULL)
9127 /* FIXME: calculation of value should be done while parsing */
9128 /* TODO: quadratic algorithm here. Change to an n log n one */
9129 long last_value = -1;
9130 const entity_t *entry = enumt->enume->base.next;
9131 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9132 entry = entry->base.next) {
9133 const expression_t *expression = entry->enum_value.value;
9134 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9136 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9137 if (l->expression == NULL)
9139 if (l->first_case <= value && value <= l->last_case) {
9145 source_position_t const *const pos = &statement->base.source_position;
9146 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9153 * Parse a switch statement.
9155 static statement_t *parse_switch(void)
9157 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9161 PUSH_PARENT(statement);
9162 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9164 expression_t *const expr = parse_condition();
9165 type_t * type = skip_typeref(expr->base.type);
9166 if (is_type_integer(type)) {
9167 type = promote_integer(type);
9168 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9169 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9171 } else if (is_type_valid(type)) {
9172 errorf(&expr->base.source_position,
9173 "switch quantity is not an integer, but '%T'", type);
9174 type = type_error_type;
9176 statement->switchs.expression = create_implicit_cast(expr, type);
9178 switch_statement_t *rem = current_switch;
9179 current_switch = &statement->switchs;
9180 statement->switchs.body = parse_inner_statement();
9181 current_switch = rem;
9183 if (statement->switchs.default_label == NULL) {
9184 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9186 check_enum_cases(&statement->switchs);
9193 static statement_t *parse_loop_body(statement_t *const loop)
9195 statement_t *const rem = current_loop;
9196 current_loop = loop;
9198 statement_t *const body = parse_inner_statement();
9205 * Parse a while statement.
9207 static statement_t *parse_while(void)
9209 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9213 PUSH_PARENT(statement);
9214 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9216 expression_t *const cond = parse_condition();
9217 statement->whiles.condition = cond;
9218 /* §6.8.5:2 The controlling expression of an iteration statement shall
9219 * have scalar type. */
9220 semantic_condition(cond, "condition of 'while'-statement");
9222 statement->whiles.body = parse_loop_body(statement);
9230 * Parse a do statement.
9232 static statement_t *parse_do(void)
9234 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9238 PUSH_PARENT(statement);
9239 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9241 add_anchor_token(T_while);
9242 statement->do_while.body = parse_loop_body(statement);
9243 rem_anchor_token(T_while);
9246 expression_t *const cond = parse_condition();
9247 statement->do_while.condition = cond;
9248 /* §6.8.5:2 The controlling expression of an iteration statement shall
9249 * have scalar type. */
9250 semantic_condition(cond, "condition of 'do-while'-statement");
9259 * Parse a for statement.
9261 static statement_t *parse_for(void)
9263 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9267 PUSH_PARENT(statement);
9268 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9270 add_anchor_token(')');
9276 } else if (is_declaration_specifier(&token)) {
9277 parse_declaration(record_entity, DECL_FLAGS_NONE);
9279 add_anchor_token(';');
9280 expression_t *const init = parse_expression();
9281 statement->fors.initialisation = init;
9282 mark_vars_read(init, ENT_ANY);
9283 if (!expression_has_effect(init)) {
9284 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9286 rem_anchor_token(';');
9292 if (token.kind != ';') {
9293 add_anchor_token(';');
9294 expression_t *const cond = parse_expression();
9295 statement->fors.condition = cond;
9296 /* §6.8.5:2 The controlling expression of an iteration statement
9297 * shall have scalar type. */
9298 semantic_condition(cond, "condition of 'for'-statement");
9299 mark_vars_read(cond, NULL);
9300 rem_anchor_token(';');
9303 if (token.kind != ')') {
9304 expression_t *const step = parse_expression();
9305 statement->fors.step = step;
9306 mark_vars_read(step, ENT_ANY);
9307 if (!expression_has_effect(step)) {
9308 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9311 rem_anchor_token(')');
9313 statement->fors.body = parse_loop_body(statement);
9321 * Parse a goto statement.
9323 static statement_t *parse_goto(void)
9325 statement_t *statement;
9326 if (GNU_MODE && look_ahead(1)->kind == '*') {
9327 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9331 expression_t *expression = parse_expression();
9332 mark_vars_read(expression, NULL);
9334 /* Argh: although documentation says the expression must be of type void*,
9335 * gcc accepts anything that can be casted into void* without error */
9336 type_t *type = expression->base.type;
9338 if (type != type_error_type) {
9339 if (!is_type_pointer(type) && !is_type_integer(type)) {
9340 errorf(&expression->base.source_position,
9341 "cannot convert to a pointer type");
9342 } else if (type != type_void_ptr) {
9343 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9345 expression = create_implicit_cast(expression, type_void_ptr);
9348 statement->computed_goto.expression = expression;
9350 statement = allocate_statement_zero(STATEMENT_GOTO);
9353 label_t *const label = get_label("while parsing goto");
9356 statement->gotos.label = label;
9358 /* remember the goto's in a list for later checking */
9359 *goto_anchor = &statement->gotos;
9360 goto_anchor = &statement->gotos.next;
9362 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9371 * Parse a continue statement.
9373 static statement_t *parse_continue(void)
9375 if (current_loop == NULL) {
9376 errorf(HERE, "continue statement not within loop");
9379 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9387 * Parse a break statement.
9389 static statement_t *parse_break(void)
9391 if (current_switch == NULL && current_loop == NULL) {
9392 errorf(HERE, "break statement not within loop or switch");
9395 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9403 * Parse a __leave statement.
9405 static statement_t *parse_leave_statement(void)
9407 if (current_try == NULL) {
9408 errorf(HERE, "__leave statement not within __try");
9411 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9419 * Check if a given entity represents a local variable.
9421 static bool is_local_variable(const entity_t *entity)
9423 if (entity->kind != ENTITY_VARIABLE)
9426 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9427 case STORAGE_CLASS_AUTO:
9428 case STORAGE_CLASS_REGISTER: {
9429 const type_t *type = skip_typeref(entity->declaration.type);
9430 if (is_type_function(type)) {
9442 * Check if a given expression represents a local variable.
9444 static bool expression_is_local_variable(const expression_t *expression)
9446 if (expression->base.kind != EXPR_REFERENCE) {
9449 const entity_t *entity = expression->reference.entity;
9450 return is_local_variable(entity);
9453 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9455 if (c_mode & _CXX || strict_mode) {
9458 warningf(WARN_OTHER, pos, msg);
9463 * Parse a return statement.
9465 static statement_t *parse_return(void)
9467 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9470 expression_t *return_value = NULL;
9471 if (token.kind != ';') {
9472 return_value = parse_expression();
9473 mark_vars_read(return_value, NULL);
9476 const type_t *const func_type = skip_typeref(current_function->base.type);
9477 assert(is_type_function(func_type));
9478 type_t *const return_type = skip_typeref(func_type->function.return_type);
9480 source_position_t const *const pos = &statement->base.source_position;
9481 if (return_value != NULL) {
9482 type_t *return_value_type = skip_typeref(return_value->base.type);
9484 if (is_type_void(return_type)) {
9485 if (!is_type_void(return_value_type)) {
9486 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9487 /* Only warn in C mode, because GCC does the same */
9488 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9489 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9490 /* Only warn in C mode, because GCC does the same */
9491 err_or_warn(pos, "'return' with expression in function returning 'void'");
9494 assign_error_t error = semantic_assign(return_type, return_value);
9495 report_assign_error(error, return_type, return_value, "'return'",
9498 return_value = create_implicit_cast(return_value, return_type);
9499 /* check for returning address of a local var */
9500 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9501 const expression_t *expression = return_value->unary.value;
9502 if (expression_is_local_variable(expression)) {
9503 warningf(WARN_OTHER, pos, "function returns address of local variable");
9506 } else if (!is_type_void(return_type)) {
9507 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9508 err_or_warn(pos, "'return' without value, in function returning non-void");
9510 statement->returns.value = return_value;
9517 * Parse a declaration statement.
9519 static statement_t *parse_declaration_statement(void)
9521 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9523 entity_t *before = current_scope->last_entity;
9525 parse_external_declaration();
9527 parse_declaration(record_entity, DECL_FLAGS_NONE);
9530 declaration_statement_t *const decl = &statement->declaration;
9531 entity_t *const begin =
9532 before != NULL ? before->base.next : current_scope->entities;
9533 decl->declarations_begin = begin;
9534 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9540 * Parse an expression statement, ie. expr ';'.
9542 static statement_t *parse_expression_statement(void)
9544 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9546 expression_t *const expr = parse_expression();
9547 statement->expression.expression = expr;
9548 mark_vars_read(expr, ENT_ANY);
9555 * Parse a microsoft __try { } __finally { } or
9556 * __try{ } __except() { }
9558 static statement_t *parse_ms_try_statment(void)
9560 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9563 PUSH_PARENT(statement);
9565 ms_try_statement_t *rem = current_try;
9566 current_try = &statement->ms_try;
9567 statement->ms_try.try_statement = parse_compound_statement(false);
9572 if (next_if(T___except)) {
9573 expression_t *const expr = parse_condition();
9574 type_t * type = skip_typeref(expr->base.type);
9575 if (is_type_integer(type)) {
9576 type = promote_integer(type);
9577 } else if (is_type_valid(type)) {
9578 errorf(&expr->base.source_position,
9579 "__expect expression is not an integer, but '%T'", type);
9580 type = type_error_type;
9582 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9583 } else if (!next_if(T__finally)) {
9584 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9586 statement->ms_try.final_statement = parse_compound_statement(false);
9590 static statement_t *parse_empty_statement(void)
9592 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9593 statement_t *const statement = create_empty_statement();
9598 static statement_t *parse_local_label_declaration(void)
9600 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9604 entity_t *begin = NULL;
9605 entity_t *end = NULL;
9606 entity_t **anchor = &begin;
9607 add_anchor_token(';');
9608 add_anchor_token(',');
9610 source_position_t pos;
9611 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9613 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9614 if (entity != NULL && entity->base.parent_scope == current_scope) {
9615 source_position_t const *const ppos = &entity->base.source_position;
9616 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9618 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9619 entity->base.parent_scope = current_scope;
9622 anchor = &entity->base.next;
9625 environment_push(entity);
9628 } while (next_if(','));
9629 rem_anchor_token(',');
9630 rem_anchor_token(';');
9632 statement->declaration.declarations_begin = begin;
9633 statement->declaration.declarations_end = end;
9637 static void parse_namespace_definition(void)
9641 entity_t *entity = NULL;
9642 symbol_t *symbol = NULL;
9644 if (token.kind == T_IDENTIFIER) {
9645 symbol = token.base.symbol;
9646 entity = get_entity(symbol, NAMESPACE_NORMAL);
9647 if (entity && entity->kind != ENTITY_NAMESPACE) {
9649 if (entity->base.parent_scope == current_scope && is_entity_valid(entity)) {
9650 error_redefined_as_different_kind(HERE, entity, ENTITY_NAMESPACE);
9656 if (entity == NULL) {
9657 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9658 entity->base.parent_scope = current_scope;
9661 if (token.kind == '=') {
9662 /* TODO: parse namespace alias */
9663 panic("namespace alias definition not supported yet");
9666 environment_push(entity);
9667 append_entity(current_scope, entity);
9669 PUSH_SCOPE(&entity->namespacee.members);
9670 PUSH_CURRENT_ENTITY(entity);
9672 add_anchor_token('}');
9675 rem_anchor_token('}');
9678 POP_CURRENT_ENTITY();
9683 * Parse a statement.
9684 * There's also parse_statement() which additionally checks for
9685 * "statement has no effect" warnings
9687 static statement_t *intern_parse_statement(void)
9689 /* declaration or statement */
9690 statement_t *statement;
9691 switch (token.kind) {
9692 case T_IDENTIFIER: {
9693 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9694 if (la1_type == ':') {
9695 statement = parse_label_statement();
9696 } else if (is_typedef_symbol(token.base.symbol)) {
9697 statement = parse_declaration_statement();
9699 /* it's an identifier, the grammar says this must be an
9700 * expression statement. However it is common that users mistype
9701 * declaration types, so we guess a bit here to improve robustness
9702 * for incorrect programs */
9706 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9708 statement = parse_expression_statement();
9712 statement = parse_declaration_statement();
9720 case T___extension__: {
9721 /* This can be a prefix to a declaration or an expression statement.
9722 * We simply eat it now and parse the rest with tail recursion. */
9724 statement = intern_parse_statement();
9730 statement = parse_declaration_statement();
9734 statement = parse_local_label_declaration();
9737 case ';': statement = parse_empty_statement(); break;
9738 case '{': statement = parse_compound_statement(false); break;
9739 case T___leave: statement = parse_leave_statement(); break;
9740 case T___try: statement = parse_ms_try_statment(); break;
9741 case T_asm: statement = parse_asm_statement(); break;
9742 case T_break: statement = parse_break(); break;
9743 case T_case: statement = parse_case_statement(); break;
9744 case T_continue: statement = parse_continue(); break;
9745 case T_default: statement = parse_default_statement(); break;
9746 case T_do: statement = parse_do(); break;
9747 case T_for: statement = parse_for(); break;
9748 case T_goto: statement = parse_goto(); break;
9749 case T_if: statement = parse_if(); break;
9750 case T_return: statement = parse_return(); break;
9751 case T_switch: statement = parse_switch(); break;
9752 case T_while: statement = parse_while(); break;
9755 statement = parse_expression_statement();
9759 errorf(HERE, "unexpected token %K while parsing statement", &token);
9760 statement = create_error_statement();
9769 * parse a statement and emits "statement has no effect" warning if needed
9770 * (This is really a wrapper around intern_parse_statement with check for 1
9771 * single warning. It is needed, because for statement expressions we have
9772 * to avoid the warning on the last statement)
9774 static statement_t *parse_statement(void)
9776 statement_t *statement = intern_parse_statement();
9778 if (statement->kind == STATEMENT_EXPRESSION) {
9779 expression_t *expression = statement->expression.expression;
9780 if (!expression_has_effect(expression)) {
9781 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9789 * Parse a compound statement.
9791 static statement_t *parse_compound_statement(bool inside_expression_statement)
9793 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9795 PUSH_PARENT(statement);
9796 PUSH_SCOPE(&statement->compound.scope);
9799 add_anchor_token('}');
9800 /* tokens, which can start a statement */
9801 /* TODO MS, __builtin_FOO */
9802 add_anchor_token('!');
9803 add_anchor_token('&');
9804 add_anchor_token('(');
9805 add_anchor_token('*');
9806 add_anchor_token('+');
9807 add_anchor_token('-');
9808 add_anchor_token(';');
9809 add_anchor_token('{');
9810 add_anchor_token('~');
9811 add_anchor_token(T_CHARACTER_CONSTANT);
9812 add_anchor_token(T_COLONCOLON);
9813 add_anchor_token(T_IDENTIFIER);
9814 add_anchor_token(T_MINUSMINUS);
9815 add_anchor_token(T_NUMBER);
9816 add_anchor_token(T_PLUSPLUS);
9817 add_anchor_token(T_STRING_LITERAL);
9818 add_anchor_token(T__Bool);
9819 add_anchor_token(T__Complex);
9820 add_anchor_token(T__Imaginary);
9821 add_anchor_token(T___PRETTY_FUNCTION__);
9822 add_anchor_token(T___alignof__);
9823 add_anchor_token(T___attribute__);
9824 add_anchor_token(T___builtin_va_start);
9825 add_anchor_token(T___extension__);
9826 add_anchor_token(T___func__);
9827 add_anchor_token(T___imag__);
9828 add_anchor_token(T___label__);
9829 add_anchor_token(T___real__);
9830 add_anchor_token(T___thread);
9831 add_anchor_token(T_asm);
9832 add_anchor_token(T_auto);
9833 add_anchor_token(T_bool);
9834 add_anchor_token(T_break);
9835 add_anchor_token(T_case);
9836 add_anchor_token(T_char);
9837 add_anchor_token(T_class);
9838 add_anchor_token(T_const);
9839 add_anchor_token(T_const_cast);
9840 add_anchor_token(T_continue);
9841 add_anchor_token(T_default);
9842 add_anchor_token(T_delete);
9843 add_anchor_token(T_double);
9844 add_anchor_token(T_do);
9845 add_anchor_token(T_dynamic_cast);
9846 add_anchor_token(T_enum);
9847 add_anchor_token(T_extern);
9848 add_anchor_token(T_false);
9849 add_anchor_token(T_float);
9850 add_anchor_token(T_for);
9851 add_anchor_token(T_goto);
9852 add_anchor_token(T_if);
9853 add_anchor_token(T_inline);
9854 add_anchor_token(T_int);
9855 add_anchor_token(T_long);
9856 add_anchor_token(T_new);
9857 add_anchor_token(T_operator);
9858 add_anchor_token(T_register);
9859 add_anchor_token(T_reinterpret_cast);
9860 add_anchor_token(T_restrict);
9861 add_anchor_token(T_return);
9862 add_anchor_token(T_short);
9863 add_anchor_token(T_signed);
9864 add_anchor_token(T_sizeof);
9865 add_anchor_token(T_static);
9866 add_anchor_token(T_static_cast);
9867 add_anchor_token(T_struct);
9868 add_anchor_token(T_switch);
9869 add_anchor_token(T_template);
9870 add_anchor_token(T_this);
9871 add_anchor_token(T_throw);
9872 add_anchor_token(T_true);
9873 add_anchor_token(T_try);
9874 add_anchor_token(T_typedef);
9875 add_anchor_token(T_typeid);
9876 add_anchor_token(T_typename);
9877 add_anchor_token(T_typeof);
9878 add_anchor_token(T_union);
9879 add_anchor_token(T_unsigned);
9880 add_anchor_token(T_using);
9881 add_anchor_token(T_void);
9882 add_anchor_token(T_volatile);
9883 add_anchor_token(T_wchar_t);
9884 add_anchor_token(T_while);
9886 statement_t **anchor = &statement->compound.statements;
9887 bool only_decls_so_far = true;
9888 while (token.kind != '}' && token.kind != T_EOF) {
9889 statement_t *sub_statement = intern_parse_statement();
9890 if (sub_statement->kind == STATEMENT_ERROR) {
9894 if (sub_statement->kind != STATEMENT_DECLARATION) {
9895 only_decls_so_far = false;
9896 } else if (!only_decls_so_far) {
9897 source_position_t const *const pos = &sub_statement->base.source_position;
9898 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
9901 *anchor = sub_statement;
9902 anchor = &sub_statement->base.next;
9906 /* look over all statements again to produce no effect warnings */
9907 if (is_warn_on(WARN_UNUSED_VALUE)) {
9908 statement_t *sub_statement = statement->compound.statements;
9909 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9910 if (sub_statement->kind != STATEMENT_EXPRESSION)
9912 /* don't emit a warning for the last expression in an expression
9913 * statement as it has always an effect */
9914 if (inside_expression_statement && sub_statement->base.next == NULL)
9917 expression_t *expression = sub_statement->expression.expression;
9918 if (!expression_has_effect(expression)) {
9919 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9924 rem_anchor_token(T_while);
9925 rem_anchor_token(T_wchar_t);
9926 rem_anchor_token(T_volatile);
9927 rem_anchor_token(T_void);
9928 rem_anchor_token(T_using);
9929 rem_anchor_token(T_unsigned);
9930 rem_anchor_token(T_union);
9931 rem_anchor_token(T_typeof);
9932 rem_anchor_token(T_typename);
9933 rem_anchor_token(T_typeid);
9934 rem_anchor_token(T_typedef);
9935 rem_anchor_token(T_try);
9936 rem_anchor_token(T_true);
9937 rem_anchor_token(T_throw);
9938 rem_anchor_token(T_this);
9939 rem_anchor_token(T_template);
9940 rem_anchor_token(T_switch);
9941 rem_anchor_token(T_struct);
9942 rem_anchor_token(T_static_cast);
9943 rem_anchor_token(T_static);
9944 rem_anchor_token(T_sizeof);
9945 rem_anchor_token(T_signed);
9946 rem_anchor_token(T_short);
9947 rem_anchor_token(T_return);
9948 rem_anchor_token(T_restrict);
9949 rem_anchor_token(T_reinterpret_cast);
9950 rem_anchor_token(T_register);
9951 rem_anchor_token(T_operator);
9952 rem_anchor_token(T_new);
9953 rem_anchor_token(T_long);
9954 rem_anchor_token(T_int);
9955 rem_anchor_token(T_inline);
9956 rem_anchor_token(T_if);
9957 rem_anchor_token(T_goto);
9958 rem_anchor_token(T_for);
9959 rem_anchor_token(T_float);
9960 rem_anchor_token(T_false);
9961 rem_anchor_token(T_extern);
9962 rem_anchor_token(T_enum);
9963 rem_anchor_token(T_dynamic_cast);
9964 rem_anchor_token(T_do);
9965 rem_anchor_token(T_double);
9966 rem_anchor_token(T_delete);
9967 rem_anchor_token(T_default);
9968 rem_anchor_token(T_continue);
9969 rem_anchor_token(T_const_cast);
9970 rem_anchor_token(T_const);
9971 rem_anchor_token(T_class);
9972 rem_anchor_token(T_char);
9973 rem_anchor_token(T_case);
9974 rem_anchor_token(T_break);
9975 rem_anchor_token(T_bool);
9976 rem_anchor_token(T_auto);
9977 rem_anchor_token(T_asm);
9978 rem_anchor_token(T___thread);
9979 rem_anchor_token(T___real__);
9980 rem_anchor_token(T___label__);
9981 rem_anchor_token(T___imag__);
9982 rem_anchor_token(T___func__);
9983 rem_anchor_token(T___extension__);
9984 rem_anchor_token(T___builtin_va_start);
9985 rem_anchor_token(T___attribute__);
9986 rem_anchor_token(T___alignof__);
9987 rem_anchor_token(T___PRETTY_FUNCTION__);
9988 rem_anchor_token(T__Imaginary);
9989 rem_anchor_token(T__Complex);
9990 rem_anchor_token(T__Bool);
9991 rem_anchor_token(T_STRING_LITERAL);
9992 rem_anchor_token(T_PLUSPLUS);
9993 rem_anchor_token(T_NUMBER);
9994 rem_anchor_token(T_MINUSMINUS);
9995 rem_anchor_token(T_IDENTIFIER);
9996 rem_anchor_token(T_COLONCOLON);
9997 rem_anchor_token(T_CHARACTER_CONSTANT);
9998 rem_anchor_token('~');
9999 rem_anchor_token('{');
10000 rem_anchor_token(';');
10001 rem_anchor_token('-');
10002 rem_anchor_token('+');
10003 rem_anchor_token('*');
10004 rem_anchor_token('(');
10005 rem_anchor_token('&');
10006 rem_anchor_token('!');
10007 rem_anchor_token('}');
10015 * Check for unused global static functions and variables
10017 static void check_unused_globals(void)
10019 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10022 for (const entity_t *entity = file_scope->entities; entity != NULL;
10023 entity = entity->base.next) {
10024 if (!is_declaration(entity))
10027 const declaration_t *declaration = &entity->declaration;
10028 if (declaration->used ||
10029 declaration->modifiers & DM_UNUSED ||
10030 declaration->modifiers & DM_USED ||
10031 declaration->storage_class != STORAGE_CLASS_STATIC)
10036 if (entity->kind == ENTITY_FUNCTION) {
10037 /* inhibit warning for static inline functions */
10038 if (entity->function.is_inline)
10041 why = WARN_UNUSED_FUNCTION;
10042 s = entity->function.statement != NULL ? "defined" : "declared";
10044 why = WARN_UNUSED_VARIABLE;
10048 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10052 static void parse_global_asm(void)
10054 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10057 add_anchor_token(';');
10058 add_anchor_token(')');
10059 add_anchor_token(T_STRING_LITERAL);
10062 rem_anchor_token(T_STRING_LITERAL);
10063 statement->asms.asm_text = parse_string_literals("global asm");
10064 statement->base.next = unit->global_asm;
10065 unit->global_asm = statement;
10067 rem_anchor_token(')');
10069 rem_anchor_token(';');
10073 static void parse_linkage_specification(void)
10077 source_position_t const pos = *HERE;
10078 char const *const linkage = parse_string_literals(NULL).begin;
10080 linkage_kind_t old_linkage = current_linkage;
10081 linkage_kind_t new_linkage;
10082 if (streq(linkage, "C")) {
10083 new_linkage = LINKAGE_C;
10084 } else if (streq(linkage, "C++")) {
10085 new_linkage = LINKAGE_CXX;
10087 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10088 new_linkage = LINKAGE_C;
10090 current_linkage = new_linkage;
10092 if (next_if('{')) {
10099 assert(current_linkage == new_linkage);
10100 current_linkage = old_linkage;
10103 static void parse_external(void)
10105 switch (token.kind) {
10107 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10108 parse_linkage_specification();
10110 DECLARATION_START_NO_EXTERN
10112 case T___extension__:
10113 /* tokens below are for implicit int */
10114 case '&': /* & x; -> int& x; (and error later, because C++ has no
10116 case '*': /* * x; -> int* x; */
10117 case '(': /* (x); -> int (x); */
10119 parse_external_declaration();
10125 parse_global_asm();
10129 parse_namespace_definition();
10133 if (!strict_mode) {
10134 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10141 errorf(HERE, "stray %K outside of function", &token);
10142 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10143 eat_until_matching_token(token.kind);
10149 static void parse_externals(void)
10151 add_anchor_token('}');
10152 add_anchor_token(T_EOF);
10155 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10156 unsigned short token_anchor_copy[T_LAST_TOKEN];
10157 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10160 while (token.kind != T_EOF && token.kind != '}') {
10162 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10163 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10165 /* the anchor set and its copy differs */
10166 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10169 if (in_gcc_extension) {
10170 /* an gcc extension scope was not closed */
10171 internal_errorf(HERE, "Leaked __extension__");
10178 rem_anchor_token(T_EOF);
10179 rem_anchor_token('}');
10183 * Parse a translation unit.
10185 static void parse_translation_unit(void)
10187 add_anchor_token(T_EOF);
10192 if (token.kind == T_EOF)
10195 errorf(HERE, "stray %K outside of function", &token);
10196 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10197 eat_until_matching_token(token.kind);
10202 void set_default_visibility(elf_visibility_tag_t visibility)
10204 default_visibility = visibility;
10210 * @return the translation unit or NULL if errors occurred.
10212 void start_parsing(void)
10214 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10215 label_stack = NEW_ARR_F(stack_entry_t, 0);
10219 print_to_file(stderr);
10221 assert(unit == NULL);
10222 unit = allocate_ast_zero(sizeof(unit[0]));
10224 assert(file_scope == NULL);
10225 file_scope = &unit->scope;
10227 assert(current_scope == NULL);
10228 scope_push(&unit->scope);
10230 create_gnu_builtins();
10232 create_microsoft_intrinsics();
10235 translation_unit_t *finish_parsing(void)
10237 assert(current_scope == &unit->scope);
10240 assert(file_scope == &unit->scope);
10241 check_unused_globals();
10244 DEL_ARR_F(environment_stack);
10245 DEL_ARR_F(label_stack);
10247 translation_unit_t *result = unit;
10252 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10253 * are given length one. */
10254 static void complete_incomplete_arrays(void)
10256 size_t n = ARR_LEN(incomplete_arrays);
10257 for (size_t i = 0; i != n; ++i) {
10258 declaration_t *const decl = incomplete_arrays[i];
10259 type_t *const type = skip_typeref(decl->type);
10261 if (!is_type_incomplete(type))
10264 source_position_t const *const pos = &decl->base.source_position;
10265 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10267 type_t *const new_type = duplicate_type(type);
10268 new_type->array.size_constant = true;
10269 new_type->array.has_implicit_size = true;
10270 new_type->array.size = 1;
10272 type_t *const result = identify_new_type(new_type);
10274 decl->type = result;
10278 static void prepare_main_collect2(entity_t *const entity)
10280 PUSH_SCOPE(&entity->function.statement->compound.scope);
10282 // create call to __main
10283 symbol_t *symbol = symbol_table_insert("__main");
10284 entity_t *subsubmain_ent
10285 = create_implicit_function(symbol, &builtin_source_position);
10287 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10288 type_t *ftype = subsubmain_ent->declaration.type;
10289 ref->base.source_position = builtin_source_position;
10290 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10291 ref->reference.entity = subsubmain_ent;
10293 expression_t *call = allocate_expression_zero(EXPR_CALL);
10294 call->base.source_position = builtin_source_position;
10295 call->base.type = type_void;
10296 call->call.function = ref;
10298 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10299 expr_statement->base.source_position = builtin_source_position;
10300 expr_statement->expression.expression = call;
10302 statement_t *statement = entity->function.statement;
10303 assert(statement->kind == STATEMENT_COMPOUND);
10304 compound_statement_t *compounds = &statement->compound;
10306 expr_statement->base.next = compounds->statements;
10307 compounds->statements = expr_statement;
10314 lookahead_bufpos = 0;
10315 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10318 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10319 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10320 parse_translation_unit();
10321 complete_incomplete_arrays();
10322 DEL_ARR_F(incomplete_arrays);
10323 incomplete_arrays = NULL;
10327 * Initialize the parser.
10329 void init_parser(void)
10331 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10333 init_expression_parsers();
10334 obstack_init(&temp_obst);
10338 * Terminate the parser.
10340 void exit_parser(void)
10342 obstack_free(&temp_obst, NULL);