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 "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
39 #include "walk_statements.h"
42 #include "adt/bitfiddle.h"
43 #include "adt/error.h"
44 #include "adt/array.h"
46 //#define PRINT_TOKENS
47 #define MAX_LOOKAHEAD 1
52 entity_namespace_t namespc;
55 typedef struct declaration_specifiers_t declaration_specifiers_t;
56 struct declaration_specifiers_t {
57 source_position_t source_position;
58 storage_class_t storage_class;
59 unsigned char alignment; /**< Alignment, 0 if not set. */
61 bool thread_local : 1; /**< GCC __thread */
62 attribute_t *attributes; /**< list of attributes */
67 * An environment for parsing initializers (and compound literals).
69 typedef struct parse_initializer_env_t {
70 type_t *type; /**< the type of the initializer. In case of an
71 array type with unspecified size this gets
72 adjusted to the actual size. */
73 entity_t *entity; /**< the variable that is initialized if any */
74 bool must_be_constant;
75 } parse_initializer_env_t;
77 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
79 /** The current token. */
81 /** The lookahead ring-buffer. */
82 static token_t lookahead_buffer[MAX_LOOKAHEAD];
83 /** Position of the next token in the lookahead buffer. */
84 static size_t lookahead_bufpos;
85 static stack_entry_t *environment_stack = NULL;
86 static stack_entry_t *label_stack = NULL;
87 static scope_t *file_scope = NULL;
88 static scope_t *current_scope = NULL;
89 /** Point to the current function declaration if inside a function. */
90 static function_t *current_function = NULL;
91 static entity_t *current_entity = NULL;
92 static entity_t *current_init_decl = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage = LINKAGE_INVALID;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in a type property context (evaluation only for type) */
105 static bool in_type_prop = false;
106 /** true if we are in an __extension__ context. */
107 static bool in_gcc_extension = false;
108 static struct obstack temp_obst;
109 static entity_t *anonymous_entity;
110 static declaration_t **incomplete_arrays;
113 #define PUSH_PARENT(stmt) \
114 statement_t *const prev_parent = current_parent; \
115 ((void)(current_parent = (stmt)))
116 #define POP_PARENT ((void)(current_parent = prev_parent))
118 /** special symbol used for anonymous entities. */
119 static symbol_t *sym_anonymous = NULL;
121 /** The token anchor set */
122 static unsigned char token_anchor_set[T_LAST_TOKEN];
124 /** The current source position. */
125 #define HERE (&token.source_position)
127 /** true if we are in GCC mode. */
128 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
130 static statement_t *parse_compound_statement(bool inside_expression_statement);
131 static statement_t *parse_statement(void);
133 static expression_t *parse_sub_expression(precedence_t);
134 static expression_t *parse_expression(void);
135 static type_t *parse_typename(void);
136 static void parse_externals(void);
137 static void parse_external(void);
139 static void parse_compound_type_entries(compound_t *compound_declaration);
141 static void check_call_argument(type_t *expected_type,
142 call_argument_t *argument, unsigned pos);
144 typedef enum declarator_flags_t {
146 DECL_MAY_BE_ABSTRACT = 1U << 0,
147 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
148 DECL_IS_PARAMETER = 1U << 2
149 } declarator_flags_t;
151 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
152 declarator_flags_t flags);
154 static void semantic_comparison(binary_expression_t *expression);
156 #define STORAGE_CLASSES \
157 STORAGE_CLASSES_NO_EXTERN \
160 #define STORAGE_CLASSES_NO_EXTERN \
167 #define TYPE_QUALIFIERS \
172 case T__forceinline: \
173 case T___attribute__:
175 #define COMPLEX_SPECIFIERS \
177 #define IMAGINARY_SPECIFIERS \
180 #define TYPE_SPECIFIERS \
182 case T___builtin_va_list: \
207 #define DECLARATION_START \
212 #define DECLARATION_START_NO_EXTERN \
213 STORAGE_CLASSES_NO_EXTERN \
217 #define TYPENAME_START \
221 #define EXPRESSION_START \
230 case T_CHARACTER_CONSTANT: \
231 case T_FLOATINGPOINT: \
235 case T_STRING_LITERAL: \
236 case T_WIDE_CHARACTER_CONSTANT: \
237 case T_WIDE_STRING_LITERAL: \
238 case T___FUNCDNAME__: \
239 case T___FUNCSIG__: \
240 case T___FUNCTION__: \
241 case T___PRETTY_FUNCTION__: \
242 case T___alignof__: \
243 case T___builtin_classify_type: \
244 case T___builtin_constant_p: \
245 case T___builtin_isgreater: \
246 case T___builtin_isgreaterequal: \
247 case T___builtin_isless: \
248 case T___builtin_islessequal: \
249 case T___builtin_islessgreater: \
250 case T___builtin_isunordered: \
251 case T___builtin_offsetof: \
252 case T___builtin_va_arg: \
253 case T___builtin_va_start: \
254 case T___builtin_va_copy: \
265 * Returns the size of a statement node.
267 * @param kind the statement kind
269 static size_t get_statement_struct_size(statement_kind_t kind)
271 static const size_t sizes[] = {
272 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
273 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
274 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
275 [STATEMENT_RETURN] = sizeof(return_statement_t),
276 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
277 [STATEMENT_IF] = sizeof(if_statement_t),
278 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
279 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
280 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
281 [STATEMENT_BREAK] = sizeof(statement_base_t),
282 [STATEMENT_GOTO] = sizeof(goto_statement_t),
283 [STATEMENT_LABEL] = sizeof(label_statement_t),
284 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
285 [STATEMENT_WHILE] = sizeof(while_statement_t),
286 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
287 [STATEMENT_FOR] = sizeof(for_statement_t),
288 [STATEMENT_ASM] = sizeof(asm_statement_t),
289 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
290 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
292 assert(kind < lengthof(sizes));
293 assert(sizes[kind] != 0);
298 * Returns the size of an expression node.
300 * @param kind the expression kind
302 static size_t get_expression_struct_size(expression_kind_t kind)
304 static const size_t sizes[] = {
305 [EXPR_INVALID] = sizeof(expression_base_t),
306 [EXPR_REFERENCE] = sizeof(reference_expression_t),
307 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
308 [EXPR_CONST] = sizeof(const_expression_t),
309 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
310 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
311 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
312 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
313 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
314 [EXPR_CALL] = sizeof(call_expression_t),
315 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
316 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
317 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
318 [EXPR_SELECT] = sizeof(select_expression_t),
319 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
320 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
321 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
322 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
323 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
324 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
325 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
326 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
327 [EXPR_VA_START] = sizeof(va_start_expression_t),
328 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
329 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
330 [EXPR_STATEMENT] = sizeof(statement_expression_t),
331 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
333 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
334 return sizes[EXPR_UNARY_FIRST];
336 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
337 return sizes[EXPR_BINARY_FIRST];
339 assert(kind < lengthof(sizes));
340 assert(sizes[kind] != 0);
345 * Allocate a statement node of given kind and initialize all
346 * fields with zero. Sets its source position to the position
347 * of the current token.
349 static statement_t *allocate_statement_zero(statement_kind_t kind)
351 size_t size = get_statement_struct_size(kind);
352 statement_t *res = allocate_ast_zero(size);
354 res->base.kind = kind;
355 res->base.parent = current_parent;
356 res->base.source_position = token.source_position;
361 * Allocate an expression node of given kind and initialize all
364 * @param kind the kind of the expression to allocate
366 static expression_t *allocate_expression_zero(expression_kind_t kind)
368 size_t size = get_expression_struct_size(kind);
369 expression_t *res = allocate_ast_zero(size);
371 res->base.kind = kind;
372 res->base.type = type_error_type;
373 res->base.source_position = token.source_position;
378 * Creates a new invalid expression at the source position
379 * of the current token.
381 static expression_t *create_invalid_expression(void)
383 return allocate_expression_zero(EXPR_INVALID);
387 * Creates a new invalid statement.
389 static statement_t *create_invalid_statement(void)
391 return allocate_statement_zero(STATEMENT_INVALID);
395 * Allocate a new empty statement.
397 static statement_t *create_empty_statement(void)
399 return allocate_statement_zero(STATEMENT_EMPTY);
402 static function_parameter_t *allocate_parameter(type_t *const type)
404 function_parameter_t *const param
405 = obstack_alloc(type_obst, sizeof(*param));
406 memset(param, 0, sizeof(*param));
412 * Returns the size of an initializer node.
414 * @param kind the initializer kind
416 static size_t get_initializer_size(initializer_kind_t kind)
418 static const size_t sizes[] = {
419 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
420 [INITIALIZER_STRING] = sizeof(initializer_string_t),
421 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
422 [INITIALIZER_LIST] = sizeof(initializer_list_t),
423 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
425 assert(kind < lengthof(sizes));
426 assert(sizes[kind] != 0);
431 * Allocate an initializer node of given kind and initialize all
434 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
436 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
443 * Returns the index of the top element of the environment stack.
445 static size_t environment_top(void)
447 return ARR_LEN(environment_stack);
451 * Returns the index of the top element of the global label stack.
453 static size_t label_top(void)
455 return ARR_LEN(label_stack);
459 * Return the next token.
461 static inline void next_token(void)
463 token = lookahead_buffer[lookahead_bufpos];
464 lookahead_buffer[lookahead_bufpos] = lexer_token;
467 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
470 print_token(stderr, &token);
471 fprintf(stderr, "\n");
475 static inline bool next_if(int const type)
477 if (token.type == type) {
486 * Return the next token with a given lookahead.
488 static inline const token_t *look_ahead(size_t num)
490 assert(0 < num && num <= MAX_LOOKAHEAD);
491 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
492 return &lookahead_buffer[pos];
496 * Adds a token type to the token type anchor set (a multi-set).
498 static void add_anchor_token(int token_type)
500 assert(0 <= token_type && token_type < T_LAST_TOKEN);
501 ++token_anchor_set[token_type];
505 * Set the number of tokens types of the given type
506 * to zero and return the old count.
508 static int save_and_reset_anchor_state(int token_type)
510 assert(0 <= token_type && token_type < T_LAST_TOKEN);
511 int count = token_anchor_set[token_type];
512 token_anchor_set[token_type] = 0;
517 * Restore the number of token types to the given count.
519 static void restore_anchor_state(int token_type, int count)
521 assert(0 <= token_type && token_type < T_LAST_TOKEN);
522 token_anchor_set[token_type] = count;
526 * Remove a token type from the token type anchor set (a multi-set).
528 static void rem_anchor_token(int token_type)
530 assert(0 <= token_type && token_type < T_LAST_TOKEN);
531 assert(token_anchor_set[token_type] != 0);
532 --token_anchor_set[token_type];
536 * Return true if the token type of the current token is
539 static bool at_anchor(void)
543 return token_anchor_set[token.type];
547 * Eat tokens until a matching token type is found.
549 static void eat_until_matching_token(int type)
553 case '(': end_token = ')'; break;
554 case '{': end_token = '}'; break;
555 case '[': end_token = ']'; break;
556 default: end_token = type; break;
559 unsigned parenthesis_count = 0;
560 unsigned brace_count = 0;
561 unsigned bracket_count = 0;
562 while (token.type != end_token ||
563 parenthesis_count != 0 ||
565 bracket_count != 0) {
566 switch (token.type) {
568 case '(': ++parenthesis_count; break;
569 case '{': ++brace_count; break;
570 case '[': ++bracket_count; break;
573 if (parenthesis_count > 0)
583 if (bracket_count > 0)
586 if (token.type == end_token &&
587 parenthesis_count == 0 &&
601 * Eat input tokens until an anchor is found.
603 static void eat_until_anchor(void)
605 while (token_anchor_set[token.type] == 0) {
606 if (token.type == '(' || token.type == '{' || token.type == '[')
607 eat_until_matching_token(token.type);
613 * Eat a whole block from input tokens.
615 static void eat_block(void)
617 eat_until_matching_token('{');
621 #define eat(token_type) (assert(token.type == (token_type)), next_token())
624 * Report a parse error because an expected token was not found.
627 #if defined __GNUC__ && __GNUC__ >= 4
628 __attribute__((sentinel))
630 void parse_error_expected(const char *message, ...)
632 if (message != NULL) {
633 errorf(HERE, "%s", message);
636 va_start(ap, message);
637 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
642 * Report an incompatible type.
644 static void type_error_incompatible(const char *msg,
645 const source_position_t *source_position, type_t *type1, type_t *type2)
647 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
652 * Expect the current token is the expected token.
653 * If not, generate an error, eat the current statement,
654 * and goto the end_error label.
656 #define expect(expected, error_label) \
658 if (UNLIKELY(token.type != (expected))) { \
659 parse_error_expected(NULL, (expected), NULL); \
660 add_anchor_token(expected); \
661 eat_until_anchor(); \
662 next_if((expected)); \
663 rem_anchor_token(expected); \
670 * Push a given scope on the scope stack and make it the
673 static scope_t *scope_push(scope_t *new_scope)
675 if (current_scope != NULL) {
676 new_scope->depth = current_scope->depth + 1;
679 scope_t *old_scope = current_scope;
680 current_scope = new_scope;
685 * Pop the current scope from the scope stack.
687 static void scope_pop(scope_t *old_scope)
689 current_scope = old_scope;
693 * Search an entity by its symbol in a given namespace.
695 static entity_t *get_entity(const symbol_t *const symbol,
696 namespace_tag_t namespc)
698 entity_t *entity = symbol->entity;
699 for (; entity != NULL; entity = entity->base.symbol_next) {
700 if (entity->base.namespc == namespc)
707 /* §6.2.3:1 24) There is only one name space for tags even though three are
709 static entity_t *get_tag(symbol_t const *const symbol,
710 entity_kind_tag_t const kind)
712 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
713 if (entity != NULL && entity->kind != kind) {
715 "'%Y' defined as wrong kind of tag (previous definition %P)",
716 symbol, &entity->base.source_position);
723 * pushs an entity on the environment stack and links the corresponding symbol
726 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
728 symbol_t *symbol = entity->base.symbol;
729 entity_namespace_t namespc = entity->base.namespc;
730 assert(namespc != NAMESPACE_INVALID);
732 /* replace/add entity into entity list of the symbol */
735 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
740 /* replace an entry? */
741 if (iter->base.namespc == namespc) {
742 entity->base.symbol_next = iter->base.symbol_next;
748 /* remember old declaration */
750 entry.symbol = symbol;
751 entry.old_entity = iter;
752 entry.namespc = namespc;
753 ARR_APP1(stack_entry_t, *stack_ptr, entry);
757 * Push an entity on the environment stack.
759 static void environment_push(entity_t *entity)
761 assert(entity->base.source_position.input_name != NULL);
762 assert(entity->base.parent_scope != NULL);
763 stack_push(&environment_stack, entity);
767 * Push a declaration on the global label stack.
769 * @param declaration the declaration
771 static void label_push(entity_t *label)
773 /* we abuse the parameters scope as parent for the labels */
774 label->base.parent_scope = ¤t_function->parameters;
775 stack_push(&label_stack, label);
779 * pops symbols from the environment stack until @p new_top is the top element
781 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
783 stack_entry_t *stack = *stack_ptr;
784 size_t top = ARR_LEN(stack);
787 assert(new_top <= top);
791 for (i = top; i > new_top; --i) {
792 stack_entry_t *entry = &stack[i - 1];
794 entity_t *old_entity = entry->old_entity;
795 symbol_t *symbol = entry->symbol;
796 entity_namespace_t namespc = entry->namespc;
798 /* replace with old_entity/remove */
801 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
803 assert(iter != NULL);
804 /* replace an entry? */
805 if (iter->base.namespc == namespc)
809 /* restore definition from outer scopes (if there was one) */
810 if (old_entity != NULL) {
811 old_entity->base.symbol_next = iter->base.symbol_next;
812 *anchor = old_entity;
814 /* remove entry from list */
815 *anchor = iter->base.symbol_next;
819 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
823 * Pop all entries from the environment stack until the new_top
826 * @param new_top the new stack top
828 static void environment_pop_to(size_t new_top)
830 stack_pop_to(&environment_stack, new_top);
834 * Pop all entries from the global label stack until the new_top
837 * @param new_top the new stack top
839 static void label_pop_to(size_t new_top)
841 stack_pop_to(&label_stack, new_top);
844 static int get_akind_rank(atomic_type_kind_t akind)
850 * Return the type rank for an atomic type.
852 static int get_rank(const type_t *type)
854 assert(!is_typeref(type));
855 if (type->kind == TYPE_ENUM)
856 return get_akind_rank(type->enumt.akind);
858 assert(type->kind == TYPE_ATOMIC);
859 return get_akind_rank(type->atomic.akind);
863 * §6.3.1.1:2 Do integer promotion for a given type.
865 * @param type the type to promote
866 * @return the promoted type
868 static type_t *promote_integer(type_t *type)
870 if (type->kind == TYPE_BITFIELD)
871 type = type->bitfield.base_type;
873 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
880 * Create a cast expression.
882 * @param expression the expression to cast
883 * @param dest_type the destination type
885 static expression_t *create_cast_expression(expression_t *expression,
888 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
890 cast->unary.value = expression;
891 cast->base.type = dest_type;
897 * Check if a given expression represents a null pointer constant.
899 * @param expression the expression to check
901 static bool is_null_pointer_constant(const expression_t *expression)
903 /* skip void* cast */
904 if (expression->kind == EXPR_UNARY_CAST ||
905 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
906 type_t *const type = skip_typeref(expression->base.type);
907 if (types_compatible(type, type_void_ptr))
908 expression = expression->unary.value;
911 type_t *const type = skip_typeref(expression->base.type);
913 is_type_integer(type) &&
914 is_constant_expression(expression) &&
915 !fold_constant_to_bool(expression);
919 * Create an implicit cast expression.
921 * @param expression the expression to cast
922 * @param dest_type the destination type
924 static expression_t *create_implicit_cast(expression_t *expression,
927 type_t *const source_type = expression->base.type;
929 if (source_type == dest_type)
932 return create_cast_expression(expression, dest_type);
935 typedef enum assign_error_t {
937 ASSIGN_ERROR_INCOMPATIBLE,
938 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
939 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
940 ASSIGN_WARNING_POINTER_FROM_INT,
941 ASSIGN_WARNING_INT_FROM_POINTER
944 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
945 const expression_t *const right,
947 const source_position_t *source_position)
949 type_t *const orig_type_right = right->base.type;
950 type_t *const type_left = skip_typeref(orig_type_left);
951 type_t *const type_right = skip_typeref(orig_type_right);
956 case ASSIGN_ERROR_INCOMPATIBLE:
957 errorf(source_position,
958 "destination type '%T' in %s is incompatible with type '%T'",
959 orig_type_left, context, orig_type_right);
962 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
964 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
965 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
967 /* the left type has all qualifiers from the right type */
968 unsigned missing_qualifiers
969 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
970 warningf(source_position,
971 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
972 orig_type_left, context, orig_type_right, missing_qualifiers);
977 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
979 warningf(source_position,
980 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
981 orig_type_left, context, right, orig_type_right);
985 case ASSIGN_WARNING_POINTER_FROM_INT:
987 warningf(source_position,
988 "%s makes pointer '%T' from integer '%T' without a cast",
989 context, orig_type_left, orig_type_right);
993 case ASSIGN_WARNING_INT_FROM_POINTER:
995 warningf(source_position,
996 "%s makes integer '%T' from pointer '%T' without a cast",
997 context, orig_type_left, orig_type_right);
1002 panic("invalid error value");
1006 /** Implements the rules from §6.5.16.1 */
1007 static assign_error_t semantic_assign(type_t *orig_type_left,
1008 const expression_t *const right)
1010 type_t *const orig_type_right = right->base.type;
1011 type_t *const type_left = skip_typeref(orig_type_left);
1012 type_t *const type_right = skip_typeref(orig_type_right);
1014 if (is_type_pointer(type_left)) {
1015 if (is_null_pointer_constant(right)) {
1016 return ASSIGN_SUCCESS;
1017 } else if (is_type_pointer(type_right)) {
1018 type_t *points_to_left
1019 = skip_typeref(type_left->pointer.points_to);
1020 type_t *points_to_right
1021 = skip_typeref(type_right->pointer.points_to);
1022 assign_error_t res = ASSIGN_SUCCESS;
1024 /* the left type has all qualifiers from the right type */
1025 unsigned missing_qualifiers
1026 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1027 if (missing_qualifiers != 0) {
1028 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1031 points_to_left = get_unqualified_type(points_to_left);
1032 points_to_right = get_unqualified_type(points_to_right);
1034 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1037 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1038 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1039 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1042 if (!types_compatible(points_to_left, points_to_right)) {
1043 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1047 } else if (is_type_integer(type_right)) {
1048 return ASSIGN_WARNING_POINTER_FROM_INT;
1050 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1051 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1052 && is_type_pointer(type_right))) {
1053 return ASSIGN_SUCCESS;
1054 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1055 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1056 type_t *const unqual_type_left = get_unqualified_type(type_left);
1057 type_t *const unqual_type_right = get_unqualified_type(type_right);
1058 if (types_compatible(unqual_type_left, unqual_type_right)) {
1059 return ASSIGN_SUCCESS;
1061 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1062 return ASSIGN_WARNING_INT_FROM_POINTER;
1065 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1066 return ASSIGN_SUCCESS;
1068 return ASSIGN_ERROR_INCOMPATIBLE;
1071 static expression_t *parse_constant_expression(void)
1073 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1075 if (!is_constant_expression(result)) {
1076 errorf(&result->base.source_position,
1077 "expression '%E' is not constant", result);
1083 static expression_t *parse_assignment_expression(void)
1085 return parse_sub_expression(PREC_ASSIGNMENT);
1088 static string_t parse_string_literals(void)
1090 assert(token.type == T_STRING_LITERAL);
1091 string_t result = token.v.string;
1095 while (token.type == T_STRING_LITERAL) {
1096 result = concat_strings(&result, &token.v.string);
1104 * compare two string, ignoring double underscores on the second.
1106 static int strcmp_underscore(const char *s1, const char *s2)
1108 if (s2[0] == '_' && s2[1] == '_') {
1109 size_t len2 = strlen(s2);
1110 size_t len1 = strlen(s1);
1111 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1112 return strncmp(s1, s2+2, len2-4);
1116 return strcmp(s1, s2);
1119 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1121 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1122 attribute->kind = kind;
1127 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1130 * __attribute__ ( ( attribute-list ) )
1134 * attribute_list , attrib
1139 * any-word ( identifier )
1140 * any-word ( identifier , nonempty-expr-list )
1141 * any-word ( expr-list )
1143 * where the "identifier" must not be declared as a type, and
1144 * "any-word" may be any identifier (including one declared as a
1145 * type), a reserved word storage class specifier, type specifier or
1146 * type qualifier. ??? This still leaves out most reserved keywords
1147 * (following the old parser), shouldn't we include them, and why not
1148 * allow identifiers declared as types to start the arguments?
1150 * Matze: this all looks confusing and little systematic, so we're even less
1151 * strict and parse any list of things which are identifiers or
1152 * (assignment-)expressions.
1154 static attribute_argument_t *parse_attribute_arguments(void)
1156 attribute_argument_t *first = NULL;
1157 attribute_argument_t **anchor = &first;
1158 if (token.type != ')') do {
1159 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1161 /* is it an identifier */
1162 if (token.type == T_IDENTIFIER
1163 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1164 symbol_t *symbol = token.v.symbol;
1165 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1166 argument->v.symbol = symbol;
1169 /* must be an expression */
1170 expression_t *expression = parse_assignment_expression();
1172 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1173 argument->v.expression = expression;
1176 /* append argument */
1178 anchor = &argument->next;
1179 } while (next_if(','));
1180 expect(')', end_error);
1189 static attribute_t *parse_attribute_asm(void)
1193 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1195 expect('(', end_error);
1196 attribute->a.arguments = parse_attribute_arguments();
1203 static symbol_t *get_symbol_from_token(void)
1205 switch(token.type) {
1207 return token.v.symbol;
1236 /* maybe we need more tokens ... add them on demand */
1237 return get_token_symbol(&token);
1243 static attribute_t *parse_attribute_gnu_single(void)
1245 /* parse "any-word" */
1246 symbol_t *symbol = get_symbol_from_token();
1247 if (symbol == NULL) {
1248 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1252 const char *name = symbol->string;
1255 attribute_kind_t kind;
1256 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1257 const char *attribute_name = get_attribute_name(kind);
1258 if (attribute_name != NULL
1259 && strcmp_underscore(attribute_name, name) == 0)
1263 if (kind >= ATTRIBUTE_GNU_LAST) {
1264 if (warning.attribute) {
1265 warningf(HERE, "unknown attribute '%s' ignored", name);
1267 /* TODO: we should still save the attribute in the list... */
1268 kind = ATTRIBUTE_UNKNOWN;
1271 attribute_t *attribute = allocate_attribute_zero(kind);
1273 /* parse arguments */
1275 attribute->a.arguments = parse_attribute_arguments();
1283 static attribute_t *parse_attribute_gnu(void)
1285 attribute_t *first = NULL;
1286 attribute_t **anchor = &first;
1288 eat(T___attribute__);
1289 expect('(', end_error);
1290 expect('(', end_error);
1292 if (token.type != ')') do {
1293 attribute_t *attribute = parse_attribute_gnu_single();
1294 if (attribute == NULL)
1297 *anchor = attribute;
1298 anchor = &attribute->next;
1299 } while (next_if(','));
1300 expect(')', end_error);
1301 expect(')', end_error);
1307 /** Parse attributes. */
1308 static attribute_t *parse_attributes(attribute_t *first)
1310 attribute_t **anchor = &first;
1312 while (*anchor != NULL)
1313 anchor = &(*anchor)->next;
1315 attribute_t *attribute;
1316 switch (token.type) {
1317 case T___attribute__:
1318 attribute = parse_attribute_gnu();
1322 attribute = parse_attribute_asm();
1327 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1332 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1335 case T__forceinline:
1337 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1342 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1347 /* TODO record modifier */
1349 warningf(HERE, "Ignoring declaration modifier %K", &token);
1350 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1357 *anchor = attribute;
1358 anchor = &attribute->next;
1362 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1364 static entity_t *determine_lhs_ent(expression_t *const expr,
1367 switch (expr->kind) {
1368 case EXPR_REFERENCE: {
1369 entity_t *const entity = expr->reference.entity;
1370 /* we should only find variables as lvalues... */
1371 if (entity->base.kind != ENTITY_VARIABLE
1372 && entity->base.kind != ENTITY_PARAMETER)
1378 case EXPR_ARRAY_ACCESS: {
1379 expression_t *const ref = expr->array_access.array_ref;
1380 entity_t * ent = NULL;
1381 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1382 ent = determine_lhs_ent(ref, lhs_ent);
1385 mark_vars_read(expr->select.compound, lhs_ent);
1387 mark_vars_read(expr->array_access.index, lhs_ent);
1392 if (is_type_compound(skip_typeref(expr->base.type))) {
1393 return determine_lhs_ent(expr->select.compound, lhs_ent);
1395 mark_vars_read(expr->select.compound, lhs_ent);
1400 case EXPR_UNARY_DEREFERENCE: {
1401 expression_t *const val = expr->unary.value;
1402 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1404 return determine_lhs_ent(val->unary.value, lhs_ent);
1406 mark_vars_read(val, NULL);
1412 mark_vars_read(expr, NULL);
1417 #define ENT_ANY ((entity_t*)-1)
1420 * Mark declarations, which are read. This is used to detect variables, which
1424 * x is not marked as "read", because it is only read to calculate its own new
1428 * x and y are not detected as "not read", because multiple variables are
1431 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1433 switch (expr->kind) {
1434 case EXPR_REFERENCE: {
1435 entity_t *const entity = expr->reference.entity;
1436 if (entity->kind != ENTITY_VARIABLE
1437 && entity->kind != ENTITY_PARAMETER)
1440 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1441 if (entity->kind == ENTITY_VARIABLE) {
1442 entity->variable.read = true;
1444 entity->parameter.read = true;
1451 // TODO respect pure/const
1452 mark_vars_read(expr->call.function, NULL);
1453 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1454 mark_vars_read(arg->expression, NULL);
1458 case EXPR_CONDITIONAL:
1459 // TODO lhs_decl should depend on whether true/false have an effect
1460 mark_vars_read(expr->conditional.condition, NULL);
1461 if (expr->conditional.true_expression != NULL)
1462 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1463 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1467 if (lhs_ent == ENT_ANY
1468 && !is_type_compound(skip_typeref(expr->base.type)))
1470 mark_vars_read(expr->select.compound, lhs_ent);
1473 case EXPR_ARRAY_ACCESS: {
1474 expression_t *const ref = expr->array_access.array_ref;
1475 mark_vars_read(ref, lhs_ent);
1476 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1477 mark_vars_read(expr->array_access.index, lhs_ent);
1482 mark_vars_read(expr->va_arge.ap, lhs_ent);
1486 mark_vars_read(expr->va_copye.src, lhs_ent);
1489 case EXPR_UNARY_CAST:
1490 /* Special case: Use void cast to mark a variable as "read" */
1491 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1496 case EXPR_UNARY_THROW:
1497 if (expr->unary.value == NULL)
1500 case EXPR_UNARY_DEREFERENCE:
1501 case EXPR_UNARY_DELETE:
1502 case EXPR_UNARY_DELETE_ARRAY:
1503 if (lhs_ent == ENT_ANY)
1507 case EXPR_UNARY_NEGATE:
1508 case EXPR_UNARY_PLUS:
1509 case EXPR_UNARY_BITWISE_NEGATE:
1510 case EXPR_UNARY_NOT:
1511 case EXPR_UNARY_TAKE_ADDRESS:
1512 case EXPR_UNARY_POSTFIX_INCREMENT:
1513 case EXPR_UNARY_POSTFIX_DECREMENT:
1514 case EXPR_UNARY_PREFIX_INCREMENT:
1515 case EXPR_UNARY_PREFIX_DECREMENT:
1516 case EXPR_UNARY_CAST_IMPLICIT:
1517 case EXPR_UNARY_ASSUME:
1519 mark_vars_read(expr->unary.value, lhs_ent);
1522 case EXPR_BINARY_ADD:
1523 case EXPR_BINARY_SUB:
1524 case EXPR_BINARY_MUL:
1525 case EXPR_BINARY_DIV:
1526 case EXPR_BINARY_MOD:
1527 case EXPR_BINARY_EQUAL:
1528 case EXPR_BINARY_NOTEQUAL:
1529 case EXPR_BINARY_LESS:
1530 case EXPR_BINARY_LESSEQUAL:
1531 case EXPR_BINARY_GREATER:
1532 case EXPR_BINARY_GREATEREQUAL:
1533 case EXPR_BINARY_BITWISE_AND:
1534 case EXPR_BINARY_BITWISE_OR:
1535 case EXPR_BINARY_BITWISE_XOR:
1536 case EXPR_BINARY_LOGICAL_AND:
1537 case EXPR_BINARY_LOGICAL_OR:
1538 case EXPR_BINARY_SHIFTLEFT:
1539 case EXPR_BINARY_SHIFTRIGHT:
1540 case EXPR_BINARY_COMMA:
1541 case EXPR_BINARY_ISGREATER:
1542 case EXPR_BINARY_ISGREATEREQUAL:
1543 case EXPR_BINARY_ISLESS:
1544 case EXPR_BINARY_ISLESSEQUAL:
1545 case EXPR_BINARY_ISLESSGREATER:
1546 case EXPR_BINARY_ISUNORDERED:
1547 mark_vars_read(expr->binary.left, lhs_ent);
1548 mark_vars_read(expr->binary.right, lhs_ent);
1551 case EXPR_BINARY_ASSIGN:
1552 case EXPR_BINARY_MUL_ASSIGN:
1553 case EXPR_BINARY_DIV_ASSIGN:
1554 case EXPR_BINARY_MOD_ASSIGN:
1555 case EXPR_BINARY_ADD_ASSIGN:
1556 case EXPR_BINARY_SUB_ASSIGN:
1557 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1558 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1559 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1560 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1561 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1562 if (lhs_ent == ENT_ANY)
1564 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1565 mark_vars_read(expr->binary.right, lhs_ent);
1570 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1576 case EXPR_CHARACTER_CONSTANT:
1577 case EXPR_WIDE_CHARACTER_CONSTANT:
1578 case EXPR_STRING_LITERAL:
1579 case EXPR_WIDE_STRING_LITERAL:
1580 case EXPR_COMPOUND_LITERAL: // TODO init?
1582 case EXPR_CLASSIFY_TYPE:
1585 case EXPR_BUILTIN_CONSTANT_P:
1586 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1588 case EXPR_STATEMENT: // TODO
1589 case EXPR_LABEL_ADDRESS:
1590 case EXPR_REFERENCE_ENUM_VALUE:
1594 panic("unhandled expression");
1597 static designator_t *parse_designation(void)
1599 designator_t *result = NULL;
1600 designator_t **anchor = &result;
1603 designator_t *designator;
1604 switch (token.type) {
1606 designator = allocate_ast_zero(sizeof(designator[0]));
1607 designator->source_position = token.source_position;
1609 add_anchor_token(']');
1610 designator->array_index = parse_constant_expression();
1611 rem_anchor_token(']');
1612 expect(']', end_error);
1615 designator = allocate_ast_zero(sizeof(designator[0]));
1616 designator->source_position = token.source_position;
1618 if (token.type != T_IDENTIFIER) {
1619 parse_error_expected("while parsing designator",
1620 T_IDENTIFIER, NULL);
1623 designator->symbol = token.v.symbol;
1627 expect('=', end_error);
1631 assert(designator != NULL);
1632 *anchor = designator;
1633 anchor = &designator->next;
1639 static initializer_t *initializer_from_string(array_type_t *type,
1640 const string_t *const string)
1642 /* TODO: check len vs. size of array type */
1645 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1646 initializer->string.string = *string;
1651 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1652 wide_string_t *const string)
1654 /* TODO: check len vs. size of array type */
1657 initializer_t *const initializer =
1658 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1659 initializer->wide_string.string = *string;
1665 * Build an initializer from a given expression.
1667 static initializer_t *initializer_from_expression(type_t *orig_type,
1668 expression_t *expression)
1670 /* TODO check that expression is a constant expression */
1672 /* §6.7.8.14/15 char array may be initialized by string literals */
1673 type_t *type = skip_typeref(orig_type);
1674 type_t *expr_type_orig = expression->base.type;
1675 type_t *expr_type = skip_typeref(expr_type_orig);
1676 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1677 array_type_t *const array_type = &type->array;
1678 type_t *const element_type = skip_typeref(array_type->element_type);
1680 if (element_type->kind == TYPE_ATOMIC) {
1681 atomic_type_kind_t akind = element_type->atomic.akind;
1682 switch (expression->kind) {
1683 case EXPR_STRING_LITERAL:
1684 if (akind == ATOMIC_TYPE_CHAR
1685 || akind == ATOMIC_TYPE_SCHAR
1686 || akind == ATOMIC_TYPE_UCHAR) {
1687 return initializer_from_string(array_type,
1688 &expression->string.value);
1692 case EXPR_WIDE_STRING_LITERAL: {
1693 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1694 if (get_unqualified_type(element_type) == bare_wchar_type) {
1695 return initializer_from_wide_string(array_type,
1696 &expression->wide_string.value);
1707 assign_error_t error = semantic_assign(type, expression);
1708 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1710 report_assign_error(error, type, expression, "initializer",
1711 &expression->base.source_position);
1713 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1714 result->value.value = create_implicit_cast(expression, type);
1720 * Checks if a given expression can be used as an constant initializer.
1722 static bool is_initializer_constant(const expression_t *expression)
1724 return is_constant_expression(expression)
1725 || is_address_constant(expression);
1729 * Parses an scalar initializer.
1731 * §6.7.8.11; eat {} without warning
1733 static initializer_t *parse_scalar_initializer(type_t *type,
1734 bool must_be_constant)
1736 /* there might be extra {} hierarchies */
1740 warningf(HERE, "extra curly braces around scalar initializer");
1743 } while (next_if('{'));
1746 expression_t *expression = parse_assignment_expression();
1747 mark_vars_read(expression, NULL);
1748 if (must_be_constant && !is_initializer_constant(expression)) {
1749 errorf(&expression->base.source_position,
1750 "initialisation expression '%E' is not constant",
1754 initializer_t *initializer = initializer_from_expression(type, expression);
1756 if (initializer == NULL) {
1757 errorf(&expression->base.source_position,
1758 "expression '%E' (type '%T') doesn't match expected type '%T'",
1759 expression, expression->base.type, type);
1764 bool additional_warning_displayed = false;
1765 while (braces > 0) {
1767 if (token.type != '}') {
1768 if (!additional_warning_displayed && warning.other) {
1769 warningf(HERE, "additional elements in scalar initializer");
1770 additional_warning_displayed = true;
1781 * An entry in the type path.
1783 typedef struct type_path_entry_t type_path_entry_t;
1784 struct type_path_entry_t {
1785 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1787 size_t index; /**< For array types: the current index. */
1788 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1793 * A type path expression a position inside compound or array types.
1795 typedef struct type_path_t type_path_t;
1796 struct type_path_t {
1797 type_path_entry_t *path; /**< An flexible array containing the current path. */
1798 type_t *top_type; /**< type of the element the path points */
1799 size_t max_index; /**< largest index in outermost array */
1803 * Prints a type path for debugging.
1805 static __attribute__((unused)) void debug_print_type_path(
1806 const type_path_t *path)
1808 size_t len = ARR_LEN(path->path);
1810 for (size_t i = 0; i < len; ++i) {
1811 const type_path_entry_t *entry = & path->path[i];
1813 type_t *type = skip_typeref(entry->type);
1814 if (is_type_compound(type)) {
1815 /* in gcc mode structs can have no members */
1816 if (entry->v.compound_entry == NULL) {
1820 fprintf(stderr, ".%s",
1821 entry->v.compound_entry->base.symbol->string);
1822 } else if (is_type_array(type)) {
1823 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1825 fprintf(stderr, "-INVALID-");
1828 if (path->top_type != NULL) {
1829 fprintf(stderr, " (");
1830 print_type(path->top_type);
1831 fprintf(stderr, ")");
1836 * Return the top type path entry, ie. in a path
1837 * (type).a.b returns the b.
1839 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1841 size_t len = ARR_LEN(path->path);
1843 return &path->path[len-1];
1847 * Enlarge the type path by an (empty) element.
1849 static type_path_entry_t *append_to_type_path(type_path_t *path)
1851 size_t len = ARR_LEN(path->path);
1852 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1854 type_path_entry_t *result = & path->path[len];
1855 memset(result, 0, sizeof(result[0]));
1860 * Descending into a sub-type. Enter the scope of the current top_type.
1862 static void descend_into_subtype(type_path_t *path)
1864 type_t *orig_top_type = path->top_type;
1865 type_t *top_type = skip_typeref(orig_top_type);
1867 type_path_entry_t *top = append_to_type_path(path);
1868 top->type = top_type;
1870 if (is_type_compound(top_type)) {
1871 compound_t *compound = top_type->compound.compound;
1872 entity_t *entry = compound->members.entities;
1874 if (entry != NULL) {
1875 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1876 top->v.compound_entry = &entry->declaration;
1877 path->top_type = entry->declaration.type;
1879 path->top_type = NULL;
1881 } else if (is_type_array(top_type)) {
1883 path->top_type = top_type->array.element_type;
1885 assert(!is_type_valid(top_type));
1890 * Pop an entry from the given type path, ie. returning from
1891 * (type).a.b to (type).a
1893 static void ascend_from_subtype(type_path_t *path)
1895 type_path_entry_t *top = get_type_path_top(path);
1897 path->top_type = top->type;
1899 size_t len = ARR_LEN(path->path);
1900 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1904 * Pop entries from the given type path until the given
1905 * path level is reached.
1907 static void ascend_to(type_path_t *path, size_t top_path_level)
1909 size_t len = ARR_LEN(path->path);
1911 while (len > top_path_level) {
1912 ascend_from_subtype(path);
1913 len = ARR_LEN(path->path);
1917 static bool walk_designator(type_path_t *path, const designator_t *designator,
1918 bool used_in_offsetof)
1920 for (; designator != NULL; designator = designator->next) {
1921 type_path_entry_t *top = get_type_path_top(path);
1922 type_t *orig_type = top->type;
1924 type_t *type = skip_typeref(orig_type);
1926 if (designator->symbol != NULL) {
1927 symbol_t *symbol = designator->symbol;
1928 if (!is_type_compound(type)) {
1929 if (is_type_valid(type)) {
1930 errorf(&designator->source_position,
1931 "'.%Y' designator used for non-compound type '%T'",
1935 top->type = type_error_type;
1936 top->v.compound_entry = NULL;
1937 orig_type = type_error_type;
1939 compound_t *compound = type->compound.compound;
1940 entity_t *iter = compound->members.entities;
1941 for (; iter != NULL; iter = iter->base.next) {
1942 if (iter->base.symbol == symbol) {
1947 errorf(&designator->source_position,
1948 "'%T' has no member named '%Y'", orig_type, symbol);
1951 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1952 if (used_in_offsetof) {
1953 type_t *real_type = skip_typeref(iter->declaration.type);
1954 if (real_type->kind == TYPE_BITFIELD) {
1955 errorf(&designator->source_position,
1956 "offsetof designator '%Y' may not specify bitfield",
1962 top->type = orig_type;
1963 top->v.compound_entry = &iter->declaration;
1964 orig_type = iter->declaration.type;
1967 expression_t *array_index = designator->array_index;
1968 assert(designator->array_index != NULL);
1970 if (!is_type_array(type)) {
1971 if (is_type_valid(type)) {
1972 errorf(&designator->source_position,
1973 "[%E] designator used for non-array type '%T'",
1974 array_index, orig_type);
1979 long index = fold_constant_to_int(array_index);
1980 if (!used_in_offsetof) {
1982 errorf(&designator->source_position,
1983 "array index [%E] must be positive", array_index);
1984 } else if (type->array.size_constant) {
1985 long array_size = type->array.size;
1986 if (index >= array_size) {
1987 errorf(&designator->source_position,
1988 "designator [%E] (%d) exceeds array size %d",
1989 array_index, index, array_size);
1994 top->type = orig_type;
1995 top->v.index = (size_t) index;
1996 orig_type = type->array.element_type;
1998 path->top_type = orig_type;
2000 if (designator->next != NULL) {
2001 descend_into_subtype(path);
2010 static void advance_current_object(type_path_t *path, size_t top_path_level)
2012 type_path_entry_t *top = get_type_path_top(path);
2014 type_t *type = skip_typeref(top->type);
2015 if (is_type_union(type)) {
2016 /* in unions only the first element is initialized */
2017 top->v.compound_entry = NULL;
2018 } else if (is_type_struct(type)) {
2019 declaration_t *entry = top->v.compound_entry;
2021 entity_t *next_entity = entry->base.next;
2022 if (next_entity != NULL) {
2023 assert(is_declaration(next_entity));
2024 entry = &next_entity->declaration;
2029 top->v.compound_entry = entry;
2030 if (entry != NULL) {
2031 path->top_type = entry->type;
2034 } else if (is_type_array(type)) {
2035 assert(is_type_array(type));
2039 if (!type->array.size_constant || top->v.index < type->array.size) {
2043 assert(!is_type_valid(type));
2047 /* we're past the last member of the current sub-aggregate, try if we
2048 * can ascend in the type hierarchy and continue with another subobject */
2049 size_t len = ARR_LEN(path->path);
2051 if (len > top_path_level) {
2052 ascend_from_subtype(path);
2053 advance_current_object(path, top_path_level);
2055 path->top_type = NULL;
2060 * skip any {...} blocks until a closing bracket is reached.
2062 static void skip_initializers(void)
2066 while (token.type != '}') {
2067 if (token.type == T_EOF)
2069 if (token.type == '{') {
2077 static initializer_t *create_empty_initializer(void)
2079 static initializer_t empty_initializer
2080 = { .list = { { INITIALIZER_LIST }, 0 } };
2081 return &empty_initializer;
2085 * Parse a part of an initialiser for a struct or union,
2087 static initializer_t *parse_sub_initializer(type_path_t *path,
2088 type_t *outer_type, size_t top_path_level,
2089 parse_initializer_env_t *env)
2091 if (token.type == '}') {
2092 /* empty initializer */
2093 return create_empty_initializer();
2096 type_t *orig_type = path->top_type;
2097 type_t *type = NULL;
2099 if (orig_type == NULL) {
2100 /* We are initializing an empty compound. */
2102 type = skip_typeref(orig_type);
2105 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2108 designator_t *designator = NULL;
2109 if (token.type == '.' || token.type == '[') {
2110 designator = parse_designation();
2111 goto finish_designator;
2112 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2113 /* GNU-style designator ("identifier: value") */
2114 designator = allocate_ast_zero(sizeof(designator[0]));
2115 designator->source_position = token.source_position;
2116 designator->symbol = token.v.symbol;
2121 /* reset path to toplevel, evaluate designator from there */
2122 ascend_to(path, top_path_level);
2123 if (!walk_designator(path, designator, false)) {
2124 /* can't continue after designation error */
2128 initializer_t *designator_initializer
2129 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2130 designator_initializer->designator.designator = designator;
2131 ARR_APP1(initializer_t*, initializers, designator_initializer);
2133 orig_type = path->top_type;
2134 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2139 if (token.type == '{') {
2140 if (type != NULL && is_type_scalar(type)) {
2141 sub = parse_scalar_initializer(type, env->must_be_constant);
2145 if (env->entity != NULL) {
2147 "extra brace group at end of initializer for '%Y'",
2148 env->entity->base.symbol);
2150 errorf(HERE, "extra brace group at end of initializer");
2153 descend_into_subtype(path);
2155 add_anchor_token('}');
2156 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2158 rem_anchor_token('}');
2161 ascend_from_subtype(path);
2162 expect('}', end_error);
2164 expect('}', end_error);
2165 goto error_parse_next;
2169 /* must be an expression */
2170 expression_t *expression = parse_assignment_expression();
2171 mark_vars_read(expression, NULL);
2173 if (env->must_be_constant && !is_initializer_constant(expression)) {
2174 errorf(&expression->base.source_position,
2175 "Initialisation expression '%E' is not constant",
2180 /* we are already outside, ... */
2181 if (outer_type == NULL)
2182 goto error_parse_next;
2183 type_t *const outer_type_skip = skip_typeref(outer_type);
2184 if (is_type_compound(outer_type_skip) &&
2185 !outer_type_skip->compound.compound->complete) {
2186 goto error_parse_next;
2191 /* handle { "string" } special case */
2192 if ((expression->kind == EXPR_STRING_LITERAL
2193 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2194 && outer_type != NULL) {
2195 sub = initializer_from_expression(outer_type, expression);
2198 if (token.type != '}' && warning.other) {
2199 warningf(HERE, "excessive elements in initializer for type '%T'",
2202 /* TODO: eat , ... */
2207 /* descend into subtypes until expression matches type */
2209 orig_type = path->top_type;
2210 type = skip_typeref(orig_type);
2212 sub = initializer_from_expression(orig_type, expression);
2216 if (!is_type_valid(type)) {
2219 if (is_type_scalar(type)) {
2220 errorf(&expression->base.source_position,
2221 "expression '%E' doesn't match expected type '%T'",
2222 expression, orig_type);
2226 descend_into_subtype(path);
2230 /* update largest index of top array */
2231 const type_path_entry_t *first = &path->path[0];
2232 type_t *first_type = first->type;
2233 first_type = skip_typeref(first_type);
2234 if (is_type_array(first_type)) {
2235 size_t index = first->v.index;
2236 if (index > path->max_index)
2237 path->max_index = index;
2241 /* append to initializers list */
2242 ARR_APP1(initializer_t*, initializers, sub);
2245 if (warning.other) {
2246 if (env->entity != NULL) {
2247 warningf(HERE, "excess elements in initializer for '%Y'",
2248 env->entity->base.symbol);
2250 warningf(HERE, "excess elements in initializer");
2256 if (token.type == '}') {
2259 expect(',', end_error);
2260 if (token.type == '}') {
2265 /* advance to the next declaration if we are not at the end */
2266 advance_current_object(path, top_path_level);
2267 orig_type = path->top_type;
2268 if (orig_type != NULL)
2269 type = skip_typeref(orig_type);
2275 size_t len = ARR_LEN(initializers);
2276 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2277 initializer_t *result = allocate_ast_zero(size);
2278 result->kind = INITIALIZER_LIST;
2279 result->list.len = len;
2280 memcpy(&result->list.initializers, initializers,
2281 len * sizeof(initializers[0]));
2283 DEL_ARR_F(initializers);
2284 ascend_to(path, top_path_level+1);
2289 skip_initializers();
2290 DEL_ARR_F(initializers);
2291 ascend_to(path, top_path_level+1);
2296 * Parses an initializer. Parsers either a compound literal
2297 * (env->declaration == NULL) or an initializer of a declaration.
2299 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2301 type_t *type = skip_typeref(env->type);
2302 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2303 initializer_t *result;
2305 if (is_type_scalar(type)) {
2306 result = parse_scalar_initializer(type, env->must_be_constant);
2307 } else if (token.type == '{') {
2311 memset(&path, 0, sizeof(path));
2312 path.top_type = env->type;
2313 path.path = NEW_ARR_F(type_path_entry_t, 0);
2315 descend_into_subtype(&path);
2317 add_anchor_token('}');
2318 result = parse_sub_initializer(&path, env->type, 1, env);
2319 rem_anchor_token('}');
2321 max_index = path.max_index;
2322 DEL_ARR_F(path.path);
2324 expect('}', end_error);
2326 /* parse_scalar_initializer() also works in this case: we simply
2327 * have an expression without {} around it */
2328 result = parse_scalar_initializer(type, env->must_be_constant);
2331 /* §6.7.8:22 array initializers for arrays with unknown size determine
2332 * the array type size */
2333 if (is_type_array(type) && type->array.size_expression == NULL
2334 && result != NULL) {
2336 switch (result->kind) {
2337 case INITIALIZER_LIST:
2338 assert(max_index != 0xdeadbeaf);
2339 size = max_index + 1;
2342 case INITIALIZER_STRING:
2343 size = result->string.string.size;
2346 case INITIALIZER_WIDE_STRING:
2347 size = result->wide_string.string.size;
2350 case INITIALIZER_DESIGNATOR:
2351 case INITIALIZER_VALUE:
2352 /* can happen for parse errors */
2357 internal_errorf(HERE, "invalid initializer type");
2360 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2361 cnst->base.type = type_size_t;
2362 cnst->conste.v.int_value = size;
2364 type_t *new_type = duplicate_type(type);
2366 new_type->array.size_expression = cnst;
2367 new_type->array.size_constant = true;
2368 new_type->array.has_implicit_size = true;
2369 new_type->array.size = size;
2370 env->type = new_type;
2378 static void append_entity(scope_t *scope, entity_t *entity)
2380 if (scope->last_entity != NULL) {
2381 scope->last_entity->base.next = entity;
2383 scope->entities = entity;
2385 entity->base.parent_entity = current_entity;
2386 scope->last_entity = entity;
2390 static compound_t *parse_compound_type_specifier(bool is_struct)
2392 eat(is_struct ? T_struct : T_union);
2394 symbol_t *symbol = NULL;
2395 compound_t *compound = NULL;
2396 attribute_t *attributes = NULL;
2398 if (token.type == T___attribute__) {
2399 attributes = parse_attributes(NULL);
2402 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2403 if (token.type == T_IDENTIFIER) {
2404 /* the compound has a name, check if we have seen it already */
2405 symbol = token.v.symbol;
2408 entity_t *entity = get_tag(symbol, kind);
2409 if (entity != NULL) {
2410 compound = &entity->compound;
2411 if (compound->base.parent_scope != current_scope &&
2412 (token.type == '{' || token.type == ';')) {
2413 /* we're in an inner scope and have a definition. Shadow
2414 * existing definition in outer scope */
2416 } else if (compound->complete && token.type == '{') {
2417 assert(symbol != NULL);
2418 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2419 is_struct ? "struct" : "union", symbol,
2420 &compound->base.source_position);
2421 /* clear members in the hope to avoid further errors */
2422 compound->members.entities = NULL;
2425 } else if (token.type != '{') {
2427 parse_error_expected("while parsing struct type specifier",
2428 T_IDENTIFIER, '{', NULL);
2430 parse_error_expected("while parsing union type specifier",
2431 T_IDENTIFIER, '{', NULL);
2437 if (compound == NULL) {
2438 entity_t *entity = allocate_entity_zero(kind);
2439 compound = &entity->compound;
2441 compound->alignment = 1;
2442 compound->base.namespc = NAMESPACE_TAG;
2443 compound->base.source_position = token.source_position;
2444 compound->base.symbol = symbol;
2445 compound->base.parent_scope = current_scope;
2446 if (symbol != NULL) {
2447 environment_push(entity);
2449 append_entity(current_scope, entity);
2452 if (token.type == '{') {
2453 parse_compound_type_entries(compound);
2455 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2456 if (symbol == NULL) {
2457 assert(anonymous_entity == NULL);
2458 anonymous_entity = (entity_t*)compound;
2462 if (attributes != NULL) {
2463 handle_entity_attributes(attributes, (entity_t*) compound);
2469 static void parse_enum_entries(type_t *const enum_type)
2473 if (token.type == '}') {
2474 errorf(HERE, "empty enum not allowed");
2479 add_anchor_token('}');
2481 if (token.type != T_IDENTIFIER) {
2482 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2484 rem_anchor_token('}');
2488 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2489 entity->enum_value.enum_type = enum_type;
2490 entity->base.symbol = token.v.symbol;
2491 entity->base.source_position = token.source_position;
2495 expression_t *value = parse_constant_expression();
2497 value = create_implicit_cast(value, enum_type);
2498 entity->enum_value.value = value;
2503 record_entity(entity, false);
2504 } while (next_if(',') && token.type != '}');
2505 rem_anchor_token('}');
2507 expect('}', end_error);
2513 static type_t *parse_enum_specifier(void)
2519 switch (token.type) {
2521 symbol = token.v.symbol;
2524 entity = get_tag(symbol, ENTITY_ENUM);
2525 if (entity != NULL) {
2526 if (entity->base.parent_scope != current_scope &&
2527 (token.type == '{' || token.type == ';')) {
2528 /* we're in an inner scope and have a definition. Shadow
2529 * existing definition in outer scope */
2531 } else if (entity->enume.complete && token.type == '{') {
2532 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2533 symbol, &entity->base.source_position);
2544 parse_error_expected("while parsing enum type specifier",
2545 T_IDENTIFIER, '{', NULL);
2549 if (entity == NULL) {
2550 entity = allocate_entity_zero(ENTITY_ENUM);
2551 entity->base.namespc = NAMESPACE_TAG;
2552 entity->base.source_position = token.source_position;
2553 entity->base.symbol = symbol;
2554 entity->base.parent_scope = current_scope;
2557 type_t *const type = allocate_type_zero(TYPE_ENUM);
2558 type->enumt.enume = &entity->enume;
2559 type->enumt.akind = ATOMIC_TYPE_INT;
2561 if (token.type == '{') {
2562 if (symbol != NULL) {
2563 environment_push(entity);
2565 append_entity(current_scope, entity);
2566 entity->enume.complete = true;
2568 parse_enum_entries(type);
2569 parse_attributes(NULL);
2571 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2572 if (symbol == NULL) {
2573 assert(anonymous_entity == NULL);
2574 anonymous_entity = entity;
2576 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2577 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2585 * if a symbol is a typedef to another type, return true
2587 static bool is_typedef_symbol(symbol_t *symbol)
2589 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2590 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2593 static type_t *parse_typeof(void)
2599 expect('(', end_error);
2600 add_anchor_token(')');
2602 expression_t *expression = NULL;
2604 bool old_type_prop = in_type_prop;
2605 bool old_gcc_extension = in_gcc_extension;
2606 in_type_prop = true;
2608 while (next_if(T___extension__)) {
2609 /* This can be a prefix to a typename or an expression. */
2610 in_gcc_extension = true;
2612 switch (token.type) {
2614 if (is_typedef_symbol(token.v.symbol)) {
2615 type = parse_typename();
2617 expression = parse_expression();
2618 type = revert_automatic_type_conversion(expression);
2623 type = parse_typename();
2627 expression = parse_expression();
2628 type = expression->base.type;
2631 in_type_prop = old_type_prop;
2632 in_gcc_extension = old_gcc_extension;
2634 rem_anchor_token(')');
2635 expect(')', end_error);
2637 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2638 typeof_type->typeoft.expression = expression;
2639 typeof_type->typeoft.typeof_type = type;
2646 typedef enum specifiers_t {
2647 SPECIFIER_SIGNED = 1 << 0,
2648 SPECIFIER_UNSIGNED = 1 << 1,
2649 SPECIFIER_LONG = 1 << 2,
2650 SPECIFIER_INT = 1 << 3,
2651 SPECIFIER_DOUBLE = 1 << 4,
2652 SPECIFIER_CHAR = 1 << 5,
2653 SPECIFIER_WCHAR_T = 1 << 6,
2654 SPECIFIER_SHORT = 1 << 7,
2655 SPECIFIER_LONG_LONG = 1 << 8,
2656 SPECIFIER_FLOAT = 1 << 9,
2657 SPECIFIER_BOOL = 1 << 10,
2658 SPECIFIER_VOID = 1 << 11,
2659 SPECIFIER_INT8 = 1 << 12,
2660 SPECIFIER_INT16 = 1 << 13,
2661 SPECIFIER_INT32 = 1 << 14,
2662 SPECIFIER_INT64 = 1 << 15,
2663 SPECIFIER_INT128 = 1 << 16,
2664 SPECIFIER_COMPLEX = 1 << 17,
2665 SPECIFIER_IMAGINARY = 1 << 18,
2668 static type_t *create_builtin_type(symbol_t *const symbol,
2669 type_t *const real_type)
2671 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2672 type->builtin.symbol = symbol;
2673 type->builtin.real_type = real_type;
2674 return identify_new_type(type);
2677 static type_t *get_typedef_type(symbol_t *symbol)
2679 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2680 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2683 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2684 type->typedeft.typedefe = &entity->typedefe;
2689 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2691 expect('(', end_error);
2693 attribute_property_argument_t *property
2694 = allocate_ast_zero(sizeof(*property));
2697 if (token.type != T_IDENTIFIER) {
2698 parse_error_expected("while parsing property declspec",
2699 T_IDENTIFIER, NULL);
2704 symbol_t *symbol = token.v.symbol;
2706 if (strcmp(symbol->string, "put") == 0) {
2708 } else if (strcmp(symbol->string, "get") == 0) {
2711 errorf(HERE, "expected put or get in property declspec");
2714 expect('=', end_error);
2715 if (token.type != T_IDENTIFIER) {
2716 parse_error_expected("while parsing property declspec",
2717 T_IDENTIFIER, NULL);
2721 property->put_symbol = token.v.symbol;
2723 property->get_symbol = token.v.symbol;
2726 } while (next_if(','));
2728 attribute->a.property = property;
2730 expect(')', end_error);
2736 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2738 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2739 if (next_if(T_restrict)) {
2740 kind = ATTRIBUTE_MS_RESTRICT;
2741 } else if (token.type == T_IDENTIFIER) {
2742 const char *name = token.v.symbol->string;
2744 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2746 const char *attribute_name = get_attribute_name(k);
2747 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2753 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2754 warningf(HERE, "unknown __declspec '%s' ignored", name);
2757 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2761 attribute_t *attribute = allocate_attribute_zero(kind);
2763 if (kind == ATTRIBUTE_MS_PROPERTY) {
2764 return parse_attribute_ms_property(attribute);
2767 /* parse arguments */
2769 attribute->a.arguments = parse_attribute_arguments();
2774 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2778 expect('(', end_error);
2783 add_anchor_token(')');
2785 attribute_t **anchor = &first;
2787 while (*anchor != NULL)
2788 anchor = &(*anchor)->next;
2790 attribute_t *attribute
2791 = parse_microsoft_extended_decl_modifier_single();
2792 if (attribute == NULL)
2795 *anchor = attribute;
2796 anchor = &attribute->next;
2797 } while (next_if(','));
2799 rem_anchor_token(')');
2800 expect(')', end_error);
2804 rem_anchor_token(')');
2808 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2810 entity_t *entity = allocate_entity_zero(kind);
2811 entity->base.source_position = *HERE;
2812 entity->base.symbol = symbol;
2813 if (is_declaration(entity)) {
2814 entity->declaration.type = type_error_type;
2815 entity->declaration.implicit = true;
2816 } else if (kind == ENTITY_TYPEDEF) {
2817 entity->typedefe.type = type_error_type;
2818 entity->typedefe.builtin = true;
2820 if (kind != ENTITY_COMPOUND_MEMBER)
2821 record_entity(entity, false);
2825 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2827 type_t *type = NULL;
2828 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2829 unsigned type_specifiers = 0;
2830 bool newtype = false;
2831 bool saw_error = false;
2832 bool old_gcc_extension = in_gcc_extension;
2834 specifiers->source_position = token.source_position;
2837 specifiers->attributes = parse_attributes(specifiers->attributes);
2839 switch (token.type) {
2841 #define MATCH_STORAGE_CLASS(token, class) \
2843 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2844 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2846 specifiers->storage_class = class; \
2847 if (specifiers->thread_local) \
2848 goto check_thread_storage_class; \
2852 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2853 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2854 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2855 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2856 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2859 specifiers->attributes
2860 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2864 if (specifiers->thread_local) {
2865 errorf(HERE, "duplicate '__thread'");
2867 specifiers->thread_local = true;
2868 check_thread_storage_class:
2869 switch (specifiers->storage_class) {
2870 case STORAGE_CLASS_EXTERN:
2871 case STORAGE_CLASS_NONE:
2872 case STORAGE_CLASS_STATIC:
2876 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
2877 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
2878 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
2879 wrong_thread_stoarge_class:
2880 errorf(HERE, "'__thread' used with '%s'", wrong);
2887 /* type qualifiers */
2888 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2890 qualifiers |= qualifier; \
2894 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2895 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2896 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2897 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2898 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2899 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2900 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2901 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2903 case T___extension__:
2905 in_gcc_extension = true;
2908 /* type specifiers */
2909 #define MATCH_SPECIFIER(token, specifier, name) \
2911 if (type_specifiers & specifier) { \
2912 errorf(HERE, "multiple " name " type specifiers given"); \
2914 type_specifiers |= specifier; \
2919 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2920 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2921 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2922 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2923 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2924 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2925 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2926 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2927 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2928 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2929 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2930 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2931 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2932 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2933 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2934 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2935 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2936 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2940 specifiers->is_inline = true;
2944 case T__forceinline:
2946 specifiers->modifiers |= DM_FORCEINLINE;
2951 if (type_specifiers & SPECIFIER_LONG_LONG) {
2952 errorf(HERE, "multiple type specifiers given");
2953 } else if (type_specifiers & SPECIFIER_LONG) {
2954 type_specifiers |= SPECIFIER_LONG_LONG;
2956 type_specifiers |= SPECIFIER_LONG;
2961 #define CHECK_DOUBLE_TYPE() \
2962 if ( type != NULL) \
2963 errorf(HERE, "multiple data types in declaration specifiers");
2966 CHECK_DOUBLE_TYPE();
2967 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2969 type->compound.compound = parse_compound_type_specifier(true);
2972 CHECK_DOUBLE_TYPE();
2973 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2974 type->compound.compound = parse_compound_type_specifier(false);
2977 CHECK_DOUBLE_TYPE();
2978 type = parse_enum_specifier();
2981 CHECK_DOUBLE_TYPE();
2982 type = parse_typeof();
2984 case T___builtin_va_list:
2985 CHECK_DOUBLE_TYPE();
2986 type = duplicate_type(type_valist);
2990 case T_IDENTIFIER: {
2991 /* only parse identifier if we haven't found a type yet */
2992 if (type != NULL || type_specifiers != 0) {
2993 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2994 * declaration, so it doesn't generate errors about expecting '(' or
2996 switch (look_ahead(1)->type) {
3003 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3007 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3012 goto finish_specifiers;
3016 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3017 if (typedef_type == NULL) {
3018 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3019 * declaration, so it doesn't generate 'implicit int' followed by more
3020 * errors later on. */
3021 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3027 errorf(HERE, "%K does not name a type", &token);
3030 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3032 type = allocate_type_zero(TYPE_TYPEDEF);
3033 type->typedeft.typedefe = &entity->typedefe;
3037 if (la1_type == '&' || la1_type == '*')
3038 goto finish_specifiers;
3043 goto finish_specifiers;
3048 type = typedef_type;
3052 /* function specifier */
3054 goto finish_specifiers;
3059 specifiers->attributes = parse_attributes(specifiers->attributes);
3061 in_gcc_extension = old_gcc_extension;
3063 if (type == NULL || (saw_error && type_specifiers != 0)) {
3064 atomic_type_kind_t atomic_type;
3066 /* match valid basic types */
3067 switch (type_specifiers) {
3068 case SPECIFIER_VOID:
3069 atomic_type = ATOMIC_TYPE_VOID;
3071 case SPECIFIER_WCHAR_T:
3072 atomic_type = ATOMIC_TYPE_WCHAR_T;
3074 case SPECIFIER_CHAR:
3075 atomic_type = ATOMIC_TYPE_CHAR;
3077 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3078 atomic_type = ATOMIC_TYPE_SCHAR;
3080 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3081 atomic_type = ATOMIC_TYPE_UCHAR;
3083 case SPECIFIER_SHORT:
3084 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3085 case SPECIFIER_SHORT | SPECIFIER_INT:
3086 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3087 atomic_type = ATOMIC_TYPE_SHORT;
3089 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3090 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3091 atomic_type = ATOMIC_TYPE_USHORT;
3094 case SPECIFIER_SIGNED:
3095 case SPECIFIER_SIGNED | SPECIFIER_INT:
3096 atomic_type = ATOMIC_TYPE_INT;
3098 case SPECIFIER_UNSIGNED:
3099 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3100 atomic_type = ATOMIC_TYPE_UINT;
3102 case SPECIFIER_LONG:
3103 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3104 case SPECIFIER_LONG | SPECIFIER_INT:
3105 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3106 atomic_type = ATOMIC_TYPE_LONG;
3108 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3109 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3110 atomic_type = ATOMIC_TYPE_ULONG;
3113 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3114 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3115 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3116 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3118 atomic_type = ATOMIC_TYPE_LONGLONG;
3119 goto warn_about_long_long;
3121 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3122 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3124 atomic_type = ATOMIC_TYPE_ULONGLONG;
3125 warn_about_long_long:
3126 if (warning.long_long) {
3127 warningf(&specifiers->source_position,
3128 "ISO C90 does not support 'long long'");
3132 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3133 atomic_type = unsigned_int8_type_kind;
3136 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3137 atomic_type = unsigned_int16_type_kind;
3140 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3141 atomic_type = unsigned_int32_type_kind;
3144 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3145 atomic_type = unsigned_int64_type_kind;
3148 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3149 atomic_type = unsigned_int128_type_kind;
3152 case SPECIFIER_INT8:
3153 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3154 atomic_type = int8_type_kind;
3157 case SPECIFIER_INT16:
3158 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3159 atomic_type = int16_type_kind;
3162 case SPECIFIER_INT32:
3163 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3164 atomic_type = int32_type_kind;
3167 case SPECIFIER_INT64:
3168 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3169 atomic_type = int64_type_kind;
3172 case SPECIFIER_INT128:
3173 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3174 atomic_type = int128_type_kind;
3177 case SPECIFIER_FLOAT:
3178 atomic_type = ATOMIC_TYPE_FLOAT;
3180 case SPECIFIER_DOUBLE:
3181 atomic_type = ATOMIC_TYPE_DOUBLE;
3183 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3184 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3186 case SPECIFIER_BOOL:
3187 atomic_type = ATOMIC_TYPE_BOOL;
3189 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3190 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3191 atomic_type = ATOMIC_TYPE_FLOAT;
3193 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3194 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3195 atomic_type = ATOMIC_TYPE_DOUBLE;
3197 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3198 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3199 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3202 /* invalid specifier combination, give an error message */
3203 if (type_specifiers == 0) {
3207 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3208 if (!(c_mode & _CXX) && !strict_mode) {
3209 if (warning.implicit_int) {
3210 warningf(HERE, "no type specifiers in declaration, using 'int'");
3212 atomic_type = ATOMIC_TYPE_INT;
3215 errorf(HERE, "no type specifiers given in declaration");
3217 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3218 (type_specifiers & SPECIFIER_UNSIGNED)) {
3219 errorf(HERE, "signed and unsigned specifiers given");
3220 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3221 errorf(HERE, "only integer types can be signed or unsigned");
3223 errorf(HERE, "multiple datatypes in declaration");
3228 if (type_specifiers & SPECIFIER_COMPLEX) {
3229 type = allocate_type_zero(TYPE_COMPLEX);
3230 type->complex.akind = atomic_type;
3231 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3232 type = allocate_type_zero(TYPE_IMAGINARY);
3233 type->imaginary.akind = atomic_type;
3235 type = allocate_type_zero(TYPE_ATOMIC);
3236 type->atomic.akind = atomic_type;
3239 } else if (type_specifiers != 0) {
3240 errorf(HERE, "multiple datatypes in declaration");
3243 /* FIXME: check type qualifiers here */
3244 type->base.qualifiers = qualifiers;
3247 type = identify_new_type(type);
3249 type = typehash_insert(type);
3252 if (specifiers->attributes != NULL)
3253 type = handle_type_attributes(specifiers->attributes, type);
3254 specifiers->type = type;
3258 specifiers->type = type_error_type;
3261 static type_qualifiers_t parse_type_qualifiers(void)
3263 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3266 switch (token.type) {
3267 /* type qualifiers */
3268 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3269 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3270 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3271 /* microsoft extended type modifiers */
3272 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3273 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3274 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3275 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3276 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3285 * Parses an K&R identifier list
3287 static void parse_identifier_list(scope_t *scope)
3290 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3291 entity->base.source_position = token.source_position;
3292 entity->base.namespc = NAMESPACE_NORMAL;
3293 entity->base.symbol = token.v.symbol;
3294 /* a K&R parameter has no type, yet */
3298 append_entity(scope, entity);
3299 } while (next_if(',') && token.type == T_IDENTIFIER);
3302 static entity_t *parse_parameter(void)
3304 declaration_specifiers_t specifiers;
3305 memset(&specifiers, 0, sizeof(specifiers));
3307 parse_declaration_specifiers(&specifiers);
3309 entity_t *entity = parse_declarator(&specifiers,
3310 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3311 anonymous_entity = NULL;
3315 static void semantic_parameter_incomplete(const entity_t *entity)
3317 assert(entity->kind == ENTITY_PARAMETER);
3319 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3320 * list in a function declarator that is part of a
3321 * definition of that function shall not have
3322 * incomplete type. */
3323 type_t *type = skip_typeref(entity->declaration.type);
3324 if (is_type_incomplete(type)) {
3325 errorf(&entity->base.source_position,
3326 "parameter '%#T' has incomplete type",
3327 entity->declaration.type, entity->base.symbol);
3331 static bool has_parameters(void)
3333 /* func(void) is not a parameter */
3334 if (token.type == T_IDENTIFIER) {
3335 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
3338 if (entity->kind != ENTITY_TYPEDEF)
3340 if (skip_typeref(entity->typedefe.type) != type_void)
3342 } else if (token.type != T_void) {
3345 if (look_ahead(1)->type != ')')
3352 * Parses function type parameters (and optionally creates variable_t entities
3353 * for them in a scope)
3355 static void parse_parameters(function_type_t *type, scope_t *scope)
3358 add_anchor_token(')');
3359 int saved_comma_state = save_and_reset_anchor_state(',');
3361 if (token.type == T_IDENTIFIER &&
3362 !is_typedef_symbol(token.v.symbol)) {
3363 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3364 if (la1_type == ',' || la1_type == ')') {
3365 type->kr_style_parameters = true;
3366 parse_identifier_list(scope);
3367 goto parameters_finished;
3371 if (token.type == ')') {
3372 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3373 if (!(c_mode & _CXX))
3374 type->unspecified_parameters = true;
3375 goto parameters_finished;
3378 if (has_parameters()) {
3379 function_parameter_t **anchor = &type->parameters;
3381 switch (token.type) {
3384 type->variadic = true;
3385 goto parameters_finished;
3388 case T___extension__:
3391 entity_t *entity = parse_parameter();
3392 if (entity->kind == ENTITY_TYPEDEF) {
3393 errorf(&entity->base.source_position,
3394 "typedef not allowed as function parameter");
3397 assert(is_declaration(entity));
3399 semantic_parameter_incomplete(entity);
3401 function_parameter_t *const parameter =
3402 allocate_parameter(entity->declaration.type);
3404 if (scope != NULL) {
3405 append_entity(scope, entity);
3408 *anchor = parameter;
3409 anchor = ¶meter->next;
3414 goto parameters_finished;
3416 } while (next_if(','));
3420 parameters_finished:
3421 rem_anchor_token(')');
3422 expect(')', end_error);
3425 restore_anchor_state(',', saved_comma_state);
3428 typedef enum construct_type_kind_t {
3431 CONSTRUCT_REFERENCE,
3434 } construct_type_kind_t;
3436 typedef union construct_type_t construct_type_t;
3438 typedef struct construct_type_base_t {
3439 construct_type_kind_t kind;
3440 construct_type_t *next;
3441 } construct_type_base_t;
3443 typedef struct parsed_pointer_t {
3444 construct_type_base_t base;
3445 type_qualifiers_t type_qualifiers;
3446 variable_t *base_variable; /**< MS __based extension. */
3449 typedef struct parsed_reference_t {
3450 construct_type_base_t base;
3451 } parsed_reference_t;
3453 typedef struct construct_function_type_t {
3454 construct_type_base_t base;
3455 type_t *function_type;
3456 } construct_function_type_t;
3458 typedef struct parsed_array_t {
3459 construct_type_base_t base;
3460 type_qualifiers_t type_qualifiers;
3466 union construct_type_t {
3467 construct_type_kind_t kind;
3468 construct_type_base_t base;
3469 parsed_pointer_t pointer;
3470 parsed_reference_t reference;
3471 construct_function_type_t function;
3472 parsed_array_t array;
3475 static construct_type_t *parse_pointer_declarator(void)
3479 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3480 memset(pointer, 0, sizeof(pointer[0]));
3481 pointer->base.kind = CONSTRUCT_POINTER;
3482 pointer->type_qualifiers = parse_type_qualifiers();
3483 //pointer->base_variable = base_variable;
3485 return (construct_type_t*) pointer;
3488 static construct_type_t *parse_reference_declarator(void)
3492 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
3493 parsed_reference_t *reference = &cons->reference;
3494 memset(reference, 0, sizeof(*reference));
3495 cons->kind = CONSTRUCT_REFERENCE;
3500 static construct_type_t *parse_array_declarator(void)
3503 add_anchor_token(']');
3505 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
3506 parsed_array_t *array = &cons->array;
3507 memset(array, 0, sizeof(*array));
3508 cons->kind = CONSTRUCT_ARRAY;
3510 if (next_if(T_static))
3511 array->is_static = true;
3513 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3514 if (type_qualifiers != 0 && next_if(T_static))
3515 array->is_static = true;
3516 array->type_qualifiers = type_qualifiers;
3518 if (token.type == '*' && look_ahead(1)->type == ']') {
3519 array->is_variable = true;
3521 } else if (token.type != ']') {
3522 expression_t *const size = parse_assignment_expression();
3524 /* §6.7.5.2:1 Array size must have integer type */
3525 type_t *const orig_type = size->base.type;
3526 type_t *const type = skip_typeref(orig_type);
3527 if (!is_type_integer(type) && is_type_valid(type)) {
3528 errorf(&size->base.source_position,
3529 "array size '%E' must have integer type but has type '%T'",
3534 mark_vars_read(size, NULL);
3537 rem_anchor_token(']');
3538 expect(']', end_error);
3544 static construct_type_t *parse_function_declarator(scope_t *scope)
3546 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3547 function_type_t *ftype = &type->function;
3549 ftype->linkage = current_linkage;
3550 ftype->calling_convention = CC_DEFAULT;
3552 parse_parameters(ftype, scope);
3554 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
3555 construct_function_type_t *function = &cons->function;
3556 memset(function, 0, sizeof(*function));
3557 cons->kind = CONSTRUCT_FUNCTION;
3558 function->function_type = type;
3563 typedef struct parse_declarator_env_t {
3564 bool may_be_abstract : 1;
3565 bool must_be_abstract : 1;
3566 decl_modifiers_t modifiers;
3568 source_position_t source_position;
3570 attribute_t *attributes;
3571 } parse_declarator_env_t;
3573 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3575 /* construct a single linked list of construct_type_t's which describe
3576 * how to construct the final declarator type */
3577 construct_type_t *first = NULL;
3578 construct_type_t **anchor = &first;
3580 env->attributes = parse_attributes(env->attributes);
3583 construct_type_t *type;
3584 //variable_t *based = NULL; /* MS __based extension */
3585 switch (token.type) {
3587 if (!(c_mode & _CXX))
3588 errorf(HERE, "references are only available for C++");
3589 type = parse_reference_declarator();
3593 panic("based not supported anymore");
3598 type = parse_pointer_declarator();
3602 goto ptr_operator_end;
3606 anchor = &type->base.next;
3608 /* TODO: find out if this is correct */
3609 env->attributes = parse_attributes(env->attributes);
3613 construct_type_t *inner_types = NULL;
3615 switch (token.type) {
3617 if (env->must_be_abstract) {
3618 errorf(HERE, "no identifier expected in typename");
3620 env->symbol = token.v.symbol;
3621 env->source_position = token.source_position;
3626 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3627 * interpreted as ``function with no parameter specification'', rather
3628 * than redundant parentheses around the omitted identifier. */
3629 if (look_ahead(1)->type != ')') {
3631 add_anchor_token(')');
3632 inner_types = parse_inner_declarator(env);
3633 if (inner_types != NULL) {
3634 /* All later declarators only modify the return type */
3635 env->must_be_abstract = true;
3637 rem_anchor_token(')');
3638 expect(')', end_error);
3642 if (env->may_be_abstract)
3644 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3649 construct_type_t **const p = anchor;
3652 construct_type_t *type;
3653 switch (token.type) {
3655 scope_t *scope = NULL;
3656 if (!env->must_be_abstract) {
3657 scope = &env->parameters;
3660 type = parse_function_declarator(scope);
3664 type = parse_array_declarator();
3667 goto declarator_finished;
3670 /* insert in the middle of the list (at p) */
3671 type->base.next = *p;
3674 anchor = &type->base.next;
3677 declarator_finished:
3678 /* append inner_types at the end of the list, we don't to set anchor anymore
3679 * as it's not needed anymore */
3680 *anchor = inner_types;
3687 static type_t *construct_declarator_type(construct_type_t *construct_list,
3690 construct_type_t *iter = construct_list;
3691 for (; iter != NULL; iter = iter->base.next) {
3692 switch (iter->kind) {
3693 case CONSTRUCT_INVALID:
3695 case CONSTRUCT_FUNCTION: {
3696 construct_function_type_t *function = &iter->function;
3697 type_t *function_type = function->function_type;
3699 function_type->function.return_type = type;
3701 type_t *skipped_return_type = skip_typeref(type);
3703 if (is_type_function(skipped_return_type)) {
3704 errorf(HERE, "function returning function is not allowed");
3705 } else if (is_type_array(skipped_return_type)) {
3706 errorf(HERE, "function returning array is not allowed");
3708 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3710 "type qualifiers in return type of function type are meaningless");
3714 /* The function type was constructed earlier. Freeing it here will
3715 * destroy other types. */
3716 type = typehash_insert(function_type);
3720 case CONSTRUCT_POINTER: {
3721 if (is_type_reference(skip_typeref(type)))
3722 errorf(HERE, "cannot declare a pointer to reference");
3724 parsed_pointer_t *pointer = &iter->pointer;
3725 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3729 case CONSTRUCT_REFERENCE:
3730 if (is_type_reference(skip_typeref(type)))
3731 errorf(HERE, "cannot declare a reference to reference");
3733 type = make_reference_type(type);
3736 case CONSTRUCT_ARRAY: {
3737 if (is_type_reference(skip_typeref(type)))
3738 errorf(HERE, "cannot declare an array of references");
3740 parsed_array_t *array = &iter->array;
3741 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3743 expression_t *size_expression = array->size;
3744 if (size_expression != NULL) {
3746 = create_implicit_cast(size_expression, type_size_t);
3749 array_type->base.qualifiers = array->type_qualifiers;
3750 array_type->array.element_type = type;
3751 array_type->array.is_static = array->is_static;
3752 array_type->array.is_variable = array->is_variable;
3753 array_type->array.size_expression = size_expression;
3755 if (size_expression != NULL) {
3756 if (is_constant_expression(size_expression)) {
3758 = fold_constant_to_int(size_expression);
3759 array_type->array.size = size;
3760 array_type->array.size_constant = true;
3761 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3762 * have a value greater than zero. */
3764 if (size < 0 || !GNU_MODE) {
3765 errorf(&size_expression->base.source_position,
3766 "size of array must be greater than zero");
3767 } else if (warning.other) {
3768 warningf(&size_expression->base.source_position,
3769 "zero length arrays are a GCC extension");
3773 array_type->array.is_vla = true;
3777 type_t *skipped_type = skip_typeref(type);
3779 if (is_type_incomplete(skipped_type)) {
3780 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
3781 } else if (is_type_function(skipped_type)) {
3782 errorf(HERE, "array of functions is not allowed");
3784 type = identify_new_type(array_type);
3788 internal_errorf(HERE, "invalid type construction found");
3794 static type_t *automatic_type_conversion(type_t *orig_type);
3796 static type_t *semantic_parameter(const source_position_t *pos,
3798 const declaration_specifiers_t *specifiers,
3801 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3802 * shall be adjusted to ``qualified pointer to type'',
3804 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3805 * type'' shall be adjusted to ``pointer to function
3806 * returning type'', as in 6.3.2.1. */
3807 type = automatic_type_conversion(type);
3809 if (specifiers->is_inline && is_type_valid(type)) {
3810 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3813 /* §6.9.1:6 The declarations in the declaration list shall contain
3814 * no storage-class specifier other than register and no
3815 * initializations. */
3816 if (specifiers->thread_local || (
3817 specifiers->storage_class != STORAGE_CLASS_NONE &&
3818 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3820 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3823 /* delay test for incomplete type, because we might have (void)
3824 * which is legal but incomplete... */
3829 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3830 declarator_flags_t flags)
3832 parse_declarator_env_t env;
3833 memset(&env, 0, sizeof(env));
3834 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3836 construct_type_t *construct_type = parse_inner_declarator(&env);
3838 construct_declarator_type(construct_type, specifiers->type);
3839 type_t *type = skip_typeref(orig_type);
3841 if (construct_type != NULL) {
3842 obstack_free(&temp_obst, construct_type);
3845 attribute_t *attributes = parse_attributes(env.attributes);
3846 /* append (shared) specifier attribute behind attributes of this
3848 attribute_t **anchor = &attributes;
3849 while (*anchor != NULL)
3850 anchor = &(*anchor)->next;
3851 *anchor = specifiers->attributes;
3854 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3855 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3856 entity->base.symbol = env.symbol;
3857 entity->base.source_position = env.source_position;
3858 entity->typedefe.type = orig_type;
3860 if (anonymous_entity != NULL) {
3861 if (is_type_compound(type)) {
3862 assert(anonymous_entity->compound.alias == NULL);
3863 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3864 anonymous_entity->kind == ENTITY_UNION);
3865 anonymous_entity->compound.alias = entity;
3866 anonymous_entity = NULL;
3867 } else if (is_type_enum(type)) {
3868 assert(anonymous_entity->enume.alias == NULL);
3869 assert(anonymous_entity->kind == ENTITY_ENUM);
3870 anonymous_entity->enume.alias = entity;
3871 anonymous_entity = NULL;
3875 /* create a declaration type entity */
3876 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3877 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3879 if (env.symbol != NULL) {
3880 if (specifiers->is_inline && is_type_valid(type)) {
3881 errorf(&env.source_position,
3882 "compound member '%Y' declared 'inline'", env.symbol);
3885 if (specifiers->thread_local ||
3886 specifiers->storage_class != STORAGE_CLASS_NONE) {
3887 errorf(&env.source_position,
3888 "compound member '%Y' must have no storage class",
3892 } else if (flags & DECL_IS_PARAMETER) {
3893 orig_type = semantic_parameter(&env.source_position, orig_type,
3894 specifiers, env.symbol);
3896 entity = allocate_entity_zero(ENTITY_PARAMETER);
3897 } else if (is_type_function(type)) {
3898 entity = allocate_entity_zero(ENTITY_FUNCTION);
3900 entity->function.is_inline = specifiers->is_inline;
3901 entity->function.parameters = env.parameters;
3903 if (env.symbol != NULL) {
3904 /* this needs fixes for C++ */
3905 bool in_function_scope = current_function != NULL;
3907 if (specifiers->thread_local || (
3908 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3909 specifiers->storage_class != STORAGE_CLASS_NONE &&
3910 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3912 errorf(&env.source_position,
3913 "invalid storage class for function '%Y'", env.symbol);
3917 entity = allocate_entity_zero(ENTITY_VARIABLE);
3919 entity->variable.thread_local = specifiers->thread_local;
3921 if (env.symbol != NULL) {
3922 if (specifiers->is_inline && is_type_valid(type)) {
3923 errorf(&env.source_position,
3924 "variable '%Y' declared 'inline'", env.symbol);
3927 bool invalid_storage_class = false;
3928 if (current_scope == file_scope) {
3929 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3930 specifiers->storage_class != STORAGE_CLASS_NONE &&
3931 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3932 invalid_storage_class = true;
3935 if (specifiers->thread_local &&
3936 specifiers->storage_class == STORAGE_CLASS_NONE) {
3937 invalid_storage_class = true;
3940 if (invalid_storage_class) {
3941 errorf(&env.source_position,
3942 "invalid storage class for variable '%Y'", env.symbol);
3947 if (env.symbol != NULL) {
3948 entity->base.symbol = env.symbol;
3949 entity->base.source_position = env.source_position;
3951 entity->base.source_position = specifiers->source_position;
3953 entity->base.namespc = NAMESPACE_NORMAL;
3954 entity->declaration.type = orig_type;
3955 entity->declaration.alignment = get_type_alignment(orig_type);
3956 entity->declaration.modifiers = env.modifiers;
3957 entity->declaration.attributes = attributes;
3959 storage_class_t storage_class = specifiers->storage_class;
3960 entity->declaration.declared_storage_class = storage_class;
3962 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3963 storage_class = STORAGE_CLASS_AUTO;
3964 entity->declaration.storage_class = storage_class;
3967 if (attributes != NULL) {
3968 handle_entity_attributes(attributes, entity);
3974 static type_t *parse_abstract_declarator(type_t *base_type)
3976 parse_declarator_env_t env;
3977 memset(&env, 0, sizeof(env));
3978 env.may_be_abstract = true;
3979 env.must_be_abstract = true;
3981 construct_type_t *construct_type = parse_inner_declarator(&env);
3983 type_t *result = construct_declarator_type(construct_type, base_type);
3984 if (construct_type != NULL) {
3985 obstack_free(&temp_obst, construct_type);
3987 result = handle_type_attributes(env.attributes, result);
3993 * Check if the declaration of main is suspicious. main should be a
3994 * function with external linkage, returning int, taking either zero
3995 * arguments, two, or three arguments of appropriate types, ie.
3997 * int main([ int argc, char **argv [, char **env ] ]).
3999 * @param decl the declaration to check
4000 * @param type the function type of the declaration
4002 static void check_main(const entity_t *entity)
4004 const source_position_t *pos = &entity->base.source_position;
4005 if (entity->kind != ENTITY_FUNCTION) {
4006 warningf(pos, "'main' is not a function");
4010 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4011 warningf(pos, "'main' is normally a non-static function");
4014 type_t *type = skip_typeref(entity->declaration.type);
4015 assert(is_type_function(type));
4017 function_type_t *func_type = &type->function;
4018 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4019 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4020 func_type->return_type);
4022 const function_parameter_t *parm = func_type->parameters;
4024 type_t *const first_type = parm->type;
4025 if (!types_compatible(skip_typeref(first_type), type_int)) {
4027 "first argument of 'main' should be 'int', but is '%T'",
4032 type_t *const second_type = parm->type;
4033 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4034 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4038 type_t *const third_type = parm->type;
4039 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4040 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4044 goto warn_arg_count;
4048 warningf(pos, "'main' takes only zero, two or three arguments");
4054 * Check if a symbol is the equal to "main".
4056 static bool is_sym_main(const symbol_t *const sym)
4058 return strcmp(sym->string, "main") == 0;
4061 static void error_redefined_as_different_kind(const source_position_t *pos,
4062 const entity_t *old, entity_kind_t new_kind)
4064 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4065 get_entity_kind_name(old->kind), old->base.symbol,
4066 get_entity_kind_name(new_kind), &old->base.source_position);
4069 static bool is_error_entity(entity_t *const ent)
4071 if (is_declaration(ent)) {
4072 return is_type_valid(skip_typeref(ent->declaration.type));
4073 } else if (ent->kind == ENTITY_TYPEDEF) {
4074 return is_type_valid(skip_typeref(ent->typedefe.type));
4079 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4081 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4082 if (attributes_equal(tattr, attr))
4089 * test wether new_list contains any attributes not included in old_list
4091 static bool has_new_attributes(const attribute_t *old_list,
4092 const attribute_t *new_list)
4094 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4095 if (!contains_attribute(old_list, attr))
4102 * Merge in attributes from an attribute list (probably from a previous
4103 * declaration with the same name). Warning: destroys the old structure
4104 * of the attribute list - don't reuse attributes after this call.
4106 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4109 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4111 if (contains_attribute(decl->attributes, attr))
4114 /* move attribute to new declarations attributes list */
4115 attr->next = decl->attributes;
4116 decl->attributes = attr;
4121 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4122 * for various problems that occur for multiple definitions
4124 entity_t *record_entity(entity_t *entity, const bool is_definition)
4126 const symbol_t *const symbol = entity->base.symbol;
4127 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4128 const source_position_t *pos = &entity->base.source_position;
4130 /* can happen in error cases */
4134 entity_t *const previous_entity = get_entity(symbol, namespc);
4135 /* pushing the same entity twice will break the stack structure */
4136 assert(previous_entity != entity);
4138 if (entity->kind == ENTITY_FUNCTION) {
4139 type_t *const orig_type = entity->declaration.type;
4140 type_t *const type = skip_typeref(orig_type);
4142 assert(is_type_function(type));
4143 if (type->function.unspecified_parameters &&
4144 warning.strict_prototypes &&
4145 previous_entity == NULL) {
4146 warningf(pos, "function declaration '%#T' is not a prototype",
4150 if (warning.main && current_scope == file_scope
4151 && is_sym_main(symbol)) {
4156 if (is_declaration(entity) &&
4157 warning.nested_externs &&
4158 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4159 current_scope != file_scope) {
4160 warningf(pos, "nested extern declaration of '%#T'",
4161 entity->declaration.type, symbol);
4164 if (previous_entity != NULL) {
4165 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4166 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4167 assert(previous_entity->kind == ENTITY_PARAMETER);
4169 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4170 entity->declaration.type, symbol,
4171 previous_entity->declaration.type, symbol,
4172 &previous_entity->base.source_position);
4176 if (previous_entity->base.parent_scope == current_scope) {
4177 if (previous_entity->kind != entity->kind) {
4178 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4179 error_redefined_as_different_kind(pos, previous_entity,
4184 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4185 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4186 symbol, &previous_entity->base.source_position);
4189 if (previous_entity->kind == ENTITY_TYPEDEF) {
4190 /* TODO: C++ allows this for exactly the same type */
4191 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4192 symbol, &previous_entity->base.source_position);
4196 /* at this point we should have only VARIABLES or FUNCTIONS */
4197 assert(is_declaration(previous_entity) && is_declaration(entity));
4199 declaration_t *const prev_decl = &previous_entity->declaration;
4200 declaration_t *const decl = &entity->declaration;
4202 /* can happen for K&R style declarations */
4203 if (prev_decl->type == NULL &&
4204 previous_entity->kind == ENTITY_PARAMETER &&
4205 entity->kind == ENTITY_PARAMETER) {
4206 prev_decl->type = decl->type;
4207 prev_decl->storage_class = decl->storage_class;
4208 prev_decl->declared_storage_class = decl->declared_storage_class;
4209 prev_decl->modifiers = decl->modifiers;
4210 return previous_entity;
4213 type_t *const orig_type = decl->type;
4214 assert(orig_type != NULL);
4215 type_t *const type = skip_typeref(orig_type);
4216 type_t *const prev_type = skip_typeref(prev_decl->type);
4218 if (!types_compatible(type, prev_type)) {
4220 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4221 orig_type, symbol, prev_decl->type, symbol,
4222 &previous_entity->base.source_position);
4224 unsigned old_storage_class = prev_decl->storage_class;
4226 if (warning.redundant_decls &&
4229 !(prev_decl->modifiers & DM_USED) &&
4230 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4231 warningf(&previous_entity->base.source_position,
4232 "unnecessary static forward declaration for '%#T'",
4233 prev_decl->type, symbol);
4236 storage_class_t new_storage_class = decl->storage_class;
4238 /* pretend no storage class means extern for function
4239 * declarations (except if the previous declaration is neither
4240 * none nor extern) */
4241 if (entity->kind == ENTITY_FUNCTION) {
4242 /* the previous declaration could have unspecified parameters or
4243 * be a typedef, so use the new type */
4244 if (prev_type->function.unspecified_parameters || is_definition)
4245 prev_decl->type = type;
4247 switch (old_storage_class) {
4248 case STORAGE_CLASS_NONE:
4249 old_storage_class = STORAGE_CLASS_EXTERN;
4252 case STORAGE_CLASS_EXTERN:
4253 if (is_definition) {
4254 if (warning.missing_prototypes &&
4255 prev_type->function.unspecified_parameters &&
4256 !is_sym_main(symbol)) {
4257 warningf(pos, "no previous prototype for '%#T'",
4260 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4261 new_storage_class = STORAGE_CLASS_EXTERN;
4268 } else if (is_type_incomplete(prev_type)) {
4269 prev_decl->type = type;
4272 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4273 new_storage_class == STORAGE_CLASS_EXTERN) {
4275 warn_redundant_declaration: ;
4277 = has_new_attributes(prev_decl->attributes,
4279 if (has_new_attrs) {
4280 merge_in_attributes(decl, prev_decl->attributes);
4281 } else if (!is_definition &&
4282 warning.redundant_decls &&
4283 is_type_valid(prev_type) &&
4284 strcmp(previous_entity->base.source_position.input_name,
4285 "<builtin>") != 0) {
4287 "redundant declaration for '%Y' (declared %P)",
4288 symbol, &previous_entity->base.source_position);
4290 } else if (current_function == NULL) {
4291 if (old_storage_class != STORAGE_CLASS_STATIC &&
4292 new_storage_class == STORAGE_CLASS_STATIC) {
4294 "static declaration of '%Y' follows non-static declaration (declared %P)",
4295 symbol, &previous_entity->base.source_position);
4296 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4297 prev_decl->storage_class = STORAGE_CLASS_NONE;
4298 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4300 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4302 goto error_redeclaration;
4303 goto warn_redundant_declaration;
4305 } else if (is_type_valid(prev_type)) {
4306 if (old_storage_class == new_storage_class) {
4307 error_redeclaration:
4308 errorf(pos, "redeclaration of '%Y' (declared %P)",
4309 symbol, &previous_entity->base.source_position);
4312 "redeclaration of '%Y' with different linkage (declared %P)",
4313 symbol, &previous_entity->base.source_position);
4318 prev_decl->modifiers |= decl->modifiers;
4319 if (entity->kind == ENTITY_FUNCTION) {
4320 previous_entity->function.is_inline |= entity->function.is_inline;
4322 return previous_entity;
4325 if (warning.shadow) {
4326 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4327 get_entity_kind_name(entity->kind), symbol,
4328 get_entity_kind_name(previous_entity->kind),
4329 &previous_entity->base.source_position);
4333 if (entity->kind == ENTITY_FUNCTION) {
4334 if (is_definition &&
4335 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4336 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4337 warningf(pos, "no previous prototype for '%#T'",
4338 entity->declaration.type, symbol);
4339 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4340 warningf(pos, "no previous declaration for '%#T'",
4341 entity->declaration.type, symbol);
4344 } else if (warning.missing_declarations &&
4345 entity->kind == ENTITY_VARIABLE &&
4346 current_scope == file_scope) {
4347 declaration_t *declaration = &entity->declaration;
4348 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4349 warningf(pos, "no previous declaration for '%#T'",
4350 declaration->type, symbol);
4355 assert(entity->base.parent_scope == NULL);
4356 assert(current_scope != NULL);
4358 entity->base.parent_scope = current_scope;
4359 entity->base.namespc = NAMESPACE_NORMAL;
4360 environment_push(entity);
4361 append_entity(current_scope, entity);
4366 static void parser_error_multiple_definition(entity_t *entity,
4367 const source_position_t *source_position)
4369 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4370 entity->base.symbol, &entity->base.source_position);
4373 static bool is_declaration_specifier(const token_t *token,
4374 bool only_specifiers_qualifiers)
4376 switch (token->type) {
4381 return is_typedef_symbol(token->v.symbol);
4383 case T___extension__:
4385 return !only_specifiers_qualifiers;
4392 static void parse_init_declarator_rest(entity_t *entity)
4394 assert(is_declaration(entity));
4395 declaration_t *const declaration = &entity->declaration;
4399 type_t *orig_type = declaration->type;
4400 type_t *type = skip_typeref(orig_type);
4402 if (entity->kind == ENTITY_VARIABLE
4403 && entity->variable.initializer != NULL) {
4404 parser_error_multiple_definition(entity, HERE);
4407 bool must_be_constant = false;
4408 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4409 entity->base.parent_scope == file_scope) {
4410 must_be_constant = true;
4413 if (is_type_function(type)) {
4414 errorf(&entity->base.source_position,
4415 "function '%#T' is initialized like a variable",
4416 orig_type, entity->base.symbol);
4417 orig_type = type_error_type;
4420 parse_initializer_env_t env;
4421 env.type = orig_type;
4422 env.must_be_constant = must_be_constant;
4423 env.entity = entity;
4424 current_init_decl = entity;
4426 initializer_t *initializer = parse_initializer(&env);
4427 current_init_decl = NULL;
4429 if (entity->kind == ENTITY_VARIABLE) {
4430 /* §6.7.5:22 array initializers for arrays with unknown size
4431 * determine the array type size */
4432 declaration->type = env.type;
4433 entity->variable.initializer = initializer;
4437 /* parse rest of a declaration without any declarator */
4438 static void parse_anonymous_declaration_rest(
4439 const declaration_specifiers_t *specifiers)
4442 anonymous_entity = NULL;
4444 if (warning.other) {
4445 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4446 specifiers->thread_local) {
4447 warningf(&specifiers->source_position,
4448 "useless storage class in empty declaration");
4451 type_t *type = specifiers->type;
4452 switch (type->kind) {
4453 case TYPE_COMPOUND_STRUCT:
4454 case TYPE_COMPOUND_UNION: {
4455 if (type->compound.compound->base.symbol == NULL) {
4456 warningf(&specifiers->source_position,
4457 "unnamed struct/union that defines no instances");
4466 warningf(&specifiers->source_position, "empty declaration");
4472 static void check_variable_type_complete(entity_t *ent)
4474 if (ent->kind != ENTITY_VARIABLE)
4477 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4478 * type for the object shall be complete [...] */
4479 declaration_t *decl = &ent->declaration;
4480 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4481 decl->storage_class == STORAGE_CLASS_STATIC)
4484 type_t *const orig_type = decl->type;
4485 type_t *const type = skip_typeref(orig_type);
4486 if (!is_type_incomplete(type))
4489 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4490 * are given length one. */
4491 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4492 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4496 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4497 orig_type, ent->base.symbol);
4501 static void parse_declaration_rest(entity_t *ndeclaration,
4502 const declaration_specifiers_t *specifiers,
4503 parsed_declaration_func finished_declaration,
4504 declarator_flags_t flags)
4506 add_anchor_token(';');
4507 add_anchor_token(',');
4509 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4511 if (token.type == '=') {
4512 parse_init_declarator_rest(entity);
4513 } else if (entity->kind == ENTITY_VARIABLE) {
4514 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4515 * [...] where the extern specifier is explicitly used. */
4516 declaration_t *decl = &entity->declaration;
4517 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4518 type_t *type = decl->type;
4519 if (is_type_reference(skip_typeref(type))) {
4520 errorf(&entity->base.source_position,
4521 "reference '%#T' must be initialized",
4522 type, entity->base.symbol);
4527 check_variable_type_complete(entity);
4532 add_anchor_token('=');
4533 ndeclaration = parse_declarator(specifiers, flags);
4534 rem_anchor_token('=');
4536 expect(';', end_error);
4539 anonymous_entity = NULL;
4540 rem_anchor_token(';');
4541 rem_anchor_token(',');
4544 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4546 symbol_t *symbol = entity->base.symbol;
4547 if (symbol == NULL) {
4548 errorf(HERE, "anonymous declaration not valid as function parameter");
4552 assert(entity->base.namespc == NAMESPACE_NORMAL);
4553 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4554 if (previous_entity == NULL
4555 || previous_entity->base.parent_scope != current_scope) {
4556 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4561 if (is_definition) {
4562 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4565 return record_entity(entity, false);
4568 static void parse_declaration(parsed_declaration_func finished_declaration,
4569 declarator_flags_t flags)
4571 declaration_specifiers_t specifiers;
4572 memset(&specifiers, 0, sizeof(specifiers));
4574 add_anchor_token(';');
4575 parse_declaration_specifiers(&specifiers);
4576 rem_anchor_token(';');
4578 if (token.type == ';') {
4579 parse_anonymous_declaration_rest(&specifiers);
4581 entity_t *entity = parse_declarator(&specifiers, flags);
4582 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4587 static type_t *get_default_promoted_type(type_t *orig_type)
4589 type_t *result = orig_type;
4591 type_t *type = skip_typeref(orig_type);
4592 if (is_type_integer(type)) {
4593 result = promote_integer(type);
4594 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4595 result = type_double;
4601 static void parse_kr_declaration_list(entity_t *entity)
4603 if (entity->kind != ENTITY_FUNCTION)
4606 type_t *type = skip_typeref(entity->declaration.type);
4607 assert(is_type_function(type));
4608 if (!type->function.kr_style_parameters)
4611 add_anchor_token('{');
4613 /* push function parameters */
4614 size_t const top = environment_top();
4615 scope_t *old_scope = scope_push(&entity->function.parameters);
4617 entity_t *parameter = entity->function.parameters.entities;
4618 for ( ; parameter != NULL; parameter = parameter->base.next) {
4619 assert(parameter->base.parent_scope == NULL);
4620 parameter->base.parent_scope = current_scope;
4621 environment_push(parameter);
4624 /* parse declaration list */
4626 switch (token.type) {
4628 case T___extension__:
4629 /* This covers symbols, which are no type, too, and results in
4630 * better error messages. The typical cases are misspelled type
4631 * names and missing includes. */
4633 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4641 /* pop function parameters */
4642 assert(current_scope == &entity->function.parameters);
4643 scope_pop(old_scope);
4644 environment_pop_to(top);
4646 /* update function type */
4647 type_t *new_type = duplicate_type(type);
4649 function_parameter_t *parameters = NULL;
4650 function_parameter_t **anchor = ¶meters;
4652 /* did we have an earlier prototype? */
4653 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4654 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4657 function_parameter_t *proto_parameter = NULL;
4658 if (proto_type != NULL) {
4659 type_t *proto_type_type = proto_type->declaration.type;
4660 proto_parameter = proto_type_type->function.parameters;
4661 /* If a K&R function definition has a variadic prototype earlier, then
4662 * make the function definition variadic, too. This should conform to
4663 * §6.7.5.3:15 and §6.9.1:8. */
4664 new_type->function.variadic = proto_type_type->function.variadic;
4666 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4668 new_type->function.unspecified_parameters = true;
4671 bool need_incompatible_warning = false;
4672 parameter = entity->function.parameters.entities;
4673 for (; parameter != NULL; parameter = parameter->base.next,
4675 proto_parameter == NULL ? NULL : proto_parameter->next) {
4676 if (parameter->kind != ENTITY_PARAMETER)
4679 type_t *parameter_type = parameter->declaration.type;
4680 if (parameter_type == NULL) {
4682 errorf(HERE, "no type specified for function parameter '%Y'",
4683 parameter->base.symbol);
4684 parameter_type = type_error_type;
4686 if (warning.implicit_int) {
4687 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4688 parameter->base.symbol);
4690 parameter_type = type_int;
4692 parameter->declaration.type = parameter_type;
4695 semantic_parameter_incomplete(parameter);
4697 /* we need the default promoted types for the function type */
4698 type_t *not_promoted = parameter_type;
4699 parameter_type = get_default_promoted_type(parameter_type);
4701 /* gcc special: if the type of the prototype matches the unpromoted
4702 * type don't promote */
4703 if (!strict_mode && proto_parameter != NULL) {
4704 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4705 type_t *promo_skip = skip_typeref(parameter_type);
4706 type_t *param_skip = skip_typeref(not_promoted);
4707 if (!types_compatible(proto_p_type, promo_skip)
4708 && types_compatible(proto_p_type, param_skip)) {
4710 need_incompatible_warning = true;
4711 parameter_type = not_promoted;
4714 function_parameter_t *const parameter
4715 = allocate_parameter(parameter_type);
4717 *anchor = parameter;
4718 anchor = ¶meter->next;
4721 new_type->function.parameters = parameters;
4722 new_type = identify_new_type(new_type);
4724 if (warning.other && need_incompatible_warning) {
4725 type_t *proto_type_type = proto_type->declaration.type;
4727 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4728 proto_type_type, proto_type->base.symbol,
4729 new_type, entity->base.symbol,
4730 &proto_type->base.source_position);
4733 entity->declaration.type = new_type;
4735 rem_anchor_token('{');
4738 static bool first_err = true;
4741 * When called with first_err set, prints the name of the current function,
4744 static void print_in_function(void)
4748 diagnosticf("%s: In function '%Y':\n",
4749 current_function->base.base.source_position.input_name,
4750 current_function->base.base.symbol);
4755 * Check if all labels are defined in the current function.
4756 * Check if all labels are used in the current function.
4758 static void check_labels(void)
4760 for (const goto_statement_t *goto_statement = goto_first;
4761 goto_statement != NULL;
4762 goto_statement = goto_statement->next) {
4763 /* skip computed gotos */
4764 if (goto_statement->expression != NULL)
4767 label_t *label = goto_statement->label;
4770 if (label->base.source_position.input_name == NULL) {
4771 print_in_function();
4772 errorf(&goto_statement->base.source_position,
4773 "label '%Y' used but not defined", label->base.symbol);
4777 if (warning.unused_label) {
4778 for (const label_statement_t *label_statement = label_first;
4779 label_statement != NULL;
4780 label_statement = label_statement->next) {
4781 label_t *label = label_statement->label;
4783 if (! label->used) {
4784 print_in_function();
4785 warningf(&label_statement->base.source_position,
4786 "label '%Y' defined but not used", label->base.symbol);
4792 static void warn_unused_entity(entity_t *entity, entity_t *last)
4794 entity_t const *const end = last != NULL ? last->base.next : NULL;
4795 for (; entity != end; entity = entity->base.next) {
4796 if (!is_declaration(entity))
4799 declaration_t *declaration = &entity->declaration;
4800 if (declaration->implicit)
4803 if (!declaration->used) {
4804 print_in_function();
4805 const char *what = get_entity_kind_name(entity->kind);
4806 warningf(&entity->base.source_position, "%s '%Y' is unused",
4807 what, entity->base.symbol);
4808 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4809 print_in_function();
4810 const char *what = get_entity_kind_name(entity->kind);
4811 warningf(&entity->base.source_position, "%s '%Y' is never read",
4812 what, entity->base.symbol);
4817 static void check_unused_variables(statement_t *const stmt, void *const env)
4821 switch (stmt->kind) {
4822 case STATEMENT_DECLARATION: {
4823 declaration_statement_t const *const decls = &stmt->declaration;
4824 warn_unused_entity(decls->declarations_begin,
4825 decls->declarations_end);
4830 warn_unused_entity(stmt->fors.scope.entities, NULL);
4839 * Check declarations of current_function for unused entities.
4841 static void check_declarations(void)
4843 if (warning.unused_parameter) {
4844 const scope_t *scope = ¤t_function->parameters;
4846 /* do not issue unused warnings for main */
4847 if (!is_sym_main(current_function->base.base.symbol)) {
4848 warn_unused_entity(scope->entities, NULL);
4851 if (warning.unused_variable) {
4852 walk_statements(current_function->statement, check_unused_variables,
4857 static int determine_truth(expression_t const* const cond)
4860 !is_constant_expression(cond) ? 0 :
4861 fold_constant_to_bool(cond) ? 1 :
4865 static void check_reachable(statement_t *);
4866 static bool reaches_end;
4868 static bool expression_returns(expression_t const *const expr)
4870 switch (expr->kind) {
4872 expression_t const *const func = expr->call.function;
4873 if (func->kind == EXPR_REFERENCE) {
4874 entity_t *entity = func->reference.entity;
4875 if (entity->kind == ENTITY_FUNCTION
4876 && entity->declaration.modifiers & DM_NORETURN)
4880 if (!expression_returns(func))
4883 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4884 if (!expression_returns(arg->expression))
4891 case EXPR_REFERENCE:
4892 case EXPR_REFERENCE_ENUM_VALUE:
4894 case EXPR_CHARACTER_CONSTANT:
4895 case EXPR_WIDE_CHARACTER_CONSTANT:
4896 case EXPR_STRING_LITERAL:
4897 case EXPR_WIDE_STRING_LITERAL:
4898 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4899 case EXPR_LABEL_ADDRESS:
4900 case EXPR_CLASSIFY_TYPE:
4901 case EXPR_SIZEOF: // TODO handle obscure VLA case
4904 case EXPR_BUILTIN_CONSTANT_P:
4905 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4910 case EXPR_STATEMENT: {
4911 bool old_reaches_end = reaches_end;
4912 reaches_end = false;
4913 check_reachable(expr->statement.statement);
4914 bool returns = reaches_end;
4915 reaches_end = old_reaches_end;
4919 case EXPR_CONDITIONAL:
4920 // TODO handle constant expression
4922 if (!expression_returns(expr->conditional.condition))
4925 if (expr->conditional.true_expression != NULL
4926 && expression_returns(expr->conditional.true_expression))
4929 return expression_returns(expr->conditional.false_expression);
4932 return expression_returns(expr->select.compound);
4934 case EXPR_ARRAY_ACCESS:
4936 expression_returns(expr->array_access.array_ref) &&
4937 expression_returns(expr->array_access.index);
4940 return expression_returns(expr->va_starte.ap);
4943 return expression_returns(expr->va_arge.ap);
4946 return expression_returns(expr->va_copye.src);
4948 EXPR_UNARY_CASES_MANDATORY
4949 return expression_returns(expr->unary.value);
4951 case EXPR_UNARY_THROW:
4955 // TODO handle constant lhs of && and ||
4957 expression_returns(expr->binary.left) &&
4958 expression_returns(expr->binary.right);
4964 panic("unhandled expression");
4967 static bool initializer_returns(initializer_t const *const init)
4969 switch (init->kind) {
4970 case INITIALIZER_VALUE:
4971 return expression_returns(init->value.value);
4973 case INITIALIZER_LIST: {
4974 initializer_t * const* i = init->list.initializers;
4975 initializer_t * const* const end = i + init->list.len;
4976 bool returns = true;
4977 for (; i != end; ++i) {
4978 if (!initializer_returns(*i))
4984 case INITIALIZER_STRING:
4985 case INITIALIZER_WIDE_STRING:
4986 case INITIALIZER_DESIGNATOR: // designators have no payload
4989 panic("unhandled initializer");
4992 static bool noreturn_candidate;
4994 static void check_reachable(statement_t *const stmt)
4996 if (stmt->base.reachable)
4998 if (stmt->kind != STATEMENT_DO_WHILE)
4999 stmt->base.reachable = true;
5001 statement_t *last = stmt;
5003 switch (stmt->kind) {
5004 case STATEMENT_INVALID:
5005 case STATEMENT_EMPTY:
5007 next = stmt->base.next;
5010 case STATEMENT_DECLARATION: {
5011 declaration_statement_t const *const decl = &stmt->declaration;
5012 entity_t const * ent = decl->declarations_begin;
5013 entity_t const *const last = decl->declarations_end;
5015 for (;; ent = ent->base.next) {
5016 if (ent->kind == ENTITY_VARIABLE &&
5017 ent->variable.initializer != NULL &&
5018 !initializer_returns(ent->variable.initializer)) {
5025 next = stmt->base.next;
5029 case STATEMENT_COMPOUND:
5030 next = stmt->compound.statements;
5032 next = stmt->base.next;
5035 case STATEMENT_RETURN: {
5036 expression_t const *const val = stmt->returns.value;
5037 if (val == NULL || expression_returns(val))
5038 noreturn_candidate = false;
5042 case STATEMENT_IF: {
5043 if_statement_t const *const ifs = &stmt->ifs;
5044 expression_t const *const cond = ifs->condition;
5046 if (!expression_returns(cond))
5049 int const val = determine_truth(cond);
5052 check_reachable(ifs->true_statement);
5057 if (ifs->false_statement != NULL) {
5058 check_reachable(ifs->false_statement);
5062 next = stmt->base.next;
5066 case STATEMENT_SWITCH: {
5067 switch_statement_t const *const switchs = &stmt->switchs;
5068 expression_t const *const expr = switchs->expression;
5070 if (!expression_returns(expr))
5073 if (is_constant_expression(expr)) {
5074 long const val = fold_constant_to_int(expr);
5075 case_label_statement_t * defaults = NULL;
5076 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5077 if (i->expression == NULL) {
5082 if (i->first_case <= val && val <= i->last_case) {
5083 check_reachable((statement_t*)i);
5088 if (defaults != NULL) {
5089 check_reachable((statement_t*)defaults);
5093 bool has_default = false;
5094 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5095 if (i->expression == NULL)
5098 check_reachable((statement_t*)i);
5105 next = stmt->base.next;
5109 case STATEMENT_EXPRESSION: {
5110 /* Check for noreturn function call */
5111 expression_t const *const expr = stmt->expression.expression;
5112 if (!expression_returns(expr))
5115 next = stmt->base.next;
5119 case STATEMENT_CONTINUE:
5120 for (statement_t *parent = stmt;;) {
5121 parent = parent->base.parent;
5122 if (parent == NULL) /* continue not within loop */
5126 switch (parent->kind) {
5127 case STATEMENT_WHILE: goto continue_while;
5128 case STATEMENT_DO_WHILE: goto continue_do_while;
5129 case STATEMENT_FOR: goto continue_for;
5135 case STATEMENT_BREAK:
5136 for (statement_t *parent = stmt;;) {
5137 parent = parent->base.parent;
5138 if (parent == NULL) /* break not within loop/switch */
5141 switch (parent->kind) {
5142 case STATEMENT_SWITCH:
5143 case STATEMENT_WHILE:
5144 case STATEMENT_DO_WHILE:
5147 next = parent->base.next;
5148 goto found_break_parent;
5156 case STATEMENT_GOTO:
5157 if (stmt->gotos.expression) {
5158 if (!expression_returns(stmt->gotos.expression))
5161 statement_t *parent = stmt->base.parent;
5162 if (parent == NULL) /* top level goto */
5166 next = stmt->gotos.label->statement;
5167 if (next == NULL) /* missing label */
5172 case STATEMENT_LABEL:
5173 next = stmt->label.statement;
5176 case STATEMENT_CASE_LABEL:
5177 next = stmt->case_label.statement;
5180 case STATEMENT_WHILE: {
5181 while_statement_t const *const whiles = &stmt->whiles;
5182 expression_t const *const cond = whiles->condition;
5184 if (!expression_returns(cond))
5187 int const val = determine_truth(cond);
5190 check_reachable(whiles->body);
5195 next = stmt->base.next;
5199 case STATEMENT_DO_WHILE:
5200 next = stmt->do_while.body;
5203 case STATEMENT_FOR: {
5204 for_statement_t *const fors = &stmt->fors;
5206 if (fors->condition_reachable)
5208 fors->condition_reachable = true;
5210 expression_t const *const cond = fors->condition;
5215 } else if (expression_returns(cond)) {
5216 val = determine_truth(cond);
5222 check_reachable(fors->body);
5227 next = stmt->base.next;
5231 case STATEMENT_MS_TRY: {
5232 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5233 check_reachable(ms_try->try_statement);
5234 next = ms_try->final_statement;
5238 case STATEMENT_LEAVE: {
5239 statement_t *parent = stmt;
5241 parent = parent->base.parent;
5242 if (parent == NULL) /* __leave not within __try */
5245 if (parent->kind == STATEMENT_MS_TRY) {
5247 next = parent->ms_try.final_statement;
5255 panic("invalid statement kind");
5258 while (next == NULL) {
5259 next = last->base.parent;
5261 noreturn_candidate = false;
5263 type_t *const type = skip_typeref(current_function->base.type);
5264 assert(is_type_function(type));
5265 type_t *const ret = skip_typeref(type->function.return_type);
5266 if (warning.return_type &&
5267 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5268 is_type_valid(ret) &&
5269 !is_sym_main(current_function->base.base.symbol)) {
5270 warningf(&stmt->base.source_position,
5271 "control reaches end of non-void function");
5276 switch (next->kind) {
5277 case STATEMENT_INVALID:
5278 case STATEMENT_EMPTY:
5279 case STATEMENT_DECLARATION:
5280 case STATEMENT_EXPRESSION:
5282 case STATEMENT_RETURN:
5283 case STATEMENT_CONTINUE:
5284 case STATEMENT_BREAK:
5285 case STATEMENT_GOTO:
5286 case STATEMENT_LEAVE:
5287 panic("invalid control flow in function");
5289 case STATEMENT_COMPOUND:
5290 if (next->compound.stmt_expr) {
5296 case STATEMENT_SWITCH:
5297 case STATEMENT_LABEL:
5298 case STATEMENT_CASE_LABEL:
5300 next = next->base.next;
5303 case STATEMENT_WHILE: {
5305 if (next->base.reachable)
5307 next->base.reachable = true;
5309 while_statement_t const *const whiles = &next->whiles;
5310 expression_t const *const cond = whiles->condition;
5312 if (!expression_returns(cond))
5315 int const val = determine_truth(cond);
5318 check_reachable(whiles->body);
5324 next = next->base.next;
5328 case STATEMENT_DO_WHILE: {
5330 if (next->base.reachable)
5332 next->base.reachable = true;
5334 do_while_statement_t const *const dw = &next->do_while;
5335 expression_t const *const cond = dw->condition;
5337 if (!expression_returns(cond))
5340 int const val = determine_truth(cond);
5343 check_reachable(dw->body);
5349 next = next->base.next;
5353 case STATEMENT_FOR: {
5355 for_statement_t *const fors = &next->fors;
5357 fors->step_reachable = true;
5359 if (fors->condition_reachable)
5361 fors->condition_reachable = true;
5363 expression_t const *const cond = fors->condition;
5368 } else if (expression_returns(cond)) {
5369 val = determine_truth(cond);
5375 check_reachable(fors->body);
5381 next = next->base.next;
5385 case STATEMENT_MS_TRY:
5387 next = next->ms_try.final_statement;
5392 check_reachable(next);
5395 static void check_unreachable(statement_t* const stmt, void *const env)
5399 switch (stmt->kind) {
5400 case STATEMENT_DO_WHILE:
5401 if (!stmt->base.reachable) {
5402 expression_t const *const cond = stmt->do_while.condition;
5403 if (determine_truth(cond) >= 0) {
5404 warningf(&cond->base.source_position,
5405 "condition of do-while-loop is unreachable");
5410 case STATEMENT_FOR: {
5411 for_statement_t const* const fors = &stmt->fors;
5413 // if init and step are unreachable, cond is unreachable, too
5414 if (!stmt->base.reachable && !fors->step_reachable) {
5415 warningf(&stmt->base.source_position, "statement is unreachable");
5417 if (!stmt->base.reachable && fors->initialisation != NULL) {
5418 warningf(&fors->initialisation->base.source_position,
5419 "initialisation of for-statement is unreachable");
5422 if (!fors->condition_reachable && fors->condition != NULL) {
5423 warningf(&fors->condition->base.source_position,
5424 "condition of for-statement is unreachable");
5427 if (!fors->step_reachable && fors->step != NULL) {
5428 warningf(&fors->step->base.source_position,
5429 "step of for-statement is unreachable");
5435 case STATEMENT_COMPOUND:
5436 if (stmt->compound.statements != NULL)
5438 goto warn_unreachable;
5440 case STATEMENT_DECLARATION: {
5441 /* Only warn if there is at least one declarator with an initializer.
5442 * This typically occurs in switch statements. */
5443 declaration_statement_t const *const decl = &stmt->declaration;
5444 entity_t const * ent = decl->declarations_begin;
5445 entity_t const *const last = decl->declarations_end;
5447 for (;; ent = ent->base.next) {
5448 if (ent->kind == ENTITY_VARIABLE &&
5449 ent->variable.initializer != NULL) {
5450 goto warn_unreachable;
5460 if (!stmt->base.reachable)
5461 warningf(&stmt->base.source_position, "statement is unreachable");
5466 static void parse_external_declaration(void)
5468 /* function-definitions and declarations both start with declaration
5470 declaration_specifiers_t specifiers;
5471 memset(&specifiers, 0, sizeof(specifiers));
5473 add_anchor_token(';');
5474 parse_declaration_specifiers(&specifiers);
5475 rem_anchor_token(';');
5477 /* must be a declaration */
5478 if (token.type == ';') {
5479 parse_anonymous_declaration_rest(&specifiers);
5483 add_anchor_token(',');
5484 add_anchor_token('=');
5485 add_anchor_token(';');
5486 add_anchor_token('{');
5488 /* declarator is common to both function-definitions and declarations */
5489 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5491 rem_anchor_token('{');
5492 rem_anchor_token(';');
5493 rem_anchor_token('=');
5494 rem_anchor_token(',');
5496 /* must be a declaration */
5497 switch (token.type) {
5501 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5506 /* must be a function definition */
5507 parse_kr_declaration_list(ndeclaration);
5509 if (token.type != '{') {
5510 parse_error_expected("while parsing function definition", '{', NULL);
5511 eat_until_matching_token(';');
5515 assert(is_declaration(ndeclaration));
5516 type_t *const orig_type = ndeclaration->declaration.type;
5517 type_t * type = skip_typeref(orig_type);
5519 if (!is_type_function(type)) {
5520 if (is_type_valid(type)) {
5521 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5522 type, ndeclaration->base.symbol);
5526 } else if (is_typeref(orig_type)) {
5528 errorf(&ndeclaration->base.source_position,
5529 "type of function definition '%#T' is a typedef",
5530 orig_type, ndeclaration->base.symbol);
5533 if (warning.aggregate_return &&
5534 is_type_compound(skip_typeref(type->function.return_type))) {
5535 warningf(HERE, "function '%Y' returns an aggregate",
5536 ndeclaration->base.symbol);
5538 if (warning.traditional && !type->function.unspecified_parameters) {
5539 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5540 ndeclaration->base.symbol);
5542 if (warning.old_style_definition && type->function.unspecified_parameters) {
5543 warningf(HERE, "old-style function definition '%Y'",
5544 ndeclaration->base.symbol);
5547 /* §6.7.5.3:14 a function definition with () means no
5548 * parameters (and not unspecified parameters) */
5549 if (type->function.unspecified_parameters &&
5550 type->function.parameters == NULL) {
5551 type_t *copy = duplicate_type(type);
5552 copy->function.unspecified_parameters = false;
5553 type = identify_new_type(copy);
5555 ndeclaration->declaration.type = type;
5558 entity_t *const entity = record_entity(ndeclaration, true);
5559 assert(entity->kind == ENTITY_FUNCTION);
5560 assert(ndeclaration->kind == ENTITY_FUNCTION);
5562 function_t *function = &entity->function;
5563 if (ndeclaration != entity) {
5564 function->parameters = ndeclaration->function.parameters;
5566 assert(is_declaration(entity));
5567 type = skip_typeref(entity->declaration.type);
5569 /* push function parameters and switch scope */
5570 size_t const top = environment_top();
5571 scope_t *old_scope = scope_push(&function->parameters);
5573 entity_t *parameter = function->parameters.entities;
5574 for (; parameter != NULL; parameter = parameter->base.next) {
5575 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5576 parameter->base.parent_scope = current_scope;
5578 assert(parameter->base.parent_scope == NULL
5579 || parameter->base.parent_scope == current_scope);
5580 parameter->base.parent_scope = current_scope;
5581 if (parameter->base.symbol == NULL) {
5582 errorf(¶meter->base.source_position, "parameter name omitted");
5585 environment_push(parameter);
5588 if (function->statement != NULL) {
5589 parser_error_multiple_definition(entity, HERE);
5592 /* parse function body */
5593 int label_stack_top = label_top();
5594 function_t *old_current_function = current_function;
5595 entity_t *old_current_entity = current_entity;
5596 current_function = function;
5597 current_entity = (entity_t*) function;
5598 current_parent = NULL;
5601 goto_anchor = &goto_first;
5603 label_anchor = &label_first;
5605 statement_t *const body = parse_compound_statement(false);
5606 function->statement = body;
5609 check_declarations();
5610 if (warning.return_type ||
5611 warning.unreachable_code ||
5612 (warning.missing_noreturn
5613 && !(function->base.modifiers & DM_NORETURN))) {
5614 noreturn_candidate = true;
5615 check_reachable(body);
5616 if (warning.unreachable_code)
5617 walk_statements(body, check_unreachable, NULL);
5618 if (warning.missing_noreturn &&
5619 noreturn_candidate &&
5620 !(function->base.modifiers & DM_NORETURN)) {
5621 warningf(&body->base.source_position,
5622 "function '%#T' is candidate for attribute 'noreturn'",
5623 type, entity->base.symbol);
5627 assert(current_parent == NULL);
5628 assert(current_function == function);
5629 assert(current_entity == (entity_t*) function);
5630 current_entity = old_current_entity;
5631 current_function = old_current_function;
5632 label_pop_to(label_stack_top);
5635 assert(current_scope == &function->parameters);
5636 scope_pop(old_scope);
5637 environment_pop_to(top);
5640 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5641 source_position_t *source_position,
5642 const symbol_t *symbol)
5644 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5646 type->bitfield.base_type = base_type;
5647 type->bitfield.size_expression = size;
5650 type_t *skipped_type = skip_typeref(base_type);
5651 if (!is_type_integer(skipped_type)) {
5652 errorf(HERE, "bitfield base type '%T' is not an integer type",
5656 bit_size = get_type_size(base_type) * 8;
5659 if (is_constant_expression(size)) {
5660 long v = fold_constant_to_int(size);
5661 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5664 errorf(source_position, "negative width in bit-field '%Y'",
5666 } else if (v == 0 && symbol != NULL) {
5667 errorf(source_position, "zero width for bit-field '%Y'",
5669 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5670 errorf(source_position, "width of '%Y' exceeds its type",
5673 type->bitfield.bit_size = v;
5680 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5682 entity_t *iter = compound->members.entities;
5683 for (; iter != NULL; iter = iter->base.next) {
5684 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5687 if (iter->base.symbol == symbol) {
5689 } else if (iter->base.symbol == NULL) {
5690 /* search in anonymous structs and unions */
5691 type_t *type = skip_typeref(iter->declaration.type);
5692 if (is_type_compound(type)) {
5693 if (find_compound_entry(type->compound.compound, symbol)
5704 static void check_deprecated(const source_position_t *source_position,
5705 const entity_t *entity)
5707 if (!warning.deprecated_declarations)
5709 if (!is_declaration(entity))
5711 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5714 char const *const prefix = get_entity_kind_name(entity->kind);
5715 const char *deprecated_string
5716 = get_deprecated_string(entity->declaration.attributes);
5717 if (deprecated_string != NULL) {
5718 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5719 prefix, entity->base.symbol, &entity->base.source_position,
5722 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5723 entity->base.symbol, &entity->base.source_position);
5728 static expression_t *create_select(const source_position_t *pos,
5730 type_qualifiers_t qualifiers,
5733 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5735 check_deprecated(pos, entry);
5737 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5738 select->select.compound = addr;
5739 select->select.compound_entry = entry;
5741 type_t *entry_type = entry->declaration.type;
5742 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5744 /* we always do the auto-type conversions; the & and sizeof parser contains
5745 * code to revert this! */
5746 select->base.type = automatic_type_conversion(res_type);
5747 if (res_type->kind == TYPE_BITFIELD) {
5748 select->base.type = res_type->bitfield.base_type;
5755 * Find entry with symbol in compound. Search anonymous structs and unions and
5756 * creates implicit select expressions for them.
5757 * Returns the adress for the innermost compound.
5759 static expression_t *find_create_select(const source_position_t *pos,
5761 type_qualifiers_t qualifiers,
5762 compound_t *compound, symbol_t *symbol)
5764 entity_t *iter = compound->members.entities;
5765 for (; iter != NULL; iter = iter->base.next) {
5766 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5769 symbol_t *iter_symbol = iter->base.symbol;
5770 if (iter_symbol == NULL) {
5771 type_t *type = iter->declaration.type;
5772 if (type->kind != TYPE_COMPOUND_STRUCT
5773 && type->kind != TYPE_COMPOUND_UNION)
5776 compound_t *sub_compound = type->compound.compound;
5778 if (find_compound_entry(sub_compound, symbol) == NULL)
5781 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5782 sub_addr->base.source_position = *pos;
5783 sub_addr->select.implicit = true;
5784 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5788 if (iter_symbol == symbol) {
5789 return create_select(pos, addr, qualifiers, iter);
5796 static void parse_compound_declarators(compound_t *compound,
5797 const declaration_specifiers_t *specifiers)
5802 if (token.type == ':') {
5803 source_position_t source_position = *HERE;
5806 type_t *base_type = specifiers->type;
5807 expression_t *size = parse_constant_expression();
5809 type_t *type = make_bitfield_type(base_type, size,
5810 &source_position, NULL);
5812 attribute_t *attributes = parse_attributes(NULL);
5813 attribute_t **anchor = &attributes;
5814 while (*anchor != NULL)
5815 anchor = &(*anchor)->next;
5816 *anchor = specifiers->attributes;
5818 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5819 entity->base.namespc = NAMESPACE_NORMAL;
5820 entity->base.source_position = source_position;
5821 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5822 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5823 entity->declaration.type = type;
5824 entity->declaration.attributes = attributes;
5826 if (attributes != NULL) {
5827 handle_entity_attributes(attributes, entity);
5829 append_entity(&compound->members, entity);
5831 entity = parse_declarator(specifiers,
5832 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5833 if (entity->kind == ENTITY_TYPEDEF) {
5834 errorf(&entity->base.source_position,
5835 "typedef not allowed as compound member");
5837 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5839 /* make sure we don't define a symbol multiple times */
5840 symbol_t *symbol = entity->base.symbol;
5841 if (symbol != NULL) {
5842 entity_t *prev = find_compound_entry(compound, symbol);
5844 errorf(&entity->base.source_position,
5845 "multiple declarations of symbol '%Y' (declared %P)",
5846 symbol, &prev->base.source_position);
5850 if (token.type == ':') {
5851 source_position_t source_position = *HERE;
5853 expression_t *size = parse_constant_expression();
5855 type_t *type = entity->declaration.type;
5856 type_t *bitfield_type = make_bitfield_type(type, size,
5857 &source_position, entity->base.symbol);
5859 attribute_t *attributes = parse_attributes(NULL);
5860 entity->declaration.type = bitfield_type;
5861 handle_entity_attributes(attributes, entity);
5863 type_t *orig_type = entity->declaration.type;
5864 type_t *type = skip_typeref(orig_type);
5865 if (is_type_function(type)) {
5866 errorf(&entity->base.source_position,
5867 "compound member '%Y' must not have function type '%T'",
5868 entity->base.symbol, orig_type);
5869 } else if (is_type_incomplete(type)) {
5870 /* §6.7.2.1:16 flexible array member */
5871 if (!is_type_array(type) ||
5872 token.type != ';' ||
5873 look_ahead(1)->type != '}') {
5874 errorf(&entity->base.source_position,
5875 "compound member '%Y' has incomplete type '%T'",
5876 entity->base.symbol, orig_type);
5881 append_entity(&compound->members, entity);
5884 } while (next_if(','));
5885 expect(';', end_error);
5888 anonymous_entity = NULL;
5891 static void parse_compound_type_entries(compound_t *compound)
5894 add_anchor_token('}');
5896 while (token.type != '}') {
5897 if (token.type == T_EOF) {
5898 errorf(HERE, "EOF while parsing struct");
5901 declaration_specifiers_t specifiers;
5902 memset(&specifiers, 0, sizeof(specifiers));
5903 parse_declaration_specifiers(&specifiers);
5905 parse_compound_declarators(compound, &specifiers);
5907 rem_anchor_token('}');
5911 compound->complete = true;
5914 static type_t *parse_typename(void)
5916 declaration_specifiers_t specifiers;
5917 memset(&specifiers, 0, sizeof(specifiers));
5918 parse_declaration_specifiers(&specifiers);
5919 if (specifiers.storage_class != STORAGE_CLASS_NONE
5920 || specifiers.thread_local) {
5921 /* TODO: improve error message, user does probably not know what a
5922 * storage class is...
5924 errorf(HERE, "typename may not have a storage class");
5927 type_t *result = parse_abstract_declarator(specifiers.type);
5935 typedef expression_t* (*parse_expression_function)(void);
5936 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5938 typedef struct expression_parser_function_t expression_parser_function_t;
5939 struct expression_parser_function_t {
5940 parse_expression_function parser;
5941 precedence_t infix_precedence;
5942 parse_expression_infix_function infix_parser;
5945 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5948 * Prints an error message if an expression was expected but not read
5950 static expression_t *expected_expression_error(void)
5952 /* skip the error message if the error token was read */
5953 if (token.type != T_ERROR) {
5954 errorf(HERE, "expected expression, got token %K", &token);
5958 return create_invalid_expression();
5962 * Parse a string constant.
5964 static expression_t *parse_string_const(void)
5967 if (token.type == T_STRING_LITERAL) {
5968 string_t res = token.v.string;
5970 while (token.type == T_STRING_LITERAL) {
5971 res = concat_strings(&res, &token.v.string);
5974 if (token.type != T_WIDE_STRING_LITERAL) {
5975 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5976 /* note: that we use type_char_ptr here, which is already the
5977 * automatic converted type. revert_automatic_type_conversion
5978 * will construct the array type */
5979 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5980 cnst->string.value = res;
5984 wres = concat_string_wide_string(&res, &token.v.wide_string);
5986 wres = token.v.wide_string;
5991 switch (token.type) {
5992 case T_WIDE_STRING_LITERAL:
5993 wres = concat_wide_strings(&wres, &token.v.wide_string);
5996 case T_STRING_LITERAL:
5997 wres = concat_wide_string_string(&wres, &token.v.string);
6001 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6002 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6003 cnst->wide_string.value = wres;
6012 * Parse a boolean constant.
6014 static expression_t *parse_bool_const(bool value)
6016 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6017 cnst->base.type = type_bool;
6018 cnst->conste.v.int_value = value;
6026 * Parse an integer constant.
6028 static expression_t *parse_int_const(void)
6030 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6031 cnst->base.type = token.datatype;
6032 cnst->conste.v.int_value = token.v.intvalue;
6040 * Parse a character constant.
6042 static expression_t *parse_character_constant(void)
6044 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6045 cnst->base.type = token.datatype;
6046 cnst->conste.v.character = token.v.string;
6048 if (cnst->conste.v.character.size != 1) {
6050 errorf(HERE, "more than 1 character in character constant");
6051 } else if (warning.multichar) {
6052 warningf(HERE, "multi-character character constant");
6061 * Parse a wide character constant.
6063 static expression_t *parse_wide_character_constant(void)
6065 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6066 cnst->base.type = token.datatype;
6067 cnst->conste.v.wide_character = token.v.wide_string;
6069 if (cnst->conste.v.wide_character.size != 1) {
6071 errorf(HERE, "more than 1 character in character constant");
6072 } else if (warning.multichar) {
6073 warningf(HERE, "multi-character character constant");
6082 * Parse a float constant.
6084 static expression_t *parse_float_const(void)
6086 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6087 cnst->base.type = token.datatype;
6088 cnst->conste.v.float_value = token.v.floatvalue;
6095 static entity_t *create_implicit_function(symbol_t *symbol,
6096 const source_position_t *source_position)
6098 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6099 ntype->function.return_type = type_int;
6100 ntype->function.unspecified_parameters = true;
6101 ntype->function.linkage = LINKAGE_C;
6102 type_t *type = identify_new_type(ntype);
6104 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6105 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6106 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6107 entity->declaration.type = type;
6108 entity->declaration.implicit = true;
6109 entity->base.symbol = symbol;
6110 entity->base.source_position = *source_position;
6112 if (current_scope != NULL) {
6113 bool strict_prototypes_old = warning.strict_prototypes;
6114 warning.strict_prototypes = false;
6115 record_entity(entity, false);
6116 warning.strict_prototypes = strict_prototypes_old;
6123 * Performs automatic type cast as described in §6.3.2.1.
6125 * @param orig_type the original type
6127 static type_t *automatic_type_conversion(type_t *orig_type)
6129 type_t *type = skip_typeref(orig_type);
6130 if (is_type_array(type)) {
6131 array_type_t *array_type = &type->array;
6132 type_t *element_type = array_type->element_type;
6133 unsigned qualifiers = array_type->base.qualifiers;
6135 return make_pointer_type(element_type, qualifiers);
6138 if (is_type_function(type)) {
6139 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6146 * reverts the automatic casts of array to pointer types and function
6147 * to function-pointer types as defined §6.3.2.1
6149 type_t *revert_automatic_type_conversion(const expression_t *expression)
6151 switch (expression->kind) {
6152 case EXPR_REFERENCE: {
6153 entity_t *entity = expression->reference.entity;
6154 if (is_declaration(entity)) {
6155 return entity->declaration.type;
6156 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6157 return entity->enum_value.enum_type;
6159 panic("no declaration or enum in reference");
6164 entity_t *entity = expression->select.compound_entry;
6165 assert(is_declaration(entity));
6166 type_t *type = entity->declaration.type;
6167 return get_qualified_type(type,
6168 expression->base.type->base.qualifiers);
6171 case EXPR_UNARY_DEREFERENCE: {
6172 const expression_t *const value = expression->unary.value;
6173 type_t *const type = skip_typeref(value->base.type);
6174 if (!is_type_pointer(type))
6175 return type_error_type;
6176 return type->pointer.points_to;
6179 case EXPR_ARRAY_ACCESS: {
6180 const expression_t *array_ref = expression->array_access.array_ref;
6181 type_t *type_left = skip_typeref(array_ref->base.type);
6182 if (!is_type_pointer(type_left))
6183 return type_error_type;
6184 return type_left->pointer.points_to;
6187 case EXPR_STRING_LITERAL: {
6188 size_t size = expression->string.value.size;
6189 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6192 case EXPR_WIDE_STRING_LITERAL: {
6193 size_t size = expression->wide_string.value.size;
6194 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6197 case EXPR_COMPOUND_LITERAL:
6198 return expression->compound_literal.type;
6201 return expression->base.type;
6206 * Find an entity matching a symbol in a scope.
6207 * Uses current scope if scope is NULL
6209 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6210 namespace_tag_t namespc)
6212 if (scope == NULL) {
6213 return get_entity(symbol, namespc);
6216 /* we should optimize here, if scope grows above a certain size we should
6217 construct a hashmap here... */
6218 entity_t *entity = scope->entities;
6219 for ( ; entity != NULL; entity = entity->base.next) {
6220 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6227 static entity_t *parse_qualified_identifier(void)
6229 /* namespace containing the symbol */
6231 source_position_t pos;
6232 const scope_t *lookup_scope = NULL;
6234 if (next_if(T_COLONCOLON))
6235 lookup_scope = &unit->scope;
6239 if (token.type != T_IDENTIFIER) {
6240 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6241 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6243 symbol = token.v.symbol;
6248 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6250 if (!next_if(T_COLONCOLON))
6253 switch (entity->kind) {
6254 case ENTITY_NAMESPACE:
6255 lookup_scope = &entity->namespacee.members;
6260 lookup_scope = &entity->compound.members;
6263 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6264 symbol, get_entity_kind_name(entity->kind));
6269 if (entity == NULL) {
6270 if (!strict_mode && token.type == '(') {
6271 /* an implicitly declared function */
6272 if (warning.error_implicit_function_declaration) {
6273 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6274 } else if (warning.implicit_function_declaration) {
6275 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6278 entity = create_implicit_function(symbol, &pos);
6280 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6281 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6288 /* skip further qualifications */
6289 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6291 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6294 static expression_t *parse_reference(void)
6296 entity_t *entity = parse_qualified_identifier();
6299 if (is_declaration(entity)) {
6300 orig_type = entity->declaration.type;
6301 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6302 orig_type = entity->enum_value.enum_type;
6304 panic("expected declaration or enum value in reference");
6307 /* we always do the auto-type conversions; the & and sizeof parser contains
6308 * code to revert this! */
6309 type_t *type = automatic_type_conversion(orig_type);
6311 expression_kind_t kind = EXPR_REFERENCE;
6312 if (entity->kind == ENTITY_ENUM_VALUE)
6313 kind = EXPR_REFERENCE_ENUM_VALUE;
6315 expression_t *expression = allocate_expression_zero(kind);
6316 expression->reference.entity = entity;
6317 expression->base.type = type;
6319 /* this declaration is used */
6320 if (is_declaration(entity)) {
6321 entity->declaration.used = true;
6324 if (entity->base.parent_scope != file_scope
6325 && (current_function != NULL
6326 && entity->base.parent_scope->depth < current_function->parameters.depth)
6327 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6328 if (entity->kind == ENTITY_VARIABLE) {
6329 /* access of a variable from an outer function */
6330 entity->variable.address_taken = true;
6331 } else if (entity->kind == ENTITY_PARAMETER) {
6332 entity->parameter.address_taken = true;
6334 current_function->need_closure = true;
6337 check_deprecated(HERE, entity);
6339 if (warning.init_self && entity == current_init_decl && !in_type_prop
6340 && entity->kind == ENTITY_VARIABLE) {
6341 current_init_decl = NULL;
6342 warningf(HERE, "variable '%#T' is initialized by itself",
6343 entity->declaration.type, entity->base.symbol);
6349 static bool semantic_cast(expression_t *cast)
6351 expression_t *expression = cast->unary.value;
6352 type_t *orig_dest_type = cast->base.type;
6353 type_t *orig_type_right = expression->base.type;
6354 type_t const *dst_type = skip_typeref(orig_dest_type);
6355 type_t const *src_type = skip_typeref(orig_type_right);
6356 source_position_t const *pos = &cast->base.source_position;
6358 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6359 if (dst_type == type_void)
6362 /* only integer and pointer can be casted to pointer */
6363 if (is_type_pointer(dst_type) &&
6364 !is_type_pointer(src_type) &&
6365 !is_type_integer(src_type) &&
6366 is_type_valid(src_type)) {
6367 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6371 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6372 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6376 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6377 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6381 if (warning.cast_qual &&
6382 is_type_pointer(src_type) &&
6383 is_type_pointer(dst_type)) {
6384 type_t *src = skip_typeref(src_type->pointer.points_to);
6385 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6386 unsigned missing_qualifiers =
6387 src->base.qualifiers & ~dst->base.qualifiers;
6388 if (missing_qualifiers != 0) {
6390 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6391 missing_qualifiers, orig_type_right);
6397 static expression_t *parse_compound_literal(type_t *type)
6399 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6401 parse_initializer_env_t env;
6404 env.must_be_constant = false;
6405 initializer_t *initializer = parse_initializer(&env);
6408 expression->compound_literal.initializer = initializer;
6409 expression->compound_literal.type = type;
6410 expression->base.type = automatic_type_conversion(type);
6416 * Parse a cast expression.
6418 static expression_t *parse_cast(void)
6420 add_anchor_token(')');
6422 source_position_t source_position = token.source_position;
6424 type_t *type = parse_typename();
6426 rem_anchor_token(')');
6427 expect(')', end_error);
6429 if (token.type == '{') {
6430 return parse_compound_literal(type);
6433 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6434 cast->base.source_position = source_position;
6436 expression_t *value = parse_sub_expression(PREC_CAST);
6437 cast->base.type = type;
6438 cast->unary.value = value;
6440 if (! semantic_cast(cast)) {
6441 /* TODO: record the error in the AST. else it is impossible to detect it */
6446 return create_invalid_expression();
6450 * Parse a statement expression.
6452 static expression_t *parse_statement_expression(void)
6454 add_anchor_token(')');
6456 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6458 statement_t *statement = parse_compound_statement(true);
6459 statement->compound.stmt_expr = true;
6460 expression->statement.statement = statement;
6462 /* find last statement and use its type */
6463 type_t *type = type_void;
6464 const statement_t *stmt = statement->compound.statements;
6466 while (stmt->base.next != NULL)
6467 stmt = stmt->base.next;
6469 if (stmt->kind == STATEMENT_EXPRESSION) {
6470 type = stmt->expression.expression->base.type;
6472 } else if (warning.other) {
6473 warningf(&expression->base.source_position, "empty statement expression ({})");
6475 expression->base.type = type;
6477 rem_anchor_token(')');
6478 expect(')', end_error);
6485 * Parse a parenthesized expression.
6487 static expression_t *parse_parenthesized_expression(void)
6491 switch (token.type) {
6493 /* gcc extension: a statement expression */
6494 return parse_statement_expression();
6498 return parse_cast();
6500 if (is_typedef_symbol(token.v.symbol)) {
6501 return parse_cast();
6505 add_anchor_token(')');
6506 expression_t *result = parse_expression();
6507 result->base.parenthesized = true;
6508 rem_anchor_token(')');
6509 expect(')', end_error);
6515 static expression_t *parse_function_keyword(void)
6519 if (current_function == NULL) {
6520 errorf(HERE, "'__func__' used outside of a function");
6523 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6524 expression->base.type = type_char_ptr;
6525 expression->funcname.kind = FUNCNAME_FUNCTION;
6532 static expression_t *parse_pretty_function_keyword(void)
6534 if (current_function == NULL) {
6535 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6538 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6539 expression->base.type = type_char_ptr;
6540 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6542 eat(T___PRETTY_FUNCTION__);
6547 static expression_t *parse_funcsig_keyword(void)
6549 if (current_function == NULL) {
6550 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6553 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6554 expression->base.type = type_char_ptr;
6555 expression->funcname.kind = FUNCNAME_FUNCSIG;
6562 static expression_t *parse_funcdname_keyword(void)
6564 if (current_function == NULL) {
6565 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6568 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6569 expression->base.type = type_char_ptr;
6570 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6572 eat(T___FUNCDNAME__);
6577 static designator_t *parse_designator(void)
6579 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6580 result->source_position = *HERE;
6582 if (token.type != T_IDENTIFIER) {
6583 parse_error_expected("while parsing member designator",
6584 T_IDENTIFIER, NULL);
6587 result->symbol = token.v.symbol;
6590 designator_t *last_designator = result;
6593 if (token.type != T_IDENTIFIER) {
6594 parse_error_expected("while parsing member designator",
6595 T_IDENTIFIER, NULL);
6598 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6599 designator->source_position = *HERE;
6600 designator->symbol = token.v.symbol;
6603 last_designator->next = designator;
6604 last_designator = designator;
6608 add_anchor_token(']');
6609 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6610 designator->source_position = *HERE;
6611 designator->array_index = parse_expression();
6612 rem_anchor_token(']');
6613 expect(']', end_error);
6614 if (designator->array_index == NULL) {
6618 last_designator->next = designator;
6619 last_designator = designator;
6631 * Parse the __builtin_offsetof() expression.
6633 static expression_t *parse_offsetof(void)
6635 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6636 expression->base.type = type_size_t;
6638 eat(T___builtin_offsetof);
6640 expect('(', end_error);
6641 add_anchor_token(',');
6642 type_t *type = parse_typename();
6643 rem_anchor_token(',');
6644 expect(',', end_error);
6645 add_anchor_token(')');
6646 designator_t *designator = parse_designator();
6647 rem_anchor_token(')');
6648 expect(')', end_error);
6650 expression->offsetofe.type = type;
6651 expression->offsetofe.designator = designator;
6654 memset(&path, 0, sizeof(path));
6655 path.top_type = type;
6656 path.path = NEW_ARR_F(type_path_entry_t, 0);
6658 descend_into_subtype(&path);
6660 if (!walk_designator(&path, designator, true)) {
6661 return create_invalid_expression();
6664 DEL_ARR_F(path.path);
6668 return create_invalid_expression();
6672 * Parses a _builtin_va_start() expression.
6674 static expression_t *parse_va_start(void)
6676 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6678 eat(T___builtin_va_start);
6680 expect('(', end_error);
6681 add_anchor_token(',');
6682 expression->va_starte.ap = parse_assignment_expression();
6683 rem_anchor_token(',');
6684 expect(',', end_error);
6685 expression_t *const expr = parse_assignment_expression();
6686 if (expr->kind == EXPR_REFERENCE) {
6687 entity_t *const entity = expr->reference.entity;
6688 if (!current_function->base.type->function.variadic) {
6689 errorf(&expr->base.source_position,
6690 "'va_start' used in non-variadic function");
6691 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6692 entity->base.next != NULL ||
6693 entity->kind != ENTITY_PARAMETER) {
6694 errorf(&expr->base.source_position,
6695 "second argument of 'va_start' must be last parameter of the current function");
6697 expression->va_starte.parameter = &entity->variable;
6699 expect(')', end_error);
6702 expect(')', end_error);
6704 return create_invalid_expression();
6708 * Parses a __builtin_va_arg() expression.
6710 static expression_t *parse_va_arg(void)
6712 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6714 eat(T___builtin_va_arg);
6716 expect('(', end_error);
6718 ap.expression = parse_assignment_expression();
6719 expression->va_arge.ap = ap.expression;
6720 check_call_argument(type_valist, &ap, 1);
6722 expect(',', end_error);
6723 expression->base.type = parse_typename();
6724 expect(')', end_error);
6728 return create_invalid_expression();
6732 * Parses a __builtin_va_copy() expression.
6734 static expression_t *parse_va_copy(void)
6736 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6738 eat(T___builtin_va_copy);
6740 expect('(', end_error);
6741 expression_t *dst = parse_assignment_expression();
6742 assign_error_t error = semantic_assign(type_valist, dst);
6743 report_assign_error(error, type_valist, dst, "call argument 1",
6744 &dst->base.source_position);
6745 expression->va_copye.dst = dst;
6747 expect(',', end_error);
6749 call_argument_t src;
6750 src.expression = parse_assignment_expression();
6751 check_call_argument(type_valist, &src, 2);
6752 expression->va_copye.src = src.expression;
6753 expect(')', end_error);
6757 return create_invalid_expression();
6761 * Parses a __builtin_constant_p() expression.
6763 static expression_t *parse_builtin_constant(void)
6765 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6767 eat(T___builtin_constant_p);
6769 expect('(', end_error);
6770 add_anchor_token(')');
6771 expression->builtin_constant.value = parse_assignment_expression();
6772 rem_anchor_token(')');
6773 expect(')', end_error);
6774 expression->base.type = type_int;
6778 return create_invalid_expression();
6782 * Parses a __builtin_types_compatible_p() expression.
6784 static expression_t *parse_builtin_types_compatible(void)
6786 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6788 eat(T___builtin_types_compatible_p);
6790 expect('(', end_error);
6791 add_anchor_token(')');
6792 add_anchor_token(',');
6793 expression->builtin_types_compatible.left = parse_typename();
6794 rem_anchor_token(',');
6795 expect(',', end_error);
6796 expression->builtin_types_compatible.right = parse_typename();
6797 rem_anchor_token(')');
6798 expect(')', end_error);
6799 expression->base.type = type_int;
6803 return create_invalid_expression();
6807 * Parses a __builtin_is_*() compare expression.
6809 static expression_t *parse_compare_builtin(void)
6811 expression_t *expression;
6813 switch (token.type) {
6814 case T___builtin_isgreater:
6815 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6817 case T___builtin_isgreaterequal:
6818 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6820 case T___builtin_isless:
6821 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6823 case T___builtin_islessequal:
6824 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6826 case T___builtin_islessgreater:
6827 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6829 case T___builtin_isunordered:
6830 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6833 internal_errorf(HERE, "invalid compare builtin found");
6835 expression->base.source_position = *HERE;
6838 expect('(', end_error);
6839 expression->binary.left = parse_assignment_expression();
6840 expect(',', end_error);
6841 expression->binary.right = parse_assignment_expression();
6842 expect(')', end_error);
6844 type_t *const orig_type_left = expression->binary.left->base.type;
6845 type_t *const orig_type_right = expression->binary.right->base.type;
6847 type_t *const type_left = skip_typeref(orig_type_left);
6848 type_t *const type_right = skip_typeref(orig_type_right);
6849 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6850 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6851 type_error_incompatible("invalid operands in comparison",
6852 &expression->base.source_position, orig_type_left, orig_type_right);
6855 semantic_comparison(&expression->binary);
6860 return create_invalid_expression();
6864 * Parses a MS assume() expression.
6866 static expression_t *parse_assume(void)
6868 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6872 expect('(', end_error);
6873 add_anchor_token(')');
6874 expression->unary.value = parse_assignment_expression();
6875 rem_anchor_token(')');
6876 expect(')', end_error);
6878 expression->base.type = type_void;
6881 return create_invalid_expression();
6885 * Return the declaration for a given label symbol or create a new one.
6887 * @param symbol the symbol of the label
6889 static label_t *get_label(symbol_t *symbol)
6892 assert(current_function != NULL);
6894 label = get_entity(symbol, NAMESPACE_LABEL);
6895 /* if we found a local label, we already created the declaration */
6896 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6897 if (label->base.parent_scope != current_scope) {
6898 assert(label->base.parent_scope->depth < current_scope->depth);
6899 current_function->goto_to_outer = true;
6901 return &label->label;
6904 label = get_entity(symbol, NAMESPACE_LABEL);
6905 /* if we found a label in the same function, then we already created the
6908 && label->base.parent_scope == ¤t_function->parameters) {
6909 return &label->label;
6912 /* otherwise we need to create a new one */
6913 label = allocate_entity_zero(ENTITY_LABEL);
6914 label->base.namespc = NAMESPACE_LABEL;
6915 label->base.symbol = symbol;
6919 return &label->label;
6923 * Parses a GNU && label address expression.
6925 static expression_t *parse_label_address(void)
6927 source_position_t source_position = token.source_position;
6929 if (token.type != T_IDENTIFIER) {
6930 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6933 symbol_t *symbol = token.v.symbol;
6936 label_t *label = get_label(symbol);
6938 label->address_taken = true;
6940 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6941 expression->base.source_position = source_position;
6943 /* label address is threaten as a void pointer */
6944 expression->base.type = type_void_ptr;
6945 expression->label_address.label = label;
6948 return create_invalid_expression();
6952 * Parse a microsoft __noop expression.
6954 static expression_t *parse_noop_expression(void)
6956 /* the result is a (int)0 */
6957 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6958 cnst->base.type = type_int;
6959 cnst->conste.v.int_value = 0;
6960 cnst->conste.is_ms_noop = true;
6964 if (token.type == '(') {
6965 /* parse arguments */
6967 add_anchor_token(')');
6968 add_anchor_token(',');
6970 if (token.type != ')') do {
6971 (void)parse_assignment_expression();
6972 } while (next_if(','));
6974 rem_anchor_token(',');
6975 rem_anchor_token(')');
6976 expect(')', end_error);
6983 * Parses a primary expression.
6985 static expression_t *parse_primary_expression(void)
6987 switch (token.type) {
6988 case T_false: return parse_bool_const(false);
6989 case T_true: return parse_bool_const(true);
6990 case T_INTEGER: return parse_int_const();
6991 case T_CHARACTER_CONSTANT: return parse_character_constant();
6992 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6993 case T_FLOATINGPOINT: return parse_float_const();
6994 case T_STRING_LITERAL:
6995 case T_WIDE_STRING_LITERAL: return parse_string_const();
6996 case T___FUNCTION__:
6997 case T___func__: return parse_function_keyword();
6998 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6999 case T___FUNCSIG__: return parse_funcsig_keyword();
7000 case T___FUNCDNAME__: return parse_funcdname_keyword();
7001 case T___builtin_offsetof: return parse_offsetof();
7002 case T___builtin_va_start: return parse_va_start();
7003 case T___builtin_va_arg: return parse_va_arg();
7004 case T___builtin_va_copy: return parse_va_copy();
7005 case T___builtin_isgreater:
7006 case T___builtin_isgreaterequal:
7007 case T___builtin_isless:
7008 case T___builtin_islessequal:
7009 case T___builtin_islessgreater:
7010 case T___builtin_isunordered: return parse_compare_builtin();
7011 case T___builtin_constant_p: return parse_builtin_constant();
7012 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7013 case T__assume: return parse_assume();
7016 return parse_label_address();
7019 case '(': return parse_parenthesized_expression();
7020 case T___noop: return parse_noop_expression();
7022 /* Gracefully handle type names while parsing expressions. */
7024 return parse_reference();
7026 if (!is_typedef_symbol(token.v.symbol)) {
7027 return parse_reference();
7031 source_position_t const pos = *HERE;
7032 type_t const *const type = parse_typename();
7033 errorf(&pos, "encountered type '%T' while parsing expression", type);
7034 return create_invalid_expression();
7038 errorf(HERE, "unexpected token %K, expected an expression", &token);
7039 return create_invalid_expression();
7043 * Check if the expression has the character type and issue a warning then.
7045 static void check_for_char_index_type(const expression_t *expression)
7047 type_t *const type = expression->base.type;
7048 const type_t *const base_type = skip_typeref(type);
7050 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7051 warning.char_subscripts) {
7052 warningf(&expression->base.source_position,
7053 "array subscript has type '%T'", type);
7057 static expression_t *parse_array_expression(expression_t *left)
7059 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7062 add_anchor_token(']');
7064 expression_t *inside = parse_expression();
7066 type_t *const orig_type_left = left->base.type;
7067 type_t *const orig_type_inside = inside->base.type;
7069 type_t *const type_left = skip_typeref(orig_type_left);
7070 type_t *const type_inside = skip_typeref(orig_type_inside);
7072 type_t *return_type;
7073 array_access_expression_t *array_access = &expression->array_access;
7074 if (is_type_pointer(type_left)) {
7075 return_type = type_left->pointer.points_to;
7076 array_access->array_ref = left;
7077 array_access->index = inside;
7078 check_for_char_index_type(inside);
7079 } else if (is_type_pointer(type_inside)) {
7080 return_type = type_inside->pointer.points_to;
7081 array_access->array_ref = inside;
7082 array_access->index = left;
7083 array_access->flipped = true;
7084 check_for_char_index_type(left);
7086 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7088 "array access on object with non-pointer types '%T', '%T'",
7089 orig_type_left, orig_type_inside);
7091 return_type = type_error_type;
7092 array_access->array_ref = left;
7093 array_access->index = inside;
7096 expression->base.type = automatic_type_conversion(return_type);
7098 rem_anchor_token(']');
7099 expect(']', end_error);
7104 static expression_t *parse_typeprop(expression_kind_t const kind)
7106 expression_t *tp_expression = allocate_expression_zero(kind);
7107 tp_expression->base.type = type_size_t;
7109 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7111 /* we only refer to a type property, mark this case */
7112 bool old = in_type_prop;
7113 in_type_prop = true;
7116 expression_t *expression;
7117 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7119 add_anchor_token(')');
7120 orig_type = parse_typename();
7121 rem_anchor_token(')');
7122 expect(')', end_error);
7124 if (token.type == '{') {
7125 /* It was not sizeof(type) after all. It is sizeof of an expression
7126 * starting with a compound literal */
7127 expression = parse_compound_literal(orig_type);
7128 goto typeprop_expression;
7131 expression = parse_sub_expression(PREC_UNARY);
7133 typeprop_expression:
7134 tp_expression->typeprop.tp_expression = expression;
7136 orig_type = revert_automatic_type_conversion(expression);
7137 expression->base.type = orig_type;
7140 tp_expression->typeprop.type = orig_type;
7141 type_t const* const type = skip_typeref(orig_type);
7142 char const* const wrong_type =
7143 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7144 is_type_incomplete(type) ? "incomplete" :
7145 type->kind == TYPE_FUNCTION ? "function designator" :
7146 type->kind == TYPE_BITFIELD ? "bitfield" :
7148 if (wrong_type != NULL) {
7149 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7150 errorf(&tp_expression->base.source_position,
7151 "operand of %s expression must not be of %s type '%T'",
7152 what, wrong_type, orig_type);
7157 return tp_expression;
7160 static expression_t *parse_sizeof(void)
7162 return parse_typeprop(EXPR_SIZEOF);
7165 static expression_t *parse_alignof(void)
7167 return parse_typeprop(EXPR_ALIGNOF);
7170 static expression_t *parse_select_expression(expression_t *addr)
7172 assert(token.type == '.' || token.type == T_MINUSGREATER);
7173 bool select_left_arrow = (token.type == T_MINUSGREATER);
7176 if (token.type != T_IDENTIFIER) {
7177 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7178 return create_invalid_expression();
7180 symbol_t *symbol = token.v.symbol;
7183 type_t *const orig_type = addr->base.type;
7184 type_t *const type = skip_typeref(orig_type);
7187 bool saw_error = false;
7188 if (is_type_pointer(type)) {
7189 if (!select_left_arrow) {
7191 "request for member '%Y' in something not a struct or union, but '%T'",
7195 type_left = skip_typeref(type->pointer.points_to);
7197 if (select_left_arrow && is_type_valid(type)) {
7198 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7204 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7205 type_left->kind != TYPE_COMPOUND_UNION) {
7207 if (is_type_valid(type_left) && !saw_error) {
7209 "request for member '%Y' in something not a struct or union, but '%T'",
7212 return create_invalid_expression();
7215 compound_t *compound = type_left->compound.compound;
7216 if (!compound->complete) {
7217 errorf(HERE, "request for member '%Y' in incomplete type '%T'",
7219 return create_invalid_expression();
7222 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7223 expression_t *result
7224 = find_create_select(HERE, addr, qualifiers, compound, symbol);
7226 if (result == NULL) {
7227 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7228 return create_invalid_expression();
7234 static void check_call_argument(type_t *expected_type,
7235 call_argument_t *argument, unsigned pos)
7237 type_t *expected_type_skip = skip_typeref(expected_type);
7238 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7239 expression_t *arg_expr = argument->expression;
7240 type_t *arg_type = skip_typeref(arg_expr->base.type);
7242 /* handle transparent union gnu extension */
7243 if (is_type_union(expected_type_skip)
7244 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7245 compound_t *union_decl = expected_type_skip->compound.compound;
7246 type_t *best_type = NULL;
7247 entity_t *entry = union_decl->members.entities;
7248 for ( ; entry != NULL; entry = entry->base.next) {
7249 assert(is_declaration(entry));
7250 type_t *decl_type = entry->declaration.type;
7251 error = semantic_assign(decl_type, arg_expr);
7252 if (error == ASSIGN_ERROR_INCOMPATIBLE
7253 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7256 if (error == ASSIGN_SUCCESS) {
7257 best_type = decl_type;
7258 } else if (best_type == NULL) {
7259 best_type = decl_type;
7263 if (best_type != NULL) {
7264 expected_type = best_type;
7268 error = semantic_assign(expected_type, arg_expr);
7269 argument->expression = create_implicit_cast(arg_expr, expected_type);
7271 if (error != ASSIGN_SUCCESS) {
7272 /* report exact scope in error messages (like "in argument 3") */
7274 snprintf(buf, sizeof(buf), "call argument %u", pos);
7275 report_assign_error(error, expected_type, arg_expr, buf,
7276 &arg_expr->base.source_position);
7277 } else if (warning.traditional || warning.conversion) {
7278 type_t *const promoted_type = get_default_promoted_type(arg_type);
7279 if (!types_compatible(expected_type_skip, promoted_type) &&
7280 !types_compatible(expected_type_skip, type_void_ptr) &&
7281 !types_compatible(type_void_ptr, promoted_type)) {
7282 /* Deliberately show the skipped types in this warning */
7283 warningf(&arg_expr->base.source_position,
7284 "passing call argument %u as '%T' rather than '%T' due to prototype",
7285 pos, expected_type_skip, promoted_type);
7291 * Handle the semantic restrictions of builtin calls
7293 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7294 switch (call->function->reference.entity->function.btk) {
7295 case bk_gnu_builtin_return_address:
7296 case bk_gnu_builtin_frame_address: {
7297 /* argument must be constant */
7298 call_argument_t *argument = call->arguments;
7300 if (! is_constant_expression(argument->expression)) {
7301 errorf(&call->base.source_position,
7302 "argument of '%Y' must be a constant expression",
7303 call->function->reference.entity->base.symbol);
7307 case bk_gnu_builtin_prefetch: {
7308 /* second and third argument must be constant if existent */
7309 call_argument_t *rw = call->arguments->next;
7310 call_argument_t *locality = NULL;
7313 if (! is_constant_expression(rw->expression)) {
7314 errorf(&call->base.source_position,
7315 "second argument of '%Y' must be a constant expression",
7316 call->function->reference.entity->base.symbol);
7318 locality = rw->next;
7320 if (locality != NULL) {
7321 if (! is_constant_expression(locality->expression)) {
7322 errorf(&call->base.source_position,
7323 "third argument of '%Y' must be a constant expression",
7324 call->function->reference.entity->base.symbol);
7326 locality = rw->next;
7336 * Parse a call expression, ie. expression '( ... )'.
7338 * @param expression the function address
7340 static expression_t *parse_call_expression(expression_t *expression)
7342 expression_t *result = allocate_expression_zero(EXPR_CALL);
7343 call_expression_t *call = &result->call;
7344 call->function = expression;
7346 type_t *const orig_type = expression->base.type;
7347 type_t *const type = skip_typeref(orig_type);
7349 function_type_t *function_type = NULL;
7350 if (is_type_pointer(type)) {
7351 type_t *const to_type = skip_typeref(type->pointer.points_to);
7353 if (is_type_function(to_type)) {
7354 function_type = &to_type->function;
7355 call->base.type = function_type->return_type;
7359 if (function_type == NULL && is_type_valid(type)) {
7361 "called object '%E' (type '%T') is not a pointer to a function",
7362 expression, orig_type);
7365 /* parse arguments */
7367 add_anchor_token(')');
7368 add_anchor_token(',');
7370 if (token.type != ')') {
7371 call_argument_t **anchor = &call->arguments;
7373 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7374 argument->expression = parse_assignment_expression();
7377 anchor = &argument->next;
7378 } while (next_if(','));
7380 rem_anchor_token(',');
7381 rem_anchor_token(')');
7382 expect(')', end_error);
7384 if (function_type == NULL)
7387 /* check type and count of call arguments */
7388 function_parameter_t *parameter = function_type->parameters;
7389 call_argument_t *argument = call->arguments;
7390 if (!function_type->unspecified_parameters) {
7391 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7392 parameter = parameter->next, argument = argument->next) {
7393 check_call_argument(parameter->type, argument, ++pos);
7396 if (parameter != NULL) {
7397 errorf(HERE, "too few arguments to function '%E'", expression);
7398 } else if (argument != NULL && !function_type->variadic) {
7399 errorf(HERE, "too many arguments to function '%E'", expression);
7403 /* do default promotion for other arguments */
7404 for (; argument != NULL; argument = argument->next) {
7405 type_t *type = argument->expression->base.type;
7407 type = get_default_promoted_type(type);
7409 argument->expression
7410 = create_implicit_cast(argument->expression, type);
7413 check_format(&result->call);
7415 if (warning.aggregate_return &&
7416 is_type_compound(skip_typeref(function_type->return_type))) {
7417 warningf(&result->base.source_position,
7418 "function call has aggregate value");
7421 if (call->function->kind == EXPR_REFERENCE) {
7422 reference_expression_t *reference = &call->function->reference;
7423 if (reference->entity->kind == ENTITY_FUNCTION &&
7424 reference->entity->function.btk != bk_none)
7425 handle_builtin_argument_restrictions(call);
7432 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7434 static bool same_compound_type(const type_t *type1, const type_t *type2)
7437 is_type_compound(type1) &&
7438 type1->kind == type2->kind &&
7439 type1->compound.compound == type2->compound.compound;
7442 static expression_t const *get_reference_address(expression_t const *expr)
7444 bool regular_take_address = true;
7446 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7447 expr = expr->unary.value;
7449 regular_take_address = false;
7452 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7455 expr = expr->unary.value;
7458 if (expr->kind != EXPR_REFERENCE)
7461 /* special case for functions which are automatically converted to a
7462 * pointer to function without an extra TAKE_ADDRESS operation */
7463 if (!regular_take_address &&
7464 expr->reference.entity->kind != ENTITY_FUNCTION) {
7471 static void warn_reference_address_as_bool(expression_t const* expr)
7473 if (!warning.address)
7476 expr = get_reference_address(expr);
7478 warningf(&expr->base.source_position,
7479 "the address of '%Y' will always evaluate as 'true'",
7480 expr->reference.entity->base.symbol);
7484 static void warn_assignment_in_condition(const expression_t *const expr)
7486 if (!warning.parentheses)
7488 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7490 if (expr->base.parenthesized)
7492 warningf(&expr->base.source_position,
7493 "suggest parentheses around assignment used as truth value");
7496 static void semantic_condition(expression_t const *const expr,
7497 char const *const context)
7499 type_t *const type = skip_typeref(expr->base.type);
7500 if (is_type_scalar(type)) {
7501 warn_reference_address_as_bool(expr);
7502 warn_assignment_in_condition(expr);
7503 } else if (is_type_valid(type)) {
7504 errorf(&expr->base.source_position,
7505 "%s must have scalar type", context);
7510 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7512 * @param expression the conditional expression
7514 static expression_t *parse_conditional_expression(expression_t *expression)
7516 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7518 conditional_expression_t *conditional = &result->conditional;
7519 conditional->condition = expression;
7522 add_anchor_token(':');
7524 /* §6.5.15:2 The first operand shall have scalar type. */
7525 semantic_condition(expression, "condition of conditional operator");
7527 expression_t *true_expression = expression;
7528 bool gnu_cond = false;
7529 if (GNU_MODE && token.type == ':') {
7532 true_expression = parse_expression();
7534 rem_anchor_token(':');
7535 expect(':', end_error);
7537 expression_t *false_expression =
7538 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7540 type_t *const orig_true_type = true_expression->base.type;
7541 type_t *const orig_false_type = false_expression->base.type;
7542 type_t *const true_type = skip_typeref(orig_true_type);
7543 type_t *const false_type = skip_typeref(orig_false_type);
7546 type_t *result_type;
7547 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7548 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7549 /* ISO/IEC 14882:1998(E) §5.16:2 */
7550 if (true_expression->kind == EXPR_UNARY_THROW) {
7551 result_type = false_type;
7552 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7553 result_type = true_type;
7555 if (warning.other && (
7556 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7557 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7559 warningf(&conditional->base.source_position,
7560 "ISO C forbids conditional expression with only one void side");
7562 result_type = type_void;
7564 } else if (is_type_arithmetic(true_type)
7565 && is_type_arithmetic(false_type)) {
7566 result_type = semantic_arithmetic(true_type, false_type);
7568 true_expression = create_implicit_cast(true_expression, result_type);
7569 false_expression = create_implicit_cast(false_expression, result_type);
7571 conditional->true_expression = true_expression;
7572 conditional->false_expression = false_expression;
7573 conditional->base.type = result_type;
7574 } else if (same_compound_type(true_type, false_type)) {
7575 /* just take 1 of the 2 types */
7576 result_type = true_type;
7577 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7578 type_t *pointer_type;
7580 expression_t *other_expression;
7581 if (is_type_pointer(true_type) &&
7582 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7583 pointer_type = true_type;
7584 other_type = false_type;
7585 other_expression = false_expression;
7587 pointer_type = false_type;
7588 other_type = true_type;
7589 other_expression = true_expression;
7592 if (is_null_pointer_constant(other_expression)) {
7593 result_type = pointer_type;
7594 } else if (is_type_pointer(other_type)) {
7595 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7596 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7599 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7600 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7602 } else if (types_compatible(get_unqualified_type(to1),
7603 get_unqualified_type(to2))) {
7606 if (warning.other) {
7607 warningf(&conditional->base.source_position,
7608 "pointer types '%T' and '%T' in conditional expression are incompatible",
7609 true_type, false_type);
7614 type_t *const type =
7615 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7616 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7617 } else if (is_type_integer(other_type)) {
7618 if (warning.other) {
7619 warningf(&conditional->base.source_position,
7620 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7622 result_type = pointer_type;
7624 if (is_type_valid(other_type)) {
7625 type_error_incompatible("while parsing conditional",
7626 &expression->base.source_position, true_type, false_type);
7628 result_type = type_error_type;
7631 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7632 type_error_incompatible("while parsing conditional",
7633 &conditional->base.source_position, true_type,
7636 result_type = type_error_type;
7639 conditional->true_expression
7640 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7641 conditional->false_expression
7642 = create_implicit_cast(false_expression, result_type);
7643 conditional->base.type = result_type;
7648 * Parse an extension expression.
7650 static expression_t *parse_extension(void)
7652 eat(T___extension__);
7654 bool old_gcc_extension = in_gcc_extension;
7655 in_gcc_extension = true;
7656 expression_t *expression = parse_sub_expression(PREC_UNARY);
7657 in_gcc_extension = old_gcc_extension;
7662 * Parse a __builtin_classify_type() expression.
7664 static expression_t *parse_builtin_classify_type(void)
7666 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7667 result->base.type = type_int;
7669 eat(T___builtin_classify_type);
7671 expect('(', end_error);
7672 add_anchor_token(')');
7673 expression_t *expression = parse_expression();
7674 rem_anchor_token(')');
7675 expect(')', end_error);
7676 result->classify_type.type_expression = expression;
7680 return create_invalid_expression();
7684 * Parse a delete expression
7685 * ISO/IEC 14882:1998(E) §5.3.5
7687 static expression_t *parse_delete(void)
7689 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7690 result->base.type = type_void;
7695 result->kind = EXPR_UNARY_DELETE_ARRAY;
7696 expect(']', end_error);
7700 expression_t *const value = parse_sub_expression(PREC_CAST);
7701 result->unary.value = value;
7703 type_t *const type = skip_typeref(value->base.type);
7704 if (!is_type_pointer(type)) {
7705 if (is_type_valid(type)) {
7706 errorf(&value->base.source_position,
7707 "operand of delete must have pointer type");
7709 } else if (warning.other &&
7710 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7711 warningf(&value->base.source_position,
7712 "deleting 'void*' is undefined");
7719 * Parse a throw expression
7720 * ISO/IEC 14882:1998(E) §15:1
7722 static expression_t *parse_throw(void)
7724 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7725 result->base.type = type_void;
7729 expression_t *value = NULL;
7730 switch (token.type) {
7732 value = parse_assignment_expression();
7733 /* ISO/IEC 14882:1998(E) §15.1:3 */
7734 type_t *const orig_type = value->base.type;
7735 type_t *const type = skip_typeref(orig_type);
7736 if (is_type_incomplete(type)) {
7737 errorf(&value->base.source_position,
7738 "cannot throw object of incomplete type '%T'", orig_type);
7739 } else if (is_type_pointer(type)) {
7740 type_t *const points_to = skip_typeref(type->pointer.points_to);
7741 if (is_type_incomplete(points_to) &&
7742 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7743 errorf(&value->base.source_position,
7744 "cannot throw pointer to incomplete type '%T'", orig_type);
7752 result->unary.value = value;
7757 static bool check_pointer_arithmetic(const source_position_t *source_position,
7758 type_t *pointer_type,
7759 type_t *orig_pointer_type)
7761 type_t *points_to = pointer_type->pointer.points_to;
7762 points_to = skip_typeref(points_to);
7764 if (is_type_incomplete(points_to)) {
7765 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7766 errorf(source_position,
7767 "arithmetic with pointer to incomplete type '%T' not allowed",
7770 } else if (warning.pointer_arith) {
7771 warningf(source_position,
7772 "pointer of type '%T' used in arithmetic",
7775 } else if (is_type_function(points_to)) {
7777 errorf(source_position,
7778 "arithmetic with pointer to function type '%T' not allowed",
7781 } else if (warning.pointer_arith) {
7782 warningf(source_position,
7783 "pointer to a function '%T' used in arithmetic",
7790 static bool is_lvalue(const expression_t *expression)
7792 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7793 switch (expression->kind) {
7794 case EXPR_ARRAY_ACCESS:
7795 case EXPR_COMPOUND_LITERAL:
7796 case EXPR_REFERENCE:
7798 case EXPR_UNARY_DEREFERENCE:
7802 type_t *type = skip_typeref(expression->base.type);
7804 /* ISO/IEC 14882:1998(E) §3.10:3 */
7805 is_type_reference(type) ||
7806 /* Claim it is an lvalue, if the type is invalid. There was a parse
7807 * error before, which maybe prevented properly recognizing it as
7809 !is_type_valid(type);
7814 static void semantic_incdec(unary_expression_t *expression)
7816 type_t *const orig_type = expression->value->base.type;
7817 type_t *const type = skip_typeref(orig_type);
7818 if (is_type_pointer(type)) {
7819 if (!check_pointer_arithmetic(&expression->base.source_position,
7823 } else if (!is_type_real(type) && is_type_valid(type)) {
7824 /* TODO: improve error message */
7825 errorf(&expression->base.source_position,
7826 "operation needs an arithmetic or pointer type");
7829 if (!is_lvalue(expression->value)) {
7830 /* TODO: improve error message */
7831 errorf(&expression->base.source_position, "lvalue required as operand");
7833 expression->base.type = orig_type;
7836 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7838 type_t *const orig_type = expression->value->base.type;
7839 type_t *const type = skip_typeref(orig_type);
7840 if (!is_type_arithmetic(type)) {
7841 if (is_type_valid(type)) {
7842 /* TODO: improve error message */
7843 errorf(&expression->base.source_position,
7844 "operation needs an arithmetic type");
7849 expression->base.type = orig_type;
7852 static void semantic_unexpr_plus(unary_expression_t *expression)
7854 semantic_unexpr_arithmetic(expression);
7855 if (warning.traditional)
7856 warningf(&expression->base.source_position,
7857 "traditional C rejects the unary plus operator");
7860 static void semantic_not(unary_expression_t *expression)
7862 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7863 semantic_condition(expression->value, "operand of !");
7864 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7867 static void semantic_unexpr_integer(unary_expression_t *expression)
7869 type_t *const orig_type = expression->value->base.type;
7870 type_t *const type = skip_typeref(orig_type);
7871 if (!is_type_integer(type)) {
7872 if (is_type_valid(type)) {
7873 errorf(&expression->base.source_position,
7874 "operand of ~ must be of integer type");
7879 expression->base.type = orig_type;
7882 static void semantic_dereference(unary_expression_t *expression)
7884 type_t *const orig_type = expression->value->base.type;
7885 type_t *const type = skip_typeref(orig_type);
7886 if (!is_type_pointer(type)) {
7887 if (is_type_valid(type)) {
7888 errorf(&expression->base.source_position,
7889 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7894 type_t *result_type = type->pointer.points_to;
7895 result_type = automatic_type_conversion(result_type);
7896 expression->base.type = result_type;
7900 * Record that an address is taken (expression represents an lvalue).
7902 * @param expression the expression
7903 * @param may_be_register if true, the expression might be an register
7905 static void set_address_taken(expression_t *expression, bool may_be_register)
7907 if (expression->kind != EXPR_REFERENCE)
7910 entity_t *const entity = expression->reference.entity;
7912 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7915 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7916 && !may_be_register) {
7917 errorf(&expression->base.source_position,
7918 "address of register %s '%Y' requested",
7919 get_entity_kind_name(entity->kind), entity->base.symbol);
7922 if (entity->kind == ENTITY_VARIABLE) {
7923 entity->variable.address_taken = true;
7925 assert(entity->kind == ENTITY_PARAMETER);
7926 entity->parameter.address_taken = true;
7931 * Check the semantic of the address taken expression.
7933 static void semantic_take_addr(unary_expression_t *expression)
7935 expression_t *value = expression->value;
7936 value->base.type = revert_automatic_type_conversion(value);
7938 type_t *orig_type = value->base.type;
7939 type_t *type = skip_typeref(orig_type);
7940 if (!is_type_valid(type))
7944 if (!is_lvalue(value)) {
7945 errorf(&expression->base.source_position, "'&' requires an lvalue");
7947 if (type->kind == TYPE_BITFIELD) {
7948 errorf(&expression->base.source_position,
7949 "'&' not allowed on object with bitfield type '%T'",
7953 set_address_taken(value, false);
7955 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7958 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7959 static expression_t *parse_##unexpression_type(void) \
7961 expression_t *unary_expression \
7962 = allocate_expression_zero(unexpression_type); \
7964 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
7966 sfunc(&unary_expression->unary); \
7968 return unary_expression; \
7971 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7972 semantic_unexpr_arithmetic)
7973 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7974 semantic_unexpr_plus)
7975 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7977 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7978 semantic_dereference)
7979 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7981 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7982 semantic_unexpr_integer)
7983 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7985 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7988 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7990 static expression_t *parse_##unexpression_type(expression_t *left) \
7992 expression_t *unary_expression \
7993 = allocate_expression_zero(unexpression_type); \
7995 unary_expression->unary.value = left; \
7997 sfunc(&unary_expression->unary); \
7999 return unary_expression; \
8002 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8003 EXPR_UNARY_POSTFIX_INCREMENT,
8005 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8006 EXPR_UNARY_POSTFIX_DECREMENT,
8009 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8011 /* TODO: handle complex + imaginary types */
8013 type_left = get_unqualified_type(type_left);
8014 type_right = get_unqualified_type(type_right);
8016 /* §6.3.1.8 Usual arithmetic conversions */
8017 if (type_left == type_long_double || type_right == type_long_double) {
8018 return type_long_double;
8019 } else if (type_left == type_double || type_right == type_double) {
8021 } else if (type_left == type_float || type_right == type_float) {
8025 type_left = promote_integer(type_left);
8026 type_right = promote_integer(type_right);
8028 if (type_left == type_right)
8031 bool const signed_left = is_type_signed(type_left);
8032 bool const signed_right = is_type_signed(type_right);
8033 int const rank_left = get_rank(type_left);
8034 int const rank_right = get_rank(type_right);
8036 if (signed_left == signed_right)
8037 return rank_left >= rank_right ? type_left : type_right;
8046 u_rank = rank_right;
8047 u_type = type_right;
8049 s_rank = rank_right;
8050 s_type = type_right;
8055 if (u_rank >= s_rank)
8058 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8060 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8061 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8065 case ATOMIC_TYPE_INT: return type_unsigned_int;
8066 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8067 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8069 default: panic("invalid atomic type");
8074 * Check the semantic restrictions for a binary expression.
8076 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8078 expression_t *const left = expression->left;
8079 expression_t *const right = expression->right;
8080 type_t *const orig_type_left = left->base.type;
8081 type_t *const orig_type_right = right->base.type;
8082 type_t *const type_left = skip_typeref(orig_type_left);
8083 type_t *const type_right = skip_typeref(orig_type_right);
8085 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8086 /* TODO: improve error message */
8087 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8088 errorf(&expression->base.source_position,
8089 "operation needs arithmetic types");
8094 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8095 expression->left = create_implicit_cast(left, arithmetic_type);
8096 expression->right = create_implicit_cast(right, arithmetic_type);
8097 expression->base.type = arithmetic_type;
8100 static void warn_div_by_zero(binary_expression_t const *const expression)
8102 if (!warning.div_by_zero ||
8103 !is_type_integer(expression->base.type))
8106 expression_t const *const right = expression->right;
8107 /* The type of the right operand can be different for /= */
8108 if (is_type_integer(right->base.type) &&
8109 is_constant_expression(right) &&
8110 !fold_constant_to_bool(right)) {
8111 warningf(&expression->base.source_position, "division by zero");
8116 * Check the semantic restrictions for a div/mod expression.
8118 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8120 semantic_binexpr_arithmetic(expression);
8121 warn_div_by_zero(expression);
8124 static void warn_addsub_in_shift(const expression_t *const expr)
8126 if (expr->base.parenthesized)
8130 switch (expr->kind) {
8131 case EXPR_BINARY_ADD: op = '+'; break;
8132 case EXPR_BINARY_SUB: op = '-'; break;
8136 warningf(&expr->base.source_position,
8137 "suggest parentheses around '%c' inside shift", op);
8140 static bool semantic_shift(binary_expression_t *expression)
8142 expression_t *const left = expression->left;
8143 expression_t *const right = expression->right;
8144 type_t *const orig_type_left = left->base.type;
8145 type_t *const orig_type_right = right->base.type;
8146 type_t * type_left = skip_typeref(orig_type_left);
8147 type_t * type_right = skip_typeref(orig_type_right);
8149 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8150 /* TODO: improve error message */
8151 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8152 errorf(&expression->base.source_position,
8153 "operands of shift operation must have integer types");
8158 type_left = promote_integer(type_left);
8160 if (is_constant_expression(right)) {
8161 long count = fold_constant_to_int(right);
8163 warningf(&right->base.source_position,
8164 "shift count must be non-negative");
8165 } else if ((unsigned long)count >=
8166 get_atomic_type_size(type_left->atomic.akind) * 8) {
8167 warningf(&right->base.source_position,
8168 "shift count must be less than type width");
8172 type_right = promote_integer(type_right);
8173 expression->right = create_implicit_cast(right, type_right);
8178 static void semantic_shift_op(binary_expression_t *expression)
8180 expression_t *const left = expression->left;
8181 expression_t *const right = expression->right;
8183 if (!semantic_shift(expression))
8186 if (warning.parentheses) {
8187 warn_addsub_in_shift(left);
8188 warn_addsub_in_shift(right);
8191 type_t *const orig_type_left = left->base.type;
8192 type_t * type_left = skip_typeref(orig_type_left);
8194 type_left = promote_integer(type_left);
8195 expression->left = create_implicit_cast(left, type_left);
8196 expression->base.type = type_left;
8199 static void semantic_add(binary_expression_t *expression)
8201 expression_t *const left = expression->left;
8202 expression_t *const right = expression->right;
8203 type_t *const orig_type_left = left->base.type;
8204 type_t *const orig_type_right = right->base.type;
8205 type_t *const type_left = skip_typeref(orig_type_left);
8206 type_t *const type_right = skip_typeref(orig_type_right);
8209 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8210 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8211 expression->left = create_implicit_cast(left, arithmetic_type);
8212 expression->right = create_implicit_cast(right, arithmetic_type);
8213 expression->base.type = arithmetic_type;
8214 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8215 check_pointer_arithmetic(&expression->base.source_position,
8216 type_left, orig_type_left);
8217 expression->base.type = type_left;
8218 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8219 check_pointer_arithmetic(&expression->base.source_position,
8220 type_right, orig_type_right);
8221 expression->base.type = type_right;
8222 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8223 errorf(&expression->base.source_position,
8224 "invalid operands to binary + ('%T', '%T')",
8225 orig_type_left, orig_type_right);
8229 static void semantic_sub(binary_expression_t *expression)
8231 expression_t *const left = expression->left;
8232 expression_t *const right = expression->right;
8233 type_t *const orig_type_left = left->base.type;
8234 type_t *const orig_type_right = right->base.type;
8235 type_t *const type_left = skip_typeref(orig_type_left);
8236 type_t *const type_right = skip_typeref(orig_type_right);
8237 source_position_t const *const pos = &expression->base.source_position;
8240 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8241 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8242 expression->left = create_implicit_cast(left, arithmetic_type);
8243 expression->right = create_implicit_cast(right, arithmetic_type);
8244 expression->base.type = arithmetic_type;
8245 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8246 check_pointer_arithmetic(&expression->base.source_position,
8247 type_left, orig_type_left);
8248 expression->base.type = type_left;
8249 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8250 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8251 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8252 if (!types_compatible(unqual_left, unqual_right)) {
8254 "subtracting pointers to incompatible types '%T' and '%T'",
8255 orig_type_left, orig_type_right);
8256 } else if (!is_type_object(unqual_left)) {
8257 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8258 errorf(pos, "subtracting pointers to non-object types '%T'",
8260 } else if (warning.other) {
8261 warningf(pos, "subtracting pointers to void");
8264 expression->base.type = type_ptrdiff_t;
8265 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8266 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8267 orig_type_left, orig_type_right);
8271 static void warn_string_literal_address(expression_t const* expr)
8273 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8274 expr = expr->unary.value;
8275 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8277 expr = expr->unary.value;
8280 if (expr->kind == EXPR_STRING_LITERAL ||
8281 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8282 warningf(&expr->base.source_position,
8283 "comparison with string literal results in unspecified behaviour");
8287 static void warn_comparison_in_comparison(const expression_t *const expr)
8289 if (expr->base.parenthesized)
8291 switch (expr->base.kind) {
8292 case EXPR_BINARY_LESS:
8293 case EXPR_BINARY_GREATER:
8294 case EXPR_BINARY_LESSEQUAL:
8295 case EXPR_BINARY_GREATEREQUAL:
8296 case EXPR_BINARY_NOTEQUAL:
8297 case EXPR_BINARY_EQUAL:
8298 warningf(&expr->base.source_position,
8299 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8306 static bool maybe_negative(expression_t const *const expr)
8309 !is_constant_expression(expr) ||
8310 fold_constant_to_int(expr) < 0;
8314 * Check the semantics of comparison expressions.
8316 * @param expression The expression to check.
8318 static void semantic_comparison(binary_expression_t *expression)
8320 expression_t *left = expression->left;
8321 expression_t *right = expression->right;
8323 if (warning.address) {
8324 warn_string_literal_address(left);
8325 warn_string_literal_address(right);
8327 expression_t const* const func_left = get_reference_address(left);
8328 if (func_left != NULL && is_null_pointer_constant(right)) {
8329 warningf(&expression->base.source_position,
8330 "the address of '%Y' will never be NULL",
8331 func_left->reference.entity->base.symbol);
8334 expression_t const* const func_right = get_reference_address(right);
8335 if (func_right != NULL && is_null_pointer_constant(right)) {
8336 warningf(&expression->base.source_position,
8337 "the address of '%Y' will never be NULL",
8338 func_right->reference.entity->base.symbol);
8342 if (warning.parentheses) {
8343 warn_comparison_in_comparison(left);
8344 warn_comparison_in_comparison(right);
8347 type_t *orig_type_left = left->base.type;
8348 type_t *orig_type_right = right->base.type;
8349 type_t *type_left = skip_typeref(orig_type_left);
8350 type_t *type_right = skip_typeref(orig_type_right);
8352 /* TODO non-arithmetic types */
8353 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8354 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8356 /* test for signed vs unsigned compares */
8357 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8358 bool const signed_left = is_type_signed(type_left);
8359 bool const signed_right = is_type_signed(type_right);
8360 if (signed_left != signed_right) {
8361 /* FIXME long long needs better const folding magic */
8362 /* TODO check whether constant value can be represented by other type */
8363 if ((signed_left && maybe_negative(left)) ||
8364 (signed_right && maybe_negative(right))) {
8365 warningf(&expression->base.source_position,
8366 "comparison between signed and unsigned");
8371 expression->left = create_implicit_cast(left, arithmetic_type);
8372 expression->right = create_implicit_cast(right, arithmetic_type);
8373 expression->base.type = arithmetic_type;
8374 if (warning.float_equal &&
8375 (expression->base.kind == EXPR_BINARY_EQUAL ||
8376 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8377 is_type_float(arithmetic_type)) {
8378 warningf(&expression->base.source_position,
8379 "comparing floating point with == or != is unsafe");
8381 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8382 /* TODO check compatibility */
8383 } else if (is_type_pointer(type_left)) {
8384 expression->right = create_implicit_cast(right, type_left);
8385 } else if (is_type_pointer(type_right)) {
8386 expression->left = create_implicit_cast(left, type_right);
8387 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8388 type_error_incompatible("invalid operands in comparison",
8389 &expression->base.source_position,
8390 type_left, type_right);
8392 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8396 * Checks if a compound type has constant fields.
8398 static bool has_const_fields(const compound_type_t *type)
8400 compound_t *compound = type->compound;
8401 entity_t *entry = compound->members.entities;
8403 for (; entry != NULL; entry = entry->base.next) {
8404 if (!is_declaration(entry))
8407 const type_t *decl_type = skip_typeref(entry->declaration.type);
8408 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8415 static bool is_valid_assignment_lhs(expression_t const* const left)
8417 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8418 type_t *const type_left = skip_typeref(orig_type_left);
8420 if (!is_lvalue(left)) {
8421 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8426 if (left->kind == EXPR_REFERENCE
8427 && left->reference.entity->kind == ENTITY_FUNCTION) {
8428 errorf(HERE, "cannot assign to function '%E'", left);
8432 if (is_type_array(type_left)) {
8433 errorf(HERE, "cannot assign to array '%E'", left);
8436 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8437 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8441 if (is_type_incomplete(type_left)) {
8442 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8443 left, orig_type_left);
8446 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8447 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8448 left, orig_type_left);
8455 static void semantic_arithmetic_assign(binary_expression_t *expression)
8457 expression_t *left = expression->left;
8458 expression_t *right = expression->right;
8459 type_t *orig_type_left = left->base.type;
8460 type_t *orig_type_right = right->base.type;
8462 if (!is_valid_assignment_lhs(left))
8465 type_t *type_left = skip_typeref(orig_type_left);
8466 type_t *type_right = skip_typeref(orig_type_right);
8468 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8469 /* TODO: improve error message */
8470 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8471 errorf(&expression->base.source_position,
8472 "operation needs arithmetic types");
8477 /* combined instructions are tricky. We can't create an implicit cast on
8478 * the left side, because we need the uncasted form for the store.
8479 * The ast2firm pass has to know that left_type must be right_type
8480 * for the arithmetic operation and create a cast by itself */
8481 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8482 expression->right = create_implicit_cast(right, arithmetic_type);
8483 expression->base.type = type_left;
8486 static void semantic_divmod_assign(binary_expression_t *expression)
8488 semantic_arithmetic_assign(expression);
8489 warn_div_by_zero(expression);
8492 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8494 expression_t *const left = expression->left;
8495 expression_t *const right = expression->right;
8496 type_t *const orig_type_left = left->base.type;
8497 type_t *const orig_type_right = right->base.type;
8498 type_t *const type_left = skip_typeref(orig_type_left);
8499 type_t *const type_right = skip_typeref(orig_type_right);
8501 if (!is_valid_assignment_lhs(left))
8504 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8505 /* combined instructions are tricky. We can't create an implicit cast on
8506 * the left side, because we need the uncasted form for the store.
8507 * The ast2firm pass has to know that left_type must be right_type
8508 * for the arithmetic operation and create a cast by itself */
8509 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8510 expression->right = create_implicit_cast(right, arithmetic_type);
8511 expression->base.type = type_left;
8512 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8513 check_pointer_arithmetic(&expression->base.source_position,
8514 type_left, orig_type_left);
8515 expression->base.type = type_left;
8516 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8517 errorf(&expression->base.source_position,
8518 "incompatible types '%T' and '%T' in assignment",
8519 orig_type_left, orig_type_right);
8523 static void semantic_integer_assign(binary_expression_t *expression)
8525 expression_t *left = expression->left;
8526 expression_t *right = expression->right;
8527 type_t *orig_type_left = left->base.type;
8528 type_t *orig_type_right = right->base.type;
8530 if (!is_valid_assignment_lhs(left))
8533 type_t *type_left = skip_typeref(orig_type_left);
8534 type_t *type_right = skip_typeref(orig_type_right);
8536 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8537 /* TODO: improve error message */
8538 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8539 errorf(&expression->base.source_position,
8540 "operation needs integer types");
8545 /* combined instructions are tricky. We can't create an implicit cast on
8546 * the left side, because we need the uncasted form for the store.
8547 * The ast2firm pass has to know that left_type must be right_type
8548 * for the arithmetic operation and create a cast by itself */
8549 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8550 expression->right = create_implicit_cast(right, arithmetic_type);
8551 expression->base.type = type_left;
8554 static void semantic_shift_assign(binary_expression_t *expression)
8556 expression_t *left = expression->left;
8558 if (!is_valid_assignment_lhs(left))
8561 if (!semantic_shift(expression))
8564 expression->base.type = skip_typeref(left->base.type);
8567 static void warn_logical_and_within_or(const expression_t *const expr)
8569 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8571 if (expr->base.parenthesized)
8573 warningf(&expr->base.source_position,
8574 "suggest parentheses around && within ||");
8578 * Check the semantic restrictions of a logical expression.
8580 static void semantic_logical_op(binary_expression_t *expression)
8582 /* §6.5.13:2 Each of the operands shall have scalar type.
8583 * §6.5.14:2 Each of the operands shall have scalar type. */
8584 semantic_condition(expression->left, "left operand of logical operator");
8585 semantic_condition(expression->right, "right operand of logical operator");
8586 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8587 warning.parentheses) {
8588 warn_logical_and_within_or(expression->left);
8589 warn_logical_and_within_or(expression->right);
8591 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8595 * Check the semantic restrictions of a binary assign expression.
8597 static void semantic_binexpr_assign(binary_expression_t *expression)
8599 expression_t *left = expression->left;
8600 type_t *orig_type_left = left->base.type;
8602 if (!is_valid_assignment_lhs(left))
8605 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8606 report_assign_error(error, orig_type_left, expression->right,
8607 "assignment", &left->base.source_position);
8608 expression->right = create_implicit_cast(expression->right, orig_type_left);
8609 expression->base.type = orig_type_left;
8613 * Determine if the outermost operation (or parts thereof) of the given
8614 * expression has no effect in order to generate a warning about this fact.
8615 * Therefore in some cases this only examines some of the operands of the
8616 * expression (see comments in the function and examples below).
8618 * f() + 23; // warning, because + has no effect
8619 * x || f(); // no warning, because x controls execution of f()
8620 * x ? y : f(); // warning, because y has no effect
8621 * (void)x; // no warning to be able to suppress the warning
8622 * This function can NOT be used for an "expression has definitely no effect"-
8624 static bool expression_has_effect(const expression_t *const expr)
8626 switch (expr->kind) {
8627 case EXPR_UNKNOWN: break;
8628 case EXPR_INVALID: return true; /* do NOT warn */
8629 case EXPR_REFERENCE: return false;
8630 case EXPR_REFERENCE_ENUM_VALUE: return false;
8631 /* suppress the warning for microsoft __noop operations */
8632 case EXPR_CONST: return expr->conste.is_ms_noop;
8633 case EXPR_CHARACTER_CONSTANT: return false;
8634 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8635 case EXPR_STRING_LITERAL: return false;
8636 case EXPR_WIDE_STRING_LITERAL: return false;
8637 case EXPR_LABEL_ADDRESS: return false;
8640 const call_expression_t *const call = &expr->call;
8641 if (call->function->kind != EXPR_REFERENCE)
8644 switch (call->function->reference.entity->function.btk) {
8645 /* FIXME: which builtins have no effect? */
8646 default: return true;
8650 /* Generate the warning if either the left or right hand side of a
8651 * conditional expression has no effect */
8652 case EXPR_CONDITIONAL: {
8653 conditional_expression_t const *const cond = &expr->conditional;
8654 expression_t const *const t = cond->true_expression;
8656 (t == NULL || expression_has_effect(t)) &&
8657 expression_has_effect(cond->false_expression);
8660 case EXPR_SELECT: return false;
8661 case EXPR_ARRAY_ACCESS: return false;
8662 case EXPR_SIZEOF: return false;
8663 case EXPR_CLASSIFY_TYPE: return false;
8664 case EXPR_ALIGNOF: return false;
8666 case EXPR_FUNCNAME: return false;
8667 case EXPR_BUILTIN_CONSTANT_P: return false;
8668 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8669 case EXPR_OFFSETOF: return false;
8670 case EXPR_VA_START: return true;
8671 case EXPR_VA_ARG: return true;
8672 case EXPR_VA_COPY: return true;
8673 case EXPR_STATEMENT: return true; // TODO
8674 case EXPR_COMPOUND_LITERAL: return false;
8676 case EXPR_UNARY_NEGATE: return false;
8677 case EXPR_UNARY_PLUS: return false;
8678 case EXPR_UNARY_BITWISE_NEGATE: return false;
8679 case EXPR_UNARY_NOT: return false;
8680 case EXPR_UNARY_DEREFERENCE: return false;
8681 case EXPR_UNARY_TAKE_ADDRESS: return false;
8682 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8683 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8684 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8685 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8687 /* Treat void casts as if they have an effect in order to being able to
8688 * suppress the warning */
8689 case EXPR_UNARY_CAST: {
8690 type_t *const type = skip_typeref(expr->base.type);
8691 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8694 case EXPR_UNARY_CAST_IMPLICIT: return true;
8695 case EXPR_UNARY_ASSUME: return true;
8696 case EXPR_UNARY_DELETE: return true;
8697 case EXPR_UNARY_DELETE_ARRAY: return true;
8698 case EXPR_UNARY_THROW: return true;
8700 case EXPR_BINARY_ADD: return false;
8701 case EXPR_BINARY_SUB: return false;
8702 case EXPR_BINARY_MUL: return false;
8703 case EXPR_BINARY_DIV: return false;
8704 case EXPR_BINARY_MOD: return false;
8705 case EXPR_BINARY_EQUAL: return false;
8706 case EXPR_BINARY_NOTEQUAL: return false;
8707 case EXPR_BINARY_LESS: return false;
8708 case EXPR_BINARY_LESSEQUAL: return false;
8709 case EXPR_BINARY_GREATER: return false;
8710 case EXPR_BINARY_GREATEREQUAL: return false;
8711 case EXPR_BINARY_BITWISE_AND: return false;
8712 case EXPR_BINARY_BITWISE_OR: return false;
8713 case EXPR_BINARY_BITWISE_XOR: return false;
8714 case EXPR_BINARY_SHIFTLEFT: return false;
8715 case EXPR_BINARY_SHIFTRIGHT: return false;
8716 case EXPR_BINARY_ASSIGN: return true;
8717 case EXPR_BINARY_MUL_ASSIGN: return true;
8718 case EXPR_BINARY_DIV_ASSIGN: return true;
8719 case EXPR_BINARY_MOD_ASSIGN: return true;
8720 case EXPR_BINARY_ADD_ASSIGN: return true;
8721 case EXPR_BINARY_SUB_ASSIGN: return true;
8722 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8723 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8724 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8725 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8726 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8728 /* Only examine the right hand side of && and ||, because the left hand
8729 * side already has the effect of controlling the execution of the right
8731 case EXPR_BINARY_LOGICAL_AND:
8732 case EXPR_BINARY_LOGICAL_OR:
8733 /* Only examine the right hand side of a comma expression, because the left
8734 * hand side has a separate warning */
8735 case EXPR_BINARY_COMMA:
8736 return expression_has_effect(expr->binary.right);
8738 case EXPR_BINARY_ISGREATER: return false;
8739 case EXPR_BINARY_ISGREATEREQUAL: return false;
8740 case EXPR_BINARY_ISLESS: return false;
8741 case EXPR_BINARY_ISLESSEQUAL: return false;
8742 case EXPR_BINARY_ISLESSGREATER: return false;
8743 case EXPR_BINARY_ISUNORDERED: return false;
8746 internal_errorf(HERE, "unexpected expression");
8749 static void semantic_comma(binary_expression_t *expression)
8751 if (warning.unused_value) {
8752 const expression_t *const left = expression->left;
8753 if (!expression_has_effect(left)) {
8754 warningf(&left->base.source_position,
8755 "left-hand operand of comma expression has no effect");
8758 expression->base.type = expression->right->base.type;
8762 * @param prec_r precedence of the right operand
8764 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8765 static expression_t *parse_##binexpression_type(expression_t *left) \
8767 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8768 binexpr->binary.left = left; \
8771 expression_t *right = parse_sub_expression(prec_r); \
8773 binexpr->binary.right = right; \
8774 sfunc(&binexpr->binary); \
8779 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8780 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8781 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8782 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8783 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8784 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8785 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8786 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8787 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8788 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8789 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8790 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8791 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8792 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8793 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8794 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8795 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8796 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8797 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8798 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8799 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8800 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8801 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8802 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8803 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8804 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8805 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8806 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8807 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8808 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8811 static expression_t *parse_sub_expression(precedence_t precedence)
8813 if (token.type < 0) {
8814 return expected_expression_error();
8817 expression_parser_function_t *parser
8818 = &expression_parsers[token.type];
8819 source_position_t source_position = token.source_position;
8822 if (parser->parser != NULL) {
8823 left = parser->parser();
8825 left = parse_primary_expression();
8827 assert(left != NULL);
8828 left->base.source_position = source_position;
8831 if (token.type < 0) {
8832 return expected_expression_error();
8835 parser = &expression_parsers[token.type];
8836 if (parser->infix_parser == NULL)
8838 if (parser->infix_precedence < precedence)
8841 left = parser->infix_parser(left);
8843 assert(left != NULL);
8844 assert(left->kind != EXPR_UNKNOWN);
8845 left->base.source_position = source_position;
8852 * Parse an expression.
8854 static expression_t *parse_expression(void)
8856 return parse_sub_expression(PREC_EXPRESSION);
8860 * Register a parser for a prefix-like operator.
8862 * @param parser the parser function
8863 * @param token_type the token type of the prefix token
8865 static void register_expression_parser(parse_expression_function parser,
8868 expression_parser_function_t *entry = &expression_parsers[token_type];
8870 if (entry->parser != NULL) {
8871 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8872 panic("trying to register multiple expression parsers for a token");
8874 entry->parser = parser;
8878 * Register a parser for an infix operator with given precedence.
8880 * @param parser the parser function
8881 * @param token_type the token type of the infix operator
8882 * @param precedence the precedence of the operator
8884 static void register_infix_parser(parse_expression_infix_function parser,
8885 int token_type, precedence_t precedence)
8887 expression_parser_function_t *entry = &expression_parsers[token_type];
8889 if (entry->infix_parser != NULL) {
8890 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8891 panic("trying to register multiple infix expression parsers for a "
8894 entry->infix_parser = parser;
8895 entry->infix_precedence = precedence;
8899 * Initialize the expression parsers.
8901 static void init_expression_parsers(void)
8903 memset(&expression_parsers, 0, sizeof(expression_parsers));
8905 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8906 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8907 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8908 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8909 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8910 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8911 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8912 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8913 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8914 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8915 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8916 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8917 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8918 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8919 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8920 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8921 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8922 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8923 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8924 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8925 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8926 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8927 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8928 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8929 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8930 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8931 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8932 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8933 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8934 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8935 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8936 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8937 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8938 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8939 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8940 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8941 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8943 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8944 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8945 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8946 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8947 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8948 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8949 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8950 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8951 register_expression_parser(parse_sizeof, T_sizeof);
8952 register_expression_parser(parse_alignof, T___alignof__);
8953 register_expression_parser(parse_extension, T___extension__);
8954 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8955 register_expression_parser(parse_delete, T_delete);
8956 register_expression_parser(parse_throw, T_throw);
8960 * Parse a asm statement arguments specification.
8962 static asm_argument_t *parse_asm_arguments(bool is_out)
8964 asm_argument_t *result = NULL;
8965 asm_argument_t **anchor = &result;
8967 while (token.type == T_STRING_LITERAL || token.type == '[') {
8968 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8969 memset(argument, 0, sizeof(argument[0]));
8972 if (token.type != T_IDENTIFIER) {
8973 parse_error_expected("while parsing asm argument",
8974 T_IDENTIFIER, NULL);
8977 argument->symbol = token.v.symbol;
8979 expect(']', end_error);
8982 argument->constraints = parse_string_literals();
8983 expect('(', end_error);
8984 add_anchor_token(')');
8985 expression_t *expression = parse_expression();
8986 rem_anchor_token(')');
8988 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8989 * change size or type representation (e.g. int -> long is ok, but
8990 * int -> float is not) */
8991 if (expression->kind == EXPR_UNARY_CAST) {
8992 type_t *const type = expression->base.type;
8993 type_kind_t const kind = type->kind;
8994 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8997 if (kind == TYPE_ATOMIC) {
8998 atomic_type_kind_t const akind = type->atomic.akind;
8999 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9000 size = get_atomic_type_size(akind);
9002 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9003 size = get_atomic_type_size(get_intptr_kind());
9007 expression_t *const value = expression->unary.value;
9008 type_t *const value_type = value->base.type;
9009 type_kind_t const value_kind = value_type->kind;
9011 unsigned value_flags;
9012 unsigned value_size;
9013 if (value_kind == TYPE_ATOMIC) {
9014 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9015 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9016 value_size = get_atomic_type_size(value_akind);
9017 } else if (value_kind == TYPE_POINTER) {
9018 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9019 value_size = get_atomic_type_size(get_intptr_kind());
9024 if (value_flags != flags || value_size != size)
9028 } while (expression->kind == EXPR_UNARY_CAST);
9032 if (!is_lvalue(expression)) {
9033 errorf(&expression->base.source_position,
9034 "asm output argument is not an lvalue");
9037 if (argument->constraints.begin[0] == '+')
9038 mark_vars_read(expression, NULL);
9040 mark_vars_read(expression, NULL);
9042 argument->expression = expression;
9043 expect(')', end_error);
9045 set_address_taken(expression, true);
9048 anchor = &argument->next;
9060 * Parse a asm statement clobber specification.
9062 static asm_clobber_t *parse_asm_clobbers(void)
9064 asm_clobber_t *result = NULL;
9065 asm_clobber_t **anchor = &result;
9067 while (token.type == T_STRING_LITERAL) {
9068 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9069 clobber->clobber = parse_string_literals();
9072 anchor = &clobber->next;
9082 * Parse an asm statement.
9084 static statement_t *parse_asm_statement(void)
9086 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9087 asm_statement_t *asm_statement = &statement->asms;
9091 if (next_if(T_volatile))
9092 asm_statement->is_volatile = true;
9094 expect('(', end_error);
9095 add_anchor_token(')');
9096 add_anchor_token(':');
9097 asm_statement->asm_text = parse_string_literals();
9099 if (!next_if(':')) {
9100 rem_anchor_token(':');
9104 asm_statement->outputs = parse_asm_arguments(true);
9105 if (!next_if(':')) {
9106 rem_anchor_token(':');
9110 asm_statement->inputs = parse_asm_arguments(false);
9111 if (!next_if(':')) {
9112 rem_anchor_token(':');
9115 rem_anchor_token(':');
9117 asm_statement->clobbers = parse_asm_clobbers();
9120 rem_anchor_token(')');
9121 expect(')', end_error);
9122 expect(';', end_error);
9124 if (asm_statement->outputs == NULL) {
9125 /* GCC: An 'asm' instruction without any output operands will be treated
9126 * identically to a volatile 'asm' instruction. */
9127 asm_statement->is_volatile = true;
9132 return create_invalid_statement();
9136 * Parse a case statement.
9138 static statement_t *parse_case_statement(void)
9140 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9141 source_position_t *const pos = &statement->base.source_position;
9145 expression_t *const expression = parse_expression();
9146 statement->case_label.expression = expression;
9147 if (!is_constant_expression(expression)) {
9148 /* This check does not prevent the error message in all cases of an
9149 * prior error while parsing the expression. At least it catches the
9150 * common case of a mistyped enum entry. */
9151 if (is_type_valid(skip_typeref(expression->base.type))) {
9152 errorf(pos, "case label does not reduce to an integer constant");
9154 statement->case_label.is_bad = true;
9156 long const val = fold_constant_to_int(expression);
9157 statement->case_label.first_case = val;
9158 statement->case_label.last_case = val;
9162 if (next_if(T_DOTDOTDOT)) {
9163 expression_t *const end_range = parse_expression();
9164 statement->case_label.end_range = end_range;
9165 if (!is_constant_expression(end_range)) {
9166 /* This check does not prevent the error message in all cases of an
9167 * prior error while parsing the expression. At least it catches the
9168 * common case of a mistyped enum entry. */
9169 if (is_type_valid(skip_typeref(end_range->base.type))) {
9170 errorf(pos, "case range does not reduce to an integer constant");
9172 statement->case_label.is_bad = true;
9174 long const val = fold_constant_to_int(end_range);
9175 statement->case_label.last_case = val;
9177 if (warning.other && val < statement->case_label.first_case) {
9178 statement->case_label.is_empty_range = true;
9179 warningf(pos, "empty range specified");
9185 PUSH_PARENT(statement);
9187 expect(':', end_error);
9190 if (current_switch != NULL) {
9191 if (! statement->case_label.is_bad) {
9192 /* Check for duplicate case values */
9193 case_label_statement_t *c = &statement->case_label;
9194 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9195 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9198 if (c->last_case < l->first_case || c->first_case > l->last_case)
9201 errorf(pos, "duplicate case value (previously used %P)",
9202 &l->base.source_position);
9206 /* link all cases into the switch statement */
9207 if (current_switch->last_case == NULL) {
9208 current_switch->first_case = &statement->case_label;
9210 current_switch->last_case->next = &statement->case_label;
9212 current_switch->last_case = &statement->case_label;
9214 errorf(pos, "case label not within a switch statement");
9217 statement_t *const inner_stmt = parse_statement();
9218 statement->case_label.statement = inner_stmt;
9219 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9220 errorf(&inner_stmt->base.source_position, "declaration after case label");
9228 * Parse a default statement.
9230 static statement_t *parse_default_statement(void)
9232 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9236 PUSH_PARENT(statement);
9238 expect(':', end_error);
9239 if (current_switch != NULL) {
9240 const case_label_statement_t *def_label = current_switch->default_label;
9241 if (def_label != NULL) {
9242 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9243 &def_label->base.source_position);
9245 current_switch->default_label = &statement->case_label;
9247 /* link all cases into the switch statement */
9248 if (current_switch->last_case == NULL) {
9249 current_switch->first_case = &statement->case_label;
9251 current_switch->last_case->next = &statement->case_label;
9253 current_switch->last_case = &statement->case_label;
9256 errorf(&statement->base.source_position,
9257 "'default' label not within a switch statement");
9260 statement_t *const inner_stmt = parse_statement();
9261 statement->case_label.statement = inner_stmt;
9262 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9263 errorf(&inner_stmt->base.source_position, "declaration after default label");
9270 return create_invalid_statement();
9274 * Parse a label statement.
9276 static statement_t *parse_label_statement(void)
9278 assert(token.type == T_IDENTIFIER);
9279 symbol_t *symbol = token.v.symbol;
9280 label_t *label = get_label(symbol);
9282 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9283 statement->label.label = label;
9287 PUSH_PARENT(statement);
9289 /* if statement is already set then the label is defined twice,
9290 * otherwise it was just mentioned in a goto/local label declaration so far
9292 if (label->statement != NULL) {
9293 errorf(HERE, "duplicate label '%Y' (declared %P)",
9294 symbol, &label->base.source_position);
9296 label->base.source_position = token.source_position;
9297 label->statement = statement;
9302 if (token.type == '}') {
9303 /* TODO only warn? */
9304 if (warning.other && false) {
9305 warningf(HERE, "label at end of compound statement");
9306 statement->label.statement = create_empty_statement();
9308 errorf(HERE, "label at end of compound statement");
9309 statement->label.statement = create_invalid_statement();
9311 } else if (token.type == ';') {
9312 /* Eat an empty statement here, to avoid the warning about an empty
9313 * statement after a label. label:; is commonly used to have a label
9314 * before a closing brace. */
9315 statement->label.statement = create_empty_statement();
9318 statement_t *const inner_stmt = parse_statement();
9319 statement->label.statement = inner_stmt;
9320 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9321 errorf(&inner_stmt->base.source_position, "declaration after label");
9325 /* remember the labels in a list for later checking */
9326 *label_anchor = &statement->label;
9327 label_anchor = &statement->label.next;
9334 * Parse an if statement.
9336 static statement_t *parse_if(void)
9338 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9342 PUSH_PARENT(statement);
9344 add_anchor_token('{');
9346 expect('(', end_error);
9347 add_anchor_token(')');
9348 expression_t *const expr = parse_expression();
9349 statement->ifs.condition = expr;
9350 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9352 semantic_condition(expr, "condition of 'if'-statment");
9353 mark_vars_read(expr, NULL);
9354 rem_anchor_token(')');
9355 expect(')', end_error);
9358 rem_anchor_token('{');
9360 add_anchor_token(T_else);
9361 statement_t *const true_stmt = parse_statement();
9362 statement->ifs.true_statement = true_stmt;
9363 rem_anchor_token(T_else);
9365 if (next_if(T_else)) {
9366 statement->ifs.false_statement = parse_statement();
9367 } else if (warning.parentheses &&
9368 true_stmt->kind == STATEMENT_IF &&
9369 true_stmt->ifs.false_statement != NULL) {
9370 warningf(&true_stmt->base.source_position,
9371 "suggest explicit braces to avoid ambiguous 'else'");
9379 * Check that all enums are handled in a switch.
9381 * @param statement the switch statement to check
9383 static void check_enum_cases(const switch_statement_t *statement)
9385 const type_t *type = skip_typeref(statement->expression->base.type);
9386 if (! is_type_enum(type))
9388 const enum_type_t *enumt = &type->enumt;
9390 /* if we have a default, no warnings */
9391 if (statement->default_label != NULL)
9394 /* FIXME: calculation of value should be done while parsing */
9395 /* TODO: quadratic algorithm here. Change to an n log n one */
9396 long last_value = -1;
9397 const entity_t *entry = enumt->enume->base.next;
9398 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9399 entry = entry->base.next) {
9400 const expression_t *expression = entry->enum_value.value;
9401 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9403 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9404 if (l->expression == NULL)
9406 if (l->first_case <= value && value <= l->last_case) {
9412 warningf(&statement->base.source_position,
9413 "enumeration value '%Y' not handled in switch",
9414 entry->base.symbol);
9421 * Parse a switch statement.
9423 static statement_t *parse_switch(void)
9425 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9429 PUSH_PARENT(statement);
9431 expect('(', end_error);
9432 add_anchor_token(')');
9433 expression_t *const expr = parse_expression();
9434 mark_vars_read(expr, NULL);
9435 type_t * type = skip_typeref(expr->base.type);
9436 if (is_type_integer(type)) {
9437 type = promote_integer(type);
9438 if (warning.traditional) {
9439 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9440 warningf(&expr->base.source_position,
9441 "'%T' switch expression not converted to '%T' in ISO C",
9445 } else if (is_type_valid(type)) {
9446 errorf(&expr->base.source_position,
9447 "switch quantity is not an integer, but '%T'", type);
9448 type = type_error_type;
9450 statement->switchs.expression = create_implicit_cast(expr, type);
9451 expect(')', end_error);
9452 rem_anchor_token(')');
9454 switch_statement_t *rem = current_switch;
9455 current_switch = &statement->switchs;
9456 statement->switchs.body = parse_statement();
9457 current_switch = rem;
9459 if (warning.switch_default &&
9460 statement->switchs.default_label == NULL) {
9461 warningf(&statement->base.source_position, "switch has no default case");
9463 if (warning.switch_enum)
9464 check_enum_cases(&statement->switchs);
9470 return create_invalid_statement();
9473 static statement_t *parse_loop_body(statement_t *const loop)
9475 statement_t *const rem = current_loop;
9476 current_loop = loop;
9478 statement_t *const body = parse_statement();
9485 * Parse a while statement.
9487 static statement_t *parse_while(void)
9489 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9493 PUSH_PARENT(statement);
9495 expect('(', end_error);
9496 add_anchor_token(')');
9497 expression_t *const cond = parse_expression();
9498 statement->whiles.condition = cond;
9499 /* §6.8.5:2 The controlling expression of an iteration statement shall
9500 * have scalar type. */
9501 semantic_condition(cond, "condition of 'while'-statement");
9502 mark_vars_read(cond, NULL);
9503 rem_anchor_token(')');
9504 expect(')', end_error);
9506 statement->whiles.body = parse_loop_body(statement);
9512 return create_invalid_statement();
9516 * Parse a do statement.
9518 static statement_t *parse_do(void)
9520 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9524 PUSH_PARENT(statement);
9526 add_anchor_token(T_while);
9527 statement->do_while.body = parse_loop_body(statement);
9528 rem_anchor_token(T_while);
9530 expect(T_while, end_error);
9531 expect('(', end_error);
9532 add_anchor_token(')');
9533 expression_t *const cond = parse_expression();
9534 statement->do_while.condition = cond;
9535 /* §6.8.5:2 The controlling expression of an iteration statement shall
9536 * have scalar type. */
9537 semantic_condition(cond, "condition of 'do-while'-statement");
9538 mark_vars_read(cond, NULL);
9539 rem_anchor_token(')');
9540 expect(')', end_error);
9541 expect(';', end_error);
9547 return create_invalid_statement();
9551 * Parse a for statement.
9553 static statement_t *parse_for(void)
9555 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9559 expect('(', end_error1);
9560 add_anchor_token(')');
9562 PUSH_PARENT(statement);
9564 size_t const top = environment_top();
9565 scope_t *old_scope = scope_push(&statement->fors.scope);
9567 bool old_gcc_extension = in_gcc_extension;
9568 while (next_if(T___extension__)) {
9569 in_gcc_extension = true;
9573 } else if (is_declaration_specifier(&token, false)) {
9574 parse_declaration(record_entity, DECL_FLAGS_NONE);
9576 add_anchor_token(';');
9577 expression_t *const init = parse_expression();
9578 statement->fors.initialisation = init;
9579 mark_vars_read(init, ENT_ANY);
9580 if (warning.unused_value && !expression_has_effect(init)) {
9581 warningf(&init->base.source_position,
9582 "initialisation of 'for'-statement has no effect");
9584 rem_anchor_token(';');
9585 expect(';', end_error2);
9587 in_gcc_extension = old_gcc_extension;
9589 if (token.type != ';') {
9590 add_anchor_token(';');
9591 expression_t *const cond = parse_expression();
9592 statement->fors.condition = cond;
9593 /* §6.8.5:2 The controlling expression of an iteration statement
9594 * shall have scalar type. */
9595 semantic_condition(cond, "condition of 'for'-statement");
9596 mark_vars_read(cond, NULL);
9597 rem_anchor_token(';');
9599 expect(';', end_error2);
9600 if (token.type != ')') {
9601 expression_t *const step = parse_expression();
9602 statement->fors.step = step;
9603 mark_vars_read(step, ENT_ANY);
9604 if (warning.unused_value && !expression_has_effect(step)) {
9605 warningf(&step->base.source_position,
9606 "step of 'for'-statement has no effect");
9609 expect(')', end_error2);
9610 rem_anchor_token(')');
9611 statement->fors.body = parse_loop_body(statement);
9613 assert(current_scope == &statement->fors.scope);
9614 scope_pop(old_scope);
9615 environment_pop_to(top);
9622 rem_anchor_token(')');
9623 assert(current_scope == &statement->fors.scope);
9624 scope_pop(old_scope);
9625 environment_pop_to(top);
9629 return create_invalid_statement();
9633 * Parse a goto statement.
9635 static statement_t *parse_goto(void)
9637 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9640 if (GNU_MODE && next_if('*')) {
9641 expression_t *expression = parse_expression();
9642 mark_vars_read(expression, NULL);
9644 /* Argh: although documentation says the expression must be of type void*,
9645 * gcc accepts anything that can be casted into void* without error */
9646 type_t *type = expression->base.type;
9648 if (type != type_error_type) {
9649 if (!is_type_pointer(type) && !is_type_integer(type)) {
9650 errorf(&expression->base.source_position,
9651 "cannot convert to a pointer type");
9652 } else if (warning.other && type != type_void_ptr) {
9653 warningf(&expression->base.source_position,
9654 "type of computed goto expression should be 'void*' not '%T'", type);
9656 expression = create_implicit_cast(expression, type_void_ptr);
9659 statement->gotos.expression = expression;
9660 } else if (token.type == T_IDENTIFIER) {
9661 symbol_t *symbol = token.v.symbol;
9663 statement->gotos.label = get_label(symbol);
9666 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9668 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9673 /* remember the goto's in a list for later checking */
9674 *goto_anchor = &statement->gotos;
9675 goto_anchor = &statement->gotos.next;
9677 expect(';', end_error);
9681 return create_invalid_statement();
9685 * Parse a continue statement.
9687 static statement_t *parse_continue(void)
9689 if (current_loop == NULL) {
9690 errorf(HERE, "continue statement not within loop");
9693 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9696 expect(';', end_error);
9703 * Parse a break statement.
9705 static statement_t *parse_break(void)
9707 if (current_switch == NULL && current_loop == NULL) {
9708 errorf(HERE, "break statement not within loop or switch");
9711 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9714 expect(';', end_error);
9721 * Parse a __leave statement.
9723 static statement_t *parse_leave_statement(void)
9725 if (current_try == NULL) {
9726 errorf(HERE, "__leave statement not within __try");
9729 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9732 expect(';', end_error);
9739 * Check if a given entity represents a local variable.
9741 static bool is_local_variable(const entity_t *entity)
9743 if (entity->kind != ENTITY_VARIABLE)
9746 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9747 case STORAGE_CLASS_AUTO:
9748 case STORAGE_CLASS_REGISTER: {
9749 const type_t *type = skip_typeref(entity->declaration.type);
9750 if (is_type_function(type)) {
9762 * Check if a given expression represents a local variable.
9764 static bool expression_is_local_variable(const expression_t *expression)
9766 if (expression->base.kind != EXPR_REFERENCE) {
9769 const entity_t *entity = expression->reference.entity;
9770 return is_local_variable(entity);
9774 * Check if a given expression represents a local variable and
9775 * return its declaration then, else return NULL.
9777 entity_t *expression_is_variable(const expression_t *expression)
9779 if (expression->base.kind != EXPR_REFERENCE) {
9782 entity_t *entity = expression->reference.entity;
9783 if (entity->kind != ENTITY_VARIABLE)
9790 * Parse a return statement.
9792 static statement_t *parse_return(void)
9796 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9798 expression_t *return_value = NULL;
9799 if (token.type != ';') {
9800 return_value = parse_expression();
9801 mark_vars_read(return_value, NULL);
9804 const type_t *const func_type = skip_typeref(current_function->base.type);
9805 assert(is_type_function(func_type));
9806 type_t *const return_type = skip_typeref(func_type->function.return_type);
9808 source_position_t const *const pos = &statement->base.source_position;
9809 if (return_value != NULL) {
9810 type_t *return_value_type = skip_typeref(return_value->base.type);
9812 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9813 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9814 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9815 /* Only warn in C mode, because GCC does the same */
9816 if (c_mode & _CXX || strict_mode) {
9818 "'return' with a value, in function returning 'void'");
9819 } else if (warning.other) {
9821 "'return' with a value, in function returning 'void'");
9823 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9824 /* Only warn in C mode, because GCC does the same */
9827 "'return' with expression in function returning 'void'");
9828 } else if (warning.other) {
9830 "'return' with expression in function returning 'void'");
9834 assign_error_t error = semantic_assign(return_type, return_value);
9835 report_assign_error(error, return_type, return_value, "'return'",
9838 return_value = create_implicit_cast(return_value, return_type);
9839 /* check for returning address of a local var */
9840 if (warning.other && return_value != NULL
9841 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9842 const expression_t *expression = return_value->unary.value;
9843 if (expression_is_local_variable(expression)) {
9844 warningf(pos, "function returns address of local variable");
9847 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9848 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9849 if (c_mode & _CXX || strict_mode) {
9851 "'return' without value, in function returning non-void");
9854 "'return' without value, in function returning non-void");
9857 statement->returns.value = return_value;
9859 expect(';', end_error);
9866 * Parse a declaration statement.
9868 static statement_t *parse_declaration_statement(void)
9870 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9872 entity_t *before = current_scope->last_entity;
9874 parse_external_declaration();
9876 parse_declaration(record_entity, DECL_FLAGS_NONE);
9879 declaration_statement_t *const decl = &statement->declaration;
9880 entity_t *const begin =
9881 before != NULL ? before->base.next : current_scope->entities;
9882 decl->declarations_begin = begin;
9883 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9889 * Parse an expression statement, ie. expr ';'.
9891 static statement_t *parse_expression_statement(void)
9893 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9895 expression_t *const expr = parse_expression();
9896 statement->expression.expression = expr;
9897 mark_vars_read(expr, ENT_ANY);
9899 expect(';', end_error);
9906 * Parse a microsoft __try { } __finally { } or
9907 * __try{ } __except() { }
9909 static statement_t *parse_ms_try_statment(void)
9911 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9914 PUSH_PARENT(statement);
9916 ms_try_statement_t *rem = current_try;
9917 current_try = &statement->ms_try;
9918 statement->ms_try.try_statement = parse_compound_statement(false);
9923 if (next_if(T___except)) {
9924 expect('(', end_error);
9925 add_anchor_token(')');
9926 expression_t *const expr = parse_expression();
9927 mark_vars_read(expr, NULL);
9928 type_t * type = skip_typeref(expr->base.type);
9929 if (is_type_integer(type)) {
9930 type = promote_integer(type);
9931 } else if (is_type_valid(type)) {
9932 errorf(&expr->base.source_position,
9933 "__expect expression is not an integer, but '%T'", type);
9934 type = type_error_type;
9936 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9937 rem_anchor_token(')');
9938 expect(')', end_error);
9939 statement->ms_try.final_statement = parse_compound_statement(false);
9940 } else if (next_if(T__finally)) {
9941 statement->ms_try.final_statement = parse_compound_statement(false);
9943 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9944 return create_invalid_statement();
9948 return create_invalid_statement();
9951 static statement_t *parse_empty_statement(void)
9953 if (warning.empty_statement) {
9954 warningf(HERE, "statement is empty");
9956 statement_t *const statement = create_empty_statement();
9961 static statement_t *parse_local_label_declaration(void)
9963 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9967 entity_t *begin = NULL, *end = NULL;
9970 if (token.type != T_IDENTIFIER) {
9971 parse_error_expected("while parsing local label declaration",
9972 T_IDENTIFIER, NULL);
9975 symbol_t *symbol = token.v.symbol;
9976 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9977 if (entity != NULL && entity->base.parent_scope == current_scope) {
9978 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
9979 symbol, &entity->base.source_position);
9981 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
9983 entity->base.parent_scope = current_scope;
9984 entity->base.namespc = NAMESPACE_LABEL;
9985 entity->base.source_position = token.source_position;
9986 entity->base.symbol = symbol;
9989 end->base.next = entity;
9994 environment_push(entity);
9997 } while (next_if(','));
10000 statement->declaration.declarations_begin = begin;
10001 statement->declaration.declarations_end = end;
10005 static void parse_namespace_definition(void)
10009 entity_t *entity = NULL;
10010 symbol_t *symbol = NULL;
10012 if (token.type == T_IDENTIFIER) {
10013 symbol = token.v.symbol;
10016 entity = get_entity(symbol, NAMESPACE_NORMAL);
10018 && entity->kind != ENTITY_NAMESPACE
10019 && entity->base.parent_scope == current_scope) {
10020 if (!is_error_entity(entity)) {
10021 error_redefined_as_different_kind(&token.source_position,
10022 entity, ENTITY_NAMESPACE);
10028 if (entity == NULL) {
10029 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10030 entity->base.symbol = symbol;
10031 entity->base.source_position = token.source_position;
10032 entity->base.namespc = NAMESPACE_NORMAL;
10033 entity->base.parent_scope = current_scope;
10036 if (token.type == '=') {
10037 /* TODO: parse namespace alias */
10038 panic("namespace alias definition not supported yet");
10041 environment_push(entity);
10042 append_entity(current_scope, entity);
10044 size_t const top = environment_top();
10045 scope_t *old_scope = scope_push(&entity->namespacee.members);
10047 entity_t *old_current_entity = current_entity;
10048 current_entity = entity;
10050 expect('{', end_error);
10052 expect('}', end_error);
10055 assert(current_scope == &entity->namespacee.members);
10056 assert(current_entity == entity);
10057 current_entity = old_current_entity;
10058 scope_pop(old_scope);
10059 environment_pop_to(top);
10063 * Parse a statement.
10064 * There's also parse_statement() which additionally checks for
10065 * "statement has no effect" warnings
10067 static statement_t *intern_parse_statement(void)
10069 statement_t *statement = NULL;
10071 /* declaration or statement */
10072 add_anchor_token(';');
10073 switch (token.type) {
10074 case T_IDENTIFIER: {
10075 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10076 if (la1_type == ':') {
10077 statement = parse_label_statement();
10078 } else if (is_typedef_symbol(token.v.symbol)) {
10079 statement = parse_declaration_statement();
10081 /* it's an identifier, the grammar says this must be an
10082 * expression statement. However it is common that users mistype
10083 * declaration types, so we guess a bit here to improve robustness
10084 * for incorrect programs */
10085 switch (la1_type) {
10088 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10089 goto expression_statment;
10094 statement = parse_declaration_statement();
10098 expression_statment:
10099 statement = parse_expression_statement();
10106 case T___extension__:
10107 /* This can be a prefix to a declaration or an expression statement.
10108 * We simply eat it now and parse the rest with tail recursion. */
10109 while (next_if(T___extension__)) {}
10110 bool old_gcc_extension = in_gcc_extension;
10111 in_gcc_extension = true;
10112 statement = intern_parse_statement();
10113 in_gcc_extension = old_gcc_extension;
10117 statement = parse_declaration_statement();
10121 statement = parse_local_label_declaration();
10124 case ';': statement = parse_empty_statement(); break;
10125 case '{': statement = parse_compound_statement(false); break;
10126 case T___leave: statement = parse_leave_statement(); break;
10127 case T___try: statement = parse_ms_try_statment(); break;
10128 case T_asm: statement = parse_asm_statement(); break;
10129 case T_break: statement = parse_break(); break;
10130 case T_case: statement = parse_case_statement(); break;
10131 case T_continue: statement = parse_continue(); break;
10132 case T_default: statement = parse_default_statement(); break;
10133 case T_do: statement = parse_do(); break;
10134 case T_for: statement = parse_for(); break;
10135 case T_goto: statement = parse_goto(); break;
10136 case T_if: statement = parse_if(); break;
10137 case T_return: statement = parse_return(); break;
10138 case T_switch: statement = parse_switch(); break;
10139 case T_while: statement = parse_while(); break;
10142 statement = parse_expression_statement();
10146 errorf(HERE, "unexpected token %K while parsing statement", &token);
10147 statement = create_invalid_statement();
10152 rem_anchor_token(';');
10154 assert(statement != NULL
10155 && statement->base.source_position.input_name != NULL);
10161 * parse a statement and emits "statement has no effect" warning if needed
10162 * (This is really a wrapper around intern_parse_statement with check for 1
10163 * single warning. It is needed, because for statement expressions we have
10164 * to avoid the warning on the last statement)
10166 static statement_t *parse_statement(void)
10168 statement_t *statement = intern_parse_statement();
10170 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10171 expression_t *expression = statement->expression.expression;
10172 if (!expression_has_effect(expression)) {
10173 warningf(&expression->base.source_position,
10174 "statement has no effect");
10182 * Parse a compound statement.
10184 static statement_t *parse_compound_statement(bool inside_expression_statement)
10186 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10188 PUSH_PARENT(statement);
10191 add_anchor_token('}');
10192 /* tokens, which can start a statement */
10193 /* TODO MS, __builtin_FOO */
10194 add_anchor_token('!');
10195 add_anchor_token('&');
10196 add_anchor_token('(');
10197 add_anchor_token('*');
10198 add_anchor_token('+');
10199 add_anchor_token('-');
10200 add_anchor_token('{');
10201 add_anchor_token('~');
10202 add_anchor_token(T_CHARACTER_CONSTANT);
10203 add_anchor_token(T_COLONCOLON);
10204 add_anchor_token(T_FLOATINGPOINT);
10205 add_anchor_token(T_IDENTIFIER);
10206 add_anchor_token(T_INTEGER);
10207 add_anchor_token(T_MINUSMINUS);
10208 add_anchor_token(T_PLUSPLUS);
10209 add_anchor_token(T_STRING_LITERAL);
10210 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10211 add_anchor_token(T_WIDE_STRING_LITERAL);
10212 add_anchor_token(T__Bool);
10213 add_anchor_token(T__Complex);
10214 add_anchor_token(T__Imaginary);
10215 add_anchor_token(T___FUNCTION__);
10216 add_anchor_token(T___PRETTY_FUNCTION__);
10217 add_anchor_token(T___alignof__);
10218 add_anchor_token(T___attribute__);
10219 add_anchor_token(T___builtin_va_start);
10220 add_anchor_token(T___extension__);
10221 add_anchor_token(T___func__);
10222 add_anchor_token(T___imag__);
10223 add_anchor_token(T___label__);
10224 add_anchor_token(T___real__);
10225 add_anchor_token(T___thread);
10226 add_anchor_token(T_asm);
10227 add_anchor_token(T_auto);
10228 add_anchor_token(T_bool);
10229 add_anchor_token(T_break);
10230 add_anchor_token(T_case);
10231 add_anchor_token(T_char);
10232 add_anchor_token(T_class);
10233 add_anchor_token(T_const);
10234 add_anchor_token(T_const_cast);
10235 add_anchor_token(T_continue);
10236 add_anchor_token(T_default);
10237 add_anchor_token(T_delete);
10238 add_anchor_token(T_double);
10239 add_anchor_token(T_do);
10240 add_anchor_token(T_dynamic_cast);
10241 add_anchor_token(T_enum);
10242 add_anchor_token(T_extern);
10243 add_anchor_token(T_false);
10244 add_anchor_token(T_float);
10245 add_anchor_token(T_for);
10246 add_anchor_token(T_goto);
10247 add_anchor_token(T_if);
10248 add_anchor_token(T_inline);
10249 add_anchor_token(T_int);
10250 add_anchor_token(T_long);
10251 add_anchor_token(T_new);
10252 add_anchor_token(T_operator);
10253 add_anchor_token(T_register);
10254 add_anchor_token(T_reinterpret_cast);
10255 add_anchor_token(T_restrict);
10256 add_anchor_token(T_return);
10257 add_anchor_token(T_short);
10258 add_anchor_token(T_signed);
10259 add_anchor_token(T_sizeof);
10260 add_anchor_token(T_static);
10261 add_anchor_token(T_static_cast);
10262 add_anchor_token(T_struct);
10263 add_anchor_token(T_switch);
10264 add_anchor_token(T_template);
10265 add_anchor_token(T_this);
10266 add_anchor_token(T_throw);
10267 add_anchor_token(T_true);
10268 add_anchor_token(T_try);
10269 add_anchor_token(T_typedef);
10270 add_anchor_token(T_typeid);
10271 add_anchor_token(T_typename);
10272 add_anchor_token(T_typeof);
10273 add_anchor_token(T_union);
10274 add_anchor_token(T_unsigned);
10275 add_anchor_token(T_using);
10276 add_anchor_token(T_void);
10277 add_anchor_token(T_volatile);
10278 add_anchor_token(T_wchar_t);
10279 add_anchor_token(T_while);
10281 size_t const top = environment_top();
10282 scope_t *old_scope = scope_push(&statement->compound.scope);
10284 statement_t **anchor = &statement->compound.statements;
10285 bool only_decls_so_far = true;
10286 while (token.type != '}') {
10287 if (token.type == T_EOF) {
10288 errorf(&statement->base.source_position,
10289 "EOF while parsing compound statement");
10292 statement_t *sub_statement = intern_parse_statement();
10293 if (is_invalid_statement(sub_statement)) {
10294 /* an error occurred. if we are at an anchor, return */
10300 if (warning.declaration_after_statement) {
10301 if (sub_statement->kind != STATEMENT_DECLARATION) {
10302 only_decls_so_far = false;
10303 } else if (!only_decls_so_far) {
10304 warningf(&sub_statement->base.source_position,
10305 "ISO C90 forbids mixed declarations and code");
10309 *anchor = sub_statement;
10311 while (sub_statement->base.next != NULL)
10312 sub_statement = sub_statement->base.next;
10314 anchor = &sub_statement->base.next;
10318 /* look over all statements again to produce no effect warnings */
10319 if (warning.unused_value) {
10320 statement_t *sub_statement = statement->compound.statements;
10321 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10322 if (sub_statement->kind != STATEMENT_EXPRESSION)
10324 /* don't emit a warning for the last expression in an expression
10325 * statement as it has always an effect */
10326 if (inside_expression_statement && sub_statement->base.next == NULL)
10329 expression_t *expression = sub_statement->expression.expression;
10330 if (!expression_has_effect(expression)) {
10331 warningf(&expression->base.source_position,
10332 "statement has no effect");
10338 rem_anchor_token(T_while);
10339 rem_anchor_token(T_wchar_t);
10340 rem_anchor_token(T_volatile);
10341 rem_anchor_token(T_void);
10342 rem_anchor_token(T_using);
10343 rem_anchor_token(T_unsigned);
10344 rem_anchor_token(T_union);
10345 rem_anchor_token(T_typeof);
10346 rem_anchor_token(T_typename);
10347 rem_anchor_token(T_typeid);
10348 rem_anchor_token(T_typedef);
10349 rem_anchor_token(T_try);
10350 rem_anchor_token(T_true);
10351 rem_anchor_token(T_throw);
10352 rem_anchor_token(T_this);
10353 rem_anchor_token(T_template);
10354 rem_anchor_token(T_switch);
10355 rem_anchor_token(T_struct);
10356 rem_anchor_token(T_static_cast);
10357 rem_anchor_token(T_static);
10358 rem_anchor_token(T_sizeof);
10359 rem_anchor_token(T_signed);
10360 rem_anchor_token(T_short);
10361 rem_anchor_token(T_return);
10362 rem_anchor_token(T_restrict);
10363 rem_anchor_token(T_reinterpret_cast);
10364 rem_anchor_token(T_register);
10365 rem_anchor_token(T_operator);
10366 rem_anchor_token(T_new);
10367 rem_anchor_token(T_long);
10368 rem_anchor_token(T_int);
10369 rem_anchor_token(T_inline);
10370 rem_anchor_token(T_if);
10371 rem_anchor_token(T_goto);
10372 rem_anchor_token(T_for);
10373 rem_anchor_token(T_float);
10374 rem_anchor_token(T_false);
10375 rem_anchor_token(T_extern);
10376 rem_anchor_token(T_enum);
10377 rem_anchor_token(T_dynamic_cast);
10378 rem_anchor_token(T_do);
10379 rem_anchor_token(T_double);
10380 rem_anchor_token(T_delete);
10381 rem_anchor_token(T_default);
10382 rem_anchor_token(T_continue);
10383 rem_anchor_token(T_const_cast);
10384 rem_anchor_token(T_const);
10385 rem_anchor_token(T_class);
10386 rem_anchor_token(T_char);
10387 rem_anchor_token(T_case);
10388 rem_anchor_token(T_break);
10389 rem_anchor_token(T_bool);
10390 rem_anchor_token(T_auto);
10391 rem_anchor_token(T_asm);
10392 rem_anchor_token(T___thread);
10393 rem_anchor_token(T___real__);
10394 rem_anchor_token(T___label__);
10395 rem_anchor_token(T___imag__);
10396 rem_anchor_token(T___func__);
10397 rem_anchor_token(T___extension__);
10398 rem_anchor_token(T___builtin_va_start);
10399 rem_anchor_token(T___attribute__);
10400 rem_anchor_token(T___alignof__);
10401 rem_anchor_token(T___PRETTY_FUNCTION__);
10402 rem_anchor_token(T___FUNCTION__);
10403 rem_anchor_token(T__Imaginary);
10404 rem_anchor_token(T__Complex);
10405 rem_anchor_token(T__Bool);
10406 rem_anchor_token(T_WIDE_STRING_LITERAL);
10407 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10408 rem_anchor_token(T_STRING_LITERAL);
10409 rem_anchor_token(T_PLUSPLUS);
10410 rem_anchor_token(T_MINUSMINUS);
10411 rem_anchor_token(T_INTEGER);
10412 rem_anchor_token(T_IDENTIFIER);
10413 rem_anchor_token(T_FLOATINGPOINT);
10414 rem_anchor_token(T_COLONCOLON);
10415 rem_anchor_token(T_CHARACTER_CONSTANT);
10416 rem_anchor_token('~');
10417 rem_anchor_token('{');
10418 rem_anchor_token('-');
10419 rem_anchor_token('+');
10420 rem_anchor_token('*');
10421 rem_anchor_token('(');
10422 rem_anchor_token('&');
10423 rem_anchor_token('!');
10424 rem_anchor_token('}');
10425 assert(current_scope == &statement->compound.scope);
10426 scope_pop(old_scope);
10427 environment_pop_to(top);
10434 * Check for unused global static functions and variables
10436 static void check_unused_globals(void)
10438 if (!warning.unused_function && !warning.unused_variable)
10441 for (const entity_t *entity = file_scope->entities; entity != NULL;
10442 entity = entity->base.next) {
10443 if (!is_declaration(entity))
10446 const declaration_t *declaration = &entity->declaration;
10447 if (declaration->used ||
10448 declaration->modifiers & DM_UNUSED ||
10449 declaration->modifiers & DM_USED ||
10450 declaration->storage_class != STORAGE_CLASS_STATIC)
10453 type_t *const type = declaration->type;
10455 if (entity->kind == ENTITY_FUNCTION) {
10456 /* inhibit warning for static inline functions */
10457 if (entity->function.is_inline)
10460 s = entity->function.statement != NULL ? "defined" : "declared";
10465 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10466 type, declaration->base.symbol, s);
10470 static void parse_global_asm(void)
10472 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10475 expect('(', end_error);
10477 statement->asms.asm_text = parse_string_literals();
10478 statement->base.next = unit->global_asm;
10479 unit->global_asm = statement;
10481 expect(')', end_error);
10482 expect(';', end_error);
10487 static void parse_linkage_specification(void)
10490 assert(token.type == T_STRING_LITERAL);
10492 const char *linkage = parse_string_literals().begin;
10494 linkage_kind_t old_linkage = current_linkage;
10495 linkage_kind_t new_linkage;
10496 if (strcmp(linkage, "C") == 0) {
10497 new_linkage = LINKAGE_C;
10498 } else if (strcmp(linkage, "C++") == 0) {
10499 new_linkage = LINKAGE_CXX;
10501 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10502 new_linkage = LINKAGE_INVALID;
10504 current_linkage = new_linkage;
10506 if (next_if('{')) {
10508 expect('}', end_error);
10514 assert(current_linkage == new_linkage);
10515 current_linkage = old_linkage;
10518 static void parse_external(void)
10520 switch (token.type) {
10521 DECLARATION_START_NO_EXTERN
10523 case T___extension__:
10524 /* tokens below are for implicit int */
10525 case '&': /* & x; -> int& x; (and error later, because C++ has no
10527 case '*': /* * x; -> int* x; */
10528 case '(': /* (x); -> int (x); */
10529 parse_external_declaration();
10533 if (look_ahead(1)->type == T_STRING_LITERAL) {
10534 parse_linkage_specification();
10536 parse_external_declaration();
10541 parse_global_asm();
10545 parse_namespace_definition();
10549 if (!strict_mode) {
10551 warningf(HERE, "stray ';' outside of function");
10558 errorf(HERE, "stray %K outside of function", &token);
10559 if (token.type == '(' || token.type == '{' || token.type == '[')
10560 eat_until_matching_token(token.type);
10566 static void parse_externals(void)
10568 add_anchor_token('}');
10569 add_anchor_token(T_EOF);
10572 unsigned char token_anchor_copy[T_LAST_TOKEN];
10573 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10576 while (token.type != T_EOF && token.type != '}') {
10578 bool anchor_leak = false;
10579 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10580 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10582 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10583 anchor_leak = true;
10586 if (in_gcc_extension) {
10587 errorf(HERE, "Leaked __extension__");
10588 anchor_leak = true;
10598 rem_anchor_token(T_EOF);
10599 rem_anchor_token('}');
10603 * Parse a translation unit.
10605 static void parse_translation_unit(void)
10607 add_anchor_token(T_EOF);
10612 if (token.type == T_EOF)
10615 errorf(HERE, "stray %K outside of function", &token);
10616 if (token.type == '(' || token.type == '{' || token.type == '[')
10617 eat_until_matching_token(token.type);
10625 * @return the translation unit or NULL if errors occurred.
10627 void start_parsing(void)
10629 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10630 label_stack = NEW_ARR_F(stack_entry_t, 0);
10631 diagnostic_count = 0;
10635 print_to_file(stderr);
10637 assert(unit == NULL);
10638 unit = allocate_ast_zero(sizeof(unit[0]));
10640 assert(file_scope == NULL);
10641 file_scope = &unit->scope;
10643 assert(current_scope == NULL);
10644 scope_push(&unit->scope);
10646 create_gnu_builtins();
10648 create_microsoft_intrinsics();
10651 translation_unit_t *finish_parsing(void)
10653 assert(current_scope == &unit->scope);
10656 assert(file_scope == &unit->scope);
10657 check_unused_globals();
10660 DEL_ARR_F(environment_stack);
10661 DEL_ARR_F(label_stack);
10663 translation_unit_t *result = unit;
10668 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10669 * are given length one. */
10670 static void complete_incomplete_arrays(void)
10672 size_t n = ARR_LEN(incomplete_arrays);
10673 for (size_t i = 0; i != n; ++i) {
10674 declaration_t *const decl = incomplete_arrays[i];
10675 type_t *const orig_type = decl->type;
10676 type_t *const type = skip_typeref(orig_type);
10678 if (!is_type_incomplete(type))
10681 if (warning.other) {
10682 warningf(&decl->base.source_position,
10683 "array '%#T' assumed to have one element",
10684 orig_type, decl->base.symbol);
10687 type_t *const new_type = duplicate_type(type);
10688 new_type->array.size_constant = true;
10689 new_type->array.has_implicit_size = true;
10690 new_type->array.size = 1;
10692 type_t *const result = identify_new_type(new_type);
10694 decl->type = result;
10698 void prepare_main_collect2(entity_t *entity)
10700 // create call to __main
10701 symbol_t *symbol = symbol_table_insert("__main");
10702 entity_t *subsubmain_ent
10703 = create_implicit_function(symbol, &builtin_source_position);
10705 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10706 type_t *ftype = subsubmain_ent->declaration.type;
10707 ref->base.source_position = builtin_source_position;
10708 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10709 ref->reference.entity = subsubmain_ent;
10711 expression_t *call = allocate_expression_zero(EXPR_CALL);
10712 call->base.source_position = builtin_source_position;
10713 call->base.type = type_void;
10714 call->call.function = ref;
10716 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10717 expr_statement->base.source_position = builtin_source_position;
10718 expr_statement->expression.expression = call;
10720 statement_t *statement = entity->function.statement;
10721 assert(statement->kind == STATEMENT_COMPOUND);
10722 compound_statement_t *compounds = &statement->compound;
10724 expr_statement->base.next = compounds->statements;
10725 compounds->statements = expr_statement;
10730 lookahead_bufpos = 0;
10731 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10734 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10735 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10736 parse_translation_unit();
10737 complete_incomplete_arrays();
10738 DEL_ARR_F(incomplete_arrays);
10739 incomplete_arrays = NULL;
10743 * Initialize the parser.
10745 void init_parser(void)
10747 sym_anonymous = symbol_table_insert("<anonymous>");
10749 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10751 init_expression_parsers();
10752 obstack_init(&temp_obst);
10754 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10755 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10759 * Terminate the parser.
10761 void exit_parser(void)
10763 obstack_free(&temp_obst, NULL);